Skip to content

hle_time: back the adjustable user clock with the host user clock - #20

Closed
BeeeeeMo wants to merge 148 commits into
seedds:mainfrom
BeeeeeMo:fix/adjustable-user-clock
Closed

BeeeeeMo wants to merge 148 commits into
seedds:mainfrom
BeeeeeMo:fix/adjustable-user-clock

Conversation

@BeeeeeMo

Copy link
Copy Markdown
Contributor

Problem

time::Initialize is taken over by the host, so the native SDK never receives a Horizon clock context. StandardUserSystemClock already reads host time, but AdjustableUserSystemClock still runs against that uninitialized context. A local SDK 9 startup reproduced an abort in Adjust with Result 0x74.

Change

Add two service-layer takeovers next to the standard user clock:

  • Adjust() is a no-op because this host clock reads system time directly.
  • GetCurrentTime(PosixTime*) delegates to the existing standard user-clock hook, including its DM_FIXED_TIME behavior.

This follows the existing offline host-clock policy. It does not set the host clock or emulate Horizon clock-correction state. No title-specific branches, profile changes, shader changes or new configuration are included.

Verification

Based on ec49fd3:

  • The new test fails on the unmodified implementation: both exact SDK hook registrations are missing.
  • With the fix, 27 checks pass across fixed-time and live-clock runs. The test resolves the actual forced-hook table and checks the return/output ABI, write boundaries, repeated adjustment and consistency with the standard user clock. It needs no extracted game files.
  • The full Mac host builds on Apple M2 with Xcode 27.1.
  • hle_time.c passes an arm64 iOS 26 syntax/type check. No iOS device runtime test was performed.
  • git diff --check passes. The full host test suite was not run; it also requires reference-game files.
make -C dm/host GAME=010015100B514000 game_profile
make -C dm/host/tests GAME=010015100B514000 build/t_time
dm/host/tests/build/t_time fixed
dm/host/tests/build/t_time live
make -C dm/host GAME=010015100B514000 dmhost

The test is also wired into the existing host run target. This PR is limited to the two clock hooks and their tests, not a claim of support for any additional game.

seedds added 30 commits October 12, 2026 22:04
Generic host, gfx and tools taken from d2r-mobile (MIT), with the D2R
gameplay, diagnostics and Blizzard/Granny/movie layers removed.

- hle_hid.c: generic standard-controller layer (all Npad styles)
- hle_sdk16.c: newer-SDK oe/time/pl/vsync/diag hooks
- hle_offline.c: offline stubs for prepo/ldn/socket/ssl/nifm/nsd/friends/ngc/err
- hle_fs.c, hle_account.c: SDK 16 overloads
- loader.c: unreferenced forced hooks only logged (DM_FORCE_STRICT=1 aborts)
- NVN: API 55.15, 13 newer names, ~45 state-only functions, tex_t packed
  to 0x80 (Mario allocates NVNtexture as 0x80; 0x88 corrupted the heap)

Frontier: null read at main+0x64763c inside the frame loop.
- hle_svc.c: guest AS 6 GB with a 1.25 GB alias region (newer SDK's
  AddressRegionManager always takes ~1 GB of it as its node area),
  MapPhysicalMemory rounded to 16 KB host pages, GetInfo(UserExceptionContext)
  backed by a real buffer, program id now SMBW (DM_PROGRAM_ID overrides)
- hle_audren.c (new): silent AudioRenderer, event fired every 5 ms
- hle_fs.c: SetPriorityOnCurrentThread / IsEnabledAccessLog (fsp-srv)
- hle_sdk16.c: settings language comparison; diag aborts report the call
  site and backtrace
- NVN: nvnProgramSetShadersExt (0x18-byte stage entries)

The game now runs ~40 threads; the main thread waits on job events while
render commands (CallCommands, BindTexture, BindVertexBuffer, DrawElements,
WriteTexels) are still unimplemented.
- BindTexture (combined handles go straight into the texture slot; the
  replay already splits texture / sampler ids), BindImage,
  BindTexturesDeferred, BindVertexBuffer, CallCommands
- DrawElements / BaseVertex / ArraysInstanced; viewport, scissors and
  depth ranges in single / multi forms
- ReportValue via the event-write record; new OP_CLEAR_BUF record with
  in-order replay (fillBuffer, or a pattern buffer for non-uniform values)
- TextureWriteTexels: deswizzle level, patch region, swizzle back, after
  lifting write protection
- Command memory: when the game's callback cannot supply enough, continue
  in a host segment instead of aborting
- Remaining state the replay lacks (conditional render, depth clamp,
  rasterizer discard, ...) is logged once and drawing continues

The game now runs its frame without errors from these; the main thread
waits in the job system's fork-join (executors keep polling).
- patch_nso.py: fix exclusive-window exit order. The fall-through stub
  must come right after the copied window; it was emitted last, so a
  successful stxr in 'ldxr; cmp; b.ne out; stxr; cbnz' fell into the
  branch-out stub (main 0x81c40: job-system enqueue retried forever,
  tail filled to capacity with no task stored). Bug inherited from
  d2r-mobile, latent there (no branch-out windows).
- patch_nso.py: rewrite 'mrs xN, ctr_el0' (trapped on macOS) to a
  constant with 64-byte data cache lines.
- hle_thread.c: SetThreadCoreMask moves the ideal core into the new mask
  (Horizon behavior), so pinned threads report the right core.

Frames 2 and 3 now record, submit and present (~1,900 NVN calls).
Next: Mario's shaders (bfsha) are not in the translation map yet.
Shaders
- shader_split.py (new): scan RomFS and main for every BNSH and agl BAHS
  container (bfsha, particle effects, layouts, agl/gsys packs, main):
  12,811 shaders, map + compute facts from the control section
- key = sha256(control + code): many shaders share a control section
- NVN 55 binding layout: bound textures at 0x20 + 8*slot, images 0x120
- bindless textures read from uniform buffers (tex_ubo / samp_ubo)
- GL depth mode: translator remaps z' = z/2 + w/2 in vertex shaders
- compute code areas carry a 0x30 header (magic 0x12345679)

