Mod plugins that hook the middle of game functions, swap pointers in the game's data, use the SD card or switch their hooks during play build in, and may call what the game itself calls; Zonai Fieldworks starts (#1388)

Zonai Fieldworks was refused at several steps; each is now handled:
1. The start-up asked GetInfo 6, 7, 16 and 17 and SetHeapSize; runtime/plugin_init.c serves them.
2. Its start-up calls main where the lift has no function start. The tool names those addresses (--entries-out) and
   the installer lifts again with them as `entry` lines, up to four rounds (installer/steps.py PLUGIN_ENTRY_ROUNDS).
3. Branch hooks into the middle of game functions (far-jump veneers) and pointer swaps in main's data are accepted
   hook kinds; the veneer targets seed the plugin's lift, and an Orig trampoline counts as a seed.
4. Code the start-up writes into the plugin's own .text (hook pads it switches to during play) is found by comparing
   the image before and after the init, and seeds the lift (init_code). Without it the game stopped with "no function
   at guest pc" when a feature switched on.
5. recomp/gen.py: a branch-out alternative on a flag-writing site leaves with the flags from before the site; an inline
   hook may sit on a blr.
6. nn::fs::MountSdCard mounts <profile>/sdcard (runtime/fs_host.c), and nn::settings language codes are answered
   (runtime/ov_system.c).

The import check now also allows what the game's main imports (--exefs, game_imports): the game runs on those paths,
so the runtime serves them. Left out: nn::ro, the C runtime start, the thread-local allocator hook and the shader
compiler. Break in code the hooks reach is allowed (an abort ends the game with the reason, as on the Switch), and
RenameFile, DeleteDirectoryRecursively, Commit and Unmount join the SD card calls. Checked: Zonai Fieldworks, The Second
Quest, Challenge Mode and Material Columns on 1.4.3, Full Inventory Expansion, Quick Weapon Durability and Magic of the
Kingdom on 1.2.1 accepted; UltraCam's init still crashes its service run. Plain lift unchanged; probes 4/4 on both
versions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Valiantsin DzerakhandClaude Opus 5.5 committed 2026-11-23 10:35:59 +03:00
1 parent 942b6b7b2b
commit 3fe8d7a1d9
9 files changed
+552 -136

No files matched your search

+74 -25
View File
@@ -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)
+16 -4
View File
@@ -16,6 +16,7 @@ path may be a JSON double-quoted string to preserve spaces, `#` and escaped char
stub <module> <offset>
seed <module> <offset> [<offset> ...]
orig <set> <module> <offset> <function module> <function offset>
entry <module> <offset> [<offset> ...]
<address> is a module offset (hex), <original> the instruction word the module has there (checked; a mismatch stops
the generator), each <replacement> an instruction word (hex) or `@page:x<n>`, which is `adrp x<n>, <patch page>`
@@ -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 <function module>+<function offset> a second time without its patched sites
(fo_<address>) and lists that copy at the trampoline's address in <module>'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:<module>+<offset>` 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