Rewriter (dm/tools/patch_nso.py): - Check DATA_BLOCKS and spin_quick(T, hi) at the start of spin_region before calling spin_lock(T), guard spin_lock(a) on its first instruction's mnemonic before decoding lookahead words, and clear spin_dec in spin_region's finally block after every head. - Bounds spin_dec to <= ~135 entries per head instead of growing with text size per worker (which passed 24 GB on EA SPORTS FC 27 1.8e's 185 MB main; full 1.8d main rewrite now peaks at 2.20 GiB RSS), while cutting spin-search decodes by 39% and time by 30% with byte-identical output. - Add synthetic unit tests in test_spin_waits.py and drop the two fixed pyright reportOptionalSubscript entries from lint_python_baseline.tsv. Host (dm/host/hle_fpslock.c): - Extend fb_find() to read GameRenderSettings.Enable from Frostbite reflection and locate the unique fmov vD.2d, #30.0 / adrp+ldr / stur qD, [xR, #8] regulator store (failing closed with [RED] on ambiguity), verified on EA SPORTS FC 27 v0 (0xd9f4e18), 1.8d.310c (0xda20e38), and 1.8e.50bc disassembly (0xda5d0f8). - Remove the build-gated FC 27 row from k_locks[] and its HOST_BINDING entry in docs_patches.py, add dynamic and negative cases in t_fpslock.c, and update docs and generated indexes (including the 1.8e.50bc iPhone 17 Pro and Mac 5K notes). Co-authored-by: Vertu User <[email protected]>
108 KiB
Rewriter
The NSO rewriter (dm/tools/patch_nso.py) and its per-build tables (dm/tools/sdk_patches.py, a profile's patches.py). Each entry: symptom, cause, fix, the games it was found on. The symptom index lists every symptom.
Disassembler dependencies
Capstone API version
- Symptom:
NameError: name 'CS_ARCH_ARM64' is not definedat the start ofpatch_nso.py; now[RED] Capstone 6.… is unsupportedfrom the NSP script orpatch_nso.py. - Cause: Capstone 6 renames the architecture to
CS_ARCH_AARCH64and the operand constants (ARM64_OP_*); the rewriter uses the Capstone 5 API. PyPI's Capstone 6 releases are pre-releases (6.0.0a…), so a plainpip install capstonegets 5.x; a--preinstall or another package's requirement brings in 6. - Fix: install
capstone>=5,<6(README and CI).patch_nso.pychecks the major version (cs_version()) before it disassembles anything, and the NSP script checks it before building or surveying, so the extraction is not wasted; both print the install command for the Python that runs them. Capstone 6 is not supported. - Found on: Celeste.
Patch discovery
Repository patches missing under bracketed paths
- Symptom: a build made from a checkout or folder under a name such as
Game [0400486024DEC000][v131072]silently loses the repository's per-game cuts, observation gates and frame-step stubs, although its build ID is registered; no error, as the SDK and engine patch files, named directly, still load. Under the same kind of folder,nso_match.py --registeredfinds no cuts, a provisional profile is guessed with no host hooks, and the shader split finds no NRO captured from a boot (DM_NRO_DIR, in the NSP folder): no CRA file table, no shaders from NROs. - Cause: these tools passed a folder path to
glob.globunescaped, and glob reads[...]in it as a character class, so the search matched nothing. TheDM_GAMES_DIRsearch already escaped its folders. - Fix: every folder given to
glob.globis escaped (glob.escape) before its pattern is joined:patch_nso.py'sPATCH_FILES,nso_match.registered_cuts,nso_syms.host_hooksandshader_split.boot_nros. The wildcards still select the same files under a plain path.pathlib'sPath.glob, which the other tools use, never reads the folder as a pattern.boot_nrosalso returns nothing withoutDM_NRO_DIR; the CRA lookup searched the working folder then. - Check:
test_patches.ExternalRegistry.test_repository_patches_under_bracketed_directoryloads a frame-step registration through the registry under a bracketed parent;test_bracketed_paths.pychecks the other three. The first three fail without the fix. - Found on: The Legend of Zelda: Ocarina of Time, a build in a bracketed folder (PR #1826).
Patches across updates
Function-matched cuts for unregistered builds
- Symptom: an updated game loses a needed cut because its NSO build ID changed, although the relevant code still matches a verified version; the rewriter reports
[RED] function patch ... skippedwhen that match cannot be established, and the NSP script ends with[RED] main: no function patch carries the registered builds' fixes to this buildor[RED] main: function patches not applied(Super Smash Bros. Ultimate 13.0.1: a static-initialiser abort innninitStartup, GitHub issue #375). - Cause: fixed-address
CUTScorrectly apply only to their registered builds. Copying an old address, or matching a short instruction sequence, does not identify the updated function. - Fix: a profile can opt individual cuts into
MATCH_CUTSin itspatches.py. The shared matcher,dm/tools/nso_match.py, selects a unique complete unwind function by length and SHA-256 fingerprint. It retains constants, registers and internal branch destinations; normalizes relocation addresses; and checks the normalized bodies of direct callees or their imported symbol names. Original bytes are checked again before a cut is applied. Missing boundaries, unknown callees, changed code and ambiguous matches produce a red diagnostic and no cut. Every locator fails closed this way, and a new one must too: exactly one match with its assumptions checked, or no change (dm_ue_cvarin the host as well: a console variable whose name is registered twice is not written). That is what makes a looser binding safe on builds nobody has seen (Binding). Overlapping rules stop the rewrite. Every accepted cut is recorded in<module>.cuts.tsvwith[function match]in its reason. Rules with the samenameare one patch's reviewed implementations, for a function a build changed (another size, or the cut at another offset in it). Exactly one of them must match: the log names the implementation that did, and a red line appears only when none matches or more than one does. Before this, each implementation logged a red line on every build it did not match.- A patch of several functions (
{'name', 'functions': [{'size', 'fingerprints', 'cuts'}, ...]}) applies whole or not at all: every function must match exactly once, at distinct places, or none of its cuts applies, and the red line names each function that did not match. Use it when the cuts depend on each other, as a constant used in several functions does (a region size, the place it derives, the bound checks of its end): applying some of them leaves code that disagrees about the layout, which fails later and less clearly than the original abort. Before this, rules were independent, so a constant split over several functions could not be enrolled safely. - A short callee with an ambiguous fingerprint can be located through
called_by = {'size', 'fingerprints', 'call'}. The matcher finds the unique caller by its complete fingerprint, follows the directblat its function-relativecalloffset, then checks the callee's size, fingerprint and original cut bytes. Catherine uses this to find its 60 Hz flag getter through the callback that advances the game clock. - What an unregistered build kept: for a module whose build is not registered, the rewriter writes
<module>.match.tsv: the cuts of the registered builds of that module (the repository profile'sbuildrows) and each patch's result. The NSP script reports it with the build: a red line when registered cuts have no function patch at all, or when a patch did not apply; the build itself goes on, since a derived profile is best-effort.
- A patch of several functions (
- SDK-wide patches:
dm/tools/sdk_patches.py'sMATCH_CUTS({'sdk': [rule, ...]}) apply to every game'ssdkof a build with noCUTS, whatever the profile; a build that must keep Nintendo's code registers an emptyCUTSlist. Before, they skipped a build the selected profile'sbuildrows name, which kept a registered row for every such build even where the rules gave the same cuts (18 builds' rows were removed when that changed). A patch that finds no reviewed implementation is logged as a plain line and listed by the NSP script without red, since a module may not need it (The SDK's address-region node area). The NSP script's rewrite step keys its reuse on the profile'sbuildrows as well. A callee that is one of the SDK's system call wrappers (svc #n; ret, assembly with no unwind entry) is identified by its call number. - Engine-wide patches:
dm/tools/engine_patches.py'sMATCH_CUTS({'main': [rule, ...]}) are loaded and applied the same way, to every game's module of that name with noCUTS, a plain line where nothing matches: fixes of middleware code a game ships (Unity's stream buffer handshake, from FINAL FANTASY CRYSTAL CHRONICLES and Raging Loop's Unity 2018). A game's ownpatches.pykeeps what only that game needs; engine discovery by name (ue_malloc.py,unity_bucket.py, ...) needs no fingerprint at all. - Scope: the profile selected by
DM_GAME, keyed by module name. A derived profile still uses that repository profile's rules, even when the repository has no matching rules or patch file; an external-only provisional profile can supply its own. External files cannot replace or enroll a repository profile's matching rules. Other games' rules never participate. A build with registeredCUTSuses those instead, including an explicitly empty list. SDK patches, observation gates,FRAME_STEPstubs and fixed host addresses retain their existing build-ID gates; frame-step stubs can be placed by their function instead (Frame-step stubs placed by their function). The rewrite cache includes the selected profile's patch file even for unknown builds, the selected game ID and the matching tool. Repeated search roots or symlinks to the same patch file are loaded and counted once; distinct files claiming the same build still stop the rewrite. - Limits: this is an opt-in code-identity check, not automatic compatibility for every game update. Direct callee bodies are checked one level deep; their callees, indirect-call targets and external data layouts are not proven unchanged. Enroll only a cut whose assumptions remain valid under those changes. Prefer fixing the general host behavior when possible. A replacement must contain no PC-relative instruction, except a direct branch whose target stays inside the matched function: the fingerprint keeps internal branches exact, so such a branch means the same on every matching build. A branch out of the function needs a different mechanism. Failure leaves the game potentially without its workaround, and stays visible in the rewrite log.
- Found on: Super Mario Bros. Wonder, whose former resource-heap allowance was missing on 1.0.1. The shared matcher remains, but Wonder's allowance and matching rule were later removed after the general command-record fix described in its game note. Same-name implementations: Taiko Risshiden V DX, whose frame-limiter cut has one implementation for 1.1.1 and one for the base game, where the function is shorter. A patch of several functions: Super Smash Bros. Ultimate, whose 11 engine-region cuts lie in four functions. SDK-wide: the AddressRegionManager node area and the 2 MB alignment of large regions (SDK 20's), from the SDK builds of 20 games (The SDK's address-region node area). Branches inside a replacement, and functions and callees holding the word
0xe7ffdefe(a trap left after a call that does not return, which Capstone cannot decode; read asbrk, still in the digest; 1,238 of them in this game'smain): Pokémon Legends: Arceus.
To enroll a cut for any game's own module:
- Start from a verified fixed cut and its original NSO. Run
python3 dm/tools/nso_match.py <module.nso> <offset> <old hex> <new hex> <reason>with the tools' Python environment. It emits a rule containingname,size,fingerprintsand function-relativecuts, and rejects an ambiguous reference. For cuts that must apply together,python3 dm/tools/nso_match.py <module.nso> --registered <name>makes one patch of every cut registered for that NSO's build ID, grouped by function. Keep game files and scratch outputs in the game's NSP work folder. - Check the function and callees in another known build using
nso_fnmap.pyand disassembly. Check that the cut still has the same effect.Image.match_patch(rule)must resolve the reviewed locations. If a reviewed implementation differs, generate its fingerprint separately; combine fingerprints only when function size and relative cuts agree, and otherwise add the implementation as another rule under the same name. Retain exactCUTSfor known builds. - Add the rule under
MATCH_CUTS = {'main': [rule]}(or the appropriate non-SDK module) in that game'spatches.py. Record the evidence and remaining runtime validation in the game's note. Do not transplant a workaround into unrelated games. - Verify an unregistered build-ID copy through the rewriter, comparing its output with the known fixed cut, and run
test_nso_match.py,test_patches.pyandtest_nro_pack.py. The matching tests use synthetic modules from two profiles to check relocation, rejection and isolation without game files.
Frame-step stubs placed by their function
- Symptom: 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
buildbound, blocked for want of a function-matched form. - Cause:
FRAME_STEPstubs branch out of the game's function into the patch area and back, and read the state page byadrp: addressesMATCH_CUTSreplacements may not hold, since a cut's bytes must mean the same on every build that matches. - Fix:
MATCH_FRAME_STEP = {'main': [{name, size, fingerprints, stub}]}in a game'spatches.py.nso_match.locate_stubfinds the one complete unwind function of that size and fingerprint, before any cut changes the image, by the same rules as a function-matched cut (relocations normalized, direct callees checked, rules of one name as reviewed implementations, exactly one must match).patch_nso.pythen gives the main its state page and runsstub(ctx)withctx.basethe function's start, so the stub writes its sites at offsets inside the function and assembles its body in the patch area with the addresses of this build; each site's original bytes are still asserted (ctx.site), and the cuts it lists say[function match]. No match, or two, gives[RED] frame step … skippedand no state page, so the host keeps the game's own present interval (A present cap applies only with a frame step or an engine limit the host writes). A build withFRAME_STEPkeeps those stubs. Only the profileDM_GAMEselects takes part, as forMATCH_CUTS. - Several functions: a rule's
others = {label: {size, fingerprints}}names more functions its stub patches or reads, each found the same way (ctx.others[label],Nonewith a red line when not exactly one matches); a stub that needs all of them leaves everything out when one is missing, as a part alone runs the game at the wrong speed. A global the stub needs comes from the code of a matched function:ctx.address(offset)is the data address theadrpthere and theadd, load or store after it make, read from the original text (the fingerprints mask the page). Tears of the Kingdom's frame step (six functions) rewrites 1.4.3 byte-identical to the build entry it replaced; Hyrule Warriors: Age of Calamity's (four functions, the KTGL device global from its frame task's own load, the frame-rate block from its writer's store) places its five sites on v458752, which had no frame step. - Anchored on an import: a fingerprint covers the whole function, so an update that changes anything in it, even one member offset, needs a new one. Where the site sits in the one function that calls a particular imported symbol, a rule can name that symbol instead:
{name, calls, find, stub, reviewed}.nso_match.Image.callersfinds the complete unwind functions thatblits PLT entry; exactly one must.find(fn)(annso_match.Function: its words, the calls' offsets, the text,uses(registers),branch_targets()) then checks everything the stub relies on in that build's code and returns what the stub needs (ctx.found), or raisesMatchError: a red line and no stub, as for a fingerprint that does not match.reviewedlists whatfindreturned on the builds checked by hand, which the binding page andtest_patches.pyrun the stub with. Such a rule holds over updates that change the function elsewhere, and still finds exactly one place with its assumptions checked, or none. Hades II's render size (the one caller ofnn::vi::CreateLayer; one 1280x720 constant after the call, once in the text, no branch onto its second instruction, none of the stub's registers used in the function) rewrites v0 and 1.0.141667 byte-identical to the two fingerprinted rules it replaced, and locates in 0.16 s. - Limits: Breath of the Wild (44 sites in 34 functions) and ASTRAL CHAIN (112 sites in 15 functions, its last update from 2019) stay build-bound by choice; Paper Mario: The Thousand-Year Door's cut and stub could move. A comparison with each engine's other games (2026-11-09) found none of these frame-step functions shared, so no engine-wide rule can hold them.
- Found on: The Legend of Zelda: Ocarina of Time and Mario Kart World, the first frame steps with a
gamebinding; The Legend of Zelda: Tears of the Kingdom and Hyrule Warriors: Age of Calamity, the first with several functions (2026-11-09). - Check:
test_nso_match.py(test_frame_step_rule_locates_its_function_or_nothing: a moved function, two matches, none, malformed rules);test_patches.py(each rule's sites lie inside its function; the registry scopes the rules asMATCH_CUTS). Both mains rewritten (2026-11-08): the stub at the reviewed site, its branches back into the function, the state page the fixups name.
Function-matched ordinary stubs
- Symptom: a local timing correction needs extra instructions, but declaring a frame-step state page would also change the host's pacing for a game with a native engine frame-rate setting.
- Fix:
MATCH_STUBS = {module: [rule, ...]}in a profile'spatches.pyuses the same complete-function (with optionalcalled_byfor a short ambiguous callee) or import-anchored matching asMATCH_FRAME_STEP, withctx.base,othersandfound, and the ordinarySTUBSemit/site/put/address operations. It allocates no frame-step state page.ctx.address(adrp, low=None)derives a data address from the original instructions, accepting an explicit low-instruction offset for interleaved ADRP/load pairs and checking their register relationship. Missing or ambiguous matches install no stub. A rule's optionalfps_required=Truekeeps native engine frame targets disabled unless the stub setsctx.fps_ready=Trueafter installing its complete correction: fixups recordNATIVE_FPS_BLOCKED, andhle_fpslock.cleaves the game's own limits. This also applies when a required companion function cannot be found. - Found on: Xenoblade Chronicles X: Definitive Edition: its camera's per-update angular gain must use elapsed time before its native interval can safely select 60 fps;
called_byon FINAL FANTASY TACTICS - The Ivalice Chronicles (#3046): its 8-byte job-pool signal wrapper is byte-identical to an adjacent wrapper and itsb SignalEventencoding shifts across updates. - Check: patch registry/site checks, interleaved address decoding, the native frame-limit block test, and the game's matched base/update rewrites.
A frame step state page where the patch area starts
- Symptom: the rewrite of a main that gets frame step stubs (
FRAME_STEPor aMATCH_FRAME_STEPmatch) stops withAssertionError: frame step state page; the same main rewrites without the stubs. - Cause: the state page is the page after the key page, and an appended patch area starts on the first 64 KB boundary after the key page. When the key page ends on such a boundary, that boundary is the state page itself (Hades II's v0 main: key page at
0x590c000, so the state page and the patch area both at0x5910000), and the assertion that the state page lies below the patch area fails. One main in four lays out this way; none with a frame step had before. - Fix:
patch_nso.pymoves the patch area 64 KB later for a main that gets the state page and would start its patch area on it, decided after the frame step's function is found and before anything is written to the patch area. Every other module keeps its layout, byte for byte. Render-scale stubs (state +0x10) now also give their largest scale:ctx.render_scale = n, written asRENDER_SCALE nin the fixups table, holdsDM_RENDER_SCALEto 0.5–n in the loader and sets the launcher slider's top (settings.py); the stubs that only lower the size give 1. - Found on: Hades II: its render size stub, the first state page of a main without a frame step, on v0 (issue #772; padsiwono reported the assertion on update 1.0.131248).
- Check: v0 and 1.0.141667 mains rewritten (2026-11-10): v0's patch area at
0x5920000, its state page at0x5910000; 1.0.141667's layout unchanged (patch area0x5b10000, state page0x5b08000); both ran through the opening into Erebus with the render size stub at 1.5 (v0) and 0.5 to 3.0 (1.0.141667).
Cheats carried across game updates
-
Symptom: 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. -
Cause: Atmosphère cheats name fixed offsets into the main NSO, valid for the one build the file is named after. An update moves code and data by different amounts in different parts of the image; a single shift is a guess.
-
Fix:
scripts/cheat_anchor.pyanchors each address to the game's code and compiles the cheats for any build (Cheats that survive game updates):- data through the adrp pairs (and relocated
.dataslots) that reference the nearest address at or below it; - code sites through
nso_match.py's function fingerprints, then the tool's own fallbacks (the body digest, then a unique masked window), with a code site's original words always checked; - ASM code caves through the padding before the read-only data.
The result is plain Atmosphère text, so it runs on any engine.
- data through the adrp pairs (and relocated
-
Found on:
- 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: 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.
- FINAL FANTASY CRYSTAL CHRONICLES Remastered Edition: the 1.0.1 cheatslips file, anchored on the cartridge's
Thread registers
System register accesses through x18
- Symptom: a crash (
sig=11) in the patch area a few seconds into a run, at anx18site's load, with an address a little above a small stale value (addr=0x33220, the thread'sK18slot at0x33200), shortly after the game readtpidr_el0intox18. - Cause: the guest's
x18lives in the thread slotK18, since the Apple kernel may change the register at any instruction, and everyx18site loads and stores the slot. The system register sites did not:mrs x18, tpidr_el0/tpidrro_el0put the value in the register only,msr tpidr_el0, x18stored the register intoKTLS, and the gate formrs x18, cntpct_el0/cntvct_el0wrote the savedx18, whichdm_gatedoes not restore. The nextx18site read whateverK18held before.mrs x18, ctr_el0stopped the rewrite with an assertion. - Fix: with
x18as the register, the rewriter copies between thread slots (site_slot_copy:KTLSorKTLRintoK18,K18intoKTLS, the cache type constant intoK18), carrying the value inx15withx16/x17for the slot addresses, all saved in the red zone; the value never passes throughx18. The host's counter gate writesK18for a destination ofx18. 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.pychecks that no block namesx18, 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; issue #2123): onemrs x18, tpidr_el0inmain, at+0x23f5ec0. Its reporter's version of the fix ran 19 minutes into a battle; this one awaits their run.
Jump tables
Jump tables proved over control flow
- Symptom:
jump table <addr>: <reason>assertion inpatch_nso.py, the reason being what could not be proved (the index is not bounded,the table base is not a constant,a target is not an instruction of the function,not a table, …), orjump table <addr>: an entry from another function is not proved. - Cause: offset tables used to be recognized by their shape, one recognizer for each form a game brought (the entries below), each with its own walk back to the bound and the base and its own checks of how control may enter. A shape cannot show a base set on another path, a bound made in another block, or a dispatch through another register whose targets land in this one, and each new form was one more recognizer: Manual Samuel's
andbefore itstbnzwould have been the tenth. - Fix:
dm/tools/jump_solver.pyproves every dispatch of a function (or analysis piece) at once, by forward dataflow over its control flow:br xDwherexDis a constant (the table base or anadr) plus an entry loaded byldrsw/ldrb/ldrhfrom[xB, xI …], shifted. A register holds constants (addresses fromadrp/adr, numbers frommov), or a root with a chain of operations (32-bit truncation,andwith a mask, complement, add); a root carries its range, the range of its low 32 bits and the set of its low 12 bits. A shift right (lsr,ubfx) makes a new root bounded by the shift, so a 32-bit compare then bounds all of it (ASTRAL CHAINmain+0x6db104:lsr x17,x11,#32; cmp w17,#5). A guard (cmp/b.cond,tst,cbz,tbz/tbnz) narrows the root, so every register derived from it narrows with it: the bound reaches the index through copies, masks and complements, before or after the test, in the same block or another. At a join, registers holding the same chain of one root on each side share one phi root and keep their chains, so a copy stays tied to its source around a loop (Mario + Rabbids Kingdom Battlesubsdk0+0x7340b8). A loop's joins widen a root after six visits part by part: only the parts that still grow (the range, the low 32 bits' range, the low 12 bits) become unknown, so a guard on the low 32 bits outlives a growing full range (ASTRAL CHAINmain+0x6db1a4). A table's entry is a number too: an index loaded from a byte table is bounded by its own guard (OCTOPATH TRAVELER's movie middleware,ldrb w10,[x9,x10]; cmp w10,#0xa). A table's targets become edges and the analysis runs again until no table changes; dispatches through any register count (Manual Samuel's three throughx17), and a byte or halfword table it cannot bound lands on all its pads. The function's start, the targets of calls inside the range, direct branches from the rest of the module (one scan of the text) and targets of tables in other functions start with every register unknown, and so, in text without unwind entries, does code after a terminator and its alignment padding that nothing reaches (a function an indirect call enters: DRAGON QUEST XI Smain, 70 MB without unwind entries). C++ exception landing pads (nso_code.landing_pads, from the LSDA of each FDE whose CIE names a personality routine) start with what the calls they catch left, the callee-saved registers kept. A CIE with an LSDA and no personality (zLR) points at a runtime's own data: Absolummain(.NET NativeAOT) has 85,000 of them, whose bytes read as C++ call-site tables gave counts in the millions and ran the rewrite out of memory. Calls clobber x0–x18 and x30; returns, calls and branches with pointer authentication (retab,blraa,braa, in the Switch 2 SDK) are returns, calls and branches. There are two readings. The first knows the numbers the code writes and gives the control flow. The second reads thebr x18tables again with those numbers unknown, so that each table's size is what its guards allow however control reaches it (Manual Samuelmain+0x2e8174: 7 entries bycmp w18,#6, where the numbers on the paths the first reading sees reach 2); only a table no guard bounds keeps the first reading's. A number inside page zero is never a table base: Horizon never maps page zero, so no path of a working game carries one to a load. Every target must be an instruction of the function. Halfword tables' landing pads come from the same tables (half_pads); byte and halfword tables throughx18keep their pads wherever theiraddis (jump_bytes_farbefore the solver). - Found on: every form below. It replaced their recognizers and helpers (
jump_offsets,jump_adr_offsets,jump_masked_pred,guarded_run,jump_guarded_tail,jump_guarded_cfg,copied_base,table_base,forward_table_base,check_before_copy,guarded_count,null_base,half_count) when Manual Samuel needed another form (#2562, PR #2695). - Check:
dm/tools/tests/test_jump_solver.py: each form with its game's instructions, the refusals, and the driver on synthetic modules. On the newest build of every supported game (457 modules of 150 games, rewritten by the old recognizers and by the solver), 453 rewrite byte-identically and four differ only where the solver proves a halfword table the recognizers left at 65,536 pads: Animal Crossing: New Horizons 3.0.3main(six tables, now 608–929 pads), Pikmin 4 1.1.1main(two, 451 and 562), Tears of the Kingdom 1.4.3main+0x680528(667) and PRAGMATAmain(three, 417–2,504). Manual Samuelmainmatches the rewrite of PR #2695's own patch. Rewrite time over the corpus: 12,430 s of CPU before, 10,591 s after. - Limits: a
brit cannot read (an indirect tail call) is taken to leave the function, and code no path, table or landing pad reaches is dead to it, as both are to the rewriter's own sites. A 32-bit compare bounds a 64-bit index only where the upper half is known to be zero.
A guard on a wrapping 32-bit jump-table index
- Symptom:
jump table 2c0a220: the index reaches 0xffffffffffffffffstops the rewrite. - Cause: the guard on
sub w10,w14,#1cannot always be inverted across the wrap. Its fallback creates a root for the narrowed result. Giving that root a 64-bit range let later loop joins and widening lose the proof that the 32-bit write zeroed the upper half ofx10. - Fix: carry the expression's width to the new root. The existing dataflow follows the copied table base, and the 32-bit compare can bound the full index. A compare on the low half of an index with unknown upper bits still cannot prove the table.
- Found on: Timespinner 1.0.0 (PR #1864). A full Mac rewrite resolves six dispatches in one function to four targets each.
Offset jump tables through x18 read at rewrite time
- Symptom:
jump table <addr>assertion inpatch_nso.py, in a Unity / IL2CPPmain. - Cause: the compiler used
x18for jump-table shapes other than the ones the rewriter knew. One of them is an offset table:ldrsw x18, [xB, x18, lsl #2]; add x18, x18, xB; br x18. (The samemainalso usesx18for an indirect call and analloca: see Indirect calls through x18 and Stack pointer writes through x18.) - Fix: the rewriter reads the offset table's targets at rewrite time (
site_br_tabinpatch_nso.py). - Found on: Fire Emblem Engage
main: 7 jump tables (beside 1 call and 1spwrite). - Check: Super Mario Bros. Wonder's output stays byte-identical.
Offset jump tables with the bounds check on another register
- Symptom:
jump table <addr>assertion inpatch_nso.py, in asubsdk. - Cause: the offset-table form
ldrsw x18, [xB, xI, lsl #2]; add x18, x18, xB; br x18with the bounds check on another register: the index inw0(sub w0, w18, #0xd1; cmp w0, #0x31), a copy (cmp w21, #7; …; mov w18, w21) or a masked copy (and w16, w18, #0x3f; cmp w16, #0xe; …; and x18, x18, #0x3f). The entry may also be loaded into another register, with only theaddwritingx18(Cuphead, Unity 2017.4:cmp w17, #7; ldrsw x17, [x15, x17, lsl #2]; add x18, x17, x15). - Fix: the jump solver: the copy shares the checked value's root, and the masked copy is the same
andof the same root. - Found on: The Legend of Zelda: Link's Awakening (GLSLC and movie modules); Cuphead (the entry loaded into another register).
- Check: Fire Emblem Engage's output stayed byte-identical.
Index copied before the bounds check
- Symptom:
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 onx0, thencmp w18,#4; b.hi; ldrsw x18,[x11,x0,lsl #2]; add x18,x18,x11; br x18). - Cause: every other form follows copies made after the bounds check.
- Fix: the jump solver: the
movmakesw0the same value asw18, so the compare ofw18narrows the index, however far apart the two are. - Found on: DRAGON QUEST XI S: Echoes of an Elusive Age – Definitive Edition
main+0x2dd8cd0; Mario + Rabbids Kingdom Battlesubsdk0+0x7340b8, whose copy is 71 instructions before the load, across two switches preserving both registers (beyond the former 64-instruction limit). - Note: before fixing one site, a census of all of them saves a run per site: a copy of
patch_nso.pywhose assert prints and continues found this one alone among the 25,508x18sites. Thatmainhas no unwind entries for its first 70 MB, so the rewriter disassembles them as one function and takes 6 minutes (see Long functions analysed in pieces).
64-bit bounds check of the index
- Symptom:
jump table <addr>assertion inpatch_nso.pyon an offset table whose index is checked with a 64-bit compare (cmp x22, #0x10; …; b.hi; adrp x18 + add x18; mov x0, x18; ldrsw x18, [x0, x22, lsl #2]; add x18, x18, x0; br x18). - Cause:
jump_offsetstook only a 32-bitcmp wI, #Nas the bounds check. A 64-bit compare bounds the index as well (the load uses the wholexI); here the table base also reaches the load through a copy, so only the far-base pass reads it. - Fix: the jump solver, which takes a compare of either width on what it compares: a 64-bit one bounds the whole index.
- Found on: OCTOPATH TRAVELER
main+0x1676f58(1.0.5), the only such site in thatmain.
Index zero-extended after a 32-bit bounds check
- Symptom:
jump table <addr>assertion inpatch_nso.pywhere the index is made with a 64-bitandby0xffffffffafter the check (cmp w8, #4; b.hi; and x18, x8, #0xffffffff; ldrsw x18, [x16, x18, lsl #2]; add x18, x18, x16; br x18). - Cause:
jump_offsetstook theandas a mask and looked for the same mask on the checked register, which has none, so no form matched. - Fix: the jump solver: the
andwith0xffffffffreads the low 32 bits the 32-bit compare narrowed, N + 1 entries. - Found on: Mario Tennis Aces (0100BDE00862A000)
main+0x35837c(1.0.0), a five-entry table whose targets all lie in the function (PR #778). The contributor reported thatmain,subsdk0andsdkrewrite with zero-extension recognition; gameplay validation remains open.
Guarded dispatch tails
- Symptom:
jump table <addr>assertion inpatch_nso.pyon an offset table whose bound comes from a bit test, a complemented or zero-extended mask, a mask whose highest value branches away (and w18, w17, #7; cmp w18, #7; b.eq), or acmpmore than 16 instructions before thebr. - Cause: each form needs its own reading of the guard, and each used to have its own recognizer with its own copy of the proof around it.
- Fix: now the jump solver, which needs no parser of the run. Before it: one parser of the run,
guarded_run, and one recognizer,jump_guarded_tail, tried after every other form. The guard and the index are on one straight run to thebr(at most 32 instructions):guard; …; [and xI, xS, #M; …;] ldrsw xE, [xB, xI, lsl #2]; …; add x18, xE, xB; …; br x18. The guard gives the entries:cmp wI, #N; b.hion the index itself (N + 1, far compare);and wI, wS, #M; cmp wI, #M; b.eq(M, the run starting at theand, masked bases on other paths);cmp wS, #N; b.hiwithM = 0xffffffff(N + 1, zero-extended);tst wS, #M; b.eq; mvn wS, wS(M, complemented);tbnz wS, #BwithM = 2^(B+1) - 1(2^B, bit test), before the mask or after it (bit test after the mask). The mask may be the 32-bitand wI, wS, #M, which zero-extends intoxI. One proof covers them: no gap in the run, the guard's branch leaves it, no other control flow or trap in it, the source unchanged up to the mask, the index up to the load, the entry and base up to the add,x18up to thebr. The table base is found bycopied_base(adrp+add, then only register copies, in address order). Every target must be a decoded instruction of the function outside the run. No direct branch of the function or jump table resolved so far may land past the guard; after every function, tables resolved later and direct branches from anywhere in the module are checked against each run (branch past a guard,jump table past a guard). Wherecopied_basefinds no base,jump_guarded_cfgproves it over the control flow (below). - Found on: the forms' entries; first on Mario Tennis Aces and Return of the Obra Dinn as two recognizers, merged when ULTRA STREET FIGHTER II brought two more forms (#960, PR #2108).
- Check:
dm/tools/tests/test_jump_solver.pyhas each form.
Bit-test bounded masked jump-table index
- Symptom:
jump table 590ee8assertion inpatch_nso.pyon ULTRA STREET FIGHTER II: The Final Challengers 1.1.1 (SDK 1.3.1). - Cause:
tbnz w17, #3, next; and x18, x17, #0xf; ldrsw x18, [x13, x18, lsl #2]; add x18, x18, x13; br x18bounds the index without a compare: on the fall-through bit 3 is clear and the mask removes every higher bit, so 8 entries, not the 16 the mask allows. The basex13is built byadrp+addbefore two loops around the dispatch, whose back edges land before the guard. - Fix: the jump solver: the
tbnznarrows the low bits ofw17, and the mask is of the same root: 8 entries. - Found on: ULTRA STREET FIGHTER II: The Final Challengers 1.1.1,
mainbuild8726f5e816b001b2af588df35996c4c0,main+0x590ee8(reported with a first matcher by PikaMan80 in #960, then landed in7b5d631after PR #2108).
Bit test after the mask
- Symptom:
jump table <addr>assertion inpatch_nso.pyon an offset table whose index is masked before a bit test of the mask's source, with no compare (and w13, w17, #7; tbnz w17, #2, exit; ldrsw x13, [x14, x13, lsl #2]; add x18, x13, x14; …; br x18). - Cause: the bit-test form of guarded dispatch tails looked for the
tbnzonly before the mask, and for the mask only as a 64-bitand xI. On the fall-through bit 2 ofw17is clear, so the index is 0 to 3. Manual Samuel's function holds four such dispatches (three throughx17), each with a 4-entry table 16 bytes after the one before, so the mask's 8 entries would read the next table, or code outside the function. - Fix: the jump solver: the test narrows
w17's root after the mask was taken from it, and the mask follows. The basex14is a constant on every path into the load (theb.ltonto theandand the dispatch's own table re-entering there come after itsadrp+add), and the threex17dispatches beside it are proved with it, so their targets are edges too. - Found on: Manual Samuel (
0100748009A28000) 1.0.0,mainbuildef0161e4ed3c2947b3fe8c3d200107ce,main+0x6d9d44, 4 entries (reported with a working matcher by TheLowbar in #2562; PR #2695).main,sdkandsubsdk0rewrite;maincomes out byte-identical to a rewrite with the reporter's matcher, with which the game plays at 60 fps on an iPhone 15 Pro Max. There is no profile for this title yet.
Bounds check further back than 16 instructions
- Symptom:
jump table 63607cassertion inpatch_nso.pyon ULTRA STREET FIGHTER II: The Final Challengers 1.1.1. - Cause: an ordinary
cmp w18, #0x11; b.hi; adrp x0 + add x0; mov w9, #1; ldrsw x18, [x0, x18, lsl #2], then nine constants moved into registers around theadd x18, x18, x0before thebr x18: thecmpis 24 instructions before thebr, andjump_offsetssearches 16. - Fix: the jump solver, which has no window.
- Found on: ULTRA STREET FIGHTER II: The Final Challengers 1.1.1
main+0x63607c, 18 entries. #960 namesmain+0x7d3000for a long-context dispatch; in 1.1.1 that address is a function's epilogue, and this is the only other table the rewriter stopped at.
Index masked in the block that branches to the dispatch
- Symptom:
jump table <addr>assertion in a Unity / IL2CPPmainwhose dispatch checks a fresh mask of another register than the one it indexes with. - Cause: the dispatch block masks the source again for its bounds check, while the index register was masked from the same source in the block that branches to it:
and x6,x17,#0x7ff; ubfx w18,w17,#0xb,#2; cbz w18,L, thenL: and w18,w17,#0x7ff; cmp w18,#3; b.hi; ldrsw x18,[x27,x6,lsl #2]; add x18,x18,x27; br x18, with the basex27from anadrp+addabout 1,500 instructions back. A sibling builds its base inside the block and moves registers before thebr(adrp x24+add, amov, the load and the add, then 10 register moves). No copy links the two registers, sojump_offsetsandcheck_before_copyfind no check. - Fix: the jump solver: both masks are of the same root (
w17), so the compare ofw18narrowsx6too; a narrower mask in the predecessor is bounded as well, a wider one is not. - Guards (resolved): direct calls and resolved jump tables must not enter between a predecessor's mask and its branch, since that bypasses the index assignment; direct calls into the dispatch are refused too. Undecodable words break either straight-line run, and table targets must be decoded instruction addresses, not just aligned addresses inside the function. The base uses
copied_base, which followsadrp+addand register copies while rejecting 32-bit writes that destroy a 64-bit base. - Found on: FINAL FANTASY CRYSTAL CHRONICLES Remastered Edition 1.0.0 (Unity 2018.4.2f1, SDK 8.2.1)
main+0x2d103ccand+0x2d10590, in one function; the same form in its update 1.0.3.
Zero-guarded complemented jump-table index
- Symptom:
jump table 6eea88orjump table 6eeac0assertion inpatch_nso.pyon Return of the Obra Dinn 1.0.1. - Cause: Unity's IL2CPP output uses
tst w15,#7; b.eq exit; mvn w15,w15; and x15,x15,#7; ldrsw x15,[xB,x15,lsl #2]; add x18,x15,xB; br x18. The zero test excludes one masked value before complementing it: the reachable indices are 0–6, so the table holds seven entries. Treating thetstimmediate as acmpbound reads an eighth word from the next table, introducing a target the guest cannot reach through this dispatch. - Fix: the jump solver:
tst/b.eqremoves the low-bit patterns 000, the complement and the mask then give 0–6, computed exactly from the low 12 bits. - Found on: Return of the Obra Dinn 1.0.1 (
mainbuild9e93a6566aaa27418dd2435d8d5dffe5), two dispatches in the function atmain+0x6ee8c0. - Check: the extracted update's two sites resolve to seven targets each; gameplay validation is recorded in the game note.
Offset table base set far back in the function
- Symptom:
jump table <addr>assertion on an offset table whose base was set far back (cmp w18,#5; b.hi; ldrsw x18,[x24,x18,lsl #2]; add x18,x18,x24; br x18). - Cause: the function's first block loads six table bases with
adrp+addinto registers that its loop keeps (x24441 instructions before this load), and a later block one more (x3, 549 before the load at+0x6db70c);jump_offsetsfollows the base's writer chain 256 instructions back. The function-wide search thatjump_adr_offsetsuses for a hoisted base (the oneadrp+addpair that fits) found two forx3, the other a local table of abr x17further on. - Fix: the jump solver: the bases are constants carried around the loop on every path, however far back they were set.
- Found on: ASTRAL CHAIN 1.0.1 (SDK 6)
main+0x6db4a0: three of thatmain's fivebr x18sites need it. - Check: modules that rewrote before come out the same (Tears of the Kingdom, Age of Calamity, Cuphead, DARK SOULS: REMASTERED, Luigi's Mansion 3 and Metroid Dread
mains: byte-identical).
Far table base passed through other registers
- Symptom:
jump table <addr>assertion on an offset table whose base was set far back and moved through other registers (ldrb w18,[x14]; sub w18,w18,#1; cmp w18,#6; b.hi; ldrsw x18,[x7,x18,lsl #2]; add x18,x18,x7; br x18). - Cause:
x7is built byadrp+add688 instructions before, then parked inx30around a loop (mov x30,x7…mov x7,x30), so the far chain meets amovand stops; the function-wide search finds a secondadrp x7+addpair (another table further on) whose seven targets also lie in the function. - Fix: the jump solver: a copy carries the constant.
- Found on: Super Smash Bros. Ultimate 13.0.5 (SDK 8.2.1)
main+0x2b74458: thatmain's only unhandled site. - Check: Mario Kart 8 Deluxe's three modules and Smash's
sdkand movie module come out byte-identical.
Offset table base initialized after the dispatch
- Symptom:
jump table ae95f8assertion inpatch_nso.pywhile rewriting Blasphemous 1.0.8. - Cause: the function enters an initialization block later in address order, then branches backward to
cmp w18,#9; b.hi; ldrsw x18,[x17,x18,lsl #2]; add x18,x18,x17; br x18. Theadrp x17/add x17,x17,#lopair is after the dispatch, so the backward writer searches find no base. - Fix: the jump solver: the base reaches the load over the backward branch.
- Found on: Blasphemous,
main+0xae95f8, ten table-relative targets. - Check: the extracted function resolves to the ten targets read directly from its table.
Masked dispatches sharing bases across control-flow paths
- Symptom:
jump table <addr>assertion inpatch_nso.pywhere a guarded dispatch's table base is set later in address order and other loops reuse that register for their own tables. - Cause:
copied_basewalks the base's writers back in address order, which says nothing about which writer reaches the load on another path: there is none before Tied Together's first loop, whose base is set in a block after it that branches back, and a nearby writer can belong to another loop's table. - Fix: now the jump solver, which carries every register over the control flow. Before it, where every other form failed,
jump_guarded_cfgproved the bases over the control flow. Everybrin the function (or analysis piece) must be a guarded run; each run's base is a straight-lineadrp+addcandidate whose table decodes to instructions of the function, the onecopied_basenames or else the only one (or the one whose targets a recognizer already resolved). Constant propagation of the base registers, from unknown values at the function's start, at the targets of tables resolved elsewhere and at direct branches from elsewhere, must bring each candidate to its load on every reachable path. Edges into a run past its first instruction, calls, traps, writes ofx30and undecoded words refuse the proof. During the scan it sees the tables resolved so far; afterwards the driver proves each such function again with every table and with the direct branches from the rest of the module, taken from the same scan that checks guarded runs and windows (jump table <addr>: an entry from elsewhere is not proved). An entry before a complete base initialization is fine; one between theadrpand the load, or at a run's compare, is not. - Found on: Tied Together (
0100B6D00C2DE000) 1.0.2, from a provisional profile (PR #1937):and w18, w17, #7; cmp w18, #7; b.eq, 7 entries. The game has no profile here. - Check:
dm/tools/tests/test_jump_solver.py(theb.eqform, bases set later, entries from elsewhere).
A table base register that another loop holds a small constant in
- Symptom:
AssertionError: jump table 59dc90inpatch_nso.pyon Cuphead 1.3.7main, a build its profile names, sincee5620b1a. - Cause: the function interleaves four dispatch loops that share registers.
x12is the base of one (adrp x12+add x12,x12,#0xa54at+0x59dba4) and the constant 1 of another (mov w12,#1at+0x59dbdc, in a block that leaves bybto its own dispatch); only the value ofw8keeps the paths apart.jump_offsetswalks the base's writers back in address order. Sincee5620b1ait sees a write ofwNas a write of the base (correctly), so the walk met themovfirst and gave up, and no later form takes the site. - Fix: the jump solver: a number inside page zero is never a table base. Before it: general (
patch_nso.pynull_base): before the walk had found the base'sadd, a write of a constant that puts the table inside page zero (movof an immediate or ofwzr/xzr, the constant plus 4 bytes an entry at most 0x1000) was passed. Horizon never maps page zero, so the load would fault through that value on the console too: no path of a working game carries it to the load. Any other writer still ends the chain, and a constant between theadrpand theaddis the base's own input. - Found on: Cuphead 1.3.7
main+0x59dc90(GitHub issue #1532). Its ten targets are instructions of the function, and three of them are the same as those of the two sibling tables inx15andx17that the rewriter already took. - Check:
dm/tools/tests/test_jump_solver.pytest_page_zero_numbers_are_no_base.
Offset tables relative to an adr
- Symptom:
jump table <addr>assertion, entries relative to anadr. - Cause:
cmp wI, #N; b.hi; …; adr x18, #L; ldrsw xE, [xT, xI, lsl #2]; add x18, x18, xE; br x18: target = L + entry, not table + entry. - Fix: the jump solver: the constant added to the entry is the
adr, the table base another constant. - Found on: The Legend of Zelda: Tears of the Kingdom
main+0x393bb0and others.
ADR-relative jump tables with 64-bit bounds
- Symptom:
AssertionError: jump table 30ee50cwhile rewriting an ADR-relative dispatch withcmp x9,#4. - Cause:
jump_adr_offsetsrecognized only 32-bit bounds comparisons, although a comparison of the full 64-bit index also bounds the table. Its backward copy tracking could also retain a destination whose old value had been overwritten. - Fix: the jump solver, which takes either width and sees every write.
- Found on: DRAGON QUEST I & II HD-2D Remake,
main+0x30ee50c(five targets). - Check:
dm/tools/tests/test_jump_solver.pytest_64_bit_compare_and_32_bit_values. - Resolved: the recognizer assumed the comparison had an effective unsigned bounds guard without checking the branch or the flags; it checks both now (A compare that guards nothing taken as a jump table's bound). This game's actual dispatch has
b.hiwith unchanged flags. The jump solver proves every path into it.
Vector registers read as writes of the jump-table index
- Symptom:
AssertionError: jump table 3ce6cwhile rewritingmain, on an ADR-relative dispatch that the existing form describes:ldrb w0, [x18, #5]; cmp w0, #5; b.hi; ldr s0, [sp, #8]; ldr s1, [x18, #0xc]; adr x18, #L; ldrsw x1, [x17, x0, lsl #2]; add x18, x18, x1; br x18. - Cause: the backward walk from the load to the bounds check refuses the site when an instruction writes the index. It named each written register
'w' + name[1:], soldr s0became a write ofw0, the index, andjump_adr_offsetsgave up.half_count,check_before_copyand the masked form ofjump_offsetshad the same test. It also failed the other way: capstone'sreg_namecalls x30lrand x29fp, so a real write of an index in either went unseen. The complemented-index recognizer (now part ofjump_guarded_tail) missed those writes too. - Fix: now the jump solver, which reads only general-purpose registers,
lrandfpas x30 and x29. Before it, all of them askedwritten_w. - Found on: Tomodachi Life: Living the Dream (
010051F0207B2000) 1.0.0,main+0x3ce6c(six targets, table atmain+0x2a5967c), by the pull request's author: with the fix the game rewrites, packs as a Mac app from a provisional profile and boots to its first screen. The other forms were found by reading the code and shown on synthetic sites. - Check:
dm/tools/tests/test_jump_solver.pytest_writes_between_the_check_and_the_load.
Overwritten jump-table indices and bases taken as unchanged
- Symptom: no failure seen on a game. The rewriter could read a jump table with the wrong size or base, so a case's target or landing pad would be missing or wrong. In the other direction, a halfword table whose base is in x30 got all 65,536 landing pads (
Jrows with 65536 inmain.sites.tsv), which only makes the patch area larger. - Cause:
jump_offsetsandhalf_countfollowedmov w9,w0as a copy into the index but keptw9as the index too, socmp w9,#4before the copy counted as its check. The table-base writer chains andjump_adr_offsets' search for theadrcompared written names withxN, so a write ofwN, which replaces the register as well, went unseen, as didlrandfp. A compare ofxNcounted as a write there. - Fix: now the jump solver, where a copy shares its value and a write replaces it. Before it, a copy replaced the index, as
jump_adr_offsetsalready did. Those searches askwrites_reg, which sees either width and thelr/fpnames and leaves compares out.jump_offsetsalso refuses a site whose index is written after its check, such asadd w18,w18,#1, or a caller-saved index across a call. A write that keeps the value, such assxtw x0,w0, is refused too: no game on the drive has one, and a refusal stops the rewrite with ajump tableassertion instead of reading the table wrongly. - Found on: reading the code while fixing Vector registers read as writes of the jump-table index. Of the 51
mains that rewrote in a comparison of old and new, only Absolum's changed: its four tables atmain+0x1ed2dc,+0x1ed4fc,+0x1ed71cand+0x1ed8cc, based in x30, went from 65,536 pads to 445, 373, 301 and 257, each its table's largest entry + 1, and the patch area from 3.7 MB to 570 KB. - Check:
dm/tools/tests/test_jump_solver.py(writes between the check and the load, base clobbers).
A compare that guards nothing taken as a jump table's bound
- Symptom: no failure seen on a game.
jump_offsetsandjump_adr_offsetscould read a table with the wrong size and report nothing: on a synthetic site with a second compare between the real check and the load (cmp w18,#4; b.hi exit; cmp w18,#1; ldrsw x18,[x4,x18,lsl #2]) they returned 2 targets where the check allows 5, so three cases had no landing pad. - Cause: the walk back from the table load took the nearest
cmpof the index as the bounds check without looking at what acts on it. A compare bounds the index only through the branch that follows it. - Fix: now the jump solver, where only a branch on the compare's flags narrows anything, on each of its two edges. Before it,
guarded_count(patch_nso.py) took a compare only when, between it and the load, the first branch on an unsigned condition comes with the compare's flags still in place (no instruction that sets them and no call in between; a store, or acbz, changes nothing):b.hiout of the dispatch gives N + 1 entries andb.hs/b.csgives N, which had been read as N + 1;b.lsorb.lo/b.ccinto the dispatch counts the same way when the instruction before its target is ab,brorret, so the failed check does not fall into it. A compare with no such branch only sets the flags, and the walk goes on to the check before it. With none the site is refused, goes on to the other recognizers and ends in thejump tableassertion, as before for a site with no compare.half_countkeeps its own form (b.hi,b.hsorb.csright after the compare). - Found on: reading the code (GitHub issue #977). Of the 27 modules of 6 games rewritten before and after (Super Smash Bros. Ultimate 13.0.5, Super Mario Bros. Wonder, Pokémon Legends: Z-A, Pokémon Pokopia, Mario Kart World, The Legend of Zelda: Ocarina of Time), 165 sites reach these recognizers with a compare, all in Smash's
main,rtldandsubsdk0: every one iscmp; b.hion the way to the load, one with a store between the two (main+0x39be740), so none is refused or resized. - Check:
dm/tools/tests/test_jump_solver.pytest_the_branch_that_acts_on_the_compare_decidesandtest_b_ls_into_the_dispatch. - Open: no module with
b.hs, or with a branch into the dispatch, was on the drive, so those two forms are tested synthetically only.
Byte tables indexed by x30 (capstone register names)
- Symptom:
jump table <addr>assertion on a byte table indexed by x30 (adr x18, #L; ldrb w30, [x14, x12]; add x18, x18, x30, lsl #2; br x18). - Cause: capstone names x30
lr(and x29fp), so the index register looked like no register and theldrbnever matched. - Fix: the byte / halfword table check maps those names back to 30 / 29.
- Found on: Hyrule Warriors: Age of Calamity
main+0x138216c.
Byte tables whose add is far from the br
- Symptom:
jump table <addr>assertion on a byte table whoseaddis far from thebr(adr x18,#L; ldrb w0,[x17,x15]; add x18,x18,x0,lsl #2, then 17 register moves beforebr x18). - Cause: the byte / halfword search looked 16 instructions back.
- Fix:
jump_bytes_farlooks 32 back, requires that nothing writes x18 between theaddand thebr, and runs only when every other form has failed, so sites that rewrote before come out the same. - Found on: Octopath Traveler 0
main+0x37f9bc8: one of the 12br x18sites in thismain. - Note: a census of all the
br x18sites first (each shape within 16 / 32 / 48 instructions) saves a 12-minute rewrite per site.
Indirect calls through x18
- Symptom:
jump table <addr>assertion inpatch_nso.py, in a Unity / IL2CPPmain, at ablr x18. - Cause: the compiler made an indirect call through
x18(blr x18). - Fix: the rewriter calls through
x16with the original return address, so C++ unwinding still finds its frames (site_blr). - Found on: Fire Emblem Engage
main: 1 call (beside 7 jump tables and 1spwrite). - Check: Super Mario Bros. Wonder's output stays byte-identical.
Indirect tail calls through x18 in IL2CPP thunks
- Symptom:
jump table <addr>assertion on abr x18with no table in front of it. - Cause: not a jump table but an indirect tail call: an IL2CPP thunk loads the method pointer with
ldr x18, [x0, #0x18], moves its stack arguments with every other scratch register (ldr x16, [sp],ldp x17, x15, [sp, #8], …) and ends withbr x18. - Fix: when neither table form is found, the last write of
x18is a plain load and thebrends the function, it becomesx16 = guest x18; br x16(tail_call/site_br_call; at a callx16/x17are free, as forblr x18). It is tried only where the rewriter used to stop. - Found on: Ace Attorney Investigations Collection (Unity 2022.3 IL2CPP):
main+0x1d271bcand+0x204ebec. - Check: every module the rewriter accepted before comes out byte-identical.
Compare and swap of a register pair that is x18, x19
- Symptom:
RuntimeError: subst fail <addr> caspal x18, x19, x4, x5, [x16]inpatch_nso.py(subst, fromsite_plain). - Cause:
casp,caspa,casplandcaspaltake the compare pair (Rs) and the new-value pair (Rt) as an even register and the next one.substrenamesx18alone, andxS, x19is no pair, so no encoding disassembles as the original withx18replaced. - Fix:
site_casp, chosen bycasp_pair18(the encoding, either pair atx18) beforesite_plain, moves the pair to a free even pairP, P + 1:Pis loaded from the slot K18 andP + 1copied fromx19, and the instruction runs with the pair renamed. The instruction writes the compare pair with the memory's old value, so for a compare pairPthen goes back to the slot andP + 1tox19; a new-value pair is only read. The memory access is still the one instruction, so it stays atomic.P,P + 1and the slot address's register are saved belowspand restored. A base registerx18is a single field, whichsubstrenames as before. - Found on: Sonic Frontiers Definitive Edition
main+0x19ce5c4, in a 128-bit compare and swap loop: the only one of the 18,315x18sites inmainthatsubstcannot rename. - Check:
test_x18_casp.pychecks that no block namesx18and keeps onecasp, and runs the blocks with unicorn (optional): a swap that succeeds and one that fails with the compare pair atx18, a new-value pair atx18, and a 32-bit pair, whose writes clear the upper halves. A module without such an instruction takes no new path: the rewriter stopped on every one before.
Unframed pointer tail calls followed by compiler padding
- Symptom:
AssertionError: jump table d29e68while rewriting Moving Out 2 1.3.315, orjump table 478a7b4on Hello Kitty Island Adventure 2.17.2 (4a521d4in 3.0.0). - Cause: Moving Out 2 loads its method pointer with
ldp x18,x17,[x17,#0x138], moves caller stack arguments and ends withbr x18, followed by oneudf #0padding word before the next unwind entry. The terminal-tail rule accepted onlyldrand required the branch to be the last decoded instruction. Hello Kitty Island Adventure has the same unframed thunk shape withldr x18,[x0,#0x18]and two trailingnopwords; the padded-tail rule initially accepted onlyudf #0. - Fix: accept a plain paired pointer load as well as a single load when every decoded instruction after the tail is
noporudf #0, with contiguous decoding, straight-line argument moves and memory transfers, and no writes to SP, FP or LR, including their 32-bit aliases and writeback. The last write to eitherx18orw18must be the pointer load. Branches (including those entering the padding), calls, nonzero traps, decoding gaps and framed thunks do not match this fallback. NOPs and traps differ when executed; this proof leaves the suffix unreachable from the straight-line body after its unconditional tail branch. The terminal-tail rule and other nonterminal-tail checks are unchanged. The binding is the general rewriter's instruction shape, with no engine, game or build gate. - Found on: Moving Out 2 1.3.315,
mainbuildc552b6464e7348a7bb261a708b353137, at+0xd29e68. Hello Kitty Island Adventure (010027901C89C000) 2.17.2 and 3.0.0, reported with disassembly and rewrite results in issue #2923. These are rewrite-stage findings, not local gameplay validation or game profiles. - Check:
dm/tools/tests/test_tail_call.pycovers synthetic single and paired loads, zero, NOP and mixed padding, argument stores and rejection of branches into the padding, frame changes, pointer clobbers and missing instructions. A NOP followed by live code or a nonzero trap is rejected; the whole suffix must be padding.
Loaded method-pointer tail call before an error block
- Symptom:
jump table 53e9cwhile rewriting Warm Snow 2.1.4's Unity IL2CPPmain, orjump table 108bb70on Ori and the Blind Forest: Definitive Edition. - Cause: a framed IL2CPP method loads a method pointer into
x18(ldr, orldpwith the next field), moves its arguments, restores its frame and executesbr x18, with code after thebr: error blocks in a small thunk, the function's other paths in a larger one. The terminal-tail recognizer requires the jump to end the function. - Fix: keep the terminal rule, which proves no frame, unchanged. For a
br x18with code after it,tail_callproves that the frame is gone, because a jump inside a function needs that function's frame. A wrong accept turns a jump table into a call without any error, so what is not proven stays atjump table <addr>. It holds for both frames:- Pointer: the last write of
x18isldr x18, [xN, #imm]orldp x18, xM, [xN, #imm]. - The path to the
br: no call or jump after that load or the frame restore, whichever is first, no branch or store after the restore, and no branch from anywhere lands past the restore. A guard may land before it: real code skips a reload of the pointer that way. - Frame registers: nothing else on the way writes
sp,x29orx30, except thatx29may be set once to the saved pair's address, and no branch re-enters the frame's setup. - Stack stores: a fixed offset from
spor the setx29, whose bytes stay clear of the saved pair; a register offset or writeback is rejected, and so is any exclusive or atomic access, whatever its base, which the rule does not model. - After the
br: no branch comes back to thebror ahead of it, and no direct call lands in the function. - A 16-byte thunk (
stp x29, x30, [sp, #-0x10]!; mov x29, sp, restored by the instruction before thebr) proves more, as Warm Snow's does: no calls, no stores through other bases, every guard goes to the code after thebr, at least one does, and that code is error blocks that hold a call out of the function, end in a call, a trap or a branch among themselves, and hold noret,brorblr. - A function (
sub sp, sp, #Nfirst,add sp, sp, #Nright before thebr,x29, x30saved to and restored from one slot inside the N bytes) is ordinary compiled code: its body may branch, loop and call, as IL2CPP's lazy init does, its stores through other bases cannot be proven apart from its callees' and are allowed, and any of its other paths may follow thebr. A jump through another register in its body has unknown targets and is rejected.
- Pointer: the last write of
- Found on: Warm Snow 2.1.4,
mainbuild306fc054203275803dcbceba7fb7c392, at+0x53e9c. Ori and the Blind Forest: Definitive Edition,mainbuild228b944fcb08ae56180369be66727558, at+0x108bb70,+0x108ca70,+0x13ff8f0,+0x14008a0. - Check:
dm/tools/tests/test_tail_call.pycovers both forms and rejects each broken proof with synthetic AArch64 instructions; no game assets are required by the tests. The function form was measured on real framed tail calls through other registers in Unity mains, whose shapes it must accept.
Exclusive windows
Branches within an exclusive window
- Symptom:
AssertionError: retry block overlaps a window 34b790while rewriting Trails in the Sky 2nd Chapter 1.0.4main. - Cause: a conditional branch to the store inside its own exclusive window was mistaken for an out-of-line retry. The same window also contains an unconditional branch, which the window copier did not relocate.
- Fix: branches within the same window stay in its copy. Unconditional branches are relocated to the copy or an exit stub; for windows containing one, a control-flow check rejects exits with a live reservation. Direct entries into newly accepted windows from another function are rejected. A retry copy cannot branch into the uncopied middle of a window. Indirect entries outside the existing jump-table checks are not proven absent.
- Found on: Trails in the Sky 2nd Chapter 1.0.4 (01007A2027548000). Its
mainrewrites with the fix; gameplay remains unverified.
Exit stub order in exclusive windows
- Symptom: job system hangs; a queue claims thousands of tasks but every slot is empty.
- Cause: in an
ldxr … cmp … b.ne out … stxr … cbnzwindow, the rewritten stub emitted its exits in the wrong order, so successful stores took the failure path. - Fix: emit the fall-through exit first (
patch_nso.pysite_window). - Found on: Super Mario Bros. Wonder: 82 such windows. D2R had no such windows.
Out-of-line retry blocks of atomic updates
- Symptom:
branch into window <addr>assertion. - Cause: the compiler moved an atomic update's retry path out of line: the failed
stxrbranches to a blockldxr; cmp; b.eq <the stxr>that re-enters the window at its store. That block cannot jump into the window's patch copy (thex18stand-in would be loaded between its exclusive load and the store). - Fix: the retry block gets a copy of its own: the retry block and the window's tail from the store on, under one prologue (
retry_block/site_retry_window). - Found on: The Legend of Zelda: Tears of the Kingdom 1.4.3
main, 8 sites.
A window never spans a second exclusive load
- Symptom: branches to an
ldxr … stxrloop's head landed mid-window. - Cause: before this rule, a retry block's
ldxropened a window that ran on into the next, unrelatedldxr … stxrloop (main+0x5a4674). - Fix: a window never spans a second exclusive load.
- Found on: The Legend of Zelda: Tears of the Kingdom 1.4.3
main(with Out-of-line retry blocks of atomic updates).
adrp inside an exclusive window
- Symptom:
AssertionError: 0x…insite_windowon anadrpinside an exclusive window (ldaxr x9,[x9]; cmp x9,x25; b.ne out; adrp x10 + add x10(the same address again, for the store);mov x18,x26; stlxr w9,x8,[x10], then loads andcbnz w9back). - Cause: a window that uses x18 is copied into the patch area, and an
adrpthere would build another page. - Fix: it is re-encoded for the copy's address with the same target page (x18 as its stand-in), in both window copiers (
window_adrp). - Found on: Pikmin 4 1.1.1 (Unreal Engine 4.26.2)
main+0x43da14c. - Check: only windows that stopped the rewrite change, so every other module rewrites byte for byte as before.
Patch area reach
Halfword jump table landing pads sized to the largest entry
- Symptom:
B()assertion at a spin wait: a branch into the patch area beyond the ±128 MB abreaches. - Cause: each halfword jump table (
ldrh wE, [xT, xI, lsl #1]; …; adr x18, #L; add x18, x18, xE, lsl #2; br x18) got a landing pad for every one of the 65,536 values an entry can hold (768 KB a table), whatever the switch's size: thatmainhas 51 of them, 40 MB, and the spin-wait stubs placed after them were out of reach. - Fix: each table is padded only up to its largest entry, read from the table the jump solver proves (
half_padsinpatch_nso.py); a table it cannot prove keeps all 65,536. With the first reader (half_count, a walk back to the bounds check and the base), 7 of the 51 kept 65,536, and the patch area went from 42 MB to 7.9 MB. - Found on: Animal Crossing: New Horizons 3.0.3
main, 63 MB of text. - Check: in the other titles' modules only such tables changed: one in the
sdkof several SDK 11–20 builds (936 to 1,320 pads), 1 to 6 in somemains (Tears of the Kingdom, Breath of the Wild, Silksong, Monster Hunter Rise, Absolum, STEINS;GATE RE:BOOT) and one in some movie and middlewaresubsdks.
Patch area before the module base for a large bss
- Symptom:
B()range assertion inpatch_nso.py(site_plain), only for one module. - Cause: its bss is 1.8 GB, the engine's static heap, so a patch area appended after the image starts 1.9 GB from the code and no
B(±128 MB) reaches it. - Fix: when an appended patch area would start beyond 112 MB, the rewriter puts it 32 MB before the module base (negative
PATCH_OFF).patched.binthen holds only text + ro + data (FILE_IMAGE_LEN) followed by the patch bytes, and the loader maps the bss and the key page as zero pages (IMAGE_SIZE). The Mac loader, the iOS embedding (gen_embed.py: no bss in the executable) andQueryMemoryhandle both layouts. - Found on: Metroid Dread
main. - Check: Mario's and Engage's output is byte-identical to before.
Frame-step state with a front patch area
- Symptom:
frame step state pageassertion when aFRAME_STEPprofile is added to a module with a large BSS. - Cause: frame-state allocation required a patch area after the image, although the stubs can address the state page through ADRP with either layout.
- Fix: for a front patch area, reserve a zero-filled 16 KB state page immediately after the key page by extending
IMAGE_SIZE. The existing Mac and iOS loaders map it with the BSS; no padding is added to the game binary. Ordinary modules retain their existing layout. - Found on: ASTRAL CHAIN.
Patch area right before the base for a long text
- Symptom:
B()range assertion, thenpatch area of … bytes does not fit in the … before the base. - Cause: with the patch area 32 MB before the base, sites near the end of the text are more than 128 MB away.
- Fix: when the text ends within 32 MB of the reach (
BIG_TEXT), the patch area goes right before the base: the stubs follow the sites in address order, so each site's stub is about as far from it as the text is long. The first pass tries the gap that keeps every site in reach (2.6 MB here); when the patch area is larger (3.6 MB, 34,322 sites), the rewriter runs itself again with exactly that size (DM_PATCH_FRONT, set only by the rerun) andB()checks every branch. - Found on: Monster Hunter Rise
main: 125.3 MB of text.
Two patch areas for a text longer than a branch reaches
- Symptom:
main: patch area of 0x6b9d38 bytes does not fit in -0x39c0000 before the base; rewriting again with 0x6c0000, then aB()range assertion insite_window: the gap before the base came out negative. - Cause: a text longer than the ±128 MB a
breaches has no place for one patch area from which every site is in reach: before the base the last sites are too far, after the image the first ones. - Fix: such a module (
TWOinpatch_nso.py: the text alone ends past the reach) gets two patch areas. The front one, 16 MB before the base, takes the sites belowSPLIT(128 MB less the front area and 1 MB of margin for a stub's exits past its site); the back one, right after bss, the key page and the frame step page (BACK_OFF, 64 KB aligned), takes the others. A site's stubs and their branches back stay in its own area (use_area); when the front sites need more room, the rewriter runs again with exactly that size, andB()checks every branch. The file is the image, the front area padded to 16 KB, then the back area;fixups.tsvaddsBACK_OFFandBACK_LEN, andIMAGE_SIZEcovers the back area. The Mac loader copies it toBACK_OFFand seals it read-only and executable, the iOS embedding gives it a fourth section (gen_embed.py:__TEXT,__dm<name>x2) that the loader remaps there, andsvcQueryMemoryreports it as CodeData+RX like a patch area after the image (data and bss end at it). A module that does not need it is rewritten byte for byte as before. - Found on: EA SPORTS FC 27
main(1.8d.310c): 185.6 MB of text, 177,058 sites; 3.9 MB of stubs in front and 3.2 MB atBACK_OFF0xdec0000.
Split point within the back area's reach
- Symptom: a
B()range assertion insite_plainon the branch back to the site, in a module that takes two patch areas. - Cause:
SPLITonly kept the front area in reach. The back area sits after ro, data and bss, so when those are large it is more than 128 MB from the sites just above a split set by a 16 MB front area: hereSPLITwas0x6f00000and the back area at0xfa40000reaches down to0x7a40000. - Fix:
SPLITis also no lower thanBACK_MIN,BACK_OFFless the reach plus the same 1 MB of margin. When that lifts it, the front area's first pass takes the gap up toBACK_MINinstead of 16 MB, so the front area still reaches every site below the split; the rerun with exactly the size its sites need works as before, andB()checks every branch. A module whose back area already reaches the 16 MB split (EA SPORTS FC 27) is rewritten byte for byte as before; one where no split reaches takes hops. - Found on: Hello Kitty Party Land
main(1.0.2): 151.8 MB of text and 98 MB of ro, data and bss after it;SPLIT0x7b40000, 1.7 MB of stubs in a 3.75 MB front area (no rerun) and 123 KB atBACK_OFF0xfa40000.
Hops for sites neither patch area reaches
- Symptom:
AssertionError: no split reaches: the back patch area reaches no site below 0x9480000, too close to the front area's reachinpatch_nso.py, before any site is rewritten. - Cause: 185 MB of text and 90 MB of ro, data and bss after it. The front area before the base reaches sites up to about 127 MB, the back area after bss (
BACK_OFF0x11380000) sites from 148.5 MB (BACK_MIN), and the 21 MB of text between them (1,190 x18 sites and 669mrs tpidr_el0) has no executable memory within ±128 MB that is not the module itself: no place for a patch area reaches them. - Fix: a branch between the code and a patch area that a
bdoes not reach goes through a hop (reach_via,BX): abwritten into a word of the text that no path runs, within reach of both ends, as a linker's range extension thunk does. Those words are the alignment padding before functions: nop or zero words right before an unwind entry's start, after ab,br,retorbrk, and fewer bytes of them than the start's alignment. One hop serves every branch to its target that it reaches. WithGAP(BACK_MINpast the front area's reach), the sites between the two areas' reach take hops through either area. Every branch into a stub (put_branch) and every branch from a stub back to the code goes throughBX, which is a plainbwhenever that reaches. - Found on: Resident Evil 4
main(v131072): 5,647 hops in 600,000 padding words, 0.76 MB of stubs in front and 1.25 MB atBACK_OFF; no direct branch, conditional branch oradrof the original text lands on a hop.
Distributing branch hops between patch areas
- Symptom:
no padding word for a hopon a branch back to a site in a large module. - Cause: every site between the front and back reach went to the back area. There were 20,564 sites in that gap in Minecraft, and the back area could reach only 21,639 padding words; entry and return typically need one each.
- Fix:
patch_nso.pydivides those sites between the front and back areas in proportion to their reachable padding. Individual branches still go through the checked branch encoder and fail if no suitable padding exists. Offsets and executable sections keep their existing layout. - Found on: Minecraft for Nintendo Switch 1.26.62, with 261.8 MiB of text and 39,859 emitted hops in the completed rewrite.
Cuts and observation gates
Observation gates on any relocatable instruction
- Symptom:
observation gate neither at a function entry nor after a bl;observation gate neither at a function entry, after a bl nor before a callon an epilogue. - Cause: the rewriter assumed the host may change x9–x17 in a gate. So a gate was placed only where they carry nothing: a function entry, after a
bl, or (from 2026-10-22,scratch_dead) where the straight-line code ahead writes them before reading them. The assumption never held. Since the first host, the gate frame (dm/host/entry.S,_dm_gate) has saved x0–x28, the vector registers and the flags and restored them, and the gate block borrows only x29 and x30, which it restores from the stack. - Fix: since 2026-10-31 there is no placement rule: any instruction
site_obscan relocate takes a gate. A register changes only when the callback writes it (OBS_STDALLOC_INIT's x2,OBS_UE_REGION's size register and x1). - Found on:
- DRAGON QUEST VII Reimagined: the gate on
mov x0, x19atmain+0x32758e4, after a cutbland anadrp. - Pikmin 4: the gate on
ldp x29, x30, [sp, #0x10]right after the cut allocator constructor call,main+0x353f78c. - Both gates were removed on 2026-10-30: the engine-wide allocator rule puts its gate on the cut call itself (Unreal's FMallocBinned3 replaced by the host allocator).
- The engine region's gate sits on a store that reads x10 (
str x1, [x10, #0x280], Octopath Traveler 0main+0x12e20), which the old rule refused: Unreal's engine address region and its options.
- DRAGON QUEST VII Reimagined: the gate on
- Note: the gate table takes the original instruction as a word value (
aa1303e0), the cut table as bytes (e00313aa).
Functions, unwind entries and data in text
Code before the first unwind entry is one function
- Symptom:
jump table <addr>assertion on an ordinary byte table near the start of the text (adr x18; ldrb w0,[x17,x16]; add x18,x18,x0,lsl #2; br x18). - Cause: the module has no unwind entry before
main+0x6a75d4, andfunc_ofmade every site before the first FDE a function of one instruction, so no form saw theadrin front of thebr. - Fix: the text before the first FDE is now one function, from the end of the data block before it (or the text's start), as a gap between two FDEs already was (
func_of). - Found on: FINAL FANTASY RESONANCE 1.0.1
main(Unreal Engine 5.6.1):main+0x219234. - Check: of the 120 modules of 33 games on hand, only DRAGON QUEST VII Reimagined's
mainhas otherx18sites there (110 before+0xb310, none in a window or abr x18), and its rewrite is byte-identical.
Long functions analysed in pieces
- Symptom: the rewrite never finishes, the Mac swaps, the rewriter's footprint reaches 100 GB.
- Cause: a stretch without FDEs is one function to
func_of, and its detailed disassembly costs about 880 bytes an instruction once built (2.6 KB while capstone builds it): 21.6 million instructions. In FINAL FANTASY RESONANCE'smain, 82 MB atmain+0x6c4f88–+0x59220c0and the 6.65 MB before the first FDE have no unwind entries. Octopath Traveler 0 (71 MB), DRAGON QUEST XI S (68 MB) and DRAGON QUEST VII Reimagined (two of 23 MB) have such stretches too; they got through on a quieter Mac with the compressor and swap. - Fix: a function longer than 256 KB is now analysed in pieces (
piecesinpatch_nso.py), cut only right after aret/br/bwhere no conditional branch and nobwithin 64 KB crosses, so a window, a jump table's bounds check and table base, and a retry block stay in one piece. After all pieces, every fartherb/bland every jump table target is checked against the windows and retry blocks of all pieces. Countingbup to 1 MB left only 21,385 cut points in the 82 MB (tail calls between neighbours) and pieces of up to 6.5 MB; with 64 KB there are 185,228, and no piece is over 256 KB (the two stretches: 28 and 344 pieces). The rewrite then takes 13 minutes at about 2.7 GB resident on a loaded Mac. - Found on: FINAL FANTASY RESONANCE 1.0.1
main; also Octopath Traveler 0, DRAGON QUEST XI S: Echoes of an Elusive Age – Definitive Edition, DRAGON QUEST VII Reimagined. - Check: DRAGON QUEST VII Reimagined's
maincame out byte-identical to its rewrite by the previouspatch_nso.py. FINAL FANTASY RESONANCE's came out the same as withbcounted up to 1 MB (3 and 136 pieces), and DRAGON QUEST XI S's (292 pieces) and Octopath Traveler 0's the same as with 1 MB pieces andbwithin 256 KB (75 pieces for DQ XI S), so the analysis does not depend on where the cuts fall.
Disassembly goes on after undecodable words
- Symptom:
KeyErroratsite_brfor abr x18that is an ordinary byte jump table. - Cause: capstone stops at the first word it cannot decode, and the function held a trap word (
0xe7ffdefe,main+0x6b34540) before the jump table, so the table was never analysed. - Fix: function disassembly now goes on after undecodable words (
disasm_fn). - Found on: Monster Hunter Rise
main+0x6b346d0.
Data blocks at the start of the text
- Symptom:
RuntimeError: 788 ldr x18, #0xd1eb0inpatch_nso.py, or any rewrite site in data. - Cause: the text segment starts with 1.7 MB of data (
main+0x0–+0x1b5000, high-entropy, no FDE covers it, and noadrpor relocation points into it): 62% of its words do not decode, and 6,858 of the rest read as instructions that usex18, plus three "svc" words with numbers such as#0x91e7. The linear sweep rewrote them all. - Fix:
dm/tools/nso_code.pyfinds such data blocks: a stretch of at least 4 KB between the.eh_frameFDE ranges in which more than a quarter of the words do not decode. The sweep skips them (DATA_BLOCKS, logged asdata blocks left alone), and so doesinsn_census.py, whose counts then match the rewriter's again (11,744x18sites in Absolum'smain). Code without unwind information is still swept: it decodes (Absolum's zlib atmain+0x75261c, libunwind's register restore atmain+0x28dbd4). - Found on: Absolum
main(.NET NativeAOT). - Check: no module of the 19 other games on hand has a data block, and their rewrites are byte-identical.
NRO metadata inside the text segment
- Symptom:
RuntimeError: 44 ldr x18, #0xfffffffffff40370while rewriting an NRO. - Cause: an NRO's text segment includes its metadata header. The arbitrary build ID at
+0x40can decode as instructions;magic_0898_2015.nrocontains a literal load intox18at+0x44. The ordinary 4 KB data-gap heuristic cannot exclude this 120-byte header. - Fix:
nso_code.data_blocksexplicitly excludes+8..+0x80when the image has theNRO0header. The initial entry branch and MOD0 pointer remain intact, and scanning resumes at the first possible function. NSO scanning is unchanged. - Found on: FINAL FANTASY X/X-2 HD Remaster, 1,432 registered NROs.
- Check:
test_nro_header.pyruns the real rewriter on synthetic NROs whose build IDs decode as anx18load orbr x18, checks the header byte-for-byte, and checks that an actualx18instruction immediately after it is rewritten. Code before the first unwind entry is covered too: per-function analysis must not reenter the header even when the linear scans exclude it.
Stack and system registers
An x18 scratch spill overwrites a live stack temporary
- Symptom: crackle in Super Mario Sunshine's 3D file-select menu and gameplay, with both stereo and six-channel output. The crackle is already in the PCM Hagi submits to AudioOut.
- Cause: Hagi's pitch resampler restores
spwhile the tail of its 80-entry phase table is still live below it. The plain x18 stub forcsel x11,x11,x18,gtsaves two registers at[sp-16, sp)and overwrites entries 72–79 before Hagi reads them. - Fix: a conditional select with one x18 source can branch on the original flags. The x18 arm loads
K18using the destination and one temporary without spilling to the guest stack. The rewriter uses this form only when every path in the unwind function overwrites the temporary before reading it or returns normally. It keeps the existing lowering when it cannot prove that a temporary is dead. - Check: on Sunshine 1.1.4, 24 of 30 synthetic resampler cases differed from the original with the old rewrite. All 30 match the original PCM and final state with the new rewrite, and all returns restore
sp.test_x18_select.pychecks both source positions and widths with an unmapped guest stack, and checks that live registers are rejected. - Found on: Super Mario Sunshine (issue #2623).
Stack pointer writes through x18
- Symptom:
jump table <addr>assertion inpatch_nso.py, in a Unity / IL2CPPmain, at analloca(mov sp, x18). - Cause: the compiler wrote
spfromx18for analloca(mov sp, x18). - Fix: the rewriter restores its scratch registers relative to the old
sp(site_sp). - Found on: Fire Emblem Engage
main: 1spwrite (beside 7 jump tables and 1 call). - Check: Super Mario Bros. Wonder's output stays byte-identical.
Stack arguments reserved with sub sp, sp, xN
- Symptom:
CRASH sig=10 addr=0on anstprelative tosp, withspnot a multiple of 16 (main+0x2bbba4,sub sp, sp, #0xc0thenstp d15, d14, [sp, #0x60]with sp ending in…9dc). - Cause: Horizon leaves stack alignment checking off for user code; Apple's kernel faults on an sp-based access while sp is misaligned. The game's script engine calls native functions through six hand-written bridges (
main+0x17c140and five more beside it): each reserves the callee's stack arguments withsub sp, sp, x19, x19 being their sizes added up (4 for one int,[x0 + 0x238]), and gives them back withadd sp, sp, x19after the call, so the callee ran with sp 4 bytes off. - Fix: the rewriter now sends every
sub sp, sp, xN(extended-register form, no shift) through a stub that rounds xN up to 16 first (site_sp_align); theaddthen gives back the same amount. Compiled code keeps such sizes 16-aligned, so there it changes nothing.insn_census.pycounts the sites assub sp, sp, xN. - Found on: Paper Mario: The Thousand-Year Door
main(its AngelScript call bridges). - Check: of the 22 games' modules on hand only this
mainhas the form (6 sites), so every other rewrite is byte-identical.
Stack frames of an odd size: sub sp, sp, #imm
- Symptom:
CRASH sig=10 addr=0 pc=main+0x4e8a18onstr x1, [sp]right aftersub sp, sp, #0x98, withspending in…8; the game runs until its UI changes screen for the second time (Civilization VII's first-run options: Continue, then Continue or Back). - Cause: the same alignment rule as Stack arguments reserved with sub sp, sp, xN, with an immediate. Civilization VII's
mainhas four hand-written blocks (main+0x4e8a14,+0x556914,+0x57e914,+0x57ec18) that save x1–x17 in a 0x98-byte frame aroundsvc #0x29(GetInfo with info type 0x55) and give it back withadd sp, sp, #0x98; the frame leavessp8 bytes off. These eight are the onlyspadjustments in its code that are not a multiple of 16. - Fix:
odd_sp_framesinpatch_nso.pyrounds both immediates of such a pair up to 16 (0x98 → 0xa0), in place; a frame of 0xff1–0xfff rounds to 0x1000, which only the shifted immediate holds (#1, lsl #12;sp_adjust). It takes a pair only when theaddwith the same immediate follows within 64 instructions and every instruction between leavesspalone, is a call or ansvc, or loads / stores withspas its only base, no writeback, inside the frame; a branch, anotherspwrite, a copy ofspor an access past the frame leaves it as it was.test_sp_frame.pycovers Civilization VII's block, aligned frames, calls inside a frame, an access past it, its last slot, writeback, a branch, aret, a copy ofsp, and asubwith noadd, and the 0x1000 encoding. - Found on: Sid Meier's Civilization VII (1.5.0.1): 4 frames in
main; itssdkand NRO have none. The host's GetInfo answers 0 for the unknown info type, so the block returns as it does on the console. With the rule the game got past the crash to its first-run Auto Save screen, and a 14-minute Mac session (49,800 frames) ended without a crash. The rule takes no frame in themain,sdkandsubsdk0of The Legend of Zelda: Tears of the Kingdom (v393216) or METAL GEAR SOLID 4 (0100D0B01C4F4000, v1), so their rewrites are unchanged.
System register reads that macOS traps
- Symptom: SIGILL / trap on a system register read.
- Cause: a newer SDK reads a register macOS traps (
CTR_EL0in SDK 16'sFlushDataCache). - Fix: rewrite to a constant (
patch_nso.py, thectrsite kind).
Relocations and module layout
Gate tables grow with the loaded modules
- Symptom:
FATAL gate overflowwhile loading rewritten modules, before the game starts. - Cause: the host used one fixed 32,768-slot hash table for every NSO and preloaded NRO, and stopped once their combined gate count exceeded 8,192. A module can fit by itself while the collection does not. The limit is in the host's dispatch index, not the rewriter's patch area.
- Fix:
hle.cgrows and rehashes the index duringload_modules, keeping its load factor at most one quarter. All NRO gates are registered during preload too; runtime NRO load/unload only relocates the already mapped modules. Guest dispatch reads the completed table without locks or allocations. Duplicate-address and unknown-gate checks remain in place. - Found on: Assassin's Creed III Remastered startup report, issue #3118. The capacity failure is reproduced with synthetic gates; the game's boot and rendering remain unvalidated.
Packed relative relocations (DT_RELR)
- Symptom: every pointer in
.data/ the GOT is a module offset, crashes everywhere. - Cause: SDK 20 modules pack their relative relocations as
DT_RELR(tag 36, size tag 35):mainhas 223,994 of them and itsDT_RELAonly symbol relocations. Each 8-byte entry is either an even offset (relocate it, move to the next slot) or an odd bitmap whose bits 1–63 stand for the following 63 slots; the addend is the slot's own value. - Fix:
relr_applyinloader.c;DM_LOADHASHandnvn_slots_got.pyread it too. The loader's log line counts them asrelr=. - Found on: The Legend of Zelda: Breath of the Wild 1.9.0 (SDK 20).
Regression rewrites register copied profiles twice
- Symptom:
regress.py checkstops before gameplay withCUTS of build ... in both ..., naming a revision profile and its copied harness profile. - Cause: shader builds use a writable profile copy for generated tables. Passing that copy to the rewriter exposes its
patches.pyalongside the revision's original, registering every cut twice. - Fix: registered games rewrite with the revision's original profile; provisional games retain their external profile path. Shader builds continue using their writable copies. The harness regression covers both selections.
- Found on: NieR:Automata geometry review, when comparing rewrites after reconciling PRs #336 and #416.
Rewriter performance
Parallel scans preserve rewrite output
- Symptom: packing spends most of the rewrite step on the x18 scan and the spin-wait search, using one core per module. Cancelling a parallel rewrite can leave its workers running;
DM_REWRITE_J=0or a negative value can silently omit spin gates, and the NSP script can ignore an explicit worker limit. - Cause: both searches analyse an unchanged image, but ran sequentially. A default SIGTERM exits without unwinding the pool's context manager. The spin search's job count assumed a positive worker count, and the NSP script always replaced the caller's setting with its automatic budget.
- Fix:
patch_nso.pyscans code ranges in 1 MB pieces and distributes spin candidates across forked workers. Each pool inherits the image and analysis state at that pass; workers return addresses, and the parent rebuilds accepted spin regions in address order before emitting patches. SIGTERM exits through Python's cleanup so the pool terminates and joins its children.DM_REWRITE_Jmust be a positive integer (1runs serially), checked before loading modules; the NSP script honours an explicit value and otherwise chooses its budget from the core and module counts. These changes apply to every NSO and NRO; patch selection and runtime semantics stay the same. - Found on: Breath of the Wild.
- Check: synthetic tests cover SIGTERM during active pool jobs, invalid counts and explicit worker limits through the packing script. The original speed measurements and module comparisons are in PR #761; their timings are contributor measurements, not local regression results. Local game validation is recorded in Breath of the Wild's note; other games and NROs have no new local runtime validation here.
Spin-wait search memory bounded
- Symptom: the rewrite step's memory keeps growing in
find_spin_regionsand the rewrite does not finish. EA SPORTS FC 27 1.8e'smain(185 MB of text) passed 24 GB withDM_REWRITE_J=1(reported in PR #3234). - Cause:
spin_inskept every decoded instruction (0.5–2.6 KB each with capstone details) inspin_decfor the whole search, per forked worker, even thoughfind_spin_regionsstrides heads by8 * WORKERSso cross-head reuse is effectively zero. In addition,spin_regioncalledspin_lock(T)(decoding 6 instructions) beforeDATA_BLOCKSandspin_quick(T, hi)filtered out non-candidates (44% of 931,397 heads on FC 27 1.8dmain), andspin_lock(a)decoded 6 instructions before checkinga's mnemonic. - Fix:
spin_regionnow checksDATA_BLOCKSandspin_quick(T, hi)before decoding anything,spin_lock(a)decodes lookahead instructions only whena's mnemonic can start a lock or test sequence, andspin_regionclearsspin_decin afinallyblock after every head. The cache therefore holds at most the ~135 instructions in[T - 4, hi + 20]for the head being analysed; returned regions keep the instruction objects they need andspin_emitdecodes nothing. This holds for every NSO and NRO. - Found on: EA SPORTS FC 27 1.8e.50bc.
- Check:
test_spin_waits.py(cache cleared on found and rejected heads, zero decodes onspin_quick-rejected heads, no extra lookahead on non-lock instructions) andtest_rewrite_parallel.py. On a 1/64 worker slice of FC 27 1.8dmain(14,554 heads), total decodes dropped 39% (146,104 → 88,639) and time dropped 30% (2.59 → 1.80 s) with identical spin regions. A full parallel rewrite of FC 27 1.8dmain(185.6 MB text, 318 spin waits) finished at 2.20 GiB max RSS (down from >24 GB), and all 7 rewrittensdkoutputs were byte-identical againstorigin/main.
A pool's shutdown hangs on a worker that has just started
- Symptom: a rewrite never ends, using no CPU:
patch_nso.pywaits inwait4and one forked worker of the same command insem_wait, inmultiprocessing/queues.pyget, having run no job. It is rare and needs small jobs (about 1 in 6,000 pools of tiny jobs under load). Separately, a SIGTERM could be ignored until the rewrite ended, or leave workers behind. - Cause: workers inherited the Python SIGTERM handler that lets the parent exit through the pool's context manager.
Pool.terminatetakes the job queue's lock for good, sends each worker one SIGTERM and joins it with no timeout, so it needs that signal to end the worker. A handler only sets a flag, and Python clears flags in a new child, so a worker just forked lost the signal, then waited for that lock forever. Resetting SIGTERM in the pool's initializer alone does not help: the signal can land before the initializer runs. In the parent, the handler'ssys.exitcould also be raised during the pool's teardown, where it stopped a terminate halfway or was discarded in a destructor. - Fix:
in_parallelblocks SIGTERM across the fork, which keeps it pending in the kernel, and each worker restores the default action before unblocking it. In the parent SIGTERM acts only while waiting for results. A finished pool leaves bycloseandjoin, so no SIGTERM is sent. - Open: cancelling a rewrite still ends in
Pool.terminate, and a worker it kills while sending a result never releases the result queue's lock, so the parent can hang (Python's own limit; 2 in about 25,000 cancellations of a process doing nothing but pools, far rarer in a real rewrite, which spends its time in analysis). A rewrite that finishes never reaches it. - Found on: the Python tool tests (
discover -s dm/tools/tests), which hung for 2 hours in a test's small NRO; no game was seen to hang. - Check:
test_rewrite_parallel.pychecks that SIGTERM is blocked from the fork on and that a worker has the default action unblocked before any job, and sends SIGTERM during pool start and during teardown. The race itself is too rare and too slow to repeat in a test.
Mod code plugins
A mod's exefs plugin is left out, and its game files wait for it
- Symptom: a mod with an Atmosphère
exefs/(asubsdk<N>code plugin, usually built on exlaunch) beside itsromfs/boots to a black screen withDM_ROMFS_OVERLAYon its RomFS: the last file read (DM_FSLOG) is the mod's script (Pokémon Compass:script/lua/bin/release/main_dynamic.blua), then the main thread waits on a condition variable for good. The plugin registers the functions those scripts call. - Cause: the overlay only takes RomFS files; nothing loaded the plugin. Rewritten as it was, its start-up then stops on what exlaunch asks of Horizon:
patch_nso.pyfound no.eh_frame_hdr(devkitA64 links none); its module walk (FindModules) asserts the first module isrtld, which the host does not load; it takes its process handle fromGetInfo65001 (Mesosphere) and writes hooks throughMapProcessMemoryviews of module code; and it seedsstd::mt19937_64fromsvcGetSystemTick, which answered 0 inx0, sovirtmemFindAslrdrew the same address forever. - Fix:
scripts/prepare_mod.py <mod>rewrites a mod'ssubsdk<N>NSOs once into<mod>/exefs/nxnative/; on the Mac, with the mod's RomFS inDM_ROMFS_OVERLAY, the host loads them in numeric order beforesdk(hle_exl.c), andloader.creserves one contiguous virtual span for non-JIT startup modules so they sit in strict ascending load order with a 3-page slot belowmainfor the stand-inrtld.patch_nso.pyandmod_layout.pywalk.eh_framedirectly whenMOD0's.eh_frame_hdrrange is empty. When a mod plugin is loaded (or a manually loadedsubsdkcarries exlaunch's signature in.rodata), the stand-inrtldis populated belowmain;GetInfo65001 answers the current-process handle;MapProcessMemorymaps a writable copy in the free ASLR region andUnmapProcessMemory/ per-moduleDT_INITsync write only changed words back into the module's guest image through a sharedmach_vm_remapwritable alias (code_write.h), refusing any word in<module>.changed.tsv(verified againstbuild_id) or pastkey_page_off.svcGetSystemTickreturns the tick inx0as Horizon does. A mod'sexefs/mainis refused, and iOS skips mod code plugins cleanly (signed code pages cannot be written). - Found on: Pokémon Violet 3.0.1 (
v720896, a derived profile) with Pokémon Compass 2.1.1.1 (PR #3178, M3, macOS 27.2: 12 hooks inmain, none refused, reaches the new-game character screen). Not checked: playing past the character screen with Compass, other exlaunch plugins, plugins that replacemain.
Checking a rewriter change
Rewrite every extracted module of every title with the old and the new patch_nso.py and compare all outputs; only build_src.sha256 (the rewriter's own hash) may differ for titles the change is not meant for.