diff --git a/docs/mods.md b/docs/mods.md index 1fd24061..040d7cf6 100644 --- a/docs/mods.md +++ b/docs/mods.md @@ -123,14 +123,22 @@ The Mods tab order decides between a plugin and another mod's patch on the same plugin site over one of the port's own patches turns that built-in patch off while the mod is on. The rebuild refuses a plugin when its start-up or the code its redirects reach needs what the port does not give it: -system calls other than the few its start-up needs (memory queries and maps, the clock, debug output), library calls -outside a reviewed list (memory and string functions, the heap, text formatting), threads, services or input; a -redirect that is not one of exlaunch's hook shapes (inline hook, replace hook, call-site rewrite); or two runs of its -start-up that differ in code; or a start-up that crashes the service run or does not return within two minutes. The -row then says **Its plugin ... cannot run in the port** with the reason, and the mod stays off; **Use without its -code** uses the rest of it, including its other plugins that were built in. UltraCam stays refused: it hooks the graphics API, +system calls other than the few its start-up needs (memory queries and maps, the heap size, the clock, debug output), +or a library call the game itself never makes and a reviewed list does not hold (memory and string functions, the heap, +text formatting, mutexes, the clock, the system language, the SD card's files), such as network sockets or the module +loader. A library call the game makes (threads, input, time, its files) runs on the path the game runs on. A start-up +still gets only the system calls above, so it cannot start a thread or open a service; a redirect that is not one of exlaunch's hook shapes +(inline hook, replace hook, call-site rewrite, a branch into its code from inside a game function, a pointer in the +game's data swapped for one into its code); a write into the game's read-only data or into another module; two runs of +its start-up that differ in code; or a start-up that crashes the service run or does not return within two minutes. +The row then says **Its plugin ... cannot run in the port** with the reason, and the mod stays off; **Use without +its code** uses the rest of it, including its other plugins that were built in. UltraCam stays refused: it hooks the graphics API, reads input and opens sockets. +When a start-up calls into the middle of a game function, the rebuild lifts the game again with that address as a +function start and reruns the start-up, up to four times. A plugin that reads or writes files on the SD card gets +the folder `sdcard` in the game's profile folder in its place. + `plugin_trace = 1` in `totk.ini` logs the first call into each of a plugin's hooks (`plugins: hook entry ... reached`). ## Cheats diff --git a/installer/steps.py b/installer/steps.py index f231eec5..2686db46 100644 --- a/installer/steps.py +++ b/installer/steps.py @@ -64,6 +64,7 @@ TEMP_NEED = 3 * GiB # generated C (about 0.9 GB) and objects KIT_NEED = 1 * GiB # the build kit (Kit), about 0.65 GB HOSTCHECK = Path(__file__).resolve().parent / 'hostcheck.c' STAMP = '.install-key' +PLUGIN_ENTRY_ROUNDS = 4 # plugin lifts at most: each finds where an init called into main past a function start # ---- helpers @@ -1246,20 +1247,39 @@ class Lift(Step): lift_plugins = [] if plugins: listed = ['--plugins', ','.join(str(f) for f in plugins)] - code, log = run_tool(ctx, 'lift', layout.recomp / 'gen.py', args + ['--patches', patches] + listed, parse) - if not code: - code, log = run_tool(ctx, 'lift', layout.tools / 'build_game.py', build_args(ctx, gen)) - if not code: - # the service run's totk.exe loads its DLLs from its own folder, as the installed one does - for dll in layout.dlls: - replace_file(dll, ctx.temp / 'build' / dll.name) - code, log = run_tool(ctx, 'lift', layout.tools / 'exefs_plugins.py', [ - '--exe', ctx.temp / 'build' / ('totk' + EXE), '--out', ctx.temp / 'plugins', '--mods', - ctx.dest / 'mods', '--patches', patches, '--patches-out', ctx.temp / 'patches-plugins.txt', - '--status', plugins_status(ctx)]) - # exit 1 with a status file: refused plugins, their reasons in it; the rest goes on - if plugins_status(ctx).is_file() and (ctx.temp / 'patches-plugins.txt').is_file(): - code = 0 + # An init that calls into main where the lift has no function start crashes its service run; the tool + # names those addresses (--entries-out), and one more lift with them as `entry` lines lets the init go on + # (Zonai Fieldworks calls the second word of a 1.4.3 function). Each round adds what the last one found. + lift_patches, found = patches, [] + for _ in range(PLUGIN_ENTRY_ROUNDS): + code, log = run_tool(ctx, 'lift', layout.recomp / 'gen.py', args + ['--patches', lift_patches] + listed, + parse) + if not code: + code, log = run_tool(ctx, 'lift', layout.tools / 'build_game.py', build_args(ctx, gen)) + if not code: + # the service run's totk.exe loads its DLLs from its own folder, as the installed one does + for dll in layout.dlls: + replace_file(dll, ctx.temp / 'build' / dll.name) + entries_file = ctx.temp / 'plugin-entries.txt' + entries_file.unlink(missing_ok=True) + code, log = run_tool(ctx, 'lift', layout.tools / 'exefs_plugins.py', [ + '--exe', ctx.temp / 'build' / ('totk' + EXE), '--out', ctx.temp / 'plugins', '--mods', + ctx.dest / 'mods', '--exefs', ctx.dest / 'exefs', '--patches', lift_patches, + '--patches-out', ctx.temp / 'patches-plugins.txt', '--status', plugins_status(ctx), + '--entries-out', entries_file]) + # exit 1 with a status file: refused plugins, their reasons in it; the rest goes on + if plugins_status(ctx).is_file() and (ctx.temp / 'patches-plugins.txt').is_file(): + code = 0 + if code: + break + new = [line for line in (entries_file.read_text(encoding='utf-8').splitlines() + if entries_file.is_file() else []) if line and line not in found] + if not new: + break + found += new + lift_patches = ctx.temp / 'patches-entries.txt' + lift_patches.write_text(Path(patches).read_text(encoding='utf-8') + '\n' + '\n'.join(found) + '\n', + encoding='utf-8') if code: drop([plugins_status(ctx)]) skipped['warn.plugins_skipped'] = log diff --git a/recomp/gen.py b/recomp/gen.py index 8bf0e24b..9e48416f 100644 --- a/recomp/gen.py +++ b/recomp/gen.py @@ -96,10 +96,13 @@ def orig_name(a): def open_module(name, path, base, table, plugin=False): """Module name for lifting: a plugin with a `plugin` line of the patch table (recomp/patches.py) is lifted from its - image after the init, its inline-hook stubs returning where they would branch to their trampolines.""" + image after the init, its inline-hook stubs returning where they would branch to their trampolines. A game module's + `entry` lines are function starts of its lift.""" p = table.plugins.get(name) if not p: - return Module(name, path, base, 'c', plugin=plugin) + mod = Module(name, path, base, 'c', plugin=plugin) + mod.entries = sorted(base + o for o in table.entries.get(name, ())) + return mod image = Path(p['image']).read_bytes() mod = Module(name, path, base, 'c', plugin=True, image=image, rets=[o + 12 for o in p['stubs']], seeds=sorted(p['stubs'] | p['seeds'])) @@ -195,24 +198,58 @@ def discover(mod): stats = {'seeds': int(len(seeds)), 'bl_targets': int(len(np.unique(bl_tgt))), 'materialised_targets': int(len(np.unique(mat))), 'initial_starts': int(len(starts))} - rounds = 0 - while True: - rounds += 1 - f = np.searchsorted(starts, br_src, side='right') - 1 - live = f >= 0 - f = np.where(live, f, 0) - lo = starts[f] - hi = np.where(f + 1 < len(starts), starts[np.minimum(f + 1, len(starts) - 1)], n) - out = live & ((br_tgt < lo) | (br_tgt >= hi)) - new = np.setdiff1d(br_tgt[out], starts, assume_unique=False) - if not len(new): - break - starts = np.union1d(starts, new) - stats['rounds'] = rounds + def close(starts): + rounds = 0 + while True: + rounds += 1 + f = np.searchsorted(starts, br_src, side='right') - 1 + live = f >= 0 + f = np.where(live, f, 0) + lo = starts[f] + hi = np.where(f + 1 < len(starts), starts[np.minimum(f + 1, len(starts) - 1)], n) + out = live & ((br_tgt < lo) | (br_tgt >= hi)) + new = np.setdiff1d(br_tgt[out], starts, assume_unique=False) + if not len(new): + return starts, rounds + starts = np.union1d(starts, new) + + starts, stats['rounds'] = close(starts) + entries = getattr(mod, 'entries', ()) + if entries: + extra = entry_starts(mod, starts, entries, br) + stats['entries'] = len(entries) + starts, more = close(np.union1d(starts, (np.asarray(sorted(extra), dtype=np.int64) - pc0) >> 2)) + stats['rounds'] += more stats['functions'] = int(len(starts)) return starts, stats +def entry_starts(mod, starts, entries, br): + """The function starts mod's `entry` addresses add (recomp/patches.py): each entry, and every target of the jump + tables of the function that held it. A table whose cases fell on both sides of the new boundary would reach the + cases outside its function through rt_dispatch, which only enters function starts; with every case a start, the + table's br dispatches to them (the all-label fallback). An unresolved computed br there gets a warning: its targets + are not known, so a case past the entry would stop the game with a named fatal.""" + out, pc0 = set(), mod.lo + for e in entries: + if not mod.in_text(e): + raise SystemExit(f'{mod.name}: the entry {e:#x} is outside its .text') + k = int(np.searchsorted(starts, (e - pc0) >> 2, side='right')) - 1 + lo = pc0 + int(starts[k]) * 4 + hi = pc0 + int(starts[k + 1]) * 4 if k + 1 < len(starts) else mod.hi + out.add(e) + if e == lo: + continue + for i in br[(br >= (lo - pc0) >> 2) & (br < (hi - pc0) >> 2)].tolist(): + jt = jumptables.resolve(mod, pc0 + 4 * i, lo, hi) + if jt: + out.update(jt) + elif jumptables.is_computed(mod, pc0 + 4 * i, lo): + print(f'{mod.name}: warning: the entry {e:#x} lies in the function {lo:#x} with an unresolved table ' + f'jump at {pc0 + 4 * i:#x}', flush=True) + return out + + def estimate_sizes(mod, starts): """Estimated bytes of C per function (for chunking only; the manifest records the real sizes).""" w = mod.words @@ -316,7 +353,8 @@ class Emitter: def replacements(self, a): """The lifted words of each alternative of the patched site a, in set order. Only the last word of an - alternative may branch (bl, b, b.cond / cbz / tbz, ret).""" + alternative may branch (bl, blr, b, b.cond / cbz / tbz, ret); a blr is a site's own word kept after an inline + hook.""" out = [] for _, words in self.patched[a]: # ('call', target): a plugin's inline hook (recomp/patches.py @call), before the site's own instruction @@ -325,7 +363,7 @@ class Emitter: last = j == len(lifted) - 1 if r.kind == 'hook' and not last: continue - if r.kind != 'op' and not (last and r.kind in ('bl', 'b', 'bcond', 'ret')): + if r.kind != 'op' and not (last and r.kind in ('bl', 'blr', 'b', 'bcond', 'ret')): raise patches.PatchError(f'{a:#x}: replacement word {words[j]:08x} is a {r.kind}') out.append(lifted) return out @@ -378,7 +416,7 @@ class Emitter: effects.append(self.patched_effect(ins, a)) for words in self.replacements(a): r = words[-1] - if r.kind == 'bl': + if r.kind in ('bl', 'blr'): calls.add(i) elif r.kind in ('b', 'bcond') and not entry <= r.target < end: exits.add(i) @@ -391,19 +429,26 @@ class Emitter: def patched_effect(self, ins, a): """Flag effect of a patched site: every alternative (the original and each replacement) must write the same - flags, in at most one word each; the site reads flags when any alternative does (a b.cond reads them).""" + flags, in at most one word each; the site reads flags when any alternative does (a b.cond reads them). + An alternative that only branches out of the module (a plugin's branch hook, whose trampoline runs the + original word) counts for none: it leaves with the flags from before the site, which its tail exit publishes + (flags.plan), and nothing after the site in this function sees it.""" alts = [] - for words in [[ins]] + self.replacements(a): + for k, words in enumerate([[ins]] + self.replacements(a)): fx = [flags.effect(w.code or '') if w.kind == 'op' else flags.effect(w.cond) for w in words if w.kind in ('op', 'bcond')] fx = [e for e in fx if e[0] or e[1]] if len(fx) > 1: raise patches.PatchError(f'{a:#x}: several flag-using words in one alternative') + last = words[-1] + if k and not fx and last.kind == 'b' and not self.mod.lo <= last.target < self.mod.hi: + continue alts.append(fx[0] if fx else (False, None)) if any(e[1] != alts[0][1] for e in alts): raise patches.PatchError(f'{a:#x}: the alternatives write different flags ({[e[1] for e in alts]})') reads = any(e[0] for e in alts) - if (alts[0][1] or reads) and (ins.kind == 'bl' or any(w[-1].kind == 'bl' for w in self.replacements(a))): + if (alts[0][1] or reads) and (ins.kind in ('bl', 'blr') or + any(w[-1].kind in ('bl', 'blr') for w in self.replacements(a))): raise patches.PatchError(f'{a:#x}: a patched call that uses flags') return reads, alts[0][1] @@ -511,6 +556,9 @@ class Emitter: return f'if ({fx(i, r.cond)}) {{ {jump(r.target, i)} }}' if r.kind == 'ret': return f'{spill}return;' + if r.kind == 'blr': # an original call through a register (a plugin hooks Zonai Fieldworks' blr x8 sites) + return (f'{give(i)}c->pc = {r.target}; c->x[30] = {hx(a + 4)}; {spill}rt_dispatch(c);{reload_call}' + f'{take(i)}') if r.kind == 'hook': # a call that writes no x30, the whole Cpu current before it and read back after it: the stub saves and # restores x30 itself, and the callback may change any register through exlaunch's hook context @@ -523,7 +571,7 @@ class Emitter: def patch(i, ins, a): """if (switch) { replacement } else if ... else { original } for a patched site (recomp/patches.py); an ordered set of a contested site tests the site's pick byte instead of its switch.""" - if ins.kind not in ('op', 'bl', 'b', 'bcond'): + if ins.kind not in ('op', 'bl', 'blr', 'b', 'bcond'): raise patches.PatchError(f'{a:#x}: patched instruction is a {ins.kind}') line = ' ' n, values = self.picks.get(a, (None, {})) @@ -1004,8 +1052,9 @@ def main(): n = len(starts) if not args.limit else min(args.limit, len(starts)) ends = np.append(abs_starts[1:], mod.hi) chunks = partition(est[:n], args.chunk_fns, args.chunk_bytes, args.big_fn) - missing = sorted(base + o for o in (table.plugins.get(name) or {}).get('seeds', ()) - if base + o not in set(abs_starts.tolist())) + # a seed that is an `orig` trampoline counts as found: dispatch takes its address to the function's copy + missing = sorted(base + o for o in set((table.plugins.get(name) or {}).get('seeds', ())) | + table.entries.get(name, set()) if base + o not in set(abs_starts.tolist()) | set(extra)) if missing: raise SystemExit(f'{name}: the seeds {", ".join(hex(a) for a in missing)} are no function starts') mkey = module_key(gen_key, name, path, base, abs_starts) diff --git a/recomp/patches.py b/recomp/patches.py index ad738a68..03ebc018 100644 --- a/recomp/patches.py +++ b/recomp/patches.py @@ -16,6 +16,7 @@ path may be a JSON double-quoted string to preserve spaces, `#` and escaped char stub seed [ ...] orig + entry [ ...]
is a module offset (hex), the instruction word the module has there (checked; a mismatch stops the generator), each an instruction word (hex) or `@page:x`, which is `adrp x, ` @@ -41,7 +42,7 @@ wins, a tie goes to the set later in the file). The other alternatives of a cont their rt_patch_on test, so a cheat before the mods' sets still wins while it is on. A site with at most one ordered set, and a table without contested sites, is emitted exactly as without the keyword. -The original may be any instruction but br, blr and ret; a replacement's last word may be +The original may be any instruction but br and ret; a replacement's last word may be a bl (lifted with the site's return address), a b or b.cond / cbz / tbz (its target joins the function's labels when inside it) or a ret; earlier words must not branch. Every alternative of a site writes the same flags. The generator writes patches.h (set names, switches, the page address, the contested sites) next to layout.h for the runtime. @@ -68,6 +69,12 @@ run's record; the design follows #845 by itaskaev2): lifts the function at + a second time without its patched sites (fo_
) and lists that copy at the trampoline's address in 's function table, so the call reaches the original code and not the hook again. +An `entry` line names addresses of a game module that a plugin calls by pointer although they are no function start +of the game's code (Zonai Fieldworks calls main+0x481918 of 1.4.3, the second word of a function, skipping its first +test). gen.py makes each one a function start of the module's lift: the function that held it ends there and runs on +into it by a tail jump, as at any function boundary, so the game's own path through the code does not change. +tools/exefs_plugins.py writes them when a service run calls such an address (installer/steps.py lifts again). + A replacement word `@call:+` is a call of the function there that writes no x30: every register in the Cpu at the call and all read back after it (the callback may change any of them, as exlaunch's hook context allows); the flags are published before it and taken back after it, since exlaunch's hook impl saves no NZCV and the @@ -104,8 +111,9 @@ class Table: from here (for_module, picks_for, spins_for, hooks_for) is in the lift cache's key (recomp/gen.py chunk_key); a new kind of line the Emitter reads must go there too.""" - def __init__(self, sets=(), sites=None, page=0, spins=None, hooks=None, ordered=(), plugins=None): + def __init__(self, sets=(), sites=None, page=0, spins=None, hooks=None, ordered=(), plugins=None, entries=None): self.sets = list(sets) + self.entries = entries or {} # {module: {offset}}: `entry` lines self.sites = sites or {} self.page = page self.spins = spins or {} # {module: {back-edge offset: head offset}} @@ -187,7 +195,7 @@ class Table: def load(path, mods): """Table from a patch file; mods is layout() output [(name, base, size)].""" - sets, index, sites, spins, hooks, ordered, plugins = [], {}, {}, {}, {}, set(), {} + sets, index, sites, spins, hooks, ordered, plugins, entries = [], {}, {}, {}, {}, set(), {}, {} bases = {n: (b, s) for n, b, s in mods} for no, raw in enumerate(Path(path).read_text(encoding='utf-8').splitlines(), 1): where = f'{path}:{no}' @@ -255,6 +263,10 @@ def load(path, mods): 'seeds': set(), 'origs': {}} elif f[0] in ('expect', 'stub', 'seed', 'orig'): plugin_line(f, where, index, bases, plugins) + elif f[0] == 'entry' and len(f) >= 3: + if f[1] not in bases: + raise PatchError(f'{where}: module {f[1]} not in the layout') + entries.setdefault(f[1], set()).update(int(o, 16) for o in f[2:]) elif f[0] == 'hook' and len(f) >= 3: if f[1] not in bases: raise PatchError(f'{where}: module {f[1]} not in the layout') @@ -266,7 +278,7 @@ def load(path, mods): nxt = min((b for _, b, _ in mods if b > base), default=None) if nxt is not None and page + PAGE > nxt: raise PatchError(f'no room for the patch page after main ({page:#x})') - table = Table(sets, sites, page, spins, hooks, ordered, plugins) + table = Table(sets, sites, page, spins, hooks, ordered, plugins, entries) table.bases = {n: b for n, (b, _) in bases.items()} return table diff --git a/runtime/fs_host.c b/runtime/fs_host.c index 9391c5b5..5379ea69 100644 --- a/runtime/fs_host.c +++ b/runtime/fs_host.c @@ -11,6 +11,8 @@ // /save-backup/