Skip to content

Guard Metal image atomics and validate backing bounds - #178

Closed
b4f8abbb24dbf56a7d0280f296e16eeb wants to merge 1 commit into
seedds:mainfrom
b4f8abbb24dbf56a7d0280f296e16eeb:fix/image-atomic-bounds-clean
Closed

b4f8abbb24dbf56a7d0280f296e16eeb wants to merge 1 commit into
seedds:mainfrom
b4f8abbb24dbf56a7d0280f296e16eeb:fix/image-atomic-bounds-clean

Conversation

@b4f8abbb24dbf56a7d0280f296e16eeb

Copy link
Copy Markdown
Contributor

What this fixes

Image atomics lowered to Metal buffers could write outside their backing allocation. Redirecting block-linear image atomics to scratch storage does not prevent this: an invalid coordinate can still produce an address far beyond the scratch buffer.

During Z-A investigation, shader validation reported 1,836 invalid stores into a 3 MiB buffer, including offsets around 16 GiB. The reviewed shader uses non-returning SURED with IGN out-of-bounds behavior. That mode was decoded but lost before the atomic operation was generated.

Changes

  • Preserve the supported non-returning IGN contract and check every coordinate, including array layers, before constructing the image pointer or executing the atomic. Negative coordinates cannot wrap into large unsigned offsets.
  • Keep the original SPIR-V coordinates unchanged. Replace only the recognized Metal 2.3 coordinate-helper definition with typed, layer-aware 64-bit addressing; reject unknown helper forms.
  • Reject unsupported source widths, formats and atomic modes explicitly rather than silently treating them as 32-bit operations.
  • Resolve matching IMG/IMGA bindings together and check their extent, backing, offset and capacity. Refuse the old short-dummy fallback when a full-sized image has no adequate atomic buffer.
  • Rebuild the two affected managed translator assemblies and include helper changes in both translation-chain and shader-cache fingerprints.

This is a shared translator/binding correction, not a game-specific instruction patch. Merely enlarging the scratch buffer would leave the underlying invalid-coordinate arithmetic intact.

Supported contract

Compiler coverage includes buffer, normalized 1D/1D-array, 2D and 2D-array routes for supported 32-bit integer operations; unsupported cases fail closed. Host direct backing is deliberately limited to verified packed base buffer/2D layouts. Padded rows, derived views, direct arrays and other unproven layouts are rejected rather than assigned an invented memory layout. Existing block-linear scratch/discard behavior is preserved.

Validation

  • Portable compiler/helper tests pass: 48 accepted synthetic cases and 16 expected rejections, with SPIR-V validation and generated-helper checks.
  • Host layout tests pass normally and under ASan/UBSan; cache/chain and binding-wiring tests pass.
  • Native shader CI passed 192 macOS/iPhone Metal compile-and-metallib checks across bundled and independently rebuilt translators.
  • Native host CI passes: four Mac host builds, all graphics-test compilation, iPhone host-source compilation (133 files, zero failures), and host/tool/layout sanitizer tests.

In the development build, Z-A 1.0.0 on M1 Max went from 1,836 invalid-store reports to zero, and the tester reported no freeze with shader validation disabled. This clean upstream-based revision still needs its own gameplay/device validation.

Shaders must be regenerated after updating: a host-only rebuild would retain the old translated code. New chain: f2ddeb7bff36.

Related reports: #149 has the same GPU page-fault/freeze signature after the scratch-buffer workaround; #139 reports a station-to-world freeze without diagnostic logs. Their device/version cases have not been verified fixed by this PR.

Preserve nonreturning IGN semantics and guard original coordinates before image pointer construction. Use a checked, layer-aware 64-bit Metal emulation helper, reject unsupported source widths and modes, and refuse mismatched or undersized IMG/IMGA backing.

Rebuild the managed translator and update measured cache fingerprints. Add synthetic compiler, helper, layout and cache regressions. This change is independent of shared-memory takeover and IPC work.
seedds added a commit that referenced this pull request Oct 25, 2026
Apply the generalized image-atomic bounds and backing checks from PR #178.
Also reject unsupported descriptor formats before integer fallback and fail
unresolved bindless atomics instead of silently deleting them. Rebuild the
translator and record chain 467efdfd0b62, with regression tests and findings.

Validation: compiler/helper and sanitizer tests, 96 Metal compile/link checks,
ten GPU probes, all 28,603 Z-A shaders for Mac and iPhone, and a 240-second
Mac station-area run reaching 6,987 frames without a freeze or GPU fault.
Reported iPhone cases and the station-to-world transition remain unverified.

Co-authored-by: b4f8abbb24dbf56a7d0280f296e16eeb <51352400+b4f8abbb24dbf56a7d0280f296e16eeb@users.noreply.github.com>
@seedds

seedds commented Oct 25, 2026

