Skip to content

Play your own Switch games on iPhone/iPad — one-click macOS app, no terminal. | 把 Switch 游戏装进 iPhone:图形界面一键构建,不用命令行。Bring your own game.

sync: dm/games/game.py belongs in OURS, not behind a verifier

LNPANDYaae0d97b138b
diff --git a/dm/games/010020400E1C2000/README.md b/dm/games/010020400E1C2000/README.md
index ec34c270..aa92080a 100644
--- a/dm/games/010020400E1C2000/README.md
+++ b/dm/games/010020400E1C2000/README.md
@@ -29,6 +29,8 @@ Base game 1.0.0 (v0), SDK 7.3.2. Unity 2018.3.10f1 IL2CPP with FMOD on NVN. Modu
- **Resolved: the split stopped with "no bundle has a Shader type tree of the same hash to borrow"** (hash `8db76007…`). There are no bundles, and no game of that Unity version with a bundle was at hand, so `SHADER_2018_3` in `unityfs.py`'s `KNOWN_TREES` is written from AssetRipper's TypeTreeDumps (`StructsDump/release/2018.3.10f1.dump`), checked node for node against the dump (1,325 nodes, the alignment flags included). It is a layout of its own, older than the common structs: no conservative raster state, `BufferBinding` without `m_ArraySize`, `ConstantBuffer` without `m_IsPartialCB`, the parameters in each subprogram and no `m_CommonParameters`, one segment per platform (the pre-2019.3 form Cuphead's trees gave `shader_programs`). Each of the 48 objects reads to its exact end: 450 subprograms of version 201802150 (older than the local keyword list, which starts at 201806140).
- The two built-in `ComputeShader` objects in `unity default resources` stay unread (a `[RED]` line in the split): their 2018 layout lists kernels with no unique variants. The game dispatches no compute.
- To take one file out of an NSP without extracting the RomFS, filter `nx_extract`'s `Copy` by path.
+- **Direct-image validation (2026-10-27):** the merged base writes a `RomFS.img` with 1,473 resource files (919,413,381 file-data bytes), no RomFS directory. Every image path, size and first 32 bytes matches an independent LibHac manifest. The image scan retains all 452 registered shader rows unchanged and adds 15 compute shaders from `unity default resources` supported by the current parser; the registered profile's older map/facts therefore stop the full build at table validation. The profile was not changed for this storage work.
+- **Direct-image runtime checked:** the current host with the registered 452-shader package rebuilt for chain `157e1b96c8da` ran 4,200 frames (about 70 seconds) through the opening and tutorial, reading the image in place. The log records the image mount (1,518 entries), 143 filesystem opens and no `[RED]` lines; the frame-3,600 screenshot shows the tutorial choices. Evidence stays in `<NSP folder>/010020400E1C2000-work/direct-romfs-run/`. This checks populated-image gameplay; it is not a timing comparison against folder storage.
## Mac routes
@@ -36,6 +38,8 @@ Base game 1.0.0 (v0), SDK 7.3.2. Unity 2018.3.10f1 IL2CPP with FMOD on NVN. Modu
## Found on this game
+- **Direct extraction and scanning of a RomFS image:** [RomFS image build pipeline](../../../docs/reference/packing.md#building-creates-a-full-romfs-tree-before-packing-its-image).
+
- **Unity 2018.3's `Shader` layout written out** (`SHADER_2018_3`, from AssetRipper's TypeTreeDumps): [Unity Shader layouts written out for players without bundles](../../../docs/reference/shaders.md#unity-shader-layouts-written-out-for-players-without-bundles).
- **The heap check keeps the hardware pool** for a Unity 2018.3 game that maps only inside StandardAllocator's region: [dm/games/README.md, Adding a game](../README.md#adding-a-game).
diff --git a/dm/games/010020D01AD24000/README.md b/dm/games/010020D01AD24000/README.md
index 3333c3cf..698a45ab 100644
--- a/dm/games/010020D01AD24000/README.md
+++ b/dm/games/010020D01AD24000/README.md
@@ -8,7 +8,7 @@ On the Mac: the opening rooms at 60 fps with movement, jumping and audio; item p
| Setting | Where | Why |
|---|---|---|
-| `romfs_marker` empty | [`game.tsv`](game.tsv) | the Program NCAs have no data section: `nx_extract` creates an empty RomFS directory, which the empty marker checks; see [Files](#files) |
+| `romfs_marker` empty | [`game.tsv`](game.tsv) | the Program NCAs have no data section: `nx_extract --romfs-image` creates an empty RomFS image, which the empty marker checks; see [Files](#files) |
| 3.5 GB layout: `mem_reserve 0xe0000000`, `mem_alias 0x10000000`, `mem_stack 0x10000000`, `app_pool 0xCD500000` | `game.tsv` | the provisional layout, which holds: a 256 MB alias region, a 256 MB stack region and a 2816 MB heap region. `main` sets a heap of at most the pool − 64 MB − 536 MB of bss (counted as used memory) |
| `sys_resource 0x0` | `game.tsv` | the NPDM declares 0 MB of system resource: `IsVirtualAddressMemoryEnabled` is false, as on Horizon |
| `pad_layout simple` | `game.tsv` | the 2D virtual pad; B jumps |
@@ -17,7 +17,13 @@ On the Mac: the opening rooms at 60 fps with movement, jumping and audio; item p
## Files
- Both the base and the update Program NCAs have no data section. The assets live in `main`, whose read-only segment is about 32 MB.
-- **Current:** `nx_extract` creates an empty RomFS directory (and a header-only survey manifest) when neither program has a data section. Base and update extraction were checked in both full and manifest modes.
+- **Current:** `nx_extract --romfs-image` directly writes a 56-byte `DMROMFS1` image (one root entry), with no RomFS directory; survey mode still writes a header-only manifest. It passes the same index validator as a populated image. Since the game keeps its assets in `main` and does not mount RomFS on the tested opening route, its gameplay check cannot establish populated-image read performance; synthetic filesystem tests cover reads and overlays. See [RomFS images](../../../docs/reference/packing.md#romfs-folder-transfers-fail-or-leave-stale-game-files).
+- **Direct extraction checked on 2026-10-27:** the NSP pipeline produced `AnimalWell-DirectRomFS.ipa` (54.6 MiB), with all 46 iOS shaders and exactly one `Payload/DmIOS.app/romfs.img` entry. Both the extraction and IPA contain no RomFS directory. The archive's CRC check passed. This unsigned IPA has not been tested on an iPhone here.
+- **Direct extraction regression: PASS.** The full 100-second `regress.py` route against `08b8a3c1ef1c` kept all 46 shaders and their MSL unchanged, with no new `[RED]` lines: 59.5 → 59.7 fps, p99 16.76 → 16.77 ms, peak 980 → 981 MiB. Screenshot differences were 1–3 dHash bits. Both hosts used `DM_PRESENT_LINK=0` for the window-occlusion control described below; the report is `<NSP folder>/010020D01AD24000-work/regress-direct-extraction/report.md`.
+- **Rechecked after integration with main `4f24ce6489a2`: PASS.** A fresh 100-second baseline and candidate both ran at 60.0 fps; p99 16.77 → 16.76 ms, peak 997 → 996 MiB, all 46 shaders/MSL unchanged, screenshots within tolerance (2–3 dHash bits), no new `[RED]` lines. Both used the same diagnostic control and were marked busy by the harness. The report is `<NSP folder>/010020D01AD24000-work/regress-romfs-main/report.md`. The combined host suite, 347 tool tests, 31 iOS tests, 71 graphics Python tests and the Metal graphics suite passed; the rebuilt unsigned IPA's CRC check passed too.
+- **Checked on 2026-10-27:** Mac runs with the folder and image selected both reached the opening room and passed 2,400 presented frames, with no `[RED]` lines in the completed comparison runs. Five control-triggered screenshots per input cover the room, pause and resume; all pairs are within the harness's image tolerances (2–6 dHash bits and 0.44–2.71 mean RGB difference out of 255). The folder captures use the windowless path after a busy windowed run missed captures; this establishes picture/boot behavior, not a performance comparison. An initial audio-enabled folder run recovered through the existing AudioUnit restart path. A separate unsigned `AnimalWell-RomFS.ipa` was built (54.6 MiB), with all 46 iOS shaders; it has not been installed or tested on an iPhone here. The `smoke.tsv` route uses a fresh save and leaves the character still in the opening room.
+- **Measurement constraint:** a default windowed baseline/candidate comparison reported 59.7 → 27.5 fps and p99 16.75 → 134.53 ms. The candidate logged focus state 2 and display-link callbacks about once per second; the baseline remained active and used the existing silent-link rescue. A reverse-order probe reproduced the slowdown in the unchanged host too. With the existing `DM_PRESENT_LINK=0` applied to both hosts as a diagnostic control, both gave 60.0 fps and p99 16.76 ms in the 15-second measured windows. This is the documented [occluded Mac display-link behavior](../../../docs/reference/frame-rate.md#present-thread-rescues-a-silent-display-link); no presentation setting or default was changed by the image implementation. Keep the window visible and foreground for normal timing comparisons. The full multi-game regression remains pending; the attempted run reached Balatro's unsupported OpenGL chain check and began a separate game's 73,330-shader rebuild before this pass was limited to this game.
+- **Controlled full-route regression: PASS.** `regress.py check --baseline 08b8a3c1ef1c --games 010020D01AD24000 --no-hud --env DM_PRESENT_LINK=0` compared the baseline with the image implementation for 100 seconds each on an M4 Pro, macOS 27.0.1 / Xcode 27.1. Both built all 46 shaders, with unchanged MSL and no interface failures or new `[RED]` lines. Baseline → candidate: 59.5 → 59.3 fps, frame p99 16.76 → 17.01 ms, peak footprint 980 → 981 MiB; all three screenshot pairs differ by one dHash bit and mean RGB 0.70–1.13 out of 255. The direct-drawable switch was applied equally to control the window-occlusion effect above; both samples were marked busy by the harness. The report is in `<NSP folder>/010020D01AD24000-work/regress-animal-well-direct/`.
## Shaders
@@ -31,6 +37,7 @@ On the Mac: the opening rooms at 60 fps with movement, jumping and audio; item p
## Found on this game
- **An empty RomFS for a program without a data section** (`nx_extract`; an empty `romfs_marker` checks the directory itself): [dm/games/README.md](../README.md).
+- **An empty RomFS image:** [RomFS images](../../../docs/reference/packing.md#romfs-folder-transfers-fail-or-leave-stale-game-files).
- **Resolved:** `--platform mac-app` stopped at the pipeline archive (`pso_offline: no base to build`) because the profile's `shader_pairs.tsv` holds no pair; a pair list with no pair is now nothing to build and the app is packed without an archive: [Offline pipeline archive reuse and fallback](../../../docs/reference/shaders.md#offline-pipeline-archive-reuse-and-fallback) ([GitHub issue #338](https://github.com/seedds/nxnative/issues/338)).
## Open
diff --git a/dm/games/0100535012974000/README.md b/dm/games/0100535012974000/README.md
index 0c6bab36..8885a0c9 100644
--- a/dm/games/0100535012974000/README.md
+++ b/dm/games/0100535012974000/README.md
@@ -29,6 +29,7 @@ The layer was written for this game (Super Mario Galaxy extended it later: [0100
## Services
- **Resolved: the notification event.** The game polls `oe::GetNotificationMessageEvent` every frame. The SDK's own event was never created (the host's `oe::Initialize` is a no-op), so the host now hands out an event of its own, signalled while a notification is queued.
+- **Resolved: `NetworkPollThread` kept a host core busy (issue #334).** The thread (`main+0x27aaa0`, priority 31, started at `main+0x273b68`) runs for good: yield, `nifm::SubmitNetworkRequest`, then while `IsNetworkRequestOnHold` up to 2,000 rounds of `SleepThread(0)` and a query, `CancelNetworkRequest` when they run out, `IsNetworkAvailable` into a flag under a mutex, and round again. The other caller (`main+0x421e10`) is the online account path (`SubmitNetworkRequestAndWait`). With the host's 50 ms hold the 2,000 queries (0.1 ms here) always ran out first: in 60 s of the smoke route, 1.17 billion queries, 833,250 submits, 582,637 cancels and 117 s of process CPU. The request is now on hold for the first query only, and the back-off now catches a wait at two yields (w23 is 0 at the one between rounds and 2,000 at the one in the wait): 101,564 submits, two queries each, no cancel, 216,000 yields and 62 s of CPU, the frames and the picture as before. Both changes are general: [Network requests stay on hold before they settle](../../../docs/reference/services.md#network-requests-stay-on-hold-before-they-settle), [A wait at two yields is not progress](../../../docs/reference/threads.md#a-wait-at-two-yields-is-not-progress).
- **Current: offline.** `main` imports `EOS_*` functions (Epic Online Services, from `/nro/EOSSDK-Switch-Shipping.nro`, loaded through `nn::ro`); they stay offline. `main` imports only EOS Auth, Connect and PlayerDataStorage (Epic-account cross-save, which the host cannot serve). Since the host loads NROs, it refuses online SDKs: an NRR that registers only such modules fails `RegisterModuleInfo`, and Hades never asks for the module (checked on 1.0.38233: `refused an NRR that registers only online SDKs (1 hashes)`, no `LoadModule`, its frames as before).
## Rewriter
@@ -45,6 +46,8 @@ General host changes first needed here; each applies to every game:
- **The Vulkan layer on Metal** (`dm/gfx/vk/hle_vk.m`) and the SPIR-V translation (`vk_shaders.py`), described above; [dm/games/README.md, What the game files decide at every build](../README.md#what-the-game-files-decide-at-every-build).
- **A host notification event** for `oe::GetNotificationMessageEvent` (`hle_oe.c`), described above.
+- **A network request on hold for its first query only** (`hle_net.c`, `nn::nifm`): [Network requests stay on hold before they settle](../../../docs/reference/services.md#network-requests-stay-on-hold-before-they-settle).
+- **A wait at two yields gets the back-off** (`thr_yield`, `hle_thread.c`): [A wait at two yields is not progress](../../../docs/reference/threads.md#a-wait-at-two-yields-is-not-progress).
## Open
diff --git a/dm/games/0100B7C00933A000/README.md b/dm/games/0100B7C00933A000/README.md
index 51521c53..22b528cc 100644
--- a/dm/games/0100B7C00933A000/README.md
+++ b/dm/games/0100B7C00933A000/README.md
@@ -36,7 +36,7 @@ Status: on the Mac, the boot, the title (a VP9 movie behind the logo), the main
## Services
-- **Resolved: the boot sat at a black loading screen for good, CPU nearly idle, every thread waiting, about 1 boot in 6 (3 in 4 with four Mac hosts at once).** The title movie was never opened and the save files never probed. The game's boot state machine (`main+0x1f2f0e0`, state at `this+0xd4`) stayed in state 7, which polls the status word (+0x14) of the game's BCAT news runnable ("OlimarMemo") for 0, 4, 5, 6 or 7; it read 1. The runnable's constructor (`main+0x203f3b0`) clears the status, starts `FBCATThread` and only then stores 1; the thread's `Run` (`main+0x203f510`) stores 2, calls `nn::nifm::SubmitNetworkRequest`, sleeps while `IsNetworkRequestOnHold`, and stores 6 when `IsNetworkAvailable` is false. On a Switch the request stays on hold while the nifm service evaluates it, so the constructor's 1 always comes first; the host answered "not on hold" at once, and a thread that ran before the constructor's store finished at 6, which the 1 then overwrote. The host now keeps a submitted request on hold for 50 ms, then settles it as unavailable, as Horizon's asynchronous request does (`hle_net.c`): 12 of 12 boots with four hosts at once reached the title.
+- **Resolved: the boot sat at a black loading screen for good, CPU nearly idle, every thread waiting, about 1 boot in 6 (3 in 4 with four Mac hosts at once).** The title movie was never opened and the save files never probed. The game's boot state machine (`main+0x1f2f0e0`, state at `this+0xd4`) stayed in state 7, which polls the status word (+0x14) of the game's BCAT news runnable ("OlimarMemo") for 0, 4, 5, 6 or 7; it read 1. The runnable's constructor (`main+0x203f3b0`) clears the status, starts `FBCATThread` and only then stores 1; the thread's `Run` (`main+0x203f510`) stores 2, calls `nn::nifm::SubmitNetworkRequest`, sleeps while `IsNetworkRequestOnHold`, and stores 6 when `IsNetworkAvailable` is false. On a Switch the request stays on hold while the nifm service evaluates it, so the constructor's 1 always comes first; the host answered "not on hold" at once, and a thread that ran before the constructor's store finished at 6, which the 1 then overwrote. The host now keeps a submitted request on hold for the first query, then settles it as unavailable, as Horizon's asynchronous request does (`hle_net.c`); the thread sleeps 10 ms between its queries. 12 of 12 boots with four hosts at once reached the title (first with a 50 ms hold, which Hades showed was too long for a game that counts its queries, then with the hold for one query; a host that answers at once hung 1 of 4 in the same test).
- How it was found: the hung boots' logs diverged from good ones at the save probe (`DM_FS=1`), the thread dumps showed nothing but idle waits, and `DM_PROBE` on the state machine (found by probing the save probe's call stack and dumping the state each tick), then `peek` lines in a hung run's `DM_CTL` file, followed the pointers to the status word. A probe on the hot path slowed the boot enough to hide the race (8 of 8 good).
## Rewriter
@@ -58,7 +58,7 @@ Status: on the Mac, the boot, the title (a VP9 movie behind the logo), the main
General host changes first needed here; each applies to every game:
-- **A network request kept on hold for 50 ms** (`hle_net.c`, `nn::nifm`): [Network requests stay on hold before they settle](../../../docs/reference/services.md#network-requests-stay-on-hold-before-they-settle).
+- **A network request kept on hold before it settles** (`hle_net.c`, `nn::nifm`): [Network requests stay on hold before they settle](../../../docs/reference/services.md#network-requests-stay-on-hold-before-they-settle).
- **Rewriter:** an `adrp` re-encoded inside a copied exclusive window (`window_adrp`) and gates before a `ret` (`scratch_dead`): [`adrp` inside an exclusive window](../../../docs/reference/rewriter.md#adrp-inside-an-exclusive-window), [Observation gates where x9–x17 are dead](../../../docs/reference/rewriter.md#observation-gates-where-x9x17-are-dead). Spin waits that store (`patch_nso.py` "Spin waits"): [development.md, Power](../../../docs/development.md#power).
- **An Unreal engine region whose default is cut instead of capped by `game_args`**: [Unreal's engine address region and its options](../../../docs/reference/memory.md#unreals-engine-address-region-and-its-options).
diff --git a/dm/games/0100F2C0115B6000/README.md b/dm/games/0100F2C0115B6000/README.md
index 7fd752f0..880a61d0 100644
--- a/dm/games/0100F2C0115B6000/README.md
+++ b/dm/games/0100F2C0115B6000/README.md
@@ -62,6 +62,7 @@ Game-specific findings. The general host changes they led to are listed under [F
- **Resolved in the shader builder (#283): BAHS pipeline interfaces.** The local 1.4.3 libraries reproduce all 11 reported pairs: four vertex shaders omit `locn1` or `locn6`, which their pixel partners read. Every failing pair is in the split's 4,159 BAHS pairs; none of the profile's 20,016 other pairs has a missing output. The shared fix makes padding read both tables; see [Pixel shader inputs the vertex shader does not write](../../../docs/reference/shaders.md#pixel-shader-inputs-the-vertex-shader-does-not-write). Targeted validation: the affected vertex sources compile for Mac and iOS, and every affected pair builds into `g13s` and `g16s` Metal archives with both depth entry points. This uses Metal 32023.921; the original TotK sources reproduce the reported rejection on that toolchain too. Full Mac rebuild: 28,669 of 28,669 shaders successful, no binding or pulling-library failures, no regressions, and no interface mismatches across all 24,175 pairs. The Mac host also rebuilt with the regenerated uniform tables. The complete `g16s` archive also succeeds: all 24,153 eligible bases, 1,306 MiB, Metal 32023.921 (2,494 s in the compiler with other builds running). The compiler peaked around 36 GB; a late sample was releasing `AIRNTDispose` / `LLVMContext` contexts. No new gameplay or iPhone run.
- **Current: prewarm capture reported in [PR #261](https://github.com/seedds/nxnative/pull/261).** The seed in `pso_manifest.tsv` contains 1,537 shader, 2,512 render-pipeline and 43 compute-pipeline rows, recorded on an M2 iPad Pro with update 1.4.3 on 2026-10-25 over about 33 minutes: boot, title, a save load and overworld exploration. The author reports no pipeline compilations in the second session's long frames with this list. This covers the recorded route, not the whole game; no new gameplay or cold-install validation here. The capture is separate from the shared deswizzle and symbol-index optimizations.
- Most RomFS files are zstd with dictionaries (`*.zs`); the dictionaries are `Pack/ZsDic.pack.zs`, which is also the profile's `romfs_marker`.
+- **Reported in [PR #369](https://github.com/seedds/nxnative/pull/369):** copying the 17 GB, 304,000-file RomFS folder with `devicectl` failed with `EMFILE`; synchronous deletion of a previous copy hit the iOS launch watchdog. Its author reports a 39 s image pack, about one minute to transfer, and gameplay on an iPhone. No new timing or gameplay check of this title is claimed here. The general image implementation and validation are described in [RomFS images](../../../docs/reference/packing.md#romfs-folder-transfers-fail-or-leave-stale-game-files).
- Shaders: `Shader/*.bfsha.zs` (BNSH; `material.bfsha` holds most) and the layout shaders in `Shader/ApplicationPackage.Nin_NX_NVN.release.sarc.zs`.
- **Resolved in the host: duplicate pipeline keys from unused colour state.** MacNativeGames commit `f3e2f66`, reported in [PR #196](https://github.com/seedds/nxnative/pull/196), found 8,479 of 24,146 recorded render pipelines (35%) differed only in unused state. The general normalization and prewarm deduplication are ported; this is the source project's measurement, with no new gameplay or prewarm-count measurement on this game here.
@@ -75,6 +76,8 @@ Game-specific findings. The general host changes they led to are listed under [F
General host changes first needed here; each applies to every game:
+- **RomFS folder transfer and startup deletion failures:** [RomFS images](../../../docs/reference/packing.md#romfs-folder-transfers-fail-or-leave-stale-game-files).
+
- **Resolved in the host (#342): recurring startup crash during archive compaction**, with a workaround for Metal's serializer defect: [Pipeline archive compaction crashes in Metal's serializer](../../../docs/reference/shaders.md#a-compaction-flush-that-crashes-then-crashes-every-start). Confirmed with local manifest replays; no new gameplay or iOS validation.
- **BAHS pairs omitted from vertex padding:** [Pixel shader inputs the vertex shader does not write](../../../docs/reference/shaders.md#pixel-shader-inputs-the-vertex-shader-does-not-write).
@@ -92,6 +95,7 @@ General host changes first needed here; each applies to every game:
- **Rewriter:** out-of-line atomic retry blocks (`retry_block` / `site_retry_window`, 8 sites) and jump tables relative to an `adr` (`jump_adr_offsets`, `main+0x393bb0`): [Out-of-line retry blocks of atomic updates](../../../docs/reference/rewriter.md#out-of-line-retry-blocks-of-atomic-updates), [Offset tables relative to an adr](../../../docs/reference/rewriter.md#offset-tables-relative-to-an-adr).
- **Resolved: black screen at boot since `9a56ecf` (issue #247), handoffs that waited for the whole core:** [Same-core wake handoffs](../../../docs/reference/threads.md#same-core-wake-handoffs). Each wake's handoff waited for every runnable higher-priority thread pinned to the caller's core. `BootupBackgroundWorkThread` (priority 58) then waited 200–290 ms at a time for `ARes Loading 1`, `Presentation Thread` and `BaseProcExecutor`, threads its wake had not made runnable. Checked on the Mac with update 1.4.3 and no shader libraries for chain `8393d85a4eae` (draws skipped), the issue #70 route for 180 s. On `82ab25b` the scene stayed empty (`84 functions 771 calls` a frame, no texture uploaded), and handoffs waited 250,008 ms in total. With handoffs limited to the threads the wake made runnable, they waited 1,221 ms, and the run matched `9feac2f` (before the change) frame by frame: 11 first uploads in both, 14,500–20,500 calls a frame. Gameplay with shaders has not been rechecked.
- **Slotted command lists** (`OP_RESERVE`, `t_nvn` "slotted lists"): [Prerecorded lists in slots of their measured size](../../../docs/reference/nvn-objects.md#prerecorded-lists-in-slots-of-their-measured-size).
+- **Resolved in the NSP script's extractor: a cartridge dump with the update on it** (1G+1U XCI, [PR #311](https://github.com/seedds/nxnative/pull/311)): [A cartridge dump with its update on it extracts the update as the base game](../../../docs/reference/packing.md#a-cartridge-dump-with-its-update-on-it-extracts-the-update-as-the-base-game).
## Open
diff --git a/dm/games/profile_guess.py b/dm/games/profile_guess.py
index 9b982386..dc4bde68 100644
--- a/dm/games/profile_guess.py
+++ b/dm/games/profile_guess.py
@@ -8,11 +8,12 @@
# cannot tell the games that need them (Tears of the Kingdom) from those that only use what they answer (Wonder's conditional clears, Breath of the Wild's flushed textures).
# Usage: profile_guess.py <ExeFS dir> <romfs_manifest.tsv | RomFS dir> the facts and the guessed keys
# profile_guess.py --check [<NSP root>] every profile in dm/games against its extraction under <NSP root> (default /Volumes/T7/nsp): where the guess differs
-import collections, os, re, struct, sys
+import collections, re, struct, sys
from pathlib import Path
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE.parent / 'tools')); import nso_syms # dynamic symbols, the host's hooks
+from romfs import Path, os, open, is_image, source
MAGICS = [(b'UnityFS\0', 'UnityFS'), (b'UnityWeb', 'UnityWeb'), (b'UnityRaw', 'UnityRaw'), (b'BNSH', 'BNSH'), (b'BAHS', 'BAHS'), (b'SARC', 'SARC'), (b'Yaz0', 'Yaz0'),
(bytes.fromhex('28b52ffd'), 'zstd'), (b'FRES', 'bfres'), (b'BNTX', 'BNTX'), (b'BWAV', 'BWAV'), (b'FSAR', 'BFSAR'), (b'CPK ', 'CRI CPK'), (b'CRID', 'CRI USM'),
@@ -51,7 +52,7 @@ def kind(m): # a short name for what a module is: its NintendoSDK component, G
def romfs_files(romfs): # (path, size, first 32 bytes) of every RomFS file: from nx_extract's manifest, or read from a RomFS folder
romfs = Path(romfs)
- if romfs.is_file():
+ if romfs.is_file() and not is_image(romfs):
for line in romfs.read_text(errors='replace').splitlines():
if line.startswith('#'): continue
path, size, head = line.split('\t'); yield path, int(size), bytes.fromhex(head)
@@ -343,12 +344,12 @@ def find_extraction(root, g): # (ExeFS, RomFS manifest or folder) for a profil
base = d / data
for v in [g.get('package', '')] + sorted(x.name for x in base.glob('v*')):
w = base / v
- if (w / 'ExeFS').is_dir() and (w / 'RomFS').is_dir(): return w / 'ExeFS', w / 'RomFS'
+ if (w / 'ExeFS').is_dir() and source(w).is_dir(): return w / 'ExeFS', source(w)
return None
def loose_nros(root, g, ex): # {name: path} of the loose NROs in a profile's RomFS: the extraction's own folder, else an NSP script extraction of the packed version beside its survey
- roms = [Path(ex[1])] if Path(ex[1]).is_dir() else [d / f'{g.id}_build/extract' / g.get('package', '') / 'RomFS' for d in sorted(Path(root).iterdir())]
+ roms = [Path(ex[1])] if Path(ex[1]).is_dir() else [source(d / f'{g.id}_build/extract' / g.get('package', '')) for d in sorted(Path(root).iterdir())]
rom = next((r for r in roms if r.is_dir()), None)
return {p.name: p for p in sorted(rom.rglob('*.nro')) if p.is_file()} if rom else {}
diff --git a/dm/gfx/nvn/hle_nvn.c b/dm/gfx/nvn/hle_nvn.c
index 7e3b2d12..a66cc0f7 100644
--- a/dm/gfx/nvn/hle_nvn.c
+++ b/dm/gfx/nvn/hle_nvn.c
@@ -1856,7 +1856,11 @@ NVN(nvnQueuePresentTexture, void, NVNqueue *q, NVNwindow *w, int idx) {
g_pres_iv[g_presn++ % TWIN] = a_ < 0 ? -1 : (a_ > 0 && b_ > 0 ? (a_ - b_) * 1e3 : 0);
{ double iv_ = a_ < 0 ? -1 : (a_ > 0 && b_ > 0 ? (a_ - b_) * 1e3 : 0); mtl_ub_present(iv_); } // same-process alternating measurement (DM_NVN_UB) tallies on-screen present intervals per phase; when off it is just one atomic read
dm_perf_present(a_ < 0 ? -1 : (a_ > 0 && b_ > 0 ? (a_ - b_) * 1e3 : 0)); // on-screen present intervals are also kept in a separate ring; tsummary reports dropped frames every 300 frames (M1 criterion)
- if (a_ > 0) trow(f - 8, "@pres_at_ms", a_ * 1e3 - g_t0_ns / 1e6); } // on-screen present time (ms since process start; presentedTime shares a time base with mach_absolute_time)
+ if (a_ > 0) trow(f - 8, "@pres_at_ms", a_ * 1e3 - g_t0_ns / 1e6); // on-screen present time (ms since process start; presentedTime shares a time base with mach_absolute_time)
+ // The display-link tick that took this frame: its target display time (same base as @pres_at_ms, so @pres_at_ms − @link_target_ms is how late the system showed it), the callback's lead
+ // before that target, the callbacks since the previous frame's (1 = every tick took a frame) and the longest interval between them (33 ms on a 60 Hz link = a refresh the link skipped)
+ double lt, ll, lg; int lk;
+ if (g_tsv && mtl_link_tick(n, &lt, &ll, &lk, &lg)) { trow(f - 8, "@link_target_ms", lt * 1e3 - g_t0_ns / 1e6); trow(f - 8, "@link_lead_ms", ll); trow(f - 8, "@link_ticks", lk); trow(f - 8, "@link_gap_ms", lg); } }
if (f >= 8 && slow_on()) slow_emit(f - 8);
prev_out = now_ns();
}
diff --git a/dm/gfx/nvn/nvn_mtl.m b/dm/gfx/nvn/nvn_mtl.m
index 63888ea7..8f753bc3 100644
--- a/dm/gfx/nvn/nvn_mtl.m
+++ b/dm/gfx/nvn/nvn_mtl.m
@@ -112,6 +112,7 @@ static pthread_cond_t g_link_cv = PTHREAD_COND_INITIALIZER;
static pthread_mutex_t g_link_mu = PTHREAD_MUTEX_INITIALIZER;
static uint64_t g_link_tick_ns, g_link_tick_n;
static uint64_t g_link_dropped;
+static uint64_t g_link_empty; // Under g_pq_mu: ticks that found no new frame queued (counted here, not as ticks minus presents: presents before the link starts and while it is rescued are not on ticks)
static double g_link_hold_until; static uint64_t g_link_held; // Changed only on the display-link callback thread: the time the previous frame must stay on screen until by its present interval (0 = no hold), and the ticks that took no new frame because of it
static int g_pq_inflight; // Under g_pq_mu: number of presents committed to the GPU whose completion callback has not arrived yet
int g_dm_present_link; // Present pacing mode (runtime value of DM_PRESENT_LINK, modified directly during same-process alternating measurement): 0 = acquire the drawable itself; 1 = display link at 60 Hz; 2 = display link at 120 Hz, the game presents a frame every other display-link tick
@@ -10111,6 +10112,14 @@ typedef struct { uint64_t n; double t; } pres_ent;
static pres_ent g_pres[PRING];
// Get the actual presentation time of the nth present (returns 0 if not ready, -1 if dropped)
double mtl_presented_time(uint64_t n) { pres_ent e = g_pres[n % PRING]; return e.n == n ? e.t : 0; }
+// Ring of the display-link tick that took each present (written on the display-link callback thread, read 8 presents later for DM_NVN_TSV, as g_pres): its target display time
+// (seconds, CACurrentMediaTime base), how long before it the callback ran, the callbacks since the previous present's (1 = no tick without a frame) and the longest interval between them
+typedef struct { uint64_t n; double target, lead_ms, gap_ms; int ticks; } link_ent;
+static link_ent g_link_ring[PRING];
+int mtl_link_tick(uint64_t n, double *target, double *lead_ms, int *ticks, double *gap_ms) {
+ link_ent e = g_link_ring[n % PRING]; if (e.n != n) return 0;
+ *target = e.target; *lead_ms = e.lead_ms; *ticks = e.ticks; *gap_ms = e.gap_ms; return 1;
+}
static _Atomic uint64_t g_drawable_ns; // Accumulated wall clock waiting for nextDrawable in present (timing instrumentation)
uint64_t mtl_drawable_ns_take(void) { return atomic_exchange(&g_drawable_ns, 0); }
// Maximum refresh rate (Hz) of the screen when there is a window; returns 0 without a window. Mac uses CoreGraphics display modes (thread-safe C interface; the present configuration is read on the game thread)
@@ -10451,7 +10460,7 @@ static int present_now(const tex_t *t, double period, uint64_t frame, uint64_t t
double b[300]; memcpy(b, e2e, sizeof b);
for (int i = 1; i < 300; i++) { double v = b[i]; int j = i - 1; while (j >= 0 && b[j] > v) { b[j + 1] = b[j]; j--; } b[j + 1] = v; }
MLOG("display link up to tick %llu: ticks 300, presents %llu, empty ticks %llu (held for the present interval %llu), old frames dropped by merging %llu; submission ahead of target display p50 %.3f ms / min %.3f ms; game enqueue to target display p50 %.3f ms / min %.3f / max %.3f ms",
- (unsigned long long)g_link_tick_n, (unsigned long long)g_present_n, (unsigned long long)(g_link_tick_n - g_present_n), (unsigned long long)g_link_held,
+ (unsigned long long)g_link_tick_n, (unsigned long long)g_present_n, (unsigned long long)g_link_empty, (unsigned long long)g_link_held,
(unsigned long long)g_link_dropped, a[149], a[0], b[149], b[0], b[299]);
}
}
@@ -10512,6 +10521,7 @@ __attribute__((weak)) uint64_t dm_focus_in_since(void) { return 0; }
@implementation NvMetalDisplayLinkDelegate
- (void)metalDisplayLink:(CAMetalDisplayLink *)link needsUpdate:(CAMetalDisplayLinkUpdate *)update {
(void)link;
+ double cb = CACurrentMediaTime();
pthread_mutex_lock(&g_pq_mu);
if (g_stall_t0) { uint64_t since = dm_focus_in_since(), t = now_ns();
MLOG("display link recovered: stalled %.0f ms (%.0f ms of it active), fallback dropped %llu frames (stall #%llu)", (t - g_stall_t0) / 1e6, (t - (g_stall_t0 > since ? g_stall_t0 : since)) / 1e6, (unsigned long long)g_stall_drop, (unsigned long long)g_stall_n); g_stall_t0 = 0; }
@@ -10523,13 +10533,16 @@ __attribute__((weak)) uint64_t dm_focus_in_since(void) { return 0; }
if (t < next - g_link_vhalf) return;
next += vp; tol += 2 * g_link_vhalf; // a tick lies up to half a refresh off its slot, so two of them up to one refresh nearer each other than the slots
}
+ static double cb_prev, gap_max; static int nticks; // for g_link_ring: callbacks counted as ticks since the previous present, and the longest interval between them
+ if (cb_prev > 0 && cb - cb_prev > gap_max) gap_max = cb - cb_prev;
+ cb_prev = cb; nticks++;
pthread_mutex_lock(&g_link_mu);
__atomic_store_n(&g_link_tick_ns, now_ns(), __ATOMIC_RELAXED);
g_link_tick_n++;
pthread_cond_broadcast(&g_link_cv);
pthread_mutex_unlock(&g_link_mu);
pthread_mutex_lock(&g_pq_mu);
- if (!g_dm_present_link || g_rescue_mode || g_pq_read == g_pq_in) { pthread_mutex_unlock(&g_pq_mu); return; }
+ if (!g_dm_present_link || g_rescue_mode || g_pq_read == g_pq_in) { if (g_dm_present_link && !g_rescue_mode) g_link_empty++; pthread_mutex_unlock(&g_pq_mu); return; }
// The previous frame's present interval was >= 2 (period > 25 ms): keep it on screen for its whole period before taking the next one, as the Switch flips only every N vertical syncs. This also holds while the link runs at 60 Hz (Mario 1.2.1 sets 2 for single frames, see nvn_game_fps in hle_nvn.c);
// before, every tick took the newest frame, so that frame, carrying the extra time step the game advanced for it, was shown for only 16.7 ms and the game looked like it jumped ahead
if (g_link_hold_until > 0 && update.targetPresentationTimestamp < g_link_hold_until - tol) { g_link_held++; pthread_mutex_unlock(&g_pq_mu); return; }
@@ -10543,6 +10556,7 @@ __attribute__((weak)) uint64_t dm_focus_in_since(void) { return 0; }
g_pq_read = ticket;
if (ticket > first) { g_link_dropped += ticket - first; for (uint64_t k = first; k < ticket; k++) g_pres[k % PRING] = (pres_ent){k, -1}; } // Old frames merged and dropped are recorded as "not presented", so the present statistics honestly count them as dropped frames
if (ticket > 1 && g_pq_done < ticket - 1) g_pq_done = ticket - 1;
+ g_link_ring[ticket % PRING] = (link_ent){ticket, update.targetPresentationTimestamp, (update.targetPresentationTimestamp - cb) * 1e3, gap_max * 1e3, nticks}; nticks = 0; gap_max = 0;
pthread_cond_broadcast(&g_pq_cv);
pthread_mutex_unlock(&g_pq_mu);
int submitted;
diff --git a/dm/gfx/nvn/nvn_obj.h b/dm/gfx/nvn/nvn_obj.h
index b6968a85..e9f8abc8 100644
--- a/dm/gfx/nvn/nvn_obj.h
+++ b/dm/gfx/nvn/nvn_obj.h
@@ -213,6 +213,7 @@ int mtl_link_wait_tick(int vsyncs, uint64_t timeout_ns); // vsyncs = the game'
int mtl_link_wait_ticks(int ticks, uint64_t timeout_ns); // the same in the display link's own ticks
int mtl_link_rate(void); // the display link's rate: 120, 60 or 30 Hz
double mtl_presented_time(uint64_t n);
+int mtl_link_tick(uint64_t n, double *target, double *lead_ms, int *ticks, double *gap_ms); // the display-link tick that took the n-th present (0 = none: no display link, or not taken yet)
int mtl_link_stalled(void); // the display link is silent (background, occluded window, a stall) and queued frames are dropped instead of shown
int mtl_snap_on(void); uint64_t mtl_snap_acquire_wait(void); // present snapshots (DM_PRESENT_SNAP): on, and acquire's wait for ring capacity (returns ns spent pacing)
// Actual presentation time (seconds) of the n-th present (counted from 1); 0 = not ready, −1 = dropped
diff --git a/dm/gfx/tools/cpk.py b/dm/gfx/tools/cpk.py
index f1ba4d8f..5c2c49b7 100644
--- a/dm/gfx/tools/cpk.py
+++ b/dm/gfx/tools/cpk.py
@@ -4,7 +4,9 @@
# DirName, FileName, FileSize (stored), ExtractSize, FileOffset (relative to the smaller of TocOffset and ContentOffset). A file whose stored size is smaller than its size is
# CRILAYLA-compressed (crilayla). The @UTF tables may be stored masked (Unicorn Overlord; unmask). shader_split.py reads every CPK through it (cpk_jobs).
# Usage: cpk.py <file.cpk> [--extract <dir> [<name regex>]] lists (or extracts) the files.
-import re, struct, sys
+import re, struct, sys, os
+sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../../tools'))
+from romfs import open
from pathlib import Path
def unmask(b):
diff --git a/dm/gfx/tools/gl_shaders.py b/dm/gfx/tools/gl_shaders.py
index 82943c6c..4ec87f71 100644
--- a/dm/gfx/tools/gl_shaders.py
+++ b/dm/gfx/tools/gl_shaders.py
@@ -23,6 +23,8 @@
# <TAB> where it came from
# Usage: gl_shaders.py <input path>... <out dir> [--ios <dir>] (input paths: the RomFS, the main NSO, capture folders)
import concurrent.futures as cf, hashlib, json, os, re, subprocess, sys, tempfile
+sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../../tools'))
+from romfs import os, open
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import mvgl
from dmsh_chain import SPIRV_CROSS # the in-repo spirv-cross build the NVN chain uses too (spirv_cross_bin)
@@ -64,7 +66,8 @@ def sources(roots):
st = 'vert' if nm.endswith('_vp.shad') else 'frag' if nm.endswith('_fp.shad') else None
yield text_of(a.read(nm)), st, f'/{os.path.relpath(p, r)}:{nm}'
elif fn.endswith(('.vert', '.frag')):
- yield text_of(open(p, 'rb').read()), fn.rsplit('.', 1)[1], '/' + os.path.relpath(p, r)
+ with open(p, 'rb') as f: source = text_of(f.read())
+ yield source, fn.rsplit('.', 1)[1], '/' + os.path.relpath(p, r)
# NVIDIA's GLSL compiler accepts more than the GLSL ES 3.20 specification, and glslang does not; these fix-ups run on the preprocessed text (glslang -E, so macros are expanded):
# · the GLSL ES 1.0 texture functions (89 of Digimon's fragment shaders call textureCube; with -V glslang reads textureCube as Vulkan's texture type, so a macro cannot rename it);
diff --git a/dm/gfx/tools/mvgl.py b/dm/gfx/tools/mvgl.py
index d1e1323f..35bb3d46 100644
--- a/dm/gfx/tools/mvgl.py
+++ b/dm/gfx/tools/mvgl.py
@@ -9,7 +9,9 @@
# bit 7 stored), the length and the stored length in that width, then the stream: a 32-bit control word per 32 items (bit 0 first, 0 = literal byte, 1 = match),
# refilled when only its sentinel bit is left; a match is 1 to 4 bytes by its low 3 bits (offset and length - 3, see MATCH). The last 8 bytes are always literals.
# Usage: mvgl.py list <archive> [ext] | mvgl.py get <archive> <name>.<ext> <out file>
-import struct, sys
+import os, struct, sys
+sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../../tools'))
+from romfs import os, open
MATCH = [(0xff, 2, 0, 0, 1), (0xffff, 2, 0, 0, 2), (0xffff, 6, 15, 2, 2), (0xffffff, 8, 31, 3, 3),
(0xff, 2, 0, 0, 1), (0xffff, 2, 0, 0, 2), (0xffff, 6, 15, 2, 2), (0xffffffff, 11, 255, 3, 4)] # mask, offset shift, length mask, length shift, size
diff --git a/dm/gfx/tools/shader_split.py b/dm/gfx/tools/shader_split.py
index 6c41fa37..94a4a3ae 100644
--- a/dm/gfx/tools/shader_split.py
+++ b/dm/gfx/tools/shader_split.py
@@ -50,6 +50,8 @@
# Unity type trees need Unity's common string table, which is taken from the first main
# Pair table: (vertex key, pixel key) of every BNSH variation (every Unity program); dmsh_build uses it to give vertex shaders the outputs their pixel shaders read but they do not write (see dmsh_build.py vs_pad)
import collections, concurrent.futures as cf, hashlib, json, os, re, struct, subprocess, sys, zlib
+sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../../tools'))
+from romfs import os, open, is_image
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../games')); import game as _game
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))); import uepak
GAME = _game.load() # the current game profile (DM_GAME, required): source group rules and the table header note
@@ -350,7 +352,7 @@ def idrk_shaders(path, label, out):
as GLSLC compiler outputs (glslc_shaders). One '_DOK0000' container (type KTID 0x20a6a0bb, the engine's system resources; once in system.rdb.bin and once in the update's .bin1) holds 151 bare
GLSLC outputs without a G2S wrapper, among them 21 shaders the first battle draws. No other entry type holds any. The RDB files are up to 3.8 GB, so they are mapped rather than read,
and only entries whose data starts with one of those two magics are inflated"""
- import mmap
+ from romfs import mmap
with open(path, 'rb') as f, mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as d:
for a, b, flags in idrk_entries(d):
if idrk_data(d, a, b, flags, 4) in (b'_S2G', b'_DOK'): out.extend(glslc_shaders(idrk_data(d, a, b, flags), f'{label}#IDRK@{a:#x}', need=False))
@@ -396,7 +398,7 @@ def linkdata_jobs(path, rel, parts=64):
return jobs
def linkdata_shaders(path, rel, rng, out):
- import mmap
+ from romfs import mmap
with open(os.path.join(os.path.dirname(path), 'DATA0.bin'), 'rb') as f: idx = f.read()
with open(path, 'rb') as f, mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as d:
for i in range(*rng):
@@ -463,7 +465,7 @@ def sdf_shaders(d, label):
return out
def kpka_shaders(path, rel, ents, out):
- import mmap
+ from romfs import mmap
with open(path, 'rb') as f, mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as d:
for e in ents:
if e[3] >= 0x10 and kpka_data(d, e, 4) == b'SDF\0': out.extend(sdf_shaders(kpka_data(d, e), f'/{rel}#{e[0]:016x}'))
@@ -551,7 +553,7 @@ def zip_jobs(files, parts=64):
with open(p, 'rb') as f: h = f.read(4)
if h != ZIP: continue
try:
- with zipfile.ZipFile(p) as z: zs.append((p, r, [(i.filename, i.file_size) for i in z.infolist() if not i.is_dir()]))
+ with open(p, 'rb') as source, zipfile.ZipFile(source) as z: zs.append((p, r, [(i.filename, i.file_size) for i in z.infolist() if not i.is_dir()]))
except (zipfile.BadZipFile, OSError, ValueError) as e: print(f'[RED] /{r}: the zip cannot be read ({e}); scanned as one file', flush=True)
jobs, step = [], sum(n for _, _, es in zs for _, n in es) / parts
for p, r, es in zs:
@@ -566,7 +568,7 @@ def zip_shaders(path, rel, names, out):
"""A range of zip members (zip_jobs), each inflated and scanned like a loose file: scan_blob, then whole GLSLC outputs (Portal's .nvsb files: a 0x60-byte 'NVSB' header, then one
GLSLC output of a vertex and a pixel shader)"""
import zipfile
- with zipfile.ZipFile(path) as z:
+ with open(path, 'rb') as source, zipfile.ZipFile(source) as z:
for nm in names:
d = z.read(nm); n = len(out)
scan_blob(d, f'/{rel}/{nm}', out)
@@ -819,16 +821,20 @@ def gfpak_members(d, label):
yield f'#{i}', data
NLG_DICT = bytes.fromhex('5824f3a9')
-def nlg_dict(d):
+def nlg_dict(d, label):
"""Next Level Games' archive index (Luigi's Mansion 3: '<name>.dict' beside '<name>.data', every RomFS file but the Wwise banks): u32 magic 0xa9f32458, u8 4, u8 1, u8 compressed,
u8 0, u32 the largest stored chunk, u8 chunk count, u8 record count, u8 name count, u8 0; then one 0x18-byte record per variant {u32 hash, u16 top-level entry count of its
table, u16, u8 chunk of each of its 16 sections (0 = none)}, one 0x10-byte chunk per piece of data {u32 offset, u32 length, u32 stored length (one zlib stream), u16 alignment
(log2 in the low 5 bits), u8 file, u8 GPU memory}, and the file names ('.data', '.debug', '.nxpc'). Record v's own entry table is chunk v: 12 bytes per entry {u32 kind (bit 31: a
list of w1 entries from entry w2; bits 27..30 section; bits 22..26 log2 alignment), u32 length, u32 offset in the section}. The game reads the archive in main+0x1ba00 (Luigi's
Mansion 3 1.4.0). → (compressed, records [(top, chunks)], chunks [(offset, length, stored, file)], file names)"""
- comp, nchunk, nrec, nname = d[6], d[0xc], d[0xd], d[0xe]
- recs = [(struct.unpack_from('<H', d, 0x14 + 0x18 * i)[0], list(d[0x18 + 0x18 * i:0x28 + 0x18 * i])) for i in range(nrec)]
+ nchunk, nrec = (d[0xc], d[0xd]) if len(d) >= 0x10 else (0, 0)
co = 0x10 + 0x18 * nrec
+ # The layout above, checked before it is read: Mario Strikers: Battle League's (another revision, PR #282) stopped the split with an IndexError that named no file
+ if len(d) < co + 0x10 * nchunk or nrec > nchunk or any(c >= nchunk for i in range(nrec) for c in d[0x18 + 0x18 * i:0x28 + 0x18 * i]):
+ red(f'{label}: the index ({len(d):#x} bytes, header {d[4:0x10].hex(" ")}) is not in the layout of Luigi\'s Mansion 3\'s archives, the only one nlg_dict reads')
+ comp, nname = d[6], d[0xe]
+ recs = [(struct.unpack_from('<H', d, 0x14 + 0x18 * i)[0], list(d[0x18 + 0x18 * i:0x28 + 0x18 * i])) for i in range(nrec)]
chunks = [struct.unpack_from('<3I2xB', d, co + 0x10 * i) for i in range(nchunk)]
names = d[co + 0x10 * nchunk:].split(b'\0')[:nname]
return comp, recs, chunks, [n.decode('latin-1') for n in names]
@@ -866,7 +872,7 @@ def nlg_shaders(path, label, out):
Every variant whose files are in RomFS is read (the 13 even records; the odd ones point into '.nxpc', which is not shipped), and the shaders found pair by order (checked one by one)"""
import zlib
d = open(path, 'rb').read(); stem = path[:-len('.dict')]
- comp, recs, chunks, names = nlg_dict(d)
+ comp, recs, chunks, names = nlg_dict(d, label)
files = {i: open(stem + nm, 'rb').read() for i, nm in enumerate(names) if os.path.exists(stem + nm)}
patch = open(stem + '.patch', 'rb').read() if os.path.exists(stem + '.patch') else None
cache = {}
@@ -965,7 +971,7 @@ def bnd3_members(d, label):
def bdt_shaders(path, rel, ents, out):
"""Dark Souls Remastered's shaders: GLSLC outputs, one per BND3 entry ('.vpo' vertex, '.fpo' pixel; 3,225 in six DCX-compressed BND3 archives in dvdbnd0.bdt, 3,088 of them the
FLVER material shaders). The engine combines vertex and pixel shaders per draw, so they are paired as single-stage programs (separable_pairs)"""
- import mmap
+ from romfs import mmap
with open(path, 'rb') as f, mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as m:
for h, off, n in ents:
label = f'/{rel}#{h:08x}'; d = m[off:off + n]
@@ -1403,7 +1409,7 @@ def trpfs_jobs(files, parts=64):
0 file hashes [u64], 1 pack names [string], 2 file infos [{0 pack index u64}] (in file hash order), 3 pack infos [{0 pack size u64, 1 file count u64}]. The file system: 'ONEPACK\\0', u64 offset of its
root table {0 pack name hashes [u64], 1 pack offsets [u64]}, each pack a table of its own at its offset. A pack is named through its first file's hash (its own name hash is not a plain FNV-1a of the
descriptor's name). → ([(path, rel, ((pack offset, pack name), …)), …] in about equal sizes, the paths taken)"""
- import mmap
+ from romfs import mmap
jobs, taken = [], set()
for p, r in files:
if not p.endswith('.trpfs') or not os.path.exists(p[:-1] + 'd'): continue
@@ -1448,7 +1454,8 @@ def smash_arc_jobs(files, parts=128):
def smash_arc_shaders(path, rel, ents, out):
"""Each file of a range scanned as a file of its own: GLSLC outputs in the SSBH shader databases ('HBSS' … 'RDHS', the .nushdb files: 41 in 13.0.5), BNSH in the effects ('EFFN') and the UI
layout archives (SARC). Labels name the file by its format (an SSBH resource by its type, 'SHDR') and its path's hash40: /data.arc/SHDR#<hash40>"""
- import mmap, smash_arc
+ from romfs import mmap
+ import smash_arc
with open(path, 'rb') as f, mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as d:
for e in ents:
if not e[3]: continue
@@ -1481,7 +1488,7 @@ def oodle(comp, n):
def trinity_shaders(path, rel, packs, out):
"""A range of Trinity packs (trpfs_jobs). Pack table: 0 file hashes [u64], 1 files [{1 compression i8 (3 = Oodle; stored otherwise), 2 level u8, 3 length u64, 4 data [u8]}]; each file is scanned like a loose one"""
- import mmap
+ from romfs import mmap
with open(path, 'rb') as f, mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as d:
for off, name in packs:
pr = fb_root(d, off); hs = fb_vec(d, pr, 0)
@@ -2008,7 +2015,17 @@ def var_pairs(found):
return {(v['vs'], v['ps']) + (('prog',) if '#BAHS#prog' in g else ()) for g, v in var.items() if 'vs' in v and 'ps' in v}
def scan_file(args):
- """→ (relative path, {key: …}, pairs, extra); extra = this file's Unity type trees, or 'defer' (no type tree, scanned again in the second pass)"""
+ """→ (relative path, {key: …}, pairs, extra); extra = this file's Unity type trees, 'defer' (no type tree, scanned again in the second pass), or ('unreadable', why).
+ A file no reader can read (a format revision the reader does not know: its red line, or the exception it raised) is left out, and the split goes on: one such
+ archive used to end the whole split with nothing written (PR #282: one of Mario Strikers: Battle League's 879 Next Level Games archives). main reports them"""
+ try: return scan_file_in(args)
+ except (Exception, SystemExit) as e: # red() is a SystemExit
+ why = str(e).removeprefix('[RED] ') if isinstance(e, SystemExit) else f'{type(e).__name__}: {e}'
+ if not why.lstrip('/').startswith(args[1]): why = f'{args[1]}: {why}' # most red lines name the file already
+ print(f'[RED] {why} (its shaders are left out)', flush=True)
+ return args[1], {}, set(), ('unreadable', why)
+
+def scan_file_in(args):
path, rel = args[:2]
stem, ext = os.path.splitext(path)
if ext in ('.data', '.patch', '.debug', '.nxpc') and os.path.exists(stem + '.dict'): return rel, {}, set(), {} # read through its Next Level Games index (nlg_shaders)
@@ -2145,7 +2162,8 @@ def main():
for nm in names: found += ue_shaders(open(os.path.join(ued, nm), 'rb').read(), f'/ue_shaders/{nm}')
results.append(('main', {skey(c, k): (w, s, c, k) for w, s, c, k in found}, var_pairs(found), {}))
for romfs in dlc_v:
- tag = 'aoc/' + os.path.basename(os.path.normpath(romfs))
+ name = os.path.basename(os.path.normpath(romfs))
+ tag = 'aoc/' + (name.removesuffix('.img') if is_image(romfs) else name)
files += sorted((os.path.join(dp, f), tag + '/' + os.path.relpath(os.path.join(dp, f), romfs)) for dp, _, fs in os.walk(romfs) for f in fs)
zdicts = {k: v for r in romfs_v + dlc_v for k, v in zs_dicts(r).items()} # Tears of the Kingdom's zstd dictionaries (zs_dicts)
keys = {}
@@ -2168,7 +2186,7 @@ def main():
trees, defer = {}, []
for rel, uniq, pr, extra in results:
if extra == 'defer': defer.append(rel)
- elif extra: trees.update(extra)
+ elif isinstance(extra, dict): trees.update(extra)
if defer:
# a hash no bundle supplied takes the layout unityfs.py has for it (KNOWN_TREES); only here, so files a bundle lends a tree to keep their place in the tables (Ace Attorney's built-ins)
import unityfs
@@ -2178,6 +2196,8 @@ def main():
for rel, uniq, pr, extra in again:
if extra == 'defer': red(f'{rel}: Unity serialized file without type trees, and no bundle has a Shader type tree of the same hash to borrow')
results = [r for r in results if r[3] != 'defer'] + again
+ bad = [extra[1] for *_, extra in results if isinstance(extra, tuple)]
+ if bad: print(f'[RED] {len(bad)} file(s) could not be read, their shaders are left out (first: {bad[0]})', flush=True) # build_ipa_from_nsp.py reads this line
per_src = collections.Counter(); pairs = set()
for rel, uniq, pr, _ in results:
pairs |= pr
diff --git a/dm/gfx/tools/smash_arc.py b/dm/gfx/tools/smash_arc.py
index 1cd76e8a..b12fe88a 100644
--- a/dm/gfx/tools/smash_arc.py
+++ b/dm/gfx/tools/smash_arc.py
@@ -1,7 +1,9 @@
#!/usr/bin/env python3
"""Super Smash Bros. Ultimate's data.arc: the file-system table and the current file of each path (files), and a file's bytes (read). Used by shader_split.py (its shaders) and
dm/tools/nro_collect.py (its NROs). The paths are only Hash40 values (CRC-32 of the path and its length); the extension Hash40 (crc32(b'nro') | 3 << 32) tells a file's kind."""
-import struct, sys
+import os, struct, sys
+sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../../tools'))
+from romfs import os, open
MAGIC = struct.pack('<Q', 0xABCDEF9876543210)
ZSTD_MAGIC = bytes.fromhex('28b52ffd')
diff --git a/dm/gfx/tools/uepak.py b/dm/gfx/tools/uepak.py
index 7288288c..97ad9364 100644
--- a/dm/gfx/tools/uepak.py
+++ b/dm/gfx/tools/uepak.py
@@ -36,6 +36,8 @@
# decoded at once); IoStore shader libraries (UE 5.6) decoded at once through the game's Oodle in the host (OodleHost)
# uepak.py finish <work dir> <out dir> after the host has run the job: the archives with every shader decoded
import ctypes, json, os, struct, sys
+sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../../tools'))
+from romfs import os, open
PAK_MAGIC, ARCHIVE_VERSION = 0x5A6F12E1, 2
JOB_MAGIC, OUT_MAGIC = 0x4a4f4d44, 0x524f4d44 # "DMOJ", "DMOR" (hle_oodle.c)
diff --git a/dm/gfx/tools/vk_shaders.py b/dm/gfx/tools/vk_shaders.py
index 93e6c57e..3a1cec7e 100644
--- a/dm/gfx/tools/vk_shaders.py
+++ b/dm/gfx/tools/vk_shaders.py
@@ -22,6 +22,8 @@
# p push constants)
# Usage: vk_shaders.py <SPIR-V dir>... <out dir> [--ios <dir>] (SPIR-V dirs: the RomFS, capture folders)
import concurrent.futures as cf, hashlib, json, os, re, struct, subprocess, sys, tempfile
+sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../../tools'))
+from romfs import os, open
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from dmsh_chain import SPIRV_CROSS # the in-repo spirv-cross build the NVN chain uses too (spirv_cross_bin)
diff --git a/dm/host/Makefile b/dm/host/Makefile
index 20fc9524..e820e8b8 100644
--- a/dm/host/Makefile
+++ b/dm/host/Makefile
@@ -50,7 +50,7 @@ endif
endif
.PHONY: FORCE
FORCE:
-dmhost: $(SRC) $(GFX) ../third_party/stb_vorbis/stb_vorbis.c dm.h hle.h dm_input.h pad_slots.h hle_haptics.h haptics_apple.h front.h $(GFX_H) $(GAME_H) $(GAME_STAMP) $(VPX_LIB)
+dmhost: $(SRC) $(GFX) ../third_party/stb_vorbis/stb_vorbis.c dm.h hle.h romfs_image.h dm_input.h pad_slots.h hle_haptics.h haptics_apple.h front.h $(GFX_H) $(GAME_H) $(GAME_STAMP) $(VPX_LIB)
clang $(CFLAGS) -I../gfx/nvn/include -I../third_party/vulkan-headers/include -I$(dir $(GAME_H)) -I$(VPX) -I../third_party/stb_vorbis -fobjc-arc -o $@ $(SRC) $(GFX) $(VPX_LIB) -framework Cocoa -framework QuartzCore -framework Metal -framework MetalFX -framework GameController -framework CoreHaptics -framework IOKit -framework AudioToolbox -framework VideoToolbox -framework CoreMedia -framework CoreVideo -framework ImageIO -framework UniformTypeIdentifiers
clean: # the host and everything make generates for it (gen/: the profile headers, the game stamp and the libvpx build; dmhost_* and *.dSYM beside them, as in .gitignore)
rm -rf gen dmhost dmhost_* *.dSYM
diff --git a/dm/host/hle_fs.c b/dm/host/hle_fs.c
index 2285c439..f1089b93 100644
--- a/dm/host/hle_fs.c
+++ b/dm/host/hle_fs.c
@@ -17,6 +17,7 @@
#include <stdatomic.h>
#include <sys/clonefile.h>
#include <sys/xattr.h>
+#include "romfs_image.h"
// Every take-over in this file runs on the big host stack (hle_bigstack.c): path buffers are sized by PATH_MAX and one file open takes 6-7 KB of stack, while a game's save thread can have as little as 8 KB (Super Mario 3D World + Bowser's Fury)
#undef HLE_FORCE
@@ -36,8 +37,16 @@ _Static_assert(sizeof(DirectoryEntry) == 0x310, "DirectoryEntry layout");
// Host: at mount, the committed directory commit (= $DM_SAVE) is clonefile'd as a whole tree into the working directory <commit>.work (APFS copy-on-write, nearly zero cost), and the mount points at the working directory,
// all game reads and writes happen in the working directory; Commit = clonefile(work → <commit>.new), then renamex_np(RENAME_SWAP) swaps it atomically with commit, then the swapped-out old version is deleted.
// Killed at any moment, commit is either the old version or the new version, never half-written / a mix of old and new; the next mount discards leftover .work / .new.
+// RomFS image (dm/tools/romfs_image.py): DM_ROMFS may name one image file instead of a folder. Its index is read at mount; a file handle is then an entry of the image
+// (IMG_HANDLE, bit 62 set, never a valid fd), read with pread at its offset in the one descriptor kept open, and a directory lists its consecutive child entries.
+// One file instead of a few hundred thousand copies to an iPhone at full speed: a folder copy of Tears of the Kingdom's 304,000 files ran the phone's file service out of open files
+#define IMG_HANDLE(mi, k) ((1ull << 62) | ((uint64_t)(mi) << 32) | (uint64_t)(k))
+#define IMG_H(h) (((h) >> 62) == 1)
+#define IMG_M(h) ((int)(((h) >> 32) & 0x3fffffff))
+#define IMG_K(h) ((uint32_t)(h))
typedef struct {
char name[32]; char dir[1024]; char overlay[4096]; char commit[1024];
+ romfs_img *img; // non-NULL: dir is a RomFS image file
int ro;
int txn_root; // canonical mount entry for this backing transaction, or -1
_Atomic int poison; // failure state belongs to this backing, not to the process
@@ -115,6 +124,53 @@ static int dm_fs_test_fail(const char *pt) {
}
static int in_txn_dir(const char *hp) { return save_txn_from_path(hp); }
static int rm_tree(const char *p);
+// Reads and checks a RomFS image's header and index; NULL (and a red line) when it is not a complete image
+static romfs_img *img_open(const char *path) {
+ romfs_img *m = romfs_image_open(path);
+ if (m) LOG("fs RomFS image %s: %llu entries", path, (unsigned long long)m->n);
+ else LOG("[RED] fs RomFS image %s is not a complete image (copied in part? errno=%d)", path, errno);
+ return m;
+}
+// The entry a path names in an image: each component is a binary search of its directory's children, which the packer sorted by name (bytes, a shorter prefix first)
+static int64_t img_find(const romfs_img *m, const char *rest) {
+ uint64_t k = 0;
+ while (*rest) {
+ while (*rest == '/') rest++;
+ if (!*rest) break;
+ const char *end = strchr(rest, '/'); if (!end) end = rest + strlen(rest);
+ size_t len = end - rest;
+ if (!(len == 1 && rest[0] == '.')) {
+ if (m->e[k].type) { errno = ENOTDIR; return -1; }
+ uint64_t lo = m->e[k].a, hi = lo + m->e[k].b; int found = 0;
+ while (lo < hi) {
+ uint64_t mid = lo + (hi - lo) / 2; const img_ent *x = &m->e[mid];
+ int c = memcmp(m->names + x->name, rest, x->nlen < len ? x->nlen : len);
+ if (!c) c = (x->nlen > len) - (x->nlen < len);
+ if (!c) { k = mid; found = 1; break; }
+ if (c < 0) lo = mid + 1; else hi = mid;
+ }
+ if (!found) { errno = ENOENT; return -1; }
+ }
+ rest = end;
+ }
+ return (int64_t)k;
+}
+static int norm_rest(const char *rest, char *out, size_t n);
+static int rom_overlay_path(const mount_t *m, const char *rest, char *out, size_t n);
+// A path on an image mount: returns 1 with the mount in *mi and the entry in *k (-1 with errno set when there is none); 0 for a path on any other mount, or one an overlay folder (DM_ROMFS_OVERLAY) has, which then opens as a host file
+static int img_path(const char *p, int *mi, int64_t *k) {
+ PATH_LOCK(); const char *c = p ? strchr(p, ':') : NULL; if (!c) return 0;
+ size_t ln = c - p;
+ for (int i = 0; i < g_nmnt; i++) {
+ if (strlen(g_mnt[i].name) != ln || strncmp(g_mnt[i].name, p, ln)) continue;
+ if (!g_mnt[i].img) return 0;
+ char normed[1024]; const char *rest = c + 1; *mi = i;
+ if (strstr(rest, "/.")) { if (!norm_rest(rest, normed, sizeof normed)) { *k = -1; return 1; } rest = normed; }
+ char ov[1024]; if (g_mnt[i].overlay[0] && rom_overlay_path(&g_mnt[i], rest, ov, sizeof ov)) return 0;
+ *k = img_find(g_mnt[i].img, rest); return 1;
+ }
+ return 0;
+}
static Result mount_ex(const char *name, const char *dir, int ro, int txn) {
pthread_once(&g_txn_lock_once, txn_locks_init);
PATH_LOCK(); pthread_mutex_lock(&g_lock);
@@ -151,6 +207,11 @@ static Result mount_ex(const char *name, const char *dir, int ro, int txn) {
atomic_store(&g_mnt[g_nmnt].first_write_ns, 0);
strlcpy(g_mnt[g_nmnt].dir, work, sizeof g_mnt[0].dir); }
} else strlcpy(g_mnt[g_nmnt].dir, dir, sizeof g_mnt[0].dir);
+ g_mnt[g_nmnt].img = NULL;
+ struct stat ist;
+ if (ro && !txn && !stat(dir, &ist) && S_ISREG(ist.st_mode)) { // a RomFS image file in place of a folder
+ if (!(g_mnt[g_nmnt].img = img_open(dir))) die("the game files %s are not a complete RomFS image", dir);
+ }
g_nmnt++;
pthread_mutex_unlock(&g_lock);
if (txn_err) front_save_failed(txn_err);
@@ -271,7 +332,7 @@ static int rom_overlay_path(const mount_t *m, const char *rest, char *out, size_
strlcpy(out, candidate, n); free(roots); return 1;
}
}
- int found = root_path(m->dir, rest, out, n) && !access(out, F_OK);
+ int found = !m->img && root_path(m->dir, rest, out, n) && !access(out, F_OK); // an image base is looked up by img_path
free(roots);
if (found) return 1;
errno = ENOENT; return 0;
@@ -425,11 +486,22 @@ static void romfs_tables(const char *dir, size_t *ndir, size_t *dbytes, size_t *
}
static size_t romfs_work_size(const char *dir) {
size_t ndir = 1, dbytes = 0x18, nfile = 0, fbytes = 0; // the root directory has an entry with an empty name
- romfs_tables(dir, &ndir, &dbytes, &nfile, &fbytes, 0);
+ struct stat st;
+ if (!stat(dir, &st) && S_ISREG(st.st_mode)) {
+ romfs_img *m = img_open(dir);
+ if (!m) return 0x1000;
+ for (uint64_t k = 1; k < m->n; k++) {
+ const img_ent *e = &m->e[k]; size_t name = (e->nlen + 3) & ~(size_t)3;
+ if (e->type) { nfile++; fbytes += 0x20 + name; }
+ else { ndir++; dbytes += 0x18 + name; }
+ }
+ romfs_image_close(m);
+ } else romfs_tables(dir, &ndir, &dbytes, &nfile, &fbytes, 0);
return 4 * romfs_buckets(ndir) + dbytes + 4 * romfs_buckets(nfile) + fbytes;
}
static int aoc_dir(char *dir, size_t n, int index) {
const char *base = getenv("DM_AOC_DIR"); struct stat st;
+ if (base && *base && snprintf(dir, n, "%s/%d.img", base, index) < (int)n && !stat(dir, &st) && S_ISREG(st.st_mode)) return 1;
return base && *base && snprintf(dir, n, "%s/%d", base, index) < (int)n && !stat(dir, &st) && S_ISDIR(st.st_mode);
}
HLE_FORCE("_ZN2nn2fs31QueryMountAddOnContentCacheSizeEPmi", "fsp-srv; add-on content reads the host directory directly, the cache is the size of its RomFS file table", Result, h_fs_QueryAocCache, size_t *out, int index) {
@@ -694,6 +766,15 @@ static int arc_file(const char *hp, uint32_t *shard, uint64_t *off, uint64_t *si
static int arc_dir(const char *hp) { return romfsarc_is_dir(arc_rel(hp)); }
static void arc_norm(const char *hp, char *rel, size_t n) { strlcpy(rel, arc_rel(hp), n); }
HLE_FORCE("_ZN2nn2fs8OpenFileEPNS0_10FileHandleEPKci", "fsp-srv → open(2)", Result, h_fs_OpenFile, uint64_t *out, const char *path, int mode) {
+ int mi; int64_t k;
+ if (img_path(path, &mi, &k)) {
+ if (k < 0) return err_res("open", path);
+ if (!g_mnt[mi].img->e[k].type) return RES_PATH_NOT_FOUND;
+ if (mode & (MODE_WRITE | MODE_APPEND)) { LOG("fs write to a read-only mount: %s", path); return RES_FAIL; }
+ *out = IMG_HANDLE(mi, k);
+ if (g_flag.fs) LOG("fs open [%.2fs] %s mode=%d → image entry %lld", (now_ns() - g_t0_ns) / 1e9, path, mode, (long long)k);
+ return RES_OK;
+ }
HP(path);
if (mode & (MODE_WRITE | MODE_APPEND)) RW();
if (ROMFSARC_IS_SYNTH(hp)) { // archive entry: no fd, the handle carries shard/offset/size
@@ -721,7 +802,12 @@ HLE_FORCE("_ZN2nn2fs8OpenFileEPNS0_10FileHandleEPKci", "fsp-srv → open(2)", Re
}
HLE_FORCE("_ZN2nn2fs8ReadFileEPmNS0_10FileHandleElPvm", "fsp-srv → pread(2)", Result, h_fs_ReadFile, size_t *out, uint64_t h, int64_t off, void *buf, size_t sz) {
if (!h) { *out = 0; return RES_FAIL; } // a file handle is an fd; 0 is stdin and never a file the game opened: the null handle the game keeps using after a failed open
- size_t got = 0; int reprep = 0;
+ size_t got = 0; int reprep = 0, fd = (int)h; int64_t base = 0;
+ if (IMG_H(h)) { // an image entry: read the image's descriptor at the entry's offset, never past its end
+ const img_ent *x = &g_mnt[IMG_M(h)].img->e[IMG_K(h)];
+ fd = g_mnt[IMG_M(h)].img->fd; base = (int64_t)x->a;
+ sz = off < 0 || (uint64_t)off >= x->b ? 0 : (size_t)(x->b - off) < sz ? (size_t)(x->b - off) : sz;
+ }
dm_guest_write_prepare(buf, sz); // The destination may be a texture pool page write-protected by the graphics layer: a kernel write to a read-only page returns EFAULT instead of page-faulting, so unprotect and mark dirty first
archandle *ah;
if (arc_get(h, &ah)) { // archive entry: clamp to the file, read from its shard
@@ -738,7 +824,7 @@ HLE_FORCE("_ZN2nn2fs8ReadFileEPmNS0_10FileHandleElPvm", "fsp-srv → pread(2)",
return RES_OK;
}
while (got < sz) {
- ssize_t r = pread((int)h, (uint8_t *)buf + got, sz - got, off + got);
+ ssize_t r = pread(fd, (uint8_t *)buf + got, sz - got, base + off + got);
if (r < 0) { if (errno == EINTR) continue;
// The graphics layer write-protects tracked pages again after each upload (nvn_dirty.c), so a page made writable above can be read-only again by the time pread
// writes it: a plain write would fault into the tracker's handler, a system call gets EFAULT. Prepare the rest again (unprotect, mark dirty) and read on. Monster Train 2
@@ -759,8 +845,8 @@ HLE_FORCE("_ZN2nn2fs8ReadFileEPmNS0_10FileHandleElPvm", "fsp-srv → pread(2)",
if (g_fslog) { pthread_mutex_lock(&g_fslog_lock);
static int hash_on = -1; if (hash_on < 0) hash_on = getenv("DM_FSLOG_HASH") != NULL; // DM_FSLOG_HASH=1: append a column with the FNV-1a 64 of the content read (to compare whether the bytes read from two resource packs match)
uint64_t fh = 0xcbf29ce484222325ull; if (hash_on) for (size_t i = 0; i < got; i++) fh = (fh ^ ((uint8_t *)buf)[i]) * 0x100000001b3ull;
- if (hash_on) fprintf(g_fslog, "%.4f\t%s\t%lld\t%zu\t%p\t%016llx\n", (now_ns() - g_t0_ns) / 1e9, (int)h < 4096 && g_fdpath[(int)h] ? g_fdpath[(int)h] : "?", (long long)off, got, buf, (unsigned long long)fh);
- else fprintf(g_fslog, "%.4f\t%s\t%lld\t%zu\t%p\n", (now_ns() - g_t0_ns) / 1e9, (int)h < 4096 && g_fdpath[(int)h] ? g_fdpath[(int)h] : "?", (long long)off, got, buf);
+ if (hash_on) fprintf(g_fslog, "%.4f\t%s\t%lld\t%zu\t%p\t%016llx\n", (now_ns() - g_t0_ns) / 1e9, !IMG_H(h) && (int)h < 4096 && g_fdpath[(int)h] ? g_fdpath[(int)h] : "?", (long long)off, got, buf, (unsigned long long)fh);
+ else fprintf(g_fslog, "%.4f\t%s\t%lld\t%zu\t%p\n", (now_ns() - g_t0_ns) / 1e9, !IMG_H(h) && (int)h < 4096 && g_fdpath[(int)h] ? g_fdpath[(int)h] : "?", (long long)off, got, buf);
pthread_mutex_unlock(&g_fslog_lock); }
if (g_flag.fs) { // Read metering: print a line every 64 MiB accumulated or every 1000 reads
static uint64_t n, bytes, next_b = 64 << 20; static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
@@ -771,7 +857,7 @@ HLE_FORCE("_ZN2nn2fs8ReadFileEPmNS0_10FileHandleElPvm", "fsp-srv → pread(2)",
return RES_OK;
}
HLE_FORCE("_ZN2nn2fs9WriteFileENS0_10FileHandleElPKvmRKNS0_11WriteOptionE", "fsp-srv → pwrite(2)", Result, h_fs_WriteFile, uint64_t h, int64_t off, const void *buf, size_t sz, const void *opt) {
- if (!h) return RES_FAIL;
+ if (!h || IMG_H(h)) return RES_FAIL;
int fd = (int)h & 0xffff; uint16_t token = atomic_load(&g_ftxn[fd]); int txn = token ? token - 1 : -1;
pthread_rwlock_t *txn_guard __attribute__((cleanup(txn_unlock))) = NULL;
if (txn >= 0) { txn_guard = &g_txn_lock[txn]; pthread_rwlock_rdlock(txn_guard); }
@@ -794,11 +880,12 @@ HLE_FORCE("_ZN2nn2fs9WriteFileENS0_10FileHandleElPKvmRKNS0_11WriteOptionE", "fsp
HLE_FORCE("_ZN2nn2fs11GetFileSizeEPlNS0_10FileHandleE", "fsp-srv → fstat(2)", Result, h_fs_GetFileSize, int64_t *out, uint64_t h) {
if (!h) return RES_FAIL;
archandle *ah; if (arc_get(h, &ah)) { *out = (int64_t)ah->size; return RES_OK; }
+ if (IMG_H(h)) { *out = (int64_t)g_mnt[IMG_M(h)].img->e[IMG_K(h)].b; return RES_OK; }
struct stat st; if (fstat((int)h, &st)) return err_res("fstat", "fd");
*out = st.st_size; return RES_OK;
}
HLE_FORCE("_ZN2nn2fs11SetFileSizeENS0_10FileHandleEl", "fsp-srv → ftruncate(2)", Result, h_fs_SetFileSize, uint64_t h, int64_t sz) {
- if (!h) return RES_FAIL;
+ if (!h || IMG_H(h)) return RES_FAIL;
int fd = (int)h & 0xffff; uint16_t token = atomic_load(&g_ftxn[fd]); int txn = token ? token - 1 : -1;
pthread_rwlock_t *txn_guard __attribute__((cleanup(txn_unlock))) = NULL;
if (txn >= 0) { txn_guard = &g_txn_lock[txn]; pthread_rwlock_rdlock(txn_guard); }
@@ -808,14 +895,15 @@ HLE_FORCE("_ZN2nn2fs11SetFileSizeENS0_10FileHandleEl", "fsp-srv → ftruncate(2)
}
HLE_FORCE("_ZN2nn2fs9FlushFileENS0_10FileHandleE", "fsp-srv; host writes are already in the page cache, flushing is a no-op", Result, h_fs_FlushFile, uint64_t h) { (void)h; return RES_OK; }
HLE_FORCE("_ZN2nn2fs9CloseFileENS0_10FileHandleE", "fsp-srv → close(2)", void, h_fs_CloseFile, uint64_t h) {
- if (!h) return; // the null handle after a failed open (see ReadFile): do not touch fd 0
+ if (!h || IMG_H(h)) return; // the null handle after a failed open (see ReadFile): do not touch fd 0; an image entry holds no descriptor
if (h >> 63) { arc_free(h); return; } // archive entry: nothing to close
g_fmode[(int)h & 0xffff] = 0; atomic_store(&g_ftxn[(int)h & 0xffff], 0);
close((int)h); }
-HLE_FORCE("_ZN2nn2fs15GetFileOpenModeENS0_10FileHandleE", "fsp-srv; the open mode is recorded by the host", int, h_fs_GetFileOpenMode, uint64_t h) { return g_fmode[(int)h & 0xffff]; }
+HLE_FORCE("_ZN2nn2fs15GetFileOpenModeENS0_10FileHandleE", "fsp-srv; the open mode is recorded by the host", int, h_fs_GetFileOpenMode, uint64_t h) { return IMG_H(h) ? MODE_READ : g_fmode[(int)h & 0xffff]; }
// ---------- Path operations ----------
HLE_FORCE("_ZN2nn2fs10CreateFileEPKcl", "fsp-srv → open(O_CREAT|O_EXCL)+ftruncate", Result, h_fs_CreateFile, const char *path, int64_t sz) {
+ int mi; int64_t k; if (img_path(path, &mi, &k)) return k >= 0 ? RES_PATH_EXISTS : RES_FAIL; // as RW_CREATE answers on a read-only folder
HP_EX(path, 1); RW_CREATE();
int fd = open(hp, O_WRONLY | O_CREAT | O_EXCL, 0644);
if (fd < 0) return err_res("create", hp);
@@ -825,7 +913,9 @@ HLE_FORCE("_ZN2nn2fs10CreateFileEPKcl", "fsp-srv → open(O_CREAT|O_EXCL)+ftrunc
errno = e; return rc ? err_res("create", hp) : RES_OK;
}
HLE_FORCE("_ZN2nn2fs10DeleteFileEPKc", "fsp-srv → unlink(2)", Result, h_fs_DeleteFile, const char *path) { HP(path); RW(); return unlink(hp) ? err_res("unlink", hp) : RES_OK; }
-HLE_FORCE("_ZN2nn2fs15CreateDirectoryEPKc", "fsp-srv → mkdir(2)", Result, h_fs_CreateDirectory, const char *path) { HP_EX(path, 1); RW_CREATE();
+HLE_FORCE("_ZN2nn2fs15CreateDirectoryEPKc", "fsp-srv → mkdir(2)", Result, h_fs_CreateDirectory, const char *path) {
+ int mi; int64_t k; if (img_path(path, &mi, &k)) return k >= 0 ? RES_PATH_EXISTS : RES_FAIL;
+ HP_EX(path, 1); RW_CREATE();
if (mkdir(hp, 0755)) return err_res("mkdir", hp);
if (set_guest_name(hp, path)) { int e = errno; rmdir(hp); errno = e; return err_res("mkdir name", hp); }
return RES_OK; }
@@ -887,6 +977,8 @@ HLE_FORCE("_ZN2nn2fs10RenameFileEPKcS2_", "fsp-srv → rename(2)", Result, h_fs_
// The Great Ace Attorney Chronicles (SDK 10) imports it; a directory carries its guest name the same way as a file
HLE_FORCE("_ZN2nn2fs15RenameDirectoryEPKcS2_", "fsp-srv → rename(2) of a directory", Result, h_fs_RenameDir, const char *from, const char *to) { return rename_entry(from, to); }
HLE_FORCE("_ZN2nn2fs12GetEntryTypeEPNS0_18DirectoryEntryTypeEPKc", "fsp-srv → stat(2)", Result, h_fs_GetEntryType, int32_t *out, const char *path) {
+ int mi; int64_t k;
+ if (img_path(path, &mi, &k)) { if (k < 0) return err_res("stat", path); *out = g_mnt[mi].img->e[k].type ? ENT_FILE : ENT_DIR; return RES_OK; }
HP(path); struct stat st;
if (ROMFSARC_IS_SYNTH(hp)) { // archive entry or directory, from the index
const char *rel = arc_rel(hp); // the index stores paths without a leading slash (abe35a3)
@@ -923,38 +1015,64 @@ static void arc_snapshot(dirh_t *h, const char *hp) {
}
static void dir_snapshot(dirh_t *h, const mount_t *m, const char *rest) {
char *roots = strdup(m->overlay);
- char (*names)[0x301] = calloc(2048, sizeof *names);
+ size_t cap = 2048; char (*names)[0x301] = malloc(cap * sizeof *names);
const char **all = calloc(65, sizeof *all);
char *parent = malloc(1024), *guest = malloc(0x301), *rel = malloc(2048), *resolved = malloc(1024);
if (!roots || !names || !all || !parent || !guest || !rel || !resolved) die("rom overlay directory snapshot allocation failed");
- int nn = 0, nr = 0;
+ size_t nn = 0; int nr = 0;
all[nr++] = m->dir;
char *save = NULL;
for (char *root = strtok_r(roots, ":", &save); root && nr < 65; root = strtok_r(NULL, ":", &save)) all[nr++] = root;
for (int ri = nr - 1; ri >= 0; ri--) {
if (!root_path(all[ri], rest, parent, 1024)) continue;
- DIR *x = opendir(parent); if (!x) continue;
+ DIR *x = opendir(parent); if (!x) continue; // an image base is no folder: its names are added below
struct dirent *e;
while ((e = readdir(x))) {
if (!strcmp(e->d_name, ".") || !strcmp(e->d_name, "..")) continue;
if (!guest_name(parent, e->d_name, guest, 0x301)) continue;
- int dup = 0; for (int j = 0; j < nn; j++) if (!strcmp(names[j], guest)) { dup = 1; break; }
- if (!dup && nn < 2048) strlcpy(names[nn++], guest, sizeof names[0]);
+ int dup = 0; for (size_t j = 0; j < nn; j++) if (!strcmp(names[j], guest)) { dup = 1; break; }
+ if (dup) continue;
+ if (nn == cap && !(names = realloc(names, (cap *= 2) * sizeof *names))) die("rom overlay directory snapshot allocation failed");
+ strlcpy(names[nn++], guest, sizeof names[0]);
}
closedir(x);
}
- h->snap = calloc(nn, sizeof *h->snap); h->nsnap = nn;
- if (nn && !h->snap) die("rom overlay directory snapshot allocation failed");
- for (int j = 0; j < nn; j++) {
+ size_t nov = nn; int64_t dk = m->img ? img_find(m->img, rest) : -1;
+ if (dk >= 0 && !m->img->e[dk].type) // the image's own entries of this directory, after the overlay folders' (only those can repeat a name)
+ for (uint64_t j = 0; j < m->img->e[dk].b; j++) {
+ const img_ent *c = &m->img->e[m->img->e[dk].a + j]; size_t l = c->nlen < 0x300 ? c->nlen : 0x300;
+ memcpy(guest, m->img->names + c->name, l); guest[l] = 0;
+ int dup = 0; for (size_t i = 0; i < nov; i++) if (!strcmp(names[i], guest)) { dup = 1; break; }
+ if (dup) continue;
+ if (nn == cap && !(names = realloc(names, (cap *= 2) * sizeof *names))) die("rom overlay directory snapshot allocation failed");
+ strlcpy(names[nn++], guest, sizeof names[0]);
+ }
+ h->snap = calloc(nn ? nn : 1, sizeof *h->snap); h->nsnap = (int64_t)nn;
+ if (!h->snap) die("rom overlay directory snapshot allocation failed");
+ for (size_t j = 0; j < nn; j++) {
strlcpy(h->snap[j].name, names[j], sizeof h->snap[j].name);
snprintf(rel, 2048, "%s/%s", rest, names[j]);
- if (!rom_overlay_path(m, rel, resolved, 1024)) continue;
- struct stat st;
- if (!stat(resolved, &st)) { h->snap[j].type = S_ISDIR(st.st_mode) ? ENT_DIR : ENT_FILE; h->snap[j].size = S_ISDIR(st.st_mode) ? 0 : st.st_size; }
+ struct stat st; int64_t k;
+ if (rom_overlay_path(m, rel, resolved, 1024)) { if (!stat(resolved, &st)) { h->snap[j].type = S_ISDIR(st.st_mode) ? ENT_DIR : ENT_FILE; h->snap[j].size = S_ISDIR(st.st_mode) ? 0 : st.st_size; } }
+ else if (m->img && (k = img_find(m->img, rel)) >= 0) { h->snap[j].type = m->img->e[k].type ? ENT_FILE : ENT_DIR; h->snap[j].size = m->img->e[k].type ? (int64_t)m->img->e[k].b : 0; }
}
free(resolved); free(rel); free(guest); free(parent); free(all); free(names); free(roots);
}
HLE_FORCE("_ZN2nn2fs13OpenDirectoryEPNS0_15DirectoryHandleEPKci", "fsp-srv → opendir(3)", Result, h_fs_OpenDirectory, uint64_t *out, const char *path, int mode) {
+ int mi; int64_t k;
+ if (img_path(path, &mi, &k)) { // an image directory: its children are one run of entries, listed from a snapshot like the overlay's
+ if (k >= 0 && g_mnt[mi].img->e[k].type) errno = ENOTDIR, k = -1;
+ if (k < 0) return err_res("opendir", path);
+ const romfs_img *m = g_mnt[mi].img; const img_ent *x = &m->e[k];
+ dirh_t *h = calloc(1, sizeof *h); if (!h || !(h->snap = calloc(x->b ? x->b : 1, sizeof *h->snap))) die("RomFS image directory allocation failed");
+ h->nsnap = (int64_t)x->b; h->mode = mode; strlcpy(h->path, path, sizeof h->path);
+ for (uint64_t j = 0; j < x->b; j++) {
+ const img_ent *c = &m->e[x->a + j]; DirectoryEntry *o = &h->snap[j];
+ memcpy(o->name, m->names + c->name, c->nlen < sizeof o->name ? c->nlen : sizeof o->name - 1);
+ o->type = c->type ? ENT_FILE : ENT_DIR; o->size = c->type ? (int64_t)c->b : 0;
+ }
+ *out = (uint64_t)h; return RES_OK;
+ }
HP(path);
if (ROMFSARC_IS_SYNTH(hp)) { // archive directory: no host DIR, only the snapshot
if (!arc_dir(hp)) { errno = ENOTDIR; return err_res("opendir", hp); }
diff --git a/dm/host/hle_misc.c b/dm/host/hle_misc.c
index 93a0f905..4d8bbf0d 100644
--- a/dm/host/hle_misc.c
+++ b/dm/host/hle_misc.c
@@ -20,10 +20,12 @@ static void aoc_load(void) {
why = dir; DIR *d = opendir(dir); struct dirent *ent;
while (d && (ent = readdir(d)) && g_naoc < (int)(sizeof g_aoc / sizeof *g_aoc)) {
char *end; long i = strtol(ent->d_name, &end, 10);
- if (ent->d_name[0] >= '1' && ent->d_name[0] <= '9' && !*end && i <= 2000) g_aoc[g_naoc++] = (int)i;
+ if (ent->d_name[0] >= '1' && ent->d_name[0] <= '9' && (!*end || !strcmp(end, ".img")) && i <= 2000) g_aoc[g_naoc++] = (int)i;
}
if (d) closedir(d);
qsort(g_aoc, g_naoc, sizeof *g_aoc, aoc_int_cmp);
+ int unique = 0; for (int i = 0; i < g_naoc; i++) if (!i || g_aoc[i] != g_aoc[i - 1]) g_aoc[unique++] = g_aoc[i];
+ g_naoc = unique; // a legacy directory and its replacement image report the same DLC once
}
char list[256] = ""; for (int i = 0; i < g_naoc; i++) snprintf(list + strlen(list), sizeof list - strlen(list), "%s%d", i ? "," : "", g_aoc[i]);
LOG("aoc: reporting %d add-on contents {%s} (%s)", g_naoc, list, why);
diff --git a/dm/host/hle_net.c b/dm/host/hle_net.c
index 16b70adc..49f8e7ee 100644
--- a/dm/host/hle_net.c
+++ b/dm/host/hle_net.c
@@ -5,18 +5,22 @@
HLE_FORCE("_ZN2nn6socket10InitializeERKNS0_6ConfigE", "connects to the bsd socket service; offline, creates no session (cut)", Result, h_socket_Initialize, const void *cfg) { (void)cfg; return RES_OK; }
HLE_FORCE("_ZN2nn4nifm10InitializeEv", "connects to the nifm network management service; offline (cut)", Result, h_nifm_Initialize, void) { return RES_OK; }
-// The request is asynchronous on Horizon: SubmitNetworkRequest only hands it to the nifm service, and IsNetworkRequestOnHold stays true until the service has evaluated it, so a request
-// never settles within microseconds of its submission. Pikmin 4 (Unreal Engine 4.26, main+0x203f3b0) relies on that: it starts its BCAT thread, whose Run (main+0x203f510) sets its status
+// The request is asynchronous on Horizon: SubmitNetworkRequest only hands it to the nifm service, and IsNetworkRequestOnHold stays true until the service has evaluated it, so a query
+// right after the submission finds it on hold. Pikmin 4 (Unreal Engine 4.26, main+0x203f3b0) relies on that: it starts its BCAT thread, whose Run (main+0x203f510) sets its status
// to 2, submits, waits while on hold and sets 6 (done, offline), and only then stores status 1 itself; answered at once, a thread that ran first finished before that store, the 1 stayed,
-// and the boot state machine (main+0x1f2f764, state 7) waited for the status forever at the black loading screen (about 1 boot in 6, 3 in 4 with four at once). The request now stays
-// on hold for NIFM_HOLD_NS after it is submitted, then settles as unavailable
-enum { NIFM_HOLD_NS = 50000000 };
-static _Atomic uint64_t g_nifm_submit; // when the pending request was submitted (now_ns), 0 = none
-HLE_FORCE("_ZN2nn4nifm20SubmitNetworkRequestEv", "offline: the request is on hold for 50 ms, then settles as unavailable", void, h_nifm_Submit, void) { atomic_store(&g_nifm_submit, now_ns() | 1); }
-HLE_FORCE("_ZN2nn4nifm20CancelNetworkRequestEv", "offline: drops the pending request", void, h_nifm_Cancel, void) { atomic_store(&g_nifm_submit, 0); }
-HLE_FORCE("_ZN2nn4nifm22IsNetworkRequestOnHoldEv", "offline: on hold until 50 ms after the submission", int, h_nifm_OnHold, void) {
- uint64_t t = atomic_load(&g_nifm_submit);
- return t && now_ns() - t < NIFM_HOLD_NS;
+// and the boot state machine (main+0x1f2f764, state 7) waited for the status forever at the black loading screen (about 1 boot in 6, 3 in 4 with four at once). Pikmin 4 sleeps 10 ms
+// between its queries, so a request that is on hold at the first query is all it needs.
+// Each query is an IPC to the nifm service on Horizon, which evaluates the request as it serves them (offline, a rejection), so the request is on hold for the first query after
+// the submission and settled at the next. The hold used to be 50 ms of host time: Hades' NetworkPollThread (main+0x27aaa0) polls with SleepThread(0) and cancels after 2,000
+// queries, 2,000 IPCs on the Switch but 0.1 ms here, so it cancelled and submitted again forever (1.17 billion queries a minute, a host core). Its stamp, now_ns() | 1, also read
+// as settled at once whenever the next query came within the same 42 ns clock tick (30% of Hades' submissions)
+static _Atomic int g_nifm_hold; // queries the pending request still answers "on hold" (0 = none, or settled)
+HLE_FORCE("_ZN2nn4nifm20SubmitNetworkRequestEv", "offline: the request is on hold for the first query, then settles as unavailable", void, h_nifm_Submit, void) { atomic_store(&g_nifm_hold, 1); }
+HLE_FORCE("_ZN2nn4nifm20CancelNetworkRequestEv", "offline: drops the pending request", void, h_nifm_Cancel, void) { atomic_store(&g_nifm_hold, 0); }
+HLE_FORCE("_ZN2nn4nifm22IsNetworkRequestOnHoldEv", "offline: on hold for the first query after the submission", int, h_nifm_OnHold, void) {
+ int h = atomic_load(&g_nifm_hold);
+ while (h > 0 && !atomic_compare_exchange_weak(&g_nifm_hold, &h, h - 1)) {}
+ return h > 0;
}
HLE_FORCE("_ZN2nn4nifm18IsNetworkAvailableEv", "offline: the network is always unavailable", int, h_nifm_Available, void) { return 0; }
HLE_FORCE("_ZN2nn4nifm31HandleNetworkRequestErrorResultEv", "offline: reports failure, shows no system network screen", Result, h_nifm_HandleErr, void) { return RES_FAIL; }
diff --git a/dm/host/hle_thread.c b/dm/host/hle_thread.c
index 8bf94395..9f18518f 100644
--- a/dm/host/hle_thread.c
+++ b/dm/host/hle_thread.c
@@ -72,7 +72,7 @@ typedef struct thr {
uint64_t nspin, nspin_seen, spin_site; const char *spin_mod; // Spin wait passes (dm_spin_wait; those that yield count in nyield too) and where the last one was
uint64_t srun_svc, srun_t0, spin_ret; // Current spin wait: nsvc at its passes, when it began, when the last pass returned
uint64_t cpu_seen_us; // CPU time (µs) at the last power report (dm_thread_cpu)
- uint64_t yrun_svc, yrun_t0, yrun_sig; // Current run of yields: nsvc of the last yield, when the run began, and the caller's x19–x28 at the last yield (a run lasts while no other SVC comes between two yields and those registers stay the same, thr_yield)
+ uint64_t yrun_svc, yrun_t0, yrun_sig, yrun_sig2; // Current run of yields: nsvc of the last yield, when the run began, and the caller's x19–x28 at the last two yields (a run lasts while no other SVC comes between two yields and those registers match one of the last two, thr_yield)
mach_port_t mport; // Host thread port (to get CPU time)
_Atomic int qos_pending; // SetThreadPriority from another thread changed prio: the thread applies the new class at its next SVC (only a thread can set its own QoS)
uint32_t qos;
@@ -637,6 +637,21 @@ void svc_thread_dump(void) {
m ? m->name : "?", m ? t->last_lr - (uint64_t)m->base : t->last_lr);
if (have_raw) { char hx[200]; int q = 0; for (int i = 0; i < 64; i += 4) q += snprintf(hx + q, sizeof hx - q, "%08x ", *(uint32_t *)(raw + i));
fprintf(stderr, "[dm] %#x waited-for object, 64 bytes from %#llx: %s\n", t->handle, t->waddr & ~0xfull, hx); }
+ // A thread in an SVC: the guest code that called it, from its stack. Engines built without frame pointers (Batman: Arkham Knight's Unreal Engine 3) leave the frame-pointer backtrace
+ // at the SVC wrapper, so the words above the gate's register frame that point into a module are listed, nearest first, with x19-x28. regs + 800 holds the x29 / x30 the gate block
+ // pushed (x30 = the return address into the wrapper's caller, which the backtrace skips: the wrappers are leaf functions), the guest stack at the SVC follows at regs + 816.
+ // Read page by page up to the first unreadable one: a thread waiting near its stack top (a shallow worker) has PROT_NONE stack region above it, and one read would fail whole
+ uint64_t *sr = atomic_load(&t->svc_regs);
+ if (sr && t->wkind) { uint64_t stk[160]; size_t got = 0; vm_address_t sa = (vm_address_t)((uint8_t *)sr + 800);
+ while (got < sizeof stk) { vm_size_t n = sizeof stk - got, g4 = 0, room = vm_page_size - ((sa + got) & (vm_page_size - 1)); if (n > room) n = room;
+ if (vm_read_overwrite(mach_task_self(), sa + got, n, (vm_address_t)((uint8_t *)stk + got), &g4) || g4 != n) break;
+ got += n; }
+ if (got >= 16 && atomic_load(&t->svc_regs) == sr) { // still in that SVC: the words are its stack, not a later frame's
+ char sl[1100]; int q = snprintf(sl, sizeof sl, "[dm] %#x guest stack:", t->handle), nfr = 0;
+ for (int i = 0; i < (int)(got / 8) && nfr < 16 && q < (int)sizeof sl - 40; i++) { module_t *m2 = module_of((void *)stk[i]);
+ if (m2 && stk[i] - (uint64_t)m2->base < m2->text_end) { q += snprintf(sl + q, sizeof sl - q, " [%d]%s+%#llx", i * 8, m2->name, stk[i] - (uint64_t)m2->base); nfr++; } }
+ q += snprintf(sl + q, sizeof sl - q, " | x19=%#llx x20=%#llx x21=%#llx x22=%#llx x23=%#llx x24=%#llx x25=%#llx x26=%#llx x27=%#llx x28=%#llx", sr[19], sr[20], sr[21], sr[22], sr[23], sr[24], sr[25], sr[26], sr[27], sr[28]);
+ fprintf(stderr, "%s\n", sl); } }
thr_bt(t);
}
// Threads created by the host itself (graphics present, audio, movie decoding, etc.): not in the guest thread table, enumerated as mach threads, the first 12 frames symbolized with dladdr
@@ -704,13 +719,15 @@ static void yield_for(thr_t *me, uint64_t run_ns) {
// with the back-off each yield slept 250 µs, about 2,600 cells a second, and the screen stayed black with the loading icon for 77 s after the opening movie (now about 10 s).
// Breath of the Wild's PlacementMgr and RadarMgr yield once per item of their batches too (a list pointer and a count move; RadarMgr's batch is 94,263 items, which the back-off
// stretched to about 30 s): standing outdoors on the Mac, CPU energy 0.35–0.74 → 0.21–0.34 W at 60 fps, CPU 76–83% → 96–106% of a core, frame interval p99 19 → 20–21 ms.
-// With sched_yield on each such yield (about 200,000 a second) it was 108–121% of a core and 0.38–0.70 W
+// With sched_yield on each such yield (about 200,000 a second) it was 108–121% of a core and 0.38–0.70 W.
+// A loop that waits at two yields comes back to the registers of the yield before last: Hades' NetworkPollThread (main+0x27aaa0) yields between its passes (w23 = 0) and once
+// in each pass's wait for the nifm request (w23 = 2,000, its retry count), and spun a host core as one that moved on at every yield
static void thr_yield(thr_t *me, const uint64_t *regs) {
if (!me) { sched_yield(); return; }
uint64_t y0 = now_ns(), sig = 0xcbf29ce484222325ull;
for (int i = 19; i <= 28; i++) sig = (sig ^ regs[i]) * 0x100000001b3ull;
- int moved = me->yrun_svc + 1 == me->nsvc && me->yrun_sig != sig; // the loop moved on since its last yield
- me->nyield++; if (me->yrun_svc + 1 != me->nsvc || moved) me->yrun_t0 = y0; me->yrun_svc = me->nsvc; me->yrun_sig = sig;
+ int moved = me->yrun_svc + 1 == me->nsvc && me->yrun_sig != sig && me->yrun_sig2 != sig; // the loop moved on since its last two yields
+ me->nyield++; if (me->yrun_svc + 1 != me->nsvc || moved) me->yrun_t0 = y0; me->yrun_svc = me->nsvc; me->yrun_sig2 = me->yrun_sig; me->yrun_sig = sig;
if (!moved) yield_for(me, y0 - me->yrun_t0);
if (me->handle == 0x1001) { g_main_yield_ns += now_ns() - y0; g_main_yield_n++; }
}
diff --git a/dm/host/tests/Makefile b/dm/host/tests/Makefile
index a9a820ba..b82c76d8 100644
--- a/dm/host/tests/Makefile
+++ b/dm/host/tests/Makefile
@@ -1,9 +1,11 @@
# dm/host unit tests in one command: make -C dm/host/tests GAME=<base game title ID> run (takes seconds; build output goes to build/ and is not committed)
B = build
PYTHON ?= python3
+.DEFAULT_GOAL := run
# game profile header (dm.h needs game_profile.h, generated by the host Makefile into ../gen/<profile>/)
# tests that use the game profile need GAME=<base game title ID> (there is no default game); GINC only expands when used, so tests without the profile build as before
GINC = $(if $(strip $(GAME)),-I../gen/$(GAME) -I../../games/$(GAME),$(error GAME is not set: make GAME=<base game title ID>: $(shell python3 ../../games/game.py list | awk -F'\t' '{printf "%s (%s) ", $$1, $$3}')))
+$(B)/t_fs $(B)/t_fs_case $(B)/t_fs_commit_list $(B)/t_fs_commit_list_tsan: ../romfs_image.h
GAME_H = ../gen/$(GAME)/game_profile.h
run: $(B)/t_heap_size $(B)/t_touch $(B)/t_gesture $(B)/t_oe $(B)/t_fs $(B)/t_fs_commit_list $(B)/t_thread_leak $(B)/t_fs_case $(B)/t_audio $(B)/t_audio_spsc $(B)/t_swkbd $(B)/t_altstack $(B)/t_condvar $(B)/t_condvar_old $(B)/t_pctl $(B)/t_time $(B)/t_shared_font $(B)/t_vorbis $(B)/t_vorbis_divides $(B)/t_hid $(B)/t_haptics $(B)/t_haptics_apple $(B)/t_touchpad_geometry
$(B)/t_heap_size
@@ -81,16 +83,16 @@ $(B)/t_gesture: t_gesture.c ../hle_touch.c ../front.h ../dm.h $(GAME_H) | $(B)
clang -O1 -Wall -Wno-unused-function -I.. $(GINC) -o $@ t_gesture.c ../hle_touch.c
$(B)/t_thread_leak: t_thread_leak.c ../thread.c ../dm.h $(GAME_H) | $(B)
clang -O1 -Wno-unused-function -I.. $(GINC) -o $@ t_thread_leak.c
-$(B)/t_fs: t_fs.c t_fs_stub.c ../hle_fs.c ../hle_bigstack.c ../romfs_arc.c ../hle.h ../dm.h $(GAME_H) | $(B)
+$(B)/t_fs: t_fs.c t_fs_stub.c ../hle_fs.c ../hle_bigstack.c ../romfs_arc.c ../hle.h ../dm.h $(GAME_H) ../hle_profile.c ../hle_profile.h | $(B)
clang -O1 -Wno-unused-function -I.. $(GINC) -o $@ t_fs.c t_fs_stub.c ../hle_bigstack.c ../romfs_arc.c ../hle_profile.c
-$(B)/t_fs_commit_list: t_fs_commit_list.c t_fs_stub.c ../hle_fs.c ../hle_bigstack.c ../romfs_arc.c ../hle.h ../dm.h $(GAME_H) | $(B)
+$(B)/t_fs_commit_list: t_fs_commit_list.c t_fs_stub.c ../hle_fs.c ../hle_bigstack.c ../romfs_arc.c ../hle.h ../dm.h $(GAME_H) ../hle_profile.c ../hle_profile.h | $(B)
clang -O1 -Wall -Wno-unused-function -I.. $(GINC) -o $@ t_fs_commit_list.c t_fs_stub.c ../hle_bigstack.c ../romfs_arc.c ../hle_profile.c
$(B)/t_fs_commit_list_tsan: t_fs_commit_list.c t_fs_stub.c ../hle_fs.c ../hle_bigstack.c ../hle.h ../dm.h $(GAME_H) | $(B)
clang -O1 -g -fsanitize=thread -Wall -Wno-unused-function -I.. $(GINC) -o $@ t_fs_commit_list.c t_fs_stub.c ../hle_bigstack.c ../hle_profile.c
.PHONY: fs-tsan
fs-tsan: $(B)/t_fs_commit_list_tsan
TMPDIR="$(abspath $(B))" $(B)/t_fs_commit_list_tsan
-$(B)/t_fs_case: t_fs_case.c ../hle_fs.c ../hle_bigstack.c ../romfs_arc.c ../hle.h ../dm.h $(GAME_H) | $(B)
+$(B)/t_fs_case: t_fs_case.c ../hle_fs.c ../hle_bigstack.c ../romfs_arc.c ../hle.h ../dm.h $(GAME_H) ../hle_profile.c ../hle_profile.h | $(B)
clang -O1 -Wno-unused-function -I.. $(GINC) -o $@ t_fs_case.c ../hle_bigstack.c ../romfs_arc.c ../hle_profile.c
$(B)/t_audio: t_audio.c ../hle_audio.c ../hle.h ../dm.h $(GAME_H) | $(B)
clang -O1 -Wno-unused-function -I.. $(GINC) -o $@ t_audio.c -framework AudioToolbox
diff --git a/dm/host/tests/t_audio.c b/dm/host/tests/t_audio.c
index dfa6c044..13acfd51 100644
--- a/dm/host/tests/t_audio.c
+++ b/dm/host/tests/t_audio.c
@@ -126,25 +126,35 @@ int main(void) {
// Scenario 3: the device stops calling back while the output plays (iOS does this when another audio session takes over, without telling the AudioUnit). 20 blocks of 100 ms; at 150 ms the AudioUnit is stopped behind the host's back.
// Expected: the watchdog sees no callback for 200 ms, the silent sink takes over (all 20 blocks still released in order, about 2 s plus the 200-250 ms gap), and the AudioUnit is restarted 1 s later and calls back again
// Allow 5 s for scheduling and AudioUnit stop/start delays on virtual CI Macs; buffer order, the playback lower bound and resumed callbacks still have to hold.
+ // The virtual output of a CI Mac can also pause by itself for more than 200 ms after the restart: the watchdog then rightly stands the silent sink in again and retries 1 s later, which can fall after the
+ // last release (CI: "AudioUnit restarted", a second "has not called back for 204 ms", then Close 1 s later, "calling back again=0"). So the backend is followed on every poll until a restarted AudioUnit
+ // has called back, up to 20 s (the watchdog's back-off of 1, 2, 4 s fits), instead of being read once 100 ms after the last release; it still fails when no restarted AudioUnit ever calls back
char out3[64]; gbuf b3[20]; static int16_t pcm3[20][4800 * 2]; g_sig = 0;
if (h_au_Open(out3, ev, NULL, prm)) return 1;
for (int i = 0; i < 20; i++) h_au_SetBuf(&b3[i], pcm3[i], sizeof pcm3[i], sizeof pcm3[i]);
int app3 = 0; for (; app3 < 20 && h_au_Append(out3, &b3[app3]); app3++) ;
aout *a3 = ao(out3); t0 = now_ns(); h_au_Start(out3);
- int got3 = 0, order3 = 1, cut = 0; uint64_t cb_restart = 0;
- while (got3 < 20 && now_ns() - t0 < 10000000000ull) {
+ int got3 = 0, order3 = 1, cut = 0, standins = 0, sink = 0, restarted = 0, back = 0; uint64_t cb_restart = 0; double total3 = 0;
+ while (!(got3 == 20 && back) && now_ns() - t0 < 20000000000ull) {
uint64_t ms = (now_ns() - t0) / 1000000;
if (!cut && ms >= 150) { AudioOutputUnitStop(a3->au); cut = 1; }
- pthread_mutex_lock(&g_aos_lock); if (cut && !cb_restart && a3->backend == BK_AU && ms > 400) cb_restart = atomic_load(&a3->cb_n); pthread_mutex_unlock(&g_aos_lock);
- gbuf *r = h_au_Released(out3);
+ // The watchdog changes the backend under g_aos_lock, and a restart comes at least 1 s after the silent sink stood in, so a 1 ms poll sees every stand-in and every restart
+ pthread_mutex_lock(&g_aos_lock);
+ if (cut && a3->backend == BK_NULL && a3->stalled) { standins += !sink; sink = 1; restarted = 0; }
+ else if (standins && a3->backend == BK_AU && !a3->stalled) {
+ uint64_t n = atomic_load(&a3->cb_n); sink = 0;
+ if (!restarted) { restarted = 1; cb_restart = n; } else if (n > cb_restart) back = 1; // callbacks counted after the restart was seen
+ }
+ pthread_mutex_unlock(&g_aos_lock);
+ gbuf *r = got3 < 20 ? h_au_Released(out3) : NULL;
if (!r) { usleep(1000); continue; }
- order3 &= r == &b3[got3]; got3++;
+ order3 &= r == &b3[got3];
+ if (++got3 == 20) total3 = (now_ns() - t0) / 1e6;
if (app3 < 20) h_au_Append(out3, &b3[app3++]);
}
- double total3 = (now_ns() - t0) / 1e6; usleep(100000);
- pthread_mutex_lock(&g_aos_lock); int back = a3->backend == BK_AU && !a3->stalled; uint64_t cb_end = atomic_load(&a3->cb_n); pthread_mutex_unlock(&g_aos_lock);
+ double waited3 = (now_ns() - t0) / 1e6;
h_au_Close(out3);
- int ok3 = got3 == 20 && order3 && total3 > 1900 && total3 < 5000 && back && cb_restart && cb_end > cb_restart;
- printf("device stall: released %d/20 in order=%d in %.0f ms (expected 1900-5000), AudioUnit restarted and calling back again=%d %s\n", got3, order3, total3, back && cb_restart && cb_end > cb_restart, ok3 ? "✓" : "✗");
+ int ok3 = got3 == 20 && order3 && total3 > 1900 && total3 < 5000 && back;
+ printf("device stall: released %d/20 in order=%d in %.0f ms (expected 1900-5000), AudioUnit restarted and calling back again=%d (silent sink stood in %d times, %.0f ms) %s\n", got3, order3, total3, back, standins, waited3, ok3 ? "✓" : "✗");
return !ok3;
}
diff --git a/dm/host/tests/t_fs.c b/dm/host/tests/t_fs.c
index 267a9552..fa24302c 100644
--- a/dm/host/tests/t_fs.c
+++ b/dm/host/tests/t_fs.c
@@ -52,6 +52,45 @@ int main(void) {
CHECK(read_fs("rom:/data/same", got, sizeof got) && !strcmp(got, "overlay"), "the overlay file wins"); CHECK(read_fs("rom:/data/base", got, sizeof got) && !strcmp(got, "only-base"), "falls back to the base when the overlay lacks the file");
uint64_t rh; CHECK(h_fs_OpenFile(&rh, "rom:/data/same", MODE_WRITE) == RES_FAIL, "the two-layer mount refuses writes");
g_nmnt = 0;
+
+ printf("RomFS image\n"); // written by hand in romfs_image.py's layout: /data/a = "hello", /data/b empty directory, /data/c = "xy"
+ { uint8_t img[32 + 7 + 5 * 24 + 7] = {0}; uint64_t hd[3] = {39, 5 * 24 + 7, 5};
+ img_ent e[5] = {{1, 1, 0, 0, 0, 0}, {2, 3, 0, 4, 0, 0}, {32, 5, 4, 1, 1, 0}, {5, 0, 5, 1, 0, 0}, {37, 2, 6, 1, 1, 0}};
+ memcpy(img, "DMROMFS1", 8); memcpy(img + 8, hd, sizeof hd); memcpy(img + 32, "helloxy", 7); memcpy(img + 39, e, sizeof e); memcpy(img + 39 + sizeof e, "dataabc", 7);
+ char ip[1100]; snprintf(ip, sizeof ip, "%s/rom.img", root); FILE *f = fopen(ip, "wb"); fwrite(img, 1, sizeof img, f); fclose(f);
+ setenv("DM_ROMFS", ip, 1); unsetenv("DM_ROMFS_OVERLAY"); CHECK(h_fs_MountRom("rom", NULL, 0) == RES_OK, "mount the image");
+ CHECK(read_fs("rom:/data/a", got, sizeof got) && !strcmp(got, "hello"), "reads a file"); CHECK(read_fs("rom:/data/../data/c", got, sizeof got) && !strcmp(got, "xy"), "reads the next file, through ..");
+ uint64_t h; size_t n = 0; int64_t sz = 0; char b[16] = {0};
+ CHECK(h_fs_OpenFile(&h, "rom:/data/a", MODE_READ) == RES_OK && h_fs_ReadFile(&n, h, 3, b, 10) == RES_OK && n == 2 && !memcmp(b, "lo", 2), "a read stops at the end of the file (got %zu)", n);
+ CHECK(h_fs_GetFileSize(&sz, h) == RES_OK && sz == 5 && h_fs_GetFileOpenMode(h) == MODE_READ, "size 5, open for reading"); h_fs_CloseFile(h);
+ CHECK(h_fs_OpenFile(&h, "rom:/data/x", MODE_READ) == RES_PATH_NOT_FOUND, "a missing file is not found");
+ CHECK(h_fs_OpenFile(&h, "rom:/data/A", MODE_READ) == RES_PATH_NOT_FOUND, "names are case-sensitive");
+ CHECK(h_fs_OpenFile(&h, "rom:/data/b", MODE_READ) == RES_PATH_NOT_FOUND, "a directory does not open as a file");
+ CHECK(h_fs_OpenFile(&h, "rom:/data/a", MODE_WRITE) == RES_FAIL && h_fs_CreateFile("rom:/data/a", 1) == RES_PATH_EXISTS, "refuses writes; create answers \"exists\"");
+ int32_t t = -1; CHECK(h_fs_GetEntryType(&t, "rom:/data/b") == RES_OK && t == ENT_DIR && h_fs_GetEntryType(&t, "rom:/data/c") == RES_OK && t == ENT_FILE, "entry types");
+ DirectoryEntry de[4]; int64_t cnt = 0;
+ CHECK(h_fs_OpenDirectory(&h, "rom:/data", DIRMODE_DIR | DIRMODE_FILE) == RES_OK && h_fs_DirCount(&cnt, h) == RES_OK && cnt == 3, "a directory of 3 entries (%lld)", (long long)cnt);
+ CHECK(h_fs_ReadDirectory(&cnt, de, h, 4) == RES_OK && cnt == 3 && !strcmp(de[0].name, "a") && de[0].size == 5 && de[1].type == ENT_DIR && !strcmp(de[2].name, "c"), "lists a, b, c"); h_fs_CloseDirectory(h);
+ CHECK(h_fs_OpenDirectory(&h, "rom:/", DIRMODE_FILE) == RES_OK && h_fs_ReadDirectory(&cnt, de, h, 4) == RES_OK && cnt == 0, "the file filter hides directories"); h_fs_CloseDirectory(h);
+ CHECK(h_fs_OpenDirectory(&h, "rom:/data/b", DIRMODE_DIR | DIRMODE_FILE) == RES_OK && h_fs_DirCount(&cnt, h) == RES_OK && cnt == 0, "an empty directory"); h_fs_CloseDirectory(h);
+ g_nmnt = 0;
+ char ov[1100], ovd[1200]; snprintf(ov, sizeof ov, "%s/imgov", root); snprintf(ovd, sizeof ovd, "%s/data", ov); mkdir(ov, 0755); mkdir(ovd, 0755);
+ snprintf(fn, sizeof fn, "%s/a", ovd); put(fn, "mod"); snprintf(fn, sizeof fn, "%s/new", ovd); put(fn, "added");
+ setenv("DM_ROMFS_OVERLAY", ov, 1); CHECK(h_fs_MountRom("rom", NULL, 0) == RES_OK, "mount the image with an overlay folder");
+ CHECK(read_fs("rom:/data/a", got, sizeof got) && !strcmp(got, "mod"), "the overlay file wins over the image");
+ CHECK(read_fs("rom:/data/c", got, sizeof got) && !strcmp(got, "xy") && read_fs("rom:/data/new", got, sizeof got) && !strcmp(got, "added"), "image files and overlay-only files both read");
+ CHECK(h_fs_OpenDirectory(&h, "rom:/data", DIRMODE_DIR | DIRMODE_FILE) == RES_OK && h_fs_ReadDirectory(&cnt, de, h, 4) == RES_OK && cnt == 4, "the listing merges both, once each (%lld)", (long long)cnt);
+ int seen = 0; for (int i = 0; i < cnt; i++) { if (!strcmp(de[i].name, "a")) seen += de[i].size == 3; if (!strcmp(de[i].name, "b")) seen += de[i].type == ENT_DIR; if (!strcmp(de[i].name, "c")) seen += de[i].size == 2; if (!strcmp(de[i].name, "new")) seen += de[i].size == 5; }
+ CHECK(seen == 4, "with the right types and sizes"); h_fs_CloseDirectory(h);
+ unsetenv("DM_ROMFS_OVERLAY"); g_nmnt = 0;
+ snprintf(fn, sizeof fn, "%s/2.img", root); CHECK(!link(ip, fn), "stage a DLC image"); setenv("DM_AOC_DIR", root, 1);
+ size_t cache = 0;
+ CHECK(h_fs_QueryAocCache(&cache, 2) == RES_OK && cache == 176, "DLC image reports Horizon table size (176, got %zu)", cache);
+ CHECK(h_fs_MountAoc("aoc", 2, NULL, 0) == RES_OK && read_fs("aoc:/data/a", got, sizeof got) && !strcmp(got, "hello"), "DLC mounts and reads directly from its image");
+ unsetenv("DM_AOC_DIR"); g_nmnt = 0;
+ f = fopen(ip, "wb"); fwrite(img, 1, 39 + 50, f); fclose(f); // cut off inside the index, as a copy stopped partway
+ CHECK(!img_open(ip), "a cut-off image is refused");
+ }
snprintf(save, sizeof save, "%s/save", root); snprintf(work, sizeof work, "%s.work", save);
mkdir(save, 0755); snprintf(p, sizeof p, "%s/a", save); put(p, "old");
setenv("DM_SAVE", save, 1); setenv("DM_TEST_FS_FAIL", "write:5:28", 1); // the 5th save write fails, errno 28 = ENOSPC
diff --git a/dm/ios/Sources/main.m b/dm/ios/Sources/main.m
index 224154fd..de02ef4f 100644
--- a/dm/ios/Sources/main.m
+++ b/dm/ios/Sources/main.m
@@ -1,12 +1,14 @@
// iOS App entry: set the environment (game files, saves, shader libraries), write the host log to Documents/log.txt, create the window (front_ios.m), then run the host's dm_main on a big-stack thread.
-// The game files (RomFS) ship inside the App at <App>/romfs; Documents/romfs placed through the Files app is also accepted (lets you swap them without reinstalling).
+// The game files (RomFS) ship inside the App at <App>/romfs; Documents/romfs.img (one image, scripts/push_romfs.sh) or a Documents/romfs folder is also accepted (lets you swap them without reinstalling).
#import <UIKit/UIKit.h>
#include <pthread.h>
#include <signal.h>
#include <stdio.h>
+#include <sys/stat.h>
#include <unistd.h>
#include "hle_profile.h" // the runtime game profile (DM_PROFILE): the RomFS marker path comes from it
#include "front.h"
+#include "romfs_image.h"
int dm_main(int argc, char **argv); // dm/host/main.c compiled in with -Dmain=dm_main
UIViewController *front_ios_root(void);
@@ -14,6 +16,15 @@ void front_ios_focus_event(int ev);
static char *g_argv[4]; static int g_argc;
+// Documents/romfs.img, one RomFS image file (dm/tools/romfs_image.py, scripts/push_romfs.sh): only a complete one counts. Its index is written last and ends the file, so a copy cut off partway is skipped
+static int romfs_image_complete(NSString *path) {
+ romfs_img *m = romfs_image_open(path.fileSystemRepresentation);
+ if (!m) {
+ if (errno != ENOENT) fprintf(stderr, "[RED] boot: invalid RomFS image %s (errno=%d); trying the folders\n", path.fileSystemRepresentation, errno);
+ return 0;
+ }
+ romfs_image_close(m); return 1;
+}
// A folder holds this game's files if it has a ROMFSARC index or the profile's marker path.
// Shared by romfs_locate and the per-game layout below, so both answer the same question.
static BOOL romfs_dir_ok(NSString *d) {
@@ -28,7 +39,8 @@ static BOOL romfs_dir_ok(NSString *d) {
}
// Where one game's data lives under the per-game layout: Documents/games/<title ID>/, holding
-// romfs/ the archive (romfs.idx + shards) or a plain tree
+// romfs.img the whole RomFS as one image file (what scripts/push_romfs.sh sends), or
+// romfs/ a ROMFSARC archive or a plain tree, for copies made before images
// msl/ this game's Metal shader libraries (optional; the app's own dm/ is used otherwise)
// save/ temp/ this game's saves and scratch space
// The layout exists so several games can share one installed app and so the game data can sit on
@@ -41,13 +53,34 @@ static NSString *game_dir_for(const char *title_id) {
static NSString *romfs_locate(void) {
NSFileManager *fm = NSFileManager.defaultManager;
NSString *doc = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
- // Per-game first: Documents/games/<id>/romfs — what the launcher-style layout produces, and what
- // lets a user keep several games' data side by side (or on an external drive).
- NSString *per_game = [game_dir_for(dm_profile()->id) stringByAppendingPathComponent:@"romfs"];
- if ([fm fileExistsAtPath:per_game] && romfs_dir_ok(per_game)) return per_game;
- for (NSString *d in @[[doc stringByAppendingPathComponent:@"romfs"], [NSBundle.mainBundle.resourcePath stringByAppendingPathComponent:@"romfs"]]) {
- if (romfs_dir_ok(d)) return d;
+ // Per-game first: Documents/games/<id>/romfs.img (one file, what push_romfs.sh sends) or
+ // Documents/games/<id>/romfs/ — the launcher-style layout, and what lets a user keep several
+ // games' data side by side or on an external drive. The marker check inside romfs_dir_ok is
+ // what keeps a stray folder from being taken for this game.
+ NSString *gdir = game_dir_for(dm_profile()->id);
+ NSString *gimg = [gdir stringByAppendingPathComponent:@"romfs.img"];
+ if (romfs_image_complete(gimg)) return gimg;
+ NSString *gfolder = [gdir stringByAppendingPathComponent:@"romfs"];
+ if ([fm fileExistsAtPath:gfolder] && romfs_dir_ok(gfolder)) return gfolder;
+ NSString *img = [doc stringByAppendingPathComponent:@"romfs.img"];
+ if (romfs_image_complete(img)) {
+ // A folder copy from before images is now dead weight of up to many GB (often cut off partway). Deleting its 300,000 files here took longer than iOS allows an app to start
+ // (Tears of the Kingdom: killed on a black screen), so it is moved aside at once and deleted in the background, leftovers of an interrupted delete included
+ NSString *old = [doc stringByAppendingPathComponent:@"romfs"], *tmp = NSTemporaryDirectory();
+ if ([fm fileExistsAtPath:old] && [fm moveItemAtPath:old toPath:[tmp stringByAppendingPathComponent:[@"romfs-old-" stringByAppendingString:NSUUID.UUID.UUIDString]] error:nil])
+ fprintf(stderr, "boot: Documents/romfs moved aside for deletion (Documents/romfs.img replaces it)\n");
+ dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0), ^{
+ NSFileManager *bfm = [NSFileManager new];
+ for (NSString *n in [bfm contentsOfDirectoryAtPath:tmp error:nil]) if ([n hasPrefix:@"romfs-old-"]) [bfm removeItemAtPath:[tmp stringByAppendingPathComponent:n] error:nil];
+ });
+ return img;
}
+ NSString *bundledImage = [NSBundle.mainBundle.resourcePath stringByAppendingPathComponent:@"romfs.img"];
+ NSString *documentFolder = [doc stringByAppendingPathComponent:@"romfs"];
+ if ([fm fileExistsAtPath:[documentFolder stringByAppendingPathComponent:@(dm_profile()->romfs_marker)]]) return documentFolder;
+ if (romfs_image_complete(bundledImage)) return bundledImage;
+ for (NSString *d in @[[doc stringByAppendingPathComponent:@"romfs"], [NSBundle.mainBundle.resourcePath stringByAppendingPathComponent:@"romfs"]])
+ if (romfs_dir_ok(d)) return d;
return nil;
}
@@ -58,8 +91,8 @@ static int boot_env(void) {
NSString *res = NSBundle.mainBundle.resourcePath;
for (NSString *d in @[@"save", @"temp"]) [fm createDirectoryAtPath:[doc stringByAppendingPathComponent:d] withIntermediateDirectories:YES attributes:nil error:nil];
// Keep game files and scratch data out of device backups (Documents is backed up by default; a RomFS placed there is many GB). Saves, logs and the pipeline list stay in the backup
- for (NSString *d in @[@"romfs", @"temp"]) {
- NSURL *u = [NSURL fileURLWithPath:[doc stringByAppendingPathComponent:d] isDirectory:YES]; NSError *e = nil;
+ for (NSString *d in @[@"romfs", @"romfs.img", @"temp"]) {
+ NSURL *u = [NSURL fileURLWithPath:[doc stringByAppendingPathComponent:d]]; NSError *e = nil;
if ([fm fileExistsAtPath:u.path] && ![u setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:&e]) fprintf(stderr, "boot: %s could not be excluded from backup: %s\n", d.UTF8String, e.localizedDescription.UTF8String);
}
// Log: the host only writes to stderr; redirect it to Documents/log.txt (the previous one is kept as log.prev.txt), retrieve it from the Files app when something goes wrong
@@ -85,7 +118,7 @@ static int boot_env(void) {
if (!getenv("DM_LANG") && [lang isKindOfClass:NSString.class] && lang.length) setenv("DM_LANG", lang.UTF8String, 0);
fprintf(stderr, "boot: game language %s\n", getenv("DM_LANG") ?: "en-US");
NSString *romfs = romfs_locate();
- if (!romfs) { fprintf(stderr, "boot: game files not found (<App>/romfs or Documents/romfs)\n"); return 0; }
+ if (!romfs) { fprintf(stderr, "boot: game files not found (Documents/romfs.img, Documents/romfs or <App>/romfs)\n"); return 0; }
fprintf(stderr, "boot: game files %s\n", romfs.fileSystemRepresentation);
setenv("DM_ROMFS", romfs.fileSystemRepresentation, 0);
// Saves and scratch space: Documents/games/<id>/{save,temp} when the per-game layout is in use
diff --git a/dm/ios/tests/test_profile_pack.py b/dm/ios/tests/test_profile_pack.py
index c4b762ff..40db2b76 100644
--- a/dm/ios/tests/test_profile_pack.py
+++ b/dm/ios/tests/test_profile_pack.py
@@ -42,7 +42,7 @@ class ProfilePackTests(unittest.TestCase):
env['PSO'] = str(pso)
# Exercise the actual archive step; only the preceding Xcode build is bypassed.
script = (REPO / 'dm/ios/tools/build_ipa.sh').read_text()
- packing = script[script.index('\nP=Payload/DmIOS.app;'):]
+ packing = script[script.index('\nP=Payload/DmIOS.app\n'):]
result = subprocess.run(['/bin/bash', '-c', 'set -u\nt() { :; }; die() { echo "$*" >&2; exit 1; }\n'
'gp() { python3 "$PROFILE_TOOL" "$GAME" "$1"; }\n' + packing],
cwd=root, env=env, capture_output=True, text=True)
diff --git a/dm/ios/tests/test_romfs_startup.py b/dm/ios/tests/test_romfs_startup.py
new file mode 100644
index 00000000..89e4f220
--- /dev/null
+++ b/dm/ios/tests/test_romfs_startup.py
@@ -0,0 +1,69 @@
+"""Run the actual iOS RomFS locator on macOS/Foundation with private Documents/temp folders (no device or game files)."""
+import importlib.util
+from pathlib import Path
+import subprocess
+import sys
+import tempfile
+import unittest
+
+REPO = Path(__file__).resolve().parents[3]
+spec = importlib.util.spec_from_file_location('romfs_image', REPO / 'dm/tools/romfs_image.py')
+assert spec is not None and spec.loader is not None
+image = importlib.util.module_from_spec(spec); spec.loader.exec_module(image)
+
+
[email protected](sys.platform == 'darwin', 'Foundation required')
+class Startup(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.tools = tempfile.TemporaryDirectory(); cls.addClassCleanup(cls.tools.cleanup)
+ root = Path(cls.tools.name)
+ main = (REPO / 'dm/ios/Sources/main.m').read_text()
+ locator = main[main.index('static int romfs_image_complete'):main.index('// Boot prerequisites')]
+ source = root / 'locator.m'
+ source.write_text('#import <Foundation/Foundation.h>\n#include <stdio.h>\n#include "romfs_image.h"\n'
+ 'static NSString *fixture_doc, *fixture_tmp, *fixture_bundle;\n#define DM_GAME_ROMFS_MARKER "marker"\n'
+ '@interface FixtureBundle : NSObject\n+ (instancetype)mainBundle;\n- (NSString *)resourcePath;\n@end\n'
+ '@implementation FixtureBundle\n+ (instancetype)mainBundle { return [self new]; }\n'
+ '- (NSString *)resourcePath { return fixture_bundle; }\n@end\n#define NSBundle FixtureBundle\n'
+ '#define NSSearchPathForDirectoriesInDomains(a,b,c) @[fixture_doc]\n#define NSTemporaryDirectory() fixture_tmp\n' + locator +
+ '\nint main(int argc, char **argv) { @autoreleasepool { if (argc < 3) return 2;\n'
+ 'fixture_doc = @(argv[1]); fixture_tmp = @(argv[2]); fixture_bundle = argc > 3 ? @(argv[3]) : @"/nonexistent-fixture"; NSString *p = romfs_locate();\n'
+ 'if (!p) return 1; puts(p.fileSystemRepresentation); return 0; }}\n')
+ cls.locator = root / 'locator'
+ subprocess.run(['clang', '-fobjc-arc', '-Wall', '-Werror', '-I', str(REPO / 'dm/host'),
+ str(source), '-framework', 'Foundation', '-o', str(cls.locator)], check=True)
+
+ def test_invalid_image_preserves_working_folder_and_valid_image_replaces_it(self):
+ with tempfile.TemporaryDirectory() as temporary:
+ root = Path(temporary); doc = root / 'Documents'; folder = doc / 'romfs'; folder.mkdir(parents=True)
+ (folder / 'marker').write_text('working files')
+ tmp = root / 'temp'; tmp.mkdir()
+ img = doc / 'romfs.img'
+ img.write_bytes(image.HEAD.pack(image.MAGIC, 32, 0, 0))
+ result = subprocess.run([str(self.locator), str(doc), str(tmp)], capture_output=True, text=True)
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertEqual(result.stdout.strip(), str(folder))
+ self.assertTrue((folder / 'marker').is_file()); self.assertEqual(list(tmp.iterdir()), [])
+ image.pack(folder, img)
+ result = subprocess.run([str(self.locator), str(doc), str(tmp)], capture_output=True, text=True)
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertEqual(result.stdout.strip(), str(img)); self.assertFalse(folder.exists())
+
+ def test_bundled_image_is_used_in_place_and_documents_can_override_it(self):
+ with tempfile.TemporaryDirectory() as temporary:
+ root = Path(temporary); doc = root / 'Documents'; doc.mkdir()
+ tmp = root / 'temp'; tmp.mkdir(); bundle = root / 'App'; bundle.mkdir()
+ source = root / 'source'; source.mkdir(); (source / 'marker').write_text('resource')
+ image.pack(source, bundle / 'romfs.img')
+ def locate():
+ result = subprocess.run([str(self.locator), str(doc), str(tmp), str(bundle)], capture_output=True, text=True)
+ self.assertEqual(result.returncode, 0, result.stderr); return result.stdout.strip()
+ self.assertEqual(locate(), str(bundle / 'romfs.img'))
+ self.assertEqual(list(doc.iterdir()), []); self.assertFalse((bundle / 'romfs').exists())
+ folder = doc / 'romfs'; folder.mkdir(); (folder / 'marker').touch()
+ self.assertEqual(locate(), str(folder))
+ image.pack(source, doc / 'romfs.img'); self.assertEqual(locate(), str(doc / 'romfs.img'))
+
+
+if __name__ == '__main__': unittest.main()
diff --git a/dm/ios/tests/test_xcode_workflow.py b/dm/ios/tests/test_xcode_workflow.py
index 918760ca..83a9790d 100644
--- a/dm/ios/tests/test_xcode_workflow.py
+++ b/dm/ios/tests/test_xcode_workflow.py
@@ -142,6 +142,14 @@ class ResourceStagingTests(unittest.TestCase):
self.assertEqual((app / 'msl' / chain / 'fixture.metallib').read_text(), chain)
self.assertEqual([p.name for p in (app / 'msl').iterdir()], [chain])
self.assertEqual((app / 'aoc/1/content').read_text(), 'dlc')
+ # Quick reinstalls omit only RomFS, including removing an old bundled copy; restoring the default stages it again.
+ environment['DM_COPY_ROMFS'] = 'NO'
+ result = subprocess.run(['bash', str(REPO / 'dm/ios/tools/stage_resources.sh')], env=environment, capture_output=True)
+ self.assertEqual(result.returncode, 0); self.assertFalse((app / 'romfs').exists())
+ self.assertTrue((app / 'msl/gl/fixture.metallib').is_file()); self.assertTrue((app / 'aoc/1/content').is_file())
+ environment.pop('DM_COPY_ROMFS')
+ result = subprocess.run(['bash', str(REPO / 'dm/ios/tools/stage_resources.sh')], env=environment, capture_output=True)
+ self.assertEqual(result.returncode, 0); self.assertEqual((app / 'romfs/marker').read_text(), 'game')
# Sources moved to another shader chain since preparing: stop before copying anything.
arguments = ['gen_resources.py', str(ios), str(romfs), 'marker', str(shaders / 'b-fixture'), 'b-fixture', str(aoc), str(root / 'dd'), str(chain_h)]
with patch.object(sys, 'argv', arguments):
@@ -191,5 +199,27 @@ class ResourceStagingTests(unittest.TestCase):
self.assertFalse((app / 'pso').exists())
+class ImageStaging(unittest.TestCase):
+ def test_prepared_tools_symlink_stages_image_without_expanding_it(self):
+ import romfs_image
+ with tempfile.TemporaryDirectory() as temporary:
+ root = Path(temporary).resolve(); ios = root / 'xcode'; (ios / 'Gen').mkdir(parents=True)
+ (ios / 'tools').symlink_to(REPO / 'dm/ios/tools', target_is_directory=True)
+ (ios / 'Gen/dm.xcconfig').touch()
+ source = root / 'source'; source.mkdir(); (source / 'marker').write_text('resource')
+ image = root / 'RomFS.img'; romfs_image.pack(source, image)
+ shader = root / 'shaders/gl'; shader.mkdir(parents=True); (shader / 'k.metallib').touch()
+ with patch.object(sys, 'argv', ['gen_resources.py', str(ios), str(image), 'marker', str(shader), 'gl', '', str(root / 'dd'), 'unused']):
+ gen_resources.main()
+ app = root / 'products/Game.app'
+ environment = dict(os.environ, SRCROOT=str(ios), TARGET_BUILD_DIR=str(app.parent), UNLOCALIZED_RESOURCES_FOLDER_PATH=app.name, PLATFORM_NAME='iphoneos')
+ def stage():
+ result = subprocess.run(['bash', str(ios / 'tools/stage_resources.sh')], env=environment, capture_output=True, text=True)
+ self.assertEqual(result.returncode, 0, result.stderr)
+ stage(); self.assertEqual((app / 'romfs.img').read_bytes(), image.read_bytes()); self.assertFalse((app / 'romfs').exists())
+ environment['DM_COPY_ROMFS'] = 'NO'; stage(); self.assertFalse((app / 'romfs.img').exists())
+ environment.pop('DM_COPY_ROMFS'); stage(); self.assertTrue((app / 'romfs.img').is_file())
+
+
if __name__ == '__main__':
unittest.main()
diff --git a/dm/ios/tools/build_ipa.sh b/dm/ios/tools/build_ipa.sh
index 0e3385fb..03853ae8 100755
--- a/dm/ios/tools/build_ipa.sh
+++ b/dm/ios/tools/build_ipa.sh
@@ -23,6 +23,7 @@ gp() { python3 "$DM/games/game.py" "$GAME" "$1" || die "game profile $GD: $1"; }
[ -f "$GD/game.tsv" ] || die "no game profile $GD/game.tsv"
[ -n "${W:-}" ] || die "W is not set: W=<NSP folder>/$GAME-work (the game's work folder) $0"
PKG=$(gp package)
+if [ -z "${ROMFS:-}" ] && [ -f "$W/data/$PKG/RomFS.img" ]; then ROMFS=$W/data/$PKG/RomFS.img; fi
PATCHED=${PATCHED:-$W/build/patched_$PKG}; ROMFS=${ROMFS:-$W/data/$PKG/RomFS}; MSL_IOS=${MSL_IOS:-$W/build/ios/dmsh_b}; AOC=${AOC-$W/data/aoc}
PREPARE_XCODE=NO; [ "${1:-}" != --prepare-xcode ] || PREPARE_XCODE=YES
OUT_IPA=${1:-$(dirname "$W")/$(gp ipa)}; O=$W/build/ios/pkg; DD=$O/dd
@@ -49,7 +50,7 @@ if [ "$PREPARE_XCODE" = YES ]; then
else DM_SCHEME_NAME=DmIOS; fi
export DM_SCHEME_NAME
for f in $MODS; do [ -f "$PATCHED/$f.patched.bin" ] && [ -f "$PATCHED/$f.fixups.tsv" ] || die "no rewritten module $PATCHED/$f (run dm/tools/patch_nso.py first)"; done
-[ -e "$ROMFS/$MARKER" ] || die "no RomFS at $ROMFS (missing $MARKER)"
+python3 "$DM/tools/romfs.py" "$ROMFS" "$MARKER" || die "no RomFS at $ROMFS (missing $MARKER)"
V=$(sed -n 's/^#define DMSH_CHAIN "\(.*\)"/\1/p' "$DM/gfx/nvn/dmsh_chain.h") # the chain version the host is compiled with, one for every game
# A Vulkan game (Hades): the shaders are the game's SPIR-V, translated by dm/gfx/tools/vk_shaders.py into $MSL_IOS/vk; an OpenGL game (Digimon Story Cyber Sleuth): its GLSL, translated by
# dm/gfx/tools/gl_shaders.py into $MSL_IOS/gl; neither has NVN chain libraries. GFXAPI=nvn / vulkan / gl says which (the NSP script passes what main imports); without it, the shader
@@ -165,12 +166,13 @@ fi
# the app sets DM_AOC_DIR at launch, the host reports them as owned and mounts them from it) and the RomFS
rm -rf "$APP/msl" "$O/Payload" # Payload/: what the copy-and-zip packing left behind, as was out.ipa (and its index) unless it is the IPA packed here, which a repeat pack reuses
[ "$O/out.ipa" -ef "$OUT_IPA" ] || rm -f "$O/out.ipa"; [ "$O/out.ipa.idx" -ef "$OUT_IPA.idx" ] || rm -f "$O/out.ipa.idx"
-P=Payload/DmIOS.app; MAPS=()
-# DM_FULL_ROMFS=1 packs the RomFS into the package (upstream behaviour; only sensible for small
+P=Payload/DmIOS.app
+MAPS=()
+# DM_FULL_ROMFS=1 packs the game files into the package (upstream behaviour; only sensible for small
# games — a full package of a large game is many GB and iOS refuses to install it with
-# PackageExtractionFailed). The default is the slim package: the app reads the game files from
-# Documents/romfs (a directory tree, or a ROMFSARC archive: romfs.idx + romfs.NN shards).
-if [ -n "${DM_FULL_ROMFS:-}" ]; then MAPS=("$P/romfs=$ROMFS"); fi
+# PackageExtractionFailed). The default is the slim package: the app reads them from
+# Documents/games/<id>/ (romfs.img, or a ROMFSARC archive: romfs.idx + romfs.NN shards).
+if [ -n "${DM_FULL_ROMFS:-}" ]; then if [ -f "$ROMFS" ]; then MAPS=("$P/romfs.img=$ROMFS"); else MAPS=("$P/romfs=$ROMFS"); fi; fi
if [ -n "$AOC" ] && [ -d "$AOC" ]; then MAPS+=("$P/aoc=$AOC"); t "add-on content: $(ls "$AOC" | tr '\n' ' ')"; fi
if [ -n "${PSO:-}" ]; then MAPS+=("$P/pso=$PSO"); fi
MAPS+=("$P/msl/$MSLDIR=$MSL_IOS/$MSLDIR" "$P=$APP")
@@ -185,5 +187,5 @@ PULL=$(sed -n 's/^#define DM_GAME_PSO_MTL4 //p' "$DM/host/gen/$GAME/game_profile
case "$PULL" in 0|1) ;; *) die "no DM_GAME_PSO_MTL4 in generated game profile";; esac
# Keep this array nonempty: macOS Bash 3.2 treats an empty array as unset under set -u.
PACK_OPTS=(--store "$(gp zip_store)"); [ -n "${PSO:-}" ] || [ "${IOS_PULL:-$PULL}" = 1 ] || PACK_OPTS+=(--skip-suffix _bp.metallib)
-python3 tools/pack_ipa.py "$OUT_IPA" "${PACK_OPTS[@]}" --skip $P/_CodeSignature --skip $P/embedded.mobileprovision --skip $P/msl --skip $P/aoc --skip $P/romfs "${MAPS[@]}" || die "pack_ipa"
+python3 tools/pack_ipa.py "$OUT_IPA" "${PACK_OPTS[@]}" --skip $P/_CodeSignature --skip $P/embedded.mobileprovision --skip $P/msl --skip $P/aoc --skip $P/romfs --skip $P/romfs.img "${MAPS[@]}" || die "pack_ipa"
t "done: $OUT_IPA ($(du -h "$OUT_IPA" | cut -f1))"
diff --git a/dm/ios/tools/pack_ipa.py b/dm/ios/tools/pack_ipa.py
index 2a8ead6c..e46b7e3c 100644
--- a/dm/ios/tools/pack_ipa.py
+++ b/dm/ios/tools/pack_ipa.py
@@ -4,7 +4,7 @@
# deflate level 6, a file whose deflate is not smaller is stored (zip's rule), and names ending in a --store suffix are always stored (the profile's zip_store, compared without regard to case).
# Speed (Info-ZIP managed about 100 MB/s on the T7): files up to BIG are read, and deflated, by a thread pool (zlib releases the GIL) while this thread writes them in order;
# bigger files are streamed here, their CRC patched into the local header afterwards (no data descriptors). Zip64 fields wherever a size, an offset or the entry count passes its 32 / 16-bit field.
-# Usage: pack_ipa.py <out.ipa> [--store .a:.b] [--skip <archive path>]... <archive path>=<source folder>...
+# Usage: pack_ipa.py <out.ipa> [--store .a:.b] [--skip <archive path>]... <archive path>=<source file or folder>...
# Mappings are packed in command-line order; put the files that change least first, and the app last
# --skip: an archive path left out of the walk of the folder that holds it (folders a stale app build still has, the signature); a mapping of its own still adds it
# --skip-suffix: files whose names end so are left out of every walk (build_ipa.sh: the pulling vertex libraries _bp.metallib when the profile's pso_mtl4 is off, unless IOS_PULL overrides it)
@@ -49,7 +49,9 @@ def entries(maps, skip, skip_suffix=()):
p = '/'.join(parts[:i])
if p + '/' not in seen:
add(p + '/', None, None); parents.add(p + '/')
- add(arc + '/', src, os.stat(src)); walk(src, arc)
+ source_stat = os.stat(src)
+ if stat.S_ISREG(source_stat.st_mode): add(arc, src, source_stat)
+ else: add(arc + '/', src, source_stat); walk(src, arc)
return out
@@ -224,8 +226,8 @@ def prefix(es, files, infos, old, idx, apfs):
def main():
- ap = argparse.ArgumentParser(description='Pack an IPA (zip) from source folders mapped to archive paths, in parallel')
- ap.add_argument('out'); ap.add_argument('maps', nargs='+', metavar='archive_path=folder')
+ ap = argparse.ArgumentParser(description='Pack an IPA (zip) from files and folders mapped to archive paths, in parallel')
+ ap.add_argument('out'); ap.add_argument('maps', nargs='+', metavar='archive_path=source')
ap.add_argument('--store', default='', help='suffixes stored without compressing, separated by ":"')
ap.add_argument('--skip', action='append', default=[], help='an archive path left out of the folder walk that would add it')
ap.add_argument('--skip-suffix', action='append', default=[], help='files whose names end so are left out of every folder walk')
@@ -234,7 +236,7 @@ def main():
maps = []
for m in a.maps:
arc, sep, src = m.partition('=')
- if not sep or not arc.strip('/') or not os.path.isdir(src): sys.exit(f'[RED] pack_ipa: not <archive path>=<folder>: {m}')
+ if not sep or not arc.strip('/') or not (os.path.isdir(src) or os.path.isfile(src)): sys.exit(f'[RED] pack_ipa: not <archive path>=<file or folder>: {m}')
maps.append((arc.strip('/'), src))
store = tuple(s.lower() for s in a.store.split(':') if s)
t0 = time.time()
diff --git a/dm/ios/tools/stage_resources.sh b/dm/ios/tools/stage_resources.sh
index 00bfa7f7..6ae1c8fd 100644
--- a/dm/ios/tools/stage_resources.sh
+++ b/dm/ios/tools/stage_resources.sh
@@ -10,7 +10,8 @@ source "$SRCROOT/Gen/resources.env"
APP="${TARGET_BUILD_DIR:?}/${UNLOCALIZED_RESOURCES_FOLDER_PATH:?}"
case "$APP" in /*.app) ;; *) die "Unexpected app resource destination: $APP";; esac
# Validate every source before copying or removing anything (the external drive may be disconnected).
-[ -e "$DM_RESOURCE_ROMFS/$DM_RESOURCE_MARKER" ] || die "Game files unavailable: $DM_RESOURCE_ROMFS/$DM_RESOURCE_MARKER"
+resource_dm=$(python3 -c 'import pathlib,sys; print(pathlib.Path(sys.argv[1]).resolve().parents[2])' "$0")
+python3 "$resource_dm/tools/romfs.py" "$DM_RESOURCE_ROMFS" "$DM_RESOURCE_MARKER" || die "Game files unavailable: $DM_RESOURCE_ROMFS/$DM_RESOURCE_MARKER"
[ -d "$DM_RESOURCE_SHADERS" ] || die "Shader libraries unavailable: $DM_RESOURCE_SHADERS"
[ -z "$DM_RESOURCE_AOC" ] || [ -d "$DM_RESOURCE_AOC" ] || die "Add-on content unavailable: $DM_RESOURCE_AOC"
DM_RESOURCE_PSO=${DM_RESOURCE_PSO:-} # (a project prepared before the pipeline archive has none)
@@ -22,8 +23,16 @@ case "$DM_RESOURCE_MSLDIR" in b-*)
[ "$DM_RESOURCE_MSLDIR" = "b-$V" ] || die "The prepared shaders are chain $DM_RESOURCE_MSLDIR, the sources are now at b-$V: prepare the game again (build_ipa_from_nsp.py --prepare-xcode)";;
esac
echo 'Copy game resources (the first build copies the complete game; later builds sync changes)'
-mkdir -p "$APP/romfs" "$APP/msl/$DM_RESOURCE_MSLDIR"
-/usr/bin/rsync -a --delete -- "$DM_RESOURCE_ROMFS/" "$APP/romfs/"
+mkdir -p "$APP/msl/$DM_RESOURCE_MSLDIR"
+# DM_COPY_ROMFS=NO: the game files stay out of the app (main.m takes Documents/romfs first, copied there once): a reinstall then sends the code and shaders, not the whole game
+if [ "${DM_COPY_ROMFS:-YES}" = NO ]; then rm -rf "$APP/romfs" "$APP/romfs.img"
+elif [ -f "$DM_RESOURCE_ROMFS" ]; then
+ /usr/bin/rsync -a -- "$DM_RESOURCE_ROMFS" "$APP/romfs.img"
+ rm -rf "$APP/romfs"
+else
+ mkdir -p "$APP/romfs"; /usr/bin/rsync -a --delete -- "$DM_RESOURCE_ROMFS/" "$APP/romfs/"
+ rm -f "$APP/romfs.img"
+fi
/usr/bin/rsync -a --delete -- "$DM_RESOURCE_SHADERS/" "$APP/msl/$DM_RESOURCE_MSLDIR/"
for old in "$APP/msl/"*; do
[ "$old" = "$APP/msl/$DM_RESOURCE_MSLDIR" ] || rm -rf "$old"
diff --git a/dm/mac/launcher.c b/dm/mac/launcher.c
index fba4690d..3c5d1fef 100644
--- a/dm/mac/launcher.c
+++ b/dm/mac/launcher.c
@@ -1,7 +1,7 @@
// Mac app launcher (CFBundleExecutable of the .app that dm/mac/pack_app.py packs): sets the host's environment from the bundle, then runs the Mac host (Contents/MacOS/dmhost) as a child.
// The host is not exec'ed: macOS privacy checks (TCC) attribute a child's file access to the app that launched it, while a launcher that hands its process over (a shell script exec'ing
// dmhost) gets EPERM on every open on a removable volume, with no prompt, signed or not. The launcher forwards SIGTERM / SIGINT / SIGHUP to the host and returns its exit code.
-// Bundle layout: Resources/romfs (the game's RomFS), Resources/msl/<b-chain | vk | gl> (the Mac shader libraries), Resources/aoc/<index> (DLC), Resources/pso (the pipeline archive made
+// Bundle layout: Resources/romfs.img (the game's RomFS image; legacy romfs/ also supported), Resources/msl/<b-chain | vk | gl> (the Mac shader libraries), Resources/aoc/<index> (DLC), Resources/pso (the pipeline archive made
// offline, handed to the host as DM_PSO_BUNDLE as the iOS app's main.m does), Resources/dm (the rewritten modules, the shader tables and pairs, font/, env.txt). Saves, the pipeline list and temporary files go to ~/Library/Application Support/nxnative/<title ID>/, the host's output to ~/Library/Logs/nxnative/<title ID>.log
// (the previous run's kept as <title ID>.prev.log). Environment switches: one KEY=VALUE per line in <Application Support folder>/env.txt, then Resources/dm/env.txt (the first one wins; neither
// replaces a variable already set), as the iOS app reads Documents/env.txt and dm/env.txt.
@@ -18,6 +18,7 @@
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
+#include "romfs_image.h"
extern char **environ;
static pid_t g_child;
@@ -82,9 +83,14 @@ int main(void) {
if (!info_string("CFBundleName", name, sizeof name)) snprintf(name, sizeof name, "nxnative");
info_string("DMRomfsMarker", marker, sizeof marker); info_string("DMLanguage", lang, sizeof lang);
if (!info_string("DMTitleID", id, sizeof id) || strchr(id, '/')) { alert(name, "This app has no title ID in its Info.plist (DMTitleID): pack it again with build_ipa_from_nsp.py --platform mac-app."); return 1; }
- struct stat st; snprintf(p, sizeof p, "%s/%s", romfs, marker);
- if (access(host, X_OK) || stat(p, &st) || !modules_present(dm)) {
- alert(name, "The game data inside this app is missing or incomplete (Contents/Resources/romfs, Contents/Resources/dm or Contents/MacOS/dmhost): pack it again with build_ipa_from_nsp.py --platform mac-app.");
+ struct stat st; snprintf(p, sizeof p, "%s/romfs.img", res);
+ int valid_romfs;
+ if (!stat(p, &st)) {
+ romfs_img *image = romfs_image_open(p); valid_romfs = image != NULL;
+ romfs_image_close(image); snprintf(romfs, sizeof romfs, "%s", p);
+ } else { snprintf(p, sizeof p, "%s/%s", romfs, marker); valid_romfs = !stat(p, &st); }
+ if (access(host, X_OK) || !valid_romfs || !modules_present(dm)) {
+ alert(name, "The game data inside this app is missing or incomplete (Contents/Resources/romfs.img, Contents/Resources/dm or Contents/MacOS/dmhost): pack it again with build_ipa_from_nsp.py --platform mac-app.");
return 1;
}
const char *home = getenv("HOME"); if (!home || !*home) return 1;
diff --git a/dm/mac/pack_app.py b/dm/mac/pack_app.py
index d08d4987..bdf61634 100644
--- a/dm/mac/pack_app.py
+++ b/dm/mac/pack_app.py
@@ -1,18 +1,20 @@
#!/usr/bin/env python3
# Pack a self-contained, double-clickable Mac app of a game (the NSP script's --platform mac-app): the launcher (dm/mac/launcher.c, compiled here) as CFBundleExecutable, the Mac host beside it,
-# and in Contents/Resources what the IPA carries (dm/ios/tools/build_ipa.sh): romfs/ (the RomFS), msl/<b-chain | vk | gl>/ (the Mac shader libraries, the folder named as in the IPA),
+# and in Contents/Resources what the IPA carries (dm/ios/tools/build_ipa.sh): romfs.img (the RomFS image), msl/<b-chain | vk | gl>/ (the Mac shader libraries, the folder named as in the IPA),
# aoc/<index>/ (DLC), pso/ (an NVN game's pipeline archive made offline for this Mac's GPU, dm/gfx/tools/pso_offline.py: the launcher hands it to the host as DM_PSO_BUNDLE),
# and dm/ (the rewritten modules and their rewriter tables, nro.tsv, the profile's shader_map.tsv / pso_manifest.tsv / c1_full.tsv / cb_extent.tsv / shader_pairs.tsv / pso_pairs.tsv, font/, env.txt),
# plus AppIcon.icns from the game's icon (sips, iconutil) and the Info.plist keys the launcher reads (DMTitleID, DMRomfsMarker, DMLanguage).
# The large folders are APFS clones (cp -c) when the app is on the same APFS volume as the build, so they take no space; plain copies otherwise.
# Signing: the inner host first, then the bundle (codesign --force --sign <identity>; '-' = ad-hoc), without the hardened runtime: the host maps the game's code executable, which the hardened
# runtime refuses without entitlements, and so the app cannot be notarized.
-# Usage: pack_app.py <out.app> --host <dmhost> --patched <dir> --romfs <dir> --msl <dir> --tables <profile dir> --font <dir> --title-id <id> --name <name> [options]
+# Usage: pack_app.py <out.app> --host <dmhost> --patched <dir> --romfs <image or dir> --msl <dir> --tables <profile dir> --font <dir> --title-id <id> --name <name> [options]
# Reuses <out.app> while <out.app>.key matches; otherwise writes <out.app>.partial and swaps it in at the end. Prints "step: ..." and "app: <path>[, reused (inputs unchanged)]".
import argparse, ctypes, hashlib, json, os, plistlib, re, shutil, stat, subprocess, sys, tempfile
from pathlib import Path
HERE = Path(__file__).resolve().parent
+sys.path.insert(0, str(HERE.parent / 'tools'))
+import romfs as rfs
MODULE_FILES = ('*.patched.bin', '*.fixups.tsv', '*.gates.tsv', '*.cuts.tsv', '*.obs.tsv', 'nro.tsv') # what the host reads from the module folder (build_ipa.sh copies the same tables)
MSL_FILES = ('*.metallib', '*.json', '*.tsv') # what the host reads from msl/ (not the Mac build's .metal sources or _b_build.json)
# read beside DM_NVN_SHMAP; any of them may be absent (a Vulkan or GL game has no c1_full.tsv). The shader pairs are the pipeline prebuild's (nvn_mtl.m pso_prebuild): without them the
@@ -50,6 +52,7 @@ def can_clone(src, dst_dir): # whether a file of src can be cloned into dst_di
def tree_bytes(d):
+ if d.is_file(): return d.stat().st_size
return sum((Path(r) / f).stat().st_size for r, _, fs in os.walk(d) for f in fs)
@@ -76,7 +79,7 @@ def min_os(host): # the host's deployment target (LC_BUILD_VERSION minos): the
def build_launcher(out, minos, clang, sdk):
- run([clang, '-isysroot', sdk, '-arch', 'arm64', f'-mmacosx-version-min={minos}', '-O2', '-Wall', '-o', out, HERE / 'launcher.c', '-framework', 'CoreFoundation'])
+ run([clang, '-isysroot', sdk, '-arch', 'arm64', f'-mmacosx-version-min={minos}', '-O2', '-Wall', '-I', HERE.parent / 'host', '-o', out, HERE / 'launcher.c', '-framework', 'CoreFoundation'])
def make_icns(jpg, out): # the game's icon (256x256 JPEG) at every size an .icns holds
@@ -117,7 +120,7 @@ def inventory(root):
"""Stat trees avoid reading multi-GB game data, and detect changes to executable modes in the app."""
def walk_error(e): raise e
paths = [root]
- for parent, dirs, files in os.walk(root, onerror=walk_error):
+ for parent, dirs, files in (os.walk(root, onerror=walk_error) if root.is_dir() else []):
paths.extend(Path(parent) / n for n in dirs + files)
rows = []
for p in sorted(paths):
@@ -131,8 +134,8 @@ def selected_inputs(a):
"""Resolve once: these same lists supply both the reuse key and the copies."""
for name in ('patched', 'romfs', 'msl', 'tables', 'font', 'aoc', 'pso'):
p = getattr(a, name)
- if p and not Path(p).is_dir(): raise SystemExit(f'no {name} directory at {p}')
- if a.marker and not (Path(a.romfs) / a.marker).exists(): raise SystemExit(f'no RomFS at {a.romfs} (missing {a.marker})')
+ if p and not (rfs.Path(p).is_dir() if name == 'romfs' else Path(p).is_dir()): raise SystemExit(f'no {name} directory at {p}')
+ if a.marker and not (rfs.Path(a.romfs) / a.marker).exists(): raise SystemExit(f'no RomFS at {a.romfs} (missing {a.marker})')
mods = sorted({p for pat in MODULE_FILES for p in Path(a.patched).glob(pat)})
if not any(p.name.endswith('.patched.bin') for p in mods): raise SystemExit(f'no rewritten module in {a.patched}')
for p in mods:
@@ -185,7 +188,7 @@ def pack(a):
codesign = Path(codesign).resolve()
minos = min_os(a.host)
clang_stat = clang.stat()
- inputs = {'options': vars(a), 'files': [(str(p), p.stat().st_mode, digest(p), os.readlink(p) if p.is_symlink() else None) for p in files + [Path(__file__).resolve(), HERE / 'launcher.c']],
+ inputs = {'options': vars(a), 'files': [(str(p), p.stat().st_mode, digest(p), os.readlink(p) if p.is_symlink() else None) for p in files + [Path(__file__).resolve(), HERE / 'launcher.c', HERE.parent / 'host/romfs_image.h', HERE.parent / 'tools/romfs.py']],
'trees': [(p, inventory(Path(p))) for p in (a.romfs, a.aoc) if p],
'tools': [str(clang), clang_stat.st_mode, clang_stat.st_size, clang_stat.st_mtime_ns, clang_stat.st_ctime_ns, run([clang, '--version']).strip(),
str(sdk), run(['xcrun', '--sdk', 'macosx', '--show-sdk-version']).strip(),
@@ -219,7 +222,7 @@ def pack(a):
step('shader libraries'); msl_dst = res / 'msl' / (a.msl_name or msl.name); msl_dst.mkdir(parents=True); copy(msls, msl_dst, clone)
if aoc: step('add-on content'); copy([aoc], res / 'aoc', clone)
if pso: step('pipeline archive'); (res / 'pso').mkdir(); copy(pso, res / 'pso', pso_clone)
- step('game files'); copy([romfs], res / 'romfs', clone)
+ step('game files'); copy([romfs], res / ('romfs.img' if romfs.is_file() else 'romfs'), clone)
icon = bool(a.icon)
if icon: step('icon'); make_icns(a.icon, res / 'AppIcon.icns')
info = info_plist(a, minos, icon)
@@ -253,7 +256,7 @@ def parse(argv):
ap.add_argument('--msl-name', help='its folder name in the app (default: its own)')
ap.add_argument('--tables', required=True, help='the game profile folder (shader_map.tsv and the tables beside it)')
ap.add_argument('--font', required=True, help='the folder of the shared-font stand-ins (nintendo_ext.ttf)')
- ap.add_argument('--aoc', help='the DLC RomFS folders by index')
+ ap.add_argument('--aoc', help='the DLC RomFS images or folders by index')
ap.add_argument('--pso', help='the pipeline archive made offline for this Mac (pso_offline.py --platform macos output: <arch>.mtl4a, prebuilt.tsv)')
ap.add_argument('--pso-pairs', help='pso_pairs.tsv for a profile that has none (the shader split\'s copy)')
ap.add_argument('--env-file', help='environment switches baked in (Resources/dm/env.txt)')
diff --git a/dm/tools/impact_map.tsv b/dm/tools/impact_map.tsv
index 01b5c5fd..df05fa53 100644
--- a/dm/tools/impact_map.tsv
+++ b/dm/tools/impact_map.tsv
@@ -21,6 +21,7 @@ dm/games/*/usage.tsv - a usage manifest
dm/games/* profile one game's profile
scripts/build_ipa_from_nsp.py *:* packing: every game's build
scripts/bench.py - the benchmark
+scripts/push_romfs.sh *:* RomFS transfer: every game's iOS build
scripts/regress.py - the regression harness
dm/tools/usage.py - the usage manifests
dm/tools/impact_map.tsv - this map
@@ -82,6 +83,19 @@ dm/gfx/tools/shader_split.py shader:stage:* the shader tables (after a split)
dm/tools/patch_nso.py *:* the rewriter: every game's code
dm/tools/nso_*.py *:* the rewriter: every game's code
dm/tools/sdk_patches.py *:* the SDK modules' patches (by build ID)
+dm/tools/romfs_image.py *:* RomFS image packing: every game's files
+dm/tools/romfs.py *:* RomFS image input: every game's build tools
+dm/tools/nro_collect.py *:* NRO discovery from game resources during packing
+dm/tools/nx_extract/* *:* NSP extraction: every game's resource inputs
+dm/mac/launcher.c *:* Mac app resource discovery and host launch
+dm/mac/pack_app.py *:* Mac app packaging: every game's bundled resources
+dm/gfx/tools/cpk.py shader:stage:* CRI archive input to shader scanning
+dm/gfx/tools/mvgl.py api:gl MVGL archive input to OpenGL shader scanning
+dm/gfx/tools/smash_arc.py *:* Smash archive input to shader and NRO scanning
+dm/gfx/tools/uepak.py shader:stage:* Unreal archive input to shader scanning
+dm/host/romfs_image.h hle:*fs* RomFS image index validation shared by mounts and iOS startup
+dm/host/hle_fs.c hle:*fs* filesystem mounts, paths and file operations
+dm/host/Makefile *:* the shared host build
dm/host/hle_thread.c svc:* threads and synchronization
dm/host/hle_svc.c svc:* SVCs
dm/host/thread.c svc:* threads
diff --git a/dm/tools/lint_python_baseline.tsv b/dm/tools/lint_python_baseline.tsv
index 1402e9a0..3cfb03bf 100644
--- a/dm/tools/lint_python_baseline.tsv
+++ b/dm/tools/lint_python_baseline.tsv
@@ -23,11 +23,9 @@ pyright dm/gfx/tools/shader_split.py reportArgumentType 1 Argument of type "Lite
pyright dm/gfx/tools/shader_split.py reportArgumentType 1 Argument of type "Literal['m_ParsedForm']" cannot be assigned to parameter "s" of type "slice[SupportsIndex | None, SupportsIndex | None, SupportsIndex | None]" in function "__getitem__" "Literal['m_ParsedForm']" is not assignable to "slice[SupportsIndex | None, SupportsIndex | None, SupportsIndex | None]"
pyright dm/gfx/tools/shader_split.py reportArgumentType 1 Argument of type "Literal['variants']" cannot be assigned to parameter "s" of type "slice[SupportsIndex | None, SupportsIndex | None, SupportsIndex | None]" in function "__getitem__" "Literal['variants']" is not assignable to "slice[SupportsIndex | None, SupportsIndex | None, SupportsIndex | None]"
pyright dm/gfx/tools/shader_split.py reportArgumentType 1 Argument of type "bytes | None" cannot be assigned to parameter "buffer" of type "ReadableBuffer" in function "unpack_from" Type "bytes | None" is not assignable to type "ReadableBuffer" "None" is incompatible with protocol "Buffer" "__buffer__" is not present
-pyright dm/gfx/tools/shader_split.py reportArgumentType 1 Argument of type "list[str | None]" cannot be assigned to parameter "args" of type "_CMD" in function "__init__" Type "str | None" is not assignable to type "StrOrBytesPath" Type "None" is not assignable to type "StrOrBytesPath" "None" is not assignable to "str" "None" is not assignable to "bytes" "None" is incompatible with protocol "PathLike[str]" "__fspath__" is not present "None" is incompatible with protocol "PathLike[bytes]" "__fspath__" is not present
pyright dm/gfx/tools/shader_split.py reportArgumentType 2 Argument of type "Unknown | int | None" cannot be assigned to parameter "offset" of type "int" in function "unpack_from" Type "Unknown | int | None" is not assignable to type "int" "None" is not assignable to "int"
pyright dm/gfx/tools/shader_split.py reportAssignmentType 1 Expression with type "tuple[Any, Any] | Any" cannot be assigned to target tuple Type "tuple[Any, Any]" is incompatible with target tuple Tuple size mismatch; expected 4 but received 2
pyright dm/gfx/tools/shader_split.py reportAttributeAccessIssue 1 Cannot access attribute "get" for class "list[Any]" Attribute "get" is unknown
-pyright dm/gfx/tools/shader_split.py reportCallIssue 1 No overloads for "__init__" match the provided arguments
pyright dm/gfx/tools/shader_split.py reportCallIssue 3 No overloads for "__getitem__" match the provided arguments
pyright dm/gfx/tools/shader_split.py reportGeneralTypeIssues 2 "None" is not iterable "__iter__" method not defined
pyright dm/gfx/tools/shader_split.py reportMissingImports 1 Import "backports" could not be resolved
@@ -219,7 +217,6 @@ pyright scripts/bench.py reportArgumentType 1 Argument of type "Unknown | None"
pyright scripts/bench.py reportArgumentType 1 Argument of type "float" cannot be assigned to parameter "value" of type "int" in function "__setitem__" "float" is not assignable to "int"
pyright scripts/bench.py reportCallIssue 1 No overloads for "round" match the provided arguments
pyright scripts/bench.py reportOptionalMemberAccess 1 "group" is not a known attribute of "None"
-pyright scripts/bench.py reportOptionalOperand 1 Operator "/" not supported for "None"
pyright scripts/build_ipa_from_nsp.py reportArgumentType 1 Argument of type "str | ((n: Unknown) -> (Unknown | None))" cannot be assigned to parameter "func" of type "(_T1@__new__) -> _S@map" in function "__new__" Type "str | ((n: Unknown) -> (Unknown | None))" is not assignable to type "(Unknown) -> _S@map" Type "str" is not assignable to type "(Unknown) -> _S@map"
pyright scripts/build_ipa_from_nsp.py reportArgumentType 1 Argument of type "str | ((n: Unknown) -> (Unknown | None))" cannot be assigned to parameter "func" of type "(_T1@__new__) -> _S@map" in function "__new__" Type "str | ((n: Unknown) -> (Unknown | None))" is not assignable to type "(_T1@__new__) -> _S@map" Type "str" is not assignable to type "(_T1@__new__) -> _S@map"
pyright scripts/build_ipa_from_nsp.py reportCallIssue 1 Argument expression after ** must be a mapping with a "str" key type
@@ -253,4 +250,3 @@ ruff dm/tools/tests/test_nsp_nsz.py F401 1 `sys` imported but unused
ruff dm/tools/tests/test_spin_waits.py F401 1 `sys` imported but unused
ruff scripts/bench.py B023 1 Function definition does not bind loop variable `ok`
ruff scripts/build_ipa_from_nsp.py B020 1 Loop control variable `note` overrides iterable it iterates
-ruff scripts/build_ipa_from_nsp.py F401 1 `zlib` imported but unused
diff --git a/dm/tools/nro_collect.py b/dm/tools/nro_collect.py
index 0b151033..97104c26 100644
--- a/dm/tools/nro_collect.py
+++ b/dm/tools/nro_collect.py
@@ -8,8 +8,9 @@ The game passes nn::ro::LoadModule the NRO's bytes; the host finds the rewritten
Where: a loose file whose bytes at +0x10 are NRO0 (Hades and Hades II ship their EOS SDK so); the .nro files among the current files of an archive with an index (Super Smash Bros. Ultimate's data.arc,
read by dm/gfx/tools/smash_arc.py: 98 NROs, while the NRRs of every older release also register 666 superseded copies the archive still holds, which are left out); else a scan of the
other RomFS files for stored NROs and zstd frames that inflate to one (on data.arc: all 764 registered hashes in 7 minutes)."""
-import hashlib, mmap, os, struct, sys
+import hashlib, struct, sys
from multiprocessing import Pool
+from romfs import os, open, mmap
ZMAGIC = b'\x28\xb5\x2f\xfd'
diff --git a/dm/tools/nx_extract/Program.cs b/dm/tools/nx_extract/Program.cs
index 5d7c0bbd..e8c13925 100644
--- a/dm/tools/nx_extract/Program.cs
+++ b/dm/tools/nx_extract/Program.cs
@@ -1,11 +1,13 @@
-// NSP extraction: nx_extract <prod.keys> <base NSP> <update NSP or -> <output dir> [base RomFS dir to compare against] [--manifest]
-// Writes <output dir>/ExeFS and <output dir>/RomFS (the merged RomFS when there is an update); with a base RomFS dir, files whose content matches it become APFS clones (no new space).
+// NSP extraction: nx_extract <prod.keys> <base NSP> <update NSP or -> <output dir> [base RomFS dir to compare against] [--manifest] [--romfs-image]
+// --romfs-image streams the merged RomFS directly to <output dir>/RomFS.img (the packing script's default); only ExeFS is expanded. Without it, legacy folder extraction remains available.
+// With a base RomFS dir in legacy mode, files whose content matches it become APFS clones (no new space).
// --manifest: the RomFS is not written, only a list <output dir>/romfs_manifest.tsv (path, size, first 32 bytes), for surveying a new game (a large game's RomFS is well over 10 GB).
// A damaged NSP (a file whose data fails the NCA's hash check, e.g. a copy cut short or a broken download) stops the extraction with exit code 3 after listing every damaged file;
// --allow-damaged writes those files as read instead and only lists them (Super Mario Galaxy's base NSP with 147 MB zeroed: its two prologue WebM movies).
// Add-on content: nx_extract <prod.keys> --aoc <DLC NSP> <output dir> writes the RomFS of the DLC's data NCA to <output dir> (the packing script puts it at aoc/<index>/, the host mounts it through DM_AOC_DIR).
// Title keys come from the common tickets (.tik) inside the NSPs, so only prod.keys is needed; key values are never printed.
// The base game may also be a cartridge dump (.xci, Monster Hunter Rise): its secure partition holds the NCAs, which carry their keys in the key area (no ticket).
+// When the cartridge also carries an update (1G+1U), only the base game's NCAs (those its Application content meta lists) are read; the update comes from the update NSP.
using System;
using System.Collections.Generic;
using System.IO;
@@ -15,11 +17,13 @@ using LibHac.Common.Keys;
using LibHac.Fs;
using LibHac.Fs.Fsa;
using LibHac.FsSystem;
+using LibHac.Ncm;
using LibHac.Spl;
using LibHac.Tools.Fs;
using LibHac.Tools.FsSystem;
using LibHac.Tools.FsSystem.NcaUtils;
using LibHac.Tools.FsSystem.RomFs;
+using LibHac.Tools.Ncm;
using Path = System.IO.Path;
static class P {
@@ -27,11 +31,12 @@ static class P {
static int Main(string[] a) {
bool manifest = Array.IndexOf(a, "--manifest") >= 0; a = Array.FindAll(a, s => s != "--manifest");
+ bool image = Array.IndexOf(a, "--romfs-image") >= 0; a = Array.FindAll(a, s => s != "--romfs-image");
g_allow = Array.IndexOf(a, "--allow-damaged") >= 0; a = Array.FindAll(a, s => s != "--allow-damaged");
- if (a.Length < 4) { Console.Error.WriteLine("usage: nx_extract <prod.keys> <base.nsp> <update.nsp|-> <out dir> [base RomFS dir] [--manifest] [--allow-damaged]\n nx_extract <prod.keys> --aoc <dlc.nsp> <out dir>"); return 2; }
+ if (a.Length < 4) { Console.Error.WriteLine("usage: nx_extract <prod.keys> <base.nsp> <update.nsp|-> <out dir> [base RomFS dir] [--romfs-image|--manifest] [--allow-damaged]\n nx_extract <prod.keys> --aoc <dlc.nsp> <out dir or image> [--romfs-image]"); return 2; }
KeySet ks = ExternalKeyReader.ReadKeyFile(a[0]);
- if (a[1] == "--aoc") return Aoc(ks, a[2], a[3]);
- var basePkg = OpenNsp(ks, a[1]); var updPkg = a[2] == "-" ? null : OpenNsp(ks, a[2]);
+ if (a[1] == "--aoc") return Aoc(ks, a[2], a[3], image);
+ var basePkg = OpenNsp(ks, a[1], ContentMetaType.Application); var updPkg = a[2] == "-" ? null : OpenNsp(ks, a[2]);
Nca baseProg = Pick(basePkg, NcaContentType.Program) ?? throw new Exception("no Program NCA in the base NSP");
Nca updProg = updPkg == null ? null : Pick(updPkg, NcaContentType.Program, baseProg.Header.TitleId) ?? throw new Exception("no Program NCA of the base game's program in the update NSP");
Nca ctrl = Pick(updPkg ?? basePkg, NcaContentType.Control, baseProg.Header.TitleId);
@@ -58,7 +63,8 @@ static class P {
// A program can embed all assets in its code modules (ANIMAL WELL 1.0.10).
// Preserve the extraction layout without asking LibHac to open an absent section.
if (!baseProg.SectionExists(1) && (updProg == null || !updProg.SectionExists(1))) {
- Directory.CreateDirectory(Path.Combine(outDir, "RomFS"));
+ if (image && !manifest) WriteImage(null, Path.Combine(outDir, "RomFS.img"));
+ else if (!manifest) Directory.CreateDirectory(Path.Combine(outDir, "RomFS"));
if (manifest) File.WriteAllText(Path.Combine(outDir, "romfs_manifest.tsv"), "# path\tbytes\tfirst 32 bytes (hex)\n");
Console.WriteLine("program has no data section: empty RomFS");
return Damaged();
@@ -67,6 +73,7 @@ static class P {
// the same RomFS without hash checks, for reading damaged files as they are (--allow-damaged)
g_lenient = () => new RomFsFileSystem(updProg != null ? baseProg.OpenStorageWithPatch(updProg, NcaSectionType.Data, IntegrityCheckLevel.IgnoreOnInvalid) : baseProg.OpenStorage(NcaSectionType.Data, IntegrityCheckLevel.IgnoreOnInvalid));
if (manifest) Manifest(new RomFsFileSystem(romfs), Path.Combine(outDir, "romfs_manifest.tsv"));
+ else if (image) WriteImage(new RomFsFileSystem(romfs), Path.Combine(outDir, "RomFS.img"));
else Copy(new RomFsFileSystem(romfs), Path.Combine(outDir, "RomFS"), cmpDir);
return Damaged();
}
@@ -84,17 +91,20 @@ static class P {
}
// DLC NSP: one data NCA (content type PublicData / Data) + a meta NCA + the ticket; only the data NCA's RomFS is written
- static int Aoc(KeySet ks, string nsp, string outDir) {
+ static int Aoc(KeySet ks, string nsp, string outDir, bool image) {
var pkg = OpenNsp(ks, nsp);
Nca data = Pick(pkg, NcaContentType.PublicData) ?? Pick(pkg, NcaContentType.Data) ?? throw new Exception("no data NCA in the DLC NSP");
Console.WriteLine($"add-on content {data.Header.TitleId:x16}");
- Directory.CreateDirectory(outDir);
- Copy(new RomFsFileSystem(data.OpenStorage(NcaSectionType.Data, IntegrityCheckLevel.ErrorOnInvalid)), outDir, null);
- return 0;
+ Directory.CreateDirectory(image ? Path.GetDirectoryName(outDir) : outDir);
+ var fs = new RomFsFileSystem(data.OpenStorage(NcaSectionType.Data, IntegrityCheckLevel.ErrorOnInvalid));
+ g_lenient = () => new RomFsFileSystem(data.OpenStorage(NcaSectionType.Data, IntegrityCheckLevel.IgnoreOnInvalid));
+ if (image) WriteImage(fs, outDir); else Copy(fs, outDir, null);
+ return Damaged();
}
- // Open an NSP (PFS0) or the secure partition of an XCI, import the common tickets, list all NCAs
- static List<Nca> OpenNsp(KeySet ks, string path) {
+ // Open an NSP (PFS0) or the secure partition of an XCI, import the common tickets, list all NCAs. With a content meta type, only the NCAs that the package's content metas of
+ // that type list (when it has one): a cartridge dump with its update on it (1G+1U) holds the update's NCAs beside the base game's, its Program NCA under the same title ID
+ static List<Nca> OpenNsp(KeySet ks, string path, ContentMetaType? only = null) {
IFileSystem pfs; var st0 = new LocalStorage(path, FileAccess.Read);
byte[] magic = new byte[4]; st0.Read(0x100, magic).ThrowIfFailure();
if (System.Text.Encoding.ASCII.GetString(magic) == "HEAD") { // XCI: the card header's magic at 0x100
@@ -104,7 +114,7 @@ static class P {
} else {
var p = new PartitionFileSystem(); p.Initialize(st0).ThrowIfFailure(); pfs = p;
}
- var ncas = new List<Nca>();
+ var ncas = new List<Nca>(); var ids = new List<string>(); // ids: content IDs (the file names' hex)
foreach (DirectoryEntryEx e in pfs.EnumerateEntries("*", SearchOptions.Default)) {
using var f = new UniqueRef<IFile>();
pfs.OpenFile(ref f.Ref, e.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
@@ -113,9 +123,29 @@ static class P {
byte[] t = new byte[0x2c0]; st.Read(0, t).ThrowIfFailure();
if (t[0x281] != 0) { Console.Error.WriteLine($"[RED] {e.Name} is not a common ticket; supply the title key separately"); continue; }
ks.ExternalKeySet.Add(new RightsId(t.AsSpan(0x2a0, 0x10)), new AccessKey(t.AsSpan(0x180, 0x10))).ThrowIfFailure();
- } else if (e.Name.EndsWith(".nca", StringComparison.OrdinalIgnoreCase)) ncas.Add(new Nca(ks, st));
+ } else if (e.Name.EndsWith(".nca", StringComparison.OrdinalIgnoreCase)) { ncas.Add(new Nca(ks, st)); ids.Add(e.Name[..e.Name.IndexOf('.')].ToLowerInvariant()); }
+ }
+ if (only == null) return ncas;
+ var listed = new HashSet<string>();
+ foreach (Nca n in ncas) {
+ if (n.Header.ContentType != NcaContentType.Meta) continue;
+ IFileSystem mfs = n.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.ErrorOnInvalid);
+ foreach (DirectoryEntryEx e in mfs.EnumerateEntries("*.cnmt", SearchOptions.Default)) {
+ using var f = new UniqueRef<IFile>();
+ mfs.OpenFile(ref f.Ref, e.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
+ var cnmt = new Cnmt(f.Release().AsStream());
+ if (cnmt.Type == only) foreach (CnmtContentEntry c in cnmt.ContentEntries) listed.Add(Convert.ToHexString(c.NcaId).ToLowerInvariant());
+ }
+ }
+ if (listed.Count == 0) return ncas;
+ var kept = new List<Nca>(); int other = 0; // the meta NCAs list the others, not themselves
+ for (int i = 0; i < ncas.Count; i++) if (listed.Contains(ids[i])) kept.Add(ncas[i]); else if (ncas[i].Header.ContentType != NcaContentType.Meta) other++;
+ if (!kept.Exists(n => n.Header.ContentType == NcaContentType.Program)) { // file names that are not content IDs (renamed NCAs): nothing matches, so read every NCA as before
+ Console.WriteLine($"[RED] no NCA of {Path.GetFileName(path)} matches its {only} content meta by name (renamed NCA files?); reading all {ncas.Count}");
+ return ncas;
}
- return ncas;
+ if (other > 0) Console.WriteLine($"leaving out {other} NCAs of {Path.GetFileName(path)} that its {only} content meta does not list (an update on the cartridge)");
+ return kept;
}
// A multi-program application has a Program and a Control NCA per program index (ROMANCE OF THE THREE KINGDOMS 8 REMAKE: its update 1.1.3 adds a whole second program,
// title ID …0001, beside the game's patch, …0000): with no title ID the lowest one (program index 0, the game), else the NCA of that title ID
@@ -163,6 +193,76 @@ static class P {
return "";
}
+ sealed class ImageEntry {
+ public string Path; public byte[] Name; public bool Directory; public long Size; public ulong A, B;
+ public List<ImageEntry> Children = new List<ImageEntry>();
+ }
+ // Stream the merged, integrity-checked filesystem directly into DMROMFS1. No RomFS directories or per-resource host files are created.
+ static void WriteImage(IFileSystem fs, string dst) {
+ var root = new ImageEntry { Path = "/", Name = Array.Empty<byte>(), Directory = true };
+ var byPath = new Dictionary<string, ImageEntry>(StringComparer.Ordinal) { ["/"] = root };
+ if (fs != null) foreach (DirectoryEntryEx e in fs.EnumerateEntries("*", SearchOptions.RecurseSubdirectories)) {
+ string path = e.FullPath.TrimEnd('/'); if (path.Length == 0) continue;
+ byte[] name = System.Text.Encoding.UTF8.GetBytes(path.Substring(path.LastIndexOf('/') + 1));
+ if (name.Length == 0 || name.Length > 0x300) throw new IOException($"invalid RomFS name length: {path}");
+ byPath.Add(path, new ImageEntry { Path = path, Name = name, Directory = e.Type == DirectoryEntryType.Directory, Size = e.Size });
+ }
+ foreach (var e in byPath.Values) {
+ if (e == root) continue;
+ string parent = e.Path.Substring(0, e.Path.LastIndexOf('/')); if (parent.Length == 0) parent = "/";
+ byPath[parent].Children.Add(e);
+ }
+ var entries = new List<ImageEntry> { root };
+ for (int i = 0; i < entries.Count; i++) if (entries[i].Directory) {
+ var e = entries[i]; e.Children.Sort((a, b) => a.Name.AsSpan().SequenceCompareTo(b.Name));
+ e.A = (ulong)entries.Count; e.B = (ulong)e.Children.Count; entries.AddRange(e.Children);
+ }
+ Directory.CreateDirectory(Path.GetDirectoryName(dst));
+ string part = dst + ".part"; long files = 0, bytes = 0; int damaged = g_damaged.Count;
+ try {
+ using (var output = File.Create(part)) using (var writer = new BinaryWriter(output)) {
+ writer.Write(new byte[32]); byte[] buffer = new byte[4 << 20];
+ foreach (var e in entries) {
+ if (e.Directory) continue;
+ e.A = (ulong)output.Position; e.B = (ulong)e.Size; files++; bytes += e.Size;
+ using var f = new UniqueRef<IFile>();
+ fs.OpenFile(ref f.Ref, e.Path.ToU8Span(), OpenMode.Read).ThrowIfFailure();
+ try { WriteStream(f.Get, output, e.Size, buffer); }
+ catch (HorizonResultException x) when (HashError(x)) {
+ g_damaged.Add(e.Path);
+ if (!g_allow) continue;
+ g_lenientFs ??= g_lenient();
+ using var lf = new UniqueRef<IFile>();
+ g_lenientFs.OpenFile(ref lf.Ref, e.Path.ToU8Span(), OpenMode.Read).ThrowIfFailure();
+ output.Position = (long)e.A; output.SetLength(output.Position);
+ WriteStream(lf.Get, output, e.Size, buffer);
+ }
+ }
+ if (g_damaged.Count == damaged || g_allow) {
+ long index = output.Position; using var names = new MemoryStream();
+ foreach (var e in entries) {
+ writer.Write(e.A); writer.Write(e.B); writer.Write(checked((uint)names.Position));
+ writer.Write(checked((ushort)e.Name.Length)); writer.Write((byte)(e.Directory ? 0 : 1)); writer.Write((byte)0);
+ names.Write(e.Name);
+ }
+ names.Position = 0; names.CopyTo(output); long size = output.Position - index;
+ output.Position = 0; writer.Write(System.Text.Encoding.ASCII.GetBytes("DMROMFS1"));
+ writer.Write((ulong)index); writer.Write((ulong)size); writer.Write((ulong)entries.Count);
+ }
+ }
+ if (g_damaged.Count != damaged && !g_allow) { File.Delete(part); return; }
+ File.Move(part, dst, true);
+ Console.WriteLine($"{dst}: {files} files {bytes / 1048576.0:F1} MB, image with {entries.Count} entries");
+ } catch { File.Delete(part); throw; }
+ }
+ static void WriteStream(IFile file, Stream output, long size, byte[] buffer) {
+ for (long offset = 0; offset < size;) {
+ file.Read(out long got, offset, buffer.AsSpan(0, (int)Math.Min(buffer.Length, size - offset)), ReadOption.None).ThrowIfFailure();
+ if (got <= 0) throw new IOException($"cannot read @{offset}");
+ output.Write(buffer, 0, (int)got); offset += got;
+ }
+ }
+
// Copy out file by file; files identical to the same path in the compare dir become APFS clones instead
static void Copy(IFileSystem fs, string dst, string cmpDir) {
long n = 0, cloned = 0, bytes = 0, written = 0; byte[] buf = new byte[4 << 20], cb = new byte[4 << 20];
diff --git a/dm/tools/romfs.py b/dm/tools/romfs.py
new file mode 100644
index 00000000..7736ad23
--- /dev/null
+++ b/dm/tools/romfs.py
@@ -0,0 +1,316 @@
+"""Read-only paths inside DMROMFS1 images, without extracting their contents.
+
+Readers opt into Path/open/os/mmap here; the real filesystem is untouched. A path
+like /game/RomFS.img/Data/archive is a bounded view of that image entry. Ordinary
+paths retain their normal behavior, including writes to generated outputs.
+"""
+import builtins
+import errno
+import fnmatch
+import functools
+import io
+import mmap as _mmap
+import os as _os
+from pathlib import Path as _Path
+import stat as _stat
+import struct
+import sys
+from types import SimpleNamespace
+from typing import TYPE_CHECKING
+
+HEAD = struct.Struct('<8sQQQ')
+ENT = struct.Struct('<QQIHBB')
+MAGIC = b'DMROMFS1'
+
+
+class Image:
+ def __init__(self, path):
+ self.path = _os.path.abspath(path)
+ self.stat = _os.stat(self.path)
+ with builtins.open(self.path, 'rb') as f:
+ magic, off, size, count = HEAD.unpack(f.read(HEAD.size))
+ if magic != MAGIC or not 0 < count <= 0xffffffff or off < HEAD.size or off > self.stat.st_size or size != self.stat.st_size - off or count > size // ENT.size:
+ raise ValueError(f'invalid RomFS image header: {path}')
+ f.seek(off); self.index = f.read(size)
+ if len(self.index) != size: raise ValueError(f'incomplete RomFS image: {path}')
+ self.count, self.pool = count, count * ENT.size
+ next_child = 1
+ for k in range(count):
+ a, b, no, nl, t, pad = self.entry(k)
+ if no + nl > size - self.pool or t > 1 or pad or (k == 0 and (t or nl)):
+ raise ValueError(f'invalid RomFS image entry {k}: {path}')
+ name = self.name(k)
+ if k and (not nl or nl > 0x300 or b'\0' in name or b'/' in name or name in (b'.', b'..')):
+ raise ValueError(f'invalid RomFS image name: {path}')
+ if t:
+ if a < HEAD.size or a > off or b > off - a: raise ValueError(f'invalid RomFS image file range: {path}')
+ else:
+ if a != next_child or a <= k or a > count or b > count - a: raise ValueError(f'invalid RomFS image tree: {path}')
+ next_child += b
+ if next_child != count: raise ValueError(f'unreachable RomFS image entries: {path}')
+ for k in range(count):
+ a, b, _, _, t, _ = self.entry(k)
+ if not t and any(self.name(j - 1) >= self.name(j) for j in range(a + 1, a + b)):
+ raise ValueError(f'unsorted or duplicate RomFS image names: {path}')
+
+ def entry(self, k): return ENT.unpack_from(self.index, k * ENT.size)
+ def name(self, k):
+ _, _, no, nl, _, _ = self.entry(k)
+ return self.index[self.pool + no:self.pool + no + nl]
+
+ def find(self, relative):
+ k = 0
+ for part in relative.split('/'):
+ if not part or part == '.': continue
+ a, b, _, _, t, _ = self.entry(k)
+ if t: raise NotADirectoryError(relative)
+ lo, hi, wanted = a, a + b, _os.fsencode(part)
+ while lo < hi:
+ mid = (lo + hi) // 2
+ if self.name(mid) < wanted: lo = mid + 1
+ else: hi = mid
+ if lo == a + b or self.name(lo) != wanted: raise FileNotFoundError(relative)
+ k = lo
+ return k
+
+ def children(self, k):
+ a, b, _, _, t, _ = self.entry(k)
+ if t: raise NotADirectoryError(self.path)
+ return [(_os.fsdecode(self.name(j)), j) for j in range(a, a + b)]
+
+
[email protected]_cache(maxsize=8)
+def _image(path, identity): return Image(path) if is_image(path) else None
+
+
+def is_image(path):
+ try:
+ with builtins.open(path, 'rb') as f: return f.read(8) == MAGIC
+ except (OSError, TypeError): return False
+
+
+def _resolve(path):
+ p = _os.path.abspath(_os.fsdecode(path))
+ parts = p.split('/')
+ for i, part in enumerate(parts):
+ if not part.endswith('.img'): continue
+ image = '/'.join(parts[:i + 1])
+ try: st = _os.stat(image)
+ except OSError: continue
+ if not _stat.S_ISREG(st.st_mode): continue
+ loaded = _image(image, (st.st_ino, st.st_size, st.st_mtime_ns, st.st_ctime_ns))
+ if loaded is not None: return loaded, '/'.join(parts[i + 1:])
+ return None
+
+
+def source(extraction):
+ image = _Path(extraction) / 'RomFS.img'
+ return Path(image if image.is_file() else _Path(extraction) / 'RomFS')
+
+
+_fd_ranges = {}
+
+
+class _File(io.RawIOBase):
+ def __init__(self, image, k):
+ self.fd = _os.open(image.path, _os.O_RDONLY)
+ self.start, self.length = image.entry(k)[:2]
+ self.pos = 0
+ _fd_ranges[self.fd] = (self.start, self.length)
+ def readable(self): return True
+ def seekable(self): return True
+ def fileno(self): return self.fd
+ def tell(self): return self.pos
+ def seek(self, offset, whence=0):
+ pos = offset + (self.pos if whence == 1 else self.length if whence == 2 else 0)
+ if whence not in (0, 1, 2) or pos < 0: raise ValueError('invalid seek')
+ self.pos = pos; return pos
+ def readinto(self, buffer):
+ size = min(len(buffer), max(0, self.length - self.pos))
+ data = _os.pread(self.fd, size, self.start + self.pos)
+ buffer[:len(data)] = data; self.pos += len(data)
+ return len(data)
+ def close(self):
+ if not self.closed:
+ _fd_ranges.pop(self.fd, None); _os.close(self.fd)
+ super().close()
+
+
+# Type checkers see the builtin's overloads, so a reader's open(..., 'rb').read() stays bytes and 'r' stays str.
+if TYPE_CHECKING:
+ from builtins import open
+else:
+ def open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, **kwargs):
+ resolved = _resolve(file) if not isinstance(file, int) else None
+ if not resolved: return builtins.open(file, mode, buffering, encoding, errors, newline, **kwargs)
+ if mode not in ('r', 'rb', 'rt'): raise OSError(errno.EROFS, 'RomFS images are read-only', file)
+ image, relative = resolved; k = image.find(relative)
+ if not image.entry(k)[4]: raise IsADirectoryError(file)
+ raw = _File(image, k)
+ if buffering == 0 and 'b' in mode: return raw
+ reader = io.BufferedReader(raw, io.DEFAULT_BUFFER_SIZE if buffering < 0 else buffering or io.DEFAULT_BUFFER_SIZE)
+ return reader if 'b' in mode else io.TextIOWrapper(reader, encoding=encoding, errors=errors, newline=newline)
+
+
+def stat(path, **kwargs):
+ resolved = _resolve(path)
+ if not resolved: return _os.stat(path, **kwargs)
+ image, relative = resolved; k = image.find(relative)
+ a, b, _, _, t, _ = image.entry(k); s = image.stat
+ return SimpleNamespace(st_mode=(_stat.S_IFREG | 0o444) if t else (_stat.S_IFDIR | 0o555), st_size=b if t else 0,
+ st_ino=k + 1, st_dev=s.st_dev, st_mtime=s.st_mtime, st_mtime_ns=s.st_mtime_ns,
+ st_ctime=s.st_ctime, st_ctime_ns=s.st_ctime_ns, st_atime=s.st_atime, st_atime_ns=s.st_atime_ns)
+
+
+def exists(path):
+ try: stat(path); return True
+ except OSError: return False
+def isdir(path):
+ try: return _stat.S_ISDIR(stat(path).st_mode)
+ except OSError: return False
+def isfile(path):
+ try: return _stat.S_ISREG(stat(path).st_mode)
+ except OSError: return False
+
+
+class _Entry:
+ def __init__(self, parent, name): self.name, self.path = name, _os.path.join(parent, name)
+ def stat(self, **kwargs): return stat(self.path)
+ def is_dir(self, **kwargs): return isdir(self.path)
+ def is_file(self, **kwargs): return isfile(self.path)
+ def is_symlink(self): return False
+ def inode(self): return self.stat().st_ino
+ def __fspath__(self): return self.path
+
+
+class _Scan:
+ def __init__(self, entries): self.entries = iter(entries)
+ def __iter__(self): return self
+ def __next__(self): return next(self.entries)
+ def __enter__(self): return self
+ def __exit__(self, *args): self.close()
+ def close(self): pass
+
+
+def scandir(path):
+ resolved = _resolve(path)
+ if not resolved: return _os.scandir(path)
+ image, relative = resolved
+ return _Scan(_Entry(path, name) for name, _ in image.children(image.find(relative)))
+
+
+def walk(top, topdown=True, onerror=None, followlinks=False):
+ if not _resolve(top):
+ yield from _os.walk(top, topdown=topdown, onerror=onerror, followlinks=followlinks); return
+ def visit(path):
+ try:
+ dirs, files = [], []
+ with scandir(path) as entries:
+ for e in entries: (dirs if e.is_dir() else files).append(e.name)
+ except OSError as error:
+ if onerror: onerror(error)
+ return
+ if topdown: yield str(path), dirs, files
+ for name in dirs: yield from visit(_os.path.join(path, name))
+ if not topdown: yield str(path), dirs, files
+ yield from visit(top)
+
+
+class Path(type(_Path())):
+ def stat(self, **kwargs): return stat(self, **kwargs)
+ def exists(self, **kwargs): return exists(self)
+ def is_dir(self, **kwargs): return isdir(self)
+ def is_file(self, **kwargs): return isfile(self)
+ def read_bytes(self):
+ with self.open('rb') as f: return f.read()
+ def read_text(self, encoding=None, errors=None, newline=None):
+ with self.open('r', encoding=encoding, errors=errors, newline=newline) as f: return f.read()
+ def open(self, mode='r', buffering=-1, encoding=None, errors=None, newline=None):
+ return open(self, mode, buffering, encoding, errors, newline)
+ def iterdir(self):
+ with scandir(self) as entries:
+ for e in entries: yield self / e.name
+ def glob(self, pattern, **kwargs):
+ if not _resolve(self): yield from super().glob(pattern, **kwargs); return
+ if '/' not in pattern:
+ yield from (p for p in self.iterdir() if fnmatch.fnmatchcase(p.name, pattern)); return
+ for directory, dirs, files in walk(self):
+ for name in dirs + files:
+ p = Path(directory) / name; rel = p.relative_to(self).as_posix()
+ if fnmatch.fnmatchcase(rel, pattern) or (pattern.startswith('**/') and fnmatch.fnmatchcase(rel, pattern[3:])): yield p
+ def rglob(self, pattern, **kwargs):
+ if not _resolve(self): yield from super().rglob(pattern, **kwargs); return
+ yield from self.glob('**/' + str(pattern))
+
+
+class _PathOps:
+ exists = staticmethod(exists); isdir = staticmethod(isdir); isfile = staticmethod(isfile)
+ getsize = staticmethod(lambda path: stat(path).st_size)
+ def __getattr__(self, name): return getattr(_os.path, name)
+class _OS:
+ path = _PathOps()
+ stat = staticmethod(stat); scandir = staticmethod(scandir); walk = staticmethod(walk)
+ @staticmethod
+ def listdir(path):
+ with scandir(path) as entries: return [e.name for e in entries]
+ def __getattr__(self, name): return getattr(_os, name)
+os = _OS()
+
+
+class _Map:
+ """mmap-compatible bounded buffer. Python 3.12's buffer protocol keeps archive parsing zero-copy."""
+ def __init__(self, fd, start, length):
+ self.length, self.pos = length, 0
+ self.delta = start % _mmap.ALLOCATIONGRANULARITY
+ self.mapping = _mmap.mmap(fd, length + self.delta, access=_mmap.ACCESS_READ, offset=start - self.delta)
+ self.view = memoryview(self.mapping)[self.delta:self.delta + length]
+ def __buffer__(self, flags): return self.view
+ def __len__(self): return self.length
+ def __getitem__(self, key):
+ value = self.view[key]
+ return value.tobytes() if isinstance(key, slice) else value
+ def __contains__(self, value): return self.find(value) >= 0
+ def find(self, value, start=0, end=None):
+ a, b, _ = slice(start, end).indices(self.length)
+ found = self.mapping.find(value, self.delta + a, self.delta + b)
+ return found - self.delta if found >= 0 else -1
+ def rfind(self, value, start=0, end=None):
+ a, b, _ = slice(start, end).indices(self.length)
+ found = self.mapping.rfind(value, self.delta + a, self.delta + b)
+ return found - self.delta if found >= 0 else -1
+ def index(self, value, start=0, end=None):
+ found = self.find(value, start, end)
+ if found < 0: raise ValueError('subsection not found')
+ return found
+ def size(self): return self.length
+ def tell(self): return self.pos
+ def seek(self, offset, whence=0):
+ pos = offset + (self.pos if whence == 1 else self.length if whence == 2 else 0)
+ if whence not in (0, 1, 2) or not 0 <= pos <= self.length: raise ValueError('invalid mmap seek')
+ self.pos = pos
+ def read(self, size=-1):
+ end = self.length if size < 0 else min(self.length, self.pos + size)
+ data = self[self.pos:end]; self.pos = end; return data
+ def close(self): self.view.release(); self.mapping.close()
+ def __enter__(self): return self
+ def __exit__(self, *args): self.close()
+
+
+class _Mmap:
+ @staticmethod
+ def mmap(fd, length, *args, **kwargs):
+ if fd not in _fd_ranges: return _mmap.mmap(fd, length, *args, **kwargs)
+ if sys.version_info < (3, 12): raise RuntimeError('RomFS image archive scans require Python 3.12 or newer')
+ if args or kwargs.get('access', _mmap.ACCESS_READ) != _mmap.ACCESS_READ: raise ValueError('RomFS mappings are read-only')
+ start, size = _fd_ranges[fd]; offset = kwargs.get('offset', 0)
+ if offset < 0 or offset > size or (length and length > size - offset): raise ValueError('mapping exceeds RomFS file')
+ return _Map(fd, start + offset, length or size - offset)
+ def __getattr__(self, name): return getattr(_mmap, name)
+mmap = _Mmap()
+
+
+if __name__ == '__main__':
+ try:
+ root = Path(sys.argv[1]); marker = sys.argv[2] if len(sys.argv) > 2 else ''
+ if not root.is_dir() or not (root / marker).exists(): raise FileNotFoundError(f'missing RomFS marker {marker!r} in {root}')
+ except (OSError, ValueError, IndexError, struct.error) as error: sys.exit(f'[RED] {error}')
diff --git a/dm/tools/romfs_image.py b/dm/tools/romfs_image.py
new file mode 100644
index 00000000..dd406041
--- /dev/null
+++ b/dm/tools/romfs_image.py
@@ -0,0 +1,129 @@
+#!/usr/bin/env python3
+# Pack an extracted RomFS folder into one image file the host reads in place of the folder (hle_fs.c, "RomFS image"): DM_ROMFS may name the image instead of a folder.
+# One file instead of hundreds of thousands copies to an iPhone at full speed (Tears of the Kingdom's 304,000 files ran the phone's file service out of open files), and the host
+# keeps one descriptor open for the whole RomFS.
+# Layout (little-endian):
+# header 32 bytes: magic "DMROMFS1", u64 index offset, u64 index size, u64 entry count
+# data each file's bytes, one after another
+# index entry count entries of 24 bytes: u64 a, u64 b, u32 name offset, u16 name length, u8 type (0 directory, 1 file), u8 0
+# a directory: a = its first child's entry, b = its number of children; a file: a = data offset in the image, b = size
+# then the names, one pool. Entry 0 is the root (empty name). Each directory's children are consecutive entries sorted by name (bytes), so a lookup is a
+# binary search per path component; directories are numbered breadth-first.
+# The index comes last, so a copy cut off partway has no valid index (the header points past the end of the file) and the host refuses it.
+# Names are the guest names: a host name chosen on a case collision (.dm-case-N) is replaced by the one in its xattr, as hle_fs.c's guest_name does.
+# Usage: romfs_image.py [--reuse] <RomFS folder> <out image> (written to <out>.part, renamed at the end)
+# --reuse checks the source tree's names and file metadata, the packer's version and the image's identity before keeping a previous image.
+import argparse, hashlib, json, os, struct, subprocess
+from pathlib import Path
+
+MAGIC = b'DMROMFS1'
+HEAD = struct.Struct('<8sQQQ')
+ENT = struct.Struct('<QQIHBB')
+GUEST_NAME = 'org.d2rmobile.guest-name'
+
+
+def guest(parent, name):
+ if not name.startswith('.dm-case-'): return name
+ r = subprocess.run(['xattr', '-p', GUEST_NAME, os.path.join(parent, name)], capture_output=True, text=True)
+ return r.stdout.rstrip('\n') if r.returncode == 0 else name
+
+
+def children(path):
+ out = []
+ with os.scandir(path) as it:
+ for e in it:
+ out.append((guest(path, e.name).encode(), e.path, e.is_dir(follow_symlinks=True)))
+ out.sort()
+ return out
+
+
+def entries(src):
+ ents = [[b'', src, True, 0, 0]] # name, host path, is dir, a, b
+ i = 0
+ while i < len(ents): # breadth-first: each directory's children land as one consecutive run
+ name, path, isdir, _, _ = ents[i]
+ if isdir:
+ kids = children(path)
+ ents[i][3], ents[i][4] = len(ents), len(kids)
+ ents.extend([n, p, d, 0, 0] for n, p, d in kids)
+ i += 1
+ return ents
+
+
+def file_identity(path):
+ s = os.stat(path)
+ return [s.st_dev, s.st_ino, s.st_size, s.st_mtime_ns, s.st_ctime_ns]
+
+
+def source_digest(src, ents):
+ h = hashlib.sha256(Path(__file__).read_bytes())
+ h.update(os.fsencode(os.path.realpath(src)) + b'\0')
+ for name, path, isdir, _, _ in ents:
+ h.update(struct.pack('<I?', len(name), isdir)); h.update(name)
+ h.update(json.dumps(file_identity(path)).encode() + b'\0')
+ return h.hexdigest()
+
+
+def pack(src, dst, reuse=False):
+ src, dst = os.fspath(src), os.fspath(dst)
+ ents = entries(src)
+ digest = source_digest(src, ents)
+ stamp = dst + '.inputs.json'
+ if reuse:
+ try:
+ cached = json.loads(Path(stamp).read_text())
+ if cached == {'source': digest, 'image': file_identity(dst)}: return len(ents)
+ except (OSError, ValueError): pass
+ part = dst + '.part'
+ with open(part, 'wb') as out:
+ out.write(b'\0' * HEAD.size)
+ off = HEAD.size
+ for e in ents:
+ if e[2]: continue
+ with open(e[1], 'rb') as f:
+ n = 0
+ while True:
+ b = f.read(8 << 20)
+ if not b: break
+ out.write(b); n += len(b)
+ e[3], e[4] = off, n; off += n
+ pool, idx = bytearray(), bytearray()
+ for name, _, isdir, a, b in ents:
+ idx += ENT.pack(a, b, len(pool), len(name), 0 if isdir else 1, 0); pool += name
+ out.write(idx); out.write(pool)
+ out.seek(0); out.write(HEAD.pack(MAGIC, off, len(idx) + len(pool), len(ents)))
+ # A changing source must not publish a mixed image or a reuse stamp for stale data.
+ if source_digest(src, entries(src)) != digest:
+ os.unlink(part)
+ raise RuntimeError('RomFS changed while packing; run the packer again when its files are stable')
+ os.replace(part, dst)
+ Path(stamp + '.part').write_text(json.dumps({'source': digest, 'image': file_identity(dst)}))
+ os.replace(stamp + '.part', stamp)
+ return len(ents)
+
+
+def read_index(img): # for tests and checks: {guest path: (is dir, offset, size)}
+ with open(img, 'rb') as f:
+ magic, ioff, isz, n = HEAD.unpack(f.read(HEAD.size))
+ assert magic == MAGIC
+ f.seek(ioff); raw = f.read(isz)
+ pool = raw[n * ENT.size:]
+ e = [ENT.unpack_from(raw, k * ENT.size) for k in range(n)]
+ out, todo = {}, [(0, '')]
+ while todo:
+ k, path = todo.pop()
+ a, b, no, nl, t, _ = e[k]
+ if t == 0:
+ if path: out[path] = (True, 0, 0)
+ todo.extend((c, (path + '/' if path else '') + pool[e[c][2]:e[c][2] + e[c][3]].decode()) for c in range(a, a + b))
+ else: out[path] = (False, a, b)
+ return out
+
+
+if __name__ == '__main__':
+ ap = argparse.ArgumentParser(description='Pack a RomFS folder into an indexed image')
+ ap.add_argument('--reuse', action='store_true', help='keep the image only while its source tree, packer and image are unchanged')
+ ap.add_argument('source'); ap.add_argument('image')
+ args = ap.parse_args()
+ n = pack(args.source, args.image, reuse=args.reuse)
+ print(f'{args.image}: {n} entries, {os.path.getsize(args.image)} bytes')
diff --git a/dm/tools/tests/test_nsp_incremental.py b/dm/tools/tests/test_nsp_incremental.py
index 26ed6f10..eeecc87c 100644
--- a/dm/tools/tests/test_nsp_incremental.py
+++ b/dm/tools/tests/test_nsp_incremental.py
@@ -274,13 +274,13 @@ class SplitShaders(Base):
for f in ('dm/gfx/tools/shader_split.py', 'dm/gfx/tools/dmsh_chain.lock', 'dm/games/game.py', 'dm/ios/tools/ios_metal.py'):
p = self.repo / f; p.parent.mkdir(parents=True, exist_ok=True); p.write_text('v1')
self.pkg = self.tmp / 'work/shader/pkg'; self.logs = self.tmp / 'logs'; self.logs.mkdir()
- self.splits, self.rows = 0, 'derived'
+ self.splits, self.rows, self.log = 0, 'derived', 'shaders: 3 (3 vertex)\n'
cm = mock.patch.object(nsp, 'run', self.split); cm.__enter__(); self.addCleanup(cm.__exit__, None, None, None)
def split(self, cmd, log, env=None, cwd=None, on_line=None): # shader_split.py: the package and the four tables, deterministic for the same rows
self.splits += 1; self.last_cmd = cmd; out = Path(cmd[4]); out.mkdir(parents=True); (out / 'main.bin').write_bytes(self.rows.encode())
for n, t in zip(self.NAMES, cmd[5:]): Path(t).write_text(self.table(n))
- Path(log).write_text('shaders: 3 (3 vertex)\n')
+ Path(log).write_text(self.log)
def table(self, n): return self.tables[n] if hasattr(self, 'tables') else f'# split header\n{n}\t{self.rows}\n'
@@ -409,6 +409,16 @@ class SplitShaders(Base):
self.assertEqual(g.table('shader_map.tsv').read_text(), self.table('shader_map.tsv'))
self.go(g); self.assertEqual(self.splits, 2)
+ def test_unreadable_files_are_reported(self): # the split leaves out a file no reader reads and goes on: a provisional build says so and packs, a registered profile stops
+ self.log = '[RED] 2 file(s) could not be read, their shaders are left out (first: /a.dict: not in the layout)\nshaders: 3 (3 vertex)\n'
+ g, said = self.own(), []
+ with mock.patch.object(nsp, 'say', said.append): self.go(g)
+ self.assertEqual(len([m for m in said if m.startswith('[RED] 2 file(s) could not be read')]), 1)
+ self.go(g); self.assertEqual(self.splits, 1)
+ self.assertIn('2 file(s) unreadable', nsp.PROG.end.call_args[0][0]) # the reused split still names them
+ for n in self.NAMES[:3]: (self.src / n).write_text(self.table(n))
+ with self.assertRaisesRegex(nsp.BuildError, r'^2 file\(s\) could not be read'): self.go(game.Game(self.src), own=False)
+
def test_mode_is_in_the_key(self): # the same files split as an own profile, then checked against them as a registered one
g = self.own(); self.go(g)
self.assertEqual(self.go(g, own=False), nsp.package_key(self.pkg)); self.assertEqual(self.splits, 2)
diff --git a/dm/tools/tests/test_nsp_mac_app.py b/dm/tools/tests/test_nsp_mac_app.py
index bbc3375f..037cda2e 100644
--- a/dm/tools/tests/test_nsp_mac_app.py
+++ b/dm/tools/tests/test_nsp_mac_app.py
@@ -92,7 +92,7 @@ class PackReuse(unittest.TestCase):
self.tmp = Path(tempfile.mkdtemp(prefix='pack-reuse-', dir=TEST_ROOT)).resolve()
self.addCleanup(shutil.rmtree, self.tmp)
t = self.tmp
- for d in ('patched', 'romfs/empty', 'msl', 'profile', 'font', 'aoc/1', 'pso', 'bin', 'sdk', 'source'):
+ for d in ('patched', 'romfs/empty', 'msl', 'profile', 'font', 'aoc/1', 'pso', 'bin', 'sdk', 'source', 'host', 'tools'):
(t / d).mkdir(parents=True)
files = {
'dmhost': b'host', 'patched/main.patched.bin': b'code', 'patched/main.fixups.tsv': b'fixups',
@@ -101,6 +101,7 @@ class PackReuse(unittest.TestCase):
'font/nintendo_ext.ttf': b'font', 'aoc/1/data': b'dlc', 'pso/gpu.mtl4a': b'archive',
'pso/prebuilt.tsv': b'prebuilt', 'pso/rest_pairs.tsv': b'rest', 'pso/archive.tsv': b'index',
'env.txt': b'DM_TEST=1', 'split.tsv': b'split', 'icon.jpg': b'jpeg', 'source/launcher.c': b'launcher',
+ 'host/romfs_image.h': b'validator', 'tools/romfs.py': b'reader',
}
for n in pack_app.TABLES: files['profile/' + n] = n.encode()
for n, content in files.items(): (t / n).write_bytes(content)
@@ -195,6 +196,17 @@ class PackReuse(unittest.TestCase):
p.with_name('added').rename(p.with_name('renamed')); self.assert_repacked()
(self.tmp / 'romfs/new-empty').mkdir(); self.assert_repacked()
+ def test_image_is_copied_once_and_its_changes_invalidate_reuse(self):
+ import romfs_image
+ source = self.tmp / 'romfs'; image = self.tmp / 'RomFS.img'
+ romfs_image.pack(source, image); self.args.romfs = str(image)
+ self.pack(); self.assert_reused()
+ resources = Path(self.args.out) / 'Contents/Resources'
+ self.assertEqual((resources / 'romfs.img').read_bytes(), image.read_bytes())
+ self.assertFalse((resources / 'romfs').exists())
+ (source / 'marker').write_text('new bytes'); romfs_image.pack(source, image)
+ self.assert_repacked()
+
def test_all_metadata_sign_identity_and_selected_paths_invalidate(self):
self.pack()
for name, value in [('name', 'New Game'), ('version', '2.0'), ('bundle_id', 'org.test.new'), ('category', 'public.app-category.action-games'),
diff --git a/dm/tools/tests/test_nsp_space.py b/dm/tools/tests/test_nsp_space.py
new file mode 100644
index 00000000..f1cb5c15
--- /dev/null
+++ b/dm/tools/tests/test_nsp_space.py
@@ -0,0 +1,41 @@
+"""NSP script: the free-space check's estimate of the extraction (extract_bytes). Two NSPs of the same size both count (the sizes were once collected in a set, PR #277);
+with clones the base game counts once, without them once per version. No game files, keys or Xcode needed (temporary files only)."""
+import importlib.util
+from pathlib import Path
+import shutil
+import tempfile
+import unittest
+
+REPO = Path(__file__).resolve().parents[3]
+spec = importlib.util.spec_from_file_location('build_ipa_from_nsp', REPO / 'scripts/build_ipa_from_nsp.py')
+assert spec is not None and spec.loader is not None
+nsp = importlib.util.module_from_spec(spec); spec.loader.exec_module(nsp)
+
+
+class Space(unittest.TestCase):
+ def setUp(self):
+ self.tmp = Path(tempfile.mkdtemp()); self.addCleanup(shutil.rmtree, self.tmp)
+
+ def nsp(self, name, size):
+ p = self.tmp / name; p.write_bytes(bytes(size)); return p
+
+ def test_same_size_nsps_both_count(self):
+ base, upd = self.nsp('base.nsp', 4), self.nsp('update.nsp', 4)
+ for clones in (True, False): self.assertEqual(nsp.extract_bytes({'v0': (base, None), 'v1': (base, upd)}, clones), 12 - 4 * clones)
+ self.assertEqual(nsp.extract_bytes({'v1': (base, upd)}, True), 8)
+
+ def test_base_once_with_clones(self):
+ base, u1, u2 = self.nsp('base.nsp', 100), self.nsp('u1.nsp', 5), self.nsp('u2.nsp', 6)
+ self.assertEqual(nsp.extract_bytes({'v0': (base, None), 'v1': (base, u1), 'v2': (base, u2)}, True), 111)
+
+ def test_base_per_version_without_clones(self):
+ base, u1, u2 = self.nsp('base.nsp', 100), self.nsp('u1.nsp', 5), self.nsp('u2.nsp', 6)
+ self.assertEqual(nsp.extract_bytes({'v0': (base, None), 'v1': (base, u1), 'v2': (base, u2)}, False), 311)
+
+ def test_no_clone_source_without_v0(self): # clones need the base game extracted alone first
+ base, u1, u2 = self.nsp('base.nsp', 100), self.nsp('u1.nsp', 5), self.nsp('u2.nsp', 6)
+ self.assertEqual(nsp.extract_bytes({'v1': (base, u1), 'v2': (base, u2)}, True), 211)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/dm/tools/tests/test_romfs_image.py b/dm/tools/tests/test_romfs_image.py
new file mode 100644
index 00000000..52f1723a
--- /dev/null
+++ b/dm/tools/tests/test_romfs_image.py
@@ -0,0 +1,158 @@
+"""Packer/cache round trips and the index validator shared by host mounts and iOS startup; synthetic files only."""
+import importlib.util
+import os
+from pathlib import Path
+import shutil
+import shlex
+import struct
+import subprocess
+import tempfile
+import unittest
+from unittest.mock import patch
+
+REPO = Path(__file__).resolve().parents[3]
+spec = importlib.util.spec_from_file_location('romfs_image', REPO / 'dm/tools/romfs_image.py')
+assert spec is not None and spec.loader is not None
+image = importlib.util.module_from_spec(spec); spec.loader.exec_module(image)
+
+
+class Images(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.tools = tempfile.TemporaryDirectory()
+ cls.addClassCleanup(cls.tools.cleanup)
+ root = Path(cls.tools.name)
+ source = root / 'validate.c'
+ source.write_text('#include "romfs_image.h"\nint main(int argc, char **argv) {\n'
+ 'if (argc != 2) return 2; romfs_img *m = romfs_image_open(argv[1]);\n'
+ 'if (!m) return 1; romfs_image_close(m); return 0; }\n')
+ cls.validator = root / 'validate'
+ subprocess.run(['cc', '-std=gnu11', '-Wall', '-Wextra', '-Werror', '-I', str(REPO / 'dm/host'),
+ str(source), '-o', str(cls.validator)], check=True)
+
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory(); self.addCleanup(self.tmp.cleanup)
+ self.root = Path(self.tmp.name)
+ self.src = self.root / 'RomFS'; self.src.mkdir()
+ self.dst = self.root / 'romfs.img'
+
+ def valid(self):
+ return subprocess.run([str(self.validator), str(self.dst)]).returncode == 0
+
+ def content(self, name):
+ isdir, offset, size = image.read_index(self.dst)[name]
+ self.assertFalse(isdir)
+ with self.dst.open('rb') as f:
+ f.seek(offset); return f.read(size)
+
+ def test_empty_romfs_and_packed_files_use_the_host_validator(self):
+ image.pack(self.src, self.dst)
+ self.assertTrue(self.valid()); self.assertEqual(self.dst.stat().st_size, 56)
+ (self.src / 'data/empty').mkdir(parents=True)
+ (self.src / 'data/a').write_bytes(b'hello')
+ (self.src / 'data/z').write_bytes(b'')
+ image.pack(self.src, self.dst)
+ self.assertTrue(self.valid()); self.assertEqual(self.content('data/a'), b'hello')
+ self.assertEqual(self.content('data/z'), b'')
+ self.assertTrue(image.read_index(self.dst)['data/empty'][0])
+
+ def test_reuse_rebuilds_changed_added_removed_and_renamed_files(self):
+ (self.src / 'a').write_bytes(b'old')
+ image.pack(self.src, self.dst, reuse=True)
+ identity = image.file_identity(self.dst)
+ image.pack(self.src, self.dst, reuse=True)
+ self.assertEqual(image.file_identity(self.dst), identity)
+ # Same length and a restored mtime: ctime still invalidates the cached image.
+ times = (self.src / 'a').stat()
+ (self.src / 'a').write_bytes(b'new')
+ os.utime(self.src / 'a', ns=(times.st_atime_ns, times.st_mtime_ns))
+ image.pack(self.src, self.dst, reuse=True)
+ self.assertEqual(self.content('a'), b'new')
+ (self.src / 'added').write_bytes(b'added')
+ image.pack(self.src, self.dst, reuse=True); self.assertEqual(self.content('added'), b'added')
+ (self.src / 'added').rename(self.src / 'renamed'); (self.src / 'a').unlink()
+ image.pack(self.src, self.dst, reuse=True)
+ self.assertEqual(set(image.read_index(self.dst)), {'renamed'})
+
+ def test_changed_image_and_forced_repack_are_not_reused(self):
+ image.pack(self.src, self.dst, reuse=True)
+ self.dst.write_bytes(image.HEAD.pack(image.MAGIC, 32, 0, 0))
+ image.pack(self.src, self.dst, reuse=True); self.assertTrue(self.valid())
+ identity = image.file_identity(self.dst)
+ image.pack(self.src, self.dst)
+ self.assertNotEqual(image.file_identity(self.dst), identity)
+
+ def test_changed_source_during_pack_preserves_previous_image(self):
+ (self.src / 'a').write_bytes(b'old'); image.pack(self.src, self.dst)
+ original = self.dst.read_bytes()
+ scan = image.entries
+ calls = 0
+ def changed(src):
+ nonlocal calls
+ calls += 1
+ if calls == 2: (self.src / 'a').write_bytes(b'changed during packing')
+ return scan(src)
+ with patch.object(image, 'entries', side_effect=changed), self.assertRaisesRegex(RuntimeError, 'changed while packing'):
+ image.pack(self.src, self.dst)
+ self.assertEqual(self.dst.read_bytes(), original)
+ self.assertFalse(Path(str(self.dst) + '.part').exists())
+
+ def test_push_helper_refreshes_cache_and_propagates_copy_failure(self):
+ resources = self.root / 'resources.env'
+ resources.write_text('DM_RESOURCE_ROMFS=' + shlex.quote(str(self.src)) + '\n')
+ bin_dir = self.root / 'bin'; bin_dir.mkdir()
+ xcrun = bin_dir / 'xcrun'
+ xcrun.write_text('#!/bin/sh\nprintf "%s\\n" "$@" > "$ROMFS_PUSH_ARGS"\nexit "${ROMFS_PUSH_RC:-0}"\n')
+ xcrun.chmod(0o755)
+ args_file = self.root / 'copy-args'
+ env = dict(os.environ, PATH=str(bin_dir) + os.pathsep + os.environ['PATH'], ROMFS_PUSH_ARGS=str(args_file))
+ cmd = ['bash', str(REPO / 'scripts/push_romfs.sh'), 'fixture-device', 'fixture.bundle', str(resources)]
+ (self.src / 'a').write_bytes(b'old')
+ def push(*args): return subprocess.run(cmd + list(args), env=env, capture_output=True, text=True)
+ self.assertEqual(push().returncode, 0)
+ self.dst = Path(str(self.src) + '.img')
+ self.assertEqual(self.content('a'), b'old')
+ (self.src / 'a').write_bytes(b'new')
+ self.assertEqual(push().returncode, 0); self.assertEqual(self.content('a'), b'new')
+ identity = image.file_identity(self.dst)
+ result = push('--repack'); self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertNotEqual(image.file_identity(self.dst), identity)
+ self.assertIn('Documents/romfs.img', args_file.read_text())
+ env['ROMFS_PUSH_RC'] = '7'; result = push()
+ self.assertEqual(result.returncode, 7); self.assertNotIn('game files on the phone', result.stdout)
+
+ def test_case_collision_guest_names(self):
+ if not shutil.which('xattr'): self.skipTest('macOS xattr tool required')
+ (self.src / 'a').write_bytes(b'lower')
+ alias = self.src / '.dm-case-1'; alias.write_bytes(b'upper')
+ subprocess.run(['xattr', '-w', image.GUEST_NAME, 'A', str(alias)], check=True)
+ image.pack(self.src, self.dst)
+ self.assertTrue(self.valid()); self.assertEqual(self.content('A'), b'upper')
+ self.assertEqual(self.content('a'), b'lower')
+
+ def test_size_consistent_invalid_index_is_rejected(self):
+ for raw in (image.HEAD.pack(image.MAGIC, 32, 0, 0),
+ image.HEAD.pack(image.MAGIC, 32, 24, 1) + image.ENT.pack(1, 0, 0, 0, 1, 0)):
+ with self.subTest(raw=raw):
+ self.dst.write_bytes(raw); self.assertFalse(self.valid())
+ (self.src / 'a').write_bytes(b'content'); (self.src / 'b').write_bytes(b'other')
+ image.pack(self.src, self.dst); complete = self.dst.read_bytes()
+ _, index, _, _ = image.HEAD.unpack_from(complete)
+ mutations = {
+ 'truncated': complete[:-1], 'trailing bytes': complete + b'x',
+ 'root cycle': (index, '<Q', 0), 'missing child': (index + 8, '<Q', 1),
+ 'bad name offset': (index + 24 + 16, '<I', 0xffffffff),
+ 'file in header': (index + 24, '<Q', 0), 'file into index': (index + 24 + 8, '<Q', index),
+ 'duplicate children': (index + 48 + 16, '<I', 0),
+ 'unsorted children': complete[:-2] + b'ba', 'path separator': complete[:-2] + b'a/',
+ }
+ for name, change in mutations.items():
+ with self.subTest(name=name):
+ raw = bytearray(complete)
+ if isinstance(change, tuple):
+ off, fmt, value = change; struct.pack_into(fmt, raw, off, value)
+ else: raw = change
+ self.dst.write_bytes(raw); self.assertFalse(self.valid())
+
+
+if __name__ == '__main__': unittest.main()
diff --git a/dm/tools/tests/test_romfs_read.py b/dm/tools/tests/test_romfs_read.py
new file mode 100644
index 00000000..7000b3e5
--- /dev/null
+++ b/dm/tools/tests/test_romfs_read.py
@@ -0,0 +1,119 @@
+"""Direct image extraction, bounded archive reads and the build tools' image inputs."""
+import hashlib
+import os
+from pathlib import Path
+import re
+import shutil
+import struct
+import subprocess
+import sys
+import tempfile
+import unittest
+from unittest.mock import patch
+import zipfile
+
+REPO = Path(__file__).resolve().parents[3]
+sys.path[:0] = [str(REPO / 'dm/tools'), str(REPO / 'dm/gfx/tools')]
+import romfs
+import romfs_image
+
+
+class ReadImage(unittest.TestCase):
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory(); self.addCleanup(self.tmp.cleanup)
+ self.root = Path(self.tmp.name)
+ self.src = self.root / 'files'; self.src.mkdir()
+ (self.src / 'data/empty').mkdir(parents=True)
+ (self.src / 'a').write_bytes(b'prefix!')
+ self.data = b'\x03\x02\x23\x07' + b'ABC\0' * 20000
+ (self.src / 'data/archive').write_bytes(self.data)
+ (self.src / 'data/zero').touch()
+ (self.src / 'data/test.vert').write_text('#version 320 es\nvoid main() {}')
+ with zipfile.ZipFile(self.src / 'data/game.zip', 'w') as z: z.writestr('member', b'archive member')
+ self.image = self.root / 'RomFS.img'; romfs_image.pack(self.src, self.image)
+ self.virtual = romfs.Path(self.image)
+
+ def test_metadata_paths_and_normal_output_paths(self):
+ self.assertTrue(self.virtual.is_dir()); self.assertFalse(self.virtual.is_file())
+ self.assertEqual((self.virtual / 'data/archive').read_bytes(), self.data)
+ self.assertEqual((self.virtual / 'data/test.vert').read_text(), '#version 320 es\nvoid main() {}')
+ actual = sorted((p.relative_to(self.src).as_posix(), p.is_dir(), p.stat().st_size if p.is_file() else 0) for p in self.src.rglob('*'))
+ virtual = sorted((p.relative_to(self.virtual).as_posix(), p.is_dir(), p.stat().st_size if p.is_file() else 0) for p in self.virtual.rglob('*'))
+ self.assertEqual(virtual, actual)
+ self.assertFalse((self.virtual / 'missing').exists())
+ with self.assertRaises(FileNotFoundError): (self.virtual / 'missing').read_bytes()
+ with self.assertRaises(OSError): (self.virtual / 'data/archive').open('wb')
+ with romfs.open(self.root / 'output', 'wb') as f: f.write(b'normal output')
+ self.assertEqual((self.root / 'output').read_bytes(), b'normal output')
+
+ def test_seek_read_and_mmap_cannot_cross_an_entry_boundary(self):
+ with romfs.open(self.virtual / 'data/archive', 'rb') as f:
+ f.seek(-5, 2); self.assertEqual(f.read(100), self.data[-5:])
+ f.seek(len(self.data) + 10); self.assertEqual(f.read(), b'')
+ with romfs.mmap.mmap(f.fileno(), 0, access=romfs.mmap.ACCESS_READ) as m:
+ self.assertEqual(len(m), len(self.data)); self.assertEqual(m[:], self.data)
+ self.assertEqual(struct.unpack_from('<I', m)[0], 0x07230203)
+ found = re.search(b'ABC', m); assert found is not None; self.assertEqual(found.start(), 4)
+ self.assertEqual(hashlib.sha256(m).digest(), hashlib.sha256(self.data).digest())
+ self.assertEqual(m.find(b'ABC'), 4); self.assertEqual(m.rfind(b'ABC'), len(self.data) - 4)
+ self.assertEqual(m.find(b'archive member'), -1)
+ with romfs.open(self.virtual / 'data/zero', 'rb') as f: self.assertEqual(f.read(), b'')
+ with romfs.open(self.virtual / 'data/game.zip', 'rb') as f, zipfile.ZipFile(f) as z:
+ self.assertEqual(z.read('member'), b'archive member')
+
+ def test_build_scanners_discover_the_same_inputs_from_image_and_folder(self):
+ import gl_shaders
+ import vk_shaders
+ with patch.dict(os.environ, DM_GAME='010020D01AD24000'):
+ import shader_split
+ self.assertEqual(list(gl_shaders.sources([str(self.virtual)])), list(gl_shaders.sources([str(self.src)])))
+ self.assertEqual([Path(p).relative_to(self.virtual) for p in vk_shaders.spirv_files(str(self.virtual))],
+ [Path(p).relative_to(self.src) for p in vk_shaders.spirv_files(str(self.src))])
+ jobs, paths = shader_split.zip_jobs([(str(self.virtual / 'data/game.zip'), 'data/game.zip')])
+ self.assertEqual(paths, {str(self.virtual / 'data/game.zip')})
+ self.assertEqual(jobs[0][2][1], ('member',))
+ self.assertEqual(shader_split.scan_file(jobs[0])[1], {})
+ # Image replacement must invalidate the process's cached index.
+ (self.src / 'new').write_text('new entry'); romfs_image.pack(self.src, self.image)
+ self.assertEqual((self.virtual / 'new').read_text(), 'new entry')
+
+ def test_ipa_packer_keeps_image_as_one_file_and_reuses_it(self):
+ out = self.root / 'game.ipa'
+ cmd = [sys.executable, str(REPO / 'dm/ios/tools/pack_ipa.py'), str(out), f'Payload/Game.app/romfs.img={self.image}']
+ for _ in range(2):
+ subprocess.run(cmd, check=True, capture_output=True)
+ with zipfile.ZipFile(out) as z:
+ self.assertEqual(z.namelist(), ['Payload/', 'Payload/Game.app/', 'Payload/Game.app/romfs.img'])
+ self.assertEqual(z.read('Payload/Game.app/romfs.img'), self.image.read_bytes())
+
+
[email protected](shutil.which('dotnet'), '.NET SDK required')
+class ExtractImage(unittest.TestCase):
+ def test_extractor_streams_populated_and_empty_filesystems(self):
+ # Exercise the actual LibHac writer without an NSP or keys, including empty
+ # directories and a file larger than its streaming buffer.
+ with tempfile.TemporaryDirectory() as temporary:
+ root = Path(temporary); src = root / 'files'; (src / 'data/empty').mkdir(parents=True)
+ data = b'\x00\x01\x02\xff' * (2 << 20)
+ (src / 'data/large').write_bytes(data); (src / 'zero').touch()
+ project = root / 'fixture.csproj'
+ project.write_text('<Project Sdk="Microsoft.NET.Sdk"><PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net10.0</TargetFramework>'
+ '<StartupObject>Fixture</StartupObject><AllowUnsafeBlocks>true</AllowUnsafeBlocks></PropertyGroup><ItemGroup>'
+ f'<Compile Include="{REPO}/dm/tools/nx_extract/Program.cs" Link="Extractor.cs" />'
+ '<PackageReference Include="LibHac" Version="0.19.0" /></ItemGroup></Project>')
+ (root / 'Fixture.cs').write_text('using System.Reflection; using LibHac.FsSystem; class Fixture { static void Main(string[] a) {'
+ 'var write = typeof(P).GetMethod("WriteImage", BindingFlags.NonPublic | BindingFlags.Static);'
+ 'using var fs = new LocalFileSystem(a[0]); write.Invoke(null, new object[]{fs, a[1]});'
+ 'write.Invoke(null, new object[]{null, a[2]}); }}')
+ image, empty = root / 'RomFS.img', root / 'empty.img'
+ result = subprocess.run(['dotnet', 'run', '--project', str(project), '--', str(src), str(image), str(empty)], capture_output=True, text=True, timeout=120)
+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
+ shutil.rmtree(src)
+ virtual = romfs.Path(image)
+ self.assertEqual((virtual / 'data/large').read_bytes(), data)
+ self.assertTrue((virtual / 'data/empty').is_dir()); self.assertEqual((virtual / 'zero').read_bytes(), b'')
+ self.assertEqual(list(romfs.Path(empty).iterdir()), [])
+ self.assertFalse((root / 'RomFS').exists()); self.assertFalse(Path(str(image) + '.part').exists())
+
+
+if __name__ == '__main__': unittest.main()
diff --git a/dm/tools/tests/test_split_unreadable.py b/dm/tools/tests/test_split_unreadable.py
new file mode 100644
index 00000000..6f76c1fc
--- /dev/null
+++ b/dm/tools/tests/test_split_unreadable.py
@@ -0,0 +1,80 @@
+"""shader_split: a file no reader can read is left out with a red line, and the split goes on (PR #282: one Next Level Games archive of a revision nlg_dict does not
+know ended a whole split with nothing written). nlg_dict checks its layout before reading it, so such an index is named, not an IndexError. No game files needed."""
+import contextlib
+import io
+import os
+import struct
+import subprocess
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+from unittest import mock
+
+REPO = Path(__file__).resolve().parents[3]
+sys.path.insert(0, str(REPO / 'dm/gfx/tools'))
+_had = os.environ.get('DM_GAME'); os.environ['DM_GAME'] = '01007BB017812000' # shader_split loads a profile at import; other tests expect no default game
+import shader_split as ss
+if _had is None: del os.environ['DM_GAME']
+else: os.environ['DM_GAME'] = _had
+
+
+def index(nchunk, nrec, recs=None, chunks=None, names=b'.data\0'): # nlg_dict's layout: header, 0x18-byte records, 0x10-byte chunks, names
+ d = ss.NLG_DICT + bytes([4, 1, 1, 0]) + struct.pack('<I', 0x1000) + bytes([nchunk, nrec, names.count(b'\0'), 0])
+ for r in (recs if recs is not None else [bytes(16)] * nrec): d += struct.pack('<IHH', 0, 0, 0) + r
+ for c in (chunks if chunks is not None else [(0, 0, 0, 0)] * nchunk): d += struct.pack('<3IHBB', *c[:3], 0, c[3], 0)
+ return d + names
+
+
+class NlgLayout(unittest.TestCase):
+ def test_known_layout_reads(self):
+ self.assertEqual(ss.nlg_dict(index(2, 1, [bytes([0, 1]) + bytes(14)]), '/a.dict'), (1, [(0, [0, 1] + [0] * 14)], [(0, 0, 0, 0), (0, 0, 0, 0)], ['.data']))
+
+ def test_other_layouts_are_named(self):
+ for name, d in (('cut short', index(5, 2)[:0x28]), ('header only', ss.NLG_DICT + bytes(4)),
+ ('section chunk out of range', index(2, 1, [bytes([0, 2]) + bytes(14)])), ('more records than chunks', index(1, 2))):
+ with self.subTest(name), self.assertRaisesRegex(SystemExit, r"^\[RED\] /a\.dict: the index .* is not in the layout of Luigi's Mansion 3's archives"):
+ ss.nlg_dict(d, '/a.dict')
+
+
+class ScanFile(unittest.TestCase):
+ def setUp(self):
+ self.tmp = Path(tempfile.mkdtemp()); self.addCleanup(lambda: __import__('shutil').rmtree(self.tmp))
+
+ def scan(self, path, rel):
+ out = io.StringIO()
+ with contextlib.redirect_stdout(out): r = ss.scan_file((str(path), rel))
+ return r, out.getvalue()
+
+ def test_red_line_of_a_reader(self):
+ p = self.tmp / 'a.dict'; p.write_bytes(index(5, 2)[:0x28])
+ (rel, keys, pairs, extra), out = self.scan(p, 'sub/a.dict')
+ self.assertEqual((rel, keys, pairs, extra[0]), ('sub/a.dict', {}, set(), 'unreadable'))
+ self.assertTrue(extra[1].startswith('/sub/a.dict: the index'))
+ self.assertEqual(out.count('/sub/a.dict'), 1); self.assertTrue(out.startswith('[RED] /sub/a.dict: the index') and out.endswith('(its shaders are left out)\n'))
+
+ def test_exception_of_a_reader(self):
+ p = self.tmp / 'a.dict'; p.write_bytes(index(1, 1))
+ with mock.patch.object(ss, 'nlg_shaders', side_effect=IndexError('list index out of range')):
+ (_, _, _, extra), out = self.scan(p, 'a.dict')
+ self.assertEqual(extra, ('unreadable', 'a.dict: IndexError: list index out of range'))
+ self.assertEqual(out, '[RED] a.dict: IndexError: list index out of range (its shaders are left out)\n')
+
+ def test_interrupt_is_not_taken(self):
+ p = self.tmp / 'a.dict'; p.write_bytes(index(1, 1))
+ with mock.patch.object(ss, 'nlg_shaders', side_effect=KeyboardInterrupt), self.assertRaises(KeyboardInterrupt): self.scan(p, 'a.dict')
+
+ def test_split_goes_on(self): # the whole split: the unreadable archive is reported once more at the end, the tables are written and the split exits 0
+ rom = self.tmp / 'RomFS'; (rom / 'sub').mkdir(parents=True)
+ (rom / 'sub/a.dict').write_bytes(index(5, 2)[:0x28]); (rom / 'sub/a.data').write_bytes(bytes(64)); (rom / 'b.bin').write_bytes(b'no shaders')
+ main = self.tmp / 'main'; main.write_bytes(bytes(0x100)) # an NSO header of three empty segments
+ out = [self.tmp / n for n in ('pkg', 'map.tsv', 'facts.tsv', 'pairs.tsv', 'pso.tsv')]
+ r = subprocess.run([sys.executable, REPO / 'dm/gfx/tools/shader_split.py', rom, main, *out], capture_output=True, text=True,
+ env=dict(os.environ, DM_GAME='01007BB017812000', J='2'))
+ self.assertEqual(r.returncode, 0, r.stderr)
+ self.assertIn('\n[RED] 1 file(s) could not be read, their shaders are left out (first: /sub/a.dict: the index', '\n' + r.stdout)
+ self.assertIn('shaders: 0 (', r.stdout)
+ for p in out: self.assertTrue(p.exists(), p)
+
+
+if __name__ == '__main__': unittest.main()
diff --git a/docs/agents/01-extract.md b/docs/agents/01-extract.md
index dd689dc6..138882cc 100644
--- a/docs/agents/01-extract.md
+++ b/docs/agents/01-extract.md
@@ -70,7 +70,7 @@ The work folder `$W` sits in the game's NSP folder, beside the NSP script's `<ti
- Game Freak's Trinity engine (Pokémon Legends: Z-A) keeps almost everything in one archive, `arc/data.trpfs` (4.4 GB, 13,181 packs, 238,546 files, 17.7 GB unpacked), indexed by `arc/data.trpfd`; both are FlatBuffers. The descriptor's root table holds the file hashes (u64, sorted), the pack names (`arc/<the first file's path without its slashes>.trpak`), one info table per file (its pack index) and one per pack (size, file count). The file system starts with `ONEPACK\0` and the u64 offset of its own root table: the pack name hashes and the pack offsets. The name hash is not a plain FNV-1a 64 of the descriptor's name, so a pack is named through its first file's hash. A pack is a table of file hashes and file tables `{1 compression i8, 2 level u8, 3 length u64, 4 data}`; compression 3 is Oodle (every file but 15,528 small stored ones), and every Oodle stream is Mermaid (header `8C 0A`, `CC 0A` for an uncompressed chunk). Oodle is linked into `main` and there is no Mermaid decoder with a licence fit for this repository, so the shader split runs the game's own `OodleLZ_Decompress` in the Mac host's tool mode (`dm/host/hle_oodle.c`, `DM_OODLE_SERVE=1`: requests on stdin, answers on stdout). The host finds it in `main` by the one function that references its name string (as for Unreal's archives), and calls it as the game does (`main+0x1a9b7bc` on 2.0.2: fuzz safe, no CRC check, thread phase 3). The shader split's full scan (every file decoded, 17.7 GB) takes 5 minutes with 12 workers on a 12-core Apple M6.
- The older KTGL of Fire Emblem: Three Houses uses a LINKDATA archive instead: `DATA0.bin` is an index of 32-byte entries `{u64 offset, u64 length, u64 stored length, u64 compressed}` into `DATA1.bin` (6.9 GB), and `patch1`–`patch4` hold loose overrides listed by `patchN/INFO0.bin` (0x120-byte entries ending in a `rom:/patchN/…` path). Its compressed entries and `*.gz` files are another chunked zlib: u32 chunk size (0x10000), u32 chunk count, u32 length, the stored length of each chunk, then the chunks at 0x80 alignment, each a u32 length + one zlib stream, or the plain bytes when the stored length equals the chunk's length (`kt_gz` in `shader_split.py`).
- **One archive of hashed names** (Super Smash Bros. Ultimate 13.0.5): the RomFS is `data.arc` (17.6 GB) and 14 NRRs. Its header (magic `0xABCDEF9876543210`) gives the offsets of the music, file and shared-file sections and of the file system table (one zstd frame of 50 MB); paths are Hash40s (CRC-32 of the path, its length in the top byte). A path leads to its current file through its info index, file info, info-to-data entry and file data, at file section + directory offset + 4 × its offset, zstd or stored (`dm/gfx/tools/smash_arc.py` documents the layout). The archive also keeps every earlier version of updated files, which no path leads to any more: 183,882 data blobs, 169,939 of them current (the 98 fighter NROs, 764 with their old versions, which the NRRs of older releases still list). A file's first bytes name its format: SSBH `HBSS` resources (`RDHS` shader databases, `XFUN` effect libraries, `LDOM` / `HSEM` / `LTAM` / `MINA` / `LEKS` models, meshes, materials, animations, skeletons), `EFFN` effects, `SARC` UI layouts, `BNTX`, `NUS3` sound and the NROs (`NRO0` at +0x10).
-- Next Level Games' engine (Luigi's Mansion 3) keeps everything but its Wwise banks in archives of its own: `<name>.dict` indexes `<name>.data` (`init`, `global`, `Hotel/<floor>`, … 98 of them). The `.dict` is 3,203 bytes in every archive: u32 magic `0xa9f32458`, u8 4, u8 1, u8 compressed, u8 0, u32 the largest stored chunk, u8 chunk count (120), u8 record count (52), u8 name count (3), u8 0; then the records (0x18 bytes: u32 hash, u16 the top-level entry count of its table, u16, and one chunk index for each of 16 sections), the chunks (0x10 bytes: u32 offset, length, stored length (one zlib stream; 0 in an archive stored as is), u16 alignment as log2, u8 file, u8 GPU memory) and the file names `.data`, `.debug`, `.nxpc`. Only `.data` ships: the 13 even records are the game's variants (languages), the odd ones point into `.nxpc`. Record v's resource table is chunk v: 12-byte entries {u32 kind (bit 31: a list of w1 entries from entry w2; bits 27–30 the section; bits 22–26 the alignment as log2), u32 length, u32 offset in the section}. The game reads an archive in `main+0x1ba00` (1.4.0).
+- Next Level Games' engine (Luigi's Mansion 3) keeps everything but its Wwise banks in archives of its own: `<name>.dict` indexes `<name>.data` (`init`, `global`, `Hotel/<floor>`, … 98 of them). The `.dict` is 3,203 bytes in every archive: u32 magic `0xa9f32458`, u8 4, u8 1, u8 compressed, u8 0, u32 the largest stored chunk, u8 chunk count (120), u8 record count (52), u8 name count (3), u8 0; then the records (0x18 bytes: u32 hash, u16 the top-level entry count of its table, u16, and one chunk index for each of 16 sections), the chunks (0x10 bytes: u32 offset, length, stored length (one zlib stream; 0 in an archive stored as is), u16 alignment as log2, u8 file, u8 GPU memory) and the file names `.data`, `.debug`, `.nxpc`. Only `.data` ships: the 13 even records are the game's variants (languages), the odd ones point into `.nxpc`. Record v's resource table is chunk v: 12-byte entries {u32 kind (bit 31: a list of w1 entries from entry w2; bits 27–30 the section; bits 22–26 the alignment as log2), u32 length, u32 offset in the section}. The game reads an archive in `main+0x1ba00` (1.4.0). `nlg_dict` checks this layout before reading; Mario Strikers: Battle League's archives are another revision it does not read yet ([A file no reader reads](../reference/shaders.md#a-file-no-reader-reads)).
- An update to that engine (Luigi's Mansion 3 1.4.0) leaves `.dict` and `.data` as they were and adds `<name>.patch`: u64 a bitmask of the records it patches, u32 offset, stored and inflated length of its body (one zlib stream: 16 u32 section offsets, 16 u16 alignments, then each section's new data), then 0xd0 bytes per patched record {u32 offset, stored length and entry count of its new resource table (one zlib stream), u16 its top-level entry count, u16, u32 the new length of each of 16 sections, 16 u32 end and 16 u32 start of the old data that is overwritten before it is read}. After loading a section the game walks the new table and packs that section's entries from its start at their alignment, each from the old section (an offset below its length) or from the body (the rest, counted from the old length), and writes the new offset into the entry (`main+0x1c8d0`, `main+0x1cbd0`); it does this in place, keeping a copy of the old data in [start, end). `shader_split.py` `nlg_patch_section` does the same. The base game's `init` has 5,149 shaders, 1.4.0's 5,317; 46 of the 103 the title draws exist only in the patched sections.
- PlatinumGames' engine (Bayonetta 3) keeps everything but its WebM movies in 72 PKZ archives in the RomFS root (14 GB; `root_000.pkz`, `core_000.pkz`, `pl_000.pkz`, `st1_000.pkz`, `sound_000.pkz` … `sound_017.pkz`, …). A PKZ is `pkzl`, u32 version 0x20000, u64 archive length, u32 file count, u32 entry table offset (0x20), u32 name table length, u32 alignment (0x1000), then one 0x20-byte entry per file: u32 name offset, u32 compression name offset (both into the name table that follows the entries), u64 length, u64 offset, u64 stored length. The compression is named per entry, `OodleKraken` or `None` here (11,760 and 5,159 entries); `main` knows `ZStandard` too (`main+0xcbdf80` maps the three names to 0xc9, 0x65 and 0). Inside are DAT archives: `DAT\0`, u32 file count, then the offsets of the file offset table (u32 each), the extension table (4 bytes each), the name table (u32 name length, then one name of that length each), the file length table (u32 each) and a name hash map. Their members are the engine's own formats (`.wmb` models, `.wtb` / `.wta` textures, `.bxm`, `.eff`, …) and, in `root_000.pkz`'s `shader*.dat` and `autoshadereff.dat`, its shader objects ([04](04-graphics.md)). There is no Kraken decoder fit for this repository, and this `main` reads its archives only through Oodle's streaming decoder (`main+0xcbc698` creates one, `main+0xcbc7f8` feeds it 256 KB at a time into a 10 MB window), so `OodleLZ_Decompress` was never linked in and its name string is not there: `hle_oodle.c` finds `OodleLZDecoder_MemorySizeNeeded`, `Create`, `Destroy` and `DecodeSome` instead (by the strings of Oodle's `oodlelzcompressors.cpp` and their order) and decodes each entry with them in `DM_OODLE_SERVE`. The shader split decodes every entry of every PKZ (8 workers, one Mac host each) in about 20 s; only `root_000.pkz` holds shaders.
- The same engine in its Wii U form (Bayonetta 2, SDK 3.6.0) keeps everything but its USM movies and Wwise sound in six CRI CPK archives in the RomFS root (`data000.cpk` … `data006.cpk`, there is no `data004.cpk`; 9.5 GB, 6,091 files). A CPK is `CPK `, u32 0xff, u32 the length of the @UTF table at +0x10 that names `TocOffset` and `ContentOffset`; at `TocOffset` comes `TOC `, 12 bytes and another @UTF table with one row per file: `DirName`, `FileName`, `FileSize` (stored), `ExtractSize`, `FileOffset` (relative to the smaller of `TocOffset` and `ContentOffset`). An @UTF table is big-endian: `@UTF`, u32 length, then from +8 u16 version, u16 rows offset, u32 strings offset, u32 data offset, u32 table name, u16 column count, u16 row width, u32 row count, and one flag byte (storage 0x10 zero, 0x30 constant, 0x50 per row; type in the low nibble) and a name offset per column. Vanillaware's CPKs (Unicorn Overlord) store their @UTF tables masked: each byte XOR the low byte of a 16-bit value that starts at 0x655f and is multiplied by 0x4115 after every byte (`cpk.py` `unmask`); the split reads their 7,744 files, 6.5 GB unpacked, in 38 s and finds no shader there, so Unicorn Overlord's tables are unchanged. 5,693 of the files (6.9 GB stored, 12 GB unpacked) are CRILAYLA: `CRILAYLA`, u32 size, u32 compressed length, the compressed bits, then the output's first 0x100 bytes stored; the bits are read from the end backwards and the output written from its end backwards (`dm/gfx/tools/cpk.py`, about 29 MB/s in Python with the bits read from a string). Inside are PlatinumGames DAT archives, as in Bayonetta 3; the shaders are BNSH files (`.vso` / `.pso` members of `shader.dat`, `shader2.dat` and `shadereff.dat` in `data000.cpk`), which the split finds by decoding every entry of every CPK (`shader_split.py` `cpk_jobs`, about 2.5 minutes with 12 workers). Bayonetta (SDK 3.6.0) has the same layout in nine CPKs (`data00.cpk` … `data03.cpk`, `data10.cpk` … `data14.cpk`, 4.25 GB), its shaders in `shader.dat` of `data00.cpk`; `cpk.py` reads them as they are.
diff --git a/docs/agents/03-bringup.md b/docs/agents/03-bringup.md
index 1988b290..cb67b6ab 100644
--- a/docs/agents/03-bringup.md
+++ b/docs/agents/03-bringup.md
@@ -21,7 +21,7 @@ $W/run/boot.sh <log name> [seconds] [VAR=value ...]
| `[longframe]` | A long frame, with submit / GPU / pipeline / upload breakdown |
| `memory up to frame N: resident … GPU allocated …` | Memory report (RSS, Metal allocated size). Printed when memory moves; steady growth here is a leak. A watchdog exits at 24 GB. Also: memory pools and how many are resident (pools join the residency set on first GPU use), finalized pool buffers still alive, the storage-sharing texture table, and on iOS `headroom to the system memory limit` (`os_proc_available_memory`, how far the app is from being killed for memory) |
| `CRASH sig=… pc=… lr=…` + registers + `bt:` + `stack scan` + thread dump | Crash report: see [05](05-debugging.md) |
-| `thread 0x10xx 'name' … waits:<state> addr=…` | Thread dump: what each guest thread waits on (`address` = address arbiter, `mutex` = mutex with holder, `condvar`, `sync object`, `running/not waiting` = running) |
+| `thread 0x10xx 'name' … waits:<state> addr=…` | Thread dump: what each guest thread waits on (`address` = address arbiter, `mutex` = mutex with holder, `condvar`, `sync object`, `running/not waiting` = running); a thread waiting in an SVC also gets a `guest stack:` line, the words on its guest stack that point into a module (its callers when the code keeps no frame pointers) and x19–x28 |
Useful switches: `DM_FS=1` (file opens, and not-found probes), `DM_SVC=1` (memory SVCs and other syscalls), `DM_THR=1` (thread SVCs), `DM_WATCH=<s>` (dump all threads after s seconds), `DM_WATCH_STALL=<s>` (dump when the frame loop stops progressing).
diff --git a/docs/agents/05-debugging.md b/docs/agents/05-debugging.md
index 002ba72b..74049c53 100644
--- a/docs/agents/05-debugging.md
+++ b/docs/agents/05-debugging.md
@@ -151,7 +151,7 @@ The phone runs an unsigned IPA the user sideloads; nothing is attached to a debu
- **Switches**: `DM_ENV_FILE=<file> dm/ios/tools/build_ipa.sh` bakes `KEY=VALUE` lines into the app (`dm/env.txt`); `Documents/env.txt` overrides them without a rebuild. Every applied switch is logged at boot (`boot: env KEY=VALUE (source file)`). The app's working directory is `Documents`, so relative output paths (`DM_NVN_SHOT=3600:shot_%d.png`, `DM_NVN_TEXDUMP`) land where the Files app can reach them.
- **Which build ran**: the first lines name the modules (`main: … patch_off …`), the shader map size (`shader map N entries`) and, for builds that have it, the build-ID gate line. Compare them with the build you sent before reading further; users sometimes send an old log. The save path (`fs mount save:`) shows the data folder, which changes when a sideloading tool gives a reinstall a new one.
-- **Reading the periodic lines**: `[longframe]` gives each long frame's submit / GPU / pipeline-compile / upload split; a burst of `new pipelines` in long frames after an install is first-use compilation (see "Prewarm lists" in [docs/development.md](../development.md)). In `display link up to tick N: …`, `empty ticks` (refreshes with no new frame) and `old frames dropped by merging` are totals since launch, not per window. `on-screen up to frame N` windows give dropped frames (a frame on screen longer than 1.5 × its own hold, so a frame-step hold of 2 vsyncs at 33.3 ms is not dropped; discarded presents count too), p99 frame time and the physical footprint; `memory up to frame N` gives resident and Metal-allocated memory. Memory that steps up at level loads and stays flat in between is not a leak.
+- **Reading the periodic lines**: `[longframe]` gives each long frame's submit / GPU / pipeline-compile / upload split; a burst of `new pipelines` in long frames after an install is first-use compilation (see "Prewarm lists" in [docs/development.md](../development.md)). In `display link up to tick N: …`, `empty ticks` (refreshes with no new frame) and `old frames dropped by merging` are totals since launch, not per window. Per frame, `DM_NVN_TSV` has the display-link tick that took it: `@link_target_ms` (same time base as `@pres_at_ms`, so their difference is how late the system showed the frame: 8.3 ms = one 120 Hz refresh), `@link_lead_ms` (the callback's lead before that target: about 50 ms in a window, 16 ms in fullscreen at frame latency 1), `@link_ticks` (callbacks since the previous frame's; above 1 = ticks without a new frame) and `@link_gap_ms` (the longest interval between them; 33 ms on a 60 Hz link = a refresh the link skipped). `on-screen up to frame N` windows give dropped frames (a frame on screen longer than 1.5 × its own hold, so a frame-step hold of 2 vsyncs at 33.3 ms is not dropped; discarded presents count too), p99 frame time and the physical footprint; `memory up to frame N` gives resident and Metal-allocated memory. Memory that steps up at level loads and stays flat in between is not a leak.
- **Power**: `power up to frame N` covers the window since the previous one, for the whole process: CPU energy in watts and per frame (`task_energy` from `TASK_POWER_INFO_V2`, CPU only; compare per frame when one build holds the frame rate better), CPU time (100% = one core) and the share on performance cores, wakeups per second, the thermal state (0 nominal … 3 critical; changes are also logged as `front end: thermal state → n`), and the two guest threads that yielded most with how many of those yields the back-off turned into sleeps (`DM_YIELD_BACKOFF`, see [docs/development.md](../development.md)), and its spin wait passes with the last loop head. A thread yielding hundreds of thousands of times per window with few back-off sleeps is a busy spin. A busy thread that never yields and is not in the list may poll in a loop the spin wait rule does not take: sample it and look at its loop. `residency set up to frame N` gives residency-set commits and their time, what was added by source line of `nvn_mtl.m` (count, MB), removals, how many draw passes began with a full barrier or without one (`DM_NVN_BARRIER=game`), and segment commits: a source line adding gigabytes per window is allocation churn. It ends with render-target traffic per frame: attachment bytes loaded and stored, passes that load and store everything, and the stores `DM_NVN_UNWRITTEN_DC` saved (the same counters as the TSV's `@rt_load_mb` / `@rt_store_mb`). `threads up to frame N` gives guest-thread CPU time in ms per second by Switch priority band (≤ 44, the main thread's level and above; 45–59; ≥ 60) and the three busiest threads with their priority; it shows what `DM_QOS_MAP` would move. On the Mac the same lines appear; energy readings vary by tens of percent between identical runs, so compare runs interleaved and over the same scene.
- **Screen recordings** from the user are useful for timing and visual symptoms; extract frames with `ffmpeg -ss <t> -i rec.mov -frames:v 1 out.png`.
diff --git a/docs/agents/symptoms.md b/docs/agents/symptoms.md
index 23fdf60e..3a10a9bb 100644
--- a/docs/agents/symptoms.md
+++ b/docs/agents/symptoms.md
@@ -6,7 +6,10 @@ One line per symptom in the [subsystem references](../reference/): what you see
- the first extraction stops with `nx_extract exit code 131` and `.NET location: Not found`, even though `dotnet` is on `PATH`. The shader translator can fail the same way. → [Homebrew .NET is on PATH but apphosts cannot find the runtime](../reference/packing.md#homebrew-net-is-on-path-but-apphosts-cannot-find-the-runtime)
- packing succeeds, but `unzip -t` or Python's `ZipFile.testzip()` reports a bad CRC for a large deflated file. → [A streamed file changes size and the IPA fails its CRC check](../reference/packing.md#a-streamed-file-changes-size-and-the-ipa-fails-its-crc-check)
+- `devicectl` copying a large RomFS folder fails with POSIX error 24 (`EMFILE`) or spends most of its time on small files; deleting an old folder during iOS startup hits the launch watchdog. A push after changing extracted files can also keep sending old assets if an image is reused solely because it exists. → [RomFS folder transfers fail or leave stale game files](../reference/packing.md#romfs-folder-transfers-fail-or-leave-stale-game-files)
+- reducing the iPhone transfer to one image still creates thousands of resource files on the Mac, and build scanners require the expanded folder. → [Building creates a full RomFS tree before packing its image](../reference/packing.md#building-creates-a-full-romfs-tree-before-packing-its-image)
- `decompress NSZ` stops immediately with `nsz: error: unrecognized arguments: --keys …`. → [NSZ decompression rejects `--keys`](../reference/packing.md#nsz-decompression-rejects---keys)
+- the extraction of a game whose base is an XCI that also carries its update (a "1G+1U" dump) stops with `[RED] nx_extract exit code -6`. `extract_v<version>.log` lists the update's build IDs even for the base game alone, then ends in an unhandled exception from the RomFS (`ResultFsNonRealDataVerificationFailed (2002-4604): Hash error!` from `RomFsFileSystem..ctor`, or `ArgumentException` / `InvalidOperationException` from the patch layers). → [A cartridge dump with its update on it extracts the update as the base game](../reference/packing.md#a-cartridge-dump-with-its-update-on-it-extracts-the-update-as-the-base-game)
## Rewriter
@@ -93,6 +96,7 @@ One line per symptom in the [subsystem references](../reference/): what you see
- a 30 Hz game thread runs at 27 Hz, and whatever it paces comes out slow (cutscenes at 36 ms per frame instead of 33.3; gameplay was fine at 60). → [Timer slack in guest sleeps (`sleep_precise`)](../reference/threads.md#timer-slack-in-guest-sleeps-sleep_precise)
- a guest thread keeps a core at 100% with billions of `SleepThread` calls. → [Sleeps under 20 µs take the yield path](../reference/threads.md#sleeps-under-20-µs-take-the-yield-path)
- a loading screen sits for a minute with the CPU nearly idle; one thread yields thousands of times a second, every yield a back-off sleep (the power line's top yielder, with as many back-off sleeps). → [Yields that make progress return at once (`thr_yield`)](../reference/threads.md#yields-that-make-progress-return-at-once-thr_yield)
+- one guest thread keeps a host core at 100% with about a billion yields a minute (`SVC 0xb` in `DM_HLECOUNT`), none of them a back-off sleep, while the game itself plays normally. → [A wait at two yields is not progress](../reference/threads.md#a-wait-at-two-yields-is-not-progress)
- a host helper thread aborts when signalling a destroyed `SystemEvent`; repeated `vi::GetDisplayVsyncEvent` calls double the event's tick rate. Rapid replacement can abort with `too many vsync events`, or a retired vsync worker can signal another service's event at reused storage. → [Service-event producers follow the binding lifetime](../reference/threads.md#service-event-producers-follow-the-binding-lifetime)
- the main thread waits forever on a job's done event at boot while every worker sleeps, two of them on one event (`main+0x1426c` waiting on `Job::m_doneEvent`); 4 of 6 Mac runs. → [One auto-clear event shared by a pool's workers](../reference/threads.md#one-auto-clear-event-shared-by-a-pools-workers)
- abort in `os::WaitSystemEvent` under `oe::PopNotificationMessage` (The Legend of Zelda: Link's Awakening); one guest thread at about 1000 ms/s on the iPhone only, the phone hot, CPU energy 5–7 W (Monster Hunter Rise's `MessageSuperviseThread`, priority 32, in the `[nvn] threads` lines). → [The oe notification event and its queue](../reference/threads.md#the-oe-notification-event-and-its-queue)
@@ -411,6 +415,7 @@ One line per symptom in the [subsystem references](../reference/): what you see
## Shaders
+- the shader split stops on one archive with a Python traceback (an `IndexError` or `struct.error` naming no file), or a reader's `[RED]` line about a format it does not know, and nothing is written; the NSP script loses the build at the split. → [A file no reader reads](../reference/shaders.md#a-file-no-reader-reads)
- `shader_split.py` finds 0 shaders in a RomFS of zstd files named `.zst`. → [Zstd files recognised by their magic](../reference/shaders.md#zstd-files-recognised-by-their-magic)
- the game asks for shaders the map does not have (`[RED] shader ... is not in the shader map`, hundreds of lines), and the split finds far fewer shaders than the game uses (121 against 27,288 on Kirby and the Forgotten Land). → [HAL's `.cmp` containers: a size-prefixed frame](../reference/shaders.md#hals-cmp-containers-a-size-prefixed-frame)
- a provisional split finds only a fraction of the shaders (3,126 of Pokémon Sword's 41,516). → [BNSH entries of GFPAK archives](../reference/shaders.md#bnsh-entries-of-gfpak-archives)
diff --git a/docs/development.md b/docs/development.md
index b478e7a8..88703bb1 100644
--- a/docs/development.md
+++ b/docs/development.md
@@ -139,7 +139,7 @@ In Spyder, open the script, fill in the settings at the top (`NSP_DIR`, `PROD_KE
What the script does:
1. It finds the game profile from the title ID (the `[title ID]` in the file names, or the NSP's ticket; the update by its `[vN]` tag). The update is optional: it packs the newest version in the folder (`-p` / `PACKAGE` picks another).
-2. It extracts the NSPs.
+2. It extracts ExeFS and streams the merged, integrity-checked RomFS directly into `<id>_build/extract/<version>/RomFS.img`. No RomFS folder or individual resource files are written. Shader scanners, profile discovery and NRO collection read bounded file ranges from that image through `dm/tools/romfs.py`; archive readers map only the archive's range. This requires Python 3.12 or newer. An old folder extraction is replaced atomically after the new extraction succeeds. Each DLC similarly becomes `aoc/<index>.img`.
3. It rewrites the code modules, checking each build ID against the profile. A version the profile does not register (the base game alone when the profile was brought up on an update, another update, or files whose build IDs differ), or one whose shader tables need a version that is not in the folder, is built from a profile derived from it in `<id>_build/profile/<id>/`: the profile's keys, that version's build row, and shader tables, chain header, `c1_full.tsv` and `cb_extent.tsv` made from that version's own files (as for a provisional profile, without the heap check). The rewriter's cuts and the host's fixes for a registered build do not reach a module of another build; the script says which modules those are. A title ID no profile has is first looked up by build: when its `main` (of the base game with its newest update, else of the base game alone, read from a code-only extraction) is a build a profile registers, a regional release of the same build (Advance Wars 1+2: Re-Boot Camp under `0100300012FFF000`, issue #114), it packs from a profile derived from that one, with the folder's title ID and `main.npdm`'s program ID (`same_build`, `game.py` `by_build`); only otherwise is it surveyed. A provisional profile (a game without one in `dm/games`) then gets `mem_used` from the rewritten modules, and, when the game has virtual address memory and sets a heap, a heap check: the Mac host is built into `<id>_build/tools/dmhost` and the game boots in it until its first heap request (a few seconds, log `<id>_build/logs/heap_check.log`), which sizes the heap region (see [dm/games/README.md](../dm/games/README.md), Adding a game).
4. For a game whose `main` holds GLSL sources and calls `glslcCompile` (Three Houses), it captures the shaders the game compiles at run time, which no game file holds. It builds the Mac host into `<id>_build/tools/dmhost` and boots the game in it, headless and silent, with `DM_GLSLC_CAPTURE` pointing at `<id>_build/extract/<version>/glslc_capture`. The save, temporary storage and log all stay in `<id>_build/`. It stops the game as soon as every capture file named in the profile's shader map is there (Three Houses: 9, about a second after launch), and gives up after 30 s. A folder that already holds them all is reused.
A Vulkan game without SPIR-V files in its RomFS (Super Mario Galaxy) gets the same kind of run: the game boots in the Mac host with `DM_VK_CAPTURE` pointing at `<id>_build/extract/<version>/vk_capture` until every SPIR-V key in the profile's `vk_capture.tsv` is there (Galaxy: 3,089, about 7 s after launch), and gives up after 120 s.
@@ -189,7 +189,7 @@ The Mac is the development host. To test or debug a game on the Mac, `--platform
It skips the iOS shaders, the Xcode project and the IPA. For Mario Kart 8 Deluxe that saves about 30,000 iOS shader compiles and the 12 GB IPA. It keeps the extracted files even with `--no-keep-extracted`, because the game runs from them. It needs a Mac with Apple silicon, and it cannot be combined with `--prepare-xcode`. The last line it prints is the command that runs the game, built from the run's own paths (step 5 of [Build by hand (Mac)](#build-by-hand-mac)), for example:
```
-cd "<NSP folder>/<id>_build/run" && DM_ROOT="<NSP folder>/<id>_build" DM_ROMFS="<NSP folder>/<id>_build/extract/<version>/RomFS" DM_SAVE="<NSP folder>/<id>_build/run/save" DM_TEMP="<NSP folder>/<id>_build/run/temp" DM_MSL_DIR="<NSP folder>/<id>_build/shader/cache" DM_FONT_DIR="<NSP folder>/<id>_build/font" DM_NVN_SHMAP="<repository>/dm/games/<id>/shader_map.tsv" DM_LANG=en-US DM_WINDOW=1 DM_AUDIO=1 "<NSP folder>/<id>_build/tools/dmhost" "<NSP folder>/<id>_build/patched_<version>"
+cd "<NSP folder>/<id>_build/run" && DM_ROOT="<NSP folder>/<id>_build" DM_ROMFS="<NSP folder>/<id>_build/extract/<version>/RomFS.img" DM_SAVE="<NSP folder>/<id>_build/run/save" DM_TEMP="<NSP folder>/<id>_build/run/temp" DM_MSL_DIR="<NSP folder>/<id>_build/shader/cache" DM_FONT_DIR="<NSP folder>/<id>_build/font" DM_NVN_SHMAP="<repository>/dm/games/<id>/shader_map.tsv" DM_LANG=en-US DM_WINDOW=1 DM_AUDIO=1 "<NSP folder>/<id>_build/tools/dmhost" "<NSP folder>/<id>_build/patched_<version>"
```
The save is in `<id>_build/run/save` and stays there from run to run. `DM_AOC_DIR` is added when the folder has DLC. `DM_NVN_SHMAP` is added for an NVN game; it names the profile's shader map, or the derived or provisional profile's. A Vulkan or GL game's `DM_MSL_DIR` is `<id>_build/shader`. The switches of `--env-file` are added to the command.
@@ -245,7 +245,7 @@ The bundle holds what the IPA holds, with the Mac's shader libraries:
Info.plist name, version, bundle ID, the profile's app_category; DMTitleID, DMRomfsMarker, DMLanguage and DMModuleFiles for the launcher
MacOS/nxnative the launcher (dm/mac/launcher.c, compiled by pack_app.py)
MacOS/dmhost the Mac host built for the profile
- Resources/romfs/ the packed version's RomFS
+ Resources/romfs.img the packed version's RomFS image
Resources/msl/b-<chain>/ the Mac shader libraries, reflection JSON and runtime TSV tables (vk/ or gl/ for a Vulkan or GL game)
Resources/aoc/<index>/ the DLC, when the folder has some
Resources/pso/ an NVN game's pipeline archive made offline for this Mac's GPU (<arch>.mtl4a, prebuilt.tsv; --gpu none leaves it out)
@@ -285,7 +285,7 @@ open "<NSP parent folder>/NxNative.xcworkspace"
3. Connect and trust your iPhone or iPad, enable **Developer Mode** on the device, and select it as the run destination. The iOS Simulator cannot run the game's code.
4. Select the game's scheme, named **Game name (title ID)**, and press **Run**. Its Run configuration is **Release**. Xcode manages provisioning, signs the app and installs it on your device.
-Each game has its own generated project at `<NSP folder>/<title ID>_build/xcode/DmIOS.xcodeproj`. Its **Copy game resources** target phase (`dm/ios/tools/stage_resources.sh`) runs before code signing: it syncs the RomFS, the iOS shader libraries and the add-on content named in the project's `Gen/resources.env` to `DmIOS.app/romfs`, `DmIOS.app/msl/<b-chain, vk or gl>` and `DmIOS.app/aoc`. The rewritten game code is embedded by `Gen/embed.S` at link time. No keys are copied to the device. The project links `Sources`, `tools` and the host sources to the checkout it was prepared from (relinked on each preparation), so code edits apply to every prepared game. The prepared shaders do not follow a chain change: when the profile's `dmsh_chain.h` names another chain than the prepared shader folder (after a pull, or `dmsh_chain.py --header`), the phase stops and asks to prepare the game again.
+Each game has its own generated project at `<NSP folder>/<title ID>_build/xcode/DmIOS.xcodeproj`. Its **Copy game resources** target phase (`dm/ios/tools/stage_resources.sh`) runs before code signing: it syncs the RomFS, the iOS shader libraries and the add-on content named in the project's `Gen/resources.env` to `DmIOS.app/romfs.img`, `DmIOS.app/msl/<b-chain, vk or gl>` and `DmIOS.app/aoc`. The rewritten game code is embedded by `Gen/embed.S` at link time. No keys are copied to the device. The project links `Sources`, `tools` and the host sources to the checkout it was prepared from (relinked on each preparation), so code edits apply to every prepared game. The prepared shaders do not follow a chain change: when the profile's `dmsh_chain.h` names another chain than the prepared shader folder (after a pull, or `dmsh_chain.py --header`), the phase stops and asks to prepare the game again.
The project asks for the Increased Memory Limit capability (`Gen/DmIOS.entitlements`; without it iOS closes the bigger games, see the README). `DM_ENTITLEMENTS=<plist>` when preparing uses another entitlements file, and an empty `DM_ENTITLEMENTS=` none, for an account that cannot provision it.
@@ -293,6 +293,15 @@ The first Xcode build copies the complete game, so allow free space on the game'
Each prepared game is a scheme in the shared workspace (by default `NxNative.xcworkspace` beside the NSP folder; `--xcode-workspace`, `XCODE_WORKSPACE` in Spyder, collects games from different folders in one). Give each game its own bundle ID (`--bundle-id`) to keep them installed together; keep it when updating an installed game, as another ID is a separate app with separate saves. The script rejects a bundle ID that another project in the workspace uses. Preparing a game again regenerates only its project and keeps its Release bundle ID and team, including changes made in Xcode; `--bundle-id` / `--team-id` (`BUNDLE_ID` / `TEAM_ID` in Spyder, or `DM_TEAM_ID`) override them. Other manual project edits are replaced; edit `dm/ios/project.yml` for shared changes. Prepare a game again after changing its game files, profile, shaders or the project template; switching games needs only the scheme menu.
+### Quick reinstalls
+
+A full install sends the whole app, about 11 GB for Animal Crossing: New Horizons (3 to 4 minutes). The game files can stay on the phone instead:
+
+1. Once per game, with an app built with image support installed: `scripts/push_romfs.sh <device UDID> <bundle ID> "<NSP folder>/<title ID>_build/xcode/Gen/resources.env"`. It validates and copies the extracted image directly to `Documents/romfs.img`. A legacy folder source is packed first; its `.inputs.json` stamp tracks source names and metadata, the packer and image identity, and `--repack` forces that legacy conversion again. The host reads file ranges through one descriptor, with `DM_ROMFS_OVERLAY` folders taking precedence. iOS startup and the host share the complete index validator: an invalid or interrupted image leaves the folder fallback intact. Only after validation is an old `Documents/romfs` moved aside and deleted in the background. Rerun the push after a failed transfer. The Mac also accepts `DM_ROMFS=<image>` (in `~/Library/Application Support/nxnative/<title ID>/env.txt`). See [RomFS images](reference/packing.md#romfs-folder-transfers-fail-or-leave-stale-game-files) for the format, failure modes and validation limits.
+2. Build with `DM_COPY_ROMFS=NO` (a build setting read by `stage_resources.sh`, for example `xcodebuild ... DM_COPY_ROMFS=NO`). The shaders, add-on content and pipeline archive still go into the app.
+
+PR #368 reports Animal Crossing's app shrinking from 11 GB to 1.2 GB, with reinstalls in 30 to 60 seconds. Deleting the app deletes its `Documents`, so push the game files again after a delete. The copy needs one `devicectl` transfer at a time.
+
The unsigned IPA build still uses the repository's `dm/ios/DmIOS.xcodeproj`, skips the resource phase (`DM_COPY_GAME_RESOURCES=NO`) and packs the resources straight from the drive as before.
## Port another game
@@ -320,20 +329,20 @@ To add a game:
```
G=010015100B514000; W="<NSP folder>/$G-work"; VER=v327680
-# 1. extract: the base game alone (update -), or an update layered over it (the last argument lets unchanged files become clones)
+# 1. extract: the base game alone (update -), or an update layered over it, directly into an image
dotnet build dm/tools/nx_extract -c Release -o $W/build/nx_extract
-$W/build/nx_extract/nx_extract <prod.keys> <base NSP> - $W/data/v0
-$W/build/nx_extract/nx_extract <prod.keys> <base NSP> <update NSP> $W/data/$VER $W/data/v0/RomFS
+$W/build/nx_extract/nx_extract <prod.keys> <base NSP> - $W/data/v0 --romfs-image
+$W/build/nx_extract/nx_extract <prod.keys> <base NSP> <update NSP> $W/data/$VER --romfs-image
# 2. rewrite the profile's code modules
for m in $(python3 dm/games/game.py $G modules); do python3 dm/tools/patch_nso.py $W/data/$VER/ExeFS/$m $W/build/patched_$VER $m; done
# 3. shaders: extract from every version in the profile's shader_versions (comma-separated, base first), then translate into <cache>/b-<chain version>/
-DM_GAME=$G python3 dm/gfx/tools/shader_split.py $W/data/v0/RomFS,$W/data/$VER/RomFS $W/data/v0/ExeFS/main,$W/data/$VER/ExeFS/main $W/shader/pkg dm/games/$G/shader_map.tsv dm/games/$G/shader_facts.tsv dm/games/$G/shader_pairs.tsv
+DM_GAME=$G python3 dm/gfx/tools/shader_split.py $W/data/v0/RomFS.img,$W/data/$VER/RomFS.img $W/data/v0/ExeFS/main,$W/data/$VER/ExeFS/main $W/shader/pkg dm/games/$G/shader_map.tsv dm/games/$G/shader_facts.tsv dm/games/$G/shader_pairs.tsv
DM_GAME=$G python3 dm/gfx/tools/dmsh_build.py $W/shader/pkg $W/build/cache/metal_shader_cache # also writes dm/games/$G/c1_full.tsv and cb_extent.tsv
# 4. the host, and the button-icon font for the Nintendo-extension shared font
make -C dm/host GAME=$G dmhost
python3 dm/tools/make_ext_font.py $W/build/font/nintendo_ext.ttf
# 5. run on the Mac
-DM_ROOT=$W DM_ROMFS=$W/data/$VER/RomFS DM_SAVE=$W/run/save DM_TEMP=$W/run/temp DM_MSL_DIR=$W/build/cache/metal_shader_cache DM_FONT_DIR=$W/build/font dm/host/dmhost $W/build/patched_$VER
+DM_ROOT=$W DM_ROMFS=$W/data/$VER/RomFS.img DM_SAVE=$W/run/save DM_TEMP=$W/run/temp DM_MSL_DIR=$W/build/cache/metal_shader_cache DM_FONT_DIR=$W/build/font dm/host/dmhost $W/build/patched_$VER
# 6. iOS shader libraries (about 15 min for Mario), then the IPA (default <NSP folder>/<the profile's ipa>)
IOSOUT=$W/build/ios/dmsh_b DM_GAME=$G python3 dm/gfx/tools/dmsh_build.py $W/shader/pkg $W/build/cache/metal_shader_cache
GAME=$G W=$W dm/ios/tools/build_ipa.sh [out.ipa]
@@ -343,9 +352,9 @@ Notes on these steps:
- `dmsh_build.py` stops when a tool differs from `dm/gfx/tools/dmsh_chain.lock`. To try another Metal compiler, run `DM_ALLOW_OTHER_METAL=1 dm/gfx/tools/own_compilers.py` with the same arguments and environment. It reports the actual compiler and keeps its cached libraries separate from the tested compiler's; the translator and SPIRV-Cross must still match.
- After a chain change, `python3 dm/gfx/tools/shader_regressions.py $W/build/cache/metal_shader_cache` lists the shaders that translated in the previous `b-*/` there and fail in the current one (exit status 1), as the NSP script does after its shader step.
- `dmsh_build.py` compiles each shader's Metal source through a cache keyed by that source, the compile flags and the compiler (`dm/gfx/tools/dmsh_mtlcache.py`, in `<cache>/cas/metallib/`). A chain change that leaves a shader's MSL unchanged costs that shader no Metal compile while the cache format and compiler stay unchanged. Before building, the cache takes libraries from earlier `b-*/` folders beside its output (and beside `IOSOUT`), and from `DMSH_PREFILL=<Mac root>[=<iOS root>]` (several separated by `:`). Every imported library must record the current flags and compiler identity in its reflection; unmarked legacy libraries are rebuilt. A fresh compile of two shaders per stage also checks their bytes. The summary line `Metal cache:` shows reused, compiled and filled counts per target.
-- `build_ipa.sh` takes the rewritten modules from `$W/build/patched_<package>` and the RomFS from `$W/data/<package>/RomFS`; `PATCHED` and `ROMFS` override them. In unsigned IPA mode, `pack_ipa.py` packs the shader libraries, RomFS and add-on content beside the app Xcode built, as `DmIOS.app/msl/b-<chain version>`, `romfs` and `aoc`. Prepared Xcode projects instead sync these resources into the app before signing.
+- `build_ipa.sh` takes the rewritten modules from `$W/build/patched_<package>` and the RomFS image from `$W/data/<package>/RomFS.img` (legacy folders are also accepted); `PATCHED` and `ROMFS` override them. In unsigned IPA mode, `pack_ipa.py` packs the shader libraries, RomFS and add-on content beside the app Xcode built, as `DmIOS.app/msl/b-<chain version>`, `romfs` and `aoc`. Prepared Xcode projects instead sync these resources into the app before signing.
- It also bundles a standard font (macOS's Arial Unicode, `STD_FONT=` overrides it) and the generated `nintendo_ext.ttf`.
-- The icon is the `icon.jpg` that `nx_extract` saves next to `RomFS/`; `DM_ICON=` points at another image.
+- The icon is the `icon.jpg` that `nx_extract` saves next to `RomFS.img`; `DM_ICON=` points at another image.
- `DM_ENV_FILE=` bakes environment switches into the app, and `DM_DISPLAY_NAME=` renames it.
- `DM_LANG=<code>` is the game language (`DMLanguage` in `Info.plist`, default `en-US`; `main.m` sets `DM_LANG` from it unless `Documents/env.txt` or the baked env file sets it).
- `DM_METAL_CAPTURE=1` makes a build that can write GPU frame captures (`MetalCaptureEnabled` in `Info.plist`, for `DM_GPU_CAPTURE`, [GPU measurement](#gpu-measurement)).
@@ -472,7 +481,7 @@ Each game's notes are in its profile folder, `dm/games/<id>/README.md`: what the
| Tool | What it does |
|---|---|
-| `nx_extract/` | NSP → ExeFS / RomFS / icon with LibHac, merging an update over the base game (C#, `dotnet build`). `--manifest` writes ExeFS and a RomFS file list only, for surveys |
+| `nx_extract/` | NSP → ExeFS / RomFS image / icon with LibHac, merging an update over the base game (C#, `dotnet build`, `--romfs-image`). `--manifest` writes ExeFS and a RomFS file list only, for surveys; omitting both options retains legacy folder extraction |
| `nso_fnmap.py` | Carries offsets from one build to another (function matching with addresses masked; globals via their references) |
| `nso2elf.py` | Converts NSO to ELF for Ghidra / REA |
| `env_switches.py` | Writes [docs/env_switches.tsv](env_switches.tsv): every `DM_*` environment switch the code reads, with its class and a one-line meaning. The classes: player (a launcher setting, `dm/games/settings.tsv`), path (names a file or folder), switch (changes what the host or a tool does), diagnostic (logs, dumps, probes, measurements), test (read only by tests). It keeps the class and meaning of each row and adds a row for a new switch, whose meaning its author writes; `test_env_switches.py` fails until they do, and when a row names a switch nothing reads. It also lists the names the docs quote that nothing reads |
diff --git a/docs/env_switches.tsv b/docs/env_switches.tsv
index 5bee441c..814429dc 100644
--- a/docs/env_switches.tsv
+++ b/docs/env_switches.tsv
@@ -12,6 +12,7 @@ DM_AUDREN_TRACE diagnostic When set, the CPU audio renderer logs every update wi
DM_BOOTPROF diagnostic When set, logs boot timing: the loader's breakdown (mapping, relocation, probes), Metal library loading, pipeline creation, texture uploads and the first present
DM_BUNDLE_ID switch Overrides the iOS app's bundle ID in `build_ipa.sh` (default `org.nxnative.<title ID in lowercase>`)
DM_COPY_GAME_RESOURCES switch `NO` skips the Xcode build phase that copies the game's resources into the app (`stage_resources.sh`, on by default); `build_ipa.sh` sets it for its unsigned build, which packs them itself
+DM_COPY_ROMFS switch `NO` keeps the game files out of the app in the Xcode build phase (`stage_resources.sh`, on by default): `main.m` takes the validated `Documents/romfs.img` copied by `scripts/push_romfs.sh`, then a `Documents/romfs` folder
DM_CTL diagnostic `=<file>` (Mac): the host polls the file every 100 ms and runs each appended line: button presses, `shot`, `passdump`, `texdump`, `env KEY=VALUE`, `peek`, `memdump`, `drag` and more
DM_DBG diagnostic When set, prints the guest's `svcOutputDebugString` text to stderr as `[guest]` lines
DM_DBG_AU_FRAMES diagnostic `=<frames>` asks the Mac's Core Audio output for that many frames per callback instead of about 5 ms (1024 reproduces the iOS default that caused crackling)
diff --git a/docs/reference/frame-rate.md b/docs/reference/frame-rate.md
index 491faf9e..7b4e24a7 100644
--- a/docs/reference/frame-rate.md
+++ b/docs/reference/frame-rate.md
@@ -78,7 +78,7 @@ Frame pacing: the host's frame step, engine frame limiters, present intervals an
- **Symptom:** the app is active and the game keeps running, but the picture freezes while display-link callbacks stop; the log repeatedly drops queued frames.
- **Cause:** dropping frames releases the game's swapchain textures but never displays them. A display link may stop while the app is active, including an occluded Mac window.
- **Fix:** after 500 ms of silence while active, `mtl_present_wait` requests rescue. `link_sync` invalidates the display link on its run loop before releasing the layer to the present thread, which takes its own drawables in mode 0. Retry delays are 3, 6, 12, 24, 48 and then at most 60 seconds. Rescue state changes take `g_pq_mu`; the requested `g_dm_present_link` stays unchanged, and a new runtime mode ends rescue immediately. A retry resets stall timing. Inactive and background time do not count towards the 500 ms threshold, including a focus timestamp newer than the watchdog's clock sample.
-- **Found on:** d2r-mobile commit `afad65c` (an iPhone picture froze for 80 seconds), carried through MacNativeGames `cf1e629` and [PR #198](https://github.com/seedds/nxnative/pull/198). That upstream title has no profile in this repository; no local game reproduction is claimed.
+- **Found on:** d2r-mobile commit `afad65c` (an iPhone picture froze for 80 seconds), carried through MacNativeGames `cf1e629` and [PR #198](https://github.com/seedds/nxnative/pull/198). That upstream title has no profile in this repository. Mac window occlusion also affected [ANIMAL WELL's image validation](../../dm/games/010020D01AD24000/README.md#files): foreground rescue and out-of-focus fallback produced incomparable timings; its note records the controlled comparison.
- **Check:** `make -C dm/gfx/tests GAME=010015100B514000 t_present_rescue` and `dm/gfx/tests/t_present_rescue` exercise the production wait and retry paths with a controlled clock and a silent link double, without a GPU. They cover foreground grace, backoff saturation, runtime mode changes, and layer release only after run-loop invalidation. The test also runs in CPU graphics CI. `make -C dm/gfx/tests GAME=010015100B514000 check_t_present_rescue` adds a paused real Metal display link on an offscreen Mac layer: rescue invalidates it, then `nextDrawable` succeeds (47 checks, zero failures with Metal validation). `DM_TEST_LINK_STALL=<start seconds>,<duration seconds>` pauses a real window's display link for manual verification.
- **Not checked:** gameplay during stalled-link recovery or the iPhone; the PR's gameplay runs were headless.
diff --git a/docs/reference/packing.md b/docs/reference/packing.md
index a79237aa..48a45048 100644
--- a/docs/reference/packing.md
+++ b/docs/reference/packing.md
@@ -18,6 +18,22 @@
- **Fix:** count uncompressed bytes as they are read and compare them with the listed size before completing either streamed method. A mismatch stops the pack and removes the partial archive, preserving the previous IPA and its reuse index. Regression tests cover growth and shrinkage with both deflate and store.
- **Found on:** synthetic IPA inputs while reviewing [PR #279](https://github.com/seedds/nxnative/pull/279); no game files required.
+## RomFS images
+
+### RomFS folder transfers fail or leave stale game files
+
+- **Symptom:** `devicectl` copying a large RomFS folder fails with POSIX error 24 (`EMFILE`) or spends most of its time on small files; deleting an old folder during iOS startup hits the launch watchdog. A push after changing extracted files can also keep sending old assets if an image is reused solely because it exists.
+- **Cause:** a folder transfer performs hundreds of thousands of file operations. The image cache must track its source tree, and magic plus total length cannot establish that an image's index is valid. Accepting that weak check before deleting the working folder loses the fallback when mounting later rejects the index.
+- **Fix:** `dm/tools/romfs_image.py` packs one `DMROMFS1` file: a 32-byte header, file bytes, then the index and name pool. Each directory has a sorted, contiguous run of child entries; the host binary-searches each path component and reads file ranges with `pread` through one descriptor per mount. Overlay folders keep precedence and directory listings merge both sources. The shared `dm/host/romfs_image.h` loader checks the full index before either mounting or iOS folder cleanup: length, entry and name bounds, file ranges, a rooted breadth-first directory tree, and sorted, unique child names. It supports an empty root too. Invalid images fall back to the folders on iOS; an explicit invalid `DM_ROMFS` image is refused with a `[RED]` line. The index check detects interrupted sequential transfers and structural damage, not same-length corruption inside file contents. The packer publishes by rename only after the source stays stable. Its reuse stamp tracks source names and file metadata including ctime, the packer and image identity; the push helper always checks it, and `--repack` forces a rebuild. Usage: [Quick reinstalls](../development.md#quick-reinstalls).
+- **Found on:** [Tears of the Kingdom](../../dm/games/0100F2C0115B6000/README.md#files-and-shaders), whose 304,000-file transfer and startup deletion failures are reported in [PR #369](https://github.com/seedds/nxnative/pull/369). [ANIMAL WELL](../../dm/games/010020D01AD24000/README.md#files) provides the empty-image boot case. Synthetic packer/host tests cover actual file reads, case aliases, overlay merging, corrupt indexes and changed sources; the macOS Foundation test executes iOS's locator to check that rejected images preserve its folder.
+
+### Building creates a full RomFS tree before packing its image
+
+- **Symptom:** reducing the iPhone transfer to one image still creates thousands of resource files on the Mac, and build scanners require the expanded folder.
+- **Cause:** folder extraction followed by a separate image pack duplicates the work; ordinary filesystem APIs cannot address files inside an image.
+- **Fix:** the NSP pipeline passes `--romfs-image` to `nx_extract`. LibHac layers the update over the base and checks its integrity while the writer streams file bytes into a temporary `DMROMFS1` image, appends the sorted directory index and publishes by rename. ExeFS remains expanded; RomFS and each DLC remain one physical file. `dm/tools/romfs.py` gives the scanners read-only virtual paths, bounded seeks and archive mappings (Python 3.12+), without changing the process's standard filesystem APIs. The IPA packer maps the physical image to `Payload/DmIOS.app/romfs.img`; iOS and the Mac launcher validate and mount it in place. Neither installation nor startup expands the resource files. Documents overrides and legacy folder inputs remain supported. A source image is uncompressed; the IPA can deflate it, so file-count reduction does not imply a smaller installed byte count. Full images for separate game versions cannot share unchanged individual files through APFS clones as legacy folder extraction did.
+- **Found on:** [ANIMAL WELL](../../dm/games/010020D01AD24000/README.md#files), whose direct image is an empty root (56 bytes); the local Baba Is You provisional build exercises 6,374 files in a 103,473,292-byte image, 131 shaders and an unsigned IPA containing only the single image entry. [Raging Loop](../../dm/games/010020400E1C2000/README.md#files-and-shaders) supplies Unity resources: all 1,473 source manifest entries match the image, and every registered shader remains in the scan. Synthetic integration tests call the actual LibHac writer, read unaligned archive ranges, and exercise IPA mapping, Xcode staging and bundled-image startup.
+
## Compressed inputs
### NSZ decompression rejects `--keys`
@@ -26,3 +42,12 @@
- **Cause:** `nsz` 4.6.1 has no `--keys` argument. It loads `keys.txt` beside `sys.argv[0]`, or falls back to `~/.switch/prod.keys`, while importing its modules, before parsing arguments ([4.6.1 key loader](https://github.com/nicoboss/nsz/blob/4.6.1/nsz/nut/Keys.py)). Newer upstream code supports `--keys`; staging `keys.txt` also supports 4.6.1.
- **Fix:** `scripts/build_ipa_from_nsp.py` `decompress_nsz` links the file selected by `-k` as `keys.txt` in the conversion's temporary folder and runs `nsz -D` there, with `sys.argv[0]` set to `nsz` before import. Input and output paths are absolute. The temporary folder and link are removed on success or failure; the user's default keys are untouched.
- **Found on:** [Super Mario Odyssey](../../dm/games/0100000000010000/README.md), converting its v0 NSZ. Applies to NSZ and XCZ inputs for every game.
+
+## Cartridge dumps
+
+### A cartridge dump with its update on it extracts the update as the base game
+
+- **Symptom:** the extraction of a game whose base is an XCI that also carries its update (a "1G+1U" dump) stops with `[RED] nx_extract exit code -6`. `extract_v<version>.log` lists the update's build IDs even for the base game alone, then ends in an unhandled exception from the RomFS (`ResultFsNonRealDataVerificationFailed (2002-4604): Hash error!` from `RomFsFileSystem..ctor`, or `ArgumentException` / `InvalidOperationException` from the patch layers).
+- **Cause:** the XCI's secure partition holds the update's NCAs beside the base game's, and the update's Program NCA has the program's title ID too. `nx_extract` took the first Program NCA of the lowest title ID as the base, which is the update's when the dump lists it first. Its data section is a patch (BKTR) over the base RomFS, so it cannot be read alone or under another patch. The ExeFS still opens, with the update's build IDs, because an update's code section is complete. The Control NCA (display version, icon) was also whichever of the two came last.
+- **Fix:** `dm/tools/nx_extract/Program.cs` `OpenNsp` reads the base package's content metas (`*.cnmt` in its Meta NCAs) and keeps only the NCAs that its Application content meta lists, and prints how many it left out. When none of them is a Program NCA (NCA files renamed, so their names are not content IDs), it prints a `[RED]` line and reads every NCA as before. An NSP or a base-only XCI keeps every NCA but its meta NCA, so it extracts as before (Balatro's NSPs and Monster Hunter Rise's XCI give identical manifests). The update is still taken from the update NSP in the folder; the one on the cartridge is not used, so an XCI alone packs the base game's version.
+- **Found on:** [The Legend of Zelda: Tears of the Kingdom](../../dm/games/0100F2C0115B6000/README.md), a 1G+1U XCI (base v0 with update 1.4.3, whose 524 MB Program NCA is listed before the base's 17.1 GB one) beside the 1.4.3 update NSP ([PR #311](https://github.com/seedds/nxnative/pull/311)). Reproduced with a package of Balatro's update NSP followed by its base NSP: the base alone and the base with the update now give the same manifests and control data as the separate NSPs. Applies to any game's XCI that carries its update.
diff --git a/docs/reference/services.md b/docs/reference/services.md
index ecd8ad85..2cb066a8 100644
--- a/docs/reference/services.md
+++ b/docs/reference/services.md
@@ -473,9 +473,10 @@ Most service calls can be found before they crash, before the first boot or the
- **Symptom:** the boot sits at a black loading screen for good, CPU nearly idle, every thread waiting, about 1 boot in 6 (3 in 4 with four Mac hosts at once); the title movie is never opened, and the save files are never probed.
- **Cause:** a race the host's instant offline answers lost. The game's boot state machine (`main+0x1f2f0e0`, state at `this+0xd4`, found by probing the save probe's call stack and dumping the state each tick) stayed in state 7, which polls the status word (+0x14) of the game's BCAT news runnable ("OlimarMemo") for 0, 4, 5, 6 or 7; it read 1. The runnable's constructor (`main+0x203f3b0`) clears the status, starts `FBCATThread` and only then stores 1; the thread's `Run` (`main+0x203f510`) stores 2, calls `nn::nifm::SubmitNetworkRequest`, sleeps while `IsNetworkRequestOnHold`, and stores 6 when `IsNetworkAvailable` is false. On a Switch the request stays on hold while the nifm service evaluates it, so the constructor's 1 always comes first; the host answered "not on hold" at once, and a thread that ran before the constructor's store finished at 6, which the 1 then overwrote.
-- **Fix:** the host now keeps a submitted request on hold for 50 ms, then settles it as unavailable, as Horizon's asynchronous request does (`hle_net.c`).
-- **Found on:** [Pikmin 4](../../dm/games/0100B7C00933A000/README.md) (Unreal Engine 4.26.2).
-- **Check:** 12 of 12 boots with four hosts at once reached the title.
+- **Fix:** a submitted request is on hold for the first `IsNetworkRequestOnHold` after the submission and settled as unavailable at the next (`hle_net.c`). On Horizon each query is an IPC to the nifm service, which evaluates the request as it serves them, offline a rejection; Pikmin 4 sleeps 10 ms between its queries, so the constructor's store always comes first.
+- **Note:** the first fix held the request for 50 ms of host time. A game that bounds its wait by the number of queries never saw that end: Hades' `NetworkPollThread` (`main+0x27aaa0`) yields between queries and cancels after 2,000 (2,000 IPCs on a Switch, 0.1 ms here), then submits again at once, which kept a host core busy (1.17 billion queries a minute; with [A wait at two yields is not progress](threads.md#a-wait-at-two-yields-is-not-progress), 216,000 yields and half the CPU). Its stamp, `now_ns() | 1`, also read as settled whenever the next query came within the same 42 ns tick of the Mac's clock: 30% of Hades' submissions, and 42% back to back.
+- **Found on:** [Pikmin 4](../../dm/games/0100B7C00933A000/README.md) (Unreal Engine 4.26.2); [Hades](../../dm/games/0100535012974000/README.md) (the 50 ms hold).
+- **Check:** 12 of 12 boots with four hosts at once reached the title, with both fixes; a host that answers at once hung 1 of 4 in the same test.
- **Note:** how it was found: the hung boots' logs diverged from good ones at the save probe (`DM_FS=1`), the thread dumps showed nothing but idle waits, and `DM_PROBE` on the state machine, then `peek` lines in a hung run's `DM_CTL` file, followed the pointers to the status word (a probe on the hot path slowed the boot enough to hide the race: 8 of 8 good).
### Socket `Poll` and `Select` with nothing to wait on
diff --git a/docs/reference/shaders.md b/docs/reference/shaders.md
index 845ba864..436a7bfb 100644
--- a/docs/reference/shaders.md
+++ b/docs/reference/shaders.md
@@ -4,6 +4,13 @@ Finding, keying and translating shaders (`dm/gfx/tools/shader_split.py`, `dmsh_b
## Containers by engine
+### A file no reader reads
+
+- **Symptom:** the shader split stops on one archive with a Python traceback (an `IndexError` or `struct.error` naming no file), or a reader's `[RED]` line about a format it does not know, and nothing is written; the NSP script loses the build at the split.
+- **Cause:** a worker's exception (and `red()`, a `SystemExit`) ended the whole split through the process pool, so one archive of a format revision a reader does not know stopped every other file's shaders too. `nlg_dict` read its index without checking the layout, so an index of another revision gave an `IndexError` instead of a line naming the archive.
+- **Fix:** `scan_file` leaves out a file whose reader fails, with `[RED] <file>: <why> (its shaders are left out)`, and the split goes on; at the end it prints `[RED] <n> file(s) could not be read, their shaders are left out (first: …)` and writes its tables. The NSP script shows that line and packs a provisional profile's IPA without those shaders; for a registered profile it stops there, since the profile's tables were split from every file. `nlg_dict` checks that the records and chunks fit the index and every chunk index is in range before reading it. The format itself still needs a reader: the line names the archive and, for NLG, its header bytes.
+- **Found on:** Mario Strikers: Battle League (no profile; [seedds/nxnative#282](https://github.com/seedds/nxnative/pull/282)): one of its 879 Next Level Games archives, a revision `nlg_dict` does not read.
+
### BNSH in NintendoWare archives and in main
- BNSH (`BNSH\0\0\0\0` + `grsc` block at +0x60) is found inside `bfsha`, particle effects (`esetb`, VFXB), UI layouts (`blarc`), and `main` itself.
diff --git a/docs/reference/threads.md b/docs/reference/threads.md
index 6b2847cb..cae6dc4a 100644
--- a/docs/reference/threads.md
+++ b/docs/reference/threads.md
@@ -124,6 +124,14 @@ The yield back-off (`DM_YIELD_BACKOFF`) and the rewriter's spin waits (`patch_ns
- **Check:** check such a change on [The Legend of Zelda: Breath of the Wild](../../dm/games/01007EF00011E000/README.md) outdoors: its `PlacementMgr` and `RadarMgr` turned out to yield per item too, and a `sched_yield` on each of their 200,000 yields a second cost a third of a core more than the back-off had; with no host call, CPU energy fell instead (numbers in [development.md](../development.md) "Yield loops").
- **Note:** a temporary log of which of x19–x28 move at each yield, per thread, is what told the two kinds apart.
+### A wait at two yields is not progress
+
+- **Symptom:** one guest thread keeps a host core at 100% with about a billion yields a minute (`SVC 0xb` in `DM_HLECOUNT`), none of them a back-off sleep, while the game itself plays normally.
+- **Cause:** the loop waits at two yields whose callee-saved registers differ, so each yield looked as if the loop had moved on since the last one, and returned at once. Hades' `NetworkPollThread` (`main+0x27aaa0`) yields between its passes with w23 = 0, and in each pass yields while the nifm request is on hold with w23 = 2,000, its retry count.
+- **Fix:** a yield is progress only when x19–x28 differ from both of the last two yields (`thr_yield` in `hle_thread.c`): a loop that comes back to the registers of the yield before last is waiting, and the run goes on to the back-off. Counters and cursors (Animal Crossing's grid walk, Breath of the Wild's batches) never come back, so they still return at once.
+- **Found on:** [Hades](../../dm/games/0100535012974000/README.md), with [Network requests stay on hold before they settle](services.md#network-requests-stay-on-hold-before-they-settle). Neither change alone was enough: in 60 s of its smoke route the process used 117 s of CPU on `main`, 119 s with only the nifm change (627 million submits, a pass now ended at the second query) and 122 s with only this one (1.38 billion queries, the 50 ms hold still timed out). With both it used 62 s, as with the poll thread's yields turned into sleeps: 216,000 yields, most of them back-off sleeps.
+- **Check:** a temporary per-thread count of the yields only this rule keeps in a run, and of the back-off sleeps those runs then took, on boots and play of other games: Tears of the Kingdom's main thread and ModuleSystem workers about 0.1% of their yields (761 of 926,116 on the main thread in 120 s) and no back-off sleep; Breath of the Wild outdoors at most 7 per thread in 150 s, no back-off sleep; Three Houses up to 95 per thread, Donkey Kong Country: Tropical Freeze about 1,000 on the main thread, neither with a back-off sleep from them; Kirby at most 1; Celeste, BALL x PIT, Bayonetta and Ghost Trick none. Their frame rates matched `main` in runs that kept the window's focus (a run whose window loses focus to another app drops to about 30 fps, on `main` as well).
+
## Events and notifications
### Service-event producers follow the binding lifetime
diff --git a/scripts/bench.py b/scripts/bench.py
index b84d92bd..215cf25e 100644
--- a/scripts/bench.py
+++ b/scripts/bench.py
@@ -17,6 +17,8 @@ import argparse, datetime, json, math, os, re, shutil, signal, statistics, subpr
from pathlib import Path
REPO = Path(__file__).resolve().parent.parent
+sys.path.insert(0, str(REPO / 'dm/tools'))
+import romfs as rfs
def fail(msg):
@@ -78,8 +80,8 @@ def run_one(a, gid, build, var, route, out, lock):
host = Path(var.get('host') or build / 'tools/dmhost')
patched = Path(var.get('patched') or newest(build.glob('patched_v*')) or fail(f'no rewritten modules (patched_v*) in {build}'))
ver = patched.name.removeprefix('patched_')
- romfs = build / 'extract' / ver / 'RomFS'
- if not romfs.is_dir(): romfs = newest(build.glob('extract/v*')) / 'RomFS'
+ romfs = rfs.source(build / 'extract' / ver)
+ if not romfs.is_dir(): romfs = rfs.source(newest(build.glob('extract/v*')))
prof = build / 'profile' / gid if (build / 'profile' / gid / 'game.tsv').is_file() else REPO / 'dm/games' / gid
out.mkdir(parents=True, exist_ok=True); save, temp = out / 'save', out / 'temp'
shutil.rmtree(save, ignore_errors=True); shutil.copytree(a.save, save); temp.mkdir(exist_ok=True)
diff --git a/scripts/build_ipa_from_nsp.py b/scripts/build_ipa_from_nsp.py
index 18053657..b4faba93 100755
--- a/scripts/build_ipa_from_nsp.py
+++ b/scripts/build_ipa_from_nsp.py
@@ -18,7 +18,7 @@
# Uses only three things: this repository, a folder holding one game's NSPs (the base game, with or without an update; DLC NSPs, when present, are packed too and unlock the add-on content already in the game), and prod.keys.
# The newest version in the folder is packed. A version the profile registers (with every version in its shader_versions in the folder) is built from the profile as it is; any other
# version (the base game alone, another update) from a profile derived from it in <id>_build/profile: the same settings, and the version's own shaders (derive_profile).
-# Every intermediate file is under <id>_build/ in the NSP folder: nsp/ (NSZ / XCZ files converted to NSP / XCI with nsz -D, kept for the next build; pip install nsz), extract/ (the extracted game files, kept for the next build unless KEEP_EXTRACTED / --no-keep-extracted), aoc/ (each DLC's RomFS by index), tools/ (nx_extract, and the Mac host for a run-time shader capture), patched_*/, shader/ (shader package and caches, kept so the next build is fast), logs/ (each step's full output), tmp/, ipa/. The finished IPA also goes to the NSP folder by default.
+# Every intermediate file is under <id>_build/ in the NSP folder: nsp/ (NSZ / XCZ files converted to NSP / XCI with nsz -D, kept for the next build; pip install nsz), extract/ (the extracted game files, kept for the next build unless KEEP_EXTRACTED / --no-keep-extracted), aoc/ (one RomFS image per DLC index), tools/ (nx_extract, and the Mac host for a run-time shader capture), patched_*/, shader/ (shader package and caches, kept so the next build is fast), logs/ (each step's full output), tmp/, ipa/. The finished IPA also goes to the NSP folder by default.
# The DLC, the rewrite, the shader split and the iOS (or Vulkan) shaders are reused when all their inputs are as at their last successful run (the game files, the tools, the profile, Xcode and the in-repo spirv-cross: fingerprint() keys beside their output);
# the iOS shaders' inputs are the shader package's content and the chain's own tools, so a split that runs again and writes the same package leaves them reused.
# The chain version header dm/gfx/nvn/dmsh_chain.h (one version for every game) is written again when a chain change was committed without it (chain_header: it follows from the source alone),
@@ -27,10 +27,12 @@
# The shader translator is the in-repo dm/gfx/tools/dmsh_xlate_bin (the build whose fingerprints match dmsh_chain.lock; a rebuilt dll has different fingerprints and dmsh_build refuses it; its launcher is universal, so an Intel Mac runs it too). SPIRV-Cross is the in-repo dm/gfx/tools/spirv_cross_bin and must match the lock too.
# The shader libraries are built through dm/gfx/tools/own_compilers.py. The Metal compiler must match the lock (Xcode 27.1): another one stops an NVN game's build before its shader steps,
# unless ALLOW_OTHER_METAL / --allow-other-metal. Issue #242 reported corruption with another compiler; the cause is still unconfirmed.
-# The Python running this file needs lz4, capstone and fonttools (and backports.zstd before Python 3.14); also needed: Xcode, xcodegen, .NET SDK 10, zstd. SPIRV-Cross is the in-repo build. A first run takes 2 (Metroid Dread) to 10 minutes (Breath of the Wild: 5 of them the shader split), longer when shader libraries must be compiled; a repeat run with unchanged inputs takes about 20 s (Metroid Dread), mostly packing the IPA. Key values are never printed.
+# Python 3.12+ is required for bounded archive mappings inside images. The Python running this file needs lz4, capstone and fonttools (and backports.zstd before Python 3.14); also needed: Xcode, xcodegen, .NET SDK 10, zstd. SPIRV-Cross is the in-repo build. A first run takes 2 (Metroid Dread) to 10 minutes (Breath of the Wild: 5 of them the shader split), longer when shader libraries must be compiled; a repeat run with unchanged inputs takes about 20 s (Metroid Dread), mostly packing the IPA. Key values are never printed.
# The console shows one line per stage ([k/n] stage, with a bar, done/total, percent, elapsed time and ETA where the work can be counted); the tools' own output goes only to logs/ (PROGRESS / --progress). --progress json writes newline-delimited JSON events to stdout.
-import ast, collections, ctypes, getpass, pwd, hashlib, importlib.util, json, os, re, shlex, shutil, struct, subprocess, sys, tempfile, threading, time, types, zlib
+import ast, collections, ctypes, getpass, pwd, hashlib, importlib.util, json, os, re, shlex, shutil, struct, subprocess, sys, tempfile, threading, time, types
from pathlib import Path
+sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "dm/tools"))
+import romfs as rfs
# ---- Settings ----
NSP_DIR = '' # folder holding the NSPs (empty = ask at run time)
@@ -276,7 +278,7 @@ def progress_mode(want): # auto: redraw in a terminal or in Spyder (IPython ha
def tree_size(d): # (files, bytes) under d; (0, 0) when it does not exist yet
n = b = 0; todo = [str(d)]
while todo:
- try: it = os.scandir(todo.pop())
+ try: it = rfs.os.scandir(todo.pop())
except OSError: continue
with it:
for e in it:
@@ -519,6 +521,13 @@ def pick_nsps(fam, have, versions):
return out
+def extract_bytes(picks, clones):
+ """What the extraction writes, estimated from the NSPs' sizes. Later versions clone the base game's RomFS when the base is extracted alone (v0) and the volume supports clones:
+ then each NSP counts once (by path: two NSPs can have the same size). Otherwise every version is a full copy of the base game with its update"""
+ if clones and any(u is None for _, u in picks.values()): return sum(p.stat().st_size for p in {p for b, u in picks.values() for p in (b, u) if p})
+ return sum(b.stat().st_size + (u.stat().st_size if u else 0) for b, u in picks.values())
+
+
def can_clone(d): # whether this volume supports APFS clones (nx_extract uses them to save space; without them it writes full copies)
a, b = d / '.clone_test', d / '.clone_test2'
try:
@@ -766,7 +775,7 @@ def derive_profile(g, pdir, ver, d, mods, app=None, shader_only=False):
def files_under(d): # (relative path, stat) of every file under d, sorted; [] when it does not exist
out, todo = [], [str(d)]
while todo:
- try: it = os.scandir(todo.pop())
+ try: it = rfs.os.scandir(todo.pop())
except OSError: continue
with it:
for e in it:
@@ -784,7 +793,7 @@ def fingerprint(*items, env=None):
kind, v = it if isinstance(it, tuple) and len(it) == 2 and it[0] in ('files', 'tree', 'stat', 'cmd') else ('repr', it)
h.update(f'\0{kind}\0'.encode())
if kind == 'files':
- for p in map(Path, v):
+ for p in map(rfs.Path, v):
h.update(p.name.encode() + b'\0')
try: h.update(hashlib.sha256(p.read_bytes()).digest())
except OSError: h.update(b'missing')
@@ -804,7 +813,7 @@ def reused(keyfile, key): # the note the stage's last successful run wrote bes
def tool_files(repo): # what the shader stages run: dm/gfx/tools' scripts and the lock of the translator's fingerprints, the profile reader, the iOS compile convention, the NSO reader
- return sorted((repo / 'dm/gfx/tools').glob('*.py')) + [repo / p for p in ('dm/gfx/tools/dmsh_chain.lock', 'dm/games/game.py', 'dm/ios/tools/ios_metal.py')]
+ return sorted((repo / 'dm/gfx/tools').glob('*.py')) + [repo / p for p in ('dm/gfx/tools/dmsh_chain.lock', 'dm/games/game.py', 'dm/ios/tools/ios_metal.py', 'dm/tools/romfs.py')]
def chain_files(repo): # what the iOS shaders run: dmsh_build.py and every repository module it imports, at any depth (dmsh_*.py, ios_metal.py, game.py), and the translator's lock; not the split's readers (shader_split.py, unityfs.py, uepak.py)
@@ -864,7 +873,9 @@ def extracted(log): # (files, bytes) from the summary lines nx_extract wrote t
def extract(nx, keys, ex, name, base, upd, cmp_dir, logs, g): # the build IDs are checked by the caller (build_mismatch)
dst, marker, log = ex / name, g.get('romfs_marker'), logs / f'extract_{name}.log'
- if (dst / 'ExeFS' / 'main').exists() and (dst / 'RomFS' / marker).exists():
+ try: reusable = (dst / 'ExeFS' / 'main').exists() and (dst / 'RomFS.img').is_file() and not (dst / 'RomFS').exists() and (rfs.source(dst) / marker).exists()
+ except (OSError, ValueError, struct.error): reusable = False
+ if reusable:
PROG.stage(f'extract {name}')
say(f'reusing the extracted {name}: {dst}')
PROG.end('reused')
@@ -874,7 +885,7 @@ def extract(nx, keys, ex, name, base, upd, cmp_dir, logs, g): # the build IDs
def poll():
n, b = tree_size(tmp); return {'done': b, 'note': f'{n:,} files'}
PROG.stage(f'extract {name}', poll=poll, unit='B', total=last[1] if last else base.stat().st_size + (upd.stat().st_size if upd else 0), est=not last)
- run([nx, keys, base, upd or '-', tmp] + ([cmp_dir] if cmp_dir else []) + (['--allow-damaged'] if ALLOW_DAMAGED else []), log)
+ run([nx, keys, base, upd or '-', tmp, '--romfs-image'] + (['--allow-damaged'] if ALLOW_DAMAGED else []), log)
swap_in(tmp, dst)
n, b = extracted(log) or (0, 0)
PROG.end(f'{n:,} files, {amount(b, "B")}')
@@ -882,7 +893,7 @@ def extract(nx, keys, ex, name, base, upd, cmp_dir, logs, g): # the build IDs
def extract_aoc(nx, keys, repo, work, app, fam, logs):
- """DLC NSPs in the folder → <id>_build/aoc/<index>/ (the RomFS of each one's data NCA; index = title ID − base − 0x1000). The host reports these indices as owned and mounts them (DM_AOC_DIR).
+ """DLC NSPs in the folder → <id>_build/aoc/<index>.img (the RomFS of each one's data NCA; index = title ID − base − 0x1000). The host reports these indices as owned and mounts them (DM_AOC_DIR).
Returns None without DLC. Reused when the DLC NSPs (names, sizes and times) and nx_extract's sources are as at the last extraction (Monster Hunter Rise: 250 DLC, 30 s)"""
if not fam['dlc']: return None
tmp, dst = work / 'aoc.partial', work / 'aoc'; rmtree(tmp)
@@ -900,7 +911,7 @@ def extract_aoc(nx, keys, repo, work, app, fam, logs):
idx = tid - app - 0x1000
PROG.set(step='extracting', done=i, total=len(best), unit='DLC')
say(f'DLC index {idx}: {p.name}')
- run([nx, keys, '--aoc', p, tmp / str(idx)], logs / f'aoc_{idx}.log')
+ run([nx, keys, '--aoc', p, tmp / f'{idx}.img', '--romfs-image'], logs / f'aoc_{idx}.log')
swap_in(tmp, dst)
kf.write_text(f'{key}\n{len(best)} DLC\n')
PROG.end(f'{len(best)} DLC')
@@ -935,7 +946,7 @@ def collect_nros(py, repo, romfs, dst, env, logs):
if not nrrs:
rmtree(dst); rmtree(kf) # an update can remove its NRRs: do not carry the previous manifest into the rewrite
return {}
- key = fingerprint(('files', nrrs + [repo / f for f in ('dm/tools/nro_collect.py', 'dm/tools/nso_syms.py', 'dm/gfx/tools/smash_arc.py')]), ('tree', romfs))
+ key = fingerprint(('files', nrrs + [repo / f for f in ('dm/tools/nro_collect.py', 'dm/tools/nso_syms.py', 'dm/gfx/tools/smash_arc.py', 'dm/tools/romfs.py')]), ('tree', romfs))
if not ((dst / 'nro.tsv').is_file() and reused(kf, key) is not None):
tmp = dst.with_name(dst.name + '.partial'); rmtree(tmp)
PROG.set(step=f'finding the NROs {len(nrrs)} NRR files register')
@@ -964,7 +975,7 @@ def rewrite(py, repo, exe_dir, out, env, logs, g, provisional=False):
import capstone
PROG.stage('rewrite', step='checking the inputs')
nro_dir = out.with_name('nro_' + out.name.removeprefix('patched_'))
- nros = collect_nros(py, repo, exe_dir.parent / 'RomFS', nro_dir, env, logs)
+ nros = collect_nros(py, repo, rfs.source(exe_dir.parent), nro_dir, env, logs)
if provisional and nros: g = nro_modules(g, exe_dir, nros)
mods = g.words('modules')
manifest = nro_dir / 'nro.tsv'
@@ -1089,7 +1100,7 @@ def capture_glslc(repo, dirs, pkg_ver, patched, work, env, logs, g):
rmtree(cap); rmtree(rd)
for s in ('save', 'temp'): (rd / s).mkdir(parents=True)
# everything the run writes stays in <id>_build (DM_ROOT is already there): a fresh save and temporary storage, no shader libraries yet, the profile's shader map (the host looks beside itself by default)
- henv = dict(env, DM_ROMFS=str(d / 'RomFS'), DM_SAVE=str(rd / 'save'), DM_TEMP=str(rd / 'temp'), DM_MSL_DIR=str(rd / 'msl'), DM_NVN_SHMAP=str(g.table('shader_map.tsv')), DM_GLSLC_CAPTURE=str(cap))
+ henv = dict(env, DM_ROMFS=str(rfs.source(d)), DM_SAVE=str(rd / 'save'), DM_TEMP=str(rd / 'temp'), DM_MSL_DIR=str(rd / 'msl'), DM_NVN_SHMAP=str(g.table('shader_map.tsv')), DM_GLSLC_CAPTURE=str(cap))
PROG.set(step='booting the game', done=0, total=len(want) if want else None, unit='shaders')
say(f'booting the game in the Mac host to capture the shaders it compiles at run time → {d / "glslc_capture"}')
t0 = time.time()
@@ -1113,7 +1124,7 @@ UE_DECODE_SECS = 300 # the longest Oodle decode run: Octopath Traveler 0's 10,
def ue_stamp(d): # what an extraction's decoded shader archives were made from: its paks and IoStore TOCs (paths and sizes)
- return ''.join(f'{p.relative_to(d / "RomFS")}\t{p.stat().st_size}\n' for p in sorted([*(d / 'RomFS').rglob('*.pak'), *(d / 'RomFS').rglob('*.utoc')]))
+ return ''.join(f'{p.relative_to(rfs.source(d))}\t{p.stat().st_size}\n' for p in sorted([*(rfs.source(d)).rglob('*.pak'), *(rfs.source(d)).rglob('*.utoc')]))
def decode_ue_shaders(repo, dirs, pkg_ver, patched, work, env, logs, g):
@@ -1135,16 +1146,16 @@ def decode_ue_shaders(repo, dirs, pkg_ver, patched, work, env, logs, g):
rmtree(jd); rmtree(rd)
for s in ('save', 'temp'): (rd / s).mkdir(parents=True)
dec = None
- if uepak.io_shader_tocs(str(d / 'RomFS')):
+ if uepak.io_shader_tocs(str(rfs.source(d))):
if not host:
PROG.set(step='building the Mac host')
host = build_mac_host(repo, work / 'tools/dmhost', env, logs, g)
dec = uepak.OodleHost(host, patched, env)
PROG.set(step=f'{v}: shader archives out of the paks' + (' and IoStore containers' if dec else ''))
- try: listing, n = uepak.job(str(d / 'RomFS'), str(d / 'ExeFS/main'), str(jd), decode=dec)
+ try: listing, n = uepak.job(str(rfs.source(d)), str(d / 'ExeFS/main'), str(jd), decode=dec)
finally:
if dec: dec.close()
- if not listing: raise BuildError(f'the RomFS has Unreal paks, but none under {d / "RomFS"} holds a shader code archive: where the shaders are has to be found first')
+ if not listing: raise BuildError(f'the RomFS has Unreal paks, but none under {rfs.source(d)} holds a shader code archive: where the shaders are has to be found first')
say(f'{v}: ' + '; '.join(f'{x["name"]} {x["shaders"]:,} shaders' + (f' ({x["compression"]})' if x.get('compression') else '') for x in listing)
+ (f'; decoding {n:,} with the game\'s Oodle in the Mac host' if n else ''))
if n: # Oodle-compressed shaders (Octopath Traveler 0); LZ4 ones (Unreal Engine 4.26 and later by default) are decoded by uepak.py already
@@ -1152,7 +1163,7 @@ def decode_ue_shaders(repo, dirs, pkg_ver, patched, work, env, logs, g):
PROG.set(step='building the Mac host')
host = build_mac_host(repo, work / 'tools/dmhost', env, logs, g)
PROG.set(step=f'{v}: decoding {n:,} shaders in the Mac host')
- henv = dict(env, DM_ROMFS=str(dirs[pkg_ver] / 'RomFS'), DM_SAVE=str(rd / 'save'), DM_TEMP=str(rd / 'temp'), DM_MSL_DIR=str(rd / 'msl'), DM_OODLE_JOB=str(jd / 'oodle.job'))
+ henv = dict(env, DM_ROMFS=str(rfs.source(dirs[pkg_ver])), DM_SAVE=str(rd / 'save'), DM_TEMP=str(rd / 'temp'), DM_MSL_DIR=str(rd / 'msl'), DM_OODLE_JOB=str(jd / 'oodle.job'))
rc = boot_mac(host, patched, henv, rd, log, UE_DECODE_SECS)
if rc != 0 or not (jd / 'oodle.job.out').exists():
PROG.end(ok=False)
@@ -1200,7 +1211,7 @@ def capture_shaders(repo, d, patched, work, env, logs, g, api):
rmtree(cap); rmtree(rd); cap.mkdir(parents=True)
for x in ('save', 'temp', 'msl'): (rd / x).mkdir(parents=True)
# everything the run writes stays in <id>_build (DM_ROOT is already there): a fresh save and temporary storage, an empty shader library folder (pipelines fail, the game still creates every shader)
- henv = dict(env, DM_ROMFS=str(d / 'RomFS'), DM_SAVE=str(rd / 'save'), DM_TEMP=str(rd / 'temp'), DM_MSL_DIR=str(rd / 'msl'), **{C['env']: str(cap)})
+ henv = dict(env, DM_ROMFS=str(rfs.source(d)), DM_SAVE=str(rd / 'save'), DM_TEMP=str(rd / 'temp'), DM_MSL_DIR=str(rd / 'msl'), **{C['env']: str(cap)})
PROG.set(step='booting the game', done=0, total=len(want) if want else None, unit='shaders')
say(f'booting the game in the Mac host to capture the {C["what"]} at run time → {out}')
t0 = time.time(); last = {'n': 0, 't': t0}
@@ -1334,7 +1345,7 @@ def heap_check(repo, d, patched, work, env, logs, g):
rmtree(rd)
for x in ('save', 'temp', 'msl'): (rd / x).mkdir(parents=True)
# a fresh save and temporary storage, no shader libraries (only the heap request matters), the profile's shader map
- henv = dict(env, DM_ROMFS=str(d / 'RomFS'), DM_SAVE=str(rd / 'save'), DM_TEMP=str(rd / 'temp'), DM_MSL_DIR=str(rd / 'msl'), DM_NVN_SHMAP=str(g.table('shader_map.tsv')))
+ henv = dict(env, DM_ROMFS=str(rfs.source(d)), DM_SAVE=str(rd / 'save'), DM_TEMP=str(rd / 'temp'), DM_MSL_DIR=str(rd / 'msl'), DM_NVN_SHMAP=str(g.table('shader_map.tsv')))
PROG.set(step='booting the game')
t0, seen = time.time(), {}
def done(): # the first heap request answered (or refused for good), or nnMain running for a while without one
@@ -1428,7 +1439,12 @@ def split_shaders(py, repo, roms, mains, pkg, env, logs, g, provisional=False, o
tmp = pkg.with_name(pkg.name + '.partial'); rmtree(tmp); (tmp / 'tables').mkdir(parents=True)
run([py, repo / 'dm/gfx/tools/shader_split.py', ','.join(map(str, roms)), ','.join(map(str, mains)), tmp / 'pkg'] + [tmp / 'tables' / n for n in names + ('pso_pairs.tsv',)] + ([','.join(map(str, dlc_roms))] if dlc_roms else []),
logs / 'shader_split.log', env=env)
- m = re.search(r'shaders: (\d+) \(', (logs / 'shader_split.log').read_text(errors='replace'))
+ text = (logs / 'shader_split.log').read_text(errors='replace')
+ m = re.search(r'shaders: (\d+) \(', text)
+ bad = re.search(r'^\[RED\] (\d+) file\(s\) could not be read.*$', text, re.M) # the split leaves out a file no reader reads (its own red line per file in the log) and goes on
+ if bad and not provisional: # the profile's tables were split from every file: one that does not read now is a reader change
+ raise BuildError(f'{bad.group(0).removeprefix("[RED] ")}; the profile\'s tables hold every file\'s shaders (each file in {logs / "shader_split.log"})')
+ if bad: say(f'{bad.group(0)}; the IPA goes without them (each file in {logs / "shader_split.log"})')
if m and m.group(1) == '0': # dmsh_build.py would make no library, and the iOS shader step stop with no word of why
raise BuildError('the shader split found no shaders in main or the RomFS: the game keeps them in a form shader_split.py does not read; locate them (docs/agents) and add a reader')
# pso_pairs.tsv (agl BAHS program variations): checked like the others where the profile has one; else kept beside the
@@ -1444,7 +1460,7 @@ def split_shaders(py, repo, roms, mains, pkg, env, logs, g, provisional=False, o
diff = [n for n in names if data_rows((tmp / 'tables' / n).read_bytes()) != data_rows(g.table(n).read_bytes())]
if diff: raise BuildError(f'the split shader tables differ from game profile {g.id}\'s: {", ".join(diff)} (game files not the versions the profile registers?)')
rmtree(kf); swap_in(tmp / 'pkg', pkg); rmtree(tmp)
- note = f'{int(m.group(1)):,} shaders' if m else ''
+ note = (f'{int(m.group(1)):,} shaders' if m else '') + (f', {bad.group(1)} file(s) unreadable' if bad else '')
if key: # an own profile's tables are outputs too; the next split checks the profile after they were written
key = fingerprint(*inputs, ('files', profile_files(g)))
kf.write_text(f'{key}\n{note}\n')
@@ -1727,7 +1743,7 @@ def mac_run(work, game, patched, host, font, msl, aoc, gfx, lang, env, logs, g,
c1_full.tsv and cb_extent.tsv are read beside it), the game language, and the switches of an environment file (DM_ENV_FILE / --env-file)"""
rd = work / 'run'
for d in ('save', 'temp'): (rd / d).mkdir(parents=True, exist_ok=True)
- renv = {'DM_ROOT': work, 'DM_ROMFS': game / 'RomFS', 'DM_SAVE': rd / 'save', 'DM_TEMP': rd / 'temp', 'DM_MSL_DIR': msl, 'DM_FONT_DIR': font}
+ renv = {'DM_ROOT': work, 'DM_ROMFS': rfs.source(game), 'DM_SAVE': rd / 'save', 'DM_TEMP': rd / 'temp', 'DM_MSL_DIR': msl, 'DM_FONT_DIR': font}
if aoc: renv['DM_AOC_DIR'] = aoc
if gfx == 'nvn': renv['DM_NVN_SHMAP'] = g.table('shader_map.tsv')
renv.update(DM_LANG=lang, DM_WINDOW=1, DM_AUDIO=1)
@@ -1801,7 +1817,7 @@ def mac_app(py, repo, out, app, work, game, patched, host, font, msl, aoc, gfx,
lib = msl / (f'b-{chain_of(repo)}' if gfx == 'nvn' else 'vk' if gfx == 'vulkan' else 'gl')
pso = mac_pso(py, repo, work, lib, g, gpus, env, logs) if gfx == 'nvn' and g.table('shader_pairs.tsv').is_file() else None # a stage of its own, before the app's
PROG.stage('Mac app', step='starting')
- cmd = [py, repo / 'dm/mac/pack_app.py', out, '--host', host, '--patched', patched, '--romfs', game / 'RomFS', '--msl', lib, '--tables', g.table('shader_map.tsv').parent,
+ cmd = [py, repo / 'dm/mac/pack_app.py', out, '--host', host, '--patched', patched, '--romfs', rfs.source(game), '--msl', lib, '--tables', g.table('shader_map.tsv').parent,
'--font', font, '--title-id', f'{app:016X}', '--name', name, '--bundle-id', bundle_id, '--lang', lang, '--sign', sign or '-']
split_pairs = work / 'shader/pso_pairs.tsv' # the split's copy of pso_pairs.tsv, for a profile without the table (as mac_run's DM_PSO_PAIRS)
for opt, v in (('--version', version), ('--category', g.get('app_category')), ('--marker', g.get('romfs_marker')), ('--aoc', aoc), ('--icon', icon),
@@ -1892,6 +1908,7 @@ def main(args=None):
global ALLOW_SHADER_REGRESSIONS; ALLOW_SHADER_REGRESSIONS = args.allow_shader_regressions or ALLOW_SHADER_REGRESSIONS
global ALLOW_OTHER_METAL; ALLOW_OTHER_METAL = args.allow_other_metal or ALLOW_OTHER_METAL
here = Path(globals().get('__file__') or sys.argv[0]).resolve()
+ if sys.version_info < (3, 12): raise BuildError('Direct RomFS image builds require Python 3.12 or newer')
repo = find_repo(here)
prepare_xcode = args.prepare_xcode or PREPARE_XCODE
platform = args.platform or PLATFORM
@@ -2010,18 +2027,17 @@ def main(args=None):
picks = pick_nsps(fam, have, versions)
ex = work / 'extract'; ex.mkdir(parents=True, exist_ok=True); (work / 'tmp').mkdir(exist_ok=True)
- gb = sum({p.stat().st_size for b, u in picks.values() for p in (b, u) if p}) / 2**30 + 6 # extraction + shader cache + slack
+ gb = extract_bytes(picks, False) / 2**30 + 6 # every merged image is complete, including on APFS; shader cache + slack
if free_gb(work) < gb and not all((ex / v).exists() for v in versions): raise BuildError(f'less than {gb:.0f} GB free on the volume of {work}')
heapck = provisional and HEAP_CHECK and not args.no_heap_check and not heap_checked(g) # the heap check, when the game needs one (once per provisional profile: it stamps the profile)
PROG.plan(1 + len(versions) + bool(fam['dlc']) + 4 - (prepare_xcode or (mac and not mac_pack))) # prepare Xcode (a Mac-only build: the Mac host) replaces app build + IPA pack with one stage (a Mac app: Mac host + Mac app)
PROG.stage('build nx_extract')
nx = build_nx_extract(repo, work, logs, env)
PROG.end()
- dirs, clone = {}, None
- for ver in versions: # the base game is extracted alone first; later updates clone against its RomFS
+ dirs = {}
+ for ver in versions: # each merged version streams directly into its own image
b, u = picks[ver]
- dirs[ver] = extract(nx, keys, ex, ver, b, u, clone, logs, g)
- if u is None and clone is None and can_clone(ex): clone = dirs[ver] / 'RomFS'
+ dirs[ver] = extract(nx, keys, ex, ver, b, u, None, logs, g)
bad = [] if derived else [f'{v}: {x}' for v in versions for x in build_mismatch(dirs[v], v, g)] # every module's build ID must be the one the profile registers for its version
if bad and provisional: raise BuildError(f'not the builds provisional game profile {g.id} registers: {"; ".join(bad)}')
if bad: # files of other builds under a registered version's tag: packed like any other version
@@ -2039,7 +2055,7 @@ def main(args=None):
sv = versions if derived else need # the versions whose files the shaders come from
game = dirs[pkg_ver]
# how the shaders are got follows from the packed version's files (profile_guess.py shader_sources): the graphics API, and the shaders made only at run time
- src = pg.build_sources(game / 'ExeFS', game / 'RomFS', g.words('modules'))
+ src = pg.build_sources(game / 'ExeFS', rfs.source(game), g.words('modules'))
gfx = src['graphics'][0] # nvn, vulkan (Hades: the host's Vulkan layer, SPIR-V shaders) or gl (Digimon Story Cyber Sleuth: the host's GL layer, GLSL sources)
glslc = gfx == 'nvn' and src['glslc_capture'][0] # shaders the game compiles at run time, captured in the Mac host (capture_glslc)
vkcap = gfx == 'vulkan' and src['vk_capture'][0] # SPIR-V shaders the game generates at run time, captured in the Mac host (capture_shaders)
@@ -2052,7 +2068,7 @@ def main(args=None):
if on: say(src[k][1])
PROG.add(glslc + vkcap + glcap + uedec + (gfx == 'nvn'))
aoc = extract_aoc(nx, keys, repo, work, app, fam, logs)
- dlc_roms = sorted(p for p in aoc.iterdir() if p.is_dir()) if aoc else []
+ dlc_roms = sorted(p for p in aoc.iterdir() if p.is_dir() or p.suffix == '.img') if aoc else []
base = next((dirs[v] for v in versions if picks[v][1] is None), dirs[versions[0]]) # the folder the base game was extracted to alone
# the app name and bundle ID both come from the base NSP: the game name in its control data, and a bundle ID from its title ID; a setting / the command line overrides them
app_name = args.app_name or APP_NAME or nacp.name(base / 'control.nacp')
@@ -2086,10 +2102,10 @@ def main(args=None):
sh = work / 'shader'
if gfx == 'vulkan': # the packed version's merged RomFS holds the SPIR-V files the game loads; a capture holds those it generates
cap = capture_shaders(repo, game, patched, work, env, logs, g, 'vk') if vkcap else None
- ios = build_vk_shaders(py, repo, [game / 'RomFS'] + dlc_roms + ([cap] if cap else []), sh, env, logs, g, reuse=not ALLOW_DAMAGED, mac=mac, provisional=bool(provisional or derived))
+ ios = build_vk_shaders(py, repo, [rfs.source(game)] + dlc_roms + ([cap] if cap else []), sh, env, logs, g, reuse=not ALLOW_DAMAGED, mac=mac, provisional=bool(provisional or derived))
elif gfx == 'gl': # the GLSL sources in the packed version's archives and in its main (the game compiles them at run time; the host finds each by the hash of its text), and a capture of those it puts together
cap = capture_shaders(repo, game, patched, work, env, logs, g, 'gl') if glcap else None
- ios = build_gl_shaders(py, repo, [game / 'RomFS', game / 'ExeFS/main'] + dlc_roms + ([cap] if cap else []), sh, env, logs, g, reuse=not ALLOW_DAMAGED, mac=mac, provisional=bool(provisional or derived))
+ ios = build_gl_shaders(py, repo, [rfs.source(game), game / 'ExeFS/main'] + dlc_roms + ([cap] if cap else []), sh, env, logs, g, reuse=not ALLOW_DAMAGED, mac=mac, provisional=bool(provisional or derived))
else:
# Trinity packs and legacy Unreal paks: the split decodes them with the packed version's own decoder (Oodle, LZ5), in the Mac host built for the profile
oodle = (lambda: {'DM_OODLE_HOST': str(build_mac_host(repo, work / 'tools/dmhost', env, logs, g)), 'DM_OODLE_MODULES': str(patched)}) if src['oodle_packs'][0] or src['ue_legacy'][0] else None
@@ -2105,7 +2121,7 @@ def main(args=None):
g = gamemod.load(g.id)
say(f'{derived}: using a shader-only derived profile at {g.dir}; registered module fixes are preserved')
return g
- pkey = split_shaders(py, repo, [dirs[v] / 'RomFS' for v in sv], [dirs[v] / 'ExeFS/main' for v in sv], sh / 'pkg', env, logs, g, own, oodle, dlc_roms, derive_installed_dlc if not own else None)
+ pkey = split_shaders(py, repo, [rfs.source(dirs[v]) for v in sv], [dirs[v] / 'ExeFS/main' for v in sv], sh / 'pkg', env, logs, g, own, oodle, dlc_roms, derive_installed_dlc if not own else None)
ios = build_shaders(py, repo, sh, xlate, env, logs, g, pkey, mac)
icon = next((d / 'icon.jpg' for d in (game, base) if (d / 'icon.jpg').exists()), None) # the game icon nx_extract saved from the control data (English, icon.jpg); the packed version's first, then the base game's
if mac_pack: # a Mac app: the Mac host, then the app packed from it and the build's files
@@ -2129,7 +2145,7 @@ def main(args=None):
if not prepare_xcode and free_gb(out_ipa.parent) < 5: raise BuildError(f'less than 5 GB free on the volume of {out_ipa.parent}')
say('preparing the Xcode project' if prepare_xcode else f'building the IPA → {out_ipa}')
- ipa_env = dict(env, GAME=g.id, W=str(work / 'ipa'), PATCHED=str(patched), ROMFS=str(game / 'RomFS'), MSL_IOS=str(ios), GFXAPI=gfx, FONT_PY=py, DM_DISPLAY_NAME=app_name, DM_BUNDLE_ID=bundle_id, AOC=str(aoc or ''), DM_XCODE_DERIVED_DATA=str(work / 'xcode-derived-data'), DM_TEAM_ID=team_id, DM_LANG=lang)
+ ipa_env = dict(env, GAME=g.id, W=str(work / 'ipa'), PATCHED=str(patched), ROMFS=str(rfs.source(game)), MSL_IOS=str(ios), GFXAPI=gfx, FONT_PY=py, DM_DISPLAY_NAME=app_name, DM_BUNDLE_ID=bundle_id, AOC=str(aoc or ''), DM_XCODE_DERIVED_DATA=str(work / 'xcode-derived-data'), DM_TEAM_ID=team_id, DM_LANG=lang)
if prepare_xcode: ipa_env['DM_XCODE_PROJECT_DIR'] = str(project.parent)
if app_version: ipa_env['DM_APP_VERSION'] = app_version
if icon: ipa_env['DM_ICON'] = str(icon); say(f'app icon: {icon}') # app icon (found above)
diff --git a/scripts/push_romfs.sh b/scripts/push_romfs.sh
new file mode 100644
index 00000000..4cf553ed
--- /dev/null
+++ b/scripts/push_romfs.sh
@@ -0,0 +1,19 @@
+#!/bin/bash
+# Copy a game's files to its iPhone app's Documents/romfs.img once, so later installs built with DM_COPY_ROMFS=NO skip them (see docs/development.md, Quick reinstalls).
+# The files go as one RomFS image (dm/tools/romfs_image.py), packed next to the RomFS folder on first use: one file copies at full speed, where a folder of a few hundred
+# thousand files ran the phone's file service out of open files (Tears of the Kingdom: 304,000). main.m only takes a complete image, so a copy cut off halfway is never used.
+# Usage: push_romfs.sh <device UDID> <bundle ID> <game>_build/xcode/Gen/resources.env [--repack]
+# Run it while the app (any build with that bundle ID) is installed. Rerun after a failure.
+set -eu
+[ "$#" = 3 ] || { [ "$#" = 4 ] && [ "$4" = --repack ]; } || { echo "usage: $0 <device UDID> <bundle ID> <resources.env> [--repack]" >&2; exit 1; }
+dev=$1 id=$2; source "$3"
+if [ -f "$DM_RESOURCE_ROMFS" ]; then img=$DM_RESOURCE_ROMFS
+else
+ img=${DM_RESOURCE_ROMFS%/}.img
+ repack=${4:-}; set -- "$DM_RESOURCE_ROMFS" "$img"
+ [ "$repack" = --repack ] || set -- --reuse "$@"
+ python3 -I "$(dirname "$0")/../dm/tools/romfs_image.py" "$@"
+fi
+python3 -I "$(dirname "$0")/../dm/tools/romfs.py" "$img" "${DM_RESOURCE_MARKER:-}"
+xcrun devicectl device copy to --device "$dev" --domain-type appDataContainer --domain-identifier "$id" --source "$img" --destination Documents/romfs.img -q
+echo "game files on the phone: $id"
diff --git a/scripts/regress.py b/scripts/regress.py
index 31567679..d2b552b1 100644
--- a/scripts/regress.py
+++ b/scripts/regress.py
@@ -175,8 +175,8 @@ class Game:
self.derived = (build / 'profile' / self.id / 'game.tsv').is_file()
def romfs(self):
- r = self.build / 'extract' / self.ver / 'RomFS'
- return r if r.is_dir() else bench.newest(self.build.glob('extract/v*')) / 'RomFS'
+ r = bench.rfs.source(self.build / 'extract' / self.ver)
+ return r if r.is_dir() else bench.rfs.source(bench.newest(self.build.glob('extract/v*')))
def route(self):
f = REPO / 'dm/games' / self.id / 'smoke.tsv'
diff --git a/scripts/sync_upstream.py b/scripts/sync_upstream.py
index 893559f3..2b63a199 100644
--- a/scripts/sync_upstream.py
+++ b/scripts/sync_upstream.py
@@ -40,11 +40,15 @@ OURS = {'dm/host/romfs_arc.c', 'dm/host/romfs_arc.h', 'dm/tools/romfs_arc.py',
# silently drop the fix (issue #29, found by v0lumehi reading the sync script). If upstream
# takes seedds PR for it, these leave OURS and come back with the sync instead.
'dm/host/hle_time.c', 'dm/host/tests/t_time.c',
+ # dm/games/game.py carries the tex_bc_cpu profile key and the 'profile' subcommand that
+ # writes the runtime profile; both are fork-only, so the file is never taken from upstream
+ # (a verify-only patcher was not enough: the sync replaced it first and then complained).
+ 'dm/games/game.py',
'dm/gfx/tex/tests/t_bcdec.c'}
# Vendored files that carry fork patches: taken fresh from upstream, then patched below.
PATCHED = ('dm/host/hle_fs.c', 'dm/host/Makefile', 'dm/host/tests/Makefile', 'dm/ios/tools/build_ipa.sh',
'scripts/build_ipa_from_nsp.py', 'dm/gfx/tools/shader_split.py',
- 'dm/ios/Sources/main.m', 'dm/gfx/nvn/nvn_mtl.m', 'dm/games/game.py', 'dm/host/dm.h')
+ 'dm/ios/Sources/main.m', 'dm/gfx/nvn/nvn_mtl.m', 'dm/host/dm.h')
def git(*a):
r = subprocess.run(['git', *a], cwd=REPO, capture_output=True, text=True)
@@ -855,22 +859,6 @@ def patch_main_m(t):
done(f'main.m {name}')
return t
-def patch_game_py(t):
- """dm/games/game.py carries two fork additions: the tex_bc_cpu profile key (BC decode for
- GPUs without BC support) and the 'profile' subcommand that writes the runtime profile the
- host reads from DM_PROFILE. Both are needed by other fork files, so a sync must keep them.
- """
- if "a[0] == 'profile'" in t and 'tex_bc_cpu' in t: return skip('game.py (already patched)')
- bad = []
- if "'profile'" not in t:
- bad.append('profile subcommand')
- if 'tex_bc_cpu' not in t:
- bad.append('tex_bc_cpu')
- if bad: fail(f'dm/games/game.py: fork additions missing: {", ".join(bad)} '
- '(the sync replaced this file with a version without them; re-apply by hand)')
- return skip('game.py (fork additions present)')
-
-
def patch_dm_h(t):
"""dm.h pulls in hle_profile.h, so every host source can call dm_profile().
@@ -914,7 +902,6 @@ MARKERS = {
'dm/gfx/nvn/nvn_mtl.m': 'if (on_sub_thread()) rec_publish();',
'dm/games/0100A00019DE0000/game.tsv': 'build v1 1.0.137848',
'dm/host/dm.h': 'hle_profile.h',
- 'dm/games/game.py': "elif len(a) == 3 and a[0] == 'profile':",
}
PATCHERS = {
'dm/host/hle_fs.c': patch_hle_fs,
@@ -927,7 +914,6 @@ PATCHERS = {
'dm/gfx/nvn/nvn_mtl.m': patch_nvn_mtl,
'dm/games/0100A00019DE0000/game.tsv': patch_hades2,
'dm/host/dm.h': patch_dm_h,
- 'dm/games/game.py': patch_game_py,
}
report, problems = [], []