Reverse engineeringguide
Replaying boot-time RAM copies before decompiling Cortex-M firmware
A Cortex-M startup routine copies more than .data from flash to SRAM (static random-access memory) when the build asks for it. With a function attribute that places code in RAM (random-access memory), or a relocation option, part or most of the code is copied too and runs from SRAM. A decompiler that imports the flash image at its flash address reads those bytes at the wrong address. Interrupt handlers and function pointers that point into SRAM resolve to nothing, and calls inside the copied code land on plausible but false functions. A false “this build adds a new function” finding came from exactly this in my own notes, and two rounds of analysis rested on it before a later pass caught it.
This guide finds the copy tables in a raw image, decides which copies hold code, replays them in a Ghidra import and moves earlier findings to the run addresses. It assumes a raw image with a known flash base address, headless Ghidra, Python 3 and the arm-none-eabi binutils for the example. I ran the example on Ghidra 12.2. The image in the example is made up and every address in it is illustrative.
For the wider method around imports and claim checking, see Reverse engineering with a coding agent and headless Ghidra. For an image analysed this way and then patched, see Patching an nRF52840 gaming mouse’s firmware.
Load address and run address
Section titled “Load address and run address”A linker script gives each output section two addresses: the one it runs at and the one it is stored at. GNU (GNU’s Not Unix) ld calls the stored address the load address and sets it with AT or AT>.1 A section that runs from SRAM but is stored in flash has the two different, and something has to copy it before it is used. In Zephyr that is the architecture’s early data copy, which copies the data region and then the RAM-function region from their load addresses.2 The .ramfunc section is linked to run in RAM with its load address recorded for that copy.3 The code relocation feature does the same for whole source files or libraries: a build script generates a copy function that calls a memcpy-style helper once per relocated region, with destination, source and size.45 In older Zephyr trees the early copy was called z_data_copy; current main calls it arch_data_copy.
A raw .bin carries no section headers, so nothing in the file says that a block of it is meant for another address. Three things go wrong when the block is analysed where it is stored:
- A vector table entry that points at SRAM has no memory behind it. The disassembler keeps the entry as a constant, and the handler is never decompiled.
- A function pointer stored in data, or a literal-pool word loaded and called, points at SRAM and resolves to nothing.
- A BL (branch with link) is relative to the program counter (PC).6 Decoded at the load address
Linstead of the run addressR, a call to run addressTshows as a call toT + (L - R). IfTis in the same copied block, that is the load address of the right function and the call looks fine. IfTis in another copied block or in flash code, the two blocks have differentL - Roffsets and the target is false. In a large image it falls inside the image on a real instruction, so nothing flags it.
Table shapes
Section titled “Table shapes”The copy information sits in the image as words, and its shape depends on the toolchain. Scan for every shape in the table, because an image can use more than one.
| Build style | What the startup code reads | How to recognise it in a raw image |
|---|---|---|
| Zephyr data copy | The early copy takes the data region, then the RAM-function region.2 In the images I checked, the compiled literals are a destination start, a destination end and a source, in varying order. | Three words: the first two in SRAM with the second above the first, the third inside the image, and the source plus the length still inside it. Two such triples are usually adjacent. |
| Zephyr code and data relocation | A generated function copies each relocated region with destination, source and size.5 | Three literal-pool words per call. Their order depends on the compiler, so test both destination-source-size and size-source-destination orders. |
| CMSIS (Common Microcontroller Software Interface Standard) copy table | Records of source, destination and a count of words, between __copy_table_start__ and __copy_table_end__ in the template linker script.7 | Records of three words with a word count, not a byte count. |
| Arm Compiler region table | Four words per entry: load address, execution address, execution size and a handler. The handler copies, zeroes or decompresses.8 | A handler that is the decompress routine, or a source plus size past the end of the image, marks a compressed entry. A plain copy cannot replay it. |
| Startup loop, no table | A loop in the startup function with bounds loaded from linker symbols. The RISC-V images I checked used this for .data. | No table to find. Read the loop: two or three address constants set its bounds. |
An audit of 109 firmware images, mostly Cortex-M with about a quarter RISC-V (reduced instruction set computer), met all five shapes. Most images with code in RAM already had the copy replayed. One did not, and its decompile showed 53 distinct call targets in SRAM with no function bodies behind them. Images from the Arm Compiler with compressed read-write data could not be classified as code or data from their bytes at all; see the gotchas below.
A worked example on a made-up image
Section titled “A worked example on a made-up image”The example image has three copied blocks: relocated code with an interrupt handler, a RAM function that nothing but the relocated code calls, and a data block. Linker script, with illustrative addresses:
MEMORY { FLASH (rx) : ORIGIN = 0x00000000, LENGTH = 0x1000 SRAM (rwx) : ORIGIN = 0x20000000, LENGTH = 0x1000}SECTIONS { .vectors 0x0 : { KEEP(*(.vectors)) } > FLASH .boot : { *(.boot) } > FLASH .ramtext 0x20000000 : { *(.ramtext) } > SRAM AT> FLASH .ramfunc 0x20000100 : { *(.ramfunc) } > SRAM AT> FLASH .data 0x20000200 : { *(.data) } > SRAM AT> FLASH __ramtext_start = ADDR(.ramtext); __ramtext_end = ADDR(.ramtext)+SIZEOF(.ramtext); __ramfunc_start = ADDR(.ramfunc); __ramfunc_end = ADDR(.ramfunc)+SIZEOF(.ramfunc); __data_start = ADDR(.data); __data_end = ADDR(.data)+SIZEOF(.data); __ramtext_load = LOADADDR(.ramtext); __ramfunc_load = LOADADDR(.ramfunc); __data_load = LOADADDR(.data);}Assembly source, abbreviated to what matters. caller and nmi run from SRAM, store_one is a RAM function, and copy_table stands in for the three triples a real startup routine would compile:
.syntax unified .thumb .section .vectors, "a" .word 0x20001000 @ initial stack pointer .word reset + 1 .word nmi + 1 @ handler runs from RAM .fill 14, 4, 0 @ remaining system vectors, unused here .section .boot, "ax" .thumb_funcreset: push {r4, lr} pop {r4, pc} .align 2copy_table: @ (dst, dst_end, src) triples .word __ramtext_start, __ramtext_end, __ramtext_load .word __ramfunc_start, __ramfunc_end, __ramfunc_load .word __data_start, __data_end, __data_load .section .ramtext, "ax" .thumb_funccaller: push {r4, lr} bl store_one pop {r4, pc} .align 2 .thumb_funcnmi: push {lr} pop {pc} .section .ramfunc, "ax" .thumb_funcstore_one: push {r4, lr} movs r0, #1 pop {r4, pc} .section .data .word 0x11223344, 0x55667788, 0, 0Assemble, link and flatten it:
arm-none-eabi-as -mcpu=cortex-m4 -o toy.o toy.sarm-none-eabi-ld -T toy.ld -o toy.elf toy.oarm-none-eabi-objcopy -O binary toy.elf toy.binThe resulting layout, which is what an analyst has to reconstruct from the bare toy.bin:
| Block | Load address | Run address | Size | Holds |
|---|---|---|---|---|
| vectors and boot | 0x0 | 0x0 | 0x6c | vector table, reset handler, the copy table at 0x48 |
| relocated text | 0x6c | 0x20000000 | 0xc | caller at 0x20000000, nmi at 0x20000008 |
| RAM function | 0x78 | 0x20000100 | 0x6 | store_one |
| data | 0x7e | 0x20000200 | 0x10 | four words |
Vector slot 2, the NMI (nonmaskable interrupt) handler, holds 0x20000009: an SRAM address with the Thumb bit set. The BL in caller, at load address 0x6e, has the bytes f000 f87d, a displacement of 0xfa. Decoded at 0x6e it targets 0x16c, which is past the end of the 0x8e-byte image. Decoded at its run address 0x20000002 it targets 0x20000100, store_one. The image is small enough that the false target falls outside it; in a real image it would land on code.
Importing toy.bin at base 0 and running headless analysis with only the reset vector seeded gives the picture an unreplayed import has:
| Import | Functions found | Calls decoded |
|---|---|---|
| Flash address only | reset (0x44) | none; NMI at 0x20000008 is unmapped |
Flash address, plus a seed on the load copy of caller | reset, 0x6c | bl 0x16c, off the image |
| Copies replayed (below) | reset, 0x20000000, 0x20000008, 0x20000100 | bl 0x20000100 at 0x20000002 |
Step 1: find the copies
Section titled “Step 1: find the copies”Start from the vector table: word 1 is the reset handler, and the first few functions it calls or tail-calls are the startup code. Read it for a memcpy-style call whose arguments are literal-pool loads, or a copy loop. Independently, scan the whole image for the shapes in the table above. This script finds the destination-end-source shape and counts the evidence for code (the next step explains it):
#!/usr/bin/env python3# usage: scan_copies.py IMAGE LOAD_BASE RAM_LO RAM_HIimport struct, sys
img = open(sys.argv[1], "rb").read()base, ram_lo, ram_hi = (int(a, 0) for a in sys.argv[2:5])end = base + len(img)u32 = lambda off: struct.unpack_from("<I", img, off)[0]u16 = lambda off: struct.unpack_from("<H", img, off)[0]
# every (dst, dst_end, src) word triple: dst range in SRAM, source inside the imagecopies = []for off in range(0, len(img) - 11, 4): dst, dst_end, src = u32(off), u32(off + 4), u32(off + 8) if ram_lo <= dst < dst_end <= ram_hi and base <= src and src + (dst_end - dst) <= end: copies.append((base + off, dst, dst_end, src))
# evidence of code: odd words (Thumb pointers) into the range whose target,# read from the load image, starts like a function (push {..., lr})for table, dst, dst_end, src in copies: hits = 0 for off in range(0, len(img) - 3, 4): v = u32(off) if v & 1 and dst <= v - 1 < dst_end: hw = u16(src - base + (v - 1 - dst)) hits += hw >> 8 == 0xB5 or hw == 0xE92D print(f"table 0x{table:x}: 0x{dst:08x}..0x{dst_end:08x} <- 0x{src:x} {hits} prologue pointers")On the example it prints:
table 0x48: 0x20000000..0x2000000c <- 0x6c 1 prologue pointerstable 0x54: 0x20000100..0x20000106 <- 0x78 0 prologue pointerstable 0x60: 0x20000200..0x20000210 <- 0x7e 0 prologue pointersEach table row is a candidate. Confirm it against the startup code before trusting it, because three words that look like a triple can be a data coincidence.
Step 2: decide which copies hold code
Section titled “Step 2: decide which copies hold code”A table says what is copied, not whether it is code. Four kinds of evidence, strongest first:
- Vector table slots that point into the destination range. A slot with the Thumb bit set pointing at an SRAM address is an interrupt handler that runs from SRAM. If startup also copies the vector table to SRAM and writes the Vector Table Offset Register (VTOR, at 0xE000ED08), the table in use is the SRAM copy and the flash one is only its source.910
- Thumb pointers: odd words anywhere in the image (function pointers in data, literal pools) that point into the range and, when translated to the load address, land on a function prologue such as
push {..., lr}. The script counts these. - Calls from code already known to be code, decoded at the run address. This catches blocks nothing points to. In the example the RAM function has no pointer and one BL from the relocated text. A second pass that decodes every BL inside copies already marked as code, and marks the copy it targets, classifies the second table as code. Without it the table stays “data”.
- Code in flash that loads a literal pointing into the range and calls it with
blx. Flash and SRAM are 512 MB apart in this layout, beyond the 16 MB reach of a BL,6 so a call from flash into SRAM has to be indirect.
Count the evidence for each copy and read the first instructions of the block at its load address. A small RAM-function block can be reached by a single call, so a fixed threshold misses it. Check a sample against a decompile before relying on the count.
Step 3: replay the copies in Ghidra
Section titled “Step 3: replay the copies in Ghidra”Analysis has to start from a fresh import. Code already disassembled at the load address stays as it is, with its false references. The replay does five things, in this order:
- Create a block at the run address of each destination range, readable, writable and executable.
- Copy the bytes from their load address into that block.
- Clear the execute flag on the load-address slice of every copy that holds code, so auto-analysis does not disassemble it at the wrong address. The bytes stay as data.
- Seed the vector table’s Thumb targets as functions, reading the table from SRAM if startup copies it there.
- Seed any entry the vector table cannot reach, with the Thumb bit set in Ghidra’s
TModecontext register.
Ghidra’s Java API (application programming interface) has what this needs: Memory.createInitializedBlock, Memory.setBytes and Memory.split, MemoryBlock.setExecute, and DisassembleCommand for seeding.11 The script below does the five steps from its arguments. It runs as a pre-script, which headless analysis runs before auto-analysis:12
// Replay boot-time RAM copies before auto-analysis.// Script args, processed in order (numbers in hex or decimal):// region:NAME:BASE:SIZE zero-filled, initialised, rwx block (skipped if the base is mapped)// copy:DST:SRC:LEN bytes at SRC are copied to DST// noexec:ADDR:LEN clear the execute flag on a slice of the load image// vec:ADDR:COUNT seed every distinct Thumb target of a word table// entry:ADDR seed one Thumb function// @category Memoryimport ghidra.app.cmd.disassemble.DisassembleCommand;import ghidra.app.script.GhidraScript;import ghidra.program.model.address.Address;import ghidra.program.model.lang.Register;import ghidra.program.model.mem.*;import java.math.BigInteger;import java.util.*;
public class ReplayRamCopies extends GhidraScript { private void seed(long a) throws Exception { Address ad = toAddr(a & ~1L); if (getInstructionAt(ad) != null) { if (getFunctionAt(ad) == null) createFunction(ad, null); return; } Register tm = currentProgram.getLanguage().getRegister("TMode"); if (tm != null) { currentProgram.getProgramContext().setValue(tm, ad, ad, BigInteger.ONE); } new DisassembleCommand(ad, null, true).applyTo(currentProgram, monitor); if (getFunctionAt(ad) == null) createFunction(ad, null); }
@Override public void run() throws Exception { Memory mem = currentProgram.getMemory(); for (String arg : getScriptArgs()) { String[] p = arg.split(":"); switch (p[0]) { case "region": { long base = Long.decode(p[2]), size = Long.decode(p[3]); if (mem.getBlock(toAddr(base)) != null) break; MemoryBlock b = mem.createInitializedBlock(p[1], toAddr(base), size, (byte) 0, monitor, false); b.setRead(true); b.setWrite(true); b.setExecute(true); break; } case "copy": { long dst = Long.decode(p[1]), src = Long.decode(p[2]); byte[] buf = new byte[Integer.decode(p[3])]; mem.getBytes(toAddr(src), buf); mem.setBytes(toAddr(dst), buf); break; } case "noexec": { long a = Long.decode(p[1]), len = Long.decode(p[2]); MemoryBlock blk = mem.getBlock(toAddr(a)); if (blk.getStart().getOffset() < a) { mem.split(blk, toAddr(a)); blk = mem.getBlock(toAddr(a)); } if (blk.getEnd().getOffset() >= a + len) { mem.split(blk, toAddr(a + len)); blk = mem.getBlock(toAddr(a)); } blk.setExecute(false); break; } case "vec": { long base = Long.decode(p[1]); Set<Long> seen = new LinkedHashSet<>(); for (int i = 1; i < Integer.decode(p[2]); i++) { // slot 0 is the stack pointer long w = mem.getInt(toAddr(base + 4L * i)) & 0xffffffffL; if ((w & 1) == 1 && seen.add(w)) seed(w); } break; } case "entry": seed(Long.decode(p[1])); break; default: throw new Exception("unknown arg " + arg); } } }}Run it on the example with one argument per step:
analyzeHeadless ./proj toy -import toy.bin \ -processor "ARM:LE:32:Cortex" -loader BinaryLoader -loader-baseAddr 0 \ -scriptPath ./scripts -preScript ReplayRamCopies.java \ region:sram:0x20000000:0x1000 \ copy:0x20000000:0x6c:0xc copy:0x20000100:0x78:6 copy:0x20000200:0x7e:0x10 \ noexec:0x6c:0xc noexec:0x78:6 \ entry:0x45 vec:0:4 entry:0x20000001 \ -postScript Dump.javavec:0:4 seeds the targets of vector slots 1 to 3; slot 1 is reset at 0x45 and slot 2 is the NMI handler. entry:0x20000001 seeds caller, which in this image nothing refers to. Dump.java is a post-script that lists the memory blocks, the functions and the call instructions:
// @category Memoryimport ghidra.app.script.GhidraScript;import ghidra.program.model.listing.*;import ghidra.program.model.mem.*;import ghidra.program.model.symbol.*;
public class Dump extends GhidraScript { @Override public void run() throws Exception { for (MemoryBlock b : currentProgram.getMemory().getBlocks()) println("BLOCK " + b.getName() + " " + b.getStart() + ".." + b.getEnd() + " " + (b.isExecute() ? "x" : "-")); for (Function f : currentProgram.getFunctionManager().getFunctions(true)) println("FUNC " + f.getEntryPoint() + " " + f.getName()); for (Instruction i : currentProgram.getListing().getInstructions(true)) if (i.getFlowType().isCall()) println("CALL " + i.getAddress() + " " + i + " -> " + java.util.Arrays.toString(i.getFlows())); }}It reports:
BLOCK ram 00000000..0000006b xBLOCK ram.split 0000006c..00000077 -BLOCK ram.split.split 00000078..0000007d -BLOCK ram.split.split.split 0000007e..0000008d xBLOCK sram 20000000..20000fff xFUNC 00000044 FUN_00000044FUNC 20000000 FUN_20000000FUNC 20000008 FUN_20000008FUNC 20000100 FUN_20000100CALL 20000002 bl 0x20000100 -> [20000100]The two code slices at 0x6c and 0x78 are marked non-executable. The data slice at 0x7e keeps its flag, because nothing in this example disassembles there. Four functions exist where the flash-address import had one, the NMI handler is among them, and the BL resolves to store_one.
Step 4: check the replay
Section titled “Step 4: check the replay”- Every vector slot with the Thumb bit set lies in an executable block.
- No call or jump target in the decompile is off the image or in an unmapped range. A target such as 0x16c in the example is the symptom.
- A function seeded at a run address shows the bytes the load address holds. Read three or four functions in both views.
- Function names derived from addresses changed:
FUN_00000044stayed, the relocated ones are nowFUN_2000..... Anything that used the old names needs the translation below.
Step 5: move earlier findings
Section titled “Step 5: move earlier findings”An address inside a copied block moves by a constant: run = dst + (load - src). In the example 0x78 becomes 0x20000100 and 0x6c becomes 0x20000000. The instruction bytes are the same, but what they decode to is not: a BL decoded in the old import shows a displaced target, so a quoted listing or a call edge from it has to be redone from the new import rather than renamed. Recheck the claims instead of editing them.
Keep findings as claims a script can check: an address, the expected function or instruction text, and the value or target the note asserts, in a small tab-separated file. After the replay, translate the code addresses in that file and rerun the check against the new decompile. Expect three outcomes: a claim holds at the new address, a claim was an artefact and is retired, or a claim that said a function exists at a flash address turns out to describe the middle of a larger function. The last one is the false “new function” case: the function appeared at the load address because two relocated callers, decoded at the wrong PC, pointed there.
Step 6: scope negative claims
Section titled “Step 6: scope negative claims”“No code writes register X” or “this build never calls Y” covers only the code that was analysed. While a copy is unreplayed, state the claim with its coverage: which ranges were decompiled, and how many bytes of copied code were not, with their load and run ranges. After the replay, rerun the search over the whole program and restate the claim. A negative that was true of the flash-resident code can be false of the program, and every “no code does X” in notes made before the replay needs this second look.
Gotchas
Section titled “Gotchas”- Compressed read-write data in an Arm Compiler image cannot be replayed with a plain copy; the decompress handler expands it.8 Its destination size is the decompressed size, so an entry whose source plus size passes the image end is a compressed one. Whether such a block holds code cannot be told from the compressed bytes. Look for the evidence in step 2 that does not need the bytes: vector slots in the range and
blxtargets. - Code that runs before the copy cannot be relocated. Zephyr’s relocation documentation says kernel and architecture files can contain early initialisation code that executes before the relocation happens.4 Code that startup runs before the copy executes from flash at that time, so a block can be needed at both its load address and its run address.
- Rescan every image: addresses, sizes and even which blocks are copied change between builds.
- The same SRAM range can hold different code at different times, as an overlay. One
copystep cannot represent both, and the evidence in step 2 will count pointers to the range for both. - A copy done by a loop with computed bounds does not show up as a triple. If the table scan finds nothing and the decompiled startup code has a loop that stores to SRAM, read its bounds by hand.
- A raw import through the binary loader found no functions at all in the example when no entry was seeded, not even the reset handler. Seed the reset handler and every vector target explicitly, as the example does.
Related docs
Section titled “Related docs”- Reverse engineering with a coding agent and headless Ghidra covers checked raw-firmware imports and claim verification.
- Patching an nRF52840 gaming mouse’s firmware analyses a Cortex-M image and patches it.
- Optical-sensor register tables in mouse firmware shows a table search that depends on the code being visible at the right address.
References
Section titled “References”-
GNU Project, “Output Section LMA,” GNU ld manual. https://sourceware.org/binutils/docs/ld/Output-Section-LMA.html ↩
-
Zephyr Project, “arch/common/xip.c,” zephyr repository. https://github.com/zephyrproject-rtos/zephyr/blob/main/arch/common/xip.c ↩ ↩2
-
Zephyr Project, “arch/common/ramfunc.ld,” zephyr repository. https://github.com/zephyrproject-rtos/zephyr/blob/main/arch/common/ramfunc.ld ↩
-
Zephyr Project, “Code And Data Relocation,” Zephyr Documentation. https://docs.zephyrproject.org/latest/kernel/code-relocation.html ↩ ↩2
-
Zephyr Project, “scripts/build/gen_relocate_app.py,” zephyr repository. https://github.com/zephyrproject-rtos/zephyr/blob/main/scripts/build/gen_relocate_app.py ↩ ↩2
-
Arm, “Armv7-M Architecture Reference Manual,” DDI 0403, section on BL (immediate): the encoding T4 offset range is -16777216 to 16777214 bytes. https://developer.arm.com/documentation/ddi0403/latest/ ↩ ↩2
-
Arm, “gcc_arm.ld,” CMSIS 5 device template. https://github.com/ARM-software/CMSIS_5/blob/develop/Device/_Template_Vendor/Vendor/Device/Source/GCC/gcc_arm.ld ↩
-
Arm, “Region Table format,” Arm Compiler for Embedded User Guide. https://developer.arm.com/documentation/100748/0624/Embedded-Software-Development/Region-Table-format ↩ ↩2
-
Arm, “Vector table,” Armv8-M Exception Model User Guide. https://developer.arm.com/documentation/107706/0100/Exceptions-and-interrupts-overview/Vector-table/VTOR-register-and-initialization ↩
-
Arm, “core_cm4.h,” CMSIS 6 Core. https://github.com/ARM-software/CMSIS_6/blob/main/CMSIS/Core/Include/core_cm4.h ↩
-
NSA, “Memory,” “MemoryBlock” and “DisassembleCommand,” Ghidra API documentation. https://ghidra.re/ghidra_docs/api/ghidra/program/model/mem/Memory.html ↩
-
NSA, “Headless Analyzer,” Ghidra help (the
-preScriptand-postScriptoptions). https://github.com/NationalSecurityAgency/ghidra/blob/master/Ghidra/Features/Base/src/main/help/help/topics/HeadlessAnalyzer/HeadlessAnalyzer.htm ↩