Copy link
Copy Markdown
Owner

Confirmed the missing coordinate guards and incorporated this PR into main in c3a0880, with credit to the original author.

Review also reproduced and fixed two gaps in the fail-closed contract:

  • Descriptor-sized atomics could coerce unsupported formats (for example R16Float) to R32Sint before validation. Bound and resolved bindless paths now reject those formats before fallback.
  • Unresolved bindless atomics could be silently deleted before the bounds checks were generated. The Metal path now rejects them explicitly.

Added regressions for both, updated the finding documentation and symptom index, and rebuilt the bundled translator. The resulting shader chain is 467efdfd0b62; shaders must be regenerated when updating.

Validation passed: 11 compiler/helper tests, layout checks including ASan/UBSan, binding/chain/documentation checks, 96 macOS/iPhone Metal compile-and-link checks, and ten native GPU coordinate probes. All 28,603 Z-A shaders built for Mac and iPhone with zero failures and no undecoded bindings. Z-A 2.0.2 then completed a 240.1-second / 6,987-frame Mac station-area smoke test with shader validation disabled, without an observed freeze, GPU page fault, missing shader, or atomic-binding rejection.

This is a shared translator/binding fix, not a game-specific patch. The reported iPhone/version cases and station-to-world transition remain unverified; this does not establish that every reported freeze has the same cause.

Closing because the implementation and follow-up fixes are now on main. Thanks for the investigation and regression coverage.

@seedds seedds closed this Oct 25, 2026
@m0eak

m0eak commented Oct 26, 2026

Copy link
Copy Markdown

macOS data point: the opening-station freeze is gone

Tested this PR on a Mac mini (Apple M4, 16 GB, macOS 27.0.1) against Pokémon Legends: Z-A 2.0.2 (v393216).

Before

On fd57159 there was a deterministic freeze at a fixed point in the opening — the scene at the station. 100% reproducible, every run.

Stack sample of the hung process at that freeze:

Thread: RenderWorker
  291  h_nvnWindowAcquireTexture  (hle_nvn.c:1267)
         -> mtl_link_wait_tick    (nvn_mtl.m:8641)
   62  h_nvnQueueSubmitCommands
         -> mtl_exec / draw / rp_begin_ex_

The main thread was idle in -[NSApplication run]; only the render worker was stuck. mtl_link_wait_tick has its own timeout, so the unbounded wait is one level down, in mtl_present_wait(tk):

uint64_t tk = *idx < 4 ? o->ticket[*idx] : 0;
if (tk) { mtl_present_wait(tk); }

a bare pthread_cond_wait in the non-display-link branch. This is consistent with the PR description: out-of-bounds image atomic writes fail the GPU submission, later commands are ignored, and the present ticket is never completed.

After (this PR applied)

  • Build: scripts/build_ipa_from_nsp.py --platform mac
  • Shaders: all 28,603 recompiled; cache fingerprint moved from b-657c42552d82 to b-f2ddeb7bff36, so the translator change is in effect
  • The station scene in the opening now plays through without freezing — that specific block is gone.

Scope of this report

I have only verified that one scene. I have not played past it in depth, so I can't speak to whether other scenes or the rest of the game are clean — there may well be further issues downstream. This is a single data point on one Mac configuration, not a full gameplay validation.

You reported verification on Z-A 1.0.0 on an M1 Max; this run was 2.0.2 (v393216) with the DLC attached on an M4.

Happy to run diagnostic builds or gather more logs if useful. Thanks for the fix.

Xanawer pushed a commit to Xanawer/nxnative-android that referenced this pull request Oct 26, 2026
…SDK 9.3.1): game profile plus general changes to the Unreal pak reader, NVN virtual pools and sparse textures, and on iOS 60 fps and a Screen setting

