Posts Tagged ‘reverse engineering microcontroller source file’

PostHeaderIcon ATtiny4313: Moving Code Between the 2 KB and 4 KB Parts

Two part numbers, one package, one pinout, one peripheral set, and a factor of two between their flash arrays. The relationship is common enough in this family that images get moved between the members informally: a build is compiled for the larger part because the larger part is what the developer had, and a production run is fitted with the smaller one because that is what purchasing could get.

Sometimes that works. Sometimes it produces a unit that boots and misbehaves in a way nobody can attribute to anything, because the code that was moved is not the code that was tested. The difference is rarely the total size of the file. It is three specific addresses.

The three addresses

what why it decides the port how to find it
highest code address used if it exceeds the smaller array, the code does not fit at all the largest target of any branch or call in the disassembly
end of the constant tables tables placed above the smaller array’s ceiling are simply absent the highest address loaded through the program-memory pointer
the stack pointer initial value a 256-byte stack frame in a 128-byte part overflows silently the immediate loaded into the stack pointer at reset

The first is obvious and the second is often missed. A build can have compact code and a large table — a font, a lookup curve, a protocol string set — and the linker places that table after the code. On the larger part the table sits above the smaller part’s ceiling even though the code itself would fit. The result is a program that runs correctly until it first needs the table, then reads whatever the program-memory access returns outside the array, which on this hardware is not a fault but a value.

The third is the one that produces the least explicable symptoms. A stack that overflows its SRAM does not stop the processor. It corrupts whatever the stack pointer walks into, which is usually the region allocated to variables, and the corruption depends on call depth and interrupt timing. A unit that fails only under load, or only when a particular interrupt coincides with a particular function call, is a stack that is too deep for the part.

Why the jump instruction does not save you

A reasonable assumption is that the assembler would refuse to emit a relative jump that cannot reach its target. On a 4 KB array that assumption is true in a way that is unhelpful: a relative jump encodes a signed offset of twelve bits, which spans two thousand and forty-eight words, and 4 KB is exactly two thousand and forty-eight words. Every address in the array is reachable from every other.

So the toolchain has no reason to complain, the image links cleanly, and the fact that the code is destined for a 2 KB part changes nothing at build time. The constraint only appears when the image is executed on the smaller device, where the addresses above the ceiling do not exist.

This is also why the reverse direction is safe. An image built for the 2 KB part runs on the 4 KB part unchanged, because every address it uses is present in both. Downgrading is the risky direction; upgrading is not.

Reading the image to answer the question

The question «will this image run on the smaller part» is answerable from a disassembly in a short time, without recompiling anything:

  1. Decode the vector table at address zero. Its length is set by the peripheral set and is identical on both parts.
  2. Walk every branch and call target, and record the maximum. If it exceeds the smaller array’s word count, the answer is no.
  3. Walk every program-memory load, note the base addresses handed to the pointer pair, and record the highest one. If any table base is above the ceiling, the answer is no even when the code fits.
  4. Read the stack pointer immediate from the reset code, and compare the implied stack size against the SRAM of the smaller part.
  5. Check the initialisation for a RAM test or a memory-clear loop, whose end address is a second, independent statement of how much SRAM the build expects.

Step 5 is the cross-check that catches a build compiled against the wrong device definition. A clear loop that stops at the top of a 256-byte SRAM is a build that was configured for the larger part, regardless of what the makefile said.

The EEPROM doubles too, and that truncates records

The capacity change is not confined to the flash array. This pair carries 128 bytes of EEPROM in the smaller part and 256 in the larger, so a configuration block that fits the smaller device may occupy only the first half of the larger array, and the reverse move silently cuts it in half.

That matters because EEPROM contents are rarely a flat parameter list. Where the structure is a rotating log — records written in sequence, the oldest overwritten when the array is full — the record at the top of the larger array is newer than everything in the smaller one. Copying the first 128 bytes of a 256-byte log therefore copies the oldest records and discards the current state, which is the exact opposite of what a migration is supposed to preserve.

The safe procedure is to identify the record structure before moving anything: fixed length, a sequence field or a timestamp, and a rule for which record is authoritative. Where the structure cannot be identified, the last written record is usually the one with a sequence number that is one higher than its neighbours, or the only one whose checksum validates against contents that are not all erased.

What this means for a recovery report

When the image is being recovered rather than ported, the same three addresses belong in the report for a different reason: they describe the memory the design occupies, and they tell the customer whether a replacement can be built on either member of the family. That is a purchasing question as much as an engineering one, and it is answered by the numbers the disassembly already produced.

The report should also state which member the image was built for, using the stack pointer constant as the evidence. It is a single number and it removes the ambiguity that the shared package creates.

The self-programming behaviour of the smaller member is covered in ATtiny2313 code recovery, and the revised silicon in ATtiny2313A heximal recovery. Where the same capacity question appears one family up, ATtiny261 code recovery covers the members that share an analogue front end.

FAQ

Can I tell the two parts apart from the image? Yes, from the stack pointer constant and from the highest address the code touches. Neither requires knowing the marking.

Does a larger part’s image always fail on the smaller one? No. It fails when the code or a table crosses the smaller ceiling, or when the stack outgrows the smaller SRAM. Small images port without change.

Is the pinout really identical? Yes within this pair, which is why the substitution happens in the first place and why the resulting faults are so hard to attribute.

Conclusion

Capacity-only siblings invite informal substitution, and the substitution is safe in one direction and conditional in the other. Three addresses settle it: the highest code target, the end of the constant tables, and the stack pointer initial value. None of them appear in a file size, and all three are visible in a disassembly that takes minutes to produce.