Replay
- 8-bit index buffers widened to 16-bit
- texture swizzle through Metal swizzled views
- non-packaged textures shared by storage (fixes a ~13 MB/frame leak
  from transient render targets rebuilt every frame)
- view_t packed to 16 bytes (SDK 16 NVNtextureView; fixes a stack smash)
- TBDR optimizations off by default until they know bindless readers

Host
- alias region 2.875 GB for the 1.75 GB VirtualAddressMemory reservation
- ideal core -2 resolves to the process default core
- shared font served with a BFTTF "decoded" header
- crash reports scan the stack and dump the popped frame

Docs: docs/agents (guides for porting other titles), AGENTS.md
- DM_KEYS scripted controller input ("seconds:button[+button][~hold]")
- NVN virtual memory pools aliased onto their physical pool when every
  MapVirtual request shares one base (Mario's 128 MB pool); previously
  MapVirtual failed and the game treated the pool as unusable
- DM_PROBE ported from d2r-mobile (host/probe.c): brk probes with
  register / backtrace output, plus DM_PROBE_X2 object dumps; used
  because lldb launches now wait on a macOS authorization prompt
- diagnostics: DM_NVN_VLOG (pools, MapVirtual), DM_NVN_CBLOG (command
  memory grants and callbacks), DM_NVN_ALLOCPROF
- docs: new failure patterns and the probe recipe

Open: starting a new game crashes while loading the opening course
(model resource heap overflow for NpcCommonerA.bfres).
…PU-written text

- patch_nso.py: Mario main cut gives every resource heap +16 KB; Model/NpcCommonerA.bfres
  came up 0x70 bytes short of its size-table budget while loading Course900
- dmsh_build.py: compute instructions start at code area +0x100, not +0x30; the misaligned
  decode turned 12 particle / post-effect compute shaders into endless loops (GPU hang)
- Linear textures in CPU-visible pools are built on the pool buffer, so the CPU-rasterized
  glyph cache reaches the GPU (menu and dialogue text)
- Host command-memory segments grow on demand; RGB10A2SN vertex format; instanced DrawArrays
- DM_PROBE: thread IDs, register-relative dumps, hit filters, ExpHeap walker
- dm/tools/ghidra/Decompile.java; agent guides and README updated
…y colour ramps

- dmsh_build.py: vertex shaders whose inputs are only used as integer bit casts are
  re-translated with uint inputs (529 shaders); bone indices were converted to floats and
  every character was stretched off screen
- Host: Metal vertex formats follow the shader input type (signedness swap, 32-bit float
  reinterpretation), mismatches reported
- LINEAR_RENDER_TARGET textures in CPU-visible pools are zero-copy too (sky colour ramps)
- Pass dump lists all vertex attributes; docs and README updated
- dm/ios: lean app shell (main.m boot/env/log, front_ios.m front.h + 16:9 Metal view,
  DmGamepad.m touch gamepad in Nintendo positions + GameController), xcodegen project,
  tools/build_ipa.sh (embedded game code, iOS shader libraries, RomFS in the bundle)
- Guest address space back to 5 GB (heap 1.625 GB; the game asks for 1.47 GB)
- README / agent guide: iOS build steps and address-space sizing
…nt, ordered copies

- Audio: run the sdk's own audio renderer on the CPU in manual mode (hle_audren.c),
  feed its DeviceSink output to the AudioOut sink; catch-up render on back-to-back
  updates fixes the ApplyLightLimiterEffect crash at the title screen
- Button icons: make_ext_font.py generates a stand-in Nintendo extension font
  (A/B/X/Y, L/R/ZL/ZR/SL/SR, +/-, D-pad, stick arrows); served as shared font type 5;
  the iOS bundle now carries both shared fonts
- Fountain panels: Metal 4 does not order copies inside one encoder; add barriers
  when ranges overlap, so the GPU wave simulation no longer reads a stale uniform
- Zero-fill new colour textures; scissored zero clears; uniform-update snapshots
- Docs: graphics ordering, audio, diagnostics, intermittent-glitch method
Ranges are rounded to 16 KB host pages but NVN pools are only 4 KB
aligned, so adjacent pools share their first / last page and one
address can fall in several registered ranges. Every lookup took the
first range containing the address:

- textures whose pool's first page is shared with a smaller preceding
  pool were judged untracked and re-uploaded on every use (two ASTC 6x5
  textures in the opening course: 12 re-uploads, about 6 MB, per frame);
- a fault or host pre-write on a shared page released only one range,
  leaving the other marked protected;
- destroying a pool could unregister its neighbour (same rounded base).

Tracked / protect / since now use the range that holds the whole span;
faults and host pre-writes release every range covering the page; pool
removal matches the exact pool start. Opening course: 3600 re-uploads
per 300 frames -> 0; DM_NVN_DIRTYCHECK=1 over 3900 frames: 0 misses.
t_dirty_slots covers the shared-page case (3 checks fail on the old code).
A sideloaded app cannot be given environment variables from outside.
main.m now reads KEY=VALUE lines from Documents/env.txt and from
dm/env.txt in the bundle (Documents wins, real environment wins over
both) and logs each applied line as "boot: 环境 ...".
build_ipa.sh copies DM_ENV_FILE=<file> into the bundle as dm/env.txt.
dmsh_chain.py --update-lock on a fresh Mac (Xcode 27.0, metal 32023.921
unchanged): the translator DLLs built here and Homebrew's spirv-cross
have different fingerprints. Chain b1a4876b9511; dmsh_build gives the
same result as documented (12809 / 12811 compile, the same 2 agl compute
shaders make SPIRV-Cross throw) and c1_full.tsv lists the same 11 shaders.
Another machine with other tool builds needs --update-lock + --header.
Opening course on an iPhone 18 Pro Max (A20 Pro GPU): black diagonal
band, black-edged white glow at the horizon, grey striped blocks,
alternating frame by frame. The Mac (M4 Pro) never shows it, not even
with the iOS metallibs, display pacing, -Os, DM_3D_SCALE=0.75 or the
no-BC path.

On-device colour-target stats (DM_DBG_TEXSTAT, diagnostic commit that
follows): even frames' main 1920x1080 RG11B10 target has 54 NaN pixels
(Mac: 52); odd frames 727k NaN, and the 960x540 / 1100x280 / 275x70
targets downsampled from it carry it on. The NaN is already in the main
target before the first downsample (pass 47 of 80), so it comes from
the scene passes, not the post-effect chain.

The translated shaders reproduce Maxwell's NaN rules with
select(x, 0, isnan(x)) (8337 / 12809 shaders). Default fast math
records air.compile.fast_math_enable, which lets each GPU's backend
compiler assume no NaN / Inf; relaxed keeps the reassociation /
contraction but preserves NaN / Inf. Hypothesis only: chain
1b46c9a2e920 (MSL byte-identical to b1a4876b9511; c1_full.tsv lists
the same 11 shaders) still has to be run on the iPhone. If the NaN
persists, the next step is finding the producing draw in passes 12-45.
Temporary instrumentation for the A20 Pro NaN investigation; every line
is tagged [DEBUG-flk1] so it can be removed with one grep.

- DM_DBG_TEXSTAT=N with DM_NVN_TEXDUMP=<frame>:<path>: for N consecutive
  frames, log one line per colour target instead of writing PNGs:
  per-channel mean, NaN / Inf counts, largest finite value, black share.
- Inside the DM_NVN_PASSDUMP window: each submission's commit->completion
  time and the counter values written back (timestamps / samples passed).
- DM_NVN_SHOT accepts up to 4096 frames (was 16).

Device capture used so far (unsigned IPA, DM_ENV_FILE for build_ipa.sh):
  DM_NVN_TEXDUMP=3600:td_%d.png
  DM_DBG_TEXSTAT=2
  DM_NVN_PASSDUMP=3600-3601
  DM_NVN_SHOT=3600,3601,3602,3603:shot_%d.png
  DM_NVN_SHOT_OUT=960x540
Fixes the flicker / black band in the opening course and the crash after
the first scene on the iPhone (A20 Pro), confirmed on the device.

- nvn_obj.h: cmd_t leaves byte +0x10 of NVNcommandBuffer to the game.
  Mario's inlined NVN code writes 1 there (main+0x4da5c, main+0xb8dec).
  It used to hit the low byte of `end`: the game's 512-byte material
  setup blocks shrank and overflowed into host segments,
  GetCommandMemoryUsed (cur - begin) returned 0, the game marked the
  setups empty and skipped calling them, and draws ran with the previous
  vertex buffers (out-of-range vertices, NaN).
- hle_nvn.c: GetCommandMemoryUsed counts bytes across host segments plus
  16 for the jump. Host segments are released only when the game
  re-grants memory overlapping the recording's guest bytes (the game
  keeps calling recorded setup blocks for many frames); the 8-frame
  recycling is gone.
