Bare lock acquires without a barrier made ldaxr by the rewriter: BotW 1.6.0 ran a job twice (issue #251, PR #562)

Breath of the Wild 1.6.0 crashed on the Mac 10 to 60 s into its first scene
(10 of 10 runs, in h_nvnBufferGetAddress and elsewhere). Its job queue takes
its lock with ldxr; cbnz; stxr; cbnz and no barrier after the loop: an
exclusive load without acquire ordering. Armv8 lets the queue reads after it
be satisfied before the lock is held; Apple cores do it, so two workers
popped the same job and built their draw lists into one arena.

patch_nso.py (acquire_lock_sites) turns every such acquire into ldaxr, found
by its instruction shape in every module, with no address list and no build
gate; a loop followed by dmb ish or dmb ishld is already ordered and left
alone (Tears of the Kingdom's 32 and Super Mario Bros. Wonder's 33 loops of
this shape all are). The statistics line counts the rewritten ones as
acquire_lock. docs/reference/threads.md has the entry, the BotW note the
finding; test_acquire_lock.py checks the shape on hand-assembled words.

Reach over the local games: only Super Mario 3D All-Stars' main (7 sites,
no repository profile) rewrites differently: 14 bytes, the 7 sites and their
7 spin-wait copies. Every other local game, BotW 1.9.0 included (no loop of
this shape), rewrites byte-identically. 1.6.0 is not on this Mac; the
contributor's runs: 10 of 10 crashed before, 0 of 7 after (up to 900 s).

Regression (1 game, narrow reach): BotW 1.9.0 full check against e513bfeb: PASS (19592/19592 shaders, 0 changed; 110 s route, fps 59.1 → 58.5, no new RED).

Co-authored-by: Suraj Mandal <[email protected]>
This commit is contained in:
seeddsandSuraj Mandal committed 2026-10-30 22:07:40 +08:00
1 parent 8bfc3a60c1
commit fe6d3dfadb
5 files changed
+80

No files matched your search

