# check_ramfunc.py

`check_ramfunc.py` checks a linked Cortex-M firmware image (ELF) for one rule: every function
reachable from a set of root functions must live in RAM. If a call chain from a root ends up in
flash, the script prints that chain and exits with status 1.

The usual reason for the rule is a fault handler. When the fault comes from flash itself (an ECC
error, or flash that is busy being erased or programmed), a handler that runs from flash can fault
again or stall. Putting the handler in RAM with a section attribute is not enough:

- A helper that the compiler does not inline becomes an ordinary call into `.text`. Under `-O0`
  and `-Og` that is the normal outcome; with LTO the same helper is often inlined and the problem
  disappears, until the next change.
- The compiler adds calls that are not in the source: `memcpy` for a struct copy, `memset` for
  `= {0}`, and the `__aeabi_*` runtime helpers for 64-bit division and, without an FPU, floating point.
- The linker adds veneers for branches that are out of range. A veneer placed in RAM can still
  jump into flash.

None of this is visible in the source code. All of it is visible in the disassembly of the linked
image, so the check runs after every link, for every build configuration.

## Requirements

- Python 3.8 or later, standard library only.
- `arm-none-eabi-objdump` from GNU binutils (any recent Arm GNU Toolchain), on the `PATH` or
  given with `--objdump`.
- An ELF with symbols, so not stripped.

## Usage

```
check_ramfunc.py [--root REGEX]... [--allow REGEX]... [--objdump PATH] [--indirect] [-v] firmware.elf
```

| Option | Meaning |
|---|---|
| `--root REGEX` | A function to start from. Matched with `re.search` against the demangled symbol names, so anchor it (`^HardFault_Handler$`) unless you mean a partial match. Required, may be repeated. A root that matches no symbol is an error, because it would silently check nothing. |
| `--allow REGEX` | A function that is allowed to be in flash. It is not reported, and the walk does not continue into it. A pattern that matches nothing is not an error: inlining differs between `-O0` and `-O2`, so an exemption needed in one build is often unused in another. |
| `--objdump PATH` | The objdump to use. Default: `arm-none-eabi-objdump`. |
| `--indirect` | Also report indirect calls (`blx`/`bx` to a register) on the walked paths. |
| `-v`, `--verbose` | Print how many functions were reached and which exemptions were used. |

Exit status: 0 when every reachable function is in RAM or exempted, 1 otherwise.

## How it works

1. Disassemble the ELF with `objdump -d -C`.
2. For each function, record its direct calls and tail calls (`bl`, `b`), its indirect calls, and
   whether it is a veneer (an `ldr pc, ...` followed by a literal address).
3. Starting from the roots, walk the call graph breadth first. A call through a veneer is followed
   to the function the veneer jumps to.
4. Every reached function whose address is outside RAM is reported with the call chain that
   reached it. The walk stops there: one report per chain is enough, and the callees of a flash
   function are not the RAM path's concern.

RAM is the Cortex-M SRAM region, `0x20000000` to `0x3FFFFFFF` (`RAM_START` and `RAM_END` at the
top of the script).

## Examples

The `example/` directory holds the code used below: a `HardFault_Handler` in RAM that saves a
fault record and then prints a report. Build it with:

```
arm-none-eabi-gcc -mcpu=cortex-m33 -mthumb -O0 -ffunction-sections -nostartfiles \
    --specs=nano.specs -T example.ld example.c -o example.elf

```

For the fixed variant, use `fixed.ld fixed.c -o fixed.elf` instead.

The output below is from Arm GNU Toolchain 15.2.Rel1 and 15.3.Rel1, which give the same result.
Another compiler version can give other addresses or inline differently. The example only links; it has no startup code that copies
`.ram_text` into RAM, so it doesn't run.

### 1. Find what leaves RAM

```
$ check_ramfunc.py --root '^HardFault_Handler$' example.elf
error: example.elf: a chain that must run from RAM reaches flash:
  HardFault_Handler -> memset at 0x0800003c is in flash
  HardFault_Handler -> read_cfsr at 0x0800001c is in flash
  HardFault_Handler -> print_fault_report at 0x08000010 is in flash
  HardFault_Handler -> save_fault_record -> memcpy at 0x0800004c is in flash
Place the callee in RAM, force it inline, keep it off this path, or --allow it if flash is deliberate there.
```