- nvn_mtl.m: failed pipelines are cached and reported once with their
  vertex / fragment keys instead of being rebuilt on every draw.
- front_ios.m / main.m: the audio session asks for a 5 ms I/O buffer at
  boot and on return to the foreground. The default (~21 ms, 1024
  frames per callback) outran the 4 x 5 ms the renderer keeps queued:
  every callback underran (crackling). Device: 240-frame callbacks,
  0 underruns.

Still contains [DEBUG-flk1] instrumentation (tagged, mostly behind
DM_DBG_* switches; audio statistics every 2000 callbacks in
hle_audio.c). To be removed with one grep.
Metal builds a pipeline only when every pixel shader input is a vertex
shader output; Maxwell gives an unwritten attribute a default. With
shaders translated one at a time, 331 of v0's 9,043 vertex / pixel
pairs failed to link and later levels lost those draws (about 11,500
failed pipeline builds in one device session).

- shader_split.py writes shader_pairs.tsv (pairs of every BNSH
  variation) and takes comma-separated RomFS / main lists for several
  game versions, writing their union (keys are content hashes; v0 rows
  keep their package indices).
- dmsh_build.py vs_pad(): vertex shaders get the outputs their partners
  read but they don't write, float4 (0, 0, 0, 1); vertex shaders with
  partners are finished last and their partner list is part of the
  cache rule. shader_pairs.tsv is part of the chain version.
- Tables now cover v0 and update 1.2.1: 16,268 shaders (1.2.1
  recompiled 3,451 SecredUber pixel shaders and added 6 effect
  shaders), 14,603 pairs. Chain 5f1ec82dfcf0: 16,266 compile (the 2
  known SPIRV-Cross failures); an offline link test of all pairs gives
  14,603 / 0 (v0 before the padding: 8,712 / 331). c1_full.tsv
  regenerated (same 11 keys).

The v0 IPA with this padding played 11 minutes on the iPhone with no
pipeline failures.
…calls