PostHeaderIcon ATtiny85: When the Firmware Is a Software USB Stack

An eight-pin part with no USB peripheral is not the obvious place to find a USB device, and yet a large share of ATtiny85 designs in the wild are exactly that. The part has enough pins, enough flash and a fast enough core for a software implementation of low-speed USB, and the reference implementation for it has been copied into thousands of small products.

That fact is worth knowing before opening the disassembly, because it changes the order in which the image should be read. A general-purpose AVR image is read from the reset vector forward, following initialisation into the main loop. A software USB image is read from its timing loops outward, because those loops are the most constrained code in the part and everything else is arranged around them.

What the part actually provides

The ATtiny85 carries 8 KB of flash, 512 bytes of SRAM, 512 bytes of EEPROM, an eight-bit timer with PWM, a second eight-bit timer, a four-channel ten-bit converter, a comparator, a universal serial interface, and six usable I/O pins on the eight-pin package. There is no USB controller anywhere in that list.

Software USB therefore has to bit-bang a 1.5 Mbit/s differential signal on two ordinary port pins, with edge timing accurate to a small fraction of a 0.667 microsecond bit period, while the same core also runs the application. It works because the task is bounded: low-speed USB is slow by modern standards, and an AVR running at 16 MHz has roughly ten instruction slots per bit.

constraint figure consequence in the image
bit period 0.667 µs a tight loop whose cycle count is the specification
core clock used 16 to 16.5 MHz from the internal PLL PLL control written early, before any USB traffic
SRAM available 512 B endpoint buffers, descriptors and application state compete for one page of memory
signal pins two port pins, usually adjacent direction and level written as whole-port operations

The PLL write is the first landmark

The internal oscillator tops out below what the timing needs, so designs enable the phase-locked loop and run the core from it. That is a write to a specific control register in the first few dozen instructions of the program, before timers are configured and long before any pin is touched.

For a reader, that write is the entry point. It says the design intends to run fast, and it dates the code: designs built around the PLL are the ones that can afford software USB, and designs running from the plain 8 MHz oscillator cannot. Finding it also fixes the clock frequency the rest of the analysis assumes, which is the number every delay loop is calibrated against.

The bit engine

The timing-critical code is small, and it looks unlike anything else in the image. It is a loop with a fixed instruction count, entered from a timer interrupt or from a pin-change interrupt, containing shifts, conditional branches on a port bit, and whole-port writes. It has no floating point, no table lookups and no calls into application code, because a call would blow the cycle budget.

Two features make it identifiable even without a symbol table. The first is that it reads a port pin and writes the same port within a handful of instructions. The second is that its branch structure corresponds to the USB line states: idle, start of packet, and the two data states. Once that loop is labelled, the rest of the protocol layer is findable by following its callers.

Descriptors live in flash, not in SRAM

A USB device has to answer requests for its device, configuration and string descriptors. On a part with 512 bytes of SRAM, those tables cannot live in RAM; they are constants in flash, read back with the load-from-program-memory instruction using a pointer pair.

That produces a distinctive pattern in the disassembly: short routines that take a descriptor index, add it to a base address, and copy bytes out of flash one at a time. String descriptors in particular are recognisable because they contain the UTF-16 encoding of a product name, which appears as readable text when the flash image is dumped as bytes. A vendor and product identifier pair stored as two sixteen-bit constants nearby is the second confirmation.

This is also the fastest route to a human-readable answer for a customer. Before any semantic analysis, the descriptors usually say what the product claims to be.

Where the application begins

Everything past the protocol layer is ordinary embedded code: an ADC read for a sensor, a PWM write for a motor or an LED, a state machine driven from the main loop. It is reached from the protocol layer when a control request asks the device to do something, and it is usually the least optimised code in the image because it has slack.

Reading outward from the timing loops therefore has a practical benefit beyond elegance. The parts of the image that are most expensive to reconstruct are the ones that are read first, while attention is fresh, and the parts that are routine are read last.

What a complete deliverable looks like

For an image of this shape the return set is the flash contents as Intel HEX, the EEPROM as a separate file, a disassembly with the PLL and timer configuration annotated, the descriptor tables extracted into readable form, and a map of which routines implement the protocol and which implement the application. The descriptor extraction is worth calling out separately because it is the part of the work most often useful to someone who is not going to read the assembly at all.

The image is also the only place the calibration value can be confirmed. Designs built on the internal oscillator store a per-device calibration byte, and an image restored to a different physical part inherits the donor’s calibration rather than the target’s. That does not stop the code running, but it does move the timing, and on a software USB design timing is the product.

The family’s pin constraints are covered in ATtiny25 flash recovery, and the erase behaviour that decides whether the EEPROM survives in ATtiny85V software recovery. Where the same part appears with more flash and a wider vector table, ATtiny45 heximal extraction covers the identification step.

FAQ

Does this part have hardware USB? No. Everything is done in software on two general-purpose pins, which is why the timing loops are the most constrained code in the image.

Why does the descriptor table matter? It answers what the device claims to be, in text, without requiring the assembly to be understood first.

Is the calibration byte part of the image? It lives in a separate signature row rather than in the flash array, but an image moved to another device carries the donor’s timing unless that row is rewritten.

Conclusion

An eight-pin part with no USB peripheral still produces images that enumerate over USB, and those images have a shape: a PLL write early, a fixed-cycle bit engine, descriptor tables in flash, and application code reached from the protocol layer. Knowing the shape turns an 8 KB disassembly from a wall of instructions into a structure with an obvious first page.