"""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 struct import sys import tempfile import unittest from types import SimpleNamespace 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(' 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('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)', h) self.assertIn('X("plugin0", 0x4100) X("plugin0", 0x4200)', h) # 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_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()