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

+14 -6
View File
@@ -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 <mod> 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 <mod> 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
+34 -14
View File
@@ -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
+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
+15 -1
View File
@@ -11,6 +11,8 @@
// <profile>/save-backup/<time>/ the three committed saves before the current one
// <profile>/temp/ emptied at start
// <profile>/cache/<index>/ cache storage
// <profile>/sdcard/ the SD card a mod plugin mounts (MountSdCard, under any mount name: Zonai
// Fieldworks keeps its settings and logs there); the game never mounts it
//
// The save mount is journaled as on Horizon: changes go to a working copy and become the committed save atomically at
// Commit; a crash or an Unmount before Commit leaves the previous committed save. Commit returns at once and the copy
@@ -33,7 +35,8 @@
#define NMOUNTS 16
#define PATH_CAP 1100
enum { M_FREE, M_SAVE, M_TEMP, M_CACHE, M_SAVE_RO }; // M_SAVE: the working copy; M_SAVE_RO: the committed save
// M_SAVE: the working copy; M_SAVE_RO: the committed save; M_SDCARD: <profile>/sdcard
enum { M_FREE, M_SAVE, M_TEMP, M_CACHE, M_SAVE_RO, M_SDCARD };
typedef struct { int kind; char name[32]; char root[1024]; } Mount;
typedef struct { PlatFile *h; int mode, save; } File; // h NULL = free; save: on a save-data mount
@@ -800,6 +803,14 @@ static uint32_t mount_temp(const char *name) {
return mount_add(name, M_TEMP, p);
}
static uint32_t mount_sdcard(const char *name) {
ready();
char p[PATH_CAP];
snprintf(p, sizeof p, "%s/sdcard", profile);
make_dirs(p);
return mount_add(name, M_SDCARD, p);
}
static void cache_dir(int index, char *out, size_t cap) { snprintf(out, cap, "%s/cache/%d", profile, index); }
static uint32_t create_cache(int index, int64_t size, int64_t journal) {
@@ -1210,6 +1221,7 @@ static void ov_mount_save(Cpu *c) { ret_x(c, mount_save(arg_p(c, 0), arg_p(c, 1)
static void ov_mount_save_ro(Cpu *c) { ret_x(c, mount_save_ro(arg_p(c, 0), arg_x(c, 1), arg_p(c, 2))); }
static void ov_save_exists(Cpu *c) { ret_x(c, save_exists(arg_x(c, 0), arg_p(c, 1))); }
static void ov_mount_temp(Cpu *c) { ret_x(c, mount_temp(arg_p(c, 0))); }
static void ov_mount_sdcard(Cpu *c) { ret_x(c, mount_sdcard(arg_p(c, 0))); }
static void ov_unmount(Cpu *c) { unmount(arg_p(c, 0)); }
static void ov_commit(Cpu *c) { ret_x(c, commit(arg_p(c, 0))); }
static void ov_create_cache(Cpu *c) { ret_x(c, create_cache(I32(0), I64(1), I64(2))); }
@@ -1245,6 +1257,7 @@ static void ov_set_priority(Cpu *c) { (void)c; }
#define S_MOUNT_SAVE_RO "_ZN2nn2fs21MountSaveDataReadOnlyEPKcNS_13ApplicationIdERKNS_7account3UidE"
#define S_SAVE_EXISTS "_ZN2nn2fs18IsSaveDataExistingENS_13ApplicationIdERKNS_7account3UidE"
#define S_MOUNT_TEMP "_ZN2nn2fs21MountTemporaryStorageEPKc"
#define S_MOUNT_SDCARD "_ZN2nn2fs11MountSdCardEPKc"
#define S_UNMOUNT "_ZN2nn2fs7UnmountEPKc"
#define S_COMMIT "_ZN2nn2fs6CommitEPKc"
#define S_CREATE_CACHE "_ZN2nn2fs18CreateCacheStorageEill"
@@ -1281,6 +1294,7 @@ HOST_OVERRIDE(S_MOUNT_SAVE, ov_mount_save);
HOST_OVERRIDE(S_MOUNT_SAVE_RO, ov_mount_save_ro);
HOST_OVERRIDE(S_SAVE_EXISTS, ov_save_exists);
HOST_OVERRIDE(S_MOUNT_TEMP, ov_mount_temp);
HOST_OVERRIDE(S_MOUNT_SDCARD, ov_mount_sdcard);
HOST_OVERRIDE(S_UNMOUNT, ov_unmount);
HOST_OVERRIDE(S_COMMIT, ov_commit);
HOST_OVERRIDE(S_CREATE_CACHE, ov_create_cache);
+13
View File
@@ -119,6 +119,18 @@ static void ov_desired_language(Cpu *c) {
ret_x(c, v);
}
// nn::settings::detail::GetLanguageCode(LanguageCode *out): the system language, the one GetDesiredLanguage gives.
// The game never calls it; Material Columns picks its text by it. x0 = 0 for the callers that read a Result.
static void ov_settings_language(Cpu *c) {
const char *code = ov_language();
uint8_t *out = arg_p(c, 0);
if (out) {
memset(out, 0, 8);
memcpy(out, code, strlen(code));
}
ret_x(c, 0);
}
static void ov_oe_initialize(Cpu *c) { (void)c; rt_log("oe: application environment: a local host process"); }
// void SetPerformanceConfiguration(PerformanceMode mode, int config)
@@ -872,6 +884,7 @@ static void ov_font_size(Cpu *c) {
// ==== registration
HOST_OVERRIDE("_ZN2nn2oe10InitializeEv", ov_oe_initialize);
HOST_OVERRIDE("_ZN2nn2oe18GetDesiredLanguageEv", ov_desired_language);
HOST_OVERRIDE("_ZN2nn8settings6detail15GetLanguageCodeEPNS0_12LanguageCodeE", ov_settings_language);
HOST_OVERRIDE("_ZN2nn2oe27SetPerformanceConfigurationENS0_15PerformanceModeEi", ov_performance_config);
HOST_OVERRIDE("_ZN2nn2oe15SetCpuBoostModeENS0_12CpuBoostModeE", ov_cpu_boost);
HOST_OVERRIDE("_ZN2nn2oe16GetOperationModeEv", ov_operation_mode);
+32 -13
View File
@@ -38,9 +38,15 @@
// hook branches reach main's .text.
// - nn::oe::GetDisplayVersion is answered with this build's game version, so the plugin picks its table for the
// installed game without the applet services.
// Only svcs the init needs are allowed (QueryMemory, GetSystemTick, OutputDebugString, GetInfo 2-5, 12-15 and 65001,
// Map/UnmapProcessMemory); any other one, such as CreateSession and ReplyAndReceive of exlaunch's process-handle
// fallback, ends the run with the reason in the record.
// - GetInfo 6, 16 and 17, the total memory and the system resource size and use, are constants (memory.c
// mem_info); 7, the memory in use, is the same at the same point of the same init. Zonai Fieldworks asks them
// after its hooks are in.
// - SetHeapSize grows the process heap past the size the game's nninitStartup set before the init runs (Zonai
// Fieldworks keeps a pool in the tail). The heap base is fixed and the game asked its size the same way at every
// start, so the init gets the same answer each time.
// Only svcs the init needs are allowed (SetHeapSize, QueryMemory, GetSystemTick, OutputDebugString, GetInfo 2-7,
// 12-17 and 65001, Map/UnmapProcessMemory); any other one, such as CreateSession and ReplyAndReceive of exlaunch's
// process-handle fallback, ends the run with the reason in the record.
//
// The record, in DIR: record.json (modules, which plugins' inits ran, the writes into every game module as words, the
// alias calls, svc and import counts, the tick offset, a refusal), plugin<N>.img (the plugin's image after its init,
@@ -69,7 +75,9 @@
#define POOL_SIZE (64 * GiB)
#define POOL_ALIGN (4 * GiB)
#define RTLD_ALIGN 0x200000ull
#define MAX_ALIASES 256
// exlaunch maps a page alias for every patch it writes and unmaps it after; Zonai Fieldworks makes over 211 in its
// init. Each slot is 48 bytes, and only the live aliases hold a copy of their pages.
#define MAX_ALIASES 2048
#define MAX_IMPORTS 64
#define CUR_PROCESS 0xFFFF8001u
// Horizon memory states and permissions of QueryMemory, and results.
@@ -94,7 +102,7 @@ static uint64_t pool_base;
static int running; // a plugin's init runs: svcs and imports are counted
static int play; // plugins_start: a refused SVC fails the plugin instead of ending the process
static char failed[256]; // play: why the running init was refused
static uint64_t svc_count[0x80], info_count[16], info_65001;
static uint64_t svc_count[0x80], info_count[18], info_65001;
static struct { const char *name; uint64_t calls; } imports[MAX_IMPORTS];
static int nimports;
static uint8_t **pre; // per loaded module: its image before the plugins' inits
@@ -198,11 +206,22 @@ static uint32_t process_memory(int unmap, uint64_t dst, uint32_t process, uint64
}
return R_INVALID_STATE;
}
if (!module_holding(src, size)) return R_INVALID_STATE; // only the modules' own memory
if (!module_holding(src, size)) { // only the modules' own memory
rt_log("plugin-init: MapProcessMemory refused: the source %#llx+%#llx is no module's memory",
(unsigned long long)src, (unsigned long long)size);
return R_INVALID_STATE;
}
RtMemoryInfo q;
mem_query(dst, &q);
if (q.state != ST_FREE || dst + size > q.base + q.size) return R_INVALID_STATE;
if (naliases == MAX_ALIASES) return R_LIMIT_REACHED;
if (q.state != ST_FREE || dst + size > q.base + q.size) {
rt_log("plugin-init: MapProcessMemory refused: the destination %#llx+%#llx is not free (state %#x)",
(unsigned long long)dst, (unsigned long long)size, q.state);
return R_INVALID_STATE;
}
if (naliases == MAX_ALIASES) {
rt_log("plugin-init: MapProcessMemory refused: all %d alias slots used", MAX_ALIASES);
return R_LIMIT_REACHED;
}
if (!plat_mem_commit(dst, size)) return R_INVALID_STATE; // not inside one of our reservations
Alias *al = &aliases[naliases];
al->snap = malloc(size);
@@ -235,10 +254,10 @@ static int plugin_svc(Cpu *c, uint32_t imm, uint64_t pc) {
svc_count[imm & 0x7F]++;
char why[256], at[128];
switch (imm) {
case 0x06: case 0x1E: case 0x27: case 0x74: case 0x75: return 0;
case 0x01: case 0x06: case 0x1E: case 0x27: case 0x74: case 0x75: return 0;
case 0x29: {
uint32_t id = (uint32_t)c->x[1];
if ((id >= 2 && id <= 5) || (id >= 12 && id <= 15)) {
if ((id >= 2 && id <= 7) || (id >= 12 && id <= 17)) {
info_count[id]++;
return 0;
}
@@ -252,8 +271,8 @@ static int plugin_svc(Cpu *c, uint32_t imm, uint64_t pc) {
return 1;
}
}
snprintf(why, sizeof why, "svc %#x at %s (only QueryMemory, GetSystemTick, OutputDebugString, GetInfo 2-5, 12-15 "
"and 65001, Map/UnmapProcessMemory are served)", imm, ldr_describe(pc, at, sizeof at));
snprintf(why, sizeof why, "svc %#x at %s (only SetHeapSize, QueryMemory, GetSystemTick, OutputDebugString, "
"GetInfo 2-7, 12-17 and 65001, Map/UnmapProcessMemory are served)", imm, ldr_describe(pc, at, sizeof at));
refuse(why);
c->x[0] = R_NOT_IMPLEMENTED;
return 1;
@@ -392,7 +411,7 @@ static void write_record(const char *refused) {
if (svc_count[i]) fprintf(f, "%s\"%#x\": %llu", first ? "" : ", ", i, (unsigned long long)svc_count[i]), first = 0;
fputs("},\n\"get_info\": {", f);
first = 1;
for (int i = 0; i < 16; i++)
for (int i = 0; i < 18; i++)
if (info_count[i]) fprintf(f, "%s\"%d\": %llu", first ? "" : ", ", i, (unsigned long long)info_count[i]), first = 0;
if (info_65001) fprintf(f, "%s\"65001\": %llu", first ? "" : ", ", (unsigned long long)info_65001);
fputs("},\n\"imports\": {", f);
+140 -13
View File
@@ -15,6 +15,7 @@ import sys
import tempfile
import unittest
from types import SimpleNamespace
from unittest import mock
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
@@ -208,18 +209,22 @@ class Check(unittest.TestCase):
self.assertEqual(hooks[0]['kind'], 'replace')
self.assertEqual(hooks[0]['trampoline'], f'plugin0+{TRAMP_OFF:#x}')
def test_replace_inside_function(self):
def test_branch_inside_function(self): # a far hook: the plugin's code comes back through an entry
w = [{'module': 'main', 'offset': SITE_OFF, 'old': 0x94000010, 'new': b(MAIN + SITE_OFF, PLUGIN + THUNK_OFF),
'fn_start': False}]
self.refused(record(writes=w), 'from inside a main function')
hooks, reasons = xp.check_record(record(writes=w), IMPLS)
self.assertEqual(reasons, [])
self.assertEqual(hooks[0]['kind'], 'branch')
def test_call_into_function_middle(self):
def test_call_into_function_middle(self): # the target becomes a seed of the plugin's lift
w = [{'module': 'main', 'offset': SITE_OFF, 'old': 0x94000010, 'new': b(MAIN + SITE_OFF, PLUGIN + 0xf08, True)}]
self.refused(record(writes=w), 'neither an inline-hook stub nor a function start')
hooks, reasons = xp.check_record(record(writes=w), IMPLS)
self.assertEqual(reasons, [])
self.assertEqual((hooks[0]['kind'], hooks[0]['target']), ('call', 'plugin0+0xf08'))
def test_bl_to_stub(self): # an inline stub is entered by b; a bl there would skip the saved x30
w = [{'module': 'main', 'offset': SITE_OFF, 'old': 0x94000010, 'new': b(MAIN + SITE_OFF, PLUGIN + STUB_OFF, True)}]
self.refused(record(writes=w), 'neither an inline-hook stub nor a function start')
self.refused(record(writes=w), 'into an inline-hook stub')
def test_refused_run(self):
self.refused(record(refused='svc 0x40 at plugin0+0x76a0'), 'the run was refused')
@@ -233,13 +238,43 @@ class Check(unittest.TestCase):
def test_import(self):
self.refused(record(imports={'_ZN2nn2fs8MountRomEPKcPvm': 1}), 'the import _ZN2nn2fs8MountRom')
def test_write_main_data(self):
def test_import_the_game_imports_is_allowed(self):
rec = record(imports={'_ZN2nn3hid13GetNpadStatesEPNS0_16NpadFullKeyStateEiRKj': 1})
self.assertTrue(xp.check_record(rec, IMPLS)[1])
self.assertEqual(xp.check_record(rec, IMPLS, frozenset(rec['imports']))[1], [])
def test_game_imports_leave_out_the_loader_and_the_boot_hooks(self):
names = ['_ZN2nn2ro10LoadModuleEPNS0_6ModuleEPKvPvmi', '__nnmusl_init_dso', 'glslcCompile',
'_ZN2nn2os32SetMemoryAllocatorForThreadLocalEPFPvmmEPFvS1_mE']
self.assertEqual([n for n in names if not xp.GAME_IMPORTS_LEFT_OUT.search(n)], [])
kept = ['abort', '_ZN2nn2os12CreateThreadEPNS0_10ThreadTypeEPFvPvES3_S3_mi', '_ZN2nn2fs6CommitEPKc']
self.assertEqual([n for n in kept if xp.GAME_IMPORTS_LEFT_OUT.search(n)], [])
def test_game_imports_of_a_missing_exefs_are_none(self):
with tempfile.TemporaryDirectory() as d:
self.assertEqual(xp.game_imports(Path(d)), frozenset())
self.assertEqual(xp.game_imports(None), frozenset())
def test_write_main_data(self): # kept as written, compared at every start
w = [{'module': 'main', 'offset': 0x180008, 'old': 0, 'new': 1}]
self.refused(record(writes=w), "outside main's .text: main+0x180008")
hooks, reasons = xp.check_record(record(writes=w), IMPLS)
self.assertEqual(reasons, [])
self.assertEqual(hooks[0]['kind'], 'data')
self.assertNotIn('target', hooks[0])
def test_pointer_swap(self): # a table entry of main's .data now points at a plugin function
w = [{'module': 'main', 'offset': 0x180010, 'old': 0x00001000, 'new': (PLUGIN + THUNK_OFF) & 0xFFFFFFFF}]
hooks, reasons = xp.check_record(record(writes=w), IMPLS)
self.assertEqual(reasons, [])
self.assertEqual(hooks[0]['target'], f'plugin0+{THUNK_OFF:#x}')
def test_write_main_rodata(self): # the lift read .rodata as constants
w = [{'module': 'main', 'offset': 0x120000, 'old': 0, 'new': 1}]
self.refused(record(writes=w), "a write into main's .rodata: main+0x120000")
def test_write_other_module(self):
w = [{'module': 'sdk', 'offset': 0x100, 'old': 0, 'new': 1}]
self.refused(record(writes=w), "outside main's .text: sdk+0x100")
self.refused(record(writes=w), 'a write outside main: sdk+0x100')
def test_not_a_branch(self):
w = [{'module': 'main', 'offset': SITE_OFF, 'old': 0x94000010, 'new': 0xD503201F}]
@@ -249,10 +284,12 @@ class Check(unittest.TestCase):
w = [{'module': 'main', 'offset': SITE_OFF, 'old': 0x94000010, 'new': b(MAIN + SITE_OFF, MAIN + 0x8000)}]
self.refused(record(writes=w), "does not reach into a plugin's .text")
def test_stub_shape(self):
def test_stub_shape(self): # not exlaunch's stub: plugin code the site branches to, a far hook
stub_at = PLUGIN + STUB_OFF
words = [0xD503201F, b(stub_at + 4, PLUGIN + IMPL_OFF, True), xp.LDUR_X30, b(stub_at + 12, PLUGIN + TRAMP_OFF)]
self.refused(record(stub=words), 'neither an inline-hook stub nor a function start')
hooks, reasons = xp.check_record(record(stub=words), IMPLS)
self.assertEqual(reasons, [])
self.assertEqual(hooks[0]['kind'], 'branch')
def test_stub_impl(self):
stub_at = PLUGIN + STUB_OFF
@@ -281,7 +318,28 @@ class Check(unittest.TestCase):
self.refused(rec, 'no b to the site + 4')
def test_indirect_original(self):
self.refused(record(original=0xD65F03C0), 'is a br, blr or ret')
self.refused(record(original=0xD65F03C0), 'is a br or ret')
self.refused(record(original=0xD61F0100), 'is a br or ret')
def test_blr_original(self): # Zonai Fieldworks hooks blr x8 sites: the call returns, the site goes on
self.assertEqual(self.reasons(record(original=0xD63F0100)), [])
def test_veneer_entries(self): # Zonai Fieldworks: site -> veneer -> slot -> trampoline -> b site + 4
site, ven, slot, tramp = MAIN + SITE_OFF, PLUGIN + 0x5000, PLUGIN + 0xd000, PLUGIN + 0x5100
w = [{'module': 'main', 'offset': SITE_OFF, 'old': 0xD5033BBF, 'new': b(site, ven), 'fn_start': False}]
rec = record(writes=w)
img = bytearray(rec['images']['plugin0'])
imm = ((slot & ~0xFFF) - (ven & ~0xFFF)) >> 12
adrp = 0x90000011 | (imm & 3) << 29 | (imm >> 2 & 0x7FFFF) << 5
struct.pack_into('<3I', img, 0x5000, adrp, 0xF9400231 | ((slot & 0xFFF) // 8) << 10, 0xD61F0220)
struct.pack_into('<Q', img, 0xd000, tramp)
struct.pack_into('<2I', img, 0x5100, 0xD5033BBF, b(tramp + 4, site + 4))
rec['images']['plugin0'] = bytes(img)
hooks, reasons = xp.check_record(rec, IMPLS)
self.assertEqual(reasons, [])
back, ahead = xp.entries(rec, hooks, 'plugin0')
self.assertEqual(back, [SITE_OFF + 4])
self.assertEqual(ahead, [0x5100])
# exlaunch's long forms (tools/exefs_plugins.py relocation_end, returns_to): the trampoline at plugin0+off
def long_form(self, original, off, words):
@@ -384,12 +442,12 @@ class Reach(unittest.TestCase):
# root: bl +0x40; ret. callee at 0x40: svc 0x40; ret
img = bytearray(code([b(self.BASE, self.BASE + 0x40, True), RET_W]))
struct.pack_into('<II', img, 0x40, SVC_40, RET_W)
svcs, imports, indirect, outside = xp.reach(bytes(img), self.BASE, 0x200, [self.BASE], {})
svcs, imports, indirect, outside, _ = xp.reach(bytes(img), self.BASE, 0x200, [self.BASE], {})
self.assertEqual(svcs, {0x40})
def test_imports_through_plt(self):
img = code([b(self.BASE, self.BASE + 0x80, True), RET_W])
svcs, imports, _, _ = xp.reach(img, self.BASE, 0x200, [self.BASE], {self.BASE + 0x80: 'malloc'})
svcs, imports, _, _, _ = xp.reach(img, self.BASE, 0x200, [self.BASE], {self.BASE + 0x80: 'malloc'})
self.assertEqual((svcs, imports), (set(), {'malloc': 1}))
def test_stub_returns_at_its_trampoline_branch(self):
@@ -415,6 +473,36 @@ class Reach(unittest.TestCase):
reasons, _ = xp.reach_check(rec, hooks, IMPLS)
self.assertTrue(any('svc 0x40' in r for r in reasons), reasons)
def test_check_allows_the_game_imports_in_callbacks(self):
# callback: bl <PLT stub of a hid import>; ret
rec = record()
img = bytearray(rec['images']['plugin0'])
plt_at = PLUGIN + 0x7000
struct.pack_into('<II', img, CB_OFF, b(PLUGIN + CB_OFF, plt_at, True), RET_W)
struct.pack_into('<I', img, IMPL_OFF, RET_W)
rec['images']['plugin0'] = bytes(img)
hid = '_ZN2nn3hid13GetNpadStatesEPNS0_16NpadFullKeyStateEiRKj'
hooks, _ = xp.check_record(rec, IMPLS)
with tempfile.NamedTemporaryFile(delete=False) as f:
rec['modules'][2]['file'] = f.name
try:
with mock.patch.object(xp, 'Nso'), mock.patch.object(xp, 'plt_imports', return_value={plt_at: hid}):
refused, _ = xp.reach_check(rec, hooks, IMPLS)
allowed, _ = xp.reach_check(rec, hooks, IMPLS, frozenset({hid}))
finally:
Path(f.name).unlink()
self.assertEqual(refused, [f'the code its hooks reach calls the import {hid}'])
self.assertEqual(allowed, [])
def test_check_allows_break(self): # an abort or a failed assert ends the game, as on the Switch
rec = record()
img = bytearray(rec['images']['plugin0'])
struct.pack_into('<II', img, CB_OFF, 0xD40004C1, RET_W) # svc 0x26
struct.pack_into('<I', img, IMPL_OFF, RET_W)
rec['images']['plugin0'] = bytes(img)
hooks, _ = xp.check_record(rec, IMPLS)
self.assertEqual(xp.reach_check(rec, hooks, IMPLS)[0], [])
def test_check_allows_output_debug_string(self):
rec = record()
img = bytearray(rec['images']['plugin0'])
@@ -755,6 +843,45 @@ class Generator(unittest.TestCase):
self.assertIn(f'void fo_{m:x}(Cpu *c);', tab)
self.assertIn(f'fo_{m:x}', tab[tab.index('_fn_ptrs'):])
def test_branch_hook_on_a_flag_write_leaves_with_the_flags_before_it(self):
# cmp x0, x1; cmp x2, x3 (b to the plugin's trampoline, which runs the cmp); b.eq +8; ret; ret
pb = self.bases['plugin0']
m = self.bases['main'] + FN
self.code({FN: 0xEB01001F, FN + 4: 0xEB03005F, FN + 8: 0x54000040, FN + 12: RET_W, FN + 16: RET_W})
t = self.table(f'site mod_x main {FN + 4:x} eb03005f {b(m + 4, pb + 0x4200):08x}', ['seed plugin0 4200'])
c = self.emit(t, 'main', m, m + 20)
on = c[c.index('if (rt_patch_on[0])'):]
on = on[:on.index('} else {')]
self.assertIn('c->nzcv = fnz_sub64(&F);', on) # the first cmp's flags go to the trampoline
self.assertIn(f'{pb + 0x4200:#x}', on)
def test_inline_hook_on_a_register_call(self):
# blr x8 (inline-hooked); ret
self.code({FN: 0xD63F0100, FN + 4: RET_W})
t = self.table(f'site mod_x main {FN:x} d63f0100 @call:plugin0+4000 d63f0100', ['stub plugin0 4000'])
m = self.bases['main'] + FN
c = self.emit(t, 'main', m, m + 8)
stub = self.bases['plugin0'] + 0x4000
on = c[c.index('if (rt_patch_on[0])'):]
on = on[:on.index('} else {')]
self.assertLess(on.index(f'f_{stub:x}(c);'), on.index('rt_dispatch(c);')) # the hook, then the blr
self.assertIn(f'x30 = {m + 4:#x}ull; c->x[30] = x30; rt_dispatch(c);', on)
def test_orig_trampoline_counts_as_a_seed(self):
# a veneer slot names a replace hook's trampoline: dispatch serves it with the function's unpatched copy
main = self.d / 'exefs' / 'main'
raw = bytearray(main.read_bytes())
struct.pack_into('<II', raw, 0x108, b(8, FN, True), RET_W)
main.write_bytes(raw)
m = self.bases['main'] + FN
self.table(f'site mod_x main {FN:x} aa0003f3 {b(m, self.bases["plugin0"] + 0x4200):08x}',
[f'orig mod_x plugin0 2000 main {FN:x}', 'seed plugin0 4200 2000'])
run = subprocess.run([sys.executable, str(ROOT / 'recomp/gen.py'), '--exefs', str(self.d / 'exefs'),
'--out', str(self.d / 'generated'), '--modules', 'main,plugin0', '--plugins',
str(self.plugin_file), '--patches', str(self.d / 'p.txt'), '--jobs', '1'],
capture_output=True, text=True, timeout=30)
self.assertEqual(run.returncode, 0, run.stdout + run.stderr)
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
+214 -60
View File
@@ -34,7 +34,8 @@ the plugin's .text or .rodata) refuses the plugin: its start could not be compar
The check (check_record) accepts a record only when every rule holds; each broken rule is one reason:
- the run was not refused (an svc outside the served set, such as CreateSession of exlaunch's process-handle
fallback, ends the run with the reason);
- the init called only the svcs ALLOWED_SVCS, GetInfo with ALLOWED_INFO, and the imports ALLOWED_IMPORTS;
- the init called only the svcs ALLOWED_SVCS, GetInfo with ALLOWED_INFO, and the imports ALLOWED_IMPORTS or the
game's (--exefs: what the game's main imports, game_imports);
- every write into a game module is a word of main's .text whose original is no br, blr or ret, and it is one of:
- an inline hook (MSFix, Full Inventory Expansion): `b <stub>` into a plugin's .text, the stub in exlaunch's
shape (stur x30, [sp, #-0x10]; bl one of exlaunch's hook impls, HOOK_IMPLS; ldur x30, [sp, #-0x10];
@@ -47,8 +48,8 @@ The check (check_record) accepts a record only when every rule holds; each broke
the plugin's lift; the Orig trampoline (the original relocated, back to site+4) is listed when the pool holds
one.
- the code the hooks reach (the stubs, exlaunch's hook impls, the callbacks, the replace and call targets, and what
they reach by direct branches and calls, reach()) has no svc but OutputDebugString and calls only the imports
REACH_IMPORTS. An indirect call (blr) is not followed: what it reaches cannot be known before the run.
they reach by direct branches and calls, reach()) makes only the svcs REACH_SVCS and calls only the imports
REACH_IMPORTS or the game's. An indirect call (blr) is not followed: what it reaches cannot be known before the run.
A site shared with a built-in patch set turns that set off while the mod is on (the status line names it); a site
shared with another mod goes through the run time's pick (the Mods tab order, runtime/patches.c).
"""
@@ -56,6 +57,7 @@ import argparse
import hashlib
import json
import os
import re
import struct
import subprocess
import sys
@@ -67,25 +69,52 @@ from cheats import fnv # noqa: E402
from exefs_patches import EXEFS_PLACES, builtin_sites # noqa: E402
from nso import R_AARCH64_JUMP_SLOT, Nso # noqa: E402
ALLOWED_SVCS = {0x06: 'QueryMemory', 0x1E: 'GetSystemTick', 0x27: 'OutputDebugString', 0x29: 'GetInfo',
0x74: 'MapProcessMemory', 0x75: 'UnmapProcessMemory'}
ALLOWED_INFO = {2, 3, 4, 5, 12, 13, 14, 15, 65001}
# Reviewed one by one: SNPrintf formats into the caller's buffer; GetDisplayVersion is answered by the runtime with
# the build's game version; mersenne_twister_engine<uint64_t, ...>::_M_gen_rand (Full Inventory Expansion's alias
# picker) refills the state of the engine object it is given, which lives in the plugin's .bss; memcmp and strlen only
# read; memcpy, memmove and memset write the buffers they are given; malloc and free use the game's heap (sdk's musl
# allocator), and since the init runs again at every start, a block it keeps exists at play time (Quick Weapon
# Durability's init keeps one in its .bss).
SAFE_LIBC = {'malloc', 'free', 'memcpy', 'memmove', 'memset', 'memcmp', 'strlen'}
ALLOWED_SVCS = {0x01: 'SetHeapSize', 0x06: 'QueryMemory', 0x1E: 'GetSystemTick', 0x27: 'OutputDebugString',
0x29: 'GetInfo', 0x74: 'MapProcessMemory', 0x75: 'UnmapProcessMemory'}
ALLOWED_INFO = {2, 3, 4, 5, 6, 7, 12, 13, 14, 15, 16, 17, 65001} # 6, 7, 16, 17: runtime/plugin_init.c header
# Reviewed one by one: SNPrintf and snprintf format into the caller's buffer; GetDisplayVersion is answered by the
# runtime with the build's game version; mersenne_twister_engine<uint64_t, ...>::_M_gen_rand (Full Inventory
# Expansion's alias picker) refills the state of the engine object it is given, which lives in the plugin's .bss;
# memcmp and strlen only read; memcpy, memmove and memset write the buffers they are given; malloc and free use the
# game's heap (sdk's musl allocator), and since the init runs again at every start, a block it keeps exists at play
# time (Quick Weapon Durability's init keeps one in its .bss); nn::os::InitializeMutex fills the mutex object it is
# given, GetSystemTickFrequency is a constant (Zonai Fieldworks).
SAFE_LIBC = {'malloc', 'free', 'memcpy', 'memmove', 'memset', 'memcmp', 'strlen', 'snprintf'}
MT_GEN_RAND = ('_ZNSt23mersenne_twister_engineImLm64ELm312ELm156ELm31ELm13043109905998158313ELm29ELm6148914691236517205'
'ELm17ELm8202884508482404352ELm37ELm18444473444759240704ELm43ELm6364136223846793005EE11_M_gen_randEv')
SNPRINTF = '_ZN2nn4util8SNPrintfEPcmPKcz'
ALLOWED_IMPORTS = SAFE_LIBC | {SNPRINTF, '_ZN2nn2oe17GetDisplayVersionEPNS0_14DisplayVersionE', MT_GEN_RAND}
OS_MUTEX = {'_ZN2nn2os15InitializeMutexEPNS0_9MutexTypeEbi', '_ZN2nn2os9LockMutexEPNS0_9MutexTypeE',
'_ZN2nn2os12TryLockMutexEPNS0_9MutexTypeE', '_ZN2nn2os11UnlockMutexEPNS0_9MutexTypeE'}
OS_TIME = {'_ZN2nn2os22GetSystemTickFrequencyEv', '_ZN2nn2os16GetCurrentThreadEv'}
ALLOWED_IMPORTS = SAFE_LIBC | {SNPRINTF, '_ZN2nn2oe17GetDisplayVersionEPNS0_14DisplayVersionE', MT_GEN_RAND,
'_ZN2nn2os15InitializeMutexEPNS0_9MutexTypeEbi', '_ZN2nn2os22GetSystemTickFrequencyEv'}
# nn::fs functions the runtime serves on the host (runtime/fs_host.c): a plugin's files live on the mounts it opens,
# the SD card (MountSdCard, <profile>/sdcard) or the game's RomFS with the mods' files over it.
HOST_FS = {'_ZN2nn2fs11MountSdCardEPKc', '_ZN2nn2fs8OpenFileEPNS0_10FileHandleEPKci',
'_ZN2nn2fs11GetFileSizeEPlNS0_10FileHandleE', '_ZN2nn2fs9CloseFileENS0_10FileHandleE',
'_ZN2nn2fs8ReadFileENS0_10FileHandleElPvm', '_ZN2nn2fs8ReadFileEPmNS0_10FileHandleElPvm',
'_ZN2nn2fs9WriteFileENS0_10FileHandleElPKvmRKNS0_11WriteOptionE', '_ZN2nn2fs9FlushFileENS0_10FileHandleE',
'_ZN2nn2fs11SetFileSizeENS0_10FileHandleEl', '_ZN2nn2fs10CreateFileEPKcl', '_ZN2nn2fs10DeleteFileEPKc',
'_ZN2nn2fs15CreateDirectoryEPKc', '_ZN2nn2fs13OpenDirectoryEPNS0_15DirectoryHandleEPKci',
'_ZN2nn2fs13ReadDirectoryEPlPNS0_14DirectoryEntryENS0_15DirectoryHandleEl',
'_ZN2nn2fs14CloseDirectoryENS0_15DirectoryHandleE', '_ZN2nn2fs12GetEntryTypeEPNS0_18DirectoryEntryTypeEPKc',
'_ZN2nn2fs8ReadFileEPmNS0_10FileHandleElPvmRKNS0_10ReadOptionE', '_ZN2nn2fs10RenameFileEPKcS2_',
'_ZN2nn2fs26DeleteDirectoryRecursivelyEPKc', '_ZN2nn2fs6CommitEPKc', '_ZN2nn2fs7UnmountEPKc'}
LANGUAGE = {'_ZN2nn2oe18GetDesiredLanguageEv', '_ZN2nn8settings6detail15GetLanguageCodeEPNS0_12LanguageCodeE'}
# The imports the code the hooks reach may call while the game runs (reach()). Each reviewed for what it touches: the
# libc ones above (the caller's buffers and the game's heap), SNPrintf (the caller's buffer). Nothing that waits,
# talks to a service or changes memory mappings.
REACH_IMPORTS = SAFE_LIBC | {SNPRINTF}
SVC_OUTPUT_DEBUG_STRING = 0x27
# libc ones above (the caller's buffers and the game's heap), SNPrintf (the caller's buffer), the sdk's mutexes and
# thread and tick queries (the game's threads use the same ones), the host file functions above and the language
# (runtime/ov_system.c). Nothing that talks to a service or changes memory mappings.
REACH_IMPORTS = SAFE_LIBC | {SNPRINTF} | OS_MUTEX | OS_TIME | HOST_FS | LANGUAGE
# Besides the lists above, a plugin may call what the game's main imports (game_imports): the game runs on those paths,
# so the runtime serves them, through its overrides or the lifted sdk, on every thread. Left out are the imports the
# game calls once at boot or not at all in play, where a second call from a plugin would meet a path nothing has run:
# the module loader (nn::ro), the C runtime's start, the thread-local allocator hook and the shader compiler.
GAME_IMPORTS_LEFT_OUT = re.compile(r'_ZN2nn2ro|__nnmusl_init|SetMemoryAllocatorForThreadLocal|^glslc')
# svcs the code the hooks reach may make: OutputDebugString (the log), GetSystemTick and SleepThread, which the
# runtime serves to every game thread the same way, and Break, an abort or a failed assert, which ends the game with
# the reason in the log as it ends it on the Switch (runtime/svc.c).
REACH_SVCS = {0x0B, 0x1E, 0x26, 0x27}
# exlaunch's inline-hook entry points. Each saves the registers its context holds, calls the callback with that context
# and restores them; none saves NZCV (recomp/flags.py). exl_inline_hook_with_fp_impl (Magic of the Kingdom) saves
# d0..d15 next to x0..x29.
@@ -94,6 +123,9 @@ STUR_X30 = 0xF81F03FE # stur x30, [sp, #-0x10]
LDUR_X30 = 0xF85F03FE # ldur x30, [sp, #-0x10]
STUB_WORDS = 6 # 4 instructions and the callback's .quad
TICK_OFFSET = 0x0123456789AB
# An init that calls into main where the lift has no function start (Zonai Fieldworks calls main+0x481918 of 1.4.3,
# the second word of a function): the runtime's fatal names the address (runtime/dispatch.c dispatch_fail).
MID_CALL = re.compile(r'no function at guest pc 0x[0-9a-f]+ \(main\+0x([0-9a-f]+)\): not a function start')
def u(v):
@@ -110,6 +142,7 @@ def ran_view(rec):
view['modules'] = [dict(m, plugin=False) if m['plugin'] and not m.get('ran', True) else m for m in rec['modules']]
names = {m['name'] for m in view['modules'] if m['plugin']}
view['images'] = {k: v for k, v in rec['images'].items() if k in names}
view['pre_images'] = {k: v for k, v in rec.get('pre_images', {}).items() if k in names}
return view
@@ -271,15 +304,18 @@ def orig_trampoline(img, p, original, site):
# ---- records
def load_record(d):
"""record.json of a service run directory, with the images of its plugins as bytes (key 'images')."""
"""record.json of a service run directory, with the images of its plugins as bytes (key 'images') and their
images from before the init (key 'pre_images', where the run wrote one)."""
d = Path(d)
rec = json.loads((d / 'record.json').read_text(encoding='utf-8'))
rec['images'] = {}
rec['images'], rec['pre_images'] = {}, {}
for m in rec['modules']:
for k in ('base', 'size', 'text_end', 'data_off', 'init'):
m[k] = u(m[k])
if m.get('image'):
rec['images'][m['name']] = (d / m['image']).read_bytes()
if m.get('pre_image') and (d / m['pre_image']).is_file():
rec['pre_images'][m['name']] = (d / m['pre_image']).read_bytes()
for w in rec['writes']:
for k in ('offset', 'old', 'new'):
w[k] = u(w[k])
@@ -297,8 +333,17 @@ def hook_impls(rec):
return out
def check_record(rec, impls):
"""(hooks, reasons): one dict per hook site, and one line per broken rule (no lines: the record is accepted)."""
def game_imports(exefs):
"""The imports of the game's main in the ExeFS folder exefs, without GAME_IMPORTS_LEFT_OUT; empty without one."""
main = Path(exefs) / 'main' if exefs else None
if not main or not main.is_file():
return frozenset()
return frozenset(s[0] for s in Nso(main).imports() if not GAME_IMPORTS_LEFT_OUT.search(s[0]))
def check_record(rec, impls, game=frozenset()):
"""(hooks, reasons): one dict per hook site, and one line per broken rule (no lines: the record is accepted).
game: the game's imports (game_imports), which the init may call besides ALLOWED_IMPORTS."""
reasons, hooks = [], []
if rec.get('refused'):
reasons.append(f'the run was refused: {rec["refused"]}')
@@ -309,7 +354,7 @@ def check_record(rec, impls):
if int(i) not in ALLOWED_INFO:
reasons.append(f'the init asked GetInfo id {i}')
for name, calls in rec.get('imports', {}).items():
if calls and name not in ALLOWED_IMPORTS:
if calls and name not in ALLOWED_IMPORTS and name not in game:
reasons.append(f'the init called the import {name}')
mods = {m['name']: m for m in rec['modules']}
plugins = [m for m in rec['modules'] if m['plugin']]
@@ -324,8 +369,25 @@ def check_record(rec, impls):
main = mods.get('main')
for w in rec['writes']:
where = f'{w["module"]}+{w["offset"]:#x}'
if w['module'] != 'main' or not main or w['offset'] >= main['text_end'] or w['offset'] & 3:
reasons.append(f'a write outside main\'s .text: {where} {w["old"]:#010x} -> {w["new"]:#010x}')
if w['module'] != 'main' or not main or w['offset'] & 3:
reasons.append(f'a write outside main: {where} {w["old"]:#010x} -> {w["new"]:#010x}')
continue
if w['offset'] >= main['text_end']:
# main's .data and .bss: the init runs at every start before the game's constructors and leaves these
# 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.
if w['offset'] < main['data_off']:
reasons.append(f"a write into main's .rodata: {where} {w['old']:#010x} -> {w['new']:#010x}")
continue
hook = {'site': f'main+{w["offset"]:#x}', 'original': f'{w["old"]:#010x}', 'kind': 'data',
'new': f'{w["new"]:#010x}'}
if w['offset'] % 8 == 0:
p, _ = plugin_word(main['base'] & ~0xFFFFFFFF | w['new'])
if p is not None:
hook['target'] = f'{p["name"]}+{(main["base"] & ~0xFFFFFFFF | w["new"]) - p["base"]:#x}'
hooks.append(hook)
continue
site = main['base'] + w['offset']
stub = branch_target(w['new'], site)
@@ -333,30 +395,32 @@ def check_record(rec, impls):
if stub is None:
reasons.append(f'{where}: the new word {w["new"]:#010x} is no b or bl')
continue
if is_indirect(w['old']):
reasons.append(f'{where}: the original {w["old"]:#010x} is a br, blr or ret')
if w['old'] & 0xFFFFFC1F in (0xD61F0000, 0xD65F0000): # br, ret: the site would end its function
reasons.append(f'{where}: the original {w["old"]:#010x} is a br or ret')
p, _ = plugin_word(stub)
if p is None:
reasons.append(f"{where}: {'bl' if link else 'b'} {stub:#x} does not reach into a plugin's .text")
continue
if not (not link and inline_stub(rec['images'][p['name']], stub - p['base'], p)):
# A b or bl straight into the plugin's code (CodePatcher-style call-site rewrite): a site whose replacement
# is that branch, when the target is a function start of the plugin's lift.
# A b replaces the whole main function, so it must sit at a function start of main; exlaunch's replace
# hook keeps the function's first instruction relocated + b site+4 in its pool for the callback's Orig.
exl = inline_stub(rec['images'][p['name']], stub - p['base'], p)
if link and exl: # an inline stub is entered by b: it saves x30 itself
reasons.append(f"{where}: bl {p['name']}+{stub - p['base']:#x} into an inline-hook stub")
continue
if not exl:
# A b or bl straight into the plugin's code: a site whose replacement is that branch, its target a
# function start of the plugin's lift (a seed). A bl returns to the site + 4 inside the lifted function
# (Quick Weapon Durability's call-site rewrite). A b leaves main's function: at a function start it
# replaces it (Full Inventory Expansion's Sort Fixer; exlaunch keeps the first instruction relocated +
# b site+4 for the callback's Orig), inside one it is a far hook (Zonai Fieldworks' veneers and gated
# edits). Where the plugin's code comes back into main, entries() makes a function start of the lift.
o = stub - p['base']
hook = {'site': f'main+{w["offset"]:#x}', 'original': f'{w["old"]:#010x}',
'kind': 'call' if link else 'replace', 'target': f'{p["name"]}+{o:#x}'}
orig = orig_trampoline(rec['images'][p['name']], p, w['old'], site)
kind = 'call' if link else 'replace' if w.get('fn_start') else 'branch'
hook = {'site': f'main+{w["offset"]:#x}', 'original': f'{w["old"]:#010x}', 'kind': kind,
'target': f'{p["name"]}+{o:#x}'}
# the Orig trampoline of a replace hook (an `orig` line); a far hook's way back is an entry instead
orig = orig_trampoline(rec['images'][p['name']], p, w['old'], site) if kind == 'replace' else None
if orig is not None:
hook['trampoline'] = f'{p["name"]}+{orig:#x}'
hooks.append(hook)
if o not in {u(x) for x in p.get('functions', [])}:
reasons.append(f"{where}: {'bl' if link else 'b'} {p['name']}+{o:#x} is neither an inline-hook stub "
f"nor a function start of {p['name']}'s lift")
if not link and not w.get('fn_start'):
reasons.append(f"{where}: b {p['name']}+{o:#x} from inside a main function (only a function start can "
f"be replaced)")
continue
img, o = rec['images'][p['name']], stub - p['base']
s = struct.unpack_from('<4IQ', img, o)
@@ -406,11 +470,26 @@ def plt_imports(nso, img, base, text_end):
return out
def veneer_slot(img, base, text_end, a):
"""Image offset of the pointer a far-jump veneer at a goes through (adrp x17, page; ldr x17, [x17, #off];
br x17: Zonai Fieldworks' hook pads), else None."""
o = a - base
if not 0 <= o <= text_end - 12:
return None
w0, w1, w2 = struct.unpack_from('<3I', img, o)
if w0 & 0x9F00001F != 0x90000011 or w1 & 0xFFC003FF != 0xF9400231 or w2 != 0xD61F0220:
return None
imm = sext((w0 >> 29 & 3) | (w0 >> 5 & 0x7FFFF) << 2, 21)
slot = (a & ~0xFFF) + (imm << 12) + (w1 >> 10 & 0xFFF) * 8 - base
return slot if 0 <= slot <= len(img) - 8 else None
def reach(img, base, text_end, roots, plt, stubs=()):
"""What the code from roots (absolute addresses in the plugin's .text) reaches by falling through, direct branches
and direct calls: (svc immediates, {import: calls}, indirect calls, words outside the .text it branched to). A
stub's b to its trampoline counts as its return (recomp/patches.py `stub`)."""
svcs, imports, indirect, outside = set(), {}, 0, set()
and direct calls: (svc immediates, {import: calls}, indirect calls, words outside the .text it branched to,
veneer targets). A stub's b to its trampoline counts as its return (recomp/patches.py `stub`). A veneer goes on to
the pointer its slot holds after the init (the plugin may change it later, to code its own lift discovers)."""
svcs, imports, indirect, outside, veneers = set(), {}, 0, set(), set()
seen, work = set(), list(roots)
stub_rets = {s + 12 for s in stubs}
while work:
@@ -428,6 +507,11 @@ def reach(img, base, text_end, roots, plt, stubs=()):
w = struct.unpack_from('<I', img, a - base)[0]
if a in stub_rets:
break
slot = veneer_slot(img, base, text_end, a)
if slot is not None:
a = struct.unpack_from('<Q', img, slot)[0]
veneers.add(a)
continue
if w & 0xFFE0001F == 0xD4000001: # svc #imm
svcs.add(w >> 5 & 0xFFFF)
if w & 0x7C000000 == 0x14000000: # b, bl
@@ -446,11 +530,12 @@ def reach(img, base, text_end, roots, plt, stubs=()):
elif w == 0 or w & 0xFFE0001F == 0xD4200000: # udf, brk: ends too
break
a += 4
return svcs, imports, indirect, outside
return svcs, imports, indirect, outside, veneers
def reach_check(rec, hooks, impls):
"""Reasons the code the hooks reach breaks the rules (svcs, imports), and a summary line."""
def reach_check(rec, hooks, impls, game=frozenset()):
"""Reasons the code the hooks reach breaks the rules (svcs, imports), and a summary line. game: the game's imports
(game_imports), which that code may call besides REACH_IMPORTS."""
reasons, notes = [], []
for p in (m for m in rec['modules'] if m['plugin'] and m['name'] in rec['images']):
img, base = rec['images'][p['name']], p['base']
@@ -462,12 +547,13 @@ def reach_check(rec, hooks, impls):
if h['kind'] == 'inline' and h['stub'].startswith(p['name'] + '+'):
stubs.add(base + int(h['stub'].split('+')[1], 16))
roots |= {a for a in impls if base <= a < base + p['text_end']}
roots |= init_code(rec, hooks, p['name'])
nso = Nso(p['file']) if p.get('file') and Path(p['file']).is_file() else None
plt = plt_imports(nso, img, base, p['text_end']) if nso else {}
svcs, imports, indirect, outside = reach(img, base, p['text_end'], sorted(roots), plt, stubs)
for imm in sorted(svcs - {SVC_OUTPUT_DEBUG_STRING}):
svcs, imports, indirect, outside, _ = reach(img, base, p['text_end'], sorted(roots), plt, stubs)
for imm in sorted(svcs - REACH_SVCS):
reasons.append(f'the code its hooks reach has svc {imm:#x}')
for name in sorted(set(imports) - REACH_IMPORTS):
for name in sorted(set(imports) - REACH_IMPORTS - game):
reasons.append(f'the code its hooks reach calls the import {name}')
notes.append(f'{p["name"]}: hooks reach {len(roots)} roots, imports {", ".join(sorted(imports)) or "none"}, '
f'{indirect} indirect calls not followed' + (f', {len(outside)} branches out of its .text'
@@ -486,8 +572,55 @@ def mod_of(nso_path, mods):
def hooks_of(hooks, module):
"""The hooks whose stub or target lies in the plugin module: its own, when one record holds several plugins."""
return [h for h in hooks if (h.get('stub') or h.get('target') or '').split('+')[0] == module]
"""The hooks whose stub or target lies in the plugin module: its own, when one record holds several plugins. A
data write without a target belongs to the plugin whose init ran (each record is one plugin's, TOTK_PLUGIN_ONLY)."""
return [h for h in hooks if (h.get('stub') or h.get('target') or module).split('+')[0] == module]
def init_code(rec, hooks, module):
"""Absolute starts of the code module's init wrote into its own .text where the file had zeros: exlaunch's
trampolines of its far hooks (the moved original words and a branch back). The plugin may point a veneer at any of
them at play (Zonai Fieldworks turns its features' hooks on and off), so each is a root of the reach check and a
seed of the lift. The trampolines of inline hooks (never run) and the Orig trampolines of replace hooks (the lift
serves them with the function's unpatched copy) are left out: their way back would split main's functions."""
p = {m['name']: m for m in rec['modules']}[module]
img, pre = rec['images'].get(module), rec.get('pre_images', {}).get(module)
if img is None or pre is None:
return set()
n = p['text_end'] // 4
now, old = struct.unpack_from(f'<{n}I', img), struct.unpack_from(f'<{n}I', pre)
known = {p['base'] + int(h['trampoline'].split('+')[1], 16) for h in hooks
if (h.get('trampoline') or '').startswith(module + '+')}
out, inside = set(), False # inside: the word before is a written word that goes on to this one
for i in range(n):
new = old[i] == 0 and now[i] != 0
if new and not inside:
out.add(p['base'] + 4 * i)
# b, br, ret end a trampoline; one may follow right after
inside = new and now[i] & 0xFC000000 != 0x14000000 and now[i] & 0xFFFFFC1F not in (0xD61F0000, 0xD65F0000)
return out - known
def entries(rec, hooks, module):
"""(main offsets, plugin offsets): where module's hook code comes back into main's .text, which the lift makes
function starts (recomp/patches.py `entry`), and the code its veneers lead to, seeds of its lift. The site + 4 of a
far hook, and of a replace hook without an Orig trampoline, is one either way: the plugin may point the site's
veneer at its own code later (Zonai Fieldworks turns a feature's hooks on and off at play), and that code comes
back there too."""
mods = {m['name']: m for m in rec['modules']}
main, p = mods['main'], mods[module]
out = {int(h['site'].split('+')[1], 16) + 4 for h in hooks
if h['kind'] == 'branch' or h['kind'] == 'replace' and not h.get('trampoline')}
base, img = p['base'], rec['images'][module]
roots = {base + int(h['target'].split('+')[1], 16) for h in hooks
if h['kind'] in ('branch', 'call', 'data', 'replace') and h.get('target', '').startswith(module + '+')}
tramps = init_code(rec, hooks, module)
roots |= tramps
nso = Nso(p['file']) if p.get('file') and Path(p['file']).is_file() else None
plt = plt_imports(nso, img, base, p['text_end']) if nso else {}
_, _, _, outside, veneers = reach(img, base, p['text_end'], sorted(roots), plt)
out |= {a - main['base'] for a in outside if main['base'] <= a < main['base'] + main['text_end'] and a % 4 == 0}
return sorted(out), sorted(v - base for v in veneers | tramps if base <= v < base + p['text_end'])
def plugin_lines(rec, hooks, name, record_dir, module):
@@ -522,6 +655,9 @@ def plugin_lines(rec, hooks, name, record_dir, module):
impl = branch_target(struct.unpack_from('<I', rec['images'][sm], so + 4)[0], stub_at + 4)
seeds.setdefault(sm, set()).add(impl - mods[sm]['base'])
lines.append(f'site {name} main {site:x} {u(h["original"]):08x} @call:{sm}+{so:x} {u(h["original"]):08x}')
elif h['kind'] == 'data':
if h.get('target', '').startswith(module + '+'):
seeds.setdefault(module, set()).add(at(h['target'])[1])
else:
tm, to = at(h['target'])
seeds.setdefault(tm, set()).add(to)
@@ -530,10 +666,15 @@ def plugin_lines(rec, hooks, name, record_dir, module):
if h['kind'] == 'replace' and h.get('trampoline'):
rm, ro = at(h['trampoline'])
lines.append(f'orig {name} {rm} {ro:x} main {site:x}')
back, ahead = entries(rec, hooks, module)
if ahead:
seeds.setdefault(module, set()).update(ahead)
for m in sorted(stubs):
lines += [f'stub {m} {o:x}' for o in sorted(stubs[m])]
for m in sorted(seeds):
lines.append(f'seed {m} ' + ' '.join(f'{o:x}' for o in sorted(seeds[m])))
if back:
lines.append('entry main ' + ' '.join(f'{o:x}' for o in back))
return lines
@@ -668,11 +809,11 @@ def run(exe, out, tick_offset, timeout, only):
return r.returncode, None
def report(rec, label):
def report(rec, label, game=frozenset()):
rec = ran_view(rec)
impls = hook_impls(rec)
hooks, reasons = check_record(rec, impls)
more, notes = reach_check(rec, hooks, impls)
hooks, reasons = check_record(rec, impls, game)
more, notes = reach_check(rec, hooks, impls, game)
reasons += more
for n in notes:
print(f' {n}')
@@ -684,6 +825,9 @@ def report(rec, label):
if h['kind'] == 'inline':
print(f' inline hook {h["site"]} (was {h["original"]}) -> stub {h["stub"]} -> {h["impl"]}, callback '
f'{h["callback"]}, trampoline {h["trampoline"]} ({h.get("relocated")}; back to site+4)')
elif h['kind'] == 'data':
print(f' data {h["site"]} {h["original"]} -> {h["new"]}' +
(f' (points at {h["target"]})' if h.get('target') else ''))
else:
print(f' {h["kind"]} {h["site"]} (was {h["original"]}) -> {"bl" if h["kind"] == "call" else "b"} '
f'{h["target"]}' + (f', Orig trampoline {h["trampoline"]}' if h.get('trampoline') else ''))
@@ -694,7 +838,7 @@ def report(rec, label):
return hooks, reasons
def plugin_runs(exe, out, module, timeout):
def plugin_runs(exe, out, module, timeout, game=frozenset()):
"""The two service runs of one plugin (run2 with the tick offset) into out/<module>: (its first record or None,
hooks, reasons)."""
recs = []
@@ -707,9 +851,9 @@ def plugin_runs(exe, out, module, timeout):
recs.append(load_record(d))
print(f'{module} run {i}: exit {code}, tick offset {offset:#x}')
if recs[0].get('refused'): # refused: a second run says nothing more
hooks, bad = report(recs[0], f'{module} run 1')
hooks, bad = report(recs[0], f'{module} run 1', game)
return recs[0], hooks, bad
hooks, bad = report(recs[0], f'{module} run 1')
hooks, bad = report(recs[0], f'{module} run 1', game)
diff = diff_records(ran_view(recs[0]), ran_view(recs[1]))
print(f'{module} run 1 against run 2: {len(diff)} differences' + (':' if diff else ''))
for line in diff:
@@ -729,9 +873,12 @@ def main():
ap.add_argument('--check', type=Path, help='check the record in this directory only')
ap.add_argument('--timeout', type=int, default=120, help='seconds a service run may take')
ap.add_argument('--mods', type=Path, help='the mods folder the plugins come from')
ap.add_argument('--exefs', type=Path, help="the game's ExeFS folder: a plugin may call what its main imports")
ap.add_argument('--patches', type=Path, help='the patch file so far')
ap.add_argument('--patches-out', type=Path, help='the patch file with the plugins\' sets added')
ap.add_argument('--status', type=Path, help='the plugin status file (build-cache/plugins.status)')
ap.add_argument('--entries-out', type=Path, help='file for `entry main` lines: addresses of main an init called '
'that the lift has no function start for; a lift with them lets the init go on')
args = ap.parse_args()
sys.stdout.reconfigure(errors='replace')
emitting = bool(args.patches_out or args.status)
@@ -739,7 +886,7 @@ def main():
ap.error('--mods, --patches-out and --status go together')
if args.check:
rec = load_record(args.check)
hooks, bad = report(rec, str(args.check))
hooks, bad = report(rec, str(args.check), game_imports(args.exefs))
if emitting:
emit([(m['name'], m.get('file'), rec, args.check, hooks, bad) for m in ran_view(rec)['modules']
if m['plugin']], args)
@@ -753,13 +900,20 @@ def main():
print(f'the service run without inits gave no record: {why}; see {args.out / "list" / "run.log"}')
return 2
listing = load_record(args.out / 'list')
game = game_imports(args.exefs)
results = []
for m in (m for m in listing['modules'] if m['plugin']):
rec, hooks, bad = plugin_runs(args.exe, args.out, m['name'], args.timeout)
rec, hooks, bad = plugin_runs(args.exe, args.out, m['name'], args.timeout, game)
print(f'{m["name"]}: ' + (f'refused: {bad[0]}' if bad else f'accepted, {len(hooks)} hooks'))
results.append((m['name'], m.get('file'), rec, args.out / m['name'] / 'run1', hooks, bad))
if emitting:
emit(results, args)
if args.entries_out:
found = sorted({int(m.group(1), 16) for r in results for why in r[5] for m in MID_CALL.finditer(why)})
args.entries_out.write_text(''.join(f'entry main {o:x}\n' for o in found), encoding='utf-8')
if found:
print('plugins: inits call main where the lift has no function start: ' +
', '.join(f'main+{o:#x}' for o in found))
return 1 if any(r[5] for r in results) else 0