+3
View File
@@ -191,6 +191,7 @@ Before publishing, the fixes were integrated with main's pipeline archive and GP
## Found on this game
- **Resolved, two stale chain folders held 4.4 GB:** [Old shader library folders grew a game's build folder with each chain change](../../../docs/reference/shaders.md#old-shader-library-folders-grew-a-games-build-folder-with-each-chain-change).
- **Resolved: 1.6.0 (v786432) crashed 10-60 s into the first scene (issue #251)** in `h_nvnBufferGetAddress` (`main+0x14ef6e0`, reader `main+0x14ef440`) and in other places (`main+0x12970dc`, `+0x13615f4`, `+0x1445d48`, `+0x1db5cb8`, `+0x1472470`): the game's job queue (`main+0x13a0730`) takes its lock with a bare `ldxr` (no acquire), so on Apple cores two workers popped the same job, and two threads built draw lists into one view and arena (`main+0x14e8884` begin, commit `main+0x14ee3c0`). [Lock acquire without acquire ordering runs a queue item twice](../../../docs/reference/threads.md#lock-acquire-without-acquire-ordering-runs-a-queue-item-twice).
- **Resolved build guard and cache isolation; rendering cause open:** [Tested tools and compiler-specific shader caches](../../../docs/reference/shaders.md#tested-tools-and-compiler-specific-shader-caches).
General host changes first needed here; each applies to every game:
@@ -232,6 +233,8 @@ General host changes first needed here; each applies to every game:
## Open
- **1.6.0 (v786432): the corrupted picture of [issue #251](https://github.com/seedds/nxnative/issues/251) has another cause (current, open):** the 1.9.0 shader map lacks 178 keys that the 1.6.0 shaders use. Not retested after the crash fix.
- The shipped pipeline archive without the device's own earlier prebuild files (the test iPhone's `pso_archive/` still held them, [Pipelines on a cold start](#pipelines-on-a-cold-start)): the footprint against the app's memory limit and the frame times after it.
- Frame capture and replay ([development.md](../../../docs/development.md#frame-capture-and-replay), GitHub issue #402): a fresh replay does not always give the same digest, with or without segmented submission (open). Outdoors route, frame 4000, `DM_NVN_CUT=0` (2026-10-28, M4 Pro): the live digest in most fresh replays, another in 2 to 7 of 24, among about eight others. The replay has one segment then (nothing is committed before the frame's end), the per-draw pass dumps (state, vertex-stage uniform content, vertex streams) of a matching and a differing replay are identical, every texture the frame has by then is identical at every level after the G-buffer pass (pass 32), and so are that pass's depth and its colour targets 0 and 5; only colour targets 1 and 3 differ (the normal and material outputs of fragment shader `8d56b5cee7c434f6`), and each other digest follows from them. Dropping some of the pass's draws (a probe not kept) narrowed it to 2 pixels where draw 520 of the frame and a later draw both write, the later one usually winning; with depth compare `ALWAYS` for that shader it still varies. Ruled out, each by 16 to 30 fresh replays that still varied: pipelines through the `MTLDevice` (`DM_PSO_MTL4=0`), no prewarm, archive or prediction, the uniform copy worker (`DM_NVN_UB_COPY_THREAD=0`; its shadows also equal synchronous copies), a barrier between every operation of the copy encoder, waiting for every upload batch, a fill pattern in new arena blocks; Metal's API validation reports no error, and shader validation only the [non-resident views](../../../docs/reference/rendering.md#compatible-views-made-from-the-texture-under-a-view) (fixed; not the cause). The earlier reading of Zora's Domain, frame 3000 (one segment boundary between passes 38 and 39 changes the digest, `DM_NVN_CUT=0` always matches), fits this variation too. A second capture of the outdoors route (frame 4000, then frame 5000, same Mac and day) shows the same: with the default segmented submission every fresh replay differs from the live frame, in 97 to 124 pixels (two recurring sets, at most 46 of 255), and with `DM_NVN_CUT=0` between one and five in eight do, in 3 to 124 pixels (also with the `tex_fit` fix); the first difference is again in pass 32, four edge pixels one draw writes (vertex shader `d9670d25c6290936`, fragment `a331f28b1ddbc517`). Ending pass 32 after every draw, or every 100 draws, makes the frame repeat 16 times in 16; every 500 draws, or one break anywhere, does not. What varies is the outcome of depth-equal tests (2026-10-29, frame 5000, `DM_NVN_CUT=0`): pass 32 has draws with depth test `EQUAL` and no depth write (1208–1217 and 1394–1429 in frame 4000), and drawing every such draw with less-or-equal instead (a probe, not kept) makes 16 fresh replays of 16 give one digest, where the unchanged build gave the live one in 11 and another in 5. Nothing the GPU writes in the frame is read by pass 32 (`--writes`, with each writer and reader placed by draw), so its vertex and uniform inputs are the captured bytes in every replay; the depth an `EQUAL` draw compares against, or its own, is then not bit-reproducible from run to run inside a long pass on this GPU. Two more probes (10 fresh replays each): with the `EQUAL` draws' fragment output replaced by their fragment depth's bits in colour target 0 (and their test set to `ALWAYS`), those bits are identical in every replay wherever no later draw covers them; and pass 32's depth buffer at the end of the frame is identical in every replay, also in the two whose pass 32 differs (in 22 and 4 pixels, colour targets 1 and 3 only). The `EQUAL` draws use no depth bias or clamp (46 of 46 in frame 4000). So both operands of the test, as far as they can be read, are the same in every replay while its result is not: the depth the test reads at that moment, inside one long pass, is the remaining suspect, on the GPU's side (partial renders of a long pass are one candidate, not shown). A third replay of the ten differs only after pass 32, so a second varying spot exists later in the frame. Also ruled out there: the regions' addresses (mapped at fixed addresses), the order of separate commits (each waiting on a queue event for the one before), residency (`DM_RES_CHECK=1`) and the vertex / fragment interface. A cause on the GPU side in long passes is likely, not shown; a GPU capture of a matching and a differing replay is the next step. `nvn_replay --max-pixels` judges a change within this noise. A second replay in one process (`--warm`) also differs. Pool blocks after the frame match the live run except counter reports and the blocks the CPU writes during the frame. The variation is this game's, not the replay layer's in general: a frame of Super Mario Bros. Wonder's opening course (59 passes, 436 draws, segmented submission on) gives the live digest in 8 fresh replays of 8 (2026-10-29, M4 Pro). Fixed on the way: block-compressed textures (a 32x32 BC4) and transient render targets rLine truncated
+21
View File
@@ -6,6 +6,7 @@
# mrs tpidrro_el0 → read thread slot KTLR (Horizon ThreadLocalRegion pointer)
# 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 rt,[rn]; cbnz rt,<it>; stxr ws,rk,[rn]; cbnz ws,<it> with no dmb after it (a test-and-set lock acquire with no acquire ordering) → ldaxr (acquire_lock_sites; the games ran on the Switch's Cortex-A57 without the ordering, Apple cores need it)
# spin wait loops → a copy whose back-edges pass a spin gate (the host yields there; a busy poll costs nothing on the Switch, see "Spin waits")
# Registered cuts (CUTS of the patch files, restricted by NSO build ID, see "Registered patches"): before rewriting, the original bytes are asserted one by one and any mismatch aborts; results are listed in <name>.cuts.tsv
# Function-matched cuts (MATCH_CUTS of the selected game's patches.py): unknown builds only, unique complete-function and direct-callee fingerprints, then original-byte assertions
@@ -526,6 +527,26 @@ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import nso_code
DATA_BLOCKS = nso_code.data_blocks(IMG, TEXT_END, md)
CODE_RANGES = list(zip([0] + [e for _, e in DATA_BLOCKS], [s for s, _ in DATA_BLOCKS] + [TEXT_END]))
def acquire_lock_sites(img, ranges):
"""Offsets of exclusive test-and-set lock acquires without acquire ordering: ldxr rt,[rn]; cbnz rt,<the ldxr>; stxr ws,rk,[rn]; cbnz ws,<the ldxr> (w or x, rk not zero), not followed by
dmb ish / dmb ishld (Tears of the Kingdom's and Super Mario Bros. Wonder's locks of this shape all are, which orders them already). Armv8 lets the loads after such a lock be satisfied
before it is held; the games ran on the Switch's Cortex-A57 without that showing, Apple cores do it, so two threads take the same queue item (Breath of the Wild 1.6.0 main: 412 of this shape counted without the barrier check,
the job queue pop at main+0x13a0784 ran one job on two threads, see docs/reference/threads.md). Nintendo's own SDK locks use ldaxr"""
out = []
for s, e in ranges:
for o in range(s, e - 12, 4):
w = struct.unpack_from('<I', img, o)[0]
if w & 0xBFFFFC00 != 0x885F7C00: continue
c1, st, c2 = struct.unpack_from('<III', img, o + 4)
rt, rn, rs, rk = w & 31, w >> 5 & 31, st >> 16 & 31, st & 31
cbnz = lambda x, r, back: x & 0x7F00001F == 0x35000000 | r and x >> 5 & 0x7FFFF == 0x80000 - back # cbnz r, <the ldxr>: back words
fenced = o + 20 <= e and struct.unpack_from('<I', img, o + 16)[0] in (0xD5033BBF, 0xD50339BF) # dmb ish, dmb ishld right after the loop
if cbnz(c1, rt, 1) and cbnz(c2, rs, 3) and st & 0xBFE0FC00 == 0x88007C00 and st >> 5 & 31 == rn and rk != 31 and rs not in (rn, rk) and not fenced:
out.append(o)
return out
for o in acquire_lock_sites(IMG, CODE_RANGES):
struct.pack_into('<I', IMG, o, struct.unpack_from('<I', IMG, o)[0] | 0x8000) # ldxr → ldaxr
stat('acquire_lock')
md_lite = Cs(CS_ARCH_ARM64, CS_MODE_ARM) # no details: the x18 scan reads only the operand text
R18 = re.compile(r'\b[xw]18\b')
def x18_words(lo, hi):
+47
View File
@@ -0,0 +1,47 @@
"""patch_nso.py's search for test-and-set lock acquires without acquire ordering (acquire_lock_sites), on hand-assembled words, without game files."""
import ast
from pathlib import Path
import struct
from typing import Any
import unittest
tree = ast.parse((Path(__file__).resolve().parents[1] / 'patch_nso.py').read_text()) # the program loads and rewrites an image: compile only the search
ns: dict[str, Any] = {'struct': struct}
exec(compile(ast.Module([n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name == 'acquire_lock_sites'], []), 'patch_nso.py', 'exec'), ns)
find = ns['acquire_lock_sites']
def cbnz(rt, back, x=0): return 0x35000000 | x << 31 | (0x80000 - back) << 5 | rt
def ldxr(rt, rn, x=0): return 0x885F7C00 | x << 30 | rn << 5 | rt
def stxr(rs, rk, rn, x=0): return 0x88007C00 | x << 30 | rs << 16 | rn << 5 | rk
def img(*w): return b''.join(struct.pack('<I', x) for x in w)
class AcquireLock(unittest.TestCase):
def test_w_and_x_forms_found(self): # BotW main+0x13a0784: ldxr w9,[x23]; cbnz w9; stxr w9,w8,[x23]; cbnz w9
pad = img(0xD503201F)
for x in (0, 1):
code = pad + img(ldxr(9, 23, x), cbnz(9, 1, x), stxr(9, 8, 23, x), cbnz(9, 3, x)) + pad
self.assertEqual(find(code, [(0, len(code))]), [4])
def test_not_a_plain_acquire(self):
pad = img(0xD503201F)
for name, w in (('release store', (ldxr(9, 23), cbnz(9, 1), stxr(9, 31, 23), cbnz(9, 3))), # stxr wzr: an unlock
('already ldaxr', (ldxr(9, 23) | 0x8000, cbnz(9, 1), stxr(9, 8, 23), cbnz(9, 3))),
('other base', (ldxr(9, 23), cbnz(9, 1), stxr(9, 8, 22), cbnz(9, 3))),
('retry elsewhere', (ldxr(9, 23), cbnz(9, 1), stxr(9, 8, 23), cbnz(9, 4))),
('stlxr', (ldxr(9, 23), cbnz(9, 1), stxr(9, 8, 23) | 0x8000, cbnz(9, 3)))):
code = pad + img(*w) + pad
self.assertEqual(find(code, [(0, len(code))]), [], name)
def test_fenced_lock_left_alone(self): # Tears of the Kingdom, Super Mario Bros. Wonder: the same loop, then dmb ish (or dmb ishld): already ordered
for dmb in (0xD5033BBF, 0xD50339BF):
code = img(ldxr(9, 23), cbnz(9, 1), stxr(9, 8, 23), cbnz(9, 3), dmb)
self.assertEqual(find(code, [(0, len(code))]), [])
def test_range_is_respected(self):
code = img(ldxr(9, 23), cbnz(9, 1), stxr(9, 8, 23), cbnz(9, 3), 0xD503201F)
self.assertEqual(find(code, [(0, 12)]), [])
self.assertEqual(find(code, [(0, 16)]), [0])
if __name__ == '__main__':
unittest.main()
+1
View File
@@ -119,6 +119,7 @@ One line per symptom in the [subsystem references](../reference/): what you see
- none seen; found while investigating Fire Emblem Engage's demo crash, which it did not change (that was the address-space shortage, Size-aligned regions exhaust the alias address space). → [`SignalToAddress` type 2 with count ≤ 0](../reference/threads.md#signaltoaddress-type-2-with-count--0)
- a 64-bit wait could return at once or block when it should not (not met in a game). → [`WaitForAddress` type 3: 64-bit wait if equal](../reference/threads.md#waitforaddress-type-3-64-bit-wait-if-equal)
- boot stops before or soon after the first frame with the CPU at 0% and every guest thread waiting on a condition variable: the main thread in `nn::os::AcquireSemaphore` after posting a command to `UnityGfxDeviceWorker`, the worker in `AcquireSemaphore` too, one condition wait after it (`wait #` one higher); 3 of 5 Mac runs, at random points. → [Unity's stream buffer handshake loses a wake-up on Apple cores](../reference/threads.md#unitys-stream-buffer-handshake-loses-a-wake-up-on-apple-cores)
- a game that runs on the Switch crashes on the Mac 10 to 60 s into a scene, at a different place each run, with garbage in a list the game just built (Breath of the Wild 1.6.0: `h_nvnBufferGetAddress` called with a row's metadata word as the buffer pointer, `main+0x14ef6e0`; also faults in `main+0x12970dc`, `+0x13615f4`, `+0x1445d48`, `+0x1472470`). A trace of the draw-list builders shows two threads inside the same view at once, running the same job descriptor. → [Lock acquire without acquire ordering runs a queue item twice](../reference/threads.md#lock-acquire-without-acquire-ordering-runs-a-queue-item-twice)
- a PhysX worker crashes in a task's `removeReference` with a null task manager, right as the game switches to 30 fps (`pc=main+0x10ccf28`, `lr=main+0x13c236c`); on the iPhone and in 2 of 5 Mac runs, in every Mac run with 12 busy loops loading the CPU. → [Late PhysX task destructor after the unlock](../reference/threads.md#late-physx-task-destructor-after-the-unlock)
- `game called nn::diag abort: Result 0, call site sdk+0x153c34` during `main`'s static initialisers, `bt: sdk+0x153c34 sdk+0x137eb4 sdk+0x13dc50 sdk+0x13fa90 sdk+0xa4d64 main+0x134 run_module_inits+0xa8 guest_main+0x15c main+0xfc start+0x1a20`, and no game code on the stack at all. → [The thread ID at ThreadLocalRegion+0x110 (SDK 22)](../reference/threads.md#the-thread-id-at-threadlocalregion0x110-sdk-22)
- a 30 Hz game thread runs at 27 Hz, and whatever it paces comes out slow (cutscenes at 36 ms per frame instead of 33.3; gameplay was fine at 60). → [Timer slack in guest sleeps (`sleep_precise`)](../reference/threads.md#timer-slack-in-guest-sleeps-sleep_precise)
+8
View File
@@ -125,6 +125,14 @@ Guest threads, their synchronization and how the host schedules them. Each entry
- **Found on:** [FINAL FANTASY CRYSTAL CHRONICLES Remastered Edition](../../dm/games/0100CE4010AAC000/README.md) 1.0.0 and 1.0.3 (Unity 2018.4.2f1, SDK 8.2.1; its `patches.py`: 1.0.0 `main+0x1e425b0` and the stream functions after it, the same sites +0x25380 in 1.0.3).
- **Check:** another Unity title that stops this way: look for `stlr` followed by a plain `ldr` of the other word in its `ThreadedStreamBuffer` (the functions around the `AcquireSemaphore` the worker waits in).
### Lock acquire without acquire ordering runs a queue item twice
- **Symptom:** a game that runs on the Switch crashes on the Mac 10 to 60 s into a scene, at a different place each run, with garbage in a list the game just built (Breath of the Wild 1.6.0: `h_nvnBufferGetAddress` called with a row's metadata word as the buffer pointer, `main+0x14ef6e0`; also faults in `main+0x12970dc`, `+0x13615f4`, `+0x1445d48`, `+0x1472470`). A trace of the draw-list builders shows two threads inside the same view at once, running the same job descriptor.
- **Cause:** the game's own spin lock takes the lock with `ldxr w9,[x23]; cbnz w9,<ldxr>; stxr w9,w8,[x23]; cbnz w9,<ldxr>`: an exclusive load with no acquire ordering, and no barrier after the loop. The architecture lets the loads that follow (the queue's count, head and ring) be satisfied before the lock is held; the game ran on the Switch's Cortex-A57 without that showing (why is not known), Apple cores do it, so two workers read the same head, both pop it and both run the job. The unlock is ordered (`dmb ish` before the store), and Nintendo's SDK locks use `ldaxr`. The same loop followed by `dmb ish` is ordered and harmless: Tears of the Kingdom's main has 32 such, Super Mario Bros. Wonder's 33, all fenced. In Breath of the Wild 1.6.0 the job queue pop (`main+0x13a0784`) and submit (`main+0x13a0068`) have the bare form, 412 loops of this shape in the module (counted without the barrier check; 1.9.0 has none of either form); Super Mario 3D All-Stars' main has 7.
- **Fix:** `patch_nso.py` makes every such acquire an `ldaxr` (`acquire_lock_sites`), in every module of every game, found by the instruction shape (an exclusive load, a `cbnz` back to it, a store-exclusive of a non-zero value to the same address, a `cbnz` back to the load), unless a `dmb ish` or `dmb ishld` follows the loop. No address list. `dm/tools/tests/test_acquire_lock.py` checks the shape on hand-assembled words.
- **Found on:** [The Legend of Zelda: Breath of the Wild](../../dm/games/01007EF00011E000/README.md) 1.6.0 ([issue #251](https://github.com/seedds/nxnative/issues/251)): the same job descriptor ran on two threads 8 us apart.
- **Check:** another game that fails like this: trace which job a worker takes (a branch slot at the job entry, a lock-free per-thread ring); the same descriptor on two threads at once is this bug. Count the unfenced bare `ldxr` acquires (`acquire_lock` in the rewriter's statistics line).
### Late PhysX task destructor after the unlock
- **Symptom:** a PhysX worker crashes in a task's `removeReference` with a null task manager, right as the game switches to 30 fps (`pc=main+0x10ccf28`, `lr=main+0x13c236c`); on the iPhone and in 2 of 5 Mac runs, in every Mac run with 12 busy loops loading the CPU.