Posts Tagged ‘mcu flash reverse engineering’
Interrupted Erase: Why Half-Erased Is Usually Recoverable
A device that lost power during a firmware update is the most common recovery case we receive, and the most commonly misdiagnosed. The owner reports a dead unit and assumes the flash is empty. In most cases the flash is not empty; it is a mixture, and the mixture is what makes recovery possible.
The reason is that erase is a physical process with duration, not a command with an instantaneous effect.
What an erase does over time
Erasing a block means removing charge from every floating gate in it, and the mechanism is a high field applied across the tunnel oxide for a period measured in milliseconds. During that period the threshold voltages of the cells fall together from the programmed distribution toward the erased distribution.
The fall is not instantaneous and it is not simultaneous across the block. Cells differ slightly in geometry and coupling, so the threshold distribution widens before it moves. If the field is removed halfway through, the block is left with a distribution that is neither programmed nor erased, and the width of that distribution is the reason the block is still readable in principle.
| Elapsed fraction | Cell state | Readable |
|---|---|---|
| 0 | Programmed, intact | Yes, normally |
| 0.3 | Distribution widened, means shifted | Yes, with margin |
| 0.6 | Means between states | Ambiguous per cell |
| 0.9 | Near erased, residual charge | Usually reads as erased |
| 1.0 | Erased | Nothing left |
Why block granularity helps
The more important protection is that erase commands operate on blocks, and a firmware update erases many blocks in sequence.
The erase pointer moves monotonically through the address space. Blocks below the interruption point are fully erased and hold nothing. Blocks above it were never touched and hold everything, bit for bit, exactly as they were before the update started. Only the block being erased at the moment of the interruption is in the intermediate state.
| Region | State | Contents |
|---|---|---|
| Below the erase pointer | Erased | Gone |
| The block at the pointer | Partial | Ambiguous, often partly readable |
| Above the erase pointer | Untouched | Intact |
This is why the recoverable fraction is usually large. A boot loader that erases the application region from the bottom upward and loses power at thirty percent has erased thirty percent of the application and destroyed nothing else. The boot loader itself, the parameter block, and the file system above the application are all intact.
Reading a partially erased block
The block at the pointer needs a different read strategy from the rest of the array. A normal read compares each cell’s threshold to a fixed reference and returns a bit. Applied to a partially erased block, that comparison is a coin toss for cells sitting between the two distributions.
The useful technique is to sweep the reference. Read the block at the nominal reference, then at references offset above and below it, and compare the three results. Cells whose value is stable across the sweep are decided; cells that flip are the ambiguous ones, and their count is a measure of how far the erase progressed.
| Sweep result | Interpretation | Action |
|---|---|---|
| Stable at all references | Cell is decided | Accept the value |
| Flips at one reference | Marginal cell | Flag, use context |
| Flips at every reference | Deeply ambiguous | Treat as unknown |
The third category is usually small. Even a sixty-percent-complete erase leaves most cells clearly on one side, and error-correcting codes elsewhere in the image absorb the remainder, provided the block has any.
The failures that are not recoverable
Three scenarios destroy the data, and they are worth separating from the recoverable ones.
The first is interruption during the erase of a metadata block that the rest of the image depends on. If the block holding the file system superblock is erased, the data blocks above it are intact but unaddressed, and reconstruction becomes a forensic exercise rather than a read.
The second is a boot loader that retries the erase on the next power-up. The device comes back, sees an update in progress, and erases again from the beginning, this time over blocks that were previously untouched. Each retry destroys more, and a device that is power-cycled repeatedly during a failed update can end up genuinely empty.
| Scenario | Recoverable fraction | Method |
|---|---|---|
| Single interruption, no retry | Most of the array | Straight read plus sweep |
| Repeated power cycles | Boot region and above only | Region-wise read |
| Interrupted metadata erase | Data present, structure lost | Reconstruction |
| Erase completed, then programming failed | Nothing | Rebuild from another source |
The third is a programming failure rather than an erase failure, and it is common on devices that lost power during the write phase. Here the blocks are erased and partially rewritten, which means the image is a mixture of new data in the first blocks and 0xFF in the rest. Nothing can be recovered from the erased part, and the case moves to three sources for rebuilding flash.
The order of operations
Recovery has a fixed order, and reversing it costs data.
The first action is to read the whole array and keep the raw dump. Not a parsed image, not a partial read of the interesting region — the entire array, byte for byte, with the read parameters recorded. Every later step works from that dump and never from the device, because the device can be lost and the dump cannot.
The second action is to identify the layout, which determines what the fragments belong to. The method is the one in five flash layouts, and it applies to a damaged image exactly as it applies to an intact one, because the fingerprints survive a partial erase.
The third action is the reference sweep on the boundary block, performed on a copy of the dump rather than the dump itself, so that the original measurement remains available for a second interpretation.
When recovery is not the goal
A frequent mismatch in expectations is a customer who asks for recovery when what they need is a working device. Those are different objectives with different costs.
If the goal is a working device, the fastest route is usually to erase the remainder and program a known image, provided one exists. If the goal is the data — calibration values, a production log, a key that only exists on this unit — then recovery is the only route and the effort is justified.
| Goal | Route | Data outcome |
|---|---|---|
| Working device | Erase and reprogram | Replaced |
| Per-unit data | Extract the parameter block | Preserved |
| Code for analysis | Read the untouched regions | Partial |
| Both device and data | Extract, then reprogram | Preserved, then extended |
The parameter block is the region most often worth recovering on its own. It is small, it survives interruption more often than the code does because it usually sits at the top of the array, and it cannot be obtained from any other unit.
What the service does
We read the array first and report what is actually there, before quoting any recovery work.
| Deliverable | Content |
|---|---|
| Raw dump | Full array, with read parameters recorded |
| Region map | Which regions are intact, erased, or partial |
| Recoverable estimate | Percentage and which parts |
| Sweep analysis | Decided versus ambiguous cells in the boundary block |
The estimate is delivered before the work rather than after, because a device that is eighty percent intact and a device that is five percent intact look identical from the outside, and the customer deserves to know which one they have. Where the answer is that the untouched regions are enough, the remaining work overlaps with extraction margins on aged cells, since a device that has just survived an interrupted erase is not a device in its first cycle.
Five Flash Layouts and Their Fingerprints
A flash dump arrives as a single file with no map. Before any code analysis is possible, someone has to decide where the boot loader ends, where the application begins, whether there is a file system, and where the calibration constants live. That decision is made from the binary, not from a datasheet, because the datasheet describes the silicon and not the product.
Five layouts account for almost everything we see. Each has a fingerprint that is visible in a hex view, an entropy plot, or a search for a handful of byte patterns.
Layout one: a single flat region
The simplest layout is one image occupying the whole array, starting at address zero with a reset vector and continuing without interruption.
The fingerprint is a valid vector table at the very start — a stack pointer value that lies inside RAM, a reset vector that points inside the array, and a run of handler addresses all in the same range. After that the entropy stays roughly constant, with occasional clusters of zeros or 0xFF where constant tables and uninitialised padding sit.
The mistake this layout invites is assuming that a low-entropy region is unused. It is more often a lookup table, and deleting it to save space breaks the device in a way that is hard to trace later.
Layout two: a boot loader plus an application
The second layout splits the array into a small boot region at address zero and a larger application above it. This is what makes field update possible without a debugger.
The fingerprint is two vector tables. The first is at address zero and belongs to the boot loader. The second sits at the application’s base address, which is aligned to a block boundary and usually to a round number such as 0x4000 or 0x8000. Between the two there is a gap of unused space, filled with 0xFF, which is the visual signature of a layout boundary.
| Feature | Boot region | Application region |
|---|---|---|
| Vector table | At 0x0000 | At its base address |
| Size | Small, one to sixteen blocks | The rest of the array |
| Contents | UART or USB protocol handler | The product |
| Tell in the binary | A jump into higher memory | A second SP and reset pair |
The jump instruction at the end of the boot loader is the confirmation. It loads the application’s stack pointer from the second table and branches to the second reset vector, and seeing that sequence removes any doubt about where the boundary lies.
Layout three: dual bank
Dual bank exists so that an update can be interrupted without bricking the device. One bank holds the running image, the other receives the new one, and a marker decides which is valid after the next reset.
The fingerprint is symmetry. Two regions of identical size, each starting with a vector table, each ending at a block boundary, and each accompanied by a small header containing a version number, a length, and a checksum. Often one bank is entirely 0xFF because it has never been used.
| Observation | Interpretation |
|---|---|
| Two equal regions, one blank | Bank B never written |
| Two regions, different versions | Update completed, old bank retained |
| Two regions, one with a bad checksum | Interrupted update |
| Header at bank start, not at 0x0 | Swap mechanism is header-driven |
The interrupted-update case is the one worth care. The bank with the bad checksum is not garbage; it is a partially written image, and the intact part of it is often useful for comparison against the running bank.
Layout four: an image plus a file system
Devices that log, store configuration, or hold user assets usually carry a small file system above the code. The common choices are littlefs, SPIFFS, and on larger parts a FAT variant.
The fingerprint is block-structured rather than code-like. Instead of a dense stream of instructions, there are repeating headers at fixed intervals, wear-levelling counters that increment across erase cycles, and a superblock near the start of the region that names the geometry.
| File system | Tell in a raw dump |
|---|---|
| littlefs | Pairs of blocks with revision counters; a superblock with block size and count |
| SPIFFS | Object headers with page indices; a large proportion of 0xFF at the end |
| FAT | A boot sector with 0x55AA at offset 510, then a FAT table |
The counter pattern is the most reliable sign. A region whose first few bytes change every few hundred bytes, incrementing slowly, is a journal, and journals belong to file systems.
Layout five: an image plus a parameter area
The fifth layout adds a small region that is written far more often than the rest. Calibration values, run-hour counters, MAC addresses, and trimmed oscillator settings all live here.
The fingerprint is a small erase-block-sized region, usually the last block or the one immediately after the code, with a short record structure repeated at intervals. Each record starts with a marker and ends with a checksum, and older records are superseded by newer ones rather than overwritten, because a flash cell can be programmed without an erase only if it is still erased.
| Signal | Meaning |
|---|---|
| Same structure repeated every 16 to 64 bytes | Append-only record log |
| A monotonic counter field | Sequence number for the newest record |
| A single-byte or two-byte checksum | Record integrity |
| Region under 4 KB | Sized to one erase block on purpose |
This region is the one most often lost in a careless rebuild, because it looks like padding. It is also the region that a reference device cannot supply, since the values are per-unit.
Fingerprints that do not lie
Three measurements settle most layout questions quickly, and all three can be scripted.
The entropy plot comes first. Code sits in a narrow band, compressed data sits near the top, erased flash sits at zero, and a layout boundary shows as a step rather than a slope.
The second is a scan for vector-table candidates: any offset where two consecutive words both point inside the array and the second one, masked to the instruction-set alignment, lands on another plausible pointer chain. Genuine tables appear two or three times in a well-structured image and nowhere else.
| Measurement | What it resolves |
|---|---|
| Entropy per block | Where data ends and code begins |
| Vector table scan | Where each bank or image starts |
| 0xFF run lengths | Where regions were never programmed |
| ASCII string map | Which region is configuration rather than code |
The third is a string map, filtered to printable runs of six characters or more. Version strings, file system names, boot messages, and AT command tables cluster inside the region that owns them, and the clustering is usually enough to assign a region to a role.
Reading the map before reading the code
The order matters because the map decides which tool applies. A code region goes to a disassembler for the right architecture. A file system goes to a parser. A parameter block goes to a record decoder, and the record decoder needs the record layout, which is inferred from the repetition rather than from documentation.
Attempting the disassembler first is the usual failure. A file system region disassembles into plausible-looking instructions, because any byte sequence does on a variable-length instruction set, and the analysis produces pages of meaningless output before anyone notices.
What the service does
We produce a layout map as a separate deliverable, before analysis, because it makes the analysis quotable.
| Output | Content |
|---|---|
| Region table | Start, end, size, and role for each region |
| Confidence | Which regions are certain and which are inferred |
| Fingerprint evidence | The measurement that supports each assignment |
| Per-unit data list | Regions that a reference device cannot supply |
The map is also the input to two downstream questions: which regions an extraction must preserve byte for byte, covered in floating gate margins, and which regions a copy can legitimately rebuild, covered in NAND and NOR copying.
Where the code itself then needs to be understood rather than located, the method is the one in MCU source code reverse engineering. The layout map is what tells that work where to start.