From e5c9543fae83170f094a2e58293a787f4242c7ef Mon Sep 17 00:00:00 2001 From: anthonyanderson Date: Fri, 27 Nov 2026 09:28:17 -0500 Subject: [PATCH 1/3] Engine: journal settings, props and binds; checked backups; room checks Recover now puts back the settings, live props and binds an apply or trial changed, not only its files: a trial's persist.* prop stayed set after "trial undone", and the next apply took it for stock. Stock backups are copied beside, checked against the stock md5, then renamed, as install.sh's backup() does. An app's odex backup has its md5 recorded, and every backup is checked before a restore or rebuild; a NEMESIS copy with the recorded md5 stands in for a damaged one, else the engine stops and names it. The journal's saved copies are checked the same way. An apply checks room on /system and /data before writing anything; recover removes a cut-off copy, and on a full /system the file, before its saved copy goes back. A damaged journal, or a saved copy that's gone, is set aside (state/journal.bad.json) instead of failing at every start. build.prop and live props refuse dalvik.* and persist.sys.dalvik.* without overrides.allow_critical; CRITICAL takes framework-res.apk, libz, libcrypto, the ICU files, libgui, libEGL, lib/hw and lib/egl, and the boot daemons Android waits for. update-hmgapi refuses while a journal is pending. The Dalvik cache clean-up touches only the app's own entry, priv-app included. Tests: core/runtime/journal-test.sh, plus safety-test.sh and usb-test.sh. Off-car only. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 31 ++ core/runtime/java/hmgapi/engine/Engine.java | 513 +++++++++++++++--- .../java/hmgapi/engine/UsbUpdates.java | 16 + core/runtime/journal-test.sh | 255 +++++++++ core/runtime/safety-test.sh | 32 ++ core/runtime/usb-test.sh | 6 + tools/test-all.sh | 4 +- tools/test-select.py | 4 +- 8 files changed, 790 insertions(+), 71 deletions(-) create mode 100644 core/runtime/journal-test.sh diff --git a/CHANGELOG.md b/CHANGELOG.md index c4168555..33b9898f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,36 @@ # Changelog +## Unreleased + +- **An undone trial or a cut-off apply puts settings, live props and binds back too.** The + journal kept only files and the state, so a trial's `persist.*` prop (or one set by an apply + cut off after its settings) stayed set after "trial undone", the next apply took it for stock, + and `engine restore` left it set. `binds.txt` wasn't rolled back either. The journal now keeps + each one's value before, and `engine recover` writes them back. +- **Stock backups are checked before every use.** They're taken as the installer takes its + own: copied beside, checked against the stock md5, then renamed, so a cut-off copy never sits + under the backup's name. An app's odex backup has its md5 recorded now. A restore, uninstall or + rebuild never writes a backup that isn't the recorded md5 (a short odex under a stock apk with + no `classes.dex` crashed that app at every launch): a NEMESIS copy with that md5 stands in, or + the engine stops and names the backup and the md5 it should have. +- **Room is checked before an apply** writes anything, on `/system` and `/data`. If `/system` + filled up anyway, `engine recover` removes the cut-off copy first and, when there's still no + room, the file before its saved copy goes back, instead of failing at every start. +- **A damaged journal, or a saved copy that's gone, no longer blocks everything.** `engine + recover` sets the journal aside (`state/journal.bad.json`) and says so; `engine status` and + `engine keep` say what's wrong instead of failing. +- **More is refused unless `hmgapi.json overrides.allow_critical` lists it** (with a warning): + `dalvik.*` and `persist.sys.dalvik.*` keys in `build.prop` and as live props + (`"prop:"`, e.g. the runtime switch `persist.sys.dalvik.vm.lib`), `framework-res.apk`, + `libz`, `libcrypto`, `libssl`, the ICU libraries and data file, `libgui`, `libui`, `libEGL`, + `libGLESv2`, `libhardware`, `libsqlite`, `libexpat`, everything in `/system/lib/hw/` and + `/system/lib/egl/`, and `netd`, `mediaserver`, `logwrapper` and `e2fsck`. +- **HMG-API doesn't update itself while an apply is unfinished or a trial is in place** + (`engine update-hmgapi`, `--force` included): `engine keep` or `engine recover` first. +- **A rebuilt app's Dalvik cache entry is the only one touched.** The clean-up also deleted + other apps' entries whose names ended the same way, and the entry filled after a restore was + always named `system@app@`, wrong for an app in `/system/priv-app`. Tested off-car only. + ## 1.1.0-rc.10 (2026-11-25) - **No owner-facing way to force an unknown `app_process`, for now.** An empty `HMGAPI/FORCE` diff --git a/core/runtime/java/hmgapi/engine/Engine.java b/core/runtime/java/hmgapi/engine/Engine.java index 1a5de4e8..f4f09a9f 100644 --- a/core/runtime/java/hmgapi/engine/Engine.java +++ b/core/runtime/java/hmgapi/engine/Engine.java @@ -42,10 +42,12 @@ * src, else puts stock back (nothing on disk changes; a restart clears it). * * Safety (the unit must always boot): /system/build.prop only takes "props" - * changes, never to ro.* keys, and every edit must keep every other line; - * boot-critical files (see CRITICAL) are refused unless hmgapi.json - * overrides.allow_critical lists the path; files HMG-API's installer owns are - * always refused. Live properties ("prop") are persist.* only: they live in + * changes, never to ro.*, dalvik.* or persist.sys.dalvik.* keys (CRITICAL_PROPS), + * and every edit must keep every other line; boot-critical files (see critical()) + * are refused unless hmgapi.json overrides.allow_critical lists the path + * ("/system/build.prop:" for a key, "prop:" for a live property); files + * HMG-API's installer owns are always refused. Live properties ("prop") are + * persist.* only (not persist.sys.dalvik.*: the runtime switch): they live in * /data/property, and removing that file undoes them. A prop's "value" "" means * unset. "mirror": a live (non-persist) property set to the same value, for init * triggers such as sys.usb.config; "restart": services restarted after the @@ -337,10 +339,8 @@ String bindRefused(String src, String target, String svc) { if (!target.matches("/(sbin|system/bin)/[A-Za-z0-9._-]+")) return "target must be in /sbin or /system/bin"; if (!svc.matches("[a-z0-9_]+")) return "service must be an init service name"; for (String x : HMGAPI_OWNED) if (x.equals(target) || x.equals(src)) return target + " belongs to HMG-API's own install"; - for (String x : CRITICAL) { - if (x.equals(target) && !allowedCritical(target)) { - return "the unit needs " + target + " to boot (hmgapi.json overrides.allow_critical lists it to allow, at your own risk)"; - } + if (critical(target) && !allowedCritical(target)) { + return "the unit needs " + target + " to boot (hmgapi.json overrides.allow_critical lists it to allow, at your own risk)"; } if ("/sbin/ueventd".equals(target) || "/sbin/healthd".equals(target) || target.equals("/init")) return target + " can't be swapped"; return null; @@ -461,9 +461,9 @@ int run(String[] args) throws Exception { if ("apply".equals(cmd)) LiveState.publish(this); // a switch with no file change still reaches running apps return 0; } - apply(p, trial); - LiveState.publish(this); - return 0; + int rc = apply(p, trial); + if (rc == 0) LiveState.publish(this); + return rc; } // ------------------------------------------------------------------ mods @@ -912,10 +912,11 @@ static final class Target { boolean exists; // result exists String result; // md5 of the result, or "absent" String stock; // md5 of the stock original, or "absent" - File baseline; // where the stock bytes come from (null = absent) + File baseline; // where the stock bytes come from (null = absent); restore: what's written back boolean newBackup; // baseline must be backed up at apply boolean app; // rebuilt app: odex regenerated - File odexSrc; // app: the stock odex its delta was built from (backed up at apply) + File odexSrc; // app: the stock odex its delta was built from (backed up at apply); restore: what's written back + String odexStock; // app: that odex's md5 (recorded in files.json "odex"; null in an older engine's records) Set mods = new LinkedHashSet(); boolean restore; // no mod wants it any more: back to stock } @@ -1029,6 +1030,14 @@ Plan plan(boolean restoreAll, boolean force) throws Exception { + " ro.* can't change, and build.prop edits aren't used for properties)"); continue; } + if (criticalProp(key) != null) { + if (!allowedCritical("prop:" + key)) { + problems.add(m.id + ": prop " + key + ": " + criticalProp(key) + ", so it's refused (hmgapi.json" + + " overrides.allow_critical \"prop:" + key + "\" allows it, at your own risk)"); + continue; + } + out.add("WARNING: prop " + key + " can keep the unit from booting; setting it because overrides.allow_critical lists it"); + } } if ("setting".equals(ch.type) && c.get("add") instanceof List) { // a list setting (enabled_input_methods "a:b"): every mod's entries on top of the stock value @@ -1116,10 +1125,7 @@ Plan plan(boolean restoreAll, boolean force) throws Exception { List skipped = new ArrayList(); for (Target t : p.targets.values()) { if (t.restore) { - Map f = (Map) files.get(t.path); - t.stock = (String) f.get("stock"); - t.result = t.stock; - t.app = Boolean.TRUE.equals(f.get("app")); + restoreFrom(t, (Map) files.get(t.path)); continue; } int before = problems.size(); @@ -1151,14 +1157,89 @@ Plan plan(boolean restoreAll, boolean force) throws Exception { else { // owned before, can't be built now: back to stock Target t = p.targets.get(path); t.restore = true; - t.stock = (String) f.get("stock"); - t.result = t.stock; - t.app = Boolean.TRUE.equals(f.get("app")); + restoreFrom(t, f); } } return p; } + /** + * A file going back to stock: where its stock bytes (and an app's stock odex) come from. + * Each backup is checked against the md5 recorded when it was taken; a damaged one is + * never written back (a short odex under a stock apk with no classes.dex: the app + * crashes at every launch). A NEMESIS copy with the recorded md5 stands in, else the + * plan stops, saying which backup and what it should be. + */ + void restoreFrom(Target t, Map f) throws IOException { + t.stock = (String) f.get("stock"); + t.result = t.stock; + t.app = Boolean.TRUE.equals(f.get("app")); + if (!"absent".equals(t.stock)) { + t.baseline = stockCopy(t.path, t.stock); + if (t.baseline == null) return; + } + if (t.app) { + String odex = t.path.replaceAll("\\.apk$", ".odex"); + t.odexStock = (String) f.get("odex"); + t.odexSrc = t.odexStock != null ? stockCopy(odex, t.odexStock) : wholeOdex(odex); + } + } + + /** + * HMG-API's backup of a stock file if it has the md5 recorded for it, else a NEMESIS copy + * that does (noted; a rebuild backs it up again); null, with the problem, if neither. + */ + File stockCopy(String path, String md5) throws IOException { + File b = backup(path); + String have = md5(b); + if (have.equals(md5)) return b; + File nem = nemesisStock(path, Collections.singleton(md5)); + if (nem != null) { + out.add("note " + path + ": HMG-API's stock backup is " + ("absent".equals(have) ? "missing" : "damaged (" + have + ")") + + "; using the stock copy NEMESIS kept (" + nem.getParentFile().getName() + "), which has the recorded md5 " + md5); + return nem; + } + problems.add(path + ": HMG-API's stock backup " + b.getPath().substring(root.length()) + " is " + + ("absent".equals(have) ? "missing" : "damaged (md5 " + have + ")") + ", not the stock file recorded (md5 " + md5 + + "), so it can't be put back. Copy the stock file (md5 " + md5 + ") there, then try again"); + return null; + } + + /** + * An app's odex backup from before HMG-API recorded its md5: a Dalvik odex ("dey\n" and + * its header's opt section) must be as long as its header says; a short one (a cut-off + * copy) is refused. Anything else can't be told apart, so it's used as before. + */ + File wholeOdex(String odex) throws IOException { + File b = backup(odex); + if (!b.isFile()) { + problems.add(odex + ": HMG-API's backup of the stock odex " + b.getPath().substring(root.length()) + + " is missing, so the stock app (which has no code of its own) can't be put back. Copy the stock odex there, then try again"); + return null; + } + byte[] h = new byte[40]; + InputStream in = new FileInputStream(b); + int n; + try { + n = in.read(h); + } finally { + in.close(); + } + if (n == 40 && h[0] == 'd' && h[1] == 'e' && h[2] == 'y' && h[3] == '\n') { + long optOff = le32(h, 24), optLen = le32(h, 28); + if (b.length() < optOff + optLen) { + problems.add(odex + ": HMG-API's backup of the stock odex " + b.getPath().substring(root.length()) + " is cut short (" + + b.length() + " bytes, its header says " + (optOff + optLen) + "), so it can't be put back. Copy the stock odex there, then try again"); + return null; + } + } + return b; + } + + static long le32(byte[] b, int at) { + return (b[at] & 0xffL) | (b[at + 1] & 0xffL) << 8 | (b[at + 2] & 0xffL) << 16 | (b[at + 3] & 0xffL) << 24; + } + /** live md5s taken as found this plan (Plan.rebased), for build() */ Map rebaseAccept = new TreeMap(); @@ -1232,13 +1313,46 @@ static boolean backupName(String n, String path) { /** Files the unit can't boot (or HMG-API can't run) without. */ static final String[] CRITICAL = { + // the shell, the linker, the daemons init starts at boot that Android waits for (system_server + // hangs without netd or mediaserver's audio), and what init's mount_all runs on /data "/system/bin/linker", "/system/bin/sh", "/system/bin/mksh", "/system/bin/toolbox", "/system/bin/servicemanager", "/system/bin/vold", "/system/bin/surfaceflinger", "/system/bin/dexopt", "/system/bin/installd", + "/system/bin/netd", "/system/bin/mediaserver", "/system/bin/logwrapper", "/system/bin/e2fsck", + // what the zygote, system_server and surfaceflinger load "/system/lib/libc.so", "/system/lib/libdl.so", "/system/lib/libm.so", "/system/lib/libstdc++.so", "/system/lib/liblog.so", "/system/lib/libcutils.so", "/system/lib/libutils.so", "/system/lib/libbinder.so", "/system/lib/libdvm.so", "/system/lib/libandroid_runtime.so", "/system/lib/libnativehelper.so", "/system/lib/libselinux.so", + "/system/lib/libz.so", "/system/lib/libcrypto.so", "/system/lib/libssl.so", "/system/lib/libicuuc.so", + "/system/lib/libicui18n.so", "/system/usr/icu/icudt51l.dat", "/system/lib/libgui.so", "/system/lib/libui.so", + "/system/lib/libEGL.so", "/system/lib/libGLESv2.so", "/system/lib/libhardware.so", "/system/lib/libsqlite.so", + "/system/lib/libexpat.so", + "/system/framework/framework-res.apk", "/system/etc/init.sh", "/system/etc/mkshrc", }; + /** Folders whose every file is boot-critical: the hardware modules and the GPU's EGL drivers. */ + static final String[] CRITICAL_DIRS = { "/system/lib/hw/", "/system/lib/egl/" }; + /** Property prefixes a mod can't set (build.prop keys, live props) without overrides.allow_critical. */ + static final String[] CRITICAL_PROPS = { "ro.", "dalvik.", "persist.sys.dalvik." }; + + /** Whether the unit needs this file to boot (CRITICAL, CRITICAL_DIRS, the boot class path). */ + static boolean critical(String path) { + for (String x : CRITICAL) if (x.equals(path)) return true; + for (String d : CRITICAL_DIRS) if (path.startsWith(d)) return true; + for (String j : BOOT_JARS) { + if (path.equals("/system/framework/" + j + ".jar") || path.equals("/system/framework/" + j + ".odex")) return true; + } + return false; + } + + /** Why a property can keep the unit from booting, or null if it can't. */ + static String criticalProp(String key) { + if (key.startsWith("ro.")) return "ro.* properties set how the firmware identifies and boots itself"; + if (key.startsWith("dalvik.") || key.startsWith("persist.sys.dalvik.")) { + return "dalvik.* and persist.sys.dalvik.* properties set how Dalvik starts (persist.sys.dalvik.vm.lib picks the runtime;" + + " a wrong one and no app starts)"; + } + return null; + } /** Boot class path jars (and their odex): Dalvik won't start without them intact. */ static final String[] BOOT_JARS = { "core", "conscrypt", "okhttp", "core-junit", "bouncycastle", "ext", "framework", "framework2", "telephony-common", "voip-common", "mms-common", "android.policy", "services", "apache-xml", @@ -1284,11 +1398,12 @@ String guard(Target t) { if (set instanceof Map) keys.addAll(((Map) set).keySet()); if (rm instanceof List) for (Object k : (List) rm) keys.add(String.valueOf(k)); for (String k : keys) { - if (k.startsWith("ro.") && !allowedCritical(t.path + ":" + k)) { - return t.path + ": " + ch.mod.id + " changes " + k + "; ro.* properties set how the firmware identifies and" - + " boots itself, so they're refused (hmgapi.json overrides.allow_critical \"" + t.path + ":" + k - + "\" allows it, at your own risk)"; + String why = criticalProp(k); + if (why != null && !allowedCritical(t.path + ":" + k)) { + return t.path + ": " + ch.mod.id + " changes " + k + "; " + why + ", so they're refused" + + " (hmgapi.json overrides.allow_critical \"" + t.path + ":" + k + "\" allows it, at your own risk)"; } + if (why != null) out.add("WARNING: " + t.path + ": " + k + " can keep the unit from booting; changing it because overrides.allow_critical lists it"); if (!k.matches("[A-Za-z0-9._-]+")) return t.path + ": " + ch.mod.id + ": \"" + k + "\" isn't a property name"; } if (set instanceof Map) { @@ -1300,11 +1415,7 @@ String guard(Target t) { } return null; } - boolean critical = false; - for (String x : CRITICAL) critical |= x.equals(t.path); - for (String j : BOOT_JARS) { - critical |= t.path.equals("/system/framework/" + j + ".jar") || t.path.equals("/system/framework/" + j + ".odex"); - } + boolean critical = critical(t.path); if (critical && !allowedCritical(t.path)) { return t.path + ": the unit needs this file to boot, so mods can't change it (hmgapi.json overrides.allow_critical" + " lists paths allowed anyway, at your own risk)"; @@ -1342,7 +1453,12 @@ void build(Target t, Map owned) throws Exception { } if (owned != null) { t.stock = (String) owned.get("stock"); - t.baseline = "absent".equals(t.stock) ? null : backup(t.path); + if (!"absent".equals(t.stock)) { + // rebuilt from the backup only if it's still the stock file recorded (a NEMESIS copy that is stands in) + t.baseline = stockCopy(t.path, t.stock); + if (t.baseline == null) return; + t.newBackup = !t.baseline.equals(backup(t.path)); + } } else { String m = md5(live); if ("absent".equals(m)) { @@ -1490,21 +1606,28 @@ else if (!m.equals(addMd5)) { // (lpatch only builds from the exact stock bytes, so trying each is safe) String odexPath = t.path.replaceAll("\\.apk$", ".odex"); List odexes = new ArrayList(); - if (owned != null) odexes.add(backup(odexPath)); - else { + String bad = null; + if (owned != null) { + // the live odex is HMG-API's dexopt output now, never stock. A backup that isn't the + // recorded md5 is left out; NEMESIS's copies stand in (backed up again at apply) + String rec = (String) owned.get("odex"), have = md5(backup(odexPath)); + if (rec == null || rec.equals(have)) odexes.add(backup(odexPath)); + else bad = "HMG-API's backup of the stock odex is " + ("absent".equals(have) ? "missing" : "damaged (" + have + ")") + + ", recorded " + rec; + } else { odexes.add(sys(odexPath)); odexes.add(new File(stockDir, odexPath)); - odexes.addAll(nemesisCopies(odexPath)); } + odexes.addAll(nemesisCopies(odexPath)); File dex = new File(stageDir, t.path.replace('/', '_') + ".dex"); - String why = "no stock odex found"; + String why = bad != null ? bad + ", and no NEMESIS copy fits" : "no stock odex found"; t.odexSrc = null; for (String d : ch.srcs("delta")) { for (File odex : odexes) { if (!odex.isFile()) continue; Run r = exec(lpatch, "delta", d, odex.getPath(), dex.getPath()); if (r.code == 0 && dex.isFile()) { t.odexSrc = odex; break; } - why = r.text.trim(); + if (bad == null) why = r.text.trim(); } if (t.odexSrc != null) break; } @@ -1512,6 +1635,7 @@ else if (!m.equals(addMd5)) { problems.add(t.path + ": " + ch.mod.id + "'s app delta doesn't fit this app's stock odex: " + why); return; } + t.odexStock = md5(t.odexSrc); // lpatch built from it, so these are the stock bytes: recorded with the backup File next = new File(work.getPath() + ".a"); Run r = exec(lpatch, "zipadd", work.getPath(), dex.getPath(), next.getPath()); if (r.code != 0 || !next.isFile()) { @@ -1828,7 +1952,7 @@ File find(File dir, String path, Set accepted, int depth) { // ------------------------------------------------------------------ apply @SuppressWarnings("unchecked") - void apply(Plan p, boolean trial) throws Exception { + int apply(Plan p, boolean trial) throws Exception { Map files = (Map) p.state.get("files"); Map st = (Map) p.state.get("settings"); List changed = new ArrayList(); @@ -1836,8 +1960,14 @@ void apply(Plan p, boolean trial) throws Exception { // --force: also a file whose result is unchanged but which was deleted or changed outside HMG-API (#103) if (t.restore || !t.result.equals(p.owned(t.path)) || (p.force && !t.result.equals(md5(sys(t.path))))) changed.add(t); } + String full = room(changed); + if (full != null) { + out.add("nothing changed: " + full); + return 3; + } - // journal: what each file was before, so a lost apply or a trial can be rolled back + // journal: what each file was before, so a lost apply or a trial can be rolled back. Each saved + // copy is checked against the live file and its md5 kept, so recover never writes a short one back rm(prevDir); prevDir.mkdirs(); List entries = new ArrayList(); @@ -1848,17 +1978,32 @@ void apply(Plan p, boolean trial) throws Exception { File live = sys(path); if (live.isFile()) { File prev = new File(prevDir, path.replace('/', '_')); - copy(live, prev); + e.put("md5", checkedCopy(live, prev, md5(live))); e.put("prev", prev.getPath()); e.put("mode", mode(live)); } entries.add(e); } } + // settings, live props and binds as they are now: recover writes them back too (a trial's + // persist.* prop, or an apply cut off after the settings but before the state, stayed set and + // was then taken as stock by the next apply) + Map wasSet = new LinkedHashMap(); + Map before = new LinkedHashMap(); + for (Map.Entry e : p.settings.entrySet()) { + Map s = (Map) st.get(e.getKey()); + if (s != null && String.valueOf(e.getValue()[0]).equals(String.valueOf(s.get("value")))) continue; // not written + journalSetting(wasSet, before, e.getKey(), (Map) e.getValue()[2], s); + } + for (String k : p.settingsRestore) journalSetting(wasSet, before, k, null, (Map) st.get(k)); + File bindsFile = new File(stateDir, "binds.txt"), bindsFailed = new File(stateDir, "binds.failed"); Map j = new LinkedHashMap(); j.put("trial", trial); j.put("committed", false); j.put("entries", entries); + j.put("settings", wasSet); + j.put("binds", bindsFile.isFile() ? read(bindsFile) : null); + j.put("binds_failed", bindsFailed.isFile() ? read(bindsFailed) : null); j.put("state", Json.parse(Json.write(p.state))); // a copy: p.state changes below write(journalFile, Json.write(j)); @@ -1867,13 +2012,15 @@ void apply(Plan p, boolean trial) throws Exception { rm(backup(path)); if (path.endsWith(".apk")) rm(backup(path.replaceAll("\\.apk$", ".odex"))); } - // stock backups, once + // stock backups, as install.sh's backup() takes them: copied beside, checked against the stock md5, + // then renamed, so a cut-off copy never sits under the backup's name. Taken once, and again only + // when the one there isn't the stock file (a damaged one, replaced from a NEMESIS copy) for (Target t : changed) { - if (!t.newBackup) continue; - copy(t.baseline, backup(t.path)); - if (t.app) { - String odex = t.path.replaceAll("\\.apk$", ".odex"); - if (t.odexSrc != null && t.odexSrc.isFile() && !backup(odex).isFile()) copy(t.odexSrc, backup(odex)); + if (t.restore) continue; + if (t.newBackup) checkedCopy(t.baseline, backup(t.path), t.stock); + if (t.app && t.odexSrc != null && t.odexStock != null) { + File ob = backup(t.path.replaceAll("\\.apk$", ".odex")); + if (!t.odexStock.equals(md5(ob))) checkedCopy(t.odexSrc, ob, t.odexStock); } } @@ -1895,7 +2042,7 @@ void apply(Plan p, boolean trial) throws Exception { String was; if (s == null) { s = new LinkedHashMap(); - s.put("stock", settingGet(k)); + s.put("stock", before.get(k)); // read once, for the journal st.put(k, s); was = s.get("stock") == null ? "" : String.valueOf(s.get("stock")); } else { @@ -1922,15 +2069,17 @@ void apply(Plan p, boolean trial) throws Exception { if (!back.equals(String.valueOf(s.get("value")))) after(s, back); out.add("set " + k + " back to " + s.get("stock")); } + cut("settings"); // binds: hmgapid does them after the output is printed (restarting a service like adbd // may cut the link that asked); a new list clears earlier failures String bt = bindsText(p.binds); if (!bt.equals(currentBinds())) { - write(new File(stateDir, "binds.txt"), bt); - new File(stateDir, "binds.failed").delete(); + write(bindsFile, bt); + bindsFailed.delete(); bindsChanged = true; } + cut("binds"); // state for (Target t : changed) { @@ -1943,6 +2092,7 @@ void apply(Plan p, boolean trial) throws Exception { f.put("result", t.result); f.put("mods", new ArrayList(t.mods)); if (t.app) f.put("app", true); + if (t.app && t.odexStock != null) f.put("odex", t.odexStock); files.put(t.path, f); } write(stateFile, Json.write(p.state)); @@ -1959,6 +2109,106 @@ void apply(Plan p, boolean trial) throws Exception { for (Target t : changed) needs.add(restart(t.path)); if (!p.settings.isEmpty() || !p.settingsRestore.isEmpty()) needs.add("settings applied now"); out.add("done: " + changed.size() + " file(s); " + needs); + return 0; + } + + /** a setting, live prop or list setting's value before this apply, with what undoing it needs (mirror, restart) */ + void journalSetting(Map was, Map before, String k, Map c, Map s) + throws Exception { + String v = settingGet(k); + before.put(k, v); + Map e = new LinkedHashMap(); + e.put("value", v); + for (String x : new String[] { "mirror", "restart" }) { + Object o = c != null && c.get(x) != null ? c.get(x) : s != null ? s.get(x) : null; + if (o != null) e.put(x, o); + } + was.put(k, e); + } + + /** + * Off-car tests only (HMGAPI_TEST_CUT=): the engine stops dead here, as when the + * unit loses power mid-apply, so recover can be tested on what that leaves. + */ + void cut(String point) { + if (host && point.equals(env("HMGAPI_TEST_CUT", null))) { + System.out.flush(); + Runtime.getRuntime().halt(137); + } + } + + /** + * Room for this apply, checked before anything is written. On /system: each new file is + * written beside the old one, then renamed over it. An app's old apk and odex are freed + * then (the app is stopped while its files change), so only the growth counts, plus the + * largest old one while both are there; any other file counts whole (a running process + * may still map the old one until the restart). On /data: the journal's copies, new + * backups and the Dalvik cache. A /system that filled mid-apply left a half-done apply + * that recover couldn't put back either. null, or why not. + */ + String room(List changed) throws IOException { + long sys = 0, both = 0, dat = 0; + for (Target t : changed) { + File src = t.restore ? t.baseline : t.exists ? t.stage : null; + long nw = src == null ? 0 : src.length(), old = sys(t.path).length(); + for (String path : withOdex(t)) dat += sys(path).length(); // the journal's copies + if (t.newBackup && t.baseline != null) dat += t.baseline.length(); + if (t.app) { + long odex = t.odexSrc != null ? t.odexSrc.length() : 0, oldOdex = sys(t.path.replaceAll("\\.apk$", ".odex")).length(); + File dex = new File(stageDir, t.path.replace('/', '_') + ".dex"); + long est = t.restore ? odex : Math.max(odex, dex.length() + dex.length() / 4); // dexopt's odex: about the dex and a quarter + sys += Math.max(0, nw - old) + Math.max(0, est - oldOdex); + both = Math.max(both, Math.max(old, oldOdex)); + dat += est + odex; // the Dalvik cache copy, and the odex backup + } else { + sys += nw; + } + } + if (sys == 0 && dat == 0) return null; + long sysFree = free("system", sys(SYSTEM)), datFree = free("data", data); + long sysNeed = sys + both + SYSTEM_SPARE, datNeed = dat + DATA_SPARE; + if (sysFree < sysNeed) return "not enough room on /system: this apply needs about " + mb(sysNeed) + ", " + mb(sysFree) + " free"; + if (datFree < datNeed) return "not enough room on /data: this apply needs about " + mb(datNeed) + ", " + mb(datFree) + + " free (HMG-API keeps a copy of each file it changes, and its stock backup)"; + return null; + } + + static final String SYSTEM = "/system"; + static final long SYSTEM_SPARE = 512 * 1024, DATA_SPARE = 16 * 1024 * 1024; + + static String mb(long n) { + return String.format(java.util.Locale.US, "%.1f MB", n / 1048576.0); + } + + /** + * Free bytes on the filesystem holding f, as root sees it on /system (root may use its + * reserved blocks; the engine runs as root) and as apps do on /data (Android needs its + * reserve there). Off-car tests: HMGAPI_TEST_FREE="system= data=". + */ + long free(String which, File f) { + if (host) { + for (String kv : env("HMGAPI_TEST_FREE", "").split(" ")) if (kv.startsWith(which + "=")) return Long.parseLong(kv.substring(which.length() + 1)); + } + while (f != null && !f.exists()) f = f.getParentFile(); + if (f == null) return Long.MAX_VALUE; + return "system".equals(which) ? f.getFreeSpace() : f.getUsableSpace(); + } + + /** + * Copied beside dst, checked against the md5 it must have, then renamed onto dst: a copy + * that fails or is cut off never leaves a short file under dst's name. Returns the md5. + */ + static String checkedCopy(File src, File dst, String want) throws IOException { + File tmp = new File(dst.getPath() + ".hmgapi-new"); + try { + copy(src, tmp); + String got = md5(tmp); + if (!got.equals(want)) throw new IOException("copy of " + src + " to " + dst + " came out " + got + ", not " + want); + if (!tmp.renameTo(dst)) throw new IOException("rename onto " + dst); + return got; + } finally { + tmp.delete(); + } } List withOdex(Target t) { @@ -1974,11 +2224,11 @@ void swap(Target t) throws Exception { if ("absent".equals(t.stock)) { if (dst.exists() && !dst.delete()) throw new IOException("delete " + dst); } else { - put(backup(t.path), dst, "644"); + put(t.baseline, dst, "644"); // checked against its recorded md5 in the plan (restoreFrom) } if (t.app) { String odex = t.path.replaceAll("\\.apk$", ".odex"); - if (backup(odex).isFile()) put(backup(odex), sys(odex), "644"); + if (t.odexSrc != null) put(t.odexSrc, sys(odex), "644"); dalvik(t.path, sys(odex), false); } out.add("restored " + t.path); @@ -1998,23 +2248,37 @@ void swap(Target t) throws Exception { out.add("wrote " + t.path); } - /** dexopt a rebuilt app and fill its Dalvik cache entry, as the 1.x package did. */ + /** + * The Dalvik cache entry of an app on /system: its path without the leading /, each / + * an @, then @classes.dex (system@app@X.apk@classes.dex, system@priv-app@X.apk@classes.dex). + */ + static String dalvikName(String apkPath) { + return apkPath.substring(1).replace('/', '@') + "@classes.dex"; + } + + /** + * dexopt a rebuilt app and fill its Dalvik cache entry, as the 1.x package did. Only this + * app's own entry goes (a *X.apk* glob also took MyX.apk's). Off the unit: no dexopt, and + * the cache under HMGAPI_ROOT when the test made one. + */ void dalvik(String apkPath, File odex, boolean dexopt) throws Exception { - if (host) return; - String apk = new File(apkPath).getName(); - exec("/system/bin/sh", "-c", "rm -f /data/dalvik-cache/*" + apk + "* /cache/dalvik-cache/*" + apk + "*"); - if (dexopt) { + String name = dalvikName(apkPath); + File cache = new File(root + "/data/dalvik-cache/" + name); + cache.delete(); + new File(root + "/cache/dalvik-cache/" + name).delete(); + if (dexopt && !host) { Run r = exec("/system/bin/dexopt", "--preopt", sys(apkPath).getPath(), odex.getPath(), "m=y,u=n"); if (r.code != 0 || !odex.isFile()) throw new IOException("dexopt " + apkPath + ": " + r.text); exec("/system/bin/chmod", "644", odex.getPath()); exec("/system/bin/chown", "1000:1000", odex.getPath()); } - if (odex.isFile()) { - File cache = new File("/data/dalvik-cache/system@app@" + apk + "@classes.dex"); + if (odex.isFile() && cache.getParentFile().isDirectory()) { File tmp = new File(cache.getPath() + ".tmp"); copy(odex, tmp); - exec("/system/bin/chmod", "644", tmp.getPath()); - exec("/system/bin/chown", "1000:1000", tmp.getPath()); + if (!host) { + exec("/system/bin/chmod", "644", tmp.getPath()); + exec("/system/bin/chown", "1000:1000", tmp.getPath()); + } if (!tmp.renameTo(cache)) tmp.delete(); } } @@ -2088,13 +2352,49 @@ int status() throws Exception { Set on = new LinkedHashSet(); adbTcpWarning(LiveState.mods(this, on), on); if (journalFile.exists()) { - Map j = Json.object(read(journalFile)); - out.add(Boolean.TRUE.equals(j.get("trial")) ? "trial apply in place: `engine keep` keeps it, the next start undoes it" + Map j = journal(); + out.add(j == null ? "an apply didn't finish, and its journal (state/journal.json) is damaged: the next start sets it aside (`engine recover`)" + : Boolean.TRUE.equals(j.get("trial")) && Boolean.TRUE.equals(j.get("committed")) + ? "trial apply in place: `engine keep` keeps it, the next start undoes it" : "an apply didn't finish: the next start rolls it back (`engine recover`)"); } return bad == 0 ? 0 : 4; } + /** the journal, or null if it can't be read or isn't whole (entries, each with a path, and the state) */ + @SuppressWarnings("unchecked") + Map journal() { + try { + Map j = Json.object(read(journalFile)); + if (!(j.get("entries") instanceof List) || !(j.get("state") instanceof Map)) return null; + for (Object o : (List) j.get("entries")) { + if (!(o instanceof Map) || !(((Map) o).get("path") instanceof String)) return null; + String path = (String) ((Map) o).get("path"); + if (!systemPath(path)) return null; + } + if (j.get("settings") != null && !(j.get("settings") instanceof Map)) return null; + return j; + } catch (Exception e) { + return null; + } + } + + /** + * A journal that can't be used, set aside (state/journal.bad.json, its saved copies in + * state/prev.bad/) so apply, restore and uninstall aren't refused for good. What it would + * have put back stays as it is: `engine status` shows what isn't HMG-API's result. + */ + void setAside(String why) { + File bad = new File(stateDir, "journal.bad.json"), prevBad = new File(stateDir, "prev.bad"); + bad.delete(); + rm(prevBad); + boolean moved = journalFile.renameTo(bad); + if (!moved) journalFile.delete(); + if (prevDir.exists() && !prevDir.renameTo(prevBad)) rm(prevDir); + out.add("journal " + why + "; set aside as state/" + (moved ? bad.getName() : "(deleted: couldn't be moved)") + + (prevBad.exists() ? ", its saved copies in state/" + prevBad.getName() + "/" : "")); + } + /** * The car's ADB TCP switch (persist.service.adb.tcp.enable=1: Engineering Mode, or * NEMESIS's Enable ADB) also runs `ifconfig eth0 192.168.0.123` (init.daudio.rc), @@ -2123,7 +2423,11 @@ int keep() throws Exception { out.add("no trial to keep"); return 0; } - Map j = Json.object(read(journalFile)); + Map j = journal(); + if (j == null) { + out.add("the last apply's journal (state/journal.json) is damaged; `engine recover` sets it aside"); + return 1; + } if (!Boolean.TRUE.equals(j.get("trial")) || !Boolean.TRUE.equals(j.get("committed"))) { out.add("the last apply didn't finish; it can only be rolled back (`engine recover`)"); return 1; @@ -2140,32 +2444,107 @@ int recover() throws Exception { out.add("nothing to recover"); return 0; } - Map j = Json.object(read(journalFile)); + Map j = journal(); + if (j == null) { + // no way to tell what it would put back; kept as it is, it refuses every apply, restore and uninstall + setAside("state/journal.json is damaged (an apply was cut off while writing it?), so nothing could be put back from it"); + out.add("the files and settings that apply changed stay as they are; `engine status` shows them, and `engine apply`" + + " (or apply --force) builds them again"); + return 0; + } + // each saved copy checked before any is written: one that's gone or isn't what was saved is skipped, + // not written back, and not tried again at every start + List lost = new ArrayList(); + for (Object o : (List) j.get("entries")) { + Map e = (Map) o; + Object prev = e.get("prev"); + if (prev == null) continue; + File pf = new File(String.valueOf(prev)); + String have = md5(pf); + if ("absent".equals(have) || (e.get("md5") != null && !have.equals(e.get("md5")))) lost.add((String) e.get("path")); + } remount("rw"); try { for (Object o : (List) j.get("entries")) { Map e = (Map) o; String path = (String) e.get("path"); File dst = sys(path); + new File(dst.getPath() + ".hmgapi-new").delete(); // a cut-off apply's half-written copy: its room back first + if (lost.contains(path)) { + out.add("can't put back " + path + ": its saved copy is " + ("absent".equals(md5(new File(String.valueOf(e.get("prev"))))) + ? "gone" : "damaged") + "; left as it is"); + continue; + } Object prev = e.get("prev"); if (prev == null) { if (dst.exists()) dst.delete(); } else { - put(new File((String) prev), dst, e.get("mode") == null ? "644" : String.valueOf(e.get("mode"))); + putBack(new File((String) prev), dst, e.get("mode") == null ? "644" : String.valueOf(e.get("mode"))); } - if (path.endsWith(".odex") && !host) dalvik(path.replaceAll("\\.odex$", ".apk"), dst, false); + if (path.endsWith(".odex")) dalvik(path.replaceAll("\\.odex$", ".apk"), dst, false); out.add("rolled back " + path); } } finally { remount("ro"); } + recoverSettings(j); + if (j.containsKey("binds")) { + File bf = new File(stateDir, "binds.txt"), ff = new File(stateDir, "binds.failed"); + String was = (String) j.get("binds"), now = bf.isFile() ? read(bf) : null; + if (!eq(was, now)) { + if (was == null) bf.delete(); + else write(bf, was); + bindsChanged = true; + out.add("rolled back binds"); + } + String wasFailed = (String) j.get("binds_failed"); + if (wasFailed == null) ff.delete(); + else write(ff, wasFailed); + } write(stateFile, Json.write(j.get("state"))); - journalFile.delete(); - rm(prevDir); - out.add(Boolean.TRUE.equals(j.get("trial")) ? "trial undone" : "unfinished apply rolled back"); + if (lost.isEmpty()) { + journalFile.delete(); + rm(prevDir); + } else { + setAside(lost.size() + " file(s) couldn't be put back"); + out.add("`engine status` shows them (CHANGED); `engine apply --force` builds them again"); + } + out.add(Boolean.TRUE.equals(j.get("trial")) && Boolean.TRUE.equals(j.get("committed")) ? "trial undone" : "unfinished apply rolled back"); return 0; } + /** the settings and live props an apply changed, back to what the journal says they were */ + @SuppressWarnings("unchecked") + void recoverSettings(Map j) throws Exception { + Object so = j.get("settings"); + if (!(so instanceof Map)) return; // a journal from an older engine: files only + for (Map.Entry e : ((Map) so).entrySet()) { + String k = e.getKey(); + if (!(e.getValue() instanceof Map)) continue; + Map s = (Map) e.getValue(); + String was = s.get("value") == null ? null : String.valueOf(s.get("value")); + String now = settingGet(k); + if (eq(was == null || was.isEmpty() ? null : was, now == null || now.isEmpty() ? null : now)) continue; + settingPut(k, was); + after(s, was == null ? "" : was); + out.add("rolled back setting " + k + " = " + (was == null ? "(unset)" : was)); + } + } + + /** + * put() for recover. A /system that filled up mid-apply may have no room for the copy + * beside the file (put writes there, then renames): then the file goes first and its + * saved copy takes its place. The saved copy and the journal stay until recover finishes, + * so a cut here is put right at the next start. + */ + void putBack(File src, File dst, String mode) throws Exception { + if (dst.isFile() && free("system", dst.getParentFile()) < src.length() + SYSTEM_SPARE) { + if (!dst.delete()) throw new IOException("delete " + dst); + out.add("room /system is short of room: " + dst.getPath().substring(root.length()) + " removed before its saved copy goes back"); + } + put(src, dst, mode); + } + /** * A firmware update put /system back to stock under HMG-API (install.sh finds its wrapper * gone): every file HMG-API changed that isn't its result any more is the new firmware's diff --git a/core/runtime/java/hmgapi/engine/UsbUpdates.java b/core/runtime/java/hmgapi/engine/UsbUpdates.java index a1531edd..f950e6b9 100644 --- a/core/runtime/java/hmgapi/engine/UsbUpdates.java +++ b/core/runtime/java/hmgapi/engine/UsbUpdates.java @@ -159,7 +159,23 @@ static String installedVersion(Engine e) { return Engine.HMGAPI_VERSION; } + /** + * Why HMG-API can't update itself now, or null: never while an apply is unfinished or a + * trial is in place. The new installer would build on files and records that the next + * start rolls back (and its engine on a journal it may not read the same way). The + * catalogue's update asks this before it downloads. + */ + static String pendingWhy(Engine e) { + if (!e.journalFile.exists()) return null; + return "an earlier apply isn't finished or is a trial: run `engine keep` (trial) or `engine recover` first, then update HMG-API"; + } + static int updateHmgApi(Engine e, String path, boolean force) throws Exception { + String pending = pendingWhy(e); + if (pending != null) { // --force is for an older release, not this + e.out.add("refused: " + pending); + return 1; + } File zip = new File(path); if (!zip.isFile()) { e.out.add("no release at " + path); diff --git a/core/runtime/journal-test.sh b/core/runtime/journal-test.sh new file mode 100644 index 00000000..ad9a9b77 --- /dev/null +++ b/core/runtime/journal-test.sh @@ -0,0 +1,255 @@ +#!/bin/sh +# Off-car test of the engine's journal and backups: recover puts back settings, live props +# and binds as well as files (a trial, an apply cut off part-way); stock backups are taken +# checked and used only when they're still the stock file; room is checked before an +# apply; a damaged journal or saved copy is set aside instead of failing every start; the +# Dalvik cache entries touched are only the app's own. +# Needs a JDK, python3 with bsdiff4, and out/lpatch-host (./build.sh lpatch). +set -e +cd "$(dirname "$0")/../.." +REPO=$PWD +[ -x out/lpatch-host ] || { echo "run ./build.sh lpatch first"; exit 1; } +CP=$(mktemp -d) +sh tools/engine-classes.sh "$CP" +T=$(mktemp -d) +trap 'rm -rf "$T" "$CP"' EXIT +R=$T/root +D=$R/data/hmgapi +fail=0 +check() { if [ "$2" = "$3" ]; then echo "ok $1"; else echo "FAIL $1: wanted [$2], got [$3]"; fail=1; fi; } +hasnt() { case "$3" in *"$2"*) echo "FAIL $1: [$2] in [$3]"; fail=1 ;; *) echo "ok $1" ;; esac; } +has() { case "$3" in *"$2"*) echo "ok $1" ;; *) echo "FAIL $1: wanted [$2] in [$3]"; fail=1 ;; esac; } +md5() { [ -f "$1" ] && md5sum "$1" | cut -d' ' -f1 || echo absent; } +yes_no() { if [ -e "$1" ]; then echo yes; else echo no; fi; } +eng() { set +e; out=$(HMGAPI_ROOT=$R HMGAPI_HOST=1 HMGAPI_TEST_ANY_CAR=1 HMGAPI_PRODUCT=CVEV.USA.0000.V015 HMGAPI_ONEBIN=cvev_us \ + HMGAPI_LPATCH=$REPO/out/lpatch-host java -cp "$CP" hmgapi.engine.Engine "$@" 2>&1); rc=$?; set -e; } +rec() { python3 -c 'import json,sys; s=json.load(open(sys.argv[1])); print(eval(sys.argv[2]))' "$@"; } + +# ---- a fake head unit: a library, an app in /system/app and one in /system/priv-app +mkdir -p $R/system/lib $R/system/app $R/system/priv-app $R/system/etc/permissions $D/mods $D/settings $R/data/dalvik-cache +printf 'ro.build.product=CVEV.USA.0000.V015\npersist.ium.support=none\n' > $R/system/build.prop +python3 - "$T" "$R" <<'PY' +import sys, random, zipfile +T, R = sys.argv[1], sys.argv[2] +random.seed(5) +stock = bytearray(random.getrandbits(8) for _ in range(65536)) +open(R + "/system/lib/libtest.so", "wb").write(stock) +a = bytearray(stock); a[0x1000:0x1004] = b"\x01\x02\x03\x04"; open(T + "/lib.a", "wb").write(a) +b = bytearray(stock); b[0x3000:0x3004] = b"\x05\x06\x07\x08"; open(T + "/lib.b", "wb").write(b) +for d, n in (("app", "Test"), ("priv-app", "Priv")): + with zipfile.ZipFile(R + "/system/%s/%s.apk" % (d, n), "w") as z: + z.writestr("AndroidManifest.xml", b"manifest " + n.encode()) +odex = bytes(random.getrandbits(8) for _ in range(8192)) +open(R + "/system/app/Test.odex", "wb").write(odex) +open(R + "/system/priv-app/Priv.odex", "wb").write(odex) # the same bytes, so one delta fits both +open(T + "/classes.dex", "wb").write(b"dex\n035\0" + bytes(random.getrandbits(8) for _ in range(4096))) +PY +STOCK_LIB=$(md5 $R/system/lib/libtest.so); STOCK_APK=$(md5 $R/system/app/Test.apk); STOCK_ODEX=$(md5 $R/system/app/Test.odex) +STOCK_PRIV=$(md5 $R/system/priv-app/Priv.apk); cp $R/system/lib/libtest.so $T/lib.stock +mkdir -p $T/m +python3 tools/mkrecipe.py ra /system/lib/libtest.so $R/system/lib/libtest.so $T/lib.a > $T/m/ra.recipe +python3 tools/mkrecipe.py rb /system/lib/libtest.so $R/system/lib/libtest.so $T/lib.b > $T/m/rb.recipe +python3 tools/mkdelta.py $R/system/app/Test.odex $T/classes.dex $T/m/Test.lpd > /dev/null +mod() { # mod + d=$D/mods/$1; rm -rf $d; mkdir -p $d/patches/ev6 $d/files + printf '{"id": "%s", "version": "1.0.0"}\n' "$1" > $d/mod.json + printf '{"cars": {"CVEV.USA.": "ev6"}, "changes": [%s]}\n' "$2" > $d/patches.json + printf 'libtest.so %s\nTest.apk %s\nTest.odex %s\nPriv.apk %s\nPriv.odex %s\n' $STOCK_LIB $STOCK_APK $STOCK_ODEX $STOCK_PRIV $STOCK_ODEX > $d/patches/ev6/stock + cp $T/m/* $d/; echo bin > $d/files/x +} +APPS='{"type": "recipe", "path": "/system/lib/libtest.so", "recipe": "ra.recipe"}, + {"type": "app", "path": "/system/app/Test.apk", "delta": "Test.lpd"}, + {"type": "app", "path": "/system/priv-app/Priv.apk", "delta": "Test.lpd"}' + +# ---- Dalvik cache: only the app's own entry, by its real name (priv-app too) +echo old > $R/data/dalvik-cache/system@app@Test.apk@classes.dex +echo other > $R/data/dalvik-cache/system@app@MyTest.apk@classes.dex +echo old > $R/data/dalvik-cache/system@priv-app@Priv.apk@classes.dex +mod base "$APPS" +eng apply +check "apply: two apps and a library" 0 $rc +check "the app's own cache entry dropped" absent "$(md5 $R/data/dalvik-cache/system@app@Test.apk@classes.dex)" +check "... the priv-app's by its own name" absent "$(md5 $R/data/dalvik-cache/system@priv-app@Priv.apk@classes.dex)" +check "... an app whose name ends the same way untouched" other "$(cat $R/data/dalvik-cache/system@app@MyTest.apk@classes.dex)" +check "odex backup taken" "$STOCK_ODEX" "$(md5 $D/stock/system/app/Test.odex)" +check "... its md5 recorded" "$STOCK_ODEX" "$(rec $D/state/files.json 's["files"]["/system/app/Test.apk"].get("odex")')" +check "no half-written backup left" "" "$(find $D/stock -name '*.hmgapi-new')" +eng restore +check "restore" 0 $rc +check "... the stock odex back" "$STOCK_ODEX" "$(md5 $R/system/app/Test.odex)" +check "... its cache entry filled from it" "$STOCK_ODEX" "$(md5 $R/data/dalvik-cache/system@app@Test.apk@classes.dex)" +check "... the priv-app's entry under system@priv-app@" "$STOCK_ODEX" "$(md5 $R/data/dalvik-cache/system@priv-app@Priv.apk@classes.dex)" +check "... no system@app@ entry made for the priv-app" absent "$(md5 $R/data/dalvik-cache/system@app@Priv.apk@classes.dex)" +check "... the other app's entry still untouched" other "$(cat $R/data/dalvik-cache/system@app@MyTest.apk@classes.dex)" + +# ---- a trial's settings, live props and binds: undone by recover with its files +printf 'global/foo=1\n' > $R/settings.txt +mod base "$APPS" +eng apply +BEFORE_LIB=$(md5 $R/system/lib/libtest.so) +mod tx '{"type": "prop", "key": "persist.test.x", "value": "1"}, + {"type": "setting", "namespace": "global", "key": "foo", "value": "2"}, + {"type": "bind", "src": "files/x", "target": "/sbin/adbd", "service": "adbd"}, + {"type": "recipe", "path": "/system/lib/libtest.so", "recipe": "rb.recipe"}' +rm -f $R/actions.log +eng apply --trial +check "trial apply" 0 $rc +has "... the prop set" "prop/persist.test.x=1" "$(cat $R/settings.txt)" +has "... the setting set" "global/foo=2" "$(cat $R/settings.txt)" +check "... the bind listed" "/data/hmgapi/mods/tx/files/x /sbin/adbd adbd" "$(cat $D/state/binds.txt)" +eng status +has "status: a trial in place" "trial apply in place" "$out" +rm -f $R/actions.log +eng recover +check "recover" 0 $rc +has "... says the trial is undone" "trial undone" "$out" +check "... the library back" "$BEFORE_LIB" "$(md5 $R/system/lib/libtest.so)" +hasnt "... the trial's prop unset again" "persist.test.x" "$(cat $R/settings.txt)" +has "... the setting back to its old value" "global/foo=1" "$(cat $R/settings.txt)" +check "... binds as before the trial" "" "$(cat $D/state/binds.txt 2>/dev/null)" +has "... hmgapid told to undo the bind" "binds" "$(cat $R/actions.log 2>/dev/null)" +has "... and said so" "rolled back setting prop/persist.test.x = (unset)" "$out" +eng apply +check "the next apply" 0 $rc +check "... records the prop's stock as unset (not the trial's 1)" None "$(rec $D/state/files.json 's["settings"]["prop/persist.test.x"]["stock"]')" +check "... and the setting's as 1" 1 "$(rec $D/state/files.json 's["settings"]["global/foo"]["stock"]')" +rm -r $D/mods/tx +eng apply +hasnt "the mod off: its prop unset" "persist.test.x" "$(cat $R/settings.txt)" +has "... the setting stock" "global/foo=1" "$(cat $R/settings.txt)" + +# ---- an apply cut off after its settings, before its state: recover puts them back +mod cut '{"type": "prop", "key": "persist.cut.y", "value": "1"}, {"type": "recipe", "path": "/system/lib/libtest.so", "recipe": "rb.recipe"}' +BEFORE_LIB=$(md5 $R/system/lib/libtest.so); BEFORE_STATE=$(md5 $D/state/files.json) +export HMGAPI_TEST_CUT=settings; eng apply; unset HMGAPI_TEST_CUT +check "cut off (power lost)" 137 $rc +has "... the prop was set" "prop/persist.cut.y=1" "$(cat $R/settings.txt)" +check "... the journal left" yes "$(yes_no $D/state/journal.json)" +eng status +has "status: an apply didn't finish" "an apply didn't finish" "$out" +eng apply +check "another apply waits for recover" 1 $rc +eng recover +check "recover" 0 $rc +has "... an unfinished apply, not a trial" "unfinished apply rolled back" "$out" +hasnt "... the prop unset" "persist.cut.y" "$(cat $R/settings.txt)" +check "... the library back" "$BEFORE_LIB" "$(md5 $R/system/lib/libtest.so)" +check "... the state as before" "$BEFORE_STATE" "$(md5 $D/state/files.json)" +mod cut '{"type": "bind", "src": "files/x", "target": "/sbin/adbd", "service": "adbd"}' +export HMGAPI_TEST_CUT=binds; eng apply; unset HMGAPI_TEST_CUT +check "cut off after the binds" 137 $rc +eng recover +check "... binds as before" "" "$(cat $D/state/binds.txt 2>/dev/null)" +rm -r $D/mods/cut + +# ---- room: checked before anything is written +mod rb '{"type": "recipe", "path": "/system/lib/libtest.so", "recipe": "rb.recipe"}' +BEFORE_LIB=$(md5 $R/system/lib/libtest.so) +export HMGAPI_TEST_FREE="system=1000"; eng apply; unset HMGAPI_TEST_FREE +check "/system full: refused" 3 $rc +has "... saying how much it needs" "not enough room on /system: this apply needs about" "$out" +check "... nothing written" "$BEFORE_LIB" "$(md5 $R/system/lib/libtest.so)" +check "... no journal" no "$(yes_no $D/state/journal.json)" +export HMGAPI_TEST_FREE="data=1000"; eng apply; unset HMGAPI_TEST_FREE +check "/data full: refused" 3 $rc +has "... saying so" "not enough room on /data" "$out" +# a /system that filled up mid-apply: recover makes room (a cut-off copy, then the file itself) +eng apply --trial +check "a trial" 0 $rc +echo half > $R/system/lib/libtest.so.hmgapi-new +export HMGAPI_TEST_FREE="system=0"; eng recover; unset HMGAPI_TEST_FREE +check "recover with /system full" 0 $rc +check "... the cut-off copy beside the file removed" absent "$(md5 $R/system/lib/libtest.so.hmgapi-new)" +check "... the file put back" "$BEFORE_LIB" "$(md5 $R/system/lib/libtest.so)" +has "... saying why it went first" "/system is short of room" "$out" +check "... no journal left" no "$(yes_no $D/state/journal.json)" +rm -r $D/mods/rb + +# ---- a damaged journal, a saved copy that's gone: set aside, not failing at every start +echo '{"trial": true, "entr' > $D/state/journal.json +eng status +has "status: the journal is damaged" "its journal (state/journal.json) is damaged" "$out" +eng keep +has "keep: says recover sets it aside" "damaged; \`engine recover\` sets it aside" "$out" +eng restore +check "restore waits for recover" 1 $rc +eng recover +check "recover with a damaged journal" 0 $rc +has "... set aside" "set aside as state/journal.bad.json" "$out" +hasnt "... claims nothing rolled back (the boot step restarts on that)" "rolled back" "$out" +check "... the journal gone" no "$(yes_no $D/state/journal.json)" +check "... kept to look at" yes "$(yes_no $D/state/journal.bad.json)" +eng apply +check "apply works again" 0 $rc +mod tx '{"type": "prop", "key": "persist.test.z", "value": "1"}, {"type": "recipe", "path": "/system/lib/libtest.so", "recipe": "rb.recipe"}' +eng apply --trial +rm $D/state/prev/_system_lib_libtest.so +eng recover +check "recover with a saved copy gone" 0 $rc +has "... that file named" "can't put back /system/lib/libtest.so: its saved copy is gone" "$out" +hasnt "... the rest still put back (the prop)" "persist.test.z" "$(cat $R/settings.txt)" +check "... the journal set aside, not tried again at every start" no "$(yes_no $D/state/journal.json)" +eng recover +has "... a second recover has nothing to do" "nothing to recover" "$out" +eng apply +has "... the next apply says the file isn't HMG-API's result" "/system/lib/libtest.so: changed outside HMG-API" "$out" +eng apply --force +check "... --force builds it again" 0 $rc +rm -r $D/mods/tx +eng apply --trial +printf 'x' >> "$(ls $D/state/prev/* | head -n 1)" +eng recover +has "a saved copy that isn't what was saved: not written back" "its saved copy is damaged" "$out" +eng apply --force >/dev/null + +# ---- backups: checked against the recorded md5 before every use +eng restore +check "restore to stock" 0 $rc +check "... library stock" "$STOCK_LIB" "$(md5 $R/system/lib/libtest.so)" +mod base "$APPS" +eng apply +check "apply again" 0 $rc +head -c 4000 $T/classes.dex > $D/stock/system/app/Test.odex # a cut-off odex backup +APK_NOW=$(md5 $R/system/app/Test.apk) +eng restore +check "a damaged odex backup: restore refused" 3 $rc +has "... saying which and what it should be" "HMG-API's stock backup /data/hmgapi/stock/system/app/Test.odex is damaged" "$out" +check "... the app left as it is (not a stock apk with a short odex)" "$APK_NOW" "$(md5 $R/system/app/Test.apk)" +# the priv-app's odex backup has the same stock bytes as Test.odex's +mkdir -p $R/data/nemesis/backup/pkg; cp $D/stock/system/priv-app/Priv.odex $R/data/nemesis/backup/pkg/Test.odex +eng restore +check "... a NEMESIS copy with the recorded md5 stands in" 0 $rc +has "... noted" "using the stock copy NEMESIS kept (pkg)" "$out" +check "... the stock odex back" "$STOCK_ODEX" "$(md5 $R/system/app/Test.odex)" +rm -r $R/data/nemesis +eng apply +head -c 30000 $R/system/lib/libtest.so > $D/stock/system/lib/libtest.so # a cut-off backup of the library +mod rb '{"type": "recipe", "path": "/system/lib/libtest.so", "recipe": "rb.recipe"}' +eng plan +check "a damaged backup: no rebuild from it" 3 $rc +has "... saying so" "HMG-API's stock backup /data/hmgapi/stock/system/lib/libtest.so is damaged" "$out" +mkdir -p $R/data/nemesis/backup/pkg; cp $T/lib.stock $R/data/nemesis/backup/pkg/libtest.so +eng apply +check "... rebuilt from a NEMESIS copy with the recorded md5" 0 $rc +check "... the backup taken again, whole" "$STOCK_LIB" "$(md5 $D/stock/system/lib/libtest.so)" +rm -r $R/data/nemesis $D/mods/rb +eng apply +# an app's rebuild with a damaged odex backup: a NEMESIS copy that fits is used, and backed up again +mkdir -p $R/data/nemesis/backup/pkg; cp $D/stock/system/app/Test.odex $R/data/nemesis/backup/pkg/Test.odex +printf 'x' >> $D/stock/system/app/Test.odex +rm $R/system/app/Test.apk # so --force writes the app again +eng apply --force +check "app rebuilt with its odex backup damaged" 0 $rc +check "... the odex backup is stock again" "$STOCK_ODEX" "$(md5 $D/stock/system/app/Test.odex)" +rm -r $R/data/nemesis +# a record from before the odex md5 was kept: a cut-short Dalvik odex is still caught by its header +python3 - $D/state/files.json $D/stock/system/app/Test.odex <<'PY' +import json, struct, sys +s = json.load(open(sys.argv[1])); del s["files"]["/system/app/Test.apk"]["odex"]; json.dump(s, open(sys.argv[1], "w")) +open(sys.argv[2], "wb").write(b"dey\n036\0" + struct.pack("<8I", 40, 1000, 1040, 10, 1050, 90000, 0, 0) + b"\0" * 1000) +PY +eng restore +check "an older record, odex shorter than its header says: refused" 3 $rc +has "... saying so" "is cut short" "$out" + +exit $fail diff --git a/core/runtime/safety-test.sh b/core/runtime/safety-test.sh index cc8defb7..52ea1dcc 100644 --- a/core/runtime/safety-test.sh +++ b/core/runtime/safety-test.sh @@ -78,6 +78,16 @@ printf '{"overrides": {"allow_critical": ["/system/build.prop:ro.build.version.r mod a '{"type": "props", "path": "/system/build.prop", "set": {"ro.build.version.release": "4.4.4"}, "stock": "any"}' eng plan; check "ro.* key allowed by override" 0 $rc rm $R/data/hmgapi/settings/hmgapi.json +mod a '{"type": "props", "path": "/system/build.prop", "set": {"dalvik.vm.heapsize": "512m"}, "stock": "any"}' +eng plan; has "dalvik.* key refused" "dalvik.vm.heapsize; dalvik.* and persist.sys.dalvik.* properties set how Dalvik starts" "$out"; check "... refusal exit" 3 $rc +mod a '{"type": "props", "path": "/system/build.prop", "set": {"persist.sys.dalvik.vm.lib": "libart.so"}, "stock": "any"}' +eng plan; has "persist.sys.dalvik.* key in build.prop refused (the runtime switch)" "changes persist.sys.dalvik.vm.lib" "$out" +printf '{"overrides": {"allow_critical": ["/system/build.prop:dalvik.vm.heapsize"]}}\n' > $R/data/hmgapi/settings/hmgapi.json +mod a '{"type": "props", "path": "/system/build.prop", "set": {"dalvik.vm.heapsize": "512m"}, "stock": "any"}' +eng plan; check "dalvik.* key allowed by override" 0 $rc +has "... with a warning" "WARNING: /system/build.prop: dalvik.vm.heapsize can keep the unit from booting" "$out" +rm $R/data/hmgapi/settings/hmgapi.json +check "build.prop still untouched" "$STOCK_PROP" "$(md5 $R/system/build.prop)" # ---- boot-critical and HMG-API's own files mod a '{"type": "add", "path": "/system/lib/libc.so", "src": "a.xml", "stock": "any"}' @@ -89,10 +99,29 @@ eng plan; has "HMG-API's own files refused even with overrides" "belongs to HMG- rm $R/data/hmgapi/settings/hmgapi.json mod a '{"type": "add", "path": "/system/framework/framework.jar", "src": "a.xml"}' eng plan; has "boot class path jar refused" "framework.jar: the unit needs this file to boot" "$out" +for p in /system/framework/framework-res.apk /system/lib/libz.so /system/lib/libcrypto.so /system/lib/libicuuc.so \ + /system/usr/icu/icudt51l.dat /system/lib/libgui.so /system/lib/libEGL.so /system/lib/hw/gralloc.tcc803x.so \ + /system/lib/egl/libGLES_mali.so /system/bin/netd /system/bin/mediaserver; do + mod a '{"type": "add", "path": "'$p'", "src": "a.xml", "stock": "any"}' + eng plan; has "boot-critical: $p refused" "$p: the unit needs this file to boot" "$out" +done +printf '{"overrides": {"allow_critical": ["/system/lib/hw/gralloc.tcc803x.so"]}}\n' > $R/data/hmgapi/settings/hmgapi.json +mod a '{"type": "add", "path": "/system/lib/hw/gralloc.tcc803x.so", "src": "a.xml", "stock": "any"}' +eng plan; has "a hardware module allowed by override, with a warning" "WARNING: /system/lib/hw/gralloc.tcc803x.so is boot-critical" "$out" +rm $R/data/hmgapi/settings/hmgapi.json +mod a '{"type": "add", "path": "/system/lib/hwx/x.so", "src": "a.xml", "stock": "any"}' +eng plan; check "a folder that only starts like hw/ isn't critical" 0 $rc # ---- live props mod a '{"type": "prop", "key": "ro.secure", "value": "0"}' eng plan; has "non-persist prop refused" "only persist.* properties can be set" "$out" +mod a '{"type": "prop", "key": "persist.sys.dalvik.vm.lib", "value": "libart.so"}' +eng plan; has "the runtime switch refused" "prop persist.sys.dalvik.vm.lib: dalvik.* and persist.sys.dalvik.* properties" "$out" +has "... naming the override" "overrides.allow_critical \"prop:persist.sys.dalvik.vm.lib\"" "$out"; check "... refusal exit" 3 $rc +printf '{"overrides": {"allow_critical": ["prop:persist.sys.dalvik.vm.lib"]}}\n' > $R/data/hmgapi/settings/hmgapi.json +eng plan; check "... allowed by override" 0 $rc +has "... with a warning" "WARNING: prop persist.sys.dalvik.vm.lib can keep the unit from booting" "$out" +rm $R/data/hmgapi/settings/hmgapi.json printf 'prop/persist.sys.iap2.wifi=f\n' > $R/settings.txt mod a '{"type": "prop", "key": "persist.sys.iap2.wifi", "value": "t"}, {"type": "prop", "key": "persist.iap2.iden.wireless", "value": "t"}' eng apply; has "persist prop set live" "prop/persist.sys.iap2.wifi=t" "$(cat $R/settings.txt)" @@ -123,6 +152,9 @@ has "hmgapid told to do it" "binds" "$(cat $R/actions.log 2>/dev/null)" mod a '{"type": "bind", "src": "files/x", "target": "/system/bin/linker", "service": "x"}' mkdir -p $R/data/hmgapi/mods/a/files; echo bin > $R/data/hmgapi/mods/a/files/x eng plan; has "bind over a boot-critical binary refused" "the unit needs /system/bin/linker to boot" "$out" +mod a '{"type": "bind", "src": "files/x", "target": "/system/bin/netd", "service": "netd"}' +mkdir -p $R/data/hmgapi/mods/a/files; echo bin > $R/data/hmgapi/mods/a/files/x +eng plan; has "bind over a boot daemon refused" "the unit needs /system/bin/netd to boot" "$out" mod a '{"type": "add", "path": "/system/etc/permissions/b.xml", "src": "a.xml"}' eng apply; has "binds dropped with the mod: unbind planned" "binds" "$(cat $R/actions.log)" check "binds.txt empty again" "" "$(cat $R/data/hmgapi/state/binds.txt)" diff --git a/core/runtime/usb-test.sh b/core/runtime/usb-test.sh index 0502dc94..7a6fb1d3 100755 --- a/core/runtime/usb-test.sh +++ b/core/runtime/usb-test.sh @@ -64,6 +64,12 @@ has "update in place" '"version": "2.0.0"' "$(cat $R/data/hmgapi/mods/beta/mod.j eng update-hmgapi $U/HMGAPI/updates/hmgapi-fake.zip; check "fake release not run" 3 $rc check "its installer didn't run" no "$([ -e $R/installed-9.9.9 ] && echo yes || echo no)" +echo '{"trial": true, "committed": true, "entries": [], "state": {}}' > $R/data/hmgapi/state/journal.json +eng update-hmgapi $U/HMGAPI/updates/hmgapi-9.9.9.zip; check "a trial in place: no self-update" 1 $rc +has "... saying what to do first" "refused: an earlier apply isn't finished or is a trial: run \`engine keep\` (trial) or \`engine recover\` first" "$out" +eng update-hmgapi $U/HMGAPI/updates/hmgapi-9.9.9.zip --force; check "... --force doesn't step around it" 1 $rc +check "... its installer didn't run" no "$([ -e $R/installed-9.9.9 ] && echo yes || echo no)" +rm $R/data/hmgapi/state/journal.json eng update-hmgapi $U/HMGAPI/updates/hmgapi-9.9.9.zip; check "genuine release runs its installer" 0 $rc has "installer output passed on" "fake installer ran" "$out" check "installer ran" yes "$([ -e $R/installed-9.9.9 ] && echo yes)" diff --git a/tools/test-all.sh b/tools/test-all.sh index 0d50eb41..64d76673 100755 --- a/tools/test-all.sh +++ b/tools/test-all.sh @@ -7,9 +7,9 @@ # Each test: "ok" (its checks, and how many it skipped), "skip" (it skipped everything, # and why) or "FAIL" (its failed checks). cd "$(dirname "$0")/.." -ALL="core/hmgapid/test.sh core/zygote/test.sh tools/lpatch/test.sh core/runtime/engine-test.sh core/runtime/signing-test.sh core/runtime/system-test.sh core/runtime/safety-test.sh core/runtime/packages-test.sh core/runtime/map-test.sh core/runtime/local-map-test.sh core/runtime/usb-test.sh core/runtime/hooks-test.sh core/runtime/mod-dex-test.sh core/runtime/live-test.sh core/runtime/native-test.sh core/runtime/runtime-test.sh core/runtime/net-test.sh core/runtime/problem-test.sh core/runtime/homewifi-test.sh core/runtime/overlap-test.sh core/runtime/keys-test.sh core/runtime/commands-test.sh core/runtime/scriptcheck-test.sh core/hookpoints/test.sh core/app/qr-test.sh install/common/test.sh install/common/install-test.sh install/common/orders-test.sh install/usb/test.sh install/nemesis/mod-test.sh install/nemesis/sync-test.sh tools/mod-draft-test.sh tools/catalog-test.sh tools/car-triage-test.sh tools/version-test.sh tools/mkicon-test.sh tools/micom-decode-test.sh tools/cars-test.sh tools/sdk-test.sh tools/check-scripts.sh" +ALL="core/hmgapid/test.sh core/zygote/test.sh tools/lpatch/test.sh core/runtime/engine-test.sh core/runtime/signing-test.sh core/runtime/system-test.sh core/runtime/safety-test.sh core/runtime/journal-test.sh core/runtime/packages-test.sh core/runtime/map-test.sh core/runtime/local-map-test.sh core/runtime/usb-test.sh core/runtime/hooks-test.sh core/runtime/mod-dex-test.sh core/runtime/live-test.sh core/runtime/native-test.sh core/runtime/runtime-test.sh core/runtime/net-test.sh core/runtime/problem-test.sh core/runtime/homewifi-test.sh core/runtime/overlap-test.sh core/runtime/keys-test.sh core/runtime/commands-test.sh core/runtime/scriptcheck-test.sh core/hookpoints/test.sh core/app/qr-test.sh install/common/test.sh install/common/install-test.sh install/common/orders-test.sh install/usb/test.sh install/nemesis/mod-test.sh install/nemesis/sync-test.sh tools/mod-draft-test.sh tools/catalog-test.sh tools/car-triage-test.sh tools/version-test.sh tools/mkicon-test.sh tools/micom-decode-test.sh tools/cars-test.sh tools/sdk-test.sh tools/check-scripts.sh" # no build, no ARM toolchain: all but hmgapid, the zygote wrapper, lpatch, the installers and the SDK -FAST="core/runtime/engine-test.sh core/runtime/signing-test.sh core/runtime/system-test.sh core/runtime/safety-test.sh core/runtime/packages-test.sh core/runtime/map-test.sh core/runtime/local-map-test.sh core/runtime/usb-test.sh core/runtime/hooks-test.sh core/runtime/mod-dex-test.sh core/runtime/live-test.sh core/runtime/native-test.sh core/runtime/runtime-test.sh core/runtime/net-test.sh core/runtime/problem-test.sh core/runtime/homewifi-test.sh core/runtime/overlap-test.sh core/runtime/keys-test.sh core/runtime/commands-test.sh core/runtime/scriptcheck-test.sh core/hookpoints/test.sh core/app/qr-test.sh install/common/test.sh install/nemesis/mod-test.sh install/nemesis/sync-test.sh tools/mod-draft-test.sh tools/catalog-test.sh tools/car-triage-test.sh tools/version-test.sh tools/mkicon-test.sh tools/micom-decode-test.sh tools/check-scripts.sh" +FAST="core/runtime/engine-test.sh core/runtime/signing-test.sh core/runtime/system-test.sh core/runtime/safety-test.sh core/runtime/journal-test.sh core/runtime/packages-test.sh core/runtime/map-test.sh core/runtime/local-map-test.sh core/runtime/usb-test.sh core/runtime/hooks-test.sh core/runtime/mod-dex-test.sh core/runtime/live-test.sh core/runtime/native-test.sh core/runtime/runtime-test.sh core/runtime/net-test.sh core/runtime/problem-test.sh core/runtime/homewifi-test.sh core/runtime/overlap-test.sh core/runtime/keys-test.sh core/runtime/commands-test.sh core/runtime/scriptcheck-test.sh core/hookpoints/test.sh core/app/qr-test.sh install/common/test.sh install/nemesis/mod-test.sh install/nemesis/sync-test.sh tools/mod-draft-test.sh tools/catalog-test.sh tools/car-triage-test.sh tools/version-test.sh tools/mkicon-test.sh tools/micom-decode-test.sh tools/check-scripts.sh" # these write out/ (usb: out/payload and out/dist; sdk: out/mods, out/packages, out/dist) or read # what another writes (install-test: out/payload), so they run one after another SERIAL="install/common/install-test.sh install/usb/test.sh tools/sdk-test.sh" diff --git a/tools/test-select.py b/tools/test-select.py index 37887ed8..346b20c7 100755 --- a/tools/test-select.py +++ b/tools/test-select.py @@ -15,7 +15,7 @@ RUNTIME = ['core/runtime/*-test.sh'] # the tests that compile hmgapi.engine (tools/engine-classes.sh): the rest of core/runtime's # Java (hook, vehicle) is only compiled by the build and the SDK, and its own tests -ENGINE = ['core/runtime/engine-test.sh', 'core/runtime/signing-test.sh', 'core/runtime/system-test.sh', 'core/runtime/safety-test.sh', +ENGINE = ['core/runtime/engine-test.sh', 'core/runtime/signing-test.sh', 'core/runtime/system-test.sh', 'core/runtime/safety-test.sh', 'core/runtime/journal-test.sh', 'core/runtime/packages-test.sh', 'core/runtime/map-test.sh', 'core/runtime/local-map-test.sh', 'core/runtime/usb-test.sh', 'core/runtime/hooks-test.sh', 'core/runtime/live-test.sh', 'core/runtime/native-test.sh', 'core/runtime/runtime-test.sh', 'core/runtime/net-test.sh', 'core/runtime/homewifi-test.sh', 'core/runtime/overlap-test.sh', 'core/runtime/scriptcheck-test.sh', 'install/nemesis/mod-test.sh', 'install/nemesis/sync-test.sh', @@ -54,7 +54,7 @@ (['install/*'], INSTALL + ['core/runtime/packages-test.sh']), (['tools/zygote-orders.py'], ['install/common/orders-test.sh']), (['install/nemesis/mod/*', 'install/nemesis/bin/open.sh'], SDK), - (['tools/mkdelta.py', 'tools/mkrecipe.py', 'tools/mkmemrecipe.py'], ['core/runtime/engine-test.sh', 'core/runtime/safety-test.sh', 'tools/lpatch/test.sh']), + (['tools/mkdelta.py', 'tools/mkrecipe.py', 'tools/mkmemrecipe.py'], ['core/runtime/engine-test.sh', 'core/runtime/safety-test.sh', 'core/runtime/journal-test.sh', 'tools/lpatch/test.sh']), (['tools/mkinstallers.sh', 'tools/mkrelease.sh', 'tools/mkmodpkg.sh', 'tools/mknemesismod.sh', 'tools/nemesis-version.py', 'tools/nemesis-meta.py', 'tools/release-mods.txt'], INSTALL + ['core/runtime/signing-test.sh', 'core/runtime/usb-test.sh'] + SDK + MODS), # the mod SDK and the reusable mod workflow (['tools/build-mod.sh', 'tools/check-points.py', 'tools/sdk/*', 'tools/sdk-test.sh', 'tools/mkrecipe.py', 'tools/mkdelta.py', 'tools/mkmemrecipe.py', 'tools/mkicon.sh', 'tools/mod-draft.py', 'tools/check-scripts.sh', '.github/workflows/mod.yml'], SDK), From fc20f5f02d7cdfdfda1560ba4518d2d58d308b12 Mon Sep 17 00:00:00 2001 From: anthonyanderson Date: Mon, 30 Nov 2026 16:31:26 -0500 Subject: [PATCH 2/3] A damaged stock backup holds back only its own file When a stock backup isn't the recorded md5 and no NEMESIS copy has it, the plan used to stop as a whole, so every later apply and the uninstall waited until the owner copied a stock file over by hand. Now only that file waits: it's left as it is and never written from the bad copy, the warning names the backup and the md5 it should have, and the rest of the apply or restore goes on. files.json keeps the file's record with "held" (why), `engine status` shows it as CHANGED, and the next apply clears it once a stock copy is in place. `engine restore` ends with code 4 while anything is held, so the uninstall stops before removing HMG-API and its backups. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 7 +- core/runtime/java/hmgapi/engine/Engine.java | 72 +++++++++++++++------ core/runtime/journal-test.sh | 42 ++++++++++-- install/common/uninstall.sh | 2 +- 4 files changed, 94 insertions(+), 29 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index da5f9099..743c60cd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,8 +13,11 @@ own: copied beside, checked against the stock md5, then renamed, so a cut-off copy never sits under the backup's name. An app's odex backup has its md5 recorded now. A restore, uninstall or rebuild never writes a backup that isn't the recorded md5 (a short odex under a stock apk with - no `classes.dex` crashed that app at every launch): a NEMESIS copy with that md5 stands in, or - the engine stops and names the backup and the md5 it should have. + no `classes.dex` crashed that app at every launch): a NEMESIS copy with that md5 stands in. + Without one, only that file waits: it's left as it is, and the apply, restore or uninstall + warns, naming the backup and the md5 it should have; the rest goes on. `engine status` shows + it as CHANGED until the stock file is copied there. `engine restore` then ends with code 4, so + an uninstall stops before removing HMG-API and leaves that file's record and backups in place. - **Room is checked before an apply** writes anything, on `/system` and `/data`. If `/system` filled up anyway, `engine recover` removes the cut-off copy first and, when there's still no room, the file before its saved copy goes back, instead of failing at every start. diff --git a/core/runtime/java/hmgapi/engine/Engine.java b/core/runtime/java/hmgapi/engine/Engine.java index f4f09a9f..1fdea98d 100644 --- a/core/runtime/java/hmgapi/engine/Engine.java +++ b/core/runtime/java/hmgapi/engine/Engine.java @@ -456,13 +456,20 @@ int run(String[] args) throws Exception { return 3; } if ("plan".equals(cmd)) return 0; + int rc = 0; if (p.isEmpty()) { out.add("nothing to do"); if ("apply".equals(cmd)) LiveState.publish(this); // a switch with no file change still reaches running apps - return 0; + } else { + rc = apply(p, trial); + if (rc == 0) LiveState.publish(this); + } + // a file left as it is: everything else is back to stock, but not it, so the uninstall + // (which runs restore first) stops with HMG-API, its record and backups still in place + if (rc == 0 && restoreAll && !p.held.isEmpty()) { + out.add("not all back to stock: " + p.held.size() + " file(s) left as they are (`engine status`)"); + return 4; } - int rc = apply(p, trial); - if (rc == 0) LiveState.publish(this); return rc; } @@ -919,6 +926,7 @@ static final class Target { String odexStock; // app: that odex's md5 (recorded in files.json "odex"; null in an older engine's records) Set mods = new LinkedHashSet(); boolean restore; // no mod wants it any more: back to stock + String held; // its stock backup is damaged and no NEMESIS copy fits: left as it is, and why } final class Plan { @@ -929,10 +937,17 @@ final class Plan { Set settingsRestore = new LinkedHashSet(); Map rebased = new TreeMap(); // path -> live md5: changed outside HMG-API, built on again Map rebasedFrom = new TreeMap(); // path -> what HMG-API had written (merges: checked after build) + Map held = new TreeMap(); // path -> why: owned, left as it is (Target.held) boolean force; // --force: owned files that aren't what HMG-API wrote are written again + @SuppressWarnings("unchecked") boolean isEmpty() throws IOException { if (!rebased.isEmpty()) return false; + Map files = (Map) state.get("files"); + for (Map.Entry f : files.entrySet()) { + Object was = ((Map) f.getValue()).get("held"); + if (was == null ? held.containsKey(f.getKey()) : !was.equals(held.get(f.getKey()))) return false; + } for (Target t : targets.values()) if (t.restore || t.result == null || !t.result.equals(owned(t.path))) return false; if (force) for (Target t : targets.values()) if (!t.result.equals(md5(sys(t.path)))) return false; for (String k : settings.keySet()) if (!String.valueOf(settings.get(k)[0]).equals(ownedSetting(k))) return false; @@ -966,6 +981,7 @@ void report(Engine e) { + (v.isEmpty() ? "(unset)" : v) + " [" + s.getValue()[1] + "]"); } for (String k : settingsRestore) e.out.add("setting " + k + " back to stock"); + for (Map.Entry h : held.entrySet()) e.out.add("WARNING: " + h.getKey() + " is left as it is: " + h.getValue()); String now = currentBinds(); for (Map.Entry b : binds.entrySet()) { String[] w = b.getKey().split(" "); @@ -1160,6 +1176,14 @@ Plan plan(boolean restoreAll, boolean force) throws Exception { restoreFrom(t, f); } } + // a damaged stock backup with no NEMESIS copy that fits: only that file waits (as it is, never + // written from the bad copy, named in `engine status`); the rest of the plan goes on + for (java.util.Iterator it = p.targets.values().iterator(); it.hasNext(); ) { + Target t = it.next(); + if (t.held == null) continue; + p.held.put(t.path, t.held); + it.remove(); + } return p; } @@ -1167,29 +1191,29 @@ Plan plan(boolean restoreAll, boolean force) throws Exception { * A file going back to stock: where its stock bytes (and an app's stock odex) come from. * Each backup is checked against the md5 recorded when it was taken; a damaged one is * never written back (a short odex under a stock apk with no classes.dex: the app - * crashes at every launch). A NEMESIS copy with the recorded md5 stands in, else the - * plan stops, saying which backup and what it should be. + * crashes at every launch). A NEMESIS copy with the recorded md5 stands in, else that file + * is left as it is (Target.held), saying which backup and what it should be. */ void restoreFrom(Target t, Map f) throws IOException { t.stock = (String) f.get("stock"); t.result = t.stock; t.app = Boolean.TRUE.equals(f.get("app")); if (!"absent".equals(t.stock)) { - t.baseline = stockCopy(t.path, t.stock); + t.baseline = stockCopy(t, t.path, t.stock); if (t.baseline == null) return; } if (t.app) { String odex = t.path.replaceAll("\\.apk$", ".odex"); t.odexStock = (String) f.get("odex"); - t.odexSrc = t.odexStock != null ? stockCopy(odex, t.odexStock) : wholeOdex(odex); + t.odexSrc = t.odexStock != null ? stockCopy(t, odex, t.odexStock) : wholeOdex(t, odex); } } /** * HMG-API's backup of a stock file if it has the md5 recorded for it, else a NEMESIS copy - * that does (noted; a rebuild backs it up again); null, with the problem, if neither. + * that does (noted; a rebuild backs it up again); null if neither, with t held and why. */ - File stockCopy(String path, String md5) throws IOException { + File stockCopy(Target t, String path, String md5) throws IOException { File b = backup(path); String have = md5(b); if (have.equals(md5)) return b; @@ -1199,9 +1223,9 @@ File stockCopy(String path, String md5) throws IOException { + "; using the stock copy NEMESIS kept (" + nem.getParentFile().getName() + "), which has the recorded md5 " + md5); return nem; } - problems.add(path + ": HMG-API's stock backup " + b.getPath().substring(root.length()) + " is " + t.held = "HMG-API's stock backup " + b.getPath().substring(root.length()) + " is " + ("absent".equals(have) ? "missing" : "damaged (md5 " + have + ")") + ", not the stock file recorded (md5 " + md5 - + "), so it can't be put back. Copy the stock file (md5 " + md5 + ") there, then try again"); + + "), and no NEMESIS copy has it, so it's never written from it. Copy the stock file (md5 " + md5 + ") there, then apply again"; return null; } @@ -1210,11 +1234,11 @@ File stockCopy(String path, String md5) throws IOException { * its header's opt section) must be as long as its header says; a short one (a cut-off * copy) is refused. Anything else can't be told apart, so it's used as before. */ - File wholeOdex(String odex) throws IOException { + File wholeOdex(Target t, String odex) throws IOException { File b = backup(odex); if (!b.isFile()) { - problems.add(odex + ": HMG-API's backup of the stock odex " + b.getPath().substring(root.length()) - + " is missing, so the stock app (which has no code of its own) can't be put back. Copy the stock odex there, then try again"); + t.held = "HMG-API's backup of the stock odex " + b.getPath().substring(root.length()) + + " is missing, so the stock app (which has no code of its own) can't be put back. Copy the stock odex there, then apply again"; return null; } byte[] h = new byte[40]; @@ -1228,8 +1252,8 @@ File wholeOdex(String odex) throws IOException { if (n == 40 && h[0] == 'd' && h[1] == 'e' && h[2] == 'y' && h[3] == '\n') { long optOff = le32(h, 24), optLen = le32(h, 28); if (b.length() < optOff + optLen) { - problems.add(odex + ": HMG-API's backup of the stock odex " + b.getPath().substring(root.length()) + " is cut short (" - + b.length() + " bytes, its header says " + (optOff + optLen) + "), so it can't be put back. Copy the stock odex there, then try again"); + t.held = "HMG-API's backup of the stock odex " + b.getPath().substring(root.length()) + " is cut short (" + + b.length() + " bytes, its header says " + (optOff + optLen) + "), so the stock app can't be put back. Copy the stock odex there, then apply again"; return null; } } @@ -1455,7 +1479,7 @@ void build(Target t, Map owned) throws Exception { t.stock = (String) owned.get("stock"); if (!"absent".equals(t.stock)) { // rebuilt from the backup only if it's still the stock file recorded (a NEMESIS copy that is stands in) - t.baseline = stockCopy(t.path, t.stock); + t.baseline = stockCopy(t, t.path, t.stock); if (t.baseline == null) return; t.newBackup = !t.baseline.equals(backup(t.path)); } @@ -1631,6 +1655,10 @@ else if (!m.equals(addMd5)) { } if (t.odexSrc != null) break; } + if (t.odexSrc == null && bad != null) { + t.held = bad + ", and no NEMESIS copy fits; " + ch.mod.id + "'s app delta needs the stock odex. Copy it there, then apply again"; + return; + } if (t.odexSrc == null) { problems.add(t.path + ": " + ch.mod.id + "'s app delta doesn't fit this app's stock odex: " + why); return; @@ -2095,6 +2123,11 @@ int apply(Plan p, boolean trial) throws Exception { if (t.app && t.odexStock != null) f.put("odex", t.odexStock); files.put(t.path, f); } + for (Map.Entry e : files.entrySet()) { // left as it is: named until it can be built or put back + Map f = (Map) e.getValue(); + if (p.held.containsKey(e.getKey())) f.put("held", p.held.get(e.getKey())); + else f.remove("held"); + } write(stateFile, Json.write(p.state)); if (trial) { j.put("committed", true); @@ -2340,10 +2373,11 @@ int status() throws Exception { for (Map.Entry e : files.entrySet()) { Map f = (Map) e.getValue(); String live = md5(sys(e.getKey())); - boolean ok = live.equals(f.get("result")); + boolean ok = live.equals(f.get("result")) && f.get("held") == null; if (!ok) bad++; out.add((ok ? "ok " : "CHANGED ") + e.getKey() + " " + f.get("mods") + " stock " + f.get("stock") + ", expected " - + f.get("result") + (ok ? "" : ", found " + live)); + + f.get("result") + (live.equals(f.get("result")) ? "" : ", found " + live) + + (f.get("held") == null ? "" : "; left as it is: " + f.get("held"))); } for (Map.Entry e : ((Map) state.get("settings")).entrySet()) { Map s = (Map) e.getValue(); diff --git a/core/runtime/journal-test.sh b/core/runtime/journal-test.sh index ad9a9b77..3640eb01 100644 --- a/core/runtime/journal-test.sh +++ b/core/runtime/journal-test.sh @@ -212,9 +212,18 @@ check "apply again" 0 $rc head -c 4000 $T/classes.dex > $D/stock/system/app/Test.odex # a cut-off odex backup APK_NOW=$(md5 $R/system/app/Test.apk) eng restore -check "a damaged odex backup: restore refused" 3 $rc -has "... saying which and what it should be" "HMG-API's stock backup /data/hmgapi/stock/system/app/Test.odex is damaged" "$out" +check "a damaged odex backup: restore says not all is stock" 4 $rc +has "... saying which and what it should be" "WARNING: /system/app/Test.apk is left as it is: HMG-API's stock backup /data/hmgapi/stock/system/app/Test.odex is damaged" "$out" check "... the app left as it is (not a stock apk with a short odex)" "$APK_NOW" "$(md5 $R/system/app/Test.apk)" +check "... only that file: the library is stock" "$STOCK_LIB" "$(md5 $R/system/lib/libtest.so)" +check "... and the other app" "$STOCK_PRIV" "$(md5 $R/system/priv-app/Priv.apk)" +check "... its record kept, with why" "(['/system/app/Test.apk'], True)" "$(rec $D/state/files.json 'list(s["files"]), "Test.odex is damaged" in s["files"]["/system/app/Test.apk"]["held"]')" +eng status +check "... status: not all as it should be" 4 $rc +has "... CHANGED, and why" "CHANGED /system/app/Test.apk [base] stock $STOCK_APK, expected $APK_NOW; left as it is: HMG-API's stock backup" "$out" +eng restore +check "... a second restore: the same" 4 $rc +check "... and the damaged backup never written" "$APK_NOW" "$(md5 $R/system/app/Test.apk)" # the priv-app's odex backup has the same stock bytes as Test.odex's mkdir -p $R/data/nemesis/backup/pkg; cp $D/stock/system/priv-app/Priv.odex $R/data/nemesis/backup/pkg/Test.odex eng restore @@ -225,13 +234,19 @@ rm -r $R/data/nemesis eng apply head -c 30000 $R/system/lib/libtest.so > $D/stock/system/lib/libtest.so # a cut-off backup of the library mod rb '{"type": "recipe", "path": "/system/lib/libtest.so", "recipe": "rb.recipe"}' -eng plan -check "a damaged backup: no rebuild from it" 3 $rc -has "... saying so" "HMG-API's stock backup /data/hmgapi/stock/system/lib/libtest.so is damaged" "$out" +LIB_NOW=$(md5 $R/system/lib/libtest.so) +eng apply +check "a damaged backup: the rest of the apply goes on" 0 $rc +has "... the library left as it is, saying why" "WARNING: /system/lib/libtest.so is left as it is: HMG-API's stock backup /data/hmgapi/stock/system/lib/libtest.so is damaged" "$out" +check "... not rebuilt from it" "$LIB_NOW" "$(md5 $R/system/lib/libtest.so)" +check "... its record as it was, with why" "(['base'], True)" "$(rec $D/state/files.json 's["files"]["/system/lib/libtest.so"]["mods"], "held" in s["files"]["/system/lib/libtest.so"]')" +eng status +has "... status names it" "CHANGED /system/lib/libtest.so" "$out" mkdir -p $R/data/nemesis/backup/pkg; cp $T/lib.stock $R/data/nemesis/backup/pkg/libtest.so eng apply check "... rebuilt from a NEMESIS copy with the recorded md5" 0 $rc check "... the backup taken again, whole" "$STOCK_LIB" "$(md5 $D/stock/system/lib/libtest.so)" +check "... no longer held" "(['base', 'rb'], False)" "$(rec $D/state/files.json 's["files"]["/system/lib/libtest.so"]["mods"], "held" in s["files"]["/system/lib/libtest.so"]')" rm -r $R/data/nemesis $D/mods/rb eng apply # an app's rebuild with a damaged odex backup: a NEMESIS copy that fits is used, and backed up again @@ -242,6 +257,19 @@ eng apply --force check "app rebuilt with its odex backup damaged" 0 $rc check "... the odex backup is stock again" "$STOCK_ODEX" "$(md5 $D/stock/system/app/Test.odex)" rm -r $R/data/nemesis +# ... and with no NEMESIS copy that fits: only the app waits +printf 'x' >> $D/stock/system/app/Test.odex +rm $R/system/app/Test.apk +eng apply --force +check "app's odex backup damaged, no NEMESIS copy: the rest goes on" 0 $rc +has "... the app left as it is, saying why" "WARNING: /system/app/Test.apk is left as it is: HMG-API's backup of the stock odex is damaged" "$out" +check "... not written" absent "$(md5 $R/system/app/Test.apk)" +eng status +has "... status names it" "CHANGED /system/app/Test.apk" "$out" +head -c 8192 $D/stock/system/app/Test.odex > $T/odex.fix; cp $T/odex.fix $D/stock/system/app/Test.odex +eng apply --force +check "... the stock odex copied back: built again" 0 $rc +check "... and no longer held" False "$(rec $D/state/files.json '"held" in s["files"]["/system/app/Test.apk"]')" # a record from before the odex md5 was kept: a cut-short Dalvik odex is still caught by its header python3 - $D/state/files.json $D/stock/system/app/Test.odex <<'PY' import json, struct, sys @@ -249,7 +277,7 @@ s = json.load(open(sys.argv[1])); del s["files"]["/system/app/Test.apk"]["odex"] open(sys.argv[2], "wb").write(b"dey\n036\0" + struct.pack("<8I", 40, 1000, 1040, 10, 1050, 90000, 0, 0) + b"\0" * 1000) PY eng restore -check "an older record, odex shorter than its header says: refused" 3 $rc -has "... saying so" "is cut short" "$out" +check "an older record, odex shorter than its header says: not written back" 4 $rc +has "... saying so" "/system/app/Test.apk is left as it is: HMG-API's backup of the stock odex /data/hmgapi/stock/system/app/Test.odex is cut short" "$out" exit $fail diff --git a/install/common/uninstall.sh b/install/common/uninstall.sh index 4b9ac981..371e2587 100644 --- a/install/common/uninstall.sh +++ b/install/common/uninstall.sh @@ -102,7 +102,7 @@ elif [ -z "$ROOT" ] && [ -f "$D/state/files.json" ]; then [ -f "$D/state/journal.json" ] && /system/bin/hmgapid engine recover if ! r=$(/system/bin/hmgapid engine restore 2>&1); then echo "$r" - fail "engine restore didn't finish, so HMG-API stays installed (mods' files must go back first). See the lines above." + fail "engine restore didn't put every file back to stock, so HMG-API stays installed (mods' files must go back first). See the lines above." fi log "mods' changes back to stock" fi From 13b98bef34da998f2db9f9a3b29f9b93913cf8c7 Mon Sep 17 00:00:00 2001 From: anthonyanderson Date: Wed, 2 Dec 2026 11:01:55 -0500 Subject: [PATCH 3/3] Status says what to do about a file left as it is A file held back by a damaged stock backup now carries what the owner can do, beside why: copy the stock file (its md5 named, or the odex the app came with) to the backup's path and run `engine apply`, or open an issue with that line, the car and its software version. The apply's warning ends with it, files.json keeps it as "fix", and `engine status` prints it under the CHANGED line until the file is built or put back. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 +- core/runtime/java/hmgapi/engine/Engine.java | 48 +++++++++++++++------ core/runtime/journal-test.sh | 7 +++ 3 files changed, 45 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5ab0d35d..c8e9ff32 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,7 +16,8 @@ no `classes.dex` crashed that app at every launch): a NEMESIS copy with that md5 stands in. Without one, only that file waits: it's left as it is, and the apply, restore or uninstall warns, naming the backup and the md5 it should have; the rest goes on. `engine status` shows - it as CHANGED until the stock file is copied there. `engine restore` then ends with code 4, so + it as CHANGED, with why and what to do (copy the stock file there and apply, or open an + issue), until it's fixed. A damaged backup is never written back, and nothing overrides that. `engine restore` then ends with code 4, so an uninstall stops before removing HMG-API and leaves that file's record and backups in place. - **Room is checked before an apply** writes anything, on `/system` and `/data`. If `/system` filled up anyway, `engine recover` removes the cut-off copy first and, when there's still no diff --git a/core/runtime/java/hmgapi/engine/Engine.java b/core/runtime/java/hmgapi/engine/Engine.java index 1b631821..9c27b8fc 100644 --- a/core/runtime/java/hmgapi/engine/Engine.java +++ b/core/runtime/java/hmgapi/engine/Engine.java @@ -927,6 +927,7 @@ static final class Target { Set mods = new LinkedHashSet(); boolean restore; // no mod wants it any more: back to stock String held; // its stock backup is damaged and no NEMESIS copy fits: left as it is, and why + String fix; // held: what the owner can do about it } final class Plan { @@ -938,6 +939,7 @@ final class Plan { Map rebased = new TreeMap(); // path -> live md5: changed outside HMG-API, built on again Map rebasedFrom = new TreeMap(); // path -> what HMG-API had written (merges: checked after build) Map held = new TreeMap(); // path -> why: owned, left as it is (Target.held) + Map fix = new TreeMap(); // path -> what the owner can do (Target.fix) boolean force; // --force: owned files that aren't what HMG-API wrote are written again @SuppressWarnings("unchecked") @@ -981,7 +983,8 @@ void report(Engine e) { + (v.isEmpty() ? "(unset)" : v) + " [" + s.getValue()[1] + "]"); } for (String k : settingsRestore) e.out.add("setting " + k + " back to stock"); - for (Map.Entry h : held.entrySet()) e.out.add("WARNING: " + h.getKey() + " is left as it is: " + h.getValue()); + for (Map.Entry h : held.entrySet()) + e.out.add("WARNING: " + h.getKey() + " is left as it is: " + h.getValue() + ". To fix: " + fix.get(h.getKey())); String now = currentBinds(); for (Map.Entry b : binds.entrySet()) { String[] w = b.getKey().split(" "); @@ -1182,6 +1185,7 @@ Plan plan(boolean restoreAll, boolean force) throws Exception { Target t = it.next(); if (t.held == null) continue; p.held.put(t.path, t.held); + p.fix.put(t.path, t.fix); it.remove(); } return p; @@ -1223,9 +1227,9 @@ File stockCopy(Target t, String path, String md5) throws IOException { + "; using the stock copy NEMESIS kept (" + nem.getParentFile().getName() + "), which has the recorded md5 " + md5); return nem; } - t.held = "HMG-API's stock backup " + b.getPath().substring(root.length()) + " is " + hold(t, "HMG-API's stock backup " + b.getPath().substring(root.length()) + " is " + ("absent".equals(have) ? "missing" : "damaged (md5 " + have + ")") + ", not the stock file recorded (md5 " + md5 - + "), and no NEMESIS copy has it, so it's never written from it. Copy the stock file (md5 " + md5 + ") there, then apply again"; + + "), and no NEMESIS copy has it, so it's never written from it", b, md5); return null; } @@ -1237,8 +1241,8 @@ File stockCopy(Target t, String path, String md5) throws IOException { File wholeOdex(Target t, String odex) throws IOException { File b = backup(odex); if (!b.isFile()) { - t.held = "HMG-API's backup of the stock odex " + b.getPath().substring(root.length()) - + " is missing, so the stock app (which has no code of its own) can't be put back. Copy the stock odex there, then apply again"; + hold(t, "HMG-API's backup of the stock odex " + b.getPath().substring(root.length()) + + " is missing, so the stock app (which has no code of its own) can't be put back", b, null); return null; } byte[] h = new byte[40]; @@ -1252,14 +1256,27 @@ File wholeOdex(Target t, String odex) throws IOException { if (n == 40 && h[0] == 'd' && h[1] == 'e' && h[2] == 'y' && h[3] == '\n') { long optOff = le32(h, 24), optLen = le32(h, 28); if (b.length() < optOff + optLen) { - t.held = "HMG-API's backup of the stock odex " + b.getPath().substring(root.length()) + " is cut short (" - + b.length() + " bytes, its header says " + (optOff + optLen) + "), so the stock app can't be put back. Copy the stock odex there, then apply again"; + hold(t, "HMG-API's backup of the stock odex " + b.getPath().substring(root.length()) + " is cut short (" + + b.length() + " bytes, its header says " + (optOff + optLen) + "), so the stock app can't be put back", b, null); return null; } } return b; } + /** + * A file left as it is (a damaged stock backup, no NEMESIS copy that fits): why, and what the + * owner can do, shown by the apply's warning and by `engine status` until it's fixed. + */ + void hold(Target t, String why, File backup, String md5) { + t.held = why; + t.fix = "copy " + (md5 != null ? "the stock file (md5 " + md5 + ")" : "the stock odex this app came with") + " to " + + backup.getPath().substring(root.length()) + ", then run `engine apply`: it's checked before it's used, and the" + + " file is built or put back. No copy at hand? Open an issue at https://github.com/Open-HMG/HMG-API/issues/new/choose" + + " with this line, your car and its head unit software version. Until then the file stays as it is and works as" + + " before, and an uninstall stops before removing HMG-API"; + } + static long le32(byte[] b, int at) { return (b[at] & 0xffL) | (b[at + 1] & 0xffL) << 8 | (b[at + 2] & 0xffL) << 16 | (b[at + 3] & 0xffL) << 24; } @@ -1630,11 +1647,12 @@ else if (!m.equals(addMd5)) { // (lpatch only builds from the exact stock bytes, so trying each is safe) String odexPath = t.path.replaceAll("\\.apk$", ".odex"); List odexes = new ArrayList(); - String bad = null; + String bad = null, rec = null; if (owned != null) { // the live odex is HMG-API's dexopt output now, never stock. A backup that isn't the // recorded md5 is left out; NEMESIS's copies stand in (backed up again at apply) - String rec = (String) owned.get("odex"), have = md5(backup(odexPath)); + rec = (String) owned.get("odex"); + String have = md5(backup(odexPath)); if (rec == null || rec.equals(have)) odexes.add(backup(odexPath)); else bad = "HMG-API's backup of the stock odex is " + ("absent".equals(have) ? "missing" : "damaged (" + have + ")") + ", recorded " + rec; @@ -1656,7 +1674,7 @@ else if (!m.equals(addMd5)) { if (t.odexSrc != null) break; } if (t.odexSrc == null && bad != null) { - t.held = bad + ", and no NEMESIS copy fits; " + ch.mod.id + "'s app delta needs the stock odex. Copy it there, then apply again"; + hold(t, bad + ", and no NEMESIS copy fits; " + ch.mod.id + "'s app delta needs the stock odex", backup(odexPath), rec); return; } if (t.odexSrc == null) { @@ -2125,8 +2143,13 @@ int apply(Plan p, boolean trial) throws Exception { } for (Map.Entry e : files.entrySet()) { // left as it is: named until it can be built or put back Map f = (Map) e.getValue(); - if (p.held.containsKey(e.getKey())) f.put("held", p.held.get(e.getKey())); - else f.remove("held"); + if (p.held.containsKey(e.getKey())) { + f.put("held", p.held.get(e.getKey())); + f.put("fix", p.fix.get(e.getKey())); + } else { + f.remove("held"); + f.remove("fix"); + } } write(stateFile, Json.write(p.state)); if (trial) { @@ -2378,6 +2401,7 @@ int status() throws Exception { out.add((ok ? "ok " : "CHANGED ") + e.getKey() + " " + f.get("mods") + " stock " + f.get("stock") + ", expected " + f.get("result") + (live.equals(f.get("result")) ? "" : ", found " + live) + (f.get("held") == null ? "" : "; left as it is: " + f.get("held"))); + if (f.get("held") != null) out.add(" to fix: " + f.get("fix")); } for (Map.Entry e : ((Map) state.get("settings")).entrySet()) { Map s = (Map) e.getValue(); diff --git a/core/runtime/journal-test.sh b/core/runtime/journal-test.sh index 3640eb01..97ea50cb 100644 --- a/core/runtime/journal-test.sh +++ b/core/runtime/journal-test.sh @@ -221,6 +221,8 @@ check "... its record kept, with why" "(['/system/app/Test.apk'], True)" "$(rec eng status check "... status: not all as it should be" 4 $rc has "... CHANGED, and why" "CHANGED /system/app/Test.apk [base] stock $STOCK_APK, expected $APK_NOW; left as it is: HMG-API's stock backup" "$out" +has "... and what the owner can do" " to fix: copy the stock file (md5 $STOCK_ODEX) to /data/hmgapi/stock/system/app/Test.odex, then run \`engine apply\`" "$out" +has "... or who to ask" "Open an issue at https://github.com/Open-HMG/HMG-API/issues/new/choose" "$out" eng restore check "... a second restore: the same" 4 $rc check "... and the damaged backup never written" "$APK_NOW" "$(md5 $R/system/app/Test.apk)" @@ -242,6 +244,7 @@ check "... not rebuilt from it" "$LIB_NOW" "$(md5 $R/system/lib/libtest.so)" check "... its record as it was, with why" "(['base'], True)" "$(rec $D/state/files.json 's["files"]["/system/lib/libtest.so"]["mods"], "held" in s["files"]["/system/lib/libtest.so"]')" eng status has "... status names it" "CHANGED /system/lib/libtest.so" "$out" +has "... with what to do" "to fix: copy the stock file (md5 $STOCK_LIB) to /data/hmgapi/stock/system/lib/libtest.so" "$out" mkdir -p $R/data/nemesis/backup/pkg; cp $T/lib.stock $R/data/nemesis/backup/pkg/libtest.so eng apply check "... rebuilt from a NEMESIS copy with the recorded md5" 0 $rc @@ -263,6 +266,7 @@ rm $R/system/app/Test.apk eng apply --force check "app's odex backup damaged, no NEMESIS copy: the rest goes on" 0 $rc has "... the app left as it is, saying why" "WARNING: /system/app/Test.apk is left as it is: HMG-API's backup of the stock odex is damaged" "$out" +has "... and what to do" ". To fix: copy the stock file (md5 $STOCK_ODEX) to /data/hmgapi/stock/system/app/Test.odex" "$out" check "... not written" absent "$(md5 $R/system/app/Test.apk)" eng status has "... status names it" "CHANGED /system/app/Test.apk" "$out" @@ -279,5 +283,8 @@ PY eng restore check "an older record, odex shorter than its header says: not written back" 4 $rc has "... saying so" "/system/app/Test.apk is left as it is: HMG-API's backup of the stock odex /data/hmgapi/stock/system/app/Test.odex is cut short" "$out" +has "... no md5 recorded: says which odex" "To fix: copy the stock odex this app came with to /data/hmgapi/stock/system/app/Test.odex" "$out" +eng status +has "... status says so too" "to fix: copy the stock odex this app came with" "$out" exit $fail