Skip to content
systemcoding.dev
Embedded

Track Firmware Size Growth Per Commit in CI With a Size Budget Script

Fail a CI build when firmware flash or RAM use passes a budget or jumps between commits, using arm-none-eabi-size, a short Python script and a JSON budget file.

6 min read
Summarize in AI
Flat illustration of a microcontroller wired to an LED and a sensor, with the Arm, GNU and C logos.

Firmware does not run out of flash in one commit. It runs out in forty small ones, each adding a few hundred bytes, until a feature that should have taken a day needs a week of squeezing. A size budget in CI catches the drift while each commit is still the cause of its own growth. This post builds one: a Python script that reads arm-none-eabi-size output, compares flash and RAM use with a limit and with the numbers from the main branch, and fails the job with a message that names the delta. It uses arm-none-eabi-size from the Arm GNU Toolchain 13.2 and Python 3.11, and needs nothing beyond the standard library.

What the size tool reports

arm-none-eabi-size prints three numbers per ELF file in its default Berkeley format:

Text
arm-none-eabi-size firmware.elf
Text
   text	   data	    bss	    dec	    hex	filename
  41236	    412	   5316	  46964	   b774	firmware.elf

The columns mean different things from what you might guess, and the budget script must map them correctly:

ColumnContentsLives in
textCode and read-only dataFlash
dataInitialised variables, their initial valuesFlash image and RAM
bssZero-initialised variablesRAM only

Flash used is text + data, because the initial values of .data are stored in the image after the code. RAM used by static data is data + bss. The heap and stack are not in these numbers: the linker reserves them but the size tool counts only sections. A budget for RAM should therefore leave a margin for stack and heap, and the linker script's _Min_Stack_Size and _Min_Heap_Size reservations are the better place to enforce those.

Note that text includes .rodata and the vector table, and in a build with --gc-sections it counts what survived the garbage collection. Different linker scripts may place some read-only data in another section, such as a .ARM.exidx table; the column then differs from "everything in flash". The authoritative figure is the linker's own --print-memory-usage table, and you can parse that instead if you prefer.

The budget file

A JSON file in the repository states the limits and the allowed growth per commit. Reviewers change it by pull request, which makes raising the limit a visible decision:

size-budget.jsonJSON
{
  "flash": { "limit": 262144, "max_growth": 512 },
  "ram":   { "limit": 65536,  "max_growth": 256 }
}

limit is the hard ceiling in bytes (a 256 KiB flash region and 64 KiB of RAM here). max_growth is how much one commit may add compared with its baseline. A hard limit stops the worst case; a growth cap catches a slow increase that never hits the ceiling until the last week.

The script

size_budget.pypython
#!/usr/bin/env python3
"""Compare firmware size against a budget and a baseline."""
import json
import subprocess
import sys


def measure(elf):
    out = subprocess.run(
        ["arm-none-eabi-size", elf],
        check=True, capture_output=True, text=True,
    ).stdout.splitlines()
    text, data, bss = (int(x) for x in out[1].split()[:3])
    return {"flash": text + data, "ram": data + bss}


def main():
    elf, budget_path, baseline_path = sys.argv[1:4]
    budget = json.load(open(budget_path))
    now = measure(elf)

    try:
        base = json.load(open(baseline_path))
    except FileNotFoundError:
        base = None

    failed = False
    for key in ("flash", "ram"):
        limit = budget[key]["limit"]
        used = now[key]
        line = f"{key}: {used} of {limit} bytes ({used * 100 / limit:.1f}%)"
        if base is not None:
            delta = used - base[key]
            line += f", {delta:+d} vs baseline"
            if delta > budget[key]["max_growth"]:
                line += f"  FAIL: growth over {budget[key]['max_growth']}"
                failed = True
        if used > limit:
            line += "  FAIL: over limit"
            failed = True
        print(line)

    json.dump(now, open("size-now.json", "w"))
    return 1 if failed else 0


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

The script prints one line per region and exits with status 1 if a limit or a growth cap is broken. It writes size-now.json so the job can store it as the next baseline. The first line of arm-none-eabi-size output is the header, so out[1] is the data row and split()[:3] takes text, data and bss.

Run on the example above with a baseline from the previous commit:

Text
python3 size_budget.py build/firmware.elf size-budget.json baseline.json
Text
flash: 41648 of 262144 bytes (15.9%), +96 vs baseline
ram: 5728 of 65536 bytes (8.7%), +0 vs baseline

Flash is 41236 + 412 = 41648, RAM is 412 + 5316 = 5728, and the baseline numbers here are an example. A commit that adds 900 bytes would print +900 vs baseline FAIL: growth over 512 and exit 1.

Where the baseline comes from

The baseline is the size of the target branch's last good build. There are two honest ways to keep it, and one trap.

Store it as a build artifact. The job on the main branch uploads size-now.json as an artifact. A pull request job downloads the artifact from the latest successful main run and passes it as baseline.json. No extra repository commits, and the baseline is exactly what the main build produced.

Rebuild the base commit. The job checks out the merge base, builds it, measures it, then builds the pull request head. It doubles build time but needs no stored state and is correct even when main moved. For firmware that builds in seconds, this is the simplest.

The trap is committing the baseline file to the repository. Every commit then has to update it, merge conflicts appear on every pair of branches that both change size, and people start regenerating it blindly to make the check pass, which defeats it.

A GitHub Actions step for the artifact approach looks like this:

.github/workflows/size.ymlYAML
name: size
on: [pull_request]

jobs:
  size:
    runs-on: ubuntu-24.04
    steps:
      - uses: actions/checkout@v4
      - name: Install toolchain
        run: sudo apt-get install -y gcc-arm-none-eabi
      - name: Build
        run: make
      - name: Fetch baseline
        uses: dawidd6/action-download-artifact@v6
        with:
          workflow: size-main.yml
          branch: main
          name: size-baseline
          if_no_artifact_found: ignore
      - name: Check budget
        run: python3 size_budget.py build/firmware.elf size-budget.json size-now.json

The third-party download action is one choice, and you can use gh run download from the GitHub CLI for the same effect. When no artifact is found, the script skips the growth check because the baseline file is missing, and the hard limit still applies.

Making the failure useful

A bare "growth over 512" starts an argument about whose commit did it. Two additions help. The first is a size diff by symbol, using arm-none-eabi-nm --size-sort -S on both ELF files and printing the symbols that changed most; the post on reading a linker map shows how to read that. The second is a per-section table from arm-none-eabi-size -A, which splits .text, .rodata, .data and so on, so a reviewer sees that the growth is in .rodata (a new lookup table) rather than code.

Print the failure as a pull request comment or job summary, not just a red cross, and say what the author should do: reduce the change, or raise max_growth in size-budget.json in the same pull request with a reason.

Choosing the numbers

The hard limit should be a little under the physical region, not equal to it: leave room for a bootloader's configuration page, a calibration block at the end of flash or the settings area that the application writes at run time. The growth cap should be small enough to matter but larger than the noise of a normal commit. A commit that does nothing but add a log line can still move the size by several bytes through alignment and padding. A cap of a few hundred bytes catches real additions without flagging compiler noise. Review the cap every release, since the code that justifies a larger one is usually a deliberate feature.

When the toolchain version changes, expect a jump in every number. Update the baseline with that change, not a growth exception: pin the compiler version in CI so the comparison is between commits, not between compilers.

Also inToolchains
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.