diff --git a/recomp/flags.py b/recomp/flags.py index 61188f9d..b3c26c0b 100644 --- a/recomp/flags.py +++ b/recomp/flags.py @@ -15,6 +15,11 @@ definitions then also write it. A read that can see flags a callee left reads the caller's flags from before the call instead. AAPCS64 code never reads a callee's flags, so such a read only sits on a path that does not run: in TotK it follows calls to noreturn functions (asserts) that the compiler placed before another branch's target. Plan.after_call counts them. + +A mod plugin's inline hook breaks that rule. exlaunch's exl_inline_hook_impl saves and restores x0..x29 around the +callback but not NZCV, so the hooked game code goes on with the flags the callback left (Challenge Mode's callbacks end +in a cmp, and the b.eq at their sites follows it). So in a plugin module flags pass through calls and returns (plan's +`through`), and a hook site takes the flags the stub's call left (plan's `hooks`). """ import re @@ -26,7 +31,7 @@ NZ_DEF = 'c->nzcv = ' NZ_USE = '(c->nzcv)' KIND_NAME = {'subs': 'sub', 'adds': 'add', 'logic': 'logic'} -ENTRY, CALL = 'entry', 'call' +ENTRY, CALL, HOOK = 'entry', 'call', 'hook' # HOOK: (HOOK, i), the callback's flags at hook site i class FlagError(Exception): @@ -55,6 +60,8 @@ class Plan: self.reader = [None] * n self.pack = [False] * n self.exit = [None] * n # kind of the flags to publish in c->nzcv at a tail exit, or None + self.pre = [None] * n # kind of the flags to publish before a call whose callee sees them, or None + self.takes = [False] * n # the call leaves its callee's flags (F.nz from c->nzcv after it) self.entry = False # F.nz starts as c->nzcv: flags from the entry reach a read or an exit self.entry_read = False # they reach a read, not only an exit self.after_call = 0 # reads that can see flags a callee left (see the module docstring) @@ -69,6 +76,16 @@ class Plan: k = self.exit[i] return f'c->nzcv = fnz_{k}(&F); ' if k else '' + def give(self, i): + """Statement writing the flags to c->nzcv before instruction i's call, whose callee sees them (plan's through + and hooks; '' when it need not).""" + k = self.pre[i] + return f'c->nzcv = fnz_{k}(&F); ' if k else '' + + def take(self, i): + """Statement taking the flags the callee of instruction i's call left (plan's through and hooks).""" + return ' F.nz = c->nzcv;' if self.used and self.takes[i] else '' + def rewrite(self, i, code): """code of instruction i with its flag reads and writes on F.""" rk = self.reader[i] @@ -91,7 +108,7 @@ class Plan: return code -def plan(effects, succ, calls, exits): +def plan(effects, succ, calls, exits, through=(), hooks=()): """effects[i]: (reads, kind or None); succ[i]: successor indices inside the function; calls: indices of calls, whose callee may leave any flags; exits: indices that can leave for another function other than by a call or a return (a tail branch, falling into the next function, a br through rt_dispatch). @@ -99,25 +116,41 @@ def plan(effects, succ, calls, exits): Discovery can start a function inside another one (a branch target, a materialised address), and the code before it then falls or branches into it with live flags. So a tail exit publishes the flags in c->nzcv, and a function whose reads can see its entry flags starts F.nz from c->nzcv. Calls and returns publish nothing: AAPCS64 - code neither passes flags to a callee nor reads a callee's, so a call's flags count as no definition.""" + code neither passes flags to a callee nor reads a callee's, so a call's flags count as no definition. + + through: calls whose flags pass both ways (a plugin module, see the module docstring; its returns are in exits): + each publishes the flags before the call (Plan.give) and defines F.nz from c->nzcv after it (Plan.take). + hooks: patched sites with a plugin inline hook before the site's own word, when the hook's set is on: the hook + publishes the flags before its call and leaves the callback's after it, which the site's own word reads unless it + writes flags itself. With the set off the flags are the ones before the site, so what follows can see both.""" n = len(effects) p = Plan(n) if not any(r or k for r, k in effects): return p p.used = True + hooks = set(hooks) - set(calls) # a hook before a bl: the bl's callee leaves the flags reach = [set() for _ in range(n)] reach[0].add(ENTRY) work = [0] while work: i = work.pop() - out = {i} if effects[i][1] else ({CALL} if i in calls else reach[i]) + if effects[i][1] or i in through: + out = {i} + elif i in calls: + out = {CALL} + elif i in hooks: + out = reach[i] | {(HOOK, i)} + else: + out = reach[i] for s in succ[i]: if not out <= reach[s]: reach[s] |= out work.append(s) def kind(d): - return 'nz' if d == ENTRY else effects[d][1] + if d == ENTRY or isinstance(d, tuple): + return 'nz' + return effects[d][1] or 'nz' # a through call leaves its callee's flags packed def use(r): """Kind a use of the definitions r reads; several kinds read the packed form, which they then all write.""" @@ -127,18 +160,27 @@ def plan(effects, succ, calls, exits): if len(kinds) == 1: return kinds.pop() for d in r: - if d != ENTRY: + if isinstance(d, int) and effects[d][1]: p.pack[d] = True return 'nz' # several kinds, or none (unreachable) + def seen(i): + """What a read or an exit at instruction i sees: at a hook site also the callback's flags.""" + return reach[i] | {(HOOK, i)} if i in hooks else reach[i] + for i, (reads, _) in enumerate(effects): if reads: p.after_call += CALL in reach[i] - p.reader[i] = use(reach[i] - {CALL}) + p.reader[i] = use(seen(i) - {CALL}) p.entry_read |= ENTRY in reach[i] for i in exits: # Entry flags alone are still in c->nzcv. - r = reach[i] - {CALL} + r = seen(i) - {CALL} if r and r != {ENTRY}: p.exit[i] = use(r) + for i in set(through) | hooks: + p.takes[i] = True + r = reach[i] - {CALL} + if r and r != {ENTRY}: + p.pre[i] = use(r) return p diff --git a/recomp/gen.py b/recomp/gen.py index f41b55e1..8bf0e24b 100644 --- a/recomp/gen.py +++ b/recomp/gen.py @@ -363,7 +363,7 @@ class Emitter: def flag_plan(self, insns, entry, end, tables, succ): """recomp/flags.py plan for the function: each instruction's flag use over the flow succ (flow()).""" n = len(insns) - calls, effects, exits = set(), [], {n} + calls, effects, exits, hooks = set(), [], {n}, set() for i, ins in enumerate(insns): k, a = ins.kind, entry + 4 * i if k in ('bl', 'blr'): @@ -372,6 +372,8 @@ class Emitter: exits.add(i) elif k == 'br': exits.add(i) # through rt_dispatch, also a table's default + elif k == 'ret' and self.mod.plugin: + exits.add(i) # a plugin's caller sees the flags it leaves (recomp/flags.py) if a in self.patched: effects.append(self.patched_effect(ins, a)) for words in self.replacements(a): @@ -380,10 +382,12 @@ class Emitter: calls.add(i) elif r.kind in ('b', 'bcond') and not entry <= r.target < end: exits.add(i) + if any(w.kind == 'hook' for w in words): + hooks.add(i) else: effects.append(flags.effect(ins.cond if k == 'bcond' else ins.code or '')) effects.append((False, None)) - return flags.plan(effects, succ, calls, exits) + return flags.plan(effects, succ, calls, exits, through=calls if self.mod.plugin else (), hooks=hooks) def patched_effect(self, ins, a): """Flag effect of a patched site: every alternative (the original and each replacement) must write the same @@ -450,6 +454,12 @@ class Emitter: def publish(i): return fp.publish(i) if fp and fp.used else '' + def give(i): # flags a plugin's callee or a hook's callback sees (recomp/flags.py plan's through, hooks) + return fp.give(i) if fp and fp.used else '' + + def take(i): # flags that callee or callback left + return fp.take(i) if fp and fp.used else '' + def jump(t, i): if entry <= t < end: return f'goto L_{t:x};' @@ -478,12 +488,12 @@ class Emitter: if fp.used: out.append(' ' + fp.decl()) - def call(t, a): + def call(t, a, i): if t in starts: refs.add(t) - return f'c->x[30] = {hx(a + 4)}; {spill}{fname(t)}(c);{reload_call}' + return f'{give(i)}c->x[30] = {hx(a + 4)}; {spill}{fname(t)}(c);{reload_call}{take(i)}' self.stats['external_calls'] += 1 - return f'c->x[30] = {hx(a + 4)}; {spill}c->pc = {hx(t)}; rt_dispatch(c);{reload_call}' + return f'{give(i)}c->x[30] = {hx(a + 4)}; {spill}c->pc = {hx(t)}; rt_dispatch(c);{reload_call}{take(i)}' def op(i, code): code = fx(i, code) @@ -494,7 +504,7 @@ class Emitter: if r.kind == 'op': return op(i, r.code) if r.kind == 'bl': - return call(r.target, a) + return call(r.target, a, i) if r.kind == 'b': return jump(r.target, i) if r.kind == 'bcond': @@ -504,9 +514,10 @@ class Emitter: 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 + # exlaunch's hook impl saves no NZCV: the callback sees the flags and the site goes on with its own refs.add(r.target) self.stats['plugin_hook_calls'] += 1 - return f'{spill}{fname(r.target)}(c);{reload}' + return f'{give(i)}{spill}{fname(r.target)}(c);{reload}{take(i)}' raise patches.PatchError(f'{a:#x}: patched instruction is a {r.kind}') def patch(i, ins, a): @@ -548,9 +559,10 @@ class Emitter: self.stats['spin_gates'] += 1 emit(i, ' ' + j if k == 'b' else f' if ({fx(i, ins.cond)}) {{ {j} }}') elif k == 'bl': - emit(i, ' ' + call(ins.target, a)) + emit(i, ' ' + call(ins.target, a, i)) elif k == 'blr': - emit(i, f' c->pc = {ins.target}; c->x[30] = {hx(a + 4)}; {spill}rt_dispatch(c);{reload_call}') + emit(i, f' {give(i)}c->pc = {ins.target}; c->x[30] = {hx(a + 4)}; {spill}rt_dispatch(c);{reload_call}' + f'{take(i)}') elif k == 'br': jt = tables.get(a) if jt == 'all': @@ -562,7 +574,7 @@ class Emitter: else: emit(i, f' {publish(i)}{spill}c->pc = {ins.target}; {MUSTTAIL} rt_dispatch(c);') elif k == 'ret': - emit(i, f' {spill}return;') + emit(i, f' {publish(i)}{spill}return;') else: raise ValueError(f'{a:#x}: unknown instruction kind {k!r}') n = len(insns) diff --git a/recomp/patches.py b/recomp/patches.py index a3746ac5..d58353bd 100644 --- a/recomp/patches.py +++ b/recomp/patches.py @@ -69,8 +69,9 @@ run's record; the design follows #845 by itaskaev2): the original code and not the hook again. A replacement word `@call:+` is a call of the function there that writes no x30: every register in the Cpu at the call and all read back after it (the callback may change any of them, as exlaunch's hook context -allows); the flags stay as they were. It may stand before the site's last word, which is then the original -instruction. +allows); the flags are published before it and taken back after it, since exlaunch's hook impl saves no NZCV and the +game code goes on with the flags the callback left (recomp/flags.py plan's hooks). It may stand before the site's last +word, which is then the original instruction. A `hook` line names guest functions (module offsets of function starts; gen.py stops on any other address) whose entry the runtime watches: their lifted C starts with FN_ENTER (runtime/cpu.h), a load of g_fnprof and a predicted diff --git a/tests/exefs_plugins_test.py b/tests/exefs_plugins_test.py index e0a72d51..4de41eff 100644 --- a/tests/exefs_plugins_test.py +++ b/tests/exefs_plugins_test.py @@ -613,6 +613,55 @@ class Generator(unittest.TestCase): 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