mirror of
https://github.com/seedds/nxnative.git
synced 2026-11-23 11:39:42 -10:00
A system register access whose register is x18 goes through the thread slot K18: mrs x18, tpidr_el0 / tpidrro_el0 copies KTLS / KTLR into K18, msr tpidr_el0, x18 copies K18 into KTLS, and the counter gate writes K18 for mrs x18, cntpct_el0. The Hinokami Chronicles 2 no longer reads a stale K18 and faults 2 s in (issue #2123)
- patch_nso.py: site_slot_copy copies one thread slot to another, with the value in x15 and the slot addresses in x16 / x17, all saved in the red zone, so the value never passes through x18, which the Apple kernel may change at any instruction. site_sysreg_read and site_tpidr_write take it for x18; mrs x18, ctr_el0 stores the cache type constant into K18 instead of stopping the rewrite at an assertion. Every other register keeps its block - hle.c: the cntpct / cntvct gate sets K18 with pthread_setspecific for a destination of x18; dm_gate does not restore x18, so regs[18] was dropped - test_x18_sysreg.py: no block names x18; each of the four forms runs on a thread slot area with unicorn (optional). It fails on the old rewriter - docs/reference/rewriter.md: System register accesses through x18; symptom index regenerated The reporter found main+0x23f5ec0 (mrs x18, tpidr_el0) followed by ldr w8,[x18,x0] reading K18 = 0x33200, fault at 0x33220; their own form of the fix ran 19 minutes into a battle. That form carried the value through x18 between its load and store; this one does not. None of 203 unique modules on the drives has one of these instructions: Bastion's main and sdk rewrite byte-identical (only build_src.sha256 differs). The rewriter tests, test_docs and lint pass; the host builds. The game is not here: not run with this commit. No regression run: the new paths run only at x18 system register sites, which no module on hand has. Co-authored-by: pinkyhong <[email protected]>
This commit is contained in:
1 parent
adaff7356b
commit
f3ec8fc81e
5 files changed
+138
-4
No files matched your search
+2
-1
@@ -116,7 +116,8 @@ uint64_t gate_dispatch(uint64_t ret_addr, uint64_t *regs) {
|
||||
case G_CNTPCT: case G_CNTVCT: {
|
||||
guest_clock_read_wait();
|
||||
uint64_t t = guest_ticks(); // the system counter (19.2 / 31.25 MHz); original instruction mrs xN, cntpct_el0, arg = N
|
||||
regs[g->arg] = t;
|
||||
// dm_gate does not restore x18 (the Apple platform register): the guest's x18 is the thread slot K18, which every rewritten x18 site reads
|
||||
if (g->arg == 18) pthread_setspecific(g_key18, (void *)(uintptr_t)t); else regs[g->arg] = t;
|
||||
return t;
|
||||
}
|
||||
case G_OBS: if (g_obs_fn[g->arg & 0xff]) g_obs_fn[g->arg & 0xff](regs, g->arg >> 8); return 0; // dm_gate writes x0–x29 back: the original values, unless the callback changed one (OBS_STDALLOC_INIT)
|
||||
|
||||
+19
-3
@@ -4,6 +4,7 @@
|
||||
# x18 read/write → thread slot K18 (TSD, via tpidrro_el0)
|
||||
# mrs tpidr_el0 → read thread slot KTLS; msr tpidr_el0 → write KTLS
|
||||
# mrs tpidrro_el0 → read thread slot KTLR (Horizon ThreadLocalRegion pointer)
|
||||
# any of these with x18 as its register → a copy between thread slots, K18 among them (site_slot_copy; the host gate writes K18 for mrs x18, cntpct_el0)
|
||||
# svc #n, mrs cntpct_el0 → host gate (gate address taken from thread slot KGATE; once in C, gates.tsv is looked up by return point)
|
||||
# sub sp, sp, xN → xN rounded up to 16 first (Apple's kernel faults on a misaligned sp, Horizon does not; site_sp_align)
|
||||
# ldxr* / ldxp → ldaxr* / ldaxp, stxr* / stxp → stlxr* / stlxp: every exclusive access gets acquire or release ordering (exclusive_order_sites; the games ran on the Switch's Cortex-A57 without it, Apple cores need it)
|
||||
@@ -449,9 +450,23 @@ def site_br_call(ins):
|
||||
emit(MRS_TPIDRRO(16)); emit_slot_addr(16, 17, 'K18'); emit(LDRX(16, 16)); emit(BR(16))
|
||||
return start
|
||||
|
||||
def site_slot_copy(ins, src, dst):
|
||||
"""A system register access whose general-purpose register is x18: the guest's x18 is the thread slot K18, so the access becomes a copy from one thread slot to another
|
||||
(mrs x18, tpidr_el0: KTLS → K18; mrs x18, tpidrro_el0: KTLR → K18; msr tpidr_el0, x18: K18 → KTLS), or src is a word that puts the value in x15 (mrs x18, ctr_el0).
|
||||
The Apple kernel may change x18 at any instruction, so the value never passes through it: x15 carries it, and x16 / x17 form the slot addresses, all three saved in the red zone"""
|
||||
start = here()
|
||||
emit(STP(16, 17, 31, -16)); emit(STUR(15, 31, -24))
|
||||
if isinstance(src, str): emit(MRS_TPIDRRO(16)); emit_slot_addr(16, 17, src); emit(LDRX(15, 16))
|
||||
else: emit(src)
|
||||
emit(MRS_TPIDRRO(16)); emit_slot_addr(16, 17, dst); emit(STRX(15, 16))
|
||||
emit(LDUR(15, 31, -24)); emit(LDP(16, 17, 31, -16))
|
||||
emit(B(here(), ins.address + 4))
|
||||
return start
|
||||
|
||||
def site_sysreg_read(ins, kind):
|
||||
"""mrs xN, tpidr_el0 / tpidrro_el0 → xN = thread slot value."""
|
||||
N = ins.bytes[0] & 31
|
||||
if N == 18: return site_slot_copy(ins, kind, 'K18')
|
||||
tmp = 16 if N != 16 else 17
|
||||
start = here()
|
||||
emit(STUR(tmp, 31, -16)); emit(MRS_TPIDRRO(N)); emit_slot_addr(N, tmp, kind); emit(LDRX(N, N)); emit(LDUR(tmp, 31, -16)) # tmp is saved by borrowing the red zone
|
||||
@@ -460,6 +475,7 @@ def site_sysreg_read(ins, kind):
|
||||
|
||||
def site_tpidr_write(ins):
|
||||
N = struct.unpack('<I', ins.bytes)[0] & 31
|
||||
if N == 18: return site_slot_copy(ins, 'K18', 'KTLS')
|
||||
(T,) = pick({N}, 1)
|
||||
start = here()
|
||||
emit(0xF81F0000 | (31 << 5) | T) # stur xT,[sp,#-16]
|
||||
@@ -1484,9 +1500,9 @@ for a in sorted(kinds):
|
||||
elif k == 'svc': st = site_gate(ins, 'svc', arg); stat(k)
|
||||
elif k in ('cntpct', 'cntvct'): st = site_gate(ins, k, arg); stat(k)
|
||||
elif k == 'sp_align': st = site_sp_align(ins, arg); stat(k)
|
||||
elif k == 'ctr': # replaced in place by a constant: DminLine = 4 (64-byte lines); movz xN, #4, lsl #16
|
||||
assert arg != 18, f'{a:x} mrs x18, ctr_el0'
|
||||
struct.pack_into('<I', IMG, a, 0xD2A00080 | arg); stat(k); continue
|
||||
elif k == 'ctr': # a constant: DminLine = 4 (64-byte lines); movz xN, #4, lsl #16, in place, or into the slot K18 for x18
|
||||
if arg == 18: st = site_slot_copy(ins, 0xD2A00080 | 15, 'K18'); stat(k)
|
||||
else: struct.pack_into('<I', IMG, a, 0xD2A00080 | arg); stat(k); continue
|
||||
put_branch(a, st)
|
||||
|
||||
obs = list(PATCHES['OBS'].get(BUILD_ID, []))
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
"""System register accesses whose register is x18 (issue #2123), without game binaries: the rewritten block copies between thread slots and never names x18.
|
||||
|
||||
Optional dependency: unicorn, which runs the blocks. On macOS its JIT needs execution outside the sandbox."""
|
||||
import ast
|
||||
import importlib
|
||||
from itertools import combinations
|
||||
from pathlib import Path
|
||||
import re
|
||||
import struct
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
from capstone import Cs, CS_ARCH_ARM64, CS_MODE_ARM
|
||||
|
||||
TOOLS = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(TOOLS))
|
||||
import nso_asm
|
||||
|
||||
try:
|
||||
uc, arm = importlib.import_module('unicorn'), importlib.import_module('unicorn.arm64_const')
|
||||
except ImportError:
|
||||
uc = arm = None
|
||||
|
||||
md = Cs(CS_ARCH_ARM64, CS_MODE_ARM)
|
||||
md.detail = True
|
||||
PATCH_BASE, KEY_PAGE, TSD, STACK = 0x10000, 0x20000, 0x30000, 0x40000
|
||||
KEY_INDEX = {k: i for i, k in enumerate(('K18', 'KTLS', 'KTLR', 'KGATE'))}
|
||||
SLOT = {'K18': 0x40, 'KTLS': 0x48, 'KTLR': 0x50, 'KGATE': 0x58} # byte offsets from tpidrro_el0, as the key page holds them
|
||||
scope = dict(vars(nso_asm), re=re, struct=struct, combinations=combinations, md=md,
|
||||
patch=bytearray(), PATCH_BASE=PATCH_BASE, KEY_PAGE_OFF=KEY_PAGE, KEY_INDEX=KEY_INDEX, fix=[])
|
||||
names = {'here', 'emit', 'emit_key_addr', 'emit_slot_addr', 'dis', 'regset', 'num', 'regs_in', 'pick',
|
||||
'site_slot_copy', 'site_sysreg_read', 'site_tpidr_write'}
|
||||
tree = ast.parse((TOOLS / 'patch_nso.py').read_text())
|
||||
exec(compile(ast.Module(body=[n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name in names],
|
||||
type_ignores=[]), str(TOOLS / 'patch_nso.py'), 'exec'), scope)
|
||||
|
||||
SITE = 0x1000 # the original instruction's address; every block ends with b SITE + 4
|
||||
MRS_TPIDR, MRS_TPIDRRO, MSR_TPIDR, MRS_CTR = 0xD53BD040, 0xD53BD060, 0xD51BD040, 0xD53B0020
|
||||
MOVZ_CTR = 0xD2A00080 # movz xN, #4, lsl #16
|
||||
|
||||
|
||||
def block(word):
|
||||
scope['patch'].clear(); scope['fix'].clear()
|
||||
ins = scope['dis'](word, SITE)
|
||||
if word & ~31 == MRS_TPIDR: scope['site_sysreg_read'](ins, 'KTLS')
|
||||
elif word & ~31 == MRS_TPIDRRO: scope['site_sysreg_read'](ins, 'KTLR')
|
||||
elif word & ~31 == MSR_TPIDR: scope['site_tpidr_write'](ins)
|
||||
else: assert word == MRS_CTR | 18; scope['site_slot_copy'](ins, MOVZ_CTR | 15, 'K18') # as the rewriter's ctr case does
|
||||
return bytes(scope['patch'])
|
||||
|
||||
|
||||
class StaticShape(unittest.TestCase):
|
||||
def test_x18_forms_never_name_x18(self):
|
||||
for word in (MRS_TPIDR | 18, MRS_TPIDRRO | 18, MSR_TPIDR | 18, MRS_CTR | 18):
|
||||
with self.subTest(word=word):
|
||||
code = block(word)
|
||||
ins = list(md.disasm(code, PATCH_BASE))
|
||||
self.assertEqual(len(ins) * 4, len(code))
|
||||
self.assertFalse([i for i in ins if re.search(r'\b[xw]18\b', i.op_str)], [f'{i.mnemonic} {i.op_str}' for i in ins])
|
||||
self.assertEqual((ins[-1].mnemonic, ins[-1].operands[0].imm), ('b', SITE + 4))
|
||||
|
||||
def test_other_registers_unchanged(self):
|
||||
# The register forms other than x18 keep their blocks: x16 borrowed in the red zone, the value in xN
|
||||
ins = list(md.disasm(block(MRS_TPIDR | 0), PATCH_BASE))
|
||||
self.assertEqual([f'{i.mnemonic} {i.op_str}' for i in ins][:2], ['stur x16, [sp, #-0x10]', 'mrs x0, tpidrro_el0'])
|
||||
|
||||
|
||||
@unittest.skipIf(uc is None, 'optional ARM64 execution dependency: unicorn')
|
||||
class Run(unittest.TestCase):
|
||||
def run_block(self, word, slots, regs=None):
|
||||
assert uc is not None and arm is not None
|
||||
code = block(word)
|
||||
mu = uc.Uc(uc.UC_ARCH_ARM64, uc.UC_MODE_ARM)
|
||||
for base in (0, PATCH_BASE, KEY_PAGE, TSD, STACK): mu.mem_map(base, 0x10000)
|
||||
mu.mem_write(PATCH_BASE, code)
|
||||
for k, i in KEY_INDEX.items(): mu.mem_write(KEY_PAGE + 8 * i, struct.pack('<Q', SLOT[k]))
|
||||
for k, v in slots.items(): mu.mem_write(TSD + SLOT[k], struct.pack('<Q', v))
|
||||
mu.reg_write(arm.UC_ARM64_REG_TPIDRRO_EL0, TSD)
|
||||
mu.reg_write(arm.UC_ARM64_REG_SP, STACK + 0x8000)
|
||||
regs = regs or {r: 0x1000 + r for r in range(31) if r != 18}
|
||||
for r, v in regs.items(): mu.reg_write(arm.UC_ARM64_REG_X0 + r, v)
|
||||
mu.reg_write(arm.UC_ARM64_REG_X18, 0xdead) # what the Apple platform register happens to hold: never read
|
||||
mu.emu_start(PATCH_BASE, SITE + 4)
|
||||
out = {k: struct.unpack('<Q', bytes(mu.mem_read(TSD + SLOT[k], 8)))[0] for k in SLOT}
|
||||
for r, v in regs.items(): self.assertEqual(mu.reg_read(arm.UC_ARM64_REG_X0 + r), v, f'x{r}')
|
||||
return out
|
||||
|
||||
def test_mrs_x18_tpidr_el0_writes_k18(self):
|
||||
out = self.run_block(MRS_TPIDR | 18, {'K18': 0x33200, 'KTLS': 0x7bdf11c420})
|
||||
self.assertEqual(out['K18'], 0x7bdf11c420)
|
||||
|
||||
def test_mrs_x18_tpidrro_el0_writes_k18(self):
|
||||
out = self.run_block(MRS_TPIDRRO | 18, {'K18': 0x33200, 'KTLR': 0x7be3b6c000})
|
||||
self.assertEqual(out['K18'], 0x7be3b6c000)
|
||||
|
||||
def test_msr_tpidr_el0_x18_reads_k18(self):
|
||||
out = self.run_block(MSR_TPIDR | 18, {'K18': 0x1234500, 'KTLS': 0})
|
||||
self.assertEqual((out['KTLS'], out['K18']), (0x1234500, 0x1234500))
|
||||
|
||||
def test_mrs_x18_ctr_el0_writes_k18(self):
|
||||
out = self.run_block(MRS_CTR | 18, {'K18': 0x33200})
|
||||
self.assertEqual(out['K18'], 4 << 16)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -72,6 +72,7 @@ One line per symptom in the [subsystem references](../reference/): what you see
|
||||
- a game that steps its time by a fixed amount per frame needs the host's frame step (the frame step), but its stubs could only be keyed by the main's build ID: every update needed a new port, and the binding page listed each such patch as `build` bound, blocked for want of a function-matched form. → [Frame-step stubs placed by their function](../reference/rewriter.md#frame-step-stubs-placed-by-their-function)
|
||||
- the rewrite of a main that gets frame step stubs (`FRAME_STEP` or a `MATCH_FRAME_STEP` match) stops with `AssertionError: frame step state page`; the same main rewrites without the stubs. → [A frame step state page where the patch area starts](../reference/rewriter.md#a-frame-step-state-page-where-the-patch-area-starts)
|
||||
- after a game update, the Cheats menu lists only `Cheats for build … (another version of the game)`, and nothing runs. Or a cheat file converted to the new build by hand writes into the wrong place: a table instead of a variable, or code that moved. → [Cheats carried across game updates](../reference/rewriter.md#cheats-carried-across-game-updates)
|
||||
- a crash (`sig=11`) in the patch area a few seconds into a run, at an `x18` site's load, with an address a little above a small stale value (`addr=0x33220`, the thread's `K18` slot at `0x33200`), shortly after the game read `tpidr_el0` into `x18`. → [System register accesses through x18](../reference/rewriter.md#system-register-accesses-through-x18)
|
||||
- `jump table <addr>` assertion in `patch_nso.py`, in a Unity / IL2CPP `main`. → [Offset jump tables through x18 read at rewrite time](../reference/rewriter.md#offset-jump-tables-through-x18-read-at-rewrite-time)
|
||||
- `jump table <addr>` assertion in `patch_nso.py`, in a `subsdk`. → [Offset jump tables with the bounds check on another register](../reference/rewriter.md#offset-jump-tables-with-the-bounds-check-on-another-register)
|
||||
- `jump table <addr>` assertion where the index is a copy made before the check (`mov w0,w18`, then 41 instructions holding two other jump tables on `x0`, then `cmp w18,#4; b.hi; ldrsw x18,[x11,x0,lsl #2]; add x18,x18,x11; br x18`). → [Index copied before the bounds check](../reference/rewriter.md#index-copied-before-the-bounds-check)
|
||||
|
||||
@@ -76,6 +76,16 @@ To enroll a cut for any game's own module:
|
||||
- FINAL FANTASY CRYSTAL CHRONICLES Remastered Edition: the 1.0.1 cheatslips file, anchored on the cartridge's `main`, compiles to exactly the hand-verified +0x43680 on 1.0.3 (12 of 12 cheats, 4 of 4 references each). The 1.0.3 file (5 ASM cheats with a code cave, 7 stat cheats, Mog's fatigue) compiles back to identical writes on 1.0.3 and to all 18 entries on the cartridge's build (code sites: 4 exact, 3 by body digest, 2 by window).
|
||||
- [13 Sentinels: Aegis Rim](../../dm/games/01003FC01670C000/README.md#cheats): a 1.10 Ryujinx list compiles back to identical writes and to 1.00, where every site lies 0x330 lower and the hook site was found by its body digest.
|
||||
|
||||
## Thread registers
|
||||
|
||||
### System register accesses through x18
|
||||
|
||||
- **Symptom:** a crash (`sig=11`) in the patch area a few seconds into a run, at an `x18` site's load, with an address a little above a small stale value (`addr=0x33220`, the thread's `K18` slot at `0x33200`), shortly after the game read `tpidr_el0` into `x18`.
|
||||
- **Cause:** the guest's `x18` lives in the thread slot `K18`, since the Apple kernel may change the register at any instruction, and every `x18` site loads and stores the slot. The system register sites did not: `mrs x18, tpidr_el0` / `tpidrro_el0` put the value in the register only, `msr tpidr_el0, x18` stored the register into `KTLS`, and the gate for `mrs x18, cntpct_el0` / `cntvct_el0` wrote the saved `x18`, which `dm_gate` does not restore. The next `x18` site read whatever `K18` held before. `mrs x18, ctr_el0` stopped the rewrite with an assertion.
|
||||
- **Fix:** with `x18` as the register, the rewriter copies between thread slots (`site_slot_copy`: `KTLS` or `KTLR` into `K18`, `K18` into `KTLS`, the cache type constant into `K18`), carrying the value in `x15` with `x16` / `x17` for the slot addresses, all saved in the red zone; the value never passes through `x18`. The host's counter gate writes `K18` for a destination of `x18`. The other registers keep their blocks, so every other rewrite is byte-identical: none of 203 modules on hand has one of these instructions.
|
||||
- **Check:** `test_x18_sysreg.py` checks that no block names `x18`, and runs each block on a thread slot area with unicorn (optional); it fails without the fix.
|
||||
- **Found on:** The Hinokami Chronicles 2 (`0100AD80208A8000`, 1.70, SDK 22.0.0; not in the [games table](../../dm/games/README.md#games); [issue #2123](https://github.com/seedds/nxnative/issues/2123)): one `mrs x18, tpidr_el0` in `main`, at `+0x23f5ec0`. Its reporter's version of the fix ran 19 minutes into a battle; this one awaits their run.
|
||||
|
||||
## Jump tables
|
||||
|
||||
### Offset jump tables through x18 read at rewrite time
|
||||
|
||||
Reference in new issue
Block a user