From e1eb5acc43e822c3a857eadb98d8c76e930763e6 Mon Sep 17 00:00:00 2001 From: Adrian Smith Date: Sat, 7 Nov 2026 02:47:51 +1030 Subject: [PATCH 1/2] Probes: DM_PROBE_EVERY=N counts every hit and prints every N-th, its # the true hit count (rates of a loop's branches without a line per hit) --- dm/host/probe.c | 8 +++++--- docs/env_switches.tsv | 1 + 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/dm/host/probe.c b/dm/host/probe.c index b6dc4c461b..b2804f6b07 100644 --- a/dm/host/probe.c +++ b/dm/host/probe.c @@ -22,7 +22,7 @@ void crash_set_trap_hook(int (*fn)(ucontext_t *uc)); // The trampoline borrows x16: place probes only at function entries or at points where x16 is dead; the original instruction must not be PC-relative (adr/adrp/b/bl/ldr literal/cbz...). #define MAX_PROBE 16 typedef void (*probe_fn)(ucontext_t *uc); -static struct { uint64_t at; uint32_t *slot; unsigned hits; char name[40]; long dump, dpost; probe_fn fn; int freg; long foff; uint64_t fval; int hreg; } g_probe[MAX_PROBE]; // dpost: @*xN+off+dpost +static struct { uint64_t at; uint32_t *slot; unsigned hits, seen; char name[40]; long dump, dpost; probe_fn fn; int freg; long foff; uint64_t fval; int hreg; } g_probe[MAX_PROBE]; // dpost: @*xN+off+dpost // !xN: treat xN as a sead::ExpHeap and print its free and used blocks (block size at block +0x18, alignment pad at +0x12). Settings (docs/agents/05-debugging.md): // DM_PROBE_HEAP=,,,, layout by sead version (hex; node offset at list +0x14), default SMBW 0,28,30,b0,c8 (no name), BotW 28,38,40,e0,f8; @@ -78,7 +78,7 @@ static void probe_heapwalk(uint64_t h) { } // dump: on hit print 16 bytes at [x0+dump] (-1 = do not print); fn: dedicated handler (replaces the default print) static int g_nprobe; static uint64_t g_probe_frame_first, g_probe_frame_last = UINT64_MAX; -static unsigned g_probe_limit; +static unsigned g_probe_limit, g_probe_every; // DM_PROBE_LIMIT printed hits per probe; DM_PROBE_EVERY=N every hit counts, every N-th prints (#N is then the true hit count: rates) uint64_t dm_guest_frame(void); static void probe_str(uint64_t p) { char buf[80]; vm_size_t got = 0; @@ -112,6 +112,7 @@ static int probe_hit(ucontext_t *uc) { // Registered by probe_install with the for (int i = 0; i < g_nprobe; i++) if (g_probe[i].at == pc) { if (g_probe[i].fn) { g_probe[i].hits++; g_probe[i].fn(uc); uc->uc_mcontext->__ss.__pc = (uint64_t)g_probe[i].slot; return 1; } uint64_t frame = dm_guest_frame(); + if (g_probe_every && frame >= g_probe_frame_first && frame <= g_probe_frame_last && ++g_probe[i].seen % g_probe_every) { uc->uc_mcontext->__ss.__pc = (uint64_t)g_probe[i].slot; return 1; } if (frame < g_probe_frame_first || frame > g_probe_frame_last || (g_probe_limit && g_probe[i].hits >= g_probe_limit)) { uc->uc_mcontext->__ss.__pc = (uint64_t)g_probe[i].slot; return 1; } @@ -126,7 +127,7 @@ static int probe_hit(ucontext_t *uc) { // Registered by probe_install with the } probe_dump_once(); flockfile(stderr); // One block per hit when threads hit at once - { extern uint64_t g_t0_ns; uint64_t now_ns(void); uint32_t thr_cur_handle(void); fprintf(stderr, "[dm] PROBE %s #%u [%.4fs] F=%llu T=%x", g_probe[i].name, ++g_probe[i].hits, (now_ns() - g_t0_ns) / 1e9, (unsigned long long)frame, thr_cur_handle()); } + { extern uint64_t g_t0_ns; uint64_t now_ns(void); uint32_t thr_cur_handle(void); ++g_probe[i].hits; fprintf(stderr, "[dm] PROBE %s #%u [%.4fs] F=%llu T=%x", g_probe[i].name, g_probe_every ? g_probe[i].seen : g_probe[i].hits, (now_ns() - g_t0_ns) / 1e9, (unsigned long long)frame, thr_cur_handle()); } for (int r = 0; r < 8; r++) { uint64_t v = uc->uc_mcontext->__ss.__x[r]; fprintf(stderr, " x%d=%#llx", r, v); probe_str(v); } for (int r = 19; r < 24; r++) fprintf(stderr, " x%d=%#llx", r, uc->uc_mcontext->__ss.__x[r]); if (getenv("DM_PROBE_ALL")) for (int r = 8; r < 19; r++) fprintf(stderr, " x%d=%#llx", r, uc->uc_mcontext->__ss.__x[r]); // also print x8–x18 @@ -381,6 +382,7 @@ void probe_install(void) { } const char *limit = getenv("DM_PROBE_LIMIT"); if (limit) g_probe_limit = (unsigned)strtoul(limit, NULL, 10); + if ((limit = getenv("DM_PROBE_EVERY"))) g_probe_every = (unsigned)strtoul(limit, NULL, 10); const char *e = getenv("DM_PROBE"); if (e) { char spec[512]; strlcpy(spec, e, sizeof spec); diff --git a/docs/env_switches.tsv b/docs/env_switches.tsv index 71a188769d..3b1f01cf0b 100644 --- a/docs/env_switches.tsv +++ b/docs/env_switches.tsv @@ -245,6 +245,7 @@ DM_PREV_PROGRAM switch What `oe::GetPreviousProgramIndex` answers (default -1, s DM_PROBE diagnostic `=module:offset,…` (Mac only): puts a `brk` at each guest address and on every hit prints the thread, registers, strings they point to and a backtrace, then runs the original instruction DM_PROBE_ALL diagnostic Set: probe hits (`DM_PROBE`) also print x8–x18 DM_PROBE_DUMP diagnostic `=module:offset:length[:file]`: on the first hit of any probe, writes that range of guest memory to a file (default `run//probe_dump.bin`) +DM_PROBE_EVERY diagnostic `=N`: every guest probe hit inside `DM_PROBE_FRAMES` counts, every N-th prints (its `#` is then the true hit count, for rates); `DM_PROBE_LIMIT` caps the printed ones DM_PROBE_FRAMES diagnostic Presented frame or inclusive `start-end` range in which guest probes print observations DM_PROBE_HEAP diagnostic `=,,,,`: hex offsets of the sead heap layout the probes' `!xN` heap walk uses (default Mario's `0,28,30,b0,c8`) DM_PROBE_HEAPFRAME diagnostic `=` (hex): the probes' heap walk treats heaps of that class as frame heaps (head +0xe0, tail +0xe8) From c7aab3ff982335c9d479d563672e40b400dc8482 Mon Sep 17 00:00:00 2001 From: Adrian Smith Date: Sat, 7 Nov 2026 02:54:32 +1030 Subject: [PATCH 2/2] RomFS image: a .zs file that is not a zstd stream is served as the profile's romfs_substitute, else "not found"; Ocarina of Time's three damaged textures substituted The Ocarina of Time NUP at hand holds Tex/CmnTex_Map_Soil_FairyFountain_Floor_D_Nrm.bntx.zs, Tex/Rock_WaterTemple_Gate_M_01_Nrm.bntx.zs and Tex/RBake_Scene_GanonStage_G_2_1_d0_t0.bntx.zs with their first 12 KB zeroed (the container's SHA-256 of them matches, so they were so when it was packed; whether a retail copy has them is not known). The first kept the Kokiri Forest fairy fountain model from loading, so the OptimizeChangeBanc thread (main+0xf7a0, priority 55) never finished its pass over the area's 852 entries and asked for the model again ~22 times a second for the whole session: ~980 ms/s of CPU on the Mac and the iPad, plus ~750 ms/s of ParallelDecompThread decompressing the 2.4 MB model each time. hle_fs.c img_serve checks a .zs image file's first 4 bytes once (open and entry type). A damaged one is served as the substitute the new profile key romfs_substitute names (DM_ROMFS_SUBST overrides; DM_ROMFS_ZSTD_CHECK=0 serves it as stored), else answered "not found" ("not found" alone still fails the model). Ocarina of Time's profile serves the two normal maps as the game's own 1x1 flat normal and the Ganon stage bake as its neighbour cell's. Mac, 5-minute runs in Kokiri Forest, windows from frame 5000: CPU 412% -> 180%, OptimizeChangeBanc and ParallelDecompThread out of the top five (idle after frame ~3900), frame p50 17.7 -> 17.3 ms, p95 21.9 -> 18.8, submit CPU 8.9 -> 5.7 ms a frame. Test: t_fs (148 checks). Documented in docs/reference/packing.md (symptom index regenerated). --- dm/games/0400486024DEC000/README.md | 2 + dm/games/0400486024DEC000/game.tsv | 7 ++++ dm/games/README.md | 1 + dm/games/game.py | 3 ++ dm/host/hle_fs.c | 59 ++++++++++++++++++++++++++++- dm/host/tests/t_fs.c | 22 +++++++++++ docs/agents/symptoms.md | 1 + docs/env_switches.tsv | 2 + docs/reference/packing.md | 7 ++++ 9 files changed, 103 insertions(+), 1 deletion(-) diff --git a/dm/games/0400486024DEC000/README.md b/dm/games/0400486024DEC000/README.md index 13c8fb21a3..8d8d3b021d 100644 --- a/dm/games/0400486024DEC000/README.md +++ b/dm/games/0400486024DEC000/README.md @@ -20,6 +20,8 @@ A Switch 2 game: update v131072, SDK 22.2.8 (`Ounce`). Nintendo EPD's engine (se One [NUP container](../../../docs/development.md#the-packing-script-in-detail) of 25.6 GB: `scripts/pack_nup.py` unpacks it to `extract/v131072/`. The RomFS keeps most files as zstd with dictionaries from `Pack/ZsDic.pack.zs`. The movies are AV1. +The NUP at hand has three damaged files: `Tex/CmnTex_Map_Soil_FairyFountain_Floor_D_Nrm.bntx.zs`, `Tex/Rock_WaterTemple_Gate_M_01_Nrm.bntx.zs` and `Tex/RBake_Scene_GanonStage_G_2_1_d0_t0.bntx.zs` begin with 12 KB of zeros (the container's SHA-256 of them matches, so they were so when it was packed; whether a retail copy has them is not known; the other 102,182 `.zs` files begin with a zstd frame). The first kept the Kokiri Forest fairy fountain model from ever loading: the `OptimizeChangeBanc` thread asked for it ~22 times a second all session (one core) and a `ParallelDecompThread` decompressed its 2.4 MB each time (~0.75 core). The profile key `romfs_substitute` serves them as the game's 1x1 flat normal map (the Ganon stage bake as its neighbour cell's): Mac CPU 412% → 180%, frame p95 21.9 → 18.8 ms ([A `.zs` file that is not a zstd stream](../../../docs/reference/packing.md#a-zs-file-that-is-not-a-zstd-stream)). + ## Shaders - About 42,850 in [`shader_map.tsv`](shader_map.tsv), including 500 mesh and 20 task shaders in the BNSH programs ([Task and mesh shaders in BNSH](../../../docs/reference/shaders.md#task-and-mesh-shaders-in-bnsh-and-indirect-mesh-draws)), and the movie library's in an NDVE pack ([`nn::ndve`](../../../docs/reference/shaders.md#nnndves-movie-enhancement-file)). diff --git a/dm/games/0400486024DEC000/game.tsv b/dm/games/0400486024DEC000/game.tsv index f09f807dd9..63601dc43b 100644 --- a/dm/games/0400486024DEC000/game.tsv +++ b/dm/games/0400486024DEC000/game.tsv @@ -22,6 +22,13 @@ modules main subsdk0 sdk romfs_marker Pack/ZsDic.pack.zs zip_store .zs:.bwav:.webm:.metallib +# In the NUP at hand three RomFS files begin with 12 KB of zeros (the container's SHA-256 of them matches, so they were so when it was packed; whether a retail copy has them is not known), so they cannot be decompressed. Served as stored, the fairy +# fountain model that uses the first never loaded and the OptimizeChangeBanc thread (main+0xf7a0) asked for it again ~22 times a second all session: one core, plus ~0.75 core of +# ParallelDecompThread decompressing the 2.4 MB model each time (Mac CPU 365%, iPad 400-460%). "Not found" fails the model the same way. Served as the game's own 1x1 flat normal map, the +# model loads once and both threads go idle (Mac CPU 412% -> 180%, frame p95 21.9 -> 18.8 ms). The Ganon stage bake is served as its neighbour cell's (not checked in game). A copy without the damage +# needs none of this: the host substitutes only a .zs file that is not a zstd stream (hle_fs.c img_serve) +romfs_substitute Tex/CmnTex_Map_Soil_FairyFountain_Floor_D_Nrm.bntx.zs=Tex/Dummy_Flat_Normal_CmnTex_Chara_DetailMap_Nrm.bntx.zs Tex/Rock_WaterTemple_Gate_M_01_Nrm.bntx.zs=Tex/Dummy_Flat_Normal_CmnTex_Chara_DetailMap_Nrm.bntx.zs Tex/RBake_Scene_GanonStage_G_2_1_d0_t0.bntx.zs=Tex/RBake_Scene_GanonStage_G_2_2_d0_t0.bntx.zs + # ---- Memory ---- # The Switch 2 leaves games 9 GB of its 12 GB (Donkey Kong Bananza's figure). The NPDM declares 48 MB of system resource, so virtual address memory is on. # nninitStartup asks SetHeapSize 0x18ce00000 (6.2 GB) with the 9 GB pool, as Mario Kart World. 256 MB in front + 4 GB alias region + 256 MB stack region + 8 GB heap region: a starting split, to be measured diff --git a/dm/games/README.md b/dm/games/README.md index 02aa26df93..1f2376923c 100644 --- a/dm/games/README.md +++ b/dm/games/README.md @@ -243,6 +243,7 @@ One row per profile; the notes are each profile's `README.md`. | `gpu_timestamps` | What a timestamp report (`nvnCommandBufferReportCounter`) records: `submission` (the default) = the time the whole submission completed, the same for every report in it; `segment` = the GPU start (`TIMESTAMP_TOP`) or end (the other types) of the segment the report was encoded in (the host commits a submission in segments of 64 draws, `sub_cut` in `nvn_mtl.m`), so two reports of one submission bracket the GPU time between them, as on hardware. Breath of the Wild needs `segment`: its frame-interval controller and its dynamic resolution read the GPU time between the frame's first and last report, and with one time for both they read 0 (the game kept 60 fps in slow motion when the GPU could not keep up). `DM_NVN_GPU_TS=segment` / `submission` overrides it, also from `Documents/env.txt` | | `draw_barriers` | `full` (the default) / `game`: how draw passes are ordered. `full`: each waits for all earlier GPU work. `game`: by the game's own barriers (NVN asks for one before results of rendering are read), so a pass's vertex work overlaps the previous pass's fragments. Ocarina of Time's GPU time 25 → 18 ms, about 180 full barriers a frame halved. Only vertex-stage reads of the previous pass's output without a barrier change order. `DM_NVN_BARRIER` overrides it | | `vconv_range` | `on` / `off` (the default): vertex attributes the replay converts on the CPU (integer shader inputs fed float-type formats and the like, `vconv_bind` in `nvn_mtl.m`) are converted only over the vertices each draw reads (first / count, or the smallest and largest index of a direct indexed draw, kept while the index pages stay unwritten) instead of the whole bound range. Age of Calamity binds whole mesh pools: in a battle that was millions of vertices a frame. Indirect draws, per-instance streams and indices with a GPU write queued on them keep the whole range. `DM_NVN_VCONV_CHECK=1` scans the indices again at every reuse and reports differences; `DM_NVN_VCONV_RANGE=0` / `1` overrides it | +| `romfs_substitute` | `=` pairs, RomFS paths without a leading `/` (none by default): a RomFS image file named `*.zs` that does not begin with a zstd frame (damaged) is served as the other image file (`hle_fs.c` `img_serve`; `DM_ROMFS_SUBST` replaces the list); one without a substitute is answered "not found". Ocarina of Time: three textures of the NUP at hand begin with 12 KB of zeros; the fairy fountain's normal map, served as the game's 1x1 flat normal, ends the OptimizeChangeBanc reload loop (one core all session). | | `shader_key_skip` | `+` (none by default): control-section bytes every shader key hashes as zeros, in `shader_split.py` (`key_ctl`) and the host (`hle_nvn.c` `keys_hash`), for an engine that shares one control section among shaders that differ only there. Batman: Arkham Knight: `0x770+0x78`, GLSLC's compile information (+0x778..+0x791 and +0x7d0..+0x7e7); without it the game asks for shaders the map does not have, each the control section of one record with the code area of another. It must stay clear of `+0x700..+0x75f`, which the tools read; it is a shader chain input, as every `shader_*` key | | `shader_groups`, `shader_note` | `shader_split.py` source groups and the map header note (Engage: `engine` for `data.unity3d` and `Resources/`, `assets` for the Addressables bundles). Both are shader inputs, the note too: changing either one, even by a word, builds every shader of the game again. Keep them as they are when a provisional profile moves into `dm/games` | diff --git a/dm/games/game.py b/dm/games/game.py index 53e23ee897..5324c8cd4b 100644 --- a/dm/games/game.py +++ b/dm/games/game.py @@ -208,6 +208,8 @@ def header_one(g): if dbr not in ('full', 'game'): sys.exit(f'{g.id}: draw_barriers must be full or game: {dbr}') gts = g.get('gpu_timestamps', 'submission') # counter timestamps (nvn_mtl.m rep_ticks): submission = one time per submission, segment = the GPU start / end of the segment holding the report if gts not in ('submission', 'segment'): sys.exit(f'{g.id}: gpu_timestamps must be submission or segment: {gts}') + rsub = ' '.join(g.get('romfs_substitute', '').split()) # damaged RomFS files (a .zs that is not a zstd stream) served as another image file (hle_fs.c img_serve; DM_ROMFS_SUBST overrides): = ... + if any(w.count('=') != 1 or w.startswith(('=', '/')) or w.endswith('=') or '=/' in w for w in rsub.split()): sys.exit(f'{g.id}: romfs_substitute takes = pairs, RomFS paths without a leading /: {rsub}') om = g.get('op_mode', 'console') # the operation mode reported at start (hle_oe.c dm_opmode; DM_OPMODE overrides): console = docked, handheld = touch screen in use (Super Mario Galaxy's pointer) if om not in ('console', 'handheld'): sys.exit(f'{g.id}: op_mode must be console or handheld: {om}') if pl == 'touch' and om != 'handheld': sys.exit(f'{g.id}: pad_layout touch needs op_mode handheld (the touch screen reaches the game only in handheld mode)') @@ -265,6 +267,7 @@ def header_one(g): f'#define DM_GAME_DRAW_BARRIERS_GAME {int(dbr == "game")}', f'#define DM_GAME_UPSCALER_KEYS {q(",".join(ups))}', f'#define DM_GAME_UPSCALER_N {len(ups)}', f'#define DM_GAME_VCONV_RANGE {int(vcr == "on")}', + f'#define DM_GAME_ROMFS_SUBST {q(rsub)}', *([f'#define DM_GAME_NVN_API_MAJOR {api.split(".")[0]}', f'#define DM_GAME_NVN_API_MINOR {api.split(".")[1]}'] if g.get('device_api', '') else []), # without the key: by the SDK version (hle_nvn.c nvn_api) ''] return '\n'.join(L) diff --git a/dm/host/hle_fs.c b/dm/host/hle_fs.c index 34925534ce..f749e669d6 100644 --- a/dm/host/hle_fs.c +++ b/dm/host/hle_fs.c @@ -784,6 +784,62 @@ HLE_FORCE("_ZN2nn2fs7UnmountEPKc", "fsp-srv; host mounts are permanent, a no-op; } // ---------- Files ---------- +// A RomFS image file named *.zs that does not begin with a zstd frame (or a skippable frame) cannot be decompressed. Such a file is served as the substitute the profile key +// romfs_substitute names for it (= pairs, image paths without the mount; DM_ROMFS_SUBST replaces the profile's list), else answered "path not found", as a file +// the dump lacks; one [RED] line names it. Ocarina of Time (Switch 2), the NUP at hand: Tex/CmnTex_Map_Soil_FairyFountain_Floor_D_Nrm.bntx.zs, Tex/Rock_WaterTemple_Gate_M_01_Nrm.bntx.zs and +// Tex/RBake_Scene_GanonStage_G_2_1_d0_t0.bntx.zs begin with 12 KB of zeros (the container's SHA-256 of them matches: they were so when it was packed; whether a retail copy has them is not known). Served as stored, the fairy fountain model that uses +// the first (Model/Land_FairyFountain_Base_A.Land_FairyFountain_Base_A_01.bfres) failed to load, and the OptimizeChangeBanc thread (main+0xf7a0) asked for it again about 22 times a second for +// the whole session: its pass over the 852 entries of the area never ended "all done", so it never went back to its 16 ms sleep (one core, ~980 ms/s, on the Mac and the iPad), and a +// ParallelDecompThread decompressed the 2.4 MB model each time (~750 ms/s). "Not found" fails the model the same way (the game then asks for the .bntx, also missing); the game's own 1x1 flat +// normal map (Tex/Dummy_Flat_Normal_CmnTex_Chara_DetailMap_Nrm.bntx.zs) in its place loads the model once, and both threads go idle: Mac CPU 412% -> 180% (medians of 5-minute runs). +// Checked once per entry, at its first open or entry type (4 bytes); DM_ROMFS_ZSTD_CHECK=0 serves such files as stored +#define IMG_ENT_ZCHECKED 4 // in memory only: the zstd head check has run for this entry +#define IMG_ENT_BADZSTD 8 // in memory only: ... and found no zstd frame at the start +#ifndef DM_GAME_ROMFS_SUBST +#define DM_GAME_ROMFS_SUBST "" +#endif +static int64_t img_subst(mount_t *m, const char *path, const char **donor, int *dlen) { // the substitute entry for a damaged path (-1: none named, or not in the image) + const char *c = strchr(path, ':'), *rest = c ? c + 1 : path, *s = getenv("DM_ROMFS_SUBST"); + while (*rest == '/') rest++; + if (!s) s = DM_GAME_ROMFS_SUBST; + size_t rl = strlen(rest); + while (*s) { + while (*s == ' ' || *s == '\t') s++; + const char *end = s + strcspn(s, " \t"), *eq = memchr(s, '=', (size_t)(end - s)); + if (eq && (size_t)(eq - s) == rl && !memcmp(s, rest, rl)) { + char d[1024]; snprintf(d, sizeof d, "/%.*s", (int)(end - eq - 1), eq + 1); + if (donor) { *donor = eq + 1; *dlen = (int)(end - eq - 1); } + int64_t k = img_find(m->img, d); + return k > 0 && m->img->e[k].type ? k : -1; + } + s = end; + } + return -1; +} +// The entry to serve for entry k: k itself, a damaged file's substitute, or -1 (answered "not found") +static int64_t img_serve(mount_t *m, int64_t k, const char *path) { + img_ent *ent = &m->img->e[k]; + const char *nm = m->img->names + ent->name; + if (!ent->type || ent->nlen <= 3 || memcmp(nm + ent->nlen - 3, ".zs", 3)) return k; // other files keep their flags as they are + uint8_t f = __atomic_load_n(&ent->flags, __ATOMIC_ACQUIRE); + if (f & IMG_ENT_ZCHECKED) return f & IMG_ENT_BADZSTD ? img_subst(m, path, NULL, NULL) : k; + static int on = -1; if (on < 0) { const char *e = getenv("DM_ROMFS_ZSTD_CHECK"); on = !(e && *e == '0'); } + int bad = 0; int64_t r = k; + if (on && ent->b >= 4) { + uint8_t h[4]; + if (romfs_image_read(m->img->fd, h, 4, (off_t)ent->a)) { + uint32_t mg = (uint32_t)h[0] | (uint32_t)h[1] << 8 | (uint32_t)h[2] << 16 | (uint32_t)h[3] << 24; + bad = mg != 0xFD2FB528u && (mg & 0xFFFFFFF0u) != 0x184D2A50u; + if (bad) { + const char *d = NULL; int dl = 0; r = img_subst(m, path, &d, &dl); + if (r >= 0) LOG("[RED] fs %s is not a zstd stream (begins %02x %02x %02x %02x; damaged): served as %.*s (romfs_substitute)", path, h[0], h[1], h[2], h[3], dl, d); + else LOG("[RED] fs %s is not a zstd stream (begins %02x %02x %02x %02x; damaged): answered \"not found\"%s (DM_ROMFS_ZSTD_CHECK=0 serves it as stored)", path, h[0], h[1], h[2], h[3], d ? ", its substitute is not in the image" : ""); + } + } + } + __atomic_fetch_or(&ent->flags, (uint8_t)(IMG_ENT_ZCHECKED | (bad ? IMG_ENT_BADZSTD : 0)), __ATOMIC_RELEASE); + return r; +} HLE_FORCE("_ZN2nn2fs8OpenFileEPNS0_10FileHandleEPKci", "fsp-srv → open(2)", Result, h_fs_OpenFile, uint64_t *out, const char *path, int mode) { dm_thread_service_request(); int mi; int64_t k; if (img_path(path, &mi, &k)) { @@ -793,6 +849,7 @@ HLE_FORCE("_ZN2nn2fs8OpenFileEPNS0_10FileHandleEPKci", "fsp-srv → open(2)", Re img_ent *ent = &g_mnt[mi].img->e[k]; // a damaged file is named once, at its first open if ((ent->flags & IMG_ENT_DAMAGED) && !(__atomic_fetch_or(&ent->flags, IMG_ENT_REPORTED, __ATOMIC_RELAXED) & IMG_ENT_REPORTED)) LOG("[RED] fs %s failed the NCA's hash check when it was extracted (a damaged NSP, --allow-damaged); its bytes may be wrong", path); + if ((k = img_serve(&g_mnt[mi], k, path)) < 0) return RES_PATH_NOT_FOUND; *out = FH_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; @@ -982,7 +1039,7 @@ HLE_FORCE("_ZN2nn2fs10RenameFileEPKcS2_", "fsp-srv → rename(2)", Result, h_fs_ HLE_FORCE("_ZN2nn2fs15RenameDirectoryEPKcS2_", "fsp-srv → rename(2) of a directory", Result, h_fs_RenameDir, const char *from, const char *to) { dm_thread_service_request(); return rename_entry(from, to); } HLE_FORCE("_ZN2nn2fs12GetEntryTypeEPNS0_18DirectoryEntryTypeEPKc", "fsp-srv → stat(2)", Result, h_fs_GetEntryType, int32_t *out, const char *path) { dm_thread_service_request(); 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; } + if (img_path(path, &mi, &k)) { if (k < 0) return err_res("stat", path); if (img_serve(&g_mnt[mi], k, path) < 0) return RES_PATH_NOT_FOUND; *out = g_mnt[mi].img->e[k].type ? ENT_FILE : ENT_DIR; return RES_OK; } // a damaged .zs without a substitute is "not found" here too (img_serve) HP(path); struct stat st; if (stat(hp, &st)) return err_res("stat", hp); *out = S_ISDIR(st.st_mode) ? ENT_DIR : ENT_FILE; return RES_OK; diff --git a/dm/host/tests/t_fs.c b/dm/host/tests/t_fs.c index 75e1910282..fee3a66298 100644 --- a/dm/host/tests/t_fs.c +++ b/dm/host/tests/t_fs.c @@ -159,6 +159,28 @@ int main(void) { 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"); } + printf("RomFS image: a .zs file that is not a zstd stream\n"); // /data/x.zs = a zstd frame's magic, /data/y.zs = zeros (Ocarina of Time's NUP: three textures begin with 12 KB of zeros) + { uint8_t img[32 + 12 + 4 * 24 + 12] = {0}; uint64_t hd[3] = {44, 4 * 24 + 12, 4}; + img_ent e[4] = {{1, 1, 0, 0, 0, 0}, {2, 2, 0, 4, 0, 0}, {32, 6, 4, 4, 1, 0}, {38, 6, 8, 4, 1, 0}}; + memcpy(img, "DMROMFS1", 8); memcpy(img + 8, hd, sizeof hd); memcpy(img + 32, "\x28\xb5\x2f\xfd\x01\x02", 6); memcpy(img + 44, e, sizeof e); memcpy(img + 44 + sizeof e, "datax.zsy.zs", 12); + char ip[1100]; snprintf(ip, sizeof ip, "%s/zs.img", root); FILE *f = fopen(ip, "wb"); fwrite(img, 1, sizeof img, f); fclose(f); + g_nmnt = 0; setenv("DM_ROMFS", ip, 1); unsetenv("DM_ROMFS_OVERLAY"); CHECK(h_fs_MountRom("rom", NULL, 0) == RES_OK, "mount the image"); + uint64_t h; size_t n = 0; char b[8] = {0}; int32_t t = -1; + CHECK(h_fs_OpenFile(&h, "rom:/data/x.zs", MODE_READ) == RES_OK && h_fs_ReadFile(&n, h, 0, b, 6) == RES_OK && n == 6 && !memcmp(b, "\x28\xb5\x2f\xfd", 4), "a zstd stream opens and reads"); h_fs_CloseFile(h); + CHECK(h_fs_GetEntryType(&t, "rom:/data/x.zs") == RES_OK && t == ENT_FILE, "and is a file"); + CHECK(h_fs_GetEntryType(&t, "rom:/data/y.zs") == RES_PATH_NOT_FOUND, "a .zs file of zeros is not found by its entry type"); + CHECK(h_fs_OpenFile(&h, "rom:/data/y.zs", MODE_READ) == RES_PATH_NOT_FOUND && h_fs_OpenFile(&h, "rom:/data/y.zs", MODE_READ) == RES_PATH_NOT_FOUND, "nor opens, also the second time"); + CHECK(g_mnt[0].img->e[3].flags == (IMG_ENT_ZCHECKED | IMG_ENT_BADZSTD) && g_mnt[0].img->e[2].flags == IMG_ENT_ZCHECKED, "checked once each, in memory"); + g_nmnt = 0; + // a substitute named for it (the profile's romfs_substitute, here DM_ROMFS_SUBST): served in its place, also when the check ran before (the flags stay) + setenv("DM_ROMFS_SUBST", "data/q.zs=data/x.zs data/y.zs=data/x.zs", 1); CHECK(h_fs_MountRom("rom", NULL, 0) == RES_OK, "mount again with a substitute"); + memset(b, 0, sizeof b); n = 0; + CHECK(h_fs_OpenFile(&h, "rom:/data/y.zs", MODE_READ) == RES_OK && h_fs_ReadFile(&n, h, 0, b, 8) == RES_OK && n == 6 && !memcmp(b, "\x28\xb5\x2f\xfd\x01\x02", 6), "the damaged file reads as its substitute"); h_fs_CloseFile(h); + CHECK(h_fs_GetEntryType(&t, "rom:/data/y.zs") == RES_OK && t == ENT_FILE, "and is a file"); + setenv("DM_ROMFS_SUBST", "data/y.zs=data/none.zs", 1); + CHECK(h_fs_OpenFile(&h, "rom:/data/y.zs", MODE_READ) == RES_PATH_NOT_FOUND, "a substitute that is not in the image: not found"); + unsetenv("DM_ROMFS_SUBST"); g_nmnt = 0; + } 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/docs/agents/symptoms.md b/docs/agents/symptoms.md index b12851bff7..abb54f38d4 100644 --- a/docs/agents/symptoms.md +++ b/docs/agents/symptoms.md @@ -49,6 +49,7 @@ One line per symptom in the [subsystem references](../reference/): what you see - `nx_extract` stops with exit code 134 and `Unhandled exception. System.InvalidOperationException: The LinkedList is empty.` from `LibHac.Tools.FsSystem.CachedStorage.GetBlock`, with no `[RED] hash check failed` list, with or without `--allow-damaged`. → [Extraction of a damaged NSP ends in "The LinkedList is empty"](../reference/packing.md#extraction-of-a-damaged-nsp-ends-in-the-linkedlist-is-empty) - `[RED] the NSP is damaged: a filesystem's own tables fail the NCA's hash check`, exit code 3, right after the build IDs; before 2026-11-04, `[RED] nx_extract exit code -6` with an unhandled `ResultFsNonRealDataVerificationFailed (2002-4604)` under `RomfsHeader`. The ExeFS reads, and the build IDs and name are printed, since only the RomFS is hit. → [A damaged RomFS's own tables](../reference/packing.md#a-damaged-romfss-own-tables) - a build packed with `--allow-damaged` crashes or draws wrongly in game code, the same way on each run, at a place unrelated to the host's last work. The log gave no sign of damage; the build log's list (`logs/extract_.log`) is the only record, and it is not part of a bug report's run log. → [A crash from a damaged NSP's file looks like a host bug](../reference/packing.md#a-crash-from-a-damaged-nsps-file-looks-like-a-host-bug) +- one guest thread busy all session in a scene that should be idle (Ocarina of Time: `OptimizeChangeBanc` about one core, a `ParallelDecompThread` about 0.75 core, the process at about 400% CPU on the Mac), and with `DM_FS=1` the same model and texture opened again about 22 times a second. Now `[RED] fs rom:/.zs is not a zstd stream (begins 00 00 00 00; damaged): served as (romfs_substitute)`, or `... answered "not found"`. → [A `.zs` file that is not a zstd stream](../reference/packing.md#a-zs-file-that-is-not-a-zstd-stream) - the NSP script stops at the offline HTML pages (`logs/extract_html_.log`) with `[RED] the NSP is damaged: files fail the NCA's hash check` and a list under `/html-document/`, although the program extracted cleanly and the NSZ tool verified every NCA of the update. → [An update's offline HTML pages reported as a damaged NSP](../reference/packing.md#an-updates-offline-html-pages-reported-as-a-damaged-nsp) - for a game with no profile, the NSP script stops at `build ID lookup · main of the base game` with `[RED] nx_extract exit code -6`; `_survey/logs/exefs.log` ends in `ResultFsNonRealDataVerificationFailed (2002-4604): Hash error!` from `PartitionFileSystemMetaCore.QueryMetaDataSize` under `Nca.OpenFileSystem`, although every NCA in both NSPs matches its content ID (the SHA-256 that names it) and the base game with its update extracts cleanly. → [The survey's build ID lookup stops on the base game alone with a hash error](../reference/packing.md#the-surveys-build-id-lookup-stops-on-the-base-game-alone-with-a-hash-error) - the NSP script stops right after `extract v<version>` with `[RED] the NSP is damaged: a filesystem's own tables fail the NCA's hash check` and `nx_extract exit code 3` from `logs/extract_html_<version>.log`, although every NCA's SHA-256 matches its name. → [The offline pages of a sparse base game stop the build as a damaged NSP](../reference/packing.md#the-offline-pages-of-a-sparse-base-game-stop-the-build-as-a-damaged-nsp) diff --git a/docs/env_switches.tsv b/docs/env_switches.tsv index 3b1f01cf0b..0f57887c11 100644 --- a/docs/env_switches.tsv +++ b/docs/env_switches.tsv @@ -296,6 +296,8 @@ DM_RES_CHECK diagnostic `=1` prints the first 40 textures or buffers a shader re DM_REWRITE_J switch `=<positive integer>`: worker processes per module for `patch_nso.py`'s x18 scan and spin wait search; `=1` runs serially. Default: one per core directly, an automatic per-module budget in the NSP script. An explicit value overrides that budget DM_ROMFS path The game's RomFS folder, mounted read-only as `rom` (default `$DM_ROOT/romfs`); the Mac launcher, the iOS app and the NSP script set it DM_ROMFS_OVERLAY path `=<dir>[:<dir>…]`: RomFS reads look in these folders first, in order, and fall back to `DM_ROMFS` (for a modified copy of some files) +DM_ROMFS_SUBST switch `=<path>=<substitute path> …` (RomFS paths without a leading `/`, space-separated pairs) replaces the profile's `romfs_substitute`: damaged `*.zs` files (not a zstd stream) served as other image files +DM_ROMFS_ZSTD_CHECK switch `0` serves a RomFS image file named `*.zs` that does not begin with a zstd frame as stored; by default such a damaged file is served as its `romfs_substitute` (profile key, or `DM_ROMFS_SUBST`) or else answered "not found" (open and entry type), with one `[RED]` line (`hle_fs.c` `img_serve`) DM_ROOT path Workspace root (default `~/dm-work`): the host's and tools' default paths (RomFS, temporary storage, shader libraries under `build/cache/metal_shader_cache`, probe dumps) are under it DM_RT diagnostic `0` leaves the thread that acquires the window on its QoS only, with no Mach time-constraint policy declaring the frame deadline (on by default; for power A/B) DM_RT_COMP switch `=<ms>` fixes the computation the present thread's time-constraint policy declares; default `auto` re-declares it every 120 frames from that thread's per-frame CPU time (p90 and peak) diff --git a/docs/reference/packing.md b/docs/reference/packing.md index c1bcbfb68c..fae1e102cd 100644 --- a/docs/reference/packing.md +++ b/docs/reference/packing.md @@ -347,6 +347,13 @@ - **Fix:** the entry's last byte in a `DMROMFS1` index ([format](../../dm/tools/romfs_image.py)) is 1 on a file that failed the check (`img_ent.flags`, `romfs_image.h`; `nx_extract` sets it, and every reader refuses another value, or a flag on a directory). The mark stays with the image in an IPA, a Mac app or a hand-copied `romfs.img`. The host logs `[RED] fs RomFS image <path>: damaged files <N>: ...` at the mount and `[RED] fs rom:/<file> failed the NCA's hash check ...` at each damaged file's first open. A clean image is byte-identical to one from before this mark (checked on SteamWorld Dig), so its identity does not change. Not marked: an image extracted before this change, and folder extraction, which has no index (the NSP script writes images). Search a crash's log for `hash check` before looking for a cause in the host. - **Found on:** [Breath of the Wild](../../dm/games/01007EF00011E000/README.md#found-on-this-game) ([issue #810](https://github.com/seedds/nxnative/issues/810)). `dm/host/tests/t_fs.c` checks the count, the single report at first open and the refused flags; a boot of SteamWorld Dig on a deliberately damaged image logged the count and the files it opened. +### A `.zs` file that is not a zstd stream + +- **Symptom:** one guest thread busy all session in a scene that should be idle (Ocarina of Time: `OptimizeChangeBanc` about one core, a `ParallelDecompThread` about 0.75 core, the process at about 400% CPU on the Mac), and with `DM_FS=1` the same model and texture opened again about 22 times a second. Now `[RED] fs rom:/<file>.zs is not a zstd stream (begins 00 00 00 00; damaged): served as <substitute> (romfs_substitute)`, or `... answered "not found"`. +- **Cause:** a RomFS file named `*.zs` that does not begin with a zstd frame cannot be decompressed. In the Ocarina of Time NUP at hand, three textures begin with 12 KB of zeros: `Tex/CmnTex_Map_Soil_FairyFountain_Floor_D_Nrm.bntx.zs`, `Tex/Rock_WaterTemple_Gate_M_01_Nrm.bntx.zs` and `Tex/RBake_Scene_GanonStage_G_2_1_d0_t0.bntx.zs` (the other 102,182 `.zs` files begin with a zstd frame). The container's SHA-256 of them matches, so they were so when it was packed; whether a retail copy has them is not known. A NUP or a dump folder carries no NCA hashes, so the extraction cannot see this, unlike [a damaged NSP's file](#a-crash-from-a-damaged-nsps-file-looks-like-a-host-bug). The first texture kept the Kokiri Forest fairy fountain model (`Model/Land_FairyFountain_Base_A.Land_FairyFountain_Base_A_01.bfres.zs`, 2.4 MB) from loading. The game's background loader (`OptimizeChangeBanc`, `main+0xf7a0`) walks the area's 852 entries and sleeps only after a pass that finds them all done, so it asked for the model again pass after pass, and a decompression thread unpacked the 2.4 MB each time. Answering "not found" fails the model the same way (the game then asks for the `.bntx`, which is not there either). +- **Fix:** `img_serve` in `hle_fs.c` reads the first 4 bytes of an image file named `*.zs` once, at its first open or entry type, and marks the entry in memory. A file that begins with neither a zstd frame nor a skippable frame is served as the file the profile key `romfs_substitute` names for it (`<path>=<substitute path>` pairs; `DM_ROMFS_SUBST` replaces the list), else answered "not found". `DM_ROMFS_ZSTD_CHECK=0` serves such files as stored. Ocarina of Time's profile serves both normal maps as the game's own 1x1 flat normal map (`Tex/Dummy_Flat_Normal_CmnTex_Chara_DetailMap_Nrm.bntx.zs`; this game's normal maps are ASTC with X in RGB and Y in A, so a flat one is 0.5 in all four channels) and the Ganon stage bake as its neighbour cell's (`..._G_2_2_d0_t0`, not checked in game). A copy without the damage is served as before: only a `.zs` file that is not a zstd stream is substituted. +- **Found on:** [Ocarina of Time](../../dm/games/0400486024DEC000/README.md) (update v131072). Mac, 5-minute runs in Kokiri Forest, medians from frame 5000: CPU 412% → 180%, `OptimizeChangeBanc` and `ParallelDecompThread` idle after frame ~3900, submit CPU 8.9 → 5.7 ms a frame, frame p50 17.7 → 17.3 ms, p95 21.9 → 18.8 ms. The model and its texture open once. `dm/host/tests/t_fs.c` checks a zstd stream served as stored, a file of zeros "not found" by entry type and by open (checked once), served as its substitute, and "not found" when the substitute is not in the image. + ### An update's offline HTML pages reported as a damaged NSP - **Symptom:** the NSP script stops at the offline HTML pages (`logs/extract_html_<version>.log`) with `[RED] the NSP is damaged: <n> files fail the NCA's hash check` and a list under `/html-document/`, although the program extracted cleanly and the NSZ tool verified every NCA of the update.