Skip to content

unity: read the pre-2019.3 serialized / Shader formats - #2

Closed
armyja wants to merge 1 commit into
seedds:mainfrom
armyja:unity-old-format-pr
Closed

armyja wants to merge 1 commit into
seedds:mainfrom
armyja:unity-old-format-pr

Conversation

@armyja

@armyja armyja commented Oct 16, 2026

Copy link
Copy Markdown
Contributor

What

Reading a pre-2019.3 Unity title needs four things the current reader does not do. Found while surveying Cuphead (Unity 2017.4.9f1, SDK 5.5.0.0, base v0); without them shader_split.py reports 0 shaders and exits silently (the serialized files are not even recognised).

# difference where
1 serialized file format 17 (the code took only 19..22) unityfs.py
2 TypeTreeNode without the trailing refTypeHash(u64) → the node is 24 bytes, not 32 unityfs.py
3 Shader subprogram table before 2019.3: one segment per platform, 8-byte {offset, length} entries (not 12-byte with a segment index) unityfs.py
4 program code before 2019.3: 0x10 header {?, ?, control size, code size} + control + code, one stage per subprogram, and the stage is not in the code shader_split.py

For (4) the stage comes from the Shader's m_ParsedForm passes (progVertex/progFragment/… m_SubPrograms[].m_BlobIndex); the new helper unity_stages() is used for that and is simply unused by the newer layout, where the program code carries its stages.

Evidence

Each one was pinned down against the file itself:

  • 17: is_serialized failed because of the version range; the <22 header layout the code already had (msz/fsz/ver/doff at 0, endianness at 16, little-endian metadata) matches (fsz == len, target_platform = 38 = Switch).
  • 24 bytes: the type tree's own string buffer starts at nodes_at + 24*nn, and with a 24-byte node node1 decodes to sensible offsets (type 0x80000348, name 0x800001ab, both high-bit → the common string table) while 32 does not.
  • 8 bytes: the single segment of a subprogram says count = 2 and the two entries (2856, 5432) and (20, 2836) tile it exactly (2856+5432 = 8288 = len(seg), 20+2836 = 2856), and offset 20 holds a subprogram version (201708220).
  • 0x10 + control + code: 0x10 + h[2] + h[3] = len(code) for every subprogram seen (0x10+2128+2304 = 4448, and three more), and code[0x10:0x14] is the control magic 0x98761234.

Result before → after:

0 shaders
3026 shaders (1511 pixel / 1515 vertex), 0 red lines
chain: 1412 variants, 1397 compiled, "绑定没解出槽号的着色器 0"

Scope

Only the two tool files. The Cuphead profile and its generated tables are not included: dmsh_chain.h / c1_full.tsv are computed from the local tool fingerprints (this machine has no Metal compiler, so its chain version is not yours), and you would regenerate them anyway. Happy to send the profile (game.tsv + tables) as a separate PR if you want it — with it the title's whole library reads, translates and resolves its bindings (the NVN layout measured by the census is Mario's 0x20 + 8r texture table, not Engage/D2R's 0x168).

Older Unity titles (2019.3 and before) differ from the ones the reader was
written for in four ways. Surveying Cuphead (Unity 2017.4.9f1, SDK 5.5.0.0)
without them finds 0 shaders; with them the title's whole library reads end to
end (3026 shaders, 1511 pixel / 1515 vertex) and the chain translates it with
no unresolved binding and no red line.

- serialized file format 17: `is_serialized` / `serialized_objects` took only
  19..22; the header and metadata layout below 22 is the one the code already
  assumed for <22.
- TypeTreeNode without the trailing refTypeHash(u64): below format 21 the node
  is 24 bytes, not 32 (verified against the type tree's own string buffer
  position: buffer = nodes_at + 24*nn).
- Shader subprogram table before 2019.3: one segment per platform and 8-byte
  {offset, length} entries, not 12-byte {offset, length, segment}. `offsets`
  being a scalar per platform is the discriminator.
- program code before 2019.3: a 0x10 header {?, ?, control size, code size} +
  control section + code area, one stage per subprogram; the stage is not in
  the code, it comes from the Shader's m_ParsedForm passes
  (progVertex/progFragment/... m_SubPrograms[].m_BlobIndex).

The m_ParsedForm stage mapping (unity_stages) also covers the newer layout,
where it is simply unused.
TianZuo555 pushed a commit to TianZuo555/nxnative that referenced this pull request Oct 17, 2026
Mario Kart 8 Deluxe's NVN module (subsdk0, build id d9de423e...) switches on a
jump table whose base is a function argument, not something the function
computes:

    0x1ae1cc  sub   w18, w13, seedds#3
    0x1ae1d4  cmp   w18, #0x1a
    0x1ae1e0  ldrsw x13, [x10, x18, lsl seedds#2]     <- table base in x10
    0x1ae1e4  add   x18, x13, x10
    0x1ae1f0  br    x18

`jump_offsets` recovers a table by walking back to the `adrp` + `add` pair that
builds its base.  Here there is no such pair, so it returns None and the rewrite
stops at `assert tgt, f'jump table {ins.address:x}'` -- `subsdk0` never gets
rewritten, so the title cannot be packaged at all.

Two sites in this module have that shape (0x1ae1f0 and 0x1b18ec), both with
27-entry tables of 32-bit self-relative offsets.  Each table was read out of the
module image and every entry checked to land inside the same function, which is
what the existing "no target into a window" assertion re-verifies at rewrite
time.

With this, all three modules rewrite:

    main     plain 3548  pcrel 23  cond 56
    subsdk0  plain 8119  cond 224  pcrel 17  br 2
    sdk      plain 6754  cond 97  pcrel 35  br 1  ctr 2  svc 57  gates 91

Also adds dm/games/0100152000022000/game.tsv, a survey-only profile for this
title: identity, build IDs, module list, RomFS marker and the memory partition
(measured -- nninitStartup asks SetHeapSize for 0xc1c00000, which succeeds with
the standard 0xCD500000 application pool).  The shader-related keys are
deliberately absent because there are no shader tables yet, so
`build_ipa_from_nsp.py` still stops before packaging rather than producing an
IPA that would not run.  The profile is what makes the survey run reach the
rewriter in the first place, so it belongs with this change.
seedds pushed a commit that referenced this pull request Oct 18, 2026
…ster

Cuphead (Unity 2017.4) main+0x1bb872c loads the table entry into x17 and only
the add writes x18: cmp w17,#7; ldrsw x17,[x15,x17,lsl #2]; add x18,x17,x15;
br x18. jump_offsets now takes the loaded register from the add; the walk
from the index back to the bounds check is unchanged.

Ported from GitHub pull request #1 onto the current jump_offsets (the PR's
other two shapes already pass since Link's Awakening's subsdk work). All 35
rewritable modules of the 9 extracted titles give byte-identical output.

