diff --git a/native/waze-on-cluster/CHANGELOG.md b/native/waze-on-cluster/CHANGELOG.md index 090b7804..19dc66ab 100644 --- a/native/waze-on-cluster/CHANGELOG.md +++ b/native/waze-on-cluster/CHANGELOG.md @@ -2,6 +2,15 @@ ## Unreleased +CarPlay's cluster map patch is applied in CarPlay's memory each time it +starts, and `/usr/bin/carplay` stays as it ships: no write of the system +partition to patch, remove or recover it. Updating from an earlier version +puts the original file back and keeps the map, with at most one head-unit +restart; where CarPlay already runs the earlier patch, none. The earlier +patch stays in the file where the file holds another change besides it, +where boot recovery counts a failed start, or where the patch in memory +cannot be set up. + ## 0.10.12 The diagnostic journal is kept in memory and written to storage only around diff --git a/native/waze-on-cluster/Makefile b/native/waze-on-cluster/Makefile index 5b9380fd..4ce01f07 100644 --- a/native/waze-on-cluster/Makefile +++ b/native/waze-on-cluster/Makefile @@ -59,7 +59,7 @@ WOC_SRC = src/main.cpp src/refused.cpp src/video_producer.cpp src/freeze_watch.c CR_SRC = $(CR)/client/client.cpp $(CR)/client/protocol.cpp SRC = $(WOC_SRC) $(CR_SRC) $(CR)/src/config.cpp $(CR)/src/log.cpp $(CR)/src/head_unit.cpp -.PHONY: all test test-bin test-cpp test-node test-x86 test-x86-in-docker test-firmware target target-in-docker clean +.PHONY: all test test-bin test-cpp test-node test-x86 test-x86-in-docker test-firmware target target-in-docker test-preload test-preload-in-docker clean CPP_TESTS = $(BUILD)/host/nal_reader_test $(BUILD)/host/rtp_h264_test $(BUILD)/host/udp_probe_test \ $(BUILD)/host/map_feed_test $(BUILD)/host/keyframe_wait_test $(BUILD)/host/freeze_watch_test \ @@ -105,6 +105,7 @@ test-node: umask 077 && $(NODE) patch/test/wifi_band_test.js umask 077 && $(NODE) patch/test/dlt_capture_test.js umask 077 && $(NODE) patch/test/recovery_test.js + umask 077 && $(NODE) patch/test/inmem_test.js umask 077 && $(NODE) patch/test/journal_keep_test.js umask 077 && $(NODE) patch/test/logs_test.js umask 077 && $(NODE) patch/test/collect_logs_test.js @@ -266,7 +267,36 @@ target: docker run --rm --platform linux/amd64 --user "$$(id -u):$$(id -g)" -v "$(CURDIR):/w" -v "$(abspath $(CR)):/cr" -w /w $(IMAGE) \ make -s -j$(JOBS) BUILD=$(BUILD) CR=/cr target-in-docker -target-in-docker: $(T)/waze-on-cluster +target-in-docker: $(T)/waze-on-cluster $(T)/libwocpatch.so + +# The in-memory carplay patch (preload/wocpatch.c, PATCH.md "In memory"): +# C, no C++ runtime, exports nothing, libc only. +PRELOAD_FLAGS = -std=gnu99 -O2 -g -Wall -Wextra -Werror -fPIC -fvisibility=hidden -D_FORTIFY_SOURCE=2 +PRELOAD_LINK = -shared -Wl,-z,now -Wl,-z,relro -Wl,--no-undefined + +$(T)/libwocpatch.so: preload/wocpatch.c + @mkdir -p $(@D) + gcc $(PRELOAD_FLAGS) $(PRELOAD_LINK) -o $@ $< + +# The library against a test program, in the unit's toolchain image. +test-preload: + $(DOCKER_IMAGE) + docker run --rm --platform linux/amd64 --user "$$(id -u):$$(id -g)" -v "$(CURDIR):/w" -v "$(abspath $(CR)):/cr" -w /w $(IMAGE) \ + make -s BUILD=$(BUILD)/x86 CR=/cr test-preload-in-docker + +test-preload-in-docker: $(BUILD)/preload/libwocpatch.so $(BUILD)/preload/libwocpatch-crash.so + gcc -std=gnu99 -O2 -fPIE -pie -Wl,--build-id -o $(BUILD)/preload/target preload/test/target.c + gcc -std=gnu99 -O2 -fPIC -shared -o $(BUILD)/preload/libthread.so preload/test/thread.c -lpthread + sh preload/test/preload_test.sh $(abspath $(BUILD)/preload/libwocpatch.so) $(abspath $(BUILD)/preload/target) $(abspath $(BUILD)/preload/work) + +# A test build that aborts once it has applied: an armed start that crashes. +$(BUILD)/preload/libwocpatch-crash.so: preload/wocpatch.c + @mkdir -p $(@D) + gcc $(PRELOAD_FLAGS) -DWOC_TEST_CRASH $(PRELOAD_LINK) -o $@ $< + +$(BUILD)/preload/libwocpatch.so: preload/wocpatch.c + @mkdir -p $(@D) + gcc $(PRELOAD_FLAGS) $(PRELOAD_LINK) -o $@ $< # Link-only stubs exporting the unit libraries' symbols. Each carries the real # SONAME, so the binary records the right DT_NEEDED. diff --git a/native/waze-on-cluster/README.md b/native/waze-on-cluster/README.md index 769edc9c..4fa61ccf 100644 --- a/native/waze-on-cluster/README.md +++ b/native/waze-on-cluster/README.md @@ -20,8 +20,8 @@ driven from the HMI by the companion app Both send the cluster map only as H.264 video, with no map data, so this is a video pipeline: -1. **Ungate the second display.** A reversible patch to - `/usr/bin/carplay` makes `KI_KOMBI_VARIANT` 7 resolve to a supported +1. **Ungate the second display.** A patch of carplay, applied in its + memory at start while `/usr/bin/carplay` stays as it ships, makes `KI_KOMBI_VARIANT` 7 resolve to a supported cluster variant, makes CarPlay start the cluster stream itself, and advertises the size the map is shown at ([patch/PATCH.md](patch/PATCH.md)). Another to `/usr/bin/aapd` and `/etc/aapd.conf` does the same for Android @@ -44,17 +44,21 @@ The Store installs it with the app `robertn_waze_cluster`; it requires `cluster-render` and `mgu-deploy` (`component.json`, `"requires"`). **Install.** The deploy tool runs `patchd.js activate` as root. On a car -coded `KI_KOMBI_VARIANT` 7 with a proven carplay build (or one CarPlay's -Patch button patched before), it writes the patch and never stops, kills or +coded `KI_KOMBI_VARIANT` 7 with a proven carplay build, it plans the patch +in memory and arms CarPlay's next start, and never stops, kills or restarts CarPlay: the Store shows a restart pending, the app `Status: -Patched after restart`, and one head-unit start runs the patched CarPlay. -It then writes the Android Auto patch the same way on a proven aapd build. -Anywhere else it leaves the binary as it is, and the app's Status says why -(PATCH.md "Install-time activation"). +Patched after restart`, and one head-unit start runs CarPlay with the +patch. Over an earlier release's patch of `/usr/bin/carplay` it puts the +shipped file back in the same step; the earlier patch keeps running until +CarPlay next starts, which then applies the patch in memory, so no restart +is needed for it. It then writes the Android Auto patch on a proven aapd +build. Anywhere else it leaves everything as it is, and the app's Status +says why (PATCH.md "Install-time activation", "In memory"). **Remove.** In the Store, remove the app, then the tool (refused while the -app is installed). `patchd.js deactivate` reverts our edits to carplay, -aapd and aapd.conf and drops our backups; the deploy tool then removes this +app is installed). `patchd.js deactivate` turns the patch in memory off, +reverts our edits to aapd and aapd.conf (and to carplay, where an earlier +release wrote them) and drops our backups; the deploy tool then removes this tool's services and files. The next head-unit start runs the original CarPlay and aapd. @@ -70,9 +74,10 @@ restarts it at once only where that cannot restart the head unit (PATCH.md on SIGTERM, which restarts the head unit. **Boot recovery.** If a patch keeps the head unit restarting, the boot step -restores the original binary before CarPlay (or aapd) starts: after one -failed start for a patch not yet proven on that car, after two for a proven -one. CarPlay comes back without the map, its Status reads `Removed — head +stops arming CarPlay's patch in memory (and restores the original aapd) +before CarPlay (or aapd) starts: after one failed start for a patch not yet +proven on that car, after two for a proven one. CarPlay comes back without +the map, its Status reads `Removed — head unit kept restarting`, and its Patch button applies the patch again (PATCH.md "Boot recovery"). Android Auto's patch is removed at the first crash of the patched aapd, and aapd is started again after every end, so @@ -264,8 +269,10 @@ sources are left out. ### The patches `patch/carplay_patch.js` and `patch/aapd_patch.js` (Node 8, no -dependencies) find their edit sites in the build, check them, take a -verified full backup, and write by atomic rename. The install patches only +dependencies) find their edit sites in the build and check them. +carplay's edits go into a plan that `preload/wocpatch.c` +(`libwocpatch.so`, preloaded into carplay) applies in memory; aapd's are +written to the file with a verified full backup, by atomic rename. The install patches only a proven build; another build whose sites are all found is patched once a Patch button (or `apply --unproven`) asks. Edits, sites and proven builds: [patch/PATCH.md](patch/PATCH.md). @@ -289,6 +296,7 @@ It remounts `/` read-write only for the write. ```sh make test # host tests +make test-preload # libwocpatch.so against a test program, with the unit's toolchain in Docker make test-x86 # the C++ tests with the unit's toolchain in Docker (SSE2 paths) make target # build/target/waze-on-cluster in Docker, imports checked make test-firmware ROOTFS= # DLT capture against the unit's own dlt-daemon in Docker diff --git a/native/waze-on-cluster/component.json b/native/waze-on-cluster/component.json index ff428cdd..decc6d3e 100644 --- a/native/waze-on-cluster/component.json +++ b/native/waze-on-cluster/component.json @@ -78,6 +78,16 @@ "from": "patch/recovery.js", "mode": "0644" }, + { + "path": "inmem.js", + "from": "patch/inmem.js", + "mode": "0644" + }, + { + "path": "libwocpatch.so", + "from": "build/target/libwocpatch.so", + "mode": "0644" + }, { "path": "patch_record.js", "from": "patch/patch_record.js", diff --git a/native/waze-on-cluster/patch/PATCH.md b/native/waze-on-cluster/patch/PATCH.md index 9062fd57..28bc0a58 100644 --- a/native/waze-on-cluster/patch/PATCH.md +++ b/native/waze-on-cluster/patch/PATCH.md @@ -1,10 +1,14 @@ # The carplay patch, byte for byte -Six reversible edits to `/usr/bin/carplay` let waze-on-cluster receive the -CarPlay instrument-cluster map, at the size it displays and from the phone's -connection, on a head unit coded `KI_KOMBI_VARIANT` 7. `carplay_patch.js` applies, verifies and reverts them; -`patchd.js` runs it for the app and the install hooks, `woc-patch.sh` from a -shell. +Six edits to carplay let waze-on-cluster receive the CarPlay +instrument-cluster map, at the size it displays and from the phone's +connection, on a head unit coded `KI_KOMBI_VARIANT` 7. This tool applies +them in carplay's memory at each start it arms, and `/usr/bin/carplay` stays +as it ships ("In memory"). `carplay_patch.js` locates and checks them and +makes the plan the preloaded `libwocpatch.so` applies; it also applies, +verifies and reverts them in the file, as earlier releases did and +`woc-patch.sh` does from a shell. `patchd.js` runs it for the app and +the install hooks. ## Supported head units @@ -682,6 +686,136 @@ the deploy tool stops and removes the tool's units, recmgr entries and `/var/opt/waze-on-cluster`; the renderer releases the map's slot, and the capture restores the DLT tracing mode and default log level as it stops. +## In memory + +This tool applies the six edits to carplay's memory, never to +`/usr/bin/carplay`: the file stays as it ships, and `/` is not remounted +to patch, unpatch or recover CarPlay. The edits, their sites and their +checks are the ones above, from the same locator. + +**The plan.** `carplay_patch.js plan` reads carplay on disk, which must be +the pristine build, runs every check an apply's first edit runs (the head +unit, the coding, the locator, a proven build or `--unproven`) and builds +the edited image as `apply` does. For each edit region that differs it +writes one line: the region's virtual address, the bytes the build ships +there and the bytes to write. It then lays the plan over the file again +(`overlay`) and keeps it only when that gives exactly the edited image. + +``` +wocplan 1 +build-id 5de62156575d737391ea42254e778a97dbbb51f8 +edit variant 2ba4f0 ecf2f7ff bcf2f7ff +edit selfstart 18176c e8effdffff e89f000000 +... +end 10 +``` + +`patchd` keeps the plan in `/var/opt/waze-on-cluster/inmem-carplay.plan` +and its record in `inmem-carplay.json` (`inmem.js`): enabled or not, by +whom it was turned off (`user`, `recovery`), `proven` or `trial`, the +plan's SHA-256 and carplay's inode, size and modification time. The record +describes carplay only while all of them match: a firmware update that +replaces carplay, or any other write of the file, leaves nothing armed. + +**The library.** `libwocpatch.so` (C, libc only, exports nothing) runs as +a constructor of a preloaded library, after the libraries' own +constructors and before carplay's: its static initialisers (Edit 5's site +is one) and `main` have not run. It reads the plan and applies every edit +or none: + +- the main program's GNU build-id, from its own `PT_NOTE` in memory, must + be the plan's; any other program (one carplay starts, which inherits + `LD_PRELOAD`) is left alone and writes no result; +- the plan must be whole: its version, every line, its closing count, and + only kinds of line this library knows, so a newer plan never meets an + older library half-understood; +- each region must lie inside the file-backed part of one `PT_LOAD`, + outside `PT_GNU_RELRO`, and read exactly its stock bytes. A site that + reads patched (a patched file on disk) refuses the plan too. A region + the plan leaves as it ships (the sink in the avb mode) is listed too and + checked the same way. + +It then makes each page writable, keeping a code page executable for that +moment (`libdlt`'s constructor has started two threads by then; neither +runs carplay's code, which has not started), writes, gives each page its +segment's protection back and reads every region back. A failure before +the write changes nothing; one after it makes every page writable again, +writes the stock bytes back and restores the protections. Only a page that +cannot get its protection back ends carplay (`abort`), a crash boot +recovery counts; so does a page that cannot be made writable again to +put the stock bytes back. A region inside `PT_GNU_RELRO` refuses the plan. A plan that cannot +be read or parsed is reported on stderr only. The result goes to `/run/woc-preload/carplay.result` +(`{pid, applied, edits, why}`, a file the boot step made for carplay's user; +the library never creates one) and to the journal. + +**Arming.** The tool's drop-in for `carplay.service` has +`EnvironmentFile=-/run/woc-preload/carplay.env`. Without that file carplay +starts as it ships. Boot recovery writes it, only for a start it arms +(below), last after the plan copy and the empty result file: +`LD_PRELOAD` holds the unit's own preload (`carplay.service` has +`Environment=LD_PRELOAD=/usr/lib/libschedconfig.so.1`; an `EnvironmentFile` +setting replaces it, so it is read from the unit and kept first), then +this version's library, and `WOC_PATCH_PLAN` and `WOC_PATCH_RESULT`. `/run` +starts empty at every head-unit start, so a start is armed only by that +boot's decision. carplay runs as `cia_13002` and is not setuid, so the +loader honours the preload; the library and plan are world-readable. + +**Activation.** A change of the patch in memory takes effect when carplay +next starts. `patchd` restarts carplay itself where it may (above, +"Activation": SIGKILL with the run recorded, then start), so CarPlay's +Patch and Remove patch buttons need no head-unit start there. Install and +removal never restart it. + +| On disk before the install | `activate` | Head-unit starts to get the map | +|---|---|---| +| the pristine proven build | plans and arms; a change pending | 1 | +| an earlier release's patch, with our backup | checks the plan on the backup, then reverts the file from it, drops the backup, plans and arms, in one step | 0 when the running carplay holds the plan's bytes (the earlier patch runs them), else 1 | +| the same, with another change in the file besides our patch, a patch that would start on trial while boot recovery counts a failure, or no way to arm here (the library, carplay.service's user, `/run/woc-preload`) | nothing: the earlier patch stays in the file, which this version's boot recovery guards | — | +| the original with our backup (Remove patch was used), or a patch boot recovery removed | nothing: the patch stays off; its Patch button applies it | — | + +The patch in memory keeps the earlier patch's proven state where carplay +holds exactly the plan's bytes and its record says it ran healthy on this +car; otherwise it starts on trial. After the migration carplay on disk is +the shipped file and the running +carplay keeps the earlier patch until it ends; any later start of this boot +(a crash restart included) is armed, so the map is never off between the +two. + +`patchd`'s status reads the plan's overlay of carplay for `res`, `safe`, +`mapurl` and the mode, and reads the running carplay's memory at the +plan's sites (`/proc//mem`, read-only, at the mapping of the file it +runs): `patched` while it holds the plan's bytes, else the change is +pending (`Patched after restart`), unless the library's result for the +running carplay says it refused: then the conflict `not applied in memory: +`, which a restart does not change. A plan turned off while carplay +still holds it reads `Removed after restart`. + +**Boot recovery.** A start armed in memory is counted as a patched start +is ("Boot recovery" below), with the same thresholds: 1 failed start or +crash for a patch on trial or unproven, 2 for a proven one. One rule is +stricter: a restart recmgr or crashhandler recorded counts even after a +healthy run, since a reset that beats the shutdown mark leaves only that +record. At the threshold the restore is: remove the env file, then turn the +record off (`by: "recovery"`). Nothing is written to `/`, and the next +start, in this boot or the next, runs carplay as it ships. A patch on +trial becomes proven after a healthy run in which the running carplay's +memory holds the plan and the library's result names its PID. After boot +recovery turned a patch off, its Patch button plans it again, on trial; a +patch the user turned off keeps its proven state for the same plan. + +**Removal and rollback.** `deactivate` turns the patch off (env removed, +record and plan deleted) and reverts any patch of an earlier release left +in the file. A release installed after this one finds a stock carplay with +no backup: it patches the file as it always did, and its boot recovery +restores that patch to stock. The record no longer describes that file, so +this version, installed again, never arms the plan over it +(`rollback_test.js`, part 6). An older release's drop-in has no +`EnvironmentFile`, so an env file left in `/run` from this boot is never +read. + +Android Auto's patch is written to `/usr/bin/aapd` and `/etc/aapd.conf` +("Android Auto"). + ## Reversibility Before the first edit the patcher writes the backup under a temporary name and diff --git a/native/waze-on-cluster/patch/carplay_patch.js b/native/waze-on-cluster/patch/carplay_patch.js index cff3cae1..eb114b35 100644 --- a/native/waze-on-cluster/patch/carplay_patch.js +++ b/native/waze-on-cluster/patch/carplay_patch.js @@ -581,49 +581,15 @@ function restorePlan(target, cur, c) { return { b: b, bc: bc, regionWise: false, out: orig }; } -function cmdApply(target, panel, capture, sink, res, safe, yes, unproven, codingFile) { - var hu = headUnit.refused(); - if (hu) die('refusing: ' + hu); - if (panel !== 'high' && panel !== 'mid') die('--panel must be high or mid'); - var coding = readCoding(codingFile), codingBad = codingRefusal(coding); - if (codingBad && !unproven) die('refusing: ' + codingBad + '; pass --unproven to patch it anyway'); - var wantRes = resFor(panel, res, safe); - var sinkUrl = sinkUrlFor(capture, sink), slotLen = locator.SINK_STOCK.length; - if (sinkUrl !== undefined && Buffer.byteLength(sinkUrl, 'latin1') > slotLen) - die('sink URL too long: "' + sinkUrl + '" is ' + Buffer.byteLength(sinkUrl, 'latin1') + ' bytes, slot holds ' + slotLen); - - var buf = readTarget(target), c = classify(buf), bad = unrecognised(c); - if (bad.length) die('refusing: ' + bad.join('; ')); - - /* Back up the pristine original before the first edit; require that a - * pre-existing backup is the pristine original of this build. */ - var bak = backupPath(target), orig = buf; - if (!fs.existsSync(bak)) { - var why = notPristine(c, buf); - if (why) die('first edit requires the pristine build: ' + why); - if (!PROVEN[c.loc.buildId] && !unproven) die(label(c) + ' (carplay ' + (c.loc.version || 'version unknown') + ') is not a proven build; pass --unproven to patch it anyway'); - /* The backup is written and checked under a temporary name, its record - * written in full and renamed into place, then the backup renamed: a - * backup never exists without its record. */ - var bakTmp = bak + '.tmp', metaTmp = metaPath(target) + '.tmp'; - [bakTmp, metaTmp].forEach(function (f) { try { fs.unlinkSync(f); } catch (e) {} }); /* an earlier apply's, cut short */ - fs.writeFileSync(bakTmp, buf, { mode: 0o600 }); - fsyncFile(bakTmp); - if (!fs.readFileSync(bakTmp).equals(buf)) { try { fs.unlinkSync(bakTmp); } catch (e) {} die('backup verification failed; no change made'); } - var origStat = fs.statSync(target); /* the original's mode and owner, which every later write gives carplay */ - fs.writeFileSync(metaTmp, JSON.stringify({ target: path.resolve(target), version: label(c), buildId: c.loc.buildId, - sha256_original: sha256(buf), mode: origStat.mode & 0o7777, uid: origStat.uid, gid: origStat.gid, - savedAt: new Date().toISOString() }, null, 2) + '\n', { mode: 0o600 }); - fsyncFile(metaTmp); - fs.renameSync(metaTmp, metaPath(target)); - fs.renameSync(bakTmp, bak); - } else { - var b = checkedBackup(target); - if (b.err) die('existing backup ' + bak + ' is not a pristine original (' + b.err + '); refusing'); - if (!sameBuild(c, b.c)) die('existing backup ' + bak + ' is the original of another build; refusing'); - orig = b.buf; - } - +/* The edited image of `buf` (classified as `c`; `orig`, the pristine + * original of its build, whose stock geometry `--res stock` and the mid + * panel write back): { out, changed (what each changed region is for), + * writes ({ mapurl, showui, res }: what the edit leaves written), wrong (why + * the edited image does not read as exactly the requested state, at the + * same sites, changed only in the edit regions; null when it does) }. The + * disk patch (apply) and the in-memory plan (plan) both come from here. */ +function edited(buf, c, orig, panel, sinkUrl, wantRes) { + var slotLen = locator.SINK_STOCK.length; var loc = c.loc, out = Buffer.from(buf), changed = []; function put(what, off, bytes) { if (out.slice(off, off + bytes.length).equals(bytes)) return; @@ -662,11 +628,6 @@ function cmdApply(target, panel, capture, sink, res, safe, yes, unproven, coding if (writes.mapurl) c.mapurl.sites.forEach(function (s) { put('map URL -> ' + MAP_URL, s[0], Buffer.from(s[1], 'hex')); }); if (writes.showui) c.showui.sites.forEach(function (s) { put('ShowUI URL -> ' + SHOWUI_URL, s[0], Buffer.from(s[1], 'hex')); }); - var rec = applyRecord(record.current(target), !!PROVEN[loc.buildId], coding, c, writes); - if (changed.length === 0) { - repairMode(target, yes); - process.stdout.write('nothing to do; already in the requested state\n'); record.ensure(target, rec); return; - } /* The edited image must read as exactly the requested state, at the same * sites, changed only in the edit regions, before it is written. */ @@ -678,7 +639,59 @@ function cmdApply(target, panel, capture, sink, res, safe, yes, unproven, coding : cc.mapurl.state !== (writes.mapurl ? 'patched' : 'absent') ? 'map URL' : cc.showui.state !== (writes.showui ? 'patched' : 'absent') ? 'ShowUI URL' : !onlyRegionsDiffer(buf, out, regions(c)) ? 'bytes outside the edit regions' : null; - if (wrong) die('refusing: the edited binary does not verify (' + wrong + '); no change made'); + return { out: out, changed: changed, writes: writes, wrong: wrong }; +} + +function cmdApply(target, panel, capture, sink, res, safe, yes, unproven, codingFile) { + var hu = headUnit.refused(); + if (hu) die('refusing: ' + hu); + if (panel !== 'high' && panel !== 'mid') die('--panel must be high or mid'); + var coding = readCoding(codingFile), codingBad = codingRefusal(coding); + if (codingBad && !unproven) die('refusing: ' + codingBad + '; pass --unproven to patch it anyway'); + var wantRes = resFor(panel, res, safe); + var sinkUrl = sinkUrlFor(capture, sink), slotLen = locator.SINK_STOCK.length; + if (sinkUrl !== undefined && Buffer.byteLength(sinkUrl, 'latin1') > slotLen) + die('sink URL too long: "' + sinkUrl + '" is ' + Buffer.byteLength(sinkUrl, 'latin1') + ' bytes, slot holds ' + slotLen); + + var buf = readTarget(target), c = classify(buf), bad = unrecognised(c); + if (bad.length) die('refusing: ' + bad.join('; ')); + + /* Back up the pristine original before the first edit; require that a + * pre-existing backup is the pristine original of this build. */ + var bak = backupPath(target), orig = buf; + if (!fs.existsSync(bak)) { + var why = notPristine(c, buf); + if (why) die('first edit requires the pristine build: ' + why); + if (!PROVEN[c.loc.buildId] && !unproven) die(label(c) + ' (carplay ' + (c.loc.version || 'version unknown') + ') is not a proven build; pass --unproven to patch it anyway'); + /* The backup is written and checked under a temporary name, its record + * written in full and renamed into place, then the backup renamed: a + * backup never exists without its record. */ + var bakTmp = bak + '.tmp', metaTmp = metaPath(target) + '.tmp'; + [bakTmp, metaTmp].forEach(function (f) { try { fs.unlinkSync(f); } catch (e) {} }); /* an earlier apply's, cut short */ + fs.writeFileSync(bakTmp, buf, { mode: 0o600 }); + fsyncFile(bakTmp); + if (!fs.readFileSync(bakTmp).equals(buf)) { try { fs.unlinkSync(bakTmp); } catch (e) {} die('backup verification failed; no change made'); } + var origStat = fs.statSync(target); /* the original's mode and owner, which every later write gives carplay */ + fs.writeFileSync(metaTmp, JSON.stringify({ target: path.resolve(target), version: label(c), buildId: c.loc.buildId, + sha256_original: sha256(buf), mode: origStat.mode & 0o7777, uid: origStat.uid, gid: origStat.gid, + savedAt: new Date().toISOString() }, null, 2) + '\n', { mode: 0o600 }); + fsyncFile(metaTmp); + fs.renameSync(metaTmp, metaPath(target)); + fs.renameSync(bakTmp, bak); + } else { + var b = checkedBackup(target); + if (b.err) die('existing backup ' + bak + ' is not a pristine original (' + b.err + '); refusing'); + if (!sameBuild(c, b.c)) die('existing backup ' + bak + ' is the original of another build; refusing'); + orig = b.buf; + } + + var e = edited(buf, c, orig, panel, sinkUrl, wantRes), out = e.out, changed = e.changed, writes = e.writes, loc = c.loc; + var rec = applyRecord(record.current(target), !!PROVEN[loc.buildId], coding, c, writes); + if (changed.length === 0) { + repairMode(target, yes); + process.stdout.write('nothing to do; already in the requested state\n'); record.ensure(target, rec); return; + } + if (e.wrong) die('refusing: the edited binary does not verify (' + e.wrong + '); no change made'); process.stdout.write('About to patch ' + target + ':\n'); changed.forEach(function (x) { process.stdout.write(' ' + x + '\n'); }); @@ -795,6 +808,147 @@ function repairMode(target, yes) { * patched; fall back to in-place rewrite on a cross-device/busy rename. * Either way carplay gets its mode and owner explicitly (file_mode.js). The * caller remounts / read-write around this (deploy's remount window). */ +/* ---- in memory (PATCH.md "In memory") ---- */ + +/* The names of the regions regions(c) lists, in its order. */ +function regionNames(c) { + var out = ['variant', 'sink', 'selfstart', 'res-mm', 'res-px', 'res-safe1', 'res-safe2']; + URL_EDITS.forEach(function (e) { if (c[e].sites) c[e].sites.forEach(function (s, i) { out.push(e + '-' + (i + 1)); }); }); + return out; +} + +/* The plan libwocpatch.so applies ("wocplan 1"): the build-id, and for + * every edit region its virtual address, the bytes `buf` holds there and + * the bytes `out` holds (the same where the edit leaves the region stock, + * as the sink in the avb mode: the library checks it, and patchd's memory + * check tells a process running another mode's sink apart). Each region + * lies in one file-backed PT_LOAD part. { text, edits (the regions that + * change) } or { err }. */ +function planText(buf, out, c) { + var elf = locator.elf.parseElf(buf), names = regionNames(c), lines = ['wocplan 1', 'build-id ' + c.loc.buildId], edits = []; + if (!elf.load || !c.loc.buildId) return { err: 'no ELF load segments or no build-id' }; + var rs = regions(c); + for (var i = 0; i < rs.length; i++) { + var off = rs[i][0], len = rs[i][1]; + var seg = elf.load.filter(function (s) { return off >= s.off && off + len <= s.off + s.size; })[0]; + if (!seg) return { err: names[i] + ' at ' + hex(off) + ' is not inside one loaded segment' }; + if (len > 128) return { err: names[i] + ' is ' + len + ' bytes, more than a plan line holds' }; + lines.push(['edit', names[i], (seg.va + off - seg.off).toString(16), buf.slice(off, off + len).toString('hex'), out.slice(off, off + len).toString('hex')].join(' ')); + if (!buf.slice(off, off + len).equals(out.slice(off, off + len))) edits.push(names[i]); + } + if (!edits.length) return { err: 'nothing to edit' }; + lines.push('end ' + rs.length); + return { text: lines.join('\n') + '\n', edits: edits }; +} + +/* A plan's edits ([{name, va, stock, patched}]) and build-id, or { err }. */ +function parsePlan(text) { + var lines = text.split('\n'), edits = [], id = null, ended = false; + if (lines.pop() !== '' || lines[0] !== 'wocplan 1') return { err: 'not a version 1 plan' }; + for (var i = 1; i < lines.length; i++) { + var f = lines[i].split(' '); + if (ended) return { err: 'lines after its end' }; + if (f[0] === 'build-id' && f.length === 2) id = f[1]; + else if (f[0] === 'edit' && f.length === 5) edits.push({ name: f[1], va: parseInt(f[2], 16), stock: Buffer.from(f[3], 'hex'), patched: Buffer.from(f[4], 'hex') }); + else if (f[0] === 'end' && f.length === 2 && Number(f[1]) === edits.length) ended = true; + else return { err: 'bad line ' + (i + 1) }; + } + return ended && id && edits.length ? { id: id, edits: edits } : { err: 'cut short' }; +} + +/* What an earlier release's patch in `cur` is, against the original + * `orig` of its build and a plan made from `orig`: onlyPlan, the two differ + * only inside the plan's regions (a revert gives back exactly `orig`), and + * same, `cur` holds the plan's bytes at every one of them (the patch runs + * what the plan writes). { onlyPlan, same } or { err }. */ +function againstPlan(cur, orig, text) { + var p = parsePlan(text), elf = locator.elf.parseElf(orig); + if (p.err) return { err: 'plan: ' + p.err }; + if (!elf.load) return { err: elf.reason }; + if (cur.length !== orig.length) return { onlyPlan: false, same: false }; + var rs = [], same = true; + for (var i = 0; i < p.edits.length; i++) { + var e = p.edits[i], seg = elf.load.filter(function (s) { return e.va >= s.va && e.va + e.stock.length <= s.va + s.size; })[0]; + if (!seg) return { err: e.name + ' is not inside one loaded segment' }; + var off = seg.off + e.va - seg.va; + rs.push([off, e.stock.length]); + if (!cur.slice(off, off + e.stock.length).equals(e.patched)) same = false; + } + return { onlyPlan: onlyRegionsDiffer(cur, orig, rs), same: same }; +} + +/* `buf` with the plan laid over it, as the process the plan is applied to + * sees it, or { err } when the plan is not for this build or a site does + * not read stock. */ +function overlay(buf, text) { + var p = parsePlan(text), elf = locator.elf.parseElf(buf); + if (p.err) return { err: 'plan: ' + p.err }; + if (!elf.load) return { err: elf.reason }; + if (locator.elf.noteBuildId(buf, elf.notes) !== p.id) return { err: 'the plan is for build ' + p.id }; + var out = Buffer.from(buf); + for (var i = 0; i < p.edits.length; i++) { + var e = p.edits[i], seg = elf.load.filter(function (s) { return e.va >= s.va && e.va + e.stock.length <= s.va + s.size; })[0]; + if (!seg) return { err: e.name + ' is not inside one loaded segment' }; + var off = seg.off + e.va - seg.va; + if (!buf.slice(off, off + e.stock.length).equals(e.stock)) return { err: e.name + ' does not read as the plan\'s stock bytes' }; + e.patched.copy(out, off); + } + return { buf: out, edits: p.edits.map(function (e) { return e.name; }) }; +} + +/* `plan`: what `apply` would write, as a plan for libwocpatch.so, made from + * the file on disk, which must be the pristine build (it is what the + * process maps) and stays as it is. The same checks as apply's first edit: + * the head unit, the coding (--unproven), the locator, a proven build + * (--unproven). Writes the plan to `outFile` by rename and prints one JSON + * line: build, sha256, size, edits, provenBuild, coding ('ok', 'refused', + * 'unreadable'), writes. */ +function cmdPlan(target, panel, capture, sink, res, safe, unproven, codingFile, outFile) { + var hu = headUnit.refused(); + if (hu) die('refusing: ' + hu); + if (!outFile) die('plan needs --out '); + if (panel !== 'high' && panel !== 'mid') die('--panel must be high or mid'); + var coding = readCoding(codingFile), codingBad = codingRefusal(coding); + if (codingBad && !unproven) die('refusing: ' + codingBad + '; pass --unproven to patch it anyway'); + var wantRes = resFor(panel, res, safe); + var sinkUrl = sinkUrlFor(capture, sink); + if (sinkUrl !== undefined && Buffer.byteLength(sinkUrl, 'latin1') > locator.SINK_STOCK.length) die('sink URL too long'); + var buf = readTarget(target), c = classify(buf), bad = unrecognised(c); + if (bad.length) die('refusing: ' + bad.join('; ')); + var why = notPristine(c, buf); + if (why) die('in memory needs the pristine build on disk: ' + why); + if (!PROVEN[c.loc.buildId] && !unproven) die(label(c) + ' (carplay ' + (c.loc.version || 'version unknown') + ') is not a proven build; pass --unproven to patch it anyway'); + var e = edited(buf, c, buf, panel, sinkUrl, wantRes); + if (e.wrong) die('refusing: the edited image does not verify (' + e.wrong + ')'); + var p = planText(buf, e.out, c); + if (p.err) die('refusing: ' + p.err); + var o = overlay(buf, p.text); + if (o.err || !o.buf.equals(e.out)) die('refusing: the plan does not reproduce the edited image (' + (o.err || 'bytes differ') + ')'); + var tmp = outFile + '.tmp'; + fs.writeFileSync(tmp, p.text, { mode: 0o644 }); + fsyncFile(tmp); + fs.renameSync(tmp, outFile); + process.stdout.write(JSON.stringify({ build: c.loc.buildId, version: label(c), sha256: sha256(buf), size: buf.length, edits: p.edits, + provenBuild: !!PROVEN[c.loc.buildId], coding: cd(coding), writes: { mapurl: e.writes.mapurl, showui: e.writes.showui, res: e.writes.res ? resKey(e.writes.res) : null }, + planSha256: sha256(Buffer.from(p.text)) }) + '\n'); + function cd(x) { return x.err ? 'unreadable' : codingRefusal(x) ? 'refused' : 'ok'; } +} + +/* `overlay`: the edit lines of `status` for the file with the plan laid + * over it (what a process the plan was applied to runs), then `overlay: + * ok` or `overlay: NO — why`. Read-only. */ +function cmdOverlay(target, planFile) { + var buf = readTarget(target), text; + try { text = fs.readFileSync(planFile, 'utf8'); } catch (e) { line('overlay', 'NO — ' + e.message); return; } + var o = overlay(buf, text); + if (o.err) { line('overlay', 'NO — ' + o.err); return; } + var c = classify(o.buf); + if (!c.ok) { line('overlay', 'NO — ' + c.reason); return; } + EDITS.concat(URL_EDITS).forEach(function (e) { line(e, describe(e, c[e])); }); + line('edits', o.edits.join(' ')); + line('overlay', 'ok'); +} + function writeInPlace(target, buf) { try { fileMode.replace(target, buf, wantedMode(target), true); } catch (e) { die('writing ' + target + ': ' + e.message); } } @@ -820,6 +974,8 @@ function parseArgs(argv) { else if (t === '--target') a.target = argv[++i]; else if (t === '--coding') a.coding = argv[++i]; else if (t === '--panel') a.panel = argv[++i]; + else if (t === '--out') a.out = argv[++i]; + else if (t === '--plan') a.plan = argv[++i]; else if (t === '--capture') { /* A missing or flag-shaped value is an error, not "no capture". */ a.capture = (i + 1 < argv.length && argv[i + 1].indexOf('--') !== 0) ? argv[++i] : null; @@ -844,9 +1000,11 @@ function main() { else if (cmd === 'apply') cmdApply(target, a.panel, a.capture, a.sink, a.res, a.safe, a.yes, a.unproven, coding); else if (cmd === 'revert') cmdRevert(target, a.yes, a.force, a.dropBackup); else if (cmd === 'verify') cmdVerify(target); - else { process.stderr.write('usage: carplay_patch.js status|probe|apply|revert|verify [--target ] [--coding ] [--panel high|mid] [--capture | --sink ] [--res WxH|stock] [--safe WxH+X+Y|full] [--unproven] [--yes] [--force] [--drop-backup]\n'); process.exit(2); } + else if (cmd === 'plan') cmdPlan(target, a.panel, a.capture, a.sink, a.res, a.safe, a.unproven, coding, a.out); + else if (cmd === 'overlay') { cmdOverlay(target, a.plan); line('end', 'complete'); } + else { process.stderr.write('usage: carplay_patch.js status|probe|apply|revert|verify|plan|overlay [--target ] [--coding ] [--panel high|mid] [--capture | --sink ] [--res WxH|stock] [--safe WxH+X+Y|full] [--unproven] [--yes] [--force] [--drop-backup]\n'); process.exit(2); } } -module.exports = { trustedBackup: trustedBackup, PROVEN: PROVEN }; +module.exports = { trustedBackup: trustedBackup, PROVEN: PROVEN, parsePlan: parsePlan, overlay: overlay, againstPlan: againstPlan }; if (require.main === module) main(); diff --git a/native/waze-on-cluster/patch/inmem.js b/native/waze-on-cluster/patch/inmem.js new file mode 100644 index 00000000..b3c9cd2b --- /dev/null +++ b/native/waze-on-cluster/patch/inmem.js @@ -0,0 +1,360 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Copyright (C) 2026 Robert Nisipeanu +'use strict'; +/* inmem.js — the carplay patch applied in memory (PATCH.md "In memory"). + * /usr/bin/carplay stays as it ships; libwocpatch.so, preloaded into a + * carplay start the boot step armed, applies the same edits to the process + * before carplay's own code runs. + * + * On /var/opt (no remount of / for any of it): + * inmem-carplay.plan the plan (carplay_patch.js plan): the build-id and, + * per edit region, its address, stock and patched + * bytes + * inmem-carplay.json the record: {v, enabled, target, ino, size, mtime, + * sha256, build, planSha256, edits, opts, writes, + * proven, trial, at, and when turned off by: "user" | + * "recovery" | "refused" (recovery also fails, why)} + * It describes the target only while its inode, size and modification + * time are the recorded ones, and the plan only while its SHA-256 is. + * + * In /run (gone at every head-unit start), written by arm() before carplay + * starts, only while the record is current and enabled: + * /run/woc-preload/carplay.plan the plan, readable by carplay's user + * /run/woc-preload/carplay.result empty, owned by carplay's user: the + * library writes its result there + * /run/woc-preload/carplay.env LD_PRELOAD (the unit's own preloads, + * then this version's library), + * WOC_PATCH_PLAN, WOC_PATCH_RESULT; + * written last. The tool's carplay.service + * drop-in reads it with EnvironmentFile=-, + * so without it carplay starts stock. + * + * Node 8 on the unit. No dependencies. + */ +var fs = require('fs'); +var path = require('path'); +var cp = require('child_process'); +var crypto = require('crypto'); + +var STATE_DIR = process.env.WOC_STATE_DIR || '/var/opt/waze-on-cluster'; +var RUN_DIR = process.env.WOC_PRELOAD_DIR || '/run/woc-preload'; +var LIB = process.env.WOC_PRELOAD_LIB || path.join(__dirname, 'libwocpatch.so'); +var PROC = process.env.WOC_PROC || '/proc'; +var SYSTEMCTL = process.env.WOC_SYSTEMCTL || 'systemctl'; +var PASSWD = process.env.WOC_PASSWD || '/etc/passwd'; + +var TARGETS = { + carplay: { name: 'carplay', unit: 'carplay.service', target: process.env.WOC_CARPLAY || '/usr/bin/carplay' }, +}; + +function paths(name) { + return { + record: path.join(STATE_DIR, 'inmem-' + name + '.json'), + plan: path.join(STATE_DIR, 'inmem-' + name + '.plan'), + env: path.join(RUN_DIR, name + '.env'), + runPlan: path.join(RUN_DIR, name + '.plan'), + result: path.join(RUN_DIR, name + '.result'), + }; +} + +/* The folder, made where it is missing (Node 8: no recursive mkdir). */ +function ensureDir(d) { + try { fs.mkdirSync(d, 0o755); } catch (e) { if (e.code !== 'EEXIST') throw e; } +} + +function sha256(buf) { return crypto.createHash('sha256').update(buf).digest('hex'); } +function readOr(f, enc) { try { return fs.readFileSync(f, enc); } catch (e) { return null; } } + +function fsyncPath(p) { + var fd = fs.openSync(p, 'r'); + try { fs.fsyncSync(fd); } finally { fs.closeSync(fd); } +} + +/* Writes data to file whole: a temporary file, fsynced, renamed, the folder + * synced. Throws when it cannot; the previous file then stays. */ +function writeWhole(file, data, mode) { + var tmp = file + '.tmp'; + try { + fs.writeFileSync(tmp, data, { mode: mode || 0o644 }); + fs.chmodSync(tmp, mode || 0o644); + fsyncPath(tmp); + fs.renameSync(tmp, file); + } catch (e) { + try { fs.unlinkSync(tmp); } catch (e2) {} + throw e; + } + try { fsyncPath(path.dirname(file)); } catch (e) {} +} + +/* The record as written, or null. */ +function readRecord(name) { + var r = null; + try { r = JSON.parse(fs.readFileSync(paths(name).record, 'utf8')); } catch (e) { return null; } + return r && typeof r === 'object' && r.v === 1 ? r : null; +} + +/* Whether the record describes the target as it is now and the plan on + * /var/opt is the one it names. */ +function describes(name, rec) { + var st, t = TARGETS[name], plan = readOr(paths(name).plan); + try { st = fs.statSync(t.target); } catch (e) { return false; } + return !!rec && rec.ino === st.ino && rec.size === st.size && rec.mtime === st.mtime.getTime() && !!plan && sha256(plan) === rec.planSha256; +} + +/* The record while it describes the target and is enabled, else null. */ +function current(name) { + var rec = readRecord(name); + return rec && rec.enabled === true && describes(name, rec) ? rec : null; +} + +/* What boot recovery counts the patch as: 'proven', 'unproven' (on trial, + * or a build outside the proven list or a car coded otherwise), or null + * when nothing is to be armed. */ +function kind(name) { + var rec = current(name); + return !rec ? null : rec.proven === true && rec.trial !== true ? 'proven' : 'unproven'; +} + +/* The record with fields merged in, written whole. Throws. */ +function update(name, fields) { + var rec = readRecord(name); + if (!rec) throw new Error('no in-memory record for ' + name); + writeWhole(paths(name).record, JSON.stringify(Object.assign(rec, fields)) + '\n'); + return rec; +} + +/* Makes the plan for the target as it is on disk (carplay_patch.js plan, + * every check of an apply's first edit), and on success writes it with a + * record, enabled. prior: the record before (its proven state carries over + * only for the same plan of the same file); opts.ran: this car ran these + * very bytes healthy (an earlier release's proven patch of the file), so + * a proven build on the proven coding is recorded proven. cb(err, rec): err.refused with + * the patcher's own words when it refuses the file (a conflict, not a + * failure). */ +function makePlan(name, args, timeoutMs, cb, opts) { + var t = TARGETS[name], p = paths(name), tmp = p.plan + '.new', st0; + try { st0 = fs.statSync(t.target); ensureDir(STATE_DIR); } catch (e) { cb(e); return; } + cp.execFile(process.execPath, [path.join(__dirname, 'carplay_patch.js'), 'plan', '--target', t.target, '--out', tmp].concat(args), + { timeout: timeoutMs || 60000 }, function (err, out, errOut) { + var m = /^error: (.*)$/m.exec((errOut || '') + ''), sum = null; + if (err) { + try { fs.unlinkSync(tmp); } catch (e) {} + var e = new Error(m ? m[1] : err.message); + if (m) e.refused = m[1]; + cb(e); + return; + } + try { sum = JSON.parse(((out || '') + '').trim().split('\n').pop()); } catch (e2) { cb(new Error('plan: no summary')); return; } + var st1; + try { st1 = fs.statSync(t.target); } catch (e3) { cb(e3); return; } + if (st1.ino !== st0.ino || st1.size !== st0.size || st1.mtime.getTime() !== st0.mtime.getTime()) { + try { fs.unlinkSync(tmp); } catch (e) {} + cb(new Error(t.target + ' changed while the plan was made')); + return; + } + var prior = readRecord(name); + var same = !!prior && prior.planSha256 === sum.planSha256 && prior.ino === st1.ino && prior.mtime === st1.mtime.getTime(); + /* Proven carries over only from a patch that ran healthy here and is + * on, or that the user turned off (Remove patch); one boot recovery + * turned off goes on trial again. */ + var proven = sum.provenBuild && sum.coding === 'ok' && ((same && prior.proven === true && prior.trial !== true && + (prior.enabled === true || prior.by === 'user')) || !!(opts && opts.ran)); + var onTrial = !proven && sum.provenBuild && sum.coding !== 'refused'; + var rec = { v: 1, enabled: true, target: t.target, ino: st1.ino, size: st1.size, mtime: st1.mtime.getTime(), sha256: sum.sha256, + build: sum.build, version: sum.version, planSha256: sum.planSha256, edits: sum.edits, writes: sum.writes, args: args, + proven: proven, trial: onTrial, at: new Date().toISOString() }; + try { + fs.renameSync(tmp, p.plan); + writeWhole(p.record, JSON.stringify(rec) + '\n'); + } catch (e4) { cb(e4); return; } + cb(null, rec); + }); +} + +/* Runs the plan's checks on file (an original a revert would put in + * place), writing no plan or record. cb(err, planText): err.refused with + * the patcher's words when it refuses. */ +function checkPlan(file, args, timeoutMs, cb) { + var tmp = path.join(STATE_DIR, 'inmem-check.plan'); + try { ensureDir(STATE_DIR); } catch (e) { cb(e); return; } + cp.execFile(process.execPath, [path.join(__dirname, 'carplay_patch.js'), 'plan', '--target', file, '--out', tmp].concat(args), + { timeout: timeoutMs || 60000 }, function (err, out, errOut) { + var text = readOr(tmp, 'utf8'); + try { fs.unlinkSync(tmp); } catch (e) {} + var m = /^error: (.*)$/m.exec((errOut || '') + ''); + if (!err) { cb(null, text); return; } + var e = new Error(m ? m[1] : err.message); + if (m) e.refused = m[1]; + cb(e); + }); +} + +/* Turns the patch off for later starts: the record enabled false with why + * (fields: {by, ...}). The running process keeps what it applied until it + * ends; disarm() keeps the next start of this boot stock. Throws. */ +function disable(name, fields) { + var rec = readRecord(name); + if (!rec) return null; + return update(name, Object.assign({ enabled: false, at: new Date().toISOString() }, fields)); +} + +/* Removes the record, the plan and this boot's files in RUN_DIR (a + * removal of the tool). */ +function remove(name) { + var p = paths(name); + [p.record, p.plan, p.plan + '.new', p.record + '.tmp', p.env, p.runPlan, p.result].forEach(function (f) { + try { fs.unlinkSync(f); } catch (e) { if (e.code !== 'ENOENT') throw e; } + }); + try { fs.rmdirSync(RUN_DIR); } catch (e) {} +} + +/* The LD_PRELOAD the unit sets itself (carplay.service's Environment=, + * BMW's libschedconfig), kept in front of ours. */ +function unitPreload(unit) { + var out = ''; + try { out = cp.execFileSync(SYSTEMCTL, ['show', unit, '-p', 'Environment'], { timeout: 10000, encoding: 'utf8' }); } catch (e) { return null; } + var m = /(?:^Environment=|\s)LD_PRELOAD=(\S+)/m.exec(out); + return m ? m[1] : ''; +} + +function unitUser(unit) { + var out = ''; + try { out = cp.execFileSync(SYSTEMCTL, ['show', unit, '-p', 'User'], { timeout: 10000, encoding: 'utf8' }); } catch (e) { return null; } + var m = /^User=(\S+)/m.exec(out); + return m ? m[1] : null; +} + +function uidOf(user) { + var lines = (readOr(PASSWD, 'utf8') || '').split('\n'); + for (var i = 0; i < lines.length; i++) { + var f = lines[i].split(':'); + if (f[0] === user && f.length > 3) return { uid: parseInt(f[2], 10), gid: parseInt(f[3], 10) }; + } + return null; +} + +/* Whether arm() can work here, checked before anything is changed for + * it: the library, the unit's preload and user, and RUN_DIR (ours or not + * there yet). {ok} or {ok: false, why}. */ +function canArm(name) { + var t = TARGETS[name]; + if (!fs.existsSync(LIB)) return { ok: false, why: LIB + ' missing' }; + if (unitPreload(t.unit) === null) return { ok: false, why: 'cannot read ' + t.unit + '\'s environment' }; + var user = unitUser(t.unit); + if (!user || !uidOf(user)) return { ok: false, why: 'no user for ' + t.unit }; + try { + var rd = fs.lstatSync(RUN_DIR); + if (!rd.isDirectory() || rd.uid !== (process.getuid ? process.getuid() : rd.uid)) return { ok: false, why: RUN_DIR + ' is not our folder' }; + } catch (e) { if (e.code !== 'ENOENT') return { ok: false, why: e.message }; } + return { ok: true }; +} + +/* Whether this boot's next start of the service is armed with the current + * plan. */ +function armed(name) { + var rec = current(name), p = paths(name), plan = readOr(p.runPlan); + return !!rec && !!readOr(p.env) && !!plan && sha256(plan) === rec.planSha256; +} + +/* Arms the service's next starts this boot: the plan, the result file and + * last the env file in RUN_DIR. Nothing when the record is not current or + * enabled, or this boot is armed with it already (the result of a run is + * kept). {armed: true} or {armed: false, why}. Never throws. */ +function arm(name, opts) { + opts = opts || {}; + var t = TARGETS[name], p = paths(name), rec = current(name); + if (!rec) return { armed: false, why: 'no enabled in-memory patch for ' + t.target + ' as it is' }; + if (armed(name)) return { armed: true, already: true }; + try { + if (!fs.existsSync(LIB)) throw new Error(LIB + ' missing'); + var pre = opts.preload !== undefined ? opts.preload : unitPreload(t.unit); + if (pre === null) throw new Error('cannot read ' + t.unit + '\'s environment'); + if (/\s/.test(LIB)) throw new Error('unusable preload path ' + LIB); + pre = pre.split(/[\s:]+/).filter(function (x) { return x && x !== LIB; }).join(' '); + var user = opts.user !== undefined ? opts.user : unitUser(t.unit), ids = user ? uidOf(user) : null; + if (!ids) throw new Error('no user for ' + t.unit); + try { fs.mkdirSync(RUN_DIR, 0o755); } catch (e) { if (e.code !== 'EEXIST') throw e; } + var rd = fs.lstatSync(RUN_DIR); + if (!rd.isDirectory() || rd.uid !== (process.getuid ? process.getuid() : rd.uid)) throw new Error(RUN_DIR + ' is not our folder'); + fs.chmodSync(RUN_DIR, 0o755); + writeWhole(p.runPlan, fs.readFileSync(p.plan), 0o644); + try { fs.unlinkSync(p.result); } catch (e) {} + var fd = fs.openSync(p.result, 'wx', 0o644); + fs.closeSync(fd); + fs.chmodSync(p.result, 0o644); + if (process.getuid && process.getuid() === 0) fs.chownSync(p.result, ids.uid, ids.gid); + writeWhole(p.env, 'LD_PRELOAD=' + (pre ? pre + ' ' : '') + LIB + '\nWOC_PATCH_PLAN=' + p.runPlan + '\nWOC_PATCH_RESULT=' + p.result + '\n', 0o644); + return { armed: true }; + } catch (e) { + disarm(name); + return { armed: false, why: e.message }; + } +} + +/* The next start runs stock: the env file goes first. Never throws; + * false when it could not be removed. */ +function disarm(name) { + var p = paths(name), ok = true; + [p.env, p.runPlan].forEach(function (f) { try { fs.unlinkSync(f); } catch (e) { if (e.code !== 'ENOENT') ok = false; } }); + return ok; +} + +/* The library's result of this boot: {pid, applied, edits, why}, or null. */ +function result(name) { + var r = null; + try { r = JSON.parse(fs.readFileSync(paths(name).result, 'utf8')); } catch (e) { return null; } + return r && r.v === 1 ? r : null; +} + +/* The plan's edits ([{name, va, stock, patched}]), or null. */ +function planEdits(text) { + var p = require('./carplay_patch.js').parsePlan(text); + return p.err ? null : p.edits; +} + +/* What the process pid holds at the plan's sites, read from + * /proc//mem (root, read-only): 'patched' (every site), 'stock' + * (every site), 'mixed', or null when it cannot be read. The base is the + * first mapping, at file offset 0, of the file the process runs: its + * /proc//exe, or (a binary translator's exe) the target or a file a + * change replaced while it ran (.woc-running*). */ +function memState(name, pid, planText) { + var t = TARGETS[name], edits = planEdits(planText || readOr(paths(name).plan, 'utf8') || ''); + if (!edits || !(pid > 0)) return null; + var inodes = [], exe = path.join(PROC, String(pid), 'exe'), exeName = ''; + try { exeName = path.basename(fs.readlinkSync(exe)); } catch (e) {} + [exeName.indexOf(path.basename(t.target)) === 0 ? exe : null, t.target, t.target + '.woc-running', t.target + '.woc-running.1', t.target + '.woc-running.2'].forEach(function (f) { + if (f) try { inodes.push(fs.statSync(f).ino); } catch (e) {} + }); + var maps = readOr(path.join(PROC, String(pid), 'maps'), 'utf8'); + if (!maps) return null; + var base = null; + maps.split('\n').some(function (l) { + var f = l.split(/\s+/); + if (f.length < 6 || parseInt(f[2], 16) !== 0 || inodes.indexOf(Number(f[4])) < 0) return false; + base = parseInt(f[0].split('-')[0], 16); + return true; + }); + if (base === null) return null; + /* A region the plan leaves as it ships (the sink in the avb mode) must + * read so either way: a process running another mode's sink is + * neither. */ + var fd, seen = { patched: 0, stock: 0, other: 0 }, changed = 0; + try { + fd = fs.openSync(path.join(PROC, String(pid), 'mem'), 'r'); + edits.forEach(function (e) { + var b = Buffer.alloc(e.stock.length); + fs.readSync(fd, b, 0, b.length, base + e.va); + if (e.stock.equals(e.patched)) { if (!b.equals(e.stock)) seen.other++; return; } + changed++; + seen[b.equals(e.patched) ? 'patched' : b.equals(e.stock) ? 'stock' : 'other']++; + }); + } catch (e) { return null; } finally { if (fd !== undefined) fs.closeSync(fd); } + return seen.other ? 'mixed' : seen.patched === changed ? 'patched' : seen.stock === changed ? 'stock' : 'mixed'; +} + +module.exports = { + TARGETS: TARGETS, paths: paths, readRecord: readRecord, current: current, kind: kind, describes: describes, update: update, + makePlan: makePlan, checkPlan: checkPlan, canArm: canArm, disable: disable, remove: remove, arm: arm, armed: armed, disarm: disarm, result: result, memState: memState, + LIB: LIB, RUN_DIR: RUN_DIR, +}; diff --git a/native/waze-on-cluster/patch/patchd.js b/native/waze-on-cluster/patch/patchd.js index 710652d1..25a5843e 100644 --- a/native/waze-on-cluster/patch/patchd.js +++ b/native/waze-on-cluster/patch/patchd.js @@ -158,6 +158,7 @@ var bootIds = require('./boot_id.js'); var headUnit = require('./head_unit.js'); var record = require('./patch_record.js'); var wifiBand = require('./wifi_band.js'); +var inmem = require('./inmem.js'); var HERE = __dirname; var PATCHER = path.join(HERE, 'carplay_patch.js'); @@ -723,6 +724,53 @@ function writePending(t, action, run, extra) { } catch (e) { log('pending marker: ' + e.message); } } +/* The CarPlay state the edit lines of a patcher status say (status or + * overlay): {state, mode, reason, res, safe, mapurl, panel, ours}. */ +function editState(text, known) { + var variant = /variant:\s+PATCHED -> IC_(HIGH|MID)/.exec(text); + var redirect = /sink:\s+REDIRECTED -> (\S+)/.exec(text); + var sinkRedirected = !!redirect; + var sinkOriginal = /sink:\s+ORIGINAL/.test(text); + var selfstart = /selfstart:\s+SELF-START/.test(text); + var resMatch = /res:\s+PATCHED \(IC_HIGH advertises (\d+x\d+)/.exec(text); + var safeMatch = /res:\s+PATCHED \(IC_HIGH advertises [^,\n]*, safe (\d+x\d+) at (\d+),(\d+)\)/.exec(text); + var resOriginal = /res:\s+ORIGINAL/.test(text); + /* The URL edits (map URL, ShowUI URL): 'eta' (the ShowUI URL with + * the arrival-time card), 'map' (the map URL alone, on a build + * without the ShowUI URL edit), 'no-eta' (either in a form CarPlay's + * Patch button replaces or completes), 'off', or null where the + * build lacks both or the status says neither. */ + var m5 = /^mapurl:\s+(ORIGINAL|PATCHED WITH ETA|PATCHED) /m.exec(text), m6 = /^showui:\s+(ORIGINAL|PATCHED) /m.exec(text); + var e5 = m5 ? m5[1] : null, e6 = m6 ? m6[1] : null; + var mapurl = e5 === 'PATCHED WITH ETA' || (e5 === 'PATCHED' && e6 === 'ORIGINAL') || (e5 === 'ORIGINAL' && e6 === 'PATCHED') ? 'no-eta' + : e6 === 'PATCHED' ? 'eta' : e5 === 'PATCHED' ? 'map' : e5 === 'ORIGINAL' || e6 === 'ORIGINAL' ? 'off' : null; + var state, mode = null, reason = null; + var res = resMatch ? resMatch[1] : null; + /* The advertised safe area as "WxH+X+Y". A patched binary with another + * safe area than the one CarPlay's Patch button writes is still + * patched; the app compares the two and offers that button. */ + var safe = safeMatch ? safeMatch[1] + '+' + safeMatch[2] + '+' + safeMatch[3] : null; + var resOk = !variant || variant[1] !== 'HIGH' || !!resMatch; + if (!known) state = 'unknown'; + else if (variant && selfstart && resOk && (sinkRedirected || sinkOriginal)) { + state = 'patched'; + mode = !sinkRedirected ? 'avb' : /^file:\/\//.test(redirect[1]) ? 'fifo' + : /^udp:\/\//.test(redirect[1]) ? 'udp' : redirect[1].replace(/:.*/, ''); + } + else if (variant && !selfstart && (sinkRedirected || sinkOriginal)) { + state = 'unknown'; + reason = 'self-start edit missing (older patch); CarPlay\'s Patch button applies it'; + } + else if (variant && selfstart && resOriginal && (sinkRedirected || sinkOriginal)) { + state = 'unknown'; + reason = 'resolution edit missing (older patch); CarPlay\'s Patch button applies it'; + } + else if (/variant:\s+ORIGINAL/.test(text) && sinkOriginal) state = 'original'; + else state = 'unknown'; + return { state: state, mode: mode, reason: reason, res: res, safe: safe, mapurl: mapurl, panel: variant ? variant[1].toLowerCase() : null, + ours: !!(variant || selfstart || resMatch || sinkRedirected) }; +} + /* Read the patcher's state of the target binary. Only one hashing subprocess * runs at a time; a caller that arrives while one is in flight gets that * read's state. */ @@ -731,23 +779,6 @@ function readState(cb) { statusWaiters = [cb]; cp.execFile(process.execPath, [PATCHER, 'status', '--target', TARGET, '--coding', CODING], { timeout: tmo(15000) }, function (err, out) { var text = (out || '') + ''; - var variant = /variant:\s+PATCHED -> IC_(HIGH|MID)/.exec(text); - var redirect = /sink:\s+REDIRECTED -> (\S+)/.exec(text); - var sinkRedirected = !!redirect; - var sinkOriginal = /sink:\s+ORIGINAL/.test(text); - var selfstart = /selfstart:\s+SELF-START/.test(text); - var resMatch = /res:\s+PATCHED \(IC_HIGH advertises (\d+x\d+)/.exec(text); - var safeMatch = /res:\s+PATCHED \(IC_HIGH advertises [^,\n]*, safe (\d+x\d+) at (\d+),(\d+)\)/.exec(text); - var resOriginal = /res:\s+ORIGINAL/.test(text); - /* The URL edits (map URL, ShowUI URL): 'eta' (the ShowUI URL with - * the arrival-time card), 'map' (the map URL alone, on a build - * without the ShowUI URL edit), 'no-eta' (either in a form CarPlay's - * Patch button replaces or completes), 'off', or null where the - * build lacks both or the status says neither. */ - var m5 = /^mapurl:\s+(ORIGINAL|PATCHED WITH ETA|PATCHED) /m.exec(text), m6 = /^showui:\s+(ORIGINAL|PATCHED) /m.exec(text); - var e5 = m5 ? m5[1] : null, e6 = m6 ? m6[1] : null; - var mapurl = e5 === 'PATCHED WITH ETA' || (e5 === 'PATCHED' && e6 === 'ORIGINAL') || (e5 === 'ORIGINAL' && e6 === 'PATCHED') ? 'no-eta' - : e6 === 'PATCHED' ? 'eta' : e5 === 'PATCHED' ? 'map' : e5 === 'ORIGINAL' || e6 === 'ORIGINAL' ? 'off' : null; var known = /known:\s+NO/.test(text) ? false : true; var unknownWhy = /known:\s+NO — (.*)/.exec(text); var pristine = /known:\s+yes, pristine/.test(text); @@ -765,29 +796,7 @@ function readState(cb) { * keeps the stock geometry by design. mode distinguishes the capture * sink: stock avb:// the media bus the render joins, udp:// the * stream sink the bridge accepts, file:// the FIFO. */ - var state, mode = null, reason = null; - var res = resMatch ? resMatch[1] : null; - /* The advertised safe area as "WxH+X+Y". A patched binary with another - * safe area than the one CarPlay's Patch button writes is still - * patched; the app compares the two and offers that button. */ - var safe = safeMatch ? safeMatch[1] + '+' + safeMatch[2] + '+' + safeMatch[3] : null; - var resOk = !variant || variant[1] !== 'HIGH' || !!resMatch; - if (!known) state = 'unknown'; - else if (variant && selfstart && resOk && (sinkRedirected || sinkOriginal)) { - state = 'patched'; - mode = !sinkRedirected ? 'avb' : /^file:\/\//.test(redirect[1]) ? 'fifo' - : /^udp:\/\//.test(redirect[1]) ? 'udp' : redirect[1].replace(/:.*/, ''); - } - else if (variant && !selfstart && (sinkRedirected || sinkOriginal)) { - state = 'unknown'; - reason = 'self-start edit missing (older patch); CarPlay\'s Patch button applies it'; - } - else if (variant && selfstart && resOriginal && (sinkRedirected || sinkOriginal)) { - state = 'unknown'; - reason = 'resolution edit missing (older patch); CarPlay\'s Patch button applies it'; - } - else if (/variant:\s+ORIGINAL/.test(text) && sinkOriginal) state = 'original'; - else state = 'unknown'; + var es = editState(text, known), state = es.state, mode = es.mode, reason = es.reason, res = es.res, safe = es.safe, mapurl = es.mapurl; /* What keeps the tool from writing the patch by itself: a head unit * that refuses our parts, a binary the patcher cannot patch (an edit * site not found, or one it does not recognise), one something else @@ -808,14 +817,59 @@ function readState(cb) { var carplay = null, binary = state; var pending = readPending(CP); if (pending) { state = 'unknown'; mode = null; reason = pending.reason; carplay = 'deferred'; } - var st = { state: state, panel: variant ? variant[1].toLowerCase() : null, mode: mode, res: res, safe: safe, mapurl: mapurl, reason: reason, carplay: carplay, + var st = { state: state, panel: es.panel, mode: mode, res: res, safe: safe, mapurl: mapurl, reason: reason, carplay: carplay, pending: pending ? pending.action || 'apply' : null, pendingBy: pending ? pending.by : null, conflict: conflict, coding: coding ? Number(coding[1]) : null, binary: binary, known: known, backup: hasBackup, restorable: restorable, proven: proven, recovered: recovered(TARGET), - ours: !!(variant || selfstart || resMatch || sinkRedirected), unreadable: !!(err && !text), + ours: es.ours, unreadable: !!(err && !text), complete: !err && /^end:\s+complete$/m.test(text) }; - var waiters = statusWaiters; - statusWaiters = null; - waiters.forEach(function (w) { w(st); }); + st.diskConflict = conflict; + inmemOverlay(st, function () { + var waiters = statusWaiters; + statusWaiters = null; + waiters.forEach(function (w) { w(st); }); + }); + }); +} + +/* The status of the patch in memory over the file's (st, changed in + * place): with an enabled record for carplay as it is, the state the + * overlay of its plan says (carplay_patch.js overlay), patched while the + * running carplay's memory holds the plan's bytes, else waiting for the + * next start, or a conflict with the library's reason where it refused + * for the running carplay; with the record turned off and carplay still + * running the patch, the removal waiting. */ +function inmemOverlay(st, cb) { + var rec = inmem.readRecord('carplay'), cur = inmem.current('carplay'); + if (!rec) { cb(); return; } + carplayMem(function (pid, mem) { + if (!cur) { + if (rec.by === 'recovery' && inmem.describes('carplay', rec)) st.recovered = rec.fails || 1; + if (mem === 'patched') { st.state = 'unknown'; st.reason = CP.reasons.revert; st.carplay = 'deferred'; st.pending = 'revert'; st.removable = false; } + cb(); + return; + } + cp.execFile(process.execPath, [PATCHER, 'overlay', '--target', TARGET, '--plan', inmem.paths('carplay').plan], { timeout: tmo(15000) }, function (err, out) { + var text = (out || '') + ''; + if (err || !/^overlay:\s+ok$/m.test(text)) { + st.state = 'unknown'; + st.conflict = 'in-memory plan unusable: ' + ((/^overlay:\s+NO — (.*)$/m.exec(text) || [])[1] || (err ? err.message : 'no answer')); + cb(); + return; + } + var es = editState(text, true); + st.panel = es.panel; st.res = es.res; st.safe = es.safe; st.mapurl = es.mapurl; + st.removable = true; + st.conflict = headUnit.refused() ? notSupported(headUnit.refused()) : codingConflict(st.coding === null ? null : [null, String(st.coding)]) || foreignStart(CP); + var res = inmem.result('carplay'); + if (mem === 'patched') { st.state = es.state; st.mode = es.mode; st.reason = es.reason; st.carplay = null; st.pending = null; } + else if (res && res.pid === pid && res.applied === false) { + /* The library refused for the running carplay: a restart would + * not change that. */ + st.state = 'unknown'; st.mode = null; st.carplay = null; st.pending = null; + st.conflict = st.conflict || 'not applied in memory: ' + (res.why || 'no reason given'); + } else { st.state = 'unknown'; st.mode = null; st.reason = CP.reasons.apply; st.carplay = 'deferred'; st.pending = 'apply'; } + cb(); + }); }); } @@ -960,7 +1014,7 @@ function status(extra, aaExtra) { readAaState(function (aa) { var cpBusy = busy === 'carplay'; var msg = { ev: 'status', state: cpBusy ? 'busy' : st.state, panel: st.panel, mode: st.mode, res: st.res, safe: st.safe, mapurl: st.mapurl, - removable: !!st.restorable, busy: busy || (rebooting ? 'restart' : null), restart: restartMsg() }; + removable: !!(st.restorable || st.removable), busy: busy || (rebooting ? 'restart' : null), restart: restartMsg() }; if (!cpBusy && st.reason) msg.reason = st.reason; if (!cpBusy && st.carplay) msg.carplay = st.carplay; if (!cpBusy && st.pending) msg.pending = st.pending; @@ -1573,6 +1627,243 @@ function revert(noRestart, dropBackup, done) { runPatch(CP, ['revert', '--target', TARGET, '--yes'].concat(dropBackup ? ['--drop-backup'] : []), 'revert', noRestart, done); } +/* ---- the carplay patch in memory (inmem.js, PATCH.md "In memory") ---- + * + * This version never writes /usr/bin/carplay to patch it. A patch is a plan + * (carplay_patch.js plan, from the stock file on disk) and a record on + * /var/opt; boot recovery arms each start from them, and libwocpatch.so + * applies the plan in carplay's memory. A patch an earlier release wrote to + * the file is reverted (from our verified backup, which then goes), in the + * same step that arms the plan, so the next carplay start runs the stock + * file with the edits in memory. */ + +/* The plan's arguments for the patcher, as apply() gives them. */ +function planArgs(panel, mode, unproven) { + var args = ['--panel', panel, '--coding', CODING].concat(unproven ? ['--unproven'] : []); + if (mode === 'udp') args.push('--sink', 'udp://127.0.0.1:' + UDP_PORT + '?mime_type=video/H264'); + else if (mode !== 'avb') args.push('--capture', FIFO); + return args; +} + +/* carplay's main PID now (0 when none) and what its memory holds at the + * plan's sites: 'patched', 'stock', 'mixed' or null. */ +function carplayMem(cb, planText) { + cp.execFile('systemctl', ['show', CP.unit, '-p', 'MainPID'], { timeout: tmo(15000) }, function (err, out) { + var m = /^MainPID=(\d+)/m.exec((out || '') + ''), pid = m ? parseInt(m[1], 10) : 0; + cb(pid, pid > 0 ? inmem.memState('carplay', pid, planText) : null); + }); +} + +/* The failed starts and crashes boot recovery counts: its state's fails + * and this boot's arm's crashes. */ +function countedFails() { + var st = null; + try { st = JSON.parse(fs.readFileSync(require('./recovery.js').TARGETS.carplay.state, 'utf8')); } catch (e) { return 0; } + var boot = bootId(); + return (st && st.fails || 0) + (st && st.arm && st.arm.boot === boot ? st.arm.crashes || 0 : 0); +} + +/* Boot recovery's decision for this boot, run now (recovery.js _decide): + * it records this boot's arm for the enabled patch and arms carplay's next + * start, or turns the patch off at the threshold. cb(result). */ +function armNow(cb) { + var rec = require('./recovery.js'); + new rec.Recovery({ target: rec.TARGETS.carplay, log: log })._decide(function (r) { log('boot recovery: ' + r.action + (r.inmem ? ' in memory' : '')); cb(r); }); +} + +/* The patch file an earlier release wrote goes, with our backup: carplay + * on disk is then the file as shipped, which the plan needs. cb(err). */ +function dropDiskPatch(st, done) { + if (!st.ours && !st.restorable && !st.backup) { done(null); return; } + log('carplay: reverting the patch an earlier release wrote to ' + TARGET + '; the patch goes in memory'); + revert(true, true, function (pErr, roErr) { + /* The file's change waits for nothing: what carplay runs is told by + * its memory from here on. A revert that failed keeps its marker. */ + if (!pErr) unlinkQuiet(CP.pending); + if (roErr) log('WARNING: ' + roErr.message + ' — the next head-unit start mounts / read-only again'); + done(pErr || null); + }); +} + +/* Applies the patch in memory: the file on disk reverted if an earlier + * release patched it, the plan made and armed for every next start of this + * boot. Activation: where patchd may restart carplay (not at install), a + * SIGKILL and start; a carplay whose memory holds the plan's bytes already + * (an earlier release's patch running) needs nothing; otherwise the change + * waits for the next start (pending apply). done(err, roErr, activation, + * refused). */ +function inmemApply(panel, mode, noRestart, unproven, done) { + if (panel !== 'high' && panel !== 'mid') { done(new Error('panel must be high or mid')); return; } + var ran = false; + readState(function (st) { + /* A patch an earlier release wrote, with our backup: this car runs + * the build patched already (Patch button's --unproven included), and + * the plan is checked on the original first, so a plan the patcher + * refuses leaves that patch in place. */ + var disk = !!(st.ours || st.restorable || st.backup), bak = TARGET + '.woc-orig'; + if (disk && st.backup) unproven = true; + (disk && fs.existsSync(bak) ? function (cb) { inmem.checkPlan(bak, planArgs(panel, mode, unproven), tmo(60000), cb); } : function (cb) { cb(null, null); })(function (cErr, text) { + if (cErr) { done(cErr, null, null, cErr.refused); return; } + if (disk) { + /* The revert must give back exactly the original the plan is + * made from (no other tool's change in the file), and the + * patch keeps its proven state only where it runs the plan's + * very bytes and its record says it ran healthy here. A patch + * on trial with a failure counted would be turned off at once, + * and one that cannot be armed here would leave neither: it + * stays in the file. Without our backup (a proven build the + * revert rebuilds from its shipped bytes) it goes on trial. */ + var a = { onlyPlan: true, same: false }; + if (text) try { a = require('./carplay_patch.js').againstPlan(fs.readFileSync(TARGET), fs.readFileSync(bak), text); } catch (e) { a = { err: e.message }; } + if (a.err || !a.onlyPlan) { + var why = a.err ? 'the earlier patch cannot be checked (' + a.err + ')' : 'carplay holds another change besides our earlier patch'; + done(null, null, null, null, why); + return; + } + var drec = record.current(TARGET), can = inmem.canArm('carplay'); + if (!can.ok) { done(null, null, null, null, 'the patch in memory cannot be armed here (' + can.why + ')'); return; } + ran = a.same && st.coding === PROVEN_CODING && !!drec && drec.patched === true && drec.proven === true && drec.trial !== true; + if (!ran && countedFails() > 0) { + done(null, null, null, null, 'boot recovery counts a failed start; the earlier patch stays in the file until a healthy start clears it'); + return; + } + } + migrate(st); + }); + }); + function migrate(st) { + dropDiskPatch(st, function (dErr) { + if (dErr) { done(dErr, null, null); return; } + inmem.makePlan('carplay', planArgs(panel, mode, unproven), tmo(60000), function (pErr, rec) { + if (pErr) { done(pErr, null, null, pErr.refused); return; } + log('carplay: in-memory patch planned (' + rec.edits.join(', ') + '), ' + (rec.proven ? 'proven' : rec.trial ? 'on trial' : 'unproven')); + armNow(function (r) { + if (r.action !== 'armed' || r.armFailed) { done(new Error('boot recovery did not arm it (' + (r.armFailed || r.action) + ')'), null, null); return; } + activate('apply', noRestart, done); + }); + }, { ran: ran }); + }); + } +} + +/* Turns the patch off: the next start is stock (disarmed), and the record + * says by whom (removal: record and plan go). A patch an earlier release + * wrote to the file is reverted too. done(err, roErr, activation). */ +function inmemRevert(noRestart, removal, done) { + /* The plan as it was, for the memory check after it goes. */ + var planText = inmem.readRecord('carplay') ? readText(inmem.paths('carplay').plan) : null; + inmem.disarm('carplay'); + try { + if (removal) inmem.remove('carplay'); + else inmem.disable('carplay', { by: 'user' }); + } catch (e) { done(e, null, null); return; } + readState(function (st) { + /* A patch an earlier release wrote goes as it always did (its + * activation, a waiting revert included, is the file's). */ + (st.ours || st.restorable || (removal && st.backup) ? function (cb) { revert(noRestart, removal, cb); } + : function (cb) { cb(null, null, null); })(function (pErr, roErr, diskActivation) { + if (pErr) { done(pErr, roErr, null); return; } + if (!planText) { done(null, roErr, diskActivation || null); return; } + activate('revert', noRestart, function (e, r, a) { done(e, roErr || r, a || diskActivation || null); }, planText, diskActivation === 'deferred'); + }); + }); +} + +/* What carplay runs against what is wanted (action): nothing to do, a + * restart where allowed (restartBlocked), else pending until the next + * start. */ +function activate(action, noRestart, done, planText, keepPending) { + carplayMem(function (pid, mem) { + var want = action === 'apply' ? 'patched' : 'stock'; + if (mem === want || (action === 'revert' && !pid)) { + if (!keepPending) unlinkQuiet(CP.pending); + done(null, null, null); + return; + } + (noRestart ? function (cb) { cb('installing'); } : function (cb) { restartBlocked(CP, cb); })(function (blocked) { + if (blocked) { + log('carplay not restarted (' + blocked + '); ' + CP.reasons[action]); + writePending(CP, action); + done(null, null, 'deferred'); + return; + } + restartUnit(CP, function (rErr) { + if (rErr) { done(rErr, null, null); return; } + afterStart(action, function (pid2, mem2) { + log('carplay restarted (MainPID ' + pid2 + '); its memory reads ' + (mem2 || 'unreadable') + ' at the edit sites'); + done(mem2 === want ? null : new Error('carplay restarted but runs ' + (mem2 || 'unknown') + ' bytes at the edit sites; see ' + inmem.paths('carplay').result), null, 'restarted'); + }, 0, planText); + }); + }); + }, planText); +} + +/* carplay's memory once the started process is past the library's + * constructor: for an apply, until its result names the new main PID (at + * most RESTART_TRIES polls); a revert's start runs no library. */ +function afterStart(action, cb, tries, planText) { + carplayMem(function (pid, mem) { + var r = inmem.result('carplay'); + if (action === 'apply' && mem !== 'patched' && !(r && r.pid === pid) && (tries || 0) < RESTART_TRIES) { + setTimeout(function () { afterStart(action, cb, (tries || 0) + 1, planText); }, RESTART_POLL_MS); + return; + } + cb(pid, mem); + }, planText); +} + +/* The install hooks' step for carplay in memory: cb(code, {status, conflict}). */ +function inmemHook(which, cb) { + function out(code, status, conflict, reset) { + log(which + ': ' + status); + var r = { status: status }; + if (conflict) r.conflict = conflict; + if (reset) r.reset = true; + cb(code, r); + } + if (which === 'deactivate') { + inmemRevert(true, true, function (err, roErr, activation) { + if (roErr) log('WARNING: ' + roErr.message + ' — the next head-unit start mounts / read-only again'); + if (err) { out(1, 'CarPlay not undone (' + err.message + '): the tool stays to guard it'); return; } + readState(function (st) { + if (!cpUndone(st) || inmem.readRecord('carplay')) { out(1, 'CarPlay not undone (' + (!st.complete ? incomplete(st, 'carplay') : 'our edits read in carplay') + '): the tool stays to guard it'); return; } + out(0, activation === 'deferred' ? 'map patch removed' : 'carplay runs as it ships'); + }); + }); + return; + } + readState(function (st) { + var hu = headUnit.refused(), rec = inmem.readRecord('carplay'); + if (hu) { out(0, 'carplay left as it is: ' + notSupported(hu), notSupported(hu)); return; } + if (rec && rec.enabled === false && inmem.describes('carplay', rec) && (rec.by === 'recovery' || rec.by === 'user')) { + out(0, rec.by === 'recovery' ? 'boot recovery turned the patch off after ' + (rec.fails || 1) + ' failed head-unit start' + (rec.fails === 1 ? '' : 's') + '; its Patch button applies it' + : 'the patch was turned off; its Patch button applies it'); + return; + } + var reset = highfReset(CP, st), off = st.binary === 'original' && st.backup && !st.pending; + function settle() { if (highfInstall && (reset || !off)) highfMark(CP, reset ? 'applied' : 'left'); } + if (st.recovered) { out(0, 'boot recovery removed the patch after ' + st.recovered + ' failed head-unit start' + (st.recovered === 1 ? '' : 's') + '; its Patch button applies it'); return; } + if (off && !reset) { out(0, 'the patch was turned off; its Patch button applies it'); return; } + /* A disk state the patcher would not write over (not patchable, + * modified by something else, an untested build), the coding, or + * another program started as carplay. */ + var conflict = st.diskConflict || codingConflict(st.coding === null ? null : [null, String(st.coding)]) || foreignStart(CP); + if (conflict) { out(0, 'carplay left as it is: ' + conflict, conflict); return; } + inmemApply('high', 'avb', true, false, function (err, roErr, activation, refused, why) { + if (roErr) log('WARNING: ' + roErr.message + ' — the next head-unit start mounts / read-only again'); + if (why) { out(0, 'carplay left as it is: ' + why); return; } + if (refused) { + var c = /not a proven build/.test(refused) ? 'untested carplay build' : refused; + out(0, 'carplay left as it is: ' + c, c); + return; + } + if (err) { out(1, 'applying the map patch failed: ' + err.message); return; } + settle(); + out(0, activation === 'deferred' ? 'map patch armed in memory; takes effect at the next carplay start' : 'map patch armed in memory; carplay runs it already', null, reset); + }); + }); +} + var AA_FILES = ['--target', AAPD, '--conf', AAPD_CONF]; /* Writes or removes the crop override; true when it changed. */ @@ -1853,7 +2144,7 @@ function handle(line, sock) { var panel = msg.panel; var mode = (msg.mode === 'avb' || msg.mode === 'udp') ? msg.mode : 'fifo'; /* capture mode; default fifo */ operate('carplay', msg.cmd === 'apply' ? 'applying' : 'reverting', - msg.cmd === 'apply' ? function (cb) { apply(panel, mode, false, true, cb); } : function (cb) { revert(false, false, cb); }); + msg.cmd === 'apply' ? function (cb) { inmemApply(panel, mode, false, true, function (e, r, a, refused, why) { cb(e || (why ? new Error(why) : null), r, a); }); } : function (cb) { inmemRevert(false, false, cb); }); } else if (msg.cmd === 'aa-apply') { operate('aa', 'applying', aaEnable); } else if (msg.cmd === 'aa-revert') { @@ -2162,9 +2453,7 @@ function oneShot(which) { finish(1); return; } - (which === 'activate' ? trialUnstarted : function (cb) { cb(); })(function () { hookStep(which, CP, readState, function (op, cb) { - if (op === 'apply') apply('high', 'avb', true, false, cb); else revert(true, true, cb); - }, function (code, r) { + (which === 'activate' ? trialUnstarted : function (cb) { cb(); })(function () { inmemHook(which, function (code, r) { result.status = r.status; if (r.conflict) result.conflict = r.conflict; if (r.reset) result.reset = true; diff --git a/native/waze-on-cluster/patch/recovery.js b/native/waze-on-cluster/patch/recovery.js index 809211ed..88da5520 100644 --- a/native/waze-on-cluster/patch/recovery.js +++ b/native/waze-on-cluster/patch/recovery.js @@ -88,6 +88,7 @@ var lock = require('./remount_lock.js'); var headUnit = require('./head_unit.js'); var recmgr = require('./recmgr_list.js'); var fileMode = require('./file_mode.js'); +var inmem = require('./inmem.js'); /* ExecMainCode of a main process a signal ended without a core dump. */ var CLD_KILLED = '2'; @@ -121,6 +122,8 @@ function targets(o) { var t = { carplay: { name: 'carplay', unit: 'carplay.service', target: o.carplay, files: [o.carplay], floors: [fileMode.EXEC], + /* the patch applied in memory (inmem.js): armed per start, never written to the file */ + inmem: true, check: function (i, cur) { if (!exists(o.carplay + '.woc-orig')) return null; var cpp = require('./carplay_patch.js'), b = cpp.trustedBackup(o.carplay, cur || Buffer.alloc(0)); @@ -179,7 +182,7 @@ function stockBackup(file, hashes) { } var TARGETS = targets({ - state: process.env.WOC_RECOVERY_STATE || '/var/opt/waze-on-cluster/boot-recovery.json', + state: process.env.WOC_RECOVERY_STATE || path.join(process.env.WOC_STATE_DIR || '/var/opt/waze-on-cluster', 'boot-recovery.json'), sock: process.env.WOC_PATCH_SOCK || '/dev/shm/waze-on-cluster/patch.sock', carplay: process.env.WOC_CARPLAY || '/usr/bin/carplay', aapd: process.env.WOC_AAPD || '/usr/bin/aapd', @@ -290,11 +293,28 @@ function log(line) { process.stdout.write('[' + new Date().toISOString() + '] re * 'unproven' build, or 'unknown' (a backup of ours beside a target the * record does not describe). */ function patchKind(t) { + var k = inmemKind(t); + if (k) return k; if (!t.backups.some(exists)) return 'none'; var rec = record.current(t.target); return !rec ? 'unknown' : !rec.patched ? 'original' : rec.proven ? 'proven' : 'unproven'; } +/* The kind of t's in-memory patch ('proven' or 'unproven'), or null when + * none is enabled for the file as it is (inmem.js). */ +function inmemKind(t) { return t.inmem ? inmem.kind(t.name) : null; } + +/* Boot recovery's restore of an in-memory patch: the next start of this + * boot runs stock (the env file goes), then the record is turned off, so + * no later start is armed. No file of / is written. cb(err, outcome). */ +function disarmTarget(t, fails, why, refused, cb) { + if (!inmem.disarm(t.name)) { cb(new Error('could not remove ' + inmem.paths(t.name).env)); return; } + try { + inmem.disable(t.name, refused ? { by: 'refused' } : { by: 'recovery', fails: fails, why: why || 'boot' }); + } catch (e) { cb(new Error('the next start is stock; turning the patch off failed: ' + e.message)); return; } + cb(null, 'restored'); +} + /* Whether a file besides the binary (aapd.conf) still differs from its * verified backup: part of a patch a restore did not get to. */ function leftover(t) { @@ -368,7 +388,11 @@ function endOf(t, arm) { function tally(count, arm, end) { var crashes = arm.crashes || (end.state === 'failed' ? 1 : 0); if (crashes) return { fails: count.fails + crashes, unknown: 0, own: true, why: 'saw ' + crashes + ' crash' + (crashes === 1 ? '' : 'es') + ' of the service' }; - if (arm.confirmed) return { fails: 0, unknown: 0, why: 'ran healthy' }; + /* A start armed in memory counts a restart for a crash even after a + * healthy run: nothing on disk tells a later crash of the patched + * process apart, and a reset that beat the shutdown mark leaves only + * that record. */ + if (arm.confirmed && !(arm.inmem && end.crash)) return { fails: 0, unknown: 0, why: 'ran healthy' }; if (end.neverRan) return { fails: count.fails, unknown: count.unknown, why: 'ended before the service ran' }; if (end.explained) return { fails: count.fails, unknown: 0, why: 'ended for the other service\'s crash' }; if (end.crash) return { fails: count.fails + 1, unknown: 0, why: 'ended in a restart for a crash' }; @@ -575,6 +599,20 @@ function proveRecord(t, runsTarget, cb) { }); } +/* proveRecord for a patch in memory: its record (on /var/opt) says proven, + * under the remount lock so patchd does not write it meanwhile; / is not + * remounted. */ +function proveInmem(t, runsTarget, cb) { + if (!lock.tryAcquire()) { cb(new Error('remount lock held; deferring')); return; } + var wrote = false, err = null; + try { + var rec = inmem.current(t.name); + if (rec && rec.trial === true && runsTarget()) { inmem.update(t.name, { proven: true, trial: false, provenAt: new Date().toISOString() }); wrote = true; } + } catch (e) { err = new Error('writing: ' + e.message); } + lock.release(); + cb(err, wrote); +} + /* ---- the service's run ---- */ /* t.unit's current run: its id (InvocationID, else the main process's start @@ -620,14 +658,18 @@ function startTarget(t, cb) { /* ---- the counter ---- */ -function newArm(id, patch) { return { boot: id, at: Date.now(), patch: patch, crashes: 0, ran: false, confirmed: false, clean: false }; } +function newArm(id, patch, inMem) { + var a = { boot: id, at: Date.now(), patch: patch, crashes: 0, ran: false, confirmed: false, clean: false }; + if (inMem) a.inmem = true; + return a; +} /* waze-on-cluster 0.7.5 and earlier wrote the arm as {boot, state: * unconfirmed|confirmed|clean}; a unit updated mid-boot still holds one. */ function normArm(a) { if (!a || typeof a !== 'object') return null; return { boot: a.boot, at: a.at || 0, patch: a.patch || 'unknown', crashes: a.crashes || 0, ran: !!a.ran, confirmed: !!(a.confirmed || a.state === 'confirmed'), - clean: !!(a.clean || a.state === 'clean'), own: !!a.own }; + clean: !!(a.clean || a.state === 'clean'), own: !!a.own, inmem: !!a.inmem }; } function Recovery(opts) { @@ -638,10 +680,17 @@ function Recovery(opts) { this.bootId = opts.bootId || boot.bootId(); this._restore = opts.restore || function (fails, cb, why) { restoreTarget(t, false, fails, cb, 0, why); }; this._repairModes = opts.repairModes || function (cb) { repairModes(t, 0, cb); }; + this._disarm = opts.disarm || function (fails, cb, why, refused) { disarmTarget(t, fails, why, refused, cb); }; + this._arm = opts.arm || function (name) { return inmem.arm(name); }; /* Whether a process runs the target's own file: the run is of the file * the record describes, not of one a change replaced. */ - var runsTarget = this._runsTarget = opts.runsTarget || function () { return lock.inUse(t.target); }; - this._prove = opts.prove || function (cb) { proveRecord(t, runsTarget, cb); }; + var self = this; + var runsTarget = this._runsTarget = opts.runsTarget || function () { + if (!inmemKind(t)) return lock.inUse(t.target); + var r = inmem.result(t.name); + return !!r && r.applied === true && r.pid === self._pid && inmem.memState(t.name, self._pid) === 'patched'; + }; + this._prove = opts.prove || function (cb) { (inmemKind(t) ? proveInmem : proveRecord)(t, runsTarget, cb); }; this._probe = opts.probe || function (cb) { probeTarget(t, cb); }; this._systemState = opts.systemState || realSystemState; this._start = opts.start || function (cb) { startTarget(t, cb); }; @@ -688,7 +737,9 @@ Recovery.prototype._load = function () { * moment after, so it is on disk, renamed into place, before this returns. A * write that fails leaves the previous state whole. false when it failed. */ Recovery.prototype._save = function (st) { - var dir = path.dirname(this.statePath), tmp = this.statePath + '.tmp', fd; + /* The boot step, the watcher and patchd each write it: a temporary + * file of each process's own, so no write lands in another's. */ + var dir = path.dirname(this.statePath), tmp = this.statePath + '.tmp.' + process.pid, fd; try { try { fs.mkdirSync(dir, 0o755); } catch (e) { if (e.code !== 'EEXIST') throw e; } fd = fs.openSync(tmp, 'w', 0o644); @@ -760,20 +811,29 @@ Recovery.prototype._decide = function (cb) { this._log(t.name + ': failed patched boots and crashes ' + st.fails + ' (was ' + was + '): the last patched boot ' + r.why + (st.unknown ? '; 1 boot with no record' : '')); } - var kind = patchKind(t); + var kind = patchKind(t), inMem = !!inmemKind(t); + if (!inMem && t.inmem) inmem.disarm(t.name); if (kind === 'none' || kind === 'original') { if (tallied || st.fails || st.unknown || st.arm) { st.fails = 0; st.unknown = 0; st.arm = null; this._save(st); } cb({ action: 'idle' }); return; } - if (!st.arm) st.arm = newArm(this.bootId, kind); + if (!st.arm) st.arm = newArm(this.bootId, kind, inMem); + else if (inMem && !st.arm.inmem) st.arm.inmem = true; var saved = this._save(st); /* A service with a crash threshold of its own (aapd) is restored at it * when the last patched boot counted saw the service itself crash (also * when the watcher retries a restore the boot step did not finish). */ var own = !!st.prev && !!st.prev.own && st.fails > 0; var limit = own && t.crashThreshold ? Math.min(THRESHOLD[kind], t.crashThreshold) : THRESHOLD[kind]; - if (saved && st.fails < limit) { cb({ action: 'armed', patch: kind, fails: st.fails }); return; } + if (saved && st.fails < limit) { + /* In memory: the start is armed only now, once its record is saved. */ + var a = inMem ? this._arm(t.name) : null; + if (a && !a.armed) this._log(t.name + ': not armed (' + a.why + '); it starts stock'); + else if (a && !a.already) this._log(t.name + ': armed: the next start applies the patch in memory'); + cb({ action: 'armed', patch: kind, fails: st.fails, inmem: inMem || undefined, armFailed: a && !a.armed ? a.why : undefined }); + return; + } /* why: 'crash' for a service its own crash restores (aapd), else * 'boot' (failed head-unit starts). */ this._restoreWith(st.fails, saved, cb, undefined, own && t.crashThreshold ? 'crash' : 'boot'); @@ -788,7 +848,8 @@ Recovery.prototype._restoreWith = function (fails, saved, cb, refused, why) { : saved ? 'restoring the original ' + n + ' after ' + fails + ' failed patched boots or crashes' : 'restoring the original ' + n + ': the boot-recovery state cannot be saved'); this.restoring = true; - this._restore(fails, function (err, outcome) { + var inMem = !!inmemKind(this.target), restore = inMem ? this._disarm : this._restore; + restore(fails, function (err, outcome) { self.restoring = false; var r; if (err) { @@ -796,7 +857,9 @@ Recovery.prototype._restoreWith = function (fails, saved, cb, refused, why) { self._log('boot recovery restore failed: ' + err.message + '; ' + n + ' starts as it is'); r = { action: 'restore-failed', fails: fails, error: err.message }; } else { - self._log(outcome === 'restored' ? 'restored the original ' + n + ' in ' + Math.round(self._now() - t0) + ' ms; its patch is off until its Patch button applies it' + + self._log(inMem && outcome === 'restored' + ? 'turned the in-memory patch of ' + n + ' off: its next start runs it as it ships; its Patch button applies it again' + : outcome === 'restored' ? 'restored the original ' + n + ' in ' + Math.round(self._now() - t0) + ' ms; its patch is off until its Patch button applies it' + (self.target.crashThreshold ? ' or an update brings a newer patch' : '') : outcome === 'other' ? n + ' is another build than our backup (a firmware update): not ours to restore' : n + ' is the original already'); @@ -805,7 +868,7 @@ Recovery.prototype._restoreWith = function (fails, saved, cb, refused, why) { } cb(r); self._restored.splice(0).forEach(function (f) { f(); }); - }, why); + }, why, refused); }; Recovery.prototype._clear = function () { @@ -928,7 +991,7 @@ Recovery.prototype._healthy = function (now) { * clean, or the run is of another file than the target's (a change waits * for the next start). */ Recovery.prototype._trial = function (now, st) { - var self = this, t = this.target, rec = record.current(t.target); + var self = this, t = this.target, im = inmemKind(t) ? inmem.current(t.name) : null, rec = im ? { patched: true, trial: im.trial } : record.current(t.target); if (!rec || !rec.patched || !rec.trial) return false; if (!this._armed(st) || st.fails || st.arm.crashes || this._crashes) { this._log(t.name + ' ran its patch healthy, but this boot is not clean (' + (!this._armed(st) ? 'not armed' : 'failed starts and crashes ' + diff --git a/native/waze-on-cluster/patch/test/carplay_proc.js b/native/waze-on-cluster/patch/test/carplay_proc.js new file mode 100644 index 00000000..340d8291 --- /dev/null +++ b/native/waze-on-cluster/patch/test/carplay_proc.js @@ -0,0 +1,61 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Copyright (C) 2026 Robert Nisipeanu +'use strict'; +/* carplay's process in a fake /proc (WOC_PROC), for the host tests of the + * patch in memory: //exe is a hard link to the file it runs (its + * inode), maps maps that file at BASE from offset 0, and mem holds each + * loaded segment of the file at BASE plus its address, as inmem.js's memory + * check reads it. A start the boot step armed (/carplay.env, with the + * plan at /carplay.plan) holds the plan's bytes at its sites, as + * libwocpatch.so writes them, and its result (/carplay.result, when the + * boot step made that file) names the pid. carplay is one process: a start + * ends any other in the fake /proc. + */ +var fs = require('fs'); +var path = require('path'); +var cp = require('child_process'); + +var BASE = 0x1000; + +/* Ends every process of the fake /proc. */ +function stop(proc) { + var pids = []; + try { pids = fs.readdirSync(proc).filter(function (n) { return /^\d+$/.test(n); }); } catch (e) {} + pids.forEach(function (p) { cp.execFileSync('rm', ['-rf', path.join(proc, p)]); }); +} + +/* The bytes at the process's addresses: buf's loaded segments at their + * addresses (the whole file at 0 where buf is no ELF). */ +function writeMem(memFile, buf) { + var elf = require('../carplay_locate.js').elf.parseElf(buf), fd = fs.openSync(memFile, 'w'); + try { + if (!elf.load || !elf.load.length) fs.writeSync(fd, buf, 0, buf.length, BASE); + else elf.load.forEach(function (s) { fs.writeSync(fd, buf, s.off, s.size, BASE + s.va); }); + } finally { fs.closeSync(fd); } +} + +/* carplay started as process pid from file; runDir: the boot step's folder + * (WOC_PRELOAD_DIR). 'patched' when the start was armed and the library + * applied the plan, 'refused' when it was armed and the library refused it, + * else 'stock'. */ +function start(proc, pid, file, runDir) { + stop(proc); + var pd = path.join(proc, String(pid)), buf = fs.readFileSync(file), how = 'stock'; + fs.mkdirSync(pd); + fs.linkSync(file, path.join(pd, 'exe')); + fs.writeFileSync(path.join(pd, 'maps'), '00000800-00000900 r--p 00000000 00:01 1 /lib/ld-linux-x86-64.so.2\n' + + BASE.toString(16).padStart(8, '0') + '-00400000 r-xp 00000000 fd:00 ' + fs.statSync(file).ino + ' /usr/bin/carplay\n'); + var env = runDir ? path.join(runDir, 'carplay.env') : null, plan = runDir ? path.join(runDir, 'carplay.plan') : null; + if (env && fs.existsSync(env) && fs.existsSync(plan)) { + var o = require('../carplay_patch.js').overlay(buf, fs.readFileSync(plan, 'utf8')), result = path.join(runDir, 'carplay.result'); + if (o.err) how = 'refused'; + else { buf = o.buf; how = 'patched'; } + if (fs.existsSync(result)) { + fs.writeFileSync(result, JSON.stringify(o.err ? { v: 1, pid: pid, applied: false, why: o.err } : { v: 1, pid: pid, applied: true, edits: o.edits }) + '\n'); + } + } + writeMem(path.join(pd, 'mem'), buf); + return how; +} + +module.exports = { start: start, stop: stop, BASE: BASE }; diff --git a/native/waze-on-cluster/patch/test/inmem_test.js b/native/waze-on-cluster/patch/test/inmem_test.js new file mode 100644 index 00000000..4d9bd462 --- /dev/null +++ b/native/waze-on-cluster/patch/test/inmem_test.js @@ -0,0 +1,236 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Copyright (C) 2026 Robert Nisipeanu +'use strict'; +/* The carplay patch in memory (inmem.js, PATCH.md "In memory"): the plan + * and its overlay, the record, arming and disarming, the memory check, and + * boot recovery counting armed starts and turning the patch off at the + * threshold. The plan tests take carplay 22.28.3 (CARPLAY_BIN) and are + * skipped without it. */ +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const cp = require('child_process'); +const assert = require('assert'); + +const hu = require('./head_unit_env.js'); +const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'woc-inmem-')); +const T = path.join(dir, 'usr-bin-carplay'); +Object.assign(process.env, { + WOC_STATE_DIR: path.join(dir, 'var'), WOC_PRELOAD_DIR: path.join(dir, 'run'), WOC_CARPLAY: T, + WOC_PRELOAD_LIB: path.join(dir, 'lib', 'libwocpatch.so'), WOC_PROC: path.join(dir, 'proc'), WOC_PASSWD: path.join(dir, 'passwd'), + WOC_RECOVERY_STATE: path.join(dir, 'var', 'boot-recovery.json'), WOC_PATCH_SOCK: path.join(dir, 'shm', 'patch.sock'), + WOC_REMOUNT_LOCK: path.join(dir, 'shm', 'remount.lock'), +}); +['var', 'lib', 'proc', 'shm'].forEach((d) => fs.mkdirSync(path.join(dir, d))); +fs.writeFileSync(process.env.WOC_PRELOAD_LIB, 'lib'); +fs.writeFileSync(process.env.WOC_PASSWD, 'root:x:0:0::/:/bin/sh\ncia_13002:x:13002:13002::/:/bin/false\n'); +const inmem = require('../inmem.js'); +const recovery = require('../recovery.js'); + +const CARPLAY_BIN = process.env.CARPLAY_BIN || ''; +const tests = []; +function test(name, fn, needsBin) { tests.push({ name, fn, needsBin }); } +const P = inmem.paths('carplay'); + +function plan(args) { + return new Promise((res, rej) => inmem.makePlan('carplay', ['--panel', 'high', '--coding', hu.CODING].concat(args || []), 60000, (e, r) => e ? rej(e) : res(r))); +} + +test('a plan of the stock build: the record on trial, the overlay reads patched, the file untouched', async () => { + fs.copyFileSync(CARPLAY_BIN, T); + const before = fs.readFileSync(T), st = fs.statSync(T); + const rec = await plan(); + assert(fs.readFileSync(T).equals(before) && fs.statSync(T).mtime.getTime() === st.mtime.getTime(), 'carplay not written'); + assert.strictEqual(rec.enabled, true); + assert.strictEqual(rec.trial, true, 'a first patch is on trial'); + assert.strictEqual(inmem.kind('carplay'), 'unproven'); + assert.deepStrictEqual(rec.edits, ['variant', 'selfstart', 'res-mm', 'res-px', 'res-safe1', 'res-safe2', 'mapurl-1', 'mapurl-2', 'showui-1', 'showui-2']); + const text = fs.readFileSync(P.plan, 'utf8'); + assert(/^wocplan 1\nbuild-id 5de62156575d737391ea42254e778a97dbbb51f8\n/.test(text) && /\nend 11\n$/.test(text)); + assert(text.indexOf('edit variant 2ba4f0 ecf2f7ff bcf2f7ff\n') > 0, 'Edit 1 at its PATCH.md site'); + const o = cp.execFileSync(process.execPath, [path.join(__dirname, '..', 'carplay_patch.js'), 'overlay', '--target', T, '--plan', P.plan], { encoding: 'utf8' }); + assert(/^variant:\s+PATCHED -> IC_HIGH/m.test(o) && /^selfstart:\s+SELF-START/m.test(o) && /^showui:\s+PATCHED/m.test(o) && /^overlay:\s+ok$/m.test(o), o); +}, true); + +test('the plan of a patched file is refused; a changed file or plan is no longer described', async () => { + const rec = inmem.readRecord('carplay'); + const buf = fs.readFileSync(T); + buf[0x2ba4f0] = 0xbc; + fs.writeFileSync(T + '.patched', buf); + const r = cp.spawnSync(process.execPath, [path.join(__dirname, '..', 'carplay_patch.js'), 'plan', '--target', T + '.patched', '--panel', 'high', '--coding', hu.CODING, '--out', path.join(dir, 'x.plan')], { encoding: 'utf8' }); + assert.notStrictEqual(r.status, 0); + assert(/pristine build/.test(r.stderr), r.stderr); + const t = new Date(Date.now() - 5000); + fs.utimesSync(T, t, t); + assert.strictEqual(inmem.current('carplay'), null, 'another mtime: not described'); + fs.copyFileSync(CARPLAY_BIN, T); + await plan(); + fs.appendFileSync(P.plan, '#'); + assert.strictEqual(inmem.current('carplay'), null, 'another plan: not described'); + await plan(); + assert(inmem.current('carplay') && rec); +}, true); + +test('a build outside the proven list is refused without --unproven, and unproven (not on trial) with it', async () => { + const buf = fs.readFileSync(CARPLAY_BIN); + const id = buf.indexOf(Buffer.from('5de62156575d737391ea42254e778a97dbbb51f8', 'hex')); + buf[id] ^= 1; + fs.writeFileSync(T, buf); + await assert.rejects(plan(), (e) => /not a proven build/.test(e.refused || '')); + const rec = await plan(['--unproven']); + assert.strictEqual(rec.trial, false); + assert.strictEqual(rec.proven, false); + fs.copyFileSync(CARPLAY_BIN, T); + await plan(); +}, true); + +test('proven carries over only for the same plan, on or turned off by the user, never after boot recovery', async () => { + inmem.update('carplay', { proven: true, trial: false }); + let rec = await plan(); + assert.strictEqual(rec.proven, true, 'the same plan, on'); + inmem.disable('carplay', { by: 'user' }); + rec = await plan(); + assert.strictEqual(rec.proven, true, 'after Remove patch'); + inmem.disable('carplay', { by: 'recovery', fails: 2 }); + rec = await plan(); + assert.strictEqual(rec.proven, false); + assert.strictEqual(rec.trial, true, 'after boot recovery: on trial again'); + inmem.update('carplay', { proven: true, trial: false }); + rec = await plan(['--res', '1280x564']); + assert.strictEqual(rec.trial, true, 'another plan: on trial'); + await plan(); +}, true); + +test('arm: the plan, the result file and the env (the unit\'s preload first); again changes nothing; disarm', async () => { + const a = inmem.arm('carplay', { preload: '/usr/lib/libschedconfig.so.1', user: 'cia_13002' }); + assert.deepStrictEqual(a, { armed: true }); + const env = fs.readFileSync(P.env, 'utf8'); + assert.strictEqual(env, 'LD_PRELOAD=/usr/lib/libschedconfig.so.1 ' + process.env.WOC_PRELOAD_LIB + '\nWOC_PATCH_PLAN=' + P.runPlan + '\nWOC_PATCH_RESULT=' + P.result + '\n'); + assert(fs.readFileSync(P.runPlan).equals(fs.readFileSync(P.plan))); + assert.strictEqual(fs.readFileSync(P.result, 'utf8'), ''); + fs.writeFileSync(P.result, '{"v":1,"pid":7,"applied":true}\n'); + assert.strictEqual(inmem.arm('carplay', { preload: '/usr/lib/libschedconfig.so.1', user: 'cia_13002' }).already, true); + assert.strictEqual(inmem.result('carplay').pid, 7, 'a run\'s result is kept'); + assert(inmem.disarm('carplay') && !fs.existsSync(P.env) && !fs.existsSync(P.runPlan)); + assert.strictEqual(inmem.armed('carplay'), false); +}, true); + +test('arm refuses, and leaves nothing armed: no enabled record, no library, no user', async () => { + fs.renameSync(process.env.WOC_PRELOAD_LIB, process.env.WOC_PRELOAD_LIB + '.x'); + let a = inmem.arm('carplay', { preload: '', user: 'cia_13002' }); + assert(!a.armed && /missing/.test(a.why) && !fs.existsSync(P.env)); + fs.renameSync(process.env.WOC_PRELOAD_LIB + '.x', process.env.WOC_PRELOAD_LIB); + a = inmem.arm('carplay', { preload: '', user: 'nobody' }); + assert(!a.armed && !fs.existsSync(P.env)); + inmem.disable('carplay', { by: 'user' }); + a = inmem.arm('carplay', { preload: '', user: 'cia_13002' }); + assert(!a.armed && !fs.existsSync(P.env)); + await plan(); +}, true); + +test('the memory check reads the plan\'s sites at the base of the target\'s mapping', () => { + const pid = '4242', pd = path.join(dir, 'proc', pid); + fs.mkdirSync(pd, { recursive: true }); + const ino = fs.statSync(T).ino, base = 0x1000; + fs.writeFileSync(path.join(pd, 'maps'), '00000800-00000900 r--p 00000000 00:01 1 /lib/other.so\n' + + base.toString(16).padStart(8, '0') + '-00400000 r-xp 00000000 fd:00 ' + ino + ' /usr/bin/carplay\n'); + const mem = path.join(pd, 'mem'), edits = require('../carplay_patch.js').parsePlan(fs.readFileSync(P.plan, 'utf8')).edits; + const fd = fs.openSync(mem, 'w'); + edits.forEach((e) => fs.writeSync(fd, e.stock, 0, e.stock.length, base + e.va)); + fs.closeSync(fd); + assert.strictEqual(inmem.memState('carplay', 4242), 'stock'); + const fd2 = fs.openSync(mem, 'r+'); + edits.forEach((e) => fs.writeSync(fd2, e.patched, 0, e.patched.length, base + e.va)); + assert.strictEqual(inmem.memState('carplay', 4242), 'patched'); + fs.writeSync(fd2, edits[0].stock, 0, edits[0].stock.length, base + edits[0].va); + fs.closeSync(fd2); + assert.strictEqual(inmem.memState('carplay', 4242), 'mixed'); + assert.strictEqual(inmem.memState('carplay', 4243), null, 'no such process'); +}, true); + +function rec(bootId, extra) { + const logs = []; + const r = new recovery.Recovery(Object.assign({ target: recovery.TARGETS.carplay, bootId: bootId, log: (l) => logs.push(l), + arm: () => inmem.arm('carplay', { preload: '', user: 'cia_13002' }), repairModes: (cb) => cb(null, 0) }, extra || {})); + r.logs = logs; + return r; +} +function decide(r) { return new Promise((res) => r._decide(res)); } +function state() { return JSON.parse(fs.readFileSync(process.env.WOC_RECOVERY_STATE, 'utf8')); } + +test('boot recovery arms an enabled patch, counts a crash of an armed start and turns a patch on trial off at 1, writing nothing to the file', async () => { + try { fs.unlinkSync(process.env.WOC_RECOVERY_STATE); } catch (e) {} + const before = fs.statSync(T); + let r = await decide(rec('boot-1')); + assert.strictEqual(r.action, 'armed'); + assert.strictEqual(r.inmem, true); + assert(inmem.armed('carplay'), 'the next start is armed'); + assert.strictEqual(state().arm.inmem, true); + /* the armed start crashed: the watcher's count */ + const st = state(); + st.arm.crashes = 1; + fs.writeFileSync(process.env.WOC_RECOVERY_STATE, JSON.stringify(st)); + inmem.disarm('carplay'); /* /run is empty at the next boot */ + r = await decide(rec('boot-2')); + assert.strictEqual(r.action, 'restored'); + assert(!fs.existsSync(P.env), 'not armed'); + const rc = inmem.readRecord('carplay'); + assert.strictEqual(rc.enabled, false); + assert.strictEqual(rc.by, 'recovery'); + assert.strictEqual(fs.statSync(T).mtime.getTime(), before.mtime.getTime(), 'carplay untouched'); + r = await decide(rec('boot-3')); + assert.strictEqual(r.action, 'idle'); + assert(!fs.existsSync(P.env), 'the next boot runs stock too'); + await plan(); +}, true); + +test('a proven patch is turned off at 2; a healthy start between clears the count', async () => { + try { fs.unlinkSync(process.env.WOC_RECOVERY_STATE); } catch (e) {} + inmem.update('carplay', { proven: true, trial: false }); + assert.strictEqual(inmem.kind('carplay'), 'proven'); + let r = await decide(rec('p-1')); + assert.strictEqual(r.action, 'armed'); + function crashed() { const st = state(); st.arm.crashes = 1; fs.writeFileSync(process.env.WOC_RECOVERY_STATE, JSON.stringify(st)); } + crashed(); + r = await decide(rec('p-2')); + assert.strictEqual(r.action, 'armed', 'one crash of a proven patch'); + assert.strictEqual(r.fails, 1); + const st = state(); st.arm.confirmed = true; st.arm.ran = true; fs.writeFileSync(process.env.WOC_RECOVERY_STATE, JSON.stringify(st)); + r = await decide(rec('p-3')); + assert.strictEqual(r.fails, 0, 'a healthy start clears it'); + crashed(); + r = await decide(rec('p-4')); + crashed(); + r = await decide(rec('p-5')); + assert.strictEqual(r.action, 'restored'); + assert.strictEqual(inmem.readRecord('carplay').fails, 2); + await plan(); +}, true); + +test('in memory, a restart for a crash counts even after a healthy run (a reset that beat the shutdown mark)', () => { + const c = { fails: 0, unknown: 0 }; + assert.strictEqual(recovery.tally(c, { confirmed: true, inmem: true }, { crash: true }).fails, 1); + assert.strictEqual(recovery.tally(c, { confirmed: true, inmem: true }, { crash: false }).fails, 0); + assert.strictEqual(recovery.tally(c, { confirmed: true }, { crash: true }).fails, 0, 'the file patch keeps its rule'); +}); + +test('a plan is never armed for another file: a firmware update that replaced carplay', async () => { + fs.unlinkSync(T); + fs.copyFileSync(CARPLAY_BIN, T); + assert.strictEqual(inmem.kind('carplay'), null); + const r = await decide(rec('fw-1')); + assert.strictEqual(r.action, 'idle'); + assert(!fs.existsSync(P.env)); +}, true); + +(async () => { + let failed = 0, n = 0; + for (const t of tests) { + if (t.needsBin && !CARPLAY_BIN) { console.log('ok ' + t.name + '\n (skipped: CARPLAY_BIN not set)'); continue; } + n++; + try { await t.fn(); console.log('ok ' + t.name); } catch (e) { failed++; console.log('FAIL ' + t.name + '\n ' + (e.stack || e).toString().split('\n').slice(0, 4).join('\n ')); } + } + cp.execFileSync('rm', ['-rf', dir]); + console.log((n - failed) + '/' + n + ' passed'); + process.exit(failed ? 1 : 0); +})(); diff --git a/native/waze-on-cluster/patch/test/patchd_activate_test.js b/native/waze-on-cluster/patch/test/patchd_activate_test.js index 98ace470..08dc6ca7 100644 --- a/native/waze-on-cluster/patch/test/patchd_activate_test.js +++ b/native/waze-on-cluster/patch/test/patchd_activate_test.js @@ -2,39 +2,46 @@ // SPDX-License-Identifier: GPL-3.0-or-later // Copyright (C) 2026 Robert Nisipeanu /* Proves the install-time activation (`patchd.js activate` / `deactivate`, the - * deploy tool's hooks) against the unit's carplay binary (CARPLAY_BIN): a fresh - * install writes CarPlay's Patch button's patch and leaves it pending for the next - * head-unit start; carplay is never stopped, killed or restarted, even where - * recmgr would allow it; the running binary stays linked and / goes read-only - * again; a second run changes nothing; after that start the patch is left as - * it is, a user's revert is kept, an older patch of ours is brought up to - * date (also the patches 0.9.11-0.10.3 wrote, without the ShowUI URL edit - * and 0.10.2's with the URL with ETA, which patchd reports and removal - * reverts), a stock build outside the proven list is left as a conflict until - * CarPlay's Patch button patched it, then patched like the proven one. Removal (deactivate) reverts and drops our backup: before the pending - * start it moves carplay's running file back and leaves nothing pending; - * while carplay runs the patch it keeps that file linked and hands it to the - * deploy tool (removeWhenUnused); with carplay not running it keeps nothing; - * changes another tool made elsewhere in the binary stay; an install after a - * removal patches again. patchd removes the link once nothing runs it and - * keeps one carplay runs (boot recovery's). A binary with an edit site not - * found, one modified by something else and a carplay.service that starts - * another program are left untouched (a conflict, exit 0); a remount failure before - * any write exits non-zero. On a head unit that refuses our parts the - * install writes nothing, patchd refuses CarPlay's Patch button and the - * removal reverts; MID and HIGH F patch as HIGH. The first install on HIGH F - * applies the patch again to an original 0.8.2's boot recovery restored. The pending marker is the world-readable JSON - * patchd and the app read. Runs the real patchd.js and carplay_patch.js on a - * temporary copy, with a fake /proc (carplay's process holds the inode it - * runs), a fake mount that, like the kernel, refuses read-only while a file a - * process runs is unlinked, and a recording systemctl, kill and reboot. - * Without CARPLAY_BIN it skips. + * deploy tool's hooks) against the unit's carplay binary (CARPLAY_BIN), with + * CarPlay's patch in memory (PATCH.md "In memory"). A fresh install leaves + * carplay on disk as it ships, keeps the plan and its record (enabled, on + * trial) and arms carplay's next start; the running carplay's memory is not + * patched, so the change is pending for the next head-unit start. carplay is + * never stopped, killed or restarted, even where recmgr would allow it. A + * second run changes nothing; after that start the patch is left as it is + * and a user's Remove patch is kept. An earlier release's patch on disk with + * our backup is reverted from the backup, which goes, in the step that arms + * the plan: nothing is pending when the running carplay's memory holds the + * plan's bytes (that patch, current), else the apply is (an older patch, the + * patches 0.9.11-0.10.3 wrote, 0.10.6's safe area), and its proven record + * does not prove the plan. A stock build outside the proven list is left as + * a conflict. Removal (deactivate) disarms the next start, deletes the plan + * and its record, reverts an earlier release's patch left on disk and drops + * our backup: a revert is pending only while the running carplay's memory + * holds the patch; changes another tool made elsewhere in the binary stay; + * an install after a removal plans again. patchd removes a link of carplay's + * running file once nothing runs it and keeps one carplay runs (boot + * recovery's). A binary with an edit site not found, one modified by + * something else and a carplay.service that starts another program are left + * untouched (a conflict, exit 0); a remount failure before any write exits + * non-zero. On a head unit that refuses our parts the install plans nothing, + * patchd refuses CarPlay's Patch button and the removal turns the patch + * off; MID and HIGH F plan as HIGH. The first install on HIGH F applies the + * patch again to an original 0.8.2's boot recovery restored. The cluster + * coding: an install plans only on a car coded KI_KOMBI_VARIANT 7. The + * pending marker is the world-readable JSON patchd and the app read. Runs + * the real patchd.js and carplay_patch.js on a temporary copy, with a fake + * /proc (carplay's process: its exe, maps and mem, carplay_proc.js), a fake + * mount that, like the kernel, refuses read-only while a file a process runs + * is unlinked, a systemctl that answers what patchd reads and records every + * call, and a recording kill and reboot. Without CARPLAY_BIN it skips. * * node patchd_activate_test.js */ 'use strict'; var headUnit = require('./head_unit_env.js'); /* a HIGH head unit, coded KI_KOMBI_VARIANT 7, for every patcher and patchd this runs */ +var carplayProc = require('./carplay_proc.js'); var fs = require('fs'); var os = require('os'); @@ -44,6 +51,7 @@ var cp = require('child_process'); var crypto = require('crypto'); var PATCHD = path.join(__dirname, '..', 'patchd.js'); +var PATCHER = path.join(__dirname, '..', 'carplay_patch.js'); var SRC = process.env.CARPLAY_BIN || ''; var SLOT = 0x2ba4f0, SINK = 0x2a20b0; @@ -70,11 +78,16 @@ var SOCKDIR = path.join(dir, 'shm'); var PENDING = path.join(SOCKDIR, 'activation-pending'); var CALLS = path.join(dir, 'systemctl.calls'); var MOUNTS = path.join(dir, 'mounts'); +var MOUNT_CALLS = path.join(dir, 'mount.calls'); var RW_FAILS = path.join(dir, 'rw-fails'); var RECMGR = path.join(dir, 'recmgr-restartlist.conf'); var PROC_STAT = path.join(dir, 'stat'); var PROC = path.join(dir, 'proc'); var UNITS = path.join(dir, 'etc-systemd'); +var STATE = path.join(dir, 'var'); +var RUN = path.join(dir, 'run'); /* WOC_PRELOAD_DIR: this boot's arming of carplay */ +var LIB = path.join(dir, 'libwocpatch.so'); +var PASSWD = path.join(dir, 'passwd'); var BOOT_S = Math.floor(Date.now() / 1000) - 60; fs.writeFileSync(PROC_STAT, 'cpu 1 2 3\nbtime ' + BOOT_S + '\n'); /* carplay in both restart lists as loaded at boot: patchd itself would @@ -82,23 +95,47 @@ fs.writeFileSync(PROC_STAT, 'cpu 1 2 3\nbtime ' + BOOT_S + '\n'); fs.writeFileSync(RECMGR, '[Whitelist]\ncarplay\n[WhitelistExitSuccess]\ncarplay\n'); fs.utimesSync(RECMGR, BOOT_S - 3600, BOOT_S - 3600); fs.writeFileSync(CALLS, ''); +fs.writeFileSync(MOUNT_CALLS, ''); fs.writeFileSync(MOUNTS, '/dev/root / ext4 ro 0 0\n'); +fs.writeFileSync(LIB, 'a stand-in for libwocpatch.so\n'); +fs.writeFileSync(PASSWD, 'root:x:0:0::/:/bin/sh\ncia_13002:x:13002:13002::/:/bin/false\n'); fs.mkdirSync(UNITS); fs.mkdirSync(PROC); +fs.mkdirSync(STATE); + +/* inmem.js in this process reads the same record, plan and arming. */ +Object.assign(process.env, { WOC_STATE_DIR: STATE, WOC_PRELOAD_DIR: RUN, WOC_PRELOAD_LIB: LIB, WOC_PASSWD: PASSWD, WOC_CARPLAY: TGT, WOC_PROC: PROC }); +var inmem = require('../inmem.js'); +var IP = inmem.paths('carplay'); var BIN = path.join(dir, 'bin'); fs.mkdirSync(BIN); -/* Every systemctl, kill or reboot is recorded; the test asserts none. */ -['systemctl', 'kill', 'reboot'].forEach(function (n) { +/* Every systemctl, kill or reboot is recorded. systemctl answers what + * patchd reads: carplay's main PID (4242 while it runs), the unit's + * environment (BMW's preload) and user, and no drop-in loaded. */ +fs.writeFileSync(path.join(BIN, 'systemctl'), '#!' + process.execPath + '\n' + [ + "var fs = require('fs'), path = require('path'), a = process.argv.slice(2);", + "fs.appendFileSync(" + JSON.stringify(CALLS) + ", 'systemctl ' + a.join(' ') + '\\n');", + "if (a[0] !== 'show') process.exit(0);", + "if (a.indexOf('Environment') >= 0) process.stdout.write('Environment=LD_PRELOAD=/usr/lib/libschedconfig.so.1\\n');", + "else if (a.indexOf('User') >= 0) process.stdout.write('User=cia_13002\\n');", + "else if (a.indexOf('DropInPaths') >= 0) process.stdout.write('DropInPaths=\\n');", + "else if (a.indexOf('MainPID') >= 0) { var p = fs.existsSync(path.join(" + JSON.stringify(PROC) + ", '4242')) ? 4242 : 0;", + " process.stdout.write('MainPID=' + p + '\\nInvocationID=inv-' + p + '\\nExecMainStartTimestampMonotonic=5\\n'); }", +].join('\n') + '\n'); +fs.chmodSync(path.join(BIN, 'systemctl'), 0o755); +['kill', 'reboot'].forEach(function (n) { fs.writeFileSync(path.join(BIN, n), '#!/bin/sh\necho "' + n + ' $*" >> "' + CALLS + '"\n'); fs.chmodSync(path.join(BIN, n), 0o755); }); -/* remount,ro fails while a process runs a file no name links any more (its - * fake /proc exe is the inode's only link), as the kernel refuses it. */ +/* Each call recorded; remount,ro fails while a process runs a file no name + * links any more (its fake /proc exe is the inode's only link), as the + * kernel refuses it. */ var MOUNT = path.join(dir, 'mount'); fs.writeFileSync(MOUNT, '#!' + process.execPath + '\n' + [ "var fs = require('fs'), path = require('path');", "var a = process.argv.slice(2).join(' '), P = " + JSON.stringify(PROC) + ", M = " + JSON.stringify(MOUNTS) + ";", + "fs.appendFileSync(" + JSON.stringify(MOUNT_CALLS) + ", a + '\\n');", "if (/remount,rw/.test(a)) {", " if (fs.existsSync(" + JSON.stringify(RW_FAILS) + ")) { process.stderr.write('mount: / is busy\\n'); process.exit(32); }", " fs.writeFileSync(M, '/dev/root / ext4 rw 0 0\\n');", @@ -113,10 +150,8 @@ fs.chmodSync(MOUNT, 0o755); var ENV = Object.assign({}, process.env, { PATH: BIN + path.delimiter + process.env.PATH, WOC_PATCH_SOCK: path.join(SOCKDIR, 'patch.sock'), - WOC_CARPLAY: TGT, WOC_MOUNT: MOUNT, WOC_PROC_MOUNTS: MOUNTS, - WOC_PROC: PROC, WOC_RECMGR_CONF: RECMGR, WOC_RECMGR_AT_BOOT: path.join(dir, 'no-recmgr-at-boot.json'), WOC_PROC_STAT: PROC_STAT, @@ -126,7 +161,6 @@ var ENV = Object.assign({}, process.env, { WOC_DLT_RECEIVE: path.join(dir, 'no-dlt-receive'), WOC_DLT_RETRY_MS: '600000', WOC_REBOOT_CMD: path.join(BIN, 'reboot'), - WOC_STATE_DIR: path.join(dir, 'var'), WOC_REMOUNT_LOCK: path.join(SOCKDIR, 'remount.lock'), }); @@ -141,40 +175,59 @@ function hook(which) { function sha(buf) { return crypto.createHash('sha256').update(buf).digest('hex'); } function disk() { return sha(fs.readFileSync(TGT)); } function ino(f) { try { return fs.statSync(f).ino; } catch (e) { return null; } } -function slot() { return fs.readFileSync(TGT).slice(SLOT, SLOT + 4).toString('hex'); } -function sinkText() { var b = fs.readFileSync(TGT).slice(SINK, SINK + 59); var n = b.indexOf(0); return b.slice(0, n < 0 ? 59 : n).toString('latin1'); } function marker() { try { return JSON.parse(fs.readFileSync(PENDING, 'utf8')); } catch (e) { return null; } } function ro() { return /\bro\b/.test(fs.readFileSync(MOUNTS, 'utf8')); } function calls() { return fs.readFileSync(CALLS, 'utf8').split('\n').filter(Boolean); } +/* What would stop, start or kill carplay, or reboot: every call but the + * reads of systemctl show. */ +function changes() { return calls().filter(function (l) { return !/^systemctl show /.test(l); }); } +var mountSeen = 0; +/* The remounts since the last call. */ +function remounts() { var all = fs.readFileSync(MOUNT_CALLS, 'utf8').split('\n').filter(Boolean), n = all.slice(mountSeen); mountSeen = all.length; return n; } function verify() { - return cp.spawnSync(process.execPath, [path.join(__dirname, '..', 'carplay_patch.js'), 'verify', '--target', TGT], { encoding: 'utf8' }).stdout; + return cp.spawnSync(process.execPath, [PATCHER, 'verify', '--target', TGT], { encoding: 'utf8' }).stdout; } -/* carplay's process runs file: its /proc//exe holds that inode. */ -function runs(file) { - stops(); - fs.mkdirSync(path.join(PROC, '4242')); - fs.linkSync(file, path.join(PROC, '4242', 'exe')); +function patcher(args) { return cp.execFileSync(process.execPath, [PATCHER].concat(args), { encoding: 'utf8' }); } +/* The patch in memory: its record (null without one), the plan, and + * whether carplay's next start this boot is armed. */ +function rec() { return inmem.readRecord('carplay'); } +function planText() { try { return fs.readFileSync(IP.plan, 'utf8'); } catch (e) { return null; } } +function armed() { return fs.existsSync(IP.env); } +function noInmem() { + [IP.record, IP.plan].forEach(function (f) { try { fs.unlinkSync(f); } catch (e) {} }); + cp.execFileSync('rm', ['-rf', RUN]); } -function stops() { cp.execFileSync('rm', ['-rf', path.join(PROC, '4242')]); } -/* The next head-unit start: /dev/shm is empty again and carplay runs what is - * on disk. */ +/* What the running carplay's memory holds at the plan's sites. */ +function mem() { return inmem.memState('carplay', 4242); } +/* carplay's process runs file (4242): armed when this boot's env file is there. */ +function runs(file) { return carplayProc.start(PROC, 4242, file, RUN); } +function stops() { carplayProc.stop(PROC); } +/* The next head-unit start: /dev/shm and /run are empty again, boot + * recovery arms an enabled patch whose record describes carplay, and + * carplay runs what is on disk. */ function headUnitStart() { try { fs.unlinkSync(PENDING); } catch (e) {} - runs(TGT); + if (!inmem.current('carplay')) cp.execFileSync('rm', ['-rf', RUN]); + return runs(TGT); } function fresh(buf) { stops(); - [PENDING, RUNNING, BAK, TGT + '.woc-orig.json', TGT + '.woc-patch.json'].forEach(function (f) { try { fs.unlinkSync(f); } catch (e) {} }); + [PENDING, RUNNING, RUNNING + '.1', RUNNING + '.2', BAK, TGT + '.woc-orig.json', TGT + '.woc-patch.json'].forEach(function (f) { try { fs.unlinkSync(f); } catch (e) {} }); + noInmem(); fs.writeFileSync(TGT, buf, { mode: 0o755 }); runs(TGT); + remounts(); } +/* The patch an earlier release's install wrote to the file (IC_HIGH, the + * stock AVB sink), with our backup and its record. */ +function earlierPatch() { patcher(['apply', '--target', TGT, '--panel', 'high', '--coding', headUnit.CODING, '--yes']); } /* patchd started (as at a head-unit start), and its first status. */ -function daemonStatus() { return daemonCommand(null, 'status'); } +function daemonStatus() { return daemonCommand(null, function (m) { return m.ev === 'status'; }); } /* patchd started, msg sent once its first status is in (none when null), - * and the first event ev after that. */ -function daemonCommand(msg, ev) { + * and the first event after that done(event) accepts. */ +function daemonCommand(msg, done) { return new Promise(function (resolve, reject) { var d = cp.spawn(process.execPath, [PATCHD], { env: ENV, stdio: ['ignore', 'ignore', 'inherit'] }); children.push(d); @@ -192,141 +245,138 @@ function daemonCommand(msg, ev) { buf = buf.slice(i + 1); if (msg && m.ev === 'status') { c.write(JSON.stringify(msg) + '\n'); msg = null; continue; } /* Resolved once it is gone, so the next patchd's socket is the only one. */ - if (m.ev === ev) { c.destroy(); d.on('exit', function () { resolve(m); }); d.kill('SIGKILL'); return; } + if (done(m)) { c.destroy(); d.on('exit', function () { resolve(m); }); d.kill('SIGKILL'); return; } } }); })(); }); } +/* CarPlay's Patch or Remove patch button: its outcome (patchd may not + * restart carplay here: no drop-in loaded). */ +function button(msg) { + return daemonCommand(msg, function (m) { return m.ev === 'refused' || (m.ev === 'status' && (m.state === 'error' || m.carplay === 'deferred' || (m.state !== 'busy' && !m.carplay))); }); +} async function main() { - var r, before, m, st, runningIno, patchedIno; + var r, before, m, st, patchedIno; /* A fresh install: the pristine build, no backup of ours, carplay running it. */ fresh(SRCBUF); - runningIno = ino(TGT); r = hook('activate'); m = marker(); ok('fresh: activate exits 0', r.code === 0, r.out); - ok('fresh: CarPlay\'s Patch button\'s patch is on disk (IC_HIGH, stock AVB sink)', slot() === 'bcf2f7ff' && /^avb:\/\//.test(sinkText()), slot() + ' ' + sinkText()); - ok('fresh: the patcher verifies it, 1088x480 and the default safe area', - /OK: variant IC_HIGH, sink original \(AVB 15\), self-start on, res 1088x480/.test(verify())); - ok('fresh: the result asks for a head-unit start', /next head-unit start/.test(r.result.reboot || '') && /written/.test(r.result.status || ''), JSON.stringify(r.result)); + ok('fresh: carplay on disk as it ships, nothing of ours beside it', disk() === sha(SRCBUF) && !fs.existsSync(BAK) && !fs.existsSync(RUNNING)); + ok('fresh: the plan and its record, enabled, on trial', !!rec() && rec().enabled === true && rec().trial === true && rec().proven === false && + /^wocplan 1\n/.test(planText() || '') && planText().indexOf('edit variant 2ba4f0 ecf2f7ff bcf2f7ff\n') > 0, JSON.stringify(rec())); + ok('fresh: carplay\'s next start armed, the unit\'s preload first', armed() && + fs.readFileSync(IP.env, 'utf8').indexOf('LD_PRELOAD=/usr/lib/libschedconfig.so.1 ' + LIB + '\n') === 0); + ok('fresh: the running carplay\'s memory is stock', mem() === 'stock', mem()); + ok('fresh: the result asks for a head-unit start', /next head-unit start/.test(r.result.reboot || '') && /armed in memory/.test(r.result.status || ''), JSON.stringify(r.result)); ok('fresh: the marker says apply', m && m.action === 'apply' && !m.by && /next head-unit start/.test(m.reason), JSON.stringify(m)); ok('fresh: the marker is world-readable, its folder traversable', (fs.statSync(PENDING).mode & 0o777) === 0o644 && (fs.statSync(SOCKDIR).mode & 0o755) === 0o755); - ok('fresh: carplay\'s running file stays linked, / read-only again', ino(RUNNING) === runningIno && ro()); - ok('fresh: no systemctl, kill or reboot', calls().length === 0, calls().join('; ')); + ok('fresh: / never remounted', remounts().length === 0 && ro()); + ok('fresh: nothing started, stopped, killed or rebooted', changes().length === 0, changes().join('; ')); st = await daemonStatus(); - ok('fresh: patchd reports the pending apply and keeps the link carplay runs', st.state === 'unknown' && st.pending === 'apply' && - st.carplay === 'deferred' && !st.conflict && ino(RUNNING) === runningIno && ro(), JSON.stringify(st)); + ok('fresh: patchd reports the pending apply', st.state === 'unknown' && st.pending === 'apply' && + st.carplay === 'deferred' && !st.conflict && st.res === '1088x480' && st.mapurl === 'eta', JSON.stringify(st)); - /* The install run again (a reinstall or a rollback's activate): no write. */ + /* The install run again (a reinstall or a rollback's activate): nothing changes. */ before = disk(); + var planBefore = planText(); r = hook('activate'); - ok('pending: a second activate changes nothing', r.code === 0 && disk() === before && marker().action === 'apply', r.out); + ok('pending: a second activate changes nothing', r.code === 0 && disk() === before && planText() === planBefore && marker().action === 'apply' && armed(), r.out); ok('pending: it still reports the head-unit start', /next head-unit start/.test(r.result.reboot || ''), JSON.stringify(r.result)); - /* The head-unit start: carplay runs the patch; patchd removes the link - * nothing runs any more as it starts. */ - headUnitStart(); + /* The head-unit start: carplay's start is armed, its memory holds the plan. */ + ok('patched: the head-unit start runs the patch in memory', headUnitStart() === 'patched' && mem() === 'patched'); st = await daemonStatus(); ok('patched: patchd reports patched, avb, high, the map URL with ETA, nothing pending', st.state === 'patched' && st.mode === 'avb' && st.panel === 'high' && - st.mapurl === 'eta' && !st.pending, JSON.stringify(st)); - ok('patched: patchd removed the unused link as it started, / read-only', !fs.existsSync(RUNNING) && ro()); + st.mapurl === 'eta' && !st.pending && !st.carplay, JSON.stringify(st)); before = disk(); r = hook('activate'); - ok('patched: activate changes nothing, asks for nothing', r.code === 0 && disk() === before && !r.result.reboot && marker() === null, JSON.stringify(r.result)); + ok('patched: activate changes nothing, asks for nothing', r.code === 0 && disk() === before && !r.result.reboot && marker() === null && armed(), JSON.stringify(r.result)); - /* Removal while carplay runs the patch: reverted, pending, our backup gone, - * carplay's file kept linked and handed to the deploy tool. */ - patchedIno = ino(TGT); + /* Removal while carplay runs the patch: the next start disarmed, the + * plan and its record gone, a revert pending. */ r = hook('deactivate'); m = marker(); - ok('removal while running the patch: reverts to the original, exit 0', r.code === 0 && disk() === sha(SRCBUF), r.out); + ok('removal while running the patch: exit 0, carplay on disk as it ships', r.code === 0 && disk() === sha(SRCBUF), r.out); + ok('removal while running the patch: the next start disarmed, the plan and its record gone', !armed() && rec() === null && planText() === null); ok('removal while running the patch: the marker is the removal\'s revert, a start is asked for', m && m.action === 'revert' && m.by === 'removal' && /next head-unit start/.test(r.result.reboot || ''), JSON.stringify([m, r.result])); - ok('removal while running the patch: our backup is dropped', !fs.existsSync(BAK) && !fs.existsSync(TGT + '.woc-orig.json')); - ok('removal while running the patch: carplay\'s file stays linked and goes to the deploy tool, / read-only', - ino(RUNNING) === patchedIno && JSON.stringify(r.result.removeWhenUnused) === JSON.stringify([RUNNING]) && ro(), JSON.stringify(r.result)); + ok('removal while running the patch: nothing handed to the deploy tool, / never remounted', !r.result.removeWhenUnused && remounts().length === 0 && ro(), + JSON.stringify(r.result)); st = await daemonStatus(); - ok('removal while running the patch: patchd reports the pending revert, keeps the link', st.pending === 'revert' && st.carplay === 'deferred' && - ino(RUNNING) === patchedIno, JSON.stringify(st)); + ok('removal while running the patch: patchd reports the pending revert', st.pending === 'revert' && st.carplay === 'deferred', JSON.stringify(st)); - /* Installed again before that start: the removal is undone; carplay's own - * file is back in place and nothing is pending. */ + /* Installed again before that start: carplay's memory holds the plan + * again, so the removal is undone and nothing is pending. */ r = hook('activate'); - ok('reinstall before the start: the running patch is back in place, nothing pending, / read-only', - r.code === 0 && ino(TGT) === patchedIno && !fs.existsSync(RUNNING) && marker() === null && !r.result.reboot && ro(), JSON.stringify(r.result)); + ok('reinstall before the start: planned and armed, the running patch is the plan, nothing pending', + r.code === 0 && armed() && !!rec() && rec().enabled === true && marker() === null && !r.result.reboot && /runs it already/.test(r.result.status || ''), JSON.stringify(r.result)); /* Removed, then the start, then installed again: a fresh install. */ r = hook('deactivate'); - ok('removal again: pending, the link handed over', r.code === 0 && marker().by === 'removal' && r.result.removeWhenUnused, JSON.stringify(r.result)); - headUnitStart(); - ok('after the start nothing runs the link', ino(RUNNING) === patchedIno); + ok('removal again: pending', r.code === 0 && marker() && marker().by === 'removal', JSON.stringify(r.result)); + ok('after the start carplay runs as it ships', headUnitStart() === 'stock' && !armed()); r = hook('activate'); - ok('reinstall after the start: patched again as a fresh install, pending', r.code === 0 && marker() && marker().action === 'apply' && - slot() === 'bcf2f7ff' && fs.existsSync(BAK), JSON.stringify(r.result)); - ok('reinstall after the start: the old unused link went in the write window, carplay\'s current file is kept, / read-only', - ino(RUNNING) !== patchedIno && ino(RUNNING) !== null && ro()); + ok('reinstall after the start: planned and armed again, pending', r.code === 0 && marker() && marker().action === 'apply' && armed() && + disk() === sha(SRCBUF), JSON.stringify(r.result)); - /* Installed and removed before the head-unit start: carplay still runs - * what it ran, so its own file goes back in place and nothing is pending. */ + /* Installed and removed before the head-unit start: carplay's memory is + * stock, so nothing is pending. */ fresh(SRCBUF); - runningIno = ino(TGT); r = hook('activate'); ok('undo: activate leaves an apply pending', r.code === 0 && marker().action === 'apply'); r = hook('deactivate'); - ok('undo: deactivate puts carplay\'s own file back, nothing pending, nothing handed over', r.code === 0 && disk() === sha(SRCBUF) && - marker() === null && ino(TGT) === runningIno && !fs.existsSync(RUNNING) && !r.result.reboot && !r.result.removeWhenUnused && - !fs.existsSync(BAK), JSON.stringify(r.result)); - ok('undo: / is read-only again', ro()); + ok('undo: deactivate disarms, nothing pending', r.code === 0 && disk() === sha(SRCBUF) && !armed() && rec() === null && + marker() === null && !r.result.reboot && !r.result.removeWhenUnused, JSON.stringify([r.result, marker()])); - /* Removal with carplay not running: nothing needs keeping. */ + /* Removal with carplay not running: nothing to wait for. */ fresh(SRCBUF); hook('activate'); headUnitStart(); stops(); r = hook('deactivate'); - ok('removal, carplay not running: reverted, no link kept or handed over, / read-only', r.code === 0 && disk() === sha(SRCBUF) && - !fs.existsSync(RUNNING) && !r.result.removeWhenUnused && ro(), JSON.stringify(r.result)); + ok('removal, carplay not running: disarmed, nothing pending', r.code === 0 && disk() === sha(SRCBUF) && !armed() && rec() === null && + marker() === null && !r.result.reboot, JSON.stringify(r.result)); - /* CarPlay's Remove patch button pressed (patchd's revert keeps the backup), taken - * effect: an update leaves the original, a removal drops the backup. */ + /* CarPlay's Remove patch button pressed (the record kept, turned off by + * the user), taken effect: an update leaves it off, a removal deletes it. */ fresh(SRCBUF); hook('activate'); headUnitStart(); - cp.execFileSync(process.execPath, [path.join(__dirname, '..', 'carplay_patch.js'), 'revert', '--target', TGT, '--yes']); + m = await button({ cmd: 'revert' }); + ok('Remove patch: the record turned off by the user, the next start disarmed, the revert pending', !!rec() && rec().enabled === false && rec().by === 'user' && + !armed() && m.pending === 'revert' && m.carplay === 'deferred', JSON.stringify([m, rec()])); headUnitStart(); + ok('Remove patch: the next start runs carplay as it ships', mem() === 'stock'); r = hook('activate'); - ok('reverted: activate leaves the original', r.code === 0 && disk() === sha(SRCBUF) && !r.result.reboot && /turned off/.test(r.result.status), JSON.stringify(r.result)); + ok('reverted: activate leaves it off', r.code === 0 && disk() === sha(SRCBUF) && !r.result.reboot && !armed() && rec().enabled === false && + /turned off/.test(r.result.status), JSON.stringify(r.result)); r = hook('deactivate'); - ok('reverted: deactivate drops the backup, nothing to restart', r.code === 0 && disk() === sha(SRCBUF) && !r.result.reboot && - !fs.existsSync(BAK) && marker() === null && ro(), JSON.stringify(r.result)); + ok('reverted: deactivate deletes the record, nothing to restart', r.code === 0 && disk() === sha(SRCBUF) && !r.result.reboot && + rec() === null && marker() === null && ro(), JSON.stringify(r.result)); r = hook('deactivate'); ok('original: deactivate has nothing to do', r.code === 0 && disk() === sha(SRCBUF) && !r.result.reboot, JSON.stringify(r.result)); - /* CarPlay's Remove patch button's revert still pending when the tool is removed: the - * revert becomes the removal's, so an install before the start patches - * again; our backup goes. */ + /* CarPlay's Remove patch button's revert still pending when the tool is + * removed: the revert becomes the removal's, so an install before the + * start applies again. */ fresh(SRCBUF); hook('activate'); headUnitStart(); - patchedIno = ino(TGT); - fs.unlinkSync(RUNNING); /* unused since the start: patchd's write window removes it */ - fs.linkSync(TGT, RUNNING); - cp.execFileSync(process.execPath, [path.join(__dirname, '..', 'carplay_patch.js'), 'revert', '--target', TGT, '--yes']); - fs.writeFileSync(PENDING, JSON.stringify({ action: 'revert' }) + '\n'); + await button({ cmd: 'revert' }); r = hook('deactivate'); - ok('pending CarPlay\'s Remove patch button, then removal: the backup goes, the revert is the removal\'s, the running file stays linked', - r.code === 0 && !fs.existsSync(BAK) && marker().action === 'revert' && marker().by === 'removal' && - /next head-unit start/.test(r.result.reboot || '') && ino(RUNNING) === patchedIno && disk() === sha(SRCBUF) && ro(), JSON.stringify(r.result)); + ok('pending Remove patch, then removal: the revert is the removal\'s', r.code === 0 && rec() === null && marker() && marker().action === 'revert' && + marker().by === 'removal' && /next head-unit start/.test(r.result.reboot || '') && disk() === sha(SRCBUF), JSON.stringify(r.result)); r = hook('activate'); - ok('pending CarPlay\'s Remove patch button, then removal: an install before the start puts the running patch back', - r.code === 0 && ino(TGT) === patchedIno && marker() === null && !fs.existsSync(RUNNING), JSON.stringify(r.result)); + ok('pending Remove patch, then removal: an install before the start arms the plan the running carplay holds, nothing pending', + r.code === 0 && armed() && marker() === null && !r.result.reboot, JSON.stringify(r.result)); /* Another tool's edit elsewhere in the binary, made after our patch: - * removal reverts our regions only and keeps it. */ + * removal leaves the file as it is. */ fresh(SRCBUF); hook('activate'); headUnitStart(); @@ -334,41 +384,61 @@ async function main() { Buffer.from('e900000000', 'hex').copy(theirs, 0x9f9a0); fs.writeFileSync(TGT + '.theirs', theirs, { mode: 0o755 }); fs.renameSync(TGT + '.theirs', TGT); - runs(TGT); + ok('another tool\'s edit: the plan does not describe the changed file', inmem.current('carplay') === null); + headUnitStart(); r = hook('deactivate'); - var after = fs.readFileSync(TGT); - ok('another tool\'s edit: removal reverts our edits only, keeps theirs, drops our backup, / read-only', - r.code === 0 && after.slice(0x9f9a0, 0x9f9a5).toString('hex') === 'e900000000' && /variant original, sink original \(AVB 15\), self-start off, res stock/.test(verify()) && - !fs.existsSync(BAK) && ro(), JSON.stringify(r.result) + ' ' + verify()); + ok('another tool\'s edit: removal keeps theirs, deletes the plan, / never remounted', + r.code === 0 && disk() === sha(theirs) && rec() === null && remounts().length === 0 && ro(), JSON.stringify(r.result) + ' ' + verify()); headUnitStart(); before = disk(); r = hook('activate'); - ok('another tool\'s edit: a later install leaves it alone (modified by something else)', r.code === 0 && disk() === before && + ok('another tool\'s edit: a later install leaves it alone (modified by something else)', r.code === 0 && disk() === before && rec() === null && /modified by something else/.test(r.result.conflict || ''), JSON.stringify(r.result)); - /* An older patch of ours (before the resolution edit): brought up to date. */ + /* An earlier release's patch on disk, with our backup, carplay running + * it: the file reverted from the backup, the backup dropped, the plan + * armed; the running carplay's memory holds the plan's bytes, so + * nothing is pending. */ fresh(SRCBUF); - hook('activate'); + earlierPatch(); headUnitStart(); + patchedIno = ino(TGT); + r = hook('activate'); + ok('earlier release\'s patch: reverted from our backup, the backup dropped, the plan armed, nothing pending', r.code === 0 && disk() === sha(SRCBUF) && + !fs.existsSync(BAK) && !fs.existsSync(TGT + '.woc-orig.json') && armed() && rec().enabled === true && marker() === null && !r.result.reboot, + JSON.stringify(r.result)); + ok('earlier release\'s patch: carplay\'s running file stays linked while it runs, / read-only', ino(RUNNING) === patchedIno && mem() === 'patched' && ro()); + st = await daemonStatus(); + ok('earlier release\'s patch: patchd reports patched, nothing pending', st.state === 'patched' && st.mode === 'avb' && !st.pending, JSON.stringify(st)); + headUnitStart(); + st = await daemonStatus(); + ok('earlier release\'s patch: after the start patchd removed the unused link, carplay runs the plan', !fs.existsSync(RUNNING) && mem() === 'patched' && + st.state === 'patched' && ro(), JSON.stringify(st)); + + /* An older patch of ours (before the resolution edit), with our backup: + * reverted, the plan armed; its memory lacks the resolution edit, so + * the apply is pending. */ + fresh(SRCBUF); + earlierPatch(); var older = Buffer.from(SRCBUF); older.writeUInt32LE(0xfff7f2bc >>> 0, SLOT); Buffer.from('e89f000000', 'hex').copy(older, 0x18176c); fs.writeFileSync(TGT, older); + headUnitStart(); r = hook('activate'); - ok('older patch: activate adds the missing edit, pending', r.code === 0 && marker().action === 'apply' && - /resolution -> 1088x480/.test(r.out), r.out); + ok('older patch: reverted from our backup, the plan armed, pending', r.code === 0 && disk() === sha(SRCBUF) && !fs.existsSync(BAK) && armed() && + mem() === 'mixed' && marker() && marker().action === 'apply' && /next head-unit start/.test(r.result.reboot || ''), JSON.stringify([r.result, mem()])); /* The patches 0.9.11-0.10.1 (the map URL alone) and 0.10.2-0.10.3 (the * URL with ETA alone) wrote, running: patchd reports each as needing the - * Patch button; an update's activate writes the URL edits, only their - * sites, after which patchd reports the URLs with ETA; a removal reverts - * each to the original. */ - fresh(SRCBUF); - hook('activate'); - headUnitStart(); - var full = fs.readFileSync(TGT), loc0 = require('../carplay_locate.js').locate(full), mu = loc0.mapurl, su = loc0.showui; - st = await daemonStatus(); - ok('this version\'s patch: patchd reports the URLs with ETA', st.state === 'patched' && st.mapurl === 'eta' && !st.pending, JSON.stringify(st)); + * Patch button; an update's activate reverts the file and arms the plan, + * pending, after which patchd reports the URLs with ETA; a removal + * reverts each to the original. */ + var FULL = path.join(dir, 'full', 'carplay'); + fs.mkdirSync(path.dirname(FULL)); + fs.writeFileSync(FULL, SRCBUF); + patcher(['apply', '--target', FULL, '--panel', 'high', '--coding', headUnit.CODING, '--yes']); + var full = fs.readFileSync(FULL), loc0 = require('../carplay_locate.js').locate(full), mu = loc0.mapurl, su = loc0.showui; function release(form) { var b = Buffer.from(full), f = mu.forms.filter(function (x) { return x.name === form; })[0]; Buffer.from(f.slotBytes, 'hex').copy(b, mu.slot); Buffer.from(f.leaBytes, 'hex').copy(b, mu.lea); @@ -377,62 +447,62 @@ async function main() { } for (var rf = 0; rf < 2; rf++) { var form = ['current', 'eta'][rf], what = ['0.9.11\'s patch', '0.10.2\'s patch'][rf], relBuf = release(form); + fresh(SRCBUF); + earlierPatch(); fs.writeFileSync(TGT, relBuf); headUnitStart(); st = await daemonStatus(); ok(what + ': patchd reports patched, the URLs needing the Patch button', st.state === 'patched' && st.mapurl === 'no-eta' && !st.pending, JSON.stringify(st)); r = hook('activate'); - ok(what + ': activate writes the URL edits, only them, pending', r.code === 0 && marker() && marker().action === 'apply' && - /ShowUI URL -> maps:\/car\/instrumentcluster\?showETA=yes/.test(r.out) && /map URL -> maps:\/car\/instrumentcluster\/map$/m.test(r.out) === (form === 'eta') && - !/variant ->|resolution ->|self-start ->|sink ->/.test(r.out) && fs.readFileSync(TGT).equals(full), r.out); + ok(what + ': activate reverts the file and arms the plan, pending', r.code === 0 && disk() === sha(SRCBUF) && !fs.existsSync(BAK) && armed() && + marker() && marker().action === 'apply', JSON.stringify(r.result)); headUnitStart(); st = await daemonStatus(); ok(what + ': after the start patchd reports the URLs with ETA', st.state === 'patched' && st.mapurl === 'eta' && !st.pending, JSON.stringify(st)); + fresh(SRCBUF); + earlierPatch(); fs.writeFileSync(TGT, relBuf); headUnitStart(); r = hook('deactivate'); ok(what + ': removal reverts to the original, drops our backup', r.code === 0 && disk() === sha(SRCBUF) && !fs.existsSync(BAK), r.out); - fresh(SRCBUF); - hook('activate'); - headUnitStart(); } - /* The patcher fails after replacing the binary (here: the backup's record - * cannot be dropped): carplay's file stays linked and the revert waits - * for the next start. */ + /* The patcher fails after replacing the binary in a removal (here: the + * backup's record cannot be dropped): the removal is refused, so the + * tool stays; carplay's file stays linked and / goes read-only. */ fresh(SRCBUF); - hook('activate'); + earlierPatch(); headUnitStart(); patchedIno = ino(TGT); fs.unlinkSync(TGT + '.woc-orig.json'); fs.mkdirSync(TGT + '.woc-orig.json'); r = hook('deactivate'); - ok('failure after the write: exit 0, the revert pending, carplay\'s file still linked, / read-only', - r.code === 0 && /dropping .*woc-orig.json/.test(r.out) && disk() === sha(SRCBUF) && marker() && marker().action === 'revert' && + ok('failure after the write: the removal refused, exit 1, the file reverted, carplay\'s file still linked, / read-only', + r.code === 1 && /^CarPlay not undone \([\s\S]*dropping [\s\S]*woc-orig\.json/.test(r.result.status || '') && disk() === sha(SRCBUF) && ino(RUNNING) === patchedIno && ro(), JSON.stringify(r.result)); fs.rmdirSync(TGT + '.woc-orig.json'); - /* Boot recovery restored the original while carplay runs the patch (it - * keeps the running file linked and clears the marker): patchd starting - * keeps that link while carplay runs it and removes it after the start. */ + /* Boot recovery restored the original of an earlier release's patch + * while carplay runs it (it keeps the running file linked and clears the + * marker): patchd starting keeps that link while carplay runs it and + * removes it after the start. */ fresh(SRCBUF); - hook('activate'); + earlierPatch(); headUnitStart(); patchedIno = ino(TGT); - try { fs.unlinkSync(RUNNING); } catch (e) {} fs.linkSync(TGT, RUNNING); - cp.execFileSync(process.execPath, [path.join(__dirname, '..', 'carplay_patch.js'), 'revert', '--target', TGT, '--yes']); - try { fs.unlinkSync(PENDING); } catch (e) {} + patcher(['revert', '--target', TGT, '--yes']); await daemonStatus(); ok('recovery\'s link: kept by patchd while carplay runs it', ino(RUNNING) === patchedIno && ro()); headUnitStart(); await daemonStatus(); ok('recovery\'s link: removed by patchd once nothing runs it, / read-only', !fs.existsSync(RUNNING) && ro()); - /* Boot recovery's own restore at its threshold (the boot step's, nothing - * running): patchd reports it, and an install leaves the patch off. */ + /* Boot recovery's own restore of an earlier release's patch at its + * threshold (the boot step's, nothing running): patchd reports it, and + * an install leaves the patch off. */ fresh(SRCBUF); - hook('activate'); + earlierPatch(); headUnitStart(); stops(); r = cp.spawnSync(process.execPath, ['-e', 'var r = require(process.argv[1]); r.restoreTarget(r.TARGETS.carplay, true, 2, function (e, o) { process.stdout.write(String(e || o)); });', @@ -442,21 +512,32 @@ async function main() { ok('boot recovery\'s restore: patchd reports the original and the failed starts it was made at', st.state === 'original' && st.recovered === 2 && !st.pending, JSON.stringify(st)); before = disk(); r = hook('activate'); - ok('boot recovery\'s restore: an install leaves the patch off, and says why', r.code === 0 && disk() === before && marker() === null && + ok('boot recovery\'s restore: an install leaves the patch off, and says why', r.code === 0 && disk() === before && marker() === null && rec() === null && /boot recovery removed the patch after 2 failed head-unit starts/.test(r.result.status || ''), JSON.stringify(r.result)); + /* Boot recovery turned the patch in memory off at its threshold: patchd + * reports it, and an install leaves it off. */ + fresh(SRCBUF); + hook('activate'); + headUnitStart(); + inmem.disarm('carplay'); + inmem.disable('carplay', { by: 'recovery', fails: 2, why: 'boot' }); + headUnitStart(); + st = await daemonStatus(); + ok('boot recovery turned it off: patchd reports the original and the failed starts', st.state === 'original' && st.recovered === 2 && !st.pending, JSON.stringify(st)); + r = hook('activate'); + ok('boot recovery turned it off: an install leaves it off, and says why', r.code === 0 && !armed() && rec().enabled === false && marker() === null && + /boot recovery turned the patch off after 2 failed head-unit starts/.test(r.result.status || ''), JSON.stringify(r.result)); + /* A write window cut short between keeping the link and the patcher's * rename leaves a link that is carplay's own file: patchd removes it as * it starts, carplay running or not. */ fresh(SRCBUF); - hook('activate'); - headUnitStart(); - try { fs.unlinkSync(RUNNING); } catch (e) {} fs.linkSync(TGT, RUNNING); - patchedIno = ino(TGT); + var ownIno = ino(TGT); await daemonStatus(); ok('a link that is carplay\'s own file: removed by patchd\'s start, carplay\'s file intact, / read-only', - !fs.existsSync(RUNNING) && ino(TGT) === patchedIno && ro()); + !fs.existsSync(RUNNING) && ino(TGT) === ownIno && ro()); /* The same leftover when the tool is removed with nothing to revert: the * removal drops it itself and hands nothing over. */ @@ -482,8 +563,8 @@ async function main() { unknown.writeUInt32LE(0x11223344, 0x2ba4d4); /* the converter table's slot 0 */ fresh(unknown); r = hook('activate'); - ok('unpatchable binary: activate leaves it, conflict names the site, exit 0', r.code === 0 && disk() === sha(unknown) && - /^not patchable: variant: slot 0 handler not a store$/.test(r.result.conflict || '') && !r.result.reboot, JSON.stringify(r.result)); + ok('unpatchable binary: activate leaves it, conflict names the site, exit 0', r.code === 0 && disk() === sha(unknown) && rec() === null && + /variant: slot 0 handler not a store$/.test(r.result.conflict || '') && !r.result.reboot, JSON.stringify(r.result)); r = hook('deactivate'); ok('unpatchable binary: deactivate leaves it, exit 0', r.code === 0 && disk() === sha(unknown), JSON.stringify(r.result)); @@ -497,8 +578,12 @@ async function main() { fs.writeFileSync(BAK, f.original, { mode: 0o600 }); fs.writeFileSync(TGT + '.woc-orig.json', JSON.stringify({ buildId: locate.buildId(f.original), sha256_original: sha(f.original) })); r = hook('activate'); - ok(f.name + ': activate leaves it, conflict, exit 0', r.code === 0 && fs.readFileSync(TGT).equals(f.patched) && - /^not patchable: /.test(r.result.conflict || '') && !r.result.reboot && ro(), JSON.stringify(r.result)); + ok(f.name + ': activate leaves it, conflict, exit 0', r.code === 0 && fs.readFileSync(TGT).equals(f.patched) && rec() === null && + /not patchable|first edit|in memory needs/.test(r.result.conflict || '') && !r.result.reboot && ro(), JSON.stringify(r.result)); + fs.writeFileSync(TGT, f.patched); + fs.writeFileSync(BAK, f.original, { mode: 0o600 }); + fs.writeFileSync(TGT + '.woc-orig.json', JSON.stringify({ buildId: locate.buildId(f.original), sha256_original: sha(f.original) })); + runs(TGT); r = hook('deactivate'); ok(f.name + ': deactivate restores the original, drops the backup, pending', r.code === 0 && fs.readFileSync(TGT).equals(f.original) && !fs.existsSync(BAK) && !fs.existsSync(TGT + '.woc-orig.json') && marker() && marker().action === 'revert' && ro(), JSON.stringify(r.result)); @@ -506,20 +591,36 @@ async function main() { } /* A build outside the proven list with every site stock: a fresh install - * leaves it, a conflict; once CarPlay's Patch button patched it (our backup), an - * install brings the patch up to date. */ + * leaves it, a conflict; CarPlay's Patch button plans it (unproven), and + * an install keeps that plan armed. An earlier release's Patch button + * patch of it on disk, with our backup, stays the patch: an install + * neither loses it nor leaves it unarmed. */ var other = Buffer.from(SRCBUF); other[other.indexOf(Buffer.from('5de62156575d737391ea42254e778a97dbbb51f8', 'hex'))] ^= 0xff; Buffer.from('e900000000', 'hex').copy(other, 0x9f9a0); fresh(other); r = hook('activate'); - ok('another build: activate leaves it, conflict, exit 0', r.code === 0 && disk() === sha(other) && !marker() && + ok('another build: activate leaves it, conflict, exit 0', r.code === 0 && disk() === sha(other) && !marker() && rec() === null && r.result.conflict === 'untested carplay build' && !r.result.reboot && ro(), JSON.stringify(r.result)); - cp.execFileSync(process.execPath, [path.join(__dirname, '..', 'carplay_patch.js'), 'apply', '--target', TGT, '--panel', 'mid', '--unproven', '--yes']); + m = await button({ cmd: 'apply', panel: 'mid', mode: 'avb' }); + ok('another build: CarPlay\'s Patch button plans it unproven, pending', m.pending === 'apply' && !!rec() && rec().enabled === true && rec().proven === false && + rec().trial === false && armed(), JSON.stringify([m, rec()])); headUnitStart(); r = hook('activate'); - ok('another build CarPlay\'s Patch button patched: activate writes CarPlay\'s Patch button\'s patch, pending', r.code === 0 && !r.result.conflict && marker() && marker().action === 'apply' && - slot() === 'bcf2f7ff' && /OK: variant IC_HIGH, sink original \(AVB 15\), self-start on, res 1088x480/.test(verify()) && ro(), JSON.stringify(r.result)); + ok('another build CarPlay\'s Patch button planned: an install keeps it armed, nothing pending', r.code === 0 && armed() && !!inmem.current('carplay') && + marker() === null && disk() === sha(other), JSON.stringify(r.result)); + r = hook('deactivate'); + ok('another build: deactivate deletes the plan, carplay as it was', r.code === 0 && disk() === sha(other) && rec() === null && !armed(), JSON.stringify(r.result)); + fresh(other); + patcher(['apply', '--target', TGT, '--panel', 'high', '--unproven', '--yes']); + var otherPatched = disk(); + headUnitStart(); + r = hook('activate'); + ok('another build an earlier release\'s Patch button patched on disk: an install keeps a patch of it', r.code === 0 && + ((disk() === otherPatched && fs.existsSync(BAK)) || (disk() === sha(other) && armed())), JSON.stringify(r.result)); + fresh(other); + patcher(['apply', '--target', TGT, '--panel', 'mid', '--unproven', '--yes']); + headUnitStart(); r = hook('deactivate'); ok('another build: deactivate restores it byte-exact', r.code === 0 && disk() === sha(other) && !fs.existsSync(BAK), JSON.stringify(r.result)); @@ -527,53 +628,64 @@ async function main() { * and the removal passes; another build cannot be, and the removal is * refused while our edits read in it. */ fresh(SRCBUF); - hook('activate'); + earlierPatch(); headUnitStart(); [BAK, TGT + '.woc-orig.json'].forEach(function (f) { fs.unlinkSync(f); }); r = hook('deactivate'); ok('the proven build patched, no backup: deactivate restores it byte-exact, exit 0', r.code === 0 && disk() === sha(SRCBUF), JSON.stringify(r.result)); fresh(other); - cp.execFileSync(process.execPath, [path.join(__dirname, '..', 'carplay_patch.js'), 'apply', '--target', TGT, '--panel', 'high', '--unproven', '--yes']); + patcher(['apply', '--target', TGT, '--panel', 'high', '--unproven', '--yes']); headUnitStart(); [BAK, TGT + '.woc-orig.json'].forEach(function (f) { fs.unlinkSync(f); }); var stillPatched = disk(); r = hook('deactivate'); - ok('another build patched, no backup: deactivate refused, exit 1, our edits named, nothing written', r.code === 1 && disk() === stillPatched && - /CarPlay not undone \(our edits read in carplay\)/.test(r.result.status || ''), JSON.stringify(r.result)); + ok('another build patched, no backup: deactivate refused, exit 1, the reason named, nothing written', r.code === 1 && disk() === stillPatched && + /^CarPlay not undone \([\s\S]*cannot revert/.test(r.result.status || '') && /the tool stays to guard it$/.test(r.result.status), JSON.stringify(r.result)); /* The pristine build with another tool's in-place edit and no backup of * ours: modified by something else. */ - var other = Buffer.from(SRCBUF); - Buffer.from('e900000000', 'hex').copy(other, 0x9f9a0); - fresh(other); + var elsewhere = Buffer.from(SRCBUF); + Buffer.from('e900000000', 'hex').copy(elsewhere, 0x9f9a0); + fresh(elsewhere); r = hook('activate'); - ok('modified elsewhere: left alone, conflict, exit 0', r.code === 0 && disk() === sha(other) && + ok('modified elsewhere: left alone, conflict, exit 0', r.code === 0 && disk() === sha(elsewhere) && rec() === null && /modified by something else/.test(r.result.conflict || ''), JSON.stringify(r.result)); /* carplay.service started through another program (another tool's - * drop-in): the install does not write the patch; an environment-only + * drop-in): the install does not plan the patch; an environment-only * drop-in is fine. */ fresh(SRCBUF); fs.mkdirSync(path.join(UNITS, 'carplay.service.d')); var dropin = path.join(UNITS, 'carplay.service.d', '60-other.conf'); fs.writeFileSync(dropin, '[Service]\nExecStart=\nExecStart=/bin/sh -c \'exec /var/opt/other/carplay "$$@"\' -- -c /etc/cinemo/cinemo_options.xml\n'); r = hook('activate'); - ok('foreign start: activate leaves the original, conflict names the drop-in', r.code === 0 && disk() === sha(SRCBUF) && + ok('foreign start: activate plans nothing, conflict names the drop-in', r.code === 0 && disk() === sha(SRCBUF) && rec() === null && !armed() && /carplay\.service starts \/bin\/sh/.test(r.result.conflict || '') && r.result.conflict.indexOf('60-other.conf') >= 0 && !r.result.reboot, JSON.stringify(r.result)); st = await daemonStatus(); ok('foreign start: patchd reports the conflict', st.state === 'original' && /60-other\.conf/.test(st.conflict || ''), JSON.stringify(st)); fs.writeFileSync(dropin, '[Service]\nEnvironment=LD_PRELOAD=/usr/lib/libschedconfig.so\nExecStart=\nExecStart=' + TGT + ' -c /etc/cinemo/cinemo_options.xml\n'); r = hook('activate'); - ok('own start: an environment drop-in that still starts carplay is fine', r.code === 0 && marker().action === 'apply' && !r.result.conflict, JSON.stringify(r.result)); + ok('own start: an environment drop-in that still starts carplay is fine', r.code === 0 && marker().action === 'apply' && armed() && !r.result.conflict, JSON.stringify(r.result)); fs.unlinkSync(dropin); - /* / cannot be remounted read-write: nothing written, exit non-zero. */ + /* / cannot be remounted read-write: a fresh install needs no remount; an + * earlier release's patch that cannot be reverted is left as it is, + * nothing armed, exit non-zero. */ fresh(SRCBUF); fs.writeFileSync(RW_FAILS, ''); r = hook('activate'); - ok('remount fails: activate exits non-zero, nothing written, no marker', r.code !== 0 && disk() === sha(SRCBUF) && marker() === null && - /remount rw/.test(r.result.status || ''), JSON.stringify(r.result)); + ok('remount fails, the pristine build: the plan armed all the same, / never remounted', r.code === 0 && disk() === sha(SRCBUF) && armed() && + remounts().length === 0, JSON.stringify(r.result)); + fs.unlinkSync(RW_FAILS); + fresh(SRCBUF); + earlierPatch(); + headUnitStart(); + before = disk(); + fs.writeFileSync(RW_FAILS, ''); + r = hook('activate'); + ok('remount fails, an earlier release\'s patch: activate exits non-zero, nothing written or armed, no marker', r.code !== 0 && disk() === before && + fs.existsSync(BAK) && !armed() && marker() === null && /remount rw/.test(r.result.status || ''), JSON.stringify(r.result)); fs.unlinkSync(RW_FAILS); /* A head unit that refuses our parts; a patch of ours from before is @@ -584,35 +696,34 @@ async function main() { fresh(SRCBUF); headUnit.set(c[1]); r = hook('activate'); - ok(c[0] + ': activate writes nothing, no backup, no marker, conflict', r.code === 0 && disk() === sha(SRCBUF) && !fs.existsSync(BAK) && - marker() === null && !r.result.reboot && r.result.conflict === c[2] && ro(), JSON.stringify(r.result)); + ok(c[0] + ': activate plans nothing, no backup, no marker, conflict', r.code === 0 && disk() === sha(SRCBUF) && !fs.existsSync(BAK) && + rec() === null && !armed() && marker() === null && !r.result.reboot && r.result.conflict === c[2] && ro(), JSON.stringify(r.result)); headUnit.set(headUnit.HIGH); }); [['MID', headUnit.MID], ['HIGH F', headUnit.HIGHF]].forEach(function (v) { fresh(SRCBUF); headUnit.set(v[1]); r = hook('activate'); - ok(v[0] + ': activate patches as on HIGH, pending', r.code === 0 && !r.result.conflict && marker() && marker().action === 'apply' && slot() === 'bcf2f7ff', - JSON.stringify(r.result)); + ok(v[0] + ': activate plans as on HIGH, pending', r.code === 0 && !r.result.conflict && marker() && marker().action === 'apply' && armed() && + (planText() || '').indexOf('edit variant 2ba4f0 ecf2f7ff bcf2f7ff\n') > 0, JSON.stringify(r.result)); headUnit.set(headUnit.HIGH); }); fresh(SRCBUF); headUnit.set(headUnit.NONE); st = await daemonStatus(); ok('no hwvariant=: patchd reports the original and the conflict', st.state === 'original' && st.conflict === NOT, JSON.stringify(st)); - m = await daemonCommand({ cmd: 'apply', panel: 'high', mode: 'avb' }, 'refused'); - ok('no hwvariant=: patchd refuses CarPlay\'s Patch button, nothing written', m.reason === headUnit.REFUSED && - disk() === sha(SRCBUF) && !fs.existsSync(BAK) && marker() === null && ro(), JSON.stringify(m)); + m = await daemonCommand({ cmd: 'apply', panel: 'high', mode: 'avb' }, function (x) { return x.ev === 'refused'; }); + ok('no hwvariant=: patchd refuses CarPlay\'s Patch button, nothing planned', m.reason === headUnit.REFUSED && + disk() === sha(SRCBUF) && rec() === null && marker() === null && ro(), JSON.stringify(m)); headUnit.set(headUnit.HIGH); hook('activate'); headUnitStart(); - patchedIno = ino(TGT); headUnit.set(headUnit.NONE); r = hook('activate'); - ok('no hwvariant=, patched before: activate leaves it, conflict, nothing pending', r.code === 0 && ino(TGT) === patchedIno && marker() === null && + ok('no hwvariant=, patched before: activate leaves it, conflict, nothing pending', r.code === 0 && mem() === 'patched' && marker() === null && r.result.conflict === NOT, JSON.stringify(r.result)); r = hook('deactivate'); - ok('no hwvariant=, patched before: deactivate reverts it, drops the backup', r.code === 0 && disk() === sha(SRCBUF) && !fs.existsSync(BAK) && + ok('no hwvariant=, patched before: deactivate turns it off, the revert pending', r.code === 0 && disk() === sha(SRCBUF) && rec() === null && !armed() && marker() && marker().action === 'revert' && ro(), JSON.stringify(r.result)); headUnit.set(headUnit.HIGH); @@ -620,14 +731,14 @@ async function main() { * trusted backup. The first install on HIGH F applies the patch again, * pending, and marks CarPlay done; none after it, nor on HIGH, nor over * an untrusted backup, which stays unmarked for the next install. */ - var MARK = path.join(ENV.WOC_STATE_DIR, 'highf-repatched'); + var MARK = path.join(STATE, 'highf-repatched'); function restored(unit) { try { fs.unlinkSync(MARK); } catch (e) {} headUnit.set(headUnit.HIGH); fresh(SRCBUF); - hook('activate'); + earlierPatch(); headUnitStart(); - cp.execFileSync(process.execPath, [path.join(__dirname, '..', 'carplay_patch.js'), 'revert', '--target', TGT, '--yes']); + patcher(['revert', '--target', TGT, '--yes']); headUnitStart(); headUnit.set(unit); } @@ -637,105 +748,119 @@ async function main() { var mark = null; try { mark = JSON.parse(fs.readFileSync(MARK, 'utf8')); } catch (e) {} ok('HIGH F restored by 0.8.2: the install applies the patch again, pending, and marks it done', r.code === 0 && m && m.action === 'apply' && - slot() === 'bcf2f7ff' && r.result.reset === true && mark && mark.carplay === 'applied', JSON.stringify([r.result, mark])); + armed() && r.result.reset === true && mark && mark.carplay === 'applied', JSON.stringify([r.result, mark])); st = await daemonStatus(); ok('HIGH F restored by 0.8.2: patchd reports the pending apply', st.pending === 'apply' && !st.conflict, JSON.stringify(st)); headUnitStart(); - cp.execFileSync(process.execPath, [path.join(__dirname, '..', 'carplay_patch.js'), 'revert', '--target', TGT, '--yes']); + await button({ cmd: 'revert' }); headUnitStart(); r = hook('activate'); - ok('HIGH F, marker present: a Remove patch since stays', r.code === 0 && disk() === sha(SRCBUF) && marker() === null && /turned off/.test(r.result.status), + ok('HIGH F, marker present: a Remove patch since stays', r.code === 0 && disk() === sha(SRCBUF) && marker() === null && !armed() && /turned off/.test(r.result.status), JSON.stringify(r.result)); restored(headUnit.HIGH); r = hook('activate'); - ok('HIGH: an original with our backup stays off, no marker', r.code === 0 && disk() === sha(SRCBUF) && marker() === null && + ok('HIGH: an original with our backup stays off, no marker', r.code === 0 && disk() === sha(SRCBUF) && marker() === null && !armed() && /turned off/.test(r.result.status) && !fs.existsSync(MARK), JSON.stringify(r.result)); restored(headUnit.HIGHF); fs.writeFileSync(TGT + '.woc-orig.json', JSON.stringify({ sha256_original: '0'.repeat(64) })); r = hook('activate'); - ok('HIGH F, untrusted backup: nothing written, CarPlay left for the next install', r.code === 0 && disk() === sha(SRCBUF) && marker() === null && - !fs.existsSync(MARK), JSON.stringify(r.result)); + ok('HIGH F, untrusted backup: nothing planned, CarPlay left for the next install', r.code === 0 && disk() === sha(SRCBUF) && marker() === null && + !armed() && !fs.existsSync(MARK), JSON.stringify(r.result)); restored(headUnit.HIGHF); fs.unlinkSync(TGT + '.woc-orig.json'); r = hook('activate'); - ok('HIGH F, a backup without its record: nothing written', r.code === 0 && disk() === sha(SRCBUF) && marker() === null, JSON.stringify(r.result)); + ok('HIGH F, a backup without its record: nothing planned', r.code === 0 && disk() === sha(SRCBUF) && marker() === null && !armed(), JSON.stringify(r.result)); try { fs.unlinkSync(MARK); } catch (e) {} headUnit.set(headUnit.HIGH); - /* The cluster coding. An install patches only a car coded + /* The cluster coding. An install plans only on a car coded * KI_KOMBI_VARIANT 7, and its first patch there is on trial (unproven - * until boot recovery's watcher sees it run healthy). On another coding, - * or one that cannot be read, it writes nothing and reports the conflict - * the app shows, also on HIGH F over 0.8.2's restore; a patch CarPlay's - * Patch button wrote there is left as it is. */ + * until boot recovery's watcher sees it run healthy). An earlier + * release's patch it migrates is on trial too, whatever that release + * recorded: the plan has not run here. On another coding, or one that + * cannot be read, it plans nothing and reports the conflict the app + * shows, also on HIGH F over 0.8.2's restore; a patch CarPlay's Patch + * button planned there is left as it is. */ var record = require('../patch_record.js'); - function rec() { var x = record.current(TGT); return x ? { patched: x.patched, proven: x.proven, trial: x.trial } : null; } + function trial() { var x = rec(); return x ? { enabled: x.enabled, proven: x.proven, trial: x.trial } : null; } + var TRIAL = JSON.stringify({ enabled: true, proven: false, trial: true }); fresh(SRCBUF); r = hook('activate'); - ok('coding 7: the install patches, pending, the record on trial', r.code === 0 && !r.result.conflict && marker() && marker().action === 'apply' && - JSON.stringify(rec()) === JSON.stringify({ patched: true, proven: false, trial: true }), JSON.stringify([r.result, rec()])); + ok('coding 7: the install plans, pending, the record on trial', r.code === 0 && !r.result.conflict && marker() && marker().action === 'apply' && + JSON.stringify(trial()) === TRIAL, JSON.stringify([r.result, trial()])); headUnitStart(); r = hook('activate'); - ok('coding 7: the next install leaves the trial as it is', r.code === 0 && !r.result.reboot && - JSON.stringify(rec()) === JSON.stringify({ patched: true, proven: false, trial: true }), JSON.stringify([r.result, rec()])); - /* A car an earlier release patched and recorded proven: an update keeps - * it proven, unless the update adds or changes a URL edit or the - * geometry: a healthy run without these URLs or with another geometry - * does not prove it, so that patch is on trial. */ - var current = fs.readFileSync(TGT); - record.write(TGT, { patched: true, proven: true }); - r = hook('activate'); - ok('migration: a patch recorded proven by an earlier release stays proven', r.code === 0 && !r.result.reboot && - JSON.stringify(rec()) === JSON.stringify({ patched: true, proven: true }), JSON.stringify([r.result, rec()])); + ok('coding 7: the next install leaves the trial as it is', r.code === 0 && !r.result.reboot && JSON.stringify(trial()) === TRIAL, JSON.stringify([r.result, trial()])); + inmem.update('carplay', { proven: true, trial: false }); + r = hook('activate'); + ok('coding 7: an install keeps a proven plan proven', r.code === 0 && !r.result.reboot && + JSON.stringify(trial()) === JSON.stringify({ enabled: true, proven: true, trial: false }), JSON.stringify([r.result, trial()])); + var current = Buffer.from(full); + /* An earlier release's patch recorded proven, its file as given. */ + function earlierRelease(buf) { + fresh(SRCBUF); + earlierPatch(); + fs.writeFileSync(TGT + '.older', buf, { mode: 0o755 }); + fs.renameSync(TGT + '.older', TGT); + record.write(TGT, { patched: true, proven: true }); + headUnitStart(); + return hook('activate'); + } function olderRelease(edits) { var b = Buffer.from(SRCBUF); b.writeUInt32LE(0xfff7f2bc >>> 0, SLOT); Buffer.from('e89f000000', 'hex').copy(b, 0x18176c); edits.forEach(function (e) { current.copy(b, e[0], e[0], e[0] + e[1]); }); + return earlierRelease(b); + } + r = earlierRelease(current); + ok('migration: this version\'s patch recorded proven by an earlier release: reverted, the plan proven (the car ran these bytes healthy), nothing pending', + r.code === 0 && !r.result.reboot && disk() === sha(SRCBUF) && JSON.stringify(trial()) === JSON.stringify({ enabled: true, proven: true, trial: false }) && + marker() === null, JSON.stringify([r.result, trial()])); + /* Another tool's change besides our earlier patch: the revert would keep + * it, and the plan needs the original, so the earlier patch stays. */ + var other = Buffer.from(current); + other[other.length - 1] ^= 0xff; + r = earlierRelease(other); + ok('migration: another change in carplay besides our earlier patch: the earlier patch and our backup stay, nothing planned', + r.code === 0 && /another change/.test(r.result.status || '') && !r.result.conflict && disk() === sha(other) && fs.existsSync(TGT + '.woc-orig') && + trial() === null, JSON.stringify([r.result, trial()])); + var RES = [[0x20ca32, 8], [0x20ca54, 8], [0x20ca66, 8], [0x20ca74, 8]], URLS = [[0x257838, 55], [0x7b533, 7], [0x2908a0, 64], [0x18188a, 11]]; + /* A patch whose bytes are not the plan's goes on trial; with a failure + * counted, boot recovery would turn it off at once: it stays in the file. */ + (function () { + var st = require('../recovery.js').TARGETS.carplay.state, b = Buffer.from(current); + Buffer.from('00000000dc010000', 'hex').copy(b, 0x20ca66); Buffer.from('3201000032014800', 'hex').copy(b, 0x20ca74); + fresh(SRCBUF); + earlierPatch(); fs.writeFileSync(TGT + '.older', b, { mode: 0o755 }); fs.renameSync(TGT + '.older', TGT); record.write(TGT, { patched: true, proven: true }); headUnitStart(); - return hook('activate'); - } - var RES = [[0x20ca32, 8], [0x20ca54, 8], [0x20ca66, 8], [0x20ca74, 8]], URLS = [[0x257838, 55], [0x7b533, 7], [0x2908a0, 64], [0x18188a, 11]]; + fs.writeFileSync(st, JSON.stringify({ fails: 1, unknown: 0, arm: null, prev: null, starts: null, ended: null }) + '\n'); + r = hook('activate'); + ok('migration: a patch that goes on trial while boot recovery counts a failure stays in the file, nothing planned', + r.code === 0 && /healthy start/.test(r.result.status || '') && disk() === sha(b) && trial() === null, JSON.stringify([r.result, trial()])); + fs.unlinkSync(st); + })(); /* The safe area 0.10.6 wrote (476x306 at 306,72), in place of this version's. */ function safe0106(b) { Buffer.from('00000000dc010000', 'hex').copy(b, 0x20ca66); Buffer.from('3201000032014800', 'hex').copy(b, 0x20ca74); return b; } - r = olderRelease(URLS); - ok('migration: an older patch with the URL edits and the stock geometry recorded proven, brought up to date, is on trial', r.code === 0 && marker() && marker().action === 'apply' && - /resolution -> 1088x480/.test(r.out) && !/URL ->/.test(r.out) && disk() === sha(current) && - JSON.stringify(rec()) === JSON.stringify({ patched: true, proven: false, trial: true }), JSON.stringify([r.result, rec()])); - /* 0.10.6's patch: this version's but for the safe area 476x306. */ - var released = Buffer.from(current); - safe0106(released); - fs.writeFileSync(TGT + '.older', released, { mode: 0o755 }); - fs.renameSync(TGT + '.older', TGT); - record.write(TGT, { patched: true, proven: true }); - headUnitStart(); - r = hook('activate'); - ok('migration: 0.10.6\'s patch recorded proven, its safe area brought up to date, is on trial', r.code === 0 && marker() && marker().action === 'apply' && - /resolution -> 1088x480 at 138x61mm, safe 504x368 at 286,72/.test(r.out) && !/URL ->|variant ->/.test(r.out) && disk() === sha(current) && - JSON.stringify(rec()) === JSON.stringify({ patched: true, proven: false, trial: true }), JSON.stringify([r.result, rec()])); - r = olderRelease(RES); - ok('migration: a patch without the URL edits recorded proven, brought up to date, is on trial', r.code === 0 && marker() && marker().action === 'apply' && - /map URL -> maps:\/car\/instrumentcluster\/map$/m.test(r.out) && /ShowUI URL -> /.test(r.out) && !/resolution ->/.test(r.out) && disk() === sha(current) && - JSON.stringify(rec()) === JSON.stringify({ patched: true, proven: false, trial: true }), JSON.stringify([r.result, rec()])); - r = olderRelease(RES.concat(URLS.slice(0, 2))); - ok('migration: 0.9.11\'s patch recorded proven, the ShowUI URL edit added, is on trial', r.code === 0 && marker() && marker().action === 'apply' && - /ShowUI URL -> /.test(r.out) && !/map URL ->|resolution ->|variant ->/.test(r.out) && disk() === sha(current) && - JSON.stringify(rec()) === JSON.stringify({ patched: true, proven: false, trial: true }), JSON.stringify([r.result, rec()])); + var olderPatches = [['an older patch with the URL edits and the stock geometry', function () { return olderRelease(URLS); }], + ['0.10.6\'s patch', function () { return earlierRelease(safe0106(Buffer.from(current))); }], + ['a patch without the URL edits', function () { return olderRelease(RES); }], + ['0.9.11\'s patch', function () { return olderRelease(RES.concat(URLS.slice(0, 2))); }]]; var olderMu = require('../carplay_locate.js').locate(current).mapurl, etaForm = olderMu.forms.filter(function (f) { return f.name === 'eta'; })[0]; - var withEta = Buffer.from(current); - Buffer.from(etaForm.slotBytes, 'hex').copy(withEta, olderMu.slot); Buffer.from(etaForm.leaBytes, 'hex').copy(withEta, olderMu.lea); - SRCBUF.copy(withEta, 0x2908a0, 0x2908a0, 0x2908a0 + 64); SRCBUF.copy(withEta, 0x18188a, 0x18188a, 0x18188a + 11); - fs.writeFileSync(TGT + '.older', withEta, { mode: 0o755 }); - fs.renameSync(TGT + '.older', TGT); - record.write(TGT, { patched: true, proven: true }); - headUnitStart(); - r = hook('activate'); - ok('migration: 0.10.2\'s patch recorded proven, the URL edits written, is on trial', r.code === 0 && marker() && marker().action === 'apply' && - /map URL -> maps:\/car\/instrumentcluster\/map$/m.test(r.out) && /ShowUI URL -> /.test(r.out) && !/resolution ->|variant ->/.test(r.out) && disk() === sha(current) && - JSON.stringify(rec()) === JSON.stringify({ patched: true, proven: false, trial: true }), JSON.stringify([r.result, rec()])); + olderPatches.push(['0.10.2\'s patch', function () { + var withEta = Buffer.from(current); + Buffer.from(etaForm.slotBytes, 'hex').copy(withEta, olderMu.slot); Buffer.from(etaForm.leaBytes, 'hex').copy(withEta, olderMu.lea); + SRCBUF.copy(withEta, 0x2908a0, 0x2908a0, 0x2908a0 + 64); SRCBUF.copy(withEta, 0x18188a, 0x18188a, 0x18188a + 11); + return earlierRelease(withEta); + }]); + olderPatches.forEach(function (o) { + r = o[1](); + ok('migration: ' + o[0] + ' recorded proven: reverted, the plan on trial, pending', r.code === 0 && marker() && marker().action === 'apply' && + disk() === sha(SRCBUF) && !fs.existsSync(BAK) && armed() && mem() === 'mixed' && JSON.stringify(trial()) === TRIAL, JSON.stringify([r.result, trial(), mem()])); + }); var CODINGS = [['coding 9', 9, undefined, 'not supported on this car (KI_KOMBI_VARIANT 9)'], ['invalid coding flags', 7, 0x0b, 'cluster coding unreadable'], ['no coding', null, undefined, 'cluster coding unreadable']]; @@ -744,32 +869,34 @@ async function main() { fresh(SRCBUF); headUnit.coding(c[1], c[2]); r = hook('activate'); - ok(c[0] + ': the install writes nothing, no backup, no marker, the conflict', r.code === 0 && disk() === sha(SRCBUF) && !fs.existsSync(BAK) && - marker() === null && !r.result.reboot && r.result.conflict === c[3] && rec() === null && ro(), JSON.stringify(r.result)); + ok(c[0] + ': the install plans nothing, no marker, the conflict', r.code === 0 && disk() === sha(SRCBUF) && !fs.existsSync(BAK) && + marker() === null && !r.result.reboot && r.result.conflict === c[3] && rec() === null && !armed() && ro(), JSON.stringify(r.result)); st = await daemonStatus(); ok(c[0] + ': patchd reports the original and the conflict', st.state === 'original' && st.conflict === c[3], JSON.stringify(st)); - /* CarPlay's Patch button (patchd runs the patcher with --unproven). */ - cp.execFileSync(process.execPath, [path.join(__dirname, '..', 'carplay_patch.js'), 'apply', '--target', TGT, '--panel', 'high', '--unproven', '--yes']); + /* CarPlay's Patch button (patchd plans with --unproven). */ + await button({ cmd: 'apply', panel: 'high', mode: 'avb' }); headUnitStart(); - before = disk(); + var buttonRec = JSON.stringify(c[1] === 9 ? { enabled: true, proven: false, trial: false } : { enabled: true, proven: false, trial: true }); + ok(c[0] + ': CarPlay\'s Patch button plans it (' + (c[1] === 9 ? 'unproven' : 'on trial') + ')', JSON.stringify(trial()) === buttonRec && mem() === 'patched', + JSON.stringify(trial())); + before = fs.readFileSync(IP.record, 'utf8'); r = hook('activate'); - var buttonRec = c[1] === 9 ? { patched: true, proven: false } : { patched: true, proven: false, trial: true }; - ok(c[0] + ': a patch CarPlay\'s Patch button wrote: the install leaves it and its record (' + (buttonRec.trial ? 'on trial' : 'unproven') + ')', r.code === 0 && - disk() === before && marker() === null && r.result.conflict === c[3] && JSON.stringify(rec()) === JSON.stringify(buttonRec), JSON.stringify([r.result, rec()])); + ok(c[0] + ': the install leaves the Patch button\'s plan and its record', r.code === 0 && fs.readFileSync(IP.record, 'utf8') === before && armed() && + marker() === null && r.result.conflict === c[3], JSON.stringify([r.result, trial()])); r = hook('deactivate'); - ok(c[0] + ': the removal reverts it as ever', r.code === 0 && disk() === sha(SRCBUF) && !fs.existsSync(BAK) && marker() && marker().action === 'revert' && ro(), + ok(c[0] + ': the removal turns it off as ever', r.code === 0 && disk() === sha(SRCBUF) && rec() === null && !armed() && marker() && marker().action === 'revert' && ro(), JSON.stringify(r.result)); headUnit.coding(7); restored(headUnit.HIGHF); ok(c[0] + ', HIGH F restored by 0.8.2: the original with our trusted backup', disk() === sha(SRCBUF) && fs.existsSync(BAK) && marker() === null); headUnit.coding(c[1], c[2]); r = hook('activate'); - ok(c[0] + ', HIGH F restored by 0.8.2: the re-apply writes nothing, the conflict, left for the next install', r.code === 0 && disk() === sha(SRCBUF) && - marker() === null && !r.result.reset && r.result.conflict === c[3] && !fs.existsSync(MARK), JSON.stringify(r.result)); + ok(c[0] + ', HIGH F restored by 0.8.2: the re-apply plans nothing, the conflict, left for the next install', r.code === 0 && disk() === sha(SRCBUF) && + marker() === null && !armed() && !r.result.reset && r.result.conflict === c[3] && !fs.existsSync(MARK), JSON.stringify(r.result)); headUnit.coding(7); r = hook('activate'); ok(c[0] + ', HIGH F restored by 0.8.2: coded 7 again, the next install applies it, on trial', r.code === 0 && r.result.reset === true && - marker() && marker().action === 'apply' && JSON.stringify(rec()) === JSON.stringify({ patched: true, proven: false, trial: true }), JSON.stringify([r.result, rec()])); + marker() && marker().action === 'apply' && JSON.stringify(trial()) === TRIAL, JSON.stringify([r.result, trial()])); try { fs.unlinkSync(MARK); } catch (e) {} headUnit.set(headUnit.HIGH); } @@ -781,45 +908,43 @@ async function main() { * has started, and a variant-7 car's pending one, keep their record; a * write that fails leaves it. */ var RECORD = TGT + '.woc-patch.json'; - function earlierRelease(pending) { + function drec() { var x = record.current(TGT); return x ? { patched: x.patched, proven: x.proven, trial: x.trial } : null; } + function earlierUnstarted(pending) { headUnit.coding(7); fresh(SRCBUF); - hook('activate'); - if (!pending) fs.unlinkSync(PENDING); + fs.linkSync(TGT, RUNNING); + earlierPatch(); + if (pending) fs.writeFileSync(PENDING, JSON.stringify({ action: 'apply' }) + '\n', { mode: 0o644 }); + else runs(RUNNING); record.write(TGT, { patched: true, proven: true }); } - var TRIAL = JSON.stringify({ patched: true, proven: false, trial: true }), PROVEN = JSON.stringify({ patched: true, proven: true, trial: undefined }); + var DTRIAL = JSON.stringify({ patched: true, proven: false, trial: true }), PROVEN = JSON.stringify({ patched: true, proven: true, trial: undefined }); [['its apply pending', true], ['carplay running the file it replaced, no marker', false]].forEach(function (c) { - earlierRelease(c[1]); + earlierUnstarted(c[1]); before = disk(); headUnit.coding(9); r = hook('activate'); ok('coding 9, an earlier release\'s patch not started (' + c[0] + '): its record on trial, carplay as it was, / read-only', r.code === 0 && disk() === before && - JSON.stringify(rec()) === TRIAL && (marker() !== null) === c[1] && ro() && /recorded on trial/.test(r.out), JSON.stringify([r.result, rec()])); + JSON.stringify(drec()) === DTRIAL && (marker() !== null) === c[1] && ro() && /recorded on trial/.test(r.out), JSON.stringify([r.result, drec()])); }); - earlierRelease(true); + earlierUnstarted(true); var recBefore = fs.readFileSync(RECORD, 'utf8'); headUnit.coding(9); fs.writeFileSync(RW_FAILS, ''); r = hook('activate'); fs.unlinkSync(RW_FAILS); - ok('coding 9, the record\'s write fails: the record as it was, exit 0', r.code === 0 && fs.readFileSync(RECORD, 'utf8') === recBefore && JSON.stringify(rec()) === PROVEN, - JSON.stringify([r.result, rec()])); - earlierRelease(true); + ok('coding 9, the record\'s write fails: the record as it was, exit 0', r.code === 0 && fs.readFileSync(RECORD, 'utf8') === recBefore && JSON.stringify(drec()) === PROVEN, + JSON.stringify([r.result, drec()])); + earlierUnstarted(true); headUnitStart(); recBefore = fs.readFileSync(RECORD, 'utf8'); headUnit.coding(9); r = hook('activate'); ok('coding 9, an earlier release\'s patch that started: its proven record untouched, the conflict', r.code === 0 && fs.readFileSync(RECORD, 'utf8') === recBefore && - r.result.conflict === 'not supported on this car (KI_KOMBI_VARIANT 9)', JSON.stringify([r.result, rec()])); - earlierRelease(true); - recBefore = fs.readFileSync(RECORD, 'utf8'); - r = hook('activate'); - ok('coding 7, an earlier release\'s patch waiting for its start: its proven record untouched', r.code === 0 && fs.readFileSync(RECORD, 'utf8') === recBefore && - marker() && marker().action === 'apply', JSON.stringify([r.result, rec()])); + r.result.conflict === 'not supported on this car (KI_KOMBI_VARIANT 9)', JSON.stringify([r.result, drec()])); headUnit.coding(7); - ok('never a systemctl, kill or reboot', calls().length === 0, calls().join('; ')); + ok('never a systemctl start, stop or restart, a kill or a reboot', changes().length === 0, changes().join('; ')); } main().catch(function (e) { ok('no exception', false, e.stack); }).then(function () { diff --git a/native/waze-on-cluster/patch/test/patchd_patch_test.js b/native/waze-on-cluster/patch/test/patchd_patch_test.js index 3eba0d0c..521ec6c8 100644 --- a/native/waze-on-cluster/patch/test/patchd_patch_test.js +++ b/native/waze-on-cluster/patch/test/patchd_patch_test.js @@ -1,21 +1,27 @@ #!/usr/bin/env node // SPDX-License-Identifier: GPL-3.0-or-later // Copyright (C) 2026 Robert Nisipeanu -/* Proves patchd's patch contract against the unit's carplay binary (CARPLAY_BIN): the - * status it reports (patched only with every edit present; a binary missing - * the self-start or the resolution edit is unknown with a reason; the - * advertised size and safe area) and how a - * changed binary takes effect. With - * carplay in both recmgr restart lists as loaded at boot and the tool's - * carplay.service drop-in loaded by systemd: SIGKILL the main PID, - * wait for it to go, systemctl start, confirm is-active (no main PID, a failed - * start or a unit that stays inactive is an error). Without that (the stock - * list, a list written after boot, or no drop-in): carplay is left running, the change waits - * for the next head-unit start and status says so. Never systemctl - * restart/stop. Runs the real patchd.js and carplay_patch.js on a temporary - * copy, with a fake systemctl, mount, recmgr list and /proc/stat, and a dummy - * process standing in for carplay. Without CARPLAY_BIN it - * skips. +/* Proves patchd's patch contract against the unit's carplay binary + * (CARPLAY_BIN). The status of a patch an earlier release wrote to the file + * (patched only with every edit present; a binary missing the self-start or + * the resolution edit is unknown with a reason; the advertised size and safe + * area). CarPlay's Patch and Remove patch buttons change the patch in memory + * (PATCH.md "In memory"): carplay on disk stays as it ships and / is never + * remounted; the plan and its record are kept and carplay's next start is + * armed (or disarmed). How the change takes effect: with carplay in both + * recmgr restart lists as loaded at boot and the tool's carplay.service + * drop-in loaded by systemd, SIGKILL the main PID, wait for it to go, + * systemctl start, confirm is-active (no main PID, a failed start or a unit + * that stays inactive is an error), then wait for the started carplay's + * memory to hold the plan. Without that (the stock list, a list written + * after boot, or no drop-in): carplay is left running, the change waits for + * the next head-unit start and status says so. A change whose bytes the + * running carplay's memory holds already needs nothing. Status reads patched + * only while the running carplay's memory holds the plan's bytes. Never + * systemctl restart/stop. Runs the real patchd.js and carplay_patch.js on a + * temporary copy, with a fake systemctl, mount, recmgr list and /proc (the + * process's exe, maps and mem: carplay_proc.js), and a dummy process + * standing in for carplay. Without CARPLAY_BIN it skips. * * node patchd_patch_test.js */ @@ -23,6 +29,7 @@ var car = require('./head_unit_env.js'); /* a HIGH head unit, coded KI_KOMBI_VARIANT 7, for every patcher and patchd this runs */ var record = require('../patch_record.js'); +var carplayProc = require('./carplay_proc.js'); var fs = require('fs'); var os = require('os'); @@ -31,6 +38,7 @@ var path = require('path'); var cp = require('child_process'); var PATCHD = path.join(__dirname, '..', 'patchd.js'); +var PATCHER = path.join(__dirname, '..', 'carplay_patch.js'); var SRC = process.env.CARPLAY_BIN || ''; var SLOT = 0x2ba4f0, SINK = 0x2a20b0, SINK_LEN = 59; var UDP_SINK = 'udp://127.0.0.1:20557?mime_type=video/H264'; @@ -56,10 +64,18 @@ var DROPIN = path.join(dir, 'carplay.service.d', '50-waze-on-cluster.conf'); var SYSTEMD = path.join(dir, 'systemd.json'); /* the fake unit: main pid, state, behaviour */ var CALLS = path.join(dir, 'systemctl.calls'); var MOUNTS = path.join(dir, 'mounts'); +var MOUNT_CALLS = path.join(dir, 'mount.calls'); var RECMGR = path.join(dir, 'recmgr-restartlist.conf'); var PROC_STAT = path.join(dir, 'stat'); +var STATE = path.join(dir, 'var'); +var RUN = path.join(dir, 'run'); /* WOC_PRELOAD_DIR: this boot's arming of carplay */ +var LIB = path.join(dir, 'libwocpatch.so'); +var PASSWD = path.join(dir, 'passwd'); +var PENDING = path.join(dir, 'sock', 'activation-pending'); var BOOT_S = Math.floor(Date.now() / 1000) - 60; /* this "boot" was a minute ago */ fs.writeFileSync(PROC_STAT, 'cpu 1 2 3\nbtime ' + BOOT_S + '\n'); +fs.writeFileSync(LIB, 'a stand-in for libwocpatch.so\n'); +fs.writeFileSync(PASSWD, 'root:x:0:0::/:/bin/sh\ncia_13002:x:13002:13002::/:/bin/false\n'); /* The restart list; loadedAtBoot dates it before the boot (recmgr read it). */ function setRecmgr(names, loadedAtBoot) { fs.writeFileSync(RECMGR, '[Whitelist]\n' + names.join('\n') + '\n[WhitelistExitSuccess]\n' + names.join('\n') + '\n'); @@ -68,24 +84,25 @@ function setRecmgr(names, loadedAtBoot) { var BIN = path.join(dir, 'bin'); fs.mkdirSync(BIN); fs.writeFileSync(CALLS, ''); +fs.writeFileSync(MOUNT_CALLS, ''); fs.writeFileSync(MOUNTS, '/dev/root / ext4 ro 0 0\n'); +/* carplay's process in a fake /proc (carplay_proc.js), as the unit's main PID. */ +var PROC = path.join(dir, 'proc'); +fs.mkdirSync(PROC); +var HELPER = path.join(__dirname, 'carplay_proc.js'); + /* The fake systemctl records each call (start also records whether the killed * PID is still alive). mode: ok | nopid (MainPID=0) | startfail | inactive * (start succeeds, the unit then reads failed); dropin: whether DropInPaths - * names the tool's drop-in. restart/stop are recorded and + * names the tool's drop-in. The unit's environment carries BMW's preload and + * its user is cia_13002. A start runs carplay from the file on disk, armed + * when this boot's env file is there. restart/stop are recorded and * otherwise do nothing; the test asserts they never occur. */ -/* carplay's process in a fake /proc: its exe holds the inode it runs. */ -var PROC = path.join(dir, 'proc'); -fs.mkdirSync(PROC); -function runs(file) { - cp.execFileSync('rm', ['-rf', path.join(PROC, '4242')]); - fs.mkdirSync(path.join(PROC, '4242')); - fs.linkSync(file, path.join(PROC, '4242', 'exe')); -} fs.writeFileSync(path.join(BIN, 'systemctl'), '#!' + process.execPath + '\n' + [ "var cp = require('child_process'), path = require('path');", - "var P = " + JSON.stringify(PROC) + ", T = " + JSON.stringify(TGT) + ";", + "var P = " + JSON.stringify(PROC) + ", T = " + JSON.stringify(TGT) + ", RUN = " + JSON.stringify(RUN) + ";", + "var proc = require(" + JSON.stringify(HELPER) + ");", "var fs = require('fs');", "var ST = " + JSON.stringify(SYSTEMD) + ";", "var st = JSON.parse(fs.readFileSync(ST, 'utf8'));", @@ -94,14 +111,15 @@ fs.writeFileSync(path.join(BIN, 'systemctl'), '#!' + process.execPath + '\n' + [ "var line = a.join(' ');", "if (a[0] === 'start') line += ' killed-pid-alive=' + alive(st.pid);", "fs.appendFileSync(" + JSON.stringify(CALLS) + ", line + '\\n');", - "function gone() { cp.execFileSync('rm', ['-rf', path.join(P, '4242')]); }", "if (a[0] === 'show' && a.indexOf('DropInPaths') >= 0) process.stdout.write('DropInPaths=/run/other.conf' + (st.dropin === false ? '' : ' ' + " + JSON.stringify(DROPIN) + ") + '\\n');", - "else if (a[0] === 'show') { if (st.mode === 'nopid') gone(); var p = st.mode === 'nopid' ? 0 : st.pid; process.stdout.write('MainPID=' + p + '\\nInvocationID=inv-' + p + '\\nExecMainStartTimestampMonotonic=5\\n'); }", + "else if (a[0] === 'show' && a.indexOf('Environment') >= 0) process.stdout.write('Environment=LD_PRELOAD=/usr/lib/libschedconfig.so.1\\n');", + "else if (a[0] === 'show' && a.indexOf('User') >= 0) process.stdout.write('User=cia_13002\\n');", + "else if (a[0] === 'show') { if (st.mode === 'nopid') proc.stop(P); var p = st.mode === 'nopid' ? 0 : st.pid; process.stdout.write('MainPID=' + p + '\\nInvocationID=inv-' + p + '\\nExecMainStartTimestampMonotonic=5\\n'); }", "else if (a[0] === 'start') {", - " if (st.mode === 'startfail') { gone(); process.stderr.write('Job for carplay.service failed.\\n'); process.exit(1); }", + " if (st.mode === 'startfail') { proc.stop(P); process.stderr.write('Job for carplay.service failed.\\n'); process.exit(1); }", " st.state = st.mode === 'inactive' ? 'failed' : 'active';", " fs.writeFileSync(ST, JSON.stringify(st));", - " cp.execFileSync('rm', ['-rf', path.join(P, '4242')]); fs.mkdirSync(path.join(P, '4242')); fs.linkSync(T, path.join(P, '4242', 'exe'));", + " proc.start(P, st.pid, T, RUN);", "} else if (a[0] === 'is-active') { process.stdout.write(st.state + '\\n'); process.exit(st.state === 'active' ? 0 : 3); }", ].join('\n') + '\n'); fs.chmodSync(path.join(BIN, 'systemctl'), 0o755); @@ -113,12 +131,13 @@ fs.writeFileSync(REBOOTS, ''); var REBOOT = path.join(BIN, 'woc-reboot'); fs.writeFileSync(REBOOT, '#!/bin/sh\necho reboot >> "' + REBOOTS + '"\n'); fs.chmodSync(REBOOT, 0o755); -/* remount,ro fails while carplay runs a file no name links any more, as the - * kernel refuses it. */ +/* Each call recorded; remount,ro fails while carplay runs a file no name + * links any more, as the kernel refuses it. */ var MOUNT = path.join(dir, 'mount'); fs.writeFileSync(MOUNT, '#!' + process.execPath + '\n' + [ "var fs = require('fs'), path = require('path');", "var a = process.argv.slice(2).join(' '), P = " + JSON.stringify(PROC) + ", M = " + JSON.stringify(MOUNTS) + ";", + "fs.appendFileSync(" + JSON.stringify(MOUNT_CALLS) + ", a + '\\n');", "if (/remount,rw/.test(a)) fs.writeFileSync(M, '/dev/root / ext4 rw 0 0\\n');", "else if (/remount,ro/.test(a)) {", " var open = fs.readdirSync(P).some(function (p) { try { return fs.statSync(path.join(P, p, 'exe')).nlink <= 1; } catch (e) { return false; } });", @@ -135,11 +154,14 @@ function dummyCarplay() { c.died = new Promise(function (r) { c.on('exit', function (code, signal) { r(signal || code); }); }); return c; } -/* What the next head-unit start leaves: carplay runs the binary on disk, - * /dev/shm is empty and nothing runs the kept link. */ +/* carplay starts (the unit's main PID) from the file on disk: armed when + * this boot's env file is there. 'patched' or 'stock'. */ +function carplayStarts() { return carplayProc.start(PROC, JSON.parse(fs.readFileSync(SYSTEMD, 'utf8')).pid, TGT, RUN); } +/* What the next head-unit start leaves: /dev/shm is empty, boot recovery + * armed the enabled patch, and carplay starts. */ function nextStart() { - [path.join(dir, 'sock', 'activation-pending'), TGT + '.woc-running'].forEach(function (f) { try { fs.unlinkSync(f); } catch (e) {} }); - runs(TGT); + try { fs.unlinkSync(PENDING); } catch (e) {} + return carplayStarts(); } function diedWithin(c) { return Promise.race([c.died, sleep(5000).then(function () { return 'still running'; })]); } function setUnit(mode, pid, dropin) { fs.writeFileSync(SYSTEMD, JSON.stringify({ mode: mode, pid: pid, state: 'active', dropin: dropin !== false })); } @@ -150,6 +172,23 @@ function newCalls() { callsSeen = all.length; return fresh; } +/* The calls that stop or start carplay, and what they depend on: not the + * reads of its main PID (for its memory) or its unit's environment and user + * (for the arming). */ +function restartCalls(calls) { + return calls.filter(function (l) { return !/^show carplay\.service -p (MainPID|Environment|User)$/.test(l); }); +} +function mountCalls() { return fs.readFileSync(MOUNT_CALLS, 'utf8').split('\n').filter(Boolean); } +function onDisk() { return fs.readFileSync(TGT); } +function inmemRecord() { try { return JSON.parse(fs.readFileSync(path.join(STATE, 'inmem-carplay.json'), 'utf8')); } catch (e) { return null; } } +function armed() { return fs.existsSync(path.join(RUN, 'carplay.env')); } +function libResult() { try { return JSON.parse(fs.readFileSync(path.join(RUN, 'carplay.result'), 'utf8')); } catch (e) { return null; } } +/* Nothing of the patch in memory: no record, no plan, nothing armed. */ +function noInmem() { + [path.join(STATE, 'inmem-carplay.json'), path.join(STATE, 'inmem-carplay.plan')].forEach(function (f) { try { fs.unlinkSync(f); } catch (e) {} }); + cp.execFileSync('rm', ['-rf', RUN]); +} +function patcher(args) { return cp.execFileSync(process.execPath, [PATCHER].concat(args), { encoding: 'utf8' }); } function edit12Only() { var b = Buffer.from(SRCBUF); @@ -164,24 +203,23 @@ function edit123Only() { return b; /* resolution immediates left stock */ } -/* A crash restart cut across a revert: with CRASH_REPLACED, carplay starts - * from the file the revert replaces, as the patcher starts; with - * CRASH_WRITTEN, from the file it wrote, as the patcher ends (before patchd - * puts its running file back). */ -var CRASH_REPLACED = path.join(dir, 'crash-replaced'), CRASH_WRITTEN = path.join(dir, 'crash-written'); +/* A crash restart cut across Remove patch: with CRASH_START, carplay starts + * again while the patcher reads its status once this boot's next start is + * disarmed. */ +var CRASH_START = path.join(dir, 'crash-start'); var CRASH_HOOK = path.join(dir, 'crash-hook.js'); fs.writeFileSync(CRASH_HOOK, [ - "var fs = require('fs'), cp = require('child_process'), path = require('path');", - "var P = " + JSON.stringify(PROC) + ", T = " + JSON.stringify(TGT) + ";", - "function start() { cp.execFileSync('rm', ['-rf', path.join(P, '4242')]); fs.mkdirSync(path.join(P, '4242')); fs.linkSync(T, path.join(P, '4242', 'exe')); }", - "function once(f) { if (!fs.existsSync(f)) return false; fs.unlinkSync(f); return true; }", - "if (/carplay_patch\\.js$/.test(process.argv[1] || '') && process.argv[2] === 'revert') {", - " if (once(" + JSON.stringify(CRASH_REPLACED) + ")) start();", - " process.on('exit', function () { if (once(" + JSON.stringify(CRASH_WRITTEN) + ")) start(); });", + "var fs = require('fs');", + "if (/carplay_patch\\.js$/.test(process.argv[1] || '') && process.argv[2] === 'status' && fs.existsSync(" + JSON.stringify(CRASH_START) + ") &&", + " !fs.existsSync(" + JSON.stringify(path.join(RUN, 'carplay.env')) + ")) {", + " fs.unlinkSync(" + JSON.stringify(CRASH_START) + ");", + " require(" + JSON.stringify(HELPER) + ").start(" + JSON.stringify(PROC) + ", JSON.parse(fs.readFileSync(" + JSON.stringify(SYSTEMD) + ", 'utf8')).pid, " + + JSON.stringify(TGT) + ", " + JSON.stringify(RUN) + ");", "}", ].join('\n') + '\n'); var SOCK = path.join(dir, 'sock', 'patch.sock'); +setUnit('ok', 0); var patchd = cp.spawn(process.execPath, [PATCHD], { env: Object.assign({}, process.env, { PATH: BIN + path.delimiter + process.env.PATH, @@ -199,7 +237,10 @@ var patchd = cp.spawn(process.execPath, [PATCHD], { WOC_DLT_RECEIVE: path.join(dir, 'no-dlt-receive'), WOC_DLT_RETRY_MS: '600000', WOC_REBOOT_CMD: REBOOT, - WOC_STATE_DIR: path.join(dir, 'var'), + WOC_STATE_DIR: STATE, + WOC_PRELOAD_DIR: RUN, + WOC_PRELOAD_LIB: LIB, + WOC_PASSWD: PASSWD, WOC_REMOUNT_LOCK: path.join(dir, 'sock', 'remount.lock'), WOC_PROC: PROC, NODE_OPTIONS: '--require=' + CRASH_HOOK, @@ -233,6 +274,8 @@ function session(cmd, done) { } function status() { return session(null, function (m) { return m.state !== 'busy'; }); } function op(cmd) { return session(cmd, function (m) { return m.state === 'error' || m.carplay === 'restarted' || m.carplay === 'deferred'; }); } +/* A command whose change needs no restart: its first status once done. */ +function settled(cmd) { return session(cmd, function (m) { return m.state !== 'busy'; }); } /* Send a command and resolve to the first reboot-reply it gets. */ function rebootCmd(cmd) { return new Promise(function (resolve, reject) { @@ -253,13 +296,13 @@ function rebootCmd(cmd) { }); } function rebootCount() { return fs.readFileSync(REBOOTS, 'utf8').split('\n').filter(Boolean).length; } -function slot() { return fs.readFileSync(TGT).slice(SLOT, SLOT + 4).toString('hex'); } async function main() { for (var i = 0; i < 200 && !fs.existsSync(SOCK); i++) await sleep(25); - var r, calls, dummy; + var r, calls, dummy, rc, res; - /* Status: patched needs every edit. */ + /* Status of a patch an earlier release wrote to the file: patched needs + * every edit. */ fs.writeFileSync(TGT, edit12Only()); r = await status(); ok('status: Edit-1/2-only binary is not patched', r.state === 'unknown' && r.mode === null, JSON.stringify(r)); @@ -269,62 +312,90 @@ async function main() { ok('status: pre-resolution binary is not patched', r.state === 'unknown' && r.mode === null && r.res === null && r.safe === null, JSON.stringify(r)); ok('status: pre-resolution binary carries the missing resolution reason', /resolution edit missing/.test(r.reason || ''), JSON.stringify(r)); fs.writeFileSync(TGT, SRCBUF); + patcher(['apply', '--target', TGT, '--panel', 'high', '--sink', UDP_SINK, '--coding', car.CODING, '--yes']); + r = await status(); + ok('status: an earlier release\'s full patch on disk is patched, res 1088x480', r.state === 'patched' && r.mode === 'udp' && r.res === '1088x480' && !r.reason, JSON.stringify(r)); + ok('status: an earlier release\'s full patch on disk carries the default safe area', r.safe === '504x368+286+72', JSON.stringify(r)); + /* The full-frame safe area (the geometry before the safe-area default): + * still patched at 1088x480, with its safe area reported for the app. */ + var patchedBuf = onDisk(); + var fullSafe = Buffer.from(patchedBuf); + Buffer.from('0000000040040000', 'hex').copy(fullSafe, 0x20ca66); + Buffer.from('e001000000000000', 'hex').copy(fullSafe, 0x20ca74); + fs.writeFileSync(TGT, fullSafe); r = await status(); - ok('status: pristine binary is original', r.state === 'original', JSON.stringify(r)); + ok('status: full-frame safe area is patched, res 1088x480, safe 1088x480+0+0', + r.state === 'patched' && r.res === '1088x480' && r.safe === '1088x480+0+0' && !r.reason, JSON.stringify(r)); + fs.writeFileSync(TGT, patchedBuf); + patcher(['revert', '--target', TGT, '--yes', '--drop-backup']); + [TGT + '.woc-orig', TGT + '.woc-orig.json', record.recordPath(TGT)].forEach(function (f) { try { fs.unlinkSync(f); } catch (e) {} }); + r = await status(); + ok('status: pristine binary is original', r.state === 'original' && onDisk().equals(SRCBUF), JSON.stringify(r)); /* reboot with nothing pending is refused and reboots nothing. */ var rb = await rebootCmd({ cmd: 'reboot' }); ok('reboot: refused when no activation is pending', rb.ok === false && /no restart is pending/.test(rb.reason || ''), JSON.stringify(rb)); ok('reboot: nothing rebooted', rebootCount() === 0); - /* carplay in both restart lists, loaded at boot: an apply restarts carplay. */ + /* carplay in both restart lists, loaded at boot: CarPlay's Patch button + * restarts carplay, whose start applies the plan in memory. */ setRecmgr(['HBAdasMgu', 'carplay'], true); dummy = dummyCarplay(); setUnit('ok', dummy.pid); + carplayStarts(); + newCalls(); r = await op({ cmd: 'apply', panel: 'high', mode: 'udp' }); calls = newCalls(); - ok('apply: patched, udp, carplay restarted', r.state === 'patched' && r.mode === 'udp' && r.panel === 'high', JSON.stringify(r)); + rc = inmemRecord(); + res = libResult(); + ok('apply: patched in memory, udp, carplay restarted', r.state === 'patched' && r.mode === 'udp' && r.panel === 'high' && r.carplay === 'restarted', JSON.stringify(r)); ok('apply: the carplay main process got SIGKILL', await diedWithin(dummy) === 'SIGKILL'); ok('apply: the killed run is recorded for boot recovery', fs.readFileSync(path.join(path.dirname(SOCK), 'carplay-killed'), 'utf8') === 'inv-' + dummy.pid + '\n'); + var rcs = restartCalls(calls); ok('apply: the drop-in checked, MainPID read, then start once it was gone, then is-active', - calls.length === 4 && calls[0] === 'show carplay.service -p DropInPaths' && - calls[1] === 'show carplay.service -p MainPID -p InvocationID -p ExecMainStartTimestampMonotonic' && - calls[2] === 'start carplay.service killed-pid-alive=false' && calls[3] === 'is-active carplay.service', JSON.stringify(calls)); - ok('apply: / is read-only again', /\bro\b/.test(fs.readFileSync(MOUNTS, 'utf8'))); + rcs.length === 4 && rcs[0] === 'show carplay.service -p DropInPaths' && + rcs[1] === 'show carplay.service -p MainPID -p InvocationID -p ExecMainStartTimestampMonotonic' && + rcs[2] === 'start carplay.service killed-pid-alive=false' && rcs[3] === 'is-active carplay.service', JSON.stringify(calls)); + ok('apply: carplay on disk as it ships, / never remounted', onDisk().equals(SRCBUF) && mountCalls().length === 0 && /\bro\b/.test(fs.readFileSync(MOUNTS, 'utf8')), + mountCalls().join('; ')); + ok('apply: the plan\'s record enabled, a first patch on trial, carplay\'s next starts armed', !!rc && rc.enabled === true && rc.trial === true && rc.proven === false && armed(), + JSON.stringify(rc)); + ok('apply: the library\'s result names the started carplay', !!res && res.pid === dummy.pid && res.applied === true, JSON.stringify(res)); r = await status(); - ok('status: fully patched binary is patched, res 1088x480', r.state === 'patched' && r.mode === 'udp' && r.res === '1088x480' && !r.reason, JSON.stringify(r)); - ok('status: fully patched binary carries the default safe area', r.safe === '504x368+286+72', JSON.stringify(r)); - /* The full-frame safe area (the geometry before the safe-area default): - * still patched at 1088x480, with its safe area reported for the app. */ - var patchedBuf = fs.readFileSync(TGT); - var fullSafe = Buffer.from(patchedBuf); - Buffer.from('0000000040040000', 'hex').copy(fullSafe, 0x20ca66); - Buffer.from('e001000000000000', 'hex').copy(fullSafe, 0x20ca74); - fs.writeFileSync(TGT, fullSafe); - r = await status(); - ok('status: full-frame safe area is patched, res 1088x480, safe 1088x480+0+0', - r.state === 'patched' && r.res === '1088x480' && r.safe === '1088x480+0+0' && !r.reason, JSON.stringify(r)); - fs.writeFileSync(TGT, patchedBuf); + ok('status: carplay\'s memory holds the plan: patched, res 1088x480', r.state === 'patched' && r.mode === 'udp' && r.res === '1088x480' && !r.reason && !r.pending && + !r.carplay, JSON.stringify(r)); + ok('status: the plan\'s default safe area', r.safe === '504x368+286+72', JSON.stringify(r)); - /* No main PID: an error, and carplay is neither started nor restarted. */ + /* No main PID: an apply that needs a restart is an error, and carplay is + * neither started nor restarted; its next start is armed. */ setUnit('nopid', 0); - r = await op({ cmd: 'revert' }); - calls = newCalls(); - ok('no main PID: revert reports the error', r.state === 'error' && /no main PID \(MainPID=0\)/.test(r.reason), JSON.stringify(r)); - ok('no main PID: only the drop-in and MainPID read', calls.length === 2 && /^show .*DropInPaths/.test(calls[0]) && /^show .*MainPID/.test(calls[1]), JSON.stringify(calls)); + r = await op({ cmd: 'apply', panel: 'high', mode: 'udp' }); + calls = restartCalls(newCalls()); + ok('no main PID: apply reports the error', r.state === 'error' && /no main PID \(MainPID=0\)/.test(r.reason), JSON.stringify(r)); + ok('no main PID: only the drop-in and MainPID read', calls.length === 2 && /^show .*DropInPaths/.test(calls[0]) && /^show .*MainPID -p InvocationID/.test(calls[1]), JSON.stringify(calls)); + ok('no main PID: carplay\'s next start is armed', armed()); + /* Remove patch with no carplay running: nothing to restart. */ + r = await settled({ cmd: 'revert' }); + rc = inmemRecord(); + ok('no main PID: Remove patch turns the patch off, nothing to restart or wait for', r.state === 'original' && !r.pending && !r.carplay && !armed() && + !!rc && rc.enabled === false && rc.by === 'user', JSON.stringify([r, rc])); + ok('no main PID: Remove patch neither starts nor kills', restartCalls(newCalls()).length === 0); /* The start fails: an error, never a restart. */ dummy = dummyCarplay(); setUnit('startfail', dummy.pid); + carplayStarts(); r = await op({ cmd: 'apply', panel: 'high', mode: 'udp' }); - calls = newCalls(); + calls = restartCalls(newCalls()); ok('start fails: apply reports the error', r.state === 'error' && /systemctl start failed/.test(r.reason), JSON.stringify(r)); ok('start fails: killed, start tried once, no is-active', calls.length === 3 && /^start /.test(calls[2]) && await diedWithin(dummy) === 'SIGKILL', JSON.stringify(calls)); - /* The unit never becomes active after start: an error after the bounded wait. */ + /* The unit never becomes active after start: an error after the bounded + * wait. carplay ran the patch (its start was armed). */ dummy = dummyCarplay(); setUnit('inactive', dummy.pid); + ok('stays inactive: carplay runs the patch', carplayStarts() === 'patched'); r = await op({ cmd: 'revert' }); calls = newCalls(); ok('stays inactive: revert reports the error', r.state === 'error' && /carplay\.service is failed after start/.test(r.reason), JSON.stringify(r)); @@ -334,139 +405,124 @@ async function main() { * would fail carplay.service and run its OnFailure=, so the change waits. */ dummy = dummyCarplay(); setUnit('ok', dummy.pid, false); + ok('no drop-in: carplay runs as it ships', carplayStarts() === 'stock'); r = await op({ cmd: 'apply', panel: 'high', mode: 'udp' }); - calls = newCalls(); - ok('no drop-in: apply defers activation', r.carplay === 'deferred' && r.state === 'unknown', JSON.stringify(r)); + calls = restartCalls(newCalls()); + ok('no drop-in: apply defers activation', r.carplay === 'deferred' && r.state === 'unknown' && r.pending === 'apply', JSON.stringify(r)); ok('no drop-in: only DropInPaths read, carplay not killed', calls.length === 1 && /DropInPaths/.test(calls[0]) && dummy.exitCode === null && dummy.signalCode === null, JSON.stringify(calls)); - fs.unlinkSync(TGT); - fs.writeFileSync(TGT, SRCBUF); - nextStart(); + ok('no drop-in: carplay on disk as it ships, its next start armed', onDisk().equals(SRCBUF) && armed()); - /* The stock list (no carplay): the binary is written, carplay keeps - * running, and the change waits for the next head-unit start. */ + /* The stock list (no carplay): the plan is armed, carplay keeps running, + * and the change waits for the next head-unit start. */ setRecmgr(['HBAdasMgu'], true); - dummy = dummyCarplay(); setUnit('ok', dummy.pid); - runs(TGT); - var runningIno = fs.statSync(TGT).ino; r = await op({ cmd: 'apply', panel: 'high', mode: 'udp' }); - calls = newCalls(); + calls = restartCalls(newCalls()); ok('stock list: apply defers activation', r.carplay === 'deferred' && r.state === 'unknown' && /takes effect at the next head-unit start/.test(r.reason || ''), JSON.stringify(r)); - ok('stock list: the binary is patched on disk', slot() === 'bcf2f7ff', slot()); + ok('stock list: carplay on disk as it ships, no link of it kept, / never remounted', onDisk().equals(SRCBUF) && !fs.existsSync(TGT + '.woc-running') && + mountCalls().length === 0, mountCalls().join('; ')); ok('stock list: carplay neither killed nor started (no systemctl call)', calls.length === 0 && dummy.exitCode === null && dummy.signalCode === null, JSON.stringify(calls)); - ok('stock list: the running binary stays linked, so / is read-only again', - fs.statSync(TGT + '.woc-running').ino === runningIno && /\bro\b/.test(fs.readFileSync(MOUNTS, 'utf8'))); r = await status(); ok('stock list: status reports the pending start, not patched', r.state === 'unknown' && r.carplay === 'deferred' && /next head-unit start/.test(r.reason || ''), JSON.stringify(r)); - - ok('stock list: the marker says apply', JSON.parse(fs.readFileSync(path.join(dir, 'sock', 'activation-pending'), 'utf8')).action === 'apply'); + ok('stock list: the marker says apply', JSON.parse(fs.readFileSync(PENDING, 'utf8')).action === 'apply'); ok('stock list: status says the apply is pending', r.pending === 'apply', JSON.stringify(r)); /* carplay in the list, but written after boot (recmgr has not read it): deferred. */ setRecmgr(['HBAdasMgu', 'carplay'], false); r = await op({ cmd: 'apply', panel: 'high', mode: 'avb' }); - calls = newCalls(); + calls = restartCalls(newCalls()); + rc = inmemRecord(); ok('list written after boot: apply defers activation', r.carplay === 'deferred' && calls.length === 0 && dummy.exitCode === null, JSON.stringify([r, calls])); - ok('list written after boot: the first running binary stays linked', fs.statSync(TGT + '.woc-running').ino === runningIno); + ok('list written after boot: the stock AVB sink\'s plan armed', !!rc && rc.args.indexOf('--sink') < 0 && rc.args.indexOf('--capture') < 0 && armed(), JSON.stringify(rc)); - /* Loaded again (a later boot in effect): the next change restarts carplay, - * clears the pending start and drops the kept binary. */ + /* Loaded again (a later boot in effect): the next change restarts carplay + * and clears the pending start. */ setRecmgr(['HBAdasMgu', 'carplay'], true); setUnit('ok', dummy.pid); r = await op({ cmd: 'apply', panel: 'mid', mode: 'udp' }); - calls = newCalls(); + calls = restartCalls(newCalls()); + res = libResult(); ok('loaded list: apply restarts carplay', r.carplay === 'restarted' && r.state === 'patched' && r.panel === 'mid' && await diedWithin(dummy) === 'SIGKILL' && calls.length === 4, JSON.stringify([r, calls])); - ok('loaded list: the kept binary is gone', !fs.existsSync(TGT + '.woc-running')); + ok('loaded list: nothing pending, the library\'s result names the started carplay', !fs.existsSync(PENDING) && !!res && res.pid === dummy.pid && res.applied === true, + JSON.stringify(res)); - /* A pending change undone before the head-unit start: the kept link, - * carplay's own file, moves back into place and nothing is pending. */ + /* A pending change undone before the head-unit start: carplay's memory + * holds the plan again, so nothing is pending. */ setRecmgr(['HBAdasMgu'], true); - var undoIno = fs.statSync(TGT).ino; r = await op({ cmd: 'apply', panel: 'high', mode: 'avb' }); ok('undo: an apply on the stock list is pending', r.carplay === 'deferred' && r.pending === 'apply', JSON.stringify(r)); - r = await session({ cmd: 'apply', panel: 'mid', mode: 'udp' }, function (m) { return m.state !== 'busy'; }); - ok('undo: the running binary\'s own file back in place leaves nothing pending', r.state === 'patched' && r.panel === 'mid' && !r.carplay && !r.pending && - fs.statSync(TGT).ino === undoIno && !fs.existsSync(TGT + '.woc-running') && - !fs.existsSync(path.join(dir, 'sock', 'activation-pending')), JSON.stringify(r)); - ok('undo: no systemctl call', newCalls().length === 0); - - /* Remove patch of a waiting patch, cut across by a crash restart. Every - * file carplay runs keeps a name, so / goes read-only again, and the - * state is the true one. */ - function held() { return ['', '.1', '.2'].filter(function (s) { return fs.existsSync(TGT + '.woc-running' + s); }); } - function exeIno() { return fs.statSync(path.join(PROC, '4242', 'exe')).ino; } - function freshStart() { fs.writeFileSync(TGT, SRCBUF); ['', '.1', '.2'].forEach(function (s) { try { fs.unlinkSync(TGT + '.woc-running' + s); } catch (e) {} }); nextStart(); } - setRecmgr(['HBAdasMgu'], true); - [TGT + '.woc-orig', TGT + '.woc-orig.json'].forEach(function (f) { try { fs.unlinkSync(f); } catch (e) {} }); - freshStart(); + r = await settled({ cmd: 'apply', panel: 'mid', mode: 'udp' }); + ok('undo: the plan carplay\'s memory holds leaves nothing pending', r.state === 'patched' && r.panel === 'mid' && r.mode === 'udp' && !r.carplay && !r.pending && + !fs.existsSync(PENDING), JSON.stringify(r)); + ok('undo: no systemctl call', restartCalls(newCalls()).length === 0); + + /* Crash restarts across a change. Remove patch disarms carplay's next + * start first, so a crash restart after that runs carplay as it ships: + * nothing waits. A crash restart while an apply waits starts armed: + * carplay runs the patch and nothing waits. */ + fs.writeFileSync(CRASH_START, ''); + r = await settled({ cmd: 'revert' }); + ok('a crash restart during Remove patch, once disarmed: carplay runs as it ships, nothing waits', !fs.existsSync(CRASH_START) && r.state === 'original' && + !r.pending && !r.carplay && !armed() && onDisk().equals(SRCBUF), JSON.stringify(r)); r = await op({ cmd: 'apply', panel: 'high', mode: 'avb' }); - var patchedIno = fs.statSync(TGT).ino; - fs.writeFileSync(CRASH_REPLACED, ''); - r = await session({ cmd: 'revert' }, function (m) { return m.state !== 'busy' && m.reason !== 'reverting'; }); - ok('crash restart from the waiting patch during its removal: the removal waits, the patch kept linked, / read-only', r.pending === 'revert' && r.carplay === 'deferred' && - r.state !== 'error' && fs.readFileSync(TGT).equals(SRCBUF) && exeIno() === patchedIno && fs.statSync(TGT + '.woc-running').ino === patchedIno && - held().length === 1 && /\bro\b/.test(fs.readFileSync(MOUNTS, 'utf8')), JSON.stringify(r) + ' ' + held().join(',')); - freshStart(); - r = await op({ cmd: 'apply', panel: 'high', mode: 'avb' }); - fs.writeFileSync(CRASH_WRITTEN, ''); - r = await session({ cmd: 'revert' }, function (m) { return m.state !== 'busy' && m.reason !== 'reverting'; }); - ok('crash restart from the reverted file before the put-back: it stays linked, nothing waits, / read-only', r.state === 'original' && !r.pending && - !r.carplay && fs.readFileSync(TGT).equals(SRCBUF) && fs.readFileSync(path.join(PROC, '4242', 'exe')).equals(SRCBUF) && - fs.statSync(TGT + '.woc-running').ino === exeIno() && fs.statSync(TGT).ino !== exeIno() && held().length === 1 && - !fs.existsSync(path.join(dir, 'sock', 'activation-pending')) && /\bro\b/.test(fs.readFileSync(MOUNTS, 'utf8')), JSON.stringify(r) + ' ' + held().join(',')); - ok('crash restarts during a removal: no systemctl call', newCalls().length === 0); - freshStart(); - - /* CarPlay's Remove patch button on what an older release patched where the locator now - * refuses a site (with its backup and record): the original back, carplay - * restarted. */ + ok('a crash restart while an apply waits: the apply waits first', r.carplay === 'deferred' && r.pending === 'apply', JSON.stringify(r)); + ok('a crash restart while an apply waits: the restarted carplay runs the patch', carplayStarts() === 'patched'); + r = await status(); + ok('a crash restart while an apply waits: status reads patched, nothing pending', r.state === 'patched' && r.mode === 'avb' && !r.pending && !r.carplay, JSON.stringify(r)); + ok('crash restarts across a change: no systemctl call', restartCalls(newCalls()).length === 0); + + /* CarPlay's Remove patch button on what an older release patched where + * the locator now refuses a site (with its backup and record, nothing in + * memory yet): the original back, carplay restarted. */ if (require('crypto').createHash('sha256').update(SRCBUF).digest('hex') === 'ddb33e33161387c6479c391684b3d019b0de54ecfcee8d6877eca94aa62f3e50') { setRecmgr(['HBAdasMgu', 'carplay'], true); var locate = require('../carplay_locate.js'), fx = require('./carplay_mutations.js')(SRCBUF).oldRelease(); for (var k = 0; k < fx.length; k++) { + noInmem(); fs.writeFileSync(TGT, fx[k].patched); fs.writeFileSync(TGT + '.woc-orig', fx[k].original); fs.writeFileSync(TGT + '.woc-orig.json', JSON.stringify({ buildId: locate.buildId(fx[k].original), sha256_original: require('crypto').createHash('sha256').update(fx[k].original).digest('hex') })); dummy = dummyCarplay(); setUnit('ok', dummy.pid); + carplayStarts(); r = await op({ cmd: 'revert' }); - ok(fx[k].name + ': CarPlay\'s Remove patch button restores the original, carplay restarted', r.carplay === 'restarted' && fs.readFileSync(TGT).equals(fx[k].original) && + ok(fx[k].name + ': CarPlay\'s Remove patch button restores the original, carplay restarted', r.carplay === 'restarted' && onDisk().equals(fx[k].original) && /\bro\b/.test(fs.readFileSync(MOUNTS, 'utf8')), JSON.stringify(r)); newCalls(); } fs.writeFileSync(TGT, SRCBUF); - [TGT + '.woc-orig', TGT + '.woc-orig.json'].forEach(function (f) { try { fs.unlinkSync(f); } catch (e) {} }); + [TGT + '.woc-orig', TGT + '.woc-orig.json', TGT + '.woc-running', record.recordPath(TGT)].forEach(function (f) { try { fs.unlinkSync(f); } catch (e) {} }); } /* CarPlay's Patch button on a car coded otherwise than KI_KOMBI_VARIANT * 7, or whose coding cannot be read: patchd reports the conflict as * Android Auto does, the button still patches, and the patch is recorded - * unproven (boot recovery restores it after one failed start). On a + * unproven (boot recovery turns it off after one failed start). On a * variant-7 car the first patch is on trial. */ setRecmgr(['HBAdasMgu'], true); var cases = [[9, undefined, 'not supported on this car (KI_KOMBI_VARIANT 9)'], [7, 0x0b, 'cluster coding unreadable'], [null, undefined, 'cluster coding unreadable'], [7, undefined, null]]; for (var q = 0; q < cases.length; q++) { var cq = cases[q], what = cq[0] === null ? 'no coding' : 'coding ' + cq[0] + (cq[1] !== undefined ? ' flags 0x' + cq[1].toString(16) : ''); - [TGT + '.woc-orig', TGT + '.woc-orig.json', record.recordPath(TGT)].forEach(function (f) { try { fs.unlinkSync(f); } catch (e) {} }); - freshStart(); + noInmem(); + nextStart(); car.coding(cq[0], cq[1]); r = await status(); ok(what + ': patchd reports ' + (cq[2] || 'no conflict'), r.state === 'original' && (r.conflict || null) === cq[2], JSON.stringify(r)); r = await op({ cmd: 'apply', panel: 'high', mode: 'avb' }); - var rc = record.current(TGT); + rc = inmemRecord(); /* on trial unless the coding reads another variant */ var onTrial = cq[0] !== 9; - ok(what + ': CarPlay\'s Patch button patches it, recorded ' + (onTrial ? 'on trial' : 'unproven'), r.carplay === 'deferred' && slot() === 'bcf2f7ff' && !!rc && - rc.patched === true && rc.proven === false && (rc.trial === true) === onTrial, JSON.stringify([r, rc])); + ok(what + ': CarPlay\'s Patch button patches it in memory, recorded ' + (onTrial ? 'on trial' : 'unproven'), r.carplay === 'deferred' && onDisk().equals(SRCBUF) && + !!rc && rc.enabled === true && rc.proven === false && (rc.trial === true) === onTrial && armed(), JSON.stringify([r, rc])); nextStart(); r = await status(); ok(what + ': after the start it reads patched, the conflict still named', r.state === 'patched' && (r.conflict || null) === cq[2], JSON.stringify(r)); car.coding(7); } - [TGT + '.woc-orig', TGT + '.woc-orig.json', record.recordPath(TGT)].forEach(function (f) { try { fs.unlinkSync(f); } catch (e) {} }); - freshStart(); + noInmem(); + nextStart(); newCalls(); /* reboot with a pending activation: one head-unit restart. A second @@ -476,6 +532,7 @@ async function main() { setRecmgr(['HBAdasMgu'], true); dummy = dummyCarplay(); setUnit('ok', dummy.pid); + carplayStarts(); r = await op({ cmd: 'apply', panel: 'high', mode: 'avb' }); ok('reboot setup: a deferred patch is pending', r.carplay === 'deferred', JSON.stringify(r)); newCalls(); /* drain; the reboot must add no systemctl call */ @@ -488,7 +545,7 @@ async function main() { ok('reboot: still only one restart asked for', rebootCount() === 1); r = await session({ cmd: 'apply', panel: 'high', mode: 'avb' }, function (m) { return m.ev === 'refused' || m.state === 'error'; }); ok('reboot: apply refused while a restart is in progress', r.ev === 'refused' && /restart is in progress/.test(r.reason || ''), JSON.stringify(r)); - ok('reboot: no systemctl call (carplay not stopped or restarted)', newCalls().length === 0, 'unexpected systemctl calls'); + ok('reboot: no systemctl call (carplay not stopped or restarted)', restartCalls(newCalls()).length === 0, 'unexpected systemctl calls'); var all = fs.readFileSync(CALLS, 'utf8'); ok('never systemctl restart or stop', !/^(restart|stop|try-restart|reload-or-restart)\b/m.test(all), all); diff --git a/native/waze-on-cluster/patch/test/patchd_reboot_test.js b/native/waze-on-cluster/patch/test/patchd_reboot_test.js index c2804eff..a9f8f66c 100644 --- a/native/waze-on-cluster/patch/test/patchd_reboot_test.js +++ b/native/waze-on-cluster/patch/test/patchd_reboot_test.js @@ -36,11 +36,12 @@ process.on('exit', function () { }); /* A unit with a pending change (CarPlay's, or the marker `marker` names); - * nsm_control answers as `mode` says. */ + * nsm_control answers as `mode` says; systemctl gives carplay's main PID + * (4242 while /proc/4242 is there). */ function unit(waitMs, marker) { var d = fs.mkdtempSync(path.join(os.tmpdir(), 'woc-rb-')); dirs.push(d); - ['shm', 'var', 'bin', 'units'].forEach(function (x) { fs.mkdirSync(path.join(d, x)); }); + ['shm', 'var', 'bin', 'units', 'proc'].forEach(function (x) { fs.mkdirSync(path.join(d, x)); }); var t = { d: d, calls: path.join(d, 'calls'), mode: path.join(d, 'mode'), sock: path.join(d, 'shm', 'patch.sock') }; fs.writeFileSync(t.calls, ''); fs.writeFileSync(path.join(d, 'carplay'), 'not a carplay build\n'); @@ -54,6 +55,10 @@ function unit(waitMs, marker) { 'exit) echo "nsm_control: cannot reach NSM" >&2; exit 3;;\n' + '*) echo "[Info. request sent]";;\nesac\n'); fs.chmodSync(nsm, 0o755); + var sc = path.join(d, 'bin', 'systemctl'); + fs.writeFileSync(sc, '#!/bin/sh\ncase "$*" in *MainPID*) if [ -d "' + path.join(d, 'proc', '4242') + '" ]; then echo MainPID=4242; else echo MainPID=0; fi;; esac\n'); + fs.chmodSync(sc, 0o755); + fs.writeFileSync(path.join(d, 'lib'), 'a stand-in for libwocpatch.so\n'); t.env = Object.assign({}, process.env, { PATH: path.join(d, 'bin') + path.delimiter + process.env.PATH, WOC_PATCH_SOCK: t.sock, WOC_CARPLAY: path.join(d, 'carplay'), WOC_AAPD: path.join(d, 'none'), @@ -61,7 +66,8 @@ function unit(waitMs, marker) { WOC_MOUNT: '/usr/bin/true', WOC_UNIT_DIRS: path.join(d, 'units'), WOC_CAPTURE_SOCK: path.join(d, 'none.sock'), WOC_DLT_RECEIVE: path.join(d, 'none'), WOC_DLT_RETRY_MS: '600000', WOC_REMOUNT_LOCK: path.join(d, 'shm', 'remount.lock'), WOC_STATE_DIR: path.join(d, 'var'), WOC_REBOOT_CMD: nsm + ' --requestRestart 7 --normal', - WOC_REBOOT_WAIT_MS: String(waitMs || 600000), WOC_BOOT_ID: path.join(d, 'boot_id'), WOC_PROC_STAT: path.join(d, 'stat') + WOC_REBOOT_WAIT_MS: String(waitMs || 600000), WOC_BOOT_ID: path.join(d, 'boot_id'), WOC_PROC_STAT: path.join(d, 'stat'), + WOC_PRELOAD_DIR: path.join(d, 'run'), WOC_PRELOAD_LIB: path.join(d, 'lib'), WOC_PASSWD: path.join(d, 'none'), WOC_PROC: path.join(d, 'proc') }); return t; } @@ -104,6 +110,22 @@ function daemon(t) { }); } +/* t's carplay runs a patch in memory: the plan (one edit at 0x4) and its + * record, and carplay's process (4242) holding the plan's bytes at the base + * of its mapping of the stand-in file. */ +function inMemory(t) { + var target = path.join(t.d, 'carplay'), plan = 'wocplan 1\nbuild-id 00\nedit variant 4 61 62\nend 1\n', st = fs.statSync(target); + fs.writeFileSync(path.join(t.d, 'var', 'inmem-carplay.plan'), plan); + fs.writeFileSync(path.join(t.d, 'var', 'inmem-carplay.json'), JSON.stringify({ v: 1, enabled: true, target: target, ino: st.ino, size: st.size, + mtime: st.mtime.getTime(), planSha256: require('crypto').createHash('sha256').update(plan).digest('hex'), args: [], proven: false, trial: true }) + '\n'); + var pd = path.join(t.d, 'proc', '4242'); + fs.mkdirSync(pd); + fs.writeFileSync(path.join(pd, 'maps'), '00001000-00002000 r-xp 00000000 fd:00 ' + st.ino + ' /usr/bin/carplay\n'); + var mem = Buffer.alloc(0x1000 + 8); + mem[0x1004] = 0x62; + fs.writeFileSync(path.join(pd, 'mem'), mem); +} + function calls(t) { return fs.readFileSync(t.calls, 'utf8').split('\n').filter(Boolean); } function reply(m) { return m.ev === 'reboot-reply'; } function refused(m) { return m.ev === 'reboot-reply' && m.ok === false; } @@ -205,14 +227,16 @@ async function main() { rb = await pk2.next(reply); ok('an older patchd\'s marker without a boot id is kept: the restart it waits for is taken', rb.ok === true && fs.existsSync(aam), JSON.stringify(rb)); - /* a marker patchd writes carries this boot's id: the removal rewrites a - * pending revert as its own */ + /* a marker patchd writes carries this boot's id: the removal of a patch + * the running carplay holds in memory leaves a revert pending, its own */ var w = unit(0); var wm = path.join(w.d, 'shm', 'activation-pending'); fs.writeFileSync(wm, JSON.stringify({ action: 'revert' }) + '\n'); + inMemory(w); var hr = cp.spawnSync(process.execPath, [PATCHD, 'deactivate'], { env: w.env, encoding: 'utf8', timeout: 60000 }); var written = JSON.parse(fs.readFileSync(wm, 'utf8')); - ok('writePending stamps the boot id', written.boot === 'boot-2' && written.by === 'removal' && written.action === 'revert', + ok('writePending stamps the boot id', written.boot === 'boot-2' && written.by === 'removal' && written.action === 'revert' && + !fs.existsSync(path.join(w.d, 'var', 'inmem-carplay.json')), JSON.stringify(written) + ' ' + hr.stdout + hr.stderr); process.stdout.write(fails ? fails + ' failed\n' : 'all passed\n'); diff --git a/native/waze-on-cluster/patch/test/recovery_test.js b/native/waze-on-cluster/patch/test/recovery_test.js index b18c5152..7e28b7af 100644 --- a/native/waze-on-cluster/patch/test/recovery_test.js +++ b/native/waze-on-cluster/patch/test/recovery_test.js @@ -1128,7 +1128,7 @@ test('the boot step restores a patch at once when it cannot save the boot\'s rec for (const kind of ['unproven', 'original']) { const w = makeWorld(); w.install('carplay', kind); - fs.mkdirSync(w.T.carplay.state + '.tmp'); /* the temporary file's name is taken */ + fs.mkdirSync(w.T.carplay.state + '.tmp.' + process.pid); /* the temporary file's name is taken */ const r = await startBoot(w.recovery('carplay', 'A', { restore: (f, cb) => recovery.restoreTarget(w.T.carplay, true, f, cb, 1000) })); assert.strictEqual(r.action, kind === 'original' ? 'idle' : 'restored', kind); assert.strictEqual(w.holds('carplay'), 'original', kind); @@ -1266,7 +1266,7 @@ test('an unwritable state file restores a patch at its first crash, and does not const w = makeWorld({ recmgr: true }); w.install('carplay', 'proven'); const { watcher } = await bootUp(w, 'A'); - fs.mkdirSync(w.T.carplay.state + '.tmp'); + fs.mkdirSync(w.T.carplay.state + '.tmp.' + process.pid); w.svc.carplay.crashes(); w.now.advance(5000); const r = await tick(watcher); @@ -1410,10 +1410,10 @@ test('a save that fails leaves the previous state whole; a folder that cannot be const w = makeWorld(); const before = JSON.stringify({ fails: 1, unknown: 0, arm: { boot: 'A', patch: 'proven', crashes: 1, confirmed: false, clean: false } }) + '\n'; fs.writeFileSync(w.T.carplay.state, before); - fs.mkdirSync(w.T.carplay.state + '.tmp'); + fs.mkdirSync(w.T.carplay.state + '.tmp.' + process.pid); assert.strictEqual(w.recovery('carplay', 'B')._save({ fails: 0, arm: null }), false); assert.strictEqual(fs.readFileSync(w.T.carplay.state, 'utf8'), before); - fs.rmdirSync(w.T.carplay.state + '.tmp'); + fs.rmdirSync(w.T.carplay.state + '.tmp.' + process.pid); fs.chmodSync(path.dirname(w.T.carplay.state), 0o300); try { assert.strictEqual(w.recovery('carplay', 'B')._save({ fails: 2, arm: null }), true); } finally { fs.chmodSync(path.dirname(w.T.carplay.state), 0o700); } assert.strictEqual(w.state('carplay').fails, 2); diff --git a/native/waze-on-cluster/patch/test/rollback_test.js b/native/waze-on-cluster/patch/test/rollback_test.js index 1277ce94..bdc38f97 100644 --- a/native/waze-on-cluster/patch/test/rollback_test.js +++ b/native/waze-on-cluster/patch/test/rollback_test.js @@ -394,6 +394,50 @@ REPS.forEach(function (p) { }); })(); +/* 6. The patch in memory (PATCH.md "In memory"): this version leaves + * carplay stock on disk with a plan and a record on /var/opt, which no + * release reads. Each release then meets a stock carplay with no backup: + * its crash loop and Remove patch leave it stock, and its activate writes + * its own patch, as on a car it is installed on first. That patch is + * another file than the record describes, so this version's boot recovery + * never arms the plan over it and restores it as its own (stock), and its + * deactivate reverts it. */ +(function () { + var SD = path.join(W, 'var'); + fs.mkdirSync(SD, { recursive: true }); + var IENV = Object.assign({}, ENV, { WOC_STATE_DIR: SD, WOC_PRELOAD_DIR: path.join(W, 'run'), WOC_CODING: car.CODING }); + function inmemKind() { + var r = cp.spawnSync(process.execPath, ['-e', 'console.log(String(require(process.argv[1]).kind("carplay")))', path.join(NEW, 'inmem.js')], { encoding: 'utf8', env: IENV }); + return (r.stdout || '').trim(); + } + function makePlan() { + var r = cp.spawnSync(process.execPath, ['-e', 'require(process.argv[1]).makePlan("carplay", ["--panel", "high", "--coding", process.argv[2]].concat(process.argv[3] ? ["--unproven"] : []), 60000, function (e) { console.log(e ? "ERR " + e.message : "OK"); })', + path.join(NEW, 'inmem.js'), car.CODING, BIN ? '' : '1'], { encoding: 'utf8', env: IENV }); + return (r.stdout || '').trim(); + } + clear(); fs.writeFileSync(TGT, STOCK, { mode: 0o755 }); + var mp = makePlan(); + ok('this version plans the patch in memory over stock carplay, writing nothing to it', mp === 'OK' && fs.readFileSync(TGT).equals(STOCK) && inmemKind() !== 'null', mp); + var inmemState = snapshot(); + /* Each case starts from carplay as this version leaves it, its record + * describing that very file (planned again after the file is put). */ + function fresh() { put(inmemState); return makePlan() === 'OK' && inmemKind() !== 'null'; } + RELEASES.concat(['this']).forEach(function (v) { + var vd = relDir(v), g = relGroup(v), live = true; + live = fresh() && live; var rec = recover(vd, g), recH = holds(), recKind = inmemKind(); + live = fresh() && live; r = removePatch(vd); var rmH = r.code ? 'refused-' + holds() : holds(), rmKind = inmemKind(); + live = fresh() && live; r = apply(vd); var apH = r.code === 0 ? holds() : 'failed'; + var kind = inmemKind(); + var thisRec = recover(NEW, 'N'), backH = holds(); + live = fresh() && live; apply(vd); r = uninstall(NEW); var unH = r.code ? 'refused' : holds(); + ok(v + ' (' + g + ') over the patch in memory: a crash loop and Remove patch leave carplay stock and the plan armable, its activate patches the file; ' + + 'this version then arms nothing over that patch and restores or removes it to stock', + live && recH === 'stock' && recKind !== 'null' && (rmH === 'stock' || rmH === 'refused-stock') && rmKind !== 'null' && + apH === 'patched' && kind === 'null' && backH === 'stock' && unH === 'stock', + [live, rec, recH, recKind, rmH, rmKind, apH, kind, thisRec, backH, unH].join(' ')); + }); +})(); + process.stdout.write('\nA release over this version\'s full patch with no deactivate between (part 3):\n'); table.forEach(function (row) { process.stdout.write(' ' + (row.v + ' (' + row.g + ') ').slice(0, 14) + ' crash loop: ' + row.recovery + '; Remove patch: ' + row.remove + diff --git a/native/waze-on-cluster/preload/test/preload_test.sh b/native/waze-on-cluster/preload/test/preload_test.sh new file mode 100755 index 00000000..d4fb1646 --- /dev/null +++ b/native/waze-on-cluster/preload/test/preload_test.sh @@ -0,0 +1,90 @@ +#!/bin/sh +# SPDX-License-Identifier: GPL-3.0-or-later +# Copyright (C) 2026 Robert Nisipeanu +# libwocpatch.so against a test program (target.c): all or nothing, only the +# plan's program, the result file. Run by `make test-preload` in the unit's +# toolchain image: preload_test.sh +set -eu +LIB=$1 BIN=$2 W=$3 +mkdir -p "$W" +fails=0 +ok() { echo "ok: $*"; } +bad() { echo "FAIL: $*"; fails=$((fails + 1)); } +id=$(readelf -n "$BIN" | sed -n 's/.*Build ID: *\([0-9a-f]*\).*/\1/p') +set -- $("$BIN" dump) +mva=$2 mstock=$3; ava=$5 astock=$6 +mpatched=$(printf 'patched message' | od -An -tx1 | tr -d ' \n')00 +apatched=2a000000 +plan() { # plan [extra line] + { echo "wocplan 1"; echo "build-id $2" + echo "edit message $mva $mstock $mpatched"; echo "edit answer $ava $3 $apatched" + [ -n "${4:-}" ] && echo "$4"; echo "end ${5:-2}"; } > "$1" +} +run() { # run -> stdout of the target; result in $W/result + : > "$W/result" + WOC_PATCH_PLAN=$1 WOC_PATCH_RESULT=$W/result LD_PRELOAD=$LIB "$BIN" 2> "$W/err" +} +stock="stock message!! 41414141" + +plan "$W/p1" "$id" "$astock" +out=$(run "$W/p1") +[ "$out" = "patched message 2a +child" ] && ok "the plan's edits in .rodata and .text applied" || bad "applied: got '$out' $(cat "$W/err")" +grep -q '"applied":true,.*"edits":\["message","answer"\]' "$W/result" && ok "result: applied, both edits" || bad "result: $(cat "$W/result")" +grep -q '"pid":[1-9][0-9]*,' "$W/result" && grep -q 'applied 2 edits in memory' "$W/err" && ok "stderr says so" || bad "stderr: $(cat "$W/err")" + +plan "$W/p2" 0000000000000000000000000000000000000000 "$astock" +out=$(run "$W/p2") +[ "$out" = "$stock +child" ] && [ ! -s "$W/result" ] && [ ! -s "$W/err" ] && ok "another program's plan: nothing, no result" || bad "other build: '$out' result '$(cat "$W/result")'" + +plan "$W/p3" "$id" 00000000 +out=$(run "$W/p3") +[ "$(echo "$out" | head -1)" = "$stock" ] && grep -q '"applied":false' "$W/result" && grep -q 'answer at .* does not read as' "$W/result" \ + && ok "one site not stock: nothing applied (the other site stays stock)" || bad "mismatch: '$out' $(cat "$W/result")" + +plan "$W/p4" "$id" "$astock"; head -c -6 "$W/p4" > "$W/p4c" +out=$(run "$W/p4c") +[ "$(echo "$out" | head -1)" = "$stock" ] && [ ! -s "$W/result" ] && grep -q 'cut short\|not ended' "$W/err" && ok "a plan cut short: nothing, said on stderr, no result" || bad "cut short: $(cat "$W/result" "$W/err")" + +plan "$W/p5" "$id" "$astock" "hook answer 1000 x" +out=$(run "$W/p5") +[ "$(echo "$out" | head -1)" = "$stock" ] && grep -q 'unknown line kind' "$W/err" && ok "a kind this library does not know: nothing" || bad "unknown kind: $(cat "$W/result")" + +plan "$W/p6" "$id" "$astock" "" 3 +out=$(run "$W/p6") +[ "$(echo "$out" | head -1)" = "$stock" ] && grep -q 'its end says 3' "$W/err" && ok "an edit count that does not match: nothing" || bad "count: $(cat "$W/result")" + +{ echo "wocplan 1"; echo "build-id $id"; echo "edit far ffffff00 00 01"; echo "end 1"; } > "$W/p7" +out=$(run "$W/p7") +[ "$(echo "$out" | head -1)" = "$stock" ] && grep -q 'not in a loaded part' "$W/result" && ok "an address outside the program: nothing" || bad "outside: $(cat "$W/result")" + +out=$(WOC_PATCH_PLAN=$W/none WOC_PATCH_RESULT=$W/result LD_PRELOAD=$LIB "$BIN" 2>/dev/null) +[ "$(echo "$out" | head -1)" = "$stock" ] && ok "no plan file: stock" || bad "no plan: $out" + +out=$(LD_PRELOAD=$LIB "$BIN" 2>&1) +[ "$out" = "$stock +child" ] && ok "no WOC_PATCH_PLAN: stock, silent" || bad "unarmed: $out" + +# Another library's thread, started before ours (libdlt's in carplay): applied. +THR=$(dirname "$BIN")/libthread.so +: > "$W/result" +out=$(WOC_PATCH_PLAN=$W/p1 WOC_PATCH_RESULT=$W/result LD_PRELOAD="$LIB $THR" "$BIN" 2>/dev/null) +[ "$(echo "$out" | head -1)" = "patched message 2a" ] && grep -q '"applied":true,"threads":2' "$W/result" \ + && ok "a thread another library started: applied, code pages kept executable" || bad "with a thread: '$out' $(cat "$W/result")" + +# The test build that aborts once it has applied: the process ends with SIGABRT +# (an armed start that crashes, which boot recovery counts). +CRASH=$(dirname "$LIB")/libwocpatch-crash.so +: > "$W/result" +WOC_PATCH_PLAN=$W/p1 WOC_PATCH_RESULT=$W/result LD_PRELOAD=$CRASH "$BIN" >/dev/null 2>&1 && rc=0 || rc=$? +[ "$rc" -eq 134 ] && grep -q '"applied":true' "$W/result" && ok "the crash test build applies, then aborts" || bad "crash build: rc $rc $(cat "$W/result")" + +# The result file is never created by the library. +rm -f "$W/result" +WOC_PATCH_PLAN=$W/p1 WOC_PATCH_RESULT=$W/result LD_PRELOAD=$LIB "$BIN" >/dev/null 2>&1 +[ ! -e "$W/result" ] && ok "a missing result file is not created" || bad "result created" + +# Only the linker's own symbols (_init, _fini, the section bounds). +nm -D --defined-only "$LIB" | grep -v -E ' (__bss_start|_edata|_end|_init|_fini)$' | grep -q . && bad "exports: $(nm -D --defined-only "$LIB")" || ok "exports nothing" +[ $fails -eq 0 ] && echo "preload_test: all passed" || { echo "preload_test: $fails failed"; exit 1; } diff --git a/native/waze-on-cluster/preload/test/target.c b/native/waze-on-cluster/preload/test/target.c new file mode 100644 index 00000000..9a7b6f0c --- /dev/null +++ b/native/waze-on-cluster/preload/test/target.c @@ -0,0 +1,43 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Copyright (C) 2026 Robert Nisipeanu +/* The program preload_test.sh preloads libwocpatch.so into: a PIE with a + * string in .rodata and a function whose immediate is in .text. + * target dump the two sites as " " + * target " ", then the same from a child + * (sh -c), which inherits LD_PRELOAD */ +#define _GNU_SOURCE +#include +#include +#include +#include + +const char message[16] __attribute__((aligned(16))) = "stock message!!"; +__attribute__((noinline)) int answer(void) { return 0x41414141; } + +static int base_of(struct dl_phdr_info *info, size_t size, void *data) { + (void)size; + *(ElfW(Addr) *)data = info->dlpi_addr; + return 1; +} + +static void dump(const char *name, const void *at, size_t len, ElfW(Addr) base) { + printf("%s %lx ", name, (unsigned long)((ElfW(Addr))at - base)); + for (size_t i = 0; i < len; i++) printf("%02x", ((const unsigned char *)at)[i]); + printf("\n"); +} + +int main(int argc, char **argv) { + ElfW(Addr) base = 0; + dl_iterate_phdr(base_of, &base); + if (argc > 1 && strcmp(argv[1], "dump") == 0) { + dump("message", message, sizeof message, base); + /* the 4-byte immediate of answer()'s mov eax,imm32 */ + const unsigned char *f = (const unsigned char *)answer; + for (int i = 0; i < 16; i++) if (f[i] == 0xb8) { dump("answer", f + i + 1, 4, base); break; } + return 0; + } + printf("%s %x\n", message, answer()); + fflush(stdout); + if (argc == 1) return system("echo child"); + return 0; +} diff --git a/native/waze-on-cluster/preload/test/thread.c b/native/waze-on-cluster/preload/test/thread.c new file mode 100644 index 00000000..e7685c3e --- /dev/null +++ b/native/waze-on-cluster/preload/test/thread.c @@ -0,0 +1,13 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Copyright (C) 2026 Robert Nisipeanu +/* A library whose constructor starts a thread before libwocpatch.so's runs, + * as libdlt's does in carplay. */ +#include +#include + +static void *spin(void *arg) { (void)arg; for (;;) usleep(1000); return 0; } + +__attribute__((constructor)) static void start(void) { + pthread_t t; + pthread_create(&t, 0, spin, 0); +} diff --git a/native/waze-on-cluster/preload/wocpatch.c b/native/waze-on-cluster/preload/wocpatch.c new file mode 100644 index 00000000..fa3969fc --- /dev/null +++ b/native/waze-on-cluster/preload/wocpatch.c @@ -0,0 +1,446 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Copyright (C) 2026 Robert Nisipeanu +/* libwocpatch.so: applies waze-on-cluster's carplay edits to the running + * process's memory, before carplay's own code runs. The file on disk is + * never written (PATCH.md "In memory"). + * + * carplay.service loads it with LD_PRELOAD only when the boot step armed + * this start: it wrote /run/woc-preload/carplay.env, which the tool's + * drop-in names with EnvironmentFile=-, so without that file carplay starts + * as it ships. The env names the plan (WOC_PATCH_PLAN) and the result file + * (WOC_PATCH_RESULT). + * + * The plan is made by carplay_patch.js plan, as root, from the binary on + * disk with the patcher's own locator and checks: the build-id, and one + * line per edit region with its address, the bytes the build ships there + * and the bytes to write. This library finds nothing by itself. It applies + * every edit or none: + * + * - the main program's GNU build-id must be the plan's: any other program + * (one carplay starts, inheriting LD_PRELOAD) is left alone and writes + * no result; + * - the plan must be whole (a known version, every line well formed, its + * closing line with the edit count) and hold only kinds this library + * knows; + * - every region must lie in one PT_LOAD of the main program, inside its + * file-backed part and outside PT_GNU_RELRO, and read exactly its stock + * bytes. + * + * A plan that cannot be read or parsed names no program: it is reported on + * stderr only, and the result file is left as it is. + * Then each page is made writable, the bytes written, the page given its + * segment's protection back, and every region read back. A code page stays + * executable while it is written (read, write and execute for that + * moment): libraries' constructors start threads before this one runs + * (libdlt's dlt_receiver and dlt_segmented in carplay), and a page they + * might run must never lose execute. None of them runs carplay's own code + * yet: its constructors and main have not run, and the edits are in that + * code and its read-only data. A failure before + * any write changes nothing; one after (an mprotect refused) makes every + * page writable again, writes the stock bytes back and restores the + * protections. Only a page that cannot get its protection back ends the + * process (abort), which boot recovery counts as a crash of an armed + * start. The result, applied or not and why, goes to WOC_PATCH_RESULT (a + * file the boot step created for carplay's user; never created here) and + * to stderr, the journal. + * + * Built with the unit's toolchain (gcc 7.5, glibc 2.27). Exports nothing. + */ +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define PLAN_MAX (32 * 1024) +#define EDITS_MAX 32 +#define BYTES_MAX 128 +#define NAME_MAX_ 32 +#define ID_MAX 64 +#define PAGES_MAX (EDITS_MAX * 2) + +struct edit { + char name[NAME_MAX_]; + uintptr_t vaddr; + size_t len; + unsigned char stock[BYTES_MAX]; + unsigned char patched[BYTES_MAX]; + unsigned char *at; + int prot; /* the segment's protection */ +}; + +struct plan { + unsigned char build_id[ID_MAX]; + size_t build_id_len; + struct edit edits[EDITS_MAX]; + int n; +}; + +struct image { + uintptr_t base; + const ElfW(Phdr) *phdr; + int phnum; + int found; +}; + +static struct plan plan; +static char why[256]; + +static void because(const char *fmt, ...) { + va_list ap; + va_start(ap, fmt); + vsnprintf(why, sizeof why, fmt, ap); + va_end(ap); +} + +/* The main program is the first object dl_iterate_phdr reports. */ +static int first_object(struct dl_phdr_info *info, size_t size, void *data) { + struct image *img = data; + (void)size; + img->base = info->dlpi_addr; + img->phdr = info->dlpi_phdr; + img->phnum = info->dlpi_phnum; + img->found = 1; + return 1; +} + +/* The main program's GNU build-id, from its PT_NOTE segments in memory. */ +static int build_id(const struct image *img, const unsigned char **id, size_t *len) { + for (int i = 0; i < img->phnum; i++) { + const ElfW(Phdr) *p = &img->phdr[i]; + if (p->p_type != PT_NOTE) continue; + const unsigned char *at = (const unsigned char *)(img->base + p->p_vaddr), *end = at + p->p_memsz; + while (at + sizeof(ElfW(Nhdr)) <= end) { + const ElfW(Nhdr) *nh = (const ElfW(Nhdr) *)at; + size_t name = (nh->n_namesz + 3) & ~(size_t)3, desc = (nh->n_descsz + 3) & ~(size_t)3; + const unsigned char *n = at + sizeof *nh, *d = n + name; + if (d + desc > end) break; + if (nh->n_type == NT_GNU_BUILD_ID && nh->n_namesz == 4 && memcmp(n, "GNU", 4) == 0) { + *id = d; + *len = nh->n_descsz; + return 0; + } + at = d + desc; + } + } + return -1; +} + +static int hexval(int c) { + if (c >= '0' && c <= '9') return c - '0'; + if (c >= 'a' && c <= 'f') return c - 'a' + 10; + return -1; +} + +/* Lowercase hex of exactly 2*max bytes or fewer; returns the byte count, -1 when malformed. */ +static long unhex(const char *s, size_t slen, unsigned char *out, size_t max) { + if (slen == 0 || slen % 2 || slen / 2 > max) return -1; + for (size_t i = 0; i < slen; i += 2) { + int hi = hexval((unsigned char)s[i]), lo = hexval((unsigned char)s[i + 1]); + if (hi < 0 || lo < 0) return -1; + out[i / 2] = (unsigned char)(hi << 4 | lo); + } + return (long)(slen / 2); +} + +/* The next space-separated field of a line, or NULL. */ +static const char *field(const char **at, const char *end, size_t *len) { + const char *s = *at; + while (s < end && *s == ' ') s++; + if (s >= end) return NULL; + const char *e = s; + while (e < end && *e != ' ') e++; + *len = (size_t)(e - s); + *at = e; + return s; +} + +static int is(const char *s, size_t len, const char *word) { return len == strlen(word) && memcmp(s, word, len) == 0; } + +/* The plan (carplay_patch.js plan, "wocplan 1"): + * wocplan 1 + * build-id + * edit (one per region) + * end + * Any other line, kind or version refuses the plan. */ +static int parse_plan(const char *text, size_t size) { + const char *at = text, *end = text + size; + int lines = 0, ended = 0; + memset(&plan, 0, sizeof plan); + while (at < end) { + const char *nl = memchr(at, '\n', (size_t)(end - at)); + if (!nl) { because("plan: last line not ended"); return -1; } + const char *p = at; + size_t l1 = 0, l2 = 0, l3 = 0, l4 = 0, l5 = 0; + const char *k = field(&p, nl, &l1); + at = nl + 1; + if (ended) { because("plan: lines after its end"); return -1; } + if (!k) { because("plan: empty line"); return -1; } + if (lines++ == 0) { + const char *v = field(&p, nl, &l2); + if (!is(k, l1, "wocplan") || !v || !is(v, l2, "1") || field(&p, nl, &l3)) { because("plan: not a version 1 plan"); return -1; } + } else if (is(k, l1, "build-id")) { + const char *v = field(&p, nl, &l2); + long n = v ? unhex(v, l2, plan.build_id, ID_MAX) : -1; + if (n <= 0 || field(&p, nl, &l3)) { because("plan: bad build-id"); return -1; } + plan.build_id_len = (size_t)n; + } else if (is(k, l1, "edit")) { + if (plan.n >= EDITS_MAX) { because("plan: more than %d edits", EDITS_MAX); return -1; } + struct edit *e = &plan.edits[plan.n]; + const char *nm = field(&p, nl, &l2), *va = field(&p, nl, &l3), *st = field(&p, nl, &l4), *pa = field(&p, nl, &l5); + size_t l6 = 0; + if (!nm || !va || !st || !pa || field(&p, nl, &l6) || l2 >= NAME_MAX_) { because("plan: bad edit line %d", lines); return -1; } + memcpy(e->name, nm, l2); + uintptr_t v = 0; + for (size_t i = 0; i < l3; i++) { + int h = hexval((unsigned char)va[i]); + if (h < 0 || i >= 2 * sizeof v) { because("plan: bad address on line %d", lines); return -1; } + v = v << 4 | (uintptr_t)h; + } + long ns = unhex(st, l4, e->stock, BYTES_MAX), np = unhex(pa, l5, e->patched, BYTES_MAX); + if (ns <= 0 || ns != np) { because("plan: bad bytes on line %d", lines); return -1; } + e->vaddr = v; + e->len = (size_t)ns; + plan.n++; + } else if (is(k, l1, "end")) { + const char *v = field(&p, nl, &l2); + char num[16]; + if (!v || l2 >= sizeof num || field(&p, nl, &l3)) { because("plan: bad end line"); return -1; } + memcpy(num, v, l2); + num[l2] = 0; + if (strtol(num, NULL, 10) != plan.n) { because("plan: %d edits, its end says %s", plan.n, num); return -1; } + ended = 1; + } else { + because("plan: unknown line kind on line %d", lines); + return -1; + } + } + if (!ended) { because("plan: no end line (cut short)"); return -1; } + if (!plan.build_id_len) { because("plan: no build-id"); return -1; } + if (!plan.n) { because("plan: no edits"); return -1; } + return 0; +} + +static int read_file(const char *path, char *buf, size_t max, size_t *size) { + int fd = open(path, O_RDONLY | O_CLOEXEC); + if (fd < 0) return -1; + size_t got = 0; + for (;;) { + ssize_t r = read(fd, buf + got, max - got); + if (r < 0 && errno == EINTR) continue; + if (r < 0) { close(fd); return -1; } + if (r == 0) break; + got += (size_t)r; + if (got == max) { close(fd); errno = EFBIG; return -1; } + } + close(fd); + *size = got; + return 0; +} + +static int threads(void) { + static char buf[4096]; + size_t n; + if (read_file("/proc/self/status", buf, sizeof buf - 1, &n) < 0) return -1; + buf[n] = 0; + char *t = strstr(buf, "\nThreads:"); + return t ? atoi(t + 9) : -1; +} + +/* The other threads' names (/proc/self/task//comm), for the log. */ +static void thread_names(char *out, size_t max) { + out[0] = 0; + DIR *d = opendir("/proc/self/task"); + if (!d) return; + struct dirent *e; + size_t len = 0; + while ((e = readdir(d)) && len + 24 < max) { + if (e->d_name[0] == '.' || atol(e->d_name) == (long)getpid()) continue; + char path[300], comm[32]; + size_t got = 0; + snprintf(path, sizeof path, "/proc/self/task/%s/comm", e->d_name); + if (read_file(path, comm, sizeof comm - 1, &got) < 0) continue; + while (got && (comm[got - 1] == '\n')) got--; + comm[got] = 0; + for (char *c = comm; *c; c++) + if (!((*c >= 'a' && *c <= 'z') || (*c >= 'A' && *c <= 'Z') || (*c >= '0' && *c <= '9') || *c == '_' || *c == '-')) *c = '_'; + len += (size_t)snprintf(out + len, max - len, "%s%s", len ? "," : "", comm); + } + closedir(d); +} + +/* Every region inside one file-backed PT_LOAD part, no two overlapping. */ +static int place(const struct image *img) { + for (int i = 0; i < plan.n; i++) { + struct edit *e = &plan.edits[i]; + const ElfW(Phdr) *seg = NULL; + for (int j = 0; j < img->phnum; j++) { + const ElfW(Phdr) *p = &img->phdr[j]; + if (p->p_type == PT_LOAD && e->vaddr >= p->p_vaddr && e->vaddr + e->len <= p->p_vaddr + p->p_filesz) { seg = p; break; } + } + if (!seg) { because("%s: 0x%lx is not in a loaded part of the program", e->name, (unsigned long)e->vaddr); return -1; } + for (int j = 0; j < img->phnum; j++) { + const ElfW(Phdr) *p = &img->phdr[j]; + if (p->p_type == PT_GNU_RELRO && e->vaddr < p->p_vaddr + p->p_memsz && p->p_vaddr < e->vaddr + e->len) { + because("%s: 0x%lx is in the relocated read-only data", e->name, (unsigned long)e->vaddr); + return -1; + } + } + e->at = (unsigned char *)(img->base + e->vaddr); + e->prot = (seg->p_flags & PF_R ? PROT_READ : 0) | (seg->p_flags & PF_W ? PROT_WRITE : 0) | (seg->p_flags & PF_X ? PROT_EXEC : 0); + for (int k = 0; k < i; k++) { + const struct edit *o = &plan.edits[k]; + if (e->vaddr < o->vaddr + o->len && o->vaddr < e->vaddr + e->len) { because("%s overlaps %s", e->name, o->name); return -1; } + } + } + return 0; +} + +struct page { uintptr_t at; int prot; }; + +static int pages_of(struct page *pages, long psz) { + int n = 0; + for (int i = 0; i < plan.n; i++) { + const struct edit *e = &plan.edits[i]; + uintptr_t first = (uintptr_t)e->at & ~(uintptr_t)(psz - 1), last = ((uintptr_t)e->at + e->len - 1) & ~(uintptr_t)(psz - 1); + for (uintptr_t pg = first; pg <= last; pg += (uintptr_t)psz) { + int seen = 0; + for (int k = 0; k < n; k++) if (pages[k].at == pg) { seen = 1; if (pages[k].prot != e->prot) return -1; } + if (seen) continue; + if (n >= PAGES_MAX) return -1; + pages[n].at = pg; + pages[n].prot = e->prot; + n++; + } + } + return n; +} + +static void put_stock(int upto) { + for (int i = 0; i < upto; i++) memcpy(plan.edits[i].at, plan.edits[i].stock, plan.edits[i].len); +} + +/* All or nothing. 0 when applied. */ +static int apply(void) { + static struct page pages[PAGES_MAX]; + long psz = sysconf(_SC_PAGESIZE); + if (psz <= 0) { because("no page size"); return -1; } + for (int i = 0; i < plan.n; i++) { + const struct edit *e = &plan.edits[i]; + if (memcmp(e->at, e->stock, e->len) != 0) { + because("%s at 0x%lx does not read as the plan's stock bytes%s", e->name, (unsigned long)e->vaddr, + memcmp(e->at, e->patched, e->len) == 0 ? " (it reads patched: a patched file on disk?)" : ""); + return -1; + } + } + int n = pages_of(pages, psz); + if (n < 0) { because("edit pages: too many, or one in two segments"); return -1; } + int opened = 0; + for (; opened < n; opened++) { + if (mprotect((void *)pages[opened].at, (size_t)psz, PROT_READ | PROT_WRITE | (pages[opened].prot & PROT_EXEC)) != 0) break; + } + if (opened < n) { + int err = errno; + for (int k = 0; k < opened; k++) + if (mprotect((void *)pages[k].at, (size_t)psz, pages[k].prot) != 0) { + static const char msg[] = "wocpatch: a page could not get its protection back; aborting\n"; + (void)!write(2, msg, sizeof msg - 1); + abort(); + } + because("mprotect writable: %s", strerror(err)); + return -1; + } + for (int i = 0; i < plan.n; i++) memcpy(plan.edits[i].at, plan.edits[i].patched, plan.edits[i].len); + const char *bad = NULL; + for (int i = 0; i < plan.n; i++) if (memcmp(plan.edits[i].at, plan.edits[i].patched, plan.edits[i].len) != 0) { bad = "the written bytes did not read back"; break; } + if (bad) put_stock(plan.n); + int failed = 0; + for (int k = 0; k < n; k++) if (mprotect((void *)pages[k].at, (size_t)psz, pages[k].prot) != 0) failed++; + if (failed) { + /* A page kept its writable protection: every page writable again + * (each was, a moment ago), the stock bytes back, then each page its + * segment's protection. carplay cannot run with a page that does + * not get it back. */ + static const char msg[] = "wocpatch: a page could not get its protection back; aborting\n"; + for (int k = 0; k < n; k++) + if (mprotect((void *)pages[k].at, (size_t)psz, PROT_READ | PROT_WRITE | (pages[k].prot & PROT_EXEC)) != 0) { + (void)!write(2, msg, sizeof msg - 1); + abort(); + } + put_stock(plan.n); + for (int k = 0; k < n; k++) + if (mprotect((void *)pages[k].at, (size_t)psz, pages[k].prot) != 0) { + (void)!write(2, msg, sizeof msg - 1); + abort(); + } + bad = "mprotect: a page did not take its protection back; the stock bytes are back"; + } + if (bad) { because("%s", bad); return -1; } + return 0; +} + +static void report(int applied) { + char out[2048], names[160]; + thread_names(names, sizeof names); + int len = snprintf(out, sizeof out, "{\"v\":1,\"pid\":%ld,\"applied\":%s,\"threads\":%d,\"others\":\"%s\",\"edits\":[", (long)getpid(), applied ? "true" : "false", + threads(), names); + for (int i = 0; applied && i < plan.n && len < (int)sizeof out - 64; i++) + len += snprintf(out + len, sizeof out - (size_t)len, "%s\"%s\"", i ? "," : "", plan.edits[i].name); + len += snprintf(out + len, sizeof out - (size_t)len, "],\"why\":\""); + for (const char *c = applied ? "" : why; *c && len < (int)sizeof out - 4; c++) { + if (*c == '"' || *c == '\\') out[len++] = '\\'; + out[len++] = (unsigned char)*c < 0x20 ? ' ' : *c; + } + len += snprintf(out + len, sizeof out - (size_t)len, "\"}\n"); + const char *path = getenv("WOC_PATCH_RESULT"); + if (path) { + int fd = open(path, O_WRONLY | O_TRUNC | O_CLOEXEC | O_NOFOLLOW); + if (fd >= 0) { (void)!write(fd, out, (size_t)len); close(fd); } + } + char line[512]; + int l = applied ? snprintf(line, sizeof line, "wocpatch: applied %d edits in memory\n", plan.n) + : snprintf(line, sizeof line, "wocpatch: not applied, the program runs as it ships: %s\n", why); + if (l > 0) (void)!write(2, line, (size_t)(l < (int)sizeof line ? l : (int)sizeof line - 1)); +} + +__attribute__((constructor)) static void wocpatch_init(void) { + static char text[PLAN_MAX]; + const char *path = getenv("WOC_PATCH_PLAN"); + if (!path) return; + struct image img = { 0 }; + dl_iterate_phdr(first_object, &img); + if (!img.found) return; + const unsigned char *id; + size_t idlen; + size_t size; + /* A plan that cannot be read names no program: the line goes to + * stderr, and the result file, which may be another process's, stays + * as it is. Not the plan's program: nothing, not even a result. */ + if (read_file(path, text, sizeof text, &size) < 0) { + static char line[400]; + int l = snprintf(line, sizeof line, "wocpatch: not applied: plan %s: %s\n", path, strerror(errno)); + if (l > 0) (void)!write(2, line, (size_t)(l < (int)sizeof line ? l : (int)sizeof line - 1)); + return; + } + if (parse_plan(text, size) < 0) { + static char line[400]; + int l = snprintf(line, sizeof line, "wocpatch: not applied: %s\n", why); + if (l > 0) (void)!write(2, line, (size_t)(l < (int)sizeof line ? l : (int)sizeof line - 1)); + return; + } + if (build_id(&img, &id, &idlen) < 0 || idlen != plan.build_id_len || memcmp(id, plan.build_id, idlen) != 0) return; + if (place(&img) < 0 || apply() < 0) { report(0); return; } + report(1); +#ifdef WOC_TEST_CRASH + /* Test builds only (make test-preload): an armed start that crashes. */ + abort(); +#endif +} diff --git a/native/waze-on-cluster/systemd/carplay.service.d/50-waze-on-cluster.conf b/native/waze-on-cluster/systemd/carplay.service.d/50-waze-on-cluster.conf index 3010a3bf..e8c173d2 100644 --- a/native/waze-on-cluster/systemd/carplay.service.d/50-waze-on-cluster.conf +++ b/native/waze-on-cluster/systemd/carplay.service.d/50-waze-on-cluster.conf @@ -1,7 +1,12 @@ # SPDX-License-Identifier: GPL-3.0-or-later # Copyright (C) 2026 Robert Nisipeanu # waze-on-cluster: patchd restarts carplay with SIGKILL to load a changed -# binary. As a success exit it does not fail carplay.service, so its -# OnFailure=mediaddpserver_kill.service does not run. +# binary or the patch in memory. As a success exit it does not fail +# carplay.service, so its OnFailure=mediaddpserver_kill.service does not run. [Service] SuccessExitStatus=SIGKILL +# The patch in memory (PATCH.md "In memory"): boot recovery writes this file +# in /run only for a start it arms, with LD_PRELOAD (the unit's own +# libschedconfig, then libwocpatch.so) and the plan's paths. Without it +# ("-"), carplay starts as it ships. +EnvironmentFile=-/run/woc-preload/carplay.env