diff --git a/TOOLS/check_filament_usage.py b/TOOLS/check_filament_usage.py new file mode 100644 index 0000000..7df06b6 --- /dev/null +++ b/TOOLS/check_filament_usage.py @@ -0,0 +1,100 @@ +#!/usr/bin/env python3 +"""Read-only, bounded adaptation of lp55's cc-fw-tools PR #106 observer. + +Source: https://github.com/OpenCentauri/cc-fw-tools/pull/106#issuecomment-5357240641 +This script does not heat, move, extrude, upload files, or start a print. +""" +import argparse +import asyncio +import json +import math +import sys +import time + +FIELDS = ( + ("TotalExtrusion", "54 6F 74 61 6C 45 78 74 72 75 73 69 6F 6E 00"), + ("CurrentExtrusion", "43 75 72 72 65 6E 74 45 78 74 72 75 73 69 6F 6E 00"), +) + + +def extract_usage(message): + if not isinstance(message, dict): + return None + status = message.get("Status") + if not isinstance(status, dict) or not isinstance(status.get("PrintInfo"), dict): + return None + info = status["PrintInfo"] + result = {} + for plain, legacy in FIELDS: + key = plain if plain in info else legacy + value = info.get(key) + if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value): + return None + result[key] = value + return result + + +def self_test(): + normal = {"Status": {"PrintInfo": {"TotalExtrusion": 0.0, "CurrentExtrusion": -2.0}}} + assert extract_usage(normal) == normal["Status"]["PrintInfo"] + legacy = {"Status": {"PrintInfo": {FIELDS[0][1]: 10.0, FIELDS[1][1]: 3.0}}} + assert extract_usage(legacy) == legacy["Status"]["PrintInfo"] + mixed = {"Status": {"PrintInfo": {"TotalExtrusion": 0.0, FIELDS[0][1]: 99.0, FIELDS[1][1]: 0.0}}} + assert extract_usage(mixed) == {"TotalExtrusion": 0.0, FIELDS[1][1]: 0.0} + for value in (None, True, "1", float("nan"), float("inf")): + assert extract_usage({"Status": {"PrintInfo": {"TotalExtrusion": value, "CurrentExtrusion": 0.0}}}) is None + assert extract_usage({"Status": {"PrintInfo": {}}}) is None + assert extract_usage({"Data": {"TotalExtrusion": 10, "CurrentExtrusion": 3}}) is None + print("filament observer parser self-test passed") + + +async def observe(ip, seconds, require_change): + import websockets + good = 0 + changed = False + deadline = time.monotonic() + seconds + # ponytail: no extra close-handshake wait after the observation deadline. + async with websockets.connect(f"ws://{ip}:3030/websocket", open_timeout=seconds, close_timeout=0) as ws: + while True: + remaining = deadline - time.monotonic() + if remaining <= 0: + break + try: + raw = await asyncio.wait_for(ws.recv(), timeout=remaining) + except asyncio.TimeoutError: + break + try: + message = json.loads(raw) + except (ValueError, UnicodeDecodeError): + continue + usage = extract_usage(message) + if usage is not None: + good += 1 + delta_key = FIELDS[1][0] if FIELDS[1][0] in usage else FIELDS[1][1] + changed |= usage[delta_key] != 0 + print(json.dumps({"at": time.monotonic(), "Status": {"PrintInfo": usage}}), flush=True) + print(f"numeric_samples={good} nonzero_delta={changed}", file=sys.stderr) + return 0 if good and (changed or not require_change) else 1 + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("ip", nargs="?") + parser.add_argument("--seconds", type=float, default=30.0) + parser.add_argument("--require-change", action="store_true") + parser.add_argument("--self-test", action="store_true") + args = parser.parse_args() + if args.self_test: + self_test() + return 0 + if not args.ip or not math.isfinite(args.seconds) or args.seconds <= 0: + parser.error("provide a printer IP and a positive finite --seconds") + try: + return asyncio.run(observe(args.ip, args.seconds, args.require_change)) + except Exception as exc: + print(f"filament observer failed: {type(exc).__name__}: {exc}", file=sys.stderr) + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/TOOLS/firmware_version.py b/TOOLS/firmware_version.py index 2746f4c..a1977e9 100644 --- a/TOOLS/firmware_version.py +++ b/TOOLS/firmware_version.py @@ -16,6 +16,30 @@ def _git(repo_root: str, *args: str) -> str: ).stdout.strip() +def _declared_version(repo_root: str) -> str | None: + """OC_VERSION from the build env, else from the active patch_config edition. + + patch_planner injects the edition variables into the environment of the patch + scripts it launches, but the manifest and patch-summary tools run as separate + processes to that planner. Reading the edition file here keeps the reported + version identical to the one written into app/app. + """ + value = os.getenv("OC_VERSION") + if value: + return value + edition = os.path.join(repo_root, "oc-patches", "patch_config") + try: + with open(edition, encoding="utf-8") as stream: + for line in stream: + line = line.split("#", 1)[0].strip() + key, separator, val = line.partition("=") + if separator and key.strip() == "OC_VERSION" and val.strip(): + return val.strip().strip("'\"") + except OSError: + return None + return None + + def firmware_version(repo_root: str) -> str: """Return the OpenCentauri firmware version for the build commit.""" # Integration branches named vX.Y.Z-integrate are pre-release dev lines: @@ -34,6 +58,16 @@ def firmware_version(repo_root: str) -> str: ) return f"{m.group(1)}-beta-{sha[:7]}-oc" + # Release builds declare the version they ship instead of inheriting whatever + # tag git-describe lands on: main is always ahead of the last release tag, so + # describe would report the previous version plus a commit count. + declared = _declared_version(repo_root) + if declared: + m = re.fullmatch(r"v?(\d+\.\d+\.\d+)", declared.strip()) + if not m: + raise ValueError(f"OC_VERSION must be X.Y.Z or vX.Y.Z, got {declared!r}") + return f"{m.group(1)}-oc" + command = ["describe", "--tags"] build_commit = os.getenv("OC_BUILD_COMMIT") if build_commit: diff --git a/firmware-editions/patched b/firmware-editions/patched index c702fa5..1d70f0c 100644 --- a/firmware-editions/patched +++ b/firmware-editions/patched @@ -38,4 +38,9 @@ UPLOAD_DURING_PRINTING=true UBOOT=true UART=true MISC_APP=true +# What release builds report as their firmware version. Bump this with each release +# and tag the same version; without it the build falls back to git-describe, which on +# main reports the previous release plus a commit count. +OC_VERSION='0.5.1' + SPOOF_SLICER_FIRMWARE_VERSION=true diff --git a/oc-patches/cc1-app/AGENT-1.4.49.md b/oc-patches/cc1-app/AGENT-1.4.49.md index b7943ec..77675e5 100644 --- a/oc-patches/cc1-app/AGENT-1.4.49.md +++ b/oc-patches/cc1-app/AGENT-1.4.49.md @@ -8,19 +8,20 @@ The 1.4.49 app binary uses rodata zero runs as caves (the whole rodata sits in t | Cave Address | Used By | Size | End | |--------------|---------|------|-----| -| `0x004517e0` | `spoof_slicer_firmware_version` (spoofed version string) | 8 bytes | `0x004517e7` | +| `0x004517e0` | `spoof_slicer_firmware_version` (spoofed version string, `1.4.49 OC`) | 11 bytes | `0x004517ea` | | `0x004517f0` | `wait_for_chamber_temp` trampoline (code) | 216 bytes | `0x004518c8` | -| `0x004518d0` | `report_filament_usage` injected fn (code) | 196 bytes | `0x00451994` | +| `[0x4518d0,0x451994)` | `report_filament_usage` injected fn (code) | 196 bytes | `0x451993` | | `0x004519a0` | `report_filament_usage` key strings (data) | 34 bytes | `0x004519c1` | -(All in the ~2KB rodata zero run `0x004517e0`–`0x00451fb8`. `report_filament_usage` also uses bss state doubles at `0x004b4788`/`0x004b4790` — runtime-zero, no file backing. Remaining free: `0x004519c2`–`0x00451fb8` (~1.5KB), the `0x00451fe3` run (~2KB), and four ~240B `0x0044exxx` slots. NOTE: the 1.4.46 cave `0x00450e00` is OCCUPIED in 1.4.49 — never reuse 1.4.46 cave addresses without checking. File→VA bias is `+0x10000` below file `0x48ed08` and `+0x20000` in the RW LOAD.) +(All in the ~2KB rodata zero run `0x004517e0`–`0x00451fb8`. `report_filament_usage` also uses private BSS doubles at `0x00522f08`/`0x00522f10`; writable ELF allocation and exported end symbols extended to `0x00522f18` — runtime-zero, no file backing. Remaining free: `0x004519c2`–`0x00451fb8` (~1.5KB), the `0x00451fe3` run (~2KB), and four ~240B `0x0044exxx` slots. NOTE: the 1.4.46 cave `0x00450e00` is OCCUPIED in 1.4.49 — never reuse 1.4.46 cave addresses without checking. File→VA bias is `+0x10000` below file `0x48ed08` and `+0x20000` in the RW LOAD.) ## Patch-by-Patch Breakdown ### `set-firmware-version-patch` (1.4.49) **Type:** Data string replacement (script-driven) -- File offset `0x003FAE10` (VA `0x0040ae10`): stock `"1.4.49\0\0"` replaced with the OpenCentauri git-describe version (e.g. `"0.5.0--oc"`). +- File offset `0x003FAE10` (VA `0x0040ae10`): stock `"1.4.49\0\0"` replaced with the OpenCentauri version (e.g. `"0.5.1-oc"`). - Applied by `patch.py` with a stock-bytes guard. Version string consumers (~15 sites, all `movw`/`movt` pairs) are left pointing at the same address. +- The version comes from `TOOLS/firmware_version.py`: `vX.Y.Z-integrate` branches report `X.Y.Z-beta--oc`, otherwise the `OC_VERSION` value declared in `firmware-editions/patched` wins, otherwise `git describe --tags`. Bump `OC_VERSION` with each release. **No cave used.** ### `add-chamber-light-gcode-patch` (1.4.49) @@ -54,8 +55,10 @@ The 1.4.49 app binary uses rodata zero runs as caves (the whole rodata sits in t - WebSocket/MQTT attributes: site `0x0036bd64` (file `0x0035bd64`) - Direct request-attribute: site `0x0037fbe4` (file `0x0036fbe4`) - Guard bytes (all three sites): `103e0ae3 403040e3` → new bytes `e03701e3 453040e3` (`movw r3,#0x17e0; movt r3,#0x45`). -- Disjoint from `set-firmware-version`; write order does not matter. Slicer sees `1.4.49`, logs/UI/OTA keep the OC version. -**String cave at `0x004517e0`.** See `spoof-slicer-firmware-version/README.md`. +- Disjoint from `set-firmware-version`; write order does not matter. Slicer sees `1.4.49 OC`, logs/UI/OTA keep the OC version. +- The `OC` marker is load-bearing: Home Assistant's `elegoo_printer` only creates the OpenCentauri-only filament sensors when `FirmwareVersion` carries an `OC`/`O` marker (`sensor.py` → `printer.open_centauri` → `Printer._is_open_centauri`). Without it, HA never registers `total_extrusion`/`current_extrusion` and Spoolman sees nothing, no matter what the printer pushes. +- The patch validates all four regions before writing any byte, and refuses if the cave is no longer zero (another patch claimed it). +**String cave at `0x004517e0`, 11 bytes.** See `spoof-slicer-firmware-version/README.md`. ### `allow-uploads-during-printing-patch` (1.4.49) **Type:** Python direct binary patch (`patch.py` via `patch.sh` FW_VER branch; two-pass byte-guarded) @@ -87,14 +90,27 @@ The 1.4.49 app binary uses rodata zero runs as caves (the whole rodata sits in t ### `report-filament-usage` (1.4.49) **Type:** Hook + code cave injected fn (`patch.py` writes assembled blob from `injected-1.4.49.S` + key strings) -- Hook `0x0037f9ec` (12B movw/movt/vcvt triplet) → `movw ip,#0x18d0; movt ip,#0x45; bx ip`; fn in cave `0x004518d0` (196B). -- Emits `TotalExtrusion` (key `0x4519a0`) + `CurrentExtrusion` (key `0x4519b0`) via JSON helper `0x2c9b80` (r0=json obj = r4 at hook); E total from `[[0x4b27bc]+0xf8]+0x1c0`; bss prev/delta at `0x4b4788`/`0x4b4790` (runtime-zero, no file backing); resume `0x37f9fc` (cave replays TotalLayer — no double-emit). Idle path `0x37f858` unhooked (parity). -**Caves `0x004518d0` + `0x004519a0`; bss `0x4b4788`/`0x4b4790`.** See `report-filament-usage/README-1.4.49.md`. +- Broadcast hook `0x36d310` / file `0x35d310`, replacing movt/vmov/vcvt. +- Pre-hook `movw r1,#0x96d0` remains stock; layer value is in r3. +- PrintInfo JSON object r8; native JSON-number helper `0x2c9b80` uses r0/r1/d0. +- Cave `[0x4518d0,0x451994)` is 196 bytes in the executable LOAD segment. +- Strings `0x4519a0` / `0x4519b0` hold the plain total/delta names. +- Private BSS doubles at `0x522f08` / `0x522f10`; allocated end `0x522f18`. +- Resume `0x36d320`, after the stock TotalLayer call; the cave emits it once. +- The former Agora hook `0x37f9ec` is left untouched. + +Scratch is explicitly reserved by growing RW p_memsz (`0xc8`) from `0x741fc` +to `0x74210`, .bss sh_size (`0x492380`) from `0x710d4` to `0x710e8`, and the +four exported BSS/end symbol values at file offsets `0x1724`, `0x20a4`, +`0x3e34`, `0x4044` from `0x522f04` to `0x522f18`. File size/p_filesz do not grow. +The old port's `0x4b4788/0x4b4790` overlap stock PRNG state and are never used. + +See `report-filament-usage/README-1.4.49.md`. ## 1.4.49 Binary Notes - Stock `app-1.4.49` sha256: `1a899b50fc104a38fe3f77cf4988c810da6670f3d0cc457de5d876c49fd76843` (from `FW/FW-CentauriCarbon-v1.4.49-2026-07-29.bin`). The `unpacked/squashfs-root/app/app` in a built tree is **already patched** — never use it as a patch baseline. -- Uniform file→VA bias: `VA = file_offset + 0x10000` for all sections. +- Code/rodata VA = file offset + 0x10000; RW LOAD VA = file offset + 0x20000. BSS has no payload bytes in the file. - String/code references are `movw`/`movt` pairs, but the compiler **interleaves the pair** (other instructions may sit between `movw` and its `movt`). When scanning for address references, allow a window of ~8 instructions between `movw rd, #lo` and `movt rd, #hi`. - Gcode command strings live in a packed 8-byte-stride table in `.rodata` around `0x00416374`; handlers are registered by loading the handler address as an immediate next to the string load (see chamber-light README for the M8212/M8213 example). @@ -105,4 +121,4 @@ The 1.4.49 app binary uses rodata zero runs as caves (the whole rodata sits in t 3. **Always run `patch_planner.py 1.4.49 --dry-run` after adding a new patch.** It shows the full ordered patch chain. Then build with `sudo ./build.sh 1.4.49` and disassemble the final app to verify all cave addresses. 4. **Document new caves in this file.** If you add a patch that uses a code cave, append its address range to the table above and update the summary. 5. **Prefer in-place single-instruction patches when possible.** If the fix is just forcing a constant or removing a branch, patch the single instruction directly. This avoids cave contention entirely. -6. **Claim the next free cave from the top.** No caves are claimed yet for 1.4.49. The 1.4.46 cave region lived at `0x00450100`+; re-discover zero-filled executable space in the 1.4.49 binary before claiming anything, and document exact start/end here and in the patch README. +6. **Claim the next free cave from the top.** Existing cave claims are listed above. Verify the stock ELF mapping and full patch chain before allocating additional space; never reuse 1.4.46 addresses by assumption. diff --git a/oc-patches/cc1-app/report-filament-usage/README-1.4.49.md b/oc-patches/cc1-app/report-filament-usage/README-1.4.49.md index 92e1618..69b5870 100644 --- a/oc-patches/cc1-app/report-filament-usage/README-1.4.49.md +++ b/oc-patches/cc1-app/report-filament-usage/README-1.4.49.md @@ -1,62 +1,81 @@ -# Filament Usage JSON Patch (CC1 1.4.49) +# Filament usage in CC1 1.4.49 SDCP status -## Purpose -Extends the SDCP status JSON with two fields consumed by the Home Assistant -integration: +Based on harpua555's original OpenCentauri/cc-fw-tools PR #40, shipped in v0.3.0. +This port emits `TotalExtrusion` and `CurrentExtrusion` beneath `Status.PrintInfo`. +Both lp55's PR #106 probe and the referenced Home Assistant parser accept these +plain names as well as the original ASCII-hex wire names. -- `TotalExtrusion` — cumulative extruded E position (double) -- `CurrentExtrusion` — per-status-cycle delta (current total minus previous) +`TotalExtrusion` reads `Printer -> PrintStats -> filament_used` at +`[[0x4b27bc]+0xf8]+0x1c0`. Stock PrintStats accumulates E movement divided by the +extrusion factor. `CurrentExtrusion` is the signed difference since the previous +status-writer invocation, not a speed or positive-only total. Stock print/reset +behavior is inherited; the patch adds no tray, client, or reset policy. +The historic 250-ms description is not a timer or timing guarantee in the cave. -Key strings are byte-identical to the 1.4.46 patch (HA contract). +## Mapping (virtual addresses unless explicitly labeled file offsets) -## Why (stock check) -Stock 1.4.49's status JSON writer (VA `0x37f6fc`) emits layer/progress/speed -keys but no filament usage. The stock `filament_used` string only appears in -gcode-file metadata parsing, never in status JSON. +- Broadcast hook `0x36d310` / file `0x35d310`, replacing movt/vmov/vcvt. +- Pre-hook `movw r1,#0x96d0` remains stock; layer value is in r3. +- PrintInfo JSON object r8; native JSON-number helper `0x2c9b80` uses r0/r1/d0. +- Cave `[0x4518d0,0x451994)` is 196 bytes in the executable LOAD segment. +- Strings `0x4519a0` / `0x4519b0` hold the plain total/delta names. +- Private BSS doubles at `0x522f08` / `0x522f10`; allocated end `0x522f18`. +- Resume `0x36d320`, after the stock TotalLayer call; the cave emits it once. +- The former Agora hook `0x37f9ec` is left untouched. -## Sites (1.4.49) +Scratch is explicitly reserved by growing RW p_memsz (`0xc8`) from `0x741fc` +to `0x74210`, .bss sh_size (`0x492380`) from `0x710d4` to `0x710e8`, and the +four exported BSS/end symbol values at file offsets `0x1724`, `0x20a4`, +`0x3e34`, `0x4044` from `0x522f04` to `0x522f18`. File size/p_filesz do not grow. +The old port's `0x4b4788/0x4b4790` overlap stock PRNG state and are never used. -| Item | VA | Notes | -|---|---|---| -| Hook site | `0x0037f9ec` (file `0x0036f9ec`) | 12B `movw r1,#0x96d0; movt r1,#0x45; vcvt.f64.u32 d0,s15` → `movw ip,#0x18d0; movt ip,#0x45; bx ip` | -| Injected fn cave | `0x004518d0` | 196 bytes, rodata zero run (R-E LOAD → executable) | -| Key strings | `0x004519a0` / `0x004519b0` | `TotalExtrusion\0` / `CurrentExtrusion\0` | -| JSON double helper | `0x002c9b80` | r0=json obj (`r4` at hook), r1=key, d0=value | -| E-position path | `[[0x4b27bc]+0xf8]+0x1c0` | printer global → motion planner → E double | -| bss state | `0x004b4788` / `0x004b4790` | prev/delta doubles; runtime-zero (no file backing — not byte-guarded) | -| Resume | `0x0037f9fc` | skips stock TotalLayer `bl` (cave replays it — no double-emit) | +The patcher validates every guard/cave/key/allocation field before any write. +Wrong firmware, truncated files, cave collisions, and reapplication are rejected. +It runs only on disposable extracted rootfs files, not a running app. +The cave still has no ARM unwind entry; allocation exceptions inside it retain +the original accepted termination risk. -The cave fn: replay triplet → emit TotalLayer → load E → update prev/delta -bss → emit both new keys → resume. Register hygiene: `push {r0-r7}` + -`vpush {d12}`/`vpop`; `r4` (json obj) and `s15` (TotalLayer value, loaded -pre-hook) are consumed before any helper call. +## Host checks (from repository root) -Idle path (`0x37f858`, constant 0.0) deliberately unhooked — parity with 1.4.46. +```bash +PYTHONDONTWRITEBYTECODE=1 uv run --no-project --with unicorn==2.1.4 python3 tests/test_report_filament_usage.py -v +python3 TOOLS/check_filament_usage.py --self-test +python3 oc-patches/patch_planner.py 1.4.49 --dry-run +``` -## Files -- `injected-1.4.49.S` — injected function source (source of truth) -- `patch.py` — applies hook + blob + key strings (byte-guarded, cave/key regions zero-checked) -- `patch.sh` — dispatches 1.4.49 to `patch.py`; older versions keep the bsdiff path +The binary regression uses pristine app-1.1.40 and app-1.4.49 from +`/home/paul/carbon/cc-firmware/stock/`; override ORIGINAL_STOCK_APP/STOCK_APP +when using another workspace. It executes the original and ported trampolines +with a mocked native JSON helper. This does not replace a device capture. -## Rebuilding the blob +## Live check (only on an approved CC1 test device/build) ```bash -arm-none-eabi-as -march=armv7-a -mfpu=vfpv3 -o injected-1.4.49.o injected-1.4.49.S -arm-none-eabi-ld -Ttext=0x4518d0 -o injected-1.4.49.elf injected-1.4.49.o -arm-none-eabi-objcopy -O binary injected-1.4.49.elf injected-1.4.49.bin -xxd -p injected-1.4.49.bin | tr -d '\n' # -> FN hex in patch.py +uv run --no-project --with websockets==13.1 python3 TOOLS/check_filament_usage.py "$PRINTER_IP" --seconds 30 --require-change ``` -## Verification -- Pristine stock: hook shows `movw ip,#0x18d0; movt ip,#0x45; bx ip`; cave head - shows `push {r0-r7}; vpush {d12}; movw r1,#0x96d0; …`; keys present; re-run refuses. -- Behavior: status JSON includes `TotalExtrusion`/`CurrentExtrusion` while printing. - -## Accepted risks -- **No unwind coverage:** the cave has no `.ARM.exidx` entry; a C++ exception - thrown with the PC inside the injected fn (the JSON helper's allocator can - throw `bad_alloc`) terminates instead of unwinding. Accepted — same shape as - the shipped 1.4.46 patch; the allocation is a ~48-byte JSON node. -- **bss scratch is not byte-guardable** (no file backing); unreferenced in a - ±0x100 static scan, but base+index accesses are invisible to that scan — - same accepted risk as 1.4.46. +`--seconds` bounds connection opening and the observation window; closing does +not wait for a peer's close-handshake reply. WebSocket keepalive remains enabled. + +Start a normal supervised print separately. Expected: finite numeric fields under +Status.PrintInfo, changing total and signed nonzero deltas during extrusion. +The observer sends no motion, heat, or print commands. Idle-only manual extrusion +may not update stock PrintStats, so it is not sufficient acceptance. +Source procedure: https://github.com/OpenCentauri/cc-fw-tools/pull/106#issuecomment-5357240641 + +## Home Assistant / Spoolman + +These fields alone are not enough for HA: `elegoo_printer` only registers its +OpenCentauri-only sensors - `total_extrusion` and `current_extrusion`, which Spoolman +reads - when it believes the firmware is OpenCentauri +(`PRINTER_STATUS_FDM_OPEN_CENTAURI` in `custom_components/elegoo_printer/definitions.py`, +gated on `printer.open_centauri` in `sensor.py`, computed by +`Printer._is_open_centauri(model, firmware)` from an `OC`/`O` marker in the reported +`FirmwareVersion`). A bare stock version string makes the integration treat the printer +as stock and it never creates those entities, so raw fields passing does not prove +HA/Spoolman works. + +The slicer spoof therefore reports `1.4.49 OC` instead of `1.4.49`: the leading version +keeps ElegooSlicer recognising the firmware, and the marker keeps HA on the +OpenCentauri entity set. Verify both on a device before claiming end-to-end success - +the slicer side is the unproven half. diff --git a/oc-patches/cc1-app/report-filament-usage/injected-1.4.49.S b/oc-patches/cc1-app/report-filament-usage/injected-1.4.49.S index d852d1b..3fd995e 100644 --- a/oc-patches/cc1-app/report-filament-usage/injected-1.4.49.S +++ b/oc-patches/cc1-app/report-filament-usage/injected-1.4.49.S @@ -1,67 +1,50 @@ -@ report-filament-usage injected function for CC1 1.4.49 -@ Cave VA: 0x4518d0 (rodata zero run, R-E LOAD segment — executable) -@ Hook: 0x37f9ec 12B (movw r1,#0x96d0; movt r1,#0x45; vcvt.f64.u32 d0,s15) -@ -> movw ip,#0x18d0; movt ip,#0x45; bx ip -@ Port of the 1.4.46 injected fn (0x450a00). Emits TotalLayer (replayed stock -@ call), then TotalExtrusion (cumulative E) and CurrentExtrusion (per-cycle -@ delta) via the stock JSON double helper. -@ -@ Key strings (written by patch.py): "TotalExtrusion\0" @ 0x4519a0, -@ "CurrentExtrusion\0" @ 0x4519b0 — exact 1.4.46 strings (HA integration -@ contract). -@ -@ Build: arm-none-eabi-as -march=armv7-a -mfpu=vfpv3 -o injected-1.4.49.o injected-1.4.49.S -@ arm-none-eabi-ld -Ttext=0x4518d0 -o injected-1.4.49.elf injected-1.4.49.o -@ arm-none-eabi-objcopy -O binary injected-1.4.49.elf injected-1.4.49.bin +@ CC1 stock-1.4.49 SDCP Status.PrintInfo filament usage. +@ Based on harpua555's original patch, OpenCentauri/cc-fw-tools PR #40. +@ Cave 0x4518d0; hook 0x36d310; r8 is the PrintInfo JSON object. .syntax unified .arm .text .global _start - -.equ JSON_HELPER, 0x2c9b80 @ (r0=json obj, r1=key, d0=value) -.equ PRINTER_PTR, 0x4b27bc @ global printer object ptr -.equ KEY_TOTAL, 0x4519a0 @ "TotalExtrusion\0" -.equ KEY_DELTA, 0x4519b0 @ "CurrentExtrusion\0" -.equ BSS_PREV, 0x4b4788 @ previous E total (double, runtime-zero) -.equ BSS_DELTA, 0x4b4790 @ last computed delta (double, runtime-zero) -.equ RESUME, 0x37f9fc @ instruction after stock TotalLayer bl +.equ JSON_HELPER, 0x2c9b80 +.equ PRINTER_PTR, 0x4b27bc +.equ KEY_TOTAL, 0x4519a0 +.equ KEY_DELTA, 0x4519b0 +.equ BSS_PREV, 0x522f08 +.equ BSS_DELTA, 0x522f10 +.equ RESUME, 0x36d320 _start: push {r0-r7} vpush {d12} - - @ --- replay clobbered triplet + emit TotalLayer (stock behavior) --- - movw r1, #0x96d0 @ "TotalLayer" key (stock) + @ Replay the overwritten TotalLayer instructions; low r1 is set pre-hook. movt r1, #0x45 - vcvt.f64.u32 d0, s15 @ s15 = TotalLayer value (loaded pre-hook) - mov r0, r4 @ json obj + vmov s15, r3 + vcvt.f64.u32 d0, s15 + mov r0, r8 movw ip, #:lower16:JSON_HELPER movt ip, #:upper16:JSON_HELPER - blx ip + blx ip - @ --- current E total: [[PRINTER_PTR]+0xf8]+0x1c0 (double) --- + @ Printer -> PrintStats -> accumulated, flow-normalized filament_used. movw r0, #:lower16:PRINTER_PTR movt r0, #:upper16:PRINTER_PTR - ldr r0, [r0] - ldr r0, [r0, #0xf8] @ motion planner - add r0, r0, #0x1c0 + ldr r0, [r0] + ldr r0, [r0, #0xf8] + add r0, r0, #0x1c0 ldrd r2, [r0] - vmov d0, r2, r3 @ cur - - @ --- delta bookkeeping --- + vmov d0, r2, r3 movw r5, #:lower16:BSS_PREV movt r5, #:upper16:BSS_PREV - ldrd r6, [r5] @ prev + ldrd r6, [r5] vmov d12, r6, r7 - strd r2, [r5] @ prev = cur - vsub.f64 d0, d0, d12 @ delta = cur - prev + strd r2, [r5] + vsub.f64 d0, d0, d12 vmov r6, r7, d0 movw r5, #:lower16:BSS_DELTA movt r5, #:upper16:BSS_DELTA - strd r6, [r5] @ store delta + strd r6, [r5] - @ --- emit TotalExtrusion (cumulative) --- - mov r0, r4 + mov r0, r8 movw r1, #:lower16:KEY_TOTAL movt r1, #:upper16:KEY_TOTAL movw r5, #:lower16:BSS_PREV @@ -70,10 +53,9 @@ _start: vmov d0, r6, r7 movw ip, #:lower16:JSON_HELPER movt ip, #:upper16:JSON_HELPER - blx ip + blx ip - @ --- emit CurrentExtrusion (delta) --- - mov r0, r4 + mov r0, r8 movw r1, #:lower16:KEY_DELTA movt r1, #:upper16:KEY_DELTA movw r5, #:lower16:BSS_DELTA @@ -82,8 +64,7 @@ _start: vmov d0, r6, r7 movw ip, #:lower16:JSON_HELPER movt ip, #:upper16:JSON_HELPER - blx ip - + blx ip vpop {d12} - pop {r0-r7} - b RESUME + pop {r0-r7} + b RESUME diff --git a/oc-patches/cc1-app/report-filament-usage/patch.py b/oc-patches/cc1-app/report-filament-usage/patch.py index 01f4552..69164a3 100755 --- a/oc-patches/cc1-app/report-filament-usage/patch.py +++ b/oc-patches/cc1-app/report-filament-usage/patch.py @@ -1,74 +1,63 @@ #!/usr/bin/env python3 -"""Report filament usage in PrintStats JSON (CC1 1.4.49). +"""CC1 1.4.49 SDCP filament usage, based on harpua555's PR #40. -Hooks the SDCP status JSON writer at VA 0x37f9ec (the "printing"-path -TotalLayer emission): the 12-byte movw/movt/vcvt triplet becomes -`movw ip,#0x18d0; movt ip,#0x45; bx ip` into the cave fn at 0x4518d0, which -replays the triplet, emits TotalLayer (stock helper 0x2c9b80), then emits -TotalExtrusion (cumulative E from [[0x4b27bc]+0xf8]+0x1c0) and CurrentExtrusion -(per-cycle delta, state doubles at 0x4b4788/0x4b4790), then resumes at -0x37f9fc. - -Key strings "TotalExtrusion\0" @ 0x4519a0 and "CurrentExtrusion\0" @ 0x4519b0 -are written by this script (exact 1.4.46 strings — HA integration contract). - -Injected fn blob: built from injected-1.4.49.S (see README-1.4.49.md). 196 -bytes at cave VA 0x4518d0. The bss state doubles are runtime-zero (no file -backing) — not byte-guardable, documented in the README. +Patch the broadcast PrintInfo writer and reserve private zero-initialized BSS. +Validate every region before writing any byte; never reuse stock PRNG storage. """ - import os +from pathlib import Path +import struct -SQUASHFS_ROOT = os.getenv("SQUASHFS_ROOT") -FW_VER = os.getenv("FW_VER", "1.4.49") - -if not SQUASHFS_ROOT: - raise RuntimeError("SQUASHFS_ROOT environment variable is required") -if FW_VER != "1.4.49": - raise RuntimeError(f"Unsupported firmware version for report-filament-usage patch.py: {FW_VER}") - -APP = os.path.join(SQUASHFS_ROOT, "app", "app") - -HOOK_OFF = 0x0036f9ec # VA 0x37f9ec -HOOK_OLD = "d01609e3451040e3670bb8ee" # movw r1,#0x96d0; movt r1,#0x45; vcvt.f64.u32 d0,s15 -HOOK_NEW = "d0c801e345c040e31cff2fe1" # movw ip,#0x18d0; movt ip,#0x45; bx ip - -CAVE_OFF = 0x004418d0 # VA 0x4518d0 -FN = "ff002de902cb2dedd01609e3451040e3670bb8ee0400a0e180cb09e32cc040e33cff2fe1bc0702e34b0040e3000090e5f80090e5070d80e2d020c0e1102b43ec885704e34b5040e3d060c5e11c6b47ecf020c5e14c0b30ee106b57ec905704e34b5040e3f060c5e10400a0e1a01901e3451040e3885704e34b5040e3d060c5e1106b47ec80cb09e32cc040e33cff2fe10400a0e1b01901e3451040e3905704e34b5040e3d060c5e1106b47ec80cb09e32cc040e33cff2fe102cbbdecff00bde819b8fcea" +HOOK_OFF = 0x35d310 +HOOK_OLD = "451040e3903a07ee670bb8ee" +HOOK_NEW = "d0c801e345c040e31cff2fe1" +CAVE_OFF = 0x4418d0 +FN = "ff002de902cb2ded451040e3903a07ee670bb8ee0800a0e180cb09e32cc040e33cff2fe1bc0702e34b0040e3000090e5f80090e5070d80e2d020c0e1102b43ec085f02e3525040e3d060c5e11c6b47ecf020c5e14c0b30ee106b57ec105f02e3525040e3f060c5e10800a0e1a01901e3451040e3085f02e3525040e3d060c5e1106b47ec80cb09e32cc040e33cff2fe10800a0e1b01901e3451040e3105f02e3525040e3d060c5e1106b47ec80cb09e32cc040e33cff2fe102cbbdecff00bde8626efcea" FN_SIZE = 196 - -KEY1_OFF = 0x004419a0 # VA 0x4519a0 -KEY1 = b"TotalExtrusion\x00" -KEY2_OFF = 0x004419b0 # VA 0x4519b0 -KEY2 = b"CurrentExtrusion\x00" +KEY1_OFF = 0x4419a0 +KEY1 = b"TotalExtrusion\0" +KEY2_OFF = 0x4419b0 +KEY2 = b"CurrentExtrusion\0" +ELF_EDITS = ((0xc8, 0x741fc, 0x74210), + (0x492380, 0x710d4, 0x710e8), + (0x1724, 0x522f04, 0x522f18), + (0x20a4, 0x522f04, 0x522f18), + (0x3e34, 0x522f04, 0x522f18), + (0x4044, 0x522f04, 0x522f18)) -def main() -> None: +def main(): + root = os.environ.get("SQUASHFS_ROOT") + if not root: + raise RuntimeError("SQUASHFS_ROOT environment variable is required") + if os.environ.get("FW_VER", "1.4.49") != "1.4.49": + raise RuntimeError("report-filament-usage patch.py only supports 1.4.49") blob = bytes.fromhex(FN) - assert len(blob) == FN_SIZE, f"injected blob is {len(blob)} bytes, expected {FN_SIZE}" - with open(APP, "r+b") as fp: - fp.seek(HOOK_OFF) - found = fp.read(12).hex() - if found != HOOK_OLD: - raise RuntimeError( - f"hook: expected {HOOK_OLD} at offset 0x{HOOK_OFF:08x}, found {found}; refusing to patch" - ) - for off, data, label in ((CAVE_OFF, blob, "cave"), (KEY1_OFF, KEY1, "key1"), (KEY2_OFF, KEY2, "key2")): - fp.seek(off) - cur = fp.read(len(data)) - if any(cur): - raise RuntimeError(f"{label} region at 0x{off:08x} is not zero-filled; refusing to patch") - fp.seek(HOOK_OFF) - fp.write(bytes.fromhex(HOOK_NEW)) - print(f"hook: patched 0x{HOOK_OFF:08x} (VA 0x{HOOK_OFF + 0x10000:08x}) -> bx 0x4518d0") - fp.seek(CAVE_OFF) - fp.write(blob) - print(f"cave: wrote {FN_SIZE}-byte fn at 0x{CAVE_OFF:08x} (VA 0x{CAVE_OFF + 0x10000:08x})") - fp.seek(KEY1_OFF) - fp.write(KEY1) - fp.seek(KEY2_OFF) - fp.write(KEY2) - print(f"keys: wrote TotalExtrusion/CurrentExtrusion at VA 0x4519a0/0x4519b0") + if len(blob) != FN_SIZE: + raise RuntimeError("injected blob must be 196 bytes") + writes = [(HOOK_OFF, bytes.fromhex(HOOK_NEW)), (CAVE_OFF, blob), + (KEY1_OFF, KEY1), (KEY2_OFF, KEY2)] + guards = [(HOOK_OFF, bytes.fromhex(HOOK_OLD)), + (0x35d30c, bytes.fromhex("d01609e3")), + (0x35d31c, bytes.fromhex("1772fdeb")), + (CAVE_OFF, bytes(FN_SIZE)), + (KEY1_OFF, bytes(len(KEY1))), (KEY2_OFF, bytes(len(KEY2)))] + for offset, old, new in ELF_EDITS: + guards.append((offset, struct.pack("-oc`). The real version string at `0x0040ae10` is left +so the slicer sees a stock-shaped `1.4.49 OC` instead of the actual OpenCentauri +version (`0.5.1-oc`). The real version string at `0x0040ae10` is left untouched so local logs, UI labels, and OTA update checks still show the correct version. @@ -37,8 +37,24 @@ movt r3, #0x45 ; r3 = 0x004517e0 ``` The cave is a 2KB zero run in `.rodata` (claimed in `../AGENT-1.4.49.md` cave -table) and receives the 7-byte string `1.4.49\0`, matching the stock 7-byte -copy before `sprintf("V%s", ...)`. +table) and receives the 11-byte string `1.4.49 OC\0`, ending at `0x004517ea` - +the next claim (`wait_for_chamber_temp`) starts at `0x004517f0`. The stock copy +before `sprintf("V%s", ...)` was 7 bytes; the output buffer is 0x80+, so the +extra bytes cost nothing at runtime. + +## Why the `OC` marker + +ElegooSlicer needs a version it recognises, but Home Assistant's `elegoo_printer` +integration needs to know the firmware is OpenCentauri. It only registers the +OpenCentauri-only sensors - `total_extrusion` / `current_extrusion`, which Spoolman +reads - when `Printer._is_open_centauri(model, firmware)` finds an `OC`/`O` marker in +the reported `FirmwareVersion` (`sensor.py` → `printer.open_centauri` → +`PRINTER_STATUS_FDM_OPEN_CENTAURI`). A bare `1.4.49` makes HA treat the printer as +stock and the extrusion entities are never created at all. + +So the spoofed string is `1.4.49 OC` → clients see `V1.4.49 OC`: the leading version +keeps the slicer happy, the marker keeps HA on the OpenCentauri entity set. +`tests/test_spoof_slicer_firmware_version.py` locks both halves of that contract. NOTE: the 1.4.46 cave `0x00450e00` is OCCUPIED in 1.4.49 (string data) — do not reuse it. @@ -52,8 +68,12 @@ seeing the OC version. Write order between the two patches does not matter. ## Verification -- `patch.py` refuses to apply if the guard bytes differ (wrong firmware or - already patched). +- `patch.py` validates all four regions before writing a byte, and refuses if the + guard bytes differ (wrong firmware or already patched) or the cave is no longer + zero-filled (another patch claimed it). - After applying to a stock `app-1.4.49`: the three sites disassemble to - `movw r3,#0x17e0; movt r3,#0x45`, `0x004517e0` reads `1.4.49\0`, and + `movw r3,#0x17e0; movt r3,#0x45`, `0x004517e0` reads `1.4.49 OC\0`, and `0x0040ae10` is unchanged. +- `tests/test_spoof_slicer_firmware_version.py` covers the byte patch, the cave + string, region confinement, non-mutating guard failures, and the HA/slicer + contract on the reported string. diff --git a/oc-patches/cc1-app/spoof-slicer-firmware-version/patch.py b/oc-patches/cc1-app/spoof-slicer-firmware-version/patch.py index 6977d80..5c7e087 100755 --- a/oc-patches/cc1-app/spoof-slicer-firmware-version/patch.py +++ b/oc-patches/cc1-app/spoof-slicer-firmware-version/patch.py @@ -7,12 +7,19 @@ - Direct request-attribute responses (VA 0x0037fbe4) This patch repoints the source pointer in all three functions to a new code cave at -VA 0x004517e0 containing a fixed "1.4.49\\0" string. The original version string at +VA 0x004517e0 containing a fixed "1.4.49 OC\\0" string. The original version string at VA 0x0040ae10 (logs, UI, OTA) is left untouched. + +The "OC" marker is deliberate. Home Assistant's elegoo_printer integration only creates +the OpenCentauri-only sensors (total/current extrusion, which Spoolman reads) when the +reported FirmwareVersion carries an "OC"/"O" marker - see +custom_components/elegoo_printer/sdcp/models/printer.py:_is_open_centauri and +sensor.py PRINTER_STATUS_FDM_OPEN_CENTAURI. A bare "1.4.49" makes the integration treat +the printer as stock and it never creates the extrusion entities at all. The leading +"1.4.49" is kept so ElegooSlicer still recognises the firmware. """ import os -import sys SQUASHFS_ROOT = os.getenv("SQUASHFS_ROOT") FW_VER = os.getenv("FW_VER", "1.4.49") @@ -33,36 +40,48 @@ EXPECTED_OLD = bytes.fromhex("103e0ae3403040e3") # movw r3,#0xae10; movt r3,#0x40 NEW_BYTES = bytes.fromhex("e03701e3453040e3") # movw r3,#0x17e0; movt r3,#0x45 -CAVE_STRING = b"1.4.49\x00" # 7 bytes, matching the stock 7-byte version slot +# 11 bytes, ending at 0x004517ea. The next cave claim (wait_for_chamber_temp) starts at +# 0x004517f0, so this stays inside the string's own region. The "OC" suffix is what makes +# Home Assistant treat the printer as OpenCentauri and create the extrusion sensors. +CAVE_STRING = b"1.4.49 OC\x00" +CAVE_SIZE = 11 -def patch_movw_movt(label: str, offset: int) -> None: - with open(APP, "r+b") as fp: - fp.seek(offset) - old = fp.read(8) - if old != EXPECTED_OLD: +SITES = (("udp_discovery", UDP_VERSION_PTR), + ("ws_attributes", WS_VERSION_PTR), + ("req_attribute", REQ_VERSION_PTR)) + + +def validate(data: bytes) -> None: + """Check every guarded byte before anything is written.""" + for label, offset in SITES: + found = data[offset:offset + len(EXPECTED_OLD)] + if found != EXPECTED_OLD: raise RuntimeError( f"{label}: expected {EXPECTED_OLD.hex()} at offset 0x{offset:08x}, " - f"found {old.hex()}; refusing to patch" + f"found {found.hex()}; refusing to patch" ) - fp.seek(offset) - fp.write(NEW_BYTES) - print(f"{label}: patched 0x{offset:08x} (VA 0x{offset+0x10000:08x}) to point at 0x{CAVE_VA:08x}") + region = data[CAVE_FILE_OFFSET:CAVE_FILE_OFFSET + CAVE_SIZE] + if any(region): + raise RuntimeError( + f"cave at file offset 0x{CAVE_FILE_OFFSET:08x} is not zero-filled " + f"({region.hex()}); another patch already claimed it; refusing to patch" + ) -def write_cave() -> None: - with open(APP, "r+b") as fp: - fp.seek(CAVE_FILE_OFFSET) - before = fp.read(len(CAVE_STRING)) - if any(before): - print(f"WARNING: cave at file offset 0x{CAVE_FILE_OFFSET:08x} was not zero-filled before write", file=sys.stderr) - fp.seek(CAVE_FILE_OFFSET) - fp.write(CAVE_STRING) - print(f"wrote cave string {CAVE_STRING!r} at file offset 0x{CAVE_FILE_OFFSET:08x} (VA 0x{CAVE_VA:08x})") +def apply(data: bytes) -> dict[int, bytes]: + return {offset: NEW_BYTES for _, offset in SITES} | {CAVE_FILE_OFFSET: CAVE_STRING} if __name__ == "__main__": - patch_movw_movt("udp_discovery", UDP_VERSION_PTR) - patch_movw_movt("ws_attributes", WS_VERSION_PTR) - patch_movw_movt("req_attribute", REQ_VERSION_PTR) - write_cave() + with open(APP, "rb") as fp: + image = fp.read() + validate(image) + with open(APP, "r+b") as fp: + for offset, payload in apply(image).items(): + fp.seek(offset) + fp.write(payload) + for label, offset in SITES: + print(f"{label}: patched 0x{offset:08x} (VA 0x{offset + 0x10000:08x}) to point at 0x{CAVE_VA:08x}") + print(f"wrote cave string {CAVE_STRING!r} at file offset 0x{CAVE_FILE_OFFSET:08x} " + f"({CAVE_SIZE} bytes, VA 0x{CAVE_VA:08x})") diff --git a/tests/test_firmware_version.py b/tests/test_firmware_version.py new file mode 100644 index 0000000..9024f76 --- /dev/null +++ b/tests/test_firmware_version.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python3 +"""Version string written into app/app by the set-firmware-version patch.""" +from pathlib import Path +import os +import subprocess +import sys +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "TOOLS")) + +from firmware_version import firmware_version # noqa: E402 + +CLEAN = {"OC_BUILD_BRANCH": "", "OC_BUILD_COMMIT": "", "OC_VERSION": "", "GITHUB_REF_NAME": ""} + + +def version(**env): + with mock.patch.dict(os.environ, {**CLEAN, **env}, clear=False): + return firmware_version(str(ROOT)) + + +class FirmwareVersionTests(unittest.TestCase): + def test_declared_release_version_wins(self): + self.assertEqual(version(OC_VERSION="0.5.1"), "0.5.1-oc") + self.assertEqual(version(OC_VERSION="v0.5.1"), "0.5.1-oc") + + def test_manifest_tools_see_the_declared_version_without_env(self): + # create_manifest.py and the patch summary run outside patch_planner's + # environment, so the edition file has to carry the version on its own. + self.assertEqual(version(), "0.5.1-oc") + + def test_integrate_branch_beta_still_wins_over_declared_version(self): + self.assertEqual(version(OC_BUILD_BRANCH="v0.5.1-integrate", OC_BUILD_COMMIT="abcdef1234", + OC_VERSION="0.5.1"), "0.5.1-beta-abcdef1-oc") + + def test_invalid_declared_version_is_rejected(self): + with self.assertRaises(ValueError): + version(OC_VERSION="0.5") + with self.assertRaises(ValueError): + version(OC_VERSION="latest") + + def test_edition_config_declares_the_release_version(self): + config = (ROOT / "firmware-editions/patched").read_text().splitlines() + declared = [line for line in config if line.startswith("OC_VERSION=")] + self.assertEqual(declared, ["OC_VERSION='0.5.1'"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_report_filament_usage.py b/tests/test_report_filament_usage.py new file mode 100644 index 0000000..eac4276 --- /dev/null +++ b/tests/test_report_filament_usage.py @@ -0,0 +1,211 @@ +#!/usr/bin/env python3 +"""Machine-code regression for the CC1 1.4.49 filament-reporting port.""" +import ast +import hashlib +import os +from pathlib import Path +import struct +import subprocess +import tempfile +import unittest + +from unicorn import Uc, UC_ARCH_ARM, UC_MODE_ARM, UC_HOOK_CODE +from unicorn.arm_const import ( + UC_CPU_ARM_CORTEX_A7, UC_ARM_REG_C1_C0_2, UC_ARM_REG_FPEXC, + UC_ARM_REG_R0, UC_ARM_REG_R1, UC_ARM_REG_R2, UC_ARM_REG_R3, + UC_ARM_REG_R4, UC_ARM_REG_R5, UC_ARM_REG_R6, UC_ARM_REG_R7, + UC_ARM_REG_R8, UC_ARM_REG_R9, UC_ARM_REG_R10, UC_ARM_REG_R11, + UC_ARM_REG_R12, UC_ARM_REG_SP, UC_ARM_REG_LR, UC_ARM_REG_PC, + UC_ARM_REG_D0, UC_ARM_REG_D8, +) + +ROOT = Path(__file__).resolve().parents[1] +PATCH_DIR = ROOT / "oc-patches/cc1-app/report-filament-usage" +STOCK = Path(os.environ.get("STOCK_APP", "/home/paul/carbon/cc-firmware/stock/app-1.4.49")) +ORIGINAL_STOCK = Path(os.environ.get("ORIGINAL_STOCK_APP", "/home/paul/carbon/cc-firmware/stock/app-1.1.40")) +HEX_TOTAL = "54 6F 74 61 6C 45 78 74 72 75 73 69 6F 6E 00" +HEX_DELTA = "43 75 72 72 65 6E 74 45 78 74 72 75 73 69 6F 6E 00" +REGS = (UC_ARM_REG_R0, UC_ARM_REG_R1, UC_ARM_REG_R2, UC_ARM_REG_R3, + UC_ARM_REG_R4, UC_ARM_REG_R5, UC_ARM_REG_R6, UC_ARM_REG_R7, + UC_ARM_REG_R8, UC_ARM_REG_R9, UC_ARM_REG_R10, UC_ARM_REG_R11) +ELF_EDITS = ((0xc8, 0x741fc, 0x74210), + (0x492380, 0x710d4, 0x710e8), + (0x1724, 0x522f04, 0x522f18), + (0x20a4, 0x522f04, 0x522f18), + (0x3e34, 0x522f04, 0x522f18), + (0x4044, 0x522f04, 0x522f18)) + + +def run_patch(image, fw="1.4.49"): + with tempfile.TemporaryDirectory(prefix="filament-patch-") as directory: + root = Path(directory) + (root / "app").mkdir() + target = root / "app/app" + target.write_bytes(image) + env = dict(os.environ, SQUASHFS_ROOT=str(root), FW_VER=fw) + result = subprocess.run(["python3", str(PATCH_DIR / "patch.py")], + env=env, capture_output=True, text=True) + return result, target.read_bytes() + + +def emissions(image, old=False): + """Execute only the real hook/cave; stub the native JSON-number helper.""" + entry, resume, helper, singleton, low_key = ( + (0x2deb18, 0x2deb28, 0x268720, 0x3e54d4, 0x6724) if old else + (0x36d310, 0x36d320, 0x2c9b80, 0x4b27bc, 0x96d0)) + mu = Uc(UC_ARCH_ARM, UC_MODE_ARM) + mu.ctl_set_cpu_model(UC_CPU_ARM_CORTEX_A7) + mu.reg_write(UC_ARM_REG_C1_C0_2, 0xf << 20) + mu.reg_write(UC_ARM_REG_FPEXC, 1 << 30) + mu.mem_map(0x10000, 0x530000) + phoff = struct.unpack_from("