Only `read_cfsr` and `print_fault_report` are called in the source. The `memset` comes from
`struct FaultRecord record = {0};` and the `memcpy` from `saved = *record;` in
`save_fault_record`. All four calls go through linker veneers in RAM
(`__memset_veneer` and so on); the script follows each veneer to its target.

### 2. Allow the part that may be in flash

The report printed at the end has given up on recovery and is too large to move into RAM, so it
is exempted:

```
$ check_ramfunc.py -v --root '^HardFault_Handler$' --allow '^print_fault_report$' example.elf
example.elf: 6 functions reachable from 1 root(s), 1 allowed in flash
  allowed: print_fault_report
error: example.elf: a chain that must run from RAM reaches flash:
  HardFault_Handler -> memset at 0x0800003c is in flash
  HardFault_Handler -> read_cfsr at 0x0800001c is in flash
  HardFault_Handler -> save_fault_record -> memcpy at 0x0800004c is in flash
Place the callee in RAM, force it inline, keep it off this path, or --allow it if flash is deliberate there.
```

An exemption only stops the report. A function in RAM is never exempted, because the walk only
checks exemptions for functions that are already in flash.

### 3. Fix it and pass

`fixed.c` puts `read_cfsr` in RAM. `fixed.ld` moves `memcpy` and `memset` from newlib-nano into
`.ram_text`:

```
.text : { KEEP(*(.vectors)) EXCLUDE_FILE(*libc_nano.a:*memcpy*.o *libc_nano.a:*memset*.o) *(.text*) *(.rodata*) } > FLASH
.ram_text : { *(.ram_text*) *libc_nano.a:*memcpy*.o(.text*) *libc_nano.a:*memset*.o(.text*) } > RAM AT > FLASH
```

```
$ check_ramfunc.py -v --root '^HardFault_Handler$' --allow '^print_fault_report$' fixed.elf
fixed.elf: 6 functions reachable from 1 root(s), 1 allowed in flash
  allowed: print_fault_report
$ echo $?
0
```

### 4. A root that no longer exists

A renamed or removed function would otherwise make the check pass without checking anything:

```
$ check_ramfunc.py --root '^HardFault_Handler$' --root '^Fault_Handler_typo$' example.elf
error: example.elf: no symbol matches ^Fault_Handler_typo$
```

### 5. All fault handlers, with C++ exemptions

Names are demangled, so exemptions can name a namespace:

```
check_ramfunc.py firmware.elf \
    --root '^HardFault_Handler$' --root '^MemManage_Handler$' --root '^BusFault_Handler$' \
    --root '^UsageFault_Handler$' --root '^NMI_Handler$' \
    --allow '^fmt::' --allow '^print_'
```

## Running it after every link

CMake:

```cmake
add_custom_command(TARGET firmware POST_BUILD
        COMMAND "${Python3_EXECUTABLE}" "${CMAKE_SOURCE_DIR}/tools/check_ramfunc.py"
                --objdump "${CMAKE_OBJDUMP}"
                --root "^HardFault_Handler$"
                --allow "^print_fault_report$"
                "$<TARGET_FILE:firmware>"
        COMMENT "Checking that the fault handler path stays in RAM"
        VERBATIM)
```

A failing check fails the build. Run it for every build type you ship or test: the result differs
between `-O0`, `-Os` and LTO builds.

## Other uses of the same rule

Give each path its own run with its own roots and exemptions:

- Routines that erase or program flash, on parts where flash can't be read while it is being
  written.
- Code that runs while execute-in-place from external flash is turned off.
- Interrupt handlers that must not wait for flash, such as a DMA interrupt or the RTOS tick hook.
- Handlers that must be in ITCM or another tightly coupled memory: change `RAM_START` and
  `RAM_END` to that region.

## Limits

- Calls through function pointers and virtual functions are not followed, because the target is
  not in the disassembly. `--indirect` lists them so they can be reviewed by hand.
- The walk finds every function a path *could* reach through direct calls, not only the ones that
  run. A call behind a condition that never holds is still reported.
- The patterns read objdump's output for Arm Thumb code. Other architectures need other patterns
  for calls and veneers.
- The RAM range is fixed in the script. A general version would read the memory regions from the
  linker script or from the ELF's program headers.

## Licence

Copyright 2026 Michael de Lang h.o.d.n. Volt Software. The script, this README and the files in
`example/` are licensed under the [Apache License, Version 2.0](https://www.apache.org/licenses/LICENSE-2.0);
the full text is in `LICENSE`. When you redistribute them, or a work based on them, keep the
`NOTICE` file with it (section 4(d) of the licence).