Co-authored-by: Jeffrey Wang <11900676+armyja@users.noreply.github.com>
seedds pushed a commit that referenced this pull request Oct 18, 2026
…ity 2017.4)

- serialized format 17 is accepted; type tree nodes are 24 bytes before
  format 19 (the trailing refTypeHash u64 arrived with Unity 2019.1)
- before 2019.3 a platform's subprograms sit in one segment with 8-byte
  {offset, length} entries (the old scalar branch read 12-byte entries)
- before 2019.3 a subprogram's program code is a 0x10 header {?, ?, control
  length, code length} + control section + code area holding one stage; the
  stage comes from the Shader's m_ParsedForm, and a subprogram missing there
  is a red line

From GitHub pull request #2, with the node size cut at format 19 instead of
21 (formats 19 and 20 keep reading as before). Fire Emblem Engage (format 22)
splits to an identical package and tables.

Co-authored-by: Jeffrey Wang <11900676+armyja@users.noreply.github.com>
@seedds

seedds commented Oct 18, 2026

Copy link
Copy Markdown
Owner

感谢!四点里有三点我核对过都是对的:

  • 接受序列化格式 17;
  • 2019.3 之前子程序表项是 8 字节 {偏移, 长度}(原来那个分支按 12 字节读,是个从没跑到过的 bug);
  • 2019.3 之前的程序代码是 0x10 头 + 控制段 + 代码区,阶段取自 m_ParsedForm。

有一处需要改:TypeTreeNode 末尾的 refTypeHash(u64)是从序列化格式 19(Unity 2019.1,TypeTreeNodeWithTypeFlags)开始有的,不是 21。PR 按 ver >= 21 判断,会把格式 19 / 20(Unity 2019.1–2019.2)的文件按 24 字节节点读坏,而现在的 main 能正确读这两种格式。

另外两处小改动:

  • m_ParsedForm 里查不到阶段的子程序,PR 默认当顶点着色器;我改成报红线,免得悄悄出错;
  • 这几个文件从 20cba12 起注释只用英文(除 README 外都是),那次提交也改了上下文行,所以 PR 没法直接合并。

修改后的版本提交为 90d2992,注明是你发现的,提交带 Co-authored-by。

验证:Fire Emblem Engage(Unity 2020.3,格式 22)用新旧代码拆出的着色器包和三张表完全相同。Cuphead 的结果我这里没法复核(没有这个游戏);如果你用现在的 main 再跑一遍,还是 3026 个着色器、0 条红线,就说明移植没问题。

所以这个 PR 先关掉,再次感谢!

@seedds seedds closed this Oct 18, 2026
seedds pushed a commit that referenced this pull request Oct 18, 2026
…les (Tears of the Kingdom)

Tears of the Kingdom 1.4.3's main stopped the rewriter at three new shapes:

- An atomic update's retry path moved out of line: the failed stxr branches to
  ldxr; cmp; b.eq <the stxr>, which re-enters the window at its store
  (main+0x18598 -> 0x181fc, 8 sites). retry_block / site_retry_window give
  that block a patch copy of its own: the retry block and the window's tail
  from the store on, under one prologue, so no memory access falls between
  the exclusive load and the store.
- A window no longer spans a second exclusive load. A retry block's ldxr at
  main+0x5a4674 used to open a window that ran on into the next, unrelated
  ldxr ... stxr loop, and branches to that loop's head landed mid-window.
- Jump tables whose entries are relative to an adr, not to the table
  (main+0x393bb0: adr x18; ldrsw x1,[x17,x0,lsl #2]; add x18,x18,x1; br x18),
  with the bounds check on a copied register (mov w16,w15) and, once, a
  table base built far from the dispatch: every adrp + add pair building
  that register in the function is tried, and a table is accepted only if
  exactly one makes every target an instruction of the function.
  jump_adr_offsets is tried only where jump_offsets finds nothing.

main now rewrites (134 windows, 8 retry windows, 814 tpidr_el0 reads as in
the census). Every other extracted module of every title (31: Mario 1.0 and
1.2.1, Engage, Metroid, Sentinels, 3D World, Breath of the Wild, Link's
Awakening, Odyssey, Hades) gives byte-identical output; only
build_src.sha256, the rewriter's own hash, differs.
digitalhivehub added a commit to digitalhivehub/nxnative that referenced this pull request Oct 19, 2026
…ump tables)

TotK 1.4.2's main (SDK 20 compiler) has two shapes v0 and the other games
never had:
- Outlined LL/SC retry: a cold block 'ldxr; cmp; b.eq <stxr inside a window>'
  repeats the window's exclusive load and joins its store. When the cold block
  or the joined tail uses x18 they are copied as one window (no slot access
  between load and store); otherwise they run in place. The window scan no
  longer pairs an exclusive load with a store past a second exclusive load.
- Jump table 'adr x18, #anchor; ldrsw xE, [xB, xI, lsl seedds#2]; add x18, x18, xE':
  target = anchor + entry; the table base is found by following branches into
  the block (set 1385 instructions back, or in another block).
Both only apply where the rewriter used to stop: v0's three rewritten modules
are byte-identical to before. 1.4.2 main: 129 windows, 5 retry windows.
seedds added a commit that referenced this pull request Oct 21, 2026
…ster

Cuphead (Unity 2017.4) main+0x1bb872c loads the table entry into x17 and only
the add writes x18: cmp w17,#7; ldrsw x17,[x15,x17,lsl #2]; add x18,x17,x15;
br x18. jump_offsets now takes the loaded register from the add; the walk
from the index back to the bounds check is unchanged.

Ported from GitHub pull request #1 onto the current jump_offsets (the PR's
other two shapes already pass since Link's Awakening's subsdk work). All 35
rewritable modules of the 9 extracted titles give byte-identical output.