- dm/tools/nx_extract (C#, LibHac 0.19): hactool stops with "Invalid
  BKTR layout!" on the update's patch NCA. nx_extract reads the NCAs
  straight from both NSPs, imports their common tickets, merges the
  update's RomFS over the base game, prints the display version and
  module build IDs, and writes files identical to a base RomFS as APFS
  clones (the merged 1.2.1 RomFS adds about 114 MB).
- dm/tools/nso_fnmap.py: carries offsets between builds by matching
  eh_frame functions with address bits masked; globals through their
  adrp references.
- patch_nso.py: resource heap +16 KB cut for 1.2.1 main ff773e90...
  (main+0x1cf9b0, mapped from v0 0x1e62fc; the function is identical
  after masking). fixups.tsv now records the module build ID; the
  loader keeps it in module_t.build_id.
- hle_oe.c: the 3D render scale inherited from d2r-mobile writes and
  calls fixed main addresses (0x31e0848, 0x8582f0). In Mario v0
  0x8582f0 is the middle of a static initializer; it only did nothing
  because the pointer read 0. Now enabled only on D2R's build.
- hle_misc.c: owned add-on content defaults to none except on D2R's
  build (DM_AOC_OWNED overrides).
- New imports in 1.2.1 answered as a Switch 1 without amiibo:
  nn::nfp (one NFC device on the connected controller, detection never
  finds a tag; nfp::Initialize at boot used to abort in nn::sm),
  pl::IsRunningOnOunce (false), ec::ShowShopApplicationInformation-
  ForUpgrade (no-op), account::PopOpenUsers (none: the game falls back
  to TryOpenPreselectedUser as in v0). oe::GetDisplayVersion by build
  (1.0.0 / 1.2.1).

Mac: 1.2.1 and v0 both run the scripted opening for 120 s with only
the known SetRenderEnableConditional red line. iPhone: 1.2.1 played
8.5 minutes with no crash.
- README: status for v0 / 1.2.1 on the iPhone, update 1.2.1 build
  steps, diagnostic env files, finishing the IPA by hand when Xcode
  uses a custom build location, app data folders after a reinstall,
  prewarm lists (pso_user.tsv / pso_manifest.tsv).
- AGENTS.md: per-build knowledge keyed by build ID, shader_pairs.tsv on
  the chain, unsigned IPAs only.
- docs/agents: update extraction and offset porting (01), the
  command-buffer byte, command memory, iOS audio, update imports and
  build-gated D2R code (03), vertex output padding and iOS math mode
  (04), on-device diagnostics and the offline link check (05).
- dm/gfx README / nvn_metal_mapping (en + zh-CN): pairs table, several
  game versions, prewarm lists, DM_PSO_USER, command buffer notes;
  corrected shader key, build script and 8-bit index lines.
- dm/host/README(.zh-CN).md removed: an index of d2r-mobile's D2R
  features; most files it listed no longer exist.
- DmGamepad.m: layout after a PS remote-play pad. ZL above L and ZR
  above R (teardrops) in the top corners; -/+ in the bottom corners
  with the D-pad (four arrow pads) and the A/B/X/Y diamond just above
  them; left and right sticks next to those along the bottom edge.
  Everything hugs the edges to leave the picture room. Layout
  constants are at the top of the file.
- Sticks are fixed rings (tilt from the ring centre, 0.12 R dead zone)
  instead of the floating left stick; the new right stick merges with
  a physical pad's right stick the same way as the left one.
- One CAShapeLayer per control instead of a full-screen drawRect: a
  press swaps the fill, a stick move only moves its knob. Colours
  carry low alpha (fill 0.14, outline 0.38, labels 0.6) rather than a
  view alpha, which would add an off-screen pass.
- front_ios.m header and the README app-shell line follow.
- dm/ios/tools/build_ipa_from_nsp.py (Spyder or python3): picks the
  base game and update 1.2.1 by title ID (DLC is skipped), extracts
  them with nx_extract, checks the main / sdk build IDs, rewrites the
  modules, splits the shaders and requires the tables to match the
  repo's byte for byte, builds the iOS shader libraries, then runs
  build_ipa.sh. It uses only the repo, the NSP folder and prod.keys:
  intermediates go to <NSP folder>/smbw_build/ (full step logs in
  logs/), and the extracted game files are deleted after success.
  Tested end to end: first run 33 min, re-run 10 min.
- dm/gfx/tools/dmsh_xlate_bin: the translator build that matches
  dmsh_chain.lock. A fresh dotnet publish gives different dmsh_xlate
  and Ryujinx dll fingerprints, which dmsh_build refuses.
- build_ipa.sh: when Xcode's Locations setting is a custom location,
  take the app path from the build log instead of stopping at
  "no built app".
- README: the script; the custom-location note replaces the by-hand
  finish.
- nx_extract --manifest: write ExeFS and romfs_manifest.tsv (path,
  size, first 32 bytes of every file) instead of the RomFS, so a large
  title can be surveyed without writing its game files.
- nx_extract prints the build ID of every NSO module, the display
  version and the game name, and saves the raw control.nacp next to
  the output for naming the app.
- Game name: newer SDKs compress the NACP title area (u16 size + raw
  deflate, inflating to 32 languages x 0x300; Mario 1.2.1 does this).
  LibHac 0.19 does not decode it, so nx_extract does.
- nso_syms.py: '-' for the reference game compares one game's imports
  with the host hooks only.
- dm/games/<id>/game.tsv holds what is specific to one game: title and
  program ID, known builds (module build IDs, display versions),
  package and shader versions, code modules, RomFS marker, zip store
  list, memory split, NVN driver constants, shader split groups, app
  name / bundle ID / IPA name. Mario's profile is smbw, the default.
- The shader tables, c1_full.tsv, pso_manifest.tsv, bf_want.tsv and
  dmsh_chain.h move from dm/gfx/nvn to dm/games/smbw.
- dm/games/game.py loads profiles (DM_GAME, by title ID), answers
  shell queries and generates the host's game_profile.h.
- Shader tools (dmsh_chain, dmsh_build, dmsh_facts, shader_split,
  tbdr_budget) take tables and constants from the profile. dmsh_build
  stops if the profile's texture / sampler bases differ from the
  translator's built-in ones. dmsh_chain hashes the profile's nvn_* /
  shader_* keys; the chain version is now 02ed42db694f. All 16,266
  translated shaders are byte-identical to 5f1ec82dfcf0's, and
  c1_full.tsv differs only in its header.
- Host: GAME ?= smbw in the Makefile; memory split, display versions,
  NVN bases, default modules, window title and the shader map path
  come from the profile. D2R-only code (Settings.json edits, the
  main+0x3509a0 read) runs only on D2R's build, which also stops a
  stray Settings.json in Mario's iOS save.
- iOS: build_ipa.sh, gen_build.py, project.yml and main.m take the
  app name, bundle ID, category, modules, RomFS marker and tables from
  the profile (GAME=<id>, workspace ~/<id>-work).
- dm/games/README(.zh-CN).md: the keys and how to add a game.
- The game comes from the NSPs' title ID and its profile in
  dm/games/; the versions to extract, the accepted build IDs, the
  modules to rewrite and the tables to compare all come from the
  profile. TITLE / BUILDS are gone from the script. Work folder:
  <NSP folder>/<id>_build/.
- A title with no profile is surveyed instead:
  <NSP folder>/<title ID>_survey/survey.md lists the NSPs, modules and
  build IDs, SDK version and components, Unity version, engine / API
  markers, RomFS folders, magics and extensions, insn_census counts,
  imports vs host hooks, and notes. Fire Emblem Engage was surveyed
  this way.
- APP_NAME setting; empty uses the game name from the base NSP's
  NACP (compressed title areas decoded), then the profile's app_name.
- PACKAGE and OUT_IPA default to the profile's package and ipa.
- Tested on Mario end to end from fresh extraction: the IPA is named
  "Super Mario Bros. Wonder" and carries the current chain's tables.
- README: presented as Switch games running natively on Apple
  platforms, with Mario as the one supported game. A games table
  (Mario playable, Fire Emblem Engage surveyed), component status,
  game profiles and how to add a game, the NSP script, generic
  step-by-step build commands (profile, workspace and version as
  variables), and a Mario section for the per-game notes (1.2.1).
- AGENTS.md: profiles, DM_GAME / GAME, workspaces, build-ID gating,
  the chain rule per profile.
- docs/agents: one repository with one profile per title; survey
  mode in 02-survey, including the compressed NACP title area.
- dm/gfx README (+ zh-CN): table paths in the profile.
- hle_nvn.c: drop the command memory callback / grant / caller
  logging, the overflow details, the +0x10 write log, the one-off
  NVN table dump, and the DM_DBG_GRANTS, DM_DBG_CALLSITES,
  DM_DBG_CMDMEM_SHRINK and DM_DBG_OLD_USED switches.
- nvn_mtl.m: drop the per-draw NaN probe (DM_DBG_NANPROBE), the
  colour target statistics (DM_DBG_TEXSTAT) and the PASSDUMP
  completion timing.
- Kept as regular diagnostics: the audio callback line every 2000
  callbacks (frames per callback, queued blocks, underruns) and
  DM_DBG_AU_FRAMES (docs/agents/03-bringup.md, crackling on iOS);
  DM_NVN_SHOT up to 4096 frames (the 05-debugging burst recipe).
- Mac 1.2.1 scripted run reaches the opening course with the same
  single red line as before.
- attach(): a render-target view that changes the format is attached
  as a Metal view of that format (kept until the submission completes),
  so pipeline formats follow it. Mario's last pass writes the RGBA8
  swapchain texture through an RGBA8_SRGB view; with the base texture
  attached, linear values were stored unencoded and the whole picture
  was darker: on the Mac and the iPhone every channel equalled the
  Switch value decoded from sRGB once more (0.55 -> 0.26). After the
  fix the Mac title frame matches a Switch screenshot (mean RGB
  0.556 / 0.621 / 0.633 vs 0.557 / 0.621 / 0.633).
- present_raw_src(): an sRGB-typed swapchain texture is sampled through
  a non-sRGB view, so the stored bytes reach the screen as on the
  Switch's scan-out (no change for Mario, whose swapchain is RGBA8).
  t_present_crop gets an sRGB case (34/34; fails without the fix).
- docs/agents/04-graphics.md and the mapping docs: the rule and how it
  was measured.
- patch_nso.py: three more x18 forms from IL2CPP code: an offset jump
  table (targets read at rewrite time), blr x18 (original return
  address kept for C++ unwinding) and an sp write from x18 (alloca).
  Mario's rewrite output stays byte-identical.
- loader.c: symbols resolve globally in load order, also for a
  module's references to its own exports (local / non-default
  visibility excepted). Engage's main overrides operator new / delete;
  sdk bound its own copies and freed Unity's blocks into the SDK heap.
