mirror of
https://github.com/valentderah/totk-pc-recomp.git
synced 2026-11-23 05:25:56 +00:00
Merge task/tramp: mod plugins with exlaunch's long trampolines build, and hooked game code reads the flags the plugin's callback left; Challenge Mode starts (#578, #1360)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
7f17cad783
5 files changed
+309
-36
No files matched your search
+50
-8
@@ -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
|
||||
+22
-10
@@ -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)
|
||||
|
||||
+3
-2
@@ -70,8 +70,9 @@ run's record; the design follows #845 by itaskaev2):
|
||||
the original code and not the hook 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 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
|
||||
|
||||
@@ -130,6 +130,11 @@ def b(src, dst, link=False):
|
||||
return (0x94000000 if link else 0x14000000) | ((dst - src) >> 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
|
||||
@@ -272,6 +277,74 @@ class Check(unittest.TestCase):
|
||||
def test_indirect_original(self):
|
||||
self.refused(record(original=0xD65F03C0), 'is a br, blr or ret')
|
||||
|
||||
# exlaunch's long forms (tools/exefs_plugins.py relocation_end, returns_to): the trampoline at plugin0+off
|
||||
def long_form(self, original, off, words):
|
||||
rec = record(original=original)
|
||||
img = bytearray(rec['images']['plugin0'])
|
||||
struct.pack_into('<I', img, STUB_OFF + 12, b(PLUGIN + STUB_OFF + 12, PLUGIN + off))
|
||||
struct.pack_into(f'<{len(words)}I', img, off, *words)
|
||||
rec['images']['plugin0'] = bytes(img)
|
||||
return rec
|
||||
|
||||
def test_trampoline_tbnz_long(self): # Challenge: tbnz w0, #0 out of the plugin's reach
|
||||
site, t = MAIN + SITE_OFF, PLUGIN + TRAMP_OFF
|
||||
words = [0x37000040, 0x14000005, xp.LDR_X17_8, xp.BR_X17, *quad(site + 0x14), b(t + 24, site + 4)]
|
||||
hooks, reasons = xp.check_record(self.long_form(0x370000A0, TRAMP_OFF, words), IMPLS)
|
||||
self.assertEqual(reasons, [])
|
||||
self.assertEqual(hooks[0]['relocated'], '0x37000040 +5 words')
|
||||
|
||||
def test_trampoline_backward_unsigned(self): # Challenge: b.eq back 0x2ec; exlaunch's .quad lacks the sign
|
||||
site, t = MAIN + SITE_OFF, PLUGIN + TRAMP_OFF
|
||||
form = [0x54000040, 0x14000005, xp.LDR_X17_8, xp.BR_X17]
|
||||
for target in (site + 0x1FFD14, site - 0x2EC):
|
||||
words = [*form, *quad(target), b(t + 24, site + 4)]
|
||||
self.assertEqual(self.reasons(self.long_form(0x54FFE8A0, TRAMP_OFF, words)), [], hex(target))
|
||||
self.refused(self.long_form(0x54FFE8A0, TRAMP_OFF, [*form, *quad(site + 0x1FFD18), b(t + 24, site + 4)]),
|
||||
'not the original')
|
||||
|
||||
def test_trampoline_long_nop(self): # the .quad 8-byte aligned by one nop before the form
|
||||
site, t = MAIN + SITE_OFF, PLUGIN + TRAMP_OFF + 4
|
||||
form = [0x37000040, 0x14000005, xp.LDR_X17_8, xp.BR_X17, *quad(site + 0x14)]
|
||||
self.assertEqual(self.reasons(self.long_form(0x370000A0, TRAMP_OFF + 4,
|
||||
[xp.NOP, *form, b(t + 28, site + 4)])), [])
|
||||
self.refused(self.long_form(0x370000A0, TRAMP_OFF + 4, [*form, b(t + 24, site + 4)]), 'not the original')
|
||||
|
||||
def test_trampoline_long_wrong_target(self):
|
||||
site, t = MAIN + SITE_OFF, PLUGIN + TRAMP_OFF
|
||||
words = [0x37000040, 0x14000005, xp.LDR_X17_8, xp.BR_X17, *quad(site + 0x18), b(t + 24, site + 4)]
|
||||
self.refused(self.long_form(0x370000A0, TRAMP_OFF, words), 'not the original')
|
||||
|
||||
def test_trampoline_bl_long(self): # ldr x17, #12; adr x30, #16; br x17; .quad, behind a nop here
|
||||
site, t = MAIN + SITE_OFF, PLUGIN + TRAMP_OFF
|
||||
words = [xp.NOP, xp.LDR_X17_12, xp.ADR_X30_16, xp.BR_X17, *quad(site + 0x40), b(t + 24, site + 4)]
|
||||
self.assertEqual(self.reasons(self.long_form(0x94000010, TRAMP_OFF, words)), [])
|
||||
|
||||
def test_trampoline_adrp_long(self): # adrp x8: ldr x8, #8; b #12; .quad <page>
|
||||
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, <literal>: 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):
|
||||
@@ -603,6 +676,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('<I', img, off, w)
|
||||
(self.d / 'plugin0.img').write_bytes(bytes(img))
|
||||
n = Nso(str(self.plugin_file))
|
||||
self.sha = hashlib.sha256(bytes(img[n.text[0]:n.text[0] + n.text[1]])).hexdigest()
|
||||
|
||||
def test_hook_site_hands_the_flags_to_the_callback_and_back(self):
|
||||
# cmp x0, x1; b.eq +8 (hooked); mov x0, x19; ret
|
||||
self.code({FN: 0xEB01001F, FN + 4: 0x54000040, FN + 8: 0xAA1303E0, FN + 12: RET_W})
|
||||
t = self.table(f'site mod_x main {FN + 4:x} 54000040 @call:plugin0+4000 54000040', ['stub plugin0 4000'])
|
||||
m = self.bases['main'] + FN
|
||||
c = self.emit(t, 'main', m, m + 16)
|
||||
stub = self.bases['plugin0'] + 0x4000
|
||||
on = c[c.index('if (rt_patch_on[0])'):]
|
||||
on, off = on[:on.index('} else {')], on[on.index('} else {'):]
|
||||
call = on.index(f'f_{stub:x}(c);')
|
||||
self.assertIn('c->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
|
||||
|
||||
+112
-16
@@ -39,11 +39,13 @@ The check (check_record) accepts a record only when every rule holds; each broke
|
||||
- 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 exl_inline_hook_impl or the float one; ldur x30, [sp, #-0x10];
|
||||
b <trampoline>; .quad <callback in the plugin's .text>), the trampoline the site's original relocated (the
|
||||
same word, or the same PC-relative target) and `b <site + 4>`;
|
||||
same word, the same PC-relative target, or exlaunch's long form of it, relocation_end) and its jump back to
|
||||
the site + 4 (returns_to);
|
||||
- a call-site rewrite (Quick Weapon Durability): `bl` straight to a function start of the plugin's lift (the
|
||||
record lists them), which the generator can emit as a patch site whose replacement is that branch;
|
||||
- a replace hook (Full Inventory Expansion's Sort Fixer): `b` from a function start of main to a function start of
|
||||
the plugin's lift; the Orig trampoline (the original relocated, b site+4) is listed when the pool holds one.
|
||||
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.
|
||||
@@ -153,6 +155,91 @@ def relocated(orig, site, word, at):
|
||||
return b is not None and a == b
|
||||
|
||||
|
||||
# exlaunch's trampolines: its relocation of a hooked instruction (exlaunch source/lib/hook/nx64/hook_impl.cpp,
|
||||
# __fix_instructions and the __fix_* helpers it calls, after And64InlineHook, MIT). A PC-relative original whose target
|
||||
# the trampoline cannot reach in one word becomes a long form that keeps the target in a .quad; exlaunch puts one nop
|
||||
# before the form when the .quad would not be 8-byte aligned. The generated code never runs a trampoline (an inline
|
||||
# hook's site calls the stub and runs main's own original after it, recomp/patches.py @call; a replace hook's Orig
|
||||
# reaches an unpatched copy of the function, `orig`), so these forms only tell an exlaunch hook from other code.
|
||||
NOP = 0xD503201F
|
||||
LDR_X17_8 = 0x58000051 # ldr x17, #8
|
||||
LDR_X17_12 = 0x58000071 # ldr x17, #12
|
||||
ADR_X30_16 = 0x1000009E # adr x30, #16
|
||||
BR_X17 = 0xD61F0220 # br x17
|
||||
|
||||
|
||||
def quad(word, a):
|
||||
"""The .quad at absolute a of word(a) (the plugin word there, None outside its .text), else None."""
|
||||
lo, hi = word(a), word(a + 4)
|
||||
return None if lo is None or hi is None else lo | hi << 32
|
||||
|
||||
|
||||
def literal_end(word, orig, at):
|
||||
"""End of exlaunch's relocation of the load-literal original at `at` (__fix_loadlit), else None. A prfm is dropped
|
||||
(no words); an ldr or ldrsw becomes the same load from #8 and a b over the literal's bytes, which follow it aligned
|
||||
to their size by leading nops. The bytes are not compared: the record holds no image of main."""
|
||||
simd, opc = orig >> 26 & 1, orig >> 30
|
||||
if not simd and opc == 3:
|
||||
return at
|
||||
size = (4, 8, 16)[opc] if simd else (4, 8, 4)[opc]
|
||||
p = at
|
||||
while word(p) == NOP and p < at + 12:
|
||||
p += 4
|
||||
if (p + 8) % size or word(p + 4 + size) is None:
|
||||
return None
|
||||
if word(p) != (orig & 0xFF00001F) | 2 << 5 or word(p + 4) != 0x14000001 + size // 4:
|
||||
return None
|
||||
return p + 8 + size
|
||||
|
||||
|
||||
def relocation_end(word, orig, site, at):
|
||||
"""End (absolute) of exlaunch's relocation of the original `orig` at `site` when it starts at `at`, else None:
|
||||
the same word or a PC-relative one re-encoded to the same target (one word), or one of the long forms:
|
||||
b.cond / cbz / tbz: <the same with offset 8>; b #20; ldr x17, #8; br x17; .quad <target>
|
||||
b: ldr x17, #8; br x17; .quad <target>
|
||||
bl: ldr x17, #12; adr x30, #16; br x17; .quad <target>
|
||||
adr / adrp: ldr <rd>, #8; b #12; .quad <its value>
|
||||
ldr / ldrsw literal: literal_end
|
||||
word(a) is the plugin word at absolute a, None outside its .text."""
|
||||
w0 = word(at)
|
||||
if w0 is None:
|
||||
return None
|
||||
if relocated(orig, site, w0, at):
|
||||
return at + 4
|
||||
rel = pc_relative(orig, site)
|
||||
if rel is None:
|
||||
return None
|
||||
(kind, _), target = rel
|
||||
if kind == 'ldr':
|
||||
return literal_end(word, orig, at)
|
||||
p = at + 4 if w0 == NOP else at
|
||||
w = [word(p + 4 * i) for i in range(4)]
|
||||
targets = {target}
|
||||
if kind in ('b.cond', 'cbz', 'tbz'):
|
||||
# exlaunch's __fix_cond_comp_test_branch takes the offset field without its sign: a backward target lands
|
||||
# 2^21 (b.cond, cbz) or 2^16 (tbz) bytes too far. Challenge Mode's trampolines hold such .quads; the generated
|
||||
# code runs main's own branch instead, to its real target.
|
||||
targets.add(site + ((orig >> 5 & (0x3FFF if kind == 'tbz' else 0x7FFFF)) << 2))
|
||||
form, data = pc_relative(w[0], p) == (rel[0], p + 8) and w[1:] == [0x14000005, LDR_X17_8, BR_X17], p + 16
|
||||
elif kind == 'b' and orig >> 31:
|
||||
form, data = w[:3] == [LDR_X17_12, ADR_X30_16, BR_X17], p + 12
|
||||
elif kind == 'b':
|
||||
form, data = w[:2] == [LDR_X17_8, BR_X17], p + 8
|
||||
else: # adr, adrp
|
||||
form, data = w[:2] == [0x58000040 | orig & 0x1F, 0x14000003], p + 8
|
||||
return data + 8 if form and data % 8 == 0 and quad(word, data) in targets else None
|
||||
|
||||
|
||||
def returns_to(word, at, back):
|
||||
"""The trampoline jumps back to `back` from `at`: b <back>, or out of its range the nop-aligned
|
||||
ldr x17, #8; br x17; .quad <back> (exlaunch __fix_instructions)."""
|
||||
w = word(at)
|
||||
if w is not None and w >> 26 == 0x05 and branch_target(w, at) == back:
|
||||
return True
|
||||
p = at + 4 if w == NOP else at
|
||||
return p % 8 == 0 and word(p) == LDR_X17_8 and word(p + 4) == BR_X17 and quad(word, p + 8) == back
|
||||
|
||||
|
||||
def inline_stub(img, o, p):
|
||||
"""The words at image offset o of plugin p have exlaunch's inline-hook entry shape: stur x30; bl; ldur x30; b;
|
||||
and the .quad after them lies inside the plugin's .text."""
|
||||
@@ -162,14 +249,19 @@ def inline_stub(img, o, p):
|
||||
return s[0] == STUR_X30 and s[2] == LDUR_X30 and s[1] >> 26 == 0x25 and s[3] >> 26 == 0x05
|
||||
|
||||
|
||||
def text_words(img, p):
|
||||
"""word(a): the word of plugin p's .text image img at absolute a, None outside that .text."""
|
||||
base, end = p['base'], p['text_end']
|
||||
return lambda a: struct.unpack_from('<I', img, a - base)[0] if base <= a <= base + end - 4 else None
|
||||
|
||||
|
||||
def orig_trampoline(img, p, original, site):
|
||||
"""Image offset of a pair in the plugin's .text that runs the site's original instruction relocated, then b site+4
|
||||
(exlaunch's Orig trampoline of a replace hook), else None."""
|
||||
base = p['base']
|
||||
"""Image offset of code in the plugin's .text that runs the site's original instruction relocated, then jumps back
|
||||
to site+4 (exlaunch's Orig trampoline of a replace hook, relocation_end and returns_to), else None."""
|
||||
base, word = p['base'], text_words(img, p)
|
||||
for o in range(0, p['text_end'] - 4, 4):
|
||||
t1 = struct.unpack_from('<I', img, o + 4)[0]
|
||||
if t1 >> 26 == 0x05 and branch_target(t1, base + o + 4) == site + 4 and \
|
||||
relocated(original, site, struct.unpack_from('<I', img, o)[0], base + o):
|
||||
end = relocation_end(word, original, site, base + o)
|
||||
if end is not None and returns_to(word, end, site + 4):
|
||||
return o
|
||||
return None
|
||||
|
||||
@@ -276,17 +368,21 @@ def check_record(rec, impls):
|
||||
reasons.append(f'{where}: the stub calls {impl:#x}, not {" or ".join(HOOK_IMPLS)}')
|
||||
if not p['base'] <= cb < p['base'] + p['text_end']:
|
||||
reasons.append(f'{where}: the stub\'s callback {cb:#x} is outside {p["name"]}\'s .text')
|
||||
tp, t0 = plugin_word(tramp)
|
||||
_, t1 = plugin_word(tramp + 4)
|
||||
if tp is None or t1 is None:
|
||||
tp, t0 = plugin_word(tramp) if tramp is not None else (None, None)
|
||||
if tp is None:
|
||||
reasons.append(f'{where}: the trampoline {tramp:#x} is outside a plugin\'s .text')
|
||||
continue
|
||||
hook['relocated'] = f'{t0:#010x}'
|
||||
if not relocated(w['old'], site, t0, tramp):
|
||||
word = text_words(rec['images'][tp['name']], tp)
|
||||
end = relocation_end(word, w['old'], site, tramp)
|
||||
hook['relocated'] = f'{t0:#010x}' + (f' +{(end - tramp) // 4 - 1} words' if end and end != tramp + 4 else '')
|
||||
if end is None:
|
||||
reasons.append(f'{where}: the trampoline {hook["trampoline"]} starts with {t0:#010x}, not the original '
|
||||
f'{w["old"]:#010x} relocated')
|
||||
if branch_target(t1, tramp + 4) != site + 4 or t1 >> 31:
|
||||
reasons.append(f'{where}: the trampoline\'s second word {t1:#010x} is no b to the site + 4')
|
||||
elif not returns_to(word, end, site + 4):
|
||||
back = word(end)
|
||||
reasons.append(f'{where}: the trampoline\'s word after the relocated original, '
|
||||
f'{back if back is not None else 0:#010x} at {tp["name"]}+{end - tp["base"]:#x}, is no b '
|
||||
f'to the site + 4')
|
||||
return hooks, reasons
|
||||
|
||||
|
||||
@@ -584,7 +680,7 @@ def report(rec, label):
|
||||
for h in hooks:
|
||||
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")}; b site+4)')
|
||||
f'{h["callback"]}, trampoline {h["trampoline"]} ({h.get("relocated")}; back to site+4)')
|
||||
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 ''))
|
||||
|
||||
Reference in new issue
Block a user