diff --git a/.github/workflows/flash_analysis.yml b/.github/workflows/flash_analysis.yml index d98fa8924db..4d131936bcc 100644 --- a/.github/workflows/flash_analysis.yml +++ b/.github/workflows/flash_analysis.yml @@ -33,8 +33,10 @@ jobs: image: ghcr.io/px4/px4-dev:v1.17.0-rc2 strategy: matrix: - target: [px4_fmu-v5x, px4_fmu-v6x] + target: [px4_fmu-v2, px4_fmu-v5x, px4_fmu-v6x] outputs: + px4_fmu-v2-bloaty-output: ${{ steps.gen-output.outputs.px4_fmu-v2-bloaty-output }} + px4_fmu-v2-memory-summary: ${{ steps.gen-output.outputs.px4_fmu-v2-memory-summary }} px4_fmu-v5x-bloaty-output: ${{ steps.gen-output.outputs.px4_fmu-v5x-bloaty-output }} px4_fmu-v5x-memory-summary: ${{ steps.gen-output.outputs.px4_fmu-v5x-memory-summary }} px4_fmu-v6x-bloaty-output: ${{ steps.gen-output.outputs.px4_fmu-v6x-bloaty-output }} @@ -79,8 +81,11 @@ jobs: - name: Build Target run: make ${{ matrix.target }}_flash-analysis - - name: Store the ELF with the change - run: cp ./build/**/*.elf ./with-change.elf + - name: Store the ELF and linker script with the change + run: | + cp ./build/**/*.elf ./with-change.elf + board=$(echo "${{ matrix.target }}" | sed 's|_|/|') + cp "boards/$board/nuttx-config/scripts/script.ld" ./with-change.ld - name: Cache - Stats after Current Build run: ccache -s @@ -108,6 +113,10 @@ jobs: if: github.event_name == 'push' run: git checkout ${{ github.event.before }} + - name: Keep flash-analysis variants added by the change + # A target new to the matrix has no flash-analysis variant on the baseline. + run: git diff --name-only --diff-filter=A HEAD ${{ github.sha }} -- 'boards/*flash-analysis*' | xargs -r git checkout ${{ github.sha }} -- + - name: Update submodules run: make submodulesupdate @@ -153,7 +162,7 @@ jobs: BLOATY_OUTPUT: ${{ steps.bloaty-step.outputs.bloaty-output }} run: | summary=$(python3 "$RUNNER_TEMP/firmware_size.py" \ - --before before-change.elf --after with-change.elf) + --before before-change.elf --after with-change.elf --linker-script with-change.ld) EOF=$(dd if=/dev/urandom bs=15 count=1 status=none | base64) { echo "${{ matrix.target }}-memory-summary=$summary" @@ -167,12 +176,9 @@ jobs: runs-on: [runs-on,runner=1cpu-linux-x64,image=ubuntu24-full-x64,"run-id=${{ github.run_id }}"] needs: [analyze_flash] env: - V5X_FLASH: ${{ fromJSON(needs.analyze_flash.outputs.px4_fmu-v5x-memory-summary).flash }} - V5X_RAM: ${{ fromJSON(needs.analyze_flash.outputs.px4_fmu-v5x-memory-summary).ram }} - V5X_CHANGED: ${{ fromJSON(needs.analyze_flash.outputs.px4_fmu-v5x-memory-summary).changed }} - V6X_FLASH: ${{ fromJSON(needs.analyze_flash.outputs.px4_fmu-v6x-memory-summary).flash }} - V6X_RAM: ${{ fromJSON(needs.analyze_flash.outputs.px4_fmu-v6x-memory-summary).ram }} - V6X_CHANGED: ${{ fromJSON(needs.analyze_flash.outputs.px4_fmu-v6x-memory-summary).changed }} + V2: ${{ needs.analyze_flash.outputs.px4_fmu-v2-memory-summary }} + V5X: ${{ needs.analyze_flash.outputs.px4_fmu-v5x-memory-summary }} + V6X: ${{ needs.analyze_flash.outputs.px4_fmu-v6x-memory-summary }} if: github.event.pull_request steps: - name: Find Comment @@ -193,8 +199,9 @@ jobs: # This can't be moved to the job-level conditions, as GH actions don't allow a job-level if condition to access the env. if: | steps.fc.outputs.comment-id != '' || - env.V5X_CHANGED == 'true' || - env.V6X_CHANGED == 'true' + fromJSON(env.V2).changed || + fromJSON(env.V5X).changed || + fromJSON(env.V6X).changed run: | mkdir -p pr-comment cat > pr-comment/manifest.json < ## 🔎 Flash and RAM Analysis - | Target | Flash change | Static RAM change | - | --- | ---: | ---: | - | px4_fmu-v5x | ${{ env.V5X_FLASH }} | ${{ env.V5X_RAM }} | - | px4_fmu-v6x | ${{ env.V6X_FLASH }} | ${{ env.V6X_RAM }} | + | Target | Flash change | Flash used | Static RAM change | Static RAM used | + | --- | ---: | ---: | ---: | ---: | + | px4_fmu-v2 (F4) | ${{ fromJSON(env.V2).flash }} | ${{ fromJSON(env.V2).flash_used }} | ${{ fromJSON(env.V2).ram }} | ${{ fromJSON(env.V2).ram_used }} | + | px4_fmu-v5x (F7) | ${{ fromJSON(env.V5X).flash }} | ${{ fromJSON(env.V5X).flash_used }} | ${{ fromJSON(env.V5X).ram }} | ${{ fromJSON(env.V5X).ram_used }} | + | px4_fmu-v6x (H7) | ${{ fromJSON(env.V6X).flash }} | ${{ fromJSON(env.V6X).flash_used }} | ${{ fromJSON(env.V6X).ram }} | ${{ fromJSON(env.V6X).ram_used }} | + +
+ px4_fmu-v2 — Bloaty section/symbol breakdown + + ``` + ${{ needs.analyze_flash.outputs.px4_fmu-v2-bloaty-output }} + ``` +
px4_fmu-v5x — Bloaty section/symbol breakdown @@ -235,8 +251,9 @@ jobs: - name: Upload pr-comment artifact if: | steps.fc.outputs.comment-id != '' || - env.V5X_CHANGED == 'true' || - env.V6X_CHANGED == 'true' + fromJSON(env.V2).changed || + fromJSON(env.V5X).changed || + fromJSON(env.V6X).changed uses: actions/upload-artifact@v7 with: name: pr-comment diff --git a/Tools/ci/firmware_size.py b/Tools/ci/firmware_size.py index ab80a4c96b5..a1482aaf178 100644 --- a/Tools/ci/firmware_size.py +++ b/Tools/ci/firmware_size.py @@ -5,12 +5,21 @@ import argparse import json import os from pathlib import Path +import re import subprocess # The commit hash compiled into px4_firmware_version_binary() changes its code # size, so identical sources on two commits can differ by up to 16 B. MIN_REPORTED_DELTA = 30 +LD_COMMENT = re.compile(r"/\*.*?\*/", re.S) +LD_MEMORY = re.compile(r"\bMEMORY\s*\{(.*?)\}", re.S) +LD_REGION = re.compile( + r"(?P\w+)\s*(?:\((?P[^)]*)\))?\s*:\s*" + r"(?:ORIGIN|org|o)\s*=\s*(?P\w+)\s*,\s*" + r"(?:LENGTH|len|l)\s*=\s*(?P\w+)" +) + def memory_usage(elf: Path) -> dict[str, int]: # Sections rather than program headers: ld may map the ELF header into the @@ -48,7 +57,35 @@ def memory_usage(elf: Path) -> dict[str, int]: raise ValueError(f"{elf}: no flash load image found") # Include alignment gaps in the programmed image, as objcopy -O binary does. - return {"flash": image_end - image_start, "ram": ram} + return {"flash": image_end - image_start, "ram": ram, "image_start": image_start} + + +def ld_number(text: str) -> int: + scale = {"K": 1 << 10, "M": 1 << 20}.get(text[-1].upper(), 1) + return int(text[:-1] if scale > 1 else text, 0) * scale + + +def memory_capacity(linker_script: Path, image_start: int) -> dict[str, int]: + # Read the board's own script: the analysis build links against an + # oversized flash region so that a change which overflows still links. + text = LD_COMMENT.sub("", linker_script.read_text()) + regions = {} + for block in LD_MEMORY.findall(text): + if re.sub(r"[\s,]", "", LD_REGION.sub("", block)): + raise ValueError(f"{linker_script}: MEMORY entry this parser cannot read") + for region in LD_REGION.finditer(block): + writable = "w" in (region["attributes"] or "").split("!")[0].lower() + regions[region["name"]] = (writable, ld_number(region["origin"]), ld_number(region["length"])) + + flash = [name for name, (_, origin, length) in regions.items() + if origin <= image_start < origin + length] + if len(flash) != 1: + raise ValueError(f"{linker_script}: no single region holds the image at {image_start:#x}") + _, origin, length = regions.pop(flash[0]) + return { + "flash": origin + length - image_start, + "ram": sum(length for writable, _, length in regions.values() if writable), + } def indicator(delta: int) -> str: @@ -67,10 +104,16 @@ def format_change(before: int, after: int) -> str: return f"{indicator(delta)}{delta:+,} B ({percentage})" -def summarize(before: dict[str, int], after: dict[str, int]) -> dict: +def format_usage(used: int, capacity: int) -> str: + return f"{used / capacity:.2%}" + + +def summarize(before: dict[str, int], after: dict[str, int], capacity: dict[str, int]) -> dict: return { "flash": format_change(before["flash"], after["flash"]), + "flash_used": format_usage(after["flash"], capacity["flash"]), "ram": format_change(before["ram"], after["ram"]), + "ram_used": format_usage(after["ram"], capacity["ram"]), "changed": any(abs(after[key] - before[key]) >= MIN_REPORTED_DELTA for key in ("flash", "ram")), } @@ -80,10 +123,12 @@ def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--before", type=Path, required=True) parser.add_argument("--after", type=Path, required=True) + parser.add_argument("--linker-script", type=Path, required=True) args = parser.parse_args() before = memory_usage(args.before) after = memory_usage(args.after) - print(json.dumps(summarize(before, after))) + capacity = memory_capacity(args.linker_script, after["image_start"]) + print(json.dumps(summarize(before, after, capacity))) if __name__ == "__main__": diff --git a/Tools/ci/test_firmware_size.py b/Tools/ci/test_firmware_size.py index 35ec7743f2b..efde280cb91 100644 --- a/Tools/ci/test_firmware_size.py +++ b/Tools/ci/test_firmware_size.py @@ -7,8 +7,9 @@ import sys import tempfile import unittest -from firmware_size import format_change, memory_usage, summarize +from firmware_size import format_change, memory_capacity, memory_usage, summarize +CAPACITY = {"flash": 1008 * 1024, "ram": 256 * 1024} class FirmwareSizeTest(unittest.TestCase): def setUp(self): @@ -68,6 +69,7 @@ SECTIONS "arm-none-eabi-objcopy", "-O", "binary", str(elf), str(binary) ], check=True) self.assertEqual(usage["flash"], binary.stat().st_size) + self.assertEqual(usage.pop("image_start"), 0x08008000) return usage def test_bss_and_reserved_buffers_only_use_ram(self): @@ -102,18 +104,38 @@ SECTIONS {"flash": 64, "ram": 80}, ) + def test_capacity_from_linker_regions(self): + # The flash alias is neither the image's region nor RAM. + self.linker.write_text(self.linker.read_text().replace( + "MEMORY\n{", "MEMORY\n{\n FLASH_ITCM (rx) : ORIGIN = 0x00208000, LENGTH = 2016K /* alias */" + )) + self.assertEqual(memory_capacity(self.linker, 0x08008000), + {"flash": 2016 * 1024, "ram": (16 + 368 + 64) * 1024}) + + def test_capacity_fails_loudly(self): + with self.assertRaisesRegex(ValueError, "no single region"): + memory_capacity(self.linker, 0x09000000) + self.linker.write_text(self.linker.read_text().replace("LENGTH = 2016K", "LENGTH = 2M - 32K")) + with self.assertRaisesRegex(ValueError, "cannot read"): + memory_capacity(self.linker, 0x08008000) + def test_opposing_changes_do_not_cancel_comment(self): - result = summarize({"flash": 1024, "ram": 1024}, {"flash": 1088, "ram": 960}) + result = summarize({"flash": 1024, "ram": 1024}, {"flash": 1088, "ram": 960}, CAPACITY) self.assertTrue(result["changed"]) self.assertEqual(result["flash"], "+64 B (+6.25%)") self.assertEqual(result["ram"], "-64 B (-6.25%)") - self.assertFalse(summarize({"flash": 1, "ram": 0}, {"flash": 1, "ram": 0})["changed"]) + self.assertFalse(summarize({"flash": 1, "ram": 0}, {"flash": 1, "ram": 0}, CAPACITY)["changed"]) self.assertEqual(format_change(0, 4488), "🔴 +4,488 B (n/a)") + def test_usage_is_the_change_against_capacity(self): + result = summarize({"flash": 1024, "ram": 1024}, {"flash": 1032192, "ram": 3840}, CAPACITY) + self.assertEqual(result["flash_used"], "100.00%") + self.assertEqual(result["ram_used"], "1.46%") + def test_small_deltas_are_not_reported(self): before = {"flash": 1000, "ram": 1000} - self.assertFalse(summarize(before, {"flash": 992, "ram": 1029})["changed"]) - self.assertTrue(summarize(before, {"flash": 970, "ram": 1000})["changed"]) + self.assertFalse(summarize(before, {"flash": 992, "ram": 1029}, CAPACITY)["changed"]) + self.assertTrue(summarize(before, {"flash": 970, "ram": 1000}, CAPACITY)["changed"]) def test_change_indicator(self): for delta, expected in ((1001, "🔴 "), (1000, "🟡 "), (101, "🟡 "), (100, ""), @@ -127,10 +149,11 @@ SECTIONS after = self.build("after", bss=96) output = subprocess.check_output([ sys.executable, str(Path(__file__).with_name("firmware_size.py").resolve()), - "--before", str(before), "--after", str(after), + "--before", str(before), "--after", str(after), "--linker-script", str(self.linker), ], cwd=self.root, text=True) self.assertEqual(json.loads(output), { - "flash": "+0 B (+0.00%)", "ram": "+64 B (+80.00%)", "changed": True, + "flash": "+0 B (+0.00%)", "flash_used": "0.00%", + "ram": "+64 B (+80.00%)", "ram_used": "0.03%", "changed": True, }) diff --git a/boards/px4/fmu-v2/flash-analysis.px4board b/boards/px4/fmu-v2/flash-analysis.px4board new file mode 100644 index 00000000000..30717ad93ca --- /dev/null +++ b/boards/px4/fmu-v2/flash-analysis.px4board @@ -0,0 +1 @@ +CONFIG_BOARD_LINKER_PREFIX="flash-analysis" diff --git a/boards/px4/fmu-v2/nuttx-config/scripts/flash-analysis-script.ld b/boards/px4/fmu-v2/nuttx-config/scripts/flash-analysis-script.ld new file mode 100644 index 00000000000..3b2f4c42c58 --- /dev/null +++ b/boards/px4/fmu-v2/nuttx-config/scripts/flash-analysis-script.ld @@ -0,0 +1,6 @@ +INCLUDE "script.ld" + +MEMORY +{ + flash (rx) : ORIGIN = 0x08004000, LENGTH = 10080K +}