- hle_svc.c: QueryMemory reports each module's Horizon layout (code,
  read-only, data, patch area) and other host memory as free, which
  the SDK's C++ unwinder (nn::ro::detail::GetExceptionInfo) needs.
- New takeovers: nn::fs::IsMounted, nn::ro (hle_ro.c), prepo
  Initialize, SDK 12 audio device names and OpenDefaultAudioOut, an
  SDK 12 hid block (single GetNpadState, modes, touch, gestures,
  six-axis details, colors, applets), movie::Decoder with no impl
  (hle_movie.c) and failing nvdrv opens (hle_nvdrv.c), and NVN getters
  / no-ops Engage calls. nvn.h: TextureGetMemoryPool returns a pointer.
- Makefile: a game stamp, so changing GAME rebuilds the host.
- docs/agents/03-bringup.md: catalogue entries for all of the above.
- Mario 1.2.1 scripted run still reaches the opening course with the
  same single red line.
- dm/games/fe_engage: identity and the 2.0.0 build IDs (main,
  subsdk0, sdk), modules in Horizon load order, RomFS marker, empty
  shader tables and their chain header. Memory: an 8 GB reservation
  with a 5.5 GB alias region for its virtual address memory (Mac only
  for now: iOS allows at most 6 GB without the extended-addressing
  entitlement); NVN constants are Mario's until measured.
- On the Mac the host boots Engage through Unity's startup and runs to
  the opening movie with nothing on screen yet: its shaders are in
  UnityFS bundles that shader_split.py cannot read, and movies are not
  decoded.
- README: the games table row.
- New dm/gfx/tools/unityfs.py: UnityFS bundles (LZ4 / LZMA blocks),
  serialized files (formats 19..22), objects read by their type trees
  (Unity's common string table comes from the game's own main), and a
  Shader object's per-platform compressed subprograms. The player's
  own files have no type trees and borrow the bundles' Shader tree of
  the same type hash.
- shader_split.py reads Unity Shader objects in a second pass: each
  Switch subprogram is one NVN program (0x60-byte header of per-stage
  offset / control size / code size, then control + code per stage);
  a program's vertex / pixel stages form a pair. Engage: 9,269
  shaders, 4,634 pairs. Mario's tables and package are byte-identical.
- Engage profile: shader groups engine / assets, measured NVN layout
  (texture handles 0x168 + 8 r, 128 slots; separate samplers 0x568),
  regenerated tables, chain a295a8035b7b. 9,268 of 9,269 compile (one
  geometry shader; Metal has none).
- dmsh_build.py: the translator's built-in bases only matter with
  per-slot facts, so the guard checks that; c2 reads count the sampler
  table and 16-byte rows overlapping a table as fillable.
- game.py: DM_GAME_NVN_SAMP_BASE. NSP script survey note updated.
- Mario chain is now 271056163ea2 (Mac and iOS libraries rebuilt,
  16,266 of 16,268 as before; c1_full regenerated).
