"""recomp/layout.py with and without mod plugins, and tools/exefs_plugins.py's check of a plugin service run record: a synthetic exlaunch-shaped record with one inline hook that passes, and one bad record per rule; the check of the code the hooks reach; the patch lines of the three hook kinds; and what recomp/patches.py and recomp/gen.py make of those lines (the hook call, the stub's return, the unpatched copy a replace hook's trampoline reaches, the start-up record in patches.h). The start-up comparison itself runs in the game (runtime/plugin_init.c plugins_start); its mods.c side is in totk.exe --probe-mods. No game files. Run with .venv (lz4 and numpy, as recomp/): python tests/exefs_plugins_test.py """ import hashlib import json import os import shutil import struct import subprocess import sys import tempfile import unittest from types import SimpleNamespace from unittest import mock from pathlib import Path ROOT = Path(__file__).resolve().parent.parent sys.path.insert(0, str(ROOT / 'tools')) sys.path.insert(0, str(ROOT / 'recomp')) import exefs_plugins as xp # noqa: E402 import gen # noqa: E402 import layout # noqa: E402 import patches # noqa: E402 from nso import Nso # noqa: E402 def nso(size_text, bss=0x1000): """An uncompressed NSO: .text of size_text bytes (b over MOD0's offset word), .rodata with MOD0 at 0x1000 past .text, .data with an empty .dynamic.""" text = bytearray(size_text) struct.pack_into('> 2) & 0x3FFFFFF def quad(v): """The two words of a .quad v.""" return [v & 0xFFFFFFFF, v >> 32] def record(original=0x94000010, trampoline_first=None, stub=None, writes=None, **extra): """A record of one inline hook at main+SITE_OFF whose original is `original` (default bl main+SITE_OFF+0x40).""" site, stub_at, tramp = MAIN + SITE_OFF, PLUGIN + STUB_OFF, PLUGIN + TRAMP_OFF img = bytearray(0x14000) words = stub or [xp.STUR_X30, b(stub_at + 4, PLUGIN + IMPL_OFF, True), xp.LDUR_X30, b(stub_at + 12, tramp)] struct.pack_into('<4IQ', img, STUB_OFF, *words, PLUGIN + CB_OFF) if trampoline_first is None: rel = xp.pc_relative(original, site) trampoline_first = (b(tramp, rel[1], True) if rel and rel[0][0] == 'b' else original) struct.pack_into(' 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(' site, t = MAIN + SITE_OFF, PLUGIN + TRAMP_OFF words = [0x58000048, 0x14000003, *quad(site & ~0xFFF), b(t + 16, site + 4)] self.assertEqual(self.reasons(self.long_form(0x90000008, TRAMP_OFF, words)), []) def test_trampoline_ldr_literal_long(self): # ldr x1, : ldr x1, #8; b over the 8 bytes; the bytes site, t = MAIN + SITE_OFF, PLUGIN + TRAMP_OFF words = [0x58000041, 0x14000003, 0x11223344, 0x55667788, b(t + 16, site + 4)] self.assertEqual(self.reasons(self.long_form(0x58000801, TRAMP_OFF, words)), []) def test_trampoline_absolute_return(self): # back to the site + 4 by ldr x17, #8; br x17; .quad, nop-aligned site = MAIN + SITE_OFF words = [0xAA0003F3, xp.NOP, xp.LDR_X17_8, xp.BR_X17, *quad(site + 4)] self.assertEqual(self.reasons(self.long_form(0xAA0003F3, TRAMP_OFF, words)), []) words[-2:] = quad(site + 8) self.refused(self.long_form(0xAA0003F3, TRAMP_OFF, words), 'no b to the site + 4') def test_replace_hook_adrp_orig(self): # a function starting with adrp: its Orig trampoline is the long form site, t, adrp = MAIN + SITE_OFF, PLUGIN + TRAMP_OFF, 0x90000008 w = [{'module': 'main', 'offset': SITE_OFF, 'old': adrp, 'new': b(site, PLUGIN + THUNK_OFF), 'fn_start': True}] rec = self.long_form(adrp, TRAMP_OFF, [0x58000048, 0x14000003, *quad(site & ~0xFFF), b(t + 16, site + 4)]) rec['writes'] = w hooks, reasons = xp.check_record(rec, IMPLS) self.assertEqual(reasons, []) self.assertEqual(hooks[0]['trampoline'], f'plugin0+{TRAMP_OFF:#x}') class Diff(unittest.TestCase): def test_lists_differing_words(self): a, c = record(), record() img = bytearray(c['images']['plugin0']) struct.pack_into('; ret rec = record() img = bytearray(rec['images']['plugin0']) plt_at = PLUGIN + 0x7000 struct.pack_into(' 7f1c0000, a start whose resolution grew the texture heap has # 87a00000 -> 823c0000 there. The word shapes no lifted code, so its expect line takes any value. rec = record(writes=[{'module': 'main', 'offset': 0x3ad6eb8, 'old': 0x84800000, 'new': 0x7F1C0000}]) rec['modules'][0]['size'] = 0x3adf000 out = self.lines(rec) self.assertIn('expect mod_x main 3ad6eb8 * *', out) self.assertFalse(any('84800000' in x or '7f1c0000' in x for x in out), out) def test_pointer_swap_keeps_its_words(self): # a table entry that now points at a plugin function is a seed of the lift: both its words stay exact new = PLUGIN + THUNK_OFF w = [{'module': 'main', 'offset': 0x180010, 'old': 0x00001000, 'new': new & 0xFFFFFFFF}, {'module': 'main', 'offset': 0x180014, 'old': 0, 'new': new >> 32}, {'module': 'main', 'offset': 0x180020, 'old': 5, 'new': 6}] out = self.lines(record(writes=w)) self.assertIn(f'expect mod_x main 180010 00001000 {new & 0xFFFFFFFF:08x}', out) self.assertIn(f'expect mod_x main 180014 00000000 {new >> 32:08x}', out) self.assertIn('expect mod_x main 180020 * *', out) # ---- one service run per plugin class PerPlugin(unittest.TestCase): """main() with three plugins in three mods and a stand-in for the service run: plugin0 hooks its site, plugin1's init ends the run without a record (a crash), plugin2's run is refused (an svc). Each gets its own status line; only plugin0's set goes into the patch file.""" def setUp(self): tmp = tempfile.TemporaryDirectory() self.addCleanup(tmp.cleanup) self.d = Path(tmp.name) self.files = [] for name in ('A', 'B', 'C'): f = self.d / 'mods' / name / 'exefs' / 'subsdk9' f.parent.mkdir(parents=True) f.write_bytes(nso(PLUGIN_TEXT) + name.encode()) self.files.append(f) (self.d / 'patches.txt').write_text('set fps60 TOTK_FPS60 1\n') self.runs = [] saved = xp.run, xp.hook_impls self.real_run = xp.run self.addCleanup(lambda: (setattr(xp, 'run', saved[0]), setattr(xp, 'hook_impls', saved[1]))) xp.run, xp.hook_impls = self.fake_run, lambda rec: IMPLS def fake_run(self, exe, out, tick_offset, timeout, only): self.runs.append(only) out.mkdir(parents=True, exist_ok=True) if only == 'plugin1': return 0xC0000005, 'its init ended the service run without a record (exit 0xc0000005)' rec = record(writes=[] if only != 'plugin0' else None) rec['modules'][2]['file'] = str(self.files[0]) for i in (1, 2): rec['modules'].append(dict(rec['modules'][2], name=f'plugin{i}', base=PLUGIN + i * 0x100000, file=str(self.files[i]))) for m in rec['modules'][2:]: m['ran'] = m['name'] == only if only == 'plugin2': rec['refused'] = 'svc 0x1 at plugin2+0x50a0' (out / 'plugin0.img').write_bytes(rec.pop('images')['plugin0']) rec['modules'][2]['image'] = 'plugin0.img' (out / 'record.json').write_text(json.dumps(rec)) return 3 if rec['refused'] else 0, None def test_each_plugin_alone(self): out, status, patched = self.d / 'rec', self.d / 'plugins.status', self.d / 'patches-out.txt' argv = sys.argv sys.argv = ['exefs_plugins.py', '--exe', 'totk.exe', '--out', str(out), '--mods', str(self.d / 'mods'), '--patches', str(self.d / 'patches.txt'), '--patches-out', str(patched), '--status', str(status)] try: code = xp.main() finally: sys.argv = argv self.assertEqual(code, 1) self.assertEqual(self.runs, ['-', 'plugin0', 'plugin0', 'plugin1', 'plugin2']) lines = {line.split('\t')[0]: line.split('\t') for line in status.read_text().splitlines()} key = {n: xp.fnv(f'{n}/exefs/subsdk9'.encode()) for n in 'ABC'} self.assertEqual(lines[key['A']][2:], ['plugin', '-', 'plugin0, 1 hooks']) self.assertEqual(lines[key['B']][2], 'unsupported') self.assertIn('ended the service run', lines[key['B']][4]) self.assertEqual(lines[key['C']][2], 'unsupported') self.assertIn('svc 0x1', lines[key['C']][4]) text = patched.read_text() self.assertIn(f'set mod_{key["A"].lower()} ', text) self.assertNotIn(f'mod_{key["B"].lower()}', text) self.assertNotIn(f'mod_{key["C"].lower()}', text) self.assertIn((out / 'plugin0' / 'run1' / 'plugin0.img').resolve().as_posix(), text) def test_run_reasons(self): # the real run(): a hang becomes its own reason, a crash names the FATAL line saved = xp.subprocess.run self.addCleanup(setattr, xp.subprocess, 'run', saved) def hang(cmd, **kw): raise xp.subprocess.TimeoutExpired(cmd, kw['timeout'], output=b'started', stderr=None) xp.subprocess.run = hang self.assertEqual(self.real_run(None, self.d / 'h', 0, 7, 'plugin0'), (None, 'its init did not return within 7 s')) xp.subprocess.run = lambda cmd, **kw: SimpleNamespace(returncode=0xC0000005, stdout='x\nFATAL: access violation ' '(0xc0000005) at host 1\n', stderr='') code, why = self.real_run(None, self.d / 'c', 0, 7, 'plugin0') self.assertEqual(why, 'its init crashed the service run: access violation (0xc0000005) at host 1') def test_ran_view_leaves_out_plugins_that_did_not_run(self): rec = record() rec['modules'].append(dict(rec['modules'][2], name='plugin1', base=PLUGIN + 0x100000, ran=False)) rec['modules'][2]['ran'] = True rec['images']['plugin1'] = rec['images']['plugin0'] view = xp.ran_view(rec) self.assertEqual([m['name'] for m in view['modules'] if m['plugin']], ['plugin0']) self.assertEqual(set(view['images']), {'plugin0'}) whole = record() # no "ran": every init ran, the record is its own view self.assertIs(xp.ran_view(whole), whole) # ---- the generator on those lines def code_nso(words_at, size_text=0x5000): """An NSO as nso() whose .text holds words_at {offset: word}.""" raw = bytearray(nso(size_text)) for off, w in words_at.items(): struct.pack_into('x[30] =', head) # no x30 written for the call self.assertIn(f'void f_{stub:x}(Cpu *c);', c) h = patches.header_text(t, 'MARK') self.assertIn('#define RT_PLUGIN_COUNT 1', h) self.assertIn(f'X(0, "main", {FN:#x}, 0xaa0003f3u, 0x14000000u, 0)', h) self.assertIn('X("plugin0", 0x4100) X("plugin0", 0x4200)', h) def test_any_value_expect_line(self): # `*` for both words: runtime/plugin_init.c check_writes matches the word by place only t = self.table(f'site mod_x main {FN:x} aa0003f3 @call:plugin0+4000 aa0003f3', ['stub plugin0 4000', 'expect mod_x main 3ad6eb8 * *']) self.assertIn(('main', 0x3ad6eb8, None, None), t.plugins['plugin0']['expect']) h = patches.header_text(t, 'MARK') self.assertIn('X(0, "main", 0x3ad6eb8, 0x00000000u, 0x00000000u, 1)', h) self.assertIn(f'X(0, "main", {FN:#x}, 0xaa0003f3u, 0x14000000u, 0)', h) for half in ('* 7f1c0000', '84800000 *'): with self.subTest(half=half), self.assertRaises(patches.PatchError): self.table(f'site mod_x main {FN:x} aa0003f3 @call:plugin0+4000 aa0003f3', ['stub plugin0 4000', f'expect mod_x main 3ad6eb8 {half}']) # exlaunch's hook impl saves no NZCV: flags pass from the site to the callback and back (recomp/flags.py) def code(self, main_words, plugin_words=None): """Main's hooked function and the plugin image's words replaced; the plugin hash follows.""" (self.d / 'exefs' / 'main').write_bytes(code_nso(main_words)) img = bytearray((self.d / 'plugin0.img').read_bytes()) for off, w in (plugin_words or {}).items(): struct.pack_into('nzcv = fnz_', on[:call]) # the callback sees the cmp's flags self.assertIn('F.nz = c->nzcv;', on[call:]) # the b.eq reads what the callback left self.assertIn('fc_nz(&F, CC_EQ)', on[call:]) self.assertIn('fc_nz(&F, CC_EQ)', off[:off.index('}', 8)]) # off: the cmp's flags, packed into F.nz self.assertIn('F.nz = fnz_sub64(&F);', c) def test_plugin_return_leaves_its_flags(self): pb = self.bases['plugin0'] # the callback: cmp w1, #5; ret self.code({FN: 0xAA0003F3, FN + 4: 0xAA1303E0, FN + 8: RET_W}, {0x4200: 0x7100143F, 0x4204: RET_W}) t = self.table(f'site mod_x main {FN:x} aa0003f3 @call:plugin0+4000 aa0003f3', ['stub plugin0 4000', 'seed plugin0 4100 4200']) c = self.emit(t, 'plugin0', pb + 0x4200, pb + 0x4208) self.assertIn('c->nzcv = fnz_sub32(&F); return;', c) def test_plugin_call_takes_the_callee_flags(self): pb = self.bases['plugin0'] # bl 0x4200; b.eq +8; ret; ret self.code({FN: 0xAA0003F3, FN + 4: 0xAA1303E0, FN + 8: RET_W}, {0x4100: b(pb + 0x4100, pb + 0x4200, True), 0x4104: 0x54000040, 0x4108: RET_W, 0x410c: RET_W}) t = self.table(f'site mod_x main {FN:x} aa0003f3 @call:plugin0+4000 aa0003f3', ['stub plugin0 4000', 'seed plugin0 4100 4200']) c = self.emit(t, 'plugin0', pb + 0x4100, pb + 0x4110) body = c[c.index(f'void f_{pb + 0x4100:x}(Cpu *c) {{'):] self.assertLess(body.index(f'c->pc = {pb + 0x4200:#x}ull; rt_dispatch(c);'), body.index('F.nz = c->nzcv;')) self.assertIn('fc_nz(&F, CC_EQ)', body) self.assertEqual(body.count('c->nzcv = fnz_nz(&F); return;'), 2) # both returns leave the flags def test_stub_returns_instead_of_branching_to_its_trampoline(self): t = self.table(f'site mod_x main {FN:x} aa0003f3 @call:plugin0+4000 aa0003f3', ['stub plugin0 4000']) stub = self.bases['plugin0'] + 0x4000 c = self.emit(t, 'plugin0', stub, stub + 16) body = c[c.index(f'void f_{stub:x}(Cpu *c) {{'):] self.assertIn('return;', body) self.assertNotIn(f'{self.bases["plugin0"] + 0x2000:#x}', body) # the trampoline is not reached def test_replace_hook_keeps_an_unpatched_copy(self): pb = self.bases['plugin0'] m = self.bases['main'] + FN new = b(m, pb + 0x4200) t = self.table(f'site mod_x main {FN:x} aa0003f3 {new:08x}', [f'orig mod_x plugin0 2000 main {FN:x}', 'seed plugin0 4200']) self.assertEqual(t.origs_for('main', self.bases['main']), {m}) self.assertEqual(t.orig_entries('plugin0', self.bases), {pb + 0x2000: m}) c = self.emit(t, 'main', m, m + 12, origs=[m]) copy = c[c.index(f'void fo_{m:x}(Cpu *c) {{'):] self.assertNotIn('rt_patch_on', copy) self.assertIn('rt_patch_on[0]', c[:c.index(f'void fo_{m:x}')]) tab = gen.table_text('plugin0', [pb + 0x4200, pb + 0x2000], {pb + 0x2000: gen.orig_name(m)}) 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(' 7f1c0000 and written at a start with a grown texture heap as 87a00000 -> 823c0000 site = f'site mod_x main {FN:x} aa0003f3 @call:plugin0+4000 aa0003f3' cases = [(FN, 0xAA0003F3, 0x14000000, 0), (FN, 0xAA0003F3, 0x14000001, -1), (0x3AD6EB8, 0x84800000, 0x7F1C0000, 1), (0x3AD6EB8, 0x87A00000, 0x823C0000, 1), (0x3AD6EBC, 0x87A00000, 0x823C0000, -1)] main = ['#include "patches.h"', '#include "plugin_writes.h"', 'static const PluginWrite tab[] = {RT_PLUGIN_WRITES(PLUGIN_WRITE)};', 'int main(void) {', ' int n = sizeof tab / sizeof *tab, bad = 0;'] for i, (off, old, new, want) in enumerate(cases): main.append(f' bad |= (plugin_write_find(tab, n, 0, "main", {off:#x}, {old:#x}u, {new:#x}u) != {want}) ' f'<< {i};') main += [' return bad;', '}'] (self.d / 'start.c').write_text('\n'.join(main) + '\n') exe = self.d / 'start.exe' for record, failed in (('expect mod_x main 3ad6eb8 84800000 7f1c0000', 1 << 3), ('expect mod_x main 3ad6eb8 * *', 0)): with self.subTest(record=record): (self.d / 'patches.h').write_text(patches.header_text(self.table(site, ['stub plugin0 4000', record]), 'MARK')) subprocess.run([CC, '-std=gnu11', '-Wall', '-Werror', '-I', str(self.d), '-I', str(ROOT / 'runtime'), str(self.d / 'start.c'), '-o', str(exe)], check=True, env=CC_ENV, timeout=60) # the exact record misses only the play-time write self.assertEqual(subprocess.run([str(exe)], env=CC_ENV, timeout=60).returncode, failed) def test_image_must_match_its_hash(self): t = self.table(f'site mod_x main {FN:x} aa0003f3 @call:plugin0+4000 aa0003f3', ['stub plugin0 4000']) t.plugins['plugin0']['sha256'] = '0' * 64 with self.assertRaises(patches.PatchError): gen.open_module('plugin0', self.plugin_file, self.bases['plugin0'], t) def test_chunk_key_takes_the_unpatched_copy(self): # the lift cache (recomp/gen.py chunk_key): a chunk whose function gets an unpatched copy is keyed apart, and a # chunk without one keeps the key it had before plugins fns = [(0x100, 0x10c)] plain = gen.chunk_key('m', 0, fns, {}, [], {}, [], None, None) self.assertEqual(gen.chunk_key('m', 0, fns, {}, [], {}, [], None, None, {0x200}), plain) self.assertNotEqual(gen.chunk_key('m', 0, fns, {}, [], {}, [], None, None, {0x100}), plain) site = {0x100: [(0, [('call', 0x7005204000), 0xAA0003F3])]} self.assertNotEqual(gen.chunk_key('m', 0, fns, site, [0x100], {}, [], None, None), gen.chunk_key('m', 0, fns, {0x100: [(0, [('call', 0x7005204010), 0xAA0003F3])]}, [0x100], {}, [], None, None)) def test_no_plugin_lines_no_plugin_header(self): (self.d / 'q.txt').write_text('set fps60 TOTK_FPS60 0\n') self.assertNotIn('PLUGIN', patches.header_text(patches.load(self.d / 'q.txt', self.mods), 'MARK')) if __name__ == '__main__': unittest.main()