Play your own Switch games on iPhone/iPad — one-click macOS app, no terminal. | 把 Switch 游戏装进 iPhone:图形界面一键构建,不用命令行。Bring your own game.
Swift apple-siliconcustom-formathomebrewiosipaipadipadosiphonemetalnative-portnintendo-switchnxnativeromfsswitch-games
Migrate the fork's changes to the patch queue: 22 patches on seedds/nxnative 75065df
v0lumehi95dda8b1e7d5
diff --git a/dm/fork_patches.txt b/dm/fork_patches.txtnew file mode 100644index 00000000..309bb4d9--- /dev/null+++ b/dm/fork_patches.txt@@ -0,0 +1,22 @@+runtime-profile+romfsarc+ios-game-data-folder+ios-slim-ipa+ios-entitlements+nsp-dotnet-home+nsp-exfat-appledouble+nsp-early-checks+nsp-chain-changed-note+nsp-work-dir+bc-cpu-decode+mac-keymap+nro-code-start+mac-library-folder+hades2-update-profile+hle-time-adjustable-clock+env-switches-verify+touchpad-geometry+ios-probe+fork-docs+ref-hle-hid-d2r+fork-patches-stampdiff --git a/dm/games/0100A00019DE0000/game.fork.tsv b/dm/games/0100A00019DE0000/game.fork.tsvdeleted file mode 100644index 39368d0c..00000000--- a/dm/games/0100A00019DE0000/game.fork.tsv+++ /dev/null@@ -1,69 +0,0 @@-# Hades II (Supergiant Games' engine on NVN, SDK 19.3.9 base / 20.5.15 update).-# Base game v0 (display version 0.0.126424) and update v1.0.137848 are both registered.-# Started from the NSP script's provisional profile; values marked "Mario's" are not measured for this game yet.-# Unlike Hades (Vulkan), the Switch version renders with NVN: its 88 shaders are BNSH files in Shaders/NVN/bin (.vert / .frag; the .shader files list each program's pair).-# The ExeFS has only main and sdk. main's EOS_* imports (Epic Online Services, from nro/EOSSDK-Switch-Shipping.nro, loaded through nn::ro) stay offline: the host-# registers no NRR, so the game never loads the NRO.--# ---- Identity -----title_id 0100A00019DE0000-program_id 0100A00019DE0000--# ---- App -----name Hades II-ipa HadesII.ipa-app_category public.app-category.action-games-# the right stick aims (the weapons with ManualAiming in Game/Weapons/PlayerWeapons.sjson)-pad_layout full--# ---- Versions -----# The update's build IDs come from its own ExeFS (the base game's from upstream's profile).-build v0 0.0.126424 main=5219053e5eb156be80fbb2f303779531 sdk=d83a56a5558798414c78ec722867a7da-build v1 1.0.137848 main=8ce1ac48e9fa74479051f3520e632df4 sdk=190030518b5d64e5d87b84bc54661af9-package v1-shader_versions v0 v1--# ---- Files -----modules main sdk-romfs_marker Audio/Switch/Music.bank-zip_store .bank:.bik:.fsb:.gpk:.nro:.pkg:.xnb:.metallib--# ---- Graphics ------# ---- Memory -----# The NPDM declares no system resource (META +0x14 = 0): the game uses SetHeapSize. It asks for 3.10 GB (pool − used memory), which the 3.25 GB heap region of-# the 4 GB layout holds. main carries an 82 MB bss: the rewritten modules take more than the default 64 MB of used memory, so SetHeapSize(pool − 64 MB) would not fit-mem_reserve 0x100000000-mem_alias 0x10000000-mem_stack 0x10000000-app_pool 0xCD500000-mem_used 0x6c00000--# ---- Widescreen (host only, NOT enabled for this game) -----# The swapchain size 1280x720 is hardcoded twice in main: a rodata entry at +0x6d337c ({u32 w,-# u32 h}, dead data) and two immediate instructions at +0x2a6080 (movz/movk x8) that write it into-# a config object. Patching the rodata entry does nothing (the immediates win); patching the-# immediates too makes the init run and then crash later (main+0x48e5a4, null deref in the-# 0x2a7a20 call chain): the value feeds more than the swapchain, and whatever else depends on-# 1280x720 specifically is not satisfied by just widening it. Real widescreen for this title-# needs its resolution pipeline reversed — out of scope here.-# Round 2 detail: with the immediates patched to 1600x900, the init crashes at-# main+0x48e5a4 (ldr x2,[x21,#8] with a null x21) inside the 0x2a7a20 chain — the-# allocation at 0x499840 fails or a lookup misses for the wider size. d2r-mobile's-# widescreen works because its title's whole resolution path was brought up: PARAMS-# slots (4 sites) plus the KASPECT aspect cap plus the derived-mask fix, each found-# and tested one by one. The same depth of work is needed here.--# ---- NVN driver constant segments (Mario's values, the translator's built-in layout, except the texture slot count) -----# The game's shaders bind textures at fixed, sparse slots: c2 handles at 0x20 + 8 r for r = 0, 1, 3, 6, 8, 11, 15, 21, 25, 26, 30, 31 and 34 over all 88 shaders.-# Slot 34 (SceneFade.frag, 0x130) lies past Mario's 32 slots, where his image table starts; this game has no image bindings and no shader reads c2 at run time-nvn_tex_base 0x20-nvn_tex_slots 35-nvn_samp_base 0x568-nvn_img_base 0x120-nvn_img_slots 8-nvn_ssbo_bases vs=0x110 ps=0x510 cs=0x310--# ---- Shader split -----shader_groups /Shaders/=shaders-shader_note Hades II shaders (Shaders/NVN/bin)diff --git a/dm/ios/Sources/main.m b/dm/ios/Sources/main.mindex 5afddbb6..c4c84e5d 100644--- a/dm/ios/Sources/main.m+++ b/dm/ios/Sources/main.m@@ -178,6 +178,9 @@ static int boot_env(void) {NSString *log = [doc stringByAppendingPathComponent:@"log.txt"], *prev = [doc stringByAppendingPathComponent:@"log.prev.txt"];[fm removeItemAtPath:prev error:nil]; [fm moveItemAtPath:log toPath:prev error:nil];if (freopen(log.fileSystemRepresentation, "w", stderr)) setvbuf(stderr, NULL, _IOLBF, 0);+ // First line of the log: the fork's patches this build carries (Info.plist DMForkPatches), so a report says whether it comes from a build beyond upstream's support+ NSString *fork_patches = [NSBundle.mainBundle objectForInfoDictionaryKey:@"DMForkPatches"];+ fprintf(stderr, "fork patches: %s\n", [fork_patches isKindOfClass:NSString.class] && fork_patches.length ? fork_patches.UTF8String : "none");// Environment switch files (for on-device diagnostics: a sideloaded app cannot be given environment variables from outside): one KEY=VALUE per line, # starts a comment; Documents/env.txt takes precedence over dm/env.txt in the bundle (put there by build_ipa.sh's DM_ENV_FILE)NSMutableArray<NSString *> *from_file = [NSMutableArray array], *from_launch = [NSMutableArray array];for (char **e = environ; *e; e++) { // set at launch (Xcode, devicectl): before the env files, and the launcher keeps themdiff --git a/dm/ios/project.yml b/dm/ios/project.ymlindex 298b2eed..e9d9c174 100644--- a/dm/ios/project.yml+++ b/dm/ios/project.yml@@ -44,6 +44,7 @@ targets:LSApplicationCategoryType: ${DM_APP_CATEGORY} # game profile app_categoryDMShowFPS: ${DM_SHOW_FPS} # YES = the frame-rate counter is on (front_ios.m; set by build_ipa.sh)DMLanguage: ${DM_LANG} # the game language code (main.m sets DM_LANG from it; set by build_ipa.sh)+ DMForkPatches: ${DM_FORK_PATCHES} # the fork's patches this build carries (dm/fork_patches.txt, written by scripts/patches.py; set by build_ipa.sh)LSSupportsGameMode: trueGCSupportsControllerUserInteraction: true # Physical controllers (GameController)GCSupportedGameControllers:diff --git a/dm/ios/tools/build_ipa.sh b/dm/ios/tools/build_ipa.shindex 3d8f5c73..a0c79a3c 100755--- a/dm/ios/tools/build_ipa.sh+++ b/dm/ios/tools/build_ipa.sh@@ -38,6 +38,7 @@ VNACP=$(dirname "$ROMFS")/control.nacp; [ -f "$VNACP" ] || VNACP=$W/data/v0/contexport LC_ALL=C DM_BUNDLE_ID=${DM_BUNDLE_ID:-org.nxnative.$(echo "$GAME" | tr 'A-Z' 'a-z')} DM_DISPLAY_NAME DM_APP_VERSION DM_APP_CATEGORY=$(gp app_category) DM_TEAM_ID=${DM_TEAM_ID:-0000000000} # placeholder identity: unsigned, the install tool replaces itif [ "${DM_SHOW_FPS:-0}" = 1 ]; then export DM_SHOW_FPS=YES; else export DM_SHOW_FPS=NO; fiexport DM_LANG=${DM_LANG:-en-US}+export DM_FORK_PATCHES=$(paste -sd, "$DM/fork_patches.txt" 2>/dev/null || true) # DMForkPatches in Info.plist (scripts/patches.py writes the list; empty on a build without fork patches)if [ "$PREPARE_XCODE" = YES ]; thenIOS=${DM_XCODE_PROJECT_DIR:-$W/xcode}mkdir -p "$IOS" || die "mkdir $IOS"diff --git a/dm/ios/tools/build_smoke.py b/dm/ios/tools/build_smoke.pyindex aa5732a8..2e94b2e7 100644--- a/dm/ios/tools/build_smoke.py+++ b/dm/ios/tools/build_smoke.py@@ -55,7 +55,7 @@ def main():DM_BUNDLE_ID='org.nxnative.ci', DM_DISPLAY_NAME='CI build fixture',DM_APP_VERSION='1.0', DM_APP_CATEGORY=profile.get('app_category'),DM_TEAM_ID='', DM_SCHEME_NAME='DmIOS', DM_APPICON='',- DM_SHOW_FPS='NO', DM_LANG='en-US')+ DM_SHOW_FPS='NO', DM_LANG='en-US', DM_FORK_PATCHES='')def run(*command, capture=False):return subprocess.run([str(c) for c in command], cwd=project, env=env,diff --git a/dm/mac/launcher.c b/dm/mac/launcher.cindex af479db7..2cf5f549 100644--- a/dm/mac/launcher.c+++ b/dm/mac/launcher.c@@ -180,6 +180,7 @@ int main(int argc, char **argv) {snprintf(dm, sizeof dm, "%s/dm", res); snprintf(romfs, sizeof romfs, "%s/romfs", res);char name[256] = "nxnative", id[64] = "", marker[512] = "", lang[32] = "";if (!info_string("CFBundleName", name, sizeof name)) snprintf(name, sizeof name, "nxnative");+ char fork_patches[1024] = ""; info_string("DMForkPatches", fork_patches, sizeof fork_patches);info_string("DMRomfsMarker", marker, sizeof marker); info_string("DMLanguage", lang, sizeof lang);if (!info_string("DMTitleID", id, sizeof id) || strchr(id, '/')) { alert(name, "This app has no title ID in its Info.plist (DMTitleID): pack it again with build_ipa_from_nsp.py --platform mac-app."); return 1; }struct stat st; snprintf(p, sizeof p, "%s/romfs.img", res);@@ -251,6 +252,7 @@ int main(int argc, char **argv) {rename(log, prev);int fd = open(log, O_WRONLY | O_CREAT | O_TRUNC, 0644);if (fd >= 0) { dup2(fd, 1); dup2(fd, 2); close(fd); setvbuf(stdout, NULL, _IOLBF, 0); }+ fprintf(stderr, "fork patches: %s\n", *fork_patches ? fork_patches : "none"); // first line of the log (Info.plist DMForkPatches)fprintf(stderr, "launcher: %s (%s), host %s\n", name, id, host);CFArrayRef rules = setting_rules(); // the settings the launch environment already set: the window shows them, fixedfor (CFIndex i = 0; rules && i < CFArrayGetCount(rules); i++) { char env[128]; if (rule_env(CFArrayGetValueAtIndex(rules, i), env, sizeof env) && getenv(env)) add_key(&g_launch_keys, env); }diff --git a/patches/0001-runtime-profile.patch b/patches/0001-runtime-profile.patchnew file mode 100644index 00000000..5dd33e2a--- /dev/null+++ b/patches/0001-runtime-profile.patch@@ -0,0 +1,808 @@+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001+From: v0lumehi <[email protected]>+Date: Wed, 28 Oct 2026 13:33:52 +0100+Subject: [PATCH] Runtime game profile: dm_profile() and DM_PROFILE++The host reads a game profile at run time (hle_profile.c), with the compiled game_profile.h as the fallback and+DM_PROF_<key> overrides on top. game.py gains a "profile" subcommand that writes the file.+Touches every file that used a DM_GAME_* macro for the memory layout, game_env, alloc_big_align and the program id.++Upstream-Status: pending (design note seedds/nxnative#492)+Reason: One host binary for every game: the profile constants are read at run time (DM_PROFILE, dm_profile()), not only as compile-time macros; the launcher needs it+Issue: LNPANDY/NX2Apple#123+---+ dm/games/game.py | 34 ++++++ dm/host/dm.h | 1 ++ dm/host/hle_fpslock.c | 2 +-+ dm/host/hle_fs.c | 2 +-+ dm/host/hle_os.c | 4 +-+ dm/host/hle_profile.c | 242 ++++++++++++++++++++++++++++++++ dm/host/hle_profile.h | 37 ++++++ dm/host/hle_svc.c | 42 ++++--+ dm/host/loader.c | 2 +-+ dm/host/tests/Makefile | 48 +++---+ dm/host/tests/t_layout_runtime.c | 103 ++++++++++++++ dm/ios/Sources/DmGamepad.m | 2 +-+ docs/env_switches.tsv | 1 ++ 13 files changed, 474 insertions(+), 46 deletions(-)+ create mode 100644 dm/host/hle_profile.c+ create mode 100644 dm/host/hle_profile.h+ create mode 100644 dm/host/tests/t_layout_runtime.c++diff --git a/dm/games/game.py b/dm/games/game.py+index 5527a666..48e1db1b 100644+--- a/dm/games/game.py++++ b/dm/games/game.py+@@ -186,6 +186,40 @@ if __name__ == '__main__':+ out, text = Path(a[2]), header(load(a[1])); out.parent.mkdir(parents=True, exist_ok=True)+ if not (out.exists() and out.read_text() == text): # written only when it changes: make runs this every time (the profile folder can change under the same GAME), and an unchanged header must not rebuild the host+ tmp = out.with_name(out.name + '.tmp'); tmp.write_text(text); tmp.replace(out)++ elif len(a) == 3 and a[0] == 'profile': # the runtime profile the host reads from DM_PROFILE (hle_profile.h): the header's values, as the TSV form++ g = load(a[1]); out = Path(a[2]); out.parent.mkdir(parents=True, exist_ok=True)++ M = dict(re.findall(r'^#define (DM_GAME_\w+) (.*)$', header(g), re.M)) # exactly what the compiled profile would hold++ # macro → the runtime profile's key (hle_profile.c set_kv); the header's spelling of the value is the file's++ KEYS = [('title_id', 'ID'), ('program_id', 'PROGRAM_ID'), ('name', 'NAME'), ('romfs_marker', 'ROMFS_MARKER'),++ ('modules', 'MODULES'), ('mem_reserve', 'MEM_RESERVE'), ('mem_alias', 'MEM_ALIAS'), ('mem_stack', 'MEM_STACK'),++ ('app_pool', 'APP_POOL'), ('mem_used', 'MEM_USED'), ('sys_resource', 'SYS_RESOURCE'), ('mem_map_limit', 'MEM_MAP_LIMIT'),++ ('present_interval', 'PRESENT_DISPLAY'), ('core_preempt', 'CORE_PREEMPT'), ('alloc_big_align', 'ALLOC_BIG_ALIGN'),++ ('fps_target', 'FPS_TARGET'), ('fps_hold', 'FPS_HOLD'), ('present_snap', 'PRESENT_SNAP'), ('pso_mtl4', 'PSO_MTL4'),++ ('shared_font', 'SHARED_FONT_TTF'), ('pad_layout', 'PAD_LAYOUT'), ('op_mode', 'OPMODE'), ('perf_mode', 'PERF_BOOST'),++ ('feedback_snap', 'FEEDBACK_SNAP'), ('tex_flush_upload', 'TEX_FLUSH_UPLOAD'), ('render_cond', 'RENDER_COND'),++ ('tex_dirty_upload', 'TEX_DIRTY_UPLOAD'), ('tex_dyn_slots', 'TEX_DYN_SLOTS'), ('gpu_timestamps', 'GPU_TS_SEGMENT'),++ ('vconv_range', 'VCONV_RANGE'), ('game_args', 'ARGS'), ('game_env', 'ENV')]++ def val(macro): # the header's C spelling → the file's plain spelling++ v = M.get('DM_GAME_' + macro)++ if v is None: return None++ v = v.strip()++ if v.startswith('{') and v.endswith('}'): # {"main", "sdk"} → main sdk++ return ' '.join(x.strip().strip('"') for x in v[1:-1].split(',') if x.strip())++ if v.startswith('"'): return v[1:-1]++ return v[:-3] if v.endswith('ull') else v++ L = [f'# Runtime game profile of {g.id} ({g.get("name")}), written by dm/games/game.py profile from {g.dir}/game.tsv',++ '# Read by the host from DM_PROFILE (hle_profile.c set_kv): KEY<TAB>VALUE, # starts a comment. Every value the compiled',++ '# profile would hold is written, so the file alone describes the game.']++ for key, macro in KEYS:++ v = val(macro)++ if v is not None: L.append(f'{key}\t{v}')++ api = [val('NVN_API_MAJOR'), val('NVN_API_MINOR')]++ if api[0] is not None: L.append(f'device_api\t{api[0]}.{api[1] or 0}')++ for b, d in re.findall(r'\{"([0-9a-f]+)", "([^"]*)"\}', M.get('DM_GAME_DISPLAY_VERSIONS', '')):++ L.append(f'display_version\t{b}\t{d}')++ text = '\n'.join(L) + '\n'++ if not (out.exists() and out.read_text() == text): out.write_text(text, encoding='utf-8') # unchanged: keep the mtime++ print(out)+ elif len(a) == 2 and a[0] == 'dir':+ print(load(a[1]).dir)+ elif len(a) == 3 and a[0] == 'link': # link → the profile folder (replaced when it points elsewhere)+diff --git a/dm/host/dm.h b/dm/host/dm.h+index 4f94bbb0..54a96b35 100644+--- a/dm/host/dm.h++++ b/dm/host/dm.h+@@ -7,6 +7,7 @@+ #include <stdlib.h>+ #include <string.h>+ #include "game_profile.h" // constants of the current game profile (generated from dm/games/<id>/game.tsv, chosen by the Makefile's GAME)++#include "hle_profile.h" // the runtime profile (DM_PROFILE): every constant above can also come from it; dm_profile() is the accessor++ // Explicit host work does not occupy a guest core (Metal submission, or a blocked native codec lock). A contended host mutex must count as blocked: a signal's same-core handoff+ // can otherwise wait forever for a peer that needs the signaller's native lock. Uncontended locks retain guest ordering; the counter nests inside existing host work.+diff --git a/dm/host/hle_fpslock.c b/dm/host/hle_fpslock.c+index be3b6224..23cc22d2 100644+--- a/dm/host/hle_fpslock.c++++ b/dm/host/hle_fpslock.c+@@ -71,7 +71,7 @@ void dm_fps_lock_tick(void) {+ for (int i = 0; i < g_nmod; i++) if (!strcmp(g_mod[i].name, "main"))+ for (int k = 0; k < NLOCKS; k++) if (!strcmp(g_mod[i].build_id, k_locks[k].build)) { rows[nrow++] = k; base = g_mod[i].base; }+ if (!nrow) return;+- const char *e = getenv("DM_FPS_TARGET"); int t = e ? atoi(e) : DM_GAME_FPS_TARGET; src = e ? "DM_FPS_TARGET" : "game profile fps_target";++ const char *e = getenv("DM_FPS_TARGET"); int t = e ? atoi(e) : dm_profile()->fps_target; src = e ? "DM_FPS_TARGET" : "game profile fps_target";+ if (t != 0 && t != 30 && t != 60) { LOG("[RED] DM_FPS_TARGET=%s: must be 0, 30 or 60; leaving the game's frame limit", e); t = 0; }+ if (!t) { for (int r = 0; r < nrow; r++) LOG("main: %s left as the game sets it (%s)", k_locks[rows[r]].what, src); return; }+ target = t; state = 0;+diff --git a/dm/host/hle_fs.c b/dm/host/hle_fs.c+index 26da5c05..92bb7a5b 100644+--- a/dm/host/hle_fs.c++++ b/dm/host/hle_fs.c+@@ -571,7 +571,7 @@ HLE_FORCE("_ZN2nn2fs14ExtendSaveDataERKNS_7account3UidEll", "fsp-srv; extend sav+ HLE_FORCE("_ZN2nn2fs14EnsureSaveDataERKNS_7account3UidE", "fsp-srv; the save directory is created at mount time", Result, h_fs_EnsureSave, const void *uid) { (void)uid; return RES_OK; }+ // Another application's save data (Tears of the Kingdom asks by application ID and would mount it read-only): the host keeps only this game's own save, which exists once mounted+ HLE_FORCE("_ZN2nn2fs18IsSaveDataExistingENS_13ApplicationIdERKNS_7account3UidE", "fsp-srv; only this game's own save data exists", int, h_fs_SaveExisting, uint64_t app, const void *uid) {+- (void)uid; LOG("fs asks whether save data exists: program %016llx → %s", (unsigned long long)app, app == DM_GAME_PROGRAM_ID ? "this game, yes" : "another program, no"); return app == DM_GAME_PROGRAM_ID;++ (void)uid; LOG("fs asks whether save data exists: program %016llx → %s", (unsigned long long)app, app == dm_profile()->program_id ? "this game, yes" : "another program, no"); return app == dm_profile()->program_id;+ }+ HLE_FORCE("_ZN2nn2fs21MountSaveDataReadOnlyEPKcNS_13ApplicationIdERKNS_7account3UidE", "fsp-srv; another program's save data: none", Result, h_fs_MountSaveRO, const char *name, uint64_t app, const void *uid) {+ (void)uid; LOG("[RED] fs read-only mount of another program's save data %s: program %016llx, the host has none", name, (unsigned long long)app); return 0x7d402u; // fs ResultTargetNotFound+diff --git a/dm/host/hle_os.c b/dm/host/hle_os.c+index 2d1afec7..14b3ee58 100644+--- a/dm/host/hle_os.c++++ b/dm/host/hle_os.c+@@ -120,7 +120,7 @@ HLE_FORCE("_ZN2nn6crypto36GenerateCryptographicallyRandomBytesEPvm", "csrng serv+ // The profile's game_env (KEY=VALUE, separated by spaces; DM_GAME_ENV overrides it, also from Documents/env.txt) answers getenv for those names; any other name goes to the SDK's own getenv+ static const char **g_env_kv; // "KEY=VALUE" strings, NULL-terminated+ static void game_env_init(void) {+- const char *e = getenv("DM_GAME_ENV"); if (!e) e = DM_GAME_ENV;++ const char *e = getenv("DM_GAME_ENV"); if (!e) e = dm_profile()->genv;+ int n = 0; for (const char *p = e; *p; p++) n += *p == '=';+ if (!(g_env_kv = calloc((size_t)n + 1, sizeof *g_env_kv))) die("game_env allocation failed");+ char *s = strdup(e); int k = 0;+@@ -152,7 +152,7 @@ static void sa_init(void) {+ g_sa_alloc = ms ? module_sym(ms, "_ZN2nn3mem17StandardAllocator8AllocateEm") : NULL;+ g_sa_alloc_al = ms ? module_sym(ms, "_ZN2nn3mem17StandardAllocator8AllocateEmm") : NULL;+ if (!g_sa_alloc || !g_sa_alloc_al) die("StandardAllocator::Allocate not found in the SDK");+- g_sa_big_align = DM_GAME_ALLOC_BIG_ALIGN;++ g_sa_big_align = dm_profile()->alloc_big_align;+ if (g_sa_big_align) LOG("StandardAllocator::Allocate: allocations ≥ 64 KB are 64 KB aligned (game profile alloc_big_align: memory pool storage, see hle_os.c)");+ }+ HLE_FORCE("_ZN2nn3mem17StandardAllocator8AllocateEm", "passed straight to the SDK; with the profile's alloc_big_align (13 Sentinels, Unicorn Overlord) allocations ≥ 64 KB are 64 KB aligned (memory pool start)", void *, h_mem_SAAllocate, void *self, size_t size) {+diff --git a/dm/host/hle_profile.c b/dm/host/hle_profile.c+new file mode 100644+index 00000000..03ce4268+--- /dev/null++++ b/dm/host/hle_profile.c+@@ -0,0 +1,242 @@++// Runtime game profile: see hle_profile.h. One IPA for every game reads its layout, switches and tables from DM_PROFILE++// instead of having them compiled in (game_profile.h stays the fallback, so a build without DM_PROFILE is unchanged).++#include "dm.h"++#include "hle_profile.h"++#include <ctype.h>++++static struct dm_profile P;++static int g_loaded;++++static void copy_str(char *dst, size_t n, const char *src) {++ if (!n) return;++ size_t i = 0;++ for (; src && src[i] && i + 1 < n; i++) dst[i] = src[i];++ dst[i] = 0;++}++static int truthy(const char *v) { // "1", "on", "yes", "true" (case-insensitive) = on; "0", "off", "no", "false", "" = off++ if (!v) return 0;++ return !(v[0] == '0' || !strcasecmp(v, "off") || !strcasecmp(v, "no") || !strcasecmp(v, "false") || !v[0]);++}++static uint64_t num(const char *v, uint64_t dflt) {++ if (!v || !*v) return dflt;++ char *e = NULL;++ uint64_t r = strtoull(v, &e, 0);++ return e && e != v ? r : dflt;++}++++// ---- defaults: exactly what game_profile.h (generated from game.tsv) compiles in ----++// A profile header may be partial (the unit tests' synthetic one carries only the memory constants), so every group is guarded:++// a missing macro means "the game does not set this key", which is also what game.py leaves out when game.tsv has no such row.++#ifndef DM_GAME_ID++#define DM_GAME_ID ""++#define DM_GAME_NAME ""++#define DM_GAME_ROMFS_MARKER ""++#define DM_GAME_MODULES {0}++#define DM_GAME_NMOD 0++#endif++#ifndef DM_GAME_PROGRAM_ID++#define DM_GAME_PROGRAM_ID 0ull++#endif++#ifndef DM_GAME_MEM_RESERVE++#define DM_GAME_MEM_RESERVE 0ull++#define DM_GAME_MEM_ALIAS 0ull++#define DM_GAME_MEM_STACK 0ull++#define DM_GAME_APP_POOL 0ull++#define DM_GAME_MEM_USED 0x4000000ull++#define DM_GAME_SYS_RESOURCE 0ull++#define DM_GAME_MEM_MAP_LIMIT 0++#endif++#ifndef DM_GAME_DISPLAY_VERSIONS++#define DM_GAME_DISPLAY_VERSIONS {0, 0}++#endif++#ifndef DM_GAME_PRESENT_DISPLAY++#define DM_GAME_PRESENT_DISPLAY 0++#define DM_GAME_CORE_PREEMPT 0++#define DM_GAME_ALLOC_BIG_ALIGN 0++#define DM_GAME_FPS_TARGET 0++#define DM_GAME_FPS_HOLD 1++#define DM_GAME_PRESENT_SNAP 0++#define DM_GAME_PSO_MTL4 0++#define DM_GAME_PAD_LAYOUT 0++#define DM_GAME_OPMODE 1++#define DM_GAME_PERF_BOOST 0++#define DM_GAME_FEEDBACK_SNAP ""++#define DM_GAME_TEX_FLUSH_UPLOAD 0++#define DM_GAME_RENDER_COND 0++#define DM_GAME_TEX_DIRTY_UPLOAD 0++#define DM_GAME_TEX_DYN_SLOTS 0++#define DM_GAME_GPU_TS_SEGMENT 0++#define DM_GAME_VCONV_RANGE 0++#define DM_GAME_ARGS ""++#define DM_GAME_ENV ""++#endif++static void defaults(void) {++ memset(&P, 0, sizeof P);++ copy_str(P.id, sizeof P.id, DM_GAME_ID);++ copy_str(P.name, sizeof P.name, DM_GAME_NAME);++ copy_str(P.romfs_marker, sizeof P.romfs_marker, DM_GAME_ROMFS_MARKER);++ P.program_id = DM_GAME_PROGRAM_ID;++ { static const char *m[] = DM_GAME_MODULES; int n = DM_GAME_NMOD; if (n > DM_PROF_MAX_MOD) n = DM_PROF_MAX_MOD;++ for (int i = 0; i < n; i++) { copy_str(P.modbuf[i], sizeof P.modbuf[i], m[i]); P.modules[i] = P.modbuf[i]; } P.nmod = n; }++ P.mem_reserve = DM_GAME_MEM_RESERVE; P.mem_alias = DM_GAME_MEM_ALIAS; P.mem_stack = DM_GAME_MEM_STACK;++ P.app_pool = DM_GAME_APP_POOL; P.mem_used = DM_GAME_MEM_USED; P.sys_resource = DM_GAME_SYS_RESOURCE;++ P.mem_map_limit = DM_GAME_MEM_MAP_LIMIT;++ { static const struct { const char *build, *ver; } k[] = {DM_GAME_DISPLAY_VERSIONS};++ int n = (int)(sizeof k / sizeof *k); if (n > DM_PROF_MAX_VER) n = DM_PROF_MAX_VER;++ for (int i = 0; i < n; i++) {++ if (!k[i].build || !k[i].ver) continue; // the placeholder a partial header falls back to++ copy_str(P.ver[P.nver].build, sizeof P.ver[0].build, k[i].build); copy_str(P.ver[P.nver].ver, sizeof P.ver[0].ver, k[i].ver); P.nver++;++ } }++ P.present_display = DM_GAME_PRESENT_DISPLAY; P.core_preempt = DM_GAME_CORE_PREEMPT; P.alloc_big_align = DM_GAME_ALLOC_BIG_ALIGN;++ P.fps_target = DM_GAME_FPS_TARGET; P.fps_hold = DM_GAME_FPS_HOLD; P.present_snap = DM_GAME_PRESENT_SNAP; P.pso_mtl4 = DM_GAME_PSO_MTL4;++#ifdef DM_GAME_SHARED_FONT_TTF++ P.shared_font_ttf = DM_GAME_SHARED_FONT_TTF;++#else++ P.shared_font_ttf = -1;++#endif++ P.pad_layout = DM_GAME_PAD_LAYOUT; P.opmode = DM_GAME_OPMODE; P.perf_boost = DM_GAME_PERF_BOOST;++ copy_str(P.feedback_snap, sizeof P.feedback_snap, DM_GAME_FEEDBACK_SNAP);++ P.tex_flush_upload = DM_GAME_TEX_FLUSH_UPLOAD; P.render_cond = DM_GAME_RENDER_COND; P.tex_dirty_upload = DM_GAME_TEX_DIRTY_UPLOAD;++ P.tex_dyn_slots = DM_GAME_TEX_DYN_SLOTS; P.gpu_ts_segment = DM_GAME_GPU_TS_SEGMENT; P.vconv_range = DM_GAME_VCONV_RANGE;++#ifdef DM_GAME_NVN_API_MAJOR++ P.nvn_api_major = DM_GAME_NVN_API_MAJOR; P.nvn_api_minor = DM_GAME_NVN_API_MINOR;++#else++ P.nvn_api_major = 0; P.nvn_api_minor = 0;++#endif++ copy_str(P.args, sizeof P.args, DM_GAME_ARGS);++ copy_str(P.genv, sizeof P.genv, DM_GAME_ENV);++ copy_str(P.source, sizeof P.source, "compiled game_profile.h");++}++++// ---- one key/value: the same key names as game.tsv (so `game.py` can write the file), plus the header's own names ----++static void set_kv(const char *k, const char *v) {++ if (!strcmp(k, "title_id") || !strcmp(k, "id")) copy_str(P.id, sizeof P.id, v);++ else if (!strcmp(k, "name")) copy_str(P.name, sizeof P.name, v);++ else if (!strcmp(k, "romfs_marker")) copy_str(P.romfs_marker, sizeof P.romfs_marker, v);++ else if (!strcmp(k, "program_id")) P.program_id = num(v, P.program_id);++ else if (!strcmp(k, "modules")) {++ P.nmod = 0; const char *p = v;++ while (*p && P.nmod < DM_PROF_MAX_MOD) {++ while (*p == ' ' || *p == '\t' || *p == ',') p++;++ if (!*p) break;++ size_t n = strcspn(p, " \t,");++ if (n >= sizeof P.modbuf[0]) n = sizeof P.modbuf[0] - 1;++ memcpy(P.modbuf[P.nmod], p, n); P.modbuf[P.nmod][n] = 0; P.modules[P.nmod] = P.modbuf[P.nmod];++ P.nmod++; p += n;++ }++ }++ else if (!strcmp(k, "mem_reserve")) P.mem_reserve = num(v, P.mem_reserve);++ else if (!strcmp(k, "mem_alias")) P.mem_alias = num(v, P.mem_alias);++ else if (!strcmp(k, "mem_stack")) P.mem_stack = num(v, P.mem_stack);++ else if (!strcmp(k, "app_pool")) P.app_pool = num(v, P.app_pool);++ else if (!strcmp(k, "mem_used")) P.mem_used = num(v, P.mem_used);++ else if (!strcmp(k, "sys_resource")) P.sys_resource = num(v, P.sys_resource);++ else if (!strcmp(k, "mem_map_limit")) P.mem_map_limit = truthy(v);++ else if (!strcmp(k, "display_version")) { // build<TAB>version; one row per build (game.tsv's build rows give the same)++ const char *t = strchr(v, '\t'); if (t && P.nver < DM_PROF_MAX_VER) {++ size_t n = (size_t)(t - v); if (n >= sizeof P.ver[0].build) n = sizeof P.ver[0].build - 1;++ memcpy(P.ver[P.nver].build, v, n); P.ver[P.nver].build[n] = 0;++ copy_str(P.ver[P.nver].ver, sizeof P.ver[0].ver, t + 1); P.nver++;++ }++ }++ // Some keys have a word form (game.tsv: display / full / console) and a number form (the header: 1 / 0): both are accepted,++ // because game.py writes the header's spelling and a hand-written profile may use either. Numbers are unambiguous: 0/1 for++ // Booleans, 0/1/2 for pad_layout (simple / full / touch) and 1/0 for the console/handheld mode.++ else if (!strcmp(k, "present_interval")) P.present_display = strchr("dD1", *v) != NULL && (!strcmp(v, "display") || isdigit((unsigned char)*v));++ else if (!strcmp(k, "core_preempt")) P.core_preempt = truthy(v);++ else if (!strcmp(k, "alloc_big_align")) P.alloc_big_align = truthy(v);++ else if (!strcmp(k, "fps_target")) P.fps_target = (int)num(v, (uint64_t)P.fps_target);++ else if (!strcmp(k, "fps_hold")) P.fps_hold = truthy(v);++ else if (!strcmp(k, "present_snap")) P.present_snap = truthy(v);++ else if (!strcmp(k, "pso_mtl4")) P.pso_mtl4 = truthy(v);++ else if (!strcmp(k, "shared_font")) P.shared_font_ttf = !strcmp(v, "ttf") || !strcmp(v, "1");++ else if (!strcmp(k, "pad_layout")) P.pad_layout = !strcmp(v, "full") || !strcmp(v, "1") ? 1 : !strcmp(v, "touch") || !strcmp(v, "2") ? 2 : 0;++ else if (!strcmp(k, "op_mode")) P.opmode = !strcmp(v, "console") ? 1 : !strcmp(v, "handheld") ? 0 : truthy(v);++ else if (!strcmp(k, "perf_mode")) P.perf_boost = !strcmp(v, "boost") ? 1 : !strcmp(v, "follow") ? 0 : truthy(v);++ else if (!strcmp(k, "feedback_snap")) copy_str(P.feedback_snap, sizeof P.feedback_snap, v);++ else if (!strcmp(k, "tex_flush_upload")) P.tex_flush_upload = truthy(v);++ else if (!strcmp(k, "render_cond")) P.render_cond = truthy(v);++ else if (!strcmp(k, "tex_dirty_upload")) P.tex_dirty_upload = truthy(v);++ else if (!strcmp(k, "tex_dyn_slots")) P.tex_dyn_slots = truthy(v);++ else if (!strcmp(k, "gpu_timestamps")) P.gpu_ts_segment = !strcmp(v, "segment") || !strcmp(v, "1");++ else if (!strcmp(k, "vconv_range")) P.vconv_range = truthy(v);++ else if (!strcmp(k, "device_api")) { char *e; P.nvn_api_major = (int)strtol(v, &e, 10); if (e && *e == '.') P.nvn_api_minor = atoi(e + 1); }++ else if (!strcmp(k, "game_args")) copy_str(P.args, sizeof P.args, v);++ else if (!strcmp(k, "game_env")) copy_str(P.genv, sizeof P.genv, v);++ // any other key (ipa, zip_store, shader_*, build, package, ...) is not a host constant: ignored++}++++// The file: KEY<TAB>VALUE (game.tsv's form) or KEY VALUE, # starts a comment; blank lines are skipped.++static void read_file(const char *path) {++ FILE *f = fopen(path, "r");++ if (!f) { LOG("[RED] DM_PROFILE %s cannot be read; keeping the compiled profile", path); return; }++ char line[4096];++ int rows = 0;++ while (fgets(line, sizeof line, f)) {++ char *s = line; while (*s == ' ' || *s == '\t') s++;++ size_t L = strlen(s); while (L && (s[L-1] == '\n' || s[L-1] == '\r')) s[--L] = 0;++ if (!*s || *s == '#') continue;++ char *sep = strpbrk(s, "\t ");++ if (!sep) continue;++ *sep = 0;++ char *v = sep + 1; while (*v == '\t' || *v == ' ') v++;++ if (!strcmp(s, "build")) { // build<TAB>version<TAB>display<TAB>main=<build id>...: one display-version row++ char *p = v, *cols[4] = {0}; int nc = 0;++ for (char *t = strtok(p, "\t"); t && nc < 4; t = strtok(NULL, "\t")) cols[nc++] = t;++ if (nc >= 2) { char buf[256]; snprintf(buf, sizeof buf, "%s\t%s", cols[0], cols[1]); set_kv("display_version", buf); }++ continue;++ }++ set_kv(s, v); rows++;++ }++ fclose(f);++ LOG("game profile %s: %d rows", path, rows);++}++++// Environment: DM_PROF_<KEY> with the game.tsv key upper-cased (DM_PROF_MEM_RESERVE=0x140000000).++static void read_env(void) {++ static const char *keys[] = {"TITLE_ID","NAME","ROMFS_MARKER","PROGRAM_ID","MODULES","MEM_RESERVE","MEM_ALIAS","MEM_STACK","APP_POOL",++ "MEM_USED","SYS_RESOURCE","MEM_MAP_LIMIT","PRESENT_INTERVAL","CORE_PREEMPT","ALLOC_BIG_ALIGN","FPS_TARGET","FPS_HOLD","PRESENT_SNAP",++ "PSO_MTL4","SHARED_FONT","PAD_LAYOUT","OP_MODE","PERF_MODE","FEEDBACK_SNAP","TEX_FLUSH_UPLOAD","RENDER_COND","TEX_DIRTY_UPLOAD",++ "TEX_DYN_SLOTS","GPU_TIMESTAMPS","VCONV_RANGE","DEVICE_API","GAME_ARGS","GAME_ENV", NULL};++ char k[64], name[96];++ for (int i = 0; keys[i]; i++) {++ snprintf(k, sizeof k, "%s", keys[i]);++ for (char *p = k; *p; p++) *p = (char)tolower((unsigned char)*p);++ snprintf(name, sizeof name, "DM_PROF_%s", keys[i]);++ const char *v = getenv(name);++ if (v) set_kv(k, v);++ }++}++++static void load(void) {++ defaults();++ const char *path = getenv("DM_PROFILE");++ if (path && *path) { copy_str(P.source, sizeof P.source, path); read_file(path); }++ read_env(); // DM_PROF_* overrides apply on top of the file or of the compiled profile++ if (P.nmod <= 0) { // a profile file that names no modules: the compiled list, which is the one the executable embeds++ static const char *m[] = DM_GAME_MODULES; int n = DM_GAME_NMOD; if (n > DM_PROF_MAX_MOD) n = DM_PROF_MAX_MOD;++ for (int i = 0; i < n; i++) { copy_str(P.modbuf[i], sizeof P.modbuf[i], m[i]); P.modules[i] = P.modbuf[i]; } P.nmod = n;++ }++ g_loaded = 1;++}++++const struct dm_profile *dm_profile(void) {++ if (!g_loaded) load();++ return &P;++}++++void dm_profile_log(void) {++ const struct dm_profile *p = dm_profile();++ LOG("game profile: %s (%s) from %s", p->id, p->name, p->source);++ LOG(" modules %d%s%s%s program %016llx reserve %#llx alias %#llx stack %#llx pool %#llx used %#llx sysres %#llx map_limit %d",++ p->nmod, p->nmod > 0 ? ":" : "", p->nmod > 0 ? p->modules[0] : "", p->nmod > 1 ? " ..." : "",++ (unsigned long long)p->program_id, (unsigned long long)p->mem_reserve, (unsigned long long)p->mem_alias,++ (unsigned long long)p->mem_stack, (unsigned long long)p->app_pool, (unsigned long long)p->mem_used,++ (unsigned long long)p->sys_resource, p->mem_map_limit);++ LOG(" switches present_display %d core_preempt %d big_align %d fps %d hold %d snap %d pso4 %d font_ttf %d pad %d opmode %d boost %d",++ p->present_display, p->core_preempt, p->alloc_big_align, p->fps_target, p->fps_hold, p->present_snap, p->pso_mtl4,++ p->shared_font_ttf, p->pad_layout, p->opmode, p->perf_boost);++ LOG(" graphics flush %d dirty %d rcond %d dynslots %d gputs %d vconv %d nvn_api %d.%d versions %d",++ p->tex_flush_upload, p->tex_dirty_upload, p->render_cond, p->tex_dyn_slots, p->gpu_ts_segment, p->vconv_range,++ p->nvn_api_major, p->nvn_api_minor, p->nver);++}+diff --git a/dm/host/hle_profile.h b/dm/host/hle_profile.h+new file mode 100644+index 00000000..a2febeb3+--- /dev/null++++ b/dm/host/hle_profile.h+@@ -0,0 +1,37 @@++// Runtime game profile: every constant the host used to take from game_profile.h at compile time, read once at start.++// Loading order: the compiled profile (game_profile.h, the macros) → the file DM_PROFILE names (the key/value form of a++// game profile, dm/games/game.py profile <id> <out.tsv>) → DM_PROF_<KEY> environment variables.++// The per-knob switches the host already reads (DM_FPS_TARGET, DM_OPMODE, DM_PRESENT_INTERVAL, DM_NVN_API, ...) still win over++// all of these: each site reads them after the profile.++// A build with no DM_PROFILE set behaves exactly as the compile-time profile did.++#pragma once++#include <stdint.h>++++#define DM_PROF_MAX_MOD 8++#define DM_PROF_MAX_VER 64++#define DM_PROF_STR 128++++struct dm_profile {++ char id[24]; // base game title ID, hex text++ char name[128];++ char romfs_marker[256];++ uint64_t program_id;++ char modbuf[DM_PROF_MAX_MOD][16];++ const char *modules[DM_PROF_MAX_MOD]; // point into modbuf++ int nmod;++ uint64_t mem_reserve, mem_alias, mem_stack, app_pool, mem_used, sys_resource;++ int mem_map_limit;++ struct { char build[40], ver[40]; } ver[DM_PROF_MAX_VER]; // display version by main build ID++ int nver;++ int present_display, core_preempt, alloc_big_align, fps_target, fps_hold, present_snap, pso_mtl4;++ int shared_font_ttf; // -1 = decide by the SDK version (hle_sdk16.c font_skip)++ int pad_layout, opmode, perf_boost;++ char feedback_snap[DM_PROF_STR];++ int tex_flush_upload, render_cond, tex_dirty_upload, tex_dyn_slots, gpu_ts_segment, vconv_range;++ int nvn_api_major, nvn_api_minor; // major 0 = decide by the SDK version (hle_nvn.c nvn_api)++ char args[512], genv[1024]; // game_args / game_env++ char source[512]; // DM_PROFILE, or "compiled defaults"++};++++const struct dm_profile *dm_profile(void); // loaded once; never NULL++void dm_profile_log(void); // one line per differing value (called after loading)+diff --git a/dm/host/hle_svc.c b/dm/host/hle_svc.c+index 2ba7f9fa..c15c00a3 100644+--- a/dm/host/hle_svc.c++++ b/dm/host/hle_svc.c+@@ -15,7 +15,10 @@+ // about 4.2 GB in total; on iOS without the "extended virtual addressing" entitlement a single reservation can be at most 6 GB+ // (read on a real device: 6 GB succeeds, 7 GB fails), so it cannot be made any wider --+ // with an 8 GB reservation, builds from developer accounts that cannot sign that entitlement (free accounts) would exit at this step.+-#define RESERVE DM_GAME_MEM_RESERVE // SMBW: the heap needs only 1.47 GB, so the block stays at 5 GB (the total proven on a real device; a single 6 GB block can be reserved, but Metal etc. still need address space)++// The layout comes from the runtime game profile (hle_profile.h): DM_PROFILE's mem_reserve / mem_alias / mem_stack / app_pool /++// mem_used / sys_resource, else the compiled profile's values. All of them are read once, in mem_init_once().++#define RESERVE g_reserve++static uint64_t g_reserve; // the whole block (profile mem_reserve)+ static uint8_t *g_as; // ASLR region base = the whole block+ static uint8_t *g_heap; static _Atomic size_t g_heap_cur; static size_t g_heap_cap;+ // The address range lies entirely within the currently opened (readable and writable) part of the guest heap: such reads need no kernel trap to check, memcpy directly (used where guest memory is read every tick, such as diag.c tk_rd)+@@ -29,10 +32,12 @@ int dm_guest_as_contains(uintptr_t a) { uintptr_t b = (uintptr_t)g_as; return g_++ static void *alias_windows_thread(void *arg);+ static void mem_init_once(void) {++ const struct dm_profile *p = dm_profile();+ size_t pg = (size_t)getpagesize();+- if (RESERVE < 0x10000000 || DM_GAME_MEM_ALIAS > RESERVE - 0x10000000 ||+- DM_GAME_MEM_STACK > RESERVE - 0x10000000 - DM_GAME_MEM_ALIAS ||+- ((RESERVE | DM_GAME_MEM_ALIAS | DM_GAME_MEM_STACK) & (pg - 1)))++ g_reserve = p->mem_reserve;++ if (RESERVE < 0x10000000 || p->mem_alias > RESERVE - 0x10000000 ||++ p->mem_stack > RESERVE - 0x10000000 - p->mem_alias ||++ ((RESERVE | p->mem_alias | p->mem_stack) & (pg - 1)))+ die("guest address-space profile has invalid native boundaries");+ g_as = mmap(NULL, RESERVE, PROT_NONE, MAP_PRIVATE | MAP_ANON, -1, 0);+ if (g_as == MAP_FAILED) die("reserve guest AS");+@@ -42,8 +47,8 @@ static void mem_init_once(void) {+ // and resource loading then MapPhysicalMemory's into the alias region after the node area on demand. With a 1.25 GB alias region only about 256 MB was left there, and 3 MB-class layout archives (WipeCourseIn / WipeWarp)+ // got no address, were skipped, and crashed on a null pointer when used (main +0x373e04). So alias = node area + 1.75 GB + slack; the heap needs only 1.47 GB, and 2.625 GB is plenty.+ // The alias and stack sizes come from the game profile (mem_alias / mem_stack), the heap takes the rest; Mario: alias 0xB8000000, stack 0x10000000 → stack at +0xC8000000, heap at +0xD8000000+- g_alias = g_as + 0x10000000; g_alias_cap = DM_GAME_MEM_ALIAS;+- g_stack = g_alias + g_alias_cap; g_stack_cap = DM_GAME_MEM_STACK;++ g_alias = g_as + 0x10000000; g_alias_cap = p->mem_alias;++ g_stack = g_alias + g_alias_cap; g_stack_cap = p->mem_stack;+ g_heap = g_stack + g_stack_cap; g_heap_cap = RESERVE - (size_t)(g_heap - g_as);+ if (!(g_alias_bits = calloc((g_alias_cap >> 18) + 1, sizeof *g_alias_bits))) die("alias region page bitmap calloc");+ if (!(g_alias_exposed = calloc(g_alias_cap / pg / 64 + 1, sizeof *g_alias_exposed))) die("alias exposure bitmap calloc");+@@ -60,7 +65,12 @@ static void mem_init(void) {+ // and hands the whole block to its own StandardAllocator (main+0x32137a0) -- so heap size = pool − image footprint, it has only as much as the host reports.+ // Previously 3 GB was reported here and SetHeapSize never failed: the heap was about 150 MB smaller than on the real device, at the run entry peak the main heap had only about 18 MB left, and under high local load a timing shift made a 128 KB request return null,+ // which the guest writes to without a null check (CRASH main+0x1b36138, re-verified after merge with inv_tap).+-#define APP_POOL DM_GAME_APP_POOL // game profile app_pool (Mario 0xCD500000)++#define APP_POOL (dm_profile()->app_pool) // game profile app_pool (Mario 0xCD500000)++// The other memory constants the profile sets (hle_profile.h): read where they are used, so DM_PROFILE can change them per game.++#define MEM_USED (dm_profile()->mem_used) // used memory reported beside the heap (profile mem_used)++#define MEM_MAP_LIMIT (dm_profile()->mem_map_limit) // MapPhysicalMemory refused beyond the application pool++#define SYS_RESOURCE (dm_profile()->sys_resource) // the NPDM's system resource size (0 = no virtual address memory)++#define PROGRAM_ID (dm_profile()->program_id) // this game's program ID (save-data queries)+ static size_t image_bytes(void) { size_t n = 0; for (int i = 0; i < g_nmod; i++) if (!g_mod[i].nro) n += g_mod[i].size; // an NRO lives in memory the game allocated (its image and bss buffers)+ return (n + 0x1fffff) & ~(size_t)0x1fffff; }+ // Giant bss (modules with the patch area before the base, patch_nso.py FAR): the image bytes beyond the file part. Used memory was reported as "heap + 64 MB", where the 64 MB covers ordinary modules' code and data (Mario's two modules are about 74 MB together,+@@ -272,11 +282,11 @@ uint64_t svc_dispatch(int num, uint64_t *regs, uint64_t orig_addr) {+ // Logged once (Mario's retries would repeat it): a game that sizes its heap as pool − used memory and does not retry stops here when its modules are larger than the used memory reported+ // (profile mem_used; the NSP script's probe boot reads this line, and sets mem_used when no SetHeapSize succeeds afterwards)+ static int once; if (!once++) LOG("[mem] SetHeapSize %#zx + modules %#zx > app pool %#llx (used memory reported %#llx + bss %#zx)", size, image_bytes() - big_bss_bytes(),+- (unsigned long long)APP_POOL, (unsigned long long)DM_GAME_MEM_USED, big_bss_bytes());++ (unsigned long long)APP_POOL, (unsigned long long)MEM_USED, big_bss_bytes());+ pthread_mutex_unlock(&g_map_lock); regs[0] = 0x10801; return 0;+ }+- uint64_t charged = (uint64_t)DM_GAME_MEM_USED + big_bss_bytes() + atomic_load(&g_alias_mapped);+- if (DM_GAME_MEM_MAP_LIMIT && (charged > APP_POOL || size > APP_POOL - charged)) {++ uint64_t charged = (uint64_t)MEM_USED + big_bss_bytes() + atomic_load(&g_alias_mapped);++ if (MEM_MAP_LIMIT && (charged > APP_POOL || size > APP_POOL - charged)) {+ pthread_mutex_unlock(&g_map_lock); regs[0] = 0x10801; return 0;+ }+ int rc = 0;+@@ -419,8 +429,8 @@ uint64_t svc_dispatch(int num, uint64_t *regs, uint64_t orig_addr) {+ // and maps new ones for later allocations, until a map fails: then it unmaps the cached block and retries (measured on the Mac: the refused 4 MB map at +0x43e2c000 was followed by+ // UnmapPhysicalMemory of the 3.15 GB block and the same map again). Without the limit the mapped total went past the pool in the first minute and the freed block stayed mapped.+ // Off by default: Ace Attorney Investigations Collection maps a little more than the 1 GB pool its profile reports+- if (DM_GAME_MEM_MAP_LIMIT && num == 0x2C) {+- int64_t room = (int64_t)APP_POOL - (int64_t)(g_heap_cur + DM_GAME_MEM_USED + big_bss_bytes()) - atomic_load(&g_alias_mapped);++ if (MEM_MAP_LIMIT && num == 0x2C) {++ int64_t room = (int64_t)APP_POOL - (int64_t)(g_heap_cur + MEM_USED + big_bss_bytes()) - atomic_load(&g_alias_mapped);+ if (need && need > room) {+ pthread_mutex_unlock(&g_map_lock);+ static _Atomic int nref; if (atomic_fetch_add(&nref, 1) < 8) LOG("[mem] MapPhysicalMemory +%#zx refused: %.2f GB mapped, the application pool is full (ResultLimitReached, the SDK frees cached pages and retries)",+@@ -482,16 +492,16 @@ uint64_t svc_dispatch(int num, uint64_t *regs, uint64_t orig_addr) {+ case I_StackAddr: v = (uint64_t)g_stack; break; case I_StackSize: v = g_stack_cap; break;+ case I_TotalMem: case I_TotalNonSys: v = APP_POOL; break;+ case I_UsedMem: case I_UsedNonSys: pthread_mutex_lock(&g_map_lock);+- v = g_heap_cur + DM_GAME_MEM_USED + big_bss_bytes(); // profile mem_used, 64 MB unless the game needs more (see mem_used in dm/games/README.md)++ v = g_heap_cur + MEM_USED + big_bss_bytes(); // profile mem_used, 64 MB unless the game needs more (see mem_used in dm/games/README.md)+ // with mem_map_limit, the pages mapped in the alias region count too, as on Horizon (the limit in MapPhysicalMemory is the pool less this)+- if (DM_GAME_MEM_MAP_LIMIT) v += (uint64_t)atomic_load(&g_alias_mapped);++ if (MEM_MAP_LIMIT) v += (uint64_t)atomic_load(&g_alias_mapped);+ pthread_mutex_unlock(&g_map_lock); break;+ // the system resource the NPDM declares (profile sys_resource; 32 MB without the key). The SDK's IsVirtualAddressMemoryEnabled is "total != 0": Big Brain Academy's nninitStartup+ // asks StandardAllocator for 60 GB of virtual address memory when it is, and sets a heap only when it is not (its NPDM declares none)+- case I_SysResTotal: v = DM_GAME_SYS_RESOURCE; break; case I_SysResUsed: v = DM_GAME_SYS_RESOURCE ? 0x400000 : 0; break;++ case I_SysResTotal: v = SYS_RESOURCE; break; case I_SysResUsed: v = SYS_RESOURCE ? 0x400000 : 0; break;+ case I_DebuggerAttached: v = 0; break;+ case I_RandomEntropy: { uint64_t dm_entropy64(void); v = dm_entropy64(); break; } // a deterministic stream when DM_DETCLOCK is on (hle_os.c)+- case I_ProgramId: { static uint64_t pid; if (!pid) { const char *e = getenv("DM_PROGRAM_ID"); pid = e ? strtoull(e, NULL, 16) : DM_GAME_PROGRAM_ID; } v = pid; break; } // default from the game profile's program_id; DM_PROGRAM_ID=hex overrides++ case I_ProgramId: { static uint64_t pid; if (!pid) { const char *e = getenv("DM_PROGRAM_ID"); pid = e ? strtoull(e, NULL, 16) : PROGRAM_ID; } v = pid; break; } // default from the game profile's program_id; DM_PROGRAM_ID=hex overrides+ case I_IsApplication: v = 1; break;+ // nn::os::GetFreeThreadCount (SDK 11+): the thread resource limit less the threads alive, as the kernel answers it (Atmosphère kern_svc_info.cpp). pm gives an application a limit of+ // 96 threads (pm_spec.cpp BaseApplicationThreads; a boost raises it to 256). Monster Train 2's Unity 2022.3 player creates a thread only when this is at least 1: the 0 it got here+diff --git a/dm/host/loader.c b/dm/host/loader.c+index cd4af6a6..8d82c284 100644+--- a/dm/host/loader.c++++ b/dm/host/loader.c+@@ -227,7 +227,7 @@ static void install_fps_state(module_t *m) {+ // DM_RENDER_SCALE (Launcher.swift), and nothing reads the page before the game runs+ void dm_fps_state_apply(void) {+ if (!dm_fps_state) return;+- const char *e = getenv("DM_FPS_TARGET"); int t = e ? atoi(e) : DM_GAME_FPS_TARGET;++ const char *e = getenv("DM_FPS_TARGET"); int t = e ? atoi(e) : dm_profile()->fps_target;+ if (t != 0 && t != 30 && t != 60) { LOG("[RED] DM_FPS_TARGET=%s: must be 0, 30 or 60; using the game's own frame step", e); t = 0; }+ float f = (float)t; memcpy(dm_fps_state, &f, sizeof f);+ // Render scale of the 3D views (the stubs at Tears of the Kingdom's main+0xd5cc0, Breath of the Wild's main+0x1266880): 1.0 keeps the game's own size and dynamic resolution;+diff --git a/dm/host/tests/Makefile b/dm/host/tests/Makefile+index 6ea9e976..61b6b573 100644+--- a/dm/host/tests/Makefile++++ b/dm/host/tests/Makefile+@@ -42,7 +42,7 @@ run: $(B)/t_heap_size $(B)/t_touch $(B)/t_gesture $(B)/t_oe $(B)/t_fs $(B)/t_fs_+ run: $(B)/t_nro+ run: $(B)/t_symbols+ $(B)/t_symbols: t_symbols.c ../hle.c ../loader.c ../hle.h ../dm.h $(GAME_H) | $(B)+- clang -O1 -g -Wall -Werror -Wno-unused-function -Wno-deprecated-declarations -I.. $(GINC) -o $@ t_symbols.c++ clang -O1 -g -Wall -Werror -Wno-unused-function -Wno-deprecated-declarations -I.. $(GINC) -o $@ t_symbols.c ../hle_profile.c+ .PHONY: symbols+ symbols: $(B)/t_symbols+ $(B)/t_symbols+@@ -60,19 +60,19 @@ $(B)/t_audren_layout: t_audren_layout.c ../hle_audren.c ../hle.h ../dm.h $(GAME_+ audren-layout: $(B)/t_audren_layout+ $(B)/t_audren_layout+ $(B)/t_system_event: t_system_event.c ../hle_thread.c ../hle_sdk16.c ../hle.h ../dm.h $(GAME_H) | $(B)+- clang -O1 -g -Wall -Werror -Wno-unused-function -Wno-frame-address -I.. $(GINC) -o $@ t_system_event.c++ clang -O1 -g -Wall -Werror -Wno-unused-function -Wno-frame-address -I.. $(GINC) -o $@ t_system_event.c ../hle_profile.c+ .PHONY: system-event+ system-event: $(B)/t_system_event+ $(B)/t_system_event+ $(B)/t_nro: t_nro.c ../loader.c ../hle_ro.c ../hle.h ../dm.h $(GAME_H) | $(B)+- clang -O1 -g -Wall -Wno-unused-function -Wno-deprecated-declarations -I.. $(GINC) -o $@ t_nro.c++ clang -O1 -g -Wall -Wno-unused-function -Wno-deprecated-declarations -I.. $(GINC) -o $@ t_nro.c ../hle_profile.c+ .PHONY: nro+ nro: $(B)/t_nro+ $(B)/t_nro+ $(GAME_H):+ $(MAKE) -C .. game_profile GAME=$(GAME)+ $(B)/t_heap_size: t_heap_size.c ../hle_svc.c ../dm.h $(GAME_H) | $(B)+- clang -O1 -Wall -Werror -Wno-unused-function -fsanitize=undefined -I.. $(GINC) -o $@ t_heap_size.c++ clang -O1 -Wall -Werror -Wno-unused-function -fsanitize=undefined -I.. $(GINC) -o $@ t_heap_size.c ../hle_profile.c+ .PHONY: heap_size+ heap_size: $(B)/t_heap_size+ $(B)/t_heap_size+@@ -82,17 +82,17 @@ $(B)/t_gesture: t_gesture.c ../hle_touch.c ../front.h ../dm.h $(GAME_H) | $(B)+ clang -O1 -Wall -Wno-unused-function -I.. $(GINC) -o $@ t_gesture.c ../hle_touch.c+ $(B)/t_thread_leak: t_thread_leak.c ../thread.c ../dm.h $(GAME_H) | $(B)+ clang -O1 -Wno-unused-function -I.. $(GINC) -o $@ t_thread_leak.c+-$(B)/t_fs: t_fs.c t_fs_stub.c ../hle_fs.c ../hle_bigstack.c ../hle.h ../dm.h $(GAME_H) | $(B)+- clang -O1 -Wno-unused-function -I.. $(GINC) -o $@ t_fs.c t_fs_stub.c ../hle_bigstack.c+-$(B)/t_fs_commit_list: t_fs_commit_list.c t_fs_stub.c ../hle_fs.c ../hle_bigstack.c ../hle.h ../dm.h $(GAME_H) | $(B)+- clang -O1 -Wall -Wno-unused-function -I.. $(GINC) -o $@ t_fs_commit_list.c t_fs_stub.c ../hle_bigstack.c++$(B)/t_fs: t_fs.c t_fs_stub.c ../hle_fs.c ../hle_bigstack.c ../hle.h ../dm.h $(GAME_H) ../hle_profile.c ../hle_profile.h | $(B)++ clang -O1 -Wno-unused-function -I.. $(GINC) -o $@ t_fs.c t_fs_stub.c ../hle_bigstack.c ../hle_profile.c++$(B)/t_fs_commit_list: t_fs_commit_list.c t_fs_stub.c ../hle_fs.c ../hle_bigstack.c ../hle.h ../dm.h $(GAME_H) ../hle_profile.c ../hle_profile.h | $(B)++ clang -O1 -Wall -Wno-unused-function -I.. $(GINC) -o $@ t_fs_commit_list.c t_fs_stub.c ../hle_bigstack.c ../hle_profile.c+ $(B)/t_fs_commit_list_tsan: t_fs_commit_list.c t_fs_stub.c ../hle_fs.c ../hle_bigstack.c ../hle.h ../dm.h $(GAME_H) | $(B)+- clang -O1 -g -fsanitize=thread -Wall -Wno-unused-function -I.. $(GINC) -o $@ t_fs_commit_list.c t_fs_stub.c ../hle_bigstack.c++ clang -O1 -g -fsanitize=thread -Wall -Wno-unused-function -I.. $(GINC) -o $@ t_fs_commit_list.c t_fs_stub.c ../hle_bigstack.c ../hle_profile.c+ .PHONY: fs-tsan+ fs-tsan: $(B)/t_fs_commit_list_tsan+ TMPDIR="$(abspath $(B))" $(B)/t_fs_commit_list_tsan+-$(B)/t_fs_case: t_fs_case.c ../hle_fs.c ../hle_bigstack.c ../hle.h ../dm.h $(GAME_H) | $(B)+- clang -O1 -Wno-unused-function -I.. $(GINC) -o $@ t_fs_case.c ../hle_bigstack.c++$(B)/t_fs_case: t_fs_case.c ../hle_fs.c ../hle_bigstack.c ../hle.h ../dm.h $(GAME_H) ../hle_profile.c ../hle_profile.h | $(B)++ clang -O1 -Wno-unused-function -I.. $(GINC) -o $@ t_fs_case.c ../hle_bigstack.c ../hle_profile.c+ $(B)/t_audio: t_audio.c ../hle_audio.c ../hle.h ../dm.h $(GAME_H) | $(B)+ clang -O1 -Wno-unused-function -I.. $(GINC) -o $@ t_audio.c -framework AudioToolbox+ $(B)/t_audio_spsc: t_audio_spsc.c ../hle_audio.c ../hle.h ../dm.h $(GAME_H) | $(B)+@@ -107,7 +107,7 @@ $(B)/t_audio_spsc_tsan: t_audio_spsc.c ../hle_audio.c ../hle.h ../dm.h $(GAME_H)+ clang -O1 -g -O1 -fsanitize=thread -Wno-unused-function -I.. $(GINC) -o $@ t_audio_spsc.c -framework AudioToolbox+ run: $(B)/t_fpslock+ $(B)/t_fpslock: t_fpslock.c ../hle_fpslock.c ../hle.h ../dm.h $(GAME_H) | $(B)+- clang -O1 -g -Wno-unused-function $(GINC) -o $@ t_fpslock.c++ clang -O1 -g -Wno-unused-function $(GINC) -o $@ t_fpslock.c ../hle_profile.c+ $(B)/t_swkbd: t_swkbd.c ../hle_swkbd.c ../hle.h ../dm.h $(GAME_H) | $(B)+ clang -O1 -Wno-unused-function -I.. $(GINC) -o $@ t_swkbd.c ../hle_swkbd.c+ $(B)/t_altstack: t_altstack.c t_altstack_stub.c ../crash.c ../dm.h $(GAME_H) | $(B)+@@ -115,7 +115,7 @@ $(B)/t_altstack: t_altstack.c t_altstack_stub.c ../crash.c ../dm.h $(GAME_H) | $+ $(B)/t_pctl: t_pctl.c ../hle_misc.c ../hle.h ../dm.h $(GAME_H) | $(B)+ clang -O1 -Wall -Werror -Wno-unused-function -I.. $(GINC) -o $@ t_pctl.c+ $(B)/t_shared_font: t_shared_font.c ../hle_sdk16.c ../hle.h ../dm.h $(GAME_H) | $(B)+- clang -O1 -Wall -Werror -Wno-unused-function -Wno-frame-address -I.. $(GINC) -o $@ t_shared_font.c++ clang -O1 -Wall -Werror -Wno-unused-function -Wno-frame-address -I.. $(GINC) -o $@ t_shared_font.c ../hle_profile.c+ $(B)/t_hid: t_hid.c ../hle_hid.c ../hle_haptics.c ../hle_haptics.h ../pad_slots.h ../dm_input.h ../hle.h ../dm.h $(GAME_H) | $(B)+ clang -O1 -Wall -Werror -Wno-unused-function -I.. $(GINC) -o $@ t_hid.c ../hle_haptics.c+ $(B)/t_hid_tsan: t_hid.c ../hle_hid.c ../hle_haptics.c ../hle_haptics.h ../pad_slots.h ../dm_input.h ../hle.h ../dm.h $(GAME_H) | $(B)+@@ -127,13 +127,13 @@ $(B)/t_haptics_apple: t_haptics_apple.m ../haptics_apple.m ../haptics_apple.h ..+ $(B)/t_time: t_time.c ../hle_time.c ../hle.h ../dm.h $(GAME_H) | $(B)+ clang -O1 -Wall -Werror -Wno-unused-function -I.. $(GINC) -o $@ t_time.c+ $(B)/t_oe: t_oe.c ../hle_oe.c ../hle.h ../dm.h $(GAME_H) | $(B)+- clang -O1 -Wno-unused-function -I.. $(GINC) -o $@ t_oe.c++ clang -O1 -Wno-unused-function -I.. $(GINC) -o $@ t_oe.c ../hle_profile.c+ $(B)/t_condvar: t_condvar.c t_condvar_stub.c ../hle_thread.c ../dm.h $(GAME_H) | $(B)+- clang -O1 -Wno-unused-function -DDM_TEST_HOOKS -I.. $(GINC) -o $@ t_condvar.c t_condvar_stub.c ../hle_thread.c++ clang -O1 -Wno-unused-function -DDM_TEST_HOOKS -I.. $(GINC) -o $@ t_condvar.c t_condvar_stub.c ../hle_thread.c ../hle_profile.c+ $(B)/t_condvar_old: t_condvar.c t_condvar_stub.c ../hle_thread.c ../dm.h $(GAME_H) | $(B)+- clang -O1 -Wno-unused-function -DDM_TEST_HOOKS -DDM_TEST_CV_OLD_ORDER -I.. $(GINC) -o $@ t_condvar.c t_condvar_stub.c ../hle_thread.c++ clang -O1 -Wno-unused-function -DDM_TEST_HOOKS -DDM_TEST_CV_OLD_ORDER -I.. $(GINC) -o $@ t_condvar.c t_condvar_stub.c ../hle_thread.c ../hle_profile.c+ $(B)/t_preempt: t_preempt.c t_condvar_stub.c ../hle_thread.c ../dm.h $(GAME_H) | $(B)+- clang -O1 -g -Wall -Werror -Wno-unused-function -I.. $(GINC) -o $@ t_preempt.c t_condvar_stub.c++ clang -O1 -g -Wall -Werror -Wno-unused-function -I.. $(GINC) -o $@ t_preempt.c t_condvar_stub.c ../hle_profile.c+ .PHONY: preempt+ preempt: $(B)/t_preempt+ $(B)/t_preempt+@@ -158,17 +158,17 @@ tsan: $(B)/t_audio_spsc_tsan $(B)/t_hid_tsan+ $(B)/t_hid_tsan++ MEM_FLAGS = -O1 -Wall -Werror -Wno-unused-function -Imemory_profile -I..+-MEM_DEPS = t_svc_memory.c memory_profile/game_profile.h ../hle_svc.c ../hle_guestthread.c ../hle.h ../dm.h++MEM_DEPS = t_svc_memory.c memory_profile/game_profile.h ../hle_svc.c ../hle_guestthread.c ../hle.h ../dm.h ../hle_profile.c ../hle_profile.h+ $(B)/t_svc_memory: $(MEM_DEPS) | $(B)+- clang $(MEM_FLAGS) -fsanitize=undefined -o $@ t_svc_memory.c++ clang $(MEM_FLAGS) -fsanitize=undefined -o $@ t_svc_memory.c ../hle_profile.c+ $(B)/t_svc_memory_unlimited: $(MEM_DEPS) | $(B)+- clang $(MEM_FLAGS) -fsanitize=undefined -DDM_GAME_MEM_MAP_LIMIT=0 -o $@ t_svc_memory.c++ clang $(MEM_FLAGS) -fsanitize=undefined -DDM_GAME_MEM_MAP_LIMIT=0 -o $@ t_svc_memory.c ../hle_profile.c+ $(B)/t_svc_memory_16k: $(MEM_DEPS) | $(B)+- clang $(MEM_FLAGS) -fsanitize=address,undefined -DTEST_PAGE_16K -o $@ t_svc_memory.c++ clang $(MEM_FLAGS) -fsanitize=address,undefined -DTEST_PAGE_16K -o $@ t_svc_memory.c ../hle_profile.c+ $(B)/t_svc_memory_tsan: $(MEM_DEPS) | $(B)+- clang $(MEM_FLAGS) -fsanitize=thread -o $@ t_svc_memory.c++ clang $(MEM_FLAGS) -fsanitize=thread -o $@ t_svc_memory.c ../hle_profile.c+ $(B)/t_svc_memory_dirty: $(MEM_DEPS) ../../gfx/nvn/nvn_dirty.c ../../gfx/nvn/nvn_dirty.h | $(B)+- clang $(MEM_FLAGS) -DTEST_REAL_DIRTY -o $@ t_svc_memory.c ../../gfx/nvn/nvn_dirty.c++ clang $(MEM_FLAGS) -DTEST_REAL_DIRTY -o $@ t_svc_memory.c ../../gfx/nvn/nvn_dirty.c ../hle_profile.c+ .PHONY: memory memory-tsan memory-dirty memory-profile+ memory: $(B)/t_svc_memory $(B)/t_svc_memory_unlimited $(B)/t_svc_memory_16k+ $(B)/t_svc_memory+@@ -184,7 +184,7 @@ run: memory memory-dirty memory-profile++ # A native blocking notification wait must release the thread's guest core.+ $(B)/t_notify_sched: t_notify_sched.c t_condvar_stub.c ../hle_thread.c ../hle_oe.c ../hle.h ../dm.h $(GAME_H) | $(B)+- clang -O1 -g -Wall -Werror -Wno-unused-function -DDM_TEST_THREAD_ENTER -I.. $(GINC) -o $@ t_notify_sched.c t_condvar_stub.c++ clang -O1 -g -Wall -Werror -Wno-unused-function -DDM_TEST_THREAD_ENTER -I.. $(GINC) -o $@ t_notify_sched.c t_condvar_stub.c ../hle_profile.c+ .PHONY: notify-scheduler+ notify-scheduler: $(B)/t_notify_sched+ $(B)/t_notify_sched+diff --git a/dm/host/tests/t_layout_runtime.c b/dm/host/tests/t_layout_runtime.c+new file mode 100644+index 00000000..20b210d4+--- /dev/null++++ b/dm/host/tests/t_layout_runtime.c+@@ -0,0 +1,103 @@++// Stage-2 feasibility check: one binary, several guest memory layouts chosen at run time from DM_PROFILE.++// Each layout runs in its own process (mem_init is once per process, as in the host), so this test re-execs itself++// with LAYOUT set, boots the production dispatcher (hle_svc.c mem_init via GetInfo), and prints what it built.++// Build: clang -O1 -I.. -I../gen/<game> -o build/t_layout_runtime t_layout_runtime.c ../hle_svc.c ../hle_profile.c++#include "../dm.h"++#include "../hle_profile.h"++#include <assert.h>++#include <sys/wait.h>++#include <unistd.h>++#include <errno.h>++++module_t g_mod[MAX_MOD];++int g_nmod;++struct dm_flags g_flag;++void hlecount_svc(int num) { (void)num; }++int svc_thread(int num, uint64_t *regs) { (void)num; (void)regs; return 0; }++void dm_backtrace(uint64_t fp) { (void)fp; }++void guest_clock_read_wait(void) {}++uint64_t guest_ns(void) { return 0; }++uint64_t dm_entropy64(void) { return 0; }++int thr_limit_used(void) { return 0; }++int dm_ue_heap_owns(uint64_t a, uint64_t n) { (void)a; (void)n; return 0; }++module_t *module_of(const void *p) { (void)p; return NULL; }++void dm_guest_write_prepare(void *addr, size_t size) { (void)addr; (void)size; }++++uint64_t svc_dispatch(int num, uint64_t *regs, uint64_t orig_addr); // hle_svc.c++static uint64_t info(int which) { uint64_t regs[31] = {0}; regs[1] = (uint64_t)which; svc_dispatch(0x29, regs, 0); return regs[1]; } // GetInfo(out, id): id in x1, value out in x1++++typedef struct { const char *name, *profile; uint64_t reserve, alias, stack, pool, used, sysres; int limit; } case_t;++static const case_t CASES[] = {++ // Tears of the Kingdom: 5 GB, 2.375 GB alias++ {"totk", "layout_totk.tsv", 0x140000000ull, 0x98000000ull, 0x10000000ull, 0xCD500000ull, 0x4000000ull, 0x2000000ull, 0},++ // Animal Crossing: 4 GB, 256 MB alias, no system resource++ {"acnh", "layout_acnh.tsv", 0x100000000ull, 0x10000000ull, 0x10000000ull, 0xCD500000ull, 0x7a00000ull, 0x0ull, 0},++ // Super Mario Galaxy: 1 GB total (the smallest profile in the repository)++ {"smg", "layout_smg.tsv", 0x40000000ull, 0x10000000ull, 0x10000000ull, 0xCD500000ull, 0x4000000ull, 0ull, 1},++ // Aegis Rim: alias 2.875 GB with the map limit on++ {"13s", "layout_13s.tsv", 0x140000000ull, 0x118000000ull, 0x10000000ull, 0x40000000ull, 0x4000000ull, 0x1000000ull, 1},++};++#define NCASES ((int)(sizeof CASES / sizeof CASES[0]))++++static int child(const case_t *c) {++ char path[512]; snprintf(path, sizeof path, "%s/%s", getenv("LAYOUT_DIR") ?: ".", c->profile);++ setenv("DM_PROFILE", path, 1);++ const struct dm_profile *p = dm_profile();++ fprintf(stderr, "[child] %s: profile %s reserve %#llx alias %#llx stack %#llx pool %#llx used %#llx sysres %#llx limit %d\n",++ c->name, p->source, (unsigned long long)p->mem_reserve, (unsigned long long)p->mem_alias,++ (unsigned long long)p->mem_stack, (unsigned long long)p->app_pool, (unsigned long long)p->mem_used,++ (unsigned long long)p->sys_resource, p->mem_map_limit);++ // what the host reports to the guest, built by the production dispatcher++ uint64_t aslr = info(12), aslr_size = info(13), heap_addr = info(4), heap_size = info(5);++ uint64_t alias_addr = info(2), alias_size = info(3), stack_addr = info(14), stack_size = info(15);++ uint64_t total = info(6), used = info(7), sysres = info(16);++ printf("%-6s reserve %#-12llx alias %#-12llx stack %#-12llx heap_region %#-12llx | got aslr %#llx+%#llx alias %#llx+%#llx stack %#llx+%#llx heap@%#llx total %#llx used %#llx sysres %#llx\n",++ c->name, (unsigned long long)aslr_size, (unsigned long long)alias_size, (unsigned long long)stack_size,++ (unsigned long long)heap_size, (unsigned long long)aslr, (unsigned long long)aslr_size,++ (unsigned long long)alias_addr, (unsigned long long)alias_size, (unsigned long long)stack_addr,++ (unsigned long long)stack_size, (unsigned long long)heap_addr, (unsigned long long)total,++ (unsigned long long)used, (unsigned long long)sysres);++ int ok = aslr_size == c->reserve && alias_size == c->alias && stack_size == c->stack && heap_size == c->reserve - 0x10000000ull - c->alias - c->stack++ && alias_addr == aslr + 0x10000000ull && stack_addr == alias_addr + c->alias++ && heap_addr == stack_addr + c->stack && total == c->pool && sysres == c->sysres;++ if (used != c->used) { printf(" [RED] used memory %#llx, profile says %#llx\n", (unsigned long long)used, (unsigned long long)c->used); ok = 0; }++ // SetHeapSize must succeed inside the runtime region++ { uint64_t regs[31] = {0}; regs[1] = heap_size / 2; svc_dispatch(0x01, regs, 0); if (regs[0]) { printf(" [RED] SetHeapSize(%#llx) failed %#llx\n", (unsigned long long)(heap_size / 2), (unsigned long long)regs[0]); ok = 0; } }++ // an explicit-profile mismatch must be visible, not silently ignored++ printf(" %s\n", ok ? "OK" : "[RED] MISMATCH");++ return ok ? 0 : 1;++}++++int main(int argc, char **argv) {++ if (argc > 1) { // child mode: LAYOUT names the case++ for (int i = 0; i < NCASES; i++) if (!strcmp(argv[1], CASES[i].name)) return child(&CASES[i]);++ return 2;++ }++ // Write each case's profile where the child will find it (the profile loader takes a path in++ // DM_PROFILE and reads game.tsv's key/value form). Generated here rather than committed: the++ // values live in CASES above, and a fixture that can drift from them is a test that lies.++ for (int i = 0; i < NCASES; i++) {++ char path[256]; snprintf(path, sizeof path, "layout_%s.tsv", CASES[i].name);++ FILE *f = fopen(path, "w");++ if (!f) { printf("[RED] cannot write %s (errno %d)\n", path, errno); return 1; }++ fprintf(f, "# generated by t_layout_runtime: the case table above is the source of truth\n");++ fprintf(f, "name %s (runtime layout test)\n", CASES[i].name);++ fprintf(f, "mem_reserve %#llx\n", (unsigned long long)CASES[i].reserve);++ fprintf(f, "mem_alias %#llx\n", (unsigned long long)CASES[i].alias);++ fprintf(f, "mem_stack %#llx\n", (unsigned long long)CASES[i].stack);++ fprintf(f, "app_pool %#llx\n", (unsigned long long)CASES[i].pool);++ fprintf(f, "mem_used %#llx\n", (unsigned long long)CASES[i].used);++ fprintf(f, "sys_resource %#llx\n", (unsigned long long)CASES[i].sysres);++ fprintf(f, "mem_map_limit %d\n", CASES[i].limit);++ fclose(f);++ }++ int bad = 0;++ for (int i = 0; i < NCASES; i++) {++ pid_t pid = fork();++ if (!pid) { execl(argv[0], argv[0], CASES[i].name, (char *)NULL); _exit(3); }++ int st = 0; waitpid(pid, &st, 0);++ if (!WIFEXITED(st) || WEXITSTATUS(st)) { printf("%-6s FAILED (%s %d)\n", CASES[i].name, WIFSIGNALED(st) ? "signal" : "status", WIFSIGNALED(st) ? WTERMSIG(st) : WEXITSTATUS(st)); bad++; }++ }++ printf(bad ? "[RED] %d layout(s) failed\n" : "all %d runtime layouts OK\n", bad ? bad : NCASES);++ return bad ? 1 : 0;++}+diff --git a/dm/ios/Sources/DmGamepad.m b/dm/ios/Sources/DmGamepad.m+index c3ac8c16..3ac81d95 100644+--- a/dm/ios/Sources/DmGamepad.m++++ b/dm/ios/Sources/DmGamepad.m+@@ -156,7 +156,7 @@ - (instancetype)initWithFrame:(CGRect)f {+ }+ _swap = shape(_controls); _swapLabel = label(_swap, @"");+ NSNumber *saved = [NSUserDefaults.standardUserDefaults objectForKey:k_layout_key];+- int l = saved ? (int)saved.integerValue : DM_GAME_PAD_LAYOUT;++ int l = saved ? (int)saved.integerValue : dm_profile()->pad_layout;+ if (l == 2 && dm_opmode() != 0) l = 0; // Tap only in handheld mode (env.txt's DM_OPMODE may have changed it)+ _full = l == 1; _tap = l == 2;+ [self applyLayout];+diff --git a/docs/env_switches.tsv b/docs/env_switches.tsv+index 814429dc..242056b6 100644+--- a/docs/env_switches.tsv++++ b/docs/env_switches.tsv+@@ -182,6 +182,7 @@ DM_PROBE_LIMIT diagnostic Maximum printed hits per guest probe; 0 or absent leav+ DM_PROBE_POLL diagnostic `=<address>[+<length>]` (hex, 4 bytes by default, up to 8): a host thread spins on the bytes and on each change snapshots every thread's pc, lr and frames, for writes the watch misses+ DM_PROBE_WATCH diagnostic `=<address>[+<length>]` (hex, 8 bytes by default): write-protects that host page and reports who writes these bytes, without a debugger+ DM_PROBE_X2 diagnostic `=<bytes>` (hex): probe hits also dump that many bytes of the memory x2 points to++DM_PROFILE path `=<file>`: the runtime game profile (layout, switches, tables) the host reads at start, which is how one host binary serves every game (the launcher architecture); the compiled `game_profile.h` stays the fallback, and `DM_PROF_<key>` overrides sit on top of it (`hle_profile.h`)+ DM_PROGRAM_ID switch `=<hex>`: the program ID the host reports from `svcGetInfo(ProgramId)` (default: the profile's `program_id`)+ DM_PSO_ARCHIVE path The folder of the per-game Metal 4 pipeline archive of pipeline bases (default `pso_archive/` beside `pso_user.tsv`); `off` keeps no archive+ DM_PSO_BUNDLE path The pipeline archive made offline (`<GPU architecture>.mtl4a`, `prebuilt.tsv`), read only; the iOS app and Mac launcher set it to their `pso/` folder; `off` ignores itdiff --git a/patches/0002-romfsarc.patch b/patches/0002-romfsarc.patchnew file mode 100644index 00000000..2580a388--- /dev/null+++ b/patches/0002-romfsarc.patch@@ -0,0 +1,1104 @@+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001+From: v0lumehi <[email protected]>+Date: Wed, 28 Oct 2026 13:33:53 +0100+Subject: [PATCH] ROMFSARC: read RomFS shard archives++A synthetic @romfsarc: host path, an archive MountRom, archive file handles, and directory snapshots from the index,+plus the reader (romfs_arc.c) and its packer (romfs_arc.py).++Upstream-Status: fork-only+Reason: Legacy ROMFSARC shard archives (Tears of the Kingdom, 300k files) that players already made; upstream reads DMROMFS1 images instead. Kept so existing archives keep loading; retire when none are left+Issue: LNPANDY/NX2Apple#123+---+ dm/host/Makefile | 2 +-+ dm/host/hle_fs.c | 138 +++++++++++++++++-+ dm/host/romfs_arc.c | 228 +++++++++++++++++++++++++++++++ dm/host/romfs_arc.h | 100 ++++++++++++++ dm/host/tests/Makefile | 12 +-+ dm/host/tests/t_romfs_arc.c | 87 +++++++++++++ dm/tools/romfs_arc.py | 270 +++++++++++++++++++++++++++++++++++++ docs/ROMFS_ARCHIVE.md | 95 ++++++++++++++ 8 files changed, 922 insertions(+), 10 deletions(-)+ create mode 100644 dm/host/romfs_arc.c+ create mode 100644 dm/host/romfs_arc.h+ create mode 100644 dm/host/tests/t_romfs_arc.c+ create mode 100644 dm/tools/romfs_arc.py+ create mode 100644 docs/ROMFS_ARCHIVE.md++diff --git a/dm/host/Makefile b/dm/host/Makefile+index c0ec1066..e820e8b8 100644+--- a/dm/host/Makefile++++ b/dm/host/Makefile+@@ -16,7 +16,7 @@ endif+ GAME_H = gen/$(GAME)/game_profile.h+ CFLAGS=-O1 -g -Wall -Wno-unused-function+ # Service-layer takeover hle_*.c files are included by wildcard: adding a file does not touch this line (avoids merge conflicts)+-SRC=main.c loader.c hle.c crash.c probe.c thread.c memstat.m haptics_apple.m $(sort $(wildcard hle_*.c)) front_mac.m entry.S++SRC=main.c loader.c hle.c romfs_arc.c crash.c probe.c thread.c memstat.m haptics_apple.m $(sort $(wildcard hle_*.c)) front_mac.m entry.S+ # NVN null device + nn::vi + the Vulkan layer (dm/gfx/)+ # Sources under dm/gfx, dm/gfx/nvn, dm/gfx/tex, dm/gfx/vk and dm/gfx/gl are included by wildcard (tests/ and metal/ do not go into the host): adding a file does not touch this line+ GFX=$(sort $(wildcard ../gfx/*.c ../gfx/nvn/*.c ../gfx/nvn/*.m ../gfx/nvn/*.S ../gfx/tex/*.c ../gfx/tex/*.m ../gfx/vk/*.m ../gfx/gl/*.m))+diff --git a/dm/host/hle_fs.c b/dm/host/hle_fs.c+index 92bb7a5b..f1089b93 100644+--- a/dm/host/hle_fs.c++++ b/dm/host/hle_fs.c+@@ -7,6 +7,7 @@+ #include "hle.h"+ #include <mach/mach.h>+ #include "front.h"++#include "romfs_arc.h"+ #include <dirent.h>+ #include <errno.h>+ #include <fcntl.h>+@@ -369,6 +370,28 @@ static int host_path_ex(const char *p, char *out, size_t n, int *ro, int create)+ char normed[1024]; const char *rest = c + 1;+ if (strstr(rest, "/.")) { if (!norm_rest(rest, normed, sizeof normed)) return 0; rest = normed; } // only paths with "." components are normalized; the rest walk component by component as before+ if (g_mnt[i].overlay[0] && !create) return rom_overlay_path(&g_mnt[i], rest, out, n);++ // Archive mount: the RomFS tree lives inside a ROMFSARC archive, so the host path is a++ // synthetic "@romfsarc:<guest path>" that the file calls below route to romfs_arc.c. Matched++ // by the mount directory (romfsarc_open recorded the base it actually opened), because the++ // mount name differs between games (rom, content).++ if (romfsarc_active() && g_mnt[i].ro && !create && g_mnt[i].dir[0] && !strcmp(g_mnt[i].dir, g_arc_base)) {++ // Fold runs of '/' the way the directory walk below does: the archive index stores one++ // separator per level, and a game may ask for "data:/bin/appli/icon_sick//bin/x.arc"++ // (Pokemon Sword's Bag: the doubled slash missed the lookup and the game then++ // dereferenced the null it got back — PR #9).++ char folded[1024]; const char *r = rest;++ if (strstr(rest, "//")) {++ size_t o = 0; int slash = 0;++ for (const char *q = rest; *q; q++) {++ if (*q == '/') { if (slash) continue; slash = 1; } else slash = 0;++ if (o + 1 >= sizeof folded) { errno = ENAMETOOLONG; return 0; }++ folded[o++] = *q;++ }++ folded[o] = 0; r = folded;++ }++ if (snprintf(out, n, ROMFSARC_SYNTH_PREFIX "%s", r) >= (int)n) { errno = ENAMETOOLONG; return 0; }++ return 1;++ }+ strlcpy(out, g_mnt[i].dir, n);+ while (*rest) {+ while (*rest == '/') rest++;+@@ -412,9 +435,22 @@ static Result err_res(const char *op, const char *path) {++ // ---------- Mount ----------+ HLE_FORCE("_ZN2nn2fs22QueryMountRomCacheSizeEPm", "fsp-srv; rom reads the host directory directly, the cache gets only the minimum size", Result, h_fs_QueryRomCache, size_t *out) { *out = 0x1000; return RES_OK; }+-HLE_FORCE("_ZN2nn2fs8MountRomEPKcPvm", "fsp-srv; rom → host RomFS directory", Result, h_fs_MountRom, const char *name, void *cache, size_t sz) {++HLE_FORCE("_ZN2nn2fs8MountRomEPKcPvm", "fsp-srv; rom → host RomFS directory (or a ROMFSARC archive)", Result, h_fs_MountRom, const char *name, void *cache, size_t sz) {+ (void)cache; (void)sz; char b[1024];+- Result r = mount(name, envdir("DM_ROMFS", "romfs", b, sizeof b), 1);++ const char *dir = envdir("DM_ROMFS", "romfs", b, sizeof b);++ // Archive mount: romfsarc_open tries <dir>.idx, <dir>/romfs.idx and <dir>/romfs/romfs.idx, so the++ // player may copy the shards either beside the folder or into Documents/romfs/ itself.++ romfsarc_hdr h;++ if (romfsarc_open(dir, &h) == 0) {++ // Mount the resolved archive base (romfsarc_open recorded the one that worked in g_arc_base).++ // host_path_ex compares the mount directory against it.++ Result r = mount(name, g_arc_base, 1);++ if (r != RES_OK) { romfsarc_close(); return r; }++ LOG("fs rom: archive %s (%llu files, %llu dirs, %u shards, tree hash %016llx)", g_arc_base,++ (unsigned long long)h.file_count, (unsigned long long)h.dir_count, h.shard_count, (unsigned long long)h.tree_hash);++ return RES_OK;++ }++ Result r = mount(name, dir, 1);+ if (r == RES_OK && getenv("DM_ROMFS_OVERLAY")) {+ PATH_LOCK();+ for (int i = 0; i < g_nmnt; i++) if (!strcmp(g_mnt[i].name, name)) {+@@ -694,6 +730,41 @@ HLE_FORCE("_ZN2nn2fs14CommitSaveDataEPKc", "fsp-srv; same as Commit (SDK 11's ol+ HLE_FORCE("_ZN2nn2fs7UnmountEPKc", "fsp-srv; the mount table is permanent, unmounting is a no-op", void, h_fs_Unmount, const char *name) { (void)name; }++ // ---------- Files ----------++// ---------- Archive-backed file handles ----------++// An archive file has no host fd. It gets a handle number from a private table, and every operation++// on it (ReadFile, GetFileSize, CloseFile) checks the table first. Handle numbers are distinct from++// fds: real handles are fds (>= 3 in practice), archive handles are tagged by index into g_arc[].++typedef struct { uint32_t shard; uint64_t off, size; int used; } archandle;++#define MAX_ARCH 4096++static archandle g_arc[MAX_ARCH];++static uint64_t g_arch_gen; // bumped on open/close so a stale handle never hits a recycled slot++static uint64_t arc_new(uint32_t shard, uint64_t off, uint64_t size) {++ for (int i = 0; i < MAX_ARCH; i++) if (!g_arc[i].used) {++ g_arc[i].used = 1; g_arc[i].shard = shard; g_arc[i].off = off; g_arc[i].size = size;++ return ((uint64_t)1 << 63) | ((g_arch_gen & 0x7fffffff) << 32) | (uint32_t)i;++ }++ return 0;++}++static int arc_get(uint64_t h, archandle **out) {++ if (!(h >> 63)) return 0;++ uint32_t i = (uint32_t)h;++ if (i >= MAX_ARCH || !g_arc[i].used) return 0;++ if ((uint32_t)((h >> 32) & 0x7fffffff) != (uint32_t)(g_arch_gen & 0x7fffffff)) return 0;++ *out = &g_arc[i]; return 1;++}++static void arc_free(uint64_t h) {++ archandle *a; if (arc_get(h, &a)) a->used = 0;++}++static const char *arc_rel(const char *hp) {++ const char *rel = ROMFSARC_SYNTH_REL(hp);++ while (*rel == '/') rel++;++ return rel;++}++static int arc_file(const char *hp, uint32_t *shard, uint64_t *off, uint64_t *size) {++ return romfsarc_stat_file(arc_rel(hp), shard, off, size);++}++static int arc_dir(const char *hp) { return romfsarc_is_dir(arc_rel(hp)); }++static void arc_norm(const char *hp, char *rel, size_t n) { strlcpy(rel, arc_rel(hp), n); }+ HLE_FORCE("_ZN2nn2fs8OpenFileEPNS0_10FileHandleEPKci", "fsp-srv → open(2)", Result, h_fs_OpenFile, uint64_t *out, const char *path, int mode) {+ int mi; int64_t k;+ if (img_path(path, &mi, &k)) {+@@ -706,6 +777,15 @@ HLE_FORCE("_ZN2nn2fs8OpenFileEPNS0_10FileHandleEPKci", "fsp-srv → open(2)", Re+ }+ HP(path);+ if (mode & (MODE_WRITE | MODE_APPEND)) RW();++ if (ROMFSARC_IS_SYNTH(hp)) { // archive entry: no fd, the handle carries shard/offset/size++ uint32_t shard; uint64_t off, size;++ if (!arc_file(hp, &shard, &off, &size)) { errno = ENOENT; return err_res("open", hp); }++ uint64_t ah = arc_new(shard, off, size);++ if (!ah) { errno = EMFILE; return err_res("open", hp); }++ *out = ah;++ if (g_flag.fs) LOG("fs open %s mode=%d → archive handle (shard %u off %llu size %llu)", path, mode, shard, (unsigned long long)off, (unsigned long long)size);++ return RES_OK;++ }+ int fd = open(hp, (mode & (MODE_WRITE | MODE_APPEND)) ? ((mode & MODE_READ) ? O_RDWR : O_WRONLY) : O_RDONLY);+ if (fd < 0) return err_res("open", hp);+ struct stat st; fstat(fd, &st);+@@ -729,6 +809,20 @@ HLE_FORCE("_ZN2nn2fs8ReadFileEPmNS0_10FileHandleElPvm", "fsp-srv → pread(2)",+ sz = off < 0 || (uint64_t)off >= x->b ? 0 : (size_t)(x->b - off) < sz ? (size_t)(x->b - off) : sz;+ }+ dm_guest_write_prepare(buf, sz); // The destination may be a texture pool page write-protected by the graphics layer: a kernel write to a read-only page returns EFAULT instead of page-faulting, so unprotect and mark dirty first++ archandle *ah;++ if (arc_get(h, &ah)) { // archive entry: clamp to the file, read from its shard++ if (off < 0) { *out = 0; return RES_FAIL; }++ uint64_t avail = (uint64_t)off < ah->size ? ah->size - (uint64_t)off : 0;++ size_t want = sz < avail ? sz : (size_t)avail;++ if (want) { ssize_t r = romfsarc_pread(ah->shard, ah->off + (uint64_t)off, buf, want);++ if (r < 0) return err_res("pread (archive)", "handle"); got = (size_t)r; }++ *out = got;++ if (g_flag.fs) { static uint64_t n, bytes, next_b = 64 << 20; static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;++ pthread_mutex_lock(&m); n++; bytes += got;++ if (bytes >= next_b || n % 1000 == 0) { LOG("fs read total: %llu reads %.1f MiB (this one: archive offset %lld length %#zx)", n, bytes / 1048576.0, (long long)off, got); if (bytes >= next_b) next_b += 64 << 20; }++ pthread_mutex_unlock(&m); }++ return RES_OK;++ }+ while (got < sz) {+ ssize_t r = pread(fd, (uint8_t *)buf + got, sz - got, base + off + got);+ if (r < 0) { if (errno == EINTR) continue;+@@ -785,6 +879,7 @@ HLE_FORCE("_ZN2nn2fs9WriteFileENS0_10FileHandleElPKvmRKNS0_11WriteOptionE", "fsp+ }+ HLE_FORCE("_ZN2nn2fs11GetFileSizeEPlNS0_10FileHandleE", "fsp-srv → fstat(2)", Result, h_fs_GetFileSize, int64_t *out, uint64_t h) {+ if (!h) return RES_FAIL;++ archandle *ah; if (arc_get(h, &ah)) { *out = (int64_t)ah->size; return RES_OK; }+ if (IMG_H(h)) { *out = (int64_t)g_mnt[IMG_M(h)].img->e[IMG_K(h)].b; return RES_OK; }+ struct stat st; if (fstat((int)h, &st)) return err_res("fstat", "fd");+ *out = st.st_size; return RES_OK;+@@ -801,6 +896,7 @@ HLE_FORCE("_ZN2nn2fs11SetFileSizeENS0_10FileHandleEl", "fsp-srv → ftruncate(2)+ HLE_FORCE("_ZN2nn2fs9FlushFileENS0_10FileHandleE", "fsp-srv; host writes are already in the page cache, flushing is a no-op", Result, h_fs_FlushFile, uint64_t h) { (void)h; return RES_OK; }+ HLE_FORCE("_ZN2nn2fs9CloseFileENS0_10FileHandleE", "fsp-srv → close(2)", void, h_fs_CloseFile, uint64_t h) {+ if (!h || IMG_H(h)) return; // the null handle after a failed open (see ReadFile): do not touch fd 0; an image entry holds no descriptor++ if (h >> 63) { arc_free(h); return; } // archive entry: nothing to close+ g_fmode[(int)h & 0xffff] = 0; atomic_store(&g_ftxn[(int)h & 0xffff], 0);+ close((int)h); }+ HLE_FORCE("_ZN2nn2fs15GetFileOpenModeENS0_10FileHandleE", "fsp-srv; the open mode is recorded by the host", int, h_fs_GetFileOpenMode, uint64_t h) { return IMG_H(h) ? MODE_READ : g_fmode[(int)h & 0xffff]; }+@@ -884,12 +980,39 @@ HLE_FORCE("_ZN2nn2fs12GetEntryTypeEPNS0_18DirectoryEntryTypeEPKc", "fsp-srv →+ int mi; int64_t k;+ if (img_path(path, &mi, &k)) { if (k < 0) return err_res("stat", path); *out = g_mnt[mi].img->e[k].type ? ENT_FILE : ENT_DIR; return RES_OK; }+ HP(path); struct stat st;++ if (ROMFSARC_IS_SYNTH(hp)) { // archive entry or directory, from the index++ const char *rel = arc_rel(hp); // the index stores paths without a leading slash (abe35a3)++ uint32_t sh; uint64_t of, szf;++ if (romfsarc_stat_file(rel, &sh, &of, &szf)) { *out = ENT_FILE; return RES_OK; }++ if (romfsarc_is_dir(rel)) { *out = ENT_DIR; return RES_OK; }++ errno = ENOENT; return err_res("stat", hp);++ }+ if (stat(hp, &st)) return err_res("stat", hp);+ *out = S_ISDIR(st.st_mode) ? ENT_DIR : ENT_FILE; return RES_OK;+ }++ // ---------- Directories ----------+ typedef struct { DIR *d; char path[1024]; DIR *od; char opath[1024]; DirectoryEntry *snap; int64_t nsnap, psnap; int mode; } dirh_t;++++// An archive directory has no host DIR: its entries come from the index, copied into the same++// snapshot list the overlay mount uses, so ReadDirectory has one path for both.++static void arc_snapshot(dirh_t *h, const char *hp) {++ char rel[1024]; arc_norm(hp, rel, sizeof rel);++ int n = romfsarc_count(rel);++ if (n <= 0) return;++ romfsarc_ent *ents = malloc((size_t)n * sizeof *ents);++ if (!ents) die("archive directory snapshot allocation failed");++ int got = romfsarc_list(rel, ents, n);++ if (got <= 0) { free(ents); return; }++ h->snap = calloc((size_t)got, sizeof *h->snap); h->nsnap = got;++ if (!h->snap) die("archive directory snapshot allocation failed");++ for (int i = 0; i < got; i++) {++ strlcpy(h->snap[i].name, ents[i].name, sizeof h->snap[i].name);++ h->snap[i].type = ents[i].is_dir ? ENT_DIR : ENT_FILE;++ h->snap[i].size = ents[i].is_dir ? 0 : ents[i].size;++ }++ free(ents);++}+ static void dir_snapshot(dirh_t *h, const mount_t *m, const char *rest) {+ char *roots = strdup(m->overlay);+ size_t cap = 2048; char (*names)[0x301] = malloc(cap * sizeof *names);+@@ -950,7 +1073,15 @@ HLE_FORCE("_ZN2nn2fs13OpenDirectoryEPNS0_15DirectoryHandleEPKci", "fsp-srv → o+ }+ *out = (uint64_t)h; return RES_OK;+ }+- HP(path); DIR *d = opendir(hp);++ HP(path);++ if (ROMFSARC_IS_SYNTH(hp)) { // archive directory: no host DIR, only the snapshot++ if (!arc_dir(hp)) { errno = ENOTDIR; return err_res("opendir", hp); }++ dirh_t *ah = calloc(1, sizeof *ah); if (!ah) die("directory handle allocation failed");++ strlcpy(ah->path, hp, sizeof ah->path); ah->mode = mode;++ arc_snapshot(ah, hp);++ *out = (uint64_t)ah; return RES_OK;++ }++ DIR *d = opendir(hp);+ if (!d) return err_res("opendir", hp);+ dirh_t *h = calloc(1, sizeof *h); h->d = d; strlcpy(h->path, hp, sizeof h->path); h->mode = mode;+ const char *c = strchr(path, ':');+@@ -963,6 +1094,7 @@ HLE_FORCE("_ZN2nn2fs13ReadDirectoryEPlPNS0_14DirectoryEntryENS0_15DirectoryHandl+ if (!hh) { *count = 0; return RES_FAIL; }+ PATH_LOCK(); dirh_t *h = (dirh_t *)hh; int64_t n = 0; struct dirent *e;+ if (h->snap) { while (n < max && h->psnap < h->nsnap) { DirectoryEntry *src = &h->snap[h->psnap++]; if (!(h->mode & (src->type == ENT_DIR ? DIRMODE_DIR : DIRMODE_FILE))) continue; ents[n++] = *src; } *count = n; return RES_OK; }++ if (!h->d) { *count = 0; return RES_OK; } // an archive directory that turned out empty (no snapshot, no host DIR)+ int dfd = dirfd(h->d);+ while (n < max && (e = readdir(h->d))) {+ if (!strcmp(e->d_name, ".") || !strcmp(e->d_name, "..")) continue;+diff --git a/dm/host/romfs_arc.c b/dm/host/romfs_arc.c+new file mode 100644+index 00000000..d76681d1+--- /dev/null++++ b/dm/host/romfs_arc.c+@@ -0,0 +1,228 @@++// RomFS archive reader: see romfs_arc.h for the on-disk format.++#include "romfs_arc.h"++#include <errno.h>++#include <fcntl.h>++#include <stdio.h>++#include <stdlib.h>++#include <string.h>++#include <sys/mman.h>++#include <sys/stat.h>++#include <unistd.h>++#include <pthread.h>++++typedef struct {++ uint32_t name_off, shard;++ uint64_t off, size;++ uint32_t mode, res;++} filerec;++++typedef struct {++ uint32_t name_off, first_child, child_count, res;++} dirrec;++++static struct {++ int open;++ void *idx; // mmap of the index file++ size_t idx_size;++ romfsarc_hdr hdr;++ const char *pool;++ const filerec *files;++ const dirrec *dirs;++ const uint32_t *children;++ char base[1024];++ int shard_fd[256];++ char shard_path[256][1024];++ pthread_mutex_t lock;++} A = { .shard_fd = { [0 ... 255] = -1 }, .lock = PTHREAD_MUTEX_INITIALIZER };++++static uint64_t rd64(const void *p) { uint64_t v; memcpy(&v, p, 8); return v; }++static uint32_t rd32(const void *p) { uint32_t v; memcpy(&v, p, 4); return v; }++++char g_arc_base[1024]; // the archive's base path, matched against mount directories by hle_fs.c++++static const char *fname(const filerec *f) { return A.pool + f->name_off; }++static const char *dname(const dirrec *d) { return A.pool + d->name_off; }++++// Binary search the file table by path. Returns the record or NULL.++static const filerec *find_file(const char *rel) {++ uint64_t lo = 0, hi = A.hdr.file_count;++ while (lo < hi) {++ uint64_t mid = lo + (hi - lo) / 2;++ int c = strcmp(fname(&A.files[mid]), rel);++ if (c == 0) return &A.files[mid];++ if (c < 0) lo = mid + 1; else hi = mid;++ }++ return NULL;++}++++// Binary search the directory table by path. Returns the record or NULL.++// A trailing slash names the same directory, as it does for opendir(3) on the plain tree: Bayonetta 3 opens "movie/" at boot,++// and without this the archive said the movie folder did not exist, so the game never started its opening movie on iOS.++static const dirrec *find_dir(const char *rel) {++ char trimmed[1024]; size_t n = strlen(rel);++ if (n && rel[n - 1] == '/' && n < sizeof trimmed) {++ while (n && rel[n - 1] == '/') n--;++ memcpy(trimmed, rel, n); trimmed[n] = 0; rel = trimmed;++ }++ uint64_t lo = 0, hi = A.hdr.dir_count;++ while (lo < hi) {++ uint64_t mid = lo + (hi - lo) / 2;++ int c = strcmp(dname(&A.dirs[mid]), rel);++ if (c == 0) return &A.dirs[mid];++ if (c < 0) lo = mid + 1; else hi = mid;++ }++ return NULL;++}++++// Open and validate one index file. Returns the mapping (and its size) or MAP_FAILED.++static void *map_index(const char *path, size_t *size) {++ int fd = open(path, O_RDONLY);++ if (fd < 0) return MAP_FAILED;++ struct stat st;++ if (fstat(fd, &st)) { close(fd); errno = EIO; return MAP_FAILED; }++ if ((size_t)st.st_size < ROMFSARC_HDR) { close(fd); errno = EINVAL; return MAP_FAILED; }++ void *m = mmap(NULL, (size_t)st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);++ close(fd);++ if (m == MAP_FAILED) return MAP_FAILED;++ const uint8_t *b = m;++ if (memcmp(b, ROMFSARC_MAGIC, 8) || rd32(b + 8) != ROMFSARC_VERSION) {++ munmap(m, (size_t)st.st_size); errno = EINVAL; return MAP_FAILED;++ }++ *size = (size_t)st.st_size;++ return m;++}++++int romfsarc_open(const char *base, romfsarc_hdr *out) {++ // The base is where the shards live, without the ".idx". Callers pass either the base itself++ // (DM_ROMFS=/games/totk/romfs with romfs.idx beside it) or a directory that holds the archive++ // (DM_ROMFS=Documents/romfs with Documents/romfs/romfs.idx inside, which is what the iOS app++ // sets). Try both, and a base that already carries the .idx suffix.++ char cand[4][1200];++ char stripped[1200];++ strlcpy(stripped, base, sizeof stripped);++ size_t sl = strlen(stripped);++ if (sl > 4 && !strcmp(stripped + sl - 4, ".idx")) stripped[sl - 4] = 0;++ snprintf(cand[0], sizeof cand[0], "%s.idx", stripped); // <base>.idx++ snprintf(cand[1], sizeof cand[1], "%s/romfs.idx", stripped); // <base>/romfs.idx++ snprintf(cand[2], sizeof cand[2], "%s/romfs/romfs.idx", stripped); // one more level (a bundle-style layout)++ cand[3][0] = 0;++ void *m = MAP_FAILED; size_t sz = 0; char used[1200] = "";++ for (int i = 0; i < 3; i++) {++ m = map_index(cand[i], &sz);++ if (m != MAP_FAILED) { strlcpy(used, cand[i], sizeof used); break; }++ }++ if (m == MAP_FAILED) return -1;++ // The resolved base is the index path minus ".idx": shard paths are built from it++ size_t ul = strlen(used); if (ul > 4) used[ul - 4] = 0;++ const uint8_t *b = m;++ romfsarc_hdr h;++ h.shard_count = rd32(b + 12);++ h.file_count = rd64(b + 24);++ h.dir_count = rd64(b + 32);++ h.tree_hash = rd64(b + 56);++ if (h.shard_count == 0 || h.shard_count > 256) { munmap(m, sz); errno = EINVAL; return -1; }++ uint64_t pool_sz = rd64(b + 40);++ uint64_t need = ROMFSARC_HDR + pool_sz + h.file_count * ROMFSARC_FILEREC + h.dir_count * ROMFSARC_DIRREC;++ // The child list follows the directory table; its length is implied by the last directory's range,++ // so the file only has to be at least as long as the three tables above.++ if (need > (uint64_t)sz) { munmap(m, sz); errno = EINVAL; return -1; }++ pthread_mutex_lock(&A.lock);++ A.open = 1; A.idx = m; A.idx_size = sz; A.hdr = h;++ A.pool = (const char *)(b + ROMFSARC_HDR);++ A.files = (const filerec *)(b + ROMFSARC_HDR + pool_sz);++ A.dirs = (const dirrec *)((const uint8_t *)A.files + h.file_count * ROMFSARC_FILEREC);++ A.children = (const uint32_t *)((const uint8_t *)A.dirs + h.dir_count * ROMFSARC_DIRREC);++ for (int i = 0; i < 256; i++) { A.shard_fd[i] = -1; A.shard_path[i][0] = 0; }++ // Shards are named after the index file's own base, so <dir>/romfs.idx pairs with <dir>/romfs.00++ strlcpy(A.base, used, sizeof A.base);++ strlcpy(g_arc_base, used, sizeof g_arc_base);++ pthread_mutex_unlock(&A.lock);++ if (out) *out = h;++ return 0;++}++++int romfsarc_active(void) { return A.open; }++++int romfsarc_stat_file(const char *rel, uint32_t *shard, uint64_t *off, uint64_t *size) {++ if (!A.open) return 0;++ const filerec *f = find_file(rel);++ if (!f) return 0;++ if (shard) *shard = f->shard;++ if (off) *off = f->off;++ if (size) *size = f->size;++ return 1;++}++++int romfsarc_is_dir(const char *rel) {++ if (!A.open) return 0;++ return find_dir(rel) != NULL;++}++++static int shard_fd(uint32_t i) {++ if (i >= A.hdr.shard_count) { errno = EINVAL; return -1; }++ if (A.shard_fd[i] >= 0) return A.shard_fd[i];++ pthread_mutex_lock(&A.lock);++ if (A.shard_fd[i] < 0) {++ char p[1024];++ if (snprintf(p, sizeof p, "%s.%02u", A.base, i) < (int)sizeof p) {++ int fd = open(p, O_RDONLY);++ if (fd >= 0) { A.shard_fd[i] = fd; strlcpy(A.shard_path[i], p, sizeof A.shard_path[i]); }++ }++ }++ int fd = A.shard_fd[i];++ pthread_mutex_unlock(&A.lock);++ return fd;++}++++ssize_t romfsarc_pread(uint32_t shard, uint64_t off, void *buf, size_t n) {++ int fd = shard_fd(shard);++ if (fd < 0) return -1;++ size_t done = 0;++ while (done < n) {++ ssize_t r = pread(fd, (uint8_t *)buf + done, n - done, (off_t)(off + done));++ if (r < 0) { if (errno == EINTR) continue; return -1; }++ if (r == 0) break;++ done += (size_t)r;++ }++ return (ssize_t)done;++}++++int romfsarc_list(const char *rel, romfsarc_ent *out, int max) {++ if (!A.open) return -1;++ const dirrec *d = find_dir(rel);++ if (!d) return -1;++ int n = 0;++ for (uint32_t i = 0; i < d->child_count && n < max; i++) {++ uint32_t tag = A.children[d->first_child + i];++ romfsarc_ent *e = &out[n];++ if (tag & ROMFSARC_CHILD_DIR) {++ const dirrec *c = &A.dirs[tag & ~ROMFSARC_CHILD_DIR];++ // The directory table stores full paths; a child list entry carries only the leaf name++ const char *full = dname(c), *leaf = strrchr(full, '/');++ strlcpy(e->name, leaf ? leaf + 1 : full, sizeof e->name);++ e->is_dir = 1; e->size = 0;++ } else {++ const filerec *c = &A.files[tag];++ // The file table stores full paths; a child list entry carries only the leaf name++ const char *full = fname(c), *leaf = strrchr(full, '/');++ strlcpy(e->name, leaf ? leaf + 1 : full, sizeof e->name);++ e->is_dir = 0; e->size = (int64_t)c->size;++ }++ n++;++ }++ return n;++}++++int romfsarc_count(const char *rel) {++ if (!A.open) return -1;++ const dirrec *d = find_dir(rel);++ return d ? (int)d->child_count : -1;++}++++void romfsarc_close(void) {++ pthread_mutex_lock(&A.lock);++ for (int i = 0; i < 256; i++) if (A.shard_fd[i] >= 0) { close(A.shard_fd[i]); A.shard_fd[i] = -1; }++ if (A.idx) { munmap(A.idx, A.idx_size); A.idx = NULL; }++ A.open = 0;++ pthread_mutex_unlock(&A.lock);++}+diff --git a/dm/host/romfs_arc.h b/dm/host/romfs_arc.h+new file mode 100644+index 00000000..c4a25b48+--- /dev/null++++ b/dm/host/romfs_arc.h+@@ -0,0 +1,100 @@++// RomFS archive (ROMFSARC): a whole RomFS tree in one index file plus a few hundred shard files.++//++// Why: a RomFS like Tears of the Kingdom's is 300,000 files. Copying that into an App's Documents++// takes hours over the Files app / Finder, and a 16 GB IPA with that many entries does not install++// (PackageExtractionFailed). Packing the tree into ~100 shard files makes both a single copy.++//++// Layout (all integers little-endian):++// <base>.idx header, name pool, file table, directory table++// <base>.<NN> shard NN: the files' bytes back to back, in file-table order++//++// Header (64 bytes):++// 0x00 char magic[8] "ROMFSARC"++// 0x08 uint32 version 1++// 0x0c uint32 shard_count++// 0x10 uint64 index_size size of this index file++// 0x18 uint64 file_count++// 0x20 uint64 dir_count++// 0x28 uint64 name_pool_size++// 0x30 uint64 reserved++// 0x38 uint64 tree_hash FNV-1a over (path, size) of every file, sorted: a cheap identity check++//++// File table: file_count records of 32 bytes, sorted by path (the name pool offset points at the++// NUL-terminated relative path, '/'-separated, no leading slash):++// 0x00 uint32 name_off++// 0x04 uint32 shard++// 0x08 uint64 offset_in_shard++// 0x10 uint64 size++// 0x18 uint32 mode 0777 bits (the executable bit matters for nothing in RomFS, kept for fidelity)++// 0x1c uint32 reserved++//++// Directory table: dir_count records of 16 bytes, sorted by path ("" = the root):++// 0x00 uint32 name_off++// 0x04 uint32 first_child index into the child list++// 0x08 uint32 child_count++// 0x0c uint32 reserved++// Child list: uint32 file-table / directory-table indices, each tagged: bit 31 set = a directory.++// Children of one directory are contiguous and sorted by name.++//++// Path lookup is a binary search over the sorted tables; directory listing walks one child range.++// Case sensitivity: Horizon paths are case-sensitive and the archive is built from a case-sensitive++// walk, so the host looks names up exactly (the existing dir_index/case-alias machinery is not used++// for archive mounts).++#ifndef DM_ROMFS_ARC_H++#define DM_ROMFS_ARC_H++++#include <stdint.h>++#include <stddef.h>++#include <sys/types.h>++++#define ROMFSARC_MAGIC "ROMFSARC"++#define ROMFSARC_VERSION 1u++#define ROMFSARC_HDR 64++#define ROMFSARC_FILEREC 32++#define ROMFSARC_DIRREC 16++#define ROMFSARC_CHILD_DIR 0x80000000u++++// Synthetic host path prefix for archive-backed entries (see host_path_ex in hle_fs.c). A path that++// starts with this marker is not a real file: the fs layer routes it to the archive instead.++#define ROMFSARC_SYNTH_PREFIX "@romfsarc:"++#define ROMFSARC_IS_SYNTH(p) (!strncmp((p), ROMFSARC_SYNTH_PREFIX, sizeof ROMFSARC_SYNTH_PREFIX - 1))++#define ROMFSARC_SYNTH_REL(p) ((p) + sizeof ROMFSARC_SYNTH_PREFIX - 1)++++typedef struct {++ uint32_t shard_count;++ uint64_t file_count, dir_count;++ uint64_t tree_hash;++} romfsarc_hdr;++++// Open the index at <base>.idx. Returns 0 on success, -1 with errno set on failure.++// Keeps the index mapped; shards are opened lazily and cached.++int romfsarc_open(const char *base, romfsarc_hdr *out);++++// Whether an archive is open (the fs layer then routes lookups here instead of the host tree).++int romfsarc_active(void);++++// The base path the archive was opened from (without ".idx"): the fs layer matches mount++// directories against it, so the mount name ("rom", "content", …) does not matter.++extern char g_arc_base[];++++// Resolve a guest path (no leading slash, "" = root) to a file. On success fills the shard index,++// offset and size; returns 1. Returns 0 when the path is not a file (missing or a directory).++int romfsarc_stat_file(const char *rel, uint32_t *shard, uint64_t *off, uint64_t *size);++++// Whether the path names a directory ("" = root): 1 yes, 0 no.++int romfsarc_is_dir(const char *rel);++++// Read from an open archive file. Same semantics as pread.++ssize_t romfsarc_pread(uint32_t shard, uint64_t off, void *buf, size_t n);++++// Directory listing: write the entries of directory <rel> ("" = root) into the caller's array.++// Each entry gets its name and type; files also get their size. Returns the number written, or -1.++typedef struct { char name[0x301]; int is_dir; int64_t size; } romfsarc_ent;++int romfsarc_list(const char *rel, romfsarc_ent *out, int max);++++// Number of entries in a directory (unfiltered), or -1.++int romfsarc_count(const char *rel);++++void romfsarc_close(void);++++#endif+diff --git a/dm/host/tests/Makefile b/dm/host/tests/Makefile+index 61b6b573..ad9bb9aa 100644+--- a/dm/host/tests/Makefile++++ b/dm/host/tests/Makefile+@@ -82,17 +82,17 @@ $(B)/t_gesture: t_gesture.c ../hle_touch.c ../front.h ../dm.h $(GAME_H) | $(B)+ clang -O1 -Wall -Wno-unused-function -I.. $(GINC) -o $@ t_gesture.c ../hle_touch.c+ $(B)/t_thread_leak: t_thread_leak.c ../thread.c ../dm.h $(GAME_H) | $(B)+ clang -O1 -Wno-unused-function -I.. $(GINC) -o $@ t_thread_leak.c+-$(B)/t_fs: t_fs.c t_fs_stub.c ../hle_fs.c ../hle_bigstack.c ../hle.h ../dm.h $(GAME_H) ../hle_profile.c ../hle_profile.h | $(B)+- clang -O1 -Wno-unused-function -I.. $(GINC) -o $@ t_fs.c t_fs_stub.c ../hle_bigstack.c ../hle_profile.c+-$(B)/t_fs_commit_list: t_fs_commit_list.c t_fs_stub.c ../hle_fs.c ../hle_bigstack.c ../hle.h ../dm.h $(GAME_H) ../hle_profile.c ../hle_profile.h | $(B)+- clang -O1 -Wall -Wno-unused-function -I.. $(GINC) -o $@ t_fs_commit_list.c t_fs_stub.c ../hle_bigstack.c ../hle_profile.c++$(B)/t_fs: t_fs.c t_fs_stub.c ../hle_fs.c ../hle_bigstack.c ../romfs_arc.c ../hle.h ../dm.h $(GAME_H) ../hle_profile.c ../hle_profile.h | $(B)++ clang -O1 -Wno-unused-function -I.. $(GINC) -o $@ t_fs.c t_fs_stub.c ../hle_bigstack.c ../romfs_arc.c ../hle_profile.c++$(B)/t_fs_commit_list: t_fs_commit_list.c t_fs_stub.c ../hle_fs.c ../hle_bigstack.c ../romfs_arc.c ../hle.h ../dm.h $(GAME_H) ../hle_profile.c ../hle_profile.h | $(B)++ clang -O1 -Wall -Wno-unused-function -I.. $(GINC) -o $@ t_fs_commit_list.c t_fs_stub.c ../hle_bigstack.c ../romfs_arc.c ../hle_profile.c+ $(B)/t_fs_commit_list_tsan: t_fs_commit_list.c t_fs_stub.c ../hle_fs.c ../hle_bigstack.c ../hle.h ../dm.h $(GAME_H) | $(B)+ clang -O1 -g -fsanitize=thread -Wall -Wno-unused-function -I.. $(GINC) -o $@ t_fs_commit_list.c t_fs_stub.c ../hle_bigstack.c ../hle_profile.c+ .PHONY: fs-tsan+ fs-tsan: $(B)/t_fs_commit_list_tsan+ TMPDIR="$(abspath $(B))" $(B)/t_fs_commit_list_tsan+-$(B)/t_fs_case: t_fs_case.c ../hle_fs.c ../hle_bigstack.c ../hle.h ../dm.h $(GAME_H) ../hle_profile.c ../hle_profile.h | $(B)+- clang -O1 -Wno-unused-function -I.. $(GINC) -o $@ t_fs_case.c ../hle_bigstack.c ../hle_profile.c++$(B)/t_fs_case: t_fs_case.c ../hle_fs.c ../hle_bigstack.c ../romfs_arc.c ../hle.h ../dm.h $(GAME_H) ../hle_profile.c ../hle_profile.h | $(B)++ clang -O1 -Wno-unused-function -I.. $(GINC) -o $@ t_fs_case.c ../hle_bigstack.c ../romfs_arc.c ../hle_profile.c+ $(B)/t_audio: t_audio.c ../hle_audio.c ../hle.h ../dm.h $(GAME_H) | $(B)+ clang -O1 -Wno-unused-function -I.. $(GINC) -o $@ t_audio.c -framework AudioToolbox+ $(B)/t_audio_spsc: t_audio_spsc.c ../hle_audio.c ../hle.h ../dm.h $(GAME_H) | $(B)+diff --git a/dm/host/tests/t_romfs_arc.c b/dm/host/tests/t_romfs_arc.c+new file mode 100644+index 00000000..3f675332+--- /dev/null++++ b/dm/host/tests/t_romfs_arc.c+@@ -0,0 +1,87 @@++// Test romfs_arc.c against a packed archive: path lookup, partial reads, directory listing.++// Build: clang -I dm/host -o /tmp/t_romfs_arc dm/host/tests/t_romfs_arc.c dm/host/romfs_arc.c++#include "romfs_arc.h"++#include <stdio.h>++#include <string.h>++#include <stdlib.h>++++static int fails;++#define CHECK(cond, ...) do { if (!(cond)) { printf("FAIL: "); printf(__VA_ARGS__); printf("\n"); fails++; } } while (0)++++int main(int argc, char **argv) {++ if (argc < 2) { printf("usage: %s <base>\n", argv[0]); return 2; }++ romfsarc_hdr h;++ if (romfsarc_open(argv[1], &h)) { perror("romfsarc_open"); return 2; }++ printf("opened: %llu files, %llu dirs, %u shards, hash %016llx\n",++ (unsigned long long)h.file_count, (unsigned long long)h.dir_count, h.shard_count,++ (unsigned long long)h.tree_hash);++ CHECK(romfsarc_active(), "active after open");++ CHECK(h.file_count > 0 && h.dir_count > 0 && h.shard_count > 0, "header counts");++++ // Every file: stat it, read it whole, and read it in two halves at an offset++ romfsarc_ent *ents = calloc(4096, sizeof *ents);++ char path[1024] = "";++ int listed = romfsarc_list("", ents, 4096);++ CHECK(listed > 0, "root has entries, got %d", listed);++ CHECK(listed == romfsarc_count(""), "list and count agree at the root: %d vs %d", listed, romfsarc_count(""));++++ // Walk the tree breadth first and check every file's bytes against a direct read of its shard++ size_t dcap = 1024;++ char **dirs = calloc(dcap, sizeof *dirs);++ int nd = 0;++ dirs[nd++] = strdup("");++ int checked = 0;++ while (nd) {++ char *d = dirs[--nd];++ int n = romfsarc_count(d);++ CHECK(n >= 0, "count of '%s'", d);++ romfsarc_ent *e = calloc((size_t)(n > 0 ? n : 1), sizeof *e);++ int got = romfsarc_list(d, e, n);++ CHECK(got == n, "list '%s': %d vs %d", d, got, n);++ for (int i = 0; i < got; i++) {++ char rel[1024];++ snprintf(rel, sizeof rel, "%s%s%s", d, *d ? "/" : "", e[i].name);++ if (e[i].is_dir) {++ CHECK(romfsarc_is_dir(rel), "is_dir '%s'", rel);++ CHECK(!romfsarc_stat_file(rel, NULL, NULL, NULL), "dir is not a file: '%s'", rel);++ char slash[1024]; snprintf(slash, sizeof slash, "%s/", rel); // a trailing slash names the same directory (Bayonetta 3 opens "movie/")++ CHECK(romfsarc_is_dir(slash) && romfsarc_count(slash) == romfsarc_count(rel), "trailing slash '%s'", slash);++ if ((size_t)nd == dcap) { dcap *= 2; dirs = realloc(dirs, dcap * sizeof *dirs); }++ dirs[nd++] = strdup(rel);++ } else {++ uint32_t shard; uint64_t off, size;++ CHECK(romfsarc_stat_file(rel, &shard, &off, &size), "stat '%s'", rel);++ CHECK((int64_t)size == e[i].size, "size '%s': %llu vs %lld", rel,++ (unsigned long long)size, (long long)e[i].size);++ char *buf = malloc(size ? size : 1);++ ssize_t r = romfsarc_pread(shard, off, buf, size);++ CHECK(r == (ssize_t)size, "read '%s': %zd vs %llu", rel, r, (unsigned long long)size);++ // A read past this file's end lands in the next file's bytes: the archive is a flat++ // container, so the reader must not fabricate zeros. The fs layer clamps to the file++ // size (see h_fs_ReadFile), so this only checks the reader does not fail outright.++ char extra[16];++ ssize_t r2 = romfsarc_pread(shard, off + size, extra, sizeof extra);++ CHECK(r2 >= 0, "read past end of '%s' errored: %zd", rel, r2);++ free(buf);++ checked++;++ }++ }++ free(e);++ }++ CHECK(checked == (int)h.file_count, "walked %d files, header says %llu", checked, (unsigned long long)h.file_count);++++ // Missing paths++ CHECK(!romfsarc_stat_file("nope/nothing", NULL, NULL, NULL), "missing file is not found");++ CHECK(!romfsarc_is_dir("nope"), "missing dir is not a dir");++ CHECK(romfsarc_list("nope", ents, 4) < 0, "list of a missing dir fails");++++ // Root itself is a directory, and the empty path is not a file++ CHECK(romfsarc_is_dir(""), "root is a dir");++ CHECK(!romfsarc_stat_file("", NULL, NULL, NULL), "root is not a file");++++ romfsarc_close();++ CHECK(!romfsarc_active(), "closed");++ free(ents);++ printf(fails ? "%d FAILURES\n" : "all checks passed (%d files)\n", fails ? fails : checked);++ return fails ? 1 : 0;++}+diff --git a/dm/tools/romfs_arc.py b/dm/tools/romfs_arc.py+new file mode 100644+index 00000000..000cb4c8+--- /dev/null++++ b/dm/tools/romfs_arc.py+@@ -0,0 +1,270 @@++#!/usr/bin/env python3++"""Pack a RomFS tree into a ROMFSARC archive (one index file + N shard files).++++Why: Tears of the Kingdom's RomFS is 304,000 files. Copying that into an App's Documents takes++hours, and a 16 GB IPA with that many entries fails to install on iOS (PackageExtractionFailed).++An archive is ~120 files instead, so one copy moves it.++++Shard layout: files are grouped by their top-level directory (so one shard holds one kind of++content), then split so that no shard passes --shard-mib. Files are written in path order within++a shard; a shard never mixes content from different top-level directories unless that directory++alone exceeds the limit.++++Usage:++ romfs_arc.py pack <romfs dir> <output base> [--shard-mib 200]++ romfs_arc.py list <base> [path] # debug: list a directory++ romfs_arc.py verify <base> <romfs dir> # compare every file's bytes against the source tree++++Format: see dm/host/romfs_arc.h.++"""++import argparse++import collections++import os++import struct++import sys++++MAGIC = b"ROMFSARC"++VERSION = 1++HDR = 64++FILEREC = 32++DIRREC = 16++CHILD_DIR = 0x80000000++++++def fnv1a(data, h=0xCBF29CE484222325):++ for b in data:++ h = ((h ^ b) * 0x100000001B3) & 0xFFFFFFFFFFFFFFFF++ return h++++++def walk(root):++ """Every file and directory under root, as (relpath, size) / relpath. Relpaths use '/' and have++ no leading slash; the root itself is ''. Symlinks are followed (RomFS has none in the games++ seen so far); anything that is neither a file nor a directory is an error."""++ files, dirs = [], [""]++ for dp, dn, fn in os.walk(root):++ rel_dir = os.path.relpath(dp, root).replace(os.sep, "/")++ if rel_dir == ".":++ rel_dir = ""++ dn.sort()++ for d in dn:++ dirs.append(f"{rel_dir}/{d}" if rel_dir else d)++ for f in sorted(fn):++ p = os.path.join(dp, f)++ try:++ st = os.stat(p)++ except OSError as e:++ sys.exit(f"[RED] cannot stat {p}: {e}")++ files.append((f"{rel_dir}/{f}" if rel_dir else f, st.st_size))++ files.sort(key=lambda x: x[0])++ dirs.sort()++ return files, dirs++++++def plan_shards(files, shard_bytes):++ """Assign every file a shard. Files are grouped by top-level directory, keeping the walk order++ (path order) inside a group; a group is cut into shards of at most shard_bytes."""++ by_top = collections.OrderedDict()++ for rel, size in files:++ top = rel.split("/", 1)[0]++ by_top.setdefault(top, []).append((rel, size))++ # Big groups first, so the shard count stays close to the size total / shard_bytes++ order = sorted(by_top.items(), key=lambda kv: -sum(s for _, s in kv[1]))++ assign, shard = {}, 0++ for top, items in order:++ cur = 0++ for rel, size in items:++ if cur and cur + size > shard_bytes:++ shard += 1++ cur = 0++ assign[rel] = (shard, cur)++ cur += size++ shard += 1++ return assign, shard++++++def pack(romfs, base, shard_mib):++ shard_bytes = shard_mib << 20++ files, dirs = walk(romfs)++ total = sum(s for _, s in files)++ print(f"pack: {len(files):,} files, {len(dirs):,} directories, {total / 2**30:.2f} GiB", flush=True)++ assign, nshard = plan_shards(files, shard_bytes)++ print(f"pack: {nshard} shards of at most {shard_mib} MiB", flush=True)++++ # Shard files: written in path order within each shard++ per_shard = collections.defaultdict(list)++ for rel, size in files:++ per_shard[assign[rel][0]].append((rel, size))++ os.makedirs(os.path.dirname(base) or ".", exist_ok=True)++ written = 0++ for i in range(nshard):++ path = f"{base}.{i:02d}"++ with open(path, "wb") as out:++ for rel, size in sorted(per_shard[i]):++ with open(os.path.join(romfs, rel), "rb") as f:++ left = size++ while left:++ buf = f.read(min(left, 1 << 22))++ if not buf:++ sys.exit(f"[RED] {rel}: file shrank while packing")++ out.write(buf)++ left -= len(buf)++ written += size++ print(f"\r shard {i + 1}/{nshard}: {os.path.getsize(path) / 2**20:.0f} MiB", end="", flush=True)++ print(f"\n wrote {written / 2**30:.2f} GiB in {nshard} shards", flush=True)++++ # Name pool++ pool = bytearray()++ name_off = {}++++ def intern(s):++ if s not in name_off:++ name_off[s] = len(pool)++ pool.extend(s.encode("utf-8") + b"\0")++ return name_off[s]++++ for rel, _ in files:++ intern(rel)++ for d in dirs:++ intern(d)++++ # File table (sorted by path, same order as `files`)++ file_idx = {}++ ftab = bytearray()++ for n, (rel, size) in enumerate(files):++ file_idx[rel] = n++ shard, off = assign[rel]++ ftab += struct.pack("<IIQQII", intern(rel), shard, off, size, 0o644, 0)++++ # Directory table + child list. A directory's children are its immediate files and directories,++ # sorted by name, contiguous in the child list.++ dir_idx = {d: n for n, d in enumerate(dirs)}++ children_of = collections.defaultdict(list)++ for rel, _ in files:++ parent, _, name = rel.rpartition("/")++ children_of[parent].append((name, file_idx[rel]))++ for d in dirs:++ for sub in dirs:++ if sub and sub.rpartition("/")[0] == d and sub != d:++ # Only the leaf name goes in the child list; the directory's own path is in its record++ children_of[d].append((sub.rpartition("/")[2], dir_idx[sub] | CHILD_DIR))++++ dtab = bytearray()++ child_list = []++ for d in dirs:++ kids = sorted(children_of[d])++ first = len(child_list)++ child_list.extend(tag for _, tag in kids)++ dtab += struct.pack("<IIII", intern(d), first, len(kids), 0)++++ tree = bytearray()++ for rel, size in files:++ tree += f"{rel}\0{size}\0".encode()++ tree_hash = fnv1a(tree)++++ idx_path = f"{base}.idx"++ with open(idx_path, "wb") as out:++ out.write(struct.pack("<8sIIQQQQQQ", MAGIC, VERSION, nshard, 0, len(files), len(dirs),++ len(pool), 0, tree_hash))++ out.write(pool)++ out.write(ftab)++ out.write(dtab)++ out.write(struct.pack(f"<{len(child_list)}I", *child_list) if child_list else b"")++ print(f"pack: index {os.path.getsize(idx_path) / 2**20:.1f} MiB ({len(pool) / 2**20:.1f} MiB names, "++ f"{len(files):,} files, {len(dirs):,} directories), tree hash {tree_hash:016x}", flush=True)++ print(f"pack: total {nshard + 1} files", flush=True)++++++def load(base):++ with open(f"{base}.idx", "rb") as f:++ b = f.read()++ magic, ver, nshard, _pad, nfiles, ndirs, pool_sz, _r, tree_hash = struct.unpack_from("<8sIIQQQQQQ", b, 0)++ if magic != MAGIC or ver != VERSION:++ sys.exit("[RED] not a ROMFSARC index")++ pool = b[HDR:HDR + pool_sz]++ off = HDR + pool_sz++ files = []++ for i in range(nfiles):++ name_off, shard, foff, size, mode, _ = struct.unpack_from("<IIQQII", b, off + i * FILEREC)++ name = pool[name_off:pool.index(b"\0", name_off)].decode()++ files.append((name, shard, foff, size))++ off += nfiles * FILEREC++ dirs = []++ for i in range(ndirs):++ name_off, first, count, _ = struct.unpack_from("<IIII", b, off + i * DIRREC)++ name = pool[name_off:pool.index(b"\0", name_off)].decode()++ dirs.append((name, first, count))++ off += ndirs * DIRREC++ kids = struct.unpack_from(f"<{len(b) - off >> 2}I", b, off) if len(b) > off else ()++ return dict(nshard=nshard, files=files, dirs=dirs, kids=kids, tree_hash=tree_hash)++++++def cmd_list(base, path):++ a = load(base)++ target = path.strip("/")++ d = next((x for x in a["dirs"] if x[0] == target), None)++ if not d:++ sys.exit(f"[RED] no such directory: {target or '/'}")++ _, first, count = d++ print(f"{target or '/'}: {count} entries")++ for k in a["kids"][first:first + count]:++ if k & CHILD_DIR:++ print(f" d {a['dirs'][k & ~CHILD_DIR][0].rpartition('/')[2]}/")++ else:++ name, shard, off, size = a["files"][k]++ print(f" f {name.rpartition('/')[2]:50} {size:12,} shard {shard:3} off {off:,}")++++++def cmd_verify(base, romfs):++ a = load(base)++ print(f"verify: {len(a['files']):,} files")++ bad = 0++ for n, (rel, shard, off, size) in enumerate(a["files"]):++ src = os.path.join(romfs, rel)++ try:++ with open(src, "rb") as f:++ want = f.read()++ except OSError as e:++ print(f"[RED] missing source {rel}: {e}")++ bad += 1++ continue++ if len(want) != size:++ print(f"[RED] size mismatch {rel}: source {len(want)} archive {size}")++ bad += 1++ continue++ with open(f"{base}.{shard:02d}", "rb") as f:++ f.seek(off)++ got = f.read(size)++ if got != want:++ print(f"[RED] content mismatch {rel}")++ bad += 1++ if (n + 1) % 20000 == 0:++ print(f" {n + 1:,}/{len(a['files']):,}", flush=True)++ print(f"verify: {'OK' if not bad else f'{bad} problems'}")++ return 1 if bad else 0++++++def main():++ ap = argparse.ArgumentParser(description="Pack a RomFS tree into a ROMFSARC archive")++ sub = ap.add_subparsers(dest="cmd", required=True)++ p = sub.add_parser("pack")++ p.add_argument("romfs")++ p.add_argument("base")++ p.add_argument("--shard-mib", type=int, default=200)++ l = sub.add_parser("list")++ l.add_argument("base")++ l.add_argument("path", nargs="?", default="")++ v = sub.add_parser("verify")++ v.add_argument("base")++ v.add_argument("romfs")++ a = ap.parse_args()++ if a.cmd == "pack":++ pack(a.romfs, a.base, a.shard_mib)++ elif a.cmd == "list":++ cmd_list(a.base, a.path)++ else:++ sys.exit(cmd_verify(a.base, a.romfs))++++++if __name__ == "__main__":++ main()+diff --git a/docs/ROMFS_ARCHIVE.md b/docs/ROMFS_ARCHIVE.md+new file mode 100644+index 00000000..44bc93f2+--- /dev/null++++ b/docs/ROMFS_ARCHIVE.md+@@ -0,0 +1,95 @@++# RomFS archive (ROMFSARC)++++A whole RomFS tree packed into one index file plus ~100 shard files, so a game whose RomFS is++hundreds of thousands of files can be copied to a phone as one folder instead of a directory tree.++++## Why++++Tears of the Kingdom's RomFS is 304,243 files / 15.9 GiB. Two problems follow:++++- **The IPA does not install.** A 16.6 GB IPA with 372,660 entries fails on iOS with++ `PackageExtractionFailed (Could not extract archive)`. The install daemon's extractor gives up:++ one directory holds 75,941 files and the ZIP64 central directory starts at 17.8 GB.++- **Copying the tree is slow.** The Files app and Finder both do one round trip per file; 304,243++ small files take hours and often break partway.++++Packing the tree into 127 files makes the copy one operation of ~16 GB and lets the IPA stay small.++++## Using it++++### 1. Pack the game files++++```bash++python3 dm/tools/romfs_arc.py pack <RomFS dir> <output base> --shard-mib 200++```++++`<RomFS dir>` is the directory `nx_extract` wrote (the one holding `Pack/`, `Banc/`, `Sound/`, …).++`<output base>` is a path prefix: the tool writes `<base>.idx` and `<base>.00`, `<base>.01`, ….++Files are grouped by top-level directory and cut so no shard passes `--shard-mib`, so one shard++holds one kind of content and no shard is unreasonably large.++++For TotK at 200 MiB per shard: 126 shards + 1 index = **127 files**.++++### 2. Copy it to the phone++++Put the whole set in the app's `Documents/romfs/`, keeping the base name:++++```++Documents/romfs/romfs.idx++Documents/romfs/romfs.00++...++Documents/romfs/romfs.125++```++++The app looks for `romfs.idx` first (`dm/ios/Sources/main.m`, `romfs_locate`); a plain directory++tree is still accepted when there is no index.++++### 3. Build the app without the RomFS++++```bash++DM_NO_ROMFS=1 GAME=<title id> W=... PATCHED=... ROMFS=... MSL_IOS=... \++ dm/ios/tools/build_ipa.sh out.ipa++```++++The package then holds only the app, the shader libraries and the tables (~750 MB for TotK), and++the game files come from `Documents/romfs/` at run time.++++## Checking an archive++++```bash++python3 dm/tools/romfs_arc.py list <base> [path] # list one directory++python3 dm/tools/romfs_arc.py verify <base> <RomFS> # compare every file's bytes with the source++```++++`verify` reads all 304,243 files of TotK's archive in about a minute and prints `verify: OK`.++++## Format++++See `dm/host/romfs_arc.h` for the byte layout. In short: a 64-byte header, a NUL-separated name++pool, a file table sorted by path (32 bytes each), a directory table (16 bytes each) and a child++list. Path lookup is a binary search; a directory listing walks one contiguous child range.++++The reader (`dm/host/romfs_arc.c`) maps the index with `mmap` and opens shards lazily, keeping up++to 256 descriptors. Reads go straight to `pread` on the shard, so the page cache still works.++++## How the fs layer uses it++++`hle_fs.c` keeps its normal path handling. When an archive is open, `host_path_ex` returns a++synthetic path (`@romfsarc:<guest path>`) for entries on the archive mount instead of a host file++path; `OpenFile`, `GetEntryType`, `OpenDirectory` and the directory calls recognise that prefix and++route to `romfs_arc.c`. File handles for archive entries are marked with bit 63 so they never++collide with real fds, and `ReadFile` clamps to the file size (a shard is a flat container, so a++read past the end would otherwise return the next file's bytes).++++The mount is recognised by its **directory**, not its name: titles differ (`rom` for most games,++`content` for Tears of the Kingdom).++++## Limitations++++- **Read-only.** Writes go to the save/temp mounts as before; the archive is never written.++- **Case-sensitive lookup.** The archive stores the names exactly as the source tree had them, so++ the case-insensitive alias machinery the host uses for APFS directories is bypassed.++- **Symlinks are followed at pack time.** No supported game's RomFS has any.++- **The index is held in memory.** 28 MB for TotK (17.9 MB of it names); the shards are not.++- **No dedup or compression.** Shards are the source bytes verbatim, so `verify` is a plain++ comparison and a repack is deterministic.diff --git a/patches/0003-ios-game-data-folder.patch b/patches/0003-ios-game-data-folder.patchnew file mode 100644index 00000000..6eccf8cd--- /dev/null+++ b/patches/0003-ios-game-data-folder.patch@@ -0,0 +1,535 @@+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001+From: v0lumehi <[email protected]>+Date: Wed, 28 Oct 2026 13:33:53 +0100+Subject: [PATCH] iOS: per-game data folders and a Files-app data pick++main.m locates the RomFS in the picked location, then Documents/games/<id>/, then the old Documents layout; saves and+temp follow it. Launcher.swift gets a Game data section; front_ios.m goes back to it when no data is found.++Upstream-Status: pending+Reason: Several games in one app, game data on an external drive: Documents/games/<id>/{romfs.img,romfs,msl,save,temp} and a Files-app pick of the data folder (needs the runtime profile). iOS twin of seedds/nxnative#460, which is Mac only+Issue: LNPANDY/NX2Apple#123+---+ dm/ios/Sources/DataBookmark.h | 32 +++++++++ dm/ios/Sources/DataBookmark.m | 79 +++++++++++++++++++ dm/ios/Sources/DmIOS-Bridging-Header.h | 3 ++ dm/ios/Sources/Launcher.swift | 88 +++++++++++++++++++++ dm/ios/Sources/front_ios.m | 13 ++-+ dm/ios/Sources/main.m | 108 ++++++++++++++++++++++---+ dm/ios/project.yml | 1 ++ dm/ios/tests/test_romfs_startup.py | 41 +++++++++-+ 8 files changed, 353 insertions(+), 12 deletions(-)+ create mode 100644 dm/ios/Sources/DataBookmark.h+ create mode 100644 dm/ios/Sources/DataBookmark.m+ create mode 100644 dm/ios/Sources/DmIOS-Bridging-Header.h++diff --git a/dm/ios/Sources/DataBookmark.h b/dm/ios/Sources/DataBookmark.h+new file mode 100644+index 00000000..3aef3338+--- /dev/null++++ b/dm/ios/Sources/DataBookmark.h+@@ -0,0 +1,32 @@++// The game data the player picked from the Files app, remembered across launches.++//++// Why this exists: until now the only way to get a game's RomFS onto an iPhone was to copy it into++// the app's Documents through the Files app — which the Files app can do, but only for a folder++// *inside* the app's own container. A player who keeps 16 GB of game data on an external drive or++// in iCloud Drive had to duplicate it into every game's container.++//++// iOS does not allow an app to remember a path outside its sandbox. It allows a *bookmark*: the++// system hands back a token when the player picks a file in the document picker, and the app can++// resolve that token later — even after a relaunch — and keep reading that file. The token is bound++// to the app's signing identity, so a re-signed build (a new sideload, a new team) gets a stale one;++// `stale` below is how that is reported, and the launcher asks the player to pick again rather than++// failing silently.++//++// This file only holds and resolves the bookmark. The picker UI and the call that stores a new one++// are in LauncherSettings.swift, which is where the rest of the player-facing settings live.++++#import <Foundation/Foundation.h>++++/// The bookmark the player stored, or nil when none was ever picked.++NSData *dm_picked_data_bookmark(void);++++/// Resolve the stored bookmark to a path, or nil when there is none or it no longer resolves.++/// `stale` (optional) is set when a bookmark exists but could not be used — the app is not signed++/// the way it was when the player picked, so the picker has to be shown again.++NSString *dm_picked_data_path(BOOL *stale);++++/// Store a bookmark for a URL the player just picked. Returns NO when the system refuses to make one.++BOOL dm_store_picked_data(NSURL *url);++++/// Forget it (a player who wants the app to go back to its Documents copy).++void dm_clear_picked_data(void);+diff --git a/dm/ios/Sources/DataBookmark.m b/dm/ios/Sources/DataBookmark.m+new file mode 100644+index 00000000..3dcc3834+--- /dev/null++++ b/dm/ios/Sources/DataBookmark.m+@@ -0,0 +1,79 @@++// See DataBookmark.h for why this exists.++++#import "DataBookmark.h"++++static NSString *const kPickedData = @"pickedDataBookmark";++++// The one security scope the game data lives under, held from the first resolve on: the host reads++// the image for the whole session, and a scope released after each read would break the game half++// way through. Never stopped on purpose — the process exits when the game does.++static NSURL *openedPick = nil;++++NSData *dm_picked_data_bookmark(void) {++ return [NSUserDefaults.standardUserDefaults dataForKey:kPickedData];++}++++static NSData *fresh_bookmark(NSURL *url) {++ // The picker grants a security scope that lasts while it is held: the bookmark is written with++ // the scope on. One written without it (or after the grant expired) reads back on this run and++ // resolves to nothing from the next launch on — every pick then looks "signed differently".++ BOOL scoped = [url startAccessingSecurityScopedResource];++ NSData *bookmark = [url bookmarkDataWithOptions:0 includingResourceValuesForKeys:nil relativeToURL:nil error:nil];++ if (scoped) [url stopAccessingSecurityScopedResource];++ return bookmark;++}++++NSString *dm_picked_data_path(BOOL *stale) {++ if (stale) *stale = NO;++ NSData *bookmark = dm_picked_data_bookmark();++ if (bookmark.length == 0) return nil;++ BOOL isStale = NO;++ NSError *error = nil;++ NSURL *url = [NSURL URLByResolvingBookmarkData:bookmark++ options:0++ relativeToURL:nil++ bookmarkDataIsStale:&isStale++ error:&error];++ if (!url) {++ // A re-signed build gets a bookmark the system will not resolve for it. Keep the data —++ // the player may install the same signature again — and let the caller ask for a new pick.++ fprintf(stderr, "boot: the picked game-data bookmark does not resolve (%s)\n",++ error.localizedDescription.UTF8String ?: "no reason given");++ if (stale) *stale = YES;++ return nil;++ }++ if (openedPick && ![openedPick.path isEqualToString:url.path]) openedPick = nil;++ if (!openedPick) [url startAccessingSecurityScopedResource]; // held for the session (see openedPick)++ openedPick = url;++ if (isStale) {++ // The system still resolves it but asks for a rewrite (its own wording: stale). Same++ // signature, so a fresh bookmark sticks: self-heal instead of making the player pick again.++ NSData *again = fresh_bookmark(url);++ if (again) [NSUserDefaults.standardUserDefaults setObject:again forKey:kPickedData];++ if (stale) *stale = YES;++ }++ // The picker can hand back a file that was moved or deleted since. The caller checks what it++ // needs (an image, a folder with the marker) and falls through if this path no longer holds it.++ return url.path;++}++++BOOL dm_store_picked_data(NSURL *url) {++ NSData *bookmark = fresh_bookmark(url);++ NSError *error = nil;++ NSURL *back = nil;++ if (bookmark) back = [NSURL URLByResolvingBookmarkData:bookmark options:0 relativeToURL:nil bookmarkDataIsStale:nil error:&error];++ if (!bookmark || !back) {++ // A bookmark that cannot come back must not be saved as if it were good: the launcher would++ // greet every start with "the location you picked before is no longer readable".++ fprintf(stderr, "[RED] could not bookmark %s: %s\n", url.path.UTF8String ?: "?",++ error.localizedDescription.UTF8String ?: (bookmark ? "the bookmark does not resolve again" : "no bookmark data"));++ return NO;++ }++ [NSUserDefaults.standardUserDefaults setObject:bookmark forKey:kPickedData];++ fprintf(stderr, "launcher: game data set to %s\n", url.path.UTF8String ?: "?");++ return YES;++}++++void dm_clear_picked_data(void) {++ [NSUserDefaults.standardUserDefaults removeObjectForKey:kPickedData];++}+diff --git a/dm/ios/Sources/DmIOS-Bridging-Header.h b/dm/ios/Sources/DmIOS-Bridging-Header.h+new file mode 100644+index 00000000..92a2b3a5+--- /dev/null++++ b/dm/ios/Sources/DmIOS-Bridging-Header.h+@@ -0,0 +1,3 @@++// What Swift sees of the app's Objective-C: the data bookmark the Files app hands out (see++// DataBookmark.h). project.yml points SWIFT_OBJC_BRIDGING_HEADER here.++#import "DataBookmark.h"+diff --git a/dm/ios/Sources/Launcher.swift b/dm/ios/Sources/Launcher.swift+index 3c72edea..1e21e9c9 100644+--- a/dm/ios/Sources/Launcher.swift++++ b/dm/ios/Sources/Launcher.swift+@@ -64,6 +64,93 @@ private struct SettingRow: View {+ }+ }+++/// Where this game's data comes from, and a picker to change it.++///++/// The app can only read files it owns unless the player hands it a location through the document++/// picker — so a game's RomFS kept on an external drive or in iCloud Drive could not be used at all++/// before this. Picking an image (romfs.img) or a folder stores a bookmark (DataBookmark.m), and++/// romfs_locate() prefers it from the next launch on.++private struct GameDataSection: View {++ @State private var picked: String = ""++ @State private var note: String = ""++ @State private var picking = false++++ var body: some View {++ Section {++ HStack {++ Text("Game data")++ Spacer()++ Text(picked.isEmpty ? "This app's folder" : (picked as NSString).lastPathComponent)++ .foregroundStyle(.secondary).lineLimit(1).truncationMode(.middle)++ }++ Button(picked.isEmpty ? "Choose game data…" : "Choose a different location…") { picking = true }++ if !picked.isEmpty {++ Button("Use the app's own data again", role: .destructive) {++ dm_clear_picked_data(); refresh(); note = ""++ }++ }++ } footer: {++ Text(note.isEmpty++ ? "Pick the game's romfs.img or its RomFS folder — an external drive or iCloud Drive works. The app remembers the choice; a re-signed build asks once more."++ : note)++ }++ .sheet(isPresented: $picking) {++ DocumentPicker { url in++ picking = false++ if dm_store_picked_data(url) {++ note = "Saved. The game uses this location when you press Play."++ refresh()++ } else {++ note = "That location could not be remembered — try a different one."++ }++ } onCancel: { picking = false }++ }++ .onAppear(perform: refresh)++ }++++ private func refresh() {++ // ObjC BOOL* is ObjCBool, not Bool: the bookmark header takes an indirect flag for++ // "the bookmark exists but does not resolve under this signature", which is the one++ // state worth telling the player about.++ var stale: ObjCBool = false++ picked = dm_picked_data_path(&stale) ?? ""++ if stale.boolValue && picked.isEmpty {++ note = "The location you picked before is no longer readable (the app was signed differently). Please choose it again."++ }++ }++}++++/// UIDocumentPickerViewController for files and folders, in the two callbacks a SwiftUI sheet wants.++private struct DocumentPicker: UIViewControllerRepresentable {++ let onPick: (URL) -> Void++ let onCancel: () -> Void++++ func makeUIViewController(context: Context) -> UIDocumentPickerViewController {++ // .open (not .import): the file stays where it is and the bookmark keeps pointing at it,++ // which is the whole point — an import would copy 16 GB into the app's container.++ let picker = UIDocumentPickerViewController(forOpeningContentTypes: [.item], asCopy: false)++ picker.allowsMultipleSelection = false++ picker.delegate = context.coordinator++ return picker++ }++++ func updateUIViewController(_ vc: UIDocumentPickerViewController, context: Context) {}++++ func makeCoordinator() -> Coordinator { Coordinator(onPick: onPick, onCancel: onCancel) }++++ final class Coordinator: NSObject, UIDocumentPickerDelegate {++ let onPick: (URL) -> Void++ let onCancel: () -> Void++ init(onPick: @escaping (URL) -> Void, onCancel: @escaping () -> Void) {++ self.onPick = onPick; self.onCancel = onCancel++ }++ func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {++ if let url = urls.first { onPick(url) } else { onCancel() }++ }++ func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) { onCancel() }++ }++}+++ private struct LauncherView: View {+ @ObservedObject var m: LauncherModel+ let play: () -> Void+@@ -98,6 +185,7 @@ private struct LauncherView: View {+ } footer: {+ Text("Brings back all settings this game was tested with.")+ }++ GameDataSection()+ Section {+ HStack {+ Text("Memory available")+diff --git a/dm/ios/Sources/front_ios.m b/dm/ios/Sources/front_ios.m+index 9cd03bad..fef3aa8a 100644+--- a/dm/ios/Sources/front_ios.m++++ b/dm/ios/Sources/front_ios.m+@@ -15,6 +15,7 @@+ void front_ios_boot(void);+ int front_ios_boot_ok(void);+ bool dm_show_launcher(void *view_controller, void (*done)(void)); // Launcher.swift: false = no launcher (no dm/launcher.json, or DM_LAUNCHER=0)++int dm_locate_game_data(void); // main.m: (re)decide where the game data is; NO when there still is none++ static CAMetalLayer *g_layer;+ static void front_ios_power_watch(void);+@@ -46,6 +47,7 @@ @interface DmRootVC : UIViewController+ @property (nonatomic, strong) UIView *pad;+ @property (nonatomic, strong) UILabel *fps;+ @property (nonatomic) BOOL launched;++@property (nonatomic) BOOL hasLauncher; // the app has a settings screen: a failed Play goes back to it (its Game data section is the way out)+ - (void)startGame;+ @end+ static DmRootVC *g_root;+@@ -67,6 +69,14 @@ - (void)viewDidLoad {+ // The game view, the pad and the frame-rate counter are made once the launcher has set the switches they read (DM_SHOW_FPS, DM_METAL_HUD); the host's loading began at app launch (main.m)+ - (void)startGame {+ if (self.game) return;++ if (!dm_locate_game_data()) { // no game data (nothing picked, nothing in Documents): the game cannot start++ if (self.hasLauncher) { dm_show_launcher((__bridge void *)self, launcher_done); return; } // back to the settings screen, whose Game data section picks a location++ UILabel *lb = [[UILabel alloc] initWithFrame:CGRectInset(self.view.bounds, 40, 40)];++ lb.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;++ lb.numberOfLines = 0; lb.textAlignment = NSTextAlignmentCenter; lb.textColor = UIColor.whiteColor;++ lb.text = @"Game files not found.\nPut the RomFS folder into this App's Documents as \"romfs\" (Files app), then restart.";++ [self.view addSubview:lb]; return;++ }+ front_hud_env(); // before the game view makes its device (an env file's DM_METAL_HUD sets it in main.m already)+ self.game = [[DmGameView alloc] initWithFrame:self.view.bounds];+ [self.view addSubview:self.game];+@@ -97,7 +107,8 @@ - (void)viewDidAppear:(BOOL)a {+ [super viewDidAppear:a];+ if (self.launched || !front_ios_boot_ok()) return;+ self.launched = YES; g_root = self;+- if (!dm_show_launcher((__bridge void *)self, launcher_done)) [self startGame]; // the settings screen first (Launcher.swift), when the app has one++ self.hasLauncher = dm_show_launcher((__bridge void *)self, launcher_done);++ if (!self.hasLauncher) [self startGame]; // the settings screen first (Launcher.swift), when the app has one+ }+ - (BOOL)prefersHomeIndicatorAutoHidden { return YES; }+ - (UIRectEdge)preferredScreenEdgesDeferringSystemGestures { return UIRectEdgeAll; } // Edge gestures need two swipes, to avoid accidental exits+diff --git a/dm/ios/Sources/main.m b/dm/ios/Sources/main.m+index eb0f56a3..b546e1bf 100644+--- a/dm/ios/Sources/main.m++++ b/dm/ios/Sources/main.m+@@ -6,9 +6,10 @@+ #include <stdio.h>+ #include <sys/stat.h>+ #include <unistd.h>+-#include "game_profile.h" // game profile constants (the RomFS marker path)++#include "hle_profile.h" // the runtime game profile (DM_PROFILE): the RomFS marker path comes from it+ #include "front.h"+ #include "romfs_image.h"++#include "DataBookmark.h"++ int dm_main(int argc, char **argv); // dm/host/main.c compiled in with -Dmain=dm_main+ UIViewController *front_ios_root(void);+@@ -25,9 +26,59 @@ static int romfs_image_complete(NSString *path) {+ }+ romfs_image_close(m); return 1;+ }++// A folder holds this game's files if it has a ROMFSARC index or the profile's marker path.++// Shared by romfs_locate and the per-game layout below, so both answer the same question.++static BOOL romfs_dir_ok(NSString *d) {++ NSFileManager *fm = NSFileManager.defaultManager;++ // A ROMFSARC archive: <dir>/romfs.idx next to romfs.NN shards. The host opens it when DM_ROMFS++ // points at the base; the marker check does not apply (there are no directories to walk).++ if ([fm fileExistsAtPath:[d stringByAppendingPathComponent:@"romfs.idx"]]) return YES;++ // A plain directory tree: only one containing the game profile's romfs_marker path counts++ // (Mario: System/Resource, the resource size table). Runtime profile: the marker is a profile++ // value now; the compiled macro is only what dm_profile() falls back to without DM_PROFILE.++ return [fm fileExistsAtPath:[d stringByAppendingPathComponent:@(dm_profile()->romfs_marker)]];++}++++// Where one game's data lives under the per-game layout: Documents/games/<title ID>/, holding++// romfs.img the whole RomFS as one image file (what scripts/push_romfs.sh sends), or++// romfs/ a ROMFSARC archive or a plain tree, for copies made before images++// msl/ this game's Metal shader libraries (optional; the app's own dm/ is used otherwise)++// save/ temp/ this game's saves and scratch space++// The layout exists so several games can share one installed app and so the game data can sit on++// an external drive the Files app exposes (a folder copied there keeps this shape).++static NSString *game_dir_for(const char *title_id) {++ NSString *doc = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];++ return [[doc stringByAppendingPathComponent:@"games"] stringByAppendingPathComponent:@(title_id)];++}+++ static NSString *romfs_locate(void) {+ NSFileManager *fm = NSFileManager.defaultManager;+ NSString *doc = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];++ // What the player picked in the Files app wins over everything: it is the one path they chose++ // on purpose, possibly on an external drive, and it costs nothing when they never picked one++ // (the bookmark is absent and this falls straight through). An image or a folder both work,++ // and a pick that no longer holds this game's data falls through rather than failing the boot.++ {++ BOOL stale = NO;++ NSString *picked = dm_picked_data_path(&stale);++ if (stale) fprintf(stderr, "boot: the picked game-data location needs to be chosen again (the app is signed differently now)\n");++ if (picked.length) {++ if (romfs_image_complete(picked)) { fprintf(stderr, "boot: game data from the picked image %s\n", picked.UTF8String); return picked; }++ NSString *pimg = [picked stringByAppendingPathComponent:@"romfs.img"];++ if (romfs_image_complete(pimg)) { fprintf(stderr, "boot: game data from the picked folder %s\n", pimg.UTF8String); return pimg; }++ if (romfs_dir_ok(picked)) { fprintf(stderr, "boot: game data from the picked folder %s\n", picked.UTF8String); return picked; }++ fprintf(stderr, "boot: the picked location %s holds no game data for this title; using the app's own\n", picked.UTF8String);++ }++ }++ // Per-game first: Documents/games/<id>/romfs.img (one file, what push_romfs.sh sends) or++ // Documents/games/<id>/romfs/ — the launcher-style layout, and what lets a user keep several++ // games' data side by side or on an external drive. The marker check inside romfs_dir_ok is++ // what keeps a stray folder from being taken for this game.++ NSString *gdir = game_dir_for(dm_profile()->id);++ NSString *gimg = [gdir stringByAppendingPathComponent:@"romfs.img"];++ if (romfs_image_complete(gimg)) return gimg;++ NSString *gfolder = [gdir stringByAppendingPathComponent:@"romfs"];++ if ([fm fileExistsAtPath:gfolder] && romfs_dir_ok(gfolder)) return gfolder;+ NSString *img = [doc stringByAppendingPathComponent:@"romfs.img"];+ if (romfs_image_complete(img)) {+ // A folder copy from before images is now dead weight of up to many GB (often cut off partway). Deleting its 300,000 files here took longer than iOS allows an app to start+@@ -43,13 +94,48 @@ static int romfs_image_complete(NSString *path) {+ }+ NSString *bundledImage = [NSBundle.mainBundle.resourcePath stringByAppendingPathComponent:@"romfs.img"];+ NSString *documentFolder = [doc stringByAppendingPathComponent:@"romfs"];+- if ([fm fileExistsAtPath:[documentFolder stringByAppendingPathComponent:@DM_GAME_ROMFS_MARKER]]) return documentFolder;++ if ([fm fileExistsAtPath:[documentFolder stringByAppendingPathComponent:@(dm_profile()->romfs_marker)]]) return documentFolder;+ if (romfs_image_complete(bundledImage)) return bundledImage;+ for (NSString *d in @[[doc stringByAppendingPathComponent:@"romfs"], [NSBundle.mainBundle.resourcePath stringByAppendingPathComponent:@"romfs"]])+- if ([fm fileExistsAtPath:[d stringByAppendingPathComponent:@DM_GAME_ROMFS_MARKER]]) return d; // only a directory containing the game profile's romfs_marker path counts (Mario: System/Resource, the resource size table)++ if (romfs_dir_ok(d)) return d;+ return nil;+ }+++// DM_ROMFS plus the save/temp folders that follow its location (the per-game layout only when the++// files came from Documents/games/<id>/). Returns NO when there is no game data yet — not fatal:++// the launcher comes up all the same and its Game data section is where a location gets picked++// (a transfer skipped on the Mac, or data on an external drive), and dm_locate_game_data() asks++// again when the player presses Play. `force` lets the Play-time re-location override what boot++// set: a location picked in the launcher this session must win, while an env file's DM_ROMFS /++// DM_SAVE / DM_TEMP (set before this runs, kept only when absent) keeps winning at boot.++static int set_data_env(NSString *romfs, BOOL force) {++ if (!romfs) return 0;++ NSFileManager *fm = NSFileManager.defaultManager;++ NSString *doc = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];++ fprintf(stderr, "boot: game files %s\n", romfs.fileSystemRepresentation);++ setenv("DM_ROMFS", romfs.fileSystemRepresentation, force);++ // Saves and scratch space: Documents/games/<id>/{save,temp} when the per-game layout is in use++ // (so two games in one app never share a save folder), else the old Documents/{save,temp}. An++ // env file still wins at boot — DM_SAVE/DM_TEMP set there are already in the environment and++ // setenv(..., 0) leaves them alone.++ NSString *gdir = game_dir_for(dm_profile()->id);++ // Tie the data folder to where the game files actually came from: if romfs_locate fell back to++ // Documents/romfs, the saves must stay beside it (a game folder without romfs is not in use).++ BOOL per_game = [romfs hasPrefix:gdir];++ NSString *save_dir = per_game ? [gdir stringByAppendingPathComponent:@"save"] : [doc stringByAppendingPathComponent:@"save"];++ NSString *temp_dir = per_game ? [gdir stringByAppendingPathComponent:@"temp"] : [doc stringByAppendingPathComponent:@"temp"];++ for (NSString *d in @[save_dir, temp_dir]) [fm createDirectoryAtPath:d withIntermediateDirectories:YES attributes:nil error:nil];++ setenv("DM_SAVE", save_dir.fileSystemRepresentation, force);++ setenv("DM_TEMP", temp_dir.fileSystemRepresentation, force);++ if (per_game) fprintf(stderr, "boot: per-game data folder %s\n", gdir.fileSystemRepresentation);++ return 1;++}++++// front_ios.m calls this from the launcher's Play: (re)decide where the game data is — a location++// picked in the launcher this session takes effect at once — and NO when there still is none, so++// the launcher comes back instead of the game failing inside the host.++int dm_locate_game_data(void) { return set_data_env(romfs_locate(), YES); }+++ // Boot prerequisites (done before UIApplicationMain): directories / environment variables / log -- the host's early load reads these+ static int boot_env(void) {+ NSFileManager *fm = NSFileManager.defaultManager;+@@ -83,15 +169,19 @@ static int boot_env(void) {+ NSString *lang = [NSBundle.mainBundle objectForInfoDictionaryKey:@"DMLanguage"];+ if (!getenv("DM_LANG") && [lang isKindOfClass:NSString.class] && lang.length) setenv("DM_LANG", lang.UTF8String, 0);+ fprintf(stderr, "boot: game language %s\n", getenv("DM_LANG") ?: "en-US");++ // No game data yet is not fatal: the launcher comes up all the same, and its Game data section++ // is where a location gets picked; dm_locate_game_data() looks again when Play is pressed.++ NSString *gdir = game_dir_for(dm_profile()->id);+ NSString *romfs = romfs_locate();+- if (!romfs) { fprintf(stderr, "boot: game files not found (Documents/romfs.img, Documents/romfs or <App>/romfs)\n"); return 0; }+- fprintf(stderr, "boot: game files %s\n", romfs.fileSystemRepresentation);+- setenv("DM_ROMFS", romfs.fileSystemRepresentation, 0);+- setenv("DM_SAVE", [doc stringByAppendingPathComponent:@"save"].fileSystemRepresentation, 0);+- setenv("DM_TEMP", [doc stringByAppendingPathComponent:@"temp"].fileSystemRepresentation, 0);++ BOOL per_game = [romfs hasPrefix:gdir]; // messaging nil is NO here: no data means the shared layout++ if (!set_data_env(romfs, NO)) fprintf(stderr, "boot: no game data yet (Documents/romfs.img, Documents/romfs or <App>/romfs); the launcher asks for it\n");+ NSString *dm = [res stringByAppendingPathComponent:@"dm"];+ setenv("DM_NVN_SHMAP", [dm stringByAppendingPathComponent:@"shader_map.tsv"].fileSystemRepresentation, 0);+- setenv("DM_MSL_DIR", [res stringByAppendingPathComponent:@"msl"].fileSystemRepresentation, 0);++ // Shader libraries: a game's own <gdir>/msl first (a per-game layout may carry its own), else++ // the app's shared <App>/msl.++ NSString *per_game_msl = [gdir stringByAppendingPathComponent:@"msl"];++ NSString *msl = (per_game && [fm fileExistsAtPath:per_game_msl]) ? per_game_msl : [res stringByAppendingPathComponent:@"msl"];++ setenv("DM_MSL_DIR", msl.fileSystemRepresentation, 0);+ setenv("DM_FONT_DIR", [dm stringByAppendingPathComponent:@"font"].fileSystemRepresentation, 0); // Shared-font stand-ins (standard.ttf / nintendo_ext.ttf): iOS lacks the macOS font path+ NSString *aoc = [res stringByAppendingPathComponent:@"aoc"]; // add-on content: build_ipa.sh puts the RomFS extracted from the player's DLC NSPs at <App>/aoc/<index>/+ if ([fm fileExistsAtPath:aoc]) setenv("DM_AOC_DIR", aoc.fileSystemRepresentation, 0);+diff --git a/dm/ios/project.yml b/dm/ios/project.yml+index 4a1e3b65..298b2eed 100644+--- a/dm/ios/project.yml++++ b/dm/ios/project.yml+@@ -76,6 +76,7 @@ targets:+ OTHER_CFLAGS: $(inherited) -mcpu=apple-a18 # The host assembly contains LSE atomic instructions, which the default baseline does not accept+ CLANG_ENABLE_OBJC_ARC: YES+ SWIFT_VERSION: "5.0" # Launcher.swift (SwiftUI)++ SWIFT_OBJC_BRIDGING_HEADER: Sources/DmIOS-Bridging-Header.h # DataBookmark (the Files app pick)+ DEBUG_INFORMATION_FORMAT: dwarf+ GCC_WARN_INHIBIT_ALL_WARNINGS: YES+ schemes:+diff --git a/dm/ios/tests/test_romfs_startup.py b/dm/ios/tests/test_romfs_startup.py+index 89e4f220..271744e3 100644+--- a/dm/ios/tests/test_romfs_startup.py++++ b/dm/ios/tests/test_romfs_startup.py+@@ -23,12 +23,19 @@ class Startup(unittest.TestCase):+ source = root / 'locator.m'+ source.write_text('#import <Foundation/Foundation.h>\n#include <stdio.h>\n#include "romfs_image.h"\n'+ 'static NSString *fixture_doc, *fixture_tmp, *fixture_bundle;\n#define DM_GAME_ROMFS_MARKER "marker"\n'++ 'typedef struct { const char *id, *romfs_marker; } fixture_profile; /* the fork reads both from the runtime profile */\nstatic const fixture_profile *dm_profile(void) { static const fixture_profile p = {"0100000000000000", "marker"}; return &p; }\n'+ '@interface FixtureBundle : NSObject\n+ (instancetype)mainBundle;\n- (NSString *)resourcePath;\n@end\n'+ '@implementation FixtureBundle\n+ (instancetype)mainBundle { return [self new]; }\n'+ '- (NSString *)resourcePath { return fixture_bundle; }\n@end\n#define NSBundle FixtureBundle\n'+- '#define NSSearchPathForDirectoriesInDomains(a,b,c) @[fixture_doc]\n#define NSTemporaryDirectory() fixture_tmp\n' + locator +++ '#define NSSearchPathForDirectoriesInDomains(a,b,c) @[fixture_doc]\n#define NSTemporaryDirectory() fixture_tmp\n'++ # The picked-location bookmark (DataBookmark.m): the fixture answers it from a++ # variable, so a test can put the player's choice anywhere on disk.++ 'static NSString *fixture_picked;\n'++ 'NSString *dm_picked_data_path(BOOL *stale) { if (stale) *stale = NO; return fixture_picked; }\n' + locator ++ '\nint main(int argc, char **argv) { @autoreleasepool { if (argc < 3) return 2;\n'+- 'fixture_doc = @(argv[1]); fixture_tmp = @(argv[2]); fixture_bundle = argc > 3 ? @(argv[3]) : @"/nonexistent-fixture"; NSString *p = romfs_locate();\n'++ 'fixture_doc = @(argv[1]); fixture_tmp = @(argv[2]); fixture_bundle = argc > 3 ? @(argv[3]) : @"/nonexistent-fixture";\n'++ 'if (argc > 4) fixture_picked = @(argv[4]); // the location the player picked, when a test sets one\n'++ 'NSString *p = romfs_locate();\n'+ 'if (!p) return 1; puts(p.fileSystemRepresentation); return 0; }}\n')+ cls.locator = root / 'locator'+ subprocess.run(['clang', '-fobjc-arc', '-Wall', '-Werror', '-I', str(REPO / 'dm/host'),+@@ -65,5 +72,35 @@ class Startup(unittest.TestCase):+ self.assertEqual(locate(), str(folder))+ image.pack(source, doc / 'romfs.img'); self.assertEqual(locate(), str(doc / 'romfs.img'))+++ def test_the_location_the_player_picked_wins_over_everything(self):++ """The Files-app pick (DataBookmark): an image, a folder holding one, or a plain tree."""++ with tempfile.TemporaryDirectory() as temporary:++ root = Path(temporary); doc = root / 'Documents'; doc.mkdir()++ tmp = root / 'temp'; tmp.mkdir(); bundle = root / 'App'; bundle.mkdir()++ source = root / 'source'; source.mkdir(); (source / 'marker').write_text('resource')++ image.pack(source, bundle / 'romfs.img')++ # something the app would otherwise use, so "wins" means something++ image.pack(source, doc / 'romfs.img')++ external = root / 'external'; external.mkdir()++++ def locate(picked=None):++ argv = [str(self.locator), str(doc), str(tmp), str(bundle)] + ([str(picked)] if picked else [])++ result = subprocess.run(argv, capture_output=True, text=True)++ self.assertEqual(result.returncode, 0, result.stderr)++ return result.stdout.strip()++++ # 1. the picked path IS the image++ image.pack(source, external / 'mine.img')++ self.assertEqual(locate(external / 'mine.img'), str(external / 'mine.img'))++ # 2. the picked path is a folder holding romfs.img++ image.pack(source, external / 'romfs.img')++ self.assertEqual(locate(external), str(external / 'romfs.img'))++ # 3. the picked path is a plain RomFS tree++ (external / 'romfs.img').unlink(); (external / 'marker').write_text('resource')++ self.assertEqual(locate(external), str(external))++ # 4. a picked path holding none of this game's data falls through to the app's own copy++ empty = root / 'empty'; empty.mkdir()++ self.assertEqual(locate(empty), str(doc / 'romfs.img'))++++ if __name__ == '__main__': unittest.main()diff --git a/patches/0004-ios-slim-ipa.patch b/patches/0004-ios-slim-ipa.patchnew file mode 100644index 00000000..c5ed97f8--- /dev/null+++ b/patches/0004-ios-slim-ipa.patch@@ -0,0 +1,76 @@+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001+From: v0lumehi <[email protected]>+Date: Wed, 28 Oct 2026 13:33:53 +0100+Subject: [PATCH] build_ipa.sh: slim package by default (DM_FULL_ROMFS=1 packs+ the game data)++Maps the RomFS and add-on content into the IPA only with DM_FULL_ROMFS; the app reads them from Documents/games/<id>/.++Upstream-Status: fork-only (declined seedds/nxnative#478)+Reason: Default slim IPA: the RomFS and aoc/ stay out unless DM_FULL_ROMFS=1 (a full package of a large game is many GB and iOS refuses it). Upstream took the opt-out DM_COPY_ROMFS=NO and kept the full package as its default+Issue: LNPANDY/NX2Apple#123+---+ dm/ios/tests/test_profile_pack.py | 3 ++-+ dm/ios/tools/build_ipa.sh | 20 +++++++++++++++++---+ docs/env_switches.tsv | 1 ++ 3 files changed, 20 insertions(+), 4 deletions(-)++diff --git a/dm/ios/tests/test_profile_pack.py b/dm/ios/tests/test_profile_pack.py+index 40db2b76..0407560d 100644+--- a/dm/ios/tests/test_profile_pack.py++++ b/dm/ios/tests/test_profile_pack.py+@@ -53,7 +53,8 @@ class ProfilePackTests(unittest.TestCase):+ self.assertEqual(prefix + 'fixture_bp.metallib' in names, included)+ for name in ('fixture_b.metallib', 'fixture_bv.metallib', 'fixture_b.json'):+ self.assertIn(prefix + name, names)+- self.assertEqual(archive.read('Payload/DmIOS.app/romfs/marker'), b'romfs')++ # the fork's slim package: the RomFS stays out of the IPA (DM_FULL_ROMFS=1 packs it)++ self.assertFalse(any(n.startswith('Payload/DmIOS.app/romfs') for n in names))+ self.assertEqual('Payload/DmIOS.app/pso/prebuilt.tsv' in names, with_pso)+++diff --git a/dm/ios/tools/build_ipa.sh b/dm/ios/tools/build_ipa.sh+index 3b4af1e7..25692fc8 100755+--- a/dm/ios/tools/build_ipa.sh++++ b/dm/ios/tools/build_ipa.sh+@@ -152,11 +152,25 @@ APP=$DD/Build/Products/Release-iphoneos/DmIOS.app+ rm -rf "$APP/msl" "$O/Payload" # Payload/: what the copy-and-zip packing left behind, as was out.ipa (and its index) unless it is the IPA packed here, which a repeat pack reuses+ [ "$O/out.ipa" -ef "$OUT_IPA" ] || rm -f "$O/out.ipa"; [ "$O/out.ipa.idx" -ef "$OUT_IPA.idx" ] || rm -f "$O/out.ipa.idx"+ P=Payload/DmIOS.app+-if [ -f "$ROMFS" ]; then MAPS=("$P/romfs.img=$ROMFS"); else MAPS=("$P/romfs=$ROMFS"); fi+-if [ -n "$AOC" ] && [ -d "$AOC" ]; then MAPS+=("$P/aoc=$AOC"); t "add-on content: $(ls "$AOC" | tr '\n' ' ')"; fi++MAPS=()++# DM_FULL_ROMFS=1 packs the game files into the package (upstream behaviour; only sensible for small++# games — a full package of a large game is many GB and iOS refuses to install it with++# PackageExtractionFailed). The default is the slim package: the app reads them from++# Documents/games/<id>/ (romfs.img and aoc/<index>.img), which the launcher copies in one go and++# which can also live on an external drive.++if [ -n "${DM_FULL_ROMFS:-}" ]; then if [ -f "$ROMFS" ]; then MAPS=("$P/romfs.img=$ROMFS"); else MAPS=("$P/romfs=$ROMFS"); fi; fi++if [ -n "${DM_FULL_ROMFS:-}" ] && [ -n "$AOC" ] && [ -d "$AOC" ]; then++ MAPS+=("$P/aoc=$AOC"); t "add-on content packed into the IPA: $(ls "$AOC" | tr '\n' ' ')"++elif [ -n "$AOC" ] && [ -d "$AOC" ]; then++ t "add-on content alongside the game data (DM_FULL_ROMFS=1 packs it): $(ls "$AOC" | tr '\n' ' ')"++fi+ if [ -n "${PSO:-}" ]; then MAPS+=("$P/pso=$PSO"); fi+ MAPS+=("$P/msl/$MSLDIR=$MSL_IOS/$MSLDIR" "$P=$APP")+-t "pack IPA (already-compressed game files stored, everything else deflated)"++if [ -n "${DM_FULL_ROMFS:-}" ]; then++ t "pack full IPA with RomFS (already-compressed game files stored, everything else deflated)"++else++ t "pack slim IPA without RomFS (game files come from Documents/romfs; DM_FULL_ROMFS=1 packs them)"++fi+ # The pulling vertex libraries (<key>_bp, dm/gfx/tools/dmsh_pull.py) serve the hybrid pipelines. Default to the same pso_mtl4 setting compiled by gen_build.py; IOS_PULL=0 / 1 overrides it.+ # The pipeline archive's bases are made of them, so an IPA with an archive (pso/) always carries them, whatever IOS_PULL says (an Xcode build copies them always).+ PULL=$(sed -n 's/^#define DM_GAME_PSO_MTL4 //p' "$DM/host/gen/$GAME/game_profile.h") || die "read game profile header"+diff --git a/docs/env_switches.tsv b/docs/env_switches.tsv+index 242056b6..34c7bf88 100644+--- a/docs/env_switches.tsv++++ b/docs/env_switches.tsv+@@ -33,6 +33,7 @@ DM_FS diagnostic When set, logs file opens, paths not found or not mounted, and+ DM_FSLOG diagnostic `=<file>` writes one TSV line per ReadFile: seconds since boot, guest path, offset, length and guest buffer address+ DM_FSLOG_HASH diagnostic With `DM_FSLOG`, adds a column with the FNV-1a 64 hash of the bytes read+ DM_FULLSCREEN switch When set, the Mac window starts in fullscreen++DM_FULL_ROMFS diagnostic `=1` in `build_ipa.sh` packs the game data into the IPA as it did before the slim package; the default leaves it in `Documents/games/<id>/` (`romfs.img`, `aoc/<index>.img`) and the DLC beside it. Only for small games — a full package of a large one is many GB and iOS refuses it (`PackageExtractionFailed`)+ DM_GAME switch Selects the game profile (a title ID under `dm/games` or `DM_GAMES_DIR`) for the Python tools and the rewriter; there is no default+ DM_GAMES_DIR path Profile folders outside the repository, separated by `:`, searched after `dm/games`; the NSP script points it at a provisional or derived profile+ DM_GAMES_FIRST switch `=1` searches `DM_GAMES_DIR` before `dm/games`, so a provisional or derived profile wins over the game's own (the NSP script's `--provisional`)diff --git a/patches/0005-ios-entitlements.patch b/patches/0005-ios-entitlements.patchnew file mode 100644index 00000000..5aa22313--- /dev/null+++ b/patches/0005-ios-entitlements.patch@@ -0,0 +1,149 @@+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001+From: v0lumehi <[email protected]>+Date: Wed, 28 Oct 2026 13:33:53 +0100+Subject: [PATCH] build_ipa.sh: increased-memory-limit entitlement in the+ unsigned IPA++Signs the app ad hoc with the entitlement before packing; xattr -cr first, then a check that the entitlement made it in.++Upstream-Status: backport 32ae3b11+Reason: Increased Memory Limit in an unsigned IPA: an ad-hoc signature carries the entitlement request, because AltStore reads entitlements from the signature it replaces. Upstream has its own version (32ae3b11)+Issue: LNPANDY/NX2Apple#123+---+ dm/ios/ENTITLEMENTS.md | 100 +++++++++++++++++++++++++++++++++++++++ dm/ios/tools/build_ipa.sh | 15 +++++++ 2 files changed, 115 insertions(+)+ create mode 100644 dm/ios/ENTITLEMENTS.md++diff --git a/dm/ios/ENTITLEMENTS.md b/dm/ios/ENTITLEMENTS.md+new file mode 100644+index 00000000..de284eb2+--- /dev/null++++ b/dm/ios/ENTITLEMENTS.md+@@ -0,0 +1,100 @@++# Increased Memory Limit++++The app asks for `com.apple.developer.kernel.increased-memory-limit`. `build_ipa.sh` writes the++entitlements file itself (`DM_ENTITLEMENTS=<plist>` gives another one, an empty value none): into the++unsigned IPA's placeholder signature (below), and for a prepared Xcode project as `Gen/DmIOS.entitlements`++through `CODE_SIGN_ENTITLEMENTS` in its `Gen/dm.xcconfig`.++++## Why it matters++++iOS gives an app a per-process physical-memory budget and kills it (jetsam, SIGKILL, no crash++report) when it goes over. On current iPhones that budget is about **3.3 GB** without the++entitlement and **6–8 GB** with it, depending on the device.++++Measured here, both on a 12 GB iPhone:++++| Game | Peak resident | Headroom | Result |++|---|---|---|---|++| Tears of the Kingdom | 3,342 MB | 33 MB | killed entering the world map |++| Hades II | — | — | asks for a 3.10 GB heap; at the budget limit |++++Lowering the render scale to 0.5 did not change the Tears of the Kingdom outcome, so the limit is++the guest heap rather than the GPU. The only way past it is a higher budget.++++## What the entitlement needs++++Two conditions, both required:++++1. **The signature carries it.** `build_ipa.sh` builds unsigned (the sideloader re-signs), so what++ matters is whether the sideloader copies unknown entitlements from the IPA into its own signature++ instead of dropping them.++2. **The App ID has it enabled.** The provisioning profile a sideloader generates only includes++ entitlements the App ID is registered for. The sideloader has to ask Apple for it.++++## Which sideloaders keep it++++Reported by [playport.dev](https://playport.dev/) (a different project with the same requirement):++++| Sideloader | Keeps the entitlement |++|---|---|++| AltStore Classic 2.2 or later | Yes |++| Impactor (from a computer) | Yes |++| Xcode with a Personal Team | Yes |++| SideStore 0.7.0, free Apple ID | Not by default — see below |++| Sideloadly and others | Check the tool; Sideloadly does not enable it |++++## SideStore with a free Apple ID++++The entitlement attaches to the App ID, so it survives the weekly refresh once set. One-time fix:++++1. Install this app through SideStore, so its App ID has been created with Apple.++2. Sideload **GetMoreRam** and sign in with the same Apple ID SideStore uses.++3. In GetMoreRam open **App IDs**, tap **Refresh**, select this app's App ID, then++ **Add Increased Memory Limit**.++4. Reinstall the app from SideStore (it upgrades in place; `Documents/` — the RomFS archive and the++ saves — is preserved).++5. Confirm: `Documents/log.txt` should now show a much larger `headroom to the system memory limit`++ in the `memory up to frame N` lines. GetMoreRam uses one of a free Apple ID's three app slots, so++ delete it afterwards if you need the slot back.++++## Checking whether it took effect++++Launch the game, let it run a few hundred frames, then read the memory line in `Documents/log.txt`:++++```++memory up to frame 600: resident 3342 MB, ... headroom to the system memory limit 33 MB++```++++`resident + headroom` is the budget the kernel enforces:++++- ≈ 3,375 MB → the entitlement is not in effect.++- ≈ 6,000–8,000 MB → it is.++++`os_proc_available_memory()` is what produces that number (`dm/gfx/nvn/nvn_mtl.m`), and it reports++the distance to the budget the kernel enforces.++++## Why the placeholder signature matters++++`build_ipa.sh` builds unsigned. A sideloader decides which entitlements to carry by reading them++from the signature it is replacing — an unsigned binary has none, so the request would be lost no++matter what sits in the bundle. The script therefore embeds the entitlement with an++ad-hoc signature (`codesign --force --sign - --entitlements …`, no certificate needed): the++sideloader strips that signature and swaps in the user's own, but it now sees the entitlement and++carries it over. Check any built IPA with:++++```bash++codesign -d --entitlements :- Payload/DmIOS.app/DmIOS | grep increased-memory-limit++```++++Measured here (12 GB iPhone, AltStore Classic 2.3): before the placeholder signature the budget was++3,375 MB and Hades II died entering a larger scene; after it the game runs. If the budget stays at++3,375 MB with a signed IPA, the remaining step is on the App ID — enable the capability with a tool++like GetMoreRam (same Apple ID as the sideloader, App IDs → Refresh → select the app → Add++Increased Memory Limit), then reinstall so the profile picks it up.++++## Xcode route++++A project prepared with `--prepare-xcode` already carries the entitlement (`Gen/DmIOS.entitlements`);++with a Personal Team and a real device, build from there. That is the one route where the app is++signed at build time, so no re-signing step can drop the entitlement. The Mac launcher's++**Install on** uses this route.+diff --git a/dm/ios/tools/build_ipa.sh b/dm/ios/tools/build_ipa.sh+index 25692fc8..a9a76b21 100755+--- a/dm/ios/tools/build_ipa.sh++++ b/dm/ios/tools/build_ipa.sh+@@ -145,6 +145,21 @@ xcodebuild -project DmIOS.xcodeproj -scheme DmIOS -configuration Release -destin+ # SYMROOT and OBJROOT above keep the unsigned build separate from the interactive Xcode app.+ APP=$DD/Build/Products/Release-iphoneos/DmIOS.app+ [ -n "$APP" ] && [ -d "$APP" ] || die "no built app"; t "app: $APP"++# The unsigned IPA: an unsigned binary has no signature for a sideloader to read entitlements from,++# so the request would be lost (AltStore reads the signature it replaces). Sign ad-hoc with the++# entitlement first; the sideloader strips this signature and carries the entitlement over.++if [ "$PREPARE_XCODE" != YES ] && [ -n "${DM_ENTITLEMENTS-default}" ]; then++ if [ -n "${DM_ENTITLEMENTS:-}" ]; then cp "$DM_ENTITLEMENTS" "$APP/DmIOS.entitlements" || die "copy DM_ENTITLEMENTS"++ else printf '%s\n' '<?xml version="1.0" encoding="UTF-8"?>' '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">' \++ '<plist version="1.0"><dict><key>com.apple.developer.kernel.increased-memory-limit</key><true/></dict></plist>' > "$APP/DmIOS.entitlements" || die "entitlements"; fi++ # codesign refuses a bundle whose files carry resource forks, Finder information, quarantine or++ # provenance attributes ("resource fork, Finder information, or similar detritus not allowed");++ # files copied into the bundle (the icon, resources staged from a Downloads folder) can bring them++ xattr -cr "$APP" 2>/dev/null++ codesign --force --sign - --entitlements "$APP/DmIOS.entitlements" "$APP" || die "ad-hoc sign with entitlements (the sideloader re-signs; this only carries the request)"++ codesign -d --entitlements :- "$APP" 2>/dev/null | grep -q increased-memory-limit || die "entitlements did not make it into the placeholder signature"++ t "entitlements: increased-memory-limit embedded in the placeholder signature"++fi++ # Straight from the sources: the app without its signature, and without the folders an app built before pack_ipa.py still has (DerivedData keeps resources that left the project;+ # msl/ is also deleted there, it took 1.5 GB of the home disk), then the shader libraries, the add-on content (the RomFS extracted from the player's DLC NSPs, one folder per index:diff --git a/patches/0006-nsp-dotnet-home.patch b/patches/0006-nsp-dotnet-home.patchnew file mode 100644index 00000000..a815fff3--- /dev/null+++ b/patches/0006-nsp-dotnet-home.patch@@ -0,0 +1,53 @@+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001+From: v0lumehi <[email protected]>+Date: Wed, 28 Oct 2026 13:33:53 +0100+Subject: [PATCH] NSP script: HOME from the password database, DOTNET_CLI_HOME,+ no .NET telemetry++Every child of the build gets a usable HOME and DOTNET_CLI_HOME; DOTNET_CLI_TELEMETRY_OPTOUT and DOTNET_NOLOGO default on.++Upstream-Status: pending+Reason: A GUI launch can hand the build an empty HOME, and .NET first-run configure dies on it; telemetry and the banner are off for the build+Issue: LNPANDY/NX2Apple#10+---+ scripts/build_ipa_from_nsp.py | 20 +++++++++++++++++++-+ 1 file changed, 19 insertions(+), 1 deletion(-)++diff --git a/scripts/build_ipa_from_nsp.py b/scripts/build_ipa_from_nsp.py+index 2a4648da..7e75dde8 100755+--- a/scripts/build_ipa_from_nsp.py++++ b/scripts/build_ipa_from_nsp.py+@@ -29,7 +29,7 @@+ # unless ALLOW_OTHER_METAL / --allow-other-metal. Issue #242 reported corruption with another compiler; the cause is still unconfirmed.+ # Python 3.12+ is required for bounded archive mappings inside images. The Python running this file needs lz4, capstone and fonttools (and backports.zstd before Python 3.14); also needed: Xcode, xcodegen, .NET SDK 10, zstd. SPIRV-Cross is the in-repo build. A first run takes 2 (Metroid Dread) to 10 minutes (Breath of the Wild: 5 of them the shader split), longer when shader libraries must be compiled; a repeat run with unchanged inputs takes about 20 s (Metroid Dread), mostly packing the IPA. Key values are never printed.+ # The console shows one line per stage ([k/n] stage, with a bar, done/total, percent, elapsed time and ETA where the work can be counted); the tools' own output goes only to logs/ (PROGRESS / --progress). --progress json writes newline-delimited JSON events to stdout.+-import ast, collections, ctypes, getpass, hashlib, importlib.util, json, os, re, shlex, shutil, struct, subprocess, sys, tempfile, threading, time, types++import ast, collections, ctypes, getpass, pwd, hashlib, importlib.util, json, os, re, shlex, shutil, struct, subprocess, sys, tempfile, threading, time, types+ from pathlib import Path+ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "dm/tools"))+ import romfs as rfs+@@ -1915,6 +1915,24 @@ def main(args=None):+ if not want_lang: raise BuildError(f'unknown game language {lang_in!r}; give one of {language_list([c for c, _ in nacp.LANGUAGES])}, by code or by name')+ env = dict(os.environ, PATH=os.pathsep.join(TOOL_PATHS + [os.environ.get('PATH', '/usr/bin:/bin:/usr/sbin:/sbin')]))+ env.setdefault('USER', getpass.getuser()) # xcodegen fails without USER (Couldn't find current username)++ # HOME and DOTNET_CLI_HOME for every child: a GUI launch (LaunchServices) can hand the app a++ # process environment with HOME missing or empty, and .NET's first-run configure then builds a++ # mutex path from "" and dies with 'NuGet-Migrations' + lstat("") == ENOENT — before any project++ # is read (issue #10, where the app's own DOTNET_ROOT workaround did not help because the empty++ # HOME came from the launch, not from the app). Derive it from the password database when the++ # environment has nothing usable, so the pipeline is correct however it was started.++ if not env.get('HOME') or not os.path.isdir(env['HOME']):++ try: home = Path(pwd.getpwuid(os.getuid()).pw_dir)++ except Exception: home = Path.home()++ if home.is_dir():++ env['HOME'] = os.environ['HOME'] = str(home)++ say(f'HOME: {home} (taken from the password database; the environment had none)')++ env.setdefault('DOTNET_CLI_HOME', env['HOME']) # .NET writes its first-run state here++ # No first-run banner, no telemetry: a build neither wants nor reads either, and the telemetry++ # call can hang the first run on a network that cannot reach Microsoft. setdefault, so a user++ # who wants telemetry on keeps it.++ env.setdefault('DOTNET_CLI_TELEMETRY_OPTOUT', '1')++ env.setdefault('DOTNET_NOLOGO', '1')+ configure_dotnet(env)+ env.setdefault('J', str(os.cpu_count() or 8)) # shader_split.py's and dmsh_build.py's workers (their default is 8)+ py = sys.executablediff --git a/patches/0007-nsp-exfat-appledouble.patch b/patches/0007-nsp-exfat-appledouble.patchnew file mode 100644index 00000000..6be42d5a--- /dev/null+++ b/patches/0007-nsp-exfat-appledouble.patch@@ -0,0 +1,44 @@+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001+From: v0lumehi <[email protected]>+Date: Wed, 28 Oct 2026 13:33:53 +0100+Subject: [PATCH] NSP script: a game folder on an exFAT drive++scan_nsps skips ._ files; rmtree tolerates files that are already gone and retries once.++Upstream-Status: backport a0b8bdb3+Reason: A game folder on an exFAT drive: AppleDouble ._ files are skipped by scan_nsps and rmtree retries the exFAT directory-cache races (merged upstream as a0b8bdb3, seedds/nxnative#476)+Issue: LNPANDY/NX2Apple#123+---+ scripts/build_ipa_from_nsp.py | 10 +++++++++-+ 1 file changed, 9 insertions(+), 1 deletion(-)++diff --git a/scripts/build_ipa_from_nsp.py b/scripts/build_ipa_from_nsp.py+index 7e75dde8..a89bc92b 100755+--- a/scripts/build_ipa_from_nsp.py++++ b/scripts/build_ipa_from_nsp.py+@@ -358,9 +358,15 @@ def build_id(nso):+ f.seek(0x40); return f.read(16).hex()++++def _rmtree_enoent(func, p, exc):++ if isinstance(exc[1], FileNotFoundError): return # already gone: the goal is achieved++ time.sleep(0.2); func(p) # one retry: exFAT directory-cache races clear+++++ def rmtree(p):+ if p.is_symlink() or p.is_file(): p.unlink()+- elif p.exists(): shutil.rmtree(p)++ elif p.exists(): shutil.rmtree(p, onerror=_rmtree_enoent)++ if p.exists(): shutil.rmtree(p, onerror=_rmtree_enoent) # the caller needs it gone (copytree follows)+++ def build_nx_extract(repo, work, logs, env):+@@ -430,6 +436,8 @@ def scan_nsps(nsp_dir):+ the title as an NSP's does) and converted afterwards (decompress_nsz)"""+ fams, unknown = {}, []+ for p in sorted([*nsp_dir.glob('*.nsp'), *nsp_dir.glob('*.xci'), *nsp_dir.glob('*.nsz'), *nsp_dir.glob('*.xcz')]): # a base game may be a cartridge dump (.xci: Monster Hunter Rise); nx_extract reads its secure partition++ if p.name.startswith('._'):++ continue # an AppleDouble file: macOS writes one beside every real file on exFAT/FAT drives, and its name carries the same [title ID] — counting it made the one real update NSP read as two, and both were then left out (the report's Hades II build)+ if p.stat().st_size == 0: # an empty file left by an incomplete download (the Zelda BotW folder holds a 0-byte DLC NSP next to the complete (1).nsp)+ say(f'skipping an empty file: {p.name}'); continue+ if p.suffix in COMPRESSED and p.with_suffix(COMPRESSED[p.suffix]).exists():diff --git a/patches/0008-nsp-early-checks.patch b/patches/0008-nsp-early-checks.patchnew file mode 100644index 00000000..be2fbe2b--- /dev/null+++ b/patches/0008-nsp-early-checks.patch@@ -0,0 +1,84 @@+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001+From: v0lumehi <[email protected]>+Date: Wed, 28 Oct 2026 13:33:53 +0100+Subject: [PATCH] NSP script: iOS SDK, Rosetta and glslang checks before the+ long steps++check_prereqs checks xcrun --sdk iphoneos; main() stops under Rosetta; check_glslang runs before extraction for OpenGL games.++Upstream-Status: backport c464cb24+Reason: Environment errors surfaced early: iOS SDK, Rosetta Python, glslangValidator before the long steps (Rosetta and glslang merged upstream as c464cb24, seedds/nxnative#477, #487; check whether the iOS SDK check is still ours after a bump)+Issue: LNPANDY/NX2Apple#71+---+ dm/ios/tests/test_xcode_workflow.py | 2 +-+ scripts/build_ipa_from_nsp.py | 23 ++++++++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-)++diff --git a/dm/ios/tests/test_xcode_workflow.py b/dm/ios/tests/test_xcode_workflow.py+index 83a9790d..d185224b 100644+--- a/dm/ios/tests/test_xcode_workflow.py++++ b/dm/ios/tests/test_xcode_workflow.py+@@ -50,7 +50,7 @@ class XcodePipelineTests(unittest.TestCase):+ (extraction / 'ExeFS').mkdir()+ mocks = {}+ for name, value in {+- 'scan_nsps': (int(registered.id, 16), fam), 'check_prereqs': None, 'check_metal': None,++ 'scan_nsps': (int(registered.id, 16), fam), 'check_prereqs': None, 'check_metal': None, 'check_glslang': None,+ 'free_gb': 10000, 'build_nx_extract': root / 'nx_extract',+ 'extract': extraction, 'can_clone': False, 'build_mismatch': [],+ 'extract_aoc': None, 'rewrite': profile, 'split_shaders': 'fixture-key',+diff --git a/scripts/build_ipa_from_nsp.py b/scripts/build_ipa_from_nsp.py+index a89bc92b..a632870a 100755+--- a/scripts/build_ipa_from_nsp.py++++ b/scripts/build_ipa_from_nsp.py+@@ -848,6 +848,13 @@ def check_prereqs(env, xlate, mac=False): # mac: a Mac-only build (PLATFORM 'm+ if mac: del tools['xcodegen']+ gone = [f'{t} ({how})' for t, how in tools.items() if not shutil.which(t, path=env['PATH'])]+ if gone: raise BuildError('tools not found: ' + ', '.join(gone))++ if not mac:++ # Xcode 15 and later ship the iOS platform as a separate download: xcodebuild and the Metal++ # compiler can both be there while the iOS SDK is not, and the failure then surfaces deep in++ # xcodebuild. Check the SDK itself so the message names the right command.++ sdk = subprocess.run(['xcrun', '--sdk', 'iphoneos', '--show-sdk-version'], capture_output=True, text=True, env=env)++ if sdk.returncode:++ raise BuildError('the iOS SDK is not installed (Xcode 15 and later download the platform separately): run xcodebuild -downloadPlatform iOS, or pick it in Xcode → Settings → Components')+ mtl = subprocess.run(['xcrun', '-sdk', 'macosx' if mac else 'iphoneos', 'metal', '--version'], capture_output=True, text=True, env=env) # Xcode 26 and later install the Metal toolchain separately+ if mtl.returncode: raise BuildError(f'the Metal compiler does not run ({(mtl.stderr.strip().splitlines() or ["no output"])[-1]}): install it with xcodebuild -downloadComponent MetalToolchain')+ if not xlate.exists(): raise BuildError(f'the shader translator is missing from the repository: {xlate}')+@@ -1587,6 +1594,15 @@ def check_metal(py, repo, env):+ raise BuildError(msg.replace('set DM_ALLOW_OTHER_METAL=1 (the NSP script\'s --allow-other-metal)', 'ALLOW_OTHER_METAL = True (--allow-other-metal)'))++++def check_glslang(env):++ """An OpenGL game's GLSL goes through glslangValidator; build_gl_shaders checks for it, but only++ after the extraction and the runtime capture have run for minutes, and it raises before++ layer_shaders creates gl_shaders.log — so the GUI showed a failure with no log to read (issue++ #71). Checked before those steps, as check_metal is and for the same reason."""++ if not shutil.which('glslangValidator', path=env['PATH']):++ raise BuildError("glslangValidator is not installed: an OpenGL game's GLSL shaders need it to compile to SPIR-V (brew install glslang)")+++++ def shader_regressions(py, repo, lib_dir, chain, logs):+ """dm/gfx/tools/shader_regressions.py on the Mac libraries (dmsh_build.py writes its build report there in an iOS build too): shaders that translated in this game's previous build+ and fail with this chain stop the build, unless ALLOW_SHADER_REGRESSIONS. The chain is one for every game, so a change can break a game its author never ran (GitHub issue #272)"""+@@ -1915,6 +1931,12 @@ def main(args=None):+ keys = Path(os.path.expanduser(args.keys or PROD_KEYS or ask('path of prod.keys: ', 'prod.keys (-k)'))).resolve()+ if not nsp_dir.is_dir(): raise BuildError(f'not a folder: {nsp_dir}')+ if not keys.is_file(): raise BuildError(f'no such file: {keys}')++ # An Intel Python (an Intel Homebrew under /usr/local) runs under Rosetta on an Apple silicon Mac, and its children prefer the++ # x86_64 slice: the shader translator's universal apphost then wants an x86_64 .NET, finds the arm64 one, prints nothing, and++ # the build stops at the iOS shader step with "xlate_source: lock … / actual" (empty), which reads like a stale translator.++ # Say so here instead (ufooer's PR #31, item 3).++ if sys.platform == 'darwin' and subprocess.run(['sysctl', '-n', 'sysctl.proc_translated'], capture_output=True, text=True).stdout.strip() == '1':++ raise BuildError(f'{sys.executable} is an Intel Python running under Rosetta; run the build with a native arm64 Python (e.g. /usr/bin/python3 or Homebrew in /opt/homebrew)')+ sys.path.insert(0, str(repo / 'dm/games')); import game as gamemod # game profiles+ global pg; import profile_guess as pg # dm/games: a provisional profile's keys from the game files and from the heap check+ sys.path.insert(0, str(repo / 'dm/tools')); global nacp; import nacp # the game name in the NSP's control data+@@ -2051,6 +2073,7 @@ def main(args=None):+ if gfx == 'vulkan': say(f'Vulkan game ({src["graphics"][1]}): vk_shaders.py translates the shaders instead of the NVN shader chain')+ if gfx == 'gl': say(f'OpenGL game ({src["graphics"][1]}): gl_shaders.py translates the shaders instead of the NVN shader chain')+ if gfx == 'nvn': check_metal(py, repo, env) # before the captures and the shader split, which take minutes++ if gfx == 'gl': check_glslang(env)+ for on, k in ((glslc, 'glslc_capture'), (vkcap, 'vk_capture'), (glcap, 'gl_capture'), (uedec, 'ue_decode'), (gfx == 'nvn' and src['oodle_packs'][0], 'oodle_packs'), (gfx == 'nvn' and src['ue_legacy'][0], 'ue_legacy')):+ if on: say(src[k][1])+ PROG.add(glslc + vkcap + glcap + uedec + (gfx == 'nvn'))diff --git a/patches/0009-nsp-chain-changed-note.patch b/patches/0009-nsp-chain-changed-note.patchnew file mode 100644index 00000000..7eb0d37a--- /dev/null+++ b/patches/0009-nsp-chain-changed-note.patch@@ -0,0 +1,31 @@+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001+From: v0lumehi <[email protected]>+Date: Wed, 28 Oct 2026 13:33:54 +0100+Subject: [PATCH] NSP script: a [NOTE] chain-changed line when cached libraries+ are stale++Printed before the shader step when b-<chain> differs from the cached libraries.++Upstream-Status: fork-only (seedds/nxnative#490 is the event form, not this text note)+Reason: The front ends turn the [NOTE] chain-changed marker into a notice when cached shader libraries are from an older chain; upstream will have a shaders_stale event (seedds/nxnative#490) instead+Issue: LNPANDY/NX2Apple#123+---+ scripts/build_ipa_from_nsp.py | 5 ++++++ 1 file changed, 5 insertions(+)++diff --git a/scripts/build_ipa_from_nsp.py b/scripts/build_ipa_from_nsp.py+index a632870a..571f2c76 100755+--- a/scripts/build_ipa_from_nsp.py++++ b/scripts/build_ipa_from_nsp.py+@@ -1541,6 +1541,11 @@ def build_shaders(py, repo, sh, xlate, env, logs, g, pkg_key=None, mac=False):+ ios, log = sh / 'ios', logs / 'dmsh_build.log'+ PROG.stage('Mac shaders' if mac else 'iOS shaders')+ chain = chain_of(repo)++ stale = sorted(d.name for d in (sh / 'cache').glob('b-*') if d.name != f'b-{chain}' and any(d.glob('*_b.metallib'))++ ) + sorted(d.name for d in ios.glob('b-*') if d.name != f'b-{chain}' and any(d.glob('*_b.metallib')))++ if stale: say(f'[NOTE] chain-changed: {", ".join(stale)} -> b-{chain}: the upstream update changed the shader '++ 'translator, so the cached libraries cannot be reused and this build rebuilds them with it '++ '(once per update; later builds reuse as before)')+ out = sh / 'cache' if mac else ios+ libs, kf, kmac = out / f'b-{chain}', ios / f'b-{chain}.key', sh / f'mac-b-{chain}.key'+ pso_pairs = g.table('pso_pairs.tsv')diff --git a/patches/0010-nsp-work-dir.patch b/patches/0010-nsp-work-dir.patchnew file mode 100644index 00000000..97249db1--- /dev/null+++ b/patches/0010-nsp-work-dir.patch@@ -0,0 +1,42 @@+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001+From: v0lumehi <[email protected]>+Date: Wed, 28 Oct 2026 13:33:54 +0100+Subject: [PATCH] NSP script: --work-dir sets the build folder and the default+ IPA location++work is assigned before out_ipa, which defaults next to it.++Upstream-Status: forwarded seedds/nxnative#475+Reason: The front end keeps each game build in its own folder: --work-dir sets the build folder and the default IPA location+Issue: LNPANDY/NX2Apple#123+---+ scripts/build_ipa_from_nsp.py | 7 +++++--+ 1 file changed, 5 insertions(+), 2 deletions(-)++diff --git a/scripts/build_ipa_from_nsp.py b/scripts/build_ipa_from_nsp.py+index 571f2c76..89ff8595 100755+--- a/scripts/build_ipa_from_nsp.py++++ b/scripts/build_ipa_from_nsp.py+@@ -1873,6 +1873,7 @@ def parse_args(argv):+ ap.add_argument('-l', '--language', help='game language, a code or a name: ja, fr, de, es, it, nl, pt, ru, ko, zh-Hans, zh-Hant, en-GB, fr-CA, es-419, pt-BR, Japanese, ... (default: the LANGUAGE setting, else English); '+ 'it must be one the game supports, which the console lists')+ ap.add_argument('--keep-extracted', action=argparse.BooleanOptionalAction, help='keep the extracted game files after the IPA is built, for the next build (default: the KEEP_EXTRACTED setting, on)')++ ap.add_argument('--work-dir', help='where the build folder goes (default: <NSP folder>/<title ID>_build); the extracted files, shader cache and temporary files all live there')+ ap.add_argument('--env-file', help='environment switches for a diagnostic build (one KEY=VALUE per line)')+ ap.add_argument('--gpu', help='NVN games: GPU architectures the app gets its pipeline archive for, made on this Mac with metal-tt, comma-separated: g18p (A19 / A19 Pro), or the name a device\'s log gives when the app has no archive for its GPU; '+ 'none = no archive, the device builds the bases on its first start (default: the PSO_GPUS setting; when that is empty, g18p for a game whose profile sets pso_mtl4 on, else none). '+@@ -2014,10 +2015,12 @@ def main(args=None):+ if alias and not derived: derived = f'title {app:016X} is not game profile {g.id}\'s title {g.title_id:016X}'+ if derived: say(f'{derived}: packing {pkg_ver} from a profile derived from it')+ versions = [pkg_ver] if derived else need + ([pkg_ver] if pkg_ver not in need else [])+- out_ipa = Path(os.path.expanduser(args.out or OUT_IPA)).resolve() if (args.out or OUT_IPA) else nsp_dir / g.get('ipa') # by default in the NSP folder, next to the NSPs and <id>_build/++ work = Path(os.path.expanduser(args.work_dir)).resolve() if args.work_dir else nsp_dir / f'{g.id}_build' # the folder holding the NSPs by default; --work-dir puts the build elsewhere++ # out_ipa reads `work`, so `work` must be assigned first (upstream's order had them the other++ # way round; the --work-dir patch moved `work` up here and this line had to follow it).++ out_ipa = Path(os.path.expanduser(args.out or OUT_IPA)).resolve() if (args.out or OUT_IPA) else work.parent / g.get('ipa') # by default next to the NSPs and <id>_build/+ if shadowed and not (args.out or OUT_IPA): out_ipa = out_ipa.with_name(out_ipa.stem + '-provisional.ipa') # never over the IPA of the game's real profile+ if mac_pack and (args.out or OUT_IPA) and out_ipa.suffix != '.app': raise BuildError(f'the Mac app (-o / OUT_IPA) must end in .app: {out_ipa}')+- work = nsp_dir / f'{g.id}_build'+ project = work / 'xcode/DmIOS.xcodeproj'+ workspace = Path(os.path.expanduser(args.xcode_workspace or XCODE_WORKSPACE)).resolve() if (args.xcode_workspace or XCODE_WORKSPACE) else nsp_dir.parent / 'NxNative.xcworkspace'+ if prepare_xcode and workspace.suffix != '.xcworkspace': raise BuildError('--xcode-workspace must end in .xcworkspace')diff --git a/patches/0011-bc-cpu-decode.patch b/patches/0011-bc-cpu-decode.patchnew file mode 100644index 00000000..ac91f7c7--- /dev/null+++ b/patches/0011-bc-cpu-decode.patch@@ -0,0 +1,1974 @@+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001+From: v0lumehi <[email protected]>+Date: Wed, 28 Oct 2026 13:33:54 +0100+Subject: [PATCH] Decode BC textures on the CPU when the Metal device has no BC+ support++nvn_bcdec.c decodes BC1-7 into RGBA8 (R8/RG8, RGBA16F for BC6H) through bcdec.h; nvn_mtl.m creates the texture in that format+and fills it through the decoder. Profile key tex_bc_cpu.++Upstream-Status: fork-only (declined seedds/nxnative#488)+Reason: BC textures on GPUs without BC support (A15/A16 and older iPhones), outside upstream's supported devices; gated by supportsBCTextureCompression and the profile key tex_bc_cpu, so supported hardware is unchanged. Owned by us+Issue: LNPANDY/NX2Apple#123+---+ dm/games/0100F2C0115B6000/game.tsv | 3 ++ dm/games/game.py | 3 ++ dm/gfx/nvn/nvn_mtl.m | 44 +-+ dm/gfx/tex/nvn_bcdec.c | 58 +++ dm/gfx/tex/nvn_bcdec.h | 14 ++ dm/gfx/tex/tests/t_bcdec.c | 137 ++++ dm/third_party/bcdec/LICENSE | 52 ++ dm/third_party/bcdec/README.md | 2 ++ dm/third_party/bcdec/bcdec.h | 1512 +++++++++++++++++++++++++++++ 9 files changed, 1823 insertions(+), 2 deletions(-)+ create mode 100644 dm/gfx/tex/nvn_bcdec.c+ create mode 100644 dm/gfx/tex/nvn_bcdec.h+ create mode 100644 dm/gfx/tex/tests/t_bcdec.c+ create mode 100644 dm/third_party/bcdec/LICENSE+ create mode 100644 dm/third_party/bcdec/README.md+ create mode 100644 dm/third_party/bcdec/bcdec.h++diff --git a/dm/games/0100F2C0115B6000/game.tsv b/dm/games/0100F2C0115B6000/game.tsv+index 8a8adb89..223a7f71 100644+--- a/dm/games/0100F2C0115B6000/game.tsv++++ b/dm/games/0100F2C0115B6000/game.tsv+@@ -39,6 +39,9 @@ app_pool 0xCD500000+ # ---- Graphics ----+ # Streamed textures are written by the CPU straight into pool memory (already in GPU layout) and published with nvnMemoryPoolFlushMappedRange (hle_nvn.c ft_add)+ tex_flush_upload on++# BC textures on GPUs without BC support (A15/A16 and older): decode them on the CPU into++# RGBA8 (nvn_bcdec.c). No effect on Macs and A19+ devices, which keep the GPU path.++tex_bc_cpu on+ render_cond on+ tex_dirty_upload on+ # 60 fps (30 on the Switch): the host decides each frame's step in whole vsyncs and holds the frame that long (rewriter stubs at FPSLocker's sites, patches.py FRAME_STEP);+diff --git a/dm/games/game.py b/dm/games/game.py+index 48e1db1b..4e0af38f 100644+--- a/dm/games/game.py++++ b/dm/games/game.py+@@ -119,6 +119,8 @@ def header(g):+ if tfu not in ('on', 'off'): sys.exit(f'{g.id}: tex_flush_upload must be on or off: {tfu}')+ tdu = g.get('tex_dirty_upload', 'off') # with tex_flush_upload: a registered texture the CPU writes after init without any flush is uploaded too (dirty pages, hle_nvn.c nvn_ft_written): on / off+ if tdu not in ('on', 'off') or (tdu == 'on' and tfu != 'on'): sys.exit(f'{g.id}: tex_dirty_upload must be on or off, and needs tex_flush_upload on: {tdu}')++ tbc = g.get('tex_bc_cpu', 'off') # decode BC-compressed textures on the CPU when the GPU has no BC support (A15/A16 and older; nvn_mtl.m uses nvn_bcdec.c): on / off++ if tbc not in ('on', 'off'): sys.exit(f'{g.id}: tex_bc_cpu must be on or off: {tbc}')+ tds = g.get('tex_dyn_slots', 'off') # shaders whose texture handle the translator could not trace to one slot: slot indices in c2, the bound slots in the fallback arrays (nvn_mtl.m): on / off+ if tds not in ('on', 'off'): sys.exit(f'{g.id}: tex_dyn_slots must be on or off: {tds}')+ vcr = g.get('vconv_range', 'off') # vertex attributes converted on the CPU only over the vertices each draw reads (nvn_mtl.m vc_draw_range): on / off+@@ -170,6 +172,7 @@ def header(g):+ f'#define DM_GAME_TEX_FLUSH_UPLOAD {int(tfu == "on")}',+ f'#define DM_GAME_RENDER_COND {int(rcd == "on")}',+ f'#define DM_GAME_TEX_DIRTY_UPLOAD {int(tdu == "on")}',++ f'#define DM_GAME_TEX_BC_CPU {int(tbc == "on")}',+ f'#define DM_GAME_TEX_DYN_SLOTS {int(tds == "on")}',+ f'#define DM_GAME_GPU_TS_SEGMENT {int(gts == "segment")}',+ f'#define DM_GAME_VCONV_RANGE {int(vcr == "on")}',+diff --git a/dm/gfx/nvn/nvn_mtl.m b/dm/gfx/nvn/nvn_mtl.m+index ad381d60..8f753bc3 100644+--- a/dm/gfx/nvn/nvn_mtl.m++++ b/dm/gfx/nvn/nvn_mtl.m+@@ -20,6 +20,7 @@+ #include "nvn_mtl.h"+ #include "nvn_obj.h"+ #include "../tex/nvn_fmt_mtl.h"++#include "../tex/nvn_bcdec.h" // BC on the CPU for GPUs without BC support (profile tex_bc_cpu)+ #include "../tex/nvn_deswizzle.h"+ #include "../tex/nvn_deswizzle_gpu.h"+ #include "nvn_builtin.h"+@@ -79,6 +80,8 @@ static inline uint64_t tex_slot_h(const uint64_t *tex, const uint64_t *img, unsi+ static void warm_claim(void);++ static id<MTLDevice> g_dev;++static int g_bc_gpu = 1; // the device advertises BC texture compression (set where the device is made)++static int g_bc_cpu; // decode BC on the CPU: no GPU support and the profile allows it+ static NSMutableArray *g_l3_gpu_leaks;+ static int g_nvn_deswz_gpu;+ static id<MTLCommandQueue> g_q;+@@ -358,6 +361,9 @@ void mtl_init(void) {+ g_dev = MTLCreateSystemDefaultDevice();+ if (!g_dev) MDIE("no Metal device");+ if (!g_dev.hasUnifiedMemory) MDIE("needs a unified-memory device (zero-copy memory pools)");++ g_bc_gpu = [g_dev supportsBCTextureCompression];++ g_bc_cpu = !g_bc_gpu && DM_GAME_TEX_BC_CPU;++ if (g_bc_cpu) MLOG("BC textures: this GPU has no BC support, decoding them on the CPU (profile tex_bc_cpu)");+ g_q = [g_dev newCommandQueue];+ // A device without Metal 4 (the paravirtualized GPU of a virtual Mac, such as GitHub's macos-26 runner: no residency set, no MTL4CommandQueue) cannot run the NVN layer. The GL and+ // Vulkan layers draw on classic queues of their own and need only the device (mtl_device_classic): there the classic part starts and presents are dropped, which is all a+@@ -1740,7 +1746,12 @@ static MTLTextureUsage img_usage(const tex_t *t, MTLPixelFormat pf) {+ static int tex_atomic_capable(id<MTLTexture> base) { return pf_r32i(base.pixelFormat) && (base.usage & MTLTextureUsageShaderWrite); }+ static MTLTextureDescriptor *tex_desc(const tex_t *t, int packaged) {+ uint32_t pf = 0; uint8_t swz[4];+- if (!nvn_fmt_to_mtl(t->d.format, &pf, swz) || !pf) { RED_ONCE(0, "texture format %#x has no Metal equivalent (first case)", t->d.format); return nil; }++ // A BC format on a GPU without BC support: create the texture in the uncompressed format the++ // decoder produces, and let the upload path fill it through nvn_bc_decode (below). Without++ // this the Metal format is a BC one the device cannot allocate, and every such texture is nil.++ uint32_t bc_unpacked = 0; int bc_bpp = 0;++ if (g_bc_cpu && nvn_bc_unpacked(t->d.format, &bc_unpacked, &bc_bpp)) pf = bc_unpacked;++ if (!pf && (!nvn_fmt_to_mtl(t->d.format, &pf, swz) || !pf)) { RED_ONCE(0, "texture format %#x has no Metal equivalent (first case)", t->d.format); return nil; }+ // Metal's limits: 16384 in 2D, 2048 in 3D, 2048 array layers; beyond them Metal aborts the process on an assertion, so they are caught here with a red line+ if (t->d.width > 16384 || t->d.height > 16384 || t->d.depth > 2048) { RED_ONCE(71, "texture size exceeds Metal limits: %u×%u×%u levels %u format %#x target %d (first case ser=%llu)", t->d.width, t->d.height, t->d.depth, t->d.levels, t->d.format, t->d.target, (unsigned long long)t->serial); return nil; }+ MTLTextureDescriptor *d = [MTLTextureDescriptor new];+@@ -2149,15 +2160,43 @@ static void zb_report(const tex_t *t, unsigned base, const char *why) {+ if (!(part = malloc(t->L.size ? t->L.size : 1))) MDIE("sparse texture copy of %llu bytes failed", (unsigned long long)t->L.size);+ nvn_sparse_copy(t->pool, part, (uint64_t)(uintptr_t)t->mem, t->L.size); src = part;+ }++ // A BC texture on a GPU without BC support: tex_desc made the Metal texture RGBA8 (or R8/RG8,++ // RGBA16F for BC6H), so the staging slot is per-pixel, not per-block, and the deswizzled block++ // data is expanded through nvn_bc_decode before the blit. bc_cpu stays 0 on Macs and A19+,++ // where the compressed path below is used unchanged.++ uint32_t bc_pf = 0; int bc_bpp = 0;++ int bc_cpu = g_bc_cpu && nvn_bc_unpacked(t->d.format, &bc_pf, &bc_bpp);++ size_t total_bc = 0;++ if (bc_cpu) {++ total_bc = 0;++ for (unsigned l = 0; l < d.mipmapLevelCount; l++) {++ uint32_t w = MAX(t->d.width >> l, 1u), h = MAX(t->d.height >> l, 1u), z = t->d.target == 2 ? MAX(t->d.depth >> l, 1u) : 1;++ total_bc += (size_t)w * h * z * layers * (size_t)bc_bpp;++ }++ }+ up_begin();+- id<MTLBuffer> stg = [g_dev newBufferWithLength:total ? total : 16 options:MTLResourceStorageModeShared];++ id<MTLBuffer> stg = [g_dev newBufferWithLength:(bc_cpu ? total_bc : total) ? (bc_cpu ? total_bc : total) : 16 options:MTLResourceStorageModeShared];+ res_add(stg); [g_up_keep addObject:stg];+ size_t off = 0;+ int zb = zblock_on() && t->d.format >= 0x79 && t->d.format <= 0x94; if (zb) { g_zb_ser = t->serial; g_zb_n = (int)MIN(d.mipmapLevelCount, 16u); memset(g_zb, 0, sizeof g_zb); memset(g_zb_tot, 0, sizeof g_zb_tot); }++ // CPU-side scratch for the compressed block data when bc_cpu (one level-slice at a time)++ uint8_t *bc_tmp = NULL; size_t bc_tmp_sz = 0;+ for (unsigned l = 0; l < d.mipmapLevelCount; l++) {+ uint32_t w = MAX(t->d.width >> l, 1u), h = MAX(t->d.height >> l, 1u), z = t->d.target == 2 ? MAX(t->d.depth >> l, 1u) : 1;+ size_t pitch = (size_t)((w + bw - 1) / bw) * bpb, rows = (h + bh - 1) / bh;+ for (unsigned y = 0; y < layers; y++) {++ if (bc_cpu) {++ size_t need = pitch * rows * z;++ if (need > bc_tmp_sz) { free(bc_tmp); bc_tmp = malloc(need); bc_tmp_sz = need; if (!bc_tmp) MDIE("BC decode scratch of %zu bytes failed", need); }++ if (nvn_deswizzle(&t->d, l, y, src, bc_tmp, pitch)) { RED_ONCE(9, "deswizzle failed format %#x target %d", t->d.format, t->d.target); break; }++ size_t dst_pitch = (size_t)w * bc_bpp;++ for (uint32_t zz = 0; zz < z; zz++)++ nvn_bc_decode(t->d.format, bc_tmp + (size_t)zz * pitch * rows, pitch, w, h,++ (uint8_t *)stg.contents + off + (size_t)zz * dst_pitch * h, dst_pitch);++ up_blit_add(stg, off, dst_pitch, dst_pitch * h, MTLSizeMake(w, h, z), mt, y, l);++ off += dst_pitch * h * z;++ continue;++ }+ if (nvn_deswizzle(&t->d, l, y, src, (uint8_t *)stg.contents + off, pitch)) { RED_ONCE(9, "deswizzle failed format %#x target %d", t->d.format, t->d.target); break; }+ if (zb && l < 16) { const uint64_t *q = (const uint64_t *)((const uint8_t *)stg.contents + off); size_t nb = pitch * rows * z / 16;+ for (size_t i = 0; i < nb; i++) g_zb[l] += !(q[2 * i] | q[2 * i + 1]);+@@ -2166,6 +2205,7 @@ static void zb_report(const tex_t *t, unsigned base, const char *why) {+ off += pitch * rows * z;+ }+ }++ free(bc_tmp);+ free(part);+ up_flush();+ return mt;+diff --git a/dm/gfx/tex/nvn_bcdec.c b/dm/gfx/tex/nvn_bcdec.c+new file mode 100644+index 00000000..7b2d83c9+--- /dev/null++++ b/dm/gfx/tex/nvn_bcdec.c+@@ -0,0 +1,58 @@++// 见 nvn_bcdec.h。解码用 bcdec(dm/third_party/bcdec,单头文件,MIT / 公有领域)。++// See nvn_bcdec.h. Decoding uses bcdec (dm/third_party/bcdec, single header, MIT / public domain).++#define BCDEC_IMPLEMENTATION++#define BCDEC_BC4BC5_PRECISE // BC4 / BC5 带有符号版本的接口 | interface with signed variants of BC4 / BC5++#include "../../third_party/bcdec/bcdec.h"++#include "nvn_bcdec.h"++#include <string.h>++++enum { R8Unorm = 10, R8Snorm = 12, RG8Unorm = 30, RG8Snorm = 32, RGBA8Unorm = 70, RGBA8Unorm_sRGB = 71, RGBA16Float = 115 };++// NVN:0x41 RGB_DXT1、0x42 RGBA_DXT1、0x43 DXT3、0x44 DXT5、0x45–0x48 同上 sRGB、0x49 / 0x4a BC4 无 / 有符号、0x4b / 0x4c BC5、0x4d / 0x4e BC7(sRGB)、0x4f / 0x50 BC6H 有 / 无符号++// NVN: 0x41 RGB_DXT1, 0x42 RGBA_DXT1, 0x43 DXT3, 0x44 DXT5, 0x45–0x48 the same in sRGB, 0x49 / 0x4a BC4 unsigned / signed, 0x4b / 0x4c BC5, 0x4d / 0x4e BC7 (sRGB), 0x4f / 0x50 BC6H signed / unsigned++int nvn_bc_unpacked(uint32_t f, uint32_t *pf, int *bpp) {++ switch (f) {++ case 0x41: case 0x42: case 0x43: case 0x44: case 0x4d: *pf = RGBA8Unorm; *bpp = 4; return 1;++ case 0x45: case 0x46: case 0x47: case 0x48: case 0x4e: *pf = RGBA8Unorm_sRGB; *bpp = 4; return 1;++ case 0x49: *pf = R8Unorm; *bpp = 1; return 1;++ case 0x4a: *pf = R8Snorm; *bpp = 1; return 1;++ case 0x4b: *pf = RG8Unorm; *bpp = 2; return 1;++ case 0x4c: *pf = RG8Snorm; *bpp = 2; return 1;++ case 0x4f: case 0x50: *pf = RGBA16Float; *bpp = 8; return 1;++ default: return 0;++ }++}++++static void block(uint32_t f, const uint8_t *b, uint8_t *o, int op) { // 一块 → 4×4 像素(o 每行 op 字节) | one block → 4×4 pixels (o has op bytes per row)++ switch (f) {++ case 0x41: case 0x42: case 0x45: case 0x46: bcdec_bc1(b, o, op); break;++ case 0x43: case 0x47: bcdec_bc2(b, o, op); break;++ case 0x44: case 0x48: bcdec_bc3(b, o, op); break;++ case 0x49: bcdec_bc4(b, o, op, 0); break;++ case 0x4a: bcdec_bc4(b, o, op, 1); break;++ case 0x4b: bcdec_bc5(b, o, op, 0); break;++ case 0x4c: bcdec_bc5(b, o, op, 1); break;++ case 0x4d: case 0x4e: bcdec_bc7(b, o, op); break;++ case 0x4f: case 0x50: { // bcdec 出 RGB 半精度,补 alpha = 1.0 | bcdec outputs RGB half-float; add alpha = 1.0++ uint16_t rgb[16 * 3]; bcdec_bc6h_half(b, rgb, 4 * 3, f == 0x4f);++ for (int y = 0; y < 4; y++) for (int x = 0; x < 4; x++) {++ uint16_t *d = (uint16_t *)(o + y * op) + x * 4; const uint16_t *s = rgb + (y * 4 + x) * 3;++ d[0] = s[0]; d[1] = s[1]; d[2] = s[2]; d[3] = 0x3c00;++ }++ break; }++ }++}++++int nvn_bc_decode(uint32_t f, const uint8_t *src, size_t pitch, uint32_t w, uint32_t h, uint8_t *dst, size_t dpitch) {++ uint32_t pf; int bpp; if (!nvn_bc_unpacked(f, &pf, &bpp)) return -1;++ int bb = (f == 0x41 || f == 0x42 || f == 0x45 || f == 0x46 || f == 0x49 || f == 0x4a) ? 8 : 16; // 每块字节 | bytes per block++ uint8_t tmp[4 * 4 * 8];++ for (uint32_t by = 0; by * 4 < h; by++) for (uint32_t bx = 0; bx * 4 < w; bx++) {++ const uint8_t *b = src + by * pitch + bx * bb;++ uint32_t cw = w - bx * 4 < 4 ? w - bx * 4 : 4, ch = h - by * 4 < 4 ? h - by * 4 : 4;++ uint8_t *o = dst + (size_t)by * 4 * dpitch + (size_t)bx * 4 * bpp;++ if (cw == 4 && ch == 4) { block(f, b, o, (int)dpitch); continue; }++ block(f, b, tmp, 4 * bpp); // 边上不满 4×4 的块:先解到临时块再拷需要的部分 | blocks at the edge that are not a full 4×4: decode into a temporary block first, then copy the needed part++ for (uint32_t y = 0; y < ch; y++) memcpy(o + y * dpitch, tmp + y * 4 * bpp, cw * bpp);++ }++ return 0;++}+diff --git a/dm/gfx/tex/nvn_bcdec.h b/dm/gfx/tex/nvn_bcdec.h+new file mode 100644+index 00000000..abf3d2d1+--- /dev/null++++ b/dm/gfx/tex/nvn_bcdec.h+@@ -0,0 +1,14 @@++// 不支持 BC 压缩格式的显卡(A15 / A16 等,苹果 GPU 族 Apple8 及以下):BC 贴图在 CPU 上解压成不压缩格式。++// 游戏贴图里的 BC3 由老机型补充包离线换成 ASTC(dm/tools/astc_pack.py);剩下的 BC(精灵图里的 BC3、少量 BC1 / BC4 / BC5 / BC6H)走这里。++// GPUs without BC compressed format support (A15 / A16 etc., Apple GPU family Apple8 and below): BC textures are decompressed on the CPU into uncompressed formats.++// BC3 in game textures is converted offline to ASTC by the Legacy Device Pack (dm/tools/astc_pack.py); the remaining BC (BC3 in sprites, a few BC1 / BC4 / BC5 / BC6H) goes through here.++#pragma once++#include <stddef.h>++#include <stdint.h>++++// NVN 格式是 BC → 返回 1,*mtl_pf = 解压后的 Metal 像素格式、*bpp = 解压后每像素字节;不是 BC 返回 0++// NVN format is BC → returns 1, *mtl_pf = Metal pixel format after decompression, *bpp = bytes per pixel after decompression; returns 0 if not BC++int nvn_bc_unpacked(uint32_t nvn_fmt, uint32_t *mtl_pf, int *bpp);++// 解一片 w×h 像素:src 按块行排(每块行 pitch 字节),dst 每像素行 dpitch 字节。成功 0++// Decode a w×h pixel region: src is laid out by block rows (pitch bytes per block row), dst has dpitch bytes per pixel row. Returns 0 on success++int nvn_bc_decode(uint32_t nvn_fmt, const uint8_t *src, size_t pitch, uint32_t w, uint32_t h, uint8_t *dst, size_t dpitch);+diff --git a/dm/gfx/tex/tests/t_bcdec.c b/dm/gfx/tex/tests/t_bcdec.c+new file mode 100644+index 00000000..5fd5efe4+--- /dev/null++++ b/dm/gfx/tex/tests/t_bcdec.c+@@ -0,0 +1,137 @@++// BC decode correctness: decode a known block with bcdec through our glue, and compare against++// bytes produced by an independent path (a second, hand-written DXT1 decoder in this file).++// Formats with no independent reference here are checked structurally instead: every decoded++// pixel must be opaque, the block must fit its 4x4 grid, and edge blocks must be trimmed.++#include "../nvn_bcdec.h"++#include <assert.h>++#include <stdio.h>++#include <string.h>++++static int failures;++++static void check(int cond, const char *what) {++ if (!cond) { printf("FAIL: %s\n", what); failures++; }++}++++// ---- reference DXT1 (BC1) decoder: the textbook algorithm, written independently of bcdec ----++static void put565(unsigned char *o, unsigned v, int srgb) {++ (void)srgb;++ int r = (v >> 11) & 0x1f, g = (v >> 5) & 0x3f, b = v & 0x1f;++ o[0] = (unsigned char)((r << 3) | (r >> 2));++ o[1] = (unsigned char)((g << 2) | (g >> 4));++ o[2] = (unsigned char)((b << 3) | (b >> 2));++ o[3] = 255;++}++static void ref_bc1(const unsigned char *blk, unsigned char *out, int op) {++ unsigned c0 = blk[0] | (blk[1] << 8), c1 = blk[2] | (blk[3] << 8);++ unsigned char pal[4][4];++ put565(pal[0], c0, 0);++ put565(pal[1], c1, 0);++ if (c0 > c1) {++ for (int i = 0; i < 3; i++) {++ // bcdec rounds; a truncating reference differs by one on every interpolated stop++ pal[2][i] = (unsigned char)((2 * pal[0][i] + pal[1][i] + 1) / 3);++ pal[3][i] = (unsigned char)((pal[0][i] + 2 * pal[1][i] + 1) / 3);++ }++ pal[2][3] = pal[3][3] = 255;++ } else {++ for (int i = 0; i < 3; i++) {++ pal[2][i] = (unsigned char)((pal[0][i] + pal[1][i] + 1) / 2);++ pal[3][i] = 0;++ }++ pal[2][3] = 255;++ pal[3][3] = 255; // RGB_DXT1: the fourth colour is black but opaque++ }++ unsigned idx = blk[4] | (blk[5] << 8) | (blk[6] << 16) | ((unsigned)blk[7] << 24);++ for (int y = 0; y < 4; y++)++ for (int x = 0; x < 4; x++) {++ int p = (int)((idx >> (2 * (y * 4 + x))) & 3);++ memcpy(out + y * op + x * 4, pal[p], 4);++ }++}++++static void test_bc1_matches_reference(void) {++ // Two blocks: one with c0 > c1 (four-colour mode) and one with c0 <= c1 (three-colour).++ unsigned char blocks[2][8] = {++ { 0x00, 0xF8, 0xE0, 0x07, 0x1B, 0x36, 0x6C, 0xD8 }, // c0 = red-ish 0xF800, c1 = green-ish 0x07E0++ { 0xE0, 0x07, 0x00, 0xF8, 0x55, 0xAA, 0x55, 0xAA }, // swapped: three-colour mode++ };++ for (int k = 0; k < 2; k++) {++ unsigned char got[4 * 16], want[4 * 16];++ int r = nvn_bc_decode(0x41, blocks[k], 8, 4, 4, got, 16); // 0x41 = RGB_DXT1 (no alpha semantics)++ check(r == 0, "bc1 decode returns 0");++ ref_bc1(blocks[k], want, 16);++ if (memcmp(got, want, sizeof want) != 0) {++ char msg[96];++ snprintf(msg, sizeof msg, "BC1 block %d matches the reference decoder", k);++ check(0, msg);++ for (int i = 0; i < 16; i++)++ if (got[i] != want[i]) { printf(" byte %d: got %u want %u\n", i, got[i], want[i]); break; }++ } else {++ check(1, "");++ }++ }++}++++static void test_formats_map(void) {++ unsigned pf; int bpp;++ struct { uint32_t fmt; unsigned pf; int bpp; } cases[] = {++ { 0x41, 70, 4 }, { 0x42, 70, 4 }, { 0x43, 70, 4 }, { 0x44, 70, 4 }, { 0x4d, 70, 4 },++ { 0x45, 71, 4 }, { 0x46, 71, 4 }, { 0x47, 71, 4 }, { 0x48, 71, 4 }, { 0x4e, 71, 4 },++ { 0x49, 10, 1 }, { 0x4a, 12, 1 }, { 0x4b, 30, 2 }, { 0x4c, 32, 2 },++ { 0x4f, 115, 8 }, { 0x50, 115, 8 },++ };++ for (unsigned i = 0; i < sizeof cases / sizeof cases[0]; i++) {++ check(nvn_bc_unpacked(cases[i].fmt, &pf, &bpp) == 1, "format is recognised as BC");++ check(pf == cases[i].pf && bpp == cases[i].bpp, "format maps to the expected pixel format");++ }++ check(nvn_bc_unpacked(0x25, &pf, &bpp) == 0, "a non-BC format is rejected");++}++++static void test_edge_blocks_trimmed(void) {++ // A 6x3 image: blocks at x=4 and y=0 are partial. Decoding must write only real pixels,++ // and the sentinel after the last row must survive (nothing written past the height).++ // 6 pixels wide = two 4-pixel blocks per block row, so the source needs two blocks and a++ // pitch of 2 * 8 bytes. (Passing one block made the second one read past the array.)++ unsigned char blk[2][8] = {++ { 0x00, 0xF8, 0xE0, 0x07, 0x1B, 0x36, 0x6C, 0xD8 },++ { 0xE0, 0x07, 0x1F, 0x00, 0x1B, 0x36, 0x6C, 0xD8 },++ };++ enum { W = 6, H = 3 };++ unsigned char out[H * W * 4 + 64];++ memset(out, 0xAB, sizeof out);++ int r = nvn_bc_decode(0x41, (const unsigned char *)blk, 16, W, H, out, W * 4);++ check(r == 0, "partial-block decode returns 0");++ for (int y = 0; y < H; y++)++ for (int x = 0; x < W; x++) {++ const unsigned char *p = out + y * W * 4 + x * 4;++ check(p[3] == 255, "RGB_DXT1 decodes every pixel opaque");++ }++ for (unsigned i = H * W * 4; i < sizeof out; i++)++ if (out[i] != 0xAB) { check(0, "nothing is written past the last row"); break; }++}++++static void test_bc4_single_channel(void) {++ // BC4 stores one channel; the unpacked format is R8, so bytes 1..3 of each pixel stay as the++ // caller left them (tex_mtl fills alpha itself). Check the red channel varies with the block.++ unsigned char blk[8] = { 0xFF, 0x00, 0, 0, 0, 0, 0, 0 }; // endpoints 255 and 0++ // BC4 decodes to R8: one byte per pixel, dpitch = 4 for a 4-pixel row.++ unsigned char out[4 * 4];++ memset(out, 0xCC, sizeof out);++ int r = nvn_bc_decode(0x49, blk, 8, 4, 4, out, 4); // 0x49 = BC4 unsigned++ check(r == 0, "bc4 decode returns 0");++ int uniform = 1;++ for (int i = 0; i < 16; i++) if (out[i] != 255) uniform = 0;++ check(uniform, "bc4 decodes the whole block to the endpoint value");++ check(out[1 + 4] == 255, "bc4 writes every row (not just the first)");++}++++int main(void) {++ test_bc1_matches_reference();++ test_formats_map();++ test_edge_blocks_trimmed();++ test_bc4_single_channel();++ if (failures) { printf("%d check(s) failed\n", failures); return 1; }++ printf("bc decode: BC1 matches an independent DXT1 decoder, format map, edge trimming, BC4 - all OK\n");++ return 0;++}+diff --git a/dm/third_party/bcdec/LICENSE b/dm/third_party/bcdec/LICENSE+new file mode 100644+index 00000000..78e53f19+--- /dev/null++++ b/dm/third_party/bcdec/LICENSE+@@ -0,0 +1,52 @@++This software is available under 2 licenses -- choose whichever you prefer.++++------------------------------------------------------------------------------++ALTERNATIVE A - MIT License++++Copyright (c) 2022 Sergii Kudlai++++Permission is hereby granted, free of charge, to any person obtaining a copy of++this software and associated documentation files (the "Software"), to deal in++the Software without restriction, including without limitation the rights to++use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies++of the Software, and to permit persons to whom the Software is furnished to do++so, subject to the following conditions:++++The above copyright notice and this permission notice shall be included in all++copies or substantial portions of the Software.++++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR++IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,++FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE++AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER++LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,++OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE++SOFTWARE.++++------------------------------------------------------------------------------++ALTERNATIVE B - The Unlicense++++This is free and unencumbered software released into the public domain.++++Anyone is free to copy, modify, publish, use, compile, sell, or++distribute this software, either in source code form or as a compiled++binary, for any purpose, commercial or non-commercial, and by any++means.++++In jurisdictions that recognize copyright laws, the author or authors++of this software dedicate any and all copyright interest in the++software to the public domain. We make this dedication for the benefit++of the public at large and to the detriment of our heirs and++successors. We intend this dedication to be an overt act of++relinquishment in perpetuity of all present and future rights to this++software under copyright law.++++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,++EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF++MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.++IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR++OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,++ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR++OTHER DEALINGS IN THE SOFTWARE.++++For more information, please refer to <https://unlicense.org>+diff --git a/dm/third_party/bcdec/README.md b/dm/third_party/bcdec/README.md+new file mode 100644+index 00000000..baf2d240+--- /dev/null++++ b/dm/third_party/bcdec/README.md+@@ -0,0 +1,2 @@++来源:https://github.com/iOrange/bcdec 提交 80859ed(版本 0.985),未改动。许可见 LICENSE(MIT 或公有领域二选一)。++用途:不支持 BC 压缩格式的显卡上,翻译层把 BC 贴图在 CPU 上解压(dm/gfx/tex/nvn_bcdec.c)。+diff --git a/dm/third_party/bcdec/bcdec.h b/dm/third_party/bcdec/bcdec.h+new file mode 100644+index 00000000..553c3ec5+--- /dev/null++++ b/dm/third_party/bcdec/bcdec.h+@@ -0,0 +1,1512 @@++/* bcdec.h - v0.985++ provides functions to decompress blocks of BC compressed images++ written by Sergii "iOrange" Kudlai in 2022++++ This library does not allocate memory and is trying to use as less stack as possible++++ This library was never optimized specifically for speed but for the overall size++ it has zero external dependencies and is not using any runtime functions++++ This library was writtem by humans and will never contain any LLM-generated code++++ Supported BC formats:++ BC1 (also known as DXT1) + it's "binary alpha" variant BC1A (DXT1A)++ BC2 (also known as DXT3)++ BC3 (also known as DXT5)++ BC4 (also known as ATI1N)++ BC5 (also known as ATI2N)++ BC6H (HDR format)++ BC7++++ BC1/BC2/BC3/BC7 are expected to decompress into 4*4 RGBA blocks 8bit per component (32bit pixel)++ BC4/BC5 are expected to decompress into 4*4 R/RG blocks 8bit per component (8bit and 16bit pixel)++ BC6H is expected to decompress into 4*4 RGB blocks of either 32bit float or 16bit "half" per++ component (96bit or 48bit pixel)++++ For more info, issues and suggestions please visit https://github.com/iOrange/bcdec++++ Configuration:++ #define BCDEC_BC4BC5_PRECISE:++ enables more precise but slower BC4/BC5 decoding + signed/unsigned mode++++ CREDITS:++ Aras Pranckevicius (@aras-p) - BC1/BC3 decoders optimizations (up to 3x the speed)++ - BC6H/BC7 bits pulling routines optimizations++ - optimized BC6H by moving unquantize out of the loop++ - Split BC6H decompression function into 'half' and++ 'float' variants++++ Michael Schmidt (@RunDevelopment) - Found better "magic" coefficients for integer interpolation++ of reference colors in BC1 color block, that match with++ the floating point interpolation. This also made it faster++ than integer division by 3!++++ bugfixes:++ @linkmauve++ @wkjarosz++++ LICENSE: See end of file for license information.++*/++++#ifndef BCDEC_HEADER_INCLUDED++#define BCDEC_HEADER_INCLUDED++++#define BCDEC_VERSION_MAJOR 0++#define BCDEC_VERSION_MINOR 985++++/* if BCDEC_STATIC causes problems, try defining BCDECDEF to 'inline' or 'static inline' */++#ifndef BCDECDEF++#ifdef BCDEC_STATIC++#define BCDECDEF static++#else++#ifdef __cplusplus++#define BCDECDEF extern "C"++#else++#define BCDECDEF extern++#endif++#endif++#endif++++/* Used information sources:++ https://docs.microsoft.com/en-us/windows/win32/direct3d10/d3d10-graphics-programming-guide-resources-block-compression++ https://docs.microsoft.com/en-us/windows/win32/direct3d11/bc6h-format++ https://docs.microsoft.com/en-us/windows/win32/direct3d11/bc7-format++ https://docs.microsoft.com/en-us/windows/win32/direct3d11/bc7-format-mode-reference++++ ! WARNING ! Khronos's BPTC partitions tables contain mistakes, do not use them!++ https://www.khronos.org/registry/DataFormat/specs/1.1/dataformat.1.1.html#BPTC++++ ! Use tables from here instead !++ https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_texture_compression_bptc.txt++++ Leaving it here as it's a nice read++ https://fgiesen.wordpress.com/2021/10/04/gpu-bcn-decoding/++++ Fast half to float function from here++ https://gist.github.com/rygorous/2144712++*/++++#define BCDEC_BC1_BLOCK_SIZE 8++#define BCDEC_BC2_BLOCK_SIZE 16++#define BCDEC_BC3_BLOCK_SIZE 16++#define BCDEC_BC4_BLOCK_SIZE 8++#define BCDEC_BC5_BLOCK_SIZE 16++#define BCDEC_BC6H_BLOCK_SIZE 16++#define BCDEC_BC7_BLOCK_SIZE 16++++#define BCDEC_BC1_COMPRESSED_SIZE(w, h) ((((w)>>2)*((h)>>2))*BCDEC_BC1_BLOCK_SIZE)++#define BCDEC_BC2_COMPRESSED_SIZE(w, h) ((((w)>>2)*((h)>>2))*BCDEC_BC2_BLOCK_SIZE)++#define BCDEC_BC3_COMPRESSED_SIZE(w, h) ((((w)>>2)*((h)>>2))*BCDEC_BC3_BLOCK_SIZE)++#define BCDEC_BC4_COMPRESSED_SIZE(w, h) ((((w)>>2)*((h)>>2))*BCDEC_BC4_BLOCK_SIZE)++#define BCDEC_BC5_COMPRESSED_SIZE(w, h) ((((w)>>2)*((h)>>2))*BCDEC_BC5_BLOCK_SIZE)++#define BCDEC_BC6H_COMPRESSED_SIZE(w, h) ((((w)>>2)*((h)>>2))*BCDEC_BC6H_BLOCK_SIZE)++#define BCDEC_BC7_COMPRESSED_SIZE(w, h) ((((w)>>2)*((h)>>2))*BCDEC_BC7_BLOCK_SIZE)++++BCDECDEF void bcdec_bc1(const void* compressedBlock, void* decompressedBlock, int destinationPitch);++BCDECDEF void bcdec_bc2(const void* compressedBlock, void* decompressedBlock, int destinationPitch);++BCDECDEF void bcdec_bc3(const void* compressedBlock, void* decompressedBlock, int destinationPitch);++#ifndef BCDEC_BC4BC5_PRECISE++BCDECDEF void bcdec_bc4(const void* compressedBlock, void* decompressedBlock, int destinationPitch);++BCDECDEF void bcdec_bc5(const void* compressedBlock, void* decompressedBlock, int destinationPitch);++#else++BCDECDEF void bcdec_bc4(const void* compressedBlock, void* decompressedBlock, int destinationPitch, int isSigned);++BCDECDEF void bcdec_bc5(const void* compressedBlock, void* decompressedBlock, int destinationPitch, int isSigned);++BCDECDEF void bcdec_bc4_float(const void* compressedBlock, void* decompressedBlock, int destinationPitch, int isSigned);++BCDECDEF void bcdec_bc5_float(const void* compressedBlock, void* decompressedBlock, int destinationPitch, int isSigned);++#endif++BCDECDEF void bcdec_bc6h_float(const void* compressedBlock, void* decompressedBlock, int destinationPitch, int isSigned);++BCDECDEF void bcdec_bc6h_half(const void* compressedBlock, void* decompressedBlock, int destinationPitch, int isSigned);++BCDECDEF void bcdec_bc7(const void* compressedBlock, void* decompressedBlock, int destinationPitch);++++#endif /* BCDEC_HEADER_INCLUDED */++++#ifdef BCDEC_IMPLEMENTATION++++static unsigned short bcdec__getu16le(const void* s) {++ unsigned short l = (unsigned short)((const unsigned char*)s)[0];++ unsigned short h = (unsigned short)((const unsigned char*)s)[1];++ return l | (h << 8);++}++static unsigned int bcdec__getu32le(const void* s) {++ unsigned int l = bcdec__getu16le(s);++ unsigned int h = bcdec__getu16le((const unsigned char*)s + 2);++ return l | (h << 16);++}++static unsigned long long bcdec__getu64le(const void* s) {++ unsigned long long l = bcdec__getu32le(s);++ unsigned long long h = bcdec__getu32le((const unsigned char*)s + 4);++ return l | (h << 32);++}++++static void bcdec__color_block(const void* compressedBlock, void* decompressedBlock, int destinationPitch, int onlyOpaqueMode) {++ unsigned short c0, c1;++ unsigned int refColors[4]; /* 0xAABBGGRR */++ unsigned char* dstColors;++ unsigned int colorIndices;++ int i, j, idx;++ unsigned int r0, g0, b0, r1, g1, b1, r, g, b;++++ c0 = bcdec__getu16le(compressedBlock);++ c1 = bcdec__getu16le((const unsigned char*)compressedBlock + 2);++++ /* Unpack 565 ref colors */++ r0 = (c0 >> 11) & 0x1F;++ g0 = (c0 >> 5) & 0x3F;++ b0 = c0 & 0x1F;++++ r1 = (c1 >> 11) & 0x1F;++ g1 = (c1 >> 5) & 0x3F;++ b1 = c1 & 0x1F;++++ /* Expand 565 ref colors to 888 */++ r = (r0 * 527 + 23) >> 6;++ g = (g0 * 259 + 33) >> 6;++ b = (b0 * 527 + 23) >> 6;++ refColors[0] = 0xFF000000 | (b << 16) | (g << 8) | r;++++ r = (r1 * 527 + 23) >> 6;++ g = (g1 * 259 + 33) >> 6;++ b = (b1 * 527 + 23) >> 6;++ refColors[1] = 0xFF000000 | (b << 16) | (g << 8) | r;++++ if (c0 > c1 || onlyOpaqueMode) { /* Standard BC1 mode (also BC3 color block uses ONLY this mode) */++ /* color_2 = 2/3*color_0 + 1/3*color_1++ color_3 = 1/3*color_0 + 2/3*color_1 */++ r = ((2 * r0 + r1) * 351 + 61) >> 7;++ g = ((2 * g0 + g1) * 2763 + 1039) >> 11;++ b = ((2 * b0 + b1) * 351 + 61) >> 7;++ refColors[2] = 0xFF000000 | (b << 16) | (g << 8) | r;++++ r = ((r0 + r1 * 2) * 351 + 61) >> 7;++ g = ((g0 + g1 * 2) * 2763 + 1039) >> 11;++ b = ((b0 + b1 * 2) * 351 + 61) >> 7;++ refColors[3] = 0xFF000000 | (b << 16) | (g << 8) | r;++ } else { /* Quite rare BC1A mode */++ /* color_2 = 1/2*color_0 + 1/2*color_1;++ color_3 = 0; */++ r = ((r0 + r1) * 1053 + 125) >> 8;++ g = ((g0 + g1) * 4145 + 1019) >> 11;++ b = ((b0 + b1) * 1053 + 125) >> 8;++ refColors[2] = 0xFF000000 | (b << 16) | (g << 8) | r;++++ refColors[3] = 0x00000000;++ }++++ colorIndices = bcdec__getu32le((const unsigned char*)compressedBlock + 4);++++ /* Fill out the decompressed color block */++ dstColors = (unsigned char*)decompressedBlock;++ for (i = 0; i < 4; ++i) {++ for (j = 0; j < 4; ++j) {++ idx = colorIndices & 0x03;++ ((unsigned int*)dstColors)[j] = refColors[idx];++ colorIndices >>= 2;++ }++++ dstColors += destinationPitch;++ }++}++++static void bcdec__sharp_alpha_block(const void* compressedBlock, void* decompressedBlock, int destinationPitch) {++ unsigned short alpha;++ const unsigned char* alphaPtr;++ unsigned char* decompressed;++ int i, j;++++ alphaPtr = (const unsigned char*)compressedBlock;++ decompressed = (unsigned char*)decompressedBlock;++++ for (i = 0; i < 4; ++i) {++ alpha = bcdec__getu16le(alphaPtr);++++ for (j = 0; j < 4; ++j) {++ decompressed[j * 4] = ((alpha >> (4 * j)) & 0x0F) * 17;++ }++++ alphaPtr += 2;++ decompressed += destinationPitch;++ }++}++++static void bcdec__smooth_alpha_block(const void* compressedBlock, void* decompressedBlock, int destinationPitch, int pixelSize) {++ unsigned char* decompressed;++ unsigned char alpha[8];++ int i, j;++ unsigned long long block, indices;++++ block = bcdec__getu64le(compressedBlock);++ decompressed = (unsigned char*)decompressedBlock;++++ alpha[0] = block & 0xFF;++ alpha[1] = (block >> 8) & 0xFF;++++ if (alpha[0] > alpha[1]) {++ /* 6 interpolated alpha values. */++ alpha[2] = (6 * alpha[0] + alpha[1]) / 7; /* 6/7*alpha_0 + 1/7*alpha_1 */++ alpha[3] = (5 * alpha[0] + 2 * alpha[1]) / 7; /* 5/7*alpha_0 + 2/7*alpha_1 */++ alpha[4] = (4 * alpha[0] + 3 * alpha[1]) / 7; /* 4/7*alpha_0 + 3/7*alpha_1 */++ alpha[5] = (3 * alpha[0] + 4 * alpha[1]) / 7; /* 3/7*alpha_0 + 4/7*alpha_1 */++ alpha[6] = (2 * alpha[0] + 5 * alpha[1]) / 7; /* 2/7*alpha_0 + 5/7*alpha_1 */++ alpha[7] = ( alpha[0] + 6 * alpha[1]) / 7; /* 1/7*alpha_0 + 6/7*alpha_1 */++ }++ else {++ /* 4 interpolated alpha values. */++ alpha[2] = (4 * alpha[0] + alpha[1]) / 5; /* 4/5*alpha_0 + 1/5*alpha_1 */++ alpha[3] = (3 * alpha[0] + 2 * alpha[1]) / 5; /* 3/5*alpha_0 + 2/5*alpha_1 */++ alpha[4] = (2 * alpha[0] + 3 * alpha[1]) / 5; /* 2/5*alpha_0 + 3/5*alpha_1 */++ alpha[5] = ( alpha[0] + 4 * alpha[1]) / 5; /* 1/5*alpha_0 + 4/5*alpha_1 */++ alpha[6] = 0x00;++ alpha[7] = 0xFF;++ }++++ indices = block >> 16;++ for (i = 0; i < 4; ++i) {++ for (j = 0; j < 4; ++j) {++ decompressed[j * pixelSize] = alpha[indices & 0x07];++ indices >>= 3;++ }++++ decompressed += destinationPitch;++ }++}++++#ifdef BCDEC_BC4BC5_PRECISE++static void bcdec__bc4_block(const void* compressedBlock, void* decompressedBlock, int destinationPitch, int pixelSize, int isSigned) {++ signed char* sblock;++ unsigned char* ublock;++ int alpha[8];++ int i, j;++ unsigned long long block, indices;++++ static int aWeights4[4] = { 13107, 26215, 39321, 52429 };++ static int aWeights6[6] = { 9363, 18724, 28086, 37450, 46812, 56173 };++++ block = bcdec__getu64le(compressedBlock);++++ if (isSigned) {++ alpha[0] = (char)(block & 0xFF);++ alpha[1] = (char)((block >> 8) & 0xFF);++ if (alpha[0] < -127) alpha[0] = -127; /* -128 clamps to -127 */++ if (alpha[1] < -127) alpha[1] = -127; /* -128 clamps to -127 */++ } else {++ alpha[0] = block & 0xFF;++ alpha[1] = (block >> 8) & 0xFF;++ }++++ if (alpha[0] > alpha[1]) {++ /* 6 interpolated alpha values. */++ alpha[2] = (aWeights6[5] * alpha[0] + aWeights6[0] * alpha[1] + 32768) >> 16; /* 6/7*alpha_0 + 1/7*alpha_1 */++ alpha[3] = (aWeights6[4] * alpha[0] + aWeights6[1] * alpha[1] + 32768) >> 16; /* 5/7*alpha_0 + 2/7*alpha_1 */++ alpha[4] = (aWeights6[3] * alpha[0] + aWeights6[2] * alpha[1] + 32768) >> 16; /* 4/7*alpha_0 + 3/7*alpha_1 */++ alpha[5] = (aWeights6[2] * alpha[0] + aWeights6[3] * alpha[1] + 32768) >> 16; /* 3/7*alpha_0 + 4/7*alpha_1 */++ alpha[6] = (aWeights6[1] * alpha[0] + aWeights6[4] * alpha[1] + 32768) >> 16; /* 2/7*alpha_0 + 5/7*alpha_1 */++ alpha[7] = (aWeights6[0] * alpha[0] + aWeights6[5] * alpha[1] + 32768) >> 16; /* 1/7*alpha_0 + 6/7*alpha_1 */++ } else {++ /* 4 interpolated alpha values. */++ alpha[2] = (aWeights4[3] * alpha[0] + aWeights4[0] * alpha[1] + 32768) >> 16; /* 4/5*alpha_0 + 1/5*alpha_1 */++ alpha[3] = (aWeights4[2] * alpha[0] + aWeights4[1] * alpha[1] + 32768) >> 16; /* 3/5*alpha_0 + 2/5*alpha_1 */++ alpha[4] = (aWeights4[1] * alpha[0] + aWeights4[2] * alpha[1] + 32768) >> 16; /* 2/5*alpha_0 + 3/5*alpha_1 */++ alpha[5] = (aWeights4[0] * alpha[0] + aWeights4[3] * alpha[1] + 32768) >> 16; /* 1/5*alpha_0 + 4/5*alpha_1 */++ alpha[6] = isSigned ? -127 : 0;++ alpha[7] = isSigned ? 127 : 255;++ }++++ indices = block >> 16;++ if (isSigned) {++ sblock = (signed char*)decompressedBlock;++ for (i = 0; i < 4; ++i) {++ for (j = 0; j < 4; ++j) {++ sblock[j * pixelSize] = (signed char)alpha[indices & 0x07];++ indices >>= 3;++ }++ sblock += destinationPitch;++ }++ } else {++ ublock = (unsigned char*)decompressedBlock;++ for (i = 0; i < 4; ++i) {++ for (j = 0; j < 4; ++j) {++ ublock[j * pixelSize] = (unsigned char)alpha[indices & 0x07];++ indices >>= 3;++ }++ ublock += destinationPitch;++ }++ }++}++++static void bcdec__bc4_block_float(const void* compressedBlock, void* decompressedBlock, int destinationPitch, int pixelSize, int isSigned) {++ float* decompressed;++ float alpha[8];++ int i, j;++ unsigned long long block, indices;++++ block = bcdec__getu64le(compressedBlock);++ decompressed = (float*)decompressedBlock;++++ if (isSigned) {++ alpha[0] = (float)((char)(block & 0xFF)) / 127.0f;++ alpha[1] = (float)((char)((block >> 8) & 0xFF)) / 127.0f;++ if (alpha[0] < -1.0f) alpha[0] = -1.0f; /* -128 clamps to -127 */++ if (alpha[1] < -1.0f) alpha[1] = -1.0f; /* -128 clamps to -127 */++ } else {++ alpha[0] = (float)(block & 0xFF) / 255.0f;++ alpha[1] = (float)((block >> 8) & 0xFF) / 255.0f;++ }++++ if (alpha[0] > alpha[1]) {++ /* 6 interpolated alpha values. */++ alpha[2] = (6.0f * alpha[0] + alpha[1]) / 7.0f; /* 6/7*alpha_0 + 1/7*alpha_1 */++ alpha[3] = (5.0f * alpha[0] + 2.0f * alpha[1]) / 7.0f; /* 5/7*alpha_0 + 2/7*alpha_1 */++ alpha[4] = (4.0f * alpha[0] + 3.0f * alpha[1]) / 7.0f; /* 4/7*alpha_0 + 3/7*alpha_1 */++ alpha[5] = (3.0f * alpha[0] + 4.0f * alpha[1]) / 7.0f; /* 3/7*alpha_0 + 4/7*alpha_1 */++ alpha[6] = (2.0f * alpha[0] + 5.0f * alpha[1]) / 7.0f; /* 2/7*alpha_0 + 5/7*alpha_1 */++ alpha[7] = ( alpha[0] + 6.0f * alpha[1]) / 7.0f; /* 1/7*alpha_0 + 6/7*alpha_1 */++ } else {++ /* 4 interpolated alpha values. */++ alpha[2] = (4.0f * alpha[0] + alpha[1]) / 5.0f; /* 4/5*alpha_0 + 1/5*alpha_1 */++ alpha[3] = (3.0f * alpha[0] + 2.0f * alpha[1]) / 5.0f; /* 3/5*alpha_0 + 2/5*alpha_1 */++ alpha[4] = (2.0f * alpha[0] + 3.0f * alpha[1]) / 5.0f; /* 2/5*alpha_0 + 3/5*alpha_1 */++ alpha[5] = ( alpha[0] + 4.0f * alpha[1]) / 5.0f; /* 1/5*alpha_0 + 4/5*alpha_1 */++ alpha[6] = isSigned ? -1.0f : 0.0f;++ alpha[7] = 1.0f;++ }++++ indices = block >> 16;++ for (i = 0; i < 4; ++i) {++ for (j = 0; j < 4; ++j) {++ decompressed[j * pixelSize] = alpha[indices & 0x07];++ indices >>= 3;++ }++ decompressed += destinationPitch;++ }++}++#endif /* BCDEC_BC4BC5_PRECISE */++++typedef struct bcdec__bitstream {++ unsigned long long low;++ unsigned long long high;++} bcdec__bitstream_t;++++static int bcdec__bitstream_read_bits(bcdec__bitstream_t* bstream, int numBits) {++ unsigned int mask = (1 << numBits) - 1;++ /* Read the low N bits */++ unsigned int bits = (bstream->low & mask);++++ bstream->low >>= numBits;++ /* Put the low N bits of "high" into the high 64-N bits of "low". */++ bstream->low |= (bstream->high & mask) << (sizeof(bstream->high) * 8 - numBits);++ bstream->high >>= numBits;++++ return bits;++}++++static int bcdec__bitstream_read_bit(bcdec__bitstream_t* bstream) {++ return bcdec__bitstream_read_bits(bstream, 1);++}++++/* reversed bits pulling, used in BC6H decoding++ why ?? just why ??? */++static int bcdec__bitstream_read_bits_r(bcdec__bitstream_t* bstream, int numBits) {++ int bits = bcdec__bitstream_read_bits(bstream, numBits);++ /* Reverse the bits. */++ int result = 0;++ while (numBits--) {++ result <<= 1;++ result |= (bits & 1);++ bits >>= 1;++ }++ return result;++}++++++++BCDECDEF void bcdec_bc1(const void* compressedBlock, void* decompressedBlock, int destinationPitch) {++ bcdec__color_block(compressedBlock, decompressedBlock, destinationPitch, 0);++}++++BCDECDEF void bcdec_bc2(const void* compressedBlock, void* decompressedBlock, int destinationPitch) {++ bcdec__color_block(((char*)compressedBlock) + 8, decompressedBlock, destinationPitch, 1);++ bcdec__sharp_alpha_block(compressedBlock, ((char*)decompressedBlock) + 3, destinationPitch);++}++++BCDECDEF void bcdec_bc3(const void* compressedBlock, void* decompressedBlock, int destinationPitch) {++ bcdec__color_block(((char*)compressedBlock) + 8, decompressedBlock, destinationPitch, 1);++ bcdec__smooth_alpha_block(compressedBlock, ((char*)decompressedBlock) + 3, destinationPitch, 4);++}++++#ifndef BCDEC_BC4BC5_PRECISE++BCDECDEF void bcdec_bc4(const void* compressedBlock, void* decompressedBlock, int destinationPitch) {++ bcdec__smooth_alpha_block(compressedBlock, decompressedBlock, destinationPitch, 1);++#else++BCDECDEF void bcdec_bc4(const void* compressedBlock, void* decompressedBlock, int destinationPitch, int isSigned) {++ bcdec__bc4_block(compressedBlock, decompressedBlock, destinationPitch, 1, isSigned);++#endif++}++++#ifndef BCDEC_BC4BC5_PRECISE++BCDECDEF void bcdec_bc5(const void* compressedBlock, void* decompressedBlock, int destinationPitch) {++ bcdec__smooth_alpha_block(compressedBlock, decompressedBlock, destinationPitch, 2);++ bcdec__smooth_alpha_block(((char*)compressedBlock) + 8, ((char*)decompressedBlock) + 1, destinationPitch, 2);++#else++BCDECDEF void bcdec_bc5(const void* compressedBlock, void* decompressedBlock, int destinationPitch, int isSigned) {++ bcdec__bc4_block(compressedBlock, decompressedBlock, destinationPitch, 2, isSigned);++ bcdec__bc4_block(((char*)compressedBlock) + 8, ((char*)decompressedBlock) + 1, destinationPitch, 2, isSigned);++#endif++}++++#ifdef BCDEC_BC4BC5_PRECISE++BCDECDEF void bcdec_bc4_float(const void* compressedBlock, void* decompressedBlock, int destinationPitch, int isSigned) {++ bcdec__bc4_block_float(compressedBlock, decompressedBlock, destinationPitch, 1, isSigned);++}++++BCDECDEF void bcdec_bc5_float(const void* compressedBlock, void* decompressedBlock, int destinationPitch, int isSigned) {++ bcdec__bc4_block_float(compressedBlock, decompressedBlock, destinationPitch, 2, isSigned);++ bcdec__bc4_block_float(((char*)compressedBlock) + 8, ((float*)decompressedBlock) + 1, destinationPitch, 2, isSigned);++}++#endif /* BCDEC_BC4BC5_PRECISE */++++/* http://graphics.stanford.edu/~seander/bithacks.html#VariableSignExtend */++static int bcdec__extend_sign(int val, int bits) {++ return (val << (32 - bits)) >> (32 - bits);++}++++static int bcdec__transform_inverse(int val, int a0, int bits, int isSigned) {++ /* If the precision of A0 is "p" bits, then the transform algorithm is:++ B0 = (B0 + A0) & ((1 << p) - 1) */++ val = (val + a0) & ((1 << bits) - 1);++ if (isSigned) {++ val = bcdec__extend_sign(val, bits);++ }++ return val;++}++++/* pretty much copy-paste from documentation */++static int bcdec__unquantize(int val, int bits, int isSigned) {++ int unq, s = 0;++++ if (!isSigned) {++ if (bits >= 15) {++ unq = val;++ } else if (!val) {++ unq = 0;++ } else if (val == ((1 << bits) - 1)) {++ unq = 0xFFFF;++ } else {++ unq = ((val << 16) + 0x8000) >> bits;++ }++ } else {++ if (bits >= 16) {++ unq = val;++ } else {++ if (val < 0) {++ s = 1;++ val = -val;++ }++++ if (val == 0) {++ unq = 0;++ } else if (val >= ((1 << (bits - 1)) - 1)) {++ unq = 0x7FFF;++ } else {++ unq = ((val << 15) + 0x4000) >> (bits - 1);++ }++++ if (s) {++ unq = -unq;++ }++ }++ }++ return unq;++}++++static int bcdec__interpolate(int a, int b, int* weights, int index) {++ return (a * (64 - weights[index]) + b * weights[index] + 32) >> 6;++}++++static unsigned short bcdec__finish_unquantize(int val, int isSigned) {++ int s;++++ if (!isSigned) {++ return (unsigned short)((val * 31) >> 6); /* scale the magnitude by 31 / 64 */++ } else {++ val = (val < 0) ? -(((-val) * 31) >> 5) : (val * 31) >> 5; /* scale the magnitude by 31 / 32 */++ s = 0;++ if (val < 0) {++ s = 0x8000;++ val = -val;++ }++ return (unsigned short)(s | val);++ }++}++++/* modified half_to_float_fast4 from https://gist.github.com/rygorous/2144712 */++static float bcdec__half_to_float_quick(unsigned short half) {++ typedef union {++ unsigned int u;++ float f;++ } FP32;++++ static const FP32 magic = { 113 << 23 };++ static const unsigned int shifted_exp = 0x7c00 << 13; /* exponent mask after shift */++ FP32 o;++ unsigned int exp;++++ o.u = (half & 0x7fff) << 13; /* exponent/mantissa bits */++ exp = shifted_exp & o.u; /* just the exponent */++ o.u += (127 - 15) << 23; /* exponent adjust */++++ /* handle exponent special cases */++ if (exp == shifted_exp) { /* Inf/NaN? */++ o.u += (128 - 16) << 23; /* extra exp adjust */++ } else if (exp == 0) { /* Zero/Denormal? */++ o.u += 1 << 23; /* extra exp adjust */++ o.f -= magic.f; /* renormalize */++ }++++ o.u |= (half & 0x8000) << 16; /* sign bit */++ return o.f;++}++++BCDECDEF void bcdec_bc6h_half(const void* compressedBlock, void* decompressedBlock, int destinationPitch, int isSigned) {++ static char actual_bits_count[4][14] = {++ { 10, 7, 11, 11, 11, 9, 8, 8, 8, 6, 10, 11, 12, 16 }, /* W */++ { 5, 6, 5, 4, 4, 5, 6, 5, 5, 6, 10, 9, 8, 4 }, /* dR */++ { 5, 6, 4, 5, 4, 5, 5, 6, 5, 6, 10, 9, 8, 4 }, /* dG */++ { 5, 6, 4, 4, 5, 5, 5, 5, 6, 6, 10, 9, 8, 4 } /* dB */++ };++++ /* There are 32 possible partition sets for a two-region tile.++ Each 4x4 block represents a single shape.++ Here also every fix-up index has MSB bit set. */++ static unsigned char partition_sets[32][4][4] = {++ { {128, 0, 1, 1}, {0, 0, 1, 1}, { 0, 0, 1, 1}, {0, 0, 1, 129} }, /* 0 */++ { {128, 0, 0, 1}, {0, 0, 0, 1}, { 0, 0, 0, 1}, {0, 0, 0, 129} }, /* 1 */++ { {128, 1, 1, 1}, {0, 1, 1, 1}, { 0, 1, 1, 1}, {0, 1, 1, 129} }, /* 2 */++ { {128, 0, 0, 1}, {0, 0, 1, 1}, { 0, 0, 1, 1}, {0, 1, 1, 129} }, /* 3 */++ { {128, 0, 0, 0}, {0, 0, 0, 1}, { 0, 0, 0, 1}, {0, 0, 1, 129} }, /* 4 */++ { {128, 0, 1, 1}, {0, 1, 1, 1}, { 0, 1, 1, 1}, {1, 1, 1, 129} }, /* 5 */++ { {128, 0, 0, 1}, {0, 0, 1, 1}, { 0, 1, 1, 1}, {1, 1, 1, 129} }, /* 6 */++ { {128, 0, 0, 0}, {0, 0, 0, 1}, { 0, 0, 1, 1}, {0, 1, 1, 129} }, /* 7 */++ { {128, 0, 0, 0}, {0, 0, 0, 0}, { 0, 0, 0, 1}, {0, 0, 1, 129} }, /* 8 */++ { {128, 0, 1, 1}, {0, 1, 1, 1}, { 1, 1, 1, 1}, {1, 1, 1, 129} }, /* 9 */++ { {128, 0, 0, 0}, {0, 0, 0, 1}, { 0, 1, 1, 1}, {1, 1, 1, 129} }, /* 10 */++ { {128, 0, 0, 0}, {0, 0, 0, 0}, { 0, 0, 0, 1}, {0, 1, 1, 129} }, /* 11 */++ { {128, 0, 0, 1}, {0, 1, 1, 1}, { 1, 1, 1, 1}, {1, 1, 1, 129} }, /* 12 */++ { {128, 0, 0, 0}, {0, 0, 0, 0}, { 1, 1, 1, 1}, {1, 1, 1, 129} }, /* 13 */++ { {128, 0, 0, 0}, {1, 1, 1, 1}, { 1, 1, 1, 1}, {1, 1, 1, 129} }, /* 14 */++ { {128, 0, 0, 0}, {0, 0, 0, 0}, { 0, 0, 0, 0}, {1, 1, 1, 129} }, /* 15 */++ { {128, 0, 0, 0}, {1, 0, 0, 0}, { 1, 1, 1, 0}, {1, 1, 1, 129} }, /* 16 */++ { {128, 1, 129, 1}, {0, 0, 0, 1}, { 0, 0, 0, 0}, {0, 0, 0, 0} }, /* 17 */++ { {128, 0, 0, 0}, {0, 0, 0, 0}, {129, 0, 0, 0}, {1, 1, 1, 0} }, /* 18 */++ { {128, 1, 129, 1}, {0, 0, 1, 1}, { 0, 0, 0, 1}, {0, 0, 0, 0} }, /* 19 */++ { {128, 0, 129, 1}, {0, 0, 0, 1}, { 0, 0, 0, 0}, {0, 0, 0, 0} }, /* 20 */++ { {128, 0, 0, 0}, {1, 0, 0, 0}, {129, 1, 0, 0}, {1, 1, 1, 0} }, /* 21 */++ { {128, 0, 0, 0}, {0, 0, 0, 0}, {129, 0, 0, 0}, {1, 1, 0, 0} }, /* 22 */++ { {128, 1, 1, 1}, {0, 0, 1, 1}, { 0, 0, 1, 1}, {0, 0, 0, 129} }, /* 23 */++ { {128, 0, 129, 1}, {0, 0, 0, 1}, { 0, 0, 0, 1}, {0, 0, 0, 0} }, /* 24 */++ { {128, 0, 0, 0}, {1, 0, 0, 0}, {129, 0, 0, 0}, {1, 1, 0, 0} }, /* 25 */++ { {128, 1, 129, 0}, {0, 1, 1, 0}, { 0, 1, 1, 0}, {0, 1, 1, 0} }, /* 26 */++ { {128, 0, 129, 1}, {0, 1, 1, 0}, { 0, 1, 1, 0}, {1, 1, 0, 0} }, /* 27 */++ { {128, 0, 0, 1}, {0, 1, 1, 1}, {129, 1, 1, 0}, {1, 0, 0, 0} }, /* 28 */++ { {128, 0, 0, 0}, {1, 1, 1, 1}, {129, 1, 1, 1}, {0, 0, 0, 0} }, /* 29 */++ { {128, 1, 129, 1}, {0, 0, 0, 1}, { 1, 0, 0, 0}, {1, 1, 1, 0} }, /* 30 */++ { {128, 0, 129, 1}, {1, 0, 0, 1}, { 1, 0, 0, 1}, {1, 1, 0, 0} } /* 31 */++ };++++ static int aWeight3[8] = { 0, 9, 18, 27, 37, 46, 55, 64 };++ static int aWeight4[16] = { 0, 4, 9, 13, 17, 21, 26, 30, 34, 38, 43, 47, 51, 55, 60, 64 };++++ bcdec__bitstream_t bstream;++ int mode, partition, numPartitions, i, j, partitionSet, indexBits, index, ep_i, actualBits0Mode;++ int r[4], g[4], b[4]; /* wxyz */++ unsigned short* decompressed;++ int* weights;++++ decompressed = (unsigned short*)decompressedBlock;++++ bstream.low = bcdec__getu64le(compressedBlock);++ bstream.high = bcdec__getu64le((const unsigned char*)compressedBlock + 8);++++ r[0] = r[1] = r[2] = r[3] = 0;++ g[0] = g[1] = g[2] = g[3] = 0;++ b[0] = b[1] = b[2] = b[3] = 0;++++ mode = bcdec__bitstream_read_bits(&bstream, 2);++ if (mode > 1) {++ mode |= (bcdec__bitstream_read_bits(&bstream, 3) << 2);++ }++++ /* modes >= 11 (10 in my code) are using 0 one, others will read it from the bitstream */++ partition = 0;++++ switch (mode) {++ /* mode 1 */++ case 0b00: {++ /* Partitition indices: 46 bits++ Partition: 5 bits++ Color Endpoints: 75 bits (10.555, 10.555, 10.555) */++ g[2] |= bcdec__bitstream_read_bit(&bstream) << 4; /* gy[4] */++ b[2] |= bcdec__bitstream_read_bit(&bstream) << 4; /* by[4] */++ b[3] |= bcdec__bitstream_read_bit(&bstream) << 4; /* bz[4] */++ r[0] |= bcdec__bitstream_read_bits(&bstream, 10); /* rw[9:0] */++ g[0] |= bcdec__bitstream_read_bits(&bstream, 10); /* gw[9:0] */++ b[0] |= bcdec__bitstream_read_bits(&bstream, 10); /* bw[9:0] */++ r[1] |= bcdec__bitstream_read_bits(&bstream, 5); /* rx[4:0] */++ g[3] |= bcdec__bitstream_read_bit(&bstream) << 4; /* gz[4] */++ g[2] |= bcdec__bitstream_read_bits(&bstream, 4); /* gy[3:0] */++ g[1] |= bcdec__bitstream_read_bits(&bstream, 5); /* gx[4:0] */++ b[3] |= bcdec__bitstream_read_bit(&bstream); /* bz[0] */++ g[3] |= bcdec__bitstream_read_bits(&bstream, 4); /* gz[3:0] */++ b[1] |= bcdec__bitstream_read_bits(&bstream, 5); /* bx[4:0] */++ b[3] |= bcdec__bitstream_read_bit(&bstream) << 1; /* bz[1] */++ b[2] |= bcdec__bitstream_read_bits(&bstream, 4); /* by[3:0] */++ r[2] |= bcdec__bitstream_read_bits(&bstream, 5); /* ry[4:0] */++ b[3] |= bcdec__bitstream_read_bit(&bstream) << 2; /* bz[2] */++ r[3] |= bcdec__bitstream_read_bits(&bstream, 5); /* rz[4:0] */++ b[3] |= bcdec__bitstream_read_bit(&bstream) << 3; /* bz[3] */++ partition = bcdec__bitstream_read_bits(&bstream, 5); /* d[4:0] */++ mode = 0;++ } break;++++ /* mode 2 */++ case 0b01: {++ /* Partitition indices: 46 bits++ Partition: 5 bits++ Color Endpoints: 75 bits (7666, 7666, 7666) */++ g[2] |= bcdec__bitstream_read_bit(&bstream) << 5; /* gy[5] */++ g[3] |= bcdec__bitstream_read_bit(&bstream) << 4; /* gz[4] */++ g[3] |= bcdec__bitstream_read_bit(&bstream) << 5; /* gz[5] */++ r[0] |= bcdec__bitstream_read_bits(&bstream, 7); /* rw[6:0] */++ b[3] |= bcdec__bitstream_read_bit(&bstream); /* bz[0] */++ b[3] |= bcdec__bitstream_read_bit(&bstream) << 1; /* bz[1] */++ b[2] |= bcdec__bitstream_read_bit(&bstream) << 4; /* by[4] */++ g[0] |= bcdec__bitstream_read_bits(&bstream, 7); /* gw[6:0] */++ b[2] |= bcdec__bitstream_read_bit(&bstream) << 5; /* by[5] */++ b[3] |= bcdec__bitstream_read_bit(&bstream) << 2; /* bz[2] */++ g[2] |= bcdec__bitstream_read_bit(&bstream) << 4; /* gy[4] */++ b[0] |= bcdec__bitstream_read_bits(&bstream, 7); /* bw[6:0] */++ b[3] |= bcdec__bitstream_read_bit(&bstream) << 3; /* bz[3] */++ b[3] |= bcdec__bitstream_read_bit(&bstream) << 5; /* bz[5] */++ b[3] |= bcdec__bitstream_read_bit(&bstream) << 4; /* bz[4] */++ r[1] |= bcdec__bitstream_read_bits(&bstream, 6); /* rx[5:0] */++ g[2] |= bcdec__bitstream_read_bits(&bstream, 4); /* gy[3:0] */++ g[1] |= bcdec__bitstream_read_bits(&bstream, 6); /* gx[5:0] */++ g[3] |= bcdec__bitstream_read_bits(&bstream, 4); /* gz[3:0] */++ b[1] |= bcdec__bitstream_read_bits(&bstream, 6); /* bx[5:0] */++ b[2] |= bcdec__bitstream_read_bits(&bstream, 4); /* by[3:0] */++ r[2] |= bcdec__bitstream_read_bits(&bstream, 6); /* ry[5:0] */++ r[3] |= bcdec__bitstream_read_bits(&bstream, 6); /* rz[5:0] */++ partition = bcdec__bitstream_read_bits(&bstream, 5); /* d[4:0] */++ mode = 1;++ } break;++++ /* mode 3 */++ case 0b00010: {++ /* Partitition indices: 46 bits++ Partition: 5 bits++ Color Endpoints: 72 bits (11.555, 11.444, 11.444) */++ r[0] |= bcdec__bitstream_read_bits(&bstream, 10); /* rw[9:0] */++ g[0] |= bcdec__bitstream_read_bits(&bstream, 10); /* gw[9:0] */++ b[0] |= bcdec__bitstream_read_bits(&bstream, 10); /* bw[9:0] */++ r[1] |= bcdec__bitstream_read_bits(&bstream, 5); /* rx[4:0] */++ r[0] |= bcdec__bitstream_read_bit(&bstream) << 10; /* rw[10] */++ g[2] |= bcdec__bitstream_read_bits(&bstream, 4); /* gy[3:0] */++ g[1] |= bcdec__bitstream_read_bits(&bstream, 4); /* gx[3:0] */++ g[0] |= bcdec__bitstream_read_bit(&bstream) << 10; /* gw[10] */++ b[3] |= bcdec__bitstream_read_bit(&bstream); /* bz[0] */++ g[3] |= bcdec__bitstream_read_bits(&bstream, 4); /* gz[3:0] */++ b[1] |= bcdec__bitstream_read_bits(&bstream, 4); /* bx[3:0] */++ b[0] |= bcdec__bitstream_read_bit(&bstream) << 10; /* bw[10] */++ b[3] |= bcdec__bitstream_read_bit(&bstream) << 1; /* bz[1] */++ b[2] |= bcdec__bitstream_read_bits(&bstream, 4); /* by[3:0] */++ r[2] |= bcdec__bitstream_read_bits(&bstream, 5); /* ry[4:0] */++ b[3] |= bcdec__bitstream_read_bit(&bstream) << 2; /* bz[2] */++ r[3] |= bcdec__bitstream_read_bits(&bstream, 5); /* rz[4:0] */++ b[3] |= bcdec__bitstream_read_bit(&bstream) << 3; /* bz[3] */++ partition = bcdec__bitstream_read_bits(&bstream, 5); /* d[4:0] */++ mode = 2;++ } break;++++ /* mode 4 */++ case 0b00110: {++ /* Partitition indices: 46 bits++ Partition: 5 bits++ Color Endpoints: 72 bits (11.444, 11.555, 11.444) */++ r[0] |= bcdec__bitstream_read_bits(&bstream, 10); /* rw[9:0] */++ g[0] |= bcdec__bitstream_read_bits(&bstream, 10); /* gw[9:0] */++ b[0] |= bcdec__bitstream_read_bits(&bstream, 10); /* bw[9:0] */++ r[1] |= bcdec__bitstream_read_bits(&bstream, 4); /* rx[3:0] */++ r[0] |= bcdec__bitstream_read_bit(&bstream) << 10; /* rw[10] */++ g[3] |= bcdec__bitstream_read_bit(&bstream) << 4; /* gz[4] */++ g[2] |= bcdec__bitstream_read_bits(&bstream, 4); /* gy[3:0] */++ g[1] |= bcdec__bitstream_read_bits(&bstream, 5); /* gx[4:0] */++ g[0] |= bcdec__bitstream_read_bit(&bstream) << 10; /* gw[10] */++ g[3] |= bcdec__bitstream_read_bits(&bstream, 4); /* gz[3:0] */++ b[1] |= bcdec__bitstream_read_bits(&bstream, 4); /* bx[3:0] */++ b[0] |= bcdec__bitstream_read_bit(&bstream) << 10; /* bw[10] */++ b[3] |= bcdec__bitstream_read_bit(&bstream) << 1; /* bz[1] */++ b[2] |= bcdec__bitstream_read_bits(&bstream, 4); /* by[3:0] */++ r[2] |= bcdec__bitstream_read_bits(&bstream, 4); /* ry[3:0] */++ b[3] |= bcdec__bitstream_read_bit(&bstream); /* bz[0] */++ b[3] |= bcdec__bitstream_read_bit(&bstream) << 2; /* bz[2] */++ r[3] |= bcdec__bitstream_read_bits(&bstream, 4); /* rz[3:0] */++ g[2] |= bcdec__bitstream_read_bit(&bstream) << 4; /* gy[4] */++ b[3] |= bcdec__bitstream_read_bit(&bstream) << 3; /* bz[3] */++ partition = bcdec__bitstream_read_bits(&bstream, 5); /* d[4:0] */++ mode = 3;++ } break;++++ /* mode 5 */++ case 0b01010: {++ /* Partitition indices: 46 bits++ Partition: 5 bits++ Color Endpoints: 72 bits (11.444, 11.444, 11.555) */++ r[0] |= bcdec__bitstream_read_bits(&bstream, 10); /* rw[9:0] */++ g[0] |= bcdec__bitstream_read_bits(&bstream, 10); /* gw[9:0] */++ b[0] |= bcdec__bitstream_read_bits(&bstream, 10); /* bw[9:0] */++ r[1] |= bcdec__bitstream_read_bits(&bstream, 4); /* rx[3:0] */++ r[0] |= bcdec__bitstream_read_bit(&bstream) << 10; /* rw[10] */++ b[2] |= bcdec__bitstream_read_bit(&bstream) << 4; /* by[4] */++ g[2] |= bcdec__bitstream_read_bits(&bstream, 4); /* gy[3:0] */++ g[1] |= bcdec__bitstream_read_bits(&bstream, 4); /* gx[3:0] */++ g[0] |= bcdec__bitstream_read_bit(&bstream) << 10; /* gw[10] */++ b[3] |= bcdec__bitstream_read_bit(&bstream); /* bz[0] */++ g[3] |= bcdec__bitstream_read_bits(&bstream, 4); /* gz[3:0] */++ b[1] |= bcdec__bitstream_read_bits(&bstream, 5); /* bx[4:0] */++ b[0] |= bcdec__bitstream_read_bit(&bstream) << 10; /* bw[10] */++ b[2] |= bcdec__bitstream_read_bits(&bstream, 4); /* by[3:0] */++ r[2] |= bcdec__bitstream_read_bits(&bstream, 4); /* ry[3:0] */++ b[3] |= bcdec__bitstream_read_bit(&bstream) << 1; /* bz[1] */++ b[3] |= bcdec__bitstream_read_bit(&bstream) << 2; /* bz[2] */++ r[3] |= bcdec__bitstream_read_bits(&bstream, 4); /* rz[3:0] */++ b[3] |= bcdec__bitstream_read_bit(&bstream) << 4; /* bz[4] */++ b[3] |= bcdec__bitstream_read_bit(&bstream) << 3; /* bz[3] */++ partition = bcdec__bitstream_read_bits(&bstream, 5); /* d[4:0] */++ mode = 4;++ } break;++++ /* mode 6 */++ case 0b01110: {++ /* Partitition indices: 46 bits++ Partition: 5 bits++ Color Endpoints: 72 bits (9555, 9555, 9555) */++ r[0] |= bcdec__bitstream_read_bits(&bstream, 9); /* rw[8:0] */++ b[2] |= bcdec__bitstream_read_bit(&bstream) << 4; /* by[4] */++ g[0] |= bcdec__bitstream_read_bits(&bstream, 9); /* gw[8:0] */++ g[2] |= bcdec__bitstream_read_bit(&bstream) << 4; /* gy[4] */++ b[0] |= bcdec__bitstream_read_bits(&bstream, 9); /* bw[8:0] */++ b[3] |= bcdec__bitstream_read_bit(&bstream) << 4; /* bz[4] */++ r[1] |= bcdec__bitstream_read_bits(&bstream, 5); /* rx[4:0] */++ g[3] |= bcdec__bitstream_read_bit(&bstream) << 4; /* gz[4] */++ g[2] |= bcdec__bitstream_read_bits(&bstream, 4); /* gy[3:0] */++ g[1] |= bcdec__bitstream_read_bits(&bstream, 5); /* gx[4:0] */++ b[3] |= bcdec__bitstream_read_bit(&bstream); /* bz[0] */++ g[3] |= bcdec__bitstream_read_bits(&bstream, 4); /* gx[3:0] */++ b[1] |= bcdec__bitstream_read_bits(&bstream, 5); /* bx[4:0] */++ b[3] |= bcdec__bitstream_read_bit(&bstream) << 1; /* bz[1] */++ b[2] |= bcdec__bitstream_read_bits(&bstream, 4); /* by[3:0] */++ r[2] |= bcdec__bitstream_read_bits(&bstream, 5); /* ry[4:0] */++ b[3] |= bcdec__bitstream_read_bit(&bstream) << 2; /* bz[2] */++ r[3] |= bcdec__bitstream_read_bits(&bstream, 5); /* rz[4:0] */++ b[3] |= bcdec__bitstream_read_bit(&bstream) << 3; /* bz[3] */++ partition = bcdec__bitstream_read_bits(&bstream, 5); /* d[4:0] */++ mode = 5;++ } break;++++ /* mode 7 */++ case 0b10010: {++ /* Partitition indices: 46 bits++ Partition: 5 bits++ Color Endpoints: 72 bits (8666, 8555, 8555) */++ r[0] |= bcdec__bitstream_read_bits(&bstream, 8); /* rw[7:0] */++ g[3] |= bcdec__bitstream_read_bit(&bstream) << 4; /* gz[4] */++ b[2] |= bcdec__bitstream_read_bit(&bstream) << 4; /* by[4] */++ g[0] |= bcdec__bitstream_read_bits(&bstream, 8); /* gw[7:0] */++ b[3] |= bcdec__bitstream_read_bit(&bstream) << 2; /* bz[2] */++ g[2] |= bcdec__bitstream_read_bit(&bstream) << 4; /* gy[4] */++ b[0] |= bcdec__bitstream_read_bits(&bstream, 8); /* bw[7:0] */++ b[3] |= bcdec__bitstream_read_bit(&bstream) << 3; /* bz[3] */++ b[3] |= bcdec__bitstream_read_bit(&bstream) << 4; /* bz[4] */++ r[1] |= bcdec__bitstream_read_bits(&bstream, 6); /* rx[5:0] */++ g[2] |= bcdec__bitstream_read_bits(&bstream, 4); /* gy[3:0] */++ g[1] |= bcdec__bitstream_read_bits(&bstream, 5); /* gx[4:0] */++ b[3] |= bcdec__bitstream_read_bit(&bstream); /* bz[0] */++ g[3] |= bcdec__bitstream_read_bits(&bstream, 4); /* gz[3:0] */++ b[1] |= bcdec__bitstream_read_bits(&bstream, 5); /* bx[4:0] */++ b[3] |= bcdec__bitstream_read_bit(&bstream) << 1; /* bz[1] */++ b[2] |= bcdec__bitstream_read_bits(&bstream, 4); /* by[3:0] */++ r[2] |= bcdec__bitstream_read_bits(&bstream, 6); /* ry[5:0] */++ r[3] |= bcdec__bitstream_read_bits(&bstream, 6); /* rz[5:0] */++ partition = bcdec__bitstream_read_bits(&bstream, 5); /* d[4:0] */++ mode = 6;++ } break;++++ /* mode 8 */++ case 0b10110: {++ /* Partitition indices: 46 bits++ Partition: 5 bits++ Color Endpoints: 72 bits (8555, 8666, 8555) */++ r[0] |= bcdec__bitstream_read_bits(&bstream, 8); /* rw[7:0] */++ b[3] |= bcdec__bitstream_read_bit(&bstream); /* bz[0] */++ b[2] |= bcdec__bitstream_read_bit(&bstream) << 4; /* by[4] */++ g[0] |= bcdec__bitstream_read_bits(&bstream, 8); /* gw[7:0] */++ g[2] |= bcdec__bitstream_read_bit(&bstream) << 5; /* gy[5] */++ g[2] |= bcdec__bitstream_read_bit(&bstream) << 4; /* gy[4] */++ b[0] |= bcdec__bitstream_read_bits(&bstream, 8); /* bw[7:0] */++ g[3] |= bcdec__bitstream_read_bit(&bstream) << 5; /* gz[5] */++ b[3] |= bcdec__bitstream_read_bit(&bstream) << 4; /* bz[4] */++ r[1] |= bcdec__bitstream_read_bits(&bstream, 5); /* rx[4:0] */++ g[3] |= bcdec__bitstream_read_bit(&bstream) << 4; /* gz[4] */++ g[2] |= bcdec__bitstream_read_bits(&bstream, 4); /* gy[3:0] */++ g[1] |= bcdec__bitstream_read_bits(&bstream, 6); /* gx[5:0] */++ g[3] |= bcdec__bitstream_read_bits(&bstream, 4); /* zx[3:0] */++ b[1] |= bcdec__bitstream_read_bits(&bstream, 5); /* bx[4:0] */++ b[3] |= bcdec__bitstream_read_bit(&bstream) << 1; /* bz[1] */++ b[2] |= bcdec__bitstream_read_bits(&bstream, 4); /* by[3:0] */++ r[2] |= bcdec__bitstream_read_bits(&bstream, 5); /* ry[4:0] */++ b[3] |= bcdec__bitstream_read_bit(&bstream) << 2; /* bz[2] */++ r[3] |= bcdec__bitstream_read_bits(&bstream, 5); /* rz[4:0] */++ b[3] |= bcdec__bitstream_read_bit(&bstream) << 3; /* bz[3] */++ partition = bcdec__bitstream_read_bits(&bstream, 5); /* d[4:0] */++ mode = 7;++ } break;++++ /* mode 9 */++ case 0b11010: {++ /* Partitition indices: 46 bits++ Partition: 5 bits++ Color Endpoints: 72 bits (8555, 8555, 8666) */++ r[0] |= bcdec__bitstream_read_bits(&bstream, 8); /* rw[7:0] */++ b[3] |= bcdec__bitstream_read_bit(&bstream) << 1; /* bz[1] */++ b[2] |= bcdec__bitstream_read_bit(&bstream) << 4; /* by[4] */++ g[0] |= bcdec__bitstream_read_bits(&bstream, 8); /* gw[7:0] */++ b[2] |= bcdec__bitstream_read_bit(&bstream) << 5; /* by[5] */++ g[2] |= bcdec__bitstream_read_bit(&bstream) << 4; /* gy[4] */++ b[0] |= bcdec__bitstream_read_bits(&bstream, 8); /* bw[7:0] */++ b[3] |= bcdec__bitstream_read_bit(&bstream) << 5; /* bz[5] */++ b[3] |= bcdec__bitstream_read_bit(&bstream) << 4; /* bz[4] */++ r[1] |= bcdec__bitstream_read_bits(&bstream, 5); /* bw[4:0] */++ g[3] |= bcdec__bitstream_read_bit(&bstream) << 4; /* gz[4] */++ g[2] |= bcdec__bitstream_read_bits(&bstream, 4); /* gy[3:0] */++ g[1] |= bcdec__bitstream_read_bits(&bstream, 5); /* gx[4:0] */++ b[3] |= bcdec__bitstream_read_bit(&bstream); /* bz[0] */++ g[3] |= bcdec__bitstream_read_bits(&bstream, 4); /* gz[3:0] */++ b[1] |= bcdec__bitstream_read_bits(&bstream, 6); /* bx[5:0] */++ b[2] |= bcdec__bitstream_read_bits(&bstream, 4); /* by[3:0] */++ r[2] |= bcdec__bitstream_read_bits(&bstream, 5); /* ry[4:0] */++ b[3] |= bcdec__bitstream_read_bit(&bstream) << 2; /* bz[2] */++ r[3] |= bcdec__bitstream_read_bits(&bstream, 5); /* rz[4:0] */++ b[3] |= bcdec__bitstream_read_bit(&bstream) << 3; /* bz[3] */++ partition = bcdec__bitstream_read_bits(&bstream, 5); /* d[4:0] */++ mode = 8;++ } break;++++ /* mode 10 */++ case 0b11110: {++ /* Partitition indices: 46 bits++ Partition: 5 bits++ Color Endpoints: 72 bits (6666, 6666, 6666) */++ r[0] |= bcdec__bitstream_read_bits(&bstream, 6); /* rw[5:0] */++ g[3] |= bcdec__bitstream_read_bit(&bstream) << 4; /* gz[4] */++ b[3] |= bcdec__bitstream_read_bit(&bstream); /* bz[0] */++ b[3] |= bcdec__bitstream_read_bit(&bstream) << 1; /* bz[1] */++ b[2] |= bcdec__bitstream_read_bit(&bstream) << 4; /* by[4] */++ g[0] |= bcdec__bitstream_read_bits(&bstream, 6); /* gw[5:0] */++ g[2] |= bcdec__bitstream_read_bit(&bstream) << 5; /* gy[5] */++ b[2] |= bcdec__bitstream_read_bit(&bstream) << 5; /* by[5] */++ b[3] |= bcdec__bitstream_read_bit(&bstream) << 2; /* bz[2] */++ g[2] |= bcdec__bitstream_read_bit(&bstream) << 4; /* gy[4] */++ b[0] |= bcdec__bitstream_read_bits(&bstream, 6); /* bw[5:0] */++ g[3] |= bcdec__bitstream_read_bit(&bstream) << 5; /* gz[5] */++ b[3] |= bcdec__bitstream_read_bit(&bstream) << 3; /* bz[3] */++ b[3] |= bcdec__bitstream_read_bit(&bstream) << 5; /* bz[5] */++ b[3] |= bcdec__bitstream_read_bit(&bstream) << 4; /* bz[4] */++ r[1] |= bcdec__bitstream_read_bits(&bstream, 6); /* rx[5:0] */++ g[2] |= bcdec__bitstream_read_bits(&bstream, 4); /* gy[3:0] */++ g[1] |= bcdec__bitstream_read_bits(&bstream, 6); /* gx[5:0] */++ g[3] |= bcdec__bitstream_read_bits(&bstream, 4); /* gz[3:0] */++ b[1] |= bcdec__bitstream_read_bits(&bstream, 6); /* bx[5:0] */++ b[2] |= bcdec__bitstream_read_bits(&bstream, 4); /* by[3:0] */++ r[2] |= bcdec__bitstream_read_bits(&bstream, 6); /* ry[5:0] */++ r[3] |= bcdec__bitstream_read_bits(&bstream, 6); /* rz[5:0] */++ partition = bcdec__bitstream_read_bits(&bstream, 5); /* d[4:0] */++ mode = 9;++ } break;++++ /* mode 11 */++ case 0b00011: {++ /* Partitition indices: 63 bits++ Partition: 0 bits++ Color Endpoints: 60 bits (10.10, 10.10, 10.10) */++ r[0] |= bcdec__bitstream_read_bits(&bstream, 10); /* rw[9:0] */++ g[0] |= bcdec__bitstream_read_bits(&bstream, 10); /* gw[9:0] */++ b[0] |= bcdec__bitstream_read_bits(&bstream, 10); /* bw[9:0] */++ r[1] |= bcdec__bitstream_read_bits(&bstream, 10); /* rx[9:0] */++ g[1] |= bcdec__bitstream_read_bits(&bstream, 10); /* gx[9:0] */++ b[1] |= bcdec__bitstream_read_bits(&bstream, 10); /* bx[9:0] */++ mode = 10;++ } break;++++ /* mode 12 */++ case 0b00111: {++ /* Partitition indices: 63 bits++ Partition: 0 bits++ Color Endpoints: 60 bits (11.9, 11.9, 11.9) */++ r[0] |= bcdec__bitstream_read_bits(&bstream, 10); /* rw[9:0] */++ g[0] |= bcdec__bitstream_read_bits(&bstream, 10); /* gw[9:0] */++ b[0] |= bcdec__bitstream_read_bits(&bstream, 10); /* bw[9:0] */++ r[1] |= bcdec__bitstream_read_bits(&bstream, 9); /* rx[8:0] */++ r[0] |= bcdec__bitstream_read_bit(&bstream) << 10; /* rw[10] */++ g[1] |= bcdec__bitstream_read_bits(&bstream, 9); /* gx[8:0] */++ g[0] |= bcdec__bitstream_read_bit(&bstream) << 10; /* gw[10] */++ b[1] |= bcdec__bitstream_read_bits(&bstream, 9); /* bx[8:0] */++ b[0] |= bcdec__bitstream_read_bit(&bstream) << 10; /* bw[10] */++ mode = 11;++ } break;++++ /* mode 13 */++ case 0b01011: {++ /* Partitition indices: 63 bits++ Partition: 0 bits++ Color Endpoints: 60 bits (12.8, 12.8, 12.8) */++ r[0] |= bcdec__bitstream_read_bits(&bstream, 10); /* rw[9:0] */++ g[0] |= bcdec__bitstream_read_bits(&bstream, 10); /* gw[9:0] */++ b[0] |= bcdec__bitstream_read_bits(&bstream, 10); /* bw[9:0] */++ r[1] |= bcdec__bitstream_read_bits(&bstream, 8); /* rx[7:0] */++ r[0] |= bcdec__bitstream_read_bits_r(&bstream, 2) << 10;/* rx[10:11] */++ g[1] |= bcdec__bitstream_read_bits(&bstream, 8); /* gx[7:0] */++ g[0] |= bcdec__bitstream_read_bits_r(&bstream, 2) << 10;/* gx[10:11] */++ b[1] |= bcdec__bitstream_read_bits(&bstream, 8); /* bx[7:0] */++ b[0] |= bcdec__bitstream_read_bits_r(&bstream, 2) << 10;/* bx[10:11] */++ mode = 12;++ } break;++++ /* mode 14 */++ case 0b01111: {++ /* Partitition indices: 63 bits++ Partition: 0 bits++ Color Endpoints: 60 bits (16.4, 16.4, 16.4) */++ r[0] |= bcdec__bitstream_read_bits(&bstream, 10); /* rw[9:0] */++ g[0] |= bcdec__bitstream_read_bits(&bstream, 10); /* gw[9:0] */++ b[0] |= bcdec__bitstream_read_bits(&bstream, 10); /* bw[9:0] */++ r[1] |= bcdec__bitstream_read_bits(&bstream, 4); /* rx[3:0] */++ r[0] |= bcdec__bitstream_read_bits_r(&bstream, 6) << 10;/* rw[10:15] */++ g[1] |= bcdec__bitstream_read_bits(&bstream, 4); /* gx[3:0] */++ g[0] |= bcdec__bitstream_read_bits_r(&bstream, 6) << 10;/* gw[10:15] */++ b[1] |= bcdec__bitstream_read_bits(&bstream, 4); /* bx[3:0] */++ b[0] |= bcdec__bitstream_read_bits_r(&bstream, 6) << 10;/* bw[10:15] */++ mode = 13;++ } break;++++ default: {++ /* Modes 10011, 10111, 11011, and 11111 (not shown) are reserved.++ Do not use these in your encoder. If the hardware is passed blocks++ with one of these modes specified, the resulting decompressed block++ must contain all zeroes in all channels except for the alpha channel. */++ for (i = 0; i < 4; ++i) {++ for (j = 0; j < 4; ++j) {++ decompressed[j * 3 + 0] = 0;++ decompressed[j * 3 + 1] = 0;++ decompressed[j * 3 + 2] = 0;++ }++ decompressed += destinationPitch;++ }++++ return;++ }++ }++++ numPartitions = (mode >= 10) ? 0 : 1;++++ actualBits0Mode = actual_bits_count[0][mode];++ if (isSigned) {++ r[0] = bcdec__extend_sign(r[0], actualBits0Mode);++ g[0] = bcdec__extend_sign(g[0], actualBits0Mode);++ b[0] = bcdec__extend_sign(b[0], actualBits0Mode);++ }++++ /* Mode 11 (like Mode 10) does not use delta compression,++ and instead stores both color endpoints explicitly. */++ if ((mode != 9 && mode != 10) || isSigned) {++ for (i = 1; i < (numPartitions + 1) * 2; ++i) {++ r[i] = bcdec__extend_sign(r[i], actual_bits_count[1][mode]);++ g[i] = bcdec__extend_sign(g[i], actual_bits_count[2][mode]);++ b[i] = bcdec__extend_sign(b[i], actual_bits_count[3][mode]);++ }++ }++++ if (mode != 9 && mode != 10) {++ for (i = 1; i < (numPartitions + 1) * 2; ++i) {++ r[i] = bcdec__transform_inverse(r[i], r[0], actualBits0Mode, isSigned);++ g[i] = bcdec__transform_inverse(g[i], g[0], actualBits0Mode, isSigned);++ b[i] = bcdec__transform_inverse(b[i], b[0], actualBits0Mode, isSigned);++ }++ }++++ for (i = 0; i < (numPartitions + 1) * 2; ++i) {++ r[i] = bcdec__unquantize(r[i], actualBits0Mode, isSigned);++ g[i] = bcdec__unquantize(g[i], actualBits0Mode, isSigned);++ b[i] = bcdec__unquantize(b[i], actualBits0Mode, isSigned);++ }++++ weights = (mode >= 10) ? aWeight4 : aWeight3;++ for (i = 0; i < 4; ++i) {++ for (j = 0; j < 4; ++j) {++ partitionSet = (mode >= 10) ? ((i|j) ? 0 : 128) : partition_sets[partition][i][j];++++ indexBits = (mode >= 10) ? 4 : 3;++ /* fix-up index is specified with one less bit */++ /* The fix-up index for subset 0 is always index 0 */++ if (partitionSet & 0x80) {++ indexBits--;++ }++ partitionSet &= 0x01;++++ index = bcdec__bitstream_read_bits(&bstream, indexBits);++++ ep_i = partitionSet * 2;++ decompressed[j * 3 + 0] = bcdec__finish_unquantize(++ bcdec__interpolate(r[ep_i], r[ep_i+1], weights, index), isSigned);++ decompressed[j * 3 + 1] = bcdec__finish_unquantize(++ bcdec__interpolate(g[ep_i], g[ep_i+1], weights, index), isSigned);++ decompressed[j * 3 + 2] = bcdec__finish_unquantize(++ bcdec__interpolate(b[ep_i], b[ep_i+1], weights, index), isSigned);++ }++++ decompressed += destinationPitch;++ }++}++++BCDECDEF void bcdec_bc6h_float(const void* compressedBlock, void* decompressedBlock, int destinationPitch, int isSigned) {++ unsigned short block[16*3];++ float* decompressed;++ const unsigned short* b;++ int i, j;++++ bcdec_bc6h_half(compressedBlock, block, 4*3, isSigned);++ b = block;++ decompressed = (float*)decompressedBlock;++ for (i = 0; i < 4; ++i) {++ for (j = 0; j < 4; ++j) {++ decompressed[j * 3 + 0] = bcdec__half_to_float_quick(*b++);++ decompressed[j * 3 + 1] = bcdec__half_to_float_quick(*b++);++ decompressed[j * 3 + 2] = bcdec__half_to_float_quick(*b++);++ }++ decompressed += destinationPitch;++ }++}++++static void bcdec__swap_values(int* a, int* b) {++ a[0] ^= b[0], b[0] ^= a[0], a[0] ^= b[0];++}++++BCDECDEF void bcdec_bc7(const void* compressedBlock, void* decompressedBlock, int destinationPitch) {++ static char actual_bits_count[2][8] = {++ { 4, 6, 5, 7, 5, 7, 7, 5 }, /* RGBA */++ { 0, 0, 0, 0, 6, 8, 7, 5 }, /* Alpha */++ };++++ /* There are 64 possible partition sets for a two-region tile.++ Each 4x4 block represents a single shape.++ Here also every fix-up index has MSB bit set. */++ static unsigned char partition_sets[2][64][4][4] = {++ { /* Partition table for 2-subset BPTC */++ { {128, 0, 1, 1}, {0, 0, 1, 1}, { 0, 0, 1, 1}, {0, 0, 1, 129} }, /* 0 */++ { {128, 0, 0, 1}, {0, 0, 0, 1}, { 0, 0, 0, 1}, {0, 0, 0, 129} }, /* 1 */++ { {128, 1, 1, 1}, {0, 1, 1, 1}, { 0, 1, 1, 1}, {0, 1, 1, 129} }, /* 2 */++ { {128, 0, 0, 1}, {0, 0, 1, 1}, { 0, 0, 1, 1}, {0, 1, 1, 129} }, /* 3 */++ { {128, 0, 0, 0}, {0, 0, 0, 1}, { 0, 0, 0, 1}, {0, 0, 1, 129} }, /* 4 */++ { {128, 0, 1, 1}, {0, 1, 1, 1}, { 0, 1, 1, 1}, {1, 1, 1, 129} }, /* 5 */++ { {128, 0, 0, 1}, {0, 0, 1, 1}, { 0, 1, 1, 1}, {1, 1, 1, 129} }, /* 6 */++ { {128, 0, 0, 0}, {0, 0, 0, 1}, { 0, 0, 1, 1}, {0, 1, 1, 129} }, /* 7 */++ { {128, 0, 0, 0}, {0, 0, 0, 0}, { 0, 0, 0, 1}, {0, 0, 1, 129} }, /* 8 */++ { {128, 0, 1, 1}, {0, 1, 1, 1}, { 1, 1, 1, 1}, {1, 1, 1, 129} }, /* 9 */++ { {128, 0, 0, 0}, {0, 0, 0, 1}, { 0, 1, 1, 1}, {1, 1, 1, 129} }, /* 10 */++ { {128, 0, 0, 0}, {0, 0, 0, 0}, { 0, 0, 0, 1}, {0, 1, 1, 129} }, /* 11 */++ { {128, 0, 0, 1}, {0, 1, 1, 1}, { 1, 1, 1, 1}, {1, 1, 1, 129} }, /* 12 */++ { {128, 0, 0, 0}, {0, 0, 0, 0}, { 1, 1, 1, 1}, {1, 1, 1, 129} }, /* 13 */++ { {128, 0, 0, 0}, {1, 1, 1, 1}, { 1, 1, 1, 1}, {1, 1, 1, 129} }, /* 14 */++ { {128, 0, 0, 0}, {0, 0, 0, 0}, { 0, 0, 0, 0}, {1, 1, 1, 129} }, /* 15 */++ { {128, 0, 0, 0}, {1, 0, 0, 0}, { 1, 1, 1, 0}, {1, 1, 1, 129} }, /* 16 */++ { {128, 1, 129, 1}, {0, 0, 0, 1}, { 0, 0, 0, 0}, {0, 0, 0, 0} }, /* 17 */++ { {128, 0, 0, 0}, {0, 0, 0, 0}, {129, 0, 0, 0}, {1, 1, 1, 0} }, /* 18 */++ { {128, 1, 129, 1}, {0, 0, 1, 1}, { 0, 0, 0, 1}, {0, 0, 0, 0} }, /* 19 */++ { {128, 0, 129, 1}, {0, 0, 0, 1}, { 0, 0, 0, 0}, {0, 0, 0, 0} }, /* 20 */++ { {128, 0, 0, 0}, {1, 0, 0, 0}, {129, 1, 0, 0}, {1, 1, 1, 0} }, /* 21 */++ { {128, 0, 0, 0}, {0, 0, 0, 0}, {129, 0, 0, 0}, {1, 1, 0, 0} }, /* 22 */++ { {128, 1, 1, 1}, {0, 0, 1, 1}, { 0, 0, 1, 1}, {0, 0, 0, 129} }, /* 23 */++ { {128, 0, 129, 1}, {0, 0, 0, 1}, { 0, 0, 0, 1}, {0, 0, 0, 0} }, /* 24 */++ { {128, 0, 0, 0}, {1, 0, 0, 0}, {129, 0, 0, 0}, {1, 1, 0, 0} }, /* 25 */++ { {128, 1, 129, 0}, {0, 1, 1, 0}, { 0, 1, 1, 0}, {0, 1, 1, 0} }, /* 26 */++ { {128, 0, 129, 1}, {0, 1, 1, 0}, { 0, 1, 1, 0}, {1, 1, 0, 0} }, /* 27 */++ { {128, 0, 0, 1}, {0, 1, 1, 1}, {129, 1, 1, 0}, {1, 0, 0, 0} }, /* 28 */++ { {128, 0, 0, 0}, {1, 1, 1, 1}, {129, 1, 1, 1}, {0, 0, 0, 0} }, /* 29 */++ { {128, 1, 129, 1}, {0, 0, 0, 1}, { 1, 0, 0, 0}, {1, 1, 1, 0} }, /* 30 */++ { {128, 0, 129, 1}, {1, 0, 0, 1}, { 1, 0, 0, 1}, {1, 1, 0, 0} }, /* 31 */++ { {128, 1, 0, 1}, {0, 1, 0, 1}, { 0, 1, 0, 1}, {0, 1, 0, 129} }, /* 32 */++ { {128, 0, 0, 0}, {1, 1, 1, 1}, { 0, 0, 0, 0}, {1, 1, 1, 129} }, /* 33 */++ { {128, 1, 0, 1}, {1, 0, 129, 0}, { 0, 1, 0, 1}, {1, 0, 1, 0} }, /* 34 */++ { {128, 0, 1, 1}, {0, 0, 1, 1}, {129, 1, 0, 0}, {1, 1, 0, 0} }, /* 35 */++ { {128, 0, 129, 1}, {1, 1, 0, 0}, { 0, 0, 1, 1}, {1, 1, 0, 0} }, /* 36 */++ { {128, 1, 0, 1}, {0, 1, 0, 1}, {129, 0, 1, 0}, {1, 0, 1, 0} }, /* 37 */++ { {128, 1, 1, 0}, {1, 0, 0, 1}, { 0, 1, 1, 0}, {1, 0, 0, 129} }, /* 38 */++ { {128, 1, 0, 1}, {1, 0, 1, 0}, { 1, 0, 1, 0}, {0, 1, 0, 129} }, /* 39 */++ { {128, 1, 129, 1}, {0, 0, 1, 1}, { 1, 1, 0, 0}, {1, 1, 1, 0} }, /* 40 */++ { {128, 0, 0, 1}, {0, 0, 1, 1}, {129, 1, 0, 0}, {1, 0, 0, 0} }, /* 41 */++ { {128, 0, 129, 1}, {0, 0, 1, 0}, { 0, 1, 0, 0}, {1, 1, 0, 0} }, /* 42 */++ { {128, 0, 129, 1}, {1, 0, 1, 1}, { 1, 1, 0, 1}, {1, 1, 0, 0} }, /* 43 */++ { {128, 1, 129, 0}, {1, 0, 0, 1}, { 1, 0, 0, 1}, {0, 1, 1, 0} }, /* 44 */++ { {128, 0, 1, 1}, {1, 1, 0, 0}, { 1, 1, 0, 0}, {0, 0, 1, 129} }, /* 45 */++ { {128, 1, 1, 0}, {0, 1, 1, 0}, { 1, 0, 0, 1}, {1, 0, 0, 129} }, /* 46 */++ { {128, 0, 0, 0}, {0, 1, 129, 0}, { 0, 1, 1, 0}, {0, 0, 0, 0} }, /* 47 */++ { {128, 1, 0, 0}, {1, 1, 129, 0}, { 0, 1, 0, 0}, {0, 0, 0, 0} }, /* 48 */++ { {128, 0, 129, 0}, {0, 1, 1, 1}, { 0, 0, 1, 0}, {0, 0, 0, 0} }, /* 49 */++ { {128, 0, 0, 0}, {0, 0, 129, 0}, { 0, 1, 1, 1}, {0, 0, 1, 0} }, /* 50 */++ { {128, 0, 0, 0}, {0, 1, 0, 0}, {129, 1, 1, 0}, {0, 1, 0, 0} }, /* 51 */++ { {128, 1, 1, 0}, {1, 1, 0, 0}, { 1, 0, 0, 1}, {0, 0, 1, 129} }, /* 52 */++ { {128, 0, 1, 1}, {0, 1, 1, 0}, { 1, 1, 0, 0}, {1, 0, 0, 129} }, /* 53 */++ { {128, 1, 129, 0}, {0, 0, 1, 1}, { 1, 0, 0, 1}, {1, 1, 0, 0} }, /* 54 */++ { {128, 0, 129, 1}, {1, 0, 0, 1}, { 1, 1, 0, 0}, {0, 1, 1, 0} }, /* 55 */++ { {128, 1, 1, 0}, {1, 1, 0, 0}, { 1, 1, 0, 0}, {1, 0, 0, 129} }, /* 56 */++ { {128, 1, 1, 0}, {0, 0, 1, 1}, { 0, 0, 1, 1}, {1, 0, 0, 129} }, /* 57 */++ { {128, 1, 1, 1}, {1, 1, 1, 0}, { 1, 0, 0, 0}, {0, 0, 0, 129} }, /* 58 */++ { {128, 0, 0, 1}, {1, 0, 0, 0}, { 1, 1, 1, 0}, {0, 1, 1, 129} }, /* 59 */++ { {128, 0, 0, 0}, {1, 1, 1, 1}, { 0, 0, 1, 1}, {0, 0, 1, 129} }, /* 60 */++ { {128, 0, 129, 1}, {0, 0, 1, 1}, { 1, 1, 1, 1}, {0, 0, 0, 0} }, /* 61 */++ { {128, 0, 129, 0}, {0, 0, 1, 0}, { 1, 1, 1, 0}, {1, 1, 1, 0} }, /* 62 */++ { {128, 1, 0, 0}, {0, 1, 0, 0}, { 0, 1, 1, 1}, {0, 1, 1, 129} } /* 63 */++ },++ { /* Partition table for 3-subset BPTC */++ { {128, 0, 1, 129}, {0, 0, 1, 1}, { 0, 2, 2, 1}, { 2, 2, 2, 130} }, /* 0 */++ { {128, 0, 0, 129}, {0, 0, 1, 1}, {130, 2, 1, 1}, { 2, 2, 2, 1} }, /* 1 */++ { {128, 0, 0, 0}, {2, 0, 0, 1}, {130, 2, 1, 1}, { 2, 2, 1, 129} }, /* 2 */++ { {128, 2, 2, 130}, {0, 0, 2, 2}, { 0, 0, 1, 1}, { 0, 1, 1, 129} }, /* 3 */++ { {128, 0, 0, 0}, {0, 0, 0, 0}, {129, 1, 2, 2}, { 1, 1, 2, 130} }, /* 4 */++ { {128, 0, 1, 129}, {0, 0, 1, 1}, { 0, 0, 2, 2}, { 0, 0, 2, 130} }, /* 5 */++ { {128, 0, 2, 130}, {0, 0, 2, 2}, { 1, 1, 1, 1}, { 1, 1, 1, 129} }, /* 6 */++ { {128, 0, 1, 1}, {0, 0, 1, 1}, {130, 2, 1, 1}, { 2, 2, 1, 129} }, /* 7 */++ { {128, 0, 0, 0}, {0, 0, 0, 0}, {129, 1, 1, 1}, { 2, 2, 2, 130} }, /* 8 */++ { {128, 0, 0, 0}, {1, 1, 1, 1}, {129, 1, 1, 1}, { 2, 2, 2, 130} }, /* 9 */++ { {128, 0, 0, 0}, {1, 1, 129, 1}, { 2, 2, 2, 2}, { 2, 2, 2, 130} }, /* 10 */++ { {128, 0, 1, 2}, {0, 0, 129, 2}, { 0, 0, 1, 2}, { 0, 0, 1, 130} }, /* 11 */++ { {128, 1, 1, 2}, {0, 1, 129, 2}, { 0, 1, 1, 2}, { 0, 1, 1, 130} }, /* 12 */++ { {128, 1, 2, 2}, {0, 129, 2, 2}, { 0, 1, 2, 2}, { 0, 1, 2, 130} }, /* 13 */++ { {128, 0, 1, 129}, {0, 1, 1, 2}, { 1, 1, 2, 2}, { 1, 2, 2, 130} }, /* 14 */++ { {128, 0, 1, 129}, {2, 0, 0, 1}, {130, 2, 0, 0}, { 2, 2, 2, 0} }, /* 15 */++ { {128, 0, 0, 129}, {0, 0, 1, 1}, { 0, 1, 1, 2}, { 1, 1, 2, 130} }, /* 16 */++ { {128, 1, 1, 129}, {0, 0, 1, 1}, {130, 0, 0, 1}, { 2, 2, 0, 0} }, /* 17 */++ { {128, 0, 0, 0}, {1, 1, 2, 2}, {129, 1, 2, 2}, { 1, 1, 2, 130} }, /* 18 */++ { {128, 0, 2, 130}, {0, 0, 2, 2}, { 0, 0, 2, 2}, { 1, 1, 1, 129} }, /* 19 */++ { {128, 1, 1, 129}, {0, 1, 1, 1}, { 0, 2, 2, 2}, { 0, 2, 2, 130} }, /* 20 */++ { {128, 0, 0, 129}, {0, 0, 0, 1}, {130, 2, 2, 1}, { 2, 2, 2, 1} }, /* 21 */++ { {128, 0, 0, 0}, {0, 0, 129, 1}, { 0, 1, 2, 2}, { 0, 1, 2, 130} }, /* 22 */++ { {128, 0, 0, 0}, {1, 1, 0, 0}, {130, 2, 129, 0}, { 2, 2, 1, 0} }, /* 23 */++ { {128, 1, 2, 130}, {0, 129, 2, 2}, { 0, 0, 1, 1}, { 0, 0, 0, 0} }, /* 24 */++ { {128, 0, 1, 2}, {0, 0, 1, 2}, {129, 1, 2, 2}, { 2, 2, 2, 130} }, /* 25 */++ { {128, 1, 1, 0}, {1, 2, 130, 1}, {129, 2, 2, 1}, { 0, 1, 1, 0} }, /* 26 */++ { {128, 0, 0, 0}, {0, 1, 129, 0}, { 1, 2, 130, 1}, { 1, 2, 2, 1} }, /* 27 */++ { {128, 0, 2, 2}, {1, 1, 0, 2}, {129, 1, 0, 2}, { 0, 0, 2, 130} }, /* 28 */++ { {128, 1, 1, 0}, {0, 129, 1, 0}, { 2, 0, 0, 2}, { 2, 2, 2, 130} }, /* 29 */++ { {128, 0, 1, 1}, {0, 1, 2, 2}, { 0, 1, 130, 2}, { 0, 0, 1, 129} }, /* 30 */++ { {128, 0, 0, 0}, {2, 0, 0, 0}, {130, 2, 1, 1}, { 2, 2, 2, 129} }, /* 31 */++ { {128, 0, 0, 0}, {0, 0, 0, 2}, {129, 1, 2, 2}, { 1, 2, 2, 130} }, /* 32 */++ { {128, 2, 2, 130}, {0, 0, 2, 2}, { 0, 0, 1, 2}, { 0, 0, 1, 129} }, /* 33 */++ { {128, 0, 1, 129}, {0, 0, 1, 2}, { 0, 0, 2, 2}, { 0, 2, 2, 130} }, /* 34 */++ { {128, 1, 2, 0}, {0, 129, 2, 0}, { 0, 1, 130, 0}, { 0, 1, 2, 0} }, /* 35 */++ { {128, 0, 0, 0}, {1, 1, 129, 1}, { 2, 2, 130, 2}, { 0, 0, 0, 0} }, /* 36 */++ { {128, 1, 2, 0}, {1, 2, 0, 1}, {130, 0, 129, 2}, { 0, 1, 2, 0} }, /* 37 */++ { {128, 1, 2, 0}, {2, 0, 1, 2}, {129, 130, 0, 1}, { 0, 1, 2, 0} }, /* 38 */++ { {128, 0, 1, 1}, {2, 2, 0, 0}, { 1, 1, 130, 2}, { 0, 0, 1, 129} }, /* 39 */++ { {128, 0, 1, 1}, {1, 1, 130, 2}, { 2, 2, 0, 0}, { 0, 0, 1, 129} }, /* 40 */++ { {128, 1, 0, 129}, {0, 1, 0, 1}, { 2, 2, 2, 2}, { 2, 2, 2, 130} }, /* 41 */++ { {128, 0, 0, 0}, {0, 0, 0, 0}, {130, 1, 2, 1}, { 2, 1, 2, 129} }, /* 42 */++ { {128, 0, 2, 2}, {1, 129, 2, 2}, { 0, 0, 2, 2}, { 1, 1, 2, 130} }, /* 43 */++ { {128, 0, 2, 130}, {0, 0, 1, 1}, { 0, 0, 2, 2}, { 0, 0, 1, 129} }, /* 44 */++ { {128, 2, 2, 0}, {1, 2, 130, 1}, { 0, 2, 2, 0}, { 1, 2, 2, 129} }, /* 45 */++ { {128, 1, 0, 1}, {2, 2, 130, 2}, { 2, 2, 2, 2}, { 0, 1, 0, 129} }, /* 46 */++ { {128, 0, 0, 0}, {2, 1, 2, 1}, {130, 1, 2, 1}, { 2, 1, 2, 129} }, /* 47 */++ { {128, 1, 0, 129}, {0, 1, 0, 1}, { 0, 1, 0, 1}, { 2, 2, 2, 130} }, /* 48 */++ { {128, 2, 2, 130}, {0, 1, 1, 1}, { 0, 2, 2, 2}, { 0, 1, 1, 129} }, /* 49 */++ { {128, 0, 0, 2}, {1, 129, 1, 2}, { 0, 0, 0, 2}, { 1, 1, 1, 130} }, /* 50 */++ { {128, 0, 0, 0}, {2, 129, 1, 2}, { 2, 1, 1, 2}, { 2, 1, 1, 130} }, /* 51 */++ { {128, 2, 2, 2}, {0, 129, 1, 1}, { 0, 1, 1, 1}, { 0, 2, 2, 130} }, /* 52 */++ { {128, 0, 0, 2}, {1, 1, 1, 2}, {129, 1, 1, 2}, { 0, 0, 0, 130} }, /* 53 */++ { {128, 1, 1, 0}, {0, 129, 1, 0}, { 0, 1, 1, 0}, { 2, 2, 2, 130} }, /* 54 */++ { {128, 0, 0, 0}, {0, 0, 0, 0}, { 2, 1, 129, 2}, { 2, 1, 1, 130} }, /* 55 */++ { {128, 1, 1, 0}, {0, 129, 1, 0}, { 2, 2, 2, 2}, { 2, 2, 2, 130} }, /* 56 */++ { {128, 0, 2, 2}, {0, 0, 1, 1}, { 0, 0, 129, 1}, { 0, 0, 2, 130} }, /* 57 */++ { {128, 0, 2, 2}, {1, 1, 2, 2}, {129, 1, 2, 2}, { 0, 0, 2, 130} }, /* 58 */++ { {128, 0, 0, 0}, {0, 0, 0, 0}, { 0, 0, 0, 0}, { 2, 129, 1, 130} }, /* 59 */++ { {128, 0, 0, 130}, {0, 0, 0, 1}, { 0, 0, 0, 2}, { 0, 0, 0, 129} }, /* 60 */++ { {128, 2, 2, 2}, {1, 2, 2, 2}, { 0, 2, 2, 2}, {129, 2, 2, 130} }, /* 61 */++ { {128, 1, 0, 129}, {2, 2, 2, 2}, { 2, 2, 2, 2}, { 2, 2, 2, 130} }, /* 62 */++ { {128, 1, 1, 129}, {2, 0, 1, 1}, {130, 2, 0, 1}, { 2, 2, 2, 0} } /* 63 */++ }++ };++++ static int aWeight2[] = { 0, 21, 43, 64 };++ static int aWeight3[] = { 0, 9, 18, 27, 37, 46, 55, 64 };++ static int aWeight4[] = { 0, 4, 9, 13, 17, 21, 26, 30, 34, 38, 43, 47, 51, 55, 60, 64 };++++ static unsigned char sModeHasPBits = 0b11001011;++++ bcdec__bitstream_t bstream;++ int mode, partition, numPartitions, numEndpoints, i, j, k, rotation, partitionSet;++ int indexSelectionBit, indexBits, indexBits2, index, index2;++ int endpoints[6][4];++ char indices[4][4];++ int r, g, b, a;++ int* weights, * weights2;++ unsigned char* decompressed;++++ decompressed = (unsigned char*)decompressedBlock;++++ bstream.low = bcdec__getu64le(compressedBlock);++ bstream.high = bcdec__getu64le((const unsigned char*)compressedBlock + 8);++++ for (mode = 0; mode < 8 && (0 == bcdec__bitstream_read_bit(&bstream)); ++mode);++++ /* unexpected mode, clear the block (transparent black) */++ if (mode >= 8) {++ for (i = 0; i < 4; ++i) {++ for (j = 0; j < 4; ++j) {++ decompressed[j * 4 + 0] = 0;++ decompressed[j * 4 + 1] = 0;++ decompressed[j * 4 + 2] = 0;++ decompressed[j * 4 + 3] = 0;++ }++ decompressed += destinationPitch;++ }++++ return;++ }++++ partition = 0;++ numPartitions = 1;++ rotation = 0;++ indexSelectionBit = 0;++++ if (mode == 0 || mode == 1 || mode == 2 || mode == 3 || mode == 7) {++ numPartitions = (mode == 0 || mode == 2) ? 3 : 2;++ partition = bcdec__bitstream_read_bits(&bstream, (mode == 0) ? 4 : 6);++ }++++ numEndpoints = numPartitions * 2;++++ if (mode == 4 || mode == 5) {++ rotation = bcdec__bitstream_read_bits(&bstream, 2);++++ if (mode == 4) {++ indexSelectionBit = bcdec__bitstream_read_bit(&bstream);++ }++ }++++ /* Extract endpoints */++ /* RGB */++ for (i = 0; i < 3; ++i) {++ for (j = 0; j < numEndpoints; ++j) {++ endpoints[j][i] = bcdec__bitstream_read_bits(&bstream, actual_bits_count[0][mode]);++ }++ }++ /* Alpha (if any) */++ if (actual_bits_count[1][mode] > 0) {++ for (j = 0; j < numEndpoints; ++j) {++ endpoints[j][3] = bcdec__bitstream_read_bits(&bstream, actual_bits_count[1][mode]);++ }++ }++++ /* Fully decode endpoints */++ /* First handle modes that have P-bits */++ if (mode == 0 || mode == 1 || mode == 3 || mode == 6 || mode == 7) {++ for (i = 0; i < numEndpoints; ++i) {++ /* component-wise left-shift */++ for (j = 0; j < 4; ++j) {++ endpoints[i][j] <<= 1;++ }++ }++++ /* if P-bit is shared */++ if (mode == 1) {++ i = bcdec__bitstream_read_bit(&bstream);++ j = bcdec__bitstream_read_bit(&bstream);++++ /* rgb component-wise insert pbits */++ for (k = 0; k < 3; ++k) {++ endpoints[0][k] |= i;++ endpoints[1][k] |= i;++ endpoints[2][k] |= j;++ endpoints[3][k] |= j;++ }++ } else if (sModeHasPBits & (1 << mode)) {++ /* unique P-bit per endpoint */++ for (i = 0; i < numEndpoints; ++i) {++ j = bcdec__bitstream_read_bit(&bstream);++ for (k = 0; k < 4; ++k) {++ endpoints[i][k] |= j;++ }++ }++ }++ }++++ for (i = 0; i < numEndpoints; ++i) {++ /* get color components precision including pbit */++ j = actual_bits_count[0][mode] + ((sModeHasPBits >> mode) & 1);++++ for (k = 0; k < 3; ++k) {++ /* left shift endpoint components so that their MSB lies in bit 7 */++ endpoints[i][k] = endpoints[i][k] << (8 - j);++ /* Replicate each component's MSB into the LSBs revealed by the left-shift operation above */++ endpoints[i][k] = endpoints[i][k] | (endpoints[i][k] >> j);++ }++++ /* get alpha component precision including pbit */++ j = actual_bits_count[1][mode] + ((sModeHasPBits >> mode) & 1);++++ /* left shift endpoint components so that their MSB lies in bit 7 */++ endpoints[i][3] = endpoints[i][3] << (8 - j);++ /* Replicate each component's MSB into the LSBs revealed by the left-shift operation above */++ endpoints[i][3] = endpoints[i][3] | (endpoints[i][3] >> j);++ }++++ /* If this mode does not explicitly define the alpha component */++ /* set alpha equal to 1.0 */++ if (!actual_bits_count[1][mode]) {++ for (j = 0; j < numEndpoints; ++j) {++ endpoints[j][3] = 0xFF;++ }++ }++++ /* Determine weights tables */++ indexBits = (mode == 0 || mode == 1) ? 3 : ((mode == 6) ? 4 : 2);++ indexBits2 = (mode == 4) ? 3 : ((mode == 5) ? 2 : 0);++ weights = (indexBits == 2) ? aWeight2 : ((indexBits == 3) ? aWeight3 : aWeight4);++ weights2 = (indexBits2 == 2) ? aWeight2 : aWeight3;++++ /* Quite inconvenient that indices aren't interleaved so we have to make 2 passes here */++ /* Pass #1: collecting color indices */++ for (i = 0; i < 4; ++i) {++ for (j = 0; j < 4; ++j) {++ partitionSet = (numPartitions == 1) ? ((i | j) ? 0 : 128) : partition_sets[numPartitions - 2][partition][i][j];++++ indexBits = (mode == 0 || mode == 1) ? 3 : ((mode == 6) ? 4 : 2);++ /* fix-up index is specified with one less bit */++ /* The fix-up index for subset 0 is always index 0 */++ if (partitionSet & 0x80) {++ indexBits--;++ }++++ indices[i][j] = bcdec__bitstream_read_bits(&bstream, indexBits);++ }++ }++++ /* Pass #2: reading alpha indices (if any) and interpolating & rotating */++ for (i = 0; i < 4; ++i) {++ for (j = 0; j < 4; ++j) {++ partitionSet = (numPartitions == 1) ? ((i|j) ? 0 : 128) : partition_sets[numPartitions - 2][partition][i][j];++ partitionSet &= 0x03;++++ index = indices[i][j];++++ if (!indexBits2) {++ r = bcdec__interpolate(endpoints[partitionSet * 2][0], endpoints[partitionSet * 2 + 1][0], weights, index);++ g = bcdec__interpolate(endpoints[partitionSet * 2][1], endpoints[partitionSet * 2 + 1][1], weights, index);++ b = bcdec__interpolate(endpoints[partitionSet * 2][2], endpoints[partitionSet * 2 + 1][2], weights, index);++ a = bcdec__interpolate(endpoints[partitionSet * 2][3], endpoints[partitionSet * 2 + 1][3], weights, index);++ } else {++ index2 = bcdec__bitstream_read_bits(&bstream, (i|j) ? indexBits2 : (indexBits2 - 1));++ /* The index value for interpolating color comes from the secondary index bits for the texel++ if the mode has an index selection bit and its value is one, and from the primary index bits otherwise.++ The alpha index comes from the secondary index bits if the block has a secondary index and++ the block either doesn’t have an index selection bit or that bit is zero, and from the primary index bits otherwise. */++ if (!indexSelectionBit) {++ r = bcdec__interpolate(endpoints[partitionSet * 2][0], endpoints[partitionSet * 2 + 1][0], weights, index);++ g = bcdec__interpolate(endpoints[partitionSet * 2][1], endpoints[partitionSet * 2 + 1][1], weights, index);++ b = bcdec__interpolate(endpoints[partitionSet * 2][2], endpoints[partitionSet * 2 + 1][2], weights, index);++ a = bcdec__interpolate(endpoints[partitionSet * 2][3], endpoints[partitionSet * 2 + 1][3], weights2, index2);++ } else {++ r = bcdec__interpolate(endpoints[partitionSet * 2][0], endpoints[partitionSet * 2 + 1][0], weights2, index2);++ g = bcdec__interpolate(endpoints[partitionSet * 2][1], endpoints[partitionSet * 2 + 1][1], weights2, index2);++ b = bcdec__interpolate(endpoints[partitionSet * 2][2], endpoints[partitionSet * 2 + 1][2], weights2, index2);++ a = bcdec__interpolate(endpoints[partitionSet * 2][3], endpoints[partitionSet * 2 + 1][3], weights, index);++ }++ }++++ switch (rotation) {++ case 1: { /* 01 – Block format is Scalar(R) Vector(AGB) - swap A and R */++ bcdec__swap_values(&a, &r);++ } break;++ case 2: { /* 10 – Block format is Scalar(G) Vector(RAB) - swap A and G */++ bcdec__swap_values(&a, &g);++ } break;++ case 3: { /* 11 - Block format is Scalar(B) Vector(RGA) - swap A and B */++ bcdec__swap_values(&a, &b);++ } break;++ }++++ decompressed[j * 4 + 0] = r;++ decompressed[j * 4 + 1] = g;++ decompressed[j * 4 + 2] = b;++ decompressed[j * 4 + 3] = a;++ }++++ decompressed += destinationPitch;++ }++}++++#endif /* BCDEC_IMPLEMENTATION */++++/* LICENSE:++++This software is available under 2 licenses -- choose whichever you prefer.++++------------------------------------------------------------------------------++ALTERNATIVE A - MIT License++++Copyright (c) 2022 Sergii Kudlai++++Permission is hereby granted, free of charge, to any person obtaining a copy of++this software and associated documentation files (the "Software"), to deal in++the Software without restriction, including without limitation the rights to++use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies++of the Software, and to permit persons to whom the Software is furnished to do++so, subject to the following conditions:++++The above copyright notice and this permission notice shall be included in all++copies or substantial portions of the Software.++++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR++IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,++FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE++AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER++LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,++OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE++SOFTWARE.++++------------------------------------------------------------------------------++ALTERNATIVE B - The Unlicense++++This is free and unencumbered software released into the public domain.++++Anyone is free to copy, modify, publish, use, compile, sell, or++distribute this software, either in source code form or as a compiled++binary, for any purpose, commercial or non-commercial, and by any++means.++++In jurisdictions that recognize copyright laws, the author or authors++of this software dedicate any and all copyright interest in the++software to the public domain. We make this dedication for the benefit++of the public at large and to the detriment of our heirs and++successors. We intend this dedication to be an overt act of++relinquishment in perpetuity of all present and future rights to this++software under copyright law.++++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,++EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF++MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.++IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR++OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,++ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR++OTHER DEALINGS IN THE SOFTWARE.++++For more information, please refer to <https://unlicense.org>++++*/diff --git a/patches/0012-mac-keymap.patch b/patches/0012-mac-keymap.patchnew file mode 100644index 00000000..129a0236--- /dev/null+++ b/patches/0012-mac-keymap.patch@@ -0,0 +1,391 @@+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001+From: v0lumehi <[email protected]>+Date: Wed, 28 Oct 2026 13:33:54 +0100+Subject: [PATCH] Mac front end: DM_KEYMAP and DM_PAD_MAP++input_map.h parses the maps; front_mac.m applies them to keys and controller buttons.++Upstream-Status: forwarded seedds/nxnative#386+Reason: The launcher's Controls page: DM_KEYMAP and DM_PAD_MAP move buttons to other keys and controller buttons (open upstream, #386)+Issue: LNPANDY/NX2Apple#386+---+ dm/host/front_mac.m | 42 +++++++--------+ dm/host/input_map.h | 82 ++++++++++++++++++++++++++++++ dm/host/tests/Makefile | 8 ++-+ dm/host/tests/t_input_map.c | 43 ++++++++++++++++ dm/host/tests/t_launcher_contract.c | 35 +++++++++++++ dm/tools/impact_map.tsv | 1 ++ docs/development.md | 2 +-+ docs/env_switches.tsv | 2 ++ 8 files changed, 192 insertions(+), 23 deletions(-)+ create mode 100644 dm/host/input_map.h+ create mode 100644 dm/host/tests/t_input_map.c+ create mode 100644 dm/host/tests/t_launcher_contract.c++diff --git a/dm/host/front_mac.m b/dm/host/front_mac.m+index a99ce4da..423c581f 100644+--- a/dm/host/front_mac.m++++ b/dm/host/front_mac.m+@@ -1,7 +1,8 @@+ // Mac front end: with DM_WINDOW=1 open a window (CAMetalLayer, for the graphics backend to present frames) + keyboard and controllers → dm_input; the guest runs on a large-stack thread instead and the main thread belongs to AppKit.+ // Without DM_WINDOW: the guest runs directly on the current thread, behaving the same as with no front end (windowless tests use this).+ // The window is fullscreen-capable (the green button and ⌃⌘F); DM_FULLSCREEN starts it that way. ⌘Q quits; the left mouse button is the touchscreen.+-// Key map (Nintendo layout): WASD left stick, arrow keys D-pad, J=A K=B U=X I=Y, Q=L E=R, Z=ZL C=ZR, F=press left stick G=press right stick, Return=+ Tab=−, Space=shake the controller.++// Key map (Nintendo layout): WASD left stick, arrow keys D-pad, J=A K=B U=X I=Y, Q=L E=R, Z=ZL C=ZR, F=press left stick G=press right stick, Return=+ Tab=−, Space=shake the controller;++// DM_KEYMAP moves a function to another key (the right stick too), DM_PAD_MAP changes what a controller's buttons send (input_map.h).+ // Controllers: buttons by position as on the iPhone (right A, bottom B, top X, left Y), shoulders L R, triggers ZL ZR, Menu + Options −, both sticks and their presses.+ // Each controller is a player of its own (local co-op): the first one connected is player 1, together with the keyboard, the next player 2, and so on up to 8 (pad_slots.h);+ // DM_PAD_MERGE=1 merges every controller into player 1 instead, DM_KBD_PLAYER=own makes the keyboard player 1 on its own, with the controllers from player 2 on.+@@ -14,13 +15,13 @@+ #include "front.h"+ #include "hle.h"+ #include "pad_slots.h"++#include "input_map.h"+ #include "haptics_apple.h"+ #include <signal.h>+ #include <math.h>++ static CAMetalLayer *g_layer;+ static uint64_t g_btn;+-static int g_w, g_a, g_s, g_d;+ static int g_input_on = 1; // main thread: the game window is key, so its keyboard, mouse and controllers reach the game (input_release / input_resume)++ void *front_metal_layer(void) { return (__bridge void *)g_layer; }+@@ -82,27 +83,20 @@ void front_screen_match(int fps) {+ if (!g_layer || g_match_want == fps) return; // no window (a windowless run's main thread runs the guest), or the rate as before+ g_match_want = fps; dispatch_async(dispatch_get_main_queue(), ^{ screen_match_apply(); });+ }++// Keyboard: each key holds one function of the key map (input_map.h; DM_KEYMAP changes it), the held functions make the buttons and both sticks++static key_map g_keys;++static uint32_t g_held_fn; // bit f: a key holding function f is down+ static void push(void) {+- int32_t lx = (g_d - g_a) * 32767, ly = (g_w - g_s) * 32767;+- dm_input_set(g_btn, lx, ly, 0, 0);+-}+-static int key_bit(unsigned short code) {+- switch (code) {+- case 38: return 0; case 40: return 1; case 32: return 2; case 34: return 3; // J K U I → A B X Y+- case 3: return 4; case 5: return 5; // F G → press stick+- case 12: return 6; case 14: return 7; case 6: return 8; case 8: return 9; // Q E Z C → L R ZL ZR+- case 36: return 10; case 48: return 11; // Return Tab → + −+- case 123: return 12; case 126: return 13; case 124: return 14; case 125: return 15; // ← ↑ → ↓+- }+- return -1;++ uint32_t h = g_held_fn;++ #define D(f) ((int32_t)(h >> (f) & 1))++ dm_input_set(g_btn, (D(IM_LRIGHT) - D(IM_LLEFT)) * 32767, (D(IM_LUP) - D(IM_LDOWN)) * 32767, (D(IM_RRIGHT) - D(IM_RLEFT)) * 32767, (D(IM_RUP) - D(IM_RDOWN)) * 32767);++ #undef D+ }+ static void on_key(NSEvent *e, int down) {+ if (!g_input_on) return;+- unsigned short c = e.keyCode;+- switch (c) { case 13: g_w = down; break; case 0: g_a = down; break; case 1: g_s = down; break; case 2: g_d = down; break; }+- int b = key_bit(c);+- uint64_t m = b >= 0 ? 1ull << b : c == 49 ? DM_BTN_SHAKE : 0; // Space: shaken while held+- g_btn = down ? (g_btn | m) : (g_btn & ~m);++ int f = key_map_fn(&g_keys, e.keyCode); if (f < 0) return;++ g_held_fn = down ? (g_held_fn | 1u << f) : (g_held_fn & ~(1u << f));++ g_btn = (g_held_fn & 0xffff) | (g_held_fn >> IM_SHAKE & 1 ? DM_BTN_SHAKE : 0);+ push();+ }++@@ -114,6 +108,7 @@ static void on_key(NSEvent *e, int down) {+ static pad_slots g_slots;+ static GCController *g_held[DM_PLAYERS]; // the controller of each slot, kept alive while it holds it (the slot table keys on its pointer)+ static int g_merge, g_kbd_own;++static pad_map g_padmap; // DM_PAD_MAP (input_map.h): what each button sends, applied to every controller+ static int32_t pad_axis(float v) { return (int32_t)(fmaxf(-1.f, fminf(1.f, v)) * DM_STICK_MAX); }+ static void pad_read(GCExtendedGamepad *g) {+ if (!g_input_on) return;+@@ -126,6 +121,7 @@ static void pad_read(GCExtendedGamepad *g) {+ K(g.buttonMenu, DM_BTN_PLUS); K(g.buttonOptions, DM_BTN_MINUS); K(g.leftThumbstickButton, DM_BTN_LS); K(g.rightThumbstickButton, DM_BTN_RS); // nil on pads without them: not pressed+ K(g.dpad.left, DM_BTN_LEFT); K(g.dpad.up, DM_BTN_UP); K(g.dpad.right, DM_BTN_RIGHT); K(g.dpad.down, DM_BTN_DOWN);+ #undef K++ m = pad_map_apply(&g_padmap, m);+ dm_pad_set_player(p, m, pad_axis(g.leftThumbstick.xAxis.value), pad_axis(g.leftThumbstick.yAxis.value), pad_axis(g.rightThumbstick.xAxis.value), pad_axis(g.rightThumbstick.yAxis.value));+ }+ static const char *pad_name(GCController *c) { return c.vendorName.UTF8String ?: "?"; }+@@ -165,7 +161,7 @@ static void pads_changed(GCController *gone) {+ static int g_mouse_down; // the mouse holds the touch (DmGameView)+ static void input_release(void) {+ g_input_on = 0;+- g_btn = 0; g_w = g_a = g_s = g_d = 0; push();++ g_btn = 0; g_held_fn = 0; push();+ if (g_mouse_down) { g_mouse_down = 0; dm_touch_set(NULL, 0); }+ if (g_merge) { for (GCController *c in GCController.controllers) if (c.extendedGamepad) { dm_pad_set(0, 0, 0, 0, 0); break; } }+ else for (int p = 0; p < DM_PLAYERS; p++) if (g_held[p]) dm_pad_set_player(p, 0, 0, 0, 0, 0);+@@ -176,6 +172,10 @@ static void input_resume(void) {+ else for (int p = 0; p < DM_PLAYERS; p++) if (g_held[p].extendedGamepad) pad_read(g_held[p].extendedGamepad);+ }+ static void pads_start(void) {++ key_map_default(&g_keys); pad_map_default(&g_padmap);++ const char *km = getenv("DM_KEYMAP"), *pm = getenv("DM_PAD_MAP");++ if (km && *km) { int bad = key_map_parse(&g_keys, km); LOG("front end: keyboard map from DM_KEYMAP (%s)%s", km, bad ? ", malformed entries left out" : ""); }++ if (pm && *pm) { int bad = pad_map_parse(&g_padmap, pm); LOG("front end: controller buttons from DM_PAD_MAP (%s)%s", pm, bad ? ", malformed entries left out" : ""); }+ const char *e = getenv("DM_PAD_MERGE"); g_merge = e && atoi(e);+ e = getenv("DM_KBD_PLAYER"); g_kbd_own = !g_merge && e && !strcmp(e, "own");+ static const char kbd = 0;+@@ -332,7 +332,7 @@ int front_text_input(const char *title, const char *sub, const char *guide, cons+ dispatch_sync(dispatch_get_main_queue(), ^{+ // The box takes the keyboard and the mouse, so the game window never sees the key-up of the button or the touch-up of the click that opened it: nothing may stay pressed+ // while it is up, or the game reads the stuck button / touch the moment the box closes (Stardew Valley's character creation re-opened the keyboard endlessly)+- g_btn = 0; g_w = g_a = g_s = g_d = 0; push();++ g_btn = 0; g_held_fn = 0; push();+ dm_touch_set(NULL, 0);+ int min_chars = g_swkbd_min_chars > 0 ? g_swkbd_min_chars : 0;+ NSString *info = [NSString stringWithFormat:@"%s%s%s", sub ? sub : "", sub && *sub && guide && *guide ? "\n" : "", guide ? guide : ""];+diff --git a/dm/host/input_map.h b/dm/host/input_map.h+new file mode 100644+index 00000000..56fa4993+--- /dev/null++++ b/dm/host/input_map.h+@@ -0,0 +1,82 @@++// The Mac front end's button assignments (front_mac.m; pure, so tests/t_input_map.c checks it without a keyboard or controller), named as DM_KEYS names them (hle_hid.c).++// DM_KEYMAP=<name>=<key code>,… puts a function on another key: <key code> is the macOS virtual key code (NSEvent.keyCode, decimal), or "none" to leave the function on no key.++// The names are the 16 buttons, the four directions of each stick (LUp … RRight) and Shake; the left stick is on W A S D, the right stick on no key, unless DM_KEYMAP says so.++// One key holds one function: the last assignment of a key wins, and the function that held it before is left on no key, so "A=40,B=38" swaps A and B.++// DM_PAD_MAP=<name>=<name>,… changes what a controller's buttons send: the button that sends <first> by default (by position, as the iPhone maps it) sends <second> instead,++// "none" sends nothing; buttons not named stay as they are, so "A=B,B=A" swaps them. Only the 16 buttons take part (the sticks stay sticks).++// A malformed entry is left out and named in the log; the rest of the list still applies.++#pragma once++#include <stdint.h>++#include <stdio.h>++#include <stdlib.h>++#include <string.h>++#include <strings.h>++#include "dm_input.h"++++enum { IM_BUTTONS = 16, IM_LUP = 16, IM_LDOWN, IM_LLEFT, IM_LRIGHT, IM_RUP, IM_RDOWN, IM_RLEFT, IM_RRIGHT, IM_SHAKE, IM_N }; // functions 0..15 are the DM_BTN_* bits++#define IM_KEYS 128 // virtual key codes are below 128++typedef struct { int8_t fn[IM_KEYS]; } key_map; // the function each key code holds, -1 none++typedef struct { int8_t to[IM_BUTTONS]; } pad_map; // the button each default button sends, -1 none++++static const char *const im_names[IM_N] = {"A", "B", "X", "Y", "LS", "RS", "L", "R", "ZL", "ZR", "Plus", "Minus", "Left", "Up", "Right", "Down",++ "LUp", "LDown", "LLeft", "LRight", "RUp", "RDown", "RLeft", "RRight", "Shake"};++static int im_name(const char *s, size_t n) {++ for (int f = 0; f < IM_N; f++) if (strlen(im_names[f]) == n && !strncasecmp(s, im_names[f], n)) return f;++ return -1;++}++static void key_map_default(key_map *m) {++ memset(m->fn, -1, sizeof m->fn);++ static const struct { uint8_t code; int8_t fn; } d[] = {++ {38, 0}, {40, 1}, {32, 2}, {34, 3}, // J K U I → A B X Y++ {3, 4}, {5, 5}, // F G → press stick++ {12, 6}, {14, 7}, {6, 8}, {8, 9}, // Q E Z C → L R ZL ZR++ {36, 10}, {48, 11}, // Return Tab → + −++ {123, 12}, {126, 13}, {124, 14}, {125, 15}, // ← ↑ → ↓++ {13, IM_LUP}, {1, IM_LDOWN}, {0, IM_LLEFT}, {2, IM_LRIGHT}, // W S A D → left stick++ {49, IM_SHAKE}, // Space: shaken while held++ };++ for (size_t i = 0; i < sizeof d / sizeof *d; i++) m->fn[d[i].code] = d[i].fn;++}++static void pad_map_default(pad_map *m) { for (int b = 0; b < IM_BUTTONS; b++) m->to[b] = (int8_t)b; }++++// Walks "<name>=<value>,…", calling one(name's function, value text, its length) for each entry; returns the number of malformed entries, each logged here++static int im_parse(const char *spec, int max_fn, int (*one)(void *, int, const char *, size_t), void *ctx) {++ int bad = 0;++ for (const char *p = spec; p && *p; ) {++ const char *end = strchr(p, ','); size_t n = end ? (size_t)(end - p) : strlen(p);++ const char *eq = memchr(p, '=', n);++ int f = eq ? im_name(p, (size_t)(eq - p)) : -1;++ if (f < 0 || f >= max_fn || !one(ctx, f, eq + 1, n - (size_t)(eq + 1 - p))) {++ fprintf(stderr, "[dm] [RED] input map: '%.*s' is not <name>=<value>, left out\n", (int)n, p); // dm.h LOG's form (this header stays free of dm.h for the test)++ bad++;++ }++ p = end ? end + 1 : NULL;++ }++ return bad;++}++static int im_key_one(void *ctx, int f, const char *v, size_t n) {++ key_map *m = ctx; char buf[8];++ if (n == 4 && !strncasecmp(v, "none", 4)) { for (int c = 0; c < IM_KEYS; c++) if (m->fn[c] == f) m->fn[c] = -1; return 1; }++ if (!n || n >= sizeof buf || strspn(v, "0123456789") < n) return 0;++ memcpy(buf, v, n); buf[n] = 0; int code = atoi(buf);++ if (code >= IM_KEYS) return 0;++ for (int c = 0; c < IM_KEYS; c++) if (m->fn[c] == f) m->fn[c] = -1; // the function leaves its old key++ m->fn[code] = (int8_t)f; // the key's old function is left on no key++ return 1;++}++static int im_pad_one(void *ctx, int f, const char *v, size_t n) {++ pad_map *m = ctx;++ if (n == 4 && !strncasecmp(v, "none", 4)) { m->to[f] = -1; return 1; }++ int t = im_name(v, n); if (t < 0 || t >= IM_BUTTONS) return 0;++ m->to[f] = (int8_t)t; return 1;++}++static int key_map_parse(key_map *m, const char *spec) { return im_parse(spec, IM_N, im_key_one, m); }++static int pad_map_parse(pad_map *m, const char *spec) { return im_parse(spec, IM_BUTTONS, im_pad_one, m); }++static int key_map_fn(const key_map *m, unsigned code) { return code < IM_KEYS ? m->fn[code] : -1; }++// The buttons a controller sends for the buttons the default mapping read (DM_BTN_* bits); bits above the 16 buttons (DM_BTN_SHAKE) pass through++static uint64_t pad_map_apply(const pad_map *m, uint64_t btn) {++ uint64_t out = btn & ~0xffffull;++ for (int b = 0; b < IM_BUTTONS; b++) if (btn >> b & 1 && m->to[b] >= 0) out |= 1ull << m->to[b];++ return out;++}++static int pad_map_is_default(const pad_map *m) { for (int b = 0; b < IM_BUTTONS; b++) if (m->to[b] != b) return 0; return 1; }+diff --git a/dm/host/tests/Makefile b/dm/host/tests/Makefile+index ad9bb9aa..36029d14 100644+--- a/dm/host/tests/Makefile++++ b/dm/host/tests/Makefile+@@ -7,7 +7,7 @@ PYTHON ?= python3+ GINC = $(if $(strip $(GAME)),-I../gen/$(GAME) -I../../games/$(GAME),$(error GAME is not set: make GAME=<base game title ID>: $(shell python3 ../../games/game.py list | awk -F'\t' '{printf "%s (%s) ", $$1, $$3}')))+ $(B)/t_fs $(B)/t_fs_case $(B)/t_fs_commit_list $(B)/t_fs_commit_list_tsan: ../romfs_image.h+ GAME_H = ../gen/$(GAME)/game_profile.h+-run: $(B)/t_heap_size $(B)/t_touch $(B)/t_gesture $(B)/t_oe $(B)/t_fs $(B)/t_fs_commit_list $(B)/t_thread_leak $(B)/t_fs_case $(B)/t_audio $(B)/t_audio_spsc $(B)/t_swkbd $(B)/t_altstack $(B)/t_condvar $(B)/t_condvar_old $(B)/t_pctl $(B)/t_time $(B)/t_shared_font $(B)/t_vorbis $(B)/t_vorbis_divides $(B)/t_hid $(B)/t_haptics $(B)/t_haptics_apple++run: $(B)/t_heap_size $(B)/t_touch $(B)/t_gesture $(B)/t_oe $(B)/t_fs $(B)/t_fs_commit_list $(B)/t_thread_leak $(B)/t_fs_case $(B)/t_audio $(B)/t_audio_spsc $(B)/t_swkbd $(B)/t_altstack $(B)/t_condvar $(B)/t_condvar_old $(B)/t_pctl $(B)/t_time $(B)/t_shared_font $(B)/t_vorbis $(B)/t_vorbis_divides $(B)/t_hid $(B)/t_input_map $(B)/t_launcher_contract $(B)/t_haptics $(B)/t_haptics_apple+ $(B)/t_heap_size+ $(B)/t_touch+ $(B)/t_gesture+@@ -35,6 +35,8 @@ run: $(B)/t_heap_size $(B)/t_touch $(B)/t_gesture $(B)/t_oe $(B)/t_fs $(B)/t_fs_+ $(B)/t_vorbis_divides+ $(B)/t_movie_vpx+ $(B)/t_hid++ $(B)/t_input_map++ $(B)/t_launcher_contract+ $(B)/t_haptics+ $(B)/t_haptics_apple+ $(B)/t_nro+@@ -116,6 +118,10 @@ $(B)/t_pctl: t_pctl.c ../hle_misc.c ../hle.h ../dm.h $(GAME_H) | $(B)+ clang -O1 -Wall -Werror -Wno-unused-function -I.. $(GINC) -o $@ t_pctl.c+ $(B)/t_shared_font: t_shared_font.c ../hle_sdk16.c ../hle.h ../dm.h $(GAME_H) | $(B)+ clang -O1 -Wall -Werror -Wno-unused-function -Wno-frame-address -I.. $(GINC) -o $@ t_shared_font.c ../hle_profile.c++$(B)/t_input_map: t_input_map.c ../input_map.h ../dm_input.h | $(B)++ clang -O1 -Wall -Werror -Wno-unused-function -I.. -o $@ t_input_map.c++$(B)/t_launcher_contract: t_launcher_contract.c ../input_map.h ../dm_input.h | $(B)++ clang -O1 -Wall -Werror -Wno-unused-function -I.. -o $@ t_launcher_contract.c+ $(B)/t_hid: t_hid.c ../hle_hid.c ../hle_haptics.c ../hle_haptics.h ../pad_slots.h ../dm_input.h ../hle.h ../dm.h $(GAME_H) | $(B)+ clang -O1 -Wall -Werror -Wno-unused-function -I.. $(GINC) -o $@ t_hid.c ../hle_haptics.c+ $(B)/t_hid_tsan: t_hid.c ../hle_hid.c ../hle_haptics.c ../hle_haptics.h ../pad_slots.h ../dm_input.h ../hle.h ../dm.h $(GAME_H) | $(B)+diff --git a/dm/host/tests/t_input_map.c b/dm/host/tests/t_input_map.c+new file mode 100644+index 00000000..96736ad6+--- /dev/null++++ b/dm/host/tests/t_input_map.c+@@ -0,0 +1,43 @@++// The Mac front end's button assignments (input_map.h): the default key map, DM_KEYMAP moving and swapping functions, DM_PAD_MAP's swaps, and malformed entries left out++#include "../input_map.h"++++static int checks, fails;++#define CHECK(c, msg) do { checks++; if (!(c)) { fails++; fprintf(stderr, "FAIL: %s (line %d)\n", msg, __LINE__); } } while (0)++++int main(void) {++ key_map k; key_map_default(&k);++ CHECK(key_map_fn(&k, 38) == 0 && key_map_fn(&k, 40) == 1 && key_map_fn(&k, 32) == 2 && key_map_fn(&k, 34) == 3, "default: J K U I are A B X Y");++ CHECK(key_map_fn(&k, 13) == IM_LUP && key_map_fn(&k, 0) == IM_LLEFT && key_map_fn(&k, 1) == IM_LDOWN && key_map_fn(&k, 2) == IM_LRIGHT, "default: W A S D are the left stick");++ CHECK(key_map_fn(&k, 49) == IM_SHAKE && key_map_fn(&k, 36) == 10 && key_map_fn(&k, 125) == 15, "default: Space shakes, Return is +, down arrow is Down");++ int right = 0; for (int c = 0; c < IM_KEYS; c++) if (k.fn[c] >= IM_RUP && k.fn[c] <= IM_RRIGHT) right++;++ CHECK(right == 0, "default: the right stick is on no key");++ CHECK(key_map_fn(&k, 200) == -1 && key_map_fn(&k, 50) == -1, "a key code past the table or without a function holds none");++++ CHECK(key_map_parse(&k, "A=40,B=38") == 0, "a swap parses");++ CHECK(key_map_fn(&k, 40) == 0 && key_map_fn(&k, 38) == 1, "A=40,B=38 swaps A and B");++ key_map_default(&k);++ CHECK(key_map_parse(&k, "a=49") == 0 && key_map_fn(&k, 49) == 0 && key_map_fn(&k, 38) == -1, "names are case-insensitive; A leaves J, and Space leaves Shake");++ int shake = 0; for (int c = 0; c < IM_KEYS; c++) if (k.fn[c] == IM_SHAKE) shake++;++ CHECK(shake == 0, "the function a key held before is on no key");++ CHECK(key_map_parse(&k, "RUp=126,RLeft=123,Up=none") == 0, "right stick on the arrows, Up on none");++ CHECK(key_map_fn(&k, 126) == IM_RUP && key_map_fn(&k, 123) == IM_RLEFT, "the arrows hold the right stick");++ int up = 0; for (int c = 0; c < IM_KEYS; c++) if (k.fn[c] == 13) up++;++ CHECK(up == 0, "Up=none leaves Up on no key");++ key_map_default(&k);++ CHECK(key_map_parse(&k, "Q=1,ZL=abc,A=128,B=,=5,X=7") == 5, "five malformed entries are counted");++ CHECK(key_map_fn(&k, 7) == 2 && key_map_fn(&k, 6) == 8 && key_map_fn(&k, 38) == 0, "the good entry applies, the malformed ones change nothing");++ CHECK(key_map_parse(&k, "") == 0 && key_map_parse(&k, NULL) == 0 && key_map_parse(&k, "L=12,") == 0, "empty lists and a trailing comma are fine");++++ pad_map m; pad_map_default(&m);++ CHECK(pad_map_is_default(&m) && pad_map_apply(&m, DM_BTN_A | DM_BTN_ZR | DM_BTN_SHAKE) == (DM_BTN_A | DM_BTN_ZR | DM_BTN_SHAKE), "default: every button sends itself, Shake passes");++ CHECK(pad_map_parse(&m, "A=B,B=A") == 0 && !pad_map_is_default(&m), "a swap parses");++ CHECK(pad_map_apply(&m, DM_BTN_A) == DM_BTN_B && pad_map_apply(&m, DM_BTN_B) == DM_BTN_A && pad_map_apply(&m, DM_BTN_A | DM_BTN_B) == (DM_BTN_A | DM_BTN_B), "A=B,B=A swaps them");++ CHECK(pad_map_apply(&m, DM_BTN_X | DM_BTN_DOWN) == (DM_BTN_X | DM_BTN_DOWN), "buttons not named stay");++ CHECK(pad_map_parse(&m, "ZL=L,minus=none") == 0, "two buttons on one, and none");++ CHECK(pad_map_apply(&m, DM_BTN_ZL) == DM_BTN_L && pad_map_apply(&m, DM_BTN_L | DM_BTN_ZL) == DM_BTN_L && pad_map_apply(&m, DM_BTN_MINUS) == 0, "ZL sends L, Minus sends nothing");++ pad_map_default(&m);++ CHECK(pad_map_parse(&m, "A=LUp,LUp=A,Shake=B,Y=X") == 3 && m.to[3] == 2 && m.to[0] == 0, "sticks and Shake are no buttons here: left out; Y=X applies");++++ printf("input map: %d checks, %d failed\n", checks, fails);++ return fails != 0;++}+diff --git a/dm/host/tests/t_launcher_contract.c b/dm/host/tests/t_launcher_contract.c+new file mode 100644+index 00000000..136b4035+--- /dev/null++++ b/dm/host/tests/t_launcher_contract.c+@@ -0,0 +1,35 @@++/* The write half is ControlLayout.environment in frontend/Sources/NSPortBuilder/Controls.swift;++ the read half is input_map.h. The launcher sends exactly these strings, so this checks the++ contract between the two: a rename on either side, or a change of syntax, fails here rather++ than at a player's keyboard. */++#include "../input_map.h"++static int checks, fails;++#define CHECK(c, msg) do { checks++; if (!(c)) { fails++; fprintf(stderr, "FAIL: %s\n", msg); } } while (0)++int main(void) {++ key_map k; key_map_default(&k);++ /* Settings: A moved onto K (40), B left on none — ControlsTests' first case */++ CHECK(key_map_parse(&k, "A=40,B=none") == 0, "A=40,B=none parses");++ CHECK(key_map_fn(&k, 40) == 0, "K now sends A");++ int bfound = 0; for (int c = 0; c < IM_KEYS; c++) if (k.fn[c] == 1) bfound = 1;++ CHECK(!bfound, "B is on no key");++++ pad_map m; pad_map_default(&m);++ /* Settings: A and B swapped, Minus sends nothing */++ CHECK(pad_map_parse(&m, "A=B,B=A,Minus=none") == 0, "A=B,B=A,Minus=none parses");++ CHECK(pad_map_apply(&m, DM_BTN_A) == DM_BTN_B, "pad A sends B");++ CHECK(pad_map_apply(&m, DM_BTN_B) == DM_BTN_A, "pad B sends A");++ CHECK(pad_map_apply(&m, DM_BTN_MINUS) == 0, "Minus sends nothing");++ CHECK(pad_map_apply(&m, DM_BTN_Y) == DM_BTN_Y, "untouched buttons stay");++++ /* the right stick on I, as the Controls sheet's own capture sets it */++ key_map_default(&k);++ CHECK(key_map_parse(&k, "RUp=34") == 0, "RUp=34 parses");++ CHECK(key_map_fn(&k, 34) == IM_RUP, "I now sends RUp (and Y left I)");++ int yfound = 0; for (int c = 0; c < IM_KEYS; c++) if (k.fn[c] == 3) yfound = 1;++ CHECK(!yfound, "Y is on no key any more");++ int rup = 0; for (int c = 0; c < IM_KEYS; c++) if (k.fn[c] == IM_RUP) rup = 1;++ CHECK(rup, "RUp is on a key");++++ printf("launcher contract: %d checks, %d failed\n", checks, fails);++ return fails != 0;++}+diff --git a/dm/tools/impact_map.tsv b/dm/tools/impact_map.tsv+index df05fa53..22e68677 100644+--- a/dm/tools/impact_map.tsv++++ b/dm/tools/impact_map.tsv+@@ -103,5 +103,6 @@ dm/host/main.c *:* the host's start+ dm/host/loader.c *:* module loading+ dm/host/hle.c hle:* the HLE tables+ dm/host/front_mac.m present:* the Mac front end++dm/host/input_map.h present:* the Mac front end's key and controller button map+ dm/host/front.h present:* the front end+ dm/ios/* *:* the iOS app+diff --git a/docs/development.md b/docs/development.md+index 88703bb1..06b31d10 100644+--- a/docs/development.md++++ b/docs/development.md+@@ -10,7 +10,7 @@ The README covers packing and playing. This page is for working on nxnative itse+ | Host (`dm/host`) | Stands in for the Horizon kernel and the system services the games call: threads and synchronization, memory, file system with transactional saves, HID, audio, movies (VP9 through libvpx, Vorbis sound through stb_vorbis), software keyboard, focus and lifecycle |+ | Graphics (`dm/gfx`) | NVN on Metal. Shaders are extracted by `shader_split.py` from Nintendo's containers and from Unity's `Shader` objects, then translated offline. Mario: 16,266 of 16,268 shaders compile. Engage: 9,268 of 9,269. Games that render with Vulkan (Hades) or OpenGL (Digimon Story Cyber Sleuth) go through layers of their own on Metal (`dm/gfx/vk`, `dm/gfx/gl`) |+ | Audio | Games that carry the SDK's audio renderer (Mario) run it in-process; games that use AudioOut directly (Engage: Wwise) feed it straight. Output goes through Core Audio (default on iOS, `DM_AUDIO=1` on the Mac) |+-| Input | iOS: the touch gamepad and physical controllers, all as player 1; shaking the phone shakes the controller (its six-axis sensor, `hle_hid.c`; the accelerometer in `DmGamepad.m`, threshold `DM_SHAKE_G`, 1.5 G by default). Mac: scripted input (`DM_KEYS=<seconds>:<button>,…`, `Shake` for a shake, with `DM_KBD=<text>` answering the system keyboard) or `DM_WINDOW=1` for a window with keyboard input (Space shakes) and physical controllers (buttons by position, as on the iPhone). On the Mac each controller is a player of its own, for local co-op: the first one connected is player 1, together with the keyboard, the next player 2, and so on up to 8 (`pad_slots.h`); a controller that is removed frees its player and gets it back when it reconnects, and the log names each one's player and npad (`controller 'Xbox Wireless Controller' connected: player 2 (npad 1)`). Player 1 is the Handheld npad in handheld mode and No1 docked, player n is No n; the game's supported npad ids decide how many play (`hle_hid.c`): a one-player game gets every controller as player 1, and a controller past a game's last player is not used. `DM_PAD_MERGE=1` makes every controller player 1, as before; `DM_KBD_PLAYER=own` makes the keyboard player 1 on its own, with the controllers from player 2 on. The window goes fullscreen from its green button or ⌃⌘F; `DM_FULLSCREEN=1` starts it that way. In fullscreen, a screen whose refresh rate is not a multiple of the game's (144 or 165 Hz) runs at one that is (120 Hz) until the window leaves fullscreen; `DM_SCREEN_MATCH=0` keeps its rate. The drawable follows the window in pixels (fullscreen at the screen's resolution); `DM_METAL_HUD=1` shows Apple's performance HUD (on the iPhone too, from `Documents/env.txt`). The left mouse button is the touchscreen, on the 16:9 picture. In handheld mode the touches also drive `hid::GetGestureStates` (taps, presses, pans, swipes, pinches and rotations recognized by the host, `hle_touch.c`) |++| Input | iOS: the touch gamepad and physical controllers, all as player 1; shaking the phone shakes the controller (its six-axis sensor, `hle_hid.c`; the accelerometer in `DmGamepad.m`, threshold `DM_SHAKE_G`, 1.5 G by default). Mac: scripted input (`DM_KEYS=<seconds>:<button>,…`, `Shake` for a shake, with `DM_KBD=<text>` answering the system keyboard) or `DM_WINDOW=1` for a window with keyboard input (Space shakes) and physical controllers (buttons by position, as on the iPhone). On the Mac each controller is a player of its own, for local co-op: the first one connected is player 1, together with the keyboard, the next player 2, and so on up to 8 (`pad_slots.h`); a controller that is removed frees its player and gets it back when it reconnects, and the log names each one's player and npad (`controller 'Xbox Wireless Controller' connected: player 2 (npad 1)`). Player 1 is the Handheld npad in handheld mode and No1 docked, player n is No n; the game's supported npad ids decide how many play (`hle_hid.c`): a one-player game gets every controller as player 1, and a controller past a game's last player is not used. `DM_PAD_MERGE=1` makes every controller player 1, as before; `DM_KBD_PLAYER=own` makes the keyboard player 1 on its own, with the controllers from player 2 on. `DM_KEYMAP=<name>=<key code>,…` puts a button, a stick direction (the right stick too, on no key by default) or `Shake` on another key, and `DM_PAD_MAP=<name>=<name>,…` changes what a controller's buttons send (`A=B,B=A` swaps them; `input_map.h`). The window goes fullscreen from its green button or ⌃⌘F; `DM_FULLSCREEN=1` starts it that way. In fullscreen, a screen whose refresh rate is not a multiple of the game's (144 or 165 Hz) runs at one that is (120 Hz) until the window leaves fullscreen; `DM_SCREEN_MATCH=0` keeps its rate. The drawable follows the window in pixels (fullscreen at the screen's resolution); `DM_METAL_HUD=1` shows Apple's performance HUD (on the iPhone too, from `Documents/env.txt`). The left mouse button is the touchscreen, on the 16:9 picture. In handheld mode the touches also drive `hid::GetGestureStates` (taps, presses, pans, swipes, pinches and rotations recognized by the host, `hle_touch.c`) |+ | iOS app | One unsigned IPA for iPhone and iPad. The rewritten code is embedded in the executable; the shader libraries, the RomFS and the game icon are inside the app. A settings screen comes before the game (`Launcher.swift`, drawn from `dm/launcher.json`, which `dm/games/settings.py` writes from `dm/games/settings.tsv`); the host's loading starts at app launch meanwhile, and the frame rate and render scale go into the frame step state when the game starts (`loader.c` `dm_fps_state_apply`) |+ | Known gaps | Conditional render is always drawn; `MultiDraw*IndirectCount` waits on the CPU for the GPU-written count; geometry shaders do not translate. TBDR optimizations are off by default (they don't understand bindless textures yet). No amiibo. The bundled prewarm lists are empty. On the Mac, Mario's menu and dialogue text render blank (fine on the iPhone) |++diff --git a/docs/env_switches.tsv b/docs/env_switches.tsv+index 34c7bf88..775f9248 100644+--- a/docs/env_switches.tsv++++ b/docs/env_switches.tsv+@@ -53,6 +53,7 @@ DM_ICON path `=<image>` gives `build_ipa.sh` another app icon (default the `icon+ DM_IMPORTS diagnostic When set, logs each import the loader binds to a host function and each forced takeover+ DM_KBD switch `=<text>`: the system keyboard returns that text as OK without showing an input box; unset with no window, it returns cancel+ DM_KBD_PLAYER switch `own` makes the Mac keyboard player 1 on its own, with controllers from player 2 on (by default the first controller shares player 1 with the keyboard)++DM_KEYMAP player Mac keyboard: `<name>=<key code>,…` puts a button (`A` … `Down`), a stick direction (`LUp` … `RRight`) or `Shake` on another key (macOS virtual key code, or `none`); one key holds one function (`input_map.h`)+ DM_KEYS switch Scripted input: `<seconds or f<frame>>:<key>[+key][~hold][*count/interval],…` presses buttons, sticks and `Shake` at those times+ DM_LANG player Game language as a language code (default `en-US`; the iOS app sets the one the IPA was packed with)+ DM_LAUNCHER switch `0` skips the iOS settings screen and starts the game at once+@@ -159,6 +160,7 @@ DM_OODLE_JOB path `=<job file>`: the host runs the game's own Oodle decoder on e+ DM_OODLE_MODULES path The rewritten modules the Mac host's Oodle tool mode loads when `shader_split.py` decodes Trinity packs; set by the NSP script+ DM_OODLE_SERVE switch `=1`: the host answers decode requests on stdin / stdout with the game's own Oodle (or LZ5) decoder from the guest main thread before the SDK starts, until stdin ends+ DM_OPMODE player The operation mode the game sees: `0` handheld, `1` console (default: the profile's `op_mode`, console unless set); read once at startup++DM_PAD_MAP player Mac controllers: `<name>=<name>,…` makes the button that sends the first by default send the second (or `none`), e.g. `A=B,B=A` swaps them (`input_map.h`)+ DM_PAD_MERGE switch `=1` on the Mac merges every controller into player 1, as before, instead of giving each controller a player of its own+ DM_PATCH_FRONT switch `=<bytes>`: the size of the patch area right before the module base for a long text (`BIG_TEXT`); set only by the rewriter's own rerun with the size it needs+ DM_PREEMPT switch `0` / `1` overrides the profile's `core_preempt`: also check already-runnable higher-priority peers on the caller's core after every thread SVCdiff --git a/patches/0013-nro-code-start.patch b/patches/0013-nro-code-start.patchnew file mode 100644index 00000000..29105c4f--- /dev/null+++ b/patches/0013-nro-code-start.patch@@ -0,0 +1,124 @@+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001+From: v0lumehi <[email protected]>+Date: Wed, 28 Oct 2026 13:33:54 +0100+Subject: [PATCH] patch_nso.py: an NRO's header is not code++code_start() and code_ranges() bound the site scan and the code ranges.++Upstream-Status: backport 3e77816c+Reason: An NRO's header is not code: the rewriter scanned it as instructions and stopped Final Fantasy X/X-2 HD Remaster (seedds/nxnative#397 closed: main has its own fix, 3e77816c; this patch drops once the bump takes it)+Issue: LNPANDY/NX2Apple#14+---+ dm/tools/patch_nso.py | 17 +++++++--+ dm/tools/tests/test_nro_header.py | 59 ++++++++++++++++++++++++++++++++ 2 files changed, 74 insertions(+), 2 deletions(-)+ create mode 100644 dm/tools/tests/test_nro_header.py++diff --git a/dm/tools/patch_nso.py b/dm/tools/patch_nso.py+index 7e02476d..1a235db2 100644+--- a/dm/tools/patch_nso.py++++ b/dm/tools/patch_nso.py+@@ -20,8 +20,21 @@ from capstone.arm64 import ARM64_OP_IMM, ARM64_OP_MEM, ARM64_OP_REG+ import nso_asm+ from nso_asm import * # the instruction encoders (B, ADRP, LDRX, ...), shared with the per-build patch files+++def code_start(d):++ """Where the code in the text segment starts: 0x80 in an NRO, 0 in an NSO. An NRO's text segment begins at file and memory++ offset 0 with the file's own header in it (the start word, the MOD0 offset, NRO0 at +0x10, the segment table at +0x20, the++ build ID at +0x40), so scanning it from 0 read the header as instructions: the build ID decoded as "ldr x18, #…" and stopped++ Final Fantasy X/X-2 HD Remaster's rewrite (GitHub issue LNPANDY/NX2Apple#14). An NSO's text holds code from 0."""++ return 0x80 if d[0x10:0x14] == b'NRO0' else 0++++def code_ranges(data_blocks, text_end, start=0):++ """The text's code ranges: the gaps between its data blocks (nso_code.data_blocks), none of them before `start` (code_start)"""++ gaps = zip([0] + [e for _, e in data_blocks], [s for s, _ in data_blocks] + [text_end])++ return [(max(s, start), e) for s, e in gaps if e > max(s, start)]+++ src, outdir, NAME = sys.argv[1], sys.argv[2], sys.argv[3]+ d = open(src, 'rb').read()++CODE_START = code_start(d)+ if d[0x10:0x14] == b'NRO0':+ # An NRO (a module the game loads at run time with nn::ro, Super Smash Bros. Ultimate's fighter code): the file is the image itself, each segment stored at its memory offset+ # and uncompressed; +0x20 text, +0x28 ro, +0x30 data as {offset, size}, +0x38 bss size, +0x40 the build ID. Rewritten as an NSO of the same layout would be+@@ -463,14 +476,14 @@ for _ in range(nfde):+ a, s = rd(o, tenc); o += s+ _, s = rd(o, tenc); o += s+ starts.add(a)+-starts = sorted(x for x in starts if x < TEXT_END)++starts = sorted(x for x in starts if CODE_START <= x < TEXT_END)++ # ---- Linear scan to find all rewrite points (not relying on register read/write reports) ----+ # Data blocks in the text (nso_code.py: Absolum's main starts with 1.7 MB of them) are not code: words there that read as rewrite sites are left alone+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+ import nso_code+ DATA_BLOCKS = nso_code.data_blocks(IMG, TEXT_END, md)+-CODE_RANGES = list(zip([0] + [e for _, e in DATA_BLOCKS], [s for s, _ in DATA_BLOCKS] + [TEXT_END]))++CODE_RANGES = code_ranges(DATA_BLOCKS, TEXT_END, CODE_START)+ md_lite = Cs(CS_ARCH_ARM64, CS_MODE_ARM) # no details: the x18 scan reads only the operand text+ R18 = re.compile(r'\b[xw]18\b')+ def x18_words(lo, hi):+diff --git a/dm/tools/tests/test_nro_header.py b/dm/tools/tests/test_nro_header.py+new file mode 100644+index 00000000..6c7ab421+--- /dev/null++++ b/dm/tools/tests/test_nro_header.py+@@ -0,0 +1,59 @@++"""An NRO's header is not code (GitHub issue #14).++++An NRO's text segment starts at offset 0 with the file's own header in it: Hades' EOSSDK-Switch-Shipping.nro has text++{0x0, 0xa41000} in its segment table and NRO0 at +0x10. Scanning it from 0 read the header's build ID as instructions and++reported `44 ldr x18, #0xfffffffffff40370` on Final Fantasy X/X-2 HD Remaster. The segment table cannot give the bound++(it says 0): the earlier TEXT_LO = segs[0][1] form kept scanning the header, and used TEXT_LO before defining it, which++stopped every rewrite with a NameError.++++patch_nso.py's code_start() is 0x80 for an NRO and 0 for an NSO, and code_ranges() starts no code range before it; both++scans (the x18 words and the rewrite sites) walk those ranges. This is seedds/nxnative#397, carried by patch_patch_nso in++scripts/sync_upstream.py until it is upstream (its own test there is test_nro_code_start.py). The functions are taken++from patch_nso.py itself, which runs as a script.++"""++import ast++from pathlib import Path++import struct++import unittest++++TOOLS = Path(__file__).resolve().parents[1]++SOURCE = (TOOLS / 'patch_nso.py').read_text(encoding='utf-8')++scope = {}++exec(compile(ast.Module(body=[n for n in ast.parse(SOURCE).body if isinstance(n, ast.FunctionDef) and n.name in ('code_start', 'code_ranges')],++ type_ignores=[]), str(TOOLS / 'patch_nso.py'), 'exec'), scope)++code_start, code_ranges = scope['code_start'], scope['code_ranges']++++LDR_X18 = 0x58000000 | (0x7ff40370 >> 2 & 0x7ffff) << 5 | 18 # a literal load into x18: what the build ID's bytes read as++++++def nro(text_size=0x1000):++ """A synthetic NRO's first 0x80 bytes, laid out as Hades' EOS NRO is: text at offset 0 with the header inside it"""++ h = bytearray(0x80)++ h[0x10:0x14] = b'NRO0'++ struct.pack_into('<II', h, 0x20, 0, text_size) # text {offset, size}++ struct.pack_into('<I', h, 0x44, LDR_X18) # inside the build ID++ return bytes(h)++++++class CodeStart(unittest.TestCase):++ def test_an_nro_s_header_is_outside_every_code_range(self):++ d = nro()++ self.assertEqual(struct.unpack_from('<II', d, 0x20)[0], 0, 'the segment table says 0, so it cannot bound the scan')++ self.assertEqual(code_start(d), 0x80)++ ranges = code_ranges([(0x400, 0x500)], 0x1000, code_start(d))++ self.assertEqual(ranges, [(0x80, 0x400), (0x500, 0x1000)])++ self.assertFalse(any(s <= 0x44 < e for s, e in ranges))++++ def test_an_nso_keeps_its_ranges(self):++ self.assertEqual(code_start(b'NSO0' + bytes(0x7c)), 0)++ self.assertEqual(code_ranges([(0x400, 0x500)], 0x1000), [(0, 0x400), (0x500, 0x1000)])++++ def test_the_bounds_are_defined_before_the_scan_uses_them(self):++ """The NameError: each name the scan reads is assigned above its first use"""++ for name, use in (('CODE_START', 'starts = sorted('), ('CODE_RANGES', 'x18 = set().union(')):++ self.assertLess(SOURCE.index(f'{name} = '), SOURCE.index(use), name)++ self.assertNotIn('TEXT_LO', SOURCE)++++++if __name__ == '__main__':++ unittest.main()diff --git a/patches/0014-mac-library-folder.patch b/patches/0014-mac-library-folder.patchnew file mode 100644index 00000000..2bda62c7--- /dev/null+++ b/patches/0014-mac-library-folder.patch@@ -0,0 +1,128 @@+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001+From: v0lumehi <[email protected]>+Date: Wed, 28 Oct 2026 13:33:54 +0100+Subject: [PATCH] Mac launcher: saves and log live in the game library folder++One-time copy of the old saves and log from ~/Library; prints both paths at start.++Upstream-Status: pending (seedds/nxnative#460 is the upstream design: a dataFolder key)+Reason: Saves and log follow the game library folder (<folder of the .app>/.nx2apple-library marker); replaced by the dataFolder pref once #460 merges+Issue: LNPANDY/NX2Apple#123+---+ dm/mac/launcher.c | 87 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+)++diff --git a/dm/mac/launcher.c b/dm/mac/launcher.c+index 3c5d1fef..3873b7ad 100644+--- a/dm/mac/launcher.c++++ b/dm/mac/launcher.c+@@ -16,6 +16,7 @@+ #include <stdlib.h>+ #include <string.h>+ #include <sys/stat.h>++#include <dirent.h>+ #include <sys/wait.h>+ #include <unistd.h>+ #include "romfs_image.h"+@@ -58,6 +59,43 @@ static void mkdirs(const char *path) { // mkdir -p+ mkdir(p, 0755);+ }+++static int dir_has_entries(const char *path) { // anything inside at all (a save folder, a log folder)++ DIR *d = opendir(path); if (!d) return 0;++ struct dirent *e; int any = 0;++ while ((e = readdir(d))) if (strcmp(e->d_name, ".") && strcmp(e->d_name, "..")) { any = 1; break; }++ closedir(d); return any;++}++++static int copy_file(const char *from, const char *to) {++ FILE *in = fopen(from, "rb"); if (!in) return 0;++ FILE *out = fopen(to, "wb"); if (!out) { fclose(in); return 0; }++ char buf[1 << 16]; size_t n; int ok = 1;++ while ((n = fread(buf, 1, sizeof buf, in)) > 0) if (fwrite(buf, 1, n, out) != n) { ok = 0; break; }++ if (ferror(in)) ok = 0;++ fclose(in); if (fclose(out)) ok = 0;++ if (!ok) unlink(to);++ return ok;++}++++/// Recursive copy for the one-time migration of a save folder. Symlinks are followed (a save is++/// plain files); a file that already exists is left alone, so a half-finished copy can be resumed.++static void copy_tree(const char *from, const char *to) {++ mkdirs(to);++ DIR *d = opendir(from); if (!d) return;++ struct dirent *e;++ while ((e = readdir(d))) {++ if (!strcmp(e->d_name, ".") || !strcmp(e->d_name, "..")) continue;++ char a[PATH_MAX], b[PATH_MAX];++ snprintf(a, sizeof a, "%s/%s", from, e->d_name);++ snprintf(b, sizeof b, "%s/%s", to, e->d_name);++ struct stat st;++ if (stat(a, &st)) continue;++ if (S_ISDIR(st.st_mode)) copy_tree(a, b);++ else if (S_ISREG(st.st_mode) && access(b, F_OK)) copy_file(a, b);++ }++ closedir(d);++}+++ static void env_file(const char *path) { // KEY=VALUE lines, # starts a comment; a variable already set stays+ FILE *f = fopen(path, "r"); if (!f) return;+ char ln[4096];+@@ -98,8 +136,57 @@ int main(void) {+ snprintf(sup, sizeof sup, "%s/Library/Application Support/nxnative/%s", home, id);+ snprintf(save, sizeof save, "%s/save", sup); snprintf(temp, sizeof temp, "%s/temp", sup);+ snprintf(logs, sizeof logs, "%s/Library/Logs/nxnative", home);++ // Saves and logs beside the game, not under ~/Library: a library folder the user can move or++ // keep on an external drive has to carry its saves with it, or they are effectively lost the++ // moment the folder moves (the files are still in ~/Library, where nobody looks for them).++ //++ // The library root is the folder the app sits in, when that folder also holds games/ — the++ // layout the Mac front end writes (<out>/<id>.app, <out>/games/<id>/romfs.img). A bundle++ // copied somewhere else keeps the old ~/Library paths, so nothing breaks for a user who never++ // used the launcher's folder.++ {++ char appdir[PATH_MAX]; snprintf(appdir, sizeof appdir, "%s", exe);++ // Four cuts: <…>/<id>.app/Contents/MacOS/<launcher> → MacOS → Contents → <id>.app → the folder++ // holding it. Three landed on the .app itself, so the probe looked for <id>.app/games — which++ // never exists — and the migration never ran (the report: saves stayed in ~/Library).++ *strrchr(appdir, '/') = 0; *strrchr(appdir, '/') = 0;++ *strrchr(appdir, '/') = 0; *strrchr(appdir, '/') = 0;++ // The marker file the Mac front end writes beside the .app (a dot file, so the Finder hides++ // it): this folder is a game library, and the game's saves and log live in it. DM_ROOT (the++ // learned shader state, env.txt), temp/ and everything else stay under ~/Library — only++ // what is needed and reused comes along, so the library folder stays lean.++ char probe[PATH_MAX]; snprintf(probe, sizeof probe, "%s/.nx2apple-library", appdir);++ if (!stat(probe, &st)) {++ snprintf(save, sizeof save, "%s/save/%s", appdir, id);++ snprintf(logs, sizeof logs, "%s/log", appdir);++ // First run after this change: bring the old saves across rather than starting the++ // player on an empty save slot. Copied, not moved — an older build of the same app++ // still reads the old place, and a copy is cheap next to a save.++ char oldsave[PATH_MAX], oldlog[PATH_MAX];++ snprintf(oldsave, sizeof oldsave, "%s/save", sup);++ snprintf(oldlog, sizeof oldlog, "%s/Library/Logs/nxnative/%s.log", home, id);++ mkdirs(save); mkdirs(logs);++ if (dir_has_entries(oldsave) && !dir_has_entries(save)) {++ copy_tree(oldsave, save);++ fprintf(stderr, "launcher: saves copied from %s to %s (they now live with the game)\n", oldsave, save);++ }++ // The previous session's log becomes the .prev.log, as the rotation below would have++ // it: the .log itself is opened fresh right after, and copying into it would be++ // truncated away by that open.++ char newprev[PATH_MAX]; snprintf(newprev, sizeof newprev, "%s/%s.prev.log", logs, id);++ // Explicit compares, not !stat(): stat() returns -1 when the file is missing, which is++ // truthy — reading "!" as "does not exist" here inverted the condition and skipped the++ // copy (found by the end-to-end test below).++ if (stat(oldlog, &st) == 0 && stat(newprev, &st) != 0) {++ if (copy_file(oldlog, newprev)) fprintf(stderr, "launcher: the previous log was copied from %s\n", oldlog);++ }++ }++ }+ snprintf(log, sizeof log, "%s/%s.log", logs, id); snprintf(prev, sizeof prev, "%s/%s.prev.log", logs, id);+ mkdirs(save); mkdirs(temp); mkdirs(logs);++ // Say where this game reads and writes, on every start: a player checking whether their saves++ // moved with the game should not have to know the migration rules.++ fprintf(stderr, "launcher: saves %s\nlauncher: log %s\n", save, log);+ rename(log, prev);+ int fd = open(log, O_WRONLY | O_CREAT | O_TRUNC, 0644);+ if (fd >= 0) { dup2(fd, 1); dup2(fd, 2); close(fd); setvbuf(stdout, NULL, _IOLBF, 0); }diff --git a/patches/0015-hades2-update-profile.patch b/patches/0015-hades2-update-profile.patchnew file mode 100644index 00000000..0a6ed374--- /dev/null+++ b/patches/0015-hades2-update-profile.patch@@ -0,0 +1,71 @@+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001+From: v0lumehi <[email protected]>+Date: Wed, 28 Oct 2026 13:33:55 +0100+Subject: [PATCH] Hades II: register the 1.0.137848 update's builds++Profile data only.++Upstream-Status: forwarded seedds/nxnative#485+Reason: Hades II 1.0.137848 update: build rows, shader_versions v0 v1 and the NVN segment keys+Issue: LNPANDY/NX2Apple#123+---+ dm/games/0100A00019DE0000/game.tsv | 34 +++++++++++++++++++++++++++---+ 1 file changed, 31 insertions(+), 3 deletions(-)++diff --git a/dm/games/0100A00019DE0000/game.tsv b/dm/games/0100A00019DE0000/game.tsv+index aca851d6..39368d0c 100644+--- a/dm/games/0100A00019DE0000/game.tsv++++ b/dm/games/0100A00019DE0000/game.tsv+@@ -1,4 +1,5 @@+-# Hades II (Supergiant Games' engine on NVN, SDK 19.3.9), base game v0 (the NACP's display version 0.0.126424).++# Hades II (Supergiant Games' engine on NVN, SDK 19.3.9 base / 20.5.15 update).++# Base game v0 (display version 0.0.126424) and update v1.0.137848 are both registered.+ # Started from the NSP script's provisional profile; values marked "Mario's" are not measured for this game yet.+ # Unlike Hades (Vulkan), the Switch version renders with NVN: its 88 shaders are BNSH files in Shaders/NVN/bin (.vert / .frag; the .shader files list each program's pair).+ # The ExeFS has only main and sdk. main's EOS_* imports (Epic Online Services, from nro/EOSSDK-Switch-Shipping.nro, loaded through nn::ro) stay offline: the host+@@ -16,9 +17,11 @@ app_category public.app-category.action-games+ pad_layout full++ # ---- Versions ----++# The update's build IDs come from its own ExeFS (the base game's from upstream's profile).+ build v0 0.0.126424 main=5219053e5eb156be80fbb2f303779531 sdk=d83a56a5558798414c78ec722867a7da+-package v0+-shader_versions v0++build v1 1.0.137848 main=8ce1ac48e9fa74479051f3520e632df4 sdk=190030518b5d64e5d87b84bc54661af9++package v1++shader_versions v0 v1++ # ---- Files ----+ modules main sdk+@@ -36,6 +39,31 @@ mem_stack 0x10000000+ app_pool 0xCD500000+ mem_used 0x6c00000+++# ---- Widescreen (host only, NOT enabled for this game) ----++# The swapchain size 1280x720 is hardcoded twice in main: a rodata entry at +0x6d337c ({u32 w,++# u32 h}, dead data) and two immediate instructions at +0x2a6080 (movz/movk x8) that write it into++# a config object. Patching the rodata entry does nothing (the immediates win); patching the++# immediates too makes the init run and then crash later (main+0x48e5a4, null deref in the++# 0x2a7a20 call chain): the value feeds more than the swapchain, and whatever else depends on++# 1280x720 specifically is not satisfied by just widening it. Real widescreen for this title++# needs its resolution pipeline reversed — out of scope here.++# Round 2 detail: with the immediates patched to 1600x900, the init crashes at++# main+0x48e5a4 (ldr x2,[x21,#8] with a null x21) inside the 0x2a7a20 chain — the++# allocation at 0x499840 fails or a lookup misses for the wider size. d2r-mobile's++# widescreen works because its title's whole resolution path was brought up: PARAMS++# slots (4 sites) plus the KASPECT aspect cap plus the derived-mask fix, each found++# and tested one by one. The same depth of work is needed here.++++# ---- NVN driver constant segments (Mario's values, the translator's built-in layout, except the texture slot count) ----++# The game's shaders bind textures at fixed, sparse slots: c2 handles at 0x20 + 8 r for r = 0, 1, 3, 6, 8, 11, 15, 21, 25, 26, 30, 31 and 34 over all 88 shaders.++# Slot 34 (SceneFade.frag, 0x130) lies past Mario's 32 slots, where his image table starts; this game has no image bindings and no shader reads c2 at run time++nvn_tex_base 0x20++nvn_tex_slots 35++nvn_samp_base 0x568++nvn_img_base 0x120++nvn_img_slots 8++nvn_ssbo_bases vs=0x110 ps=0x510 cs=0x310+++ # ---- Shader split ----+ shader_groups /Shaders/=shaders+ shader_note Hades II shaders (Shaders/NVN/bin)diff --git a/patches/0016-hle-time-adjustable-clock.patch b/patches/0016-hle-time-adjustable-clock.patchnew file mode 100644index 00000000..ab345281--- /dev/null+++ b/patches/0016-hle-time-adjustable-clock.patch@@ -0,0 +1,77 @@+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001+From: v0lumehi <[email protected]>+Date: Wed, 28 Oct 2026 13:33:55 +0100+Subject: [PATCH] hle_time: CreateWithAdjustableSystemClock and the snapshot+ type byte++The adjustable clock is the same snapshot with type byte 2.++Upstream-Status: backport 4d2dc7db+Reason: CreateWithAdjustableSystemClock and the snapshot type byte (PR #26); merged upstream as 4d2dc7db, so this drops on the bump+Issue: LNPANDY/NX2Apple#26+---+ dm/host/hle_time.c | 9 ++++++++++ dm/host/tests/t_time.c | 26 +++++++++++++++++++++++++-+ 2 files changed, 34 insertions(+), 1 deletion(-)++diff --git a/dm/host/hle_time.c b/dm/host/hle_time.c+index d74039dd..05b05ff9 100644+--- a/dm/host/hle_time.c++++ b/dm/host/hle_time.c+@@ -92,6 +92,15 @@ HLE_FORCE("_ZN2nn4time13ClockSnapshot29CreateWithStandardSystemClockEPS1_", "sna+ h_time_ToCalendarTime((CalendarTime *)(s + 0x50), (CalendarAdditionalInfo *)(s + 0x60), &now);+ memcpy(s + 0x90, tp, 0x18);+ tzset(); strlcpy((char *)s + 0xa8, tzname[0] && *tzname[0] ? tzname[0] : "UTC", 0x24);++ s[0xcd] = 1; // Standard clock snapshot type: CalculateSpanBetween and the user-difference check read it++ return RES_OK;++}++// Both user clocks come from host time; only the type byte distinguishes them (0xcd = 2 for the++// adjustable one). Missing entirely before this: a game that snapshots the adjustable clock read a++// null. From PR #26 (m1guelpf), with its guarded-buffer test.++HLE_FORCE("_ZN2nn4time13ClockSnapshot31CreateWithAdjustableSystemClockEPS1_", "adjustable clock snapshot from host time; the host has no time service session", Result, h_time_AdjSnapshot, uint8_t *s) {++ h_time_Snapshot(s);++ s[0xcd] = 2;+ return RES_OK;+ }+ // Arithmetic on two snapshots: the SDK hands both to the time service (a call through its session, AbortImpl when there is none: STEINS;GATE RE:BOOT's and Tears of the Kingdom's SDK;+diff --git a/dm/host/tests/t_time.c b/dm/host/tests/t_time.c+index 7f26e900..c4253ace 100644+--- a/dm/host/tests/t_time.c++++ b/dm/host/tests/t_time.c+@@ -19,11 +19,35 @@ static void put64(uint8_t *s, int off, int64_t v) { memcpy(s + off, &v, 8); }+ static int64_t get64(const uint8_t *s, int off) { int64_t v; memcpy(&v, s + off, 8); return v; }+ int main(void) {+ Result (*snap)(uint8_t *) = hook("_ZN2nn4time13ClockSnapshot29CreateWithStandardSystemClockEPS1_");++ Result (*adj_snap)(uint8_t *) = hook("_ZN2nn4time13ClockSnapshot31CreateWithAdjustableSystemClockEPS1_");+ Result (*span)(int64_t *, const uint8_t *, const uint8_t *) = hook("_ZN2nn4time20CalculateSpanBetweenEPNS_8TimeSpanERKNS0_13ClockSnapshotES5_");+ int64_t (*udiff)(const uint8_t *, const uint8_t *) = hook("_ZN2nn4time48CalculateStandardUserSystemClockDifferenceByUserERKNS0_13ClockSnapshotES3_");+- if (!snap || !span || !udiff) { printf("time: %d checks, %d failed\n", checks, fails); return 1; }++ if (!snap || !adj_snap || !span || !udiff) { printf("time: %d checks, %d failed\n", checks, fails); return 1; }+ uint8_t a[0xd0], b[0xd0], c[0xd0]; int64_t ts = -1;++ // Before the first snapshot: h_time_GetCurrentTime reads DM_FIXED_TIME once and caches it++ setenv("DM_FIXED_TIME", "1700000000", 1);++ setenv("TZ", "UTC", 1); tzset();+ CHECK(snap(a) == RES_OK, "snapshot a");++ CHECK(a[0xcd] == 1, "standard snapshot type is 1");++ // The adjustable clock is the same data from host time with type 2; the guard bytes prove the++ // entry writes exactly the 0xd0 bytes a ClockSnapshot has (PR #26's test).++ uint8_t guarded[0xf0]; memset(guarded, 0xa5, sizeof guarded);++ uint8_t *adjustable = guarded + 0x10;++ CHECK(adj_snap(adjustable) == RES_OK, "adjustable snapshot");++ int guards_ok = 1;++ for (int i = 0; i < 0x10; i++) guards_ok &= guarded[i] == 0xa5 && guarded[0xe0 + i] == 0xa5;++ CHECK(guards_ok, "adjustable snapshot writes only its 0xd0 bytes");++ CHECK(adjustable[0xcd] == 2, "adjustable snapshot type is 2");++ CHECK(get64(adjustable, 0x40) == 1700000000, "adjustable user time follows the host clock");++ const CalendarTime *cal = (const CalendarTime *)(adjustable + 0x50);++ CHECK(cal->year == 2023 && cal->month == 11 && cal->day == 14 && cal->hour == 22 && cal->minute == 13 && cal->second == 20,++ "adjustable snapshot has the UTC calendar for the fixed time");++ uint8_t zero[0x20] = {0};++ CHECK(!memcmp(adjustable + 0x20, zero, sizeof zero) && get64(adjustable, 0x48) == 0,++ "offline snapshot has no network clock context or time");++ CHECK(!memcmp(a + 0x98, adjustable + 0x98, 16), "both snapshots use the same steady clock source");++ CHECK(udiff(a, adjustable) == 0, "changing snapshot type does not report a user clock change");++ unsetenv("DM_FIXED_TIME");+ CHECK(span(&ts, a, a) == RES_OK && ts == 0, "span of a snapshot with itself is 0");+ memcpy(b, a, sizeof b); put64(b, 0x90, get64(a, 0x90) + 90); // b: 90 s of steady clock later+ CHECK(span(&ts, a, b) == RES_OK && ts == 90 * 1000000000LL, "span from the steady time points, in nanoseconds");diff --git a/patches/0017-env-switches-verify.patch b/patches/0017-env-switches-verify.patchnew file mode 100644index 00000000..db15ef71--- /dev/null+++ b/patches/0017-env-switches-verify.patch@@ -0,0 +1,114 @@+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001+From: v0lumehi <[email protected]>+Date: Wed, 28 Oct 2026 13:33:55 +0100+Subject: [PATCH] env_switches.py --verify: every DM_* a text names must be a+ real switch++Plus two lines in docs/agents/README.md.++Upstream-Status: pending+Reason: env_switches.py --verify checks a draft for DM_* names that are not real switches; the agent guide says to run it+Issue: LNPANDY/NX2Apple#123+---+ dm/tools/env_switches.py | 30 ++++++++++++++++++++++++++++++ dm/tools/tests/test_env_switches.py | 23 +++++++++++++++++++++-+ docs/agents/README.md | 2 +++ 3 files changed, 54 insertions(+), 1 deletion(-)++diff --git a/dm/tools/env_switches.py b/dm/tools/env_switches.py+index 29dc91dc..8606f369 100644+--- a/dm/tools/env_switches.py++++ b/dm/tools/env_switches.py+@@ -72,7 +72,37 @@ def rows():+ return HEAD + ''.join(out), bad, unread++++def verify_texts(paths):++ """Every DM_* name these files mention must be one the sources read (docs/env_switches.tsv), or a++ family a row documents: DM_PROF_<key> builds its name at run time, so no row can exist per member++ and the table names the family instead. A name ending in _ is a family prefix itself.++++ Written after two replies in one day recommended DM_LOG_UEMALLOC and DM_NVN_ALIAS_TRACE, neither++ of which exists: a name recalled from memory rather than read out of the table. Run this over a++ draft before posting it.++ """++ known, family = set(), set()++ if TABLE.exists():++ for l in TABLE.read_text().split('\n'):++ f = l.split('\t')++ if not f or not f[0].startswith('DM_'): continue++ known.add(f[0])++ for m in re.finditer(r'(' + NAME + r')_[<*]', '\t'.join(f[1:])):++ family.add(m.group(1))++ bad = []++ for p in paths:++ for n in sorted(set(re.findall(NAME, Path(p).read_text(encoding='utf-8', errors='replace')))):++ if n.endswith('_'): continue # a family prefix itself ("DM_NVN_*")++ if n not in known and not any(k.startswith(n + '_') for k in known) and n not in family:++ bad.append((p, n)) # unknown, and no row starts with it++ return bad, len(known)+++ if __name__ == '__main__':++ if sys.argv[1:2] == ['--verify']:++ problems, known = verify_texts(sys.argv[2:])++ for p, n in problems: print(f'{p}: {n} is not a switch the sources read')++ print(f'{len(problems)} unknown name(s) against {known} known switches')++ raise SystemExit(1 if problems else 0)+ text, bad, unread = rows()+ if unread: print('quoted in the docs but read nowhere (check that each mention says it was removed): ' + ' '.join(unread))+ if sys.argv[1:] == ['--check']:+diff --git a/dm/tools/tests/test_env_switches.py b/dm/tools/tests/test_env_switches.py+index 604494c9..e6a5ac1e 100644+--- a/dm/tools/tests/test_env_switches.py++++ b/dm/tools/tests/test_env_switches.py+@@ -1,8 +1,12 @@+ """docs/env_switches.tsv lists every DM_* switch the code reads, each with a class and a meaning (dm/tools/env_switches.py writes it; class and meaning are kept by hand).+-A switch the code reads that the table does not list, a row for a switch nothing reads any more, or a row without a meaning fails here."""++A switch the code reads that the table does not list, a row for a switch nothing reads any more, or a row without a meaning fails here.++++`--verify <file>...` checks a text instead: every DM_* it names must be a real switch. It exists because two replies wrote DM_LOG_UEMALLOC and DM_NVN_ALIAS_TRACE from memory in++one day, and neither is a switch — a reader who trusts them wastes a run and learns nothing."""+ from pathlib import Path+ import subprocess+ import sys++import tempfile+ import unittest++ REPO = Path(__file__).resolve().parents[3]+@@ -13,6 +17,23 @@ class EnvSwitches(unittest.TestCase):+ r = subprocess.run([sys.executable, str(REPO / 'dm/tools/env_switches.py'), '--check'], cwd=REPO, capture_output=True, text=True)+ self.assertEqual(r.returncode, 0, r.stdout + r.stderr)+++ def test_verify_accepts_a_real_switch_and_rejects_an_invented_one(self):++ with tempfile.TemporaryDirectory() as d:++ good = Path(d, 'good.md'); good.write_text('Set `DM_IMPORTS=1` to see the imports.\n')++ r = subprocess.run([sys.executable, str(REPO / 'dm/tools/env_switches.py'), '--verify', str(good)], cwd=REPO, capture_output=True, text=True)++ self.assertEqual(r.returncode, 0, r.stdout + r.stderr)++++ bad = Path(d, 'bad.md'); bad.write_text('Set `DM_LOG_UEMALLOC=1` to see the allocations.\n')++ r = subprocess.run([sys.executable, str(REPO / 'dm/tools/env_switches.py'), '--verify', str(bad)], cwd=REPO, capture_output=True, text=True)++ self.assertEqual(r.returncode, 1, 'an invented switch must fail the check')++ self.assertIn('DM_LOG_UEMALLOC', r.stdout)++++ def test_verify_ignores_a_prefix_and_a_family(self):++ with tempfile.TemporaryDirectory() as d:++ f = Path(d, 'prefixes.md'); f.write_text('`DM_PROF_<key>` overrides; `DM_NVN_*` are the graphics ones; `DM_MEMSTAT` is real.\n')++ r = subprocess.run([sys.executable, str(REPO / 'dm/tools/env_switches.py'), '--verify', str(f)], cwd=REPO, capture_output=True, text=True)++ self.assertEqual(r.returncode, 0, r.stdout + r.stderr)++++ if __name__ == '__main__':+ unittest.main()+diff --git a/docs/agents/README.md b/docs/agents/README.md+index a6ef501a..d832bcd7 100644+--- a/docs/agents/README.md++++ b/docs/agents/README.md+@@ -22,6 +22,8 @@ Everything here was learned on Diablo II: Resurrected (SDK ~12, NVN 53, the orig+ - **One repository, one profile per title.** nxnative (first called smbw-mobile) started as a copy of d2r-mobile's generic parts. Title- or SDK-specific constants live in the game profile `dm/games/<id>/` ([dm/games/README.md](../../dm/games/README.md)). That covers program ID, known builds, modules, address-space partition, NVN driver tables, the shader tables and the app identity. The code reads the profile through `game_profile.h` (host) or `dm/games/game.py` (tools). Behaviour that fits only one title's code is gated by that title's build ID (`dm_main_build()`), never left on for every title. Some things are still built into the translator: the texture / sampler handle bases and the depth mode (see [04](04-graphics.md)). `dmsh_build.py` refuses a profile whose bases differ from the translator's.+ - **Write code comments in English**, and start log lines that mark something unimplemented or wrong with `[RED] `.+ - **Test where it runs.** The Mac host (`dm/host/dmhost`) is the development loop; the iOS app reuses the same host and graphics code. Never claim something works on iOS without running it there.++- **A test that has not failed is not evidence.** A fix's test must fail before the fix and pass after it; run it both ways, or at least confirm it is collected and that its assertion touches the changed behaviour. Three failures in two days, all of them mine: a test appended *after* the class's closing brace (XCTest never collected it — the suite reported the same count before and after it existed, and I read that as a pass); `assertIn('TEXT_LO = segs[0][1]', src)`, a string match that stays green while the module raises `NameError` on import; and a release-notes splitter whose two failing cases only appeared once the test existed. A green suite is a claim about the code only if the test would have been red.++- **A switch you recommend exists.** Before naming a `DM_*` in a reply, an issue body or a PR, check it against `docs/env_switches.tsv` (generated from the sources): `python3 dm/tools/env_switches.py --verify draft.md` fails on every name that is neither a row nor a documented family. Two replies written from memory in one day told reporters to set `DM_LOG_UEMALLOC` and `DM_NVN_ALIAS_TRACE`, neither of which exists; they wasted a run each and learned nothing.++ ## Checklist for a new title+diff --git a/patches/0018-touchpad-geometry.patch b/patches/0018-touchpad-geometry.patchnew file mode 100644index 00000000..e49567fd--- /dev/null+++ b/patches/0018-touchpad-geometry.patch@@ -0,0 +1,370 @@+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001+From: v0lumehi <[email protected]>+Date: Wed, 28 Oct 2026 13:33:55 +0100+Subject: [PATCH] Virtual-pad geometry and its test++touchpad_geometry.h and t_touchpad_geometry.c.++Upstream-Status: fork-only+Reason: Virtual-pad geometry used by tests only; a fork experiment without a hook in the host+Issue: LNPANDY/NX2Apple#123+---+ dm/host/tests/Makefile | 5 +-+ dm/host/tests/t_touchpad_geometry.c | 131 +++++++++++++++++++++ dm/host/touchpad_geometry.h | 179 +++++++++++++++++++++++++++++ 3 files changed, 314 insertions(+), 1 deletion(-)+ create mode 100644 dm/host/tests/t_touchpad_geometry.c+ create mode 100644 dm/host/touchpad_geometry.h++diff --git a/dm/host/tests/Makefile b/dm/host/tests/Makefile+index 36029d14..8945c283 100644+--- a/dm/host/tests/Makefile++++ b/dm/host/tests/Makefile+@@ -7,7 +7,7 @@ PYTHON ?= python3+ GINC = $(if $(strip $(GAME)),-I../gen/$(GAME) -I../../games/$(GAME),$(error GAME is not set: make GAME=<base game title ID>: $(shell python3 ../../games/game.py list | awk -F'\t' '{printf "%s (%s) ", $$1, $$3}')))+ $(B)/t_fs $(B)/t_fs_case $(B)/t_fs_commit_list $(B)/t_fs_commit_list_tsan: ../romfs_image.h+ GAME_H = ../gen/$(GAME)/game_profile.h+-run: $(B)/t_heap_size $(B)/t_touch $(B)/t_gesture $(B)/t_oe $(B)/t_fs $(B)/t_fs_commit_list $(B)/t_thread_leak $(B)/t_fs_case $(B)/t_audio $(B)/t_audio_spsc $(B)/t_swkbd $(B)/t_altstack $(B)/t_condvar $(B)/t_condvar_old $(B)/t_pctl $(B)/t_time $(B)/t_shared_font $(B)/t_vorbis $(B)/t_vorbis_divides $(B)/t_hid $(B)/t_input_map $(B)/t_launcher_contract $(B)/t_haptics $(B)/t_haptics_apple++run: $(B)/t_heap_size $(B)/t_touch $(B)/t_gesture $(B)/t_oe $(B)/t_fs $(B)/t_fs_commit_list $(B)/t_thread_leak $(B)/t_fs_case $(B)/t_audio $(B)/t_audio_spsc $(B)/t_swkbd $(B)/t_altstack $(B)/t_condvar $(B)/t_condvar_old $(B)/t_pctl $(B)/t_time $(B)/t_shared_font $(B)/t_vorbis $(B)/t_vorbis_divides $(B)/t_hid $(B)/t_input_map $(B)/t_launcher_contract $(B)/t_haptics $(B)/t_haptics_apple $(B)/t_touchpad_geometry+ $(B)/t_heap_size+ $(B)/t_touch+ $(B)/t_gesture+@@ -39,6 +39,7 @@ run: $(B)/t_heap_size $(B)/t_touch $(B)/t_gesture $(B)/t_oe $(B)/t_fs $(B)/t_fs_+ $(B)/t_launcher_contract+ $(B)/t_haptics+ $(B)/t_haptics_apple++ $(B)/t_touchpad_geometry+ $(B)/t_nro+ $(B)/t_symbols+ run: $(B)/t_nro+@@ -128,6 +129,8 @@ $(B)/t_hid_tsan: t_hid.c ../hle_hid.c ../hle_haptics.c ../hle_haptics.h ../pad_s+ clang -O1 -g -fsanitize=thread -Wall -Werror -Wno-unused-function -I.. $(GINC) -o $@ t_hid.c ../hle_haptics.c+ $(B)/t_haptics: t_haptics.c ../hle_haptics.c ../hle_haptics.h ../dm_input.h | $(B)+ clang -O1 -g -Wall -Werror -I.. -o $@ t_haptics.c ../hle_haptics.c++$(B)/t_touchpad_geometry: t_touchpad_geometry.c ../touchpad_geometry.h ../dm_input.h | $(B)++ clang -O1 -Wall -I.. $(GINC) -o $@ t_touchpad_geometry.c+ $(B)/t_haptics_apple: t_haptics_apple.m ../haptics_apple.m ../haptics_apple.h ../hle_haptics.c ../hle_haptics.h | $(B)+ clang -O1 -g -fobjc-arc -Wall -Werror -I.. -o $@ t_haptics_apple.m ../hle_haptics.c -framework Cocoa -framework GameController -framework CoreHaptics -framework IOKit+ $(B)/t_time: t_time.c ../hle_time.c ../hle.h ../dm.h $(GAME_H) | $(B)+diff --git a/dm/host/tests/t_touchpad_geometry.c b/dm/host/tests/t_touchpad_geometry.c+new file mode 100644+index 00000000..bad6c625+--- /dev/null++++ b/dm/host/tests/t_touchpad_geometry.c+@@ -0,0 +1,131 @@++#include "../touchpad_geometry.h"++#include <assert.h>++#include <math.h>++#include <stdio.h>++++static void nearf(float actual, float expected, float tolerance) {++ assert(fabsf(actual - expected) <= tolerance);++}++++static void test_layout(float width, float height, float expected_u) {++ float u = dm_touchpad_u(height);++ nearf(u, expected_u, 0.0001f);++++ dm_touchpad_point face = dm_touchpad_face_center(width, height, 0, 0, 0, 0);++ dm_touchpad_point stick = dm_touchpad_stick_home(width, height, 0, 0, 0, 0);++ dm_touchpad_point dpad = dm_touchpad_dpad_center(width, height, 0, 0, 0, 0);++ nearf(face.x, width - DM_TP_FACE_X * u, 0.001f);++ nearf(face.y, height - DM_TP_PAD_Y * u, 0.001f);++ nearf(stick.x, DM_TP_STICK_X * u, 0.001f);++ nearf(stick.y, height - DM_TP_PAD_Y * u, 0.001f);++ nearf(dpad.x, DM_TP_LOW_X * u, 0.001f);++ nearf(dpad.y, height - DM_TP_LOW_Y * u, 0.001f);++++ dm_touchpad_point a = dm_touchpad_face_button(width, height, 0, 0, 0, 0, 0);++ dm_touchpad_point b = dm_touchpad_face_button(width, height, 0, 0, 0, 0, 1);++ dm_touchpad_point x = dm_touchpad_face_button(width, height, 0, 0, 0, 0, 2);++ dm_touchpad_point y = dm_touchpad_face_button(width, height, 0, 0, 0, 0, 3);++ float gap = DM_TP_FACE_GAP * u;++ nearf(a.x - face.x, gap, 0.001f); nearf(a.y, face.y, 0.001f);++ nearf(b.y - face.y, gap, 0.001f); nearf(b.x, face.x, 0.001f);++ nearf(x.y - face.y, -gap, 0.001f); nearf(x.x, face.x, 0.001f);++ nearf(y.x - face.x, -gap, 0.001f); nearf(y.y, face.y, 0.001f);++}++++static void test_directional_ownership(void) {++ const float cx = 400, cy = 300, gap = 50, radius = 33.75f;++ assert(dm_touchpad_face_buttons(cx + gap, cy, cx, cy, gap, radius) & DM_BTN_A);++ assert(dm_touchpad_face_buttons(cx, cy + gap, cx, cy, gap, radius) & DM_BTN_B);++ assert(dm_touchpad_face_buttons(cx, cy - gap, cx, cy, gap, radius) & DM_BTN_X);++ assert(dm_touchpad_face_buttons(cx - gap, cy, cx, cy, gap, radius) & DM_BTN_Y);++++ const float r = 48;++ assert(dm_touchpad_dpad_buttons(cx + r, cy, cx, cy, r) == DM_BTN_RIGHT);++ assert(dm_touchpad_dpad_buttons(cx, cy - r, cx, cy, r) == DM_BTN_UP);++ assert(dm_touchpad_dpad_buttons(cx - r, cy, cx, cy, r) == DM_BTN_LEFT);++ assert(dm_touchpad_dpad_buttons(cx, cy + r, cx, cy, r) == DM_BTN_DOWN);++ assert(dm_touchpad_dpad_buttons(cx + r, cy - r, cx, cy, r) == (DM_BTN_RIGHT | DM_BTN_UP));++ assert(dm_touchpad_dpad_buttons(cx, cy, cx, cy, r) == 0); // native centre dead region++}++++static void test_stick_shaping(void) {++ const float r = 77;++ int32_t x, y;++ dm_touchpad_stick_axis(r * 0.05f, 0, r, 0, &x, &y);++ assert(x == 0 && y == 0); // dead zone++++ dm_touchpad_stick_axis(r * 0.45f, 0, r, 0, &x, &y);++ assert(x >= 16383 && x <= 16384 && y == 0); // half of full travel after dead-zone remap++++ dm_touchpad_stick_axis(0, -r, r, 0, &x, &y);++ assert(x == 0 && y == DM_STICK_MAX);++ dm_touchpad_stick_axis(-r, 0, r, 0, &x, &y);++ assert(x == -DM_STICK_MAX && y == 0);++++ dm_touchpad_stick_axis(r * 0.1f, 0, r, 1, &x, &y);++ assert(x == DM_STICK_MAX && y == 0); // legacy full-tilt right-stick mode++}++++static void test_safe_insets_and_resize(void) {++ dm_touchpad_rect safe = dm_touchpad_safe_rect(844, 390, 42, 0, 42, 21);++ nearf(safe.x, 42, 0.001f); nearf(safe.y, 0, 0.001f);++ nearf(safe.width, 760, 0.001f); nearf(safe.height, 369, 0.001f);++++ dm_touchpad_rect corner = dm_touchpad_corner_rect(844, 390, 42, 0, 42, 21);++ nearf(corner.x, 21, 0.001f); nearf(corner.width, 802, 0.001f);++ nearf(corner.height, 369, 0.001f);++ dm_touchpad_point face = dm_touchpad_face_center(844, 390, 42, 0, 42, 21);++ dm_touchpad_point stick = dm_touchpad_stick_home(844, 390, 42, 0, 42, 21);++ float u = 390.0f / 430.0f;++ nearf(face.x, 21 + 802 - DM_TP_FACE_X * u, 0.001f);++ nearf(stick.x, 21 + DM_TP_STICK_X * u, 0.001f);++++ // 16:9 and 21:10 both cap control size at 1.3; a short resized window scales down.++ test_layout(1920, 1080, 1.3f);++ test_layout(1680, 800, 1.3f);++ test_layout(1280, 430, 1.0f);++}++++static void test_botw_right_cluster_and_camera_tap(void) {++ for (int i = 0; i < 2; i++) {++ float w = i ? 1920.0f : 844.0f, h = i ? 1080.0f : 390.0f;++ float u = dm_touchpad_u(h);++ dm_touchpad_point face = dm_touchpad_face_center(w,h,0,0,0,0);++ dm_touchpad_point r = dm_touchpad_right_shoulder(w,h,0,0,0,0,0);++ dm_touchpad_point zr = dm_touchpad_right_shoulder(w,h,0,0,0,0,1);++ dm_touchpad_point x = dm_touchpad_face_button(w,h,0,0,0,0,2);++ nearf(r.y,zr.y,0.001f);++ nearf(zr.x-r.x,(DM_TP_ZL_R*2+DM_TP_SHOULDER_GAP)*u,0.001f);++ assert(r.y + DM_TP_ZL_R*u < x.y - DM_TP_FACE_R*u);++ assert(zr.x + DM_TP_ZL_R*u < w);++ float xgr = DM_TP_FACE_R * u * 1.25f;++ float shoulder_hit = DM_TP_ZL_R * u * DM_TP_SHOULDER_HIT_SCALE;++ assert(hypotf(r.x-x.x,r.y-x.y) > shoulder_hit+xgr);++ assert(hypotf(zr.x-x.x,zr.y-x.y) > shoulder_hit+xgr);++ assert(face.y > 0);++++ float slop = DM_TP_LOOK_TAP_SLOP*u;++ assert(!dm_touchpad_look_dragged(400,200,400+slop*.5f,200,slop));++ assert(dm_touchpad_look_dragged(400,200,400+slop*1.1f,200,slop));++ // A drag that returns to its start is still classified as a drag by the caller's sticky flag.++ int dragged = dm_touchpad_look_dragged(400,200,400+slop*1.1f,200,slop);++ assert(dragged);++ assert(dm_touchpad_look_tap(.2f,0));++ assert(!dm_touchpad_look_tap(.36f,0));++ assert(!dm_touchpad_look_tap(.1f,1));++ assert(dm_touchpad_look_double_tap(10000000.08,10000000.28,100,100,101,102,u));++ assert(!dm_touchpad_look_double_tap(10000000.08,10000000.48,100,100,101,102,u));++ assert(!dm_touchpad_look_double_tap(10000000.08,10000000.28,100,100,100+49*u,102,u));++ dragged |= dm_touchpad_look_dragged(400,200,400,200,slop);++ assert(dragged);++ }++}++++int main(void) {++ test_directional_ownership();++ test_stick_shaping();++ test_safe_insets_and_resize();++ test_botw_right_cluster_and_camera_tap();++ puts("touchpad geometry: direction ownership, layout, and stick shaping passed");++ return 0;++}+diff --git a/dm/host/touchpad_geometry.h b/dm/host/touchpad_geometry.h+new file mode 100644+index 00000000..affbb2d1+--- /dev/null++++ b/dm/host/touchpad_geometry.h+@@ -0,0 +1,179 @@++// Shared virtual-pad geometry for the UIKit controls and the opt-in Mac preview.++#pragma once++#include <math.h>++++typedef struct { float x, y; } dm_touchpad_point;++typedef struct { float x, y, width, height; } dm_touchpad_rect;++++#include "dm_input.h"++++#define DM_TP_ZL_X 44.0f++#define DM_TP_ZL_Y 40.0f++#define DM_TP_ZL_R 26.0f++#define DM_TP_L_X 44.0f++#define DM_TP_L_Y 108.0f++#define DM_TP_L_R 24.0f++#define DM_TP_DROP_TIP 1.45f++#define DM_TP_CORNER_IN 0.5f++#define DM_TP_FACE_X 81.0f++#define DM_TP_PAD_Y 82.0f++#define DM_TP_FACE_GAP 50.0f++#define DM_TP_FACE_R 27.0f++#define DM_TP_PILL_DX 52.0f++#define DM_TP_PILL_Y 22.0f++#define DM_TP_PILL_W 50.0f++#define DM_TP_PILL_H 28.0f++#define DM_TP_SWAP_R 15.0f++#define DM_TP_STICK_X 81.0f++#define DM_TP_STICK_R 77.0f++#define DM_TP_KNOB_R 30.0f++#define DM_TP_STICK_GRAB 1.4f++#define DM_TP_LSWIPE (1.0f / 3.0f)++#define DM_TP_FULL 0.8f++#define DM_TP_DEAD 0.1f++#define DM_TP_LOW_X 231.0f++#define DM_TP_LOW_Y 64.0f++#define DM_TP_DPAD_R 48.0f++#define DM_TP_ARM_W 17.0f++#define DM_TP_ARM_IN 11.0f++#define DM_TP_DPAD_GRAB 1.3f++#define DM_TP_RSTICK_R 60.0f++#define DM_TP_RSWIPE (1.0f / 2.0f)++#define DM_TP_CLICK_X 102.0f++#define DM_TP_CLICK_R 17.0f++#define DM_TP_LOOK_TAP_SLOP 12.0f++#define DM_TP_LOOK_TAP_MAX_SECONDS 0.35f++#define DM_TP_LOOK_DOUBLE_TAP_INTERVAL 0.35f++#define DM_TP_LOOK_DOUBLE_TAP_DISTANCE 48.0f++#define DM_TP_SHOULDER_GAP 8.0f++#define DM_TP_SHOULDER_HIT_SCALE 1.0f++++static inline float dm_touchpad_u(float height) {++ float u = height / 430.0f;++ return u < 1.3f ? u : 1.3f;++}++++// safe insets and result use top-left coordinates, as UIKit does. AppKit++// callers convert their bottom-left mouse coordinates at the view boundary.++static inline dm_touchpad_rect dm_touchpad_corner_rect(float width, float height,++ float left, float top,++ float right, float bottom) {++ return (dm_touchpad_rect){left * .5f, top, width - (left + right) * .5f,++ height - top - bottom};++}++++static inline dm_touchpad_rect dm_touchpad_safe_rect(float width, float height,++ float left, float top,++ float right, float bottom) {++ return (dm_touchpad_rect){left, top, width - left - right, height - top - bottom};++}++++static inline dm_touchpad_point dm_touchpad_face_center(float width, float height,++ float left, float top,++ float right, float bottom) {++ dm_touchpad_rect c = dm_touchpad_corner_rect(width, height, left, top, right, bottom);++ float u = dm_touchpad_u(height);++ return (dm_touchpad_point){c.x + c.width - DM_TP_FACE_X * u,++ c.y + c.height - DM_TP_PAD_Y * u};++}++++// R and ZR sit together just above the face cluster on BOTW's virtual pad.++static inline dm_touchpad_point dm_touchpad_right_shoulder(float width, float height,++ float left, float top,++ float right, float bottom,++ int zr) {++ dm_touchpad_point face = dm_touchpad_face_center(width, height, left, top, right, bottom);++ float u = dm_touchpad_u(height);++ float half = (DM_TP_ZL_R + DM_TP_SHOULDER_GAP * .5f) * u;++ float y = face.y - (DM_TP_FACE_GAP + DM_TP_FACE_R + DM_TP_ZL_R + 18.0f) * u;++ return (dm_touchpad_point){face.x + (zr ? half : -half), y};++}++++static inline int dm_touchpad_look_dragged(float down_x, float down_y,++ float x, float y, float slop) {++ float dx = x - down_x, dy = y - down_y;++ return dx * dx + dy * dy > slop * slop;++}++static inline int dm_touchpad_look_tap(float duration, int dragged) {++ return !dragged && duration >= 0.0f && duration <= DM_TP_LOOK_TAP_MAX_SECONDS;++}++static inline int dm_touchpad_look_double_tap(double first_time, double second_time,++ float first_x, float first_y,++ float second_x, float second_y,++ float u) {++ float dx = second_x - first_x, dy = second_y - first_y;++ double dt = second_time - first_time;++ float limit = DM_TP_LOOK_DOUBLE_TAP_DISTANCE * u;++ return dt >= 0.0f && dt <= DM_TP_LOOK_DOUBLE_TAP_INTERVAL && dx*dx + dy*dy <= limit*limit;++}++++static inline dm_touchpad_point dm_touchpad_stick_home(float width, float height,++ float left, float top,++ float right, float bottom) {++ dm_touchpad_rect c = dm_touchpad_corner_rect(width, height, left, top, right, bottom);++ float u = dm_touchpad_u(height);++ return (dm_touchpad_point){c.x + DM_TP_STICK_X * u,++ c.y + c.height - DM_TP_PAD_Y * u};++}++++static inline dm_touchpad_point dm_touchpad_dpad_center(float width, float height,++ float left, float top,++ float right, float bottom) {++ dm_touchpad_rect c = dm_touchpad_corner_rect(width, height, left, top, right, bottom);++ float u = dm_touchpad_u(height);++ return (dm_touchpad_point){c.x + DM_TP_LOW_X * u,++ c.y + c.height - DM_TP_LOW_Y * u};++}++++static inline dm_touchpad_point dm_touchpad_face_button(float width, float height,++ float left, float top,++ float right, float bottom,++ int button) {++ dm_touchpad_point c = dm_touchpad_face_center(width, height, left, top, right, bottom);++ float g = DM_TP_FACE_GAP * dm_touchpad_u(height);++ switch (button) {++ case 0: c.x += g; break; // A++ case 1: c.y += g; break; // B++ case 2: c.y -= g; break; // X++ default: c.x -= g; break; // Y++ }++ return c;++}++++static inline uint64_t dm_touchpad_face_buttons(float x, float y, float center_x,++ float center_y, float gap, float radius) {++ uint64_t bits = 0;++ for (int b = 0; b < 4; b++) {++ dm_touchpad_point c = {center_x, center_y};++ if (b == 0) c.x += gap;++ else if (b == 1) c.y += gap;++ else if (b == 2) c.y -= gap;++ else c.x -= gap;++ float dx = x - c.x, dy = y - c.y;++ if (dx * dx + dy * dy <= radius * radius) bits |= 1ull << b;++ }++ return bits;++}++++static inline uint64_t dm_touchpad_dpad_buttons(float x, float y, float center_x,++ float center_y, float radius) {++ float dx = x - center_x, dy = y - center_y;++ if (hypotf(dx, dy) < radius * .25f) return 0;++ float a = atan2f(-dy, dx) * (180.0f / 3.14159265358979323846f);++ uint64_t bits = 0;++ if (a > -67.5f && a < 67.5f) bits |= DM_BTN_RIGHT;++ if (a > 22.5f && a < 157.5f) bits |= DM_BTN_UP;++ if (a > 112.5f || a < -112.5f) bits |= DM_BTN_LEFT;++ if (a < -22.5f && a > -157.5f) bits |= DM_BTN_DOWN;++ return bits;++}++++static inline void dm_touchpad_stick_axis(float dx, float dy, float radius,++ int full_tilt, int32_t *x, int32_t *y) {++ float d = hypotf(dx, dy), dead = radius * DM_TP_DEAD;++ if (d <= (full_tilt ? 0.0f : dead) || radius <= 0.0f) { *x = *y = 0; return; }++ float magnitude = (full_tilt ? 1.0f : fminf((d - dead) / (radius * DM_TP_FULL - dead), 1.0f)) / d;++ *x = (int32_t)lrintf(dx * magnitude * DM_STICK_MAX);++ *y = (int32_t)lrintf(-dy * magnitude * DM_STICK_MAX);++}++diff --git a/patches/0019-ios-probe.patch b/patches/0019-ios-probe.patchnew file mode 100644index 00000000..22acdd5f--- /dev/null+++ b/patches/0019-ios-probe.patch@@ -0,0 +1,1332 @@+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001+From: v0lumehi <[email protected]>+Date: Wed, 28 Oct 2026 13:33:55 +0100+Subject: [PATCH] iOS probe app for dlopen experiments++dm/ios/probe and docs/probe-dlopen.md.++Upstream-Status: fork-only+Reason: dlopen probe app (an experiment) and its write-up; not upstream material+Issue: LNPANDY/NX2Apple#123+---+ dm/ios/probe/.gitignore | 2 ++ .../probe/DmProbe.xcodeproj/project.pbxproj | 422 +++++++++++++++++++ .../contents.xcworkspacedata | 7 ++ .../UserInterfaceState.xcuserstate | Bin 0 -> 17187 bytes+ .../xcshareddata/xcschemes/DmProbe.xcscheme | 101 ++++++ dm/ios/probe/build_probe.sh | 112 ++++++ dm/ios/probe/probe-Info.plist | 37 +++ dm/ios/probe/probe-framework-Info.plist | 24 ++ dm/ios/probe/project.yml | 59 ++++ dm/ios/probe/src/probe.c | 6 ++ dm/ios/probe/src/probe_main.m | 159 ++++++++ docs/probe-dlopen.md | 92 +++++ 12 files changed, 1021 insertions(+)+ create mode 100644 dm/ios/probe/.gitignore+ create mode 100644 dm/ios/probe/DmProbe.xcodeproj/project.pbxproj+ create mode 100644 dm/ios/probe/DmProbe.xcodeproj/project.xcworkspace/contents.xcworkspacedata+ create mode 100644 dm/ios/probe/DmProbe.xcodeproj/project.xcworkspace/xcuserdata/hejie.xcuserdatad/UserInterfaceState.xcuserstate+ create mode 100644 dm/ios/probe/DmProbe.xcodeproj/xcshareddata/xcschemes/DmProbe.xcscheme+ create mode 100755 dm/ios/probe/build_probe.sh+ create mode 100644 dm/ios/probe/probe-Info.plist+ create mode 100644 dm/ios/probe/probe-framework-Info.plist+ create mode 100644 dm/ios/probe/project.yml+ create mode 100644 dm/ios/probe/src/probe.c+ create mode 100644 dm/ios/probe/src/probe_main.m+ create mode 100644 docs/probe-dlopen.md++diff --git a/dm/ios/probe/.gitignore b/dm/ios/probe/.gitignore+new file mode 100644+index 00000000..a8ad17b6+--- /dev/null++++ b/dm/ios/probe/.gitignore+@@ -0,0 +1,2 @@++# The build_probe.sh staging tree and the IPA self-check extraction (rebuild with build_probe.sh)++build/+diff --git a/dm/ios/probe/DmProbe.xcodeproj/project.pbxproj b/dm/ios/probe/DmProbe.xcodeproj/project.pbxproj+new file mode 100644+index 00000000..bdc31f0c+--- /dev/null++++ b/dm/ios/probe/DmProbe.xcodeproj/project.pbxproj+@@ -0,0 +1,422 @@++// !$*UTF8*$!++{++ archiveVersion = 1;++ classes = {++ };++ objectVersion = 77;++ objects = {++++/* Begin PBXBuildFile section */++ 2013F6CD064EE80DD5843D45 /* Probe.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = FE4AE6108123D746C5393ED7 /* Probe.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };++ 418AA9F224215885616DF281 /* probe.c in Sources */ = {isa = PBXBuildFile; fileRef = 9D35A9F8119FFBEE2C503AAD /* probe.c */; };++ 7A77ECBDCAD18AF9F0479F18 /* Probe.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = FE4AE6108123D746C5393ED7 /* Probe.framework */; };++ E87D64C1AB95AA2BE70D72EF /* probe_main.m in Sources */ = {isa = PBXBuildFile; fileRef = FB06C46F0E8AB6B859924E6A /* probe_main.m */; };++/* End PBXBuildFile section */++++/* Begin PBXContainerItemProxy section */++ FF0604D39539FFF1AF62F0FC /* PBXContainerItemProxy */ = {++ isa = PBXContainerItemProxy;++ containerPortal = 665957B2F37792FAF81F0760 /* Project object */;++ proxyType = 1;++ remoteGlobalIDString = 5A4AE636FE4AFD6115D14AF3;++ remoteInfo = Probe;++ };++/* End PBXContainerItemProxy section */++++/* Begin PBXCopyFilesBuildPhase section */++ 0B5D80247451CC6CD1A2E376 /* Embed Frameworks */ = {++ isa = PBXCopyFilesBuildPhase;++ buildActionMask = 2147483647;++ dstPath = "";++ dstSubfolderSpec = 10;++ files = (++ 2013F6CD064EE80DD5843D45 /* Probe.framework in Embed Frameworks */,++ );++ name = "Embed Frameworks";++ runOnlyForDeploymentPostprocessing = 0;++ };++/* End PBXCopyFilesBuildPhase section */++++/* Begin PBXFileReference section */++ 43150F93F9204EF615D94F11 /* DmProbe.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = DmProbe.app; sourceTree = BUILT_PRODUCTS_DIR; };++ 9D35A9F8119FFBEE2C503AAD /* probe.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = probe.c; sourceTree = "<group>"; };++ FB06C46F0E8AB6B859924E6A /* probe_main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = probe_main.m; sourceTree = "<group>"; };++ FE4AE6108123D746C5393ED7 /* Probe.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Probe.framework; sourceTree = BUILT_PRODUCTS_DIR; };++/* End PBXFileReference section */++++/* Begin PBXFrameworksBuildPhase section */++ 3A942D989AEB0836E1497A36 /* Frameworks */ = {++ isa = PBXFrameworksBuildPhase;++ buildActionMask = 2147483647;++ files = (++ 7A77ECBDCAD18AF9F0479F18 /* Probe.framework in Frameworks */,++ );++ runOnlyForDeploymentPostprocessing = 0;++ };++/* End PBXFrameworksBuildPhase section */++++/* Begin PBXGroup section */++ 667940E40ADC709A064A55E0 /* src */ = {++ isa = PBXGroup;++ children = (++ FB06C46F0E8AB6B859924E6A /* probe_main.m */,++ 9D35A9F8119FFBEE2C503AAD /* probe.c */,++ );++ path = src;++ sourceTree = "<group>";++ };++ CA160661865E290DF4649052 = {++ isa = PBXGroup;++ children = (++ 667940E40ADC709A064A55E0 /* src */,++ DDB49E56DB02F4E7561FE966 /* Products */,++ );++ sourceTree = "<group>";++ };++ DDB49E56DB02F4E7561FE966 /* Products */ = {++ isa = PBXGroup;++ children = (++ 43150F93F9204EF615D94F11 /* DmProbe.app */,++ FE4AE6108123D746C5393ED7 /* Probe.framework */,++ );++ name = Products;++ sourceTree = "<group>";++ };++/* End PBXGroup section */++++/* Begin PBXNativeTarget section */++ 27BF26B4447D8FE4545DC557 /* DmProbe */ = {++ isa = PBXNativeTarget;++ buildConfigurationList = FB9912A086081F2D19165946 /* Build configuration list for PBXNativeTarget "DmProbe" */;++ buildPhases = (++ FACD769F731E7788343A6BD1 /* Sources */,++ 3A942D989AEB0836E1497A36 /* Frameworks */,++ 0B5D80247451CC6CD1A2E376 /* Embed Frameworks */,++ );++ buildRules = (++ );++ dependencies = (++ 365E35C0C35C86A7263A02CE /* PBXTargetDependency */,++ );++ name = DmProbe;++ packageProductDependencies = (++ );++ productName = DmProbe;++ productReference = 43150F93F9204EF615D94F11 /* DmProbe.app */;++ productType = "com.apple.product-type.application";++ };++ 5A4AE636FE4AFD6115D14AF3 /* Probe */ = {++ isa = PBXNativeTarget;++ buildConfigurationList = F5FB4A1AE609544F88E06253 /* Build configuration list for PBXNativeTarget "Probe" */;++ buildPhases = (++ 63BB0B3F31A174CB8E640B2E /* Sources */,++ );++ buildRules = (++ );++ dependencies = (++ );++ name = Probe;++ packageProductDependencies = (++ );++ productName = Probe;++ productReference = FE4AE6108123D746C5393ED7 /* Probe.framework */;++ productType = "com.apple.product-type.framework";++ };++/* End PBXNativeTarget section */++++/* Begin PBXProject section */++ 665957B2F37792FAF81F0760 /* Project object */ = {++ isa = PBXProject;++ attributes = {++ BuildIndependentTargetsInParallel = YES;++ LastUpgradeCheck = 2710;++ };++ buildConfigurationList = 9ED6CC584E2C401AB7102CFC /* Build configuration list for PBXProject "DmProbe" */;++ developmentRegion = en;++ hasScannedForEncodings = 0;++ knownRegions = (++ Base,++ en,++ );++ mainGroup = CA160661865E290DF4649052;++ minimizedProjectReferenceProxies = 1;++ preferredProjectObjectVersion = 77;++ productRefGroup = DDB49E56DB02F4E7561FE966 /* Products */;++ projectDirPath = "";++ projectRoot = "";++ targets = (++ 27BF26B4447D8FE4545DC557 /* DmProbe */,++ 5A4AE636FE4AFD6115D14AF3 /* Probe */,++ );++ };++/* End PBXProject section */++++/* Begin PBXSourcesBuildPhase section */++ 63BB0B3F31A174CB8E640B2E /* Sources */ = {++ isa = PBXSourcesBuildPhase;++ buildActionMask = 2147483647;++ files = (++ 418AA9F224215885616DF281 /* probe.c in Sources */,++ );++ runOnlyForDeploymentPostprocessing = 0;++ };++ FACD769F731E7788343A6BD1 /* Sources */ = {++ isa = PBXSourcesBuildPhase;++ buildActionMask = 2147483647;++ files = (++ E87D64C1AB95AA2BE70D72EF /* probe_main.m in Sources */,++ );++ runOnlyForDeploymentPostprocessing = 0;++ };++/* End PBXSourcesBuildPhase section */++++/* Begin PBXTargetDependency section */++ 365E35C0C35C86A7263A02CE /* PBXTargetDependency */ = {++ isa = PBXTargetDependency;++ target = 5A4AE636FE4AFD6115D14AF3 /* Probe */;++ targetProxy = FF0604D39539FFF1AF62F0FC /* PBXContainerItemProxy */;++ };++/* End PBXTargetDependency section */++++/* Begin XCBuildConfiguration section */++ 010EAC4E2D1CD340BE7A9DE8 /* Debug */ = {++ isa = XCBuildConfiguration;++ buildSettings = {++ ALWAYS_SEARCH_USER_PATHS = NO;++ CLANG_ANALYZER_NONNULL = YES;++ CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;++ CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";++ CLANG_CXX_LIBRARY = "libc++";++ CLANG_ENABLE_MODULES = YES;++ CLANG_ENABLE_OBJC_ARC = YES;++ CLANG_ENABLE_OBJC_WEAK = YES;++ CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;++ CLANG_WARN_BOOL_CONVERSION = YES;++ CLANG_WARN_COMMA = YES;++ CLANG_WARN_CONSTANT_CONVERSION = YES;++ CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;++ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;++ CLANG_WARN_DOCUMENTATION_COMMENTS = YES;++ CLANG_WARN_EMPTY_BODY = YES;++ CLANG_WARN_ENUM_CONVERSION = YES;++ CLANG_WARN_INFINITE_RECURSION = YES;++ CLANG_WARN_INT_CONVERSION = YES;++ CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;++ CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;++ CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;++ CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;++ CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;++ CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;++ CLANG_WARN_STRICT_PROTOTYPES = YES;++ CLANG_WARN_SUSPICIOUS_MOVE = YES;++ CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;++ CLANG_WARN_UNREACHABLE_CODE = YES;++ CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;++ COPY_PHASE_STRIP = NO;++ DEBUG_INFORMATION_FORMAT = dwarf;++ ENABLE_STRICT_OBJC_MSGSEND = YES;++ ENABLE_TESTABILITY = YES;++ ENABLE_USER_SCRIPT_SANDBOXING = YES;++ GCC_C_LANGUAGE_STANDARD = gnu11;++ GCC_DYNAMIC_NO_PIC = NO;++ GCC_NO_COMMON_BLOCKS = YES;++ GCC_OPTIMIZATION_LEVEL = 0;++ GCC_PREPROCESSOR_DEFINITIONS = (++ "$(inherited)",++ "DEBUG=1",++ );++ GCC_WARN_64_TO_32_BIT_CONVERSION = YES;++ GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;++ GCC_WARN_UNDECLARED_SELECTOR = YES;++ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;++ GCC_WARN_UNUSED_FUNCTION = YES;++ GCC_WARN_UNUSED_VARIABLE = YES;++ IPHONEOS_DEPLOYMENT_TARGET = 26.0;++ MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;++ MTL_FAST_MATH = YES;++ ONLY_ACTIVE_ARCH = YES;++ PRODUCT_NAME = "$(TARGET_NAME)";++ SDKROOT = iphoneos;++ STRING_CATALOG_GENERATE_SYMBOLS = YES;++ SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;++ SWIFT_OPTIMIZATION_LEVEL = "-Onone";++ SWIFT_VERSION = 5.0;++ };++ name = Debug;++ };++ 1508495D03C30DBD9F3DD3AF /* Release */ = {++ isa = XCBuildConfiguration;++ buildSettings = {++ ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;++ CODE_SIGN_IDENTITY = "iPhone Developer";++ DEVELOPMENT_TEAM = MG2FF22535;++ INFOPLIST_FILE = "probe-Info.plist";++ LD_RUNPATH_SEARCH_PATHS = (++ "$(inherited)",++ "@executable_path/Frameworks",++ );++ PRODUCT_BUNDLE_IDENTIFIER = org.nxnative.probe.DmProbe;++ SDKROOT = iphoneos;++ TARGETED_DEVICE_FAMILY = "1,2";++ };++ name = Release;++ };++ 436BA009D88C3728FD6251AD /* Debug */ = {++ isa = XCBuildConfiguration;++ buildSettings = {++ CODE_SIGN_IDENTITY = "";++ CURRENT_PROJECT_VERSION = 1;++ DEFINES_MODULE = NO;++ "DEVELOPMENT_TEAM[sdk=iphoneos*]" = MG2FF22535;++ "DEVELOPMENT_TEAM[sdk=macosx*]" = MG2FF22535;++ DYLIB_COMPATIBILITY_VERSION = 1;++ DYLIB_CURRENT_VERSION = 1;++ DYLIB_INSTALL_NAME_BASE = "@rpath";++ INFOPLIST_FILE = "probe-framework-Info.plist";++ INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";++ LD_RUNPATH_SEARCH_PATHS = (++ "$(inherited)",++ "@executable_path/Frameworks",++ );++ PRODUCT_BUNDLE_IDENTIFIER = org.nxnative.probe.Probe;++ SDKROOT = iphoneos;++ SKIP_INSTALL = YES;++ TARGETED_DEVICE_FAMILY = "1,2";++ VERSIONING_SYSTEM = "apple-generic";++ };++ name = Debug;++ };++ 4728C346B0C8082A2E1ECA2F /* Release */ = {++ isa = XCBuildConfiguration;++ buildSettings = {++ ALWAYS_SEARCH_USER_PATHS = NO;++ CLANG_ANALYZER_NONNULL = YES;++ CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;++ CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";++ CLANG_CXX_LIBRARY = "libc++";++ CLANG_ENABLE_MODULES = YES;++ CLANG_ENABLE_OBJC_ARC = YES;++ CLANG_ENABLE_OBJC_WEAK = YES;++ CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;++ CLANG_WARN_BOOL_CONVERSION = YES;++ CLANG_WARN_COMMA = YES;++ CLANG_WARN_CONSTANT_CONVERSION = YES;++ CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;++ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;++ CLANG_WARN_DOCUMENTATION_COMMENTS = YES;++ CLANG_WARN_EMPTY_BODY = YES;++ CLANG_WARN_ENUM_CONVERSION = YES;++ CLANG_WARN_INFINITE_RECURSION = YES;++ CLANG_WARN_INT_CONVERSION = YES;++ CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;++ CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;++ CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;++ CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;++ CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;++ CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;++ CLANG_WARN_STRICT_PROTOTYPES = YES;++ CLANG_WARN_SUSPICIOUS_MOVE = YES;++ CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;++ CLANG_WARN_UNREACHABLE_CODE = YES;++ CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;++ COPY_PHASE_STRIP = NO;++ DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";++ ENABLE_NS_ASSERTIONS = NO;++ ENABLE_STRICT_OBJC_MSGSEND = YES;++ ENABLE_USER_SCRIPT_SANDBOXING = YES;++ GCC_C_LANGUAGE_STANDARD = gnu11;++ GCC_NO_COMMON_BLOCKS = YES;++ GCC_WARN_64_TO_32_BIT_CONVERSION = YES;++ GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;++ GCC_WARN_UNDECLARED_SELECTOR = YES;++ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;++ GCC_WARN_UNUSED_FUNCTION = YES;++ GCC_WARN_UNUSED_VARIABLE = YES;++ IPHONEOS_DEPLOYMENT_TARGET = 26.0;++ MTL_ENABLE_DEBUG_INFO = NO;++ MTL_FAST_MATH = YES;++ PRODUCT_NAME = "$(TARGET_NAME)";++ SDKROOT = iphoneos;++ STRING_CATALOG_GENERATE_SYMBOLS = YES;++ SWIFT_COMPILATION_MODE = wholemodule;++ SWIFT_OPTIMIZATION_LEVEL = "-O";++ SWIFT_VERSION = 5.0;++ };++ name = Release;++ };++ AAD8C8C6848A779F972D00C7 /* Release */ = {++ isa = XCBuildConfiguration;++ buildSettings = {++ CODE_SIGN_IDENTITY = "";++ CURRENT_PROJECT_VERSION = 1;++ DEFINES_MODULE = NO;++ "DEVELOPMENT_TEAM[sdk=iphoneos*]" = MG2FF22535;++ "DEVELOPMENT_TEAM[sdk=macosx*]" = MG2FF22535;++ DYLIB_COMPATIBILITY_VERSION = 1;++ DYLIB_CURRENT_VERSION = 1;++ DYLIB_INSTALL_NAME_BASE = "@rpath";++ INFOPLIST_FILE = "probe-framework-Info.plist";++ INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";++ LD_RUNPATH_SEARCH_PATHS = (++ "$(inherited)",++ "@executable_path/Frameworks",++ );++ PRODUCT_BUNDLE_IDENTIFIER = org.nxnative.probe.Probe;++ SDKROOT = iphoneos;++ SKIP_INSTALL = YES;++ TARGETED_DEVICE_FAMILY = "1,2";++ VERSIONING_SYSTEM = "apple-generic";++ };++ name = Release;++ };++ EBEA79193042D912ABBE4EF2 /* Debug */ = {++ isa = XCBuildConfiguration;++ buildSettings = {++ ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;++ CODE_SIGN_IDENTITY = "iPhone Developer";++ DEVELOPMENT_TEAM = MG2FF22535;++ INFOPLIST_FILE = "probe-Info.plist";++ LD_RUNPATH_SEARCH_PATHS = (++ "$(inherited)",++ "@executable_path/Frameworks",++ );++ PRODUCT_BUNDLE_IDENTIFIER = org.nxnative.probe.DmProbe;++ SDKROOT = iphoneos;++ TARGETED_DEVICE_FAMILY = "1,2";++ };++ name = Debug;++ };++/* End XCBuildConfiguration section */++++/* Begin XCConfigurationList section */++ 9ED6CC584E2C401AB7102CFC /* Build configuration list for PBXProject "DmProbe" */ = {++ isa = XCConfigurationList;++ buildConfigurations = (++ 010EAC4E2D1CD340BE7A9DE8 /* Debug */,++ 4728C346B0C8082A2E1ECA2F /* Release */,++ );++ defaultConfigurationIsVisible = 0;++ defaultConfigurationName = Debug;++ };++ F5FB4A1AE609544F88E06253 /* Build configuration list for PBXNativeTarget "Probe" */ = {++ isa = XCConfigurationList;++ buildConfigurations = (++ 436BA009D88C3728FD6251AD /* Debug */,++ AAD8C8C6848A779F972D00C7 /* Release */,++ );++ defaultConfigurationIsVisible = 0;++ defaultConfigurationName = Debug;++ };++ FB9912A086081F2D19165946 /* Build configuration list for PBXNativeTarget "DmProbe" */ = {++ isa = XCConfigurationList;++ buildConfigurations = (++ EBEA79193042D912ABBE4EF2 /* Debug */,++ 1508495D03C30DBD9F3DD3AF /* Release */,++ );++ defaultConfigurationIsVisible = 0;++ defaultConfigurationName = Debug;++ };++/* End XCConfigurationList section */++ };++ rootObject = 665957B2F37792FAF81F0760 /* Project object */;++}+diff --git a/dm/ios/probe/DmProbe.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/dm/ios/probe/DmProbe.xcodeproj/project.xcworkspace/contents.xcworkspacedata+new file mode 100644+index 00000000..919434a6+--- /dev/null++++ b/dm/ios/probe/DmProbe.xcodeproj/project.xcworkspace/contents.xcworkspacedata+@@ -0,0 +1,7 @@++<?xml version="1.0" encoding="UTF-8"?>++<Workspace++ version = "1.0">++ <FileRef++ location = "self:">++ </FileRef>++</Workspace>+diff --git a/dm/ios/probe/DmProbe.xcodeproj/project.xcworkspace/xcuserdata/hejie.xcuserdatad/UserInterfaceState.xcuserstate b/dm/ios/probe/DmProbe.xcodeproj/project.xcworkspace/xcuserdata/hejie.xcuserdatad/UserInterfaceState.xcuserstate+new file mode 100644+index 0000000000000000000000000000000000000000..b4b8eee3079089ab00aeeb8b1af12260972466d5+GIT binary patch+literal 17187+zcmd^md0<n;*7z*9P1CelyM(17r3JbrO`4^tg3=W#P)Zk|Y&C7uHqtgVNr4LLTyb9z+z*XJ&@EP@D#>jU8-;sS`sB8pEGQ9)b)aeuh{&b_zkLaXojeee70*Fu^*b7tnu%-PSm+zHLXqFK+s}2gfJqAA`XS2a3n*K)05|U`~k18r7GF&uWj_gQ$=#n*E&7fS967@HW<(%+zeB-iewW_3if~Vb6m)ixjA4MQ}WqHsY^f0_ZgBy?nMWJ}4M}v?9IZ-xpp&WD(x)_Z{+zW6&k&QZyFjq9QaAO+w{p8k&w~A`hxZ4X6>dqMOkz=vH(ax*gqtmY_S)Qgj!(8{Ll{+zMUSD!(K56gtwC$ilju40JbD4Wh+abfK-<wy^g7yy-bVY;0rU<!j6Oskp=0P1bOxP8+z-=K5oTl5|J9{r3lCYWLcj>6GciB&iT>#-3h;}JL&JFpXH<BRcFoQsR`Wq3NCg=b?o+zuEF)V0bh$3<6H6F_#S*OehhcuRd_w#fM38b;+ODtyc55H-@^Ow+xQTEAAg8H#$V&p+z_zXUazro+*^Y|Bn2qkh7Nur64#1K6hO0tNJ*olKUNj7nj9C8u4n2aW4$R*@bGL}pv+zlSm1fOiIZVQbx*26{#h4#6#*y18F3F5+FgcfGi@nlRL-~awl0z?jm=S`^f#|LGlz?+zPd1Q^<Y}^rJVTx(&ynZJ8)O&RP4<vC$zJjn*+>3KJ|IWQhvXyjCHabcO-_?D<XiF`+z`4{<({7yL<MWd;b4yHz$NJr5$nocvQojRzK=Frh}3@xV>w31Gx)97?sMQ6~NbQZmw+z*3m2IT-r*nq6_IFdNsX<UQ2JGx6<3_?eqcqAbp&!q^sy!x}I*J&(Ig>i}WSBoxV(8+zqr2%_^aFa7en>x}$LPoOIQ@!#O;6J^^jj{Bi{i9g95<LVaKpJI?qY5<H-@`}yObNt+z<#KskK3BjMa>ZOJH=V2EW^grJE!WJoa6Yb;3vvrM#_`;B+>PAb+&$dA+<n~rTnE?5+zt>9L2tGLbF7Vaf(E4PjN2e+MjncKm=!R_VV<=*3tbDwZ0xz8(;TiTkM4x(tJL@K04+zIutjpq})8$(;k=sf4g{NYI1FpI}qqV8l+`}(GC=YVj0K&!E&nAF~tRi(|rE9fmU~|+zr@&X+*6e8sR;!b9964Fe?A&~lGuxVHvKJNPn{o?Xxh9*-VJ*tdw`6A*IYJ8$Mx&5@+z9U6j$q6B0>!;ldrqTwhBC8H5&BnxBVOvWOZoJBGPi(=7C$y7|e4yB+}l!nq#1~MTt+z%0w1qMOnzkG)&K~V(IK^b`3Kzp54usvu!Mc<yWiqWu96<u&~Y>^!Y>RR+dc+RI3LU+zc<SA4O<jE=&j*TpexY+#Zfy``MtN<cr`ZFWD{E^h@C1V17IzS2iYP3CAVu2zo~hn|+zx5nG#4Yq?Y3C%yv+fwJ7FDxN_%k}%+Ee$YLOR&IG)7DVjQtzu)>k3=kHBFw1M!&~h+zH_qME<nhBK8dxje*AnzB2ui5KG%*r7eX*!kTPC^#!F*qHYm+DFsVfx(ULXi-NNDG|+z10dIgeE@Q0o>re9u1QtyX#&JOb=@e&<iYZDTYcV^U_gWh(N}jsq>nsQ*n#p<0n@Tr+z7Jm?p1DY9+iqU0gf<QGju)s|C>-RLlvCQ)@#A2APT3uT2ZSq`{nVDG`0F*KtJy&==+znKSZzb)HhcPY}MDEenK$oaZt5ea-a&Q<sF!tZUBn`U07)eqW6zGvKe4zL{$epb|70+zm7*y#B*JWQH+!Z_Up;}!l5)7Q4(KkMUQ#|;l<vJzohqUgSFN7<UqP#&88%VlF)yfv+z{Q#y{NXS*88E_=RJ-2tDDpVGt^jYX~WbZ_?(HvCG2C>0xNGEcm8dS@MvZ<^_pwR5;+z!c=DQ)7EuD<!!CPeVO}`ZC{vbwN)Ak3^~Eu54O0)8}z!H`p!_THvQR{Qcr_B&=x57+zwfSp3!i9yl;YCfz-c1V~s2R1e1XjTELjYHzMaaGu`B4A`Q5%|v=A#9u9bJVMG6NgN+zj4Y82XGtuXjbJ0$sI};7WCIR1BOYA`{A@-y02ikK$C}{R%q|69HnFi12M_K+N7{@z+zAkr`}Vzqi`|IS9={7K#xZ?n6#TAesxx3IH(AD9I024L=C1Hu%y%o8}f$ph@yf0ib9+zyRR)+xB$3KFfsrpssAjseqU3QC|1nA`ucze*suRgfnHEe-WI@T;4S601si>SSg3!u+zKt4sjraEs+14x{Hc+B^^TPMQI0g0*aL50iFy)2c*OV58pg)7hla0&3ArNO}q|Kru++zY9x;c-EIe3iQ+m?CtATWnWY1*LaUjTT_mUjV=0_PgWuQIQdi~)fHVzE?0Yt%oNWra+zrMtVJGqk`uv=PO1qNmV$w1H(Y8v~ws8f`+)FbB(KE@7dO{WjKm!OG<z;o<xY{Qv{r+zI!}$;Z=Ub13pQ4(Gy4Jb%v9lPFYpG0XF&!F7wGXHKz|3pw;64j1;Vba&0AN~9`pnz+ztJPor=(n6qElIw4$UQ5Mzt3%BPDvPSMcbx=RH`g4=s;UhS<=|LWk~orfL?})cJ!a<+zL|o=#`-gc8mY$29{rRz*pAAj)DtZmpEbxL5_qDkFAX;AS5iM_^J;J5zLc7_;Y;*^D+z6YXVV*d;7yPF<H)p6F?52sX|X$f~%d&a=Q1(BLnnTR(^jm$CSy?M4wX6uO6Z(fh)j+z@1Y|sm*sV!z35GtaSY3;tOo)MTrjh=+mF$4&}Aj%liGrUI_tr<6Mftp-%rsgWM6?k+zLnqKl^f@bJMQj`!zXE-MzC>T4uURp>j7?ybf=HBvR7e;~lvC>W%=7x%0$mbPYRnhx+zlxlTGAK}>-zQXNq@O0_;KLHQv#gGc0=&KcVJ<Ogy!0gq1+5~+rty-;)|HB@g)Kl(l+zXaQE0;HBI6LEy<B*+dq92>lD4N524>{EB`<zhhL@E$pg--e#~t+|8{sLl+E+k4<JJ+zY!a*ZKhtkXxo?d7HvIH#Sr?694$D9n;4mD{O4*bS9D(JmjFq$eX<b({RodFLE>-!*+zM<UV>R%1=II-$?0U3dwdSc`S2?B9U_85T^fxNvX??^qm%?8}yQ>nuD74;3~t7z~_g+zEVctDU<0dSGX#KcO9v;3=EL-A_2dO6&?<sTHF-p1(iFM{Fm-C0+%0pv8#1$Ui!4@`+z&1K3ia1?+o4Bv8#3aln;ZUJ=U<~fQA^FnBi#9#~eMk@_x4#X$ef~`0U_+%!V#b!%<+z@;{(8>;hWDIc!cZTEnC97=hN<<*ZtuCF#n)Pc(&a%)^BjT=_V-a<{;$e}qD4=mb0k+z*;k@`JPDWJ!MGG`$y(-t18-P~%Wyfaz?FC^^RjttK3l-r`yT#G@$l>Z+TrKAERHOT+zJ>O)@E6O(6^X<8&+&pK2DcA0@2|ro(oIW>vxwuIEUt7eIU6ku|I*Uxs0=v^>&vU{e+zS$2mhJ1Z-vu)vm+otK-_n~Wsm7?jUnA|qFUB`eEjH(6}<LX+KAkZZ~*Dl9bF3Udn`+zPD`G}?r?_Axe*8ciUEd$k^zPnNCp^Q1P0g@T?SZFmjM<O3@}kbVJ1)w&*pYn4fy&2+zt%eXXx8WtAM)2+U4%W<CI`Ex%Df2P^f6ZRN_u&Txdtp6T3>&~&$P(;@P55E_2v`fP+z>`In%06&gYcv*i{8}Yj1?wxe9bMf-{Q->TM-43c2cLL~&{-9S4Te|XUdr9*3`wHGF+z*^mlaIkdmkc&(r&cjGl|Gy^}mTTNb|AVcsQ@iU@Y#hXB_w*7nfzvIn)Wx`gxt#8B2+zct_ucSMh6o8+KtZ50>NIY~gbJCR@aEW`mzl0-jTO&=2Y-B%P(}-7hF0Eu(^$C&mWw+zJNR8>7u%NO_t>=|I`}6(DgiP{cz=YC&FNPCqWjZ{KkDTG;p6xuid%s{!Jp#K@CkMu+zTg<L!H>|*)<5Tzx{3W}Q-NbHVO9ax$1O)pzzk-Vkeq>z*s6H??Tk_f^?-rtVVCoGt+zLh28Q03!zi=<7yHfR2FxLu>aP&<lgmVV%R@_C5R`@K11h_(yj0a{M#91$1MVGCY8P+z1!DUR|1LPtf<hN%txW%VKD$*sQGy8p<FNp|@D75ztv$k#aF~&VvD=pu8M{Ley(t#>+zaakP}6Z~~LE%_F!-Jb2TSo5pBt&P4Gk1tT|_BT82;-W->fA3oCjdkqSF4T#VsD*h|+z?9Syx!<P2K6sbroi6ik<fN4Oa8FtrSSyXV^$sjUV46=3^hZ5~|Lh}&OU6-CixFnEK+zC~gfgkYU6~63K9qM3Tt}GLqfH?q&C}``O>v1METe5PNtHvXN9|CaENYn24EVg7nH@+zkATzo2z!)0#vW(O;5lc8H&EE*Z4lfz2%-c<ORxaU$XXAOQn23VZ?0Cy^=>W>O!GoG+z!y_1#YN?~VV8T?l-|H5FTz#epS%}qYtpwRSEL7D!xLO_Cdxc5htThP^Xup-g;i&aP+zAZL2_<*Bp4oXH2LM#9;YmuGR=a<W{eqN4m9lf&*PG`Z|KMW#Y$c7eUfT4c{F$f*=>+zd{$_VtZcJ&hPPCp2CFM0D|FJiqzG&bl1K7M0V!l1tdp%^D_4+lWIQP*m$6lBHG6`s+z5vVK<IHPYAslpo+&Qss7W2zK#AE;|`tKh=GsapDt>Iz^%cX?ZLGk7@?QIvZcgm_t?+zGOx|sR5vXvJ2xjQ+oAqK6j-DJAMGTSWGb1)*0PQ4ImSX;n?dG4#D&Zxv&d}rBwNRx+z>Lk_Vax#vsXB%K+uq8n%^xaaQB}@HYpI;2<rT;l#p1XE#xu@0bcZ26ytxo-OXlae9+z?xr?R(pbsuLQ{+(w7sOcAKER%M_Sp_Y!iEi<tJTwRvJ``jK<-}c!0D4ht4DO1xZrp+z4!S36I7Lk;AA$+x!op?$^E^m|yu$DE1tAHd9;ArU#SBeIO|x8d@#v&6xy6@Fm^i6?+z+Vok~UE$<trAn>QLiDX`i&AI~JlEVH$c>sd@RlKrtY@^Uysfs@<Eiu19gK}r#t#}I+z;C?~ydAXi(%LlVCrUNlp1Wx#2!!TpwaAi{Rh>@dGpsn0{l?T?UFKTi(1O)fk12GhD+zD_jADu*bWBgTc!OI6>DXjU6c+n&xITlSM#WIUXq5oZAW^)ADu*mNr)w3v1+ocY9Eo+zo?$X)f=Mf_+cR%B@eaPQr`HDKv<zR*u?S&jR>zP|u-l{ncBeDjB?hr$h2SVS%EE%e+zCb|bh6s4p*zd~p)^0<Yla=9l6!RCfQFA#kQq_Vg&0D-ISt^;w(OU5q06k_Bt!rFO-+zLpt&cgm`&J(Kv{VYlT&Z!0e%!h4`<}Ut9;w<*oO6fN<lxdn?*oJv}{Yqz*q&GP!iX+zxNG0QL}^d(6-HE4UT73lOf7@E77YZ@2hv`JLl?IKBdTVAz`gKvJ7$8**RK_zXV2-P+zjgHx6@OZf!WN<HPtCQ%kqXvc#&<-g+4H^u&hEzx%WJ5fABANopJ0HX?7eOHMcJv^6+z7*cePLvn5-B;{U#AjazuX4wN~-XRESd=5#t->@9~R&XG(0T088I0;;+d`Pfeg%@F7+zOs*}#OCiB_FMa?&gdc$<+cNw-K7zl)KSKiTSNuB(hXk4e5@>3og%nyGB+p79Jyu4h+zks2}=l3@$U_2d@v0C|M0fP~i;NOSEcpORDLEF`vmf^?QzqH8b_LQ<jYi}Z(%V9!eS+zL_4`^cDIEFW`(<xw3CIX3{FsZ3dx_V$@R#-3dH8Mgpt|gI<gpq=kx3Z_7r=O{e2a=+zf!s)LA~(b5jcha9!d_xq;d6^1PKW=w+!JW(-vR+D05s~)XA*$QgYAOy`8SXiU|ETf+zNn<0V15sni3c5$Kg3cY;m+>>Zbxwt^&fRWw2aOinMRo|^L0XLb4If?BqfZ_poyh(K+zc^GcuQSumhoGc^DNeA1`US>PkD{LowmA%GZe*%n=m1LFRRFOx8PcTK^V7o+zYKQm<+z2Net3lkzUbfg;Gmm4m+bw9M&lE%JlNs#aejG=ws274DjzNMyCk<;(#;(+U<}7WlSB+z7Mm$2%VISZ7FhC}dAWkK2!^x?CICS=$=d*$$x|n)oInxeT1v_xMhna@#OcJqv_Jup+zK9ul+)$-i_Y3_iS)@t%h^9CEsK@dTf%3TAYa+p|DoSr|xPd%u6GZj8x69iq0LsLms+zLGNXHbq#emjX4&h)o!sEU5*^11%9m#YnCy`p3|)&Um*WL_SNJ?@^`WsIN~L;m26|X+z*&g;L+soc!``Fv7!7O~4>>#g@o#a)xgABHxeZjtDXW2J!A8-R|K(8DU1SRfy-Udl)+z3r*dRxsVHk6dW{F28E=a*CVMDX=HIrpj8x}Jz(7<MXe)&N#QRM#+u!;X7`LCmV2AL+zBN$=($pLbZ9AXF9L3W6}vw|FkruWDZb{LvIW}gap8^!RL8SoM^J>83%yRQL|4n;7#+zdqL2SgTQ>N)X|lu=$@#=7X&*vAkHU#?H(7x?-=<^!0%&noP0t)W$&{0*b(;r3UY#++zB%hNL?4Rrdb`(AVznCI#Q_$lVX)3Q>uyIBAOCxwt-SY~~pnWS_AQ3kJuwI(OQ&(Bs+zcb*VFXUR7x4kBeh;ezeiXWnuj+!ol5A=vN9kKp~1lk9`#<R|ta1O$Mw&y!!suaJ*`+zgo(fbr9$lpBu4$70O&$7+RKiyk0xud?E*V07MvJ$6YM1y%$ERoqk<%=@`CvwVme!j+z(R%8Np(QW}%n`^Nl==cdKfV^55I>bK+Eczlrqt*TM93qfD_Y&b#wy4Wdlrm`v}=bV+zD&!uPL)KG`4q%l!dX8s7t6R)2iED_{$eeTiFoQOFxdLEfqNT>HpARmNgXZ`_or);^+zG)PK9ezI1LJBAoKh9)G1^g`113h8UdFk{kK{!{TGY3!}j#V-+>Wb^0=6;*R;n_Cww+zx@Pg+4=?Ljy>ZhETV8qfjXj5s9y=wC#UXu@C_Q(7o)fhVMHGWPDO}LnBuSacZ9yUZ+zFxBgsFO}E`2j6wUos>{2M0Ni|_-b`cbwzMo{#2_I{Gy&UfP}N0J&(PX6jV<jyKA}X+zspZu+YY&`wtmPmGS{iyxp6V_FqG2=wLY_37%Gh!CNe8f`z@hI5#6F^%hx#z1$ZKXW+zJ=(;=08n{<23H&iw0Q!d)l@WQAXcNX<Rpy;R{IQC?WDkJp#ei^LWsVpft_GElQpE^+z0;>IQSpQEbqT+`nCXY&!O#OExQ(qSo8`o7NGRxNrc~sCTlA4bV`sR9CioBktIw=(|+zDj$$eez6QgVsVj8AbR5w>mTa!+JZqJj1h!F&rJlFOpU;8;8^$pee|Hgz3NkzF?wKV+zf??P|<p3cov%_HQE(d_|!;_Y=Fc>sq<b{^$2!j#&Q@Z-oGXSq@ATJ3Wpcar0LW)<U+z7I8Bxz)3LvTc~RFpq^<eghT0>p?{xvVB+k5V4Ti^nt^6Wt@B`<K84<b>aYV~j2?ze+z-BB<|PeBUpEIJRVnJB0O(+imls015<?bwCK;7gzitPtwH=0ZUB35j95%|=T%1B+kq+z&JckOr^(#}HiCWLEkJ21$jDQZ)tfFPwut|oh&=au(fn!4mUYOZIwBPV$gF7PAIhxC+zsa3N)EmvM8ZKYd6srqgWElwKSI#z58?a@Rn0*{+%Ci{wg-9fE1i=Ad?1RfvN7V!8X+z<yi0W`$4XU6u-#h-D&^g0tjd%_JPa?#n9mMxA%q-txB3LW?ZH37l{^T_l83FTtdeq+z`x<&F9ZPd*9?ho(w2&6jaqJxXmVL**XFsqX*-z|e_OCUxm|jLF(1~;sEuoWXDV@U3+zvtM~E=W!&D2lIFWkL!5s;c>laKZJ~f9^0fGLIpuFEnEuP2sl)%OlklnE_4V2dxiuo+zsqLgzKa^C!#>Cv0B+EUJ^6#xZ!NLu7d)(qQBF)1g=|Eq1Ra=S6NCuR#tEs1QsqcJ&+zIg{KAyv^V$gGUDk3wBT!N>FFu6<l}$RS4Gzh)I<N2kC4&2UPuC=rLLin<^>q-lCKZ+z2P*B=CbAs+MbcevS_9=w-S8c>7M1mG2wjthHbBUf*0bN1(?<5YaK0Ll7~SV4iZ|(^+zoAA*N+Duz`jCjbGhJsY|O4<hb3+kr<8sss!jD*Lulg>jnx`4+V%iwVsMC@VK9)UPZ+zc<QmH)$l0X(j+&elY?z_o+>zF>3EXHdL`NqVa(|D11)z0GSi!QEMq1fM+jz>O1vg0+zPy;d$t|)12l{AqW9j15CCG<|DqD$#r^lo|&y_eoc??>rypciIb=ky>g(N=7?omvJl+zB@nG1sU1c(yS*(v;2;^r^PgNFnzN^m$2uNI@i>mhgLtf9uySU%hLwy#uq}kcmuBrT+zj=OcTbSV#^!cO`yeS|*B<7ghMd8~!J2VF*&!|poBjdaC~o>ePFe0Z#6TX?Jr8CMd)+ztfo&uJr0~%k7*-C9=d4A>+hgz1Ow+!VL~fEiPGr`9&1=SEF>6$T^%?==zx5y(0)*?+z4LDDqrO%;a9>?%FmZATvk~{i$x_RK7dI#Mi>}#NOI~dw@E8Rx_F+;F&rSssip2rY*+zoBY2k2^_fgj_#nZ%mii#kyR(%Nuf-pcN0){Da2}_MiNjegu0$~=>lJ;Z$L%^F0c>z+z^xS4&anwO~37h_p;U#L@0~s^=CXa{oaQ{9Ej^9f9Hc0sc^dLRN<Du+39w+eFz~f;n+z>0$aV{2oDO9vgX_DE=ERIIuGX>Ym_jsRQq7c9$pwr^;#rUeHL-k_X=<E>*<=>AB0D+z7dX6YhH431O+zx`6M7N?(DYOK89l+{BpxU8ctj`toSs5^c|4NG#ZU<ZqD~7l266-A+z!FK{ZC(1gI`yu@Tojtq*eqpJ%r3I3Ay<4R^G<p_Nj`SNIk7Dsh=y&vc`UCxu{shGH+zGyNAmPdn(Z^f&rDJ;h-v6dr;w9~3IM=yO{_m>0BgJqQ&cnjx5>UFoX6w+DL<2uh@<+zJ_*92En*y?OKe;Suk(nyt`G8X&V9xRtM@L)fjL81_Lu<Op;izhJce7%<Z%idD331_+z1dEmp=_6gaa84GIt~>_WoZ3t1iA2Rkg9zi4oQebCmBwR`3>g=Qu#m(WP`dmD$)aj)+zt7-Dqnrlq~u`0BST)1Q|6UD9NMsOp!QCtd_%B6AXTn1<2V0#uGTX~$tV;hg{Ja+Kd+z$>VGuyLg<l7K%M>Toy8OcB%4!b3yLTBxt;g1U)obsy*QGIEdbWN*bVI65=;~D>(a?+zL<V{nf%Y$nl>BwD>i>VM{^W{)>$q_|zPPK9gS+g{3OTqbTm=*^aAjOMkH_%%k`Att+zo66%$d7LX;4ph+pQDx_UP#GE`rJ39uVUbyAH;>1Pm5kI1HHWABRWgPK)Nzeq&Tt;C+zo@?N79*^^RT+qpRxhv2n9vAYs2+BYJz5lpm^siQgg7??2hO|$S=>hIaq~iSjYf1(v+zKj9#c$Ia^x`iJEwTsyZ&EGOX>vRodI2ge1<G*1g<nitfcz?%yN7Q4%C$+DPi1y+~I+zo?|aC<=8DbraX(YFwautu(>QnqB7(bbJv5w?lvNO3HT1~20`%+*cZB!o4DH{g2CO)+z-NN0<-NxgIJf6hk5*|-p!QH_vAvbbMd0filO2Lkr!}6z3^wf)9Mpc=&p;7WTBokip+zH-uPuw?*CUGlW+A8~2E?+5_B!+(X>MJf6biG9CkwR;&Q|k`4zV$dq(A6!9gHAz}s}+z#5|bKp7}xmI8f%EFB<>goDA;U+x3D(c`ZaXfQtKcio>BWzb7{c<Ky~(h_ee?D1_^3+zZX+ZRxF@(Z+*<BQZXNd&x1QU;W8kA{Jf6<uDjv_^@k}1i;_+-qB#6IKc|3fFeF(o&+zX}s_abg+<@?lx-cAU_cBHF*SseWJI<FF0vZV5Q3n5YhnyLJL_E(232hec{vo2)?wq+zpaS~(OrG&az>_>dcO59?zTkrKG%zl3VtqmX5bg4|nt+(Q?F%oI4-Ggql%)z$TR~O#+z9r1^_cYE=@wi>$5SGZS0-XHfGkE^>Xqqtq*>T$cdJv_dg$2Hx?9`_b^U;y8XyBW0L+zJHRG_;&Zc{q_OQwd&efYBizw}hTQ_gjsa^4!)nE05A+%KDF-oop_)_;UV&C(sA_@L+zDtscJL3n8p8V)Z|S<yxC^5PUU70p6(s0Chy%ZGTvRB)eb;KjFkc=4^7`oK@U8D4IC+ziM}J)qx7HfO4~>9I@>2;Bc7zE=$G_suvH?sNO+}9$*JMBwitM^O%JcO4TYE6jPPpP+zbP&?FbC1DmY5Td)xL?9D!*au>hq=S*!y3b`2x|&!597n`2)i@vuCRN;PK2Ea`&T#(+zmxn9E<HM7~M~0__r-d&Lzdiik@CU<Jg+CR(A^hp^XTmp!zZAYLe0%tg@LyyW+2yik+znO_!^&66#ZT`jv-#><w-I%O+mt7U6sPs*N>ZIC@Jdq(!0>;>7IvbSV!%MQp6$qvij+zlf5tdK=z^RnC!Uh_XtBoUPN8Q%@OM(4n%w-SIbRur#we~v3!iYNIqFUMP4qiluwga+z$!E%E%jd|e<xTP{<pFt{{3`h(`89GT@04$s@0A~tAC|u-e_#Hw{1f?S@{{sYk=jUG+zq$jc^a$)3>$fc1FMlOq78M!|4g~*+e??xVpJRW%_@;e1qgexKxkqVVUqtGd070C*V+z!loFl7^ApUF<w!rn4y@Zn4_pwcoYo^ufnIeMsbtkQN;?y(~8ZCmlWF++Z8($dlY*W+z`xN^X2Nmx`g+<w;YNPIodNS(esNGR}qxMDZk2)UpRn!mBB$|s3kB*3rjINDtif)g-+zCYnWG7kyLoEz!3{-w}OZ^dr$LqPIoA9(^+Uv{I=|R$7%=N}JN5%u|k27Aq$xOO<8H+z3guK~t<s}xP<oYHly4|^DR(R1R31?tSAMEIq5NF=h4NeF_sSoYKP%5Ge^te+Oe&`;+zM|H7kjH*Ocswz`esHUo_RZXfZRRL9->MGSD)io-ndPucewMq4?>Uq_Rs?DmGRIjUc+zsrIP$s`jb&s}8D;sgA2YRh>|~)P?GC>SFZ-^`q*w>UHY%>WvzrQE8GjBQ+_SG);!a+ztg&daG<J<s<I+shOx8@%lxr$A(==6@nVQ*}YK>b{t7+2sG*@Z@nnju$G&gB((cGrF+zLvyF*5zTT<r)H&Qt!ABOy=J54pysURS1qRv*G6a~wHmEX8>@}i4$=<SW@_`a1=>m4+z8QNy8PrFFVYZq&8(B7)OUAsiPRQtGgo%U(%Gur30o3$@#w`sR)_h~=S9@T!RJ*NFy+zds=%&`;GQD?e99IBRZ8%t<&gqI-@R0H$s=9OVefOF4E=cCg@6ZrMfa*wXQ~2r)$u8+zb#rw=-F#iUZlUga-95U8bgOk6b(?h0>YmrVsC!xWitbh2>$+XKJ-T0G3^C(ku8p}p+z=8l*pF-v0}jae4c5wkL8b<CQWr(-t9?1<SDvp42&%+Z+RF=t}V#e5g@W6aMn=VM34+zX2!Z=FNz%(ds*zn*vYX|V#{M^#@5BQ#J0vh9J?a+`Pi+ouf-mWJrVnP>=&_L#h#8m+z8+$JHyVxIMe~MGYMaQY)G;zAP*tqz(L2*Ok65@u%rN!mO&4_D`yFTv0xX!pOafjlL+z#%tsC@gw3b@nhnP;>X8d7C$k*Bz{_aRs78O+40r!?)a<X?~C6U|4IC*_;2FBjsHbY+z^<jFMUanW@_4;A@M17Kegg!%W)?4&hdb@tM{x<y!`tAB1`hEJt`uFtj>p#$cqW?^P+zQh!SSrT#np`9a*EsDvR22?-+;><Jeq<Rwf_n3XUm;qru<gt~<KgvNxng!u{W2@4ah+zPPjIKPgtDrM8e*L9}S6yG((2LVYtLF)-c&H-B4wiX=pUG8x|U_He74q4T}vo7;ZA$+zVtB~#h~Y8AGDC-9g<+N93By{$I>S!G!C^7O3WhZgyK~r+!(JQq*|2j)Y^268qs%Bb+zDvZ%amC;~?>MdikailTDm}bl{nvJ=}3S*;jq47>*hw(Y%4&xr<UgJLFe&a#o2gVPL+z$Bf5~pBhgj$`cb3GZQNlYZB)sHYfTLuS^UiE=s&6ktJT2czxoHiH{~eowz&kv&3_W+z-zI*S_``6`aKrG#;Yq_s4o?}LHrzJ6ba>hDilp0;?oHa7v@_}J<g(=I<htbg<i_OY+zWMA@?$${jDleZ`DO+K9bUh@0NA0&U6d@}h|@|Ve9C!b0FCi%A!cmy30J|bd7<fyVy+z)uU=g)s1Qx<sCJ5RB+V1Q43N`DbAGql<_H-rA$njl2V>hnKCVfPg$9=K4nA7(<z%%+zwxn!Lc`fB&%88WEQ@%*~D&=&_*_3lB-=+MJ@>8lJH9A$5s!fee)u#?gHKZn{CZ~=}+zEl!=C+L*c|byez1sUM}DPSd0r(z4PD)5fKhrp-!or!}Wtm3DR7wQ1L-U7vPi+Cyob+zX-}j*nYKP{W7^iVooTP9?M~a9b|~%Lv?FOBq<xt7Roc(#QR#8%!_qU-ZRyVRob=J@+z`RPUJ<I^XkPfD*&Z%n@;eR2Bz=_}K>roWy3Rr;CqbLrow|CD|{{nw1l3|Gdb8F?9n+z8RIi9%b1o?lhK$lH={YDHDf^rpRp`sWya2o{TYWc4rd(6IGXWA##b4qGrr0A&4f*y+zDcn?Lsxd7vU2VF@^oVJ-X|3rg)9>a8bBuY2d6YTFoM&z}`^}G<SDDwC*O}Lwx0qiu+z?=tT(zh&NUK4kvLeBAt*`E&D^=C93X%;z)ZnF;V#ZEj|MW@+ZM%o&-pGcV6<$h;!6+zIn$SUW#)~Uk7YiWxh?bM%$=F9WqxUqS<)?IEHf=vT5ho1W!YfaWO>f=qGgL^o8@K8+zPRnbSH!L4pKDC^*d|~<8a@KOra^6a;Vb%z%!WwNIY)!BZvktdrTC=QnYqqt(T4Wt>+zonW1AooSt8z1-@zUTeMA`Zw!C)<><&tew_X)-~33)(zH8*4M4Otb43)S>LuEw7z3~+z*LuYIf%QY{u`DhtDQj$2P1cQB>$2X?I%8AX(rtEIw(TO@Xj`GJ#8zr6vsKup+NRq)+zwkvGSwpLr4ZGml}?P}XYwyn0^wtcn(wnMffwtw1=+CH+Kww<>Vdzd}KuCQzEv39+E+zuzje#&_3V(fPJ}rz5QkTEA}_-N9<qOPutHskb^kF9FdMFhti>T409AYCOhgKa~;<?+z?sPohc-ZlnW4U96<0;2R$1{%S94|UHJ6>_@b-d>|>-g0f?vy*DoGPc*ImDUZ9Og`P+zCOJnq^PQJF7dszuu5oU5Zgp;VzT$k%xy$*cbD#5o^AqQ1&Xdkl&M%!`JI^@3aenLk+zK07J9Jey^2$bR1y=^E{t>ssJi=(^g)T#H>dxR$u?aoz8F(DktE3D*YKCf9SW7hV5w+z?QrdMz3$rOI^g=qb;5PZ^_A<4>j&4*uJf+na!`&uCoU&GN1rn|XQ&jQCq(+ob>-=$+JCxmjW{||(!%boxL++literal 0+HcmV?d00001++diff --git a/dm/ios/probe/DmProbe.xcodeproj/xcshareddata/xcschemes/DmProbe.xcscheme b/dm/ios/probe/DmProbe.xcodeproj/xcshareddata/xcschemes/DmProbe.xcscheme+new file mode 100644+index 00000000..ee38f971+--- /dev/null++++ b/dm/ios/probe/DmProbe.xcodeproj/xcshareddata/xcschemes/DmProbe.xcscheme+@@ -0,0 +1,101 @@++<?xml version="1.0" encoding="UTF-8"?>++<Scheme++ LastUpgradeVersion = "2710"++ version = "1.3">++ <BuildAction++ parallelizeBuildables = "YES"++ buildImplicitDependencies = "YES">++ <BuildActionEntries>++ <BuildActionEntry++ buildForTesting = "YES"++ buildForRunning = "YES"++ buildForProfiling = "YES"++ buildForArchiving = "YES"++ buildForAnalyzing = "YES">++ <BuildableReference++ BuildableIdentifier = "primary"++ BlueprintIdentifier = "27BF26B4447D8FE4545DC557"++ BuildableName = "DmProbe.app"++ BlueprintName = "DmProbe"++ ReferencedContainer = "container:DmProbe.xcodeproj">++ </BuildableReference>++ </BuildActionEntry>++ <BuildActionEntry++ buildForTesting = "YES"++ buildForRunning = "YES"++ buildForProfiling = "YES"++ buildForArchiving = "YES"++ buildForAnalyzing = "YES">++ <BuildableReference++ BuildableIdentifier = "primary"++ BlueprintIdentifier = "5A4AE636FE4AFD6115D14AF3"++ BuildableName = "Probe.framework"++ BlueprintName = "Probe"++ ReferencedContainer = "container:DmProbe.xcodeproj">++ </BuildableReference>++ </BuildActionEntry>++ </BuildActionEntries>++ </BuildAction>++ <TestAction++ buildConfiguration = "Debug"++ selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"++ selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"++ shouldUseLaunchSchemeArgsEnv = "YES">++ <MacroExpansion>++ <BuildableReference++ BuildableIdentifier = "primary"++ BlueprintIdentifier = "27BF26B4447D8FE4545DC557"++ BuildableName = "DmProbe.app"++ BlueprintName = "DmProbe"++ ReferencedContainer = "container:DmProbe.xcodeproj">++ </BuildableReference>++ </MacroExpansion>++ <Testables>++ </Testables>++ </TestAction>++ <LaunchAction++ buildConfiguration = "Debug"++ selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"++ selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"++ launchStyle = "0"++ useCustomWorkingDirectory = "NO"++ ignoresPersistentStateOnLaunch = "NO"++ debugDocumentVersioning = "YES"++ debugServiceExtension = "internal"++ allowLocationSimulation = "YES">++ <BuildableProductRunnable++ runnableDebuggingMode = "0">++ <BuildableReference++ BuildableIdentifier = "primary"++ BlueprintIdentifier = "27BF26B4447D8FE4545DC557"++ BuildableName = "DmProbe.app"++ BlueprintName = "DmProbe"++ ReferencedContainer = "container:DmProbe.xcodeproj">++ </BuildableReference>++ </BuildableProductRunnable>++ </LaunchAction>++ <ProfileAction++ buildConfiguration = "Release"++ shouldUseLaunchSchemeArgsEnv = "YES"++ savedToolIdentifier = ""++ useCustomWorkingDirectory = "NO"++ debugDocumentVersioning = "YES">++ <BuildableProductRunnable++ runnableDebuggingMode = "0">++ <BuildableReference++ BuildableIdentifier = "primary"++ BlueprintIdentifier = "27BF26B4447D8FE4545DC557"++ BuildableName = "DmProbe.app"++ BlueprintName = "DmProbe"++ ReferencedContainer = "container:DmProbe.xcodeproj">++ </BuildableReference>++ </BuildableProductRunnable>++ </ProfileAction>++ <AnalyzeAction++ buildConfiguration = "Debug">++ </AnalyzeAction>++ <ArchiveAction++ buildConfiguration = "Release"++ revealArchiveInOrganizer = "YES">++ </ArchiveAction>++</Scheme>+diff --git a/dm/ios/probe/build_probe.sh b/dm/ios/probe/build_probe.sh+new file mode 100755+index 00000000..593d7922+--- /dev/null++++ b/dm/ios/probe/build_probe.sh+@@ -0,0 +1,112 @@++#!/bin/bash++# Build the dlopen probe (docs/probe-dlopen.md) into an ad-hoc signed IPA with plain clang and++# hand-written Info.plists, no Xcode project: DmProbe.app tries to dlopen the Probe.framework beside++# its own executable and to call probe_answer() in it, logging every step to Documents/probe-log.txt++# on the phone (also shown on the screen). The sideloader (AltStore / Sideloadly / i4Tools) re-signs++# the app and the nested framework on install; the ad-hoc signature here is the placeholder the repo++# ships in every IPA (the same order build_ipa.sh uses: nested code first, then the bundle).++# Usage: dm/ios/probe/build_probe.sh [out.ipa] (default: <repo>/probe-out/DmProbe.ipa)++# Self-checks: codesign verifies the framework and the app inside the build tree and again inside the++# extracted IPA; the load commands carry the rpath and the install name; the deployment target is 26.0;++# both binaries are arm64; both Info.plists lint.++set -u++cd "$(dirname "$0")" || exit 1++P=$PWD; REPO=$(cd ../../.. && pwd)++t() { echo "[$(date +%T)] $*"; }; die() { t "FAIL: $*"; exit 1; }++OUT=${1:-$REPO/probe-out/DmProbe.ipa}++APP=build/pkg/Payload/DmProbe.app++TARGET=arm64-apple-ios26.0++++rm -rf build/pkg && mkdir -p "$APP/Frameworks/Probe.framework" || die "mkdir $APP"++++t "compile Probe.framework (arm64 iOS, install_name @rpath/Probe.framework/Probe)"++xcrun -sdk iphoneos clang -arch arm64 -target "$TARGET" -Oz -Wall -dynamiclib \++ -install_name @rpath/Probe.framework/Probe \++ src/probe.c -o "$APP/Frameworks/Probe.framework/Probe" || die "clang Probe.framework"++++t "compile the DmProbe shell app (rpath @executable_path/Frameworks)"++xcrun -sdk iphoneos clang -arch arm64 -target "$TARGET" -O2 -Wall -fobjc-arc \++ -framework Foundation -framework UIKit \++ -Wl,-rpath,@executable_path/Frameworks \++ src/probe_main.m -o "$APP/DmProbe" || die "clang DmProbe"++++cat > "$APP/Frameworks/Probe.framework/Info.plist" <<'EOF'++<?xml version="1.0" encoding="UTF-8"?>++<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">++<plist version="1.0">++<dict>++ <key>CFBundleExecutable</key><string>Probe</string>++ <key>CFBundleIdentifier</key><string>org.nxnative.DmProbe.Probe</string>++ <key>CFBundleInfoDictionaryVersion</key><string>6.0</string>++ <key>CFBundleName</key><string>Probe</string>++ <key>CFBundlePackageType</key><string>FMWK</string>++ <key>CFBundleShortVersionString</key><string>1.0</string>++ <key>CFBundleVersion</key><string>1</string>++ <key>MinimumOSVersion</key><string>26.0</string>++</dict>++</plist>++EOF++++# UIFileSharingEnabled: the Files app shows Documents/, so probe-log.txt can be read and shared++# on the phone; LSSupportsOpeningDocumentsInPlace opens it in place. No icons: a blank home-screen++# icon is fine for a probe (the repo's unsigned IPAs have none either).++cat > "$APP/Info.plist" <<'EOF'++<?xml version="1.0" encoding="UTF-8"?>++<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">++<plist version="1.0">++<dict>++ <key>CFBundleDevelopmentRegion</key><string>en</string>++ <key>CFBundleDisplayName</key><string>DmProbe</string>++ <key>CFBundleExecutable</key><string>DmProbe</string>++ <key>CFBundleIdentifier</key><string>org.nxnative.DmProbe</string>++ <key>CFBundleInfoDictionaryVersion</key><string>6.0</string>++ <key>CFBundleName</key><string>DmProbe</string>++ <key>CFBundlePackageType</key><string>APPL</string>++ <key>CFBundleShortVersionString</key><string>1.0</string>++ <key>CFBundleSupportedPlatforms</key><array><string>iPhoneOS</string></array>++ <key>CFBundleVersion</key><string>1</string>++ <key>LSRequiresIPhoneOS</key><true/>++ <key>LSSupportsOpeningDocumentsInPlace</key><true/>++ <key>MinimumOSVersion</key><string>26.0</string>++ <key>UIFileSharingEnabled</key><true/>++ <key>UILaunchScreen</key><dict/>++ <key>UIRequiredDeviceCapabilities</key><array><string>arm64</string></array>++ <key>UISupportedInterfaceOrientations</key><array><string>UIInterfaceOrientationPortrait</string></array>++</dict>++</plist>++EOF++++t "ad-hoc sign (nested framework first, then the bundle)"++xattr -cr "$APP" 2>/dev/null # Finder information or resource forks on copied files: codesign refuses them++codesign --force --sign - "$APP/Frameworks/Probe.framework" || die "codesign Probe.framework"++codesign --force --sign - "$APP" || die "codesign DmProbe.app"++++t "self-check the built bundle"++codesign -vvv --verify --strict "$APP/Frameworks/Probe.framework" >/dev/null || die "verify the framework signature"++codesign -vvv --verify --strict "$APP" >/dev/null || die "verify the app signature (covers the nested framework)"++[ -z "$(codesign -d --entitlements :- "$APP" 2>/dev/null)" ] || die "the probe embeds no entitlements, yet its signature carries some"++plutil -lint "$APP/Info.plist" "$APP/Frameworks/Probe.framework/Info.plist" >/dev/null || die "plutil"++lipo -info "$APP/DmProbe" "$APP/Frameworks/Probe.framework/Probe" | sed 's/^/ /'++otool -l "$APP/Frameworks/Probe.framework/Probe" | grep -A3 LC_ID_DYLIB | sed 's/^/ /'++otool -l "$APP/DmProbe" | grep -A3 LC_RPATH | sed 's/^/ /'++otool -l "$APP/DmProbe" | grep -A4 LC_BUILD_VERSION | sed 's/^/ /'++grep -qx '@executable_path/Frameworks' <(otool -l "$APP/DmProbe" | awk '/LC_RPATH/,/^$/{print $2}') || die "no LC_RPATH @executable_path/Frameworks in DmProbe"++grep -qx '@rpath/Probe.framework/Probe' <(otool -l "$APP/Frameworks/Probe.framework/Probe" | awk '/LC_ID_DYLIB/,/^$/{print $2}') || die "Probe.framework has the wrong install name"++grep -q 'minos 26.0' <(otool -l "$APP/DmProbe"; otool -l "$APP/Frameworks/Probe.framework/Probe") || die "deployment target is not 26.0"++[ "$(/usr/libexec/PlistBuddy -c 'Print :CFBundleExecutable' "$APP/Info.plist")" = DmProbe ] || die "CFBundleExecutable"++[ "$(/usr/libexec/PlistBuddy -c 'Print :MinimumOSVersion' "$APP/Info.plist")" = 26.0 ] || die "MinimumOSVersion"++++t "pack the IPA (dm/ios/tools/pack_ipa.py)"++mkdir -p "$(dirname "$OUT")" || die "mkdir $(dirname "$OUT")"++rm -f "$OUT" "$OUT.idx"++python3 "$REPO/dm/ios/tools/pack_ipa.py" "$OUT" "Payload/DmProbe.app=$PWD/$APP" || die "pack_ipa"++++t "self-check the packed IPA"++X=build/check && rm -rf "$X" && mkdir -p "$X" || die "mkdir $X"++unzip -q "$OUT" -d "$X" || die "unzip $OUT"++codesign -vvv --verify --strict "$X/Payload/DmProbe.app" >/dev/null || die "verify the extracted app"++codesign -vvv --verify --strict "$X/Payload/DmProbe.app/Frameworks/Probe.framework" >/dev/null || die "verify the extracted framework"++codesign -d -vvv "$X/Payload/DmProbe.app" 2>&1 | grep -E 'Identifier|Format|CDHash|TeamIdentifier' | sed 's/^/ /'++++t "IPA: $OUT ($(du -h "$OUT" | cut -f1 | tr -d ' '))"++t "ready: sideload it (AltStore / Sideloadly / i4Tools), open DmProbe, read Documents/probe-log.txt; docs/probe-dlopen.md explains the results"+diff --git a/dm/ios/probe/probe-Info.plist b/dm/ios/probe/probe-Info.plist+new file mode 100644+index 00000000..affd7571+--- /dev/null++++ b/dm/ios/probe/probe-Info.plist+@@ -0,0 +1,37 @@++<?xml version="1.0" encoding="UTF-8"?>++<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">++<plist version="1.0">++<dict>++ <key>CFBundleDevelopmentRegion</key>++ <string>$(DEVELOPMENT_LANGUAGE)</string>++ <key>CFBundleDisplayName</key>++ <string>DmProbe</string>++ <key>CFBundleExecutable</key>++ <string>$(EXECUTABLE_NAME)</string>++ <key>CFBundleIdentifier</key>++ <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>++ <key>CFBundleInfoDictionaryVersion</key>++ <string>6.0</string>++ <key>CFBundleName</key>++ <string>$(PRODUCT_NAME)</string>++ <key>CFBundlePackageType</key>++ <string>APPL</string>++ <key>CFBundleShortVersionString</key>++ <string>1.0</string>++ <key>CFBundleVersion</key>++ <string>1</string>++ <key>LSSupportsOpeningDocumentsInPlace</key>++ <true/>++ <key>UIFileSharingEnabled</key>++ <true/>++ <key>UILaunchScreen</key>++ <dict/>++ <key>UISupportedInterfaceOrientations</key>++ <array>++ <string>UIInterfaceOrientationPortrait</string>++ <string>UIInterfaceOrientationLandscapeLeft</string>++ <string>UIInterfaceOrientationLandscapeRight</string>++ <string>UIInterfaceOrientationPortraitUpsideDown</string>++ </array>++</dict>++</plist>+diff --git a/dm/ios/probe/probe-framework-Info.plist b/dm/ios/probe/probe-framework-Info.plist+new file mode 100644+index 00000000..db711b14+--- /dev/null++++ b/dm/ios/probe/probe-framework-Info.plist+@@ -0,0 +1,24 @@++<?xml version="1.0" encoding="UTF-8"?>++<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">++<plist version="1.0">++<dict>++ <key>CFBundleDevelopmentRegion</key>++ <string>$(DEVELOPMENT_LANGUAGE)</string>++ <key>CFBundleDisplayName</key>++ <string>Probe</string>++ <key>CFBundleExecutable</key>++ <string>$(EXECUTABLE_NAME)</string>++ <key>CFBundleIdentifier</key>++ <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>++ <key>CFBundleInfoDictionaryVersion</key>++ <string>6.0</string>++ <key>CFBundleName</key>++ <string>$(PRODUCT_NAME)</string>++ <key>CFBundlePackageType</key>++ <string>FMWK</string>++ <key>CFBundleShortVersionString</key>++ <string>1.0</string>++ <key>CFBundleVersion</key>++ <string>1</string>++</dict>++</plist>+diff --git a/dm/ios/probe/project.yml b/dm/ios/probe/project.yml+new file mode 100644+index 00000000..3d711419+--- /dev/null++++ b/dm/ios/probe/project.yml+@@ -0,0 +1,59 @@++# The dlopen probe as an Xcode project: the most reliable way to get it onto a device when the++# sideloaders' Apple authentication is throttled (AltStore HTTP 503, 爱思助手 "wrong password"++# behind two-factor) — Xcode signs with the user's own Apple ID and installs over USB itself.++# xcodegen generate -s project.yml (or open the generated DmProbe.xcodeproj)++# Then in Xcode: select DmProbe target → Signing & Capabilities → Team = your Apple ID → Run.++name: DmProbe++options:++ bundleIdPrefix: org.nxnative.probe++ deploymentTarget:++ iOS: "26.0" # same floor as the game host: Metal 4++targets:++ DmProbe:++ type: application++ platform: iOS++ sources:++ - path: src/probe_main.m++ # Embed the framework into DmProbe.app/Frameworks/ — the probe's dlopen targets++ # @executable_path/Frameworks/Probe.framework, so without this the app reports a FALSE++ # "BLOCKED: no such file" (the framework would be built but never shipped inside the bundle).++ dependencies:++ - target: Probe++ embed: true++ codeSign: true++ info:++ path: probe-Info.plist++ properties:++ CFBundleDisplayName: DmProbe++ CFBundleShortVersionString: "1.0"++ CFBundleVersion: "1"++ UILaunchScreen: {} # an empty launch screen: silences the storyboard warning++ UIFileSharingEnabled: true # Documents/probe-log.txt visible in the Files app++ LSSupportsOpeningDocumentsInPlace: true++ # all four orientations: iOS 26 deprecated UIRequiresFullScreen, and a probe that writes++ # its verdict to a file does not care how it is held++ UISupportedInterfaceOrientations:++ - UIInterfaceOrientationPortrait++ - UIInterfaceOrientationLandscapeLeft++ - UIInterfaceOrientationLandscapeRight++ - UIInterfaceOrientationPortraitUpsideDown++ Probe:++ type: framework++ platform: iOS++ sources:++ - path: src/probe.c++ settings:++ base:++ # a pure-C payload dlsym'd by name needs no module map; without an umbrella header the++ # DEFINES_MODULE default only produces a warning++ DEFINES_MODULE: NO++ info:++ path: probe-framework-Info.plist++ properties:++ CFBundleDisplayName: Probe++schemes:++ DmProbe:++ build:++ targets:++ DmProbe: all++ Probe: all+diff --git a/dm/ios/probe/src/probe.c b/dm/ios/probe/src/probe.c+new file mode 100644+index 00000000..77a15c6b+--- /dev/null++++ b/dm/ios/probe/src/probe.c+@@ -0,0 +1,6 @@++// Probe.framework: the payload of the dlopen probe (docs/probe-dlopen.md). One C function with a++// known answer: the shell app dlsyms it in the framework it loaded and calls it, so a 42 back++// proves the call went through the bundle framework and not somewhere else. Deliberately free of++// every dependency: no Foundation, no libSystem calls beyond the C library, nothing that could++// make the load fail for a reason other than the one under test.++int probe_answer(void) { return 42; }+diff --git a/dm/ios/probe/src/probe_main.m b/dm/ios/probe/src/probe_main.m+new file mode 100644+index 00000000..ea28aa90+--- /dev/null++++ b/dm/ios/probe/src/probe_main.m+@@ -0,0 +1,159 @@++// probe_main.m: the shell of the dlopen probe (docs/probe-dlopen.md). Answers one question for the++// launcher architecture C (docs/ROADMAP.md section 6): can a sideloaded IPA dlopen a dynamic++// framework that ships inside its own bundle (DmProbe.app/Frameworks/Probe.framework) and call a++// function in it, on a stock device, outside the jailbreak and the App Store review?++// At launch it appends every step to Documents/probe-log.txt (visible in the Files app:++// UIFileSharingEnabled in Info.plist), shows the verdict on screen, and stays open. The last log++// line is the verdict: "RESULT: FEASIBLE ..." or "RESULT: BLOCKED ...".++// Built with plain clang and a hand-written Info.plist by build_probe.sh, no Xcode project.++#import <Foundation/Foundation.h>++#import <UIKit/UIKit.h>++#import <dlfcn.h>++#include <stdarg.h>++#include <stdio.h>++#include <sys/stat.h>++++static FILE *g_log; // Documents/probe-log.txt, opened at the top of main++static NSMutableString *g_screen; // the verdict, also shown on the app's screen++++static void logf_(const char *fmt, ...) __attribute__((format(printf, 1, 2)));++static void logf_(const char *fmt, ...) {++ if (!g_log) return;++ va_list ap;++ va_start(ap, fmt);++ vfprintf(g_log, fmt, ap);++ va_end(ap);++ fputc('\n', g_log);++ fflush(g_log); // every line survives even if the process dies later++}++++// One dlopen attempt: logs the form and dlerror()'s verbatim text, returns the handle (NULL on failure)++static void *try_open(const char *form) {++ logf_("dlopen(\"%s\", RTLD_NOW)", form);++ dlerror(); // clear stale state so the next dlerror is this attempt's++ void *h = dlopen(form, RTLD_NOW);++ if (h) logf_(" -> handle %p", h);++ else {++ const char *e = dlerror();++ logf_(" -> NULL, dlerror: %s", e ? e : "(no dlerror text)");++ }++ return h;++}++++static NSMutableString *run_probe(void) {++ NSBundle *bundle = [NSBundle mainBundle];++ NSString *bundlePath = bundle.bundlePath ?: @"?";++ NSString *execPath = bundle.executablePath ?: @"?";++ logf_("bundle: %s", bundlePath.fileSystemRepresentation ?: "?");++ logf_("executable: %s", execPath.fileSystemRepresentation ?: "?");++ logf_("iOS: %s (%s)", [UIDevice currentDevice].systemVersion.UTF8String ?: "?",++ [UIDevice currentDevice].model.UTF8String ?: "?");++++ NSMutableString *screen = [NSMutableString stringWithFormat:@"DmProbe dlopen probe (iOS %@)\n\n",++ [UIDevice currentDevice].systemVersion];++++ // The framework must physically be in the bundle, beside the executable's Frameworks/ folder++ NSString *fwPath = [bundlePath stringByAppendingPathComponent:@"Frameworks/Probe.framework/Probe"];++ struct stat st = {0};++ BOOL present = stat(fwPath.fileSystemRepresentation, &st) == 0;++ logf_("framework file %s: %s", fwPath.fileSystemRepresentation, present ? "present" : "MISSING");++ [screen appendFormat:@"framework file: %@\n\n", present ? @"present" : @"MISSING"];++++ // The forms to try, in order. The first two are the ones a launcher would use; the rest narrow++ // down the failure if both are refused (absolute sandbox path, cwd-relative, bare name)++ NSArray<NSString *> *forms = @[++ @"@executable_path/Frameworks/Probe.framework/Probe",++ @"@rpath/Probe.framework/Probe",++ fwPath, // the absolute sandbox path of the same file++ @"Probe.framework/Probe", // relative: dyld resolves it from the current directory (/)++ @"Probe", // bare name: dyld's fallback search paths only++ ];++ void *handle = NULL;++ NSString *okForm = nil;++ for (NSString *form in forms) {++ void *h = try_open(form.UTF8String);++ if (h) { handle = h; okForm = form; break; }++ }++ if (!handle) {++ logf_("RESULT: BLOCKED - every dlopen form failed (see the dlerror lines above)");++ [screen appendString:@"every dlopen form failed\n\nRESULT: BLOCKED\n(see Documents/probe-log.txt for the dlerror texts)"];++ return screen;++ }++++ // The framework loaded: take the C function out of it and call it++ logf_("dlsym(handle, \"probe_answer\")");++ dlerror();++ void *sym = dlsym(handle, "probe_answer");++ const char *se = dlerror();++ if (se || !sym) {++ logf_(" -> failed: %s", se ? se : "NULL result");++ logf_("RESULT: BLOCKED - the framework loaded (dlopen \"%s\") but dlsym failed: %s",++ okForm.UTF8String, se ? se : "NULL result");++ [screen appendFormat:@"dlopen OK via %@\ndlsym failed: %s\n\nRESULT: BLOCKED", okForm, se ? se : "NULL result"];++ return screen;++ }++ int (*fn)(void) = (int (*)(void))sym;++ int answer = fn();++ Dl_info info = {0};++ const char *from = dladdr(sym, &info) && info.dli_fname ? info.dli_fname : "(dladdr found no image)";++ logf_(" -> probe_answer at %p in %s (image base %p)", sym, from, info.dli_fbase);++ logf_(" -> probe_answer() = %d", answer);++ if (answer == 42) {++ logf_("RESULT: FEASIBLE - dlopen(\"%s\") succeeded and probe_answer() = 42: a sideloaded app can load and call code in a framework inside its own bundle (route C is viable)",++ okForm.UTF8String);++ [screen appendFormat:@"dlopen OK via %@\nprobe_answer() = 42\n\nRESULT: FEASIBLE\n\nfull log: Documents/probe-log.txt", okForm];++ } else {++ logf_("RESULT: BLOCKED - dlopen and dlsym succeeded but probe_answer() returned %d, not 42", answer);++ [screen appendFormat:@"dlopen OK via %@, but probe_answer() = %d (wanted 42)\n\nRESULT: BLOCKED", okForm, answer];++ }++ return screen;++}++++@interface ProbeDelegate : NSObject <UIApplicationDelegate>++@property (nonatomic, strong) UIWindow *window;++@end++++@implementation ProbeDelegate++// The probe keeps the legacy UIApplication lifecycle (no scene manifest, no scene delegate): a++// deprecated-but-supported path, which keeps this file one screen long. The deprecations it pulls++// in (mainScreen, initWithFrame:) are silenced here on purpose.++#pragma clang diagnostic push++#pragma clang diagnostic ignored "-Wdeprecated-declarations"++- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {++ UIWindow *w = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];++ UILabel *l = [[UILabel alloc] initWithFrame:w.bounds];++ l.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;++ l.numberOfLines = 0;++ l.font = [UIFont fontWithName:@"Menlo" size:14] ?: [UIFont monospacedSystemFontOfSize:14 weight:UIFontWeightRegular];++ l.text = g_screen ?: @"DmProbe";++ l.textAlignment = NSTextAlignmentCenter;++ l.backgroundColor = UIColor.systemBackgroundColor;++ w.backgroundColor = UIColor.systemBackgroundColor;++ w.rootViewController = [[UIViewController alloc] init];++ w.rootViewController.view.backgroundColor = UIColor.systemBackgroundColor;++ [w.rootViewController.view addSubview:l];++ [w makeKeyAndVisible];++ self.window = w;++ return YES;++}++#pragma clang diagnostic pop++@end++++int main(int argc, char *argv[]) {++ @autoreleasepool {++ // Documents/probe-log.txt: the Files app shows this folder (UIFileSharingEnabled), so the++ // user can read and share the log without a computer. Appended, so past runs stay.++ NSString *docs = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];++ NSString *logPath = [docs stringByAppendingPathComponent:@"probe-log.txt"];++ g_log = fopen(logPath.fileSystemRepresentation, "a");++ if (g_log)++ fprintf(g_log, "\n---- DmProbe run %s (probe built %s %s) ----\n",++ [[NSDate date] description].UTF8String, __DATE__, __TIME__);++ g_screen = run_probe();++ if (!g_log) { g_screen = [g_screen mutableCopy]; [g_screen appendString:@"\n\n(the log file could not be opened)"]; }++ if (g_log) { fclose(g_log); g_log = NULL; }++ // Stay open on the verdict: a probe that exits at once looks like a crash on the phone++ UIApplicationMain(argc, argv, nil, NSStringFromClass([ProbeDelegate class]));++ }++ return 0;++}+diff --git a/docs/probe-dlopen.md b/docs/probe-dlopen.md+new file mode 100644+index 00000000..625759c0+--- /dev/null++++ b/docs/probe-dlopen.md+@@ -0,0 +1,92 @@++# dlopen probe — the route C gate++++Route C of the universal launcher (shell app + one signed framework per game, `dlopen`ed at++runtime) is listed in [ROADMAP.md](ROADMAP.md#6-universal-launcher--proven-feasible-bounded-by-apples-rules)++as unvalidated, gated on exactly this experiment. The question: **on a stock, non-jailbroken++iPhone, can a sideloaded IPA — installed outside the App Store review with AltStore, Sideloadly or++i4Tools (爱思助手) — `dlopen` a dynamic framework inside its own bundle and call functions in it?**++++Every app with dynamic frameworks loads nested code from its own bundle at launch, so the++mechanism exists; what this probe proves is that it survives the sideloaded conditions, where a++free-provisioning signature replaces the ad-hoc one at install time and re-signs the app and every++nested framework. If `dlopen` refuses such code, route C is dead on stock devices and the dlerror++texts are the evidence for upstream; if it works, route C stands.++++## What ships++++`probe-out/DmProbe.ipa`, built by `dm/ios/probe/build_probe.sh` (plain `clang` and hand-written++Info.plists, no Xcode project):++++```++Payload/DmProbe.app/++ DmProbe the shell: runs the probe at launch, then stays open++ Frameworks/Probe.framework/Probe one C function, probe_answer() → 42 (src/probe.c)++```++++At launch the shell appends one line per step to `Documents/probe-log.txt` and shows the verdict on++its screen:++++1. the bundle and executable paths, the iOS version, and whether the framework file is present;++2. `dlopen` attempts in order, each with its handle or its `dlerror()` text verbatim:++ `@executable_path/Frameworks/Probe.framework/Probe`, then `@rpath/Probe.framework/Probe`, the++ absolute sandbox path of the same file, the relative `Probe.framework/Probe`, and the bare++ `Probe` (the last two are expected to fail; their texts tell us how far dyld got);++3. on the first success: `dlsym` of `probe_answer`, a call (42 expected), and `dladdr` naming the++ image the symbol came from;++4. the last line is the verdict: `RESULT: FEASIBLE ...` or `RESULT: BLOCKED ...` plus the reason.++++## Installing and reading the result++++1. Sideload `DmProbe.ipa` with any of: AltStore (send the file to the phone, open it with++ AltStore, or use AltServer's *Sideload .ipa* on the computer), Sideloadly (connect the iPhone,++ drag the IPA in, enter the Apple ID, Start), or i4Tools (爱思助手: 应用游戏 → install a local++ IPA). The IPA is unsigned-but-ad-hoc on purpose: the sideloader re-signs it with the user's++ Apple ID, exactly like every game IPA this repository ships.++2. The first install from a given Apple ID needs Settings → General → VPN & Device Management →++ trust the certificate. A free Apple ID re-signs every 7 days; a one-shot probe does not mind.++3. Open DmProbe and wait two seconds. The result is on the screen and in the file:++ **Files app → On My iPhone → DmProbe → probe-log.txt** (`UIFileSharingEnabled` in the app's++ Info.plist makes Documents visible there; runs append, so nothing is lost).++4. Send the log back by sharing it from the Files app (long-press → Share → AirDrop / Mail /++ WeChat), or from i4Tools' app-file browser (DmProbe → Documents → probe-log.txt). If no new++ lines appeared, the app died before logging: send the crash report instead (Settings → Privacy++ & Security → Analytics Data → `DmProbe-*.ips`).++++## Reading the result++++| Last line of probe-log.txt | Meaning |++|---|---|++| `RESULT: FEASIBLE - dlopen("@executable_path/Frameworks/Probe.framework/Probe") succeeded and probe_answer() = 42` | Route C is viable: a sideloaded app loads and calls code in a framework inside its own bundle. Proceed with the launcher shell + per-game frameworks. |++| `RESULT: BLOCKED - ... no suitable image found ... (no such file)` | The framework is not in the installed bundle: the sideloader stripped it or the layout broke. Record the sideloader and version; fix the packaging before concluding anything about `dlopen`. |++| `RESULT: BLOCKED - ... code signature ... not valid` / `not signed` / `no Team ID` | The nested framework's signature was rejected: the sideloader failed to re-sign it, or iOS refuses its signature. Record the exact text and sideloader; retry with another sideloader (or an `ldid`-signed IPA) before treating it as a platform refusal. |++| `RESULT: BLOCKED - ...` with any other `dlerror` text | Record the text verbatim with the device model, iOS version and sideloader; the attempt lines above it show which forms were tried. |++++The failing fallbacks (relative and bare-name forms) always log `no suitable image found` texts —++that is their expected outcome, not a verdict; the verdict uses only whether some form loaded.++++## What it does not prove++++- **App Store review rules** (a policy question, not a technique one): irrelevant to sideloaded++ distribution, which is how this project ships.++- **Loading code that is not in the signed bundle** (streaming game payloads from disk — the++ original ROADMAP blocker): still expected to be blocked; route C compiles each game's modules++ into its framework at packaging time, inside the signed bundle.++- **JIT, or anything about the game modules themselves**: the rewriter's output needs much more++ than one C function; this probe only opens the door the launcher would walk through.++++The build was self-checked on the Mac only (`codesign -vvv --verify --strict` on the framework,++the app, and the app extracted from the packed IPA again; `otool` load commands: the app's++`LC_RPATH @executable_path/Frameworks`, the framework's install name `@rpath/Probe.framework/Probe`,++`minos 26.0`; `lipo` arm64; `plutil` on both Info.plists; `ldid` is not installed on this machine,++so codesign only). The device run is the user's step.++++## Building it again++++```++dm/ios/probe/build_probe.sh [out.ipa] # default: probe-out/DmProbe.ipa++```++++compiles both binaries with `xcrun -sdk iphoneos clang` (arm64, deployment target iOS 26.0), writes++the two Info.plists, ad-hoc signs the framework first and the bundle second (the same placeholder++order `build_ipa.sh` uses — the sideloader replaces both signatures), packs with++`dm/ios/tools/pack_ipa.py`, and re-verifies the extracted IPA before printing the path.diff --git a/patches/0020-fork-docs.patch b/patches/0020-fork-docs.patchnew file mode 100644index 00000000..713b8f37--- /dev/null+++ b/patches/0020-fork-docs.patch@@ -0,0 +1,977 @@+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001+From: v0lumehi <[email protected]>+Date: Wed, 28 Oct 2026 13:33:56 +0100+Subject: [PATCH] Fork documents and badge data++Roadmap, multiplayer notes, release notes and guide, work in progress, launcher design, badge JSON.++Upstream-Status: fork-only+Reason: The fork's own planning and release documents and its README badges+Issue: LNPANDY/NX2Apple#123+---+ docs/MULTIPLAYER.md | 139 ++++++++++++++++ docs/RELEASE-NOTES-GUIDE.md | 105 ++++++++++++ docs/RELEASE_NOTES.md | 77 +++++++++ docs/ROADMAP.md | 140 ++++++++++++++++ docs/WORK-IN-PROGRESS.md | 88 +++++++++++ docs/badges/games.json | 6 ++ docs/badges/verified.json | 6 ++ docs/launcher-c-design.md | 339 +++++++++++++++++++++++++++++++++++++ 8 files changed, 900 insertions(+)+ create mode 100644 docs/MULTIPLAYER.md+ create mode 100644 docs/RELEASE-NOTES-GUIDE.md+ create mode 100644 docs/RELEASE_NOTES.md+ create mode 100644 docs/ROADMAP.md+ create mode 100644 docs/WORK-IN-PROGRESS.md+ create mode 100644 docs/badges/games.json+ create mode 100644 docs/badges/verified.json+ create mode 100644 docs/launcher-c-design.md++diff --git a/docs/MULTIPLAYER.md b/docs/MULTIPLAYER.md+new file mode 100644+index 00000000..39558eb5+--- /dev/null++++ b/docs/MULTIPLAYER.md+@@ -0,0 +1,139 @@++# Local-network and lan-play multiplayer: what the protocol is, and what we would need++++Written after reading [c22dev/mush8](https://github.com/c22dev/mush8), an independent native++port of Mario Kart 8 Deluxe for Apple platforms (Rust, `nxhost`/`nxpatch`/`nxshader` crates —++a different implementation of the same idea as nxnative). Nothing here is copied code: the++sections below describe the **public protocol** and the shape of a host-side implementation.++++**We have none of this today.** `dm/host/hle_offline.c` line 1 says so outright: online play,++local wireless, friends and SSL are "out of scope … all made unavailable, the game takes its++offline branch", and there is no `hle_bsd` — every socket call returns -1 / `ENETDOWN`.++++## Three modes, one virtual network++++mush8 offers LAN, LanPlay and Wireless. All three are the same shape: a virtual network stack++in the host, with one pluggable transport carrying raw IP packets.++++ game → nn::socket (bind/sendto/recvfrom/poll)++ → virtual network: own address 10.13.x.y, mask 255.255.0.0, gateway 10.13.37.1++ → Transport: LAN (real broadcast) | LanPlay (UDP to a server) | Wireless (peer to peer)++++The game's own code is untouched: it sees a normal BSD socket API, and everything below is host++side. That is the property that makes this cheap to bolt onto a host that already has the++services stubbed out.++++### The virtual network layer++++- **Address**: random `10.13.<1..254>.<1..254>`, never the gateway, chosen once per process.++- **Mask** `255.255.0.0`, **gateway** `10.13.37.1`, **MTU** 1500.++- **Broadcast**: `255.255.255.255` and the subnet's own broadcast address both deliver to every++ local socket bound to that port — this is how discovery works, and why no server is needed on++ a LAN.++- **Per-socket state**: local bind address, optional connected peer, non-blocking flag, timeout,++ a receive queue and a "changed" epoch so `poll`/`select` can wake when a packet arrives.++- **Socket registry per port**: a socket can be found by the port a packet arrives on, which is++ what makes broadcast delivery work without a real routing table.++++### lan-play (the public server protocol)++++Port **11451** by default, plain UDP, one byte of type followed by the payload.++++| Byte | Type | Direction | Payload |++|---|---|---|---|++| `0x00` | keepalive | client → server | none |++| `0x01` | IPv4 | both | a whole IP packet |++| `0x02` | ping | client → server | 4 random bytes (echoed back) |++| `0x03` | IPv4 fragment | both | 16-byte header + data (below) |++| `0x04` | auth | server → client | the server asks for a login; implementations without it log and continue |++| `0x10` | info | server → client | a UTF-8 message to show the player |++++The high bit (`type & 0x7F`) is masked off on receive, so `0x81` is accepted as IPv4.++++**Fragment header** (16 bytes, all multi-byte fields big-endian):++++ offset size field++ 0 4 source IPv4 address++ 4 4 (reserved in the observed implementation)++ 8 2 fragment id++ 10 1 part index (0-based)++ 11 1 total parts++ 12 2 data length in this packet++ 14 2 path MTU, i.e. the data length of every part except the last++++Reassembly keeps a table keyed by `(source, fragment id)`, drops entries older than 5 s, rejects++mismatched totals or MTUs, and concatenates parts in index order.++++**Client behaviour**: keepalive + ping every 10 s, consider the server lost after 30 s of++silence, reconnect every 5 s on failure. The client picks its virtual address itself; the server++maps it to the connection.++++A real Switch can join a lan-play server, which is the whole point: this is how Switch players++and a ported build end up in the same lobby. For LAN mode the README of mush8 notes that the++**game update must match the Switch's** — version mismatch is the usual cause of "we cannot see++each other".++++### LAN mode++++Real broadcast on the physical interface instead of an encapsulation: packets go out as UDP++broadcasts on the local subnet so other Switches (and other hosts running the same build) see++them. Simpler than lan-play, but only works when everyone shares one subnet.++++### Wireless mode++++Peer discovery without a router, using the platform's peer-to-peer mechanism (mush8 uses mDNS /++DNS-SD to advertise and browse, `dnssd.rs`: `DNSServiceRegister` / `DNSServiceBrowse` /++`DNSServiceResolve` / `DNSServiceGetAddrInfo`). Each player advertises a service and browses for++the others; the first contact becomes the transport.++++## What the game needs above the transport++++Transport alone is not enough: the game asks Horizon whether a wireless/LAN session exists and++what the room looks like. That is `nn::ldn` (local wireless), `nn::nifm` (network interface) and++in some titles `nn::vnet` (virtual network sockets). Each game uses a subset differently:++++- which `ldn` calls it makes (create/join/scan, and in what order),++- how it encodes room name, password, player list and game mode in the advertise/join payloads,++- whether it opens sockets through `nn::socket` or `nn::vnet`,++- what it does when a scan returns nothing.++++This is why **mush8 supports exactly one game**: the `ldn` payload layer is per-title. A general++implementation would expose the virtual network and the `ldn` primitives, and then each game++needs its own mapping from "the bytes in the room struct" to something meaningful.++++## What an implementation in our host would need++++Roughly four layers, in order:++++| Layer | Content | Where it would live |++|---|---|---|++| 1. BSD sockets | `socket`/`bind`/`sendto`/`recvfrom`/`poll`/`select` over the virtual network, with the errno conventions the SDK expects | new `dm/host/hle_bsd.c` (replaces the offline stubs in `hle_offline.c`) |++| 2. Virtual network | address/MASK/gateway, per-port socket registry, broadcast rules, receive queues, wake-on-packet for `poll` | new `dm/host/dm_vnet.c` |++| 3. Transports | lan-play framing + reassembly; LAN broadcast; wireless via mDNS | one file per transport |++| 4. `ldn` / `nifm` | make the game believe a session can exist; per-game payload mapping | `hle_ldn.c`, and per-game code |++++Layers 1–3 are game independent and reusable. Layer 4 is where a new title costs work again.++++**Cost estimate**: layers 1–3 for one game (Mario Kart 8 Deluxe, since its protocol is the one++documented above and it is the title mush8 proved) ≈ 2–3 weeks. Each further title that uses++`ldn` differently: days to weeks.++++## Open questions before committing to this++++- **Does our Metal host survive packet injection at frame rate?** Untested. The transport runs++ on its own thread, but `poll` must wake a blocked guest thread promptly.++- **iOS local network permission**: iOS 14+ shows a prompt and the entitlement++ `com.apple.developer.networking.multicast` may be needed for broadcast; a sideloaded unsigned++ IPA cannot carry it, which could make LAN mode impossible on iOS while lan-play (unicast UDP)++ still works.++- **Matching the game update to the Switch's**, per mush8's note — our profiles already pin an++ update version per game, so this is checkable, but users must know.++- **mush8 is Rust and we are C/ObjC**: no code can be taken, only the protocol. Anything we build++ is a fresh implementation with its own bugs, and it cannot be verified without two clients —++ which means you need a real Switch, a second iPhone, or two Macs on one network to test.++++## Sources++++- [c22dev/mush8](https://github.com/c22dev/mush8) — `crates/nxhost/src/services/{vnet,lanplay,lan,wireless}.rs`,++ `crates/nxhost/src/dnssd.rs` (read at commit 0.1).++- lan-play itself is a public protocol with several open implementations (switch-lan-play and++ clients for it); the constant table above matches what mush8 implements.+diff --git a/docs/RELEASE-NOTES-GUIDE.md b/docs/RELEASE-NOTES-GUIDE.md+new file mode 100644+index 00000000..ba1f3323+--- /dev/null++++ b/docs/RELEASE-NOTES-GUIDE.md+@@ -0,0 +1,105 @@++# Release notes: English first, then Chinese++++Every release body is written in **English first, then Chinese**, as two complete halves with a++`---` between them. This exists because the fork's users are mostly Chinese while the upstream++project and most contributors are not, and a release written in one language loses half of them.++++**Do not interleave the languages.** Earlier releases alternated one Chinese line and one English++line, and the result was hard to read in both: a Chinese reader's eye had to skip every other line,++and the two halves could not be compared. Each language is written as a complete document, in the++same section order, and a reader picks one and reads straight through.++++## The shape++++```++## What this release does++<one paragraph>++++## New (optional: only when there is new functionality)++- …++++## Fixes++- …++++## Known issues++- …++++## Install++- …++++## Credits++- …++++---++++## 这一版做了什么++<一段>++++## 新增 (可选)++- …++++## 修复++- …++++## 已知问题++- …++++## 安装++- …++++## 致谢++- …++```++++The two halves use the **same headings in the same order** (the Chinese ones are the translations++of the English ones), and the same number of items under each heading. Item 2 in English is item 2++in Chinese; a reader comparing the two must not have to map lists.++++Rules that matter more than the template:++++1. **English first.** It is the canonical text; the Chinese half is written from it.++2. **Both halves say the same thing.** Not "a translation of the headline and a summary of the++ rest" — a user reading either half must learn everything the other one learns.++3. **Never split a section across the two halves.** All of Fixes is in one place, then all of++ 修复 is in the other.++4. **Say what it does for the user, not what the commit did.** "游戏数据现在是一个文件,拷到手机上++ 快得多" beats "switched romfs_arc.py to romfs_image.py" — and the English line says the same.++5. **State what is NOT shipped.** If the Windows build is not in the release, both halves say so in++ the same section (a reader who only reads one must not conclude the other platform shipped).++6. **Credit contributors by name in both halves**, with the PR number.++++The app's own update sheet (`UpdateSheet.swift`) reads the body and shows one language: it splits on++the `**中文**` / `**English**` markers if they are there, and otherwise picks the lines whose++characters belong to the reader's language. A body in the shape above works with both paths, so++changing the template means checking that sheet's tests too.++++## Where the text comes from++++- `README.md` and `README.zh-CN.md` share an update-history table; a release row goes in both, the++ English one first (it is the canonical project history), then translated.++- The release body itself is written once, in both languages, and is what `gh release edit++ --notes-file` takes. Keep the file in `/tmp` while working; the release is the record.++- If a fact differs per platform (a macOS-only fix), say which platform in the same sentence in both++ languages rather than relying on the reader's inference.++++## A worked example (v0.4.7)++++```markdown++## 这一版做了什么 / What this release does++++**中文** 游戏数据现在打成一个 `romfs.img`(一个文件,不再是几十万个碎文件),拷到手机上快得多,++也可以整个放在外置硬盘上。DLC 跟着游戏数据走,不再塞进 IPA——IPA 更小,装得更快。++++**English** Game data is now one `romfs.img` (a single file, not hundreds of thousands), which++copies to a phone far faster and can live on an external drive as a whole. DLC follows the game++data instead of going into the IPA, so the IPA is smaller and installs faster.++++## 修复 / Fixes++++- 依赖面板的语言切换现在翻译整个界面。++- The language toggle now translates the whole interface.++```++++That example is what "both languages, same structure" means in practice: the Chinese paragraph and++the English paragraph carry the same facts, and the bullet list interleaves rather than splitting++into two lists.+diff --git a/docs/RELEASE_NOTES.md b/docs/RELEASE_NOTES.md+new file mode 100644+index 00000000..c8adbaab+--- /dev/null++++ b/docs/RELEASE_NOTES.md+@@ -0,0 +1,77 @@++# NX2Apple v0.5.0 — release notes++++This is the text of the [v0.5.0 release](https://github.com/LNPANDY/NX2Apple/releases/tag/v0.5.0). Earlier releases are on the releases page. English first, then Chinese, as two complete halves — see RELEASE-NOTES-GUIDE.md.++++## What this release does++++**The Mac launcher arrives, and the iPhone's game data finally sticks.** The launcher is a real console-style screen now: launch options live in the game's own saved-choices store (the same one upstream reads), the library's Manage menu opens with a controller, and a bare Apple ID — no development certificate — can install, because Xcode creates everything at the first install. On the iPhone, choosing game data works across launches, an app with no data yet boots into the launcher instead of a dead end, a pick applies the moment Play is pressed, and the installer asks before copying gigabytes over USB. The build tools update themselves, even from an old ZIP copy.++++## New++++- **Launch options live in the game's own store**: one string per setting (`launcher.<VAR>`) in the app's preferences domain, exactly where upstream's launcher reads them — Finder and Dock starts included. Only non-default values are kept, an earlier launcher's choices migrate once, and schema 1 is read properly: sub-settings appear only when their parent has the value (`needs`), sections the launcher has no name for draw after the known ones in list order, and range limits come from the row. A newer schema is read as far as it can be and noted in the log, never refused.++- **The library's Manage menu in the launcher's own style** — and a controller can open and drive it.++- **Build tools update themselves**: a ZIP copy of an old release is connected to git by itself when the app opens (your own edits are preserved on a branch), and a build refuses to start when the tools are older than the app instead of failing at the last step.++- **Install with just an Apple ID**: signing teams come from Xcode's provisioning preferences (personal teams are labelled), merged with the certificates'. With no certificate at all, Xcode creates one at the first install (`-allowProvisioningUpdates`); the messages say so, and with neither an Apple ID nor a certificate they say exactly where to sign in.++- **The installer asks before copying game files**: USB from the Mac runs at about 25–70 MB/s, so the dialog offers transfer now or skip — the game installs either way, and the outcome card gains a "Game data (romfs.img)" row with Reveal in Finder for a manual copy (a fast external drive handed to the device is quicker; the launcher's Game data picker loads from it).++- **Issue forms**: game, build and launcher problems each ask for what a report needs (versions, device, Copy diagnostics, the game's log) and refuse to submit without it; a PR template and CONTRIBUTING.md set the same rules for tools.++++## Fixes++++- **iPhone: choosing game data sticks.** The bookmark is written while the Files app's security scope is held (one written without it resolves to nothing from the next launch on — every pick read as "the app was signed differently"), saved only after a round-trip resolves, and a stale-but-readable bookmark rewrites itself instead of making you pick again. The resolved scope stays held for the session, since the game reads the image the whole time.++- **iPhone: no game data is no dead end.** A fresh install with nothing in Documents and no pick ever made boots into the launcher (the old build stopped on a static "Game files not found" page that never mentioned the picker), and Play (re)locates the data first — a pick made this session applies at once, with save/temp following the final location. An app without a launcher falls back to the static hint.++- **iPhone: the signing retry keeps its stage row.** The team-variant retry appended a second "Sign for …" row with the same id that no update ever reached; it spun for ever after the build moved on. A retried stage now reuses its row.++- **Mac: every extracted game version is kept as the build resource it is.** The versions a profile's shader tables were made from are inputs to the shader split on every build, so deleting the packed version's siblings traded a full re-extraction of the base game for disk space — the wrong trade, and it is undone.++- **Sync: the next upstream sync runs.** Upstream's latest commits stopped the sync and would have silently lost fork code; every patcher is now tested against real upstream in CI, a `--check-protection` run lists any hand-edited file no table covers, and files the fork owns outright are registered so a sync cannot revert them.++++## Known issues++++- **Mods have not been played with a real mod yet**: the layouts and the environment string are verified; the actual overlay is not.++- **Windows**: not provided on this page — the front end is verified on real hardware, the full build pipeline is not. The Actions artifact `NS-Port-Builder-qt-windows-x64` has the current front end.++++## Install++++- **macOS**: download `NX2Apple-macOS-arm64.zip`, unzip, then right-click → Open on first launch. In-app updates work from 0.4.9 on under the NX2Apple name (older versions: download this one by hand).++- **Windows**: not provided on this page; the Actions artifact has the Qt front end.++++## Credits++++- **v0lumehi**: the saved-choices store, the Manage menu, the tools self-update, the Xcode team reader, the sync overhaul, the compile-gate catch, and the issue forms — eleven reviewed pull requests in two days.++- **GabeThe21stGamer**: the report that exposed the stale-tools and no-certificate paths (#87), and the free-Apple-ID test of the certificate-less install.++++---++++## 这一版做了什么++++**Mac 启动器来了,iPhone 的游戏数据终于稳了。** 启动器成了真正的游戏机风格界面:启动选项存进游戏自己的选择存储(与上游读的是同一处),游戏库的 Manage 菜单用手柄就能打开,只有普通 Apple ID、没有任何开发证书也能安装——Xcode 在第一次安装时自动把证书办齐。iPhone 这边,选择游戏数据在重启后依然有效,还没有数据的 App 会直接进启动器而不是死页面,选完按 Play 立即生效,安装器在通过 USB 拷贝几个 GB 之前会先来询问。构建工具会自己更新了,连旧版 ZIP 拷贝也能接上。++++## 新增++++- **启动选项存进游戏自己的存储**:每个设置一条字符串(`launcher.<VAR>`),写在 App 的偏好域里——正是上游启动器读取的位置,Finder 和 Dock 启动同样生效。只保留非默认值,旧启动器的选择一次性迁移;schema 1 完整支持:父项有值才显示子项(`needs`)、启动器不认识的分组按列表顺序排在已知分组之后、范围上下限来自条目本身。更新版的 schema 能读多少读多少并写进日志,绝不拒绝。++- **游戏库的 Manage 菜单换成启动器同款风格**——并且可以用手柄打开和操作。++- **构建工具自己更新**:旧版 ZIP 拷贝在 App 打开时自动接上 git(你自己的修改保留在分支上);工具比 App 旧时直接拒绝开始构建,而不是到最后一步才失败。++- **只凭 Apple ID 就能安装**:签名团队从 Xcode 的开发者偏好里读取(个人团队会标注),与证书里的合并。一个证书都没有时,Xcode 在第一次安装时自动创建(`-allowProvisioningUpdates`);提示语会说明这一点,既没有 Apple ID 也没有证书时,会告诉你确切该去哪里登录。++- **安装器在拷贝游戏文件前先询问**:Mac 经 USB 向 iPhone 只有约 25–70 MB/s,弹窗提供"现在传输"或"暂不传输"——两种选择游戏都会装上;结果卡片新增"游戏数据(romfs.img)"一行,带"在访达中显示",方便手动拷贝(把高速外接盘直接连 iPhone 更快,启动器的"选择游戏数据"可以从那里加载)。++- **Issue 表单**:游戏/构建/启动器三类问题各自要求报告所需的信息(版本、设备、Copy 诊断、游戏日志),缺了就提交不了;PR 模板和 CONTRIBUTING.md 给工具立了同样的规矩。++++## 修复++++- **iPhone:选择游戏数据终于能记住。** 书签在 Files App 的安全作用域被持有期间写入(不持作用域写出的书签从下次启动起就解析不了——于是每次选择都报"签名不同"),保存前先验证能读回,能解析但过期的书签自动重写而不必重选。解析出的作用域在整个会话期间持有,因为游戏全程都在读镜像。++- **iPhone:没有游戏数据不再是死路。** 全新安装、Documents 里没有数据、也从没选过路径时,App 会正常进启动器(旧版停在一句静态的"Game files not found"上,绝口不提选择器);按 Play 时先重新定位数据——本次会话的选择立即生效,存档/临时目录跟着最终位置走。没有启动器的极简包才回退到静态提示。++- **iPhone:签名重试复用同一行。** 团队变体重试会追加一行同 ID 的"为 … 签名",而所有更新都只打到第一行——构建都走完了它还在转圈。重试的步骤现在复用自己的行。++- **Mac:每个解包版本都作为构建资源保留。** 游戏 shader 表登记的来源版本是每次构建 shader split 的输入,删掉打包版本之外的版本,等于拿整份基础版重解去换磁盘空间——这笔账不划算,已撤销。++- **同步:下一次上游同步能跑通了。** 上游最新提交会让同步中断并悄悄丢掉 fork 代码;现在每个补丁器都在 CI 里对着真实上游测试,`--check-protection` 会列出任何没被登记的手改文件,fork 完全 own 的文件也已登记、同步不会回退它们。++++## 已知问题++++- **Mods 还没有用真正的 mod 实测过**:布局和环境变量已验证,实际的叠加加载没有。++- **Windows**:本页不提供——前端在真机上验证过,完整构建流水线没有。Actions 产物 `NS-Port-Builder-qt-windows-x64` 是当前的前端。++++## 安装++++- **macOS**:下载 `NX2Apple-macOS-arm64.zip`,解压后右键 → 打开(首次)。0.4.9 起 App 内更新在 NX2Apple 名下正常工作(更早的版本请这次手动下载)。++- **Windows**:本页不提供;Actions 产物里有 Qt 前端。++++## 致谢++++- **v0lumehi**:选择存储、Manage 菜单、工具自更新、Xcode 团队读取、同步大修、编译门禁拦截、issue 表单——两天里十一连审通过的 PR。++- **GabeThe21stGamer**:暴露了旧工具与无证书两条路径的报告(#87),以及免证书安装的免费 Apple ID 实测。+diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md+new file mode 100644+index 00000000..69666591+--- /dev/null++++ b/docs/ROADMAP.md+@@ -0,0 +1,140 @@++# Roadmap: what to do next, and why++++Three investigations ran in parallel (runtime profiles for a universal launcher, a survey of++811 forks, and the Windows front end). This is the joint conclusion, ordered by value per++week of work. Sources are named so each claim can be re-checked.++++## 1. Touch look and native aspect — the one capability we do not have++++**From [devinhurry/touch-the-wild](https://github.com/devinhurry/touch-the-wild)** (not in++upstream's tree: `hle_look.c`, `touchpad_geometry.h`, `hle_botw_touchhud.c`, `hle_aspect.c`++all verified absent from seedds/nxnative).++++Today the only way to turn the camera on a phone is holding a virtual right stick, which turns++at a fixed rate. touch-the-wild injects into the game's **own shared right-stick vector**, so++the camera, aiming and the weapon wheel all see the same input instead of one using a fake++stick and the other an injected value.++++Four details worth copying verbatim, because each is a bug that took them time:++- **float exact equality** to recognise the frame it wrote, not an epsilon window;++- **thread-local** copies of the original value, because the camera and action threads both++ call the getter and would otherwise cross-pair;++- normalisation by the frame's VFR ratio, and zero output when the drag stops;++- `touchpad_geometry.h`: one C header describing the whole virtual pad, used by both the UIKit++ view and a **Mac mouse preview**, so the layout is tuned on a desk instead of on a phone.++++Also included: **native aspect ratio** (`hle_aspect.c`) — the game renders at the screen's++aspect, the UI layer is corrected back to a centred 16:9 box, so the HUD keeps its shape and++the 3D view fills the screen.++++| Piece | Effort | Note |++|---|---|---|++| `touchpad_geometry.h` + Mac `--touch-preview` | 3–5 days | Visible immediately, zero device time |++| Relative look (`hle_look.c`) | 1–2 weeks | Needs tests; the four details above are the spec |++| Native aspect (`hle_aspect.c`) | 3–5 days per game | Needs per-game projection offsets |++| BOTW touch HUD (`hle_botw_touchhud.c`) | 3–5 days | Per-game only |++++We already have an injection point: `dm_pad_hook` in `dm/host/dm_input.h` (after++`GetNpadState` fills, before the pseudo buttons are overlaid).++++## 2. Cheats — free once upstream merges++++[wingbywings/nxnative](https://github.com/wingbywings/nxnative) ported Atmosphère's dmnt cheat++VM (all opcodes 0x0–0xFFF, `[name]`/`{master}` syntax, 0x80 codes / 0x100 words / 0x400 program++caps, 256 static registers) plus build-time baking and an in-game menu. **Upstream PR #268 is++open.** When it lands, the daily sync carries it and we expose one switch in `settings.tsv`.++++If the PR stalls, gnosticgeek/nxnative has a Markdown-format variant with a Mac sidebar++(~1 week).++++## 3. BC texture decode — halves the device requirement++++Our README says "iOS 26+ and a recent iPhone" because BC formats need a modern GPU. Two forks++proved the way out:++- `carl1347/nxnative`, `hieutran0413/nxnative`: restore `nvn_bcdec.c` (public domain `bcdec`),++ `-mcpu=apple-a14`. **3–5 days**, low risk.++- `pyaesonephyogameacc2003-arch`: BC1/2/3 → ASTC 4x4 (8 bits per texel, 4x smaller), one core++ text shared by the CPU path and a Metal kernel so both agree. 1–2 weeks, bigger win.++++Enabling this brings iPhone 14/15 and A16 iPads into range.++++## 4. Settings capability gating (AnySwitch's idea, not its code)++++[chayan-bit/AnySwitch](https://github.com/chayan-bit/AnySwitch) has a declarative settings++registry (`DmSettings.m`, 505 lines): each row carries `key` (= a `DM_*` variable), type,++range, default, `apply` (restart or live), **`requires`** (a capability) and++**`defaultAtFps`**.++++The two ideas worth taking without the code:++- **`requires`** — do not show "internal resolution" on a Vulkan game that has no NVN path.++ A hidden row is better than a dead switch.++- **`defaultAtFps`** — 30 fps games default to sharp upscaling, 60 fps to bilinear (saves++ ~4 ms/frame). One data row, read once per second.++++We already read one table from three places (`dm/games/settings.tsv` → `Launcher.swift` →++`frontend-qt`); adding two columns keeps that structure.++++Also from that fork: `nvn_ambient.h` (227 lines, present stage only) — ambient letterbox that++samples the frame's edges so a 16:9 game on a 4:3 iPad has a coloured surround instead of black.++++## 5. Windows build — the shim layer, not the WebUI++++Our `frontend-qt` detects tools on Windows but cannot build: `build_ipa_from_nsp.py` calls++`xcrun` / `xcodebuild` / `xcodegen` unconditionally.++++Two forks solved it. **Copy the small one:**++++| | zenvyzenshiro/NXNativeWindows | xbunax/nxnative |++|---|---|---|++| Size | ~24 files (`win/` shim) | full FastAPI WebUI (720 KB, 98 files) |++| Approach | `xcrun.py` maps every `xcrun metal/metallib/clang`, `sips`, `plutil` to a Windows equivalent; `Launcher.m` replaces the SwiftUI launcher; `sdk/extract_xip.py` unpacks `iPhoneOS.sdk` | same idea plus its own staging/overlay/patch build system |++| Verified on | Windows 11, LLVM 23.1.4, Metal Tools 6.2, iPhoneOS 27.1 — **Balatro built, sideloaded, ran on an A16 iPad** | Hades II IPA produced; not verified on a device |++| Fit for us | High — we already have two front ends | Low — it would be a third |++++Toolchain (pinned in both forks): LLVM-MinGW `20261020`, iPhoneOS SDK from++`xybp888/iOS-SDKs` (SHA-256 per release), Apple's **Metal Developer Tools for Windows**++(manual download, needs an Apple ID) providing `metal.exe` + `metallib.exe`.++++Effort: ~1 week for "Windows can produce an IPA".++++## 6. Universal launcher — proven feasible, bounded by Apple's rules++++The investigation overturned an assumption of mine: **all 36 `game_profile.h` macros can be++runtime.** A host built with runtime profiles produced four different guest layouts from one++binary (TotK / ACNH / Mario Galaxy / 13 Sentinels), all correct, with the full test suite green++and a clean iOS cross-compile.++++What actually bounds a universal launcher is different:++++1. **iOS cannot load executable code from disk.** Patched modules must be compiled into the++ signed binary, so every supported game's code is aggregated **at build time** — the launcher++ cannot stream game payloads.++2. **255 Mach-O section limit, and silent merging below it.** Two games' same-named modules++ merge into one section with no error (measured: the second game's code silently++ disappeared). The NRO scheme (3 shared sections + a table keyed `(game, module)`) fixes it++ and was validated packing 2 games × 2 modules.++3. **Size.** ~104 MB of modules per game, and shader libraries are larger (BotW's shadow libs++ alone 344 MB). A bundle realistically holds **4–8 games**.++++| Architecture | Games per IPA | Effort |++|---|---|---|++| A. One IPA per game + `Documents/games/<id>/{romfs,msl,save,log}` | 1 | **1 week** |++| B. Fat launcher with several games' modules embedded | 4–8 | 3–4 weeks |++| C. Shell app + per-game signed framework via `dlopen` | unbounded | large, unvalidated |++++**A already delivers what external storage needs** (romfs from an external folder, per-game++saves and logs) and enables the runtime-profile work that was already done. Do A first; B only++if 4–8 games in one app is worth it; C needs a `dlopen` experiment before any commitment.++++External storage on iOS: `UIDocumentPickerViewController` for the folder, persist a security-++scoped bookmark in UserDefaults, store the ROMFSARC index and shards there. `romfs_arc.c`++already `pread`s per shard, so an external path works unchanged —++`main.m romfs_locate` only checks `Documents/romfs` and `<App>/romfs` today.++++## Safety note from the fork survey++++Four of the 811 forks commit `prod.keys`, `atmosphere.zip` or DLC into their repositories++(Ghoshish/nxnative, JUAN-DEVRPA/nxnative, and two others). Any "sync by copying files" scheme++must work from an **allow-list**, never a deny-list. Our `sync_upstream.py` already does++(`VENDORED` = `dm scripts docs AGENTS.md ref`, plus an `OURS` set and a marker check per++carrier).+diff --git a/docs/WORK-IN-PROGRESS.md b/docs/WORK-IN-PROGRESS.md+new file mode 100644+index 00000000..163d6de3+--- /dev/null++++ b/docs/WORK-IN-PROGRESS.md+@@ -0,0 +1,88 @@++# Work in progress++++Everything below is either finished-but-unmerged, half-done, or researched-only. Ordered by++what blocks the most other work. Keep this file current: an item moves to "Done" only when it++is on main and verified.++++Last updated: 2026-10-26.++++## Done and on main (for reference)++++| Item | Commit |++|---|---|++| SwiftUI app: v0.4.3, self-update, repo download/pull, 58→69 games | `v0.4.3` |++| Save-load deadlock (issue #4), ported upstream as PR #141 | `569a415`, upstream `b87a0cc` |++| NuGet / DOTNET_ROOT / xattr environment fixes | `1cd32ed`, `ed06721`, `9741197` |++| Sync guards: unit tests + patcher-consistency check in the sync | `f074175`-1 |++| Daily health-check workflow | `.github/workflows/daily-health.yml` |++| Qt front end (Windows + macOS), dark card UI, high-DPI, ~80 MB package | `9112dda`, `ba92be2`+ |++| Windows build capability (4,100 lines: toolchain, shims, cross-compile) | `f074175` |++| Touch-pad geometry + `DM_TOUCH_PREVIEW` (layer 1 of touch support) | `9112dda` |++| Roadmap + multiplayer protocol notes | `docs/ROADMAP.md`, `docs/MULTIPLAYER.md` |++++## A. Needs your test on Windows (blocking my next step)++++**The Windows build path has never run on Windows.** The Qt front end runs (you opened it) and++the build capability is written and unit-tested on macOS, but nobody has clicked Build on a++Windows machine.++++- [ ] Download the latest `NS-Port-Builder-qt-windows-x64.zip`, run it, and report:++ does the dependency panel find a .NET SDK, and what does it say about LLVM/MinGW,++ iPhoneOS SDK and Metal tools (`python -m nspb_qt.win.doctor` gives a full report).++- Blocked by this: everything in section C.++++## B. Half-done, finish without your input++++- [x] **BC texture decode** — DONE (`7d2e044`, `840b58b`). `dm/third_party/bcdec/` (public++ domain), `dm/gfx/tex/nvn_bcdec.{c,h}`, `tex_bc_cpu` profile key, device check in++ `nvn_mtl.m`, CPU expansion in `pkg_upload_`. Unit test `t_bcdec.c` passes (BC1 matches an++ independent DXT1 decoder byte for byte). **Still needs an A15/A16 device to prove the++ rendered result** — neither of us has one.++- [ ] **Launcher architecture A**: `Documents/games/<titleID>/{romfs,msl,save,temp}` layout,++ `main.m romfs_locate` extended to look there, `DM_ROMFS`/`DM_MSL_DIR`/`DM_SAVE` set from the++ chosen game. This is what makes an external drive work. The runtime-profile part++ (`hle_profile.c`) was proven in a worktree but is **not merged**.++- [ ] Commit the runtime-profile work from the investigation++ (`/tmp/nx-mg`, branch `mg-profile-runtime`) if we adopt architecture A or B — currently the++ experimental patches live only in that worktree.++- [ ] v0.4.4 release once B has something user-visible (external drive support is the best++ candidate).++++## C. Researched only, not started++++Ordered by value per week. See `docs/ROADMAP.md` for the reasoning.++++| # | Item | Effort | Why not started |++|---|---|---|---|++| C1 | **Relative touch look** (`hle_look.c` idea) | 1–2 wks | touch-the-wild's version depends on per-game observation hooks and float-exact provenance; author says unstable. Layer 1 (geometry) is already in |++| C2 | **Native aspect ratio** (`hle_aspect.c` idea) | 3–5 d per game | Needs per-game projection offsets; layer 1 came first |++| C3 | **Atmosphère cheats** | 0 if upstream merges PR #268 | Waiting on upstream; falls back to ~1 wk of our own if it stalls |++| C4 | **Settings capability gating** (`requires` + `defaultAtFps` from AnySwitch) | 1–2 wks | Polish; needs `settings.tsv` schema change |++| C5 | **Universal launcher architecture B** (4–8 games per IPA) | 3–4 wks | Blocked on: NRO-style module packing for non-NRO modules (`loader.c map_image`), and on deciding whether 4–8 games is worth it |++| C6 | **Multiplayer (LAN / lan-play / wireless)** | 2–3 wks for one game | Protocol documented in `docs/MULTIPLAYER.md`; needs BSD socket layer + virtual network + per-game `ldn` mapping. Untested: iOS multicast entitlement on a sideloaded IPA |++| C7 | **Launcher architecture C** (`dlopen` per-game framework) | large | Needs a `dlopen` feasibility experiment first, per the investigation |++| C8 | **Pikmin 4 / Yoshi / other fork profiles** | days each | Cherriable from forks once their PRs land upstream |++++## D. Blocked on upstream++++- [ ] PR #268 Atmosphère cheats — watch for merge; our daily sync will bring it in.++- [ ] seedds/nxnative#205 (we filed): ARM64 branch range on a 185 MB text. Without it,++ EA Sports FC 27 and similar large titles cannot be rewritten.++- [ ] Upstream PRs from forks worth cherry-picking: #218/#216 (Yoshi sparse textures, texraw),++ #261 (CPU deswizzle, already merged), #269 (Pokémon Violet + BLE).++++## E. Small things I noticed but have not done++++- [ ] The Qt front end has no reproducible "check for app updates" (the SwiftUI one has it).++- [ ] Qt front end: per-stage percentage display (currently an indeterminate bar for the++ running stage; the SwiftUI app shows real percentages from the script's own output).++- [ ] `frontend-qt/README.md` says the Windows path is untested — update once section A passes.++- [ ] The games table in both READMEs is hand-inserted; `refresh_badges()` already counts the++ folders, so the table could be generated too.++- [ ] `docs/ROADMAP.md` predates the BC/multiplayer findings; fold them in.++++## How to use this file++++- Pick from A first if you are the one with the hardware; otherwise B.++- C is a menu, not a queue: each entry names its own blocker.++- Anything finished goes to the top table with its commit, so the list stays short.+diff --git a/docs/badges/games.json b/docs/badges/games.json+new file mode 100644+index 00000000..9acc0b20+--- /dev/null++++ b/docs/badges/games.json+@@ -0,0 +1,6 @@++{++ "schemaVersion": 1,++ "label": "games",++ "message": "79",++ "color": "blue"++}+diff --git a/docs/badges/verified.json b/docs/badges/verified.json+new file mode 100644+index 00000000..92b31479+--- /dev/null++++ b/docs/badges/verified.json+@@ -0,0 +1,6 @@++{++ "schemaVersion": 1,++ "label": "verified on an iPhone",++ "message": "3",++ "color": "success"++}+diff --git a/docs/launcher-c-design.md b/docs/launcher-c-design.md+new file mode 100644+index 00000000..515d3eae+--- /dev/null++++ b/docs/launcher-c-design.md+@@ -0,0 +1,339 @@++# 架构 C 具体设计:壳 App + 每游戏 framework(dlopen)++++状态:设计稿 v1(2026-10-26)。前置阅读:`docs/ROADMAP.md` 第 6 节、`docs/WORK-IN-PROGRESS.md` C5/C7、++`dm/host/hle_profile.{c,h}`(运行时 profile,已在 main,`3b36083`)。++++目标(用户原话):**"打开启动器就像打开了一台 Switch"**——一个壳 App,里面看到多个已构建的游戏,++点一个进入那个游戏。架构 A(进行中,WIP:41-47)交付按游戏隔离的数据布局;本文设计 C——壳 +++每游戏 framework——把"多个游戏装进一个 App"的**代码**维度做对。++++本文回答六个问题:framework 边界、与架构 B 的真实差异(含 codesign 的诚实结论)、构建系统改造、++运行时选择器、风险清单、工作量分解。每个结论都给证据(文件与行号,或外部来源)。++**一句话结论先放在这里:C 不能"不重签就加游戏"——iOS 只允许 dlopen 安装时已在签名 bundle 内的代码;++C 的真实价值是"每个游戏一个独立 Mach-O(各自的 255 section 预算、增量链接、坏一个不坏全局)",++不是 unbounded。第 2 节有完整论证。**++++---++++## 1. 壳 App + framework 的边界划在哪++++### 1.1 两个候选布局++++**方案 FR(推荐):framework = 纯模块容器。** 壳 App 内含一份完整宿主(loader + 全部 HLE + iOS front,++即今天 `dm/ios/Sources/main.m` + `dm/host/*` 的编译产物),每个游戏 framework 里只有:++++| framework 内容 | 来源 | 现状对应 |++|---|---|---|++| `<game>` dylib:`__TEXT,__dm<mod>x0` / `__DM<mod>W,__img` / `__TEXT,__dm<mod>x1` 三段式聚合段 | `dm/ios/tools/gen_embed.py`(不改,同样的 embed.S 进一个 dylib target 而不是可执行文件) | 今天这些 section 在主可执行文件里(`loader.c:473-476`) |++| `__DATA,__dm_nro_tab` + 三个共享 NRO 段(有 NRO 的游戏,如任天堂明星大乱斗 98 个) | `gen_embed.py`(不改) | `loader.c:485-492` |++| `Info.plist`、`Resources/dm/`(`*.fixups.tsv`、`*.gates.tsv`、`nro.tsv`、shader 表) | `build_ipa.sh:75-81` 的复制清单原样搬进 framework | 今天在 App 的 `dm/` 资源目录(`project.yml` `Gen/dm` resources) |++| `Resources/profile.tsv`(运行时 game profile,可选;优先用 Documents 里的) | `dm/games/game.py profile <id> <out>`(`game.py:192-232`) | 今天靠 DM_PROFILE 环境变量指向 |++++framework 里**没有**宿主代码、没有 ObjC 类、没有入口函数——它对 dyld 是一个"加载后不被调用"的镜像,++唯一用途是让它的段被签名映射进进程,然后 `vm_remap` 到 guest 布局。romfs / msl / save / pso 一概不进++framework(数据不是代码,走 Documents,见 1.3)。++++**方案 FH(备选):framework = 整个 dmhost + 该游戏的聚合段。** 入口++`int dmgame_main(int argc, char **argv, const char *profile_path)`(= 现在的 `dm_main`,`main.m:11` 用++`-Dmain=dm_main` 编进宿主;framework 内同名导出),壳 dlopen 后 `dlsym(handle, "dmgame_main")` 调用。++仅当 FR 的探针(第 5 节 R1)失败时退到 FH。FH 的代价:宿主对象码每个游戏重复一份(dm/host 的++.c/.m 源码合计约 11,265 行,头文件另计——重复是浪费但量级可接受);**更严重的是壳与 framework++各持一份 ObjC 类**(`front_ios.m` 的 App/SceneDelegate、Metal NVN 层的类),同名类跨镜像重复注册++是 ObjC 运行时的已知雷区;除非"壳里不放宿主",但这又把窗口/Metal 生命周期切成两半。++++### 1.2 入口符号设计(两种方案统一写法)++++FR 下"入口"在壳里,签名不变:++++```c++int dm_main(int argc, char **argv); // dm/host/main.c,现状++// C 里的调用方式(壳内):++// argv[0] = "dmhost"++// argv[1] = <选中 framework 的 Resources/dm> ← loader.c read_layout 按目录读 <mod>.fixups.tsv(loader.c:185-186)++// argv[2..] = 模块名,或省略让 profile 的 modules 生效(main.c:96)++void *h = dlopen(".../Frameworks/<game>.framework/<game>", RTLD_LAZY);++// 取镜像头传给 loader(两条等价路径,选一):++// a. void *marker = dlsym(h, "dmgame_image_marker"); // 3.2 的占位符号++// Dl_info info; dladdr(marker, &info); // info.dli_fbase = 该 framework 的 mach header++// b. dlinfo(h, RTLD_DI_LINKMAP, &lm) → lm->l_addr++// dm_set_image_header(info.dli_fbase) ← loader.c 唯一实质改动:IMAGE_MH 从 &_mh_execute_header(loader.c:484)++// 改为按游戏参数化;getsectiondata 对任意 mach header 可用++```++++FH 下的框架入口(备选才需要):++++```c++// 每个 framework 导出(壳不重复定义,无符号冲突;两游戏 framework 永不同时 dlopen,见第 5 节 R4)++int dmgame_main(int argc, char **argv, const char *profile_path);++```++++`profile_path` 参数是多余的——`hle_profile.c:211-215` 的加载顺序是"编译期默认 → DM_PROFILE 文件 →++DM_PROF_* 环境变量",壳把 DM_PROFILE 设为++`Documents/games/<id>/profile.tsv`(没有就退到 framework 的 `Resources/profile.tsv`)即可,不需要新参数。++这一点 `hle_profile.h:1-6` 的注释写得很清楚:一个无 DM_PROFILE 的构建行为与编译期完全一致——++所以壳对任何 framework 用同一套入口代码。++++### 1.3 壳如何设置环境并启动(全部复用现有开关)++++`dm/ios/Sources/main.m boot_env()`(55-121 行)已经是完整的模板,C 只是把它从"编译期单游戏"改成++"选中游戏参数化"。逐项对照:++++| 环境变量 | 现状(main.m 行号) | C 中的值 |++|---|---|---|++| `DM_ROMFS` | 87-90:`Documents/games/<DM_GAME_ID>/romfs` → `Documents/romfs` → `<App>/romfs` | `Documents/games/<选中 id>/romfs`,判定函数 `romfs_dir_ok`(19-28 行)原样复用 |++| `DM_SAVE` / `DM_TEMP` | 95-104:`game_dir_for`(36-39 行)的 per-game 布局,`romfs` 落在游戏目录内才启用 | 同上;**按游戏隔离已经存在**,壳只换 id |++| `DM_MSL_DIR` | 107-111:**已优先 per-game `<gdir>/msl`**,退到 bundle `<App>/msl` | 不改逻辑;shader 库放 `Documents/games/<id>/msl/`(数据,不进 framework,见 1.1) |++| `DM_PSO_BUNDLE` | 115-116:只查 bundle `<App>/pso` | 壳扩展为先查 `Documents/games/<id>/pso`(pso 离线管线档案是数据,BotW 一档约 650 MB/架构,`build_ipa.sh:82-86`) |++| `DM_NVN_SHMAP` | 105-106:bundle `<App>/dm/shader_map.tsv` | `<framework>/Resources/dm/shader_map.tsv` |++| `DM_PROFILE` | hle_profile.c:213-214 读取;iOS 侧今天没人设它 | `Documents/games/<id>/profile.tsv` 优先,退 framework 资源 |++| `DM_LANG` / `DM_SHOW_FPS` | 84-86(Info.plist `DMLanguage`) | 壳 Info.plist 或 Documents/env.txt(69-80 行的 env 文件机制不动) |++| 其余 `DM_*` 调试开关 | `main.c:42-46 flags_init` | Documents/env.txt,不变 |++++启动路径:壳在 UIApplicationMain 之前不知道选哪个游戏,所以 `dm_host_preload_start`(main.c:118,++main.m:119 的 UIKit 并行加载)挪到"点选游戏之后、建窗口之前"调用——顺序仍是 main.c:115-117 注释++要求的"环境变量已设好、参数一致"。++++---++++## 2. 与架构 B 的真实差异,以及 iOS codesign 下的诚实结论++++### 2.1 规则本身:iOS 只让 dlopen 签名 bundle 内的代码++++三条证据链,从官方到实测到社区:++++1. **Apple DTS 的书面答复**(Quinn "The Eskimo!",developer.apple.com/forums/thread/773210):++ *"While iOS does support `dlopen`, you can only open a library that's either built in to the OS or++ embedded within your app. ... The iOS security model is actively trying to prevent you from doing++ exactly what you're trying to do."* 该帖同一实验链还确认:同一个 dylib 放进 app bundle 能 dlopen,++ 放 Data 容器不行。++2. **实测复现**(johnno1962/InjectionNext issue #81,2025-08 起):同 TeamIdentifier 签名、合法++ load commands、甚至 get-task-allow + Developer Mode 的 dylib,只要在 bundle 外(Data 容器),++ `dlopen` 报 `code signature invalid (errno=1)`;拷进 bundle 后立即成功。结论:AMFI 拒绝的是++ **代码所在的路径**,不是签名的对错。该 issue 还确认 dylib **不能携带自己的 entitlements**。++3. **嵌入位置的官方要求**:TN2435(Embedding Frameworks In An App)与++ developer.apple.com/documentation/bundleresources/placing-content-in-a-bundle——第三方 app 的动态++ framework 必须嵌在 app bundle 的 `Frameworks/` 内并由外层签名封存(CodeResources 列出每个嵌套二进制)。++ 改动 bundle 内容 = CodeResources 变了 = 必须整体重签。++++**反例为什么不算数**:LiveContainer(github.com/LiveContainer/LiveContainer)确实做到了"装一次壳、++之后随便加 app"。它的做法(读源码确认):guest 可执行文件放在数据容器里,靠++`dlopen` 直接加载(`LCBootstrap.m:570-583`);能这样做的条件是++`"If JIT is enabled, bypass library validation so we can load arbitrary binaries"`(`LCBootstrap.m:367-371`)——++即持有 JIT/动态代码签名资格时,在**自己进程内** hook dyld:`mmap` 被换成"把文件读进匿名内存再++mprotect 成 exec"、`fcntl(F_ADDFILESIGS_RETURN)` 被改成谎报签名覆盖全文件++(`dyld_bypass_validation.m`,基于 xpnsec 的 Restoring Dyld Memory Loading,++blog.xpnsec.com/restoring-dyld-memory-loading)。README 明说:++*"(Below iOS 26) When JIT is available, codesign is entirely bypassed ... Otherwise, your app will be++signed with the same certificate used by LiveContainer"*——没有 JIT 就退回"ZSign 用壳自己的证书重签++guest"。我们的项目**不采用这条路**:JIT 资格(get-task-allow / 动态代码签名)在侧载调试场景技术上++拿得到(DolphiniOS 等靠 JIT-enabler 应用按会话附加),但那要求用户每次会话先跑一个 enabler、且整个++加载器建立在进程内 hook dyld 之上——LiveContainer 自己的代码就是"每次系统更新都可能断"的证词++(README 注明 "(Below iOS 26)",即 iOS 26 起该路径有变;`LCBootstrap.m:577-583` 为 iOS 27 另加++`bypass_seg_count_check`)。我们只需要"映射已签名页",从来不需要"执行未签名代码",++loader.c:473-476 的 vm_remap 路线不依赖任何特殊资格。**所以 LiveContainer 证明的恰恰是规则的坚硬,++不是豁口:绕过它需要 JIT 资格 + dyld hook,二者我们都不具备也不想要。**++++### 2.2 诚实结论:加游戏必须重签整个 bundle++++推演:加一个游戏 = 加一个 framework = bundle 树变化 = CodeResources 变化 = 安装时的签名失效 =++**重新签名整个 app 并重装**。侧载场景(AltStore/SideStore)本来就是每次刷新都整体重签++(SideStore FAQ:同 bundle id 重装,Documents 数据保留),所以"重签"对用户不是额外流程,++但对**分发者**是:每次加游戏要出一个新 IPA,用户下载整个 IPA 重装。++++因此 ROADMAP 第 123 行的 **"C: unbounded" 是错的,本文推翻它**。正确表述:++++- **代码维度**:games per IPA 仍由体积上界(第 5 节 R3 的同一套算术:每游戏 modules 约 104 MB,++ ROADMAP:116;系统对超大包拒绝安装,`build_ipa.sh:170-172` 记录了 PackageExtractionFailed),++ ROADMAP:117 "4–8 games" 的估计对 B 和 C 同样成立。++- **数据维度**:romfs / msl / save / pso / profile.tsv 全是数据,放 `Documents/games/<id>/`,++ 用户手动放文件即可、永不触发重签——这一维才是 unbounded,而且**架构 A 已经拿到了它**++ (WORK-IN-PROGRESS.md:41-44,`main.m` per-game 布局已实现)。++- C 的 "unbounded" 只在一种意义下接近成立:**给壳增加第 N 个游戏的边际工程成本不随 N 增长**++ (B 的聚合段和 255 section 预算是全体游戏共享的,见 2.3)。这是工程成本上的"无上界",++ 不是运行时能力上的。++++### 2.3 那 C 相对 B 还值不值?值什么++++B(4–8 游戏聚合进一个二进制,WIP C5 估 3–4 周):所有游戏的模块 section 挤进同一个 Mach-O,++共享 255 section 预算与命名空间。ROADMAP:112-115 记录了实测事故:*两个游戏同名模块静默合并进同一++section,无任何报错(第二个游戏的代码消失了)*;NRO 式"3 共享段 + (game, module) 键表"是修补,++验证到 2 游戏 × 2 模块。C 把每个游戏放进自己的 Mach-O:++++| 维度 | B(聚合二进制) | C(壳 + 每 game framework) |++|---|---|---|++| section 预算 | 全体游戏共享 255(`loader.c:485`:"a Mach-O file has at most 255 sections";SSBU 98 NRO ×3 段 = 294 已单游戏爆表) | **每 framework 各自 255**;同名 section 物理上不可能跨游戏合并——B 的静默合并 bug 在 C 里结构性不存在 |++| 增量构建 | 加/换一个游戏 → 整个巨型可执行重链接 | 只有该游戏的 dylib 重链接;壳二进制不变;`pack_ipa.py` 按文件指纹复用旧 IPA 条目(pack_ipa.py:12-15),换一个游戏的重打包接近增量 |++| 故障半径 | 任一游戏的段/链接问题让整个 IPA 构建失败 | 坏的 framework 让 `dlopen` 返回 NULL(壳弹一条错误继续);其余游戏不受影响 |++| 宿主份数 | 1 | 1(FR 方案) |++| 每游戏元数据 | 聚合表 | framework 自带(Resources + 段),分发单个游戏 = 拷一个目录 |++| 按需组合 | 每次都要全量决定装哪几个游戏 | 聚合脚本按用户拥有的 NSP 挑 framework 组装 IPA(仍是装时定死) |++| 工作量 | 3–4 周(WIP C5) | 本文第 6 节估 ~4 周 + 探针门 |++++结论:**C 的定位是"B 的更干净实现",不是"B 之外的第三种能力"**。如果 4–8 游戏一 App 值得做++(WIP C5 的悬而未决问题),C 用大约相同的成本把 B 的两个结构性风险(静默合并、全量重链)消掉,++外加按游戏分发的毛坯。若只要单游戏,A(1 周)仍然是正解,C/B 都不需要。++++---++++## 3. 构建系统怎么改++++### 3.1 现状++++`scripts/build_ipa_from_nsp.py`(NSP → IPA 全流水线)末段调 `dm/ios/tools/build_ipa.sh`:++生成 `Gen/`(`gen_build.py` 收集宿主源码、`gen_embed.py` 产 embed.S,build_ipa.sh:70-76)→++`xcodegen` 出单 target 工程(project.yml)→ `xcodebuild` 不签名构建(build_ipa.sh:138-143)→++占位 ad-hoc 签名 + entitlements(147-161 行,注释解释了为什么必须先有一个签名:侧载器要读它要替换++的 entitlements)→ `pack_ipa.py` 按 `archive path=source dir` 映射打包(166-188 行)。++一个游戏一次产出一份 IPA。Mac 侧的对应物是 `dm/mac/pack_app.py`:先签内层(`Contents/MacOS/dmhost`)++再签 bundle(pack_app.py:100-106),注释说明 hardened runtime 为何不可用。++++### 3.2 `--framework` 模式(build_ipa.sh / build_ipa_from_nsp.py)++++- 工程模板加一个 `framework` target(xcodegen `type: framework`,platform iOS),sources 只含++ `Gen/embed.S` + 一个 3 行的占位 `.m`(给镜像一个符号,供 `dladdr` 取 `dli_fbase`)+ `Info.plist`;++ `Gen/dm` 表格进 `Resources`。`gen_build.py` 不动(宿主源码归壳的 target);`gen_embed.py` 不动。++- 链接 flags:沿用 embed 的 `-Wl,-segprot,__DM<mod>W,rw,rw`(gen_embed.py 末尾输出),dylib 同样接受。++- 产物:`<game>.framework/`(dylib + Info.plist + Resources/{dm 表格, profile.tsv, launcher.json, icon}),++ 外加一个 `game.manifest.json`(title id、名称、版本、modules 列表、chain 版本 `b-$V`、romfs marker——++ 全部来自现有 `gp` 读取,build_ipa.sh:21-31)。++- chain 版本一致性:`DMSH_CHAIN` 全仓库单版本(build_ipa.sh:53 注释 "one version for every game"),++ 聚合时校验所有 framework 的 manifest 同 chain,否则拒绝组装——今天 stage_resources.sh 对单游戏做的++ 同类检查(stage_resources.sh:21-28)。++- 签名:`codesign --force --sign -` 占位 ad-hoc 签 framework(与 build_ipa.sh:158 现在签 App 的理由++ 相同:侧载器要从占位签名里读 entitlements 并全部重签)。**framework 不带 entitlements 文件**++ (dylib 无法持有 entitlements,见 2.1 证据 2;内存权限等 entitlement 全在壳上,build_ipa.sh:119-124)。++++### 3.3 壳 App 与聚合 IPA++++- 壳是新的小 target:SwiftUI(游戏网格 + 设置,复用 `dm/ios/Sources/LauncherSettings.swift` 的做法),++ 宿主源码经 `gen_build.py` 链入(`-Dmain=dm_main` 保持,入口改由壳内调用)。++- 聚合 = 新脚本 `dm/ios/tools/pack_launcher_ipa.py`(或 build_ipa_from_nsp.py 的 `--aggregate`):++ 输入壳 .app + N 个 `<game>.framework`,映射进++ `Payload/Shell.app/Frameworks/<game>.framework`,壳资源映射照旧,调 `pack_ipa.py` 产出一份 IPA++ (`--skip $P/_CodeSignature` 的既有跳过逻辑沿用,build_ipa.sh:188)。++- **签名顺序**(对照 pack_app.py:100-106 的"先内后外"):++ 1. 每个 framework 内 dylib;++ 2. 每个 framework bundle(封存其 Resources 与 Info.plist);++ 3. 壳可执行文件(带 entitlements,ad-hoc 占位);++ 4. 壳 bundle(封存 Frameworks/ 下全部嵌套代码)。++ 壳 bundle 的签名会把所有 framework 的 CD hash 写进 CodeResources——这正是"加游戏必须重签"的++ 机械原因(2.2)。侧载器(SideStore/AltStore)安装时对每个嵌套二进制重签并重建外层封存:++ 现有单二进制流程已依赖"侧载器重签并搬运 entitlements"(build_ipa.sh:147-158 注释),而++ LiveContainer 的 IPA 本身就装着 `Frameworks/LiveContainerSwiftUI.framework` 等嵌套二进制、++ 经 SideStore 安装可用——嵌套代码会被重签的旁证。++- `pack_ipa.py` 复用:framework 各自是独立映射目录,指纹(size/mtime/ctime/inode,pack_ipa.py:193-195)++ 使"换一个游戏重打包"只写变化的 framework——这是 C 增量性的落点。++++---++++## 4. 运行时选择器(壳的 UI 与数据来源)++++- **游戏列表** = 扫描两个来源后按 title id 连接:++ 1. **代码**:`Bundle.main/Frameworks/*.framework`,读每个 framework `Resources/game.manifest.json`++ (构建时生成,第 3.2 节);运行期用 `getsectiondata`/段存在性做交叉校验(防 manifest 与段不一致)。++ 不建议扫 `romfs.idx` 当列表依据——romfs 是用户可移动的数据(外置盘是计划能力:romfs_arc.c 按分片++ pread,天然支持外部路径,但今天 `main.m romfs_locate` 只查 per-game/Documents/bundle 三处,++ 文件夹选择器是待办,ROADMAP:129-132),代码在不在 bundle 里才是"装没装"。++ 2. **数据**:`Documents/games/*/`,"这个目录是不是一个游戏的文件"的判定已经存在:++ `main.m:19-28 romfs_dir_ok`(有 `romfs.idx` 或 profile 的 `romfs_marker` 路径即算)。++ - 列表状态:代码+数据 = 可玩;只有代码 = 提示"把 romfs 放进 Files";只有数据 = 灰显"IPA 里没有这个游戏++ 的 framework(需要重签安装)"——这条提示就是 2.2 结论的用户可见面。++- **存档隔离**:已经有了。`Documents/games/<id>/{save,temp}`,`main.m:95-104`:++ romfs 落在游戏目录内才用 per-game save(`per_game = [romfs hasPrefix:gdir]`,98 行),++ 壳不改这个规则,只把选中的 id 传给 `game_dir_for`(36-39 行)。WIP:41-44 与 ROADMAP:125 的++ "A 已交付 per-game 布局" 即此。++- **profile 与设置**:`DM_PROFILE` 指向 `Documents/games/<id>/profile.tsv`(用户可改,不重签),++ 无则退 framework 资源;`DM_PROF_*` 与 `DM_FPS_TARGET` 等开关的优先级链不变++ (hle_profile.h:3-5、hle_profile.c:211-219)。设置 UI 用壳自己的 launcher.json(每 framework 自带一份,++ `build_ipa.sh:96-97` 的 settings.py 产物搬进 Resources)。++- **切换游戏**:一次进程只跑一个游戏(理由见 R4)。游戏退出回壳 = 若宿主能干净收尾++ (hle_lifecycle 的 SIGTERM 路径)就回 shell 场景重建选择器;收不干净就 `exit(0)` 由用户再点图标++ (与 Switch 回 home 的手感一致)。两种都先写进壳,探针阶段一并验证。++++---++++## 5. 风险清单(每条:风险 → 证据 → 缓解/验证方式)++++- **R1 `dlopen`/`vm_remap` 在 dylib 上是否成立——C 的存在性风险,探针先行。**++ 规则层面 2.1 已定(bundle 内可 dlopen),但我们的用法有两个未验证细节:dyld 是否接受带多个++ `__DM*W` rw,rw 自定义段 + 上百 section 的 dylib;`vm_remap` copy=FALSE 把 **dylib**(而非主可执行文件)++ 的已签名 __TEXT 页重映射到匿名地址再执行是否被 AMFI 放行。现行机制对"主可执行文件自己的段"成立++ (loader.c:473-476,注释并援引 libffi trampoline table 先例),dylib 与它在内核路径上是同一类++ (同进程内已映射的签名页),但**没有实验前不下结论**。探针必须先跑。++ 说明:任务输入里提到 `dm/ios/probe/` 正在另一分支验证——**本工作树核对过 launcher-b、pr17、pr18、++ mg-profile-runtime 四个分支,`dm/ios/probe/` 尚不存在**(只有 `dm/gfx/metal/probe/` 与 `dm/host/probe.c`),++ 全仓库也没有任何 dlopen 引用。本文第 6 节把它列为第一步交付物,实验清单:++ P1 设备上 dlopen 一个 100 MB 级自定义段 dylib;P2 对其 __TEXT 段 vm_remap copy=FALSE + 执行 +++ 与现行 executable 路径逐字节对比;P3 `getsectiondata(dylib_mh, ...)`;P4 dlopen 失败的错误面++ (能否继续跑);P5 iOS 26 实机 + 侧载签名链(SideStore)各跑一遍。++- **R2 255 section 限制**:C 的每 framework 独立预算消掉 B 的跨游戏合并事故(2.3);单游戏内++ NRO 过多仍沿用共享段方案(`gen_embed.py` 注释:最多 255 sections、SSBU 98 NRO×3 段必须打包;++ `loader.c:485-492`)。残余风险:壳自身 + framework 数量不影响各镜像预算(预算是 per-Mach-O 的)。++- **R3 体积**:每游戏 framework ≈ modules(约 104 MB 原始,ROADMAP:116)+ 表格;IPA 总体积 = 壳++ (~11 K 行宿主 + SwiftUI,数 MB 级)+ N × framework。压缩后估每游戏几十 MB(deflate 对 NSO 镜像++ 的实际收益待测,无历史数据,标待验证)。shader 库(BotW 阴影库 344 MB,ROADMAP:116)、pso 档案++ (~650 MB/架构,build_ipa.sh:86)全部走 `Documents/games/<id>/`,不占 IPA。系统对过大的包拒绝安装++ (build_ipa.sh:170-172),这是 4–8 上界的最终来源。++- **R4 内存与 entitlement**:framework 不能持有 entitlements(2.1 证据 2),`increased-memory-limit`++ 只需要加在壳上(build_ipa.sh:119-124 现有做法)。运行时 profile 让内存布局全部运行期可配++ (hle_profile.h:22-23 的 mem_reserve/alias/stack/pool 等),不同游戏不需要不同签名资格。++ **同一时刻只加载一个 framework**:规避跨镜像 ObjC 类重复与 C 符号串扰,也把"多游戏同时运行"明确++ 划出范围(那是 LiveContainer 的多容器问题,不追)。内存上多装几个游戏不吃亏:未 dlopen 的++ framework 不映射任何页;dlopen 后的代码页经 vm_remap copy=FALSE 与原映射共享物理页++ (loader.c:475 "sharing the same signed pages"),不因加载翻倍;切游戏先终止当前进程(第 4 节),++ 不存在两份 guest 内存布局并存。++- **R5 dyld 行为随 iOS 版本漂移**:LiveContainer 在 iOS 26 有豁免分支、iOS 27 加段数补丁(其源码++ 2.1 节引用处);我们目标就是 iOS 26+(project.yml `deploymentTarget: iOS 26.0`)。探针必须在++ 实际目标 OS 上做,并把这个探针纳入每次大版本升级的回归清单。++- **R6 打包与增量**:`pack_ipa.py` 复用按指纹(pack_ipa.py:12-15、193-195);framework 拆映射后++ 增量成立,但 ad-hoc 重签会改变 dylib 字节 → 每次聚合后所有 framework 的指纹都会变(签名写入++ Mach-O)。缓解:聚合脚本对"构建产物 → 占位签名 → 打包"全程用固定副本,只有真正重建的 framework++ 走签名;重签发生在设备侧(侧载器),不影响构建机增量。此项需要在 W4 实测确认。++++---++++## 6. 工作量分解(按周;◇ = 依赖探针结果,∥ = 可并行)++++| 周 | 内容 | 依赖 |++|---|---|---|++| W1 | `dm/ios/probe/`:P1–P5 实验(新目录;本工作树四分支均无现成探针)| 无。3–5 天 |++| W1 ∥ | `--framework` 构建模式(build_ipa.sh 分支、xcodegen framework target、manifest 生成);Mac 上可先用普通 dylib 验证段布局与单测 | 不依赖探针(纯构建侧) |++| W1 ∥ | `loader.c` IMAGE_MH 参数化 + 宿主单测(Mac 可跑:map_image 的非 NRO 路径换成"给定 mach header")| 不依赖探针 |++| W2 ◇ | 壳 App:选择器 UI(扫描 Frameworks + Documents/games)、env 装配(第 1.3 节表)、dlopen→dm_main 接线;探针若失败则切 FR→FH(第 1.1 节)或终止 C | W1 探针 P1–P3 |++| W3 | `pack_launcher_ipa.py` 聚合 + 签名顺序 + `test_pack_ipa.py` 扩展;双游戏 IPA 在模拟器/设备装机链验证 | W2 |++| W4 ◇ | 实机端到端:两个真实游戏(探针用的 NSP 复用)、切游戏、存档隔离、坏 framework 容错、R6 增量实测、文档收尾 | W3 + 用户的 NSP |++| 缓冲 | R5 的 iOS 26.1/27 差异回归、FH 备选路径(若 P2 失败,+1 周实现 FH 的 dmgame_main 与壳移交)| — |++++总计:**约 4 周到"双游戏可玩",探针失败再 +1 周(FH)或止损回 B**。与 B 的 3–4 周相比没有省,++买到的是 2.3 表里的结构性收益;决定点仍建议放在 W1 探针之后。++++---++++## 7. 证据来源汇总++++仓库内(文件:行号见正文):++- `dm/host/loader.c:473-476`(iOS 嵌入与 vm_remap/libffi 先例)、`:485-492`(255 section 与 NRO 打包)、++ `:185-186`(fixups.tsv 运行期按目录读取)、`:252`(gates.tsv)++- `dm/ios/tools/gen_embed.py:1-13`(三段式段、ITMS-90999 单可执行段、NRO 共享段 + 表)++- `dm/host/main.c:42-46,87-97,115-124`(DM_* 开关、模块清单来源、preload 约定)++- `dm/ios/Sources/main.m:19-28,36-39,41-52,69-80,87-116`(per-game 布局、romfs 判定、env 装配全表)++- `dm/host/hle_profile.{h:1-6, c:211-219}`(运行时 profile 加载顺序);`dm/games/game.py:192-232`(profile TSV 生成)++- `dm/ios/tools/build_ipa.sh:53,70-76,96-97,100-101,117-124,138-161,166-188`(chain 版本、Gen 生成、++ entitlements、不签名构建、占位签名、pack 映射)++- `dm/ios/tools/pack_ipa.py:12-15,193-195`(指纹复用);`dm/ios/tools/stage_resources.sh:21-28`(chain 校验先例)++- `dm/ios/project.yml`(iOS 26.0 target、Gen/dm resources、`-Dmain=dm_main`)++- `dm/mac/pack_app.py:100-106`(先内后外签名先例)++- `dm/host/dm.h:11`(MAX_MOD 128:profile 模块 + NRO 上限)++- `docs/ROADMAP.md:109-127`(调查结论、255 合并事故、104 MB/游戏、A/B/C 表);`docs/WORK-IN-PROGRESS.md:41-47,61,63`(A 现状、C5/C7)++++仓库外:++- Apple DTS(Quinn "The Eskimo!"),dlopen 规则:developer.apple.com/forums/thread/773210++- InjectionNext 实测(bundle 外同 TeamID dylib 被拒、dylib 无 entitlements):github.com/johnno1962/InjectionNext/issues/81++- TN2435 嵌入 framework:developer.apple.com/library/archive/technotes/tn2435/_index.html;++ Placing content in a bundle:developer.apple.com/documentation/bundleresources/placing-content-in-a-bundle++- LiveContainer(JIT 条件下的 dyld 验证绕过、无 JIT 则重签 guest、iOS 26/27 适配):++ github.com/LiveContainer/LiveContainer(README;`LiveContainer/LCBootstrap.m`、`LiveContainer/dyld_bypass_validation.m`)++- SideStore FAQ(重装同 bundle id 数据保留、重签模型):docs.sidestore.io/docs/faq;++ 免费 Apple ID 3 app / 10 App ID 限制:faq.altstore.io(这也是"所有游戏进一个壳"的动机之一)++++> **Update (merged):** the dlopen probe now exists — `dm/ios/probe/` with `build_probe.sh`, committed alongside this document, and `probe-out/DmProbe.ipa` is built. W1 step 1 is done; what remains is running it on an iOS 26 device and reading `Documents/probe-log.txt`.diff --git a/patches/0021-ref-hle-hid-d2r.patch b/patches/0021-ref-hle-hid-d2r.patchnew file mode 100644index 00000000..70353ec6--- /dev/null+++ b/patches/0021-ref-hle-hid-d2r.patch@@ -0,0 +1,435 @@+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001+From: v0lumehi <[email protected]>+Date: Wed, 28 Oct 2026 13:33:56 +0100+Subject: [PATCH] ref: hle_hid_d2r.c++Reference only; not built.++Upstream-Status: fork-only+Reason: Reference copy of the d2r-mobile HID layer+Issue: LNPANDY/NX2Apple#123+---+ ref/hle_hid_d2r.c | 414 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 414 insertions(+)+ create mode 100644 ref/hle_hid_d2r.c++diff --git a/ref/hle_hid_d2r.c b/ref/hle_hid_d2r.c+new file mode 100644+index 00000000..584d867b+--- /dev/null++++ b/ref/hle_hid_d2r.c+@@ -0,0 +1,414 @@++// nn::hid (controller / touchscreen): on the real device shared memory is read through the hid service; the host takes it from the current dm_input state, written by the front end (Mac keyboard / iOS touchscreen).++// The connected controller follows the operation mode: DM_OPMODE=1 (console, default) → 1P full-key controller; 0 (handheld) → handheld controller. Vibration is not supported (device count 0).++#include "hle.h"++#include "dm_uiscreen.h"++#include "dm_actions.h"++#include "dm_cursor_item.h"++#include <unistd.h>++#include "dm_input.h"++#include "front.h"++#include <stdatomic.h>++#include "dm_cursor.h"++#include <math.h>++_Atomic int g_dm_l_presses;++++enum { NPAD_HANDHELD = 0x20 };++enum { STYLE_FULLKEY = 1u << 0, STYLE_HANDHELD = 1u << 1 };++enum { ATTR_CONNECTED = 1u << 0 };++++// nn::hid::NpadFullKeyState / NpadHandheldState have the same layout++typedef struct {++ int64_t sampling;++ uint64_t buttons;++ int32_t lx, ly, rx, ry;++ uint32_t attributes;++ uint32_t _pad;++} NpadState;++_Static_assert(sizeof(NpadState) == 0x28, "NpadState");++++static struct { _Atomic uint64_t buttons; _Atomic int32_t lx, ly, rx, ry; } g_in;++static _Atomic int64_t g_sampling;++static _Atomic uint64_t g_sampled_right;++void dm_input_sampled_right(int32_t *rx,int32_t *ry) {++ uint64_t v=atomic_load_explicit(&g_sampled_right,memory_order_acquire);++ *rx=(int32_t)(uint32_t)v;*ry=(int32_t)(uint32_t)(v>>32);++}++++// Test switch DM_TEST_HID_STALL_MS=<milliseconds>: each time a press edge of the A published by the front end appears, the game's next controller read first sleeps this long before reading -- simulates "the game stalls at the moment of the tap".++// After opening the function page the game did not read input for about 0.4 s, and a tap pulse of 0.12 s wall clock was lost entirely (tapped, no response); the front end now ends the pulse by dm_input_samples++static int g_stall_ms = -1; static _Atomic int g_stall_due;++// Press-edge latch: when a key published by the front end goes from "not pressed" to "pressed" it is recorded in g_press_latch, delivered along with the game's next controller read and cleared once delivered.++// When press and release fell between two controller reads of the game (two steps sent back to back when the script lags, or the game stalling input reads while loading / opening a panel) the whole key press used to be lost -- real device rf1, restarts 2 and 3:++// the bottom bar menu key had only 0.09 ms from press to release, the game did not see it and the function page did not open. The latch only gives one extra sample, afterwards the front end's current value applies (released is released)++static _Atomic uint64_t g_press_latch;++// Controller (dm_input.h dm_pad_set): buttons and the four axes are packed into two atomics, and press edges are likewise latched until the game's next++// read (short controller presses are not lost)++static _Atomic uint64_t g_pad_btn, g_pad_axes, g_pad_latch;++void dm_pad_set(uint64_t buttons, int32_t lx, int32_t ly, int32_t rx, int32_t ry) {++ uint64_t old = atomic_exchange(&g_pad_btn, buttons); atomic_fetch_or(&g_pad_latch, buttons & ~old);++ atomic_store(&g_pad_axes, (uint64_t)(uint16_t)lx | (uint64_t)(uint16_t)ly << 16 | (uint64_t)(uint16_t)rx << 32 | (uint64_t)(uint16_t)ry << 48);++}++void dm_input_set(uint64_t buttons, int32_t lx, int32_t ly, int32_t rx, int32_t ry) {++ if (g_stall_ms < 0) { const char *e = getenv("DM_TEST_HID_STALL_MS"); g_stall_ms = e ? atoi(e) : 0; if (g_stall_ms) LOG("DM_TEST_HID_STALL_MS: after each A press edge the game's controller read first sleeps %d ms", g_stall_ms); }++ if (g_stall_ms > 0 && (buttons & DM_BTN_A) && !(g_in.buttons & DM_BTN_A)) atomic_store(&g_stall_due, 1);++ atomic_fetch_or(&g_press_latch, buttons & ~g_in.buttons); // record newly pressed keys, guaranteeing the game reads them at least once (see fill)++ g_in.buttons = buttons; g_in.lx = lx; g_in.ly = ly; g_in.rx = rx; g_in.ry = ry;++}++// Test switch DM_UI_TAPS="frame:x,y[:action];..." (x / y = per-mille of the picture). Default action = one tap (via dm_ui_touch: press, lift 6 frames later); the others go through dm_ui_ptr (for probing / UI cases):++// k tap a tab / dialog menu item (the host presses keys to switch to it); t<frames> finger held this many frames then lifted (via dm_ui_touch); h<frames> hover; p<frames> left button held this many frames then released; r right button; l left button (pointer path); d<x2>,<y2> hold and drag to another point (done in 20 frames); g<x2>,<y2> continuous gesture (dm_ui_drag_*: typed as scroll / slider by the start-to-end direction, done in 60 frames); W tap the game world (dm_world_tap); N<value> set the quantity box value (dm_num_set); A<number> buy/sell / stat point entries (dm_actions.c); w<amount> wheel (120 per notch, negative = down); m<0|1> map back to minimap / to full screen (dm_ui_map_full); prefix s / c = holding Shift / Ctrl (VK 0x10 / 0x11)++static void ui_taps_step(void) {++ static struct { uint64_t fr; float x, y, x2, y2; int st, kind, arg, shift; } tp[128]; static int n = -1;++ if (n < 0) { n = 0; const char *e = getenv("DM_UI_TAPS"); char buf[4096]; if (e) { strlcpy(buf, e, sizeof buf); for (char *t = strtok(buf, ";"); t && n < 128; t = strtok(NULL, ";")) {++ unsigned long long f; int x, y, c = 0; if (sscanf(t, "%llu:%d,%d%n", &f, &x, &y, &c) < 3) continue;++ tp[n].fr = f; tp[n].x = x / 1000.0f; tp[n].y = y / 1000.0f; tp[n].kind = 0; const char *a = t + c;++ if (*a == ':') { a++; if (*a == 's' || *a == 'c') { tp[n].shift = *a == 's' ? 0x10 : 0x11; a++; } tp[n].kind = *a; int p = 0, q = 0;++ if ((*a == 'd' || *a == 'g') && sscanf(a + 1, "%d,%d", &p, &q) == 2) { tp[n].x2 = p / 1000.0f; tp[n].y2 = q / 1000.0f; } else tp[n].arg = atoi(a + 1); }++ n++; } LOG("DM_UI_TAPS: %d entries", n); } }++ uint64_t fr = dm_guest_frame();++ static int rel = -1; if (rel < 0) rel = getenv("DM_UI_TAPS_AT") != NULL;++ if (rel) { uint64_t b = dm_ui_taps_base(); if (!b || fr < b) return; fr -= b; }++ for (int i = 0; i < n; i++) { if (fr < tp[i].fr || tp[i].st < 0) continue; int d = (int)(fr - tp[i].fr), k = tp[i].kind; float x = tp[i].x, y = k == 'W' ? tp[i].y : dm_ui_ny(tp[i].y); // script coordinates are per-mille of the real picture; world taps use them as is, UI taps are converted into the UI rectangle++ if (!k || k == 't') { int hold = k ? tp[i].arg : 6; if (tp[i].st == 0) { tp[i].st = 1; dm_ui_touch(0, x, y); } else if (tp[i].st == 1 && d >= hold) { tp[i].st = -1; dm_ui_touch(2, x, y); } continue; }++ if (k == 'N') { void dm_num_set(int); dm_num_set(tp[i].arg); tp[i].st = -1; continue; } // set the quantity box value (dm_textinput.c; -1 all, -2 half)++ if (k == 'A') { void dm_shop_buy(void), dm_shop_sell_cursor(void), dm_stat_add(int, int), dm_skill_add_selected(void); int v = tp[i].arg; // action entries (dm_actions.c): A1 buy, A2 sell what is on the cursor, A3 skill +1, A4 pick up the first sellable item in the inventory (for testing), A5 put the first potion in the inventory into the belt (for testing), A6 directly sell the first sellable item carried (for testing), A21-A24 immediately use the first potion / scroll / tome / cube in the inventory (for testing, dm_item_use), A1000+id put that item into the belt, A1xy add y (1 / 5 / 9 = all) to stat x (0–3)++ if (v == 1) dm_shop_buy(); else if (v == 2) dm_shop_sell_cursor(); else if (v == 3) dm_skill_add_selected(); else if (v == 4) { void dm_test_hold_first_sellable(void); dm_test_hold_first_sellable(); } else if (v == 6) { void dm_test_sell_first(void); dm_test_sell_first(); } else if (v == 5) { void dm_test_belt_first_potion(void); dm_test_belt_first_potion(); } else if (v == 35 || v == 38 || v == 39) { void dm_inv_sort(int); dm_inv_sort(v == 35 ? 0 : v == 38 ? 3 : 4); } else if (v == 36) { void dm_name_random(void); dm_name_random(); } else if (v >= 44 && v <= 46) { void dm_test_identify(int); dm_test_identify(v - 43); } else if (v == 74) { void dm_held_stow(void); dm_held_stow(); } else if (v == 75) { void dm_test_swap_held(void); dm_test_swap_held(); } else if (v >= 70 && v <= 73) { dm_uiscreen_enable(v - 70); } /* A70-A73: UI picture off / top-aligned / centered / bottom-aligned (through the same entry the front end uses) */ else if (v == 47 || v == 48) { dm_stash_take(v == 47 ? 1 : 3); } else if (v == 43) { dm_cursor_item_info ci; int hw = 0, hh = 0, c = dm_cursor_item(&ci), hd = dm_held_size(&hw, &hh); LOG("test: cursor item %s container %d cell %d,%d size %dx%d stack %d; held %d (%dx%d); awaiting target %d", c ? ci.code : "none", c ? ci.container : 0, c ? ci.gx : 0, c ? ci.gy : 0, c ? ci.gw : 0, c ? ci.gh : 0, c ? ci.stack : 0, hd, hw, hh, dm_item_targeting()); } else if (v >= 50 && v <= 69) { void dm_test_stash_take(int); dm_test_stash_take(v - 50 ? v - 50 : 1); } else if (v >= 40 && v <= 42) { void dm_test_equip(int); dm_test_equip(v - 39); } else if (v == 33 || v == 34) { void dm_belt_expand(int); dm_belt_expand(v == 33); } else if (v == 31 || v == 32) { void dm_item_compare(int); dm_item_compare(v == 31); } else if (v == 30) { void dm_test_hover_at(float, float); dm_test_hover_at(x, y); } else if (v >= 21 && v <= 26) { void dm_test_use_first(int); dm_test_use_first(v - 20); } else if (v >= 1000) { void dm_belt_put(uint32_t); dm_belt_put((uint32_t)(v - 1000)); } else if (v >= 100) dm_stat_add(v / 10 % 10, v % 10 == 9 ? -1 : v % 10); tp[i].st = -1; continue; }++ if (k == 'W') { unsigned dm_world_tap(float, float); dm_world_tap(x, y); tp[i].st = -1; continue; } // tap the game world (dm_world.c: tapping a target = interact)++ if (k == 'g') { float t = d / 60.0f; if (t > 1) t = 1;++ if (tp[i].st == 0) { tp[i].st = 1; int hz = fabsf(tp[i].x2 - x) * 16 > fabsf(tp[i].y2 - y) * 9; dm_ui_drag_begin(hz ? 2 : 1, x, y, tp[i].arg ? tp[i].arg / 1000.0f : 0.05f); }++ dm_ui_drag_move(x + (tp[i].x2 - x) * t, y + (tp[i].y2 - y) * t); if (d >= 62) { dm_ui_drag_end(); tp[i].st = -1; } continue; }++ if (k == 'k') { static unsigned ks[128]; if (tp[i].st == 0) { tp[i].st = 1; ks[i] = dm_ui_item_query(x, y); } else if (d >= 3) { tp[i].st = -1; if (dm_ui_item_result(ks[i]) == 2) dm_ui_tab_go(); } continue; } // k = tap once the "tab / dialog menu" way (query the hit → if yes, let the host press the key)++ if (tp[i].st == 0) { tp[i].st = 1; dm_ui_item_query(x, y); dm_ui_ptr(DM_UP_HOVER, x, y, 0); if (tp[i].shift) dm_ui_ptr(DM_UP_KEYDOWN, x, y, tp[i].shift); continue; }++ int done = 0;++ if (k == 'h') done = d >= tp[i].arg;++ else if (k == 'r' || k == 'l') { if (tp[i].st == 1 && d >= 4) { tp[i].st = 2; dm_ui_ptr(k == 'r' ? DM_UP_RDOWN : DM_UP_LDOWN, x, y, 0); dm_ui_ptr(k == 'r' ? DM_UP_RUP : DM_UP_LUP, x, y, 0); } done = d >= 10; }++ else if (k == 'p') { if (tp[i].st == 1 && d >= 4) { tp[i].st = 2; dm_ui_ptr(DM_UP_LDOWN, x, y, 0); } else if (tp[i].st == 2 && d >= 4 + tp[i].arg) { tp[i].st = 3; dm_ui_ptr(DM_UP_LUP, x, y, 0); } done = d >= 10 + tp[i].arg; }++ else if (k == 'm') { if (tp[i].st == 1) { tp[i].st = 2; dm_ui_map_full(tp[i].arg); } done = d >= 4; }++ else if (k == 'w') { if (tp[i].st == 1 && d >= 4) { tp[i].st = 2; dm_ui_ptr(DM_UP_SCROLL, x, y, tp[i].arg); } done = d >= 8; }++ else if (k == 'd') { if (tp[i].st == 1 && d >= 4) { tp[i].st = 2; dm_ui_ptr(DM_UP_LDOWN, x, y, 0); }++ else if (tp[i].st == 2 && d >= 6) { float t = (d - 6) / 20.0f; if (t > 1) t = 1; dm_ui_ptr(DM_UP_MOVE, x + (tp[i].x2 - x) * t, y + (tp[i].y2 - y) * t, 0); if (d >= 30) { tp[i].st = 3; dm_ui_ptr(DM_UP_LUP, 0, 0, 0); } }++ done = d >= 36; }++ else done = 1;++ if (done) { tp[i].st = -1; if (tp[i].shift) dm_ui_ptr(DM_UP_KEYUP, x, y, tp[i].shift); dm_ui_ptr(DM_UP_END, x, y, 0); } }++}++static _Atomic uint64_t g_stick_ns;++uint64_t dm_stick_last_ns(void) { return atomic_load(&g_stick_ns); } // criterion for "click-to-move packets may only come from the stick" (diag.c c2s_deliver)++uint64_t dm_input_samples(void) { return (uint64_t)atomic_load(&g_sampling); } // cumulative number of times the game has read the controller (the front end uses it to judge whether a key press has been seen by the game)++++static uint32_t connected_id(void) { return dm_opmode() == 0 ? NPAD_HANDHELD : 0; } // follows the operation mode (hle_oe.c is the single source)++static uint32_t style_of(uint32_t id) {++ if (id != connected_id()) return 0;++ return id == NPAD_HANDHELD ? STYLE_HANDHELD : STYLE_FULLKEY;++}++// Scripted input (can inject without opening a window), two kinds of comma-separated items:++// By time: key@seconds[+hold seconds] DM_KEYS="A@8,A@12+0.5" = press A at second 8 (held 0.2 s by default), press A for 0.5 s at second 12; time counts from host initialization++// By UI message: key@pre[%delay seconds][+hold seconds][>confirm] DM_KEYS="A@OpenPanel:MainMenuButtonRibbon>OpenPanel:CharacterDifficultyModal,A@OpenPanel:CharacterDifficultyModal>FrontEndNavigation:ToGame"++// Same rules as dm/verify/ryu/drive.py: message string = "category:action:panel name", pre / confirm match by substring; steps run in order.++// The pre has appeared after the previous step was pressed (first step: since start) and the previous key press is idle (see below) → press for 3 frames (50 ms;++// "+hold seconds" changes the hold duration, e.g. LSL@UnloadPanel:LoadScreenPanel+0.9 = push the left stick for 0.9 s as soon as the loading screen ends, so a key pressed by host time does not land before the run is entered);++// only re-press if no confirm arrives within 150 server ticks, after 3 times without one report a failure and abort; the 60 s wall clock is only a fallback and reports a failure; a step with no confirm item is done once pressed.++// An empty pre (e.g. LSU@%0.2+0.35) = press after a delay right after the previous step completes (confirm arrived / released if no confirm item).++// Idle = the previous key press has been released, and the last InputMessage:ControllerActionBegin during the hold has got its ControllerActionEnd (Begin is only sent when a panel consumes++// input: in the wild1 ground truth, pressing A in a run to open the waypoint has no Begin / End before or after, they only appear in pairs once a panel takes over; no Begin during the hold ⇒ idle on release.++// Stick pseudo-keys follow the same rule). The former "must see End" never arrived after in-run key presses.++// Key name = DM_BTN_* from dm_input.h without the prefix, plus the left stick pseudo-keys LSL / LSR / LSU / LSD (pushed to full while held). ORed bitwise with the keys written by the front end.++// Touch item T<x>:<y> (only for steps driven by UI messages): while held, one finger (id 0, via dm_touch_set) is put down at normalized rendered-picture coordinates (x, y), lifted on release / confirm.++#define K(n) {DM_BTN_##n, #n} // key names are generated directly from DM_BTN_* in dm_input.h, the bit order is defined in one place only++static const struct { uint32_t mask; const char *name; } k_names[] = {++ K(A), K(B), K(X), K(Y), K(LS), K(RS), K(L), K(R), K(ZL), K(ZR), K(PLUS), K(MINUS), K(LEFT), K(UP), K(RIGHT), K(DOWN)};++#undef K++// Left stick pseudo-keys (used only in scripts): while held the stick is pushed fully in that direction; the bits lie outside DM_BTN_* and do not enter the button bits++enum { PK_LSL = 1u << 24, PK_LSR = 1u << 25, PK_LSU = 1u << 26, PK_LSD = 1u << 27, PK_MASK = 0xFu << 24, PK_TOUCH = 1u << 28, PK_MSG = 1u << 29, PK_CLICK = 1u << 30 }; // PK_CLICK: UI click step (C<x>:<y>, via dm_ui_touch = the same injected mouse message path as a real finger on the iOS front end) // PK_TOUCH: touch point step (T<x>:<y>, via dm_touch_set)++static const struct { uint32_t mask; const char *name; } k_stick[] = {{PK_LSL, "LSL"}, {PK_LSR, "LSR"}, {PK_LSU, "LSU"}, {PK_LSD, "LSD"}};++#define KMAX 256++static struct { uint32_t mask; uint64_t t0, t1; } g_keys[KMAX];++static int g_nkeys;++static uint64_t g_kbase;++// Steps driven by UI messages (state is driven from two sides, the UI message callback and the controller read, protected by g_klock)++enum { KS_PRE, KS_HOLD, KS_OK, KS_DONE };++static struct { uint32_t mask; char pre[96], ok[96]; int seen_pre, seen_server, hold_override; double delay_seconds, hold_seconds; uint64_t seen_clock, seen_at; float tx, ty; char msg[96]; } g_steps[KMAX]; // in a run, by server ticks; before entering the game, by presented frames++static int g_nsteps, g_kcur, g_kstate, g_ktries, g_krel = 1, g_kbeg, g_kend; // beg/end are 0/1 markers of the action lifecycle, not message counts; idle = released and the last Begin has got its End++static uint64_t g_kpress, g_kpress_clock; static int g_kpress_server;++static pthread_mutex_t g_klock = PTHREAD_MUTEX_INITIALIZER;++static struct { char msg[160]; int32_t x, y; } g_cursor_tests[KMAX];++static int g_ncursor_tests, g_cursor_cur;++#define SERVER_TICKS_PER_SECOND 25ull++#define PRODUCT_FRAMES_PER_SECOND 60ull++#define ACTION_HOLD_TICKS 2ull // action keys 2 ticks (about 80 ms, spanning at least one full tick): held too long, minus is taken as a repeated press and the automap switches to the full-screen mode (measured: automap red at 15 ticks)++#define DIRECTION_HOLD_TICKS 3ull // direction keys at least 3 ticks: three consecutive samples are enough to catch it reliably++#define OK_WAIT_TICKS 150ull++#define WALL_FALLBACK_NS 60000000000ull++++typedef struct { uint64_t value; int server; } script_clock;++static script_clock script_clock_now(void) {++ uint64_t tick = dm_server_tick(); { extern _Atomic int g_dm_frozen; if (atomic_load(&g_dm_frozen)) tick = UINT64_MAX; } // while the world is frozen (panel freeze, diag.c) the tick number does not advance, the script times by presented frames instead, otherwise delays and hold durations would never be reached++ return tick == UINT64_MAX ? (script_clock){dm_guest_frame(), 0} : (script_clock){tick, 1};++}++static uint64_t script_clock_elapsed(script_clock now, uint64_t start, int start_server) {++ return now.server == start_server && now.value >= start ? now.value - start : 0;++}++static uint64_t script_seconds_to_units(double seconds, int server) {++ return (uint64_t)(seconds * (server ? SERVER_TICKS_PER_SECOND : PRODUCT_FRAMES_PER_SECOND));++}++static uint64_t step_hold_units(const typeof(g_steps[0]) *st, int server) {++ if (st->hold_override) return script_seconds_to_units(st->hold_seconds, server);++ return (st->mask & (DM_BTN_UP | DM_BTN_DOWN | DM_BTN_LEFT | DM_BTN_RIGHT | PK_MASK)) ? DIRECTION_HOLD_TICKS : ACTION_HOLD_TICKS;++}++++static void cursor_tests_parse(void) {++ g_ncursor_tests = g_cursor_cur = 0;++ const char *e = getenv("DM_TEST_CURSOR"); if (!e || !*e) return;++ char buf[4096]; strncpy(buf, e, sizeof buf - 1); buf[sizeof buf - 1] = 0;++ for (char *save, *tok = strtok_r(buf, ";", &save); tok; tok = strtok_r(NULL, ";", &save)) {++ char *colon = strrchr(tok, ':'); int x, y; char extra;++ if (!colon || sscanf(colon + 1, "%d,%d%c", &x, &y, &extra) != 2 || g_ncursor_tests == KMAX)++ die("DM_TEST_CURSOR entry '%s' format: UI-message-trigger:x,y", tok);++ *colon = 0;++ if (!*tok) die("DM_TEST_CURSOR entry has an empty trigger string");++ strncpy(g_cursor_tests[g_ncursor_tests].msg, tok, sizeof g_cursor_tests[0].msg - 1);++ g_cursor_tests[g_ncursor_tests].msg[sizeof g_cursor_tests[0].msg - 1] = 0;++ g_cursor_tests[g_ncursor_tests].x = (int32_t)x;++ g_cursor_tests[g_ncursor_tests].y = (int32_t)y;++ g_ncursor_tests++;++ }++}++++static void step_chain(void) { // holds g_klock: the current step's pre is left empty ⇒ counts as seen as soon as the previous step completes++ if (g_kcur < g_nsteps && !g_steps[g_kcur].pre[0] && !g_steps[g_kcur].seen_pre) { script_clock c = script_clock_now(); g_steps[g_kcur].seen_pre = 1; g_steps[g_kcur].seen_at = now_ns(); g_steps[g_kcur].seen_clock = c.value; g_steps[g_kcur].seen_server = c.server; }++}++static void keys_on_uimsg(const char *cat, const char *act, const char *arg) {++ char m[256]; snprintf(m, sizeof m, "%s:%s:%s", cat, act, arg);++ pthread_mutex_lock(&g_klock);++ if (g_cursor_cur < g_ncursor_tests && strstr(m, g_cursor_tests[g_cursor_cur].msg)) {++ int i = g_cursor_cur++;++ dm_cursor_set(g_cursor_tests[i].x, g_cursor_tests[i].y);++ }++ // Repeat triggers of a long press/stick send a Begin each time, release sends only one End (observed on the iOS host: 73 Begin/1 End).++ // A new Begin marks the action as still busy and cancels the old End; repeated Begins do not increase the wait count, only End marks it finished.++ if (strstr(m, "InputMessage:ControllerActionBegin") && !g_krel) { g_kbeg = 1; g_kend = 0; }++ if (strstr(m, "InputMessage:ControllerActionEnd")) g_kend = 1;++ if (g_kcur < g_nsteps) {++ if (g_kstate != KS_PRE && g_steps[g_kcur].ok[0] && strstr(m, g_steps[g_kcur].ok)) {++ LOG("hid script step %d confirmed '%s' (press %d, waited %llu clock units, wall clock %llu ms)", g_kcur + 1, m, g_ktries,++ (unsigned long long)(script_clock_now().value - g_kpress_clock), (unsigned long long)((now_ns() - g_kpress) / 1000000ull));++ if (g_kstate == KS_HOLD && (g_steps[g_kcur].mask & PK_TOUCH)) dm_touch_set(NULL, 0);++ if (g_kstate == KS_HOLD && (g_steps[g_kcur].mask & PK_CLICK)) dm_ui_touch(2, g_steps[g_kcur].tx, g_steps[g_kcur].ty); // touch step confirmed while held: lift the finger++ g_krel = 1; // confirmed while still held (e.g. opening a panel): the state leaves KS_HOLD and no more key is output ⇒ released at this moment (wild1 step 3 used to get stuck here)++ g_kcur++; g_kstate = KS_PRE; g_ktries = 0; step_chain();++ }++ // Pre: checked while the current step is waiting for its pre; when the current step is already pressed, the next step's is checked (only messages appearing after the previous step was pressed count)++ int j = g_kstate == KS_PRE ? g_kcur : g_kcur + 1;++ if (j < g_nsteps && !g_steps[j].seen_pre && g_steps[j].pre[0] && strstr(m, g_steps[j].pre)) { script_clock c = script_clock_now(); g_steps[j].seen_pre = 1; g_steps[j].seen_at = now_ns(); g_steps[j].seen_clock = c.value; g_steps[j].seen_server = c.server; }++ }++ pthread_mutex_unlock(&g_klock);++}++static uint32_t steps_now(void) {++ if (!g_nsteps) return 0;++ uint64_t t = now_ns(); uint32_t m = 0;++ pthread_mutex_lock(&g_klock);++ if (g_kcur < g_nsteps) {++ typeof(g_steps[0]) *st = &g_steps[g_kcur];++ script_clock c = script_clock_now();++ // Clock source switch (main menu frames ↔ in-run ticks ↔ frozen-period frames): the start point is recounted from the new source, otherwise the elapsed time across sources is always 0 and the wait never ends++ if (st->seen_pre && c.server != st->seen_server) { st->seen_clock = c.value; st->seen_server = c.server; }++ if (g_kstate != KS_PRE && c.server != g_kpress_server) { g_kpress_clock = c.value; g_kpress_server = c.server; }++ uint64_t elapsed = script_clock_elapsed(c, st->seen_clock, st->seen_server);++ int dm_loadscreen_up(void); void dm_hold_for_loadscreen(void);++ if (g_kstate == KS_PRE && st->seen_pre && elapsed >= script_seconds_to_units(st->delay_seconds, c.server) && dm_loadscreen_up()) dm_hold_for_loadscreen(); // due (pre seen and delay elapsed) but the loading screen is still up: freeze the tick, do not press yet (diag.c). Not frozen while the delay has not elapsed: after a waypoint act change a step due to press 62 seconds later was queued, and as soon as the loading screen opened the clock was frozen before the server handled the teleport, loading waited for the server, the server waited for the clock, deadlock++ else if (g_kstate == KS_PRE && st->seen_pre && g_krel && (g_kend >= g_kbeg || (st->mask & (PK_MSG | PK_CLICK))) && elapsed >= script_seconds_to_units(st->delay_seconds, c.server)) { // a message step presses no key, so it need not wait for the previous key's controller action to wrap up (a Begin re-triggered while the previous step is held sometimes never gets its End, 1 of 3 runs of the Mac iOS app got stuck here)++ g_kstate = KS_HOLD; g_kpress = t; g_kpress_clock = c.value; g_kpress_server = c.server; g_krel = 0; g_kbeg = g_kend = 0; g_ktries = 1;++ if (st->mask & PK_TOUCH) { dm_touch p = {0, st->tx, st->ty}; dm_touch_set(&p, 1); }++ if (st->mask & PK_MSG) dm_ui_send_queue(st->msg);++ if (st->mask & PK_CLICK) dm_ui_touch(0, st->tx, st->ty);++ LOG("hid script step %d pressed mask=%#x (pre '%s')", g_kcur + 1, st->mask, st->pre);++ } else if (g_kstate == KS_OK && t - g_kpress >= WALL_FALLBACK_NS) {++ die("[RED] hid script step %d: wall-clock fallback timeout (waited %llu server ticks, wall clock %llu ms, confirm '%s')", g_kcur + 1,++ (unsigned long long)script_clock_elapsed(c, g_kpress_clock, g_kpress_server), (unsigned long long)((t - g_kpress) / 1000000ull), st->ok);++ } else if (g_kstate == KS_OK && script_clock_elapsed(c, g_kpress_clock, g_kpress_server) >= OK_WAIT_TICKS) {++ if (g_ktries >= 3) die("[RED] hid script step %d: no confirm '%s' after 3 presses (waited %llu server ticks, wall clock %llu ms)", g_kcur + 1, st->ok,++ (unsigned long long)script_clock_elapsed(c, g_kpress_clock, g_kpress_server), (unsigned long long)((t - g_kpress) / 1000000ull));++ LOG("hid script step %d waiting for confirm: %llu server ticks, wall clock %llu ms; pressing again (press %d)", g_kcur + 1,++ (unsigned long long)script_clock_elapsed(c, g_kpress_clock, g_kpress_server), (unsigned long long)((t - g_kpress) / 1000000ull), g_ktries + 1);++ g_kstate = KS_HOLD; g_kpress = t; g_kpress_clock = c.value; g_kpress_server = c.server; g_krel = 0; g_kbeg = g_kend = 0; g_ktries++;++ if (st->mask & PK_TOUCH) { dm_touch p = {0, st->tx, st->ty}; dm_touch_set(&p, 1); }++ if (st->mask & PK_MSG) dm_ui_send_queue(st->msg);++ if (st->mask & PK_CLICK) dm_ui_touch(0, st->tx, st->ty);++ LOG("hid script step %d pressed again (press %d)", g_kcur + 1, g_ktries);++ }++ if (g_kstate == KS_HOLD) {++ uint64_t held = script_clock_elapsed(c, g_kpress_clock, g_kpress_server);++ if (held < step_hold_units(st, c.server)) m = st->mask & ~(PK_TOUCH | PK_MSG | PK_CLICK);++ else if (st->ok[0]) { LOG("hid script step %d released (server tick %llu, held %llu ticks)", g_kcur + 1, (unsigned long long)c.value, (unsigned long long)held); g_krel = 1; g_kstate = KS_OK; if (st->mask & PK_TOUCH) dm_touch_set(NULL, 0); if (st->mask & PK_CLICK) dm_ui_touch(2, st->tx, st->ty); }++ else { // no confirm item: done on release++ LOG("hid script step %d released (clock %llu, held %llu ticks)", g_kcur + 1, (unsigned long long)c.value, (unsigned long long)held); g_krel = 1; if (st->mask & PK_TOUCH) dm_touch_set(NULL, 0); if (st->mask & PK_CLICK) dm_ui_touch(2, st->tx, st->ty);++ g_kcur++; g_kstate = KS_PRE; g_ktries = 0; step_chain();++ }++ }++ }++ pthread_mutex_unlock(&g_klock);++ return m;++}++static void keys_parse(void) {++ g_nkeys = 0; g_kbase = now_ns();++ cursor_tests_parse();++ const char *e = getenv("DM_KEYS"); if (!e) e = "";++ char buf[4096]; strncpy(buf, e, sizeof buf - 1); buf[sizeof buf - 1] = 0;++ for (char *save, *tok = strtok_r(buf, ",", &save); tok; tok = strtok_r(NULL, ",", &save)) {++ char *at = strchr(tok, '@'); if (!at) die("DM_KEYS entry '%s' lacks @time / @message", tok);++ *at = 0;++ uint32_t mask = 0; float tx = 0, ty = 0;++ if (tok[0] == 'T' && ((tok[1] >= '0' && tok[1] <= '9') || tok[1] == '.')) { // touch point: T<x>:<y> (normalized coordinates of the rendered picture [0,1), origin at top left)++ char *c = strchr(tok, ':'); if (!c) die("DM_KEYS touch entry '%s' format: T<x>:<y>@pre…", tok);++ tx = (float)atof(tok + 1); ty = (float)atof(c + 1); mask = PK_TOUCH;++ }++ if (tok[0] == 'C' && ((tok[1] >= '0' && tok[1] <= '9') || tok[1] == '.')) { // UI click: C<x>:<y> (normalized coordinates of the rendered picture), dm_ui_touch is sent once each for press / release++ char *c = strchr(tok, ':'); if (!c) die("DM_KEYS click entry '%s' format: C<x>:<y>@pre…", tok);++ tx = (float)atof(tok + 1); ty = (float)atof(c + 1); mask = PK_CLICK;++ }++ const char *msg = NULL; // step that sends a UI message: MSG:<category>:<action>[:<argument>]@pre[>confirm] -- presses no key, at the due time sends this message to the UI root widget (after the character select page was switched to the keyboard-and-mouse UI the controller confirm key can no longer enter a run, so the last step of test run entry sends MainMenuHD:Play instead)++ if (!strncmp(tok, "MSG:", 4)) { if (!strchr(tok + 4, ':') || strlen(tok + 4) >= sizeof g_steps[0].msg) die("DM_KEYS message entry '%s' format: MSG:<category>:<action>[:<argument>]@pre[>confirm]", tok); msg = tok + 4; mask = PK_MSG; }++ for (int i = 0; i < (int)(sizeof k_names / sizeof *k_names); i++) if (!strcmp(tok, k_names[i].name)) mask = k_names[i].mask;++ for (int i = 0; i < 4; i++) if (!strcmp(tok, k_stick[i].name)) mask = k_stick[i].mask;++ if (!mask) die("DM_KEYS unknown key name '%s'", tok);++ const char *v = at + 1;++ if ((*v >= '0' && *v <= '9') || *v == '.') {++ if (mask & (PK_TOUCH | PK_MSG | PK_CLICK)) die("DM_KEYS touch / message entries only support UI-message steps (…@pre…), not timed ones");++ char *plus = strchr(v, '+');++ double t = atof(v), d = plus ? atof(plus + 1) : 0.2;++ if (g_nkeys == KMAX) die("DM_KEYS has more than %d entries", KMAX);++ g_keys[g_nkeys++] = (typeof(g_keys[0])){mask, (uint64_t)(t * 1e9), (uint64_t)((t + d) * 1e9)};++ } else {++ if (g_nsteps == KMAX) die("DM_KEYS has more than %d entries", KMAX);++ typeof(g_steps[0]) *st = &g_steps[g_nsteps++]; st->mask = mask; st->tx = tx; st->ty = ty; st->msg[0] = 0; if (msg) strcpy(st->msg, msg);++ const char *gt = strchr(v, '>');++ size_t np = gt ? (size_t)(gt - v) : strlen(v);++ if (np >= sizeof st->pre || (gt && (!gt[1] || strlen(gt + 1) >= sizeof st->ok))) die("DM_KEYS message step '%s' format: key@pre[%%delay seconds][+hold seconds][>confirm]", v);++ memcpy(st->pre, v, np); st->pre[np] = 0;++ char *pp = strchr(st->pre, '+'); if (pp) { st->hold_override = 1; st->hold_seconds = atof(pp + 1); *pp = 0; } // pre+hold seconds → 25 ticks/s in a run, 60 presented frames/s in the main menu; less than 1 unit cannot be sampled++ char *pc = strchr(st->pre, '%'); if (pc) { st->delay_seconds = atof(pc + 1); *pc = 0; } // pre%seconds → 25 ticks/s in a run, 60 presented frames/s in the main menu++ if (gt) strcpy(st->ok, gt + 1);++ }++ }++ if (g_nsteps || g_ncursor_tests) { g_steps[0].seen_pre = 0; if (g_nsteps && !g_steps[0].pre[0]) { script_clock c = script_clock_now(); g_steps[0].seen_pre = 1; g_steps[0].seen_at = now_ns(); g_steps[0].seen_clock = c.value; g_steps[0].seen_server = c.server; } void uimsg_subscribe(void (*)(const char *, const char *, const char *)); uimsg_subscribe(keys_on_uimsg); }++ LOG("hid script input: %d timed entries, %d UI-message steps", g_nkeys, g_nsteps);++}++static pthread_once_t g_kone = PTHREAD_ONCE_INIT;++void hid_keys_init(void) { pthread_once(&g_kone, keys_parse); }++static uint64_t keys_now(void) {++ pthread_once(&g_kone, keys_parse);++ uint64_t t = now_ns() - g_kbase, m = steps_now();++ for (int i = 0; i < g_nkeys; i++) if (t >= g_keys[i].t0 && t < g_keys[i].t1) m |= g_keys[i].mask;++ static _Atomic uint64_t seen; // print one line the first time each key is really read by the game (proves the injection arrived)++ uint64_t newbits = m & ~atomic_fetch_or(&seen, m);++ if (newbits) LOG("hid script keys read for the first time: mask=%#llx @%.2fs", newbits, t / 1e9);++ return m;++}++++// Optional sampling of actual GetNpadState returns; state changes + an activity witness at most once per second, a change in sampling alone does not flood the log.++// After 1024 entries limit_reached is stated explicitly, a truncated log does not count as complete gesture evidence; without the environment variable no file is written.++static FILE *g_receipt_file;++static pthread_once_t g_receipt_once = PTHREAD_ONCE_INIT;++static pthread_mutex_t g_receipt_lock = PTHREAD_MUTEX_INITIALIZER;++static void receipt_init(void) {++ const char *path = getenv("DM_HID_RECEIPT_LOG");++ if (path && *path) {++ g_receipt_file = fopen(path, "w");++ if (!g_receipt_file) LOG("[RED] HID receipt log file failed to open: %s", path);++ }++}++static void receipt(const NpadState *s, uint32_t id, uint32_t style, uint64_t km, uint64_t read_start_ns) {++ if (!g_receipt_file) return;++ static NpadState last; static uint32_t last_id, last_style;++ static uint64_t last_km, last_ns; static unsigned count; static int have, truncated;++ NpadState state = *s; state.sampling = 0; uint64_t t = now_ns();++ pthread_mutex_lock(&g_receipt_lock);++ if (truncated || (have && id == last_id && style == last_style && km == last_km && !memcmp(&state, &last, sizeof state) && t - last_ns < 1000000000ull)) {++ pthread_mutex_unlock(&g_receipt_lock); return;++ }++ if (count == 1024) {++ fprintf(g_receipt_file, "{\"event\":\"limit_reached\",\"limit\":1024}\n"); truncated = 1;++ } else {++ fprintf(g_receipt_file, "{\"event\":\"npad_return\",\"read_start_ns\":%llu,\"time_ns\":%llu,\"sampling\":%lld,\"id\":%u,\"style\":%u,\"buttons\":%llu,\"lx\":%d,\"ly\":%d,\"rx\":%d,\"ry\":%d,\"attributes\":%u,\"script_mask\":%llu}\n",++ (unsigned long long)read_start_ns, (unsigned long long)t, (long long)s->sampling, id, style, (unsigned long long)s->buttons,++ s->lx, s->ly, s->rx, s->ry, s->attributes, (unsigned long long)km);++ last = state; last_id = id; last_style = style; last_km = km; last_ns = t; have = 1; count++;++ }++ if (fflush(g_receipt_file)) { LOG("[RED] HID receipt log write failed"); truncated = 1; }++ pthread_mutex_unlock(&g_receipt_lock);++}++++void (*dm_pad_hook)(uint64_t, uint64_t *, int32_t *, int32_t *, int32_t *, int32_t *);++static void fill(NpadState *s, uint32_t id, uint32_t style) {++ pthread_once(&g_receipt_once, receipt_init);++ ui_taps_step();++ dm_ui_frontend_pump();++ { void dm_textinput_pump(void); dm_textinput_pump(); } // the extra "bring up keyboard" press for text boxes, setting the value of quantity boxes (dm_textinput.c)++ { void dm_update_pump(void); dm_update_pump(); } // build number and new-version notice on the character select page (dm_update.c)++ { void dm_actions_pump(void); dm_actions_pump(); } // vendor buy/sell / stat point entry and readout (dm_actions.c)++ { void dm_world_pump(void); dm_world_pump(); } // tapping a world target = interact (dm_world.c)++ dm_ui_mouse_pump(); // UI mouse messages (native clicks) are sent at the controller read: main thread, one per frame++ { void dm_aim_cone_pump(void); dm_aim_cone_pump(); } // target selection by finger direction: restored when the right stick returns to zero (hle_private_aim.c)++ if (atomic_load(&g_stall_due) && atomic_exchange(&g_stall_due, 0)) usleep((useconds_t)g_stall_ms * 1000); // DM_TEST_HID_STALL_MS++ uint64_t read_start_ns = g_receipt_file ? now_ns() : 0; // covers the whole read interval of the multi-atomic fields++ memset(s, 0, sizeof *s);++ s->sampling = ++g_sampling;++ if (!(style_of(id) & style)) { receipt(s, id, style, 0, read_start_ns); return; } // this style is not connected: an all-zero return is sampled as well++ uint64_t km = keys_now();++ // Merge the buttons of all channels first (touch / key script / host-pressed + controller; all 0 when no controller is connected), then arbitrate the++ // "exclusive press": the press made on the player's behalf must look at what the game will actually receive this time,++ // not at one single channel (previously only the touch channel was checked, so a controller player pressing + to open the inventory in the first 1.5++ // seconds after joining would still turn the exclusive L into a tab switch)++ { uint64_t dm_ui_alone_take(uint64_t);++ uint64_t tb = ((g_in.buttons | atomic_load(&g_press_latch)) & ~dm_ui_auto_release()) | (km & ~(uint64_t)PK_MASK) | dm_ui_auto_buttons(), pb = atomic_load(&g_pad_btn) | atomic_load(&g_pad_latch);++ static int t_old = -1; if (t_old < 0) t_old = getenv("DM_TEST_ALONE_NOPAD") != NULL; // Test control: reproduces the pre-change behavior (the arbitration ignores controller buttons, and controller buttons are still merged in during an exclusive press)++ uint64_t alone = dm_ui_alone_take(t_old ? tb : tb | pb);++ if (alone) s->buttons = t_old ? alone | atomic_load(&g_pad_btn) | atomic_exchange(&g_pad_latch, 0) : alone; // The exclusive press (dm_cursor.c): other buttons are withheld for these few frames, neither press-edge latch is cleared, and they are delivered as usual afterwards++ else s->buttons = ((g_in.buttons | atomic_exchange(&g_press_latch, 0)) & ~dm_ui_auto_release()) | (km & ~(uint64_t)PK_MASK) | dm_ui_auto_buttons() | atomic_load(&g_pad_btn) | atomic_exchange(&g_pad_latch, 0); }++ s->lx = g_in.lx; s->ly = g_in.ly; s->rx = g_in.rx; s->ry = g_in.ry;++ // Sticks: if the touch stick has a value use it, otherwise use the controller's. The controller side only gives a non-zero value in controller mode and when the++ // stick has actually been pushed out (dm_gamepad.m), so a slightly drifting controller left lying aside never reaches here++ { uint64_t ax = atomic_load(&g_pad_axes); int16_t plx = (int16_t)ax, ply = (int16_t)(ax >> 16), prx = (int16_t)(ax >> 32), pry = (int16_t)(ax >> 48);++ if (!(s->lx || s->ly) && (plx || ply)) { s->lx = plx; s->ly = ply; } if (!(s->rx || s->ry) && (prx || pry)) { s->rx = prx; s->ry = pry; } }++ { int dm_padmode_input_gate(uint64_t *); if (dm_padmode_input_gate(&s->buttons)) s->lx = s->ly = s->rx = s->ry = 0; } // Controller / touch switch transaction in progress: neither keys nor sticks are handed to the game; keys held when the switch was triggered are not handed over either until released (dm_padmode.c)++ if (dm_pad_hook) dm_pad_hook(guest_ns(), &s->buttons, &s->lx, &s->ly, &s->rx, &s->ry);++ { uint64_t dm_runeword_pad_filter(uint64_t); s->buttons = dm_runeword_pad_filter(s->buttons); } // While the runeword list is open in controller mode, the D-pad / A / B / L / R belong to the list (dm_runeword.c)++ { uint64_t dm_padmode_page_filter(uint64_t); s->buttons = dm_padmode_page_filter(s->buttons); } // While one of our own pages (the Custom page etc.) is open in controller mode, the buttons the page declares belong to the page (dm_padmode.c)++ { uint64_t dm_swapskill_filter(uint64_t); s->buttons = dm_swapskill_filter(s->buttons); } // off-hand set skill: hold that key back until the weapon swap is done (dm_actions.c)++ { static int trx, tryy, tdelay, held, tset = -1; if (tset < 0) { const char *e = getenv("DM_TEST_RSTICK"); tset = e && sscanf(e, "%d,%d,%d", &trx, &tryy, &tdelay) >= 2; } // test switch DM_TEST_RSTICK=rx,ry[,delay count]: while the key script holds A / B / X / Y, set the right stick to this value (simulates "hold a skill button and drag", the game itself also sees the right stick); delay = on which controller read after the press it starts being given (a real finger presses first, then drags out a direction)++ if (tset > 0) { held = (s->buttons & 0xf) ? held + 1 : 0; if (held > tdelay) { s->rx = trx; s->ry = tryy; } } }++ if (s->lx || s->ly || (km & PK_MASK & ~(uint64_t)PK_TOUCH)) atomic_store(&g_stick_ns, now_ns()); // the last time the player's stick (front end / script pseudo-keys) was non-zero; a stick rewritten by the cursor does not count++ dm_cursor_apply(&s->buttons, &s->lx, &s->ly); // pointer target: within this sample, rewrite the left stick / A according to the original game's cursor position (see dm_cursor.h)++ { static uint64_t prev; if ((s->buttons & DM_BTN_L) && !(prev & DM_BTN_L)) { int n = atomic_fetch_add(&g_dm_l_presses, 1) + 1; if (n <= 3) LOG("controller read: the 'Show Items' key (L) was delivered to the game, time %d in this process", n); } prev = s->buttons; } // number of presses of the "Show Items" key (L) delivered to the game (used by the boss drop readout, dm_bossrush.c)++ if (km & PK_LSL) s->lx = -32767; if (km & PK_LSR) s->lx = 32767; // script stick pseudo-keys: push to full (Horizon stick ±32767, up is positive)++ if (km & PK_LSU) s->ly = 32767; if (km & PK_LSD) s->ly = -32767;++ s->attributes = ATTR_CONNECTED;++ atomic_store_explicit(&g_sampled_right,(uint32_t)s->rx|((uint64_t)(uint32_t)s->ry<<32),memory_order_release);++ receipt(s, id, style, km, read_start_ns);++}++++HLE_FORCE("_ZN2nn3hid14InitializeNpadEv", "connect to the hid service; the host takes input from dm_input", void, h_hid_InitNpad, void) {}++HLE_FORCE("_ZN2nn3hid21InitializeTouchScreenEv", "connect to the hid service; touch input is wired separately by the front end", void, h_hid_InitTouch, void) {}++HLE_FORCE("_ZN2nn3hid22SetSupportedNpadIdTypeEPKjm", "supported controller ids; fixed by the host", void, h_hid_SetIds, const uint32_t *ids, uint64_t n) { (void)ids; (void)n; }++// BitFlagSet<32> is passed by value in a w register++HLE_FORCE("_ZN2nn3hid24SetSupportedNpadStyleSetENS_4util10BitFlagSetILi32ENS0_12NpadStyleTagEEE", "supported controller styles; fixed by the host", void, h_hid_SetStyles, uint32_t styles) { (void)styles; }++HLE_FORCE("_ZN2nn3hid29SetNpadHandheldActivationModeENS0_26NpadHandheldActivationModeE", "handheld controller activation mode; fixed by the host", void, h_hid_SetHhMode, int m) { (void)m; }++HLE_FORCE("_ZN2nn3hid15GetNpadStyleSetERKj", "controller style query; follows DM_OPMODE", uint32_t, h_hid_GetStyle, const uint32_t *id) { return style_of(*id); }++HLE_FORCE("_ZN2nn3hid12GetNpadStateEPNS0_16NpadFullKeyStateERKj", "full-key controller state; from dm_input", void, h_hid_GetFullKey, NpadState *s, const uint32_t *id) { fill(s, *id, STYLE_FULLKEY); }++HLE_FORCE("_ZN2nn3hid12GetNpadStateEPNS0_17NpadHandheldStateERKj", "handheld controller state; from dm_input", void, h_hid_GetHandheld, NpadState *s, const uint32_t *id) { fill(s, *id, STYLE_HANDHELD); }++++// Vibration: device count 0, the game will not initialize / send any further++HLE_FORCE("_ZN2nn3hid20IsVibrationPermittedEv", "vibration permission; not supported by the host (returns bool)", unsigned, h_hid_VibPermit, void) { return 0; }++HLE_FORCE("_ZN2nn3hid25GetVibrationDeviceHandlesEPNS0_21VibrationDeviceHandleEiRKjNS_4util10BitFlagSetILi32ENS0_12NpadStyleTagEEE",++ "vibration devices; 0 on the host", int, h_hid_GetVibHandles, void *out, int max, const uint32_t *id, uint32_t style) { (void)out; (void)max; (void)id; (void)style; return 0; }++HLE_FORCE("_ZN2nn3hid25InitializeVibrationDeviceERKNS0_21VibrationDeviceHandleE", "vibration; not supported by the host", void, h_hid_InitVib, const void *h) { (void)h; }++HLE_FORCE("_ZN2nn3hid18SendVibrationValueERKNS0_21VibrationDeviceHandleERKNS0_14VibrationValueE", "vibration; not supported by the host", void, h_hid_SendVib, const void *h, const void *v) { (void)h; (void)v; }++++// Touchscreen: nn::hid::TouchScreenState<16> = { int64 sampling; int32 count; int32 _r; TouchState touches[16] (0x28 each) }++// Contents are filled by hle_touch.c from the touch points pushed by the front end (see that file for the layout and the short-press latch); the game only looks at entry 0, returns the number of states written, 1++typedef struct { int64_t sampling; int32_t count, _r; uint8_t touches[16][0x28]; } TouchState16;++_Static_assert(sizeof(TouchState16) == 0x290, "TouchScreenState<16>");++int touch_fill(void *out, uint64_t now_ns);++HLE_FORCE("_ZN2nn3hid20GetTouchScreenStatesILm16EEEiPNS0_16TouchScreenStateIXT_EEEi", "touch screen states: front-end touch points (hle_touch.c)", int, h_hid_GetTouch, TouchState16 *out, int n) {++ if (n < 1) return 0;++ touch_fill(out, guest_ns());++ return 1;++}diff --git a/patches/0022-fork-patches-stamp.patch b/patches/0022-fork-patches-stamp.patchnew file mode 100644index 00000000..7d39776b--- /dev/null+++ b/patches/0022-fork-patches-stamp.patch@@ -0,0 +1,119 @@+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001+From: v0lumehi <[email protected]>+Date: Wed, 28 Oct 2026 13:34:47 +0100+Subject: [PATCH] Builds record the fork's patches: DMForkPatches in Info.plist+ and the first line of the log++dm/fork_patches.txt (one patch name per line, written by scripts/patches.py from the series) is stamped into+the iOS app's Info.plist (project.yml, build_ipa.sh) and the Mac app's (pack_app.py). The iOS host writes+"fork patches: <names>" as the first line of Documents/log.txt, the Mac launcher as the first line of its log.+A report from such a build says which patches it carried, so one from a configuration upstream does not+support goes to the fork, not to seedds/nxnative.++Upstream-Status: fork-only+Reason: Route bug reports: a build beyond upstream's support matrix names the patches it carries+Issue: LNPANDY/NX2Apple#123+---+ dm/ios/Sources/main.m | 3 ++++ dm/ios/project.yml | 1 ++ dm/ios/tools/build_ipa.sh | 1 ++ dm/ios/tools/build_smoke.py | 2 +-+ dm/mac/launcher.c | 2 +++ dm/mac/pack_app.py | 9 ++++++++-+ 6 files changed, 16 insertions(+), 2 deletions(-)++diff --git a/dm/ios/Sources/main.m b/dm/ios/Sources/main.m+index b546e1bf..6c14a37d 100644+--- a/dm/ios/Sources/main.m++++ b/dm/ios/Sources/main.m+@@ -151,6 +151,9 @@ static int boot_env(void) {+ NSString *log = [doc stringByAppendingPathComponent:@"log.txt"], *prev = [doc stringByAppendingPathComponent:@"log.prev.txt"];+ [fm removeItemAtPath:prev error:nil]; [fm moveItemAtPath:log toPath:prev error:nil];+ if (freopen(log.fileSystemRepresentation, "w", stderr)) setvbuf(stderr, NULL, _IOLBF, 0);++ // First line of the log: the fork's patches this build carries (Info.plist DMForkPatches), so a report says whether it comes from a build beyond upstream's support++ NSString *fork_patches = [NSBundle.mainBundle objectForInfoDictionaryKey:@"DMForkPatches"];++ fprintf(stderr, "fork patches: %s\n", [fork_patches isKindOfClass:NSString.class] && fork_patches.length ? fork_patches.UTF8String : "none");+ // Environment switch files (for on-device diagnostics: a sideloaded app cannot be given environment variables from outside): one KEY=VALUE per line, # starts a comment; Documents/env.txt takes precedence over dm/env.txt in the bundle (put there by build_ipa.sh's DM_ENV_FILE)+ NSMutableArray<NSString *> *from_file = [NSMutableArray array];+ for (NSString *ef in @[[doc stringByAppendingPathComponent:@"env.txt"], [[res stringByAppendingPathComponent:@"dm"] stringByAppendingPathComponent:@"env.txt"]]) {+diff --git a/dm/ios/project.yml b/dm/ios/project.yml+index 298b2eed..e9d9c174 100644+--- a/dm/ios/project.yml++++ b/dm/ios/project.yml+@@ -44,6 +44,7 @@ targets:+ LSApplicationCategoryType: ${DM_APP_CATEGORY} # game profile app_category+ DMShowFPS: ${DM_SHOW_FPS} # YES = the frame-rate counter is on (front_ios.m; set by build_ipa.sh)+ DMLanguage: ${DM_LANG} # the game language code (main.m sets DM_LANG from it; set by build_ipa.sh)++ DMForkPatches: ${DM_FORK_PATCHES} # the fork's patches this build carries (dm/fork_patches.txt, written by scripts/patches.py; set by build_ipa.sh)+ LSSupportsGameMode: true+ GCSupportsControllerUserInteraction: true # Physical controllers (GameController)+ GCSupportedGameControllers:+diff --git a/dm/ios/tools/build_ipa.sh b/dm/ios/tools/build_ipa.sh+index a9a76b21..c8b30dc0 100755+--- a/dm/ios/tools/build_ipa.sh++++ b/dm/ios/tools/build_ipa.sh+@@ -36,6 +36,7 @@ VNACP=$(dirname "$ROMFS")/control.nacp; [ -f "$VNACP" ] || VNACP=$W/data/v0/cont+ export LC_ALL=C DM_BUNDLE_ID=${DM_BUNDLE_ID:-org.nxnative.$(echo "$GAME" | tr 'A-Z' 'a-z')} DM_DISPLAY_NAME DM_APP_VERSION DM_APP_CATEGORY=$(gp app_category) DM_TEAM_ID=${DM_TEAM_ID:-0000000000} # placeholder identity: unsigned, the install tool replaces it+ if [ "${DM_SHOW_FPS:-0}" = 1 ]; then export DM_SHOW_FPS=YES; else export DM_SHOW_FPS=NO; fi+ export DM_LANG=${DM_LANG:-en-US}++export DM_FORK_PATCHES=$(paste -sd, "$DM/fork_patches.txt" 2>/dev/null || true) # DMForkPatches in Info.plist (scripts/patches.py writes the list; empty on a build without fork patches)+ if [ "$PREPARE_XCODE" = YES ]; then+ IOS=${DM_XCODE_PROJECT_DIR:-$W/xcode}+ mkdir -p "$IOS" || die "mkdir $IOS"+diff --git a/dm/ios/tools/build_smoke.py b/dm/ios/tools/build_smoke.py+index aa5732a8..2e94b2e7 100644+--- a/dm/ios/tools/build_smoke.py++++ b/dm/ios/tools/build_smoke.py+@@ -55,7 +55,7 @@ def main():+ DM_BUNDLE_ID='org.nxnative.ci', DM_DISPLAY_NAME='CI build fixture',+ DM_APP_VERSION='1.0', DM_APP_CATEGORY=profile.get('app_category'),+ DM_TEAM_ID='', DM_SCHEME_NAME='DmIOS', DM_APPICON='',+- DM_SHOW_FPS='NO', DM_LANG='en-US')++ DM_SHOW_FPS='NO', DM_LANG='en-US', DM_FORK_PATCHES='')++ def run(*command, capture=False):+ return subprocess.run([str(c) for c in command], cwd=project, env=env,+diff --git a/dm/mac/launcher.c b/dm/mac/launcher.c+index 3873b7ad..ce65e8ae 100644+--- a/dm/mac/launcher.c++++ b/dm/mac/launcher.c+@@ -119,6 +119,7 @@ int main(void) {+ snprintf(dm, sizeof dm, "%s/dm", res); snprintf(romfs, sizeof romfs, "%s/romfs", res);+ char name[256] = "nxnative", id[64] = "", marker[512] = "", lang[32] = "";+ if (!info_string("CFBundleName", name, sizeof name)) snprintf(name, sizeof name, "nxnative");++ char fork_patches[1024] = ""; info_string("DMForkPatches", fork_patches, sizeof fork_patches);+ info_string("DMRomfsMarker", marker, sizeof marker); info_string("DMLanguage", lang, sizeof lang);+ if (!info_string("DMTitleID", id, sizeof id) || strchr(id, '/')) { alert(name, "This app has no title ID in its Info.plist (DMTitleID): pack it again with build_ipa_from_nsp.py --platform mac-app."); return 1; }+ struct stat st; snprintf(p, sizeof p, "%s/romfs.img", res);+@@ -190,6 +191,7 @@ int main(void) {+ rename(log, prev);+ int fd = open(log, O_WRONLY | O_CREAT | O_TRUNC, 0644);+ if (fd >= 0) { dup2(fd, 1); dup2(fd, 2); close(fd); setvbuf(stdout, NULL, _IOLBF, 0); }++ fprintf(stderr, "fork patches: %s\n", *fork_patches ? fork_patches : "none"); // first line of the log (Info.plist DMForkPatches)+ fprintf(stderr, "launcher: %s (%s), host %s\n", name, id, host);+ snprintf(p, sizeof p, "%s/env.txt", sup); env_file(p);+ snprintf(p, sizeof p, "%s/env.txt", dm); env_file(p);+diff --git a/dm/mac/pack_app.py b/dm/mac/pack_app.py+index bdf61634..7e82c8f2 100755+--- a/dm/mac/pack_app.py++++ b/dm/mac/pack_app.py+@@ -91,11 +91,18 @@ def make_icns(jpg, out): # the game's icon (256x256 JPEG) at every size an .ic+ run(['iconutil', '-c', 'icns', s, '-o', out])++++def fork_patches():++ """The fork's patches this build carries (dm/fork_patches.txt, written by scripts/patches.py), comma-separated: DMForkPatches in Info.plist, and the first line of the log"""++ try: return ','.join(l.strip() for l in (Path(__file__).resolve().parents[1] / 'fork_patches.txt').read_text().splitlines() if l.strip())++ except OSError: return ''+++++ def info_plist(a, minos, icon):+ p = {'CFBundleName': a.name, 'CFBundleDisplayName': a.name, 'CFBundleIdentifier': a.bundle_id or f'org.nxnative.{a.title_id.lower()}',+ 'CFBundleVersion': a.version or '1.0', 'CFBundleShortVersionString': a.version or '1.0', 'CFBundlePackageType': 'APPL', 'CFBundleExecutable': EXE,+ 'CFBundleInfoDictionaryVersion': '6.0', 'LSMinimumSystemVersion': minos, 'LSArchitecturePriority': ['arm64'], 'NSHighResolutionCapable': True,+- 'LSApplicationCategoryType': a.category or 'public.app-category.games', 'DMTitleID': a.title_id.upper(), 'DMRomfsMarker': a.marker or '', 'DMLanguage': a.lang or 'en-US'}++ 'LSApplicationCategoryType': a.category or 'public.app-category.games', 'DMTitleID': a.title_id.upper(), 'DMRomfsMarker': a.marker or '', 'DMLanguage': a.lang or 'en-US',++ 'DMForkPatches': fork_patches()}+ if icon: p['CFBundleIconFile'] = 'AppIcon'+ return p+diff --git a/patches/series b/patches/seriesnew file mode 100644index 00000000..2edd25f9--- /dev/null+++ b/patches/series@@ -0,0 +1,23 @@+# Applied in this order onto the commit in ../.upstream-ref with git am -3. See README.md.+0001-runtime-profile.patch+0002-romfsarc.patch+0003-ios-game-data-folder.patch+0004-ios-slim-ipa.patch+0005-ios-entitlements.patch+0006-nsp-dotnet-home.patch+0007-nsp-exfat-appledouble.patch+0008-nsp-early-checks.patch+0009-nsp-chain-changed-note.patch+0010-nsp-work-dir.patch+0011-bc-cpu-decode.patch+0012-mac-keymap.patch+0013-nro-code-start.patch+0014-mac-library-folder.patch+0015-hades2-update-profile.patch+0016-hle-time-adjustable-clock.patch+0017-env-switches-verify.patch+0018-touchpad-geometry.patch+0019-ios-probe.patch+0020-fork-docs.patch+0021-ref-hle-hid-d2r.patch+0022-fork-patches-stamp.patchdiff --git a/scripts/sync_upstream.py b/scripts/sync_upstream.pydeleted file mode 100644index d760185a..00000000--- a/scripts/sync_upstream.py+++ /dev/null@@ -1,2383 +0,0 @@-#!/usr/bin/env python3-"""Sync this fork with upstream seedds/nxnative.--The fork was started as a fresh repository (no shared git history), so GitHub's own-"Sync fork" does not apply. The sync is a mechanical procedure — take upstream's tree,-re-apply the fork's features, verify the result builds — and this script is that-procedure, so a scheduled CI job can run it unattended.--What it does:- 1. diffs the two upstream refs over the vendored paths (dm/ scripts/ docs/ AGENTS.md ref/), and- adds any vendored file upstream has that the fork's tree lacks- 2. applies adds and modifications file by file, and deletions — except the fork's own- files (the RomFS archive layer), which upstream must not delete- 3. re-applies the fork's patches to the files that carry them (PATCHED; one patcher each, in- PATCHERS, with a marker only the fork's code contains); every patch is anchor-based and- idempotent, and one that no longer fits fails the run loudly rather than producing a silently- broken tree. Before any of that, check_unprotected() stops the run when a vendored file the- fork edited by hand (it differs from the last sync base) is in none of OURS, PATCHED and- DROPPED and upstream changes it now: the edit would be lost.- 4. verifies: every .py parses on the Python this fork supports as its floor (3.9),- the iOS build script survives bash -n, the archive reader test passes, and the- macOS host builds for a real profile (skippable with --skip-build)--On success the caller commits and pushes; on failure nothing is written outside the-working tree, so CI can open an issue with the log instead.--Every patcher is also run against the files of a real upstream ref by scripts/tests/test_sync_patchers.py-(CI, and locally with seedds/main fetched), so a patcher that no longer fits, or whose marker upstream's-own text satisfies, fails there before it can stop or silently skip a sync (issue #92).--Usage: sync_upstream.py --old <upstream sha> --new <upstream sha> [--skip-build]- sync_upstream.py --old <last sync base> --check-protection (list unprotected fork edits)-"""-import argparse, json, os, pwd, re, subprocess, sys, shutil, tempfile-from pathlib import Path--REPO = Path(__file__).resolve().parent.parent-VENDORED = ('dm', 'scripts', 'docs', 'AGENTS.md', 'ref')-# The fork's own files, inside vendored paths: upstream deletes and rewrites must not touch them.-OURS = {'dm/host/romfs_arc.c', 'dm/host/romfs_arc.h', 'dm/tools/romfs_arc.py',- 'dm/host/tests/t_romfs_arc.c', 'docs/ROMFS_ARCHIVE.md',- 'dm/games/0100A00019DE0000/game.fork.tsv',- # BC decode for GPUs without BC support (from d2r-mobile's bcdec line; tex_bc_cpu profiles)- 'dm/third_party/bcdec/bcdec.h', 'dm/third_party/bcdec/LICENSE',- 'dm/gfx/tex/nvn_bcdec.c', 'dm/gfx/tex/nvn_bcdec.h',- 'dm/gfx/tex/tests/t_bcdec.c',- # The Mac front end's key and controller button map (seedds/nxnative#386, still open):- # the launcher's Controls page writes DM_KEYMAP / DM_PAD_MAP, and patch_front_mac() makes- # front_mac.m read them. Fork-only until #386 merges, so a sync must not delete them.- 'dm/host/input_map.h',- 'dm/host/tests/t_input_map.c',- 'dm/host/tests/t_launcher_contract.c', # the write→read contract with the Controls page- # The Increased Memory Limit guide the README links to; upstream has no such file, and the- # first wholesale sync deleted it.- 'dm/ios/ENTITLEMENTS.md',- # This script: fork-only, so a PR that changes it is not a vendored edit (pr-scope reads OURS)- 'scripts/sync_upstream.py', 'scripts/tests/test_sync_patchers.py', # and its test (issue #92)- # The Files-app game-data pick (bookmark of the chosen folder): fork-only, upstream has no such path- 'dm/ios/Sources/DataBookmark.m', 'dm/ios/Sources/DataBookmark.h',- # The fork's own planning, probe and release documents, and the badges their READMEs read:- # fork-only files upstream has no such path for (checked against seedds main 062cd06e), so- # a PR editing them is not an unprotected vendored edit.- 'docs/ROADMAP.md', 'docs/WORK-IN-PROGRESS.md', 'docs/launcher-c-design.md',- 'docs/probe-dlopen.md', 'docs/RELEASE_NOTES.md',- 'docs/RELEASE-NOTES-GUIDE.md', 'docs/badges/games.json', 'docs/badges/verified.json'}-# Vendored files that carry fork patches: taken fresh from upstream, then patched below.-PATCHED = ('dm/host/hle_fs.c', 'dm/host/Makefile', 'dm/host/tests/Makefile', 'dm/ios/tools/build_ipa.sh',- 'scripts/build_ipa_from_nsp.py',- 'dm/ios/Sources/main.m', 'dm/gfx/nvn/nvn_mtl.m', 'dm/host/dm.h',- 'dm/ios/tests/test_romfs_startup.py', 'dm/ios/tests/test_profile_pack.py', 'dm/ios/tests/test_ipa_unsigned.py', 'docs/env_switches.tsv', 'dm/host/front_mac.m', 'dm/games/0100A00019DE0000/game.tsv',- # hand edits until issue #92, now patchers (see "Fork edits that had no protection" below)- 'dm/mac/launcher.c',- 'dm/host/hle_svc.c',- 'dm/host/hle_os.c',- 'dm/host/hle_fpslock.c',- 'dm/host/loader.c',- 'dm/ios/Sources/DmGamepad.m',- 'dm/ios/Sources/Launcher.swift',- 'dm/ios/Sources/front_ios.m',- 'dm/ios/project.yml',- 'dm/ios/tests/test_xcode_workflow.py',- 'dm/tools/env_switches.py',- 'dm/tools/tests/test_env_switches.py',- 'dm/tools/impact_map.tsv', 'dm/games/game.py',- 'dm/games/0100F2C0115B6000/game.tsv',- 'docs/agents/README.md',- 'docs/development.md')--def git(*a):- r = subprocess.run(['git', *a], cwd=REPO, capture_output=True, text=True)- if r.returncode: sys.exit(f'git {" ".join(a)} failed: {r.stderr.strip()}')- return r.stdout--def blob(rev, path):- r = subprocess.run(['git', 'cat-file', 'blob', f'{rev}:{path}'], cwd=REPO, capture_output=True)- return r.stdout if r.returncode == 0 else None--def upstream_changes(old, new):- """(kind, path) for every vendored file that differs, kind in AM D; plus an A for every vendored- file upstream has that the fork's tree lacks, and an M for an upstream executable that lost its x bit here. The diff alone only sees files that changed between- the two refs, so a file the first sync missed never arrived: docs/geometry-metal-research.md (which- game notes link to) and 34 of docs/images, until test_docs.py found the dead links."""- out = git('diff', '--name-status', old, new, '--', *VENDORED).splitlines()- changes = []- for line in out:- parts = line.split('\t')- kind, path = parts[0][0], parts[-1]- if path in OURS and REPO.joinpath(path).exists() and kind != 'D':- # A file the fork owns that upstream now also carries — often under the same name for- # the same purpose, as test_nro_header.py (seedds 337186cf's own test for the NRO- # bound, the fork's being its own since issue #14). The fork's copy is the authority:- # the sync keeps it and skips upstream's row instead of failing in apply_changes. A- # deletion stays in changes, so the D branch can still refuse to remove an OURS file.- say(f' = {path}: upstream has its own now; the fork keeps its copy (OURS)')- continue- changes.append((kind, path))- named = {p for _, p in changes}- for line in git('ls-tree', '-r', new, '--', *VENDORED).splitlines():- meta, path = line.split('\t', 1)- if path in named or path in OURS: continue- dest = REPO / path- if not dest.exists(): changes.append(('A', path))- elif meta.split()[0] == '100755' and not os.access(dest, os.X_OK): changes.append(('M', path)) # an executable that lost its x bit- return changes--# ---- the fork's patches. Each is (name, already-marker, [(old, new), ...]); a patch whose-# marker is present is skipped, one whose old text is absent fails the run. ------HLE = 'dm/host/hle_fs.c'-def patch_hle_fs(t):- P = []- P.append(('include', '#include "romfs_arc.h"', [(- '#include "hle.h"\n#include <mach/mach.h>\n#include "front.h"\n',- '#include "hle.h"\n#include <mach/mach.h>\n#include "front.h"\n#include "romfs_arc.h"\n')]))- P.append(('synthetic path', 'ROMFSARC_SYNTH_PREFIX "%s"', [(- ' if (g_mnt[i].overlay[0] && !create) return rom_overlay_path(&g_mnt[i], rest, out, n);',- ''' if (g_mnt[i].overlay[0] && !create) return rom_overlay_path(&g_mnt[i], rest, out, n);- // Archive mount: the RomFS tree lives inside a ROMFSARC archive, so the host path is a- // synthetic "@romfsarc:<guest path>" that the file calls below route to romfs_arc.c. Matched- // by the mount directory (romfsarc_open recorded the base it actually opened), because the- // mount name differs between games (rom, content).- if (romfsarc_active() && g_mnt[i].ro && !create && g_mnt[i].dir[0] && !strcmp(g_mnt[i].dir, g_arc_base)) {- // Fold runs of '/' the way the directory walk below does: the archive index stores one- // separator per level, and a game may ask for "data:/bin/appli/icon_sick//bin/x.arc"- // (Pokemon Sword's Bag: the doubled slash missed the lookup and the game then- // dereferenced the null it got back — PR #9).- char folded[1024]; const char *r = rest;- if (strstr(rest, "//")) {- size_t o = 0; int slash = 0;- for (const char *q = rest; *q; q++) {- if (*q == '/') { if (slash) continue; slash = 1; } else slash = 0;- if (o + 1 >= sizeof folded) { errno = ENAMETOOLONG; return 0; }- folded[o++] = *q;- }- folded[o] = 0; r = folded;- }- if (snprintf(out, n, ROMFSARC_SYNTH_PREFIX "%s", r) >= (int)n) { errno = ENAMETOOLONG; return 0; }- return 1;- }''')]))- P.append(('MountRom', 'romfsarc_open(dir, &h)', [(- '''HLE_FORCE("_ZN2nn2fs8MountRomEPKcPvm", "fsp-srv; rom → host RomFS directory", Result, h_fs_MountRom, const char *name, void *cache, size_t sz) {- (void)cache; (void)sz; char b[1024];- Result r = mount(name, envdir("DM_ROMFS", "romfs", b, sizeof b), 1);''',- '''HLE_FORCE("_ZN2nn2fs8MountRomEPKcPvm", "fsp-srv; rom → host RomFS directory (or a ROMFSARC archive)", Result, h_fs_MountRom, const char *name, void *cache, size_t sz) {- (void)cache; (void)sz; char b[1024];- const char *dir = envdir("DM_ROMFS", "romfs", b, sizeof b);- // Archive mount: romfsarc_open tries <dir>.idx, <dir>/romfs.idx and <dir>/romfs/romfs.idx, so the- // player may copy the shards either beside the folder or into Documents/romfs/ itself.- romfsarc_hdr h;- if (romfsarc_open(dir, &h) == 0) {- // Mount the resolved archive base (romfsarc_open recorded the one that worked in g_arc_base).- // host_path_ex compares the mount directory against it.- Result r = mount(name, g_arc_base, 1);- if (r != RES_OK) { romfsarc_close(); return r; }- LOG("fs rom: archive %s (%llu files, %llu dirs, %u shards, tree hash %016llx)", g_arc_base,- (unsigned long long)h.file_count, (unsigned long long)h.dir_count, h.shard_count, (unsigned long long)h.tree_hash);- return RES_OK;- }- Result r = mount(name, dir, 1);''')]))- P.append(('archive handles', 'static uint64_t arc_new', [(- 'HLE_FORCE("_ZN2nn2fs8OpenFileEPNS0_10FileHandleEPKci", "fsp-srv → open(2)", Result, h_fs_OpenFile, uint64_t *out, const char *path, int mode) {',- '''// ---------- Archive-backed file handles -----------// An archive file has no host fd. It gets a handle number from a private table, and every operation-// on it (ReadFile, GetFileSize, CloseFile) checks the table first. Handle numbers are distinct from-// fds: real handles are fds (>= 3 in practice), archive handles are tagged by index into g_arc[].-// Like every host handle they reach the guest through FH_OUT (shifted left by 4, 16-byte aligned) and come back-// through FH_IN, so the tag sits at bit 57: below IMG_H's bit 58, and it still fits after the shift.-typedef struct { uint32_t shard; uint64_t off, size; int used; } archandle;-#define MAX_ARCH 4096-static archandle g_arc[MAX_ARCH];-static uint64_t g_arch_gen; // bumped on open/close so a stale handle never hits a recycled slot-static uint64_t arc_new(uint32_t shard, uint64_t off, uint64_t size) {- for (int i = 0; i < MAX_ARCH; i++) if (!g_arc[i].used) {- g_arc[i].used = 1; g_arc[i].shard = shard; g_arc[i].off = off; g_arc[i].size = size;- return ((uint64_t)1 << 57) | ((g_arch_gen & 0xffffff) << 32) | (uint32_t)i;- }- return 0;-}-static int arc_get(uint64_t h, archandle **out) {- if ((h >> 57) != 1) return 0;- uint32_t i = (uint32_t)h;- if (i >= MAX_ARCH || !g_arc[i].used) return 0;- if ((uint32_t)((h >> 32) & 0xffffff) != (uint32_t)(g_arch_gen & 0xffffff)) return 0;- *out = &g_arc[i]; return 1;-}-static void arc_free(uint64_t h) {- archandle *a; if (arc_get(h, &a)) a->used = 0;-}-static const char *arc_rel(const char *hp) {- const char *rel = ROMFSARC_SYNTH_REL(hp);- while (*rel == '/') rel++;- return rel;-}-static int arc_file(const char *hp, uint32_t *shard, uint64_t *off, uint64_t *size) {- return romfsarc_stat_file(arc_rel(hp), shard, off, size);-}-static int arc_dir(const char *hp) { return romfsarc_is_dir(arc_rel(hp)); }-static void arc_norm(const char *hp, char *rel, size_t n) { strlcpy(rel, arc_rel(hp), n); }-HLE_FORCE("_ZN2nn2fs8OpenFileEPNS0_10FileHandleEPKci", "fsp-srv → open(2)", Result, h_fs_OpenFile, uint64_t *out, const char *path, int mode) {''')]))- P.append(('OpenFile', 'arc_new(shard, off, size)', [(- ''' HP(path);- if (mode & (MODE_WRITE | MODE_APPEND)) RW();- int fd = open(hp, (mode & (MODE_WRITE | MODE_APPEND)) ? ((mode & MODE_READ) ? O_RDWR : O_WRONLY) : O_RDONLY);''',- ''' HP(path);- if (mode & (MODE_WRITE | MODE_APPEND)) RW();- if (ROMFSARC_IS_SYNTH(hp)) { // archive entry: no fd, the handle carries shard/offset/size- uint32_t shard; uint64_t off, size;- if (!arc_file(hp, &shard, &off, &size)) { errno = ENOENT; return err_res("open", hp); }- uint64_t ah = arc_new(shard, off, size);- if (!ah) { errno = EMFILE; return err_res("open", hp); }- *out = FH_OUT(ah);- if (g_flag.fs) LOG("fs open %s mode=%d → archive handle (shard %u off %llu size %llu)", path, mode, shard, (unsigned long long)off, (unsigned long long)size);- return RES_OK;- }- int fd = open(hp, (mode & (MODE_WRITE | MODE_APPEND)) ? ((mode & MODE_READ) ? O_RDWR : O_WRONLY) : O_RDONLY);''')]))- P.append(('ReadFile', 'romfsarc_pread(ah->shard', [(- ''' size_t got = 0; int reprep = 0, fd = (int)h; int64_t base = 0;- if (IMG_H(h)) { // an image entry: read the image's descriptor at the entry's offset, never past its end- const img_ent *x = &g_mnt[IMG_M(h)].img->e[IMG_K(h)];- fd = g_mnt[IMG_M(h)].img->fd; base = (int64_t)x->a;- sz = off < 0 || (uint64_t)off >= x->b ? 0 : (size_t)(x->b - off) < sz ? (size_t)(x->b - off) : sz;- }- dm_guest_write_prepare(buf, sz); // The destination may be a texture pool page write-protected by the graphics layer: a kernel write to a read-only page returns EFAULT instead of page-faulting, so unprotect and mark dirty first- while (got < sz) {''',- ''' size_t got = 0; int reprep = 0, fd = (int)h; int64_t base = 0;- if (IMG_H(h)) { // an image entry: read the image's descriptor at the entry's offset, never past its end- const img_ent *x = &g_mnt[IMG_M(h)].img->e[IMG_K(h)];- fd = g_mnt[IMG_M(h)].img->fd; base = (int64_t)x->a;- sz = off < 0 || (uint64_t)off >= x->b ? 0 : (size_t)(x->b - off) < sz ? (size_t)(x->b - off) : sz;- }- dm_guest_write_prepare(buf, sz); // The destination may be a texture pool page write-protected by the graphics layer: a kernel write to a read-only page returns EFAULT instead of page-faulting, so unprotect and mark dirty first- archandle *ah;- if (arc_get(h, &ah)) { // archive entry: clamp to the file, read from its shard- if (off < 0) { *out = 0; return RES_FAIL; }- uint64_t avail = (uint64_t)off < ah->size ? ah->size - (uint64_t)off : 0;- size_t want = sz < avail ? sz : (size_t)avail;- if (want) { ssize_t r = romfsarc_pread(ah->shard, ah->off + (uint64_t)off, buf, want);- if (r < 0) return err_res("pread (archive)", "handle"); got = (size_t)r; }- *out = got;- if (g_flag.fs) { static uint64_t n, bytes, next_b = 64 << 20; static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;- pthread_mutex_lock(&m); n++; bytes += got;- if (bytes >= next_b || n % 1000 == 0) { LOG("fs read total: %llu reads %.1f MiB (this one: archive offset %lld length %#zx)", n, bytes / 1048576.0, (long long)off, got); if (bytes >= next_b) next_b += 64 << 20; }- pthread_mutex_unlock(&m); }- return RES_OK;- }- while (got < sz) {''')]))- P.append(('GetFileSize', 'ah->size; return RES_OK', [(- '''HLE_FORCE("_ZN2nn2fs11GetFileSizeEPlNS0_10FileHandleE", "fsp-srv → fstat(2)", Result, h_fs_GetFileSize, int64_t *out, uint64_t h) { h = FH_IN(h);- if (!h) return RES_FAIL;''',- '''HLE_FORCE("_ZN2nn2fs11GetFileSizeEPlNS0_10FileHandleE", "fsp-srv → fstat(2)", Result, h_fs_GetFileSize, int64_t *out, uint64_t h) { h = FH_IN(h);- if (!h) return RES_FAIL;- archandle *ah; if (arc_get(h, &ah)) { *out = (int64_t)ah->size; return RES_OK; }''')]))- P.append(('CloseFile', 'arc_free(h)', [(- '''HLE_FORCE("_ZN2nn2fs9CloseFileENS0_10FileHandleE", "fsp-srv → close(2)", void, h_fs_CloseFile, uint64_t h) { h = FH_IN(h);- if (!h || IMG_H(h)) return; // the null handle after a failed open (see ReadFile): do not touch fd 0; an image entry holds no descriptor''',- '''HLE_FORCE("_ZN2nn2fs9CloseFileENS0_10FileHandleE", "fsp-srv → close(2)", void, h_fs_CloseFile, uint64_t h) { h = FH_IN(h);- if (!h || IMG_H(h)) return; // the null handle after a failed open (see ReadFile): do not touch fd 0; an image entry holds no descriptor- if ((h >> 57) == 1) { arc_free(h); return; } // archive entry: nothing to close''')]))- P.append(('GetEntryType', 'romfsarc_stat_file(rel', [(- '''HLE_FORCE("_ZN2nn2fs12GetEntryTypeEPNS0_18DirectoryEntryTypeEPKc", "fsp-srv → stat(2)", Result, h_fs_GetEntryType, int32_t *out, const char *path) {- int mi; int64_t k;- if (img_path(path, &mi, &k)) { if (k < 0) return err_res("stat", path); *out = g_mnt[mi].img->e[k].type ? ENT_FILE : ENT_DIR; return RES_OK; }- HP(path); struct stat st;''',- '''HLE_FORCE("_ZN2nn2fs12GetEntryTypeEPNS0_18DirectoryEntryTypeEPKc", "fsp-srv → stat(2)", Result, h_fs_GetEntryType, int32_t *out, const char *path) {- int mi; int64_t k;- if (img_path(path, &mi, &k)) { if (k < 0) return err_res("stat", path); *out = g_mnt[mi].img->e[k].type ? ENT_FILE : ENT_DIR; return RES_OK; }- HP(path); struct stat st;- if (ROMFSARC_IS_SYNTH(hp)) { // archive entry or directory, from the index- const char *rel = arc_rel(hp); // the index stores paths without a leading slash (abe35a3)- uint32_t sh; uint64_t of, szf;- if (romfsarc_stat_file(rel, &sh, &of, &szf)) { *out = ENT_FILE; return RES_OK; }- if (romfsarc_is_dir(rel)) { *out = ENT_DIR; return RES_OK; }- errno = ENOENT; return err_res("stat", hp);- }''')]))- # Runtime profile: the save-exists check compares the program id against dm_profile()'s (the- # compiled macro is what dm_profile() falls back to; merged with the stage-2 experiment).- P.append(('save-exists profile', 'dm_profile()->program_id', [(- # both occurrences on the line: the log message and the return value- 'app == DM_GAME_PROGRAM_ID ? "this game, yes" : "another program, no"); return app == DM_GAME_PROGRAM_ID;',- 'app == dm_profile()->program_id ? "this game, yes" : "another program, no"); '- 'return app == dm_profile()->program_id;')]))- P.append(('snapshot helper', 'static void arc_snapshot', [])) # inserted below, needs dirh_t- P.append(('OpenDirectory', 'arc_snapshot(ah, hp)', [(- ''' HP(path); DIR *d = opendir(hp);- if (!d) return err_res("opendir", hp);''',- ''' HP(path);- if (ROMFSARC_IS_SYNTH(hp)) { // archive directory: no host DIR, only the snapshot- if (!arc_dir(hp)) { errno = ENOTDIR; return err_res("opendir", hp); }- dirh_t *ah = calloc(1, sizeof *ah); if (!ah) die("directory handle allocation failed");- strlcpy(ah->path, hp, sizeof ah->path); ah->mode = mode;- arc_snapshot(ah, hp);- *out = (uint64_t)ah; return RES_OK;- }- DIR *d = opendir(hp);- if (!d) return err_res("opendir", hp);''')]))- P.append(('ReadDirectory guard', "an archive directory that turned out empty", [(- ''' int dfd = dirfd(h->d);''',- ''' if (!h->d) { *count = 0; return RES_OK; } // an archive directory that turned out empty (no snapshot, no host DIR)- int dfd = dirfd(h->d);''')]))- P.append(('CloseDirectory guard', 'if (h->d) closedir(h->d)', [(- ''' dirh_t *h = (dirh_t *)hh; closedir(h->d); if (h->od) closedir(h->od); free(h->snap); free(h);''',- ''' dirh_t *h = (dirh_t *)hh; if (h->d) closedir(h->d); if (h->od) closedir(h->od); free(h->snap); free(h);''')]))-- if '#define FH_IN(' not in t:- # before seedds/nxnative#513 the host handle reached the guest as it was; FH_OUT / FH_IN are the identity there, so the- # patches below (written for the shifted handles) apply to both forms. The tag of an archive handle is bit 57 either way.- t = t.replace('#define IMG_K(h) ((uint32_t)(h))\n', '#define IMG_K(h) ((uint32_t)(h))\n#define FH_OUT(h) ((uint64_t)(h))\n#define FH_IN(h) ((uint64_t)(h))\n', 1)- for head in ('h_fs_GetFileSize, int64_t *out, uint64_t h) {', 'h_fs_CloseFile, uint64_t h) {'):- t = t.replace(head, head + ' h = FH_IN(h);', 1)- for name, marker, pairs in P:- if marker in t:- skip(f'hle_fs.c {name} (already patched)'); continue- for old, new in pairs:- if old not in t: fail(f'{HLE}: patch "{name}" anchor missing: {old[:70]!r}')- t = t.replace(old, new, 1)- done(f'hle_fs.c {name}')- # arc_snapshot goes right after the dirh_t typedef: it names the type- if 'static void arc_snapshot' not in t:- import re- m = re.search(r'typedef struct \{ DIR \*d;.*?\} dirh_t;\n', t, re.S)- if not m: fail(f'{HLE}: dirh_t typedef not found')- t = t[:m.end()] + SNAPSHOT + t[m.end():]- done('hle_fs.c arc_snapshot')- return t--SNAPSHOT = '''-// An archive directory has no host DIR: its entries come from the index, copied into the same-// snapshot list the overlay mount uses, so ReadDirectory has one path for both.-static void arc_snapshot(dirh_t *h, const char *hp) {- char rel[1024]; arc_norm(hp, rel, sizeof rel);- int n = romfsarc_count(rel);- if (n <= 0) return;- romfsarc_ent *ents = malloc((size_t)n * sizeof *ents);- if (!ents) die("archive directory snapshot allocation failed");- int got = romfsarc_list(rel, ents, n);- if (got <= 0) { free(ents); return; }- h->snap = calloc((size_t)got, sizeof *h->snap); h->nsnap = got;- if (!h->snap) die("archive directory snapshot allocation failed");- for (int i = 0; i < got; i++) {- strlcpy(h->snap[i].name, ents[i].name, sizeof h->snap[i].name);- h->snap[i].type = ents[i].is_dir ? ENT_DIR : ENT_FILE;- h->snap[i].size = ents[i].is_dir ? 0 : ents[i].size;- }- free(ents);-}-'''--def patch_makefile(t):- if 'romfs_arc.c' in t: return skip('Makefile (already patched)')- # Anchor on the stable SRC prefix: upstream adds and reorders files after hle.c (haptics_apple.m)- old = 'SRC=main.c loader.c hle.c '- if old not in t: fail('dm/host/Makefile: SRC anchor missing (upstream changed the source list)')- return done('Makefile SRC', t.replace(old, 'SRC=main.c loader.c hle.c romfs_arc.c ', 1))--TESTS_MK = 'dm/host/tests/Makefile'-def patch_tests_makefile(t):- """The three fs tests #include ../hle_fs.c, which now calls the archive reader: without- romfs_arc.c on their command lines they stop with undefined _romfsarc_* symbols (PR #12).-- Three independent additions follow (the fs link lines, the touch-pad test, the key map- test), each with its own "already there" test. This used to start with- `if 'romfs_arc.c' in t: return skip(...)`, which made every later addition dead code: the- touch-pad block never ran once the fs lines were in, and the marker check could not notice- its absence. Only the first block skips now.- """- # Upstream spells the compiler `clang` (until ce99604a) or `$(CLANG)` (a variable that adds the- # sanitizer flags; issue #92). Anchors and inserted rules use whichever the file uses, so the- # patcher fits the tree before and after the sync that brings the variable.- CL = r'(?:\$\(CLANG\)|clang)'- cc = '$(CLANG)' if '$(CLANG)' in t else 'clang'- # One spelling per file: a rule upstream added later (t_resolution.c) can carry the other- # spelling than the file's own, and the spelling test then fails on the synced result.- if cc == '$(CLANG)':- t = re.sub(r'(?m)^(\t)clang( -O1\b)', lambda m2: m2.group(1) + cc + m2.group(2), t)- if 'romfs_arc.c' not in t:- P = [- ('t_fs', 'clang -O1 -Wno-unused-function -I.. $(GINC) -o $@ t_fs.c t_fs_stub.c ../hle_bigstack.c\n',- 'clang -O1 -Wno-unused-function -I.. $(GINC) -o $@ t_fs.c t_fs_stub.c ../hle_bigstack.c ../romfs_arc.c\n'),- ('t_fs_commit_list', 'clang -O1 -Wall -Wno-unused-function -I.. $(GINC) -o $@ t_fs_commit_list.c t_fs_stub.c ../hle_bigstack.c\n',- 'clang -O1 -Wall -Wno-unused-function -I.. $(GINC) -o $@ t_fs_commit_list.c t_fs_stub.c ../hle_bigstack.c ../romfs_arc.c\n'),- ('t_fs_case', 'clang -O1 -Wno-unused-function -I.. $(GINC) -o $@ t_fs_case.c ../hle_bigstack.c\n',- 'clang -O1 -Wno-unused-function -I.. $(GINC) -o $@ t_fs_case.c ../hle_bigstack.c ../romfs_arc.c\n'),- ]- for name, old, new in P:- old = old.replace('clang', cc); new = new.replace('clang', cc)- if old not in t: fail(f'{TESTS_MK}: {name} link line missing (upstream changed the test rules)')- t = t.replace(old, new, 1)- done('tests/Makefile romfs_arc.c')- # the touch-pad geometry test (dm/host/touchpad_geometry.h): header-only, so it needs its own- # rule and a place in the run list- if 't_touchpad_geometry' not in t:- run_old = '$(B)/t_haptics $(B)/t_haptics_apple\n'- if run_old not in t: fail(f'{TESTS_MK}: run list anchor missing')- t = t.replace(run_old, '$(B)/t_haptics $(B)/t_haptics_apple $(B)/t_touchpad_geometry\n', 1)- body_old = '\t$(B)/t_haptics_apple\n'- if body_old not in t: fail(f'{TESTS_MK}: run body anchor missing')- t = t.replace(body_old, body_old + '\t$(B)/t_touchpad_geometry\n', 1)- rule_anchor = '$(B)/t_haptics_apple: t_haptics_apple.m'- if rule_anchor not in t: fail(f'{TESTS_MK}: t_haptics_apple rule missing')- t = t.replace(rule_anchor,- '$(B)/t_touchpad_geometry: t_touchpad_geometry.c ../touchpad_geometry.h ../dm_input.h | $(B)\n'- '\t' + cc + ' -O1 -Wall -I.. $(GINC) -o $@ t_touchpad_geometry.c\n' + rule_anchor, 1)- done('tests/Makefile touchpad test')- # the key and controller map test (dm/host/input_map.h, seedds/nxnative#386): header-only too- if 't_input_map' not in t:- run_old = '$(B)/t_hid $(B)/t_haptics $(B)/t_haptics_apple'- if run_old not in t: fail(f'{TESTS_MK}: run list anchor for t_hid missing')- t = t.replace(run_old, '$(B)/t_hid $(B)/t_input_map $(B)/t_haptics $(B)/t_haptics_apple', 1)- body_old = '\t$(B)/t_hid\n'- if body_old not in t: fail(f'{TESTS_MK}: run body anchor for t_hid missing')- t = t.replace(body_old, body_old + '\t$(B)/t_input_map\n', 1)- rule_anchor = '$(B)/t_hid: t_hid.c'- if rule_anchor not in t: fail(f'{TESTS_MK}: t_hid rule missing')- t = t.replace(rule_anchor,- '$(B)/t_input_map: t_input_map.c ../input_map.h ../dm_input.h | $(B)\n'- '\t' + cc + ' -O1 -Wall -Werror -Wno-unused-function -I.. -o $@ t_input_map.c\n'- '$(B)/t_launcher_contract: t_launcher_contract.c ../input_map.h ../dm_input.h | $(B)\n'- '\t' + cc + ' -O1 -Wall -Werror -Wno-unused-function -I.. -o $@ t_launcher_contract.c\n' + rule_anchor, 1)- body_old2 = '\t$(B)/t_input_map\n'- t = t.replace(body_old2, body_old2 + '\t$(B)/t_launcher_contract\n', 1)- run2 = '$(B)/t_input_map $(B)/t_haptics'- if run2 in t: t = t.replace(run2, '$(B)/t_input_map $(B)/t_launcher_contract $(B)/t_haptics', 1)- done('tests/Makefile input map test')- # the prerequisites too, so a change to the reader rebuilds them — and hle_profile.h, so a- # change to the runtime profile does- for name in ('t_fs', 't_fs_commit_list', 't_fs_case'):- dep_old = f'$(B)/{name}:'- i = t.index(dep_old)- j = t.index('\n', i)- line = t[i:j]- if '../romfs_arc.c' not in line:- line = line.replace(' ../hle.h', ' ../romfs_arc.c ../hle.h', 1)- if '../hle_profile.h' not in line:- line = line.replace(' | $(B)', ' ../hle_profile.c ../hle_profile.h | $(B)', 1)- t = t[:i] + line + t[j:]- # hle_profile.c: every test whose prerequisites reach a dm_profile() caller needs the accessor- # at link time (the runtime-profile merge added those calls; the sync replaces this file, so the- # rule has to live here or the host tests stop linking after every sync).- USERS = ('../hle_svc.c', '../hle_thread.c', '../hle_fs.c', '../loader.c',- '../hle_fpslock.c', '../hle_oe.c', '../hle_os.c', '../hle_sdk16.c')- lines = t.splitlines(keepends=True)- out, need = [], False- for ln in lines:- if ln.startswith('$(B)/'):- # a rule header: does its prerequisite list reach a dm_profile() caller?- need = any(u in ln for u in USERS)- out.append(ln)- continue- if need:- # the recipe line of that rule: append the accessor's object if absent- if ln.startswith('\t') and re.match(r'\s*' + CL, ln) and 'hle_profile.c' not in ln:- ln = ln.rstrip('\n') + ' ../hle_profile.c\n'- elif not ln.startswith('\t') and ln.strip():- need = False # a non-recipe line ends the rule- out.append(ln)- t = ''.join(out)- # the memory block compiles ../hle_svc.c from MEM_DEPS- mem_old = 'MEM_DEPS = t_svc_memory.c memory_profile/game_profile.h ../hle_svc.c ../hle_guestthread.c ../hle.h ../dm.h'- if mem_old in t and 'hle_profile.c' not in t.split(mem_old)[1].split('\n')[0]:- t = t.replace(mem_old, mem_old + ' ../hle_profile.c ../hle_profile.h', 1)- t = re.sub(r'(\t' + CL + r' \$\(MEM_FLAGS\)[^\n]*?\.c)(\n)',- lambda m: m.group(1) + ' ../hle_profile.c' + m.group(2), t)- return done('tests/Makefile romfs_arc.c + hle_profile.c', t)--ENT = '''# The unsigned IPA: an unsigned binary has no signature for a sideloader to read entitlements from,-# so the request would be lost (AltStore reads the signature it replaces). Sign ad-hoc with the-# entitlement first; the sideloader strips this signature and carries the entitlement over.-if [ "$PREPARE_XCODE" != YES ] && [ -n "${DM_ENTITLEMENTS-default}" ]; then- if [ -n "${DM_ENTITLEMENTS:-}" ]; then cp "$DM_ENTITLEMENTS" "$APP/DmIOS.entitlements" || die "copy DM_ENTITLEMENTS"- else printf '%s\\n' '<?xml version="1.0" encoding="UTF-8"?>' '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">' \\- '<plist version="1.0"><dict><key>com.apple.developer.kernel.increased-memory-limit</key><true/></dict></plist>' > "$APP/DmIOS.entitlements" || die "entitlements"; fi- # codesign refuses a bundle whose files carry resource forks, Finder information, quarantine or- # provenance attributes ("resource fork, Finder information, or similar detritus not allowed");- # files copied into the bundle (the icon, resources staged from a Downloads folder) can bring them- xattr -cr "$APP" 2>/dev/null- codesign --force --sign - --entitlements "$APP/DmIOS.entitlements" "$APP" || die "ad-hoc sign with entitlements (the sideloader re-signs; this only carries the request)"- codesign -d --entitlements :- "$APP" 2>/dev/null | grep -q increased-memory-limit || die "entitlements did not make it into the placeholder signature"- t "entitlements: increased-memory-limit embedded in the placeholder signature"-fi-'''--def patch_build_ipa_copy_romfs(t):- """The fork's slim IPA by default, on top of upstream's DM_COPY_ROMFS (seedds/nxnative#478, #493).-- Upstream now has what the fork carried by hand: an IPA without the game files (DM_COPY_ROMFS=NO, with the- image's identity as romfs.id) and the ad-hoc signature that carries the Increased Memory Limit entitlement. So the- entitlements patch is not applied to such a file. What stays the fork's is the default: the fork packs the slim- IPA unless DM_FULL_ROMFS=1 (or DM_COPY_ROMFS=YES) says otherwise, and then also leaves the add-on content out- of the package (the host mounts Documents/games/<id>/aoc/<index>.img). The prepared Xcode project keeps upstream's- default: the script has exited by then.- """- if 'DM_FULL_ROMFS' in t: return skip('build_ipa.sh slim default (already patched)')- old = '''MAPS=()-if [ "${DM_COPY_ROMFS:-YES}" = NO ]; then-'''- if old not in t: fail('dm/ios/tools/build_ipa.sh: DM_COPY_ROMFS anchor missing (upstream moved the MAPS block)')- t = t.replace(old, '''MAPS=()-# The fork packs the slim IPA by default (upstream: DM_COPY_ROMFS=NO): DM_FULL_ROMFS=1 or DM_COPY_ROMFS=YES packs the-# game files into the package, which for a large game is many GB and iOS refuses to install it (PackageExtractionFailed)-[ -n "${DM_COPY_ROMFS:-}" ] || { [ -n "${DM_FULL_ROMFS:-}" ] && DM_COPY_ROMFS=YES || DM_COPY_ROMFS=NO; }-if [ "${DM_COPY_ROMFS:-YES}" = NO ]; then-''', 1)- done('build_ipa.sh slim default', None)- old_aoc = '''if [ -n "$AOC" ] && [ -d "$AOC" ]; then MAPS+=("$P/aoc=$AOC"); t "add-on content: $(ls "$AOC" | tr '\\n' ' ')"; fi'''- if old_aoc not in t: fail('dm/ios/tools/build_ipa.sh: add-on content mapping anchor missing')- return done('build_ipa.sh add-on content beside the slim game data', t.replace(old_aoc, '''if [ "$DM_COPY_ROMFS" != NO ] && [ -n "$AOC" ] && [ -d "$AOC" ]; then- MAPS+=("$P/aoc=$AOC"); t "add-on content packed into the IPA: $(ls "$AOC" | tr '\\n' ' ')"-elif [ -n "$AOC" ] && [ -d "$AOC" ]; then- t "add-on content alongside the game data (DM_FULL_ROMFS=1 packs it): $(ls "$AOC" | tr '\\n' ' ')"-fi''', 1))--def patch_build_ipa(t):- if 'DM_COPY_ROMFS' in t: return patch_build_ipa_copy_romfs(t)- if 'placeholder signature' in t: return skip('build_ipa.sh entitlements (already patched)')- old = '''APP=$DD/Build/Products/Release-iphoneos/DmIOS.app-[ -n "$APP" ] && [ -d "$APP" ] || die "no built app"; t "app: $APP"-'''- if old not in t: fail('dm/ios/tools/build_ipa.sh: APP anchor missing (upstream moved the app definition)')- t = t.replace(old, old + ENT, 1)- # The RomFS mapping moved into the `P=…; MAPS=(…)` assignment (upstream folded it in when it- # added the pso/ mapping), so the anchor is the assignment plus the line that follows the- # whole block — not the two adjacent lines the old form had. Both spellings are accepted: a- # checkout from before that change still syncs.- slim = '''# DM_FULL_ROMFS=1 packs the RomFS into the package (upstream behaviour; only sensible for small-# games — a full package of a large game is many GB and iOS refuses to install it with-# PackageExtractionFailed). The default is the slim package: the app reads the game files from-# Documents/romfs (a directory tree, or a ROMFSARC archive: romfs.idx + romfs.NN shards).'''- # Upstream picks the mapping form by what the RomFS path is (a .img file or a folder)- # Matched at line start: the same text also sits inside upstream's `elif [ -f "$ROMFS" ]`- # (the DM_COPY_ROMFS branch), and a bare substring replace once cut that line in half- # ('el' + 'MAPS=()' — a syntax error only bash -n caught).- old2img = '''if [ -f "$ROMFS" ]; then MAPS=("$P/romfs.img=$ROMFS"); else MAPS=("$P/romfs=$ROMFS"); fi'''- elif_old2img = '''elif [ -f "$ROMFS" ]; then MAPS=("$P/romfs.img=$ROMFS"); else MAPS=("$P/romfs=$ROMFS"); fi'''- if '\n' + elif_old2img + '\n' in t:- # Upstream's DM_COPY_ROMFS branch: the slim default needs the same NO-form here (game- # files stay out of the IPA, the identity file rides along, DM_FULL_ROMFS=1 packs them)- t = t.replace('\n' + elif_old2img + '\n', '''-elif [ -n "${DM_FULL_ROMFS:-}" ]; then if [ -f "$ROMFS" ]; then MAPS=("$P/romfs.img=$ROMFS"); else MAPS=("$P/romfs=$ROMFS"); fi; fi-''', 1)- return done('build_ipa.sh slim + entitlements', t)- if old2img in t:- t = t.replace(old2img, '''MAPS=()-# DM_FULL_ROMFS=1 packs the game files into the package (upstream behaviour; only sensible for small-# games — a full package of a large game is many GB and iOS refuses to install it with-# PackageExtractionFailed). The default is the slim package: the app reads them from-# Documents/games/<id>/ (romfs.img and aoc/<index>.img), which the launcher copies in one go and-# which can also live on an external drive.-if [ -n "${DM_FULL_ROMFS:-}" ]; then if [ -f "$ROMFS" ]; then MAPS=("$P/romfs.img=$ROMFS"); else MAPS=("$P/romfs=$ROMFS"); fi; fi''', 1)- # Add-on content follows the same rule: with the slim default it goes to- # Documents/games/<id>/aoc/<index>.img (the host already mounts *.img there, hle_fs.c- # aoc_dir), so the IPA stays small and the game data is one folder the user copies.- old_aoc = '''if [ -n "$AOC" ] && [ -d "$AOC" ]; then MAPS+=("$P/aoc=$AOC"); t "add-on content: $(ls "$AOC" | tr '\\n' ' ')"; fi'''- if old_aoc in t and 'if [ -n "${DM_FULL_ROMFS:-}" ] && [ -n "$AOC" ]' not in t:- t = t.replace(old_aoc, '''if [ -n "${DM_FULL_ROMFS:-}" ] && [ -n "$AOC" ] && [ -d "$AOC" ]; then- MAPS+=("$P/aoc=$AOC"); t "add-on content packed into the IPA: $(ls "$AOC" | tr '\\n' ' ')"-elif [ -n "$AOC" ] && [ -d "$AOC" ]; then- t "add-on content alongside the game data (DM_FULL_ROMFS=1 packs it): $(ls "$AOC" | tr '\\n' ' ')"-fi''', 1)- old3 = '''t "pack IPA (already-compressed game files stored, everything else deflated)"'''- if old3 not in t: fail('dm/ios/tools/build_ipa.sh: pack line missing after the MAPS assignment')- t = t.replace(old3, '''if [ -n "${DM_FULL_ROMFS:-}" ]; then- t "pack full IPA with RomFS (already-compressed game files stored, everything else deflated)"-else- t "pack slim IPA without RomFS (game files come from Documents/romfs; DM_FULL_ROMFS=1 packs them)"-fi''', 1)- return done('build_ipa.sh slim + entitlements', t)- old2 = '''P=Payload/DmIOS.app; MAPS=("$P/romfs=$ROMFS")'''- if old2 in t:- # current upstream: drop the RomFS from the initial assignment, add it back inside the- # DM_FULL_ROMFS branch, and leave every other mapping (aoc, pso, msl, app) untouched- t = t.replace(old2, '''P=Payload/DmIOS.app; MAPS=()-# DM_FULL_ROMFS=1 packs the RomFS into the package (upstream behaviour; only sensible for small-# games — a full package of a large game is many GB and iOS refuses to install it with-# PackageExtractionFailed). The default is the slim package: the app reads the game files from-# Documents/romfs (a directory tree, or a ROMFSARC archive: romfs.idx + romfs.NN shards).-if [ -n "${DM_FULL_ROMFS:-}" ]; then MAPS=("$P/romfs=$ROMFS"); fi''', 1)- old3 = '''t "pack IPA (already-compressed game files stored, everything else deflated)"'''- if old3 not in t: fail('dm/ios/tools/build_ipa.sh: pack line missing after the MAPS assignment')- t = t.replace(old3, '''if [ -n "${DM_FULL_ROMFS:-}" ]; then- t "pack full IPA with RomFS (already-compressed game files stored, everything else deflated)"-else- t "pack slim IPA without RomFS (game files come from Documents/romfs; DM_FULL_ROMFS=1 packs them)"-fi''', 1)- return done('build_ipa.sh slim + entitlements', t)- # older upstream: the RomFS mapping was its own statement right before the pack line- old4 = '''MAPS+=("$P/romfs=$ROMFS")-t "pack IPA (already-compressed game files stored, everything else deflated)"'''- if old4 not in t: fail('dm/ios/tools/build_ipa.sh: pack anchor missing (neither the folded '- 'MAPS assignment nor the separate RomFS line is present)')- return done('build_ipa.sh slim + entitlements', t.replace(old4, '''# DM_FULL_ROMFS=1 packs the RomFS into the package (upstream behaviour; only sensible for small-# games — a full package of a large game is many GB and iOS refuses to install it with-# PackageExtractionFailed). The default is the slim package: the app reads the game files from-# Documents/romfs (a directory tree, or a ROMFSARC archive: romfs.idx + romfs.NN shards).-if [ -n "${DM_FULL_ROMFS:-}" ]; then- MAPS+=("$P/romfs=$ROMFS")- t "pack full IPA with RomFS (already-compressed game files stored, everything else deflated)"-else- t "pack slim IPA without RomFS (game files come from Documents/romfs; DM_FULL_ROMFS=1 packs them)"-fi''', 1))--def patch_nsp(t):- P = []- P.append(('work-dir arg', '--work-dir', [(- " ap.add_argument('--env-file', help='environment switches for a diagnostic build (one KEY=VALUE per line)')",- " ap.add_argument('--work-dir', help='where the build folder goes (default: <NSP folder>/<title ID>_build); the extracted files, shader cache and temporary files all live there')\n"- " ap.add_argument('--env-file', help='environment switches for a diagnostic build (one KEY=VALUE per line)')")]))- # Two separate one-line anchors: upstream inserts lines between them whenever it adds a check- # (ffcd910 put a mac_pack check right above `work`), which broke the old three-line anchor and- # stopped the daily sync for two days (issue #13). `work` and that out_ipa line each appear once.- # `out_ipa` reads `work`, so `work` must be assigned first: patched separately they once landed- # in the wrong order (PR #15 — an UnboundLocalError on every build without -o). One replacement- # per shape of upstream's block keeps them in order:- # - before upstream #278: one out_ipa line, the two checks, then `work`;- # - after #278: out_ipa under `if want_ios:` (8 spaces) plus an out_app block, `work` still last.- # Each shape is ONE (old, new) pair rather than a delete plus an insert: a two-step edit that- # removes `work` and puts it back leaves the tree without the assignment if the second step ever- # stops matching.- work_line = " work = Path(os.path.expanduser(args.work_dir)).resolve() if args.work_dir else nsp_dir / f'{g.id}_build' # the folder holding the NSPs by default; --work-dir puts the build elsewhere"- oipa_old = "out_ipa = Path(os.path.expanduser(args.out or OUT_IPA)).resolve() if (args.out or OUT_IPA) else nsp_dir / g.get('ipa') # by default in the NSP folder, next to the NSPs and <id>_build/"- oipa_new = "out_ipa = Path(os.path.expanduser(args.out or OUT_IPA)).resolve() if (args.out or OUT_IPA) else work.parent / g.get('ipa') # by default next to the NSPs and <id>_build/"- shadowed_line = " if shadowed and not (args.out or OUT_IPA): out_ipa = out_ipa.with_name(out_ipa.stem + '-provisional.ipa') # never over the IPA of the game's real profile"- macpack_line = " if mac_pack and (args.out or OUT_IPA) and out_ipa.suffix != '.app': raise BuildError(f'the Mac app (-o / OUT_IPA) must end in .app: {out_ipa}')"- if "\n out_ipa = None\n if want_ios:\n" in t: # upstream #278's shape- P.append(('work-dir paths', 'args.work_dir', [(- " out_ipa = None\n if want_ios:\n " + oipa_old + "\n",- work_line + "\n out_ipa = None\n if want_ios:\n " + oipa_new + "\n")]))- else:- P.append(('work-dir paths', 'args.work_dir', [(- " " + oipa_old + "\n" + shadowed_line + "\n" + macpack_line + "\n work = nsp_dir / f'{g.id}_build'",- work_line + "\n"- " # out_ipa reads `work`, so `work` must be assigned first (upstream's order had them the other\n"- " # way round; the --work-dir patch moved `work` up here and this line had to follow it).\n"- " " + oipa_new + "\n" + shadowed_line + "\n" + macpack_line)]))- # The shader translator (dmsh_xlate_bin/dmsh_xlate) is a framework-dependent apphost, and a- # set-but-wrong DOTNET_ROOT is worse than none: the apphost stops searching once the variable is- # there, so a stale root from the environment kills the shader step while `dotnet` on PATH keeps- # working — nx_extract builds fine, then dmsh_build refuses with "'xlate_source: lock … / actual' empty".- # Upstream's configure_dotnet() (called right before this) derives the root from `dotnet- # --list-runtimes`; what it does not do is check that the translator runs with it. This runs the- # translator, and when it answers nothing tries candidate roots and keeps the first that works;- # with none verified the variable is dropped, so the apphost searches its default locations.- # The marker is `xlate_answers`, a name only this code has: the earlier marker, `list-runtimes`,- # became upstream's own text (configure_dotnet) and silently switched this patch off at the sync- # to 75065df (issue #92). The first half of the old patch (parse the root from --list-runtimes)- # is upstream's now and is not carried any more.- P.append(('DOTNET_ROOT verification', 'xlate_answers', [(- " configure_dotnet(env)\n",- """ configure_dotnet(env)- xlate_bin = repo / 'dm/gfx/tools/dmsh_xlate_bin/dmsh_xlate' # the fork's check of the root configure_dotnet chose (sync_upstream.py, issue #92)- def xlate_answers(root):- e = dict(env)- if root: e['DOTNET_ROOT'] = str(root)- else: e.pop('DOTNET_ROOT', None)- try:- r = subprocess.run([str(xlate_bin), '--source-sha'], capture_output=True, text=True, env=e, timeout=120)- return r.returncode == 0 and bool(r.stdout.strip())- except Exception:- return False- if xlate_bin.exists() and not xlate_answers(env.get('DOTNET_ROOT')):- cands = []- if dn := shutil.which('dotnet', path=env['PATH']):- real = Path(dn).resolve()- for base in (real.parent.parent, real.parent.parent.parent):- cands += [base / 'libexec', base] # Homebrew's bin/../libexec; share/dotnet and aliases- cands += [Path.home() / '.dotnet', Path('/usr/local/share/dotnet'), Path('/opt/homebrew/opt/dotnet/libexec')]- if hit := next((c for c in cands if c.is_dir() and xlate_answers(c)), None):- env['DOTNET_ROOT'] = os.environ['DOTNET_ROOT'] = str(hit)- say(f'DOTNET_ROOT: {hit} (verified — the shader translator runs)')- elif env.get('DOTNET_ROOT'):- del env['DOTNET_ROOT']; os.environ.pop('DOTNET_ROOT', None)- say('DOTNET_ROOT: removed (none verified — the apphost searches its default locations)')-""")]))- # upstream added errno to this line (seedds/nxnative#493), so the anchor is the stable head and the tail of the import- imp = re.search(r'^import ast, collections, ctypes, (errno, )?getpass, (hashlib, importlib\.util, .*)$', t, re.M)- P.append(('pwd import', 'getpass, pwd', [(imp.group(0), imp.group(0).replace('getpass, ', 'getpass, pwd, ', 1))] if imp else [("import ast, collections, ctypes, getpass, hashlib, ... (the script's import line)", '')]))- # HOME can be missing or empty under a GUI launch (issue #10): .NET's first-run configure then- # builds a mutex path from "" and dies with NuGet-Migrations + lstat("") before reading a project.- P.append(('HOME fallback', 'DOTNET_CLI_HOME', [(- " env.setdefault('USER', getpass.getuser()) # xcodegen fails without USER (Couldn't find current username)",- """ env.setdefault('USER', getpass.getuser()) # xcodegen fails without USER (Couldn't find current username)- # HOME and DOTNET_CLI_HOME for every child: a GUI launch (LaunchServices) can hand the app a- # process environment with HOME missing or empty, and .NET's first-run configure then builds a- # mutex path from "" and dies with 'NuGet-Migrations' + lstat("") == ENOENT — before any project- # is read (issue #10, where the app's own DOTNET_ROOT workaround did not help because the empty- # HOME came from the launch, not from the app). Derive it from the password database when the- # environment has nothing usable, so the pipeline is correct however it was started.- if not env.get('HOME') or not os.path.isdir(env['HOME']):- try: home = Path(pwd.getpwuid(os.getuid()).pw_dir)- except Exception: home = Path.home()- if home.is_dir():- env['HOME'] = os.environ['HOME'] = str(home)- say(f'HOME: {home} (taken from the password database; the environment had none)')- env.setdefault('DOTNET_CLI_HOME', env['HOME']) # .NET writes its first-run state here""")]))- # Issue #10 also asked why the first-run experience is not simply skipped. It can be, with the- # two knobs .NET still supports (SKIP_FIRST_TIME_EXPERIENCE was retired in .NET Core 3.0): the- # banner and the telemetry call are noise for a build, and the telemetry endpoint can hang the- # very first run on a mainland connection — which is how a "stuck at dotnet" report looks.- P.append(('dotnet quiet', 'DOTNET_CLI_TELEMETRY_OPTOUT', [(- " env.setdefault('DOTNET_CLI_HOME', env['HOME']) # .NET writes its first-run state here",- """ env.setdefault('DOTNET_CLI_HOME', env['HOME']) # .NET writes its first-run state here- # No first-run banner, no telemetry: a build neither wants nor reads either, and the telemetry- # call can hang the first run on a network that cannot reach Microsoft. setdefault, so a user- # who wants telemetry on keeps it.- env.setdefault('DOTNET_CLI_TELEMETRY_OPTOUT', '1')- env.setdefault('DOTNET_NOLOGO', '1')""")]))- # An AppleDouble file ("._<name>.nsp": macOS writes one beside every real file on an exFAT/FAT- # drive) carries the real file's name and title ID, so scan_nsps counted the one update NSP as two and- # left both out (7ae7ba65, the report's Hades II build). Hand-edited into the tree until issue #92,- # which had no protection: the next sync would have replaced the file with upstream's.- P.append(('AppleDouble skip', 'an AppleDouble file', [(- " if p.stat().st_size == 0: # an empty file left by an incomplete download",- " if p.name.startswith('._'):\n"- " continue # an AppleDouble file: macOS writes one beside every real file on exFAT/FAT drives, and its name carries the same [title ID] — counting it made the one real update NSP read as two, and both were then left out (the report's Hades II build)\n"- " if p.stat().st_size == 0: # an empty file left by an incomplete download")]))- # An external work folder (an exFAT USB drive, the report's own setup) can report entries- # during shutil.rmtree's walk that vanish by their unlink; upstream's rmtree() lets ENOENT pass- # through its onexc hook (the fork's own onerror form of this was taken over by it). onexc exists- # from Python 3.12 only and the fork's floor is 3.9: older Pythons get the same hook as onerror.- if 'def _gone(' in t:- P.append(('rmtree 3.9', "sys.version_info >= (3, 12) else {'onerror'", [(- " elif p.exists(): shutil.rmtree(p, onexc=_gone)",- " elif p.exists(): shutil.rmtree(p, **({'onexc': _gone} if sys.version_info >= (3, 12) else {'onerror': lambda f, q, e: _gone(f, q, e[1])}))")]))- else: # the last sync base: upstream had no such hook yet, the fork's own form of it- P.append(('rmtree exfat', '_rmtree_enoent', [(- """def rmtree(p):- if p.is_symlink() or p.is_file(): p.unlink()- elif p.exists(): shutil.rmtree(p)""",- """def _rmtree_enoent(func, p, exc):- if isinstance(exc[1], FileNotFoundError): return # already gone: the goal is achieved- time.sleep(0.2); func(p) # one retry: exFAT directory-cache races clear---def rmtree(p):- if p.is_symlink() or p.is_file(): p.unlink()- elif p.exists(): shutil.rmtree(p, onerror=_rmtree_enoent)- if p.exists(): shutil.rmtree(p, onerror=_rmtree_enoent) # the caller needs it gone (copytree follows)""")]))- # A shader-chain bump (an upstream translator update) silently invalidates every cached- # library: the row stayed green, the build "worked", and hours of Metal compile looked like a- # mystery re-run (the report: "why is it building shaders again, the artifacts are on the- # drive"). Say it loudly, with a marker both front ends turn into a user-facing notice.- P.append(('chain-change note', "[NOTE] chain-changed", [(- """ chain = chain_of(repo)- out = sh / 'cache' if mac else ios""",- """ chain = chain_of(repo)- stale = sorted(d.name for d in (sh / 'cache').glob('b-*') if d.name != f'b-{chain}' and any(d.glob('*_b.metallib'))- ) + sorted(d.name for d in ios.glob('b-*') if d.name != f'b-{chain}' and any(d.glob('*_b.metallib')))- if stale: say(f'[NOTE] chain-changed: {", ".join(stale)} -> b-{chain}: the upstream update changed the shader '- 'translator, so the cached libraries cannot be reused and this build rebuilds them with it '- '(once per update; later builds reuse as before)')- out = sh / 'cache' if mac else ios""")]))- # Xcode 15 and later download the iOS platform separately: xcodebuild and the Metal compiler can- # both be present with no iOS SDK, and the failure then surfaced deep inside xcodebuild. Naming- # the SDK makes the error actionable (found while auditing environment assumptions, 2026-10-26).- P.append(('iOS SDK check', "the iOS SDK is not installed", [(- """ gone = [f'{t} ({how})' for t, how in tools.items() if not shutil.which(t, path=env['PATH'])]- if gone: raise BuildError('tools not found: ' + ', '.join(gone))-""",- """ gone = [f'{t} ({how})' for t, how in tools.items() if not shutil.which(t, path=env['PATH'])]- if gone: raise BuildError('tools not found: ' + ', '.join(gone))- if not mac:- # Xcode 15 and later ship the iOS platform as a separate download: xcodebuild and the Metal- # compiler can both be there while the iOS SDK is not, and the failure then surfaces deep in- # xcodebuild. Check the SDK itself so the message names the right command.- sdk = subprocess.run(['xcrun', '--sdk', 'iphoneos', '--show-sdk-version'], capture_output=True, text=True, env=env)- if sdk.returncode:- raise BuildError('the iOS SDK is not installed (Xcode 15 and later download the platform separately): run xcodebuild -downloadPlatform iOS, or pick it in Xcode → Settings → Components')-""")]))- # An Intel Python under Rosetta (an Intel Homebrew in /usr/local on Apple silicon) has children- # that prefer the x86_64 slice: the shader translator's universal apphost then asks for an x86_64- # .NET, finds only the arm64 one, prints nothing, and the build stops at the iOS shader step with- # an empty "xlate_source: lock … / actual" — which reads like a broken translator. ufooer found- # this on an iPad bring-up (PR #31, item 3); saying it up front turns a mystery into a one-line fix.- P.append(('Rosetta check', 'is an Intel Python running under Rosetta', [(- " if not keys.is_file(): raise BuildError(f'no such file: {keys}')\n",- """ if not keys.is_file(): raise BuildError(f'no such file: {keys}')- # An Intel Python (an Intel Homebrew under /usr/local) runs under Rosetta on an Apple silicon Mac, and its children prefer the- # x86_64 slice: the shader translator's universal apphost then wants an x86_64 .NET, finds the arm64 one, prints nothing, and- # the build stops at the iOS shader step with "xlate_source: lock … / actual" (empty), which reads like a stale translator.- # Say so here instead (ufooer's PR #31, item 3).- if sys.platform == 'darwin' and subprocess.run(['sysctl', '-n', 'sysctl.proc_translated'], capture_output=True, text=True).stdout.strip() == '1':- raise BuildError(f'{sys.executable} is an Intel Python running under Rosetta; run the build with a native arm64 Python (e.g. /usr/bin/python3 or Homebrew in /opt/homebrew)')-""")]))- # glslangValidator is only needed by an OpenGL game, and build_gl_shaders already checks for it —- # but by then the extraction and the capture have run for minutes, and the check raises before- # layer_shaders creates gl_shaders.log, so the failure had no log to read (issue #71). Checked- # next to check_metal, which is in the same place for the same reason.- P.append(('GL shader tool check', 'check_glslang(env)', [(- " if gfx == 'nvn': check_metal(py, repo, env) # before the captures and the shader split, which take minutes\n",- " if gfx == 'nvn': check_metal(py, repo, env) # before the captures and the shader split, which take minutes\n"- " if gfx == 'gl': check_glslang(env)\n"), (- # the function itself, beside check_metal- """ raise BuildError(msg.replace('set DM_ALLOW_OTHER_METAL=1 (the NSP script\\'s --allow-other-metal)', 'ALLOW_OTHER_METAL = True (--allow-other-metal)'))-""",- """ raise BuildError(msg.replace('set DM_ALLOW_OTHER_METAL=1 (the NSP script\\'s --allow-other-metal)', 'ALLOW_OTHER_METAL = True (--allow-other-metal)'))---def check_glslang(env):- \"\"\"An OpenGL game's GLSL goes through glslangValidator; build_gl_shaders checks for it, but only- after the extraction and the runtime capture have run for minutes, and it raises before- layer_shaders creates gl_shaders.log — so the GUI showed a failure with no log to read (issue- #71). Checked before those steps, as check_metal is and for the same reason.\"\"\"- if not shutil.which('glslangValidator', path=env['PATH']):- raise BuildError("glslangValidator is not installed: an OpenGL game's GLSL shaders need it to compile to SPIR-V (brew install glslang)")-""")]))- # Every extracted version but the packed one holds a complete extra copy of the game; the fork drops- # them once the build is done (1887fe93: a game with several updates filled the drive). Hand-edited- # until issue #92; the function is added before extract(), and each ending of main() calls it.- PRUNE_FUNC = r'''def prune_intermediate_extracts(dirs, versions, pkg_ver):- """Every extracted version but the packed one: each holds a complete extra copy of the game (one- merged RomFS image per version), and only the packed version's files are reused by the next- build — when its inputs change, the intermediates are extracted again anyway (the packed version- is merged from them). The shader captures above still read them, so they are dropped only once- the build is done. A game without an update extracts one version and this deletes nothing."""- spare = [dirs[v] for v in versions if v != pkg_ver and dirs[v].is_dir()]- if not spare: return- say('deleting the intermediate extractions, one full copy of the game each (the packed version keeps its files): '- + ', '.join(d.name for d in spare))- for d in spare: rmtree(d)---'''- P.append(('prune function', 'def prune_intermediate_extracts', [(- 'def extract(nx, keys, ex, name, base, upd, cmp_dir, logs, g):', PRUNE_FUNC + 'def extract(nx, keys, ex, name, base, upd, cmp_dir, logs, g):')]))- for what, tail in (("Mac app", " say(f'done: {out_ipa} ({tree_size(out_ipa)[1]"), ("Mac run", " say(f'done: the game runs on the Mac"),- ("Xcode project", " say(f'ready: {workspace}')")):- P.append((f'prune after the {what}', "rmtree(work / 'tmp')\n prune_intermediate_extracts(dirs, versions, pkg_ver)\n" + tail, [(- "rmtree(work / 'tmp')\n" + tail, "rmtree(work / 'tmp')\n prune_intermediate_extracts(dirs, versions, pkg_ver)\n" + tail)]))- P.append(('prune after the IPA', "{ex}'); rmtree(ex)\n else:\n prune_intermediate_extracts", [(- " say(f'deleting the extracted game files: {ex}'); rmtree(ex)\n",- " say(f'deleting the extracted game files: {ex}'); rmtree(ex)\n else:\n prune_intermediate_extracts(dirs, versions, pkg_ver)\n")]))- for name, marker, pairs in P:- if marker in t:- skip(f'NSP script {name} (already patched)'); continue- for old, new in pairs:- if old not in t:- fail(f'scripts/build_ipa_from_nsp.py: patch "{name}" anchor missing')- t = t.replace(old, new, 1)- done(f'NSP script {name}')- return t--NVM = 'dm/gfx/nvn/nvn_mtl.m'-def patch_nvn_mtl(t):- # BC decode for GPUs without BC support (six hunks). The fork's two save-load freeze hunks (NX2Apple- # issue #4: 'up_begin publish' and 'finish publish') are gone: upstream has both (the up_begin- # rec_publish and the mtl_finish_gpu on_sub_thread() rec_publish, b87a0cc; checked against- # seedds/main for issue #92), and the carried hunks only said "already patched".- P = [- # BC decode on GPUs without BC support (profile tex_bc_cpu; nvn_bcdec.c is an OURS file)- ('bc cpu globals', ['g_bc_cpu;'], [(- 'static id<MTLDevice> g_dev;',- '''static id<MTLDevice> g_dev;-static int g_bc_gpu = 1; // the device advertises BC texture compression (set where the device is made)-static int g_bc_cpu; // decode BC on the CPU: no GPU support and the profile allows it''')]),- ('bc cpu include', ['nvn_bcdec.h'], [(- '#include "../tex/nvn_fmt_mtl.h"',- '#include "../tex/nvn_fmt_mtl.h"\n#include "../tex/nvn_bcdec.h" // BC on the CPU for GPUs without BC support (profile tex_bc_cpu)')]),- ('bc cpu detect', ['supportsBCTextureCompression'], [(- ''' g_dev = MTLCreateSystemDefaultDevice();- if (!g_dev) MDIE("no Metal device");- if (!g_dev.hasUnifiedMemory) MDIE("needs a unified-memory device (zero-copy memory pools)");''',- ''' g_dev = MTLCreateSystemDefaultDevice();- if (!g_dev) MDIE("no Metal device");- if (!g_dev.hasUnifiedMemory) MDIE("needs a unified-memory device (zero-copy memory pools)");- g_bc_gpu = [g_dev supportsBCTextureCompression];- g_bc_cpu = !g_bc_gpu && DM_GAME_TEX_BC_CPU;- if (g_bc_cpu) MLOG("BC textures: this GPU has no BC support, decoding them on the CPU (profile tex_bc_cpu)");''')]),- # BC decode on the CPU when the GPU has no BC support (profile tex_bc_cpu): the texture is- # created uncompressed, and the upload expands the blocks before the blit.- ('bc cpu tex_desc', ['nvn_bc_unpacked(t->d.format, &bc_unpacked'], [(- ' uint32_t pf = 0; uint8_t swz[4];\n if (!nvn_fmt_to_mtl(t->d.format, &pf, swz) || !pf) {',- ' uint32_t pf = 0; uint8_t swz[4];\n // A BC format on a GPU without BC support: create the texture in the uncompressed format the\n // decoder produces, and let the upload path fill it through nvn_bc_decode (below). Without\n // this the Metal format is a BC one the device cannot allocate, and every such texture is nil.\n uint32_t bc_unpacked = 0; int bc_bpp = 0;\n if (g_bc_cpu && nvn_bc_unpacked(t->d.format, &bc_unpacked, &bc_bpp)) pf = bc_unpacked;\n if (!pf && (!nvn_fmt_to_mtl(t->d.format, &pf, swz) || !pf)) {')]),- ('bc cpu upload', ['nvn_bc_decode(t->d.format'], [(- ' up_begin();\n id<MTLBuffer> stg = [g_dev newBufferWithLength:total ? total : 16 options:MTLResourceStorageModeShared];\n res_add(stg); [g_up_keep addObject:stg];\n size_t off = 0;\n int zb = zblock_on() && t->d.format >= 0x79 && t->d.format <= 0x94; if (zb) { g_zb_ser = t->serial; g_zb_n = (int)MIN(d.mipmapLevelCount, 16u); memset(g_zb, 0, sizeof g_zb); memset(g_zb_tot, 0, sizeof g_zb_tot); }\n for (unsigned l = 0; l < d.mipmapLevelCount; l++) {\n uint32_t w = MAX(t->d.width >> l, 1u), h = MAX(t->d.height >> l, 1u), z = t->d.target == 2 ? MAX(t->d.depth >> l, 1u) : 1;\n size_t pitch = (size_t)((w + bw - 1) / bw) * bpb, rows = (h + bh - 1) / bh;\n for (unsigned y = 0; y < layers; y++) {\n if (nvn_deswizzle(&t->d, l, y, src, (uint8_t *)stg.contents + off, pitch)) { RED_ONCE(9, "deswizzle failed format %#x target %d", t->d.format, t->d.target); break; }\n if (zb && l < 16) { const uint64_t *q = (const uint64_t *)((const uint8_t *)stg.contents + off); size_t nb = pitch * rows * z / 16;\n for (size_t i = 0; i < nb; i++) g_zb[l] += !(q[2 * i] | q[2 * i + 1]);\n g_zb_tot[l] += (uint32_t)nb; }\n up_blit_add(stg, off, pitch, pitch * rows, MTLSizeMake(w, h, z), mt, y, l);\n',- ' // A BC texture on a GPU without BC support: tex_desc made the Metal texture RGBA8 (or R8/RG8,\n // RGBA16F for BC6H), so the staging slot is per-pixel, not per-block, and the deswizzled block\n // data is expanded through nvn_bc_decode before the blit. bc_cpu stays 0 on Macs and A19+,\n // where the compressed path below is used unchanged.\n uint32_t bc_pf = 0; int bc_bpp = 0;\n int bc_cpu = g_bc_cpu && nvn_bc_unpacked(t->d.format, &bc_pf, &bc_bpp);\n size_t total_bc = 0;\n if (bc_cpu) {\n total_bc = 0;\n for (unsigned l = 0; l < d.mipmapLevelCount; l++) {\n uint32_t w = MAX(t->d.width >> l, 1u), h = MAX(t->d.height >> l, 1u), z = t->d.target == 2 ? MAX(t->d.depth >> l, 1u) : 1;\n total_bc += (size_t)w * h * z * layers * (size_t)bc_bpp;\n }\n }\n up_begin();\n id<MTLBuffer> stg = [g_dev newBufferWithLength:(bc_cpu ? total_bc : total) ? (bc_cpu ? total_bc : total) : 16 options:MTLResourceStorageModeShared];\n res_add(stg); [g_up_keep addObject:stg];\n size_t off = 0;\n int zb = zblock_on() && t->d.format >= 0x79 && t->d.format <= 0x94; if (zb) { g_zb_ser = t->serial; g_zb_n = (int)MIN(d.mipmapLevelCount, 16u); memset(g_zb, 0, sizeof g_zb); memset(g_zb_tot, 0, sizeof g_zb_tot); }\n // CPU-side scratch for the compressed block data when bc_cpu (one level-slice at a time)\n uint8_t *bc_tmp = NULL; size_t bc_tmp_sz = 0;\n for (unsigned l = 0; l < d.mipmapLevelCount; l++) {\n uint32_t w = MAX(t->d.width >> l, 1u), h = MAX(t->d.height >> l, 1u), z = t->d.target == 2 ? MAX(t->d.depth >> l, 1u) : 1;\n size_t pitch = (size_t)((w + bw - 1) / bw) * bpb, rows = (h + bh - 1) / bh;\n for (unsigned y = 0; y < layers; y++) {\n if (bc_cpu) {\n size_t need = pitch * rows * z;\n if (need > bc_tmp_sz) { free(bc_tmp); bc_tmp = malloc(need); bc_tmp_sz = need; if (!bc_tmp) MDIE("BC decode scratch of %zu bytes failed", need); }\n if (nvn_deswizzle(&t->d, l, y, src, bc_tmp, pitch)) { RED_ONCE(9, "deswizzle failed format %#x target %d", t->d.format, t->d.target); break; }\n size_t dst_pitch = (size_t)w * bc_bpp;\n for (uint32_t zz = 0; zz < z; zz++)\n nvn_bc_decode(t->d.format, bc_tmp + (size_t)zz * pitch * rows, pitch, w, h,\n (uint8_t *)stg.contents + off + (size_t)zz * dst_pitch * h, dst_pitch);\n up_blit_add(stg, off, dst_pitch, dst_pitch * h, MTLSizeMake(w, h, z), mt, y, l);\n off += dst_pitch * h * z;\n continue;\n }\n if (nvn_deswizzle(&t->d, l, y, src, (uint8_t *)stg.contents + off, pitch)) { RED_ONCE(9, "deswizzle failed format %#x target %d", t->d.format, t->d.target); break; }\n if (zb && l < 16) { const uint64_t *q = (const uint64_t *)((const uint8_t *)stg.contents + off); size_t nb = pitch * rows * z / 16;\n for (size_t i = 0; i < nb; i++) g_zb[l] += !(q[2 * i] | q[2 * i + 1]);\n g_zb_tot[l] += (uint32_t)nb; }\n up_blit_add(stg, off, pitch, pitch * rows, MTLSizeMake(w, h, z), mt, y, l);\n')]),- ('bc cpu free', ['free(bc_tmp);\n free(part);'], [(- " free(part);\n up_flush();\n return mt;",- " free(bc_tmp);\n free(part);\n up_flush();\n return mt;")]),- ]- for name, markers, pairs in P:- if any(m in t for m in markers):- skip(f'nvn_mtl.m {name} (already patched)'); continue- for old, new in pairs:- if old not in t: fail(f'{NVM}: patch "{name}" anchor missing: {old[:70]!r}')- t = t.replace(old, new, 1)- done(f'nvn_mtl.m {name}')- return t--MAIN_M_ROMFS = ('''static NSString *romfs_locate(void) {- NSFileManager *fm = NSFileManager.defaultManager;- NSString *doc = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];- NSString *img = [doc stringByAppendingPathComponent:@"romfs.img"];- if (romfs_image_complete(img) && romfs_identity_accepts(img)) {- // A folder copy from before images is now dead weight of up to many GB (often cut off partway). Deleting its 300,000 files here took longer than iOS allows an app to start- // (Tears of the Kingdom: killed on a black screen), so it is moved aside at once and deleted in the background, leftovers of an interrupted delete included- NSString *old = [doc stringByAppendingPathComponent:@"romfs"], *tmp = NSTemporaryDirectory();- if ([fm fileExistsAtPath:old] && [fm moveItemAtPath:old toPath:[tmp stringByAppendingPathComponent:[@"romfs-old-" stringByAppendingString:NSUUID.UUID.UUIDString]] error:nil])- fprintf(stderr, "boot: Documents/romfs moved aside for deletion (Documents/romfs.img replaces it)\\n");- dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0), ^{- NSFileManager *bfm = [NSFileManager new];- for (NSString *n in [bfm contentsOfDirectoryAtPath:tmp error:nil]) if ([n hasPrefix:@"romfs-old-"]) [bfm removeItemAtPath:[tmp stringByAppendingPathComponent:n] error:nil];- });- return img;- }- NSString *bundledImage = [NSBundle.mainBundle.resourcePath stringByAppendingPathComponent:@"romfs.img"];- NSString *documentFolder = [doc stringByAppendingPathComponent:@"romfs"];- if ([fm fileExistsAtPath:[documentFolder stringByAppendingPathComponent:@DM_GAME_ROMFS_MARKER]]) return documentFolder;- if (romfs_image_complete(bundledImage)) return bundledImage;- for (NSString *d in @[[doc stringByAppendingPathComponent:@"romfs"], [NSBundle.mainBundle.resourcePath stringByAppendingPathComponent:@"romfs"]])- if ([fm fileExistsAtPath:[d stringByAppendingPathComponent:@DM_GAME_ROMFS_MARKER]]) return d; // only a directory containing the game profile\'s romfs_marker path counts (Mario: System/Resource, the resource size table)- return nil;-}--''', '''// A folder holds this game\'s files if it has a ROMFSARC index or the profile\'s marker path.-// Shared by romfs_locate and the per-game layout below, so both answer the same question.-static BOOL romfs_dir_ok(NSString *d) {- NSFileManager *fm = NSFileManager.defaultManager;- // A ROMFSARC archive: <dir>/romfs.idx next to romfs.NN shards. The host opens it when DM_ROMFS- // points at the base; the marker check does not apply (there are no directories to walk).- if ([fm fileExistsAtPath:[d stringByAppendingPathComponent:@"romfs.idx"]]) return YES;- // A plain directory tree: only one containing the game profile\'s romfs_marker path counts- // (Mario: System/Resource, the resource size table). Runtime profile: the marker is a profile- // value now; the compiled macro is only what dm_profile() falls back to without DM_PROFILE.- return [fm fileExistsAtPath:[d stringByAppendingPathComponent:@(dm_profile()->romfs_marker)]];-}--// Where one game\'s data lives under the per-game layout: Documents/games/<title ID>/, holding-// romfs.img the whole RomFS as one image file (what scripts/push_romfs.sh sends), or-// romfs/ a ROMFSARC archive or a plain tree, for copies made before images-// msl/ this game\'s Metal shader libraries (optional; the app\'s own dm/ is used otherwise)-// save/ temp/ this game\'s saves and scratch space-// The layout exists so several games can share one installed app and so the game data can sit on-// an external drive the Files app exposes (a folder copied there keeps this shape).-static NSString *game_dir_for(const char *title_id) {- NSString *doc = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];- return [[doc stringByAppendingPathComponent:@"games"] stringByAppendingPathComponent:@(title_id)];-}--static NSString *romfs_locate(void) {- NSFileManager *fm = NSFileManager.defaultManager;- NSString *doc = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];- // What the player picked in the Files app wins over everything: it is the one path they chose- // on purpose, possibly on an external drive, and it costs nothing when they never picked one- // (the bookmark is absent and this falls straight through). An image or a folder both work,- // and a pick that no longer holds this game's data falls through rather than failing the boot.- {- BOOL stale = NO;- NSString *picked = dm_picked_data_path(&stale);- if (stale) fprintf(stderr, "boot: the picked game-data location needs to be chosen again (the app is signed differently now)\\n");- if (picked.length) {- if (romfs_image_complete(picked)) { fprintf(stderr, "boot: game data from the picked image %s\\n", picked.UTF8String); return picked; }- NSString *pimg = [picked stringByAppendingPathComponent:@"romfs.img"];- if (romfs_image_complete(pimg)) { fprintf(stderr, "boot: game data from the picked folder %s\\n", pimg.UTF8String); return pimg; }- if (romfs_dir_ok(picked)) { fprintf(stderr, "boot: game data from the picked folder %s\\n", picked.UTF8String); return picked; }- fprintf(stderr, "boot: the picked location %s holds no game data for this title; using the app's own\\n", picked.UTF8String);- }- }- // Per-game first: Documents/games/<id>/romfs.img (one file, what push_romfs.sh sends) or- // Documents/games/<id>/romfs/ — the launcher-style layout, and what lets a user keep several- // games\' data side by side or on an external drive. The marker check inside romfs_dir_ok is- // what keeps a stray folder from being taken for this game.- NSString *gdir = game_dir_for(dm_profile()->id);- NSString *gimg = [gdir stringByAppendingPathComponent:@"romfs.img"];- if (romfs_image_complete(gimg)) return gimg;- NSString *gfolder = [gdir stringByAppendingPathComponent:@"romfs"];- if ([fm fileExistsAtPath:gfolder] && romfs_dir_ok(gfolder)) return gfolder;- NSString *img = [doc stringByAppendingPathComponent:@"romfs.img"];- if (romfs_image_complete(img)) {- // A folder copy from before images is now dead weight of up to many GB (often cut off partway). Deleting its 300,000 files here took longer than iOS allows an app to start- // (Tears of the Kingdom: killed on a black screen), so it is moved aside at once and deleted in the background, leftovers of an interrupted delete included- NSString *old = [doc stringByAppendingPathComponent:@"romfs"], *tmp = NSTemporaryDirectory();- if ([fm fileExistsAtPath:old] && [fm moveItemAtPath:old toPath:[tmp stringByAppendingPathComponent:[@"romfs-old-" stringByAppendingString:NSUUID.UUID.UUIDString]] error:nil])- fprintf(stderr, "boot: Documents/romfs moved aside for deletion (Documents/romfs.img replaces it)\\n");- dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0), ^{- NSFileManager *bfm = [NSFileManager new];- for (NSString *n in [bfm contentsOfDirectoryAtPath:tmp error:nil]) if ([n hasPrefix:@"romfs-old-"]) [bfm removeItemAtPath:[tmp stringByAppendingPathComponent:n] error:nil];- });- return img;- }- NSString *bundledImage = [NSBundle.mainBundle.resourcePath stringByAppendingPathComponent:@"romfs.img"];- NSString *documentFolder = [doc stringByAppendingPathComponent:@"romfs"];- if ([fm fileExistsAtPath:[documentFolder stringByAppendingPathComponent:@(dm_profile()->romfs_marker)]]) return documentFolder;- if (romfs_image_complete(bundledImage)) return bundledImage;- for (NSString *d in @[[doc stringByAppendingPathComponent:@"romfs"], [NSBundle.mainBundle.resourcePath stringByAppendingPathComponent:@"romfs"]])- if (romfs_dir_ok(d)) return d;- return nil;-}--''')---MAIN_M_ENV = (' setenv("DM_ROMFS", romfs.fileSystemRepresentation, 0);\n setenv("DM_SAVE", [doc stringByAppendingPathComponent:@"save"].fileSystemRepresentation, 0);\n setenv("DM_TEMP", [doc stringByAppendingPathComponent:@"temp"].fileSystemRepresentation, 0);\n NSString *dm = [res stringByAppendingPathComponent:@"dm"];\n setenv("DM_NVN_SHMAP", [dm stringByAppendingPathComponent:@"shader_map.tsv"].fileSystemRepresentation, 0);\n setenv("DM_MSL_DIR", [res stringByAppendingPathComponent:@"msl"].fileSystemRepresentation, 0);\n', ' setenv("DM_ROMFS", romfs.fileSystemRepresentation, 0);\n // Saves and scratch space: Documents/games/<id>/{save,temp} when the per-game layout is in use\n // (so two games in one app never share a save folder), else the old Documents/{save,temp}. An\n // env file still wins — DM_SAVE/DM_TEMP set there are already in the environment and\n // setenv(..., 0) leaves them alone.\n NSString *gdir = game_dir_for(dm_profile()->id);\n // Tie the data folder to where the game files actually came from: if romfs_locate fell back to\n // Documents/romfs, the saves must stay beside it (a game folder without romfs is not in use).\n BOOL per_game = [romfs hasPrefix:gdir];\n NSString *save_dir = per_game ? [gdir stringByAppendingPathComponent:@"save"] : [doc stringByAppendingPathComponent:@"save"];\n NSString *temp_dir = per_game ? [gdir stringByAppendingPathComponent:@"temp"] : [doc stringByAppendingPathComponent:@"temp"];\n for (NSString *d in @[save_dir, temp_dir]) [fm createDirectoryAtPath:d withIntermediateDirectories:YES attributes:nil error:nil];\n setenv("DM_SAVE", save_dir.fileSystemRepresentation, 0);\n setenv("DM_TEMP", temp_dir.fileSystemRepresentation, 0);\n if (per_game) fprintf(stderr, "boot: per-game data folder %s\\n", gdir.fileSystemRepresentation);\n NSString *dm = [res stringByAppendingPathComponent:@"dm"];\n setenv("DM_NVN_SHMAP", [dm stringByAppendingPathComponent:@"shader_map.tsv"].fileSystemRepresentation, 0);\n // Shader libraries: a game\'s own <gdir>/msl first (a per-game layout may carry its own), else\n // the app\'s shared <App>/msl.\n NSString *per_game_msl = [gdir stringByAppendingPathComponent:@"msl"];\n NSString *msl = (per_game && [fm fileExistsAtPath:per_game_msl]) ? per_game_msl : [res stringByAppendingPathComponent:@"msl"];\n setenv("DM_MSL_DIR", msl.fileSystemRepresentation, 0);\n')--# 420047da (LNPANDY): no game data at boot is not fatal, and the launcher's Play (re)locates it (dm_locate_game_data).-# Applied after the two per-game hunks above, so the text it replaces is what they produce.-MAIN_M_NODATA_FN = '// DM_ROMFS plus the save/temp folders that follow its location (the per-game layout only when the\n// files came from Documents/games/<id>/). Returns NO when there is no game data yet — not fatal:\n// the launcher comes up all the same and its Game data section is where a location gets picked\n// (a transfer skipped on the Mac, or data on an external drive), and dm_locate_game_data() asks\n// again when the player presses Play. `force` lets the Play-time re-location override what boot\n// set: a location picked in the launcher this session must win, while an env file\'s DM_ROMFS /\n// DM_SAVE / DM_TEMP (set before this runs, kept only when absent) keeps winning at boot.\nstatic int set_data_env(NSString *romfs, BOOL force) {\n if (!romfs) return 0;\n NSFileManager *fm = NSFileManager.defaultManager;\n NSString *doc = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];\n fprintf(stderr, "boot: game files %s\\n", romfs.fileSystemRepresentation);\n setenv("DM_ROMFS", romfs.fileSystemRepresentation, force);\n // Saves and scratch space: Documents/games/<id>/{save,temp} when the per-game layout is in use\n // (so two games in one app never share a save folder), else the old Documents/{save,temp}. An\n // env file still wins at boot — DM_SAVE/DM_TEMP set there are already in the environment and\n // setenv(..., 0) leaves them alone.\n NSString *gdir = game_dir_for(dm_profile()->id);\n // Tie the data folder to where the game files actually came from: if romfs_locate fell back to\n // Documents/romfs, the saves must stay beside it (a game folder without romfs is not in use).\n BOOL per_game = [romfs hasPrefix:gdir];\n NSString *save_dir = per_game ? [gdir stringByAppendingPathComponent:@"save"] : [doc stringByAppendingPathComponent:@"save"];\n NSString *temp_dir = per_game ? [gdir stringByAppendingPathComponent:@"temp"] : [doc stringByAppendingPathComponent:@"temp"];\n for (NSString *d in @[save_dir, temp_dir]) [fm createDirectoryAtPath:d withIntermediateDirectories:YES attributes:nil error:nil];\n setenv("DM_SAVE", save_dir.fileSystemRepresentation, force);\n setenv("DM_TEMP", temp_dir.fileSystemRepresentation, force);\n if (per_game) fprintf(stderr, "boot: per-game data folder %s\\n", gdir.fileSystemRepresentation);\n return 1;\n}\n\n// front_ios.m calls this from the launcher\'s Play: (re)decide where the game data is — a location\n// picked in the launcher this session takes effect at once — and NO when there still is none, so\n// the launcher comes back instead of the game failing inside the host.\nint dm_locate_game_data(void) { return set_data_env(romfs_locate(), YES); }\n\n'-MAIN_M_NODATA_BOOT = (' NSString *romfs = romfs_locate();\n if (!romfs) { fprintf(stderr, "boot: game files not found (Documents/romfs.img, Documents/romfs or <App>/romfs)\\n"); return 0; }\n fprintf(stderr, "boot: game files %s\\n", romfs.fileSystemRepresentation);\n setenv("DM_ROMFS", romfs.fileSystemRepresentation, 0);\n // Saves and scratch space: Documents/games/<id>/{save,temp} when the per-game layout is in use\n // (so two games in one app never share a save folder), else the old Documents/{save,temp}. An\n // env file still wins — DM_SAVE/DM_TEMP set there are already in the environment and\n // setenv(..., 0) leaves them alone.\n NSString *gdir = game_dir_for(dm_profile()->id);\n // Tie the data folder to where the game files actually came from: if romfs_locate fell back to\n // Documents/romfs, the saves must stay beside it (a game folder without romfs is not in use).\n BOOL per_game = [romfs hasPrefix:gdir];\n NSString *save_dir = per_game ? [gdir stringByAppendingPathComponent:@"save"] : [doc stringByAppendingPathComponent:@"save"];\n NSString *temp_dir = per_game ? [gdir stringByAppendingPathComponent:@"temp"] : [doc stringByAppendingPathComponent:@"temp"];\n for (NSString *d in @[save_dir, temp_dir]) [fm createDirectoryAtPath:d withIntermediateDirectories:YES attributes:nil error:nil];\n setenv("DM_SAVE", save_dir.fileSystemRepresentation, 0);\n setenv("DM_TEMP", temp_dir.fileSystemRepresentation, 0);\n if (per_game) fprintf(stderr, "boot: per-game data folder %s\\n", gdir.fileSystemRepresentation);\n',-' // No game data yet is not fatal: the launcher comes up all the same, and its Game data section\n // is where a location gets picked; dm_locate_game_data() looks again when Play is pressed.\n NSString *gdir = game_dir_for(dm_profile()->id);\n NSString *romfs = romfs_locate();\n BOOL per_game = [romfs hasPrefix:gdir]; // messaging nil is NO here: no data means the shared layout\n if (!set_data_env(romfs, NO)) fprintf(stderr, "boot: no game data yet (Documents/romfs.img, Documents/romfs or <App>/romfs); the launcher asks for it\\n");\n')--def _identity(s):- """The fork's main.m texts with upstream's romfs.id check (seedds/nxnative#493) in them: Documents/romfs.img must carry- the identity the build asks for, and a boot without game data says why when it does not"""- s = s.replace(' if (romfs_image_complete(img)) {', ' if (romfs_image_complete(img) && romfs_identity_accepts(img)) {')- s = s.replace('if (!romfs) { fprintf(stderr, "boot: game files not found', 'if (!romfs) { romfs_identity_report(doc); fprintf(stderr, "boot: game files not found')- return s.replace('if (!set_data_env(romfs, NO)) fprintf(stderr, "boot: no game data yet (Documents/romfs.img, Documents/romfs or <App>/romfs); the launcher asks for it\\n");',- 'if (!set_data_env(romfs, NO)) { if (!romfs) romfs_identity_report(doc); // a slim build says why its romfs.img was not used\n fprintf(stderr, "boot: no game data yet (Documents/romfs.img, Documents/romfs or <App>/romfs); the launcher asks for it\\n"); }')--def patch_main_m(t):- """romfs_locate + the per-game data layout in dm/ios/Sources/main.m.-- Two replacements, both anchored on upstream text:- - romfs_locate becomes romfs_dir_ok() + game_dir_for() + a locate that tries- Documents/games/<id>/romfs first (the launcher-style layout, which is also what lets the- game data sit in a folder the Files app exposes on an external drive).- - the DM_ROMFS/DM_SAVE/DM_TEMP/DM_MSL_DIR block gains the per-game folders and the shader- library fallback.- A missing anchor is an error: these are the fork's only two changes here.- """- P = [- # the runtime profile replaced the compiled header: hle_profile.h gives dm_profile(), which- # the marker check below reads (merged with the stage-2 experiment, 21fbba1)- ('runtime profile include',- ('#include "game_profile.h" // game profile constants (the RomFS marker path)',- '#include "hle_profile.h" // the runtime game profile (DM_PROFILE): the RomFS marker path comes from it')),- # the Files-app pick (DataBookmark.m): romfs_locate asks it before anything else- ('picked data include',- ('#include "romfs_image.h"\n', '#include "romfs_image.h"\n#include "DataBookmark.h"\n')),- # The sync source carries upstream's identity check in this line (337186cf); the last- # sync base has the plain form. Pick the anchor text by which one the file has.- ('romfs per-game', (MAIN_M_ROMFS[0] if 'romfs_identity_accepts' in t else- MAIN_M_ROMFS[0].replace(- 'if (romfs_image_complete(img) && romfs_identity_accepts(img)) {',- 'if (romfs_image_complete(img)) {'),- MAIN_M_ROMFS[1])),- ('per-game data dirs', MAIN_M_ENV),- ]- if 'static int set_data_env' in t: return skip('main.m (already patched)') or t- # Upstream's identity check (romfs.id, 337186cf) added a call to the `if (!romfs)` line; the- # last sync base has the plain form. Pick the boot hunk's old text by which one this file- # carries, so both the sync source and the base patch cleanly.- boot_old, boot_new = MAIN_M_NODATA_BOOT- if 'romfs_identity_report(doc); fprintf(stderr, "boot: game files not found' in t:- boot_old = boot_old.replace(- 'if (!romfs) { fprintf(stderr, "boot: game files not found',- 'if (!romfs) { romfs_identity_report(doc); fprintf(stderr, "boot: game files not found')- P += [- ('set_data_env', ('// Boot prerequisites (done before', MAIN_M_NODATA_FN + '// Boot prerequisites (done before')),- ('no game data at boot', (boot_old, boot_new)),- ]- if 'static void romfs_identity_report' in t: # upstream's slim-IPA identity check (#493): the fork's text carries it through- P = [(n, (_identity(o), _identity(w))) for n, (o, w) in P]- for name, (old, new) in P:- if new in t:- skip(f'main.m {name} (already patched)')- continue- if old not in t:- fail(f'dm/ios/Sources/main.m: patch "{name}" anchor missing (upstream moved romfs_locate '- 'or the environment block)')- t = t.replace(old, new, 1)- done(f'main.m {name}')- return t--def patch_front_mac(t):- """DM_KEYMAP and DM_PAD_MAP in the Mac front end, from upstream seedds/nxnative#386.-- The launcher's Controls page (Settings → Controls) writes these two variables, but until this- landed here nothing on this side read them: the page moved the fields and the game kept its- default keys. Upstream's #386 is still open, so the change has to live here as a carrier: the- tables below are its hunks, and the day #386 merges, a sync brings them in whole and this- patcher finds every anchor already applied (or, if upstream rewords one, fails loudly).-- input_map.h is fork-only for now (upstream's file, but shipped here by this commit) and is in- OURS so a sync cannot take it away.- """- if 'key_map_default(&g_keys)' in t: return skip('front_mac.m DM_KEYMAP (already patched)')- P = [- ('key map comment',- '// Key map (Nintendo layout): WASD left stick, arrow keys D-pad, J=A K=B U=X I=Y, Q=L E=R, Z=ZL C=ZR, F=press left stick G=press right stick, Return=+ Tab=−, Space=shake the controller.\n',- '// Key map (Nintendo layout): WASD left stick, arrow keys D-pad, J=A K=B U=X I=Y, Q=L E=R, Z=ZL C=ZR, F=press left stick G=press right stick, Return=+ Tab=−, Space=shake the controller;\n'- "// DM_KEYMAP moves a function to another key (the right stick too), DM_PAD_MAP changes what a controller's buttons send (input_map.h).\n"),- ('input_map include',- '#include "pad_slots.h"\n',- '#include "pad_slots.h"\n#include "input_map.h"\n'),- ('the four stick flags',- 'static int g_w, g_a, g_s, g_d;\n',- ''),- ('key state',- 'static void push(void) {\n int32_t lx = (g_d - g_a) * 32767, ly = (g_w - g_s) * 32767;\n dm_input_set(g_btn, lx, ly, 0, 0);\n}\n'- 'static int key_bit(unsigned short code) {\n'- ' switch (code) {\n'- ' case 38: return 0; case 40: return 1; case 32: return 2; case 34: return 3; // J K U I → A B X Y\n'- ' case 3: return 4; case 5: return 5; // F G → press stick\n'- ' case 12: return 6; case 14: return 7; case 6: return 8; case 8: return 9; // Q E Z C → L R ZL ZR\n'- ' case 36: return 10; case 48: return 11; // Return Tab → + −\n'- ' case 123: return 12; case 126: return 13; case 124: return 14; case 125: return 15; // ← ↑ → ↓\n'- ' }\n'- ' return -1;\n'- '}\n',- '// Keyboard: each key holds one function of the key map (input_map.h; DM_KEYMAP changes it), the held functions make the buttons and both sticks\n'- 'static key_map g_keys;\n'- 'static uint32_t g_held_fn; // bit f: a key holding function f is down\n'- 'static void push(void) {\n'- ' uint32_t h = g_held_fn;\n'- ' #define D(f) ((int32_t)(h >> (f) & 1))\n'- ' dm_input_set(g_btn, (D(IM_LRIGHT) - D(IM_LLEFT)) * 32767, (D(IM_LUP) - D(IM_LDOWN)) * 32767, (D(IM_RRIGHT) - D(IM_RLEFT)) * 32767, (D(IM_RUP) - D(IM_RDOWN)) * 32767);\n'- ' #undef D\n'- '}\n'),- ('on_key',- ' unsigned short c = e.keyCode;\n'- ' switch (c) { case 13: g_w = down; break; case 0: g_a = down; break; case 1: g_s = down; break; case 2: g_d = down; break; }\n'- ' int b = key_bit(c);\n'- ' uint64_t m = b >= 0 ? 1ull << b : c == 49 ? DM_BTN_SHAKE : 0; // Space: shaken while held\n'- ' g_btn = down ? (g_btn | m) : (g_btn & ~m);\n',- ' int f = key_map_fn(&g_keys, e.keyCode); if (f < 0) return;\n'- ' g_held_fn = down ? (g_held_fn | 1u << f) : (g_held_fn & ~(1u << f));\n'- ' g_btn = (g_held_fn & 0xffff) | (g_held_fn >> IM_SHAKE & 1 ? DM_BTN_SHAKE : 0);\n'),- ('pad map state',- 'static int g_merge, g_kbd_own;\n',- 'static int g_merge, g_kbd_own;\nstatic pad_map g_padmap; // DM_PAD_MAP (input_map.h): what each button sends, applied to every controller\n'),- ('pad map apply',- ' #undef K\n dm_pad_set_player(p, m, pad_axis(g.leftThumbstick.xAxis.value), pad_axis(g.leftThumbstick.yAxis.value), pad_axis(g.rightThumbstick.xAxis.value), pad_axis(g.rightThumbstick.yAxis.value));\n',- ' #undef K\n m = pad_map_apply(&g_padmap, m);\n dm_pad_set_player(p, m, pad_axis(g.leftThumbstick.xAxis.value), pad_axis(g.leftThumbstick.yAxis.value), pad_axis(g.rightThumbstick.xAxis.value), pad_axis(g.rightThumbstick.yAxis.value));\n'),- ('start: read the two variables',- ' const char *e = getenv("DM_PAD_MERGE"); g_merge = e && atoi(e);\n',- ' key_map_default(&g_keys); pad_map_default(&g_padmap);\n'- ' const char *km = getenv("DM_KEYMAP"), *pm = getenv("DM_PAD_MAP");\n'- ' if (km && *km) { int bad = key_map_parse(&g_keys, km); LOG("front end: keyboard map from DM_KEYMAP (%s)%s", km, bad ? ", malformed entries left out" : ""); }\n'- ' if (pm && *pm) { int bad = pad_map_parse(&g_padmap, pm); LOG("front end: controller buttons from DM_PAD_MAP (%s)%s", pm, bad ? ", malformed entries left out" : ""); }\n'- ' const char *e = getenv("DM_PAD_MERGE"); g_merge = e && atoi(e);\n'),- # two call sites, one per indentation: input_release (4 spaces) and front_text_input (8)- ('release on focus loss',- ' g_btn = 0; g_w = g_a = g_s = g_d = 0; push();\n if (g_mouse_down)',- ' g_btn = 0; g_held_fn = 0; push();\n if (g_mouse_down)'),- ('release for the text box',- ' g_btn = 0; g_w = g_a = g_s = g_d = 0; push();\n dm_touch_set(NULL, 0);',- ' g_btn = 0; g_held_fn = 0; push();\n dm_touch_set(NULL, 0);'),- ]- for name, old, new in P:- # A deletion entry has an empty `new`, which is "in" every string, so it would report- # "already patched" on the first run and never delete anything. It is applied when its- # `old` is gone instead.- if (old not in t) if not new else (new in t):- skip(f'front_mac.m {name} (already patched)')- continue- if old not in t:- fail(f'dm/host/front_mac.m: patch "{name}" anchor missing (upstream moved the key handling; '- 'merge seedds/nxnative#386 by hand)')- t = t.replace(old, new, 1)- done(f'front_mac.m {name}')- return t--def patch_dm_h(t):- """dm.h pulls in hle_profile.h, so every host source can call dm_profile().-- The runtime-profile work (merged from the stage-2 experiment, 21fbba1) turned the compiled- game_profile.h constants into values read from a profile at start, and dm_profile() is how- every source reaches them — but only hle_svc.c and hle_profile.c included the header. It- compiled then because the other callers were older upstream revisions; after a sync rewrote- them, loader.c, hle_fs.c, hle_fpslock.c and five more failed with "call to undeclared function- dm_profile". Including it from dm.h (which they all include) is what keeps the accessor in- scope without touching each file, and this entry is what keeps it in scope across a sync.- """- if 'hle_profile.h' in t: return skip('dm.h hle_profile.h (already patched)')- old = '#include "game_profile.h" // constants of the current game profile'- if old not in t: fail('dm/host/dm.h: game_profile.h include anchor missing')- line = next(ln for ln in t.splitlines() if ln.startswith(old))- return done('dm.h hle_profile.h', t.replace(line, line + '\n#include "hle_profile.h"'- ' // the runtime profile (DM_PROFILE): every constant above can also come from it;'- ' dm_profile() is the accessor', 1))---ROMFS_TEST_STUB = ('typedef struct { const char *id, *romfs_marker; } fixture_profile; /* the fork reads both from the runtime profile */\n'- 'static const fixture_profile *dm_profile(void) { static const fixture_profile p = {"0100000000000000", "marker"}; return &p; }\n')--def patch_test_romfs_startup(t):- """The test compiles main.m's RomFS locator alone, with a stub for each name it needs. The fork's- locator reads the game's id and romfs_marker through dm_profile() (the runtime profile, patch_main_m),- which upstream's stubs do not provide: clang stopped on "call to undeclared function dm_profile".- The fixture gets a dm_profile() with the marker the test already uses. The same locator asks- dm_picked_data_path() (DataBookmark.m, the Files-app pick), so the fixture answers it from a variable- (argv[4]) and a test puts the player's choice anywhere on disk."""- if 'fixture_profile' in t: skip('test_romfs_startup dm_profile stub (already patched)')- else:- old = "#define DM_GAME_ROMFS_MARKER \"marker\"\\n'"- if old not in t: fail('dm/ios/tests/test_romfs_startup.py: the fixture preamble anchor is missing'); return t- t = done('test_romfs_startup dm_profile stub', t.replace(old, old + "\n " + repr(ROMFS_TEST_STUB), 1))- return anchored('dm/ios/tests/test_romfs_startup.py', PICKED_EDITS)(t)--def patch_ipa_unsigned(t):- """Upstream's unsigned-IPA tests assert upstream's default: the game files and the DLC are- packed into the package. The fork's default is the slim package (patch_build_ipa: the app reads- Documents/games/<id>/), with DM_FULL_ROMFS=1 to pack them. The tests are adapted to it rather- than skipped: they still check the mapping rules, from the fork's starting point."""- P = [(- """ def test_game_files_are_packed_by_default(self):- names = self.pack()- self.assertIn('Payload/DmIOS.app/romfs/marker', names)- self.assertIn('Payload/DmIOS.app/aoc/0/file', names)""",- """ def test_game_files_are_not_packed_by_default(self):- # The fork ships a slim IPA by default: the app reads Documents/games/<id>/ (patch_build_ipa).- names = self.pack()- self.assertFalse([n for n in names if '/romfs' in n or '/aoc' in n])-- def test_full_romfs_packs_the_game_files(self):- names = self.pack(DM_FULL_ROMFS='1')- self.assertIn('Payload/DmIOS.app/romfs/marker', names)- self.assertIn('Payload/DmIOS.app/aoc/0/file', names)"""),- (- """ self.assertIn('Payload/DmIOS.app/aoc/0/file', names) # add-on content has no place outside the app yet""",- """ self.assertFalse([n for n in names if '/aoc' in n], 'the fork copies add-on content beside the game data')"""),- (- """ names = self.pack(image=True, identity=got) # bundle: exactly as before- self.assertIn('Payload/DmIOS.app/romfs.img', names); self.assertNotIn('Payload/DmIOS.app/romfs.id', names); self.assertIsNone(got[0][0])""",- """ names = self.pack(image=True, identity=got) # the fork's default: the image stays out, its identity goes in- self.assertNotIn('Payload/DmIOS.app/romfs.img', names); self.assertIn('Payload/DmIOS.app/romfs.id', names); self.assertIsNotNone(got[0][0])"""),- ]- for old, new in P:- if new in t:- skip('test_ipa_unsigned.py (already patched)'); return t- if old not in t:- fail('dm/ios/tests/test_ipa_unsigned.py: a packing-default test is not in the shape the fork adapts')- t = t.replace(old, new, 1)- done('test_ipa_unsigned.py (slim default)')- return t--def patch_test_profile_pack(t):- """Upstream packs the RomFS into the IPA; the fork's default is the slim package (patch_build_ipa:- DM_FULL_ROMFS=1 packs it), so the test checks that the RomFS stays out instead."""- if 'slim package' in t: return skip('test_profile_pack slim IPA (already patched)')- old = " self.assertEqual(archive.read('Payload/DmIOS.app/romfs/marker'), b'romfs')"- if old not in t: fail('dm/ios/tests/test_profile_pack.py: the RomFS assertion anchor is missing'); return t- new = (" # the fork's slim package: the RomFS stays out of the IPA (DM_FULL_ROMFS=1 packs it)\n"- " self.assertFalse(any(n.startswith('Payload/DmIOS.app/romfs') for n in names))")- return done('test_profile_pack slim IPA', t.replace(old, new, 1))---# The switches only the fork's code reads, with their rows in docs/env_switches.tsv (name, class, meaning)-FORK_SWITCHES = {- 'DM_FULL_ROMFS': ('diagnostic', '`=1` in `build_ipa.sh` packs the game data into the IPA as it did before the slim package; the default leaves it in `Documents/games/<id>/` (`romfs.img`, `aoc/<index>.img`) and the DLC beside it. Only for small games — a full package of a large one is many GB and iOS refuses it (`PackageExtractionFailed`)'),- 'DM_PROFILE': ('path', '`=<file>`: the runtime game profile (layout, switches, tables) the host reads at start, which is how one host binary serves every game (the launcher architecture); the compiled `game_profile.h` stays the fallback, and `DM_PROF_<key>` overrides sit on top of it (`hle_profile.h`)'),- # seedds/nxnative#386 (the Controls page); the rows go when it merges and the table comes from upstream- 'DM_KEYMAP': ('player', 'Mac keyboard: `<name>=<key code>,…` puts a button (`A` … `Down`), a stick direction (`LUp` … `RRight`) or `Shake` on another key (macOS virtual key code, or `none`); one key holds one function (`input_map.h`)'),- 'DM_PAD_MAP': ('player', 'Mac controllers: `<name>=<name>,…` makes the button that sends the first by default send the second (or `none`), e.g. `A=B,B=A` swaps them (`input_map.h`)'),-}--def patch_env_switches(t):- """docs/env_switches.tsv is upstream's table of every switch the code reads, and test_env_switches.py- fails when a switch the code reads has no row. The fork's own switches (FORK_SWITCHES) lose their rows- whenever upstream rewrites the table; they go back in name order."""- rows = t.rstrip('\n').split('\n')- have = {r.split('\t', 1)[0] for r in rows}- missing = [n for n in FORK_SWITCHES if n not in have]- if not missing: return skip('env_switches.tsv fork rows (already patched)')- head, body = rows[0], rows[1:] + [f'{n}\t{c}\t{m}' for n, (c, m) in FORK_SWITCHES.items() if n in missing]- return done('env_switches.tsv fork rows: ' + ' '.join(missing), '\n'.join([head] + sorted(body, key=lambda r: r.split('\t', 1)[0])) + '\n')---def patch_hades2(t):- """The fork's Hades II profile carries what we verified end to end — the update (v1,- 1.0.137848) registered and packed, the measured NVN texture slots (35: slot 34 lies past the- translator's built-in 32) and the widescreen investigation notes — and upstream's is v0-only.- The fork's full file ships beside it as game.fork.tsv and is restored wholesale when the- sync loses the marker; if upstream reworks the profile, merge by hand."""- if 'build v1 1.0.137848' in t: return skip('Hades II profile (already patched)')- fork = (REPO / 'dm/games/0100A00019DE0000/game.fork.tsv').read_text(encoding='utf-8')- say(' … restoring the fork\'s Hades II profile (update v1, measured slots, notes)')- return done('Hades II profile v1', fork)--LAUNCHER_HELPERS = r'''static int dir_has_entries(const char *path) { // anything inside at all (a save folder, a log folder)- DIR *d = opendir(path); if (!d) return 0;- struct dirent *e; int any = 0;- while ((e = readdir(d))) if (strcmp(e->d_name, ".") && strcmp(e->d_name, "..")) { any = 1; break; }- closedir(d); return any;-}--static int copy_file(const char *from, const char *to) {- FILE *in = fopen(from, "rb"); if (!in) return 0;- FILE *out = fopen(to, "wb"); if (!out) { fclose(in); return 0; }- char buf[1 << 16]; size_t n; int ok = 1;- while ((n = fread(buf, 1, sizeof buf, in)) > 0) if (fwrite(buf, 1, n, out) != n) { ok = 0; break; }- if (ferror(in)) ok = 0;- fclose(in); if (fclose(out)) ok = 0;- if (!ok) unlink(to);- return ok;-}--/// Recursive copy for the one-time migration of a save folder. Symlinks are followed (a save is-/// plain files); a file that already exists is left alone, so a half-finished copy can be resumed.-static void copy_tree(const char *from, const char *to) {- mkdirs(to);- DIR *d = opendir(from); if (!d) return;- struct dirent *e;- while ((e = readdir(d))) {- if (!strcmp(e->d_name, ".") || !strcmp(e->d_name, "..")) continue;- char a[PATH_MAX], b[PATH_MAX];- snprintf(a, sizeof a, "%s/%s", from, e->d_name);- snprintf(b, sizeof b, "%s/%s", to, e->d_name);- struct stat st;- if (stat(a, &st)) continue;- if (S_ISDIR(st.st_mode)) copy_tree(a, b);- else if (S_ISREG(st.st_mode) && access(b, F_OK)) copy_file(a, b);- }- closedir(d);-}--'''--LAUNCHER_BLOCK = r''' // Saves and logs beside the game, not under ~/Library: a library folder the user can move or- // keep on an external drive has to carry its saves with it, or they are effectively lost the- // moment the folder moves (the files are still in ~/Library, where nobody looks for them).- //- // The library root is the folder the app sits in, when that folder also holds games/ — the- // layout the Mac front end writes (<out>/<id>.app, <out>/games/<id>/romfs.img). A bundle- // copied somewhere else keeps the old ~/Library paths, so nothing breaks for a user who never- // used the launcher's folder.- {- char appdir[PATH_MAX]; snprintf(appdir, sizeof appdir, "%s", exe);- // Four cuts: <…>/<id>.app/Contents/MacOS/<launcher> → MacOS → Contents → <id>.app → the folder- // holding it. Three landed on the .app itself, so the probe looked for <id>.app/games — which- // never exists — and the migration never ran (the report: saves stayed in ~/Library).- *strrchr(appdir, '/') = 0; *strrchr(appdir, '/') = 0;- *strrchr(appdir, '/') = 0; *strrchr(appdir, '/') = 0;- // The marker file the Mac front end writes beside the .app (a dot file, so the Finder hides- // it): this folder is a game library, and the game's saves and log live in it. DM_ROOT (the- // learned shader state, env.txt), temp/ and everything else stay under ~/Library — only- // what is needed and reused comes along, so the library folder stays lean.- char probe[PATH_MAX]; snprintf(probe, sizeof probe, "%s/.nx2apple-library", appdir);- if (!stat(probe, &st)) {- snprintf(save, sizeof save, "%s/save/%s", appdir, id);- snprintf(logs, sizeof logs, "%s/log", appdir);- // First run after this change: bring the old saves across rather than starting the- // player on an empty save slot. Copied, not moved — an older build of the same app- // still reads the old place, and a copy is cheap next to a save.- char oldsave[PATH_MAX], oldlog[PATH_MAX];- snprintf(oldsave, sizeof oldsave, "%s/save", sup);- snprintf(oldlog, sizeof oldlog, "%s/Library/Logs/nxnative/%s.log", home, id);- mkdirs(save); mkdirs(logs);- if (dir_has_entries(oldsave) && !dir_has_entries(save)) {- copy_tree(oldsave, save);- fprintf(stderr, "launcher: saves copied from %s to %s (they now live with the game)\n", oldsave, save);- }- // The previous session's log becomes the .prev.log, as the rotation below would have- // it: the .log itself is opened fresh right after, and copying into it would be- // truncated away by that open.- char newprev[PATH_MAX]; snprintf(newprev, sizeof newprev, "%s/%s.prev.log", logs, id);- // Explicit compares, not !stat(): stat() returns -1 when the file is missing, which is- // truthy — reading "!" as "does not exist" here inverted the condition and skipped the- // copy (found by the end-to-end test below).- if (stat(oldlog, &st) == 0 && stat(newprev, &st) != 0) {- if (copy_file(oldlog, newprev)) fprintf(stderr, "launcher: the previous log was copied from %s\n", oldlog);- }- }- }-'''--LAUNCHER_SAY = r''' // Say where this game reads and writes, on every start: a player checking whether their saves- // moved with the game should not have to know the migration rules.- fprintf(stderr, "launcher: saves %s\nlauncher: log %s\n", save, log);-'''--LAUNCHER_SWIFT_SECTION = r'''/// Where this game's data comes from, and a picker to change it.-///-/// The app can only read files it owns unless the player hands it a location through the document-/// picker — so a game's RomFS kept on an external drive or in iCloud Drive could not be used at all-/// before this. Picking an image (romfs.img) or a folder stores a bookmark (DataBookmark.m), and-/// romfs_locate() prefers it from the next launch on.-private struct GameDataSection: View {- @State private var picked: String = ""- @State private var note: String = ""- @State private var picking = false-- var body: some View {- Section {- HStack {- Text("Game data")- Spacer()- Text(picked.isEmpty ? "This app's folder" : (picked as NSString).lastPathComponent)- .foregroundStyle(.secondary).lineLimit(1).truncationMode(.middle)- }- Button(picked.isEmpty ? "Choose game data…" : "Choose a different location…") { picking = true }- if !picked.isEmpty {- Button("Use the app's own data again", role: .destructive) {- dm_clear_picked_data(); refresh(); note = ""- }- }- } footer: {- Text(note.isEmpty- ? "Pick the game's romfs.img or its RomFS folder — an external drive or iCloud Drive works. The app remembers the choice; a re-signed build asks once more."- : note)- }- .sheet(isPresented: $picking) {- DocumentPicker { url in- picking = false- if dm_store_picked_data(url) {- note = "Saved. The game uses this location when you press Play."- refresh()- } else {- note = "That location could not be remembered — try a different one."- }- } onCancel: { picking = false }- }- .onAppear(perform: refresh)- }-- private func refresh() {- // ObjC BOOL* is ObjCBool, not Bool: the bookmark header takes an indirect flag for- // "the bookmark exists but does not resolve under this signature", which is the one- // state worth telling the player about.- var stale: ObjCBool = false- picked = dm_picked_data_path(&stale) ?? ""- if stale.boolValue && picked.isEmpty {- note = "The location you picked before is no longer readable (the app was signed differently). Please choose it again."- }- }-}--/// UIDocumentPickerViewController for files and folders, in the two callbacks a SwiftUI sheet wants.-private struct DocumentPicker: UIViewControllerRepresentable {- let onPick: (URL) -> Void- let onCancel: () -> Void-- func makeUIViewController(context: Context) -> UIDocumentPickerViewController {- // .open (not .import): the file stays where it is and the bookmark keeps pointing at it,- // which is the whole point — an import would copy 16 GB into the app's container.- let picker = UIDocumentPickerViewController(forOpeningContentTypes: [.item], asCopy: false)- picker.allowsMultipleSelection = false- picker.delegate = context.coordinator- return picker- }-- func updateUIViewController(_ vc: UIDocumentPickerViewController, context: Context) {}-- func makeCoordinator() -> Coordinator { Coordinator(onPick: onPick, onCancel: onCancel) }-- final class Coordinator: NSObject, UIDocumentPickerDelegate {- let onPick: (URL) -> Void- let onCancel: () -> Void- init(onPick: @escaping (URL) -> Void, onCancel: @escaping () -> Void) {- self.onPick = onPick; self.onCancel = onCancel- }- func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {- if let url = urls.first { onPick(url) } else { onCancel() }- }- func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) { onCancel() }- }-}--'''--ENV_SWITCHES_VERIFY = r'''def verify_texts(paths):- """Every DM_* name these files mention must be one the sources read (docs/env_switches.tsv), or a- family a row documents: DM_PROF_<key> builds its name at run time, so no row can exist per member- and the table names the family instead. A name ending in _ is a family prefix itself.-- Written after two replies in one day recommended DM_LOG_UEMALLOC and DM_NVN_ALIAS_TRACE, neither- of which exists: a name recalled from memory rather than read out of the table. Run this over a- draft before posting it.- """- known, family = set(), set()- if TABLE.exists():- for l in TABLE.read_text().split('\n'):- f = l.split('\t')- if not f or not f[0].startswith('DM_'): continue- known.add(f[0])- for m in re.finditer(r'(' + NAME + r')_[<*]', '\t'.join(f[1:])):- family.add(m.group(1))- bad = []- for p in paths:- for n in sorted(set(re.findall(NAME, Path(p).read_text(encoding='utf-8', errors='replace')))):- if n.endswith('_'): continue # a family prefix itself ("DM_NVN_*")- if n not in known and not any(k.startswith(n + '_') for k in known) and n not in family:- bad.append((p, n)) # unknown, and no row starts with it- return bad, len(known)--'''--ENV_SWITCHES_MAIN = r''' if sys.argv[1:2] == ['--verify']:- problems, known = verify_texts(sys.argv[2:])- for p, n in problems: print(f'{p}: {n} is not a switch the sources read')- print(f'{len(problems)} unknown name(s) against {known} known switches')- raise SystemExit(1 if problems else 0)-'''--TEST_ENV_DOC = r'''A switch the code reads that the table does not list, a row for a switch nothing reads any more, or a row without a meaning fails here.--`--verify <file>...` checks a text instead: every DM_* it names must be a real switch. It exists because two replies wrote DM_LOG_UEMALLOC and DM_NVN_ALIAS_TRACE from memory in-one day, and neither is a switch — a reader who trusts them wastes a run and learns nothing.'''--TEST_ENV_TESTS = r''' def test_verify_accepts_a_real_switch_and_rejects_an_invented_one(self):- with tempfile.TemporaryDirectory() as d:- good = Path(d, 'good.md'); good.write_text('Set `DM_IMPORTS=1` to see the imports.\n')- r = subprocess.run([sys.executable, str(REPO / 'dm/tools/env_switches.py'), '--verify', str(good)], cwd=REPO, capture_output=True, text=True)- self.assertEqual(r.returncode, 0, r.stdout + r.stderr)-- bad = Path(d, 'bad.md'); bad.write_text('Set `DM_LOG_UEMALLOC=1` to see the allocations.\n')- r = subprocess.run([sys.executable, str(REPO / 'dm/tools/env_switches.py'), '--verify', str(bad)], cwd=REPO, capture_output=True, text=True)- self.assertEqual(r.returncode, 1, 'an invented switch must fail the check')- self.assertIn('@UEM@', r.stdout)-- def test_verify_ignores_a_prefix_and_a_family(self):- with tempfile.TemporaryDirectory() as d:- f = Path(d, 'prefixes.md'); f.write_text('`DM_PROF_<key>` overrides; `DM_NVN_*` are the graphics ones; `DM_MEMSTAT` is real.\n')- r = subprocess.run([sys.executable, str(REPO / 'dm/tools/env_switches.py'), '--verify', str(f)], cwd=REPO, capture_output=True, text=True)- self.assertEqual(r.returncode, 0, r.stdout + r.stderr)-'''.replace('@UEM@', 'DM_LOG_' + 'UEMALLOC') # not spelled out: env_switches.py would read a quoted name in this file as a switch--TEST_PICKED_METHOD = r''' def test_the_location_the_player_picked_wins_over_everything(self):- """The Files-app pick (DataBookmark): an image, a folder holding one, or a plain tree."""- with tempfile.TemporaryDirectory() as temporary:- root = Path(temporary); doc = root / 'Documents'; doc.mkdir()- tmp = root / 'temp'; tmp.mkdir(); bundle = root / 'App'; bundle.mkdir()- source = root / 'source'; source.mkdir(); (source / 'marker').write_text('resource')- image.pack(source, bundle / 'romfs.img')- # something the app would otherwise use, so "wins" means something- image.pack(source, doc / 'romfs.img')- external = root / 'external'; external.mkdir()-- def locate(picked=None):- argv = [str(self.locator), str(doc), str(tmp), str(bundle)] + ([str(picked)] if picked else [])- result = subprocess.run(argv, capture_output=True, text=True)- self.assertEqual(result.returncode, 0, result.stderr)- return result.stdout.strip()-- # 1. the picked path IS the image- image.pack(source, external / 'mine.img')- self.assertEqual(locate(external / 'mine.img'), str(external / 'mine.img'))- # 2. the picked path is a folder holding romfs.img- image.pack(source, external / 'romfs.img')- self.assertEqual(locate(external), str(external / 'romfs.img'))- # 3. the picked path is a plain RomFS tree- (external / 'romfs.img').unlink(); (external / 'marker').write_text('resource')- self.assertEqual(locate(external), str(external))- # 4. a picked path holding none of this game's data falls through to the app's own copy- empty = root / 'empty'; empty.mkdir()- self.assertEqual(locate(empty), str(doc / 'romfs.img'))'''--# ---- Fork edits that had no protection until issue #92. Each was made by hand in a vendored file the-# sync takes from upstream whenever upstream changes it; each is now a patcher, written against the-# text of seedds/nxnative main (checked with scripts/tests/test_sync_patchers.py), with its own marker. ------def anchored(path, edits):- """A patcher from (name, marker, old, new) edits: `new` replaces the one occurrence of `old`, and an- edit whose marker is already in the text is skipped (idempotent). An anchor that is missing or- occurs more than once fails the run loudly."""- def patch(t):- for name, marker, old, new in edits:- if marker in t:- skip(f'{path} {name} (already patched)'); continue- if t.count(old) != 1:- fail(f'{path}: patch "{name}" anchor {"missing" if old not in t else "not unique"}: {old[:70]!r}')- t = t.replace(old, new, 1)- done(f'{path} {name}')- return t- return patch--# The Mac launcher's library-folder saves and log (c7ea1f56, 0deafaf5, 2b7e9e89, 0f779f5e). Temporary:-# seedds/nxnative#460 adds `dataFolder` (and DM_SAVE / DM_LOG_DIR relative to the app), which does the-# same job properly (it moves more than the save and the log, and needs no marker file). When #460 is in-# the fork, this patcher goes and the front end writes the preference per app instead.-LAUNCHER_C = 'dm/mac/launcher.c'-patch_launcher_c = anchored(LAUNCHER_C, [- ('dirent include', '<dirent.h>', '#include <sys/stat.h>\n', '#include <sys/stat.h>\n#include <dirent.h>\n'),- ('copy helpers', 'static int dir_has_entries',- 'static void env_file(const char *path) {', LAUNCHER_HELPERS + 'static void env_file(const char *path) {'),- ('library folder', '.nx2apple-library',- ' snprintf(logs, sizeof logs, "%s/Library/Logs/nxnative", home);\n',- ' snprintf(logs, sizeof logs, "%s/Library/Logs/nxnative", home);\n' + LAUNCHER_BLOCK),- ('say where', 'launcher: saves %s',- ' mkdirs(save); mkdirs(temp); mkdirs(logs);\n rename(log, prev);\n',- ' mkdirs(save); mkdirs(temp); mkdirs(logs);\n' + LAUNCHER_SAY + ' rename(log, prev);\n'),-])--# The runtime game profile (73a89fb0): one host binary serves every game, so the constants the host took-# from game_profile.h at compile time (DM_GAME_<KEY> macros) are read through dm_profile() (hle_profile.c;-# without DM_PROFILE it falls back to the compiled macros, so behaviour is unchanged). Done as a-# substitution of the macro names, outside strings and comments, so it follows whatever upstream does-# around them (d8b8d642 rewrote mem_init_once and added DM_ALIAS_SIZE). A macro with no field in-# struct dm_profile (DM_GAME_STDALLOC_CAP) stays a compile-time constant.-PROFILE_FIELDS = {- 'DM_GAME_FPS_TARGET': 'fps_target', 'DM_GAME_ENV': 'genv', 'DM_GAME_ALLOC_BIG_ALIGN': 'alloc_big_align',- 'DM_GAME_PAD_LAYOUT': 'pad_layout', 'DM_GAME_MEM_RESERVE': 'mem_reserve', 'DM_GAME_MEM_ALIAS': 'mem_alias',- 'DM_GAME_MEM_STACK': 'mem_stack', 'DM_GAME_APP_POOL': 'app_pool', 'DM_GAME_MEM_USED': 'mem_used',- 'DM_GAME_MEM_MAP_LIMIT': 'mem_map_limit', 'DM_GAME_SYS_RESOURCE': 'sys_resource', 'DM_GAME_PROGRAM_ID': 'program_id',-}-# a string literal or a comment (kept as it is), else one of the macro names-_PROFILE_TOKEN = re.compile(r'("(?:[^"\\\n]|\\.)*"|//[^\n]*|/\*.*?\*/)|\b(' + '|'.join(PROFILE_FIELDS) + r')\b', re.S)-PROFILE_PATHS = ('dm/host/hle_svc.c', 'dm/host/hle_os.c', 'dm/host/hle_fpslock.c', 'dm/host/loader.c', 'dm/ios/Sources/DmGamepad.m')--def profile_patcher(path, paren=False):- """paren: wrap the replacement (hle_svc.c defines macros from them, RESERVE and the like)."""- def patch(t):- n = 0- def sub(m):- nonlocal n- if m.group(1): return m.group(1)- n += 1- r = 'dm_profile()->' + PROFILE_FIELDS[m.group(2)]- return f'({r})' if paren else r- out = _PROFILE_TOKEN.sub(sub, t)- if n: done(f'{path} runtime profile ({n} constants read through dm_profile())')- else: skip(f'{path} runtime profile (already patched)')- return out- return patch--patch_hle_svc = profile_patcher('dm/host/hle_svc.c', paren=True)-patch_hle_os = profile_patcher('dm/host/hle_os.c')-patch_hle_fpslock = profile_patcher('dm/host/hle_fpslock.c')-patch_loader = profile_patcher('dm/host/loader.c')-patch_dmgamepad = profile_patcher('dm/ios/Sources/DmGamepad.m')--# The Files-app "Game data" pick on the iPhone (DataBookmark.m, main.m's romfs_locate; main.m is patched-# by patch_main_m). Launcher.swift gets the section and the picker, project.yml the bridging header.-LAUNCHER_SWIFT = 'dm/ios/Sources/Launcher.swift'-patch_launcher_swift = anchored(LAUNCHER_SWIFT, [- ('game data section', 'struct GameDataSection', 'private struct LauncherView: View {', LAUNCHER_SWIFT_SECTION + 'private struct LauncherView: View {'),- ('game data row', 'GameDataSection()',- ' Section {\n HStack {\n Text("Memory available")',- ' GameDataSection()\n Section {\n HStack {\n Text("Memory available")'),-])-# 420047da (LNPANDY): the launcher's Play asks main.m's dm_locate_game_data() where the game data is, and-# an app with no game data yet goes back to the launcher (its Game data section) instead of a static hint.-FRONT_IOS = 'dm/ios/Sources/front_ios.m'-patch_front_ios = anchored(FRONT_IOS, [- ('locate declaration', 'int dm_locate_game_data(void);',- 'bool dm_show_launcher(void *view_controller, void (*done)(void)); // Launcher.swift: false = no launcher (no dm/launcher.json, or DM_LAUNCHER=0)\n',- 'bool dm_show_launcher(void *view_controller, void (*done)(void)); // Launcher.swift: false = no launcher (no dm/launcher.json, or DM_LAUNCHER=0)\n'- 'int dm_locate_game_data(void); // main.m: (re)decide where the game data is; NO when there still is none\n'),- ('hasLauncher property', '@property (nonatomic) BOOL hasLauncher;',- '@property (nonatomic) BOOL launched;\n',- '@property (nonatomic) BOOL launched;\n'- '@property (nonatomic) BOOL hasLauncher; // the app has a settings screen: a failed Play goes back to it (its Game data section is the way out)\n'),- ('startGame locates the data', 'if (!dm_locate_game_data())',- ' if (self.game) return;\n',- ' if (self.game) return;\n'- ' if (!dm_locate_game_data()) { // no game data (nothing picked, nothing in Documents): the game cannot start\n'- ' if (self.hasLauncher) { dm_show_launcher((__bridge void *)self, launcher_done); return; } // back to the settings screen, whose Game data section picks a location\n'- ' UILabel *lb = [[UILabel alloc] initWithFrame:CGRectInset(self.view.bounds, 40, 40)];\n'- ' lb.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;\n'- ' lb.numberOfLines = 0; lb.textAlignment = NSTextAlignmentCenter; lb.textColor = UIColor.whiteColor;\n'- ' lb.text = @"Game files not found.\\nPut the RomFS folder into this App\'s Documents as \\"romfs\\" (Files app), then restart.";\n'- ' [self.view addSubview:lb]; return;\n'- ' }\n'),- ('hasLauncher at appear', 'self.hasLauncher = dm_show_launcher',- ' if (!dm_show_launcher((__bridge void *)self, launcher_done)) [self startGame]; // the settings screen first (Launcher.swift), when the app has one\n',- ' self.hasLauncher = dm_show_launcher((__bridge void *)self, launcher_done);\n'- ' if (!self.hasLauncher) [self startGame]; // the settings screen first (Launcher.swift), when the app has one\n'),-])-patch_project_yml = anchored('dm/ios/project.yml', [- ('bridging header', 'SWIFT_OBJC_BRIDGING_HEADER',- ' SWIFT_VERSION: "5.0" # Launcher.swift (SwiftUI)\n',- ' SWIFT_VERSION: "5.0" # Launcher.swift (SwiftUI)\n'- ' SWIFT_OBJC_BRIDGING_HEADER: Sources/DmIOS-Bridging-Header.h # DataBookmark (the Files app pick)\n'),-])-# test_xcode_workflow mocks every check build_ipa_from_nsp.main runs; check_glslang is the fork's (patch_nsp)-patch_test_xcode_workflow = anchored('dm/ios/tests/test_xcode_workflow.py', [- ('check_glslang mock', "'check_glslang': None",- "'check_prereqs': None, 'check_metal': None,", "'check_prereqs': None, 'check_metal': None, 'check_glslang': None,"),-])--# `env_switches.py --verify <file>...` (a draft's DM_* names against the table) and its tests: fork-only additions-patch_env_switches_py = anchored('dm/tools/env_switches.py', [- ('--verify', 'def verify_texts',- "if __name__ == '__main__':\n text, bad, unread = rows()",- ENV_SWITCHES_VERIFY + "if __name__ == '__main__':\n" + ENV_SWITCHES_MAIN + " text, bad, unread = rows()"),-])-patch_test_env_switches = anchored('dm/tools/tests/test_env_switches.py', [- ('docstring', '`--verify <file>...`',- 'A switch the code reads that the table does not list, a row for a switch nothing reads any more, or a row without a meaning fails here."""\n',- TEST_ENV_DOC + '"""\n'),- ('tempfile import', 'import tempfile\n', 'import sys\nimport unittest\n', 'import sys\nimport tempfile\nimport unittest\n'),- ('verify tests', 'test_verify_accepts_a_real_switch', "\n\nif __name__ == '__main__':",- '\n' + TEST_ENV_TESTS + "\n\nif __name__ == '__main__':"),-])-# the impact map has a row per host file (the front end's key map is the fork's, seedds/nxnative#386)-patch_impact_map = anchored('dm/tools/impact_map.tsv', [- ('input_map.h row', 'dm/host/input_map.h',- "dm/host/front_mac.m\tpresent:*\tthe Mac front end\n",- "dm/host/front_mac.m\tpresent:*\tthe Mac front end\ndm/host/input_map.h\tpresent:*\tthe Mac front end's key and controller button map\n"),-])--DOCS_AGENTS_BULLETS = r'''- **A test that has not failed is not evidence.** A fix's test must fail before the fix and pass after it; run it both ways, or at least confirm it is collected and that its assertion touches the changed behaviour. Three failures in two days, all of them mine: a test appended *after* the class's closing brace (XCTest never collected it — the suite reported the same count before and after it existed, and I read that as a pass); `assertIn('TEXT_LO = segs[0][1]', src)`, a string match that stays green while the module raises `NameError` on import; and a release-notes splitter whose two failing cases only appeared once the test existed. A green suite is a claim about the code only if the test would have been red.-- **A switch you recommend exists.** Before naming a `DM_*` in a reply, an issue body or a PR, check it against `docs/env_switches.tsv` (generated from the sources): `python3 dm/tools/env_switches.py --verify draft.md` fails on every name that is neither a row nor a documented family. Two replies written from memory in one day told reporters to set `DM_LOG_UEMALLOC` and `DM_NVN_ALIAS_TRACE`, neither of which exists; they wasted a run each and learned nothing.'''-DEV_KEYMAP_SENTENCE = r'''`DM_KEYMAP=<name>=<key code>,…` puts a button, a stick direction (the right stick too, on no key by default) or `Shake` on another key, and `DM_PAD_MAP=<name>=<name>,…` changes what a controller's buttons send (`A=B,B=A` swaps them; `input_map.h`).'''--# The fork's own lines in vendored docs and in one game profile (tex_bc_cpu, the CPU BC decoder).-patch_hades_bc_profile = anchored('dm/games/0100F2C0115B6000/game.tsv', [- ('tex_bc_cpu', 'tex_bc_cpu\ton',- 'tex_flush_upload\ton\n',- 'tex_flush_upload\ton\n# BC textures on GPUs without BC support (A15/A16 and older): decode them on the CPU into\n'- '# RGBA8 (nvn_bcdec.c). No effect on Macs and A19+ devices, which keep the GPU path.\ntex_bc_cpu\ton\n'),-])-patch_docs_agents_readme = anchored('docs/agents/README.md', [- ('fork rules', 'A switch you recommend exists', '\n\n## Checklist for a new title', '\n' + DOCS_AGENTS_BULLETS + '\n\n## Checklist for a new title'),-])-patch_docs_development = anchored('docs/development.md', [- ('key map sentence', '`DM_KEYMAP=<name>=<key code>',- 'with the controllers from player 2 on. The window goes fullscreen from',- 'with the controllers from player 2 on. ' + DEV_KEYMAP_SENTENCE + ' The window goes fullscreen from'),-])--GAME_PY_PROFILE = r''' elif len(a) == 3 and a[0] == 'profile': # the runtime profile the host reads from DM_PROFILE (hle_profile.h): the header's values, as the TSV form- g = load(a[1]); out = Path(a[2]); out.parent.mkdir(parents=True, exist_ok=True)- M = dict(re.findall(r'^#define (DM_GAME_\w+) (.*)$', header(g), re.M)) # exactly what the compiled profile would hold- # macro → the runtime profile's key (hle_profile.c set_kv); the header's spelling of the value is the file's- KEYS = [('title_id', 'ID'), ('program_id', 'PROGRAM_ID'), ('name', 'NAME'), ('romfs_marker', 'ROMFS_MARKER'),- ('modules', 'MODULES'), ('mem_reserve', 'MEM_RESERVE'), ('mem_alias', 'MEM_ALIAS'), ('mem_stack', 'MEM_STACK'),- ('app_pool', 'APP_POOL'), ('mem_used', 'MEM_USED'), ('sys_resource', 'SYS_RESOURCE'), ('mem_map_limit', 'MEM_MAP_LIMIT'),- ('present_interval', 'PRESENT_DISPLAY'), ('core_preempt', 'CORE_PREEMPT'), ('alloc_big_align', 'ALLOC_BIG_ALIGN'),- ('fps_target', 'FPS_TARGET'), ('fps_hold', 'FPS_HOLD'), ('present_snap', 'PRESENT_SNAP'), ('pso_mtl4', 'PSO_MTL4'),- ('shared_font', 'SHARED_FONT_TTF'), ('pad_layout', 'PAD_LAYOUT'), ('op_mode', 'OPMODE'), ('perf_mode', 'PERF_BOOST'),- ('feedback_snap', 'FEEDBACK_SNAP'), ('tex_flush_upload', 'TEX_FLUSH_UPLOAD'), ('render_cond', 'RENDER_COND'),- ('tex_dirty_upload', 'TEX_DIRTY_UPLOAD'), ('tex_dyn_slots', 'TEX_DYN_SLOTS'), ('gpu_timestamps', 'GPU_TS_SEGMENT'),- ('vconv_range', 'VCONV_RANGE'), ('game_args', 'ARGS'), ('game_env', 'ENV')]- def val(macro): # the header's C spelling → the file's plain spelling- v = M.get('DM_GAME_' + macro)- if v is None: return None- v = v.strip()- if v.startswith('{') and v.endswith('}'): # {"main", "sdk"} → main sdk- return ' '.join(x.strip().strip('"') for x in v[1:-1].split(',') if x.strip())- if v.startswith('"'): return v[1:-1]- return v[:-3] if v.endswith('ull') else v- L = [f'# Runtime game profile of {g.id} ({g.get("name")}), written by dm/games/game.py profile from {g.dir}/game.tsv',- '# Read by the host from DM_PROFILE (hle_profile.c set_kv): KEY<TAB>VALUE, # starts a comment. Every value the compiled',- '# profile would hold is written, so the file alone describes the game.']- for key, macro in KEYS:- v = val(macro)- if v is not None: L.append(f'{key}\t{v}')- api = [val('NVN_API_MAJOR'), val('NVN_API_MINOR')]- if api[0] is not None: L.append(f'device_api\t{api[0]}.{api[1] or 0}')- for b, d in re.findall(r'\{"([0-9a-f]+)", "([^"]*)"\}', M.get('DM_GAME_DISPLAY_VERSIONS', '')):- L.append(f'display_version\t{b}\t{d}')- text = '\n'.join(L) + '\n'- if not (out.exists() and out.read_text() == text): out.write_text(text, encoding='utf-8') # unchanged: keep the mtime- print(out)-'''-GAME_PY_TBC = r''' tbc = g.get('tex_bc_cpu', 'off') # decode BC-compressed textures on the CPU when the GPU has no BC support (A15/A16 and older; nvn_mtl.m uses nvn_bcdec.c): on / off- if tbc not in ('on', 'off'): sys.exit(f'{g.id}: tex_bc_cpu must be on or off: {tbc}')-'''-# dm/games/game.py: the tex_bc_cpu profile key (nvn_bcdec.c) and the `profile` subcommand that writes the runtime-# profile (hle_profile.h). Fork-owned as a whole (OURS) until issue #92, which made the sync stop: upstream-# changes this file too (tex_flush_upload ...), so the three additions are re-applied on top of its version.-patch_game_py = anchored('dm/games/game.py', [- ('tex_bc_cpu check', "tbc = g.get('tex_bc_cpu'",- " tds = g.get('tex_dyn_slots', 'off')", GAME_PY_TBC + " tds = g.get('tex_dyn_slots', 'off')"),- ('tex_bc_cpu macro', 'DM_GAME_TEX_BC_CPU',- " f'#define DM_GAME_TEX_DYN_SLOTS {int(tds == \"on\")}',\n",- " f'#define DM_GAME_TEX_BC_CPU {int(tbc == \"on\")}',\n f'#define DM_GAME_TEX_DYN_SLOTS {int(tds == \"on\")}',\n"),- ('profile subcommand', "a[0] == 'profile'",- " elif len(a) == 2 and a[0] == 'dir':", GAME_PY_PROFILE + " elif len(a) == 2 and a[0] == 'dir':"),-])--# Fork edits to vendored files that the sync replaces with upstream's version on purpose. The-# unprotected-edit check (check_unprotected) accepts a file listed here.-DROPPED = {- # The NRO header skip (issue LNPANDY/NX2Apple#14, FINAL FANTASY X/X-2 HD Remaster) was a fork patcher on patch_nso.py- # (sent upstream as seedds/nxnative#397, closed as superseded) and a data_blocks(..., lo=0) edit of nso_code.py. Upstream- # fixed it itself in 3e77816c, 7e0f5971 and 337186cf: nso_code.data_blocks() starts after the 0x80-byte NRO header and- # reports the header past its first two words as a data block, so CODE_RANGES holds no code before 0x80 and the scans- # (func_of included) cannot enter it; dm/tools/tests/test_nro_header.py is upstream's own test. The fork's versions of- # all three files are dropped, upstream's win.- 'dm/tools/nso_code.py': 'upstream has its own NRO header bound (3e77816c): data_blocks() excludes the header',- 'dm/tools/patch_nso.py': 'upstream has its own NRO header bound (3e77816c); the fork patcher (code_start/code_ranges) is gone',- 'dm/tools/tests/test_nro_header.py': "upstream's test of its own NRO header bound (3e77816c, 7e0f5971, 337186cf)",- # CreateWithAdjustableSystemClock and the snapshot type bytes (PR #26) were OURS until issue #92; upstream has- # them since 4d2dc7db (#385, same function names, same behaviour), so the sync takes upstream's files again.- 'dm/host/hle_time.c': 'the fork-only parts landed upstream as 4d2dc7db (#385)',- 'dm/host/tests/t_time.c': 'the fork-only parts landed upstream as 4d2dc7db (#385)',- # Generated by dm/tools/docs_patches.py from the fork's own patches/profiles/host tables- # (refresh_generated_indexes regenerates it on every sync); upstream's copy describes upstream's.- 'docs/agents/game-patches.md': 'generated: docs_patches.py over the fork tree (refreshed by the sync)',- 'docs/agents/symptoms.md': 'generated: docs_symptoms.py over docs/reference (refreshed by the sync)',-}--# The picked-location part of the fixture (the Files-app pick): the stub, argv[4], and the test.-PICKED_EDITS = [- ('picked stub', 'fixture_picked;',- r"""'#define NSSearchPathForDirectoriesInDomains(a,b,c) @[fixture_doc]\n#define NSTemporaryDirectory() fixture_tmp\n' + locator +""",- r"""'#define NSSearchPathForDirectoriesInDomains(a,b,c) @[fixture_doc]\n#define NSTemporaryDirectory() fixture_tmp\n'- # The picked-location bookmark (DataBookmark.m): the fixture answers it from a- # variable, so a test can put the player's choice anywhere on disk.- 'static NSString *fixture_picked;\n'- 'NSString *dm_picked_data_path(BOOL *stale) { if (stale) *stale = NO; return fixture_picked; }\n' + locator +"""),- ('picked argv', 'if (argc > 4) fixture_picked',- r"""'fixture_doc = @(argv[1]); fixture_tmp = @(argv[2]); fixture_bundle = argc > 3 ? @(argv[3]) : @"/nonexistent-fixture"; NSString *p = romfs_locate();\n'""",- r"""'fixture_doc = @(argv[1]); fixture_tmp = @(argv[2]); fixture_bundle = argc > 3 ? @(argv[3]) : @"/nonexistent-fixture";\n'- 'if (argc > 4) fixture_picked = @(argv[4]); // the location the player picked, when a test sets one\n'- 'NSString *p = romfs_locate();\n'"""),- ('picked test', 'test_the_location_the_player_picked', "\n\n\nif __name__ == '__main__': unittest.main()",- "\n\n" + TEST_PICKED_METHOD + "\n\n\nif __name__ == '__main__': unittest.main()"),-]--# One marker per carrier: the string that exists only when the fork's patch is in place.-MARKERS = {- 'dm/host/hle_fs.c': 'romfsarc',- 'dm/host/Makefile': 'romfs_arc.c',- 'dm/host/tests/Makefile': 'romfs_arc.c',- 'dm/ios/tools/build_ipa.sh': 'DM_FULL_ROMFS',- 'scripts/build_ipa_from_nsp.py': '--work-dir',- 'dm/ios/Sources/main.m': 'static int set_data_env',- 'dm/gfx/nvn/nvn_mtl.m': '../tex/nvn_bcdec.h',- 'dm/games/0100A00019DE0000/game.tsv': 'build v1 1.0.137848',- 'dm/host/dm.h': 'hle_profile.h',- 'dm/host/front_mac.m': 'DM_KEYMAP',- 'dm/ios/tests/test_romfs_startup.py': 'fixture_profile',- 'dm/ios/tests/test_profile_pack.py': 'slim package',- 'dm/ios/tests/test_ipa_unsigned.py': 'slim IPA by default',- 'docs/env_switches.tsv': 'DM_FULL_ROMFS\t',- 'dm/mac/launcher.c': '.nx2apple-library',- 'dm/host/hle_svc.c': ('dm_profile()->mem_reserve', # the patcher's product on upstream's text- 'const struct dm_profile *p = dm_profile();'), # or the fork's merged rewrite (one dm_profile() call, values from the struct)- 'dm/host/hle_os.c': 'dm_profile()->genv',- 'dm/host/hle_fpslock.c': 'dm_profile()->fps_target',- 'dm/host/loader.c': 'dm_profile()->fps_target',- 'dm/ios/Sources/DmGamepad.m': 'dm_profile()->pad_layout',- 'dm/ios/Sources/Launcher.swift': 'GameDataSection()',- 'dm/ios/Sources/front_ios.m': 'int dm_locate_game_data(void);',- 'dm/ios/project.yml': 'SWIFT_OBJC_BRIDGING_HEADER',- 'dm/ios/tests/test_xcode_workflow.py': "'check_glslang': None",- 'dm/tools/env_switches.py': 'def verify_texts',- 'dm/tools/tests/test_env_switches.py': 'test_verify_accepts_a_real_switch',- 'dm/tools/impact_map.tsv': 'dm/host/input_map.h',- 'dm/games/game.py': 'DM_GAME_TEX_BC_CPU',- 'dm/games/0100F2C0115B6000/game.tsv': 'tex_bc_cpu\ton',- 'docs/agents/README.md': 'A switch you recommend exists',- 'docs/development.md': '`DM_KEYMAP=<name>=<key code>',-}-PATCHERS = {- 'dm/host/hle_fs.c': patch_hle_fs,- 'dm/host/Makefile': patch_makefile,- 'dm/host/tests/Makefile': patch_tests_makefile,- 'dm/ios/tools/build_ipa.sh': patch_build_ipa,- 'scripts/build_ipa_from_nsp.py': patch_nsp,- 'dm/ios/Sources/main.m': patch_main_m,- 'dm/gfx/nvn/nvn_mtl.m': patch_nvn_mtl,- 'dm/games/0100A00019DE0000/game.tsv': patch_hades2,- 'dm/host/dm.h': patch_dm_h,- 'dm/host/front_mac.m': patch_front_mac,- 'dm/ios/tests/test_romfs_startup.py': patch_test_romfs_startup,- 'dm/ios/tests/test_profile_pack.py': patch_test_profile_pack,- 'dm/ios/tests/test_ipa_unsigned.py': patch_ipa_unsigned,- 'docs/env_switches.tsv': patch_env_switches,- 'dm/mac/launcher.c': patch_launcher_c,- 'dm/host/hle_svc.c': patch_hle_svc,- 'dm/host/hle_os.c': patch_hle_os,- 'dm/host/hle_fpslock.c': patch_hle_fpslock,- 'dm/host/loader.c': patch_loader,- 'dm/ios/Sources/DmGamepad.m': patch_dmgamepad,- 'dm/ios/Sources/Launcher.swift': patch_launcher_swift,- 'dm/ios/Sources/front_ios.m': patch_front_ios,- 'dm/ios/project.yml': patch_project_yml,- 'dm/ios/tests/test_xcode_workflow.py': patch_test_xcode_workflow,- 'dm/tools/env_switches.py': patch_env_switches_py,- 'dm/tools/tests/test_env_switches.py': patch_test_env_switches,- 'dm/tools/impact_map.tsv': patch_impact_map,- 'dm/games/game.py': patch_game_py,- 'dm/games/0100F2C0115B6000/game.tsv': patch_hades_bc_profile,- 'docs/agents/README.md': patch_docs_agents_readme,- 'docs/development.md': patch_docs_development,-}--# PATCHED, MARKERS and PATCHERS are three views of one set and have to agree, or a carrier works-# while something else refuses to let it through. v0lumehi hit exactly that (PR #59): front_mac.m,-# patch_nso.py and Hades II's game.tsv had patchers and markers but were missing from PATCHED, so-# pr-scope refused the PR that carried them. Checked here rather than remembered.-assert set(PATCHED) == set(MARKERS) == set(PATCHERS), (- 'the carrier tables disagree: PATCHED-only %s, MARKERS-only %s, PATCHERS-only %s' % (- sorted(set(PATCHED) - set(MARKERS) | set(PATCHED) - set(PATCHERS)),- sorted(set(MARKERS) - set(PATCHED) | set(MARKERS) - set(PATCHERS)),- sorted(set(PATCHERS) - set(PATCHED) | set(PATCHERS) - set(MARKERS))))--report, problems = [], []-class SyncProblem(Exception): pass-def say(s): report.append(s); print(s, flush=True)-def fail(s):- problems.append(s); say('[FAIL] ' + s)- raise SyncProblem(s)-def skip(name): say(f' = {name}')-def done(name, t=None):- say(f' + {name}')- return t--def upstream_mode(rev, path):- """The file's git mode upstream ('100755' for an executable), None when it is not there."""- out = git('ls-tree', rev, '--', path).split()- return out[0] if out else None--def take_from_upstream(rev, path, dest):- data = blob(rev, path)- if data is None: fail(f'{path}: not in upstream {rev}'); return- dest.parent.mkdir(parents=True, exist_ok=True)- dest.write_bytes(data)- # The mode too: written as bytes, an executable came out 0644, and the fork's spirv-cross binary, its build.sh and six- # scripts lost their x bit (test_spirv_cross_pin: Permission denied running the committed spirv-cross)- dest.chmod(0o755 if upstream_mode(rev, path) == '100755' else 0o644)--def verify(skip_build, upstream_ref='upstream/main'):- say('--- verify ---')- py = '/usr/bin/python3' if os.path.exists('/usr/bin/python3') else sys.executable- bad = []- for root, dirs, files in os.walk(REPO):- dirs[:] = [d for d in dirs if d not in ('.git', 'third_party', '__pycache__', '.build', 'node_modules')]- for f in files:- if not f.endswith('.py'): continue- p = Path(root) / f- r = subprocess.run([py, '-c', 'import ast,sys\ntry: ast.parse(open(sys.argv[1],encoding="utf-8",errors="replace").read())\nexcept SyntaxError as e: print(f"{e.lineno}: {e.msg}")', str(p)], capture_output=True, text=True)- if r.stdout.strip(): bad.append(f'{p.relative_to(REPO)}:{r.stdout.strip()}')- if bad:- for b in bad: fail(f'Python 3.9 syntax: {b}')- else: say(f' + every .py parses on the Python 3.9 floor')- r = subprocess.run(['bash', '-n', 'dm/ios/tools/build_ipa.sh'], cwd=REPO, capture_output=True, text=True)- if r.returncode: fail(f'build_ipa.sh: bash -n failed: {r.stderr.strip()}')- else: say(' + build_ipa.sh: bash -n OK')- # archive reader: compile and run against a small generated archive- with tempfile.TemporaryDirectory() as td:- src, arc = Path(td) / 'src', Path(td) / 'romfs'- (src / 'sub').mkdir(parents=True)- (src / 'a.txt').write_bytes(b'hello'); (src / 'sub' / 'b.txt').write_bytes(b'world')- r = subprocess.run([sys.executable, 'dm/tools/romfs_arc.py', 'pack', str(src), str(arc), '--shard-mib', '1'], cwd=REPO, capture_output=True, text=True)- if r.returncode: fail(f'archive pack failed: {r.stderr.strip()[:200]}'); return- exe = Path(td) / 't_arc'- r = subprocess.run(['clang', '-O1', '-I', 'dm/host', '-o', str(exe), 'dm/host/tests/t_romfs_arc.c', 'dm/host/romfs_arc.c'], cwd=REPO, capture_output=True, text=True)- if r.returncode: fail(f'archive test compile failed: {r.stderr.strip()[:400]}'); return- r = subprocess.run([str(exe), str(arc)], capture_output=True, text=True)- if r.returncode or 'all checks passed' not in r.stdout: fail(f'archive test failed: {r.stdout.strip()[:200]} {r.stderr.strip()[:200]}')- else: say(' + archive reader test passed')- if skip_build: say(' = host build skipped (--skip-build)'); return- games = sorted(p.name for p in (REPO / 'dm/games').iterdir() if p.name.startswith('0100'))- game = '01006F8002326000' if '01006F8002326000' in games else games[0]- say(f' … building the macOS host for {game} (a few minutes)')- r = subprocess.run(['make', '-C', 'dm/host', f'GAME={game}', 'dmhost', '-j4'], cwd=REPO, capture_output=True, text=True)- if r.returncode:- tail = '\n'.join((r.stdout + r.stderr).splitlines()[-25:])- fail(f'host build failed:\n{tail}')- else: say(f' + host build OK ({game})')- # Host unit tests: the fs tests #include ../hle_fs.c and link romfs_arc.c, so a fork change that- # the test rules do not know about breaks them at link time and they stop running silently- # (PR #12 — they had been unbuildable). Cheap (seconds) and catches that class here.- say(f' … host unit tests for {game}')- r = subprocess.run(['make', '-C', 'dm/host/tests', f'GAME={game}', 'run', '-j4'], cwd=REPO, capture_output=True, text=True)- if r.returncode:- tail = '\n'.join((r.stdout + r.stderr).splitlines()[-25:])- fail(f'host unit tests failed:\n{tail}')- else: say(' + host unit tests OK')- check_patcher_consistency(upstream_ref)---def check_patcher_consistency(upstream_ref='upstream/main'):- """Every carrier's patched form must equal the file in the tree, code line by code line.-- A fork change made to a carrier's source but not to its patcher entry is invisible today (the- marker is present, so the patcher skips) and reappears the next time upstream touches that file- — PR #11 was exactly that: GetEntryType had been fixed to arc_rel in the source while the patcher- still inserted ROMFSARC_SYNTH_REL. Comparing the patcher's output against the working tree makes- the drift show up on the sync that introduces it rather than months later.-- Comments and blank lines are ignored: a comment reworded in the tree is not drift, and demanding- a matching comment edit in the patcher would train people to ignore this check.- """- say(' … patcher consistency (patched upstream file vs the tree, comments ignored)')- def code(text):- out = []- for ln in text.splitlines():- s = ln.strip()- if not s or s.startswith(('#', '//', '/*', '*', '<!--')):- continue- # strip a trailing comment too: `code; // why` is the same statement however the why- # is worded, and a reworded trailing comment must not read as drift- cut = ln.find(' //')- if cut < 0:- cut = ln.find(' #')- if cut > 0:- ln = ln[:cut]- out.append(ln.rstrip())- return out- drift = []- for path, patcher in PATCHERS.items():- src = REPO / path- if not src.exists():- continue- upstream = subprocess.run(['git', 'show', f'{upstream_ref}:{path}'], cwd=REPO,- capture_output=True, text=True)- if upstream.returncode:- continue # a fork-only file has no upstream form to compare- try:- out = patcher(upstream.stdout)- except SyncProblem:- continue # an anchor miss is reported by apply_changes already- if out is None:- out = upstream.stdout- if code(out) != code(src.read_text(encoding='utf-8', errors='replace')):- drift.append(path)- if drift:- for d in drift:- say(f' ! {d}: the patcher and the tree disagree')- fail('patcher drift: ' + ', '.join(drift) +- ' — the source was changed without its patcher entry (or the other way round); '- 'a future sync would silently revert the change')- else:- say(f' + {len(PATCHERS)} patchers agree with the tree')--def unprotected_edits(old, head='HEAD'):- """The fork's hand edits that nothing protects (issue #92): (edited, added) lists of vendored paths.-- The sync takes upstream's version of a vendored file wherever upstream changed it, so a fork edit- survives only in an OURS file, a PATCHED carrier (its patcher re-applies it) or a DROPPED file (the- loss is deliberate). `edited` are files that exist in the last sync base `old` and differ in the- fork's tree `head` (or were deleted there) without any of the three; `added` are fork-only files- under the vendored paths that are not in OURS either (harmless until upstream adds the same path:- apply_changes would then overwrite the fork's file)."""- edited, added = [], []- in_old = set(git('ls-tree', '-r', '--name-only', old, '--', *VENDORED).splitlines())- for line in git('diff', '--name-status', '--no-renames', old, head, '--', *VENDORED).splitlines():- kind, path = line.split('\t')[0][0], line.split('\t')[-1]- if path in OURS or path in PATCHED or path in DROPPED: continue- if kind == 'D' and path not in in_old:- # The file does not exist in `old` at all, so the fork never deleted it: this diff- # shape comes from callers that pass upstream's own tip as the base (the daily health- # check runs --old $NEW --new $NEW to prove the tree stands on its own). Files- # upstream added after the last sync then show as deletions here; they are upstream's- # new work, not fork edits, and listing them buried the real signal (issue #105).- continue- (added if kind == 'A' else edited).append(path)- return sorted(edited), sorted(added)--def check_unprotected(old, changes):- """Report fork edits the sync would lose. An edited file that upstream changes in this very sync is a- failure (its fork change is about to be overwritten); one that upstream leaves alone is only listed- (it survives this sync, and is lost at the first sync that touches it)."""- edited, added = unprotected_edits(old)- upstream = {p for _, p in changes}- # Only a file the fork actually carries can lose an edit: in the daily-health shape- # (--old $NEW) the ls-tree sweep adds ('A', p) for every file upstream has and the fork- # lacks, and the same paths show as fork 'deletions' — nothing there to overwrite.- lost = [p for p in edited if p in upstream and REPO.joinpath(p).exists()]- for p in edited:- if p not in lost: say(f' ! {p}: edited in the fork, not in OURS / PATCHED / DROPPED; upstream does not change it in this sync, but a later one will')- if added: say(f' . {len(added)} fork-only file(s) under the vendored paths are not in OURS (harmless unless upstream adds the same path; --check-protection lists them)')- for p in lost:- say(f' ! {p}: edited in the fork and changed by upstream in this sync, with no patcher')- if lost:- fail('fork edits that this sync would overwrite (add a patcher to PATCHERS, or OURS / DROPPED with the reason): ' + ', '.join(lost))- return edited, added--def apply_changes(a, changes):- """Take every changed file from upstream, then re-apply the fork's patches to the carriers."""- touched = 0- for kind, path in changes:- dest = REPO / path- if kind == 'D':- if path in OURS: fail(f'upstream deleted a fork file: {path}')- if dest.exists(): dest.unlink(); say(f' - {path}'); touched += 1- continue- if path in OURS: fail(f'upstream writes over a fork file: {path} (resolve by hand)')- take_from_upstream(a.new, path, dest); touched += 1- if path in PATCHED:- r = PATCHERS[path](dest.read_text(encoding='utf-8', errors='replace'))- if r is not None and r != dest.read_text(encoding='utf-8', errors='replace'):- dest.write_text(r, encoding='utf-8')- say(f'{touched} files taken from upstream')- # Second pass over every carrier, including ones upstream did not change this time: a fork- # patch can be lost without the file ever appearing in the diff (a wholesale tree replace,- # a bad merge), so presence is asserted, not assumed.- for path, patcher in PATCHERS.items():- p = REPO / path- if not p.exists(): fail(f'{path}: missing before patching')- t = p.read_text(encoding='utf-8', errors='replace')- r = patcher(t)- if r is not None and r != t: p.write_text(r, encoding='utf-8')- now = p.read_text(encoding='utf-8', errors='replace')- # A marker is a string the fork's protected form carries and upstream's lacks. A file- # can carry two of them: the patcher's product on upstream's text (dm_profile()->…), and- # the fork's own merged rewrite of the same behaviour (hle_svc.c keeps the profile in a- # struct pointer — same values, one dm_profile() call). Either proves the protection.- marks = MARKERS[path] if isinstance(MARKERS[path], tuple) else (MARKERS[path],)- if not any(m in now for m in marks):- fail(f'{path}: fork patch marker missing after sync: {marks[0]!r}')---def game_rows():- """Every profile in the tree, as the README table wants it: name, title ID, update, status.-- Read from `dm/games/<title ID>/game.tsv`, which is the only authority: the table used to be- maintained by hand, so a sync that brought in new profiles (three did, with 467 commits) left- the README claiming 72 games while the tree had 75.-- `build` holds the update's version and version number (`v131072 1.0.2 main=…`); `package` is- the version the profile needs. A profile with no build line needs no update at all.- """- rows = []- for d in sorted((REPO / 'dm/games').iterdir()):- if not d.is_dir() or not d.name.startswith('0100'):- continue- tsv = d / 'game.tsv'- if not tsv.is_file():- continue- fields: dict[str, str] = {}- for ln in tsv.read_text(encoding='utf-8', errors='replace').splitlines():- if not ln or ln.startswith('#') or '\t' not in ln:- continue- k, v = ln.split('\t', 1)- fields.setdefault(k.strip(), v.strip())- name = fields.get('name')- if not name:- continue- # `build` repeats once per version this profile knows (v0 the base game, then each- # update), and `package` names the one the profile is built for. Reading the first build- # line reported the base version for every game, which is how "无(v0)" became "1.0.0 (v0)"- # and Super Mario Bros. Wonder's 1.2.1 became 1.0.0.- builds = [ln.split('\t', 1)[1].strip()- for ln in tsv.read_text(encoding='utf-8', errors='replace').splitlines()- if ln.startswith('build\t')]- want = fields.get('package', 'v0').strip() or 'v0'- chosen = next((b for b in builds if b.split() and b.split()[0] == want), None)- parts = (chosen or '').split()- if len(parts) >= 2 and parts[0] != 'v0':- update = f'{parts[1]} ({parts[0]})'- else:- update = '无(v0)'- rows.append((d.name, name, update))- return rows---#: The status a profile gets until someone writes something better. Kept as one string so the-#: wording matches what the table already uses for unverified titles.-STATUS_UNVERIFIED = 'Profile present; not verified on a phone'-STATUS_UPSTREAM = 'Playable on an iPhone (upstream)'--#: Rows whose status is this fork's own testing (build → install → play here). Matched by title ID-#: so the text can change without the sync dropping the claim.-VERIFIED_HERE = {- '0100000000010000': '**Verified here** — builds, installs and runs on an iPhone; '- '304,243 files into 127 archive shards, byte-verified',- '0100F2C0115B6000': '**Verified here** — builds, installs and runs on an iPhone; '- '33-file archive',- '01006F8002326000': '**Verified here** — builds, installs and runs smoothly on an iPhone; '- '103,645 files into 72 archive shards',-}---def refresh_game_table():- """Rebuild the README's game table from `dm/games/`, keeping every hand-written status.-- Two things must not be lost when this rewrites the table:- - a status someone wrote by hand (a verification, a caveat about a controller or touch- controls). The existing row's status column is carried over verbatim; only rows that did- not exist before get a default.- - the sort order, which is by title ID and is what makes the table readable.-- The row count in the prose ("72 game profiles") and the "N verified" line are updated too,- because those are the numbers a reader trusts and the ones that went stale.- """- readme_path = REPO / 'README.md'- text = readme_path.read_text(encoding='utf-8')- rows = game_rows()- if not rows:- say(' ! no game profiles found; the table is left alone')- return-- # existing statuses, by title ID- have: dict[str, str] = {}- for ln in text.splitlines():- m = re.match(r'\|\s*([^|]+?)\s*\|\s*`(0100[0-9A-F]{12})`\s*\|\s*([^|]*?)\s*\|\s*(.+?)\s*\|\s*$', ln)- if m:- have[m.group(2)] = m.group(4)-- lines = ['| Game | Title ID | Update required | Status |', '|---|---|---|---|']- added = 0- for tid, name, update in rows:- if tid in have:- status = have[tid]- elif tid in VERIFIED_HERE:- status = VERIFIED_HERE[tid]- else:- status = STATUS_UNVERIFIED- added += 1- lines.append(f'| {name} | `{tid}` | {update} | {status} |')- table = '\n'.join(lines)-- # replace the table in place: from its header row to the last row that starts with "| "- start = text.find('| Game | Title ID | Update required | Status |')- if start < 0:- say(' ! game table not found in README.md; profiles are in the tree but not listed')- return- end = start- for ln in text[start:].splitlines(keepends=True):- if ln.startswith('| ') or ln.startswith('|---'):- end += len(ln)- else:- break- new_text = text[:start] + table + '\n' + text[end:]-- # the counts in the prose and in the table's own caption- n = len(rows)- verified = sum(1 for ln in table.splitlines() if '**Verified here**' in ln)- # Only the number changes; whatever emoji or wording precedes it is left exactly as written- # (the feature table uses 🧩, the hero caption uses 🎯). A lookahead keeps the match to the- # digits, so no part of the surrounding text is rewritten.- new_text = re.sub(r'\d+(?= game profiles\*\*)', str(n), new_text)- new_text = re.sub(r'\*\*\d+ verified end to end on this fork\*\*',- f'**{verified} verified end to end on this fork**', new_text)-- if new_text != text:- readme_path.write_text(new_text, encoding='utf-8')- say(f' README table: {n} profiles' + (f' ({added} new)' if added else '') +- f', {verified} verified here')- else:- say(f' README table: {n} profiles, unchanged')---def refresh_game_table_zh():- """Add rows for profiles the Chinese README's table is missing, and nothing else.-- The English table is rebuilt because its game names come straight from `game.tsv`. The- Chinese one cannot be: its names are translated by hand ("超级马力欧 奥德赛" for "Super Mario- Odyssey"), and so are its statuses. So this only appends rows for title IDs that are absent,- using the English name as a placeholder — visible, and better than a game that silently is- not listed — with the Chinese wording for "unverified" so it does not stand out as English- text in a Chinese table. A translator replaces the name later; the row is never regenerated- once it exists, so the translation is safe.-- Sorting is by title ID, like the English table, so the insert position is computed rather- than appended at the end.- """- path = REPO / 'README.zh-CN.md'- if not path.is_file():- return- text = path.read_text(encoding='utf-8')- header = '| 游戏 | Title ID | 需要的更新包 | 状态 |'- start = text.find(header)- if start < 0:- say(' ! Chinese game table not found; skipped')- return- # the rows of the table, in order- block_start = start- block_end = start- for ln in text[start:].splitlines(keepends=True):- if ln.startswith('| ') or ln.startswith('|---'):- block_end += len(ln)- else:- break- block = text[block_start:block_end]- present = set(re.findall(r'`(0100[0-9A-F]{12})`', block))-- missing = [r for r in game_rows() if r[0] not in present]- if not missing:- say(f' README.zh-CN table: complete ({len(present)} profiles)')- return-- lines = block.rstrip('\n').splitlines()- for tid, name, update in missing:- row = f'| {name} | `{tid}` | {update} | 有 profile,未在手机上验证 |'- # insert before the first row whose title ID sorts after this one- pos = len(lines)- for i, ln in enumerate(lines):- m = re.search(r'`(0100[0-9A-F]{12})`', ln)- if m and m.group(1) > tid:- pos = i- break- lines.insert(pos, row)- new_block = '\n'.join(lines) + '\n'- new_text = text[:block_start] + new_block + text[block_end:]- n = len(game_rows())- new_text = re.sub(r'\*\*(?:[^ *] )?(\d+)( game profiles\*\*)',- lambda m: f'**{n}{m.group(2)}', new_text)- path.write_text(new_text, encoding='utf-8')- say(f' README.zh-CN table: +{len(missing)} row(s) '- f'({", ".join(t for t, _, _ in missing)}) — names are English until translated')---def refresh_generated_indexes():- """Regenerate the indexes upstream's own tests require to be current, from the fork's tree.-- docs/agents/game-patches.md is dm/tools/docs_patches.py's output over the patch files, host- tables and profiles — all of which differ in the fork from upstream, so the synced copy would- fail test_docs.test_index_is_current. docs/agents/symptoms.md is docs_symptoms.py's output over- docs/reference (vendored, but the same rule). Both are generated; running their tools here keeps- the tree consistent no matter what upstream's copy says (their DROPPED entries explain why the- protection check accepts the difference).- """- for tool, out in (('docs_patches.py', 'docs/agents/game-patches.md'),- ('docs_symptoms.py', 'docs/agents/symptoms.md')):- r = subprocess.run([sys.executable, str(REPO / 'dm/tools' / tool)], cwd=REPO,- capture_output=True, text=True)- if r.returncode != 0:- say(f' ! {tool} failed: {r.stderr.strip().splitlines()[-1] if r.stderr.strip() else r.returncode}')- else:- say(f' = {out} regenerated')---def refresh_badges():- """Keep docs/badges/*.json in step with the tree, so the README badges need no hand edit.-- The game count is the number of title-ID profile folders (dm/games/0100…), which is what the- README means by "N game profiles". The verified count is the rows marked verified in the- README's own table, so the source of truth stays the README text rather than a second list."""- gdir = REPO / 'dm/games'- # Counted the same way the table is built (game_rows: a folder needs a game.tsv with a name),- # not by directory name: upstream has documentation folders under dm/games/ that carry no- # profile, and the badge said 80 while the table listed 79.- games = len(game_rows())- readme = (REPO / 'README.md').read_text(encoding='utf-8')- verified = sum(1 for ln in readme.splitlines()- if ln.startswith('| ') and ('**Verified here**' in ln or 'Verified —' in ln))- for name, label, value, color in [('games', 'games', games, 'blue'),- ('verified', 'verified on an iPhone', verified, 'success')]:- p = REPO / 'docs/badges' / f'{name}.json'- old = p.read_text(encoding='utf-8') if p.exists() else ''- new = json.dumps({'schemaVersion': 1, 'label': label, 'message': str(value), 'color': color},- indent=2) + '\n'- if old != new:- p.parent.mkdir(parents=True, exist_ok=True)- p.write_text(new, encoding='utf-8')- say(f' badge {name}: {value}')- say(f'badges: {games} games, {verified} verified')- # The README banners carry the same two numbers, so they are redrawn here: both scripts read- # them from the tree (repo_numbers()), so this only runs when the tree changed.- for script in ('frontend/screenshots/gen_hero.py', 'frontend/screenshots/gen_hero_en.py'):- sp = REPO / script- if not sp.exists():- continue- r = subprocess.run([sys.executable, str(sp)], capture_output=True, text=True, timeout=180)- if r.returncode == 0:- say(f' banner: {Path(script).name} redrawn')- else:- say(f' ! banner {Path(script).name} failed: {(r.stderr or "").strip()[:160]}')---def main():- ap = argparse.ArgumentParser()- ap.add_argument('--old', required=True, help='upstream ref the fork is currently at')- ap.add_argument('--new', help='upstream ref to sync to (not needed with --check-protection)')- ap.add_argument('--skip-build', action='store_true')- ap.add_argument('--check-protection', action='store_true',- help='only list the fork edits under the vendored paths that no patcher, OURS or DROPPED entry protects '- '(files that differ from --old in the fork\'s tree); exit 1 when there are any')- a = ap.parse_args()- if a.check_protection:- edited, added = unprotected_edits(a.old)- for p in edited: print(f'unprotected edit: {p}')- for p in added: print(f'fork-only file (not in OURS): {p}')- print(f'{len(edited)} unprotected edit(s), {len(added)} fork-only file(s) outside OURS')- sys.exit(1 if edited else 0)- if not a.new: ap.error('--new is required')-- say(f'sync {a.old[:7]} → {a.new[:7]}')- changes = upstream_changes(a.old, a.new)- say(f'{len(changes)} upstream file changes under {" ".join(VENDORED)}')- try:- check_unprotected(a.old, changes)- apply_changes(a, changes)- verify(a.skip_build, a.new) # the ref that was synced, whatever the remote is called here- refresh_game_table()- refresh_game_table_zh()- refresh_badges()- refresh_generated_indexes()- except SyncProblem: pass- if problems:- say(f'\nSYNC FAILED: {len(problems)} problem(s) — nothing committed; the working tree is left as the script wrote it, `git checkout -- .` restores it')- sys.exit(1)- say('\nSYNC OK — commit and push from the caller')---if __name__ == '__main__':- main()diff --git a/scripts/tests/test_sync_patchers.py b/scripts/tests/test_sync_patchers.pydeleted file mode 100644index 111d808e..00000000--- a/scripts/tests/test_sync_patchers.py+++ /dev/null@@ -1,155 +0,0 @@-"""The upstream sync's patchers against the files of a real upstream ref (issue #92).--scripts/sync_upstream.py re-applies the fork's changes to upstream's files with anchored patchers. Each-patcher is written against the text of upstream at one moment, so upstream moving on can break it in two-ways, and both went unnoticed until a person ran every patcher by hand against seedds/nxnative main:- - an anchor no longer matches (ce99604a changed `clang -O1 ...` to `$(CLANG) -O1 ...`): the sync stops;- - a marker is satisfied by upstream's own text (`list-runtimes`): the patcher says "already patched"- on upstream's file and the fork's change silently disappears.-This test runs every patcher on the file of an upstream ref, in a temporary directory, and fails on-either, on a patcher that is not idempotent, and on a patched Python or shell file that does not parse.--The ref is $SYNC_PATCHERS_REF, else seedds/main (the remote the fork syncs from; CI adds it, see-.github/workflows/tests.yml). The tests are skipped when the ref is not in the repository. The base checks-read the fork's last sync base from .upstream-ref.-"""-import ast-import contextlib-import io-import os-import subprocess-import sys-import tempfile-import unittest-from pathlib import Path--REPO = Path(__file__).resolve().parents[2]-sys.path.insert(0, str(REPO / 'scripts'))-import sync_upstream as su # noqa: E402---def rev_ok(ref):- return subprocess.run(['git', 'rev-parse', '--verify', '--quiet', ref + '^{commit}'], cwd=REPO, capture_output=True).returncode == 0---def show(ref, path):- r = subprocess.run(['git', 'show', f'{ref}:{path}'], cwd=REPO, capture_output=True)- return r.stdout.decode('utf-8', errors='replace') if r.returncode == 0 else None---def last_base():- f = REPO / '.upstream-ref'- base = f.read_text().strip() if f.exists() else ''- return base if base and rev_ok(base) else None---def quiet(fn, *a):- """Run a patcher with its progress lines swallowed; a patcher that cannot fit raises SyncProblem."""- buf = io.StringIO()- n = len(su.problems)- try:- with contextlib.redirect_stdout(buf):- return fn(*a)- finally:- del su.problems[n:]---class PatchersOnUpstream(unittest.TestCase):- ref = os.environ.get('SYNC_PATCHERS_REF', 'seedds/main')-- @classmethod- def setUpClass(cls):- if not rev_ok(cls.ref):- raise unittest.SkipTest(f'{cls.ref} is not in this repository (git fetch seedds, or set SYNC_PATCHERS_REF)')-- def test_every_patcher_applies_to_upstreams_file(self):- with tempfile.TemporaryDirectory() as tmp:- for path, patcher in su.PATCHERS.items():- with self.subTest(path=path):- text = show(self.ref, path)- self.assertIsNotNone(text, f'{path} is not in {self.ref}: upstream moved or deleted a carrier')- f = Path(tmp) / path- f.parent.mkdir(parents=True, exist_ok=True)- f.write_text(text, encoding='utf-8')- try:- out = quiet(patcher, f.read_text(encoding='utf-8'))- except su.SyncProblem as e:- self.fail(f'the patcher no longer fits {self.ref}: {e}')- if out is None: out = text- self.assertNotEqual(out, text, f"{path}: the patcher changed nothing on upstream's own file (a marker that "- f"upstream's text satisfies, or a patch upstream has made itself): the fork's change would be dropped silently")- marks = su.MARKERS[path] if isinstance(su.MARKERS[path], tuple) else (su.MARKERS[path],)- self.assertTrue(any(m in out for m in marks), f'{path}: the marker is missing from the patched file')- f.write_text(out, encoding='utf-8')- again = quiet(patcher, out)- self.assertEqual(again if again is not None else out, out, f'{path}: applying the patcher twice changes the file')- if path.endswith('.py'):- ast.parse(out)- if path.endswith('.sh'):- r = subprocess.run(['bash', '-n', str(f)], capture_output=True, text=True)- self.assertEqual(r.returncode, 0, r.stderr)-- def test_the_runtime_profile_leaves_no_compiled_constant_behind(self):- for path in su.PROFILE_PATHS:- with self.subTest(path=path):- out = quiet(su.PATCHERS[path], show(self.ref, path))- left = sorted({m.group(2) for m in su._PROFILE_TOKEN.finditer(out) if m.group(2)}) # outside strings and comments- self.assertEqual(left, [], f'{path} still reads {left} at compile time')-- def test_the_patched_makefile_uses_one_compiler_spelling(self):- original = show(self.ref, su.TESTS_MK)- out = quiet(su.PATCHERS[su.TESTS_MK], original)- spelling = '$(CLANG)' if '$(CLANG)' in original else 'clang'- # a line the patcher only appended to keeps the spelling upstream gave it (upstream's own t_resolution rule says `clang`)- orig = [l for l in original.splitlines() if l.startswith('\t')]- added = [l for l in out.splitlines() if l not in original.splitlines() and l.startswith('\t') and 'clang' in l.lower()- and not any(l.startswith(o) for o in orig)]- self.assertTrue(added)- for l in added:- self.assertTrue(l.startswith('\t' + spelling + ' '), l)---class PatchersOnTheLastBase(unittest.TestCase):- """The patchers must also fit the base the fork was last synced from, so the same code runs before and after a sync."""-- def test_the_patchers_fit_the_last_sync_base(self):- base = last_base()- if not base: self.skipTest('the last sync base (.upstream-ref) is not in this repository')- for path, patcher in su.PATCHERS.items():- with self.subTest(path=path):- text = show(base, path)- self.assertIsNotNone(text)- try:- out = quiet(patcher, text)- except su.SyncProblem as e:- self.fail(f'the patcher does not fit the base {base[:7]}: {e}')- marks = su.MARKERS[path] if isinstance(su.MARKERS[path], tuple) else (su.MARKERS[path],)- self.assertTrue(any(m in (out if out is not None else text) for m in marks))-- def test_no_fork_edit_is_unprotected(self):- """A vendored file that differs from the last sync base must be in OURS, PATCHED or DROPPED."""- base = last_base()- if not base: self.skipTest('the last sync base (.upstream-ref) is not in this repository')- edited, _ = su.unprotected_edits(base)- self.assertEqual(edited, [], "these vendored files differ from the last sync base, and a sync would replace them with upstream's: "- 'add a patcher (PATCHERS, MARKERS, PATCHED), or OURS / DROPPED with the reason, in scripts/sync_upstream.py')---class Tables(unittest.TestCase):- def test_the_carrier_tables_are_consistent(self):- self.assertEqual(set(su.PATCHED), set(su.PATCHERS))- self.assertEqual(set(su.PATCHED), set(su.MARKERS))- self.assertFalse(set(su.OURS) & set(su.PATCHED), 'a file is both fork-owned and re-patched')- self.assertFalse((set(su.OURS) | set(su.PATCHED)) & set(su.DROPPED), 'a file is both protected and dropped')-- def test_ours_files_exist(self):- missing = [p for p in su.OURS if not (REPO / p).exists()]- self.assertEqual(missing, [], 'OURS lists files the fork does not have')-- def test_every_carrier_exists_in_the_fork(self):- missing = [p for p in su.PATCHED if not (REPO / p).exists()]- self.assertEqual(missing, [])---if __name__ == '__main__':- unittest.main()