#!/usr/bin/env python3
#  Copyright 2026 Michael de Lang h.o.d.n. Volt Software
#  SPDX-License-Identifier: Apache-2.0
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

"""Verify that every function reachable from a set of roots lives in RAM, by reading the linked ELF.

Example: fault handlers on a Cortex-M microcontroller. When a fault comes from flash itself
(an ECC error, or flash busy being erased or programmed), a handler that executes from flash
can fault again or stall. So the handlers are placed in RAM with a section attribute. That
alone does not keep the whole path in RAM:

  - a helper the compiler declines to inline becomes an ordinary call into .text, which
    under -O0 and -Og is the normal outcome, while LTO hides it by inlining everything;
  - the compiler inserts calls the source never wrote, such as memcpy, memset and the
    __aeabi_* runtime helpers, and those live in flash unless placed otherwise;
  - the linker inserts veneers for branches that are out of range. A veneer placed in RAM
    may jump anywhere, so it is resolved to its target, never trusted.

None of this is visible in the source. All of it is visible in the disassembly of the linked
image, which is why the check runs after every link, per build configuration.

How it works:

  1. Disassemble the ELF with objdump and record, per function, its direct calls and tail
     calls (bl, b) and the veneers (ldr pc, followed by a literal target address).
  2. Starting from the functions matching --root, walk the call graph breadth first,
     following veneers to the function they reach.
  3. Every reachable function whose address is outside RAM is a violation, reported with
     the call chain that reached it. Traversal stops there: its callees are flash's problem,
     and one report per chain is enough.

Exemptions (--allow): a root set often covers a path that is only partly meant to be in RAM.
A fault handler first writes a fault record, which has to survive unreadable flash, and then
prints a report (formatting, backtrace, register dump). The report has given up on recovery
already and is far too large to move into RAM. Without exemptions such a root set reports its
own design and gets ignored, which is worse than not checking at all. An exemption only
suppresses the report: traversal stops at a flash function either way, so --allow cannot hide
a caller that is in RAM.

A root pattern that matches no symbol is an error, because it would silently check nothing.
An --allow pattern that matches nothing is not: inlining differs per configuration, so an
exemption needed at -O0 is routinely unused at -O2.

Limits: calls through function pointers (blx/bx to a register) are not followed, because the
target is not known from the disassembly. --indirect reports them, so they can at least be
reviewed. Call-graph reachability is an over-approximation of what runs, never an
under-approximation for direct calls.

Usage, with the fault handlers as roots:

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

import argparse
import re
import subprocess
import sys

#  The SRAM region of the Cortex-M default memory map. A part with ITCM, or SRAM elsewhere,
#  needs its own ranges: ideally they come from the linker script's memory regions.
RAM_START = 0x20000000
RAM_END = 0x40000000

#  "20005186:\tf000 f9af \tbl\t200054e8 <name>": address, raw halfwords, mnemonic, operands.
#  The name capture is greedy to the last '>' on the line: a demangled C++ template carries
#  its own angle brackets, and stopping at the first one truncates the name, which can then
#  match an --allow pattern it should not.
RAW = r"(?:[0-9a-f]{4,8}(?:\s+[0-9a-f]{4,8})*\s+)?"
LABEL = re.compile(r"^([0-9a-f]+)\s+<(.+)>:\s*$")
CALL = re.compile(r"^\s*([0-9a-f]+):\s+" + RAW + r"(bl|blx|b|b\.w|b\.n)\s+(?:0x)?([0-9a-f]+)\s*<(.*)>\s*$")
INDIRECT = re.compile(r"^\s*([0-9a-f]+):\s+" + RAW + r"(?:blx|bx)\s+(?!lr\b)[a-z]")
WORD = re.compile(r"^\s*([0-9a-f]+):\s+" + RAW + r"\.word\s+0x([0-9a-f]+)")
LOAD_PC = re.compile(r"^\s*([0-9a-f]+):\s+" + RAW + r"ldr(?:\.w)?\s+pc,")


def in_ram(address):
    return RAM_START <= address < RAM_END


class Program:
    """Functions, their direct call edges and the veneers those edges pass through."""

    def __init__(self, lines):
        self.names = {}      # entry address -> symbol name
        self.calls = {}      # entry address -> [(target address, target name)]
        self.indirect = {}   # entry address -> [instruction text]
        self.veneers = {}    # veneer entry address -> address it jumps to
        current, pending = None, None
        for line in lines:
            label = LABEL.match(line)
            if label:
                current = int(label.group(1), 16)
                pending = None
                self.names[current] = label.group(2)
                self.calls.setdefault(current, [])
                continue
            if current is None:
                continue
            if LOAD_PC.match(line):
                pending = current
                continue
            word = WORD.match(line)
            if word:
                if pending is not None:
                    self.veneers[pending] = int(word.group(2), 16) & ~1  # Clear the Thumb bit.
                    pending = None
                continue
            call = CALL.match(line)
            if call:
                target = int(call.group(3), 16)
                if target != current:  # A branch back to the entry is a loop, not a call.
                    self.calls[current].append((target, call.group(4)))
                continue
            if INDIRECT.match(line):
                self.indirect.setdefault(current, []).append(line.strip())

    def entry_of(self, address):
        """The function an address belongs to; a branch may land past the entry label."""
        if address in self.names:
            return address
        candidates = [entry for entry in self.names if entry <= address]
        return max(candidates) if candidates else address

    def resolve(self, address):
        """Follow veneers to the function they actually reach."""
        seen = set()
        while address in self.veneers and address not in seen:
            seen.add(address)
            address = self.veneers[address]
        return address

    def roots(self, patterns):
        found = {}
        for pattern in patterns:
            matches = [entry for entry, name in self.names.items()
                       if not name.endswith("_veneer") and re.search(pattern, name)]
            if matches:
                found[pattern] = matches
        return found


def walk(program, roots, report_indirect, allowed=()):
    """Every function reachable from the roots, with the path that got there."""
    violations, visited, exempted = [], set(), set()
    queue = [(entry, [program.names[entry]]) for entries in roots.values() for entry in entries]
    while queue:
        entry, path = queue.pop(0)
        if entry in visited:
            continue
        visited.add(entry)
        if not in_ram(entry):
            name = program.names.get(entry, "")
            if any(pattern.search(name) for pattern in allowed):
                exempted.add(name)
            else:
                violations.append(f"{' -> '.join(path)} at 0x{entry:08x} is in flash")
            continue  # Its callees are flash's problem; one report per chain is enough.
        if report_indirect and entry in program.indirect:
            for instruction in program.indirect[entry]:
                violations.append(f"{' -> '.join(path)}: unresolved indirect branch: {instruction}")
        for target, name in program.calls.get(entry, []):
            resolved = program.entry_of(program.resolve(target))
            if resolved in visited:
                continue
            queue.append((resolved, path + [program.names.get(resolved, name)]))
    return violations, visited, exempted


def main():
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("elf")
    parser.add_argument("--root", action="append", required=True,
                        help="regex matched against demangled symbol names; every function "
                             "reachable from a match must live in RAM")
    parser.add_argument("--allow", action="append", default=[],
                        help="regex matched against demangled symbol names; a match that is in "
                             "flash is deliberate and not reported")
    parser.add_argument("--objdump", default="arm-none-eabi-objdump")
    parser.add_argument("--indirect", action="store_true", help="also report indirect branches in the chain")
    parser.add_argument("-v", "--verbose", action="store_true")
    arguments = parser.parse_args()

    disassembly = subprocess.run([arguments.objdump, "-d", "-C", arguments.elf],
                                 capture_output=True, text=True, check=True).stdout.splitlines()
    program = Program(disassembly)

    roots = program.roots(arguments.root)
    missing = [pattern for pattern in arguments.root if pattern not in roots]
    if missing:
        # A root that no longer exists would silently check nothing at all.
        print(f"error: {arguments.elf}: no symbol matches {', '.join(missing)}", file=sys.stderr)
        return 1
    try:
        allowed = [re.compile(pattern) for pattern in arguments.allow]
    except re.error as error:
        print(f"error: --allow {error.pattern!r} is not a valid regex: {error}", file=sys.stderr)
        return 1

    violations, visited, exempted = walk(program, roots, arguments.indirect, allowed)
    if arguments.verbose:
        print(f"{arguments.elf}: {len(visited)} functions reachable from {len(roots)} root(s), "
              f"{len(exempted)} allowed in flash", file=sys.stderr)
        for name in sorted(exempted):
            print(f"  allowed: {name}", file=sys.stderr)
    if violations:
        print(f"error: {arguments.elf}: a chain that must run from RAM reaches flash:", file=sys.stderr)
        for violation in violations:
            print(f"  {violation}", file=sys.stderr)
        print("Place the callee in RAM, force it inline, keep it off this path, "
              "or --allow it if flash is deliberate there.", file=sys.stderr)
        return 1
    return 0


if __name__ == "__main__":
    sys.exit(main())