Plays on the iPhone 18 Pro Max (user, with a build from before main's image-atomic admission, PR seedds#178): the opening, the character naming and Jouin High School. With the 60 fps rows the phone's launcher offers Frame rate 30 / 60; its last logged session (60, Screen fit) ran its first 900 frames at frame time p50 16.7 ms. On the Mac the same route runs from a new game to the classroom at frame time p50 16.7 ms at 60 fps (33.3 at 30), at the game's own speed: the naming keyboard comes at the same wall time at either rate. On the Mac it needs the buffer-image fix of PR seedds#263: without it the image-atomic admission stops the host about 60 s into a new game.

- uepak.py / shader_split.py: legacy pak version 8 (UE 4.22 to 4.24: version 11's footer, five compression method names, Zlib here, read by Pak.read), deleted entries (flag 2) skipped, and the AES key from a key callback whose halves lie apart in main (callback_keys; kept in memory only, never printed). ue_legacy_jobs takes each pak's main for its key. 18,558 shaders split.
- hle_uemalloc.c: UE 4.23's FMallocBinned3 (74 pools of 512 MB, 37 GB of the engine's region) is replaced by the host allocator. Layout UE4_23 has 18 vtable slots and no TryMalloc / TryRealloc yet. The constructor call (main+0x1713920) is cut and the object passed at the OBS_UE_MALLOC gate (the profile's patches.py). patches.py also makes nninitStartup allocate its address region when -SwitchVirtualAddressSpaceSize= is given (it skipped the allocation and left the base 0).
- sdk_patches.py, SDK 9.3.1 sdk ad3fdfbd62a5: the node area cut and 32 MB alignment for regions of 1 GB and more, as DRAGON QUEST XI S's SDK 7.3.2 build. game_args -SwitchVirtualAddressSpaceSize=4064 in a 5 GB block.
- hle_nvn.c: sparse virtual pools. A virtual pool larger than the application pool, or every one with the new profile key virtual_pools sparse, gets an address range of its own at Initialize, and each MapVirtual request's pages are remapped into it (page table per pool, vp in pool_t). Unreal's NVN RHI gives each streaming texture a pool of its own, over a thousand by the opening, mapped 64 KB page by page from some twenty physical pools. nvnTextureGetSparseTileLayout and nvnTextureBuilderGetSparseTileLayout now fill the tiled level count (nvn.h NVNtextureSparseTileLayout fields). The unimplemented stub left a count past the texture's levels, and Unreal's out-of-memory abort followed at boot.
- nvn_tex.c: a sparse texture with 8- or 16-byte blocks and no packaged layout takes a block height of 8 GOBs, the standard 64 KB tile shape. The classroom's DXT5 lightmaps were scrambled in 4-texel columns with 16. New t_tex case.
- nvn_mtl.m / hle_nvn.c: a sampled sparse texture (tex_t sparse) is read only through the pool it was initialized in, which the host finds from the texture alone (vpool_tex: the live pool whose base is the texture's mem - off, made before the texture's serial), so a texture that outlives its pool, or a new pool at the same address, never reads another pool's pages; a texture whose pool the game finalized keeps its last upload. The level it is bound from comes from the mappings its bytes were gathered with (sparse_base). New test t_sparse_life. texraw reads a packaged texture at its sampled level. The naming cutscene came out all green, then white, from the pipeline-miss lookahead's scissor leak that main fixed for OCTOPATH TRAVELER II (pso_predict_rest restores R); its comment names this game too.
- hle_fpslock.c: rows for t.MaxFPS and rhi.SyncInterval (UE 4.23, both copies). The game's code sets t.MaxFPS 30 at run time and the Switch device profile sets rhi.syncinterval=2; either alone kept it at 30. The profile's fps_target 60 adds the launcher's Frame rate 30 / 60.
- iOS: a launcher setting Screen (DM_ASPECT fit / zoom / stretch, default fit, settings.tsv). front_ios.m keeps the game view 16:9 (its drawable follows its bounds, and present letterboxes any other ratio): zoom makes it larger than the screen, stretch widens it with a transform. Touches are mapped on the same rectangle (dm_game_rect, DmGamepad.m).

Profile: tex_flush_upload and tex_dirty_upload on (the colour grading LUT is written from the CPU; without them the picture is black), pad_layout full, depth_mode zero (the game sets near = 0), shader groups global / engine / game. Open: two of Unreal's global compute shaders (4f731ba19a5f2877, c073d1efaba9ac70) use the value their atomics return, which main's bounded Metal atomics do not translate; their dispatches are skipped (7 red lines), and the classroom comes out a little darker (mean luma 57.3 against 58.8 with their old translations put back). Docs: the game note, the games table (virtual_pools, version 8 paks, depth_mode), README (games gallery with a Mac picture of the classroom, the Screen setting, the DM_FPS_TARGET list), AGENTS.md's count (sixty-eight), docs/reference memory / nvn-objects / rendering / rewriter / shaders and the symptom index.

Checked on 6062518:
- CI's steps: the host tests for Wonder's profile and this one, tsan / memory-tsan, the thermal checks, t_perf_order and its tsan build, t_tex, the CPU-only gfx tests, the Python tests (217: dm/tools, dm/ios and dm/gfx tests, the docs check among them), the Mac host for Wonder, Hades, Digimon Story Cyber Sleuth and this profile, every gfx test compiled, the iOS compile check (133 files) and the unsigned iOS app for both profiles;
- the gfx run list (52 commands) passes under Wonder's profile, and under this one except t_readback, which aborts the same way on main under The Great Ace Attorney Chronicles' profile (tex_dirty_upload on); t_sparse_life (131 checks) under both profiles and ThreadSanitizer;
- with PR seedds#263 on top, a Mac boot from a new game through the naming to the classroom at 60 fps (frame time p50 16.65 ms): the naming cutscene and the classroom correct, only the two shaders' 7 red lines;
- on cbbb600, --prepare-xcode built the iOS project (18,558 shaders split, the chain tables match); main's image-atomic change has since moved the chain version (8393d85a4eae on 6062518), and the iOS project was not built again;
- reviews: GPT (codex gpt-6-astra) on the scissor fix, the 60 fps rows, the Screen setting, the merge with cbbb600 and, in four rounds, the sparse texture lifetime; Opus on the allocator swap, the scissor fix and the lifetime fix.

Rebased onto 82ab25b (main's present allocator fix, which shares no code with this change): the host builds for this profile, and t_sparse_life, t_present_alloc and the docs check pass.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
v0lumehi added a commit to v0lumehi/nxnative that referenced this pull request Oct 26, 2026
…ds#272)

A game's usage manifest, dm/games/<id>/usage.tsv, written by its owner with
regress.py usage: the features of its translated shaders (stages, binding
kinds, image and buffer atomics with or without a used result, transform
feedback, layer and integer outputs, translator notes, texture types) and,
from one run of its smoke route with DM_HLECOUNT and the NVN call rows, the
NVN functions, HLE functions and SVCs it called, its present path and its
profile keys. Names and counts only.

regress.py impact <base>..<head> maps the functions around the changed lines
through the host's callers (a scanner: NVN(...), HLE(...) and {"symbol", fn}
tables as roots, static functions kept to their file) and the rules of
dm/tools/impact_map.tsv to manifest rows, and lists the games that use them,
those reached only through a broad rule, and the profiles without a manifest.

Manifests for Breath of the Wild, Tears of the Kingdom and Hades (main
89744da). On c3a0880 (image atomics, seedds#178) it names neither Zelda for image
atomics (they have none) but both for the bindless and driver-read changes;
Hades is not affected. On seedds#135 (the prepare step) it names both Zeldas for
pipeline_prepare and Hades only through the front end's broad rule.
Know-It-All-Brother pushed a commit to Know-It-All-Brother/nxnative that referenced this pull request Nov 9, 2026
Apply the generalized image-atomic bounds and backing checks from PR seedds#178.
Also reject unsupported descriptor formats before integer fallback and fail
unresolved bindless atomics instead of silently deleting them. Rebuild the
translator and record chain 467efdfd0b62, with regression tests and findings.

Validation: compiler/helper and sanitizer tests, 96 Metal compile/link checks,
ten GPU probes, all 28,603 Z-A shaders for Mac and iPhone, and a 240-second
Mac station-area run reaching 6,987 frames without a freeze or GPU fault.
Reported iPhone cases and the station-to-world transition remain unverified.

Co-authored-by: b4f8abbb24dbf56a7d0280f296e16eeb <51352400+b4f8abbb24dbf56a7d0280f296e16eeb@users.noreply.github.com>
ltrdpper pushed a commit to ltrdpper/BananaNative that referenced this pull request Nov 12, 2026
…settings, Ocarina of Time on Qualcomm

- Game language: Polish (pl) and Thai (th), from SDK 21's own settings table (sdk+0xc62b5c in Ocarina of Time lists pt-BR, pl, th); the launcher list, the host's DM_LANG mapping and GetAvailableLanguageCodes. Ocarina of Time (`0400486024DEC000`) carries EUpl messages, Donkey Kong Bananza (`040074A01BF12000`) 1.1 EUpl and THth.
- Launcher: one full page per game with tabs Performance (Picture, Speed, Advanced), Game (options, Game language, Controls), Saves and Storage; rows wrap and say what they do; profile options keep their description and say when they need Prepare again.
- Recommended settings per game and phone (game.tsv recommend rows, Recommend.java): a card with Recommended / Custom and tags on the rows; facts from GLES at launcher start before the first readiness check. Ocarina of Time on Qualcomm: system driver, Performance preset, Full vegetation off.
- Resolution presets (res_preset, scene_output rows) and Scene resolution overlays from a game's own dynamic resolution palette (scene_res.py, DM_ROMFS_OVERLAY).
- Qualcomm's own driver: mesh draws through compute by default (full Ocarina of Time foliage; DM_VK_MESH=1 keeps native mesh shading).
- Mesh draws through compute: a draw takes its own record's entry, and prewarm drops mesh / pixel pairings that do not feed each other (see-through on Adreno 830, black-line flicker on Turnip, issue seedds#180).
- Texture serial map: probes past tombstones, live and tombstone counts apart (the table no longer grows with every serial ever registered).
- pack_android.py: a profile with a selected shader set builds that set on the Mac and Windows (issue seedds#178).
- PRs seedds#150, seedds#151, seedds#171 (FrenklinFish) and seedds#156, seedds#163 (Omnicrash) were merged on Forgejo before this update.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants