diff --git a/docs/mods.md b/docs/mods.md index 040d7cf6..3d4ba533 100644 --- a/docs/mods.md +++ b/docs/mods.md @@ -112,8 +112,10 @@ ahead of time, after the design in [#845](https://github.com/valentderah/totk-pc reason, and the other plugins are built in. 2. At every start each plugin's start-up runs again, before the game's own start-up code, in the same setting: it sees the game's own instructions, as in its service run. Its redirects are compared with the record of the - rebuild. When they match, the mod's code sites go on. When they do not, the plugin stays off for this run, the - mod's row says why, and the next start runs the rebuild. + rebuild. A value it writes into the game's data that redirects nothing (a size, a counter) only has to land at + the recorded place, since the game may hold another value there at this start, for example a memory pool that + grows with `render_scale`. When they match, the mod's code sites go on. When they do not, the plugin stays off for + this run, the mod's row says why, and the next start runs the rebuild, which runs the plugin's service run again. 3. The plugin keeps what its start-up made (its memory, its tables), so its code works as on the Switch. The start costs about 50 ms per plugin; the game runs no differently without a plugin. 4. Removing a plugin mod from the mods folder starts the rebuild at the next start, which builds the game without diff --git a/installer/steps.py b/installer/steps.py index 09b36f12..dadcefc4 100644 --- a/installer/steps.py +++ b/installer/steps.py @@ -1141,6 +1141,17 @@ def plugins_status(ctx): return ctx.dest / 'build-cache' / 'plugins.status' +def plugins_stale(ctx): + """True when the game listed a plugin whose start differed from the build (build-cache/plugins.stale, runtime/mods.c + mods_plugin_off): the plugin's record comes from the lift's service run and the exe's patch sets from the compile, + so both are out of date, while their keys, made of the files the steps read, are unchanged. Only Lift.run clears + the file.""" + try: + return bool((ctx.dest / 'build-cache' / 'plugins.stale').read_text(encoding='utf-8', errors='replace').strip()) + except OSError: + return False + + def built_plugins(status, files, mods): """The files of the plugins the status file lists as built (kind `plugin`), in the order of files. The key is FNV-1a 32 of "/", as tools/exefs_plugins.py and runtime/mods.c compute it.""" @@ -1194,7 +1205,8 @@ class Lift(Step): def current(self, ctx, record): gen = ctx.temp / 'gen' stamp = gen / STAMP - return (gen / 'layout.json').is_file() and stamp.is_file() and stamp.read_text().strip() == ctx.keys['lift'] + return ((gen / 'layout.json').is_file() and stamp.is_file() and stamp.read_text().strip() == ctx.keys['lift'] + and not plugins_stale(ctx)) def run(self, ctx): # gen/ of the last run stays: gen.py lifts again only the chunks whose inputs changed @@ -1369,6 +1381,8 @@ class Compile(Step): exe = ctx.dest / ('totk' + EXE) if not exe.is_file() or not (ctx.dest / 'romfs-index.bin').is_file(): return False + if plugins_stale(ctx): # the lift runs (Lift.current), and a transient step runs only with the step after it + return False if not all((ctx.dest / d.name).is_file() for d in ctx.layout.dlls): return False return file_sha256(exe) == record.get('exe_sha256') diff --git a/recomp/patches.py b/recomp/patches.py index 03ebc018..8104e876 100644 --- a/recomp/patches.py +++ b/recomp/patches.py @@ -60,7 +60,8 @@ run's record; the design follows #845 by itaskaev2): sha256> is that .text's hash: the runtime compares it with the .text its own run of the init leaves, and keeps the set off when they differ. - `expect`: one word the init writes into a game module (the hook branches into main's .text); the runtime compares - the words its run of the init wrote with these, all or nothing per plugin. + the words its run of the init wrote with these, all or nothing per plugin. `*` for and matches the word + by place only: a word of main's .data or .bss that shapes no lifted code and may differ at play. - `stub`: an exlaunch inline-hook entry stub (stur x30; bl impl; ldur x30; b trampoline; .quad callback). Its fourth word is lifted as a `ret`: the generated site calls the stub and runs its own original instruction after it (`@call` below), so the trampoline (the original relocated, b site+4) never runs. @@ -119,7 +120,8 @@ class Table: self.spins = spins or {} # {module: {back-edge offset: head offset}} self.hooks = hooks or {} # {module: {function offset}}; empty: FN_ENTER in every function self.ordered = set(ordered) - # {module: {'set', 'sha256', 'image', 'expect': [(module, offset, old, new)], 'stubs': {offset}, + # {module: {'set', 'sha256', 'image', 'expect': [(module, offset, old, new)] (old and new None for `* *`), + # 'stubs': {offset}, # 'seeds': {offset}, 'origs': {trampoline offset: (function module, function offset)}}}; empty without # plugin lines self.plugins = plugins or {} @@ -296,7 +298,10 @@ def plugin_line(f, where, index, bases, plugins): owner = [p for p in plugins.values() if p['set'] == index[f[1]]] if not owner: raise PatchError(f'{where}: set {f[1]} owns no plugin') - owner[0]['expect'].append((f[2], int(f[3], 16), int(f[4], 16), int(f[5], 16))) + if (f[4] == '*') != (f[5] == '*'): + raise PatchError(f'{where}: `*` for one of old and new only') + words = (None, None) if f[4] == '*' else (int(f[4], 16), int(f[5], 16)) + owner[0]['expect'].append((f[2], int(f[3], 16), *words)) elif f[0] == 'stub' and len(f) == 3: plugin(f[1])['stubs'].add(int(f[2], 16)) elif f[0] == 'seed' and len(f) >= 3: @@ -345,14 +350,16 @@ def header_text(table, marker): enumerate(table.sets)), ''] if table.plugins: # none: the header is what it was before plugins names = sorted(table.plugins) - writes = [f'X({i}, "{m}", {o:#x}, {old:#010x}u, {new:#010x}u)' for i, n in enumerate(names) - for m, o, old, new in sorted(table.plugins[n]['expect'])] + writes = [f'X({i}, "{m}", {o:#x}, {old or 0:#010x}u, {new or 0:#010x}u, {int(old is None)})' + for i, n in enumerate(names) + for m, o, old, new in sorted(table.plugins[n]['expect'], key=lambda e: e[:2])] lines += [f'#define RT_PLUGIN_COUNT {len(names)}', '// X(index, module, its set, SHA-256 of its .text after the init)', '#define RT_PLUGINS(X) ' + ' '.join(f'X({i}, "{n}", {table.plugins[n]["set"]}, ' f'"{table.plugins[n]["sha256"]}")' for i, n in enumerate(names)), f'#define RT_PLUGIN_WRITE_COUNT {len(writes)}', - '// X(plugin index, module, offset, old word, new word): what the init writes into game modules', + '// X(plugin index, module, offset, old word, new word, 1: any words, matched by place only): what ' + 'the init writes into game modules', '#define RT_PLUGIN_WRITES(X) ' + ' '.join(writes), '// X(module, offset): the hook entries (seed lines) TOTK_PLUGIN_TRACE counts (runtime/plugin_init.c)', '#define RT_PLUGIN_ROOTS(X) ' + ' '.join(f'X("{n}", {o:#x})' for n in names diff --git a/runtime/plugin_init.c b/runtime/plugin_init.c index 237621eb..7554da83 100644 --- a/runtime/plugin_init.c +++ b/runtime/plugin_init.c @@ -62,6 +62,7 @@ #include "kernel.h" #include "mods.h" #include "platform/platform.h" +#include "plugin_writes.h" #if __has_include("patches.h") #include "patches.h" @@ -523,11 +524,7 @@ static const struct { const char *module; int set; const char *sha256; } plugin_ RT_PLUGINS(X) #undef X }; -static const struct { int plugin; const char *module; uint64_t off; uint32_t old, now; } write_tab[] = { -#define X(p, mod, off, old, now) {p, mod, off, old, now}, - RT_PLUGIN_WRITES(X) -#undef X -}; +static const PluginWrite write_tab[] = {RT_PLUGIN_WRITES(PLUGIN_WRITE)}; #define NWRITES ((int)(sizeof write_tab / sizeof *write_tab)) #ifdef RT_PLUGIN_ROOTS static const struct { const char *module; uint64_t off; } root_tab[] = { @@ -590,7 +587,9 @@ static void restore_page(const RtLoaded *m, uint64_t off, const uint8_t *was) { } // After plugin i's init: what it wrote into the game modules, word by word, against the record of the build (its -// entries of RT_PLUGIN_WRITES). The first difference goes into why (unless a reason is there already). Then the game +// entries of RT_PLUGIN_WRITES, plugin_writes.h plugin_write_find). A recorded word the init did not change counts as +// missing, unless the record takes any value there (the init may have written the value the word held). The first +// difference goes into why (unless a reason is there already). Then the game // modules are made what they were before the init: the sealed part (.text, .rodata) gets the game's bytes back, a // write elsewhere stays and goes into pre, so the next plugin's init is compared only with what it writes itself. // The aliases this init mapped (from first_alias on) are flushed first; an earlier init's were flushed after it. @@ -612,12 +611,8 @@ static void check_writes(int plugin, int first_alias, char *why, size_t cap) { memcpy(&a, pre[i] + w, 4); memcpy(&b, now + w, 4); if (a == b) continue; - int k = 0; - while (k < NWRITES && !(write_tab[k].plugin == plugin && write_tab[k].off == w && - !strcmp(write_tab[k].module, m->name) && write_tab[k].old == a && - write_tab[k].now == b)) - k++; - if (k < NWRITES) { + int k = plugin_write_find(write_tab, NWRITES, plugin, m->name, w, a, b); + if (k >= 0) { seen[k] = 1; } else if (!unexpected++) { snprintf(first, sizeof first, "%s+%#llx %08x -> %08x", m->name, (unsigned long long)w, a, b); @@ -627,7 +622,7 @@ static void check_writes(int plugin, int first_alias, char *why, size_t cap) { else memcpy(pre[i] + off, now + off, PAGE); } } - for (int k = 0; k < NWRITES; k++) missing += write_tab[k].plugin == plugin && !seen[k]; + for (int k = 0; k < NWRITES; k++) missing += write_tab[k].plugin == plugin && !seen[k] && !write_tab[k].any; if (why[0]) return; if (unexpected) snprintf(why, cap, "its init wrote %d words the build did not record (first %s)", unexpected, first); diff --git a/runtime/plugin_writes.h b/runtime/plugin_writes.h new file mode 100644 index 00000000..deec6040 --- /dev/null +++ b/runtime/plugin_writes.h @@ -0,0 +1,31 @@ +// The build's record of what a mod plugin's init writes into the game modules (patches.h RT_PLUGIN_WRITES, from the +// `expect` lines of recomp/patches.py), and the lookup plugin_init.c check_writes makes for every word an init changed +// at the start of the game. +#pragma once +#include +#include + +// any: the expect line said `* *`, a word of main's .data or .bss that shapes no lifted code (tools/exefs_plugins.py +// plugin_lines). The game may hold another value there at play than in the service run (Zonai Fieldworks' Self Recall +// takes its storage off a pool size that grows with the resolution's texture heap), so it matches by place only. A +// hook branch in .text and a pointer into a plugin's .text match by place and both words. +typedef struct { + int plugin; + const char *module; + uint64_t off; + uint32_t old, now; + int any; +} PluginWrite; + +// The X of RT_PLUGIN_WRITES for a table of PluginWrite. +#define PLUGIN_WRITE(p, mod, off, old, now, any) {p, mod, off, old, now, any}, + +// The index of the entry of plugin that records the write of module+off from old to now, or -1. +static inline int plugin_write_find(const PluginWrite *tab, int n, int plugin, const char *module, uint64_t off, + uint32_t old, uint32_t now) { + for (int k = 0; k < n; k++) + if (tab[k].plugin == plugin && tab[k].off == off && !strcmp(tab[k].module, module) && + (tab[k].any || (tab[k].old == old && tab[k].now == now))) + return k; + return -1; +} diff --git a/tests/exefs_plugins_test.py b/tests/exefs_plugins_test.py index 5f82c976..727b161c 100644 --- a/tests/exefs_plugins_test.py +++ b/tests/exefs_plugins_test.py @@ -9,6 +9,8 @@ Run with .venv (lz4 and numpy, as recomp/): python tests/exefs_plugins_test.py """ import hashlib import json +import os +import shutil import struct import subprocess import sys @@ -588,6 +590,27 @@ class Lines(unittest.TestCase): self.assertIn(f'site mod_x main {SITE_OFF:x} 94000010 {new:08x}', out) self.assertFalse(any(x.startswith(('orig', 'stub')) for x in out)) + def test_data_word_matches_by_place(self): + # Zonai Fieldworks' Self Recall takes its storage off a pool size in main's .bss (1.4.3 main+0x3ad6eb8): the + # service run recorded 84800000 -> 7f1c0000, a start whose resolution grew the texture heap has + # 87a00000 -> 823c0000 there. The word shapes no lifted code, so its expect line takes any value. + rec = record(writes=[{'module': 'main', 'offset': 0x3ad6eb8, 'old': 0x84800000, 'new': 0x7F1C0000}]) + rec['modules'][0]['size'] = 0x3adf000 + out = self.lines(rec) + self.assertIn('expect mod_x main 3ad6eb8 * *', out) + self.assertFalse(any('84800000' in x or '7f1c0000' in x for x in out), out) + + def test_pointer_swap_keeps_its_words(self): + # a table entry that now points at a plugin function is a seed of the lift: both its words stay exact + new = PLUGIN + THUNK_OFF + w = [{'module': 'main', 'offset': 0x180010, 'old': 0x00001000, 'new': new & 0xFFFFFFFF}, + {'module': 'main', 'offset': 0x180014, 'old': 0, 'new': new >> 32}, + {'module': 'main', 'offset': 0x180020, 'old': 5, 'new': 6}] + out = self.lines(record(writes=w)) + self.assertIn(f'expect mod_x main 180010 00001000 {new & 0xFFFFFFFF:08x}', out) + self.assertIn(f'expect mod_x main 180014 00000000 {new >> 32:08x}', out) + self.assertIn('expect mod_x main 180020 * *', out) + # ---- one service run per plugin class PerPlugin(unittest.TestCase): @@ -691,6 +714,10 @@ def code_nso(words_at, size_text=0x5000): FN = 0x100 # the hooked main function: mov x19, x0; mov x0, x19; ret +MSYS_BIN = Path(r'C:\msys64\ucrt64\bin') # clang for the start-up lookup below, as tests/flags_check.py +CC = (str(MSYS_BIN / 'clang.exe') if os.name == 'nt' and (MSYS_BIN / 'clang.exe').exists() else + os.environ.get('CC') or shutil.which('clang')) +CC_ENV = dict(os.environ, PATH=str(MSYS_BIN) + os.pathsep + os.environ.get('PATH', '')) if os.name == 'nt' else None class Generator(unittest.TestCase): @@ -767,9 +794,22 @@ class Generator(unittest.TestCase): self.assertIn(f'void f_{stub:x}(Cpu *c);', c) h = patches.header_text(t, 'MARK') self.assertIn('#define RT_PLUGIN_COUNT 1', h) - self.assertIn(f'X(0, "main", {FN:#x}, 0xaa0003f3u, 0x14000000u)', h) + self.assertIn(f'X(0, "main", {FN:#x}, 0xaa0003f3u, 0x14000000u, 0)', h) self.assertIn('X("plugin0", 0x4100) X("plugin0", 0x4200)', h) + def test_any_value_expect_line(self): + # `*` for both words: runtime/plugin_init.c check_writes matches the word by place only + t = self.table(f'site mod_x main {FN:x} aa0003f3 @call:plugin0+4000 aa0003f3', + ['stub plugin0 4000', 'expect mod_x main 3ad6eb8 * *']) + self.assertIn(('main', 0x3ad6eb8, None, None), t.plugins['plugin0']['expect']) + h = patches.header_text(t, 'MARK') + self.assertIn('X(0, "main", 0x3ad6eb8, 0x00000000u, 0x00000000u, 1)', h) + self.assertIn(f'X(0, "main", {FN:#x}, 0xaa0003f3u, 0x14000000u, 0)', h) + for half in ('* 7f1c0000', '84800000 *'): + with self.subTest(half=half), self.assertRaises(patches.PatchError): + self.table(f'site mod_x main {FN:x} aa0003f3 @call:plugin0+4000 aa0003f3', + ['stub plugin0 4000', f'expect mod_x main 3ad6eb8 {half}']) + # exlaunch's hook impl saves no NZCV: flags pass from the site to the callback and back (recomp/flags.py) def code(self, main_words, plugin_words=None): """Main's hooked function and the plugin image's words replaced; the plugin hash follows.""" @@ -882,6 +922,34 @@ class Generator(unittest.TestCase): capture_output=True, text=True, timeout=30) self.assertEqual(run.returncode, 0, run.stdout + run.stderr) + @unittest.skipUnless(CC, 'no clang') + def test_start_matches_the_record(self): + # runtime/plugin_writes.h plugin_write_find on this table's patches.h, as runtime/plugin_init.c check_writes + # looks up each word an init changed: Self Recall's pool size at main+0x3ad6eb8, recorded by the service run as + # 84800000 -> 7f1c0000 and written at a start with a grown texture heap as 87a00000 -> 823c0000 + site = f'site mod_x main {FN:x} aa0003f3 @call:plugin0+4000 aa0003f3' + cases = [(FN, 0xAA0003F3, 0x14000000, 0), (FN, 0xAA0003F3, 0x14000001, -1), + (0x3AD6EB8, 0x84800000, 0x7F1C0000, 1), (0x3AD6EB8, 0x87A00000, 0x823C0000, 1), + (0x3AD6EBC, 0x87A00000, 0x823C0000, -1)] + main = ['#include "patches.h"', '#include "plugin_writes.h"', + 'static const PluginWrite tab[] = {RT_PLUGIN_WRITES(PLUGIN_WRITE)};', + 'int main(void) {', ' int n = sizeof tab / sizeof *tab, bad = 0;'] + for i, (off, old, new, want) in enumerate(cases): + main.append(f' bad |= (plugin_write_find(tab, n, 0, "main", {off:#x}, {old:#x}u, {new:#x}u) != {want}) ' + f'<< {i};') + main += [' return bad;', '}'] + (self.d / 'start.c').write_text('\n'.join(main) + '\n') + exe = self.d / 'start.exe' + for record, failed in (('expect mod_x main 3ad6eb8 84800000 7f1c0000', 1 << 3), + ('expect mod_x main 3ad6eb8 * *', 0)): + with self.subTest(record=record): + (self.d / 'patches.h').write_text(patches.header_text(self.table(site, ['stub plugin0 4000', record]), + 'MARK')) + subprocess.run([CC, '-std=gnu11', '-Wall', '-Werror', '-I', str(self.d), '-I', str(ROOT / 'runtime'), + str(self.d / 'start.c'), '-o', str(exe)], check=True, env=CC_ENV, timeout=60) + # the exact record misses only the play-time write + self.assertEqual(subprocess.run([str(exe)], env=CC_ENV, timeout=60).returncode, failed) + def test_image_must_match_its_hash(self): t = self.table(f'site mod_x main {FN:x} aa0003f3 @call:plugin0+4000 aa0003f3', ['stub plugin0 4000']) t.plugins['plugin0']['sha256'] = '0' * 64 diff --git a/tests/installer_test.py b/tests/installer_test.py index 44201d08..9175100b 100644 --- a/tests/installer_test.py +++ b/tests/installer_test.py @@ -370,6 +370,45 @@ class LiftKeyTest(unittest.TestCase): self.assertEqual(self.key(), before) +class PluginsStaleTest(unittest.TestCase): + """A plugin the game found stale (build-cache/plugins.stale, runtime/mods.c mods_plugin_off) plans the lift and the + compile of the game's rebuild: the plugin's service run is in the lift, and only Lift.run clears the file.""" + + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + base = Path(tmp.name) + dest, temp = base / 'install', base / 'temp' + (temp / 'gen').mkdir(parents=True) + (temp / 'gen' / 'layout.json').write_text('[]') + (temp / 'gen' / steps.STAMP).write_text('L\n') + (dest / 'build-cache').mkdir(parents=True) + (dest / ('totk' + steps.EXE)).write_bytes(b'MZ') + (dest / 'romfs-index.bin').write_bytes(b'') + layout = SimpleNamespace(release='1.0', dlls=[]) + records = {'lift': {'key': 'L'}, 'compile': {'key': 'C', 'exe_sha256': steps.file_sha256(dest / ('totk' + steps.EXE))}} + self.ctx = runner.Context(layout, dest, temp, Reporter(out=io.StringIO()), SimpleNamespace(), + state={'release': '1.0', 'steps': records}) + self.addCleanup(self.ctx.reporter.close) + self.ctx.steps = [steps.Lift(), steps.Compile()] + self.ctx.keys = {'lift': 'L', 'compile': 'C'} + self.stale = dest / 'build-cache' / 'plugins.stale' + + def planned(self): + self.ctx.plan() + return [s.id for s in self.ctx.steps if self.ctx.will_run(s.id)] + + def test_stale_plugin_runs_the_lift_and_the_compile(self): + self.assertEqual(self.planned(), []) + self.stale.write_text('A89F6A7C\t74492AD5\tits init wrote 1 words the build did not record ' + '(first main+0x3ad6eb8 87a00000 -> 823c0000)\n') + self.assertEqual(self.planned(), ['lift', 'compile']) + + def test_empty_stale_file_keeps_the_build(self): + self.stale.write_text('') + self.assertEqual(self.planned(), []) + + class LiftRunTest(unittest.TestCase): """Lift.run with fake tools: the ExeFS patch stage writes the status and data files, the lift lists the bytes it read, and the data writes are checked against that list after it; a failed lift or check drops both files.""" diff --git a/tools/exefs_plugins.py b/tools/exefs_plugins.py index f1d744f5..7b14d4cb 100644 --- a/tools/exefs_plugins.py +++ b/tools/exefs_plugins.py @@ -377,7 +377,8 @@ def check_record(rec, impls, game=frozenset()): # words as it left them here (runtime/plugin_init.c check_writes keeps data pages, compared word by word # with the expect lines). .rodata holds what the lift read as constants (the jump tables), so no write # goes there. A word that makes a pointer into a plugin's .text (a table entry swapped for a plugin - # function: Zonai Fieldworks, Material Columns) names a function start of that plugin's lift. + # function: Zonai Fieldworks, Material Columns) names a function start of that plugin's lift; any other + # word is compared by place only (plugin_lines). if w['offset'] < main['data_off']: reasons.append(f"a write into main's .rodata: {where} {w['old']:#010x} -> {w['new']:#010x}") continue @@ -633,10 +634,20 @@ def plugin_lines(rec, hooks, name, record_dir, module): text_sha = hashlib.sha256(img[:p['text_end']]).hexdigest() image = json.dumps((Path(record_dir) / p['image']).resolve().as_posix(), ensure_ascii=False) lines.append(f'plugin {name} {p["name"]} {text_sha} {image}') - own = {int(h['site'].split('+')[1], 16) for h in hooks} + own = {int(h['site'].split('+')[1], 16): h for h in hooks} + # A word of main's .data or .bss that is no pointer into a plugin's .text (a data hook without a target, and not + # the upper half of one with a target) shapes no lifted code, and the game may hold another value there at play + # than in the service run: Self Recall of Zonai Fieldworks takes its storage off a pool size that grows with the + # resolution's texture heap. Its expect line says `* *`: the start matches it by place only + # (runtime/plugin_init.c check_writes), and the word keeps what the init wrote at play. + pointers = {o for o, h in own.items() if h['kind'] == 'data' and h.get('target')} for w in rec['writes']: if w['module'] == 'main' and w['offset'] in own: - lines.append(f'expect {name} {w["module"]} {w["offset"]:x} {w["old"]:08x} {w["new"]:08x}') + h, o = own[w['offset']], w['offset'] + if h['kind'] == 'data' and o not in pointers and o - 4 not in pointers: + lines.append(f'expect {name} {w["module"]} {o:x} * *') + else: + lines.append(f'expect {name} {w["module"]} {o:x} {w["old"]:08x} {w["new"]:08x}') seeds, stubs = {}, {} def at(ref):