Co-authored-by: Jeffrey Wang <11900676+armyja@users.noreply.github.com>
seedds added a commit that referenced this pull request Oct 21, 2026
…ity 2017.4)

- serialized format 17 is accepted; type tree nodes are 24 bytes before
  format 19 (the trailing refTypeHash u64 arrived with Unity 2019.1)
- before 2019.3 a platform's subprograms sit in one segment with 8-byte
  {offset, length} entries (the old scalar branch read 12-byte entries)
- before 2019.3 a subprogram's program code is a 0x10 header {?, ?, control
  length, code length} + control section + code area holding one stage; the
  stage comes from the Shader's m_ParsedForm, and a subprogram missing there
  is a red line

From GitHub pull request #2, with the node size cut at format 19 instead of
21 (formats 19 and 20 keep reading as before). Fire Emblem Engage (format 22)
splits to an identical package and tables.

Co-authored-by: Jeffrey Wang <11900676+armyja@users.noreply.github.com>
seedds added a commit that referenced this pull request Oct 21, 2026
…les (Tears of the Kingdom)

Tears of the Kingdom 1.4.3's main stopped the rewriter at three new shapes:

- An atomic update's retry path moved out of line: the failed stxr branches to
  ldxr; cmp; b.eq <the stxr>, which re-enters the window at its store
  (main+0x18598 -> 0x181fc, 8 sites). retry_block / site_retry_window give
  that block a patch copy of its own: the retry block and the window's tail
  from the store on, under one prologue, so no memory access falls between
  the exclusive load and the store.
- A window no longer spans a second exclusive load. A retry block's ldxr at
  main+0x5a4674 used to open a window that ran on into the next, unrelated
  ldxr ... stxr loop, and branches to that loop's head landed mid-window.