seedds and others added 21 commits October 19, 2026 15:34
- Log messages, script output, test labels, Makefile errors and comments are English. Red log lines start with "[RED] " (was 【红】).
- Shader map stage column: vertex / pixel / compute / geometry / hull / domain (generators, dmsh_build / dmsh_facts and nvn_mtl.m stage_of follow).
- The NSP script's regexes match the new shader_split.py / dmsh_build.py summary lines; patch_nso cut scopes are all / host-only.
- Host UI text table (dm_i18n_tab.h) is English only; dm_lang_zh() removed.
- Text that matches game data (t_swkbd.c, t_textbox.c) is written as \x escapes.
- Shader chain: the chain files lose their bilingual comments, so every profile has a new chain version. dmsh_xlate.dll rebuilt from the translated Program.cs (SPIR-V byte-identical on 4,500 shaders of Wonder, TOTK and Age of Calamity), lock and dmsh_chain.h headers regenerated. c1_full.tsv restamped for Dread, 13 Sentinels and Wonder; the other profiles follow when their rebuild finishes.
- AGENTS.md and docs/agents: the language rule now covers logs; quoted log lines updated.
…r 7 more profiles; the NVN stub summary line no longer contains [RED]

Every rebuilt profile matches the previous chain: same shader counts, same Metal failures (Engage 1, 3D World 1, Three Houses 2, Odyssey 3), same iOS library counts. Metroid Dread on the Mac renders the same frames as before the change.
…l.tsv restamped

Same as the previous chain: 40,724 of 40,726 shaders (the 2 known Metal failures), 30 with an undecoded binding slot as in the last full build, 63,345 iOS libraries. All 11 NVN profiles are rebuilt.
…lays on the Mac; screenshots of both

Being ported: Tears of the Kingdom runs on an iPhone into the opening cave (the 5 GB guest layout fits),
frame rate still being worked on; Super Mario Galaxy plays on the Mac into the Star Festival, not yet
tested on an iPhone. The gallery gets Mac captures of both (TOTK after the stone-block fix). The touch
controls line names the 2D games so it covers every profile, and says Galaxy's pointer follows touches.
AGENTS.md drops the stale note that TOTK's memory layout is too large for an iPhone.
…efore Python 3.14

Tears of the Kingdom's .zs files need zstd dictionaries, read with compression.zstd, which only Python
3.14+ has. Older Pythons now use the backports.zstd package (pip install backports.zstd), the same API.
Galaxy moves from Being ported into the Games table (~3 GB IPA; packing collects its run-time shaders on
the Mac, as for Three Houses) and next to Three Houses in the gallery. Known issues: GX points and lines
are one pixel wide (the geometry shaders are not translated). AGENTS.md lists it among the twelve games
playable on the iPhone.
KTGL already updates the game 60 times a second on its main thread (a fixed 1/60 s step); the render
thread presents the latest update with the render mode's interval, 2 in the docked and handheld modes.
Per-build cuts on 1.2.0 main (patch_nso.py) set the per-mode interval tables to 1, as in the engine's
own unused 60 fps modes, so every update is shown at the same game speed. Two more cuts make the waits
cheap on the host: the frame limiter's yield-and-poll loop sleeps the time left (it spun 2 ms a frame
and ran at 59.5 updates a second), and the render thread's wait for the next update gets one frame
instead of 16 µs (a millisecond count passed to a microsecond wait; about 50,000 wakeups a second).
Mac, prologue battle: 59.9 fps, 55% of a core, 1.8 W of CPU energy (the original at 30 fps: 44%,
1.7 W). Not yet tested on an iPhone.
…Galaxy rows

The Games table's notes keep only what a player sees: Three Houses says it is upgraded to 60 fps,
Galaxy has no note.
The render thread forced present interval 2 while either of two flags was set: one for the full-screen
movie image (the opening movie), one from the scene object (the character creation screen after it, and
similar scenes). The engine's own 60 fps modes dropped to 30 there to keep 1080p; with the per-mode
tables at 1 it would also run the render thread's own steps at half speed. A cut at main+0x50fb7c
ignores both. Mac, new game: 59.9 fps through the movie and character creation; the movie lasts
210.6 s in both the original and the 60 fps build.
The route from a new game into the prologue battle counted presented frames at 30 fps. At 60 fps its
frame numbers double, and the repeating confirm step becomes Left, A, Left, A: A, Left, A loops forever
once it starts on an open dialog (A answers No, Left changes the selection, A reopens it), which
happened at character creation because A presses during the opening movie pause it and shift the
scenes after it. The new route reaches the battle in about 7 minutes. The DM_KEYS example in
05-debugging uses the same cycle.
…es; a short heap check

dm/games/profile_guess.py decides the profile keys a game's files show, each written with its reason:
graphics vulkan and the modules to load (a subsdk only when main takes something from it the host does
not supply), shader_vk_capture / shader_main_glslc / shader_separable / shader_glslc_capture, the memory
partition (giant bss, no heap, virtual address memory), the SDK 8 / 10 font and NVN API, Hagi's handheld
pointer. --check compares the guess with every profile in dm/games: all 13 agree on these keys.

