diff --git a/CHANGELOG.md b/CHANGELOG.md index 5f898a92..5aed0582 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,33 @@ # Changelog +## Unreleased + +- **A root service can read its own settings** (`HmgApi.settings()`, `saveSettings()`): the + daemon sees such a service as root, so the client names its mod (`HMGAPI_MOD`). +- **A failed apply is rolled back at once.** When a rename, a dexopt, a remount or a copy + failed part-way, /system stayed half-applied (one library new, the next stock, an app's + odex deleted) until the next start, and every other engine command was refused. Now the + same run puts every file and setting back, last changed first, deletes its temp files + (`*.hmgapi-new`, `stage/`), and starts the apps it stopped. Only a power cut, a killed + engine or a rollback that fails too leaves the journal for the next start (`engine recover`). +- **Apps stopped during an apply always come back.** The apps whose files change (GPM, + DiPO, iAP2, navigation, BtSettings) are `pm disable`d for the swap, and Android keeps them + off across restarts. The list lived only in memory, so a power cut (the driver's door, the + battery saver) or a killed engine left them off for good. It's now written to the journal + and `state/held.txt` before any is stopped; `engine recover` starts them again, and at boot, + once Android is up, `engine release-held` does (only with no unfinished apply left, so they + never run on half-changed files). Android itself (`framework-res.apk`), persistent apps + (`packages.xml`), OTAClient and apps that were off already are never stopped; an app + `pm` won't stop keeps running, as before. +- **File modes, owners and SELinux labels are kept.** Every file was written, restored and + rolled back as 644 root:root, whatever it was: uninstalling a mod that patched a binary in + `/system/bin` put the stock one back unable to run. Each file's own mode, owner and label + are now read before HMG-API first writes it and put back on restore and rollback; a change + with no `"mode"` keeps them. A new file under `/system/bin` or `/system/xbin` with no `"mode"` + is refused. Files recorded by an earlier HMG-API get Android's defaults on restore (755 + root:shell in `/system/bin` and `/system/xbin`, 644 root:root elsewhere). + Tested off-car only. + ## 1.1.0 (2026-11-28) 1.1.0-rc.10's code: only the version, this heading and the release notes changed. It is the diff --git a/core/runtime/engine-test.sh b/core/runtime/engine-test.sh index 89634abd..d8d390fd 100644 --- a/core/runtime/engine-test.sh +++ b/core/runtime/engine-test.sh @@ -433,4 +433,197 @@ for i in 1 2 3; do done echo "ok three plans at once on a fresh mod, three rounds" check "... the feature file written once, no .tmp left" "android.hardware.wifi.xml" "$(ls -A $R/data/hmgapi/mods/wa/.features)" + +# ---- a failed apply: rolled back in the same run; a cut-off one: by recover. Apps held while +# their files change are journaled first and always started again; modes, owners, labels kept. +# Off the unit, owners and labels live in $R/meta.txt (FileMeta), the mode is the file's own. +rm -rf $R/data/hmgapi/mods/* $R/data/hmgapi/state $R/data/hmgapi/stock +check "app stock before" "$STOCK_APK $STOCK_ODEX" "$(md5 $R/system/app/Test.apk) $(md5 $R/system/app/Test.odex)" +mkdir -p $R/system/bin $R/system/framework $R/data/system +. core/runtime/test-meta.sh +for f in lib/a.so lib/z.so bin/netd framework/framework-res.apk app/Pers.apk app/Off.apk app/Two.apk; do + head -c 4096 /dev/urandom > $R/system/$f; head -c 4096 /dev/urandom > $T/m/$(basename $f).new +done +chmod 640 $R/system/lib/a.so; chmod 644 $R/system/lib/z.so; chmod 755 $R/system/bin/netd +printf '%s\n' "/system/lib/a.so 1000 1000 u:object_r:system_file:s0" "/system/bin/netd 0 2000 u:object_r:netd_exec:s0" > $R/meta.txt +cp -p $R/meta.txt $T/meta.stock +OWN_A=$(own /system/lib/a.so); OWN_Z=$(own /system/lib/z.so); OWN_N=$(own /system/bin/netd) +check "stock modes and owners set up" "640 1000 1000 u:object_r:system_file:s0|644 0 0 -|755 0 2000 u:object_r:netd_exec:s0" "$OWN_A|$OWN_Z|$OWN_N" +sums() { for f in lib/a.so lib/z.so bin/netd app/Test.apk app/Test.odex framework/framework-res.apk app/Pers.apk app/Off.apk app/Two.apk; do md5 $R/system/$f; done | tr '\n' ' '; } +STOCK_ALL=$(sums) +# a package manager: Test.apk's and Two.apk's apps run (PM_REFUSE names one it won't stop), Off.apk's is off already, Pers.apk's is persistent, framework-res is android +cat > $T/pm <> $T/pm.calls +case "\$1 \$2" in + "list packages") if [ "\$3" = -f ]; then cat $T/pm.pkgs; else sed 's/^/package:/' $T/pm.off; fi ;; + "disable "*) if [ "\$2" = "\$PM_REFUSE" ]; then echo "Error: refused"; exit 1; fi + echo "\$2" >> $T/pm.off; echo "Package \$2 new state: disabled" ;; + "enable "*) grep -vx "\$2" $T/pm.off > $T/pm.off.n || true; mv $T/pm.off.n $T/pm.off; echo "Package \$2 new state: enabled" ;; +esac +EOF +chmod +x $T/pm +printf 'package:%s\n' /system/app/Test.apk=com.test.app /system/app/Two.apk=com.test.two /system/app/Off.apk=com.test.off /system/app/Pers.apk=com.test.pers \ + /system/framework/framework-res.apk=android > $T/pm.pkgs +cat > $R/data/system/packages.xml <<'X' + + + + + + + + +X +pmreset() { echo com.test.off > $T/pm.off; rm -f $T/pm.calls; } +# engf ": ...": eng with those steps failing (Engine.testFail); exported and unset again, since +# sh keeps a variable put before a function call +engf() { HMGAPI_TEST_FAIL=$1; export HMGAPI_TEST_FAIL; shift; eng "$@"; unset HMGAPI_TEST_FAIL; } +pmreset +export HMGAPI_PM=$T/pm HMGAPI_PROPS="sys.boot_completed=1" +mod rb 1.0.0 '' ' + {"type": "add", "path": "/system/lib/a.so", "src": "a.so.new", "stock": "any"}, + {"type": "add", "path": "/system/lib/z.so", "src": "z.so.new", "stock": "any"}, + {"type": "add", "path": "/system/bin/netd", "src": "netd.new", "stock": "any", "mode": "755"}, + {"type": "app", "path": "/system/app/Test.apk", "delta": "Test.lpd"}, + {"type": "add", "path": "/system/framework/framework-res.apk", "src": "framework-res.apk.new", "stock": "any"}, + {"type": "add", "path": "/system/app/Pers.apk", "src": "Pers.apk.new", "stock": "any"}, + {"type": "add", "path": "/system/app/Off.apk", "src": "Off.apk.new", "stock": "any"}, + {"type": "add", "path": "/system/app/Two.apk", "src": "Two.apk.new", "stock": "any"}' +cp $T/m/*.new $T/m/Test.lpd $R/data/hmgapi/mods/rb/ +J=$R/data/hmgapi/state/journal.json; HELD=$R/data/hmgapi/state/held.txt +left() { find $R/system -name '*.hmgapi-new' | tr '\n' ' '; } +allstock() { # allstock : every file, mode, owner and label as before, nothing left over, apps as before + check "$1: every file as it was" "$STOCK_ALL" "$(sums)" + check "$1: modes, owners, labels as they were" "$OWN_A|$OWN_Z|$OWN_N" "$(own /system/lib/a.so)|$(own /system/lib/z.so)|$(own /system/bin/netd)" + check "$1: no journal, no prev/, no held list, no temp files" "no no no " "$([ -f $J ] && echo yes || echo no) $([ -d $R/data/hmgapi/state/prev ] && echo yes || echo no) $([ -f $HELD ] && echo yes || echo no) $(left)" + check "$1: the apps it held started again; the one off before still off" "com.test.off" "$(cat $T/pm.off)" +} + +engf "swap:/system/lib/z.so" apply +check "a swap failing part-way (a.so written, z.so not): the apply fails" 1 $rc +has "... saying why" "apply failed: java.io.IOException: test: swap fails at /system/lib/z.so" "$out" +has "... rolled back in the same run, last written first" "rolled back /system/lib/a.so" "$out" +has "... all of it" "rolled back: every file is as it was before this apply" "$out" +allstock "swap failure" +has "... the app was stopped first, then started again" "disable com.test.app|" "$(tr '\n' '|' < $T/pm.calls)" +hasnt "... Android itself (framework-res.apk) never stopped" "disable android" "$(cat $T/pm.calls)" +hasnt "... nor a persistent app" "disable com.test.pers" "$(cat $T/pm.calls)" +hasnt "... nor one that was off already (or started)" "com.test.off" "$(grep -v '^list' $T/pm.calls)" +has "... said" "note com.test.pers keeps running while /system/app/Pers.apk changes (persistent)" "$out" +check "... no record of the failed apply" "" "$(grep -o 'a\.so' $R/data/hmgapi/state/files.json 2>/dev/null || true)" +eng plan +check "... other commands aren't refused after it" 0 $rc + +pmreset +engf "dexopt:/system/app/Test.apk" apply +check "dexopt failing (the odex deleted already): the apply fails" 1 $rc +allstock "dexopt failure" +check "... the odex back" "$STOCK_ODEX" "$(md5 $R/system/app/Test.odex)" + +pmreset +engf "put:/system/lib/z.so" apply +check "a copy failing: the apply fails" 1 $rc +allstock "copy failure (its temp file deleted)" + +pmreset +engf "remount:rw" apply +check "remount rw failing: the apply fails" 1 $rc +allstock "remount failure" +hasnt "... nothing had changed, so nothing rolled back" "rolled back /system" "$out" + +# pm throwing at the second app it stops: the first, off already, is still started again +pmreset +engf "disable:com.test.two" apply +check "pm failing at the second app: the apply fails" 1 $rc +has "... saying why" "apply failed: java.io.IOException: test: disable fails at com.test.two" "$out" +allstock "pm failing mid-hold" +has "... the first app stopped, then started again" "disable com.test.app|enable com.test.app|" "$(grep -v '^list' $T/pm.calls | tr '\n' '|')" + +# pm refusing to stop an app: it keeps running (as before), isn't listed as held, isn't started "again" +pmreset +PM_REFUSE=com.test.two; export PM_REFUSE +engf "swap:/system/lib/z.so" apply +unset PM_REFUSE +check "pm refusing one app (then a swap failing): the apply fails" 1 $rc +has "... the refusal said" "WARNING: couldn't stop com.test.two (Error: refused); it keeps running while its files change" "$out" +has "... only the app that stopped listed" "stopped [com.test.app] while their files change" "$out" +hasnt "... nor started again" "enable com.test.two" "$(cat $T/pm.calls)" +allstock "pm refusing an app" + +# pm failing as an app starts again: the apply's own failure is what's said, the other app starts, +# the one that didn't stays in held.txt for release-held +pmreset +engf "swap:/system/lib/z.so enable:com.test.app" apply +check "pm failing at release: the apply fails" 1 $rc +has "... with its own reason" "apply failed: java.io.IOException: test: swap fails at /system/lib/z.so" "$out" +has "... rolled back" "rolled back: every file is as it was before this apply" "$out" +has "... the other app started" "started [com.test.two] again" "$out" +check "... the one that didn't: in held.txt, still off" "com.test.app|com.test.app com.test.off" "$(cat $HELD)|$(sort $T/pm.off | tr '\n' ' ' | sed 's/ $//')" +eng release-held +check "... release-held starts it" 0 $rc +allstock "pm failing at release, then release-held" + +# a power cut (or a killed engine) in the middle: a.so new, z.so stock, the app off +pmreset +engf "halt:/system/lib/z.so" apply +check "cut off mid-swap: the journal stays" yes "$([ -f $J ] && echo yes)" +check "... a.so new, z.so stock" "$(md5 $T/m/a.so.new) $(md5 $R/data/hmgapi/state/prev/_system_lib_z.so)" "$(md5 $R/system/lib/a.so) $(md5 $R/system/lib/z.so)" +check "... the held apps journaled before they were stopped, and still off" "com.test.app com.test.two|com.test.app com.test.two" "$(tr '\n' ' ' < $HELD | sed 's/ $//')|$(python3 -c 'import json,sys; print(" ".join(json.load(open(sys.argv[1]))["held"]))' $J)" +has "... (off in the package manager)" "com.test.app" "$(cat $T/pm.off)" +eng plan +check "... other commands wait for recover" 1 $rc +eng status +has "... status names the held apps" "held [com.test.app, com.test.two]" "$out" +export HMGAPI_PROPS="" # recover at boot runs before Android is up +eng recover +check "recover before Android is up" 0 $rc +has "... rolled back" "unfinished apply rolled back" "$out" +check "... files, modes, owners back" "$STOCK_ALL|$OWN_A|$OWN_Z|$OWN_N" "$(sums)|$(own /system/lib/a.so)|$(own /system/lib/z.so)|$(own /system/bin/netd)" +has "... the app left for boot.sh" "start again once Android is up (boot.sh: engine release-held)" "$out" +check "... still in held.txt" "com.test.app com.test.two" "$(tr '\n' ' ' < $HELD | sed 's/ $//')" +eng release-held +check "release-held with Android not up: waits" 1 $rc +export HMGAPI_PROPS="sys.boot_completed=1" +eng release-held +check "release-held once Android is up" 0 $rc +allstock "power cut, then recover and release-held" + +# the rollback fails too: the journal stays, the apps stay off with their files half-changed, recover finishes later +pmreset +engf "swap:/system/lib/z.so rollback:/system/lib/a.so" apply +check "a rollback that fails too: the apply fails" 1 $rc +has "... said" "NOT rolled back: [/system/lib/a.so (test: rollback fails at /system/lib/a.so)]" "$out" +check "... the journal kept" yes "$([ -f $J ] && echo yes)" +has "... the app stays off" "com.test.app" "$(cat $T/pm.off)" +eng release-held +check "... release-held won't start it over half-changed files" 1 $rc +eng recover +check "... recover finishes it" 0 $rc +allstock "failed rollback, then recover" + +# a good apply: modes and owners kept, a mod's mode used, stock ones recorded; restore puts them back +pmreset +eng apply +check "apply" 0 $rc +check "a file with no mode keeps its stock mode, owner and label" "$OWN_A" "$(own /system/lib/a.so)" +check "netd: the mod's mode, the stock owner and label" "$OWN_N" "$(own /system/bin/netd)" +check "the held app started again" "com.test.off" "$(cat $T/pm.off)" +check "no held list left" no "$([ -f $HELD ] && echo yes || echo no)" +check "stock modes recorded" "640 1000 1000 u:object_r:system_file:s0" "$(python3 -c 'import json, sys; m = json.load(open(sys.argv[1]))["files"]["/system/lib/a.so"]["stockMeta"]["/system/lib/a.so"]; print(m["mode"], m["uid"], m["gid"], m["context"])' $R/data/hmgapi/state/files.json)" +eng restore +check "restore" 0 $rc +check "restore: files, modes, owners, labels stock" "$STOCK_ALL|$OWN_A|$OWN_Z|$OWN_N" "$(sums)|$(own /system/lib/a.so)|$(own /system/lib/z.so)|$(own /system/bin/netd)" +# a record from before modes were kept, and netd as that HMG-API wrote it (644 0:0): restore uses /system/bin's 755 0:2000 +eng apply +python3 - $R/data/hmgapi/state/files.json <<'PY' +import json, sys +s = json.load(open(sys.argv[1])) +for f in s["files"].values(): f.pop("stockMeta", None) +json.dump(s, open(sys.argv[1], "w")) +PY +chmod 644 $R/system/bin/netd; sed -i.bak '/^\/system\/bin\/netd /d' $R/meta.txt +eng restore +check "restore of an old record: /system/bin's defaults" "755 0 2000 -" "$(own /system/bin/netd)" +unset HMGAPI_PM HMGAPI_PROPS exit $fail diff --git a/core/runtime/java/hmgapi/engine/Engine.java b/core/runtime/java/hmgapi/engine/Engine.java index 9557ac56..9d83ae75 100644 --- a/core/runtime/java/hmgapi/engine/Engine.java +++ b/core/runtime/java/hmgapi/engine/Engine.java @@ -26,7 +26,8 @@ * engine keep keep a trial apply * engine restore every file and setting HMG-API changed back to stock * engine status files HMG-API owns: stock, mods, expected and live md5 - * engine recover at start (hmgapid): roll back an unfinished or trial apply + * engine recover at start (hmgapid): roll back an unfinished or trial apply, start the apps it held + * engine release-held at start, once Android is up: start apps an apply left stopped (state/held.txt) * * Mods: /data/hmgapi/mods//patches.json (see the wiki's patch engine page). * The goal: mods work side by side and never overwrite each other. HMG-API @@ -423,6 +424,7 @@ int run(String[] args) throws Exception { } if ("nemesis-sync".equals(cmd)) return NemesisSync.run(this); if ("recover".equals(cmd)) return recover(); + if ("release-held".equals(cmd)) return releaseHeld(); if ("keep".equals(cmd)) return keep(); if ("firmware-reset".equals(cmd)) return firmwareReset(); if (journalFile.exists() && !"keep".equals(cmd)) { @@ -437,7 +439,7 @@ int run(String[] args) throws Exception { if (!map.runnable) out.add("hooks are off on this car (" + map.reason + "): mods apply without their hooks"); } if (!restoreAll && !"plan".equals(cmd) && !"apply".equals(cmd)) { - out.add("usage: engine plan | apply [--trial] | keep | restore | status | recover | firmware-reset | install | remove | nemesis-sync | map | map-car [--local [--if-needed] | --write | --forget] | verify-map | report [--usb] | usb-scan | update-hmgapi | publish-state | apps"); + out.add("usage: engine plan | apply [--trial] | keep | restore | status | recover | release-held | firmware-reset | install | remove | nemesis-sync | map | map-car [--local [--if-needed] | --write | --forget] | verify-map | report [--usb] | usb-scan | update-hmgapi | publish-state | apps"); return 2; } Plan p = plan(restoreAll, force); @@ -918,6 +920,7 @@ static final class Target { File odexSrc; // app: the stock odex its delta was built from (backed up at apply) Set mods = new LinkedHashSet(); boolean restore; // no mod wants it any more: back to stock + Map stockMeta; // path (and an app's odex) -> FileMeta's map, as before HMG-API's first write } final class Plan { @@ -1120,6 +1123,7 @@ Plan plan(boolean restoreAll, boolean force) throws Exception { t.stock = (String) f.get("stock"); t.result = t.stock; t.app = Boolean.TRUE.equals(f.get("app")); + t.stockMeta = f.get("stockMeta") instanceof Map ? (Map) f.get("stockMeta") : null; continue; } int before = problems.size(); @@ -1154,6 +1158,7 @@ Plan plan(boolean restoreAll, boolean force) throws Exception { t.stock = (String) f.get("stock"); t.result = t.stock; t.app = Boolean.TRUE.equals(f.get("app")); + t.stockMeta = f.get("stockMeta") instanceof Map ? (Map) f.get("stockMeta") : null; } } return p; @@ -1313,6 +1318,12 @@ String guard(Target t) { return null; } + /** the "mode" a target's changes give it (the first that gives one), or null */ + static String modeOf(Target t) { + for (Ch ch : t.changes) if (ch.c.get("mode") != null) return String.valueOf(ch.c.get("mode")); + return null; + } + @SuppressWarnings("unchecked") boolean allowedCritical(String what) { Object o = hmgapi.get("overrides"); @@ -1343,6 +1354,7 @@ 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); + t.stockMeta = owned.get("stockMeta") instanceof Map ? (Map) owned.get("stockMeta") : null; } else { String m = md5(live); if ("absent".equals(m)) { @@ -1392,6 +1404,12 @@ void build(Target t, Map owned) throws Exception { } } } + // a file with a stock copy keeps that copy's mode, owner and label (targetMeta); a new one in + // /system/bin or /system/xbin would get 644 and not run, so its mod has to say the mode + if ("absent".equals(t.stock) && (t.path.startsWith("/system/bin/") || t.path.startsWith("/system/xbin/")) && modeOf(t) == null) { + problems.add(t.path + ": " + t.changes.get(0).mod.id + ": a new file in /system/bin or /system/xbin needs a \"mode\" (\"755\" for a program)"); + return; + } // what may be combined List excl = new ArrayList(); for (Ch ch : t.changes) { @@ -1827,6 +1845,14 @@ File find(File dir, String path, Set accepted, int depth) { // ------------------------------------------------------------------ apply + /** + * One transaction. The journal (what each file was, its bytes in prev/, its mode, owner and + * label) goes down before anything changes, the apps holding changed files are written into + * it before they're stopped, and any failure (a rename, a dexopt, a remount, a full disk) + * puts every file and setting back in this same run, last changed first, then starts the + * apps again. Only a cut-off run (a power cut, a killed engine) or a rollback that fails + * too leaves the journal for the next start (boot.sh: engine recover). + */ @SuppressWarnings("unchecked") void apply(Plan p, boolean trial) throws Exception { Map files = (Map) p.state.get("files"); @@ -1842,6 +1868,9 @@ void apply(Plan p, boolean trial) throws Exception { prevDir.mkdirs(); List entries = new ArrayList(); for (Target t : changed) { + // a file HMG-API hasn't written yet: its mode, owner and label as found are its stock ones (restore puts them back) + boolean first = !t.restore && t.stockMeta == null && p.owned(t.path) == null; + Map sm = new LinkedHashMap(); for (String path : withOdex(t)) { Map e = new LinkedHashMap(); e.put("path", path); @@ -1850,109 +1879,175 @@ void apply(Plan p, boolean trial) throws Exception { File prev = new File(prevDir, path.replace('/', '_')); copy(live, prev); e.put("prev", prev.getPath()); - e.put("mode", mode(live)); + Map meta = FileMeta.read(this, live).toMap(); + e.putAll(meta); + if (first) sm.put(path, meta); } entries.add(e); } + if (!sm.isEmpty()) t.stockMeta = sm; } Map j = new LinkedHashMap(); j.put("trial", trial); j.put("committed", false); j.put("entries", entries); + j.put("held", new ArrayList()); j.put("state", Json.parse(Json.write(p.state))); // a copy: p.state changes below write(journalFile, Json.write(j)); - // files taken as found (changed outside HMG-API): their old backups no longer say what was there - for (String path : p.rebased.keySet()) { - rm(backup(path)); - if (path.endsWith(".apk")) rm(backup(path.replaceAll("\\.apk$", ".odex"))); - } - // stock backups, once - 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)); + Set held = new LinkedHashSet(); + List settingsUndo = new ArrayList(); // {key, live value before}, in the order set + String bindsBefore = currentBinds(); + boolean rw = false, keepHeld = false; + try { + // files taken as found (changed outside HMG-API): their old backups no longer say what was there + for (String path : p.rebased.keySet()) { + rm(backup(path)); + if (path.endsWith(".apk")) rm(backup(path.replaceAll("\\.apk$", ".odex"))); + } + // stock backups, once + 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)); + } } - } - Set held = hold(changed); - try { + hold(changed, j, held); remount("rw"); + rw = true; for (Target t : changed) swap(t); - } finally { + rw = false; remount("ro"); - release(held); - } - // settings - for (Map.Entry e : p.settings.entrySet()) { - String k = e.getKey(); - String v = String.valueOf(e.getValue()[0]); - Map s = (Map) st.get(k); - if (s != null && v.equals(String.valueOf(s.get("value")))) continue; - String was; - if (s == null) { - s = new LinkedHashMap(); - s.put("stock", settingGet(k)); - st.put(k, s); - was = s.get("stock") == null ? "" : String.valueOf(s.get("stock")); + // settings + for (Map.Entry e : p.settings.entrySet()) { + String k = e.getKey(); + String v = String.valueOf(e.getValue()[0]); + Map s = (Map) st.get(k); + if (s != null && v.equals(String.valueOf(s.get("value")))) continue; + String was; + if (s == null) { + s = new LinkedHashMap(); + s.put("stock", settingGet(k)); + st.put(k, s); + was = s.get("stock") == null ? "" : String.valueOf(s.get("stock")); + } else { + was = String.valueOf(s.get("value")); + } + boolean live = !v.equals(was); // mirror/restart only when the value really changes + // already the wanted value: only take it over. Setting it again isn't harmless: + // init re-runs its triggers (persist.sys.usb.config re-enumerated USB and dropped adb) + if (live) { + settingsUndo.add(new String[] { k, settingGet(k) }); + settingPut(k, v); + } + s.put("value", v); + s.put("mod", e.getValue()[1]); + Map c = (Map) e.getValue()[2]; + if (c != null && c.get("mirror") != null) s.put("mirror", c.get("mirror")); + else s.remove("mirror"); + if (c != null && c.get("restart") != null) s.put("restart", c.get("restart")); + else s.remove("restart"); + if (live) after(s, v); + out.add("set " + k + " = " + (v.isEmpty() ? "(unset)" : v)); + } + for (String k : p.settingsRestore) { + Map s = (Map) st.remove(k); + settingsUndo.add(new String[] { k, settingGet(k) }); + settingPut(k, s.get("stock") == null ? null : String.valueOf(s.get("stock"))); + String back = s.get("stock") == null ? "" : String.valueOf(s.get("stock")); + if (!back.equals(String.valueOf(s.get("value")))) after(s, back); + out.add("set " + k + " back to " + s.get("stock")); + } + + // 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(bindsBefore)) { + write(new File(stateDir, "binds.txt"), bt); + new File(stateDir, "binds.failed").delete(); + bindsChanged = true; + } + + // state + for (Target t : changed) { + if (t.restore) { + files.remove(t.path); + continue; + } + Map f = new LinkedHashMap(); + f.put("stock", t.stock); + f.put("result", t.result); + f.put("mods", new ArrayList(t.mods)); + if (t.app) f.put("app", true); + if (t.stockMeta != null) f.put("stockMeta", t.stockMeta); + files.put(t.path, f); + } + write(stateFile, Json.write(p.state)); + if (trial) { + j.put("committed", true); + write(journalFile, Json.write(j)); + out.add("trial: undone at the next start unless you run `engine keep`"); } else { - was = String.valueOf(s.get("value")); - } - boolean live = !v.equals(was); // mirror/restart only when the value really changes - // already the wanted value: only take it over. Setting it again isn't harmless: - // init re-runs its triggers (persist.sys.usb.config re-enumerated USB and dropped adb) - if (live) settingPut(k, v); - s.put("value", v); - s.put("mod", e.getValue()[1]); - Map c = (Map) e.getValue()[2]; - if (c != null && c.get("mirror") != null) s.put("mirror", c.get("mirror")); - else s.remove("mirror"); - if (c != null && c.get("restart") != null) s.put("restart", c.get("restart")); - else s.remove("restart"); - if (live) after(s, v); - out.add("set " + k + " = " + (v.isEmpty() ? "(unset)" : v)); - } - for (String k : p.settingsRestore) { - Map s = (Map) st.remove(k); - settingPut(k, s.get("stock") == null ? null : String.valueOf(s.get("stock"))); - String back = s.get("stock") == null ? "" : String.valueOf(s.get("stock")); - if (!back.equals(String.valueOf(s.get("value")))) after(s, back); - out.add("set " + k + " back to " + s.get("stock")); - } - - // 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(); - bindsChanged = true; - } - - // state - for (Target t : changed) { - if (t.restore) { - files.remove(t.path); - continue; + journalFile.delete(); + rm(prevDir); + } + } catch (Throwable failure) { + out.add("apply failed: " + failure); + // settings and binds as they were, nothing left to run after the output + for (int i = settingsUndo.size() - 1; i >= 0; i--) { + try { + settingPut(settingsUndo.get(i)[0], settingsUndo.get(i)[1]); + } catch (Exception x) { + out.add("WARNING: couldn't put " + settingsUndo.get(i)[0] + " back to " + settingsUndo.get(i)[1] + ": " + x); + } + } + mirrors.clear(); + restarts.clear(); + if (bindsChanged) { + write(new File(stateDir, "binds.txt"), bindsBefore); + bindsChanged = false; + } + if (rw) { + rw = false; + try { + remount("ro"); + } catch (Exception ignored) { + // the rollback remounts for itself + } + } + List left = rollback(j); + if (left.isEmpty()) { + journalFile.delete(); + rm(prevDir); + out.add("rolled back: every file is as it was before this apply"); + } else { + keepHeld = true; + out.add("NOT rolled back: " + left); + out.add("the next start tries again (`engine recover`); " + (held.isEmpty() ? "" : held + " stay off until then; ") + + "other engine commands wait for it"); + } + rm(stageDir); + throw failure; + } finally { + try { + if (rw) remount("ro"); + } finally { // held apps start again even if that throws + if (!keepHeld && !held.isEmpty()) { + List still = new ArrayList(release(held)); + if (journalFile.exists()) { // a trial waiting: what recover would still turn on + j.put("held", still); + try { + write(journalFile, Json.write(j)); + } catch (Exception x) { + out.add("WARNING: couldn't update the journal's held apps: " + x); + } + } + } } - Map f = new LinkedHashMap(); - f.put("stock", t.stock); - f.put("result", t.result); - f.put("mods", new ArrayList(t.mods)); - if (t.app) f.put("app", true); - files.put(t.path, f); - } - write(stateFile, Json.write(p.state)); - if (trial) { - j.put("committed", true); - write(journalFile, Json.write(j)); - out.add("trial: undone at the next start unless you run `engine keep`"); - } else { - journalFile.delete(); - rm(prevDir); } rm(stageDir); Set needs = new LinkedHashSet(); @@ -1961,6 +2056,92 @@ void apply(Plan p, boolean trial) throws Exception { out.add("done: " + changed.size() + " file(s); " + needs); } + /** + * Puts the journaled files back as they were, last changed first, with their modes, owners + * and labels, and the state with them. A file already as it was is left alone, so a run + * cut off before the swap writes nothing. Returns what couldn't be put back (then the + * journal must stay). + */ + @SuppressWarnings("unchecked") + List rollback(Map j) throws Exception { + List entries = new ArrayList((List) j.get("entries")); + Collections.reverse(entries); + List> todo = new ArrayList>(); + Set apks = new LinkedHashSet(); + for (Object o : entries) { + Map e = (Map) o; + String path = (String) e.get("path"); + File dst = sys(path), prev = e.get("prev") == null ? null : new File((String) e.get("prev")); + boolean same = prev == null ? !dst.exists() + : dst.isFile() && md5(dst).equals(md5(prev)) && FileMeta.read(this, dst).same(journalMeta(e, path)); + if (!same) { + todo.add(e); + if (path.endsWith(".apk")) apks.add(path); + } + } + // an app's odex as it was, but its apk not: its dalvik-cache copy needs filling again + for (Object o : entries) { + Map e = (Map) o; + String path = (String) e.get("path"); + if (path.endsWith(".odex") && apks.contains(path.replaceAll("\\.odex$", ".apk")) && !todo.contains(e)) todo.add(e); + } + List left = new ArrayList(); + if (!todo.isEmpty()) { + try { + remount("rw"); + } catch (Exception x) { + for (Map e : todo) left.add(e.get("path") + " (" + x.getMessage() + ")"); + return left; + } + try { + for (Map e : todo) { + String path = (String) e.get("path"); + File dst = sys(path); + try { + testFail("rollback", path); + if (e.get("prev") == null) { + if (dst.exists() && !dst.delete()) throw new IOException("delete " + dst); + FileMeta.gone(this, dst); + } else { + put(new File((String) e.get("prev")), dst, journalMeta(e, path)); + } + if (path.endsWith(".odex")) dalvik(path.replaceAll("\\.odex$", ".apk"), dst, false); + out.add("rolled back " + path); + } catch (Exception x) { + left.add(path + " (" + x.getMessage() + ")"); + } + } + } finally { + remount("ro"); + } + } + if (left.isEmpty()) write(stateFile, Json.write(j.get("state"))); + return left; + } + + /** a journal entry's mode, owner and label (a journal from before they were read: the /system defaults) */ + static FileMeta journalMeta(Map e, String path) { + FileMeta m = FileMeta.from(e); + return m != null ? m : FileMeta.defaults(path); + } + + /** the stock mode, owner and label of path (an app's apk or odex), as recorded before HMG-API's first write */ + static FileMeta stockMeta(Target t, String path) { + FileMeta m = t.stockMeta == null ? null : FileMeta.from(t.stockMeta.get(path)); + return m != null ? m : FileMeta.defaults(path); // recorded by an HMG-API before this: the /system defaults + } + + /** what a built file is written with: its stock owner and label (else the live file's, else the defaults), the mod's mode if it gives one */ + FileMeta targetMeta(Target t) throws IOException { + FileMeta m = t.stockMeta == null ? null : FileMeta.from(t.stockMeta.get(t.path)); + File live = sys(t.path); + if (m == null) m = live.isFile() ? FileMeta.read(this, live) : FileMeta.defaults(t.path); + m = m.copy(); + String mode = modeOf(t); + if (mode != null) m.mode = Integer.parseInt(mode, 8); + return m; + } + List withOdex(Target t) { List l = new ArrayList(); l.add(t.path); @@ -1969,16 +2150,18 @@ List withOdex(Target t) { } void swap(Target t) throws Exception { + testFail("swap", t.path); File dst = sys(t.path); if (t.restore) { if ("absent".equals(t.stock)) { if (dst.exists() && !dst.delete()) throw new IOException("delete " + dst); + FileMeta.gone(this, dst); } else { - put(backup(t.path), dst, "644"); + put(backup(t.path), dst, stockMeta(t, t.path)); } if (t.app) { String odex = t.path.replaceAll("\\.apk$", ".odex"); - if (backup(odex).isFile()) put(backup(odex), sys(odex), "644"); + if (backup(odex).isFile()) put(backup(odex), sys(odex), stockMeta(t, odex)); dalvik(t.path, sys(odex), false); } out.add("restored " + t.path); @@ -1986,13 +2169,13 @@ void swap(Target t) throws Exception { } if (!t.exists) { if (dst.exists() && !dst.delete()) throw new IOException("delete " + dst); + FileMeta.gone(this, dst); return; } - put(t.stage, dst, t.changes.isEmpty() || t.changes.get(0).c.get("mode") == null ? "644" - : String.valueOf(t.changes.get(0).c.get("mode"))); + put(t.stage, dst, targetMeta(t)); if (t.app) { File odex = sys(t.path.replaceAll("\\.apk$", ".odex")); - odex.delete(); + odex.delete(); // dexopt --preopt opens its output O_EXCL; the journal has the old one dalvik(t.path, odex, true); } out.add("wrote " + t.path); @@ -2000,6 +2183,7 @@ void swap(Target t) throws Exception { /** dexopt a rebuilt app and fill its Dalvik cache entry, as the 1.x package did. */ void dalvik(String apkPath, File odex, boolean dexopt) throws Exception { + if (dexopt) testFail("dexopt", apkPath); if (host) return; String apk = new File(apkPath).getName(); exec("/system/bin/sh", "-c", "rm -f /data/dalvik-cache/*" + apk + "* /cache/dalvik-cache/*" + apk + "*"); @@ -2019,48 +2203,210 @@ void dalvik(String apkPath, File odex, boolean dexopt) throws Exception { } } - /** Write next to the target and rename, so a reader never sees half a file. */ - void put(File src, File dst, String mode) throws Exception { + /** + * Write next to the target with its mode, owner and label, then rename, so a reader never + * sees half a file or one that can't run. Nothing is left behind when it fails. + */ + void put(File src, File dst, FileMeta meta) throws Exception { File tmp = new File(dst.getPath() + ".hmgapi-new"); dst.getParentFile().mkdirs(); - copy(src, tmp); - if (!host) { - exec("/system/bin/chmod", mode, tmp.getPath()); - exec("/system/bin/chown", "0:0", tmp.getPath()); - } - if (!md5(tmp).equals(md5(src))) { + try { + testFail("put", devicePath(dst)); + copy(src, tmp); + FileMeta.set(this, tmp, meta); + if (!md5(tmp).equals(md5(src))) throw new IOException("copy to " + dst + " came out different"); + if (!tmp.renameTo(dst)) throw new IOException("rename onto " + dst); + FileMeta.moved(this, tmp, dst); + } catch (Exception e) { tmp.delete(); - throw new IOException("copy to " + dst + " came out different"); + FileMeta.gone(this, tmp); + throw e; } - if (!tmp.renameTo(dst)) { - tmp.delete(); - throw new IOException("rename onto " + dst); + } + + /** + * Off the unit only, for the tests: HMGAPI_TEST_FAIL=": ..." makes that step fail + * there (swap, put, dexopt, rollback); "halt:" ends the engine at once in swap, + * as a power cut would (no rollback, no finally). + */ + void testFail(String step, String path) throws IOException { + if (!host) return; + for (String s : env("HMGAPI_TEST_FAIL", "").split(" ")) { + if ("swap".equals(step) && s.equals("halt:" + path)) { + System.out.flush(); + Runtime.getRuntime().halt(9); + } + if (s.equals(step + ":" + path)) throw new IOException("test: " + step + " fails at " + path); } } - Set hold(List changed) throws Exception { - Set held = new LinkedHashSet(); - if (host || !"1".equals(getprop("sys.boot_completed"))) return held; + /** f's path on the unit (without HMGAPI_ROOT) */ + String devicePath(File f) { + String p = f.getPath(); + return !root.isEmpty() && p.startsWith(root) ? p.substring(root.length()) : p; + } + + // ------------------------------------------------------------------ apps held while their files change + + /** The package manager, or null where there's none (off the unit, unless a test gives one). */ + String pm() { return env("HMGAPI_PM", host ? null : "/system/bin/pm"); } + + /** never stopped: Android itself, and what HMG-API's USB install path needs */ + static final String[] NEVER_HOLD = { "android", "com.hkmc.system.app.OTAClient" }; + static final int FLAG_PERSISTENT = 1 << 3; // ApplicationInfo.FLAG_PERSISTENT + + /** + * Stops (pm disable) the apps whose apk changes, so none runs on a half-changed file (DiPO + * and iAP2 crash-looped, SIGBUS). Android keeps an app disabled across restarts, so the + * list goes into the journal and state/held.txt first: a power cut or a killed engine + * before release leaves it for recover and boot.sh. Never Android itself, a persistent + * app (Android starts those on its own; off, it may not come up at all), OTAClient, or an + * app that was off already (it stays off). Each app goes into the caller's held set before + * its pm disable, so one that stopped is started again even if a later one throws; one + * whose disable failed is dropped from it (it kept running, as before this change). + */ + void hold(List changed, Map j, Set held) throws Exception { + String pm = pm(); + if (pm == null || !"1".equals(getprop("sys.boot_completed"))) return; Map pkgs = new LinkedHashMap(); - for (String l : exec("/system/bin/pm", "list", "packages", "-f").text.split("\n")) { + for (String l : exec(pm, "list", "packages", "-f").text.split("\n")) { l = l.trim(); int eq = l.lastIndexOf('='); if (l.startsWith("package:") && eq > 0) pkgs.put(l.substring(8, eq), l.substring(eq + 1)); } + Set off = new LinkedHashSet(); + for (String l : exec(pm, "list", "packages", "-d").text.split("\n")) if (l.trim().startsWith("package:")) off.add(l.trim().substring(8)); + Map flags = packageFlags(); + Set want = new LinkedHashSet(); for (Target t : changed) { String pkg = pkgs.get(t.path); - if (pkg != null && exec("/system/bin/pm", "disable", pkg).code == 0) held.add(pkg); + if (pkg == null || off.contains(pkg)) continue; + String why = null; + for (String n : NEVER_HOLD) if (n.equals(pkg)) why = "never stopped"; + if (why == null && t.path.startsWith("/system/framework/")) why = "part of Android itself"; + if (why == null && flags.get(pkg) == null) why = "not in packages.xml, so it can't be told whether it's persistent"; + if (why == null && (flags.get(pkg) & FLAG_PERSISTENT) != 0) why = "persistent"; + if (why != null) out.add("note " + pkg + " keeps running while " + t.path + " changes (" + why + ")"); + else want.add(pkg); + } + if (want.isEmpty()) return; + // written down before any is stopped: a power cut from here on leaves them for recover and boot.sh + j.put("held", new ArrayList(want)); + write(journalFile, Json.write(j)); + Set all = readHeld(); + all.addAll(want); + writeHeld(all); + Set failed = new LinkedHashSet(); + for (String pkg : want) { + held.add(pkg); // before the call: if it throws, the finally still starts this one again + testFail("disable", pkg); + Run r = exec(pm, "disable", pkg); + if (r.code != 0 || !r.text.contains("new state")) { + held.remove(pkg); + failed.add(pkg); + out.add("WARNING: couldn't stop " + pkg + " (" + r.text.trim() + "); it keeps running while its files change"); + } + } + if (!failed.isEmpty()) { // never stopped: nothing to start again later + j.put("held", new ArrayList(held)); + write(journalFile, Json.write(j)); + all = readHeld(); + all.removeAll(failed); + writeHeld(all); } if (!held.isEmpty()) out.add("stopped " + held + " while their files change"); - return held; } - void release(Set held) throws Exception { - for (String pkg : held) exec("/system/bin/pm", "enable", pkg); + /** + * Starts held apps again (pm enable). Returns those it couldn't; they stay in held.txt for the + * next try. Never throws: it runs from apply's finally, where an exception would hide the + * apply's own result and skip the apps after it. + */ + List release(Set held) { + List left = new ArrayList(); + String pm = pm(); + Set done = new LinkedHashSet(); + for (String pkg : held) { + try { + testFail("enable", pkg); + Run r = pm == null ? null : exec(pm, "enable", pkg); + if (r != null && r.code == 0 && r.text.contains("new state")) done.add(pkg); + else left.add(pkg); + } catch (Exception x) { + left.add(pkg); + } + } + try { + Set all = readHeld(); + all.removeAll(done); + writeHeld(all); + } catch (Exception x) { + out.add("WARNING: couldn't update state/held.txt: " + x); + } + if (!done.isEmpty()) out.add("started " + done + " again"); + if (!left.isEmpty()) out.add("WARNING: couldn't start " + left + " again; the next start tries again (state/held.txt)"); + return left; + } + + /** Held apps left over (a cut-off apply, or a release that failed): started again once Android is up and no apply is waiting. */ + @SuppressWarnings("unchecked") + int releaseHeld() throws Exception { + Set held = readHeld(); + if (held.isEmpty()) { + out.add("no apps held"); + return 0; + } + if (journalFile.exists() && !Boolean.TRUE.equals(Json.object(read(journalFile)).get("committed"))) { + out.add("held " + held + " stay off: an apply didn't finish, and their files are as it left them; `engine recover` puts them back and starts them"); + return 1; + } + if (!"1".equals(getprop("sys.boot_completed"))) { + out.add("held " + held + ": Android isn't up yet"); + return 1; + } + return release(held).isEmpty() ? 0 : 1; + } + + File heldFile() { return new File(stateDir, "held.txt"); } + + Set readHeld() throws IOException { + Set s = new LinkedHashSet(); + if (!heldFile().isFile()) return s; + for (String l : read(heldFile()).split("\n")) if (l.trim().matches("[A-Za-z0-9_.]+")) s.add(l.trim()); + return s; + } + + void writeHeld(Set s) throws IOException { + if (s.isEmpty()) { + heldFile().delete(); + return; + } + StringBuilder b = new StringBuilder(); + for (String p : s) b.append(p).append('\n'); + write(heldFile(), b.toString()); + } + + /** Each package's ApplicationInfo flags, from /data/system/packages.xml (what PackageManager wrote at its last scan). */ + Map packageFlags() { + Map m = new LinkedHashMap(); + try { + java.util.regex.Matcher pk = java.util.regex.Pattern.compile("]*>").matcher(read(new File(root + "/data/system/packages.xml"))); + while (pk.find()) { + java.util.regex.Matcher n = java.util.regex.Pattern.compile("\\sname=\"([^\"]+)\"").matcher(pk.group()); + java.util.regex.Matcher f = java.util.regex.Pattern.compile("\\sflags=\"(-?[0-9]+)\"").matcher(pk.group()); + if (n.find() && f.find()) m.put(n.group(1), Long.parseLong(f.group(1))); + } + } catch (Exception e) { + // unreadable: no app counts as known, so none is held + } + return m; } void remount(String mode) throws Exception { - if (host) return; + if (host) { + if ("rw".equals(mode)) testFail("remount", "rw"); + return; + } Run r = exec(env("HMGAPI_HMGAPID", "/system/bin/hmgapid"), "remount", mode); if (r.code != 0 && "rw".equals(mode)) throw new IOException("remount rw: " + r.text); } @@ -2092,6 +2438,8 @@ int status() throws Exception { out.add(Boolean.TRUE.equals(j.get("trial")) ? "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`)"); } + Set held = readHeld(); + if (!held.isEmpty()) out.add("held " + held + " stopped (pm disable) by an apply that didn't start them again; `engine recover` starts them"); return bad == 0 ? 0 : 4; } @@ -2134,35 +2482,48 @@ int keep() throws Exception { return 0; } + /** + * An apply cut off (a power cut, a killed engine) or a waiting trial: every journaled file + * back as it was (bytes, mode, owner, label), then the apps it held started again. The + * output says "rolled back" or "trial undone" only when files changed (boot.sh restarts + * the unit on those words). Left over held apps alone: started again too. + */ @SuppressWarnings("unchecked") int recover() throws Exception { if (!journalFile.exists()) { out.add("nothing to recover"); - return 0; + return startHeld(readHeld()); } Map j = Json.object(read(journalFile)); - remount("rw"); - try { - for (Object o : (List) j.get("entries")) { - Map e = (Map) o; - String path = (String) e.get("path"); - File dst = sys(path); - 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"))); - } - if (path.endsWith(".odex") && !host) dalvik(path.replaceAll("\\.odex$", ".apk"), dst, false); - out.add("rolled back " + path); - } - } finally { - remount("ro"); + int before = out.size(); + List left = rollback(j); + if (!left.isEmpty()) { + out.add("recover didn't finish, the journal stays: couldn't put back " + left); + Set held = readHeld(); + if (j.get("held") instanceof List) for (Object o : (List) j.get("held")) held.add(String.valueOf(o)); + writeHeld(held); + if (!held.isEmpty()) out.add("held " + held + " stay off until it does"); + return 1; } - write(stateFile, Json.write(j.get("state"))); + boolean any = out.size() > before; journalFile.delete(); rm(prevDir); - out.add(Boolean.TRUE.equals(j.get("trial")) ? "trial undone" : "unfinished apply rolled back"); + if (Boolean.TRUE.equals(j.get("trial"))) out.add(any ? "trial undone" : "trial dropped: its files were as before it already"); + else out.add(any ? "unfinished apply rolled back" : "unfinished apply dropped: no file had changed yet"); + Set held = readHeld(); + if (j.get("held") instanceof List) for (Object o : (List) j.get("held")) held.add(String.valueOf(o)); + return startHeld(held); + } + + /** held apps started again now if Android is up, else left in held.txt for boot.sh (engine release-held) */ + int startHeld(Set held) throws Exception { + if (held.isEmpty()) return 0; + writeHeld(held); + if (!"1".equals(getprop("sys.boot_completed"))) { + out.add("held " + held + " start again once Android is up (boot.sh: engine release-held)"); + return 0; + } + release(held); return 0; } @@ -2220,7 +2581,6 @@ Map loadState() throws IOException { File backup(String path) { return new File(stockDir, path); } - String mode(File f) { return "644"; } String settingGet(String k) throws Exception { if (host) return hostSettings().get(k); diff --git a/core/runtime/java/hmgapi/engine/FileMeta.java b/core/runtime/java/hmgapi/engine/FileMeta.java new file mode 100644 index 00000000..ea69cfb3 --- /dev/null +++ b/core/runtime/java/hmgapi/engine/FileMeta.java @@ -0,0 +1,191 @@ +package hmgapi.engine; + +import java.io.File; +import java.io.IOException; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.TreeMap; + +/** + * A /system file's mode, owner, group and SELinux label. Read before HMG-API first writes a + * file (files.json "stockMeta" per path, and each journal entry) and put back with its bytes + * on apply, rollback and restore: a stock /system/bin binary put back as 644 doesn't run, and + * one put back as 0:0 instead of 0:2000, or with another label, may not either. + * + * On the unit: libcore's stat and android.os.SELinux (both in every 4.4 app_process), toolbox + * as the fallback. Off the unit (HMGAPI_HOST=1) the mode is the desktop file's own (chmod), + * and owners and labels, which a desktop user can't set, live in {@code /meta.txt}, one + * "