- Jump tables whose entries are relative to an adr, not to the table
  (main+0x393bb0: adr x18; ldrsw x1,[x17,x0,lsl #2]; add x18,x18,x1; br x18),
  with the bounds check on a copied register (mov w16,w15) and, once, a
  table base built far from the dispatch: every adrp + add pair building
  that register in the function is tried, and a table is accepted only if
  exactly one makes every target an instruction of the function.
  jump_adr_offsets is tried only where jump_offsets finds nothing.

main now rewrites (134 windows, 8 retry windows, 814 tpidr_el0 reads as in
the census). Every other extracted module of every title (31: Mario 1.0 and
1.2.1, Engage, Metroid, Sentinels, 3D World, Breath of the Wild, Link's
Awakening, Odyssey, Hades) gives byte-identical output; only
build_src.sha256, the rewriter's own hash, differs.
seedds added a commit that referenced this pull request Oct 23, 2026
…uctions back (ASTRAL CHAIN 1.0.1 main+0x6db4a0, SDK 6: cmp w18,#5; b.hi; ldrsw x18,[x24,x18,lsl #2]; add x18,x18,x24; br x18). The function's first block loads six table bases with adrp + add into registers its loop keeps (x24 441 instructions before this load) and a later block one more (x3, 549 before the load at +0x6db70c); jump_offsets followed the base's writer chain 256 instructions back, and the rewrite stopped with jump table 6db4a0. Where nothing writes the base in those 256, its last attempt (far_base) follows the chain to the function's start (table_base far), through no call when the base is caller-saved, and accepts the table only when every target is an instruction of the function. The function-wide search jump_adr_offsets uses for a hoisted base (the one adrp + add pair that fits) finds two for x3 there, the other the local table of a br x17 further on. Three of that main's five br x18 sites need it, their targets checked by hand; main and sdk rewrite. It runs only where every other form has failed: the Tears of the Kingdom, Age of Calamity, Cuphead, DARK SOULS: REMASTERED, Luigi's Mansion 3 and Metroid Dread mains come out byte-identical (patched image and site list)
Amost- added a commit to Amost-/nxnative that referenced this pull request Oct 30, 2026
hle_cheats.c gains Atmosphère's store register (A), register conditional
(C0) and static registers (C3), and a layer of its own over the format,
all optional (a plain community file behaves as on a Switch):

- labels and EdiZon sections instead of "(empty)" cheats; a header glued
  to a code word and code on a header's own line are read as dmnt does
- "X - on" / "X - off" entries are one switch (the restore runs one pass)
- <build>.meta.tsv from scripts/cheat_anchor.py: sections, notes, typed
  values the panel may set (<build>.values), "set" cheats that run once,
  never-decrease (a host action: Atmosphère's VM keeps no state between
  passes, so its .txt entry is empty), the compiler's left-outs
- duplicate names saved as "Name seedds#2"; a new build compiled from the same
  source takes the previous build's toggles
- a dry run (dm_cheat_preview), a master switch and, on the Mac, safe mode
  after an unclean exit (dm_cheats_exit on every clean path), and a load
  report with Atmosphère's size limits
- a heap cheat before the game opens its heap waits instead of dying

scripts/cheat_anchor.py compiles never-decrease into that empty entry
and a meta row with the type and address. dm/host/tests/t_cheats.c
covers the opcodes and the layer; verified on FFCC 1.0.3 with the
compiled file (cave patch written once, stats and Mog every frame).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit c7ed066bc121cd3e98d0838417d36aa356417b46)
seedds added a commit that referenced this pull request Nov 2, 2026
The walk from the load back to the bounds check noticed copies and masks but no
other write: cmp w18,#4; b.hi; add w18,w18,#1; ldrsw x18,[x4,x18,lsl #2] read
entries 0 to 4 while the code uses 1 to 5, so one case's target was missing with
no sign of it. A site with a write of the index after its check, or a call with
a caller-saved index, is now refused, as jump_adr_offsets and half_count already
refuse a write. A refusal goes on to the other recognizers and ends in the jump
table assertion. Writes before the check do not count, which keeps the sites
check_before_copy takes.

A write that keeps the value, such as sxtw x0,w0, is refused too; no module on
the drive has one.

Checked: test_jump_copies.py (the new cases fail on the previous rewriter). Of the
345 unique modules on the drive, old and new recognition are the same on 281, and
60 more mains were scanned on the previous code with no site this refuses. That
includes Smash 13.0.5, EA SPORTS FC 27 and Well Dweller. Four could not be checked:
New Super Mario Bros. U Deluxe's main, sdk and rtld fail alike (no profile), and
Smash 1.0.0's main stops at a table the game's note already lists. No regress.py
run: nothing changes in the modules checked.
Aznracer pushed a commit to Aznracer/Mighty-Green-Kokiri-Kid that referenced this pull request Nov 8, 2026
…c[0] storage descriptor + x) + y, so Ocarina of Time's movie network (NDVE) addresses its feature maps through storage buffers instead of the raw pool table and write log; test and reference entry (PR seedds#2)
62fixolab added a commit to 62fixolab/nxnative that referenced this pull request Nov 9, 2026
…s frame interval and its dynamic resolution's bounds by the engine's own code, and the host frees the interval and scales the bounds (issue seedds#635)

The game ran at 30 fps, as on the Switch, and its settings offered no frame rate. HAL's engine paces itself by a vsyncs-per-frame int32 in its frame object (the game sets 2). The field also accepts 0, for no limit: the frame manager then steps the game by the time that really passed, so the host's present cap sets the rate. The dynamic resolution compares the GPU's frame time with two bounds in 60 Hz vsyncs chosen for 30 fps (1.95 and 1.7), so at 60 it would keep full resolution at frame times too long for the target.

dm/tools/hal_fps.py, run by patch_nso.py on main, finds both with no build ID and names them in the fixups (HAL_FRAME_PTR, HAL_FRAME_FIELD; HAL_DR_PTR, HAL_DR_HOP0..2, HAL_DR_FIELD):
- the interval: the frame manager's switch on the field (ldr wM, [xO, #F]; cmp wM, seedds#2; b.eq; cmp wM, seedds#1; b.eq; cbnz wM) followed by the 60 Hz vsync in nanoseconds (movz / movk of 0xfe502a), and the frame object's constructor, which clears that field and stores the address of its interface at +D into a global that no other code sets but to 0: the field is at [global] + F - D
- the bounds: the last of the engine's three heap roots (globals 8 bytes apart, each read by a function that looks up which of the root's heaps holds an address), then the path +0x140, +0x1b0, +0x20, +0x34 through the heaps' bookkeeping, which is masagrator's FPSLocker config's (the same for 1.0.0 and 1.1.0) and is not read from code
Each place must be found exactly once; a field or roots found more than once give a [RED] line and nothing is written.

loader.c reads the keys into module_t, and hle_fpslock.c writes them, with no build-keyed row: a new row kind, FREE_I32, writes the interval 0 above 30 and leaves it at 30, where the game keeps its own limit; above 30 each bound becomes the game's own value times 30 / target (its own value is what it holds when that differs from the host's last write, so a bound the game sets again is scaled again). The bounds alone do not count as an engine limit for the present cap. The profile gets fps_target 60.

60 is the ceiling: the frame manager (main+0x532eb0) counts a step in whole 60 Hz vsyncs, at least one, so a shorter frame would run the game fast. On a 120 Hz display link an iPhone 17 Pro Max refreshed at 120 and the game still delivered 60, at 3.5 times the CPU energy; fps_max stays 60.

The places come from masagrator's FPSLocker config for 1.1.0 (FPSLocker-Warehouse, SaltySD/plugins/FPSLocker/patches/01004D300C5AE000/A6CE40DC3AEDB1BE.yaml), the interval found by Hazerou; the search's anchors are the code those configs name.