After the rewrite the script sets mem_used from the rewritten modules (Age of Calamity's 72 MB), writes
the empty shader tables and chain header a provisional Vulkan game lacked, and boots a game with virtual
address memory that sets a heap until its heap request to size the heap region (about 7 s; Tears of the
Kingdom gets its 0x98000000 alias region). A minute's boot could not tell which games need render_cond,
tex_flush_upload or core_preempt, so they stay with the developer.

--provisional builds a game that has a profile from a guessed one (DM_GAMES_FIRST in game.py and the host
Makefile, whose profile header is now rewritten only when it changes); --no-heap-check skips the check.
A capture run whose host stops early now says so. hle_svc.c logs a heap request the pool check refuses.
…i fix, all chains rebuilt

- Profile 0100B04011742000 (update 16.0.2, RE Engine): KPKA PAK shaders (shader_split.py kpka_jobs), XCI base game in nx_extract and the NSP script, BIG_TEXT patch area in patch_nso.py.
- Sparse virtual pool: a 4 KB page table (vpt_*) that the replay reads textures through, dirty tracking per mapped page, texture views from the first mapped level.
- MultiDraw*IndirectCount with a CPU wait for the count; pending GPU writes indexed by page; bindless handles read from queued inline updates.
- sbuf_ubo binding kind, integer vertex formats into float inputs, clears on textures that are not render targets.
- Inline keyboard text, state and finished callback; ngc::ProfanityFilter host vtable.
- Ryujinx BindlessElimination follows phi webs (218 MHR pixel shaders); dmsh_xlate_bin and dmsh_chain.lock updated; dmsh_chain.h and c1_full.tsv rebuilt for every Maxwell profile.
- README: Monster Hunter Rise under being ported, gallery image, XCI base games, Ryujinx local fixes.
- dm/ios/tools/pack_ipa.py replaces the Payload/ copy and Info-ZIP: it packs the app, the shader
  libraries, the add-on content and the RomFS straight from their folders, reading and deflating on
  all cores (zip64, modes, symlinks, the profile's zip_store as before). Metroid Dread 156 s -> 12 s,
  Breath of the Wild 171 s -> 57 s (the T7 writes at about 310 MB/s).
- The shader libraries no longer go through Xcode (Gen/msl left the project): no 1.5 GB detour
  through the home disk.
- NSP script: the rewrite, the shader split and the iOS / Vulkan shaders are reused when a sha256
  of their inputs matches the one stored beside their output; the modules are rewritten in
  parallel; J = the core count; the extraction is kept by default (--no-keep-extracted).
  A Metroid Dread repeat build: about 8 min -> 19 s.
- The idle timer is off while the app is active: only touches reset it, so with a controller or in a cutscene the screen dimmed and locked.
- Open file limit raised from 256 to 4096 at host start; Documents/romfs and temp are kept out of device backups.
- Audio: observers for audio session interruptions (Siri, alarms, calls) and media services resets (dm_audio_reset recreates the AudioUnits); becoming active ends an interruption whose "ended" never came.
- A watchdog switches a started output whose device has not called back for 200 ms to the silent sink and retries the AudioUnit after 1, 2, 4, 8 s; a start that fails falls back the same way instead of aborting. t_audio scenario 3 stops a playing AudioUnit behind the host's back.
- GetCurrentProcessorNumber: a thread with no ideal core reports the lowest core of its mask, not core 0.
- patch_nso.py FRAME_STEP_BUILD (main 277178b7, 1.4.3): stubs step the game by the measured frame time instead of its own interval (2 = 30 fps), capped at the target (30 while a prerendered movie plays), with game time that ran ahead paid back by the next frames. Also the two readers of the fps, the D-pad menu fade and the swapchain argument. Sites from masagrator's FPSLocker config for this build; the pay-back from OJZen/totk-mobile; stubs written and assembled here.
- State page after the key page (fixups key FPS_STATE_OFF): the loader writes the target (profile key fps_target, DM_FPS_TARGET; 0 = every stub runs the original instructions) and the render scale (DM_RENDER_SCALE 0.5-1.0; any factor but 1 fixes the size and drops the game's dynamic resolution).
- hle_nvn.c paces presents by the cap instead of the game's interval and logs game time against real time every 1,800 presents.
- TOTK profile: fps_target 60. Mac (M4 Pro): 60 presents a second in the opening cave, game time 1.000 of real time; at 30 and 0 as before.
…ad spun a core on iOS)

- MessageSuperviseThread (main+0x6bc8fc4) waits on oe::GetNotificationMessageEvent with WaitAny, which does not clear it, then pops until the queue is empty. The host only ever signalled the event, so after the focus change at iOS launch it stayed set and the thread looped: 995 ms/s, 5-6 W on an iPhone.
- hle_oe.c mq_ev_sync: the event is set while a notification is queued and cleared when the last one is popped (as the am service does), decided under the queue lock; hle_thread.c hle_clear_system_event.
- DM_OE_SCRIPT also starts at the game's first GetNotificationMessageEvent, for games that pop only once the event fires. Mac with focus=2@5,focus=1@6: before 995 ms/s, CPU 109%, 6.97 W; after the thread is idle, 0.05 W. Hades still pops its notifications.
- t_oe: stubs for the system event calls (it no longer linked) and 6 checks of the event state; 53/53.
- TOTK moves from "being ported" into the games table (60 fps on the iPhone, 30 on the Switch); DM_FPS_TARGET=30 in env.txt keeps 30 for battery.
- Monster Hunter Rise: runs on an iPhone at 30 fps from character creation into the opening.
- AGENTS.md: thirteen playable games.
…ost)

- hle_fpslock.c: on every present the host writes the profile's fps_target into RE Engine's frame limit at [main+0x1295b3f0]+0x434 (FPSLocker's address for build c9a3dd77; the game sets 30 after boot). Its frame loop (main+0x6b106c8) waits until [+0x430]/[+0x434] sixtieths of a second have passed and steps by the time that really passed.
- The game also asks for present interval 2: the profile's present_interval display ignores it. Both are needed; either alone stays at 30.
- Profile: fps_target 60, present_interval display; DM_FPS_TARGET=30 gives back 30. Mac: frame time p50 16.67 ms.
…n whole vsyncs decided by the host

The host decides each frame's step (1 to 3 vsyncs) from its own measurements (nvn_fstep.h, hle_nvn.c fstep_tick),
keeps the frame on screen that long and pays back real time lost to late frames one vsync per frame: even motion,
game time = real time, and 30 fps (not 40) when 60 does not hold. Tears of the Kingdom's frame-step stub writes
60 / step; Breath of the Wild gets a stub at the framework's setWaitVsyncInterval, so its VFR and every reader of the
framework's interval take the host's step, and its VFR override is published so the host holds it.
DM_FRAME_STEP=legacy (profile key frame_step) keeps each game's earlier method for the iPhone A/B test.

Mac: both games at 1.000 of real time at 60, and at 30 with 12 ms added to every frame. The docs record a
pre-existing intermittent Breath of the Wild crash at the world load (legacy too).
A stub sets the scale where the game's dynamic resolution applies its own (main+0x1266880), so the scene buffers, the
shader's resolution ratio and the LOD check all follow it; a second stub takes that apply block every frame when the
factor is not 1.0 (the game only runs it after recomputing its scale). 1.0, the default, keeps the game's dynamic
resolution. Mac: at 0.5 every scene pass halves while the shadow maps, the 1920x1080 output and the HUD keep their
size; handheld works too (960x540 at 0.75). The Mac's GPU time does not change (about 650 passes a frame, fixed cost
first); the iPhone test decides whether it helps there.
Initialize bypasses the Horizon time service, leaving the native adjustable clock without a context. Reuse the existing standard user clock policy for reads and make adjustment unnecessary on the host.

Add forced-symbol ABI tests for fixed and live time, including output canaries and repeated adjustment. The registration checks fail against the unmodified implementation.
@BeeeeeMo

Copy link
Copy Markdown
Contributor Author

Retested on c628df1 with Animal Crossing: New Horizons (base v0, SDK 9), using the native Mac host on Apple M2. This base includes the clock-context fix discussed in #14. Removing both adjustable-clock hooks still aborts during startup after about 0.8 seconds (exit 42), without diagnostic probes. A separate probed run confirmed that GetSystemClockContext() now returns success, but the subsequent native MonotonicSystemClock::GetCurrentTime() asserts because the SDK shared-memory client is not initialized by the host's time::Initialize takeover.

Both variants kept the same local region, shared-font-list and save-mount hooks, which are outside this PR, and used separate test saves. With the two clock hooks present, the control run reached the opening scene and ran for 25 seconds before being stopped by the test, without that assertion. This shows the pair is not fully superseded on this base; whether the Adjust() takeover alone can now be dropped remains untested. This is Mac startup evidence, not a claim of full game support or iOS runtime verification.

@seedds

seedds commented Oct 21, 2026

Copy link
Copy Markdown
Owner

I am sorry that I accidentally closed the PR. I will look into it.

oliverames pushed a commit to oliverames/nxnative that referenced this pull request Nov 16, 2026
… out a NACP that is not 0x4000 bytes

Symptom: a NUP made by the nup tool since its PR seedds#20 (merged 2026-11-04) writes every
meta record's type one too low (NPDM 0, NACP 1, icon 2, localized icons 9). pack_nup.py
read SPEC section 5's numbers, so for such a file it saved the icon JPEG as control.nacp
and the display version as icon.jpg: a blank game name, a random language list and no
icon. Separately, a NACP record that is not 0x4000 bytes was saved as control.nacp as it
was.

Fix: Package.meta() now tells a shifted block and reads every type one up. The records
decide first (the 0x4000-byte NACP at type 1 or 2, else a JPEG or PNG icon at 2 or 3);
only when they cannot tell does nup's PR seedds#32 rule decide (a record of type 0, or one of
type 7 that is not 32 bytes, the build ID's size). A block from an older nup is read as
it is. control() says in one line per package that it read a block one type up, and leaves
out a NACP record of another size with a line; a base game's good NACP still fills in for
an update that lacks one. The lines also show in a build with a profile, which otherwise
packs quietly (pack_version takes a note= callback, and the NSP script's survey passes its
own output to control()). docs/development.md and the README say it.

Tests: synthetic shifted and SPEC-numbered blocks, a type 7 record of 32 bytes and one of
another size, shifted localized icons, wrong-size NACPs, a standalone update whose own bad
NACP falls back to the base record, the line said once per package, and the build and the
survey saying it. test_nsp_nup.py passes (53 tests, 12 new) with backports.zstd, lz4 and
capstone installed; test_docs passes. On a Mac (M2 Pro, macOS 27.3) test_nsp_nup.py passes too (53 tests). test_nsp_mac_app.py has 23 errors both with and
without this change on Linux (it needs macOS). Not checked: the Mac app build, and a real
NUP written by nup (the claim about nup's PR seedds#20 and seedds#32 is NX18's, not re-checked).

Ported from NX18 (kencalx/NX18), by hand since the code moved:
3acdfeacb kencalx/NX18@3acdfeacb, with the follow-up fixes in
0d343ee5d and 9fffe70e0 folded in. Left out: everything about NX archive input
(scripts/pack_nx.py and its tests, the title.txt and icon.edited.jpg files, the app name
from an NX's display title).

Co-authored-by: kencalx <105067885+kencalx@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RcRaRTbNVNsBJcfGqFidW1
seedds added a commit to oliverames/nxnative that referenced this pull request Nov 20, 2026
Upstream nup PR seedds#20 started its TLV enum at 0 instead of SPEC §5's
1. This wrote JPEG icons at the NACP type and display versions at
the icon type. Normalize affected blocks at the shared reader.
Prefer NACP and icon content, then use the markers described in
upstream nup PR seedds#32. Preserve correctly numbered control data when
it appears with shift markers.

Reject NACP payloads of any size other than 0x4000 in the same
reader. Package scanning previously trusted the ID fields of some
truncated or oversized payloads, which could reject valid DLC.
Filter those payloads before either scanning or extraction uses them.

Verified with the upstream writer and a one-line enum correction,
real shifted and SPEC-numbered archives, and synthetic regression
cases for wrongly sized NACPs and valid titles beginning with META.

Ported from kencalx/NX18 (3acdfeacb, 0d343ee5d, 9fffe70e0).
PR seedds#2879

Co-authored-by: Oliver Ames <7366664+oliverames@users.noreply.github.com>
Co-authored-by: kenCalx <105067885+kencalx@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
seedds added a commit that referenced this pull request Nov 21, 2026
Upstream nup PR #20 started its TLV enum at 0 instead of SPEC §5's
1. This wrote JPEG icons at the NACP type and display versions at
the icon type. Normalize affected blocks at the shared reader.
Prefer NACP and icon content, then use the markers described in
upstream nup PR #32. Preserve correctly numbered control data when
it appears with shift markers.

Reject NACP payloads of any size other than 0x4000 in the same
reader. Package scanning previously trusted the ID fields of some
truncated or oversized payloads, which could reject valid DLC.
Filter those payloads before either scanning or extraction uses them.

Verified with the upstream writer and a one-line enum correction,
real shifted and SPEC-numbered archives, and synthetic regression
cases for wrongly sized NACPs and valid titles beginning with META.

Ported from kencalx/NX18 (3acdfeacb, 0d343ee5d, 9fffe70e0).
PR #2879

Co-authored-by: Oliver Ames <7366664+oliverames@users.noreply.github.com>
Co-authored-by: kenCalx <105067885+kencalx@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
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