Checked offline (2026-11-09): on 1.1.0 (a6ce40dc...) the search finds [0xa76728]+0x50 and the root 0xa767b0; on 1.0.0 (d9ba7db7...) 0xa72628 and 0xa726b0, the places FPSLocker's 1.0.0 config lists; nothing in 12 other mains on the game drive, Kirby Star Allies 4.0.0 and Kirby's Return to Dream Land Deluxe 1.0.0 among them, so the code is this game's (binding game, not engine). patch_nso.py on the 1.1.0 main writes those keys. Tests: test_hal_fps.py (Kirby's layout, no frame manager, a frame manager with no constructor storing its object, a global something else sets, two objects, heap roots not three in a row); t_fpslock cases 30 and 31 (60: interval 2 -> 0, bounds 1.95 / 1.7 -> 0.975 / 0.85, both again when the game sets its own again; 30: nothing written); the host tests; the tool tests as on main (test_dmsh_abi, test_host_msl and test_uepak_iostore fail the same on main on this Mac); lint_python against main, no new finding; lint_c, no finding in the changed files. In game, with a build row for the same places on 1.1.0: iPhone 17 Pro Max, iOS 27.2, 8 minutes of play, median 59.8 fps, dips to 44-50 only while areas load, 60 held at thermal state 2, footprint up to 4.0 GB; Mac, Apple M1 Max, macOS 27.2, 3 minutes of play, 60.0 fps in every power window but the first (loading); the same scripted walk ends at the same place at 30 and 60. Not checked: the run through the fixups in game, past the first area, regress.py.
Know-It-All-Brother pushed a commit to Know-It-All-Brother/nxnative that referenced this pull request Nov 9, 2026
…uctions back (ASTRAL CHAIN 1.0.1 main+0x6db4a0, SDK 6: cmp w18,seedds#5; b.hi; ldrsw x18,[x24,x18,lsl seedds#2]; add x18,x18,x24; br x18). The function's first block loads six table bases with adrp + add into registers its loop keeps (x24 441 instructions before this load) and a later block one more (x3, 549 before the load at +0x6db70c); jump_offsets followed the base's writer chain 256 instructions back, and the rewrite stopped with jump table 6db4a0. Where nothing writes the base in those 256, its last attempt (far_base) follows the chain to the function's start (table_base far), through no call when the base is caller-saved, and accepts the table only when every target is an instruction of the function. The function-wide search jump_adr_offsets uses for a hoisted base (the one adrp + add pair that fits) finds two for x3 there, the other the local table of a br x17 further on. Three of that main's five br x18 sites need it, their targets checked by hand; main and sdk rewrite. It runs only where every other form has failed: the Tears of the Kingdom, Age of Calamity, Cuphead, DARK SOULS: REMASTERED, Luigi's Mansion 3 and Metroid Dread mains come out byte-identical (patched image and site list)
Know-It-All-Brother pushed a commit to Know-It-All-Brother/nxnative that referenced this pull request Nov 9, 2026
The walk from the load back to the bounds check noticed copies and masks but no
other write: cmp w18,seedds#4; b.hi; add w18,w18,seedds#1; ldrsw x18,[x4,x18,lsl seedds#2] read
entries 0 to 4 while the code uses 1 to 5, so one case's target was missing with
no sign of it. A site with a write of the index after its check, or a call with
a caller-saved index, is now refused, as jump_adr_offsets and half_count already
refuse a write. A refusal goes on to the other recognizers and ends in the jump
table assertion. Writes before the check do not count, which keeps the sites
check_before_copy takes.

A write that keeps the value, such as sxtw x0,w0, is refused too; no module on
the drive has one.

Checked: test_jump_copies.py (the new cases fail on the previous rewriter). Of the
345 unique modules on the drive, old and new recognition are the same on 281, and
60 more mains were scanned on the previous code with no site this refuses. That
includes Smash 13.0.5, EA SPORTS FC 27 and Well Dweller. Four could not be checked:
New Super Mario Bros. U Deluxe's main, sdk and rtld fail alike (no profile), and
Smash 1.0.0's main stops at a table the game's note already lists. No regress.py
run: nothing changes in the modules checked.
Know-It-All-Brother pushed a commit to Know-It-All-Brother/nxnative that referenced this pull request Nov 9, 2026
A fullscreen HDR layer is presented only after its GPU work completes (DM_PRESENT_AFTER_GPU)
KillingStalking referenced this pull request in KillingStalking/nxnativewinfix-upstream Nov 12, 2026
Sync with upstream seedds/nxnative (48 commits, to 2026-10-28)
roandegraaf added a commit to roandegraaf/nxnative that referenced this pull request Nov 12, 2026
Mods made for Switch emulators load from a mods folder: RomFS files switched while the game runs, cheat files of every mod as one list, .pchtxt / .ips patches as a module loads (DM_MODS, the Mac window's Mods menu).

dm/host/hle_mods.c reads DM_MODS (default <DM_ROOT>/mods), one folder per mod in
the layouts mods ship in (romfs/, exefs/, cheats/ directly, or under
atmosphere/contents/<title ID>/), ordered and switched by order.txt. A folder of
mods is a pack; two of a pack that replace the same RomFS file are alternatives.

- romfs/ folders join the RomFS overlay, and the Mods menu (or DM_CTL "mod-on" /
  "mod-off") changes the list while the game runs (dm_fs_overlay_set). A
  <name>.dm-delete marker hides a game file or directory, and those of the mods
  after it. A name that differs from the game's only in case is taken, with a
  warning in the log, where it silently did nothing before.
- Every cheats/<build ID>.txt of the running build is loaded, the cheats
  folder's own first, then each mod's by priority: a cheat an earlier file has
  with the same name and code is left out, the same name with other code is a
  second entry ("Name seedds#2"), a mod's cheats are listed under its name, and
  <build>.enabled / <build>.values stay one file each, in the cheats folder.
  CHEAT_MAX is 512, for all files together.
- exefs/*.pchtxt and <build ID>.ips are written into the module whose build ID
  they name while it is still writable (loader.c map_image), a file whole or
  not at all. A file is refused with a [RED] line when a patch replaces a word
  the rewriter moved (<name>.changed.tsv) or writes an instruction the rewriter
  would have had to replace; applying those before the rewriter runs is the
  next change.

Mac-tested on 0400486024DEC000 only: two RomFS mods from the
menu, synthetic patches and cheat files. Code modules of a mod (ExLaunch,
Skyline) are not loaded, and no exefs patch is applied on iOS.

Rebased on main at 034e91a: only the game note's Found on this game list conflicted (both kept); symptom index regenerated. Main's rewriter now also rounds odd-sized sub/add sp, #imm frames (c081686), so the host refuses a patch that writes sub / add sp, sp, #imm by an amount that is not a multiple of 16 too (t_mods: five new cases). Checked again: host build, make -C dm/host/tests run (t_mods, t_cheats, t_fs, t_hid), test_docs, test_env_switches, test_architecture, lint tests.

Front-ends: new: mods are folders in DM_MODS (default <DM_ROOT>/mods), ordered and turned off by order.txt there; the host reads it at the start
Front-ends: interface: every <build ID>.txt of the running build is loaded, from the cheats folder and each enabled mod's cheats/, as one list; a cheat's section may be a mod's name
UserDerezzed pushed a commit to UserDerezzed/nxnative that referenced this pull request Nov 12, 2026
…en that can show EDR, the game's HDR10 window goes as it is into an RGB10A2 BT.2100 PQ layer, and the peak follows the screen's current headroom with no HDR10 metadata on the layer, on the Mac and iOS

- hle_vi.c: with DM_HDR=1 (the HDR output row, on by default) vi::QueryDisplayHdrStatus answers HDR on, format 1, while the window's screen can show EDR (DM_HDR=2: on any screen), and the game asks every frame, so its window follows the screen; the iOS in-game menu turns it on and off while the game runs. The paper white (DM_HDR_PAPER_WHITE, the HDR paper white row) is 100 nits by default, the screen's own white: macOS shows a PQ layer at EDR = nits / 100, measured with an extended-range screen capture, so the game's normal picture matches SDR and the headroom is left to its highlights (by eye, Mario Kart World at 100 had SDR's base brightness with brighter highlights; at 203 the whole picture was brighter).
- The peak (DM_HDR_PEAK, the HDR peak row) is automatic by default: 100 nits times the screen's current headroom (front_hdr_headroom: NSScreen's maximumExtendedDynamicRangeColorComponentValue on the Mac, UIScreen's currentEDRHeadroom on iOS), in steps of about 6 % taken once they have held for a second, at least twice the paper white, so the game tone-maps into what the screen shows. Donkey Kong Bananza and Ocarina of Time declare within the peak they are told, and all three games' pixels stay within it.
- No HDR10 metadata on the layer (DM_HDR_META=1 adds it): with metadata above 100 x headroom Core Animation compresses the whole picture, mid-tones included (measured), and Mario Kart World declares about 1.8 times the peak it is told; and in fullscreen a layer with metadata of any range showed rectangles of older frames under GPU load, in the host and in a standalone app with no game, judged by eye without knowing the mode (dm/gfx/tools/hdr_rects.mm), none without. A fixed peak above the screen's is rolled off in the present above three quarters of the screen's held peak (present.metal mode 4), keyed on the smaller of the declared range and the peak told.
- present.metal and nvn_mtl.m present_mode: the HDR10 window as it is into the PQ layer, an SDR or float source encoded at the paper white while the status answers HDR and at 100 nits, the screen's SDR white, while it answers SDR (at 203 an SDR screen showed the SDR picture twice as bright and clipped), an HDR frame brought to SDR white with its hue for screenshots and SDR drawables; RGB10A2 windows are PQ only once the status has answered HDR. A PQ layer rather than an extended-range float one, which showed black blocks over flat areas on a MacBook Air M5 while the game's frames were clean.
- With metadata in fullscreen (DM_PRESENT_AFTER_GPU), the drawable is handed to the system once its present pass has completed, without signalDrawable, which with the pass completed made frames a refresh late; it costs frames a refresh late when the pass ends close to the refresh, so it is off without metadata and in a window.
- dm/gfx/tools/edr_probe.m measures how macOS maps a PQ layer into EDR; dm/gfx/tools/hdr_rects.mm reproduces the rectangles with no game.
- t_present_hdr: the status answer, the automatic peak and its hold, the PQ decode and encode, the roll-off's curve, SDR and float sources, screenshots; test_settings: the rows and their per-platform defaults.
- Notes: Donkey Kong Bananza, Mario Kart World and Ocarina of Time's HDR windows and what each declares; three reference entries in docs/reference/rendering.md.

The PQ layer is beecrepaldi-afk's (maxdavidson#1), the present after the GPU and the standalone app that found the rectangles b1tdr3amer24's (seedds#2), the paper white and peak rows and the automatic peak's front end hook Amost's (seedds#3).

Front-ends: new: HDR output for Switch 2 games (DM_HDR, DM_HDR_PAPER_WHITE, DM_HDR_PEAK rows): the front end makes the HDR layer RGB10A2 in kCGColorSpaceITUR_2100_PQ with wantsExtendedDynamicRangeContent (front_mac.m, front_ios.m)
Front-ends: new: the HDR output row defaults to on; the host's own default, DM_HDR unset, stays SDR, so a front end that does not pass the row's value starts the game in SDR
Front-ends: new: front_hdr_screen() (the window's screen can show EDR) and front_hdr_headroom() (its current EDR headroom) are weak hooks in hle_vi.c; without front_hdr_headroom the automatic peak answers 1000 and nothing is rolled off
Front-ends: new: a front end calls dm_hdr_layer_meta_set() with whether it gave the layer HDR10 metadata, and receives the game's declared range through front_hdr_content_range() for that metadata

Co-authored-by: beecrepaldi-afk <beecrepaldi@gmail.com>
Co-authored-by: b1tdr3amer24 <240231594+b1tdr3amer24@users.noreply.github.com>
Co-authored-by: Amost <6445689+Amost-@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
UserDerezzed pushed a commit to UserDerezzed/nxnative that referenced this pull request Nov 13, 2026
…en that can show EDR, the game's HDR10 window goes as it is into an RGB10A2 BT.2100 PQ layer, and the peak follows the screen's current headroom with no HDR10 metadata on the layer, on the Mac and iOS

- hle_vi.c: with DM_HDR=1 (the HDR output row, on by default) vi::QueryDisplayHdrStatus answers HDR on, format 1, while the window's screen can show EDR (DM_HDR=2: on any screen), and the game asks every frame, so its window follows the screen; the iOS in-game menu turns it on and off while the game runs. The paper white (DM_HDR_PAPER_WHITE, the HDR paper white row) is 100 nits by default, the screen's own white: macOS shows a PQ layer at EDR = nits / 100, measured with an extended-range screen capture, so the game's normal picture matches SDR and the headroom is left to its highlights (by eye, Mario Kart World at 100 had SDR's base brightness with brighter highlights; at 203 the whole picture was brighter).
- The peak (DM_HDR_PEAK, the HDR peak row) is automatic by default: 100 nits times the screen's current headroom (front_hdr_headroom: NSScreen's maximumExtendedDynamicRangeColorComponentValue on the Mac, UIScreen's currentEDRHeadroom on iOS), in steps of about 6 % taken once they have held for a second, at least twice the paper white, so the game tone-maps into what the screen shows. Donkey Kong Bananza and Ocarina of Time declare within the peak they are told, and all three games' pixels stay within it.
- No HDR10 metadata on the layer (DM_HDR_META=1 adds it): with metadata above 100 x headroom Core Animation compresses the whole picture, mid-tones included (measured), and Mario Kart World declares about 1.8 times the peak it is told; and in fullscreen a layer with metadata of any range showed rectangles of older frames under GPU load, in the host and in a standalone app with no game, judged by eye without knowing the mode (dm/gfx/tools/hdr_rects.mm), none without. A fixed peak above the screen's is rolled off in the present above three quarters of the screen's held peak (present.metal mode 4), keyed on the smaller of the declared range and the peak told.
- present.metal and nvn_mtl.m present_mode: the HDR10 window as it is into the PQ layer, an SDR or float source encoded at the paper white while the status answers HDR and at 100 nits, the screen's SDR white, while it answers SDR (at 203 an SDR screen showed the SDR picture twice as bright and clipped), an HDR frame brought to SDR white with its hue for screenshots and SDR drawables; RGB10A2 windows are PQ only once the status has answered HDR. A PQ layer rather than an extended-range float one, which showed black blocks over flat areas on a MacBook Air M5 while the game's frames were clean.
- With metadata in fullscreen (DM_PRESENT_AFTER_GPU), the drawable is handed to the system once its present pass has completed, without signalDrawable, which with the pass completed made frames a refresh late; it costs frames a refresh late when the pass ends close to the refresh, so it is off without metadata and in a window.
- dm/gfx/tools/edr_probe.m measures how macOS maps a PQ layer into EDR; dm/gfx/tools/hdr_rects.mm reproduces the rectangles with no game.
- t_present_hdr: the status answer, the automatic peak and its hold, the PQ decode and encode, the roll-off's curve, SDR and float sources, screenshots; test_settings: the rows and their per-platform defaults.
- Notes: Donkey Kong Bananza, Mario Kart World and Ocarina of Time's HDR windows and what each declares; three reference entries in docs/reference/rendering.md.

The PQ layer is beecrepaldi-afk's (maxdavidson#1), the present after the GPU and the standalone app that found the rectangles b1tdr3amer24's (seedds#2), the paper white and peak rows and the automatic peak's front end hook Amost's (seedds#3).

Front-ends: new: HDR output for Switch 2 games (DM_HDR, DM_HDR_PAPER_WHITE, DM_HDR_PEAK rows): the front end makes the HDR layer RGB10A2 in kCGColorSpaceITUR_2100_PQ with wantsExtendedDynamicRangeContent (front_mac.m, front_ios.m)
Front-ends: new: the HDR output row defaults to on; the host's own default, DM_HDR unset, stays SDR, so a front end that does not pass the row's value starts the game in SDR
Front-ends: new: front_hdr_screen() (the window's screen can show EDR) and front_hdr_headroom() (its current EDR headroom) are weak hooks in hle_vi.c; without front_hdr_headroom the automatic peak answers 1000 and nothing is rolled off
Front-ends: new: a front end calls dm_hdr_layer_meta_set() with whether it gave the layer HDR10 metadata, and receives the game's declared range through front_hdr_content_range() for that metadata

Co-authored-by: beecrepaldi-afk <beecrepaldi@gmail.com>
Co-authored-by: b1tdr3amer24 <240231594+b1tdr3amer24@users.noreply.github.com>
Co-authored-by: Amost <6445689+Amost-@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
KatyushaScarlet added a commit to KatyushaScarlet/nxnative that referenced this pull request Nov 14, 2026
… test

Some builds mask an index, complement it and test the mask instead of a
compare before an offset table: Rabi-Ribi's main+0x446f0c does
and x27,x10,seedds#7; mvn w18,w10; tst w18,seedds#7; b.eq; ldrsw x18,[x16,x27,lsl seedds#2];
add x18,x18,x16; br x18. jump_mask_offsets reads the mask and the table's
mask+1 targets, and is tried only where jump_offsets and jump_adr_offsets find
nothing.

Checked: python -m py_compile dm/tools/patch_nso.py.
seedds added a commit that referenced this pull request Nov 16, 2026
Manual Samuel main+0x6d9d44 masks its dispatch index (and w13,w17,#7) before the bit test that bounds it (tbnz w17,#2): four entries are reachable, an eight-entry reading lands on data. Offset tables were recognized by shape, one recognizer per form a game brought, each with its own walk back to the bound and the base; this would have been the tenth (PR #2695).

dm/tools/jump_solver.py replaces them all (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). It proves every dispatch of a function at once by forward dataflow over its control flow. A register holds constants or a root with a chain of operations (32-bit truncation, and-mask, complement, add, shift right); a root carries its range, its low-32 range and its low-12-bit set, and guards (cmp/b.cond, tst, cbz, tbz) refine the root, so the bound reaches the index through copies, masks and complements in any block. Table targets become edges until nothing changes; dispatches through any register count. Entries: the function start, call targets, direct branches from the rest of the module, targets of tables elsewhere, C++ landing pads from LSDAs under a personality routine, and padded unreached starts in text without unwind entries. A constants reading gives the control flow; a guards-only reading sizes each br x18 table by what its guards allow. Halfword tables' pads come from the proved tables.

Checked on the newest build of every supported game (457 modules, 150 games), old rewriter against new: 453 byte-identical; 4 differ only where a halfword table left at 65,536 pads is now proved (Animal Crossing 3.0.3 main x6, Pikmin 4 1.1.1 main x2, Tears of the Kingdom 1.4.3 main+0x680528, PRAGMATA main x3). Manual Samuel main rewrites to the reporter's patch's bytes. Rewrite CPU over the corpus 12,430 s -> 10,591 s. The run also fixed ASTRAL CHAIN (lsr bounds, widening kept per part) and Absolum (NativeAOT 'zLR' LSDAs no longer read as C++ tables). No game was run.

Co-authored-by: TheLowbar <333664989+TheLowbar@users.noreply.github.com>
seedds added a commit that referenced this pull request Nov 16, 2026
…bit test (#2562)

Manual Samuel's and w13,w17,#7; tbnz w17,#2 gives four entries; the same form with tbnz #0 and #1 (masks #1 and #3) must give one and two, with the word past them poisoned so that a wider reading fails. Facts from PR #2695's tests.
seedds added a commit that referenced this pull request Nov 27, 2026
DRAGON BALL FighterZ 1.50 main+0x252b78 checks a 16-bit masked copy and
indexes with a second 16-bit mask of the same register:

    and   w18, w8, #0xffff
    cmp   w18, #0x10
    b.hi  ...
    and   x18, x8, #0xffff
    ldrsw x18, [x14, x18, lsl #2]

Since 8950f2e, a root constraint tracked only its full range, its low
12 bits (masks <= 0xfff), and its low 32 bits (lo32/hi32). A 16-bit mask
fell between them, so _refine left the root unnarrowed and the second
mask evaluated to 0..0xffff (65,536 entries), failing the rewrite.

Generalize the low-32-bit range on root constraints to sorted
(mask, lo, hi) ranges on (root & mask) (_mk, _mrange, _mask_prefix).
Leading w/and operations collapse to one mask on the root, so a guard
narrows (root & mask) directly and any earlier or later read of that
mask or a narrower submask (including across phi joins, widening,
post-mask offsets, or after the checked register is clobbered) inherits
the bound.

Checked: 35/35 test_jump_solver.py, 7/7 test_docs.py, 46/46 related
rewriter tests, pinned ruff/pyright ratchet (0 new), byte-identical
rewrites of Cuphead and Manual Samuel main, and Well Dweller quick
regress.py check (PASS).

Co-authored-by: Amine Bezzarga <578618+GoMino@users.noreply.github.com>
seedds added a commit that referenced this pull request Nov 27, 2026
Sonic Racing: CrossWorlds 1.41 main+0x726afc (issue #3383) spills a 32-bit subs w4, w8, #1 result to [sp, #0x80] across two calls and reloads it with ldr x4, [sp, #0x80] before cmp w4, #5; b.hi; ldrsw x0, [x17, x4, lsl #2]. Without a stack-slot model, the 64-bit reload produced an unconstrained 64-bit root whose unknown upper half a 32-bit compare cannot bound, stopping the rewrite at 'the index reaches 0xffffffffffffffff'.

Track provably local fixed stack slots inside the function's allocated frame (frame, slots, escaped) and stack-derived register offsets ('sp', offset) uniformly covering x29 frame pointers in dm/tools/jump_solver.py:
- Only track fixed-offset GPR str/stur/stlr/stp/stnp slots strictly inside [0, frame) allocated by sub sp / pre-decrement, and reload only on matching width (or a 32-bit reload of the low half of an 8-byte slot).
- Invalidate overlapping byte ranges on any fixed-offset stack write, clear slots on indexed or unknown-size stack writes (including LSE atomics), and latch escaped=True whenever a stack pointer escapes to a call (x0-x18/x30), memory, syscall, unhandled op, or mismatched join.
- Reject trusting targets solely because they lie in the function when the upper half remains unproved.

Checked: 37/37 test_jump_solver.py, 7/7 test_docs.py, 71/71 related rewriter tests, ruff/pyright (0 errors/warnings on modified files), byte-identical main rewrites on Cuphead (-0.6%) and Manual Samuel (+0.9%), and quick regress.py checks on Well Dweller and DOOM 3 (PASS). Awaits reporter retest on Sonic Racing: CrossWorlds main.

Co-authored-by: dationguyen <26321444+dationguyen@users.noreply.github.com>
Aznracer pushed a commit to Aznracer/Mighty-Green-Kokiri-Kid that referenced this pull request Nov 28, 2026
)

DRAGON BALL FighterZ 1.50 main+0x252b78 checks a 16-bit masked copy and
indexes with a second 16-bit mask of the same register:

    and   w18, w8, #0xffff
    cmp   w18, #0x10
    b.hi  ...
    and   x18, x8, #0xffff
    ldrsw x18, [x14, x18, lsl seedds#2]

Since 8950f2e, a root constraint tracked only its full range, its low
12 bits (masks <= 0xfff), and its low 32 bits (lo32/hi32). A 16-bit mask
fell between them, so _refine left the root unnarrowed and the second
mask evaluated to 0..0xffff (65,536 entries), failing the rewrite.

Generalize the low-32-bit range on root constraints to sorted
(mask, lo, hi) ranges on (root & mask) (_mk, _mrange, _mask_prefix).
Leading w/and operations collapse to one mask on the root, so a guard
narrows (root & mask) directly and any earlier or later read of that
mask or a narrower submask (including across phi joins, widening,
post-mask offsets, or after the checked register is clobbered) inherits
the bound.

Checked: 35/35 test_jump_solver.py, 7/7 test_docs.py, 46/46 related
rewriter tests, pinned ruff/pyright ratchet (0 new), byte-identical
rewrites of Cuphead and Manual Samuel main, and Well Dweller quick
regress.py check (PASS).

Co-authored-by: Amine Bezzarga <578618+GoMino@users.noreply.github.com>
(cherry picked from commit c264119)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants