Skip to content

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

Re-derive the patch series on seedds/nxnative 062cd06e (after #130, #137, #138)

v0lumehiaed88d357cae
diff --git a/dm/fork_patches.txt b/dm/fork_patches.txt
index 309bb4d9..1a70c351 100644
--- a/dm/fork_patches.txt
+++ b/dm/fork_patches.txt
@@ -2,21 +2,18 @@ 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-stamp
+nsp-dotnet-root-verify
+nsp-prune-intermediate-extracts
diff --git a/dm/ios/tests/test_ipa_unsigned.py b/dm/ios/tests/test_ipa_unsigned.py
index 68422194..42086883 100644
--- a/dm/ios/tests/test_ipa_unsigned.py
+++ b/dm/ios/tests/test_ipa_unsigned.py
@@ -55,7 +55,7 @@ class UnsignedIpaTests(unittest.TestCase):
return set(archive.namelist())
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).
+ # The fork ships a slim IPA by default: the app reads Documents/games/<id>/ (the fork patch ios-slim-ipa).
names = self.pack()
self.assertFalse([n for n in names if '/romfs' in n or '/aoc' in n])
diff --git a/dm/ios/tests/test_xcode_workflow.py b/dm/ios/tests/test_xcode_workflow.py
index 9b2b9fc9..2881f08c 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, 'check_glslang': None,
+ 'scan_nsps': (int(registered.id, 16), fam), 'check_prereqs': None, 'check_metal': 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/dm/mac/pack_app.py b/dm/mac/pack_app.py
index 44d83c23..6f28830c 100755
--- a/dm/mac/pack_app.py
+++ b/dm/mac/pack_app.py
@@ -110,11 +110,18 @@ def settings_rules(listed): # DMSettings: what the launcher accepts as each se
return rules
+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'
if a.settings:
listed = json.loads(Path(a.settings).read_text(encoding='utf-8'))['settings']
diff --git a/patches/0001-runtime-profile.patch b/patches/0001-runtime-profile.patch
index 5dd33e2a..ebf5a081 100644
--- a/patches/0001-runtime-profile.patch
+++ b/patches/0001-runtime-profile.patch
@@ -18,22 +18,22 @@ Issue: LNPANDY/NX2Apple#123
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/hle_svc.c | 34 ++---
dm/host/loader.c | 2 +-
- dm/host/tests/Makefile | 48 +++---
+ dm/host/tests/Makefile | 50 +++----
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(-)
+ 13 files changed, 466 insertions(+), 48 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
+index aea6f1ba..19688ea6 100644
--- a/dm/games/game.py
+++ b/dm/games/game.py
-@@ -186,6 +186,40 @@ if __name__ == '__main__':
+@@ -187,6 +187,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)
@@ -75,7 +75,7 @@ index 5527a666..48e1db1b 100644
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
+index c1be8d46..54f15f61 100644
--- a/dm/host/dm.h
+++ b/dm/host/dm.h
@@ -7,6 +7,7 @@
@@ -87,23 +87,23 @@ index 4f94bbb0..54a96b35 100644
// 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
+index 7e54f037..466687e5 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"))
+@@ -132,7 +132,7 @@ void dm_fps_lock_tick(void) {
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;
+ }
+ if (!nrow && !nier) 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; }
+ 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); if (nier) LOG("main: NieR frame interval left as the game sets it (%s)", src); return; }
target = t; state = 0;
diff --git a/dm/host/hle_fs.c b/dm/host/hle_fs.c
-index 26da5c05..92bb7a5b 100644
+index 74fe1331..035dbc04 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
+@@ -585,7 +585,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) {
@@ -426,114 +426,109 @@ index 00000000..a2febeb3
+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
+index 3ded3ab3..0673018b 100644
--- a/dm/host/hle_svc.c
+++ b/dm/host/hle_svc.c
-@@ -15,7 +15,10 @@
+@@ -16,7 +16,7 @@
// 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)
++#define RESERVE (dm_profile()->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)
static uint8_t *g_as; // ASLR region base = the whole block
+ static size_t g_reserve; // its size: RESERVE, or more with a DM_ALIAS_SIZE alias region
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);
+@@ -33,15 +33,15 @@ static void *alias_windows_thread(void *arg);
+ static void *regions_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)))
++ if (RESERVE < 0x10000000 || (dm_profile()->mem_alias) > RESERVE - 0x10000000 ||
++ (dm_profile()->mem_stack) > RESERVE - 0x10000000 - (dm_profile()->mem_alias) ||
++ ((RESERVE | (dm_profile()->mem_alias) | (dm_profile()->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);
+ // DM_ALIAS_SIZE=<bytes>: an alias region of that size instead of the profile's, the heap and stacks as they are; the block grows with it. A Switch-sized one (64 GB) holds what
+ // a game reserves unchanged, for measuring its address regions on the Mac (the NSP script's heap check); an iPhone has no room for more than the profile's
+- size_t alias = DM_GAME_MEM_ALIAS; const char *as = getenv("DM_ALIAS_SIZE");
++ size_t alias = (dm_profile()->mem_alias); const char *as = getenv("DM_ALIAS_SIZE");
+ if (as && *as) { alias = (size_t)strtoull(as, NULL, 0); if (alias < 0x10000000 || (alias & (pg - 1))) die("DM_ALIAS_SIZE %s: at least 256 MB, in whole host pages", as); }
+- g_reserve = RESERVE - DM_GAME_MEM_ALIAS + alias;
++ g_reserve = RESERVE - (dm_profile()->mem_alias) + alias;
+ g_as = mmap(NULL, g_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)
+ // Fixed partition (all inside the reserved block): alias 2.875 GB, stack 256 MB, heap the remaining 1.625 GB.
+@@ -51,7 +51,7 @@ static void mem_init_once(void) {
// 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_alias = g_as + 0x10000000; g_alias_cap = 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);
++ g_stack = g_alias + g_alias_cap; g_stack_cap = (dm_profile()->mem_stack);
+ g_heap = g_stack + g_stack_cap; g_heap_cap = g_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) {
+@@ -70,7 +70,7 @@ 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) {
+@@ -415,11 +415,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());
++ (unsigned long long)APP_POOL, (unsigned long long)(dm_profile()->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)) {
++ uint64_t charged = (uint64_t)(dm_profile()->mem_used) + big_bss_bytes() + atomic_load(&g_alias_mapped);
++ if ((dm_profile()->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) {
+@@ -562,8 +562,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 ((dm_profile()->mem_map_limit) && num == 0x2C) {
++ int64_t room = (int64_t)APP_POOL - (int64_t)(g_heap_cur + (dm_profile()->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) {
+@@ -625,16 +625,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)
++ v = g_heap_cur + (dm_profile()->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);
++ if ((dm_profile()->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_SysResTotal: v = (dm_profile()->sys_resource); break; case I_SysResUsed: v = (dm_profile()->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_ProgramId: { static uint64_t pid; if (!pid) { const char *e = getenv("DM_PROGRAM_ID"); pid = e ? strtoull(e, NULL, 16) : (dm_profile()->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
+index 0ede3cca..c45124eb 100644
--- a/dm/host/loader.c
+++ b/dm/host/loader.c
-@@ -227,7 +227,7 @@ static void install_fps_state(module_t *m) {
+@@ -228,7 +228,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;
@@ -543,132 +538,142 @@ index cd4af6a6..8d82c284 100644
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
+index 8fa8b342..cecd380f 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_
+@@ -51,7 +51,7 @@ run: $(B)/t_motion $(B)/t_heap_size $(B)/t_touch $(B)/t_gesture $(B)/t_oe $(B)/t
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
+- $(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_
+@@ -69,12 +69,12 @@ $(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
+- $(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
+- $(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):
+@@ -82,7 +82,7 @@ nro: $(B)/t_nro
+ $(GAME_H): FORCE
$(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
+- $(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
+@@ -92,17 +92,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
+ $(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
+- $(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
+- $(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
++ $(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
++ $(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
+- $(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
+- $(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
++ $(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
+ $(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
+@@ -117,7 +117,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
+- $(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
+ $(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) | $
+@@ -125,7 +125,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
+ $(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 ..
+- $(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_motion: t_motion.c ../motion_fusion.h | $(B)
+ $(CLANG) -O1 -Wall -Werror -Wno-unused-function -o $@ t_motion.c -lm
+ run: $(B)/t_motion_apple
+@@ -147,13 +147,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
+ $(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
+- $(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
+- $(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
+- $(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
+- $(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
+@@ -175,7 +175,7 @@ $(B):
+ mkdir -p $@
+ .PHONY: run tsan
+ $(B)/t_resolution: t_resolution.c ../hle_fpslock.c ../hle.h ../dm.h $(GAME_H) | $(B)
+- clang -O1 -Wall -Werror -Wno-unused-function -fsanitize=undefined -I.. $(GINC) -o $@ t_resolution.c
++ $(CLANG) -O1 -Wall -Werror -Wno-unused-function -fsanitize=undefined -I.. $(GINC) -o $@ t_resolution.c ../hle_profile.c
+ .PHONY: resolution
+ run: resolution
+ resolution: $(B)/t_resolution
+@@ -188,17 +188,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
+- $(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
+- $(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
+- $(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
+- $(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
+- $(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
+@@ -214,7 +214,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
+- $(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
@@ -782,10 +787,10 @@ index 00000000..20b210d4
+ return bad ? 1 : 0;
+}
diff --git a/dm/ios/Sources/DmGamepad.m b/dm/ios/Sources/DmGamepad.m
-index c3ac8c16..3ac81d95 100644
+index f80c205c..9a204578 100644
--- a/dm/ios/Sources/DmGamepad.m
+++ b/dm/ios/Sources/DmGamepad.m
-@@ -156,7 +156,7 @@ - (instancetype)initWithFrame:(CGRect)f {
+@@ -186,7 +186,7 @@ - (instancetype)initWithFrame:(CGRect)f {
}
_swap = shape(_controls); _swapLabel = label(_swap, @"");
NSNumber *saved = [NSUserDefaults.standardUserDefaults objectForKey:k_layout_key];
@@ -795,10 +800,10 @@ index c3ac8c16..3ac81d95 100644
_full = l == 1; _tap = l == 2;
[self applyLayout];
diff --git a/docs/env_switches.tsv b/docs/env_switches.tsv
-index 814429dc..242056b6 100644
+index 527c3676..b427084e 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
+@@ -206,6 +206,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
diff --git a/patches/0002-romfsarc.patch b/patches/0002-romfsarc.patch
index 2580a388..ff672cb7 100644
--- a/patches/0002-romfsarc.patch
+++ b/patches/0002-romfsarc.patch
@@ -11,14 +11,14 @@ Reason: Legacy ROMFSARC shard archives (Tears of the Kingdom, 300k files) that p
Issue: LNPANDY/NX2Apple#123
---
dm/host/Makefile | 2 +-
- dm/host/hle_fs.c | 138 +++++++++++++++++-
+ dm/host/hle_fs.c | 140 ++++++++++++++++++-
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(-)
+ 8 files changed, 924 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
@@ -26,7 +26,7 @@ Issue: LNPANDY/NX2Apple#123
create mode 100644 docs/ROMFS_ARCHIVE.md
diff --git a/dm/host/Makefile b/dm/host/Makefile
-index c0ec1066..e820e8b8 100644
+index 410b6ce4..2baa234b 100644
--- a/dm/host/Makefile
+++ b/dm/host/Makefile
@@ -16,7 +16,7 @@ endif
@@ -39,7 +39,7 @@ index c0ec1066..e820e8b8 100644
# 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
+index 035dbc04..643306f9 100644
--- a/dm/host/hle_fs.c
+++ b/dm/host/hle_fs.c
@@ -7,6 +7,7 @@
@@ -50,7 +50,7 @@ index 92bb7a5b..f1089b93 100644
#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)
+@@ -382,6 +383,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);
@@ -79,7 +79,7 @@ index 92bb7a5b..f1089b93 100644
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) {
+@@ -426,9 +449,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; }
@@ -104,7 +104,7 @@ index 92bb7a5b..f1089b93 100644
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
+@@ -708,6 +744,43 @@ 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 ----------
@@ -112,6 +112,8 @@ index 92bb7a5b..f1089b93 100644
+// 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];
@@ -119,15 +121,15 @@ index 92bb7a5b..f1089b93 100644
+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 ((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 >> 63)) return 0;
++ 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) & 0x7fffffff) != (uint32_t)(g_arch_gen & 0x7fffffff)) 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) {
@@ -146,7 +148,7 @@ index 92bb7a5b..f1089b93 100644
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
+@@ -720,6 +793,15 @@ HLE_FORCE("_ZN2nn2fs8OpenFileEPNS0_10FileHandleEPKci", "fsp-srv → open(2)", Re
}
HP(path);
if (mode & (MODE_WRITE | MODE_APPEND)) RW();
@@ -155,14 +157,14 @@ index 92bb7a5b..f1089b93 100644
+ 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;
++ *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);
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)",
+@@ -743,6 +825,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
@@ -183,23 +185,23 @@ index 92bb7a5b..f1089b93 100644
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
+@@ -799,6 +895,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) {
+ 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; }
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)
+@@ -815,6 +912,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) {
+ 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 >> 63) { arc_free(h); return; } // archive entry: nothing to close
++ if ((h >> 57) == 1) { 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 →
+ HLE_FORCE("_ZN2nn2fs15GetFileOpenModeENS0_10FileHandleE", "fsp-srv; the open mode is recorded by the host", int, h_fs_GetFileOpenMode, uint64_t h) { h = FH_IN(h); return IMG_H(h) ? MODE_READ : g_fmode[(int)h & 0xffff]; }
+@@ -898,12 +996,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;
@@ -237,9 +239,9 @@ index 92bb7a5b..f1089b93 100644
+ free(ents);
+}
static void dir_snapshot(dirh_t *h, const mount_t *m, const char *rest) {
+ char fwd[1024]; rest = fwd_slashes(rest, fwd, sizeof fwd);
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
+@@ -965,7 +1090,15 @@ HLE_FORCE("_ZN2nn2fs13OpenDirectoryEPNS0_15DirectoryHandleEPKci", "fsp-srv → o
}
*out = (uint64_t)h; return RES_OK;
}
@@ -256,7 +258,7 @@ index 92bb7a5b..f1089b93 100644
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
+@@ -978,6 +1111,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; }
@@ -605,32 +607,32 @@ index 00000000..c4a25b48
+
+#endif
diff --git a/dm/host/tests/Makefile b/dm/host/tests/Makefile
-index 61b6b573..ad9bb9aa 100644
+index cecd380f..36e32768 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
+@@ -92,17 +92,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
+ $(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
+- $(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
+- $(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
++ $(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
++ $(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
+ $(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
+- $(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
++ $(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
+ $(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
diff --git a/patches/0003-ios-game-data-folder.patch b/patches/0003-ios-game-data-folder.patch
index 6eccf8cd..daab294f 100644
--- a/patches/0003-ios-game-data-folder.patch
+++ b/patches/0003-ios-game-data-folder.patch
@@ -15,10 +15,10 @@ Issue: LNPANDY/NX2Apple#123
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/Sources/main.m | 109 +++++++++++++++++++++++--
dm/ios/project.yml | 1 +
dm/ios/tests/test_romfs_startup.py | 41 +++++++++-
- 8 files changed, 353 insertions(+), 12 deletions(-)
+ 8 files changed, 354 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
@@ -156,12 +156,12 @@ index 00000000..92a2b3a5
+// 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
+index dc63e4e3..df41a708 100644
--- a/dm/ios/Sources/Launcher.swift
+++ b/dm/ios/Sources/Launcher.swift
-@@ -64,6 +64,93 @@ private struct SettingRow: View {
- }
- }
+@@ -8,6 +8,93 @@ import os
+
+ private func info(_ key: String) -> Any? { Bundle.main.object(forInfoDictionaryKey: key) }
+/// Where this game's data comes from, and a picker to change it.
+///
@@ -253,7 +253,7 @@ index 3c72edea..1e21e9c9 100644
private struct LauncherView: View {
@ObservedObject var m: LauncherModel
let play: () -> Void
-@@ -98,6 +185,7 @@ private struct LauncherView: View {
+@@ -45,6 +132,7 @@ private struct LauncherView: View {
} footer: {
Text("Brings back all settings this game was tested with.")
}
@@ -262,18 +262,18 @@ index 3c72edea..1e21e9c9 100644
HStack {
Text("Memory available")
diff --git a/dm/ios/Sources/front_ios.m b/dm/ios/Sources/front_ios.m
-index 9cd03bad..fef3aa8a 100644
+index 45aa526b..56a432f1 100644
--- a/dm/ios/Sources/front_ios.m
+++ b/dm/ios/Sources/front_ios.m
-@@ -15,6 +15,7 @@
- void front_ios_boot(void);
+@@ -16,6 +16,7 @@
int front_ios_boot_ok(void);
+ const char *front_ios_boot_message(void); // main.m: why a build that keeps the game files off the IPA found none usable (NULL = the generic hint)
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
+@@ -47,6 +48,7 @@ @interface DmRootVC : UIViewController
@property (nonatomic, strong) UIView *pad;
@property (nonatomic, strong) UILabel *fps;
@property (nonatomic) BOOL launched;
@@ -281,7 +281,7 @@ index 9cd03bad..fef3aa8a 100644
- (void)startGame;
@end
static DmRootVC *g_root;
-@@ -67,6 +69,14 @@ - (void)viewDidLoad {
+@@ -69,6 +71,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;
@@ -296,8 +296,8 @@ index 9cd03bad..fef3aa8a 100644
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];
+@@ -104,7 +114,8 @@ - (void)viewDidAppear:(BOOL)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
@@ -307,11 +307,11 @@ index 9cd03bad..fef3aa8a 100644
- (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
+index fb37046e..5afddbb6 100644
--- a/dm/ios/Sources/main.m
+++ b/dm/ios/Sources/main.m
-@@ -6,9 +6,10 @@
- #include <stdio.h>
+@@ -7,9 +7,10 @@
+ #include <string.h>
#include <sys/stat.h>
#include <unistd.h>
-#include "game_profile.h" // game profile constants (the RomFS marker path)
@@ -319,12 +319,12 @@ index eb0f56a3..b546e1bf 100644
#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;
+ #include "romfs_identity.h"
+ #include "player_env.h"
+ #ifndef DM_PLAYER_BUILD
+@@ -40,9 +41,59 @@ static int romfs_identity_accepts(NSString *img) {
+ if (rc != ROMFS_ID_OK && rc != ROMFS_ID_NONE) fprintf(stderr, "[RED] boot: Documents/romfs.img is not the image this build needs (verdict %d); not used\n", rc);
+ return rc == ROMFS_ID_OK || rc == ROMFS_ID_NONE;
}
+// 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.
@@ -380,9 +380,9 @@ index eb0f56a3..b546e1bf 100644
+ 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)) {
+ 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
-@@ -43,13 +94,48 @@ static int romfs_image_complete(NSString *path) {
+@@ -58,13 +109,48 @@ static int romfs_identity_accepts(NSString *img) {
}
NSString *bundledImage = [NSBundle.mainBundle.resourcePath stringByAppendingPathComponent:@"romfs.img"];
NSString *documentFolder = [doc stringByAppendingPathComponent:@"romfs"];
@@ -431,9 +431,9 @@ index eb0f56a3..b546e1bf 100644
+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) {
+ // Why a slim build found no usable game files: the verdict on Documents/romfs.img, in the log and for the screen (front_ios_boot_message). NULL when the build has no romfs.id
+ static char g_boot_message[640];
+@@ -127,15 +213,20 @@ 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");
@@ -441,13 +441,14 @@ index eb0f56a3..b546e1bf 100644
+ // 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; }
+- if (!romfs) { romfs_identity_report(doc); 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");
++ if (!set_data_env(romfs, NO)) { if (!romfs) romfs_identity_report(doc); // a slim build says why its romfs.img was not used
++ 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);
@@ -472,12 +473,12 @@ index 4a1e3b65..298b2eed 100644
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
+index b31ad6ed..82d0ff92 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):
+@@ -24,12 +24,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'
+ source.write_text('#import <Foundation/Foundation.h>\n#include <stdio.h>\n#include "romfs_image.h"\n#include "romfs_identity.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'
@@ -497,9 +498,9 @@ index 89e4f220..271744e3 100644
'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'))
+@@ -92,5 +99,35 @@ class Startup(unittest.TestCase):
+ shutil.copy(root / 'other.img', doc / 'romfs.img')
+ self.assertEqual(locate().stdout.strip(), 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."""
diff --git a/patches/0004-ios-slim-ipa.patch b/patches/0004-ios-slim-ipa.patch
index 41980907..12c4107f 100644
--- a/patches/0004-ios-slim-ipa.patch
+++ b/patches/0004-ios-slim-ipa.patch
@@ -6,15 +6,57 @@ Subject: [PATCH] build_ipa.sh: slim package by default (DM_FULL_ROMFS=1 packs
Maps the RomFS and add-on content into the IPA only with DM_FULL_ROMFS; the app reads them from Documents/games/<id>/.
+The unsigned-IPA tests (test_ipa_unsigned.py, test_profile_pack.py) start from the slim default and check DM_FULL_ROMFS=1 for the packed form (LNPANDY/NX2Apple#137).
+
Upstream-Status: fork-only (upstream has the opt-in DM_COPY_ROMFS=NO since 32ae3b11; the fork's slim default differs)
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_ipa_unsigned.py | 13 +++++++++----
dm/ios/tests/test_profile_pack.py | 3 ++-
- dm/ios/tools/build_ipa.sh | 20 +++++++++++++++++---
+ dm/ios/tools/build_ipa.sh | 9 ++++++++-
docs/env_switches.tsv | 1 +
- 3 files changed, 20 insertions(+), 4 deletions(-)
+ 4 files changed, 20 insertions(+), 6 deletions(-)
+diff --git a/dm/ios/tests/test_ipa_unsigned.py b/dm/ios/tests/test_ipa_unsigned.py
+index 028d5067..42086883 100644
+--- a/dm/ios/tests/test_ipa_unsigned.py
++++ b/dm/ios/tests/test_ipa_unsigned.py
+@@ -54,8 +54,13 @@ class UnsignedIpaTests(unittest.TestCase):
+ if identity is not None: identity.append((archive.read('Payload/DmIOS.app/romfs.id').decode() if 'Payload/DmIOS.app/romfs.id' in archive.namelist() else None, (root / 'RomFS.img').read_bytes() if image else None))
+ return set(archive.namelist())
+
+- def test_game_files_are_packed_by_default(self):
++ def test_game_files_are_not_packed_by_default(self):
++ # The fork ships a slim IPA by default: the app reads Documents/games/<id>/ (the fork patch ios-slim-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)
+
+@@ -64,7 +69,7 @@ class UnsignedIpaTests(unittest.TestCase):
+ self.assertFalse([n for n in names if '/romfs' in n])
+ self.assertIn('Payload/DmIOS.app/executable', names)
+ self.assertIn('Payload/DmIOS.app/msl/b-fixture/fixture_b.metallib', 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')
+
+ def test_slim_ipa_of_an_image_carries_its_identity_and_the_default_does_not(self):
+ got = []
+@@ -76,8 +81,8 @@ class UnsignedIpaTests(unittest.TestCase):
+ with tempfile.NamedTemporaryFile() as f:
+ f.write(data); f.flush(); self.assertTrue(romfs_image.same_identity(line, romfs_image.identity(f.name)))
+ got = []
+- 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])
+
+ def test_slim_ipa_of_a_folder_has_no_identity(self):
+ self.assertNotIn('Payload/DmIOS.app/romfs.id', self.pack(DM_COPY_ROMFS='NO'))
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
@@ -30,46 +72,40 @@ index 40db2b76..0407560d 100644
diff --git a/dm/ios/tools/build_ipa.sh b/dm/ios/tools/build_ipa.sh
-index 3b4af1e7..25692fc8 100755
+index e2c174d1..3d8f5c73 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"
+@@ -174,6 +174,9 @@ if [ -n "${DM_ENTITLEMENTS-default}" ]; then
+ fi
P=Payload/DmIOS.app
--if [ -f "$ROMFS" ]; then MAPS=("$P/romfs.img=$ROMFS"); else MAPS=("$P/romfs=$ROMFS"); fi
+ 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
+ t "no game files in the IPA (DM_COPY_ROMFS=NO): the app takes Documents/romfs.img (scripts/push_romfs.sh)"
+ # The image's identity (dm/host/romfs_identity.h) goes into the app as romfs.id: main.m then uses only a Documents/romfs.img with the same size and index hash, and says so when it is another version or missing.
+@@ -183,7 +186,11 @@ if [ "${DM_COPY_ROMFS:-YES}" = NO ]; then
+ MAPS=("$P/romfs.id=$O/romfs.id"); t "game files identity: $(cat "$O/romfs.id")"
+ fi
+ elif [ -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
++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
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"
+ t "pack IPA (already-compressed game files stored, everything else deflated)"
diff --git a/docs/env_switches.tsv b/docs/env_switches.tsv
-index 242056b6..34c7bf88 100644
+index b427084e..4b731480 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
+@@ -36,6 +36,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_FULLSCREEN player `1` (any value but `0`) starts the Mac window in fullscreen; `0` or unset, a window. The Mac settings window's Display mode
+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
diff --git a/patches/0005-ios-entitlements.patch b/patches/0005-ios-entitlements.patch
deleted file mode 100644
index 5aa22313..00000000
--- a/patches/0005-ios-entitlements.patch
+++ /dev/null
@@ -1,149 +0,0 @@
-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/0005-nsp-dotnet-home.patch
similarity index 90%
rename from patches/0006-nsp-dotnet-home.patch
rename to patches/0005-nsp-dotnet-home.patch
index a815fff3..cf0393c0 100644
--- a/patches/0006-nsp-dotnet-home.patch
+++ b/patches/0005-nsp-dotnet-home.patch
@@ -14,19 +14,19 @@ Issue: LNPANDY/NX2Apple#10
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
+index a0b93d6c..e7a5afd4 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
+-import ast, collections, ctypes, errno, getpass, hashlib, importlib.util, json, os, re, shlex, shutil, struct, subprocess, sys, tempfile, threading, time, types
++import ast, collections, ctypes, errno, 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):
+@@ -2169,6 +2169,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)
diff --git a/patches/0009-nsp-chain-changed-note.patch b/patches/0006-nsp-chain-changed-note.patch
similarity index 94%
rename from patches/0009-nsp-chain-changed-note.patch
rename to patches/0006-nsp-chain-changed-note.patch
index 7eb0d37a..fa16d0b0 100644
--- a/patches/0009-nsp-chain-changed-note.patch
+++ b/patches/0006-nsp-chain-changed-note.patch
@@ -14,10 +14,10 @@ Issue: LNPANDY/NX2Apple#123
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
+index e7a5afd4..a963998b 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):
+@@ -1720,6 +1720,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)
diff --git a/patches/0007-nsp-exfat-appledouble.patch b/patches/0007-nsp-exfat-appledouble.patch
deleted file mode 100644
index 6be42d5a..00000000
--- a/patches/0007-nsp-exfat-appledouble.patch
+++ /dev/null
@@ -1,44 +0,0 @@
-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/0010-nsp-work-dir.patch b/patches/0007-nsp-work-dir.patch
similarity index 96%
rename from patches/0010-nsp-work-dir.patch
rename to patches/0007-nsp-work-dir.patch
index 97249db1..72959d00 100644
--- a/patches/0010-nsp-work-dir.patch
+++ b/patches/0007-nsp-work-dir.patch
@@ -14,10 +14,10 @@ Issue: LNPANDY/NX2Apple#123
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
+index a963998b..5d973e24 100755
--- a/scripts/build_ipa_from_nsp.py
+++ b/scripts/build_ipa_from_nsp.py
-@@ -1873,6 +1873,7 @@ def parse_args(argv):
+@@ -2062,6 +2062,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)')
@@ -25,7 +25,7 @@ index 571f2c76..89ff8595 100755
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):
+@@ -2238,10 +2239,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 [])
diff --git a/patches/0011-bc-cpu-decode.patch b/patches/0008-bc-cpu-decode.patch
similarity index 99%
rename from patches/0011-bc-cpu-decode.patch
rename to patches/0008-bc-cpu-decode.patch
index ac91f7c7..8f94f308 100644
--- a/patches/0011-bc-cpu-decode.patch
+++ b/patches/0008-bc-cpu-decode.patch
@@ -43,7 +43,7 @@ index 8a8adb89..223a7f71 100644
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
+index 19688ea6..49321b77 100644
--- a/dm/games/game.py
+++ b/dm/games/game.py
@@ -119,6 +119,8 @@ def header(g):
@@ -55,7 +55,7 @@ index 48e1db1b..4e0af38f 100644
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):
+@@ -171,6 +173,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")}',
@@ -64,7 +64,7 @@ index 48e1db1b..4e0af38f 100644
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
+index 5c792590..5568f083 100644
--- a/dm/gfx/nvn/nvn_mtl.m
+++ b/dm/gfx/nvn/nvn_mtl.m
@@ -20,6 +20,7 @@
@@ -84,7 +84,7 @@ index ad381d60..8f753bc3 100644
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) {
+@@ -388,6 +391,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)");
@@ -94,7 +94,7 @@ index ad381d60..8f753bc3 100644
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) {
+@@ -1773,7 +1779,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];
@@ -108,7 +108,7 @@ index ad381d60..8f753bc3 100644
// 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) {
+@@ -2217,15 +2228,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;
}
@@ -153,7 +153,7 @@ index ad381d60..8f753bc3 100644
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) {
+@@ -2234,6 +2273,7 @@ static void zb_report(const tex_t *t, unsigned base, const char *why) {
off += pitch * rows * z;
}
}
diff --git a/patches/0008-nsp-early-checks.patch b/patches/0008-nsp-early-checks.patch
deleted file mode 100644
index be2fbe2b..00000000
--- a/patches/0008-nsp-early-checks.patch
+++ /dev/null
@@ -1,84 +0,0 @@
-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/0012-mac-keymap.patch b/patches/0009-mac-keymap.patch
similarity index 80%
rename from patches/0012-mac-keymap.patch
rename to patches/0009-mac-keymap.patch
index 129a0236..1e35ff55 100644
--- a/patches/0012-mac-keymap.patch
+++ b/patches/0009-mac-keymap.patch
@@ -23,27 +23,28 @@ Issue: LNPANDY/NX2Apple#386
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
+index eb833d10..3df6394d 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.
+ // The window is fullscreen-capable (the green button and ⌃⌘F); DM_FULLSCREEN=1 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 @@
+@@ -14,6 +15,7 @@
#include "front.h"
#include "hle.h"
#include "pad_slots.h"
+#include "input_map.h"
#include "haptics_apple.h"
- #include <signal.h>
- #include <math.h>
+ #include "motion_apple.h"
+ #include "motion_pro_mac.h"
+@@ -22,7 +24,6 @@
static CAMetalLayer *g_layer;
static uint64_t g_btn;
@@ -51,7 +52,7 @@ index a99ce4da..423c581f 100644
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) {
+@@ -86,27 +87,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(); });
}
@@ -89,7 +90,7 @@ index a99ce4da..423c581f 100644
push();
}
-@@ -114,6 +108,7 @@ static void on_key(NSEvent *e, int down) {
+@@ -118,6 +112,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;
@@ -97,24 +98,24 @@ index a99ce4da..423c581f 100644
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) {
+@@ -130,6 +125,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)
+ // Home and Capture: without this macOS takes them as system gestures (Home opens the Games app); the host gives them no function
+@@ -186,7 +182,7 @@ static void pads_changed(GCController *gone) {
static void input_release(void) {
g_input_on = 0;
+ dm_motion_pro_active(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) {
+@@ -198,6 +194,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) {
@@ -125,7 +126,7 @@ index a99ce4da..423c581f 100644
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
+@@ -356,7 +356,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)
@@ -223,38 +224,38 @@ index 00000000..56fa4993
+}
+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
+index 36e32768..0b651aa9 100644
--- a/dm/host/tests/Makefile
+++ b/dm/host/tests/Makefile
-@@ -7,7 +7,7 @@ PYTHON ?= python3
+@@ -12,7 +12,7 @@ QUIET = $(if $(strip $(SAN)),,2>/dev/null)
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
+-run: $(B)/t_motion $(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_motion $(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
+@@ -44,6 +44,8 @@ run: $(B)/t_motion $(B)/t_heap_size $(B)/t_touch $(B)/t_gesture $(B)/t_oe $(B)/t
+ $(B)/t_motion_pro
+ $(B)/t_motion_pro_mac
$(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
+@@ -136,6 +138,10 @@ $(B)/t_motion_pro: t_motion_pro.c ../motion_pro.h | $(B)
+ $(CLANG) -O1 -g -Wall -Werror -fsanitize=address,undefined -o $@ t_motion_pro.c
+ $(B)/t_motion_pro_mac: t_motion_pro_mac.m ../motion_pro_mac.h ../motion_pro.h ../dm_input.h | $(B)
+ $(CLANG) -O1 -g -fobjc-arc -Wall -Werror -Wno-unused-function -fsanitize=address,undefined -I.. -o $@ t_motion_pro_mac.m -framework Foundation -framework GameController -framework IOKit
+$(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
++ $(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)
++ $(CLANG) -O1 -Wall -Werror -Wno-unused-function -I.. -o $@ t_launcher_contract.c
+ $(B)/t_hid: t_hid.c ../hle_hid.c ../motion_fusion.h ../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 ../motion_fusion.h ../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
@@ -346,46 +347,47 @@ index 00000000..136b4035
+ return fails != 0;
+}
diff --git a/dm/tools/impact_map.tsv b/dm/tools/impact_map.tsv
-index df05fa53..22e68677 100644
+index e0146e9b..914908af 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
+@@ -110,6 +110,7 @@ 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
+ dm/host/dm_input.h hle:*hid* the shared input interface
+ dm/host/motion_apple.h hle:*SixAxisSensor* controller motion supplied by GameController
+ dm/host/motion_fusion.h hle:*SixAxisSensor* six-axis motion mapping and orientation
diff --git a/docs/development.md b/docs/development.md
-index 88703bb1..06b31d10 100644
+index be56bfd0..bcb1028e 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`) |
+-| 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. Motion: a controller with a gyroscope drives its player's six-axis sensor (`motion_apple.h` → `dm_motion_set`, `hle_hid.c`; orientation from the gyro with tilt correction toward gravity, `motion_fusion.h`), and on iOS the phone's own device motion drives player 1's while no controller supplies fresh motion (`DmGamepad.m`, turned into the Switch frame for the screen's orientation; `DM_PHONE_MOTION=0|1|auto`; `1` selects only the phone). On the Mac, a Switch Pro Controller whose GameController motion is empty can use passive HID reports instead (`motion_pro_mac.h`; `DM_MOTION_HID=0` turns this reader off). This requires exactly one Pro in each API so it can use the same player slot without guessing; multiple Pros retain GameController input. Raw HID has its own orientation and nominal sensor scales; hardware validation of the reworked reader remains open ([Pro Controller fallback](reference/services.md#switch-pro-controller-advertises-motion-but-sends-zeroes)). `DM_MOTION_AXES` / `DM_MOTION_ACC_SIGN` apply only to GameController. Each source keeps its own orientation. Without live motion the sensor lies flat as before. `DM_MOTION_LOG=1` logs player 1's mapped sample once a second per source; `DM_MOTION_AXES` (e.g. `x,-z,y`) and `DM_MOTION_ACC_SIGN=-1` remap a controller whose axes differ, `DM_MOTION_GAIN` sets the tilt correction (0.5), `DM_MOTION=0` turns motion off (the NSP script's `--no-motion` builds it in). The console's own sensor (`SevenSixAxisSensor`, read in handheld mode) still reports no states. 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. Motion: a controller with a gyroscope drives its player's six-axis sensor (`motion_apple.h` → `dm_motion_set`, `hle_hid.c`; orientation from the gyro with tilt correction toward gravity, `motion_fusion.h`), and on iOS the phone's own device motion drives player 1's while no controller supplies fresh motion (`DmGamepad.m`, turned into the Switch frame for the screen's orientation; `DM_PHONE_MOTION=0|1|auto`; `1` selects only the phone). On the Mac, a Switch Pro Controller whose GameController motion is empty can use passive HID reports instead (`motion_pro_mac.h`; `DM_MOTION_HID=0` turns this reader off). This requires exactly one Pro in each API so it can use the same player slot without guessing; multiple Pros retain GameController input. Raw HID has its own orientation and nominal sensor scales; hardware validation of the reworked reader remains open ([Pro Controller fallback](reference/services.md#switch-pro-controller-advertises-motion-but-sends-zeroes)). `DM_MOTION_AXES` / `DM_MOTION_ACC_SIGN` apply only to GameController. Each source keeps its own orientation. Without live motion the sensor lies flat as before. `DM_MOTION_LOG=1` logs player 1's mapped sample once a second per source; `DM_MOTION_AXES` (e.g. `x,-z,y`) and `DM_MOTION_ACC_SIGN=-1` remap a controller whose axes differ, `DM_MOTION_GAIN` sets the tilt correction (0.5), `DM_MOTION=0` turns motion off (the NSP script's `--no-motion` builds it in). The console's own sensor (`SevenSixAxisSensor`, read in handheld mode) still reports no states. 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
+index 4b731480..e8b7ca63 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
+@@ -56,6 +56,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_LAUNCHER switch `0` skips the iOS settings screen or the Mac settings window and starts the game at once, with the saved choices (on the Mac also `--no-launcher`)
+@@ -182,6 +183,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 SVC
+ DM_PHONE_MOTION switch On iOS, whether the phone's own device motion drives player 1's six-axis sensor: `auto` (default) while no controller supplies fresh motion, `1` phone only, `0` never; each source keeps its own orientation
diff --git a/patches/0014-mac-library-folder.patch b/patches/0010-mac-library-folder.patch
similarity index 97%
rename from patches/0014-mac-library-folder.patch
rename to patches/0010-mac-library-folder.patch
index 2bda62c7..ccc7e426 100644
--- a/patches/0014-mac-library-folder.patch
+++ b/patches/0010-mac-library-folder.patch
@@ -13,10 +13,10 @@ Issue: LNPANDY/NX2Apple#123
1 file changed, 87 insertions(+)
diff --git a/dm/mac/launcher.c b/dm/mac/launcher.c
-index 3c5d1fef..3873b7ad 100644
+index e9f154e7..af479db7 100644
--- a/dm/mac/launcher.c
+++ b/dm/mac/launcher.c
-@@ -16,6 +16,7 @@
+@@ -22,6 +22,7 @@
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
@@ -24,7 +24,7 @@ index 3c5d1fef..3873b7ad 100644
#include <sys/wait.h>
#include <unistd.h>
#include "romfs_image.h"
-@@ -58,6 +59,43 @@ static void mkdirs(const char *path) { // mkdir -p
+@@ -72,6 +73,43 @@ static void mkdirs(const char *path) { // mkdir -p
mkdir(p, 0755);
}
@@ -68,7 +68,7 @@ index 3c5d1fef..3873b7ad 100644
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) {
+@@ -159,8 +197,57 @@ int main(int argc, char **argv) {
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);
diff --git a/patches/0015-hades2-update-profile.patch b/patches/0011-hades2-update-profile.patch
similarity index 100%
rename from patches/0015-hades2-update-profile.patch
rename to patches/0011-hades2-update-profile.patch
diff --git a/patches/0017-env-switches-verify.patch b/patches/0012-env-switches-verify.patch
similarity index 98%
rename from patches/0017-env-switches-verify.patch
rename to patches/0012-env-switches-verify.patch
index db15ef71..004a37c1 100644
--- a/patches/0017-env-switches-verify.patch
+++ b/patches/0012-env-switches-verify.patch
@@ -100,10 +100,10 @@ index 604494c9..e6a5ac1e 100644
if __name__ == '__main__':
unittest.main()
diff --git a/docs/agents/README.md b/docs/agents/README.md
-index a6ef501a..d832bcd7 100644
+index 9e31a212..10c6222c 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
+@@ -23,6 +23,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.
diff --git a/patches/0013-nro-code-start.patch b/patches/0013-nro-code-start.patch
deleted file mode 100644
index 29105c4f..00000000
--- a/patches/0013-nro-code-start.patch
+++ /dev/null
@@ -1,124 +0,0 @@
-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/0018-touchpad-geometry.patch b/patches/0013-touchpad-geometry.patch
similarity index 91%
rename from patches/0018-touchpad-geometry.patch
rename to patches/0013-touchpad-geometry.patch
index e49567fd..07dbc024 100644
--- a/patches/0018-touchpad-geometry.patch
+++ b/patches/0013-touchpad-geometry.patch
@@ -17,19 +17,19 @@ Issue: LNPANDY/NX2Apple#123
create mode 100644 dm/host/touchpad_geometry.h
diff --git a/dm/host/tests/Makefile b/dm/host/tests/Makefile
-index 36029d14..8945c283 100644
+index 0b651aa9..26bc1eac 100644
--- a/dm/host/tests/Makefile
+++ b/dm/host/tests/Makefile
-@@ -7,7 +7,7 @@ PYTHON ?= python3
+@@ -12,7 +12,7 @@ QUIET = $(if $(strip $(SAN)),,2>/dev/null)
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
+-run: $(B)/t_motion $(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_motion $(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_
+@@ -48,6 +48,7 @@ run: $(B)/t_motion $(B)/t_heap_size $(B)/t_touch $(B)/t_gesture $(B)/t_oe $(B)/t
$(B)/t_launcher_contract
$(B)/t_haptics
$(B)/t_haptics_apple
@@ -37,14 +37,14 @@ index 36029d14..8945c283 100644
$(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
+@@ -148,6 +149,8 @@ $(B)/t_hid_tsan: t_hid.c ../hle_hid.c ../motion_fusion.h ../hle_haptics.c ../hle
+ $(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
+ $(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
++ $(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
+ $(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
diff --git a/patches/0019-ios-probe.patch b/patches/0014-ios-probe.patch
similarity index 100%
rename from patches/0019-ios-probe.patch
rename to patches/0014-ios-probe.patch
diff --git a/patches/0020-fork-docs.patch b/patches/0015-fork-docs.patch
similarity index 92%
rename from patches/0020-fork-docs.patch
rename to patches/0015-fork-docs.patch
index 713b8f37..60233e6e 100644
--- a/patches/0020-fork-docs.patch
+++ b/patches/0015-fork-docs.patch
@@ -9,6 +9,7 @@ Upstream-Status: fork-only
Reason: The fork's own planning and release documents and its README badges
Issue: LNPANDY/NX2Apple#123
---
+ dm/ios/ENTITLEMENTS.md | 100 +++++++++++
docs/MULTIPLAYER.md | 139 +++++++++++++++
docs/RELEASE-NOTES-GUIDE.md | 105 +++++++++++
docs/RELEASE_NOTES.md | 77 ++++++++
@@ -17,7 +18,8 @@ Issue: LNPANDY/NX2Apple#123
docs/badges/games.json | 6 +
docs/badges/verified.json | 6 +
docs/launcher-c-design.md | 339 ++++++++++++++++++++++++++++++++++++
- 8 files changed, 900 insertions(+)
+ 9 files changed, 1000 insertions(+)
+ create mode 100644 dm/ios/ENTITLEMENTS.md
create mode 100644 docs/MULTIPLAYER.md
create mode 100644 docs/RELEASE-NOTES-GUIDE.md
create mode 100644 docs/RELEASE_NOTES.md
@@ -27,6 +29,112 @@ Issue: LNPANDY/NX2Apple#123
create mode 100644 docs/badges/verified.json
create mode 100644 docs/launcher-c-design.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/docs/MULTIPLAYER.md b/docs/MULTIPLAYER.md
new file mode 100644
index 00000000..39558eb5
@@ -608,14 +716,14 @@ index 00000000..163d6de3
+- 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
+index 00000000..2c116f37
--- /dev/null
+++ b/docs/badges/games.json
@@ -0,0 +1,6 @@
+{
+ "schemaVersion": 1,
+ "label": "games",
-+ "message": "79",
++ "message": "94",
+ "color": "blue"
+}
diff --git a/docs/badges/verified.json b/docs/badges/verified.json
diff --git a/patches/0016-hle-time-adjustable-clock.patch b/patches/0016-hle-time-adjustable-clock.patch
deleted file mode 100644
index ab345281..00000000
--- a/patches/0016-hle-time-adjustable-clock.patch
+++ /dev/null
@@ -1,77 +0,0 @@
-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/0021-ref-hle-hid-d2r.patch b/patches/0016-ref-hle-hid-d2r.patch
similarity index 100%
rename from patches/0021-ref-hle-hid-d2r.patch
rename to patches/0016-ref-hle-hid-d2r.patch
diff --git a/patches/0022-fork-patches-stamp.patch b/patches/0017-fork-patches-stamp.patch
similarity index 87%
rename from patches/0022-fork-patches-stamp.patch
rename to patches/0017-fork-patches-stamp.patch
index 7d39776b..4bcf67a1 100644
--- a/patches/0022-fork-patches-stamp.patch
+++ b/patches/0017-fork-patches-stamp.patch
@@ -23,10 +23,10 @@ Issue: LNPANDY/NX2Apple#123
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
+index 5afddbb6..c4c84e5d 100644
--- a/dm/ios/Sources/main.m
+++ b/dm/ios/Sources/main.m
-@@ -151,6 +151,9 @@ static int boot_env(void) {
+@@ -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);
@@ -34,8 +34,8 @@ index b546e1bf..6c14a37d 100644
+ 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"]]) {
+ 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 them
diff --git a/dm/ios/project.yml b/dm/ios/project.yml
index 298b2eed..e9d9c174 100644
--- a/dm/ios/project.yml
@@ -49,10 +49,10 @@ index 298b2eed..e9d9c174 100644
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
+index 3d8f5c73..a0c79a3c 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
+@@ -38,6 +38,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}
@@ -74,10 +74,10 @@ index aa5732a8..2e94b2e7 100644
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
+index af479db7..2cf5f549 100644
--- a/dm/mac/launcher.c
+++ b/dm/mac/launcher.c
-@@ -119,6 +119,7 @@ int main(void) {
+@@ -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");
@@ -85,20 +85,20 @@ index 3873b7ad..ce65e8ae 100644
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) {
+@@ -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);
- snprintf(p, sizeof p, "%s/env.txt", sup); env_file(p);
- snprintf(p, sizeof p, "%s/env.txt", dm); env_file(p);
+ CFArrayRef rules = setting_rules(); // the settings the launch environment already set: the window shows them, fixed
+ for (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/dm/mac/pack_app.py b/dm/mac/pack_app.py
-index bdf61634..7e82c8f2 100755
+index 44d83c23..6f28830c 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])
+@@ -110,11 +110,18 @@ def settings_rules(listed): # DMSettings: what the launcher accepts as each se
+ return rules
+def fork_patches():
@@ -115,5 +115,5 @@ index bdf61634..7e82c8f2 100755
+ '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
-
+ if a.settings:
+ listed = json.loads(Path(a.settings).read_text(encoding='utf-8'))['settings']
diff --git a/patches/0018-nsp-dotnet-root-verify.patch b/patches/0018-nsp-dotnet-root-verify.patch
new file mode 100644
index 00000000..5d90e496
--- /dev/null
+++ b/patches/0018-nsp-dotnet-root-verify.patch
@@ -0,0 +1,49 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: v0lumehi <[email protected]>
+Date: Wed, 28 Oct 2026 16:18:05 +0100
+Subject: [PATCH] NSP script: verify DOTNET_ROOT by running the shader
+ translator
+
+configure_dotnet takes the first runtime root `dotnet --list-runtimes` names, which can be one the translator's apphost cannot use (an arm64 .NET beside an x86_64 apphost, a Homebrew wrapper's directory). The build then stopped at the iOS shader step with an empty translator fingerprint. The script now runs `dmsh_xlate --source-sha` with the chosen root and, when it prints nothing, tries the usual roots (Homebrew libexec, ~/.dotnet, /usr/local/share/dotnet) and keeps the first that answers, or removes DOTNET_ROOT so the apphost searches its own defaults. Never falls back to a guess.
+
+Upstream-Status: pending
+Reason: configure_dotnet takes the first listed root without checking that the shader translator runs with it; the build stops at the iOS shader step with an empty fingerprint (fork commit d0ed53df). Not sent to seedds/nxnative yet
+Issue: LNPANDY/NX2Apple#123
+---
+ scripts/build_ipa_from_nsp.py | 23 +++++++++++++++++++++++
+ 1 file changed, 23 insertions(+)
+
+diff --git a/scripts/build_ipa_from_nsp.py b/scripts/build_ipa_from_nsp.py
+index 5d973e24..25426adf 100755
+--- a/scripts/build_ipa_from_nsp.py
++++ b/scripts/build_ipa_from_nsp.py
+@@ -2194,6 +2194,29 @@ def main(args=None):
+ env.setdefault('DOTNET_CLI_TELEMETRY_OPTOUT', '1')
+ env.setdefault('DOTNET_NOLOGO', '1')
+ configure_dotnet(env)
++ xlate_bin = repo / 'dm/gfx/tools/dmsh_xlate_bin/dmsh_xlate' # the fork's check of the root configure_dotnet chose (fork commit d0ed53df; the fork patch nsp-dotnet-root-verify)
++ 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)')
+ 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.executable
+ app, fam = scan_nsps(nsp_dir)
diff --git a/patches/0019-nsp-prune-intermediate-extracts.patch b/patches/0019-nsp-prune-intermediate-extracts.patch
new file mode 100644
index 00000000..bb102abc
--- /dev/null
+++ b/patches/0019-nsp-prune-intermediate-extracts.patch
@@ -0,0 +1,72 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: v0lumehi <[email protected]>
+Date: Wed, 28 Oct 2026 16:18:17 +0100
+Subject: [PATCH] NSP script: delete the intermediate extractions once the
+ build is done
+
+A game with updates extracts every version (one full copy of the game each, a merged RomFS image per version), and only the packed version's files are reused by the next build. The shader captures read the intermediates, so they are deleted after the packed output is made (Mac app, Mac build, Xcode project, IPA with --keep-extracted). A game without an update extracts one version and nothing is deleted.
+
+Upstream-Status: pending
+Reason: Disk space: every intermediate extraction is a full copy of the game and the next build re-extracts them anyway when its inputs change. Fork commit 1887fe93; not sent to seedds/nxnative yet
+Issue: LNPANDY/NX2Apple#123
+---
+ scripts/build_ipa_from_nsp.py | 18 ++++++++++++++++++
+ 1 file changed, 18 insertions(+)
+
+diff --git a/scripts/build_ipa_from_nsp.py b/scripts/build_ipa_from_nsp.py
+index 25426adf..3413d6f3 100755
+--- a/scripts/build_ipa_from_nsp.py
++++ b/scripts/build_ipa_from_nsp.py
+@@ -928,6 +928,19 @@ def extracted(log): # (files, bytes) from the summary lines nx_extract wrote t
+ return (sum(int(n) for n, _ in rows), int(sum(float(mb) for _, mb in rows) * 2**20)) if rows else None
+
+
++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)
++
++
+ def extract(nx, keys, ex, name, base, upd, cmp_dir, logs, g): # the build IDs are checked by the caller (build_mismatch)
+ dst, marker, log = ex / name, g.get('romfs_marker'), logs / f'extract_{name}.log'
+ try: reusable = (dst / 'ExeFS' / 'main').exists() and (dst / 'RomFS.img').is_file() and not (dst / 'RomFS').exists() and (rfs.source(dst) / marker).exists()
+@@ -2401,6 +2414,7 @@ def main(args=None):
+ mac_app(py, repo, out_ipa, app, work, game, patched, host, font, ios, aoc, gfx, lang, g, app_name, app_version, bundle_id, icon, args.mac_sign or MAC_SIGN, env, logs, env_file,
+ (args.gpu or PSO_GPUS).strip())
+ rmtree(work / 'tmp')
++ prune_intermediate_extracts(dirs, versions, pkg_ver)
+ say(f'done: {out_ipa} ({tree_size(out_ipa)[1] / 2**30:.1f} GB); '
+ f'open it from Finder. Its save is in ~/Library/Application Support/nxnative/{app:016X}/, its log in ~/Library/Logs/nxnative/{app:016X}.log')
+ report_profile_status(g, reg, pkg_ver, derived, provisional, 'Mac app', patched)
+@@ -2409,6 +2423,7 @@ def main(args=None):
+ host, font = mac_host(py, repo, work, env, logs, g)
+ cmd = mac_run(work, game, patched, host, font, ios, aoc, gfx, lang, env, logs, g, env_file)
+ rmtree(work / 'tmp')
++ prune_intermediate_extracts(dirs, versions, pkg_ver)
+ say(f'done: the game runs on the Mac with this command (its save in {work / "run/save"}, kept from run to run; DM_WINDOW=1 opens a window, DM_AUDIO=1 plays sound):')
+ PROG.say(cmd)
+ report_profile_status(g, reg, pkg_ver, derived, provisional, 'Mac build', patched)
+@@ -2439,6 +2454,7 @@ def main(args=None):
+ except ValueError as e: raise BuildError(str(e)) from e
+ PROG.end()
+ rmtree(work / 'tmp')
++ prune_intermediate_extracts(dirs, versions, pkg_ver)
+ say(f'ready: {workspace}')
+ say(f'game project: {project}')
+ say(f'Xcode derived data: {work / "xcode-derived-data"}')
+@@ -2454,6 +2470,8 @@ def main(args=None):
+ rmtree(work / 'tmp')
+ if not keep:
+ say(f'deleting the extracted game files: {ex}'); rmtree(ex)
++ else:
++ prune_intermediate_extracts(dirs, versions, pkg_ver)
+ say(f'done: {out_ipa} ({out_ipa.stat().st_size / 2**30:.1f} GB)')
+ if separate: say_push_romfs(rfs.source(game), bundle_id)
+ report_profile_status(g, reg, pkg_ver, derived, provisional, patched=patched)
diff --git a/patches/README.md b/patches/README.md
index e66f311f..c044488d 100644
--- a/patches/README.md
+++ b/patches/README.md
@@ -93,3 +93,13 @@ Upstream's compatibility is the baseline. A patch does not change it silently.
`.github/`, `frontend/`, `frontend-qt/`, the README, CONTRIBUTING.md, CLAUDE.md and everything else outside the five vendored paths
belong to the fork and are edited directly. Inside the vendored paths, the tool's own files (`scripts/patches.py`,
`scripts/tests/test_patches.py`) and the generated `dm/fork_patches.txt` are not part of the generated tree.
+
+## Generated files inside the vendored paths
+
+`docs/agents/game-patches.md` and `docs/agents/symptoms.md` are written by upstream's own tools (`dm/tools/docs_patches.py`,
+`dm/tools/docs_symptoms.py`) from the tree, and upstream's `test_docs.py` requires them to equal that output. With the series in,
+the tree differs from upstream's (a profile key, a patched host table), so upstream's copy would fail the test, and a patch that
+carried the file would conflict on every bump. `apply`, `bump` and `check` therefore run both tools on the patched tree and
+compare the result, and a patch that touches either file is rejected by `check` (`export` leaves them out). Nothing to do by hand:
+`apply` writes them. Not covered: `docs/badges/*.json`, which are carried as static files in `fork-docs`; the README's game table and
+banners are outside the vendored paths and no longer refreshed by a script.
diff --git a/patches/series b/patches/series
index 2edd25f9..a1d1b8ab 100644
--- a/patches/series
+++ b/patches/series
@@ -3,21 +3,18 @@
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.patch
+0005-nsp-dotnet-home.patch
+0006-nsp-chain-changed-note.patch
+0007-nsp-work-dir.patch
+0008-bc-cpu-decode.patch
+0009-mac-keymap.patch
+0010-mac-library-folder.patch
+0011-hades2-update-profile.patch
+0012-env-switches-verify.patch
+0013-touchpad-geometry.patch
+0014-ios-probe.patch
+0015-fork-docs.patch
+0016-ref-hle-hid-d2r.patch
+0017-fork-patches-stamp.patch
+0018-nsp-dotnet-root-verify.patch
+0019-nsp-prune-intermediate-extracts.patch
diff --git a/scripts/build_ipa_from_nsp.py b/scripts/build_ipa_from_nsp.py
index 2dfa2e50..3413d6f3 100755
--- a/scripts/build_ipa_from_nsp.py
+++ b/scripts/build_ipa_from_nsp.py
@@ -372,7 +372,7 @@ def rmtree(p):
"""Make p gone. An entry that vanishes between the listing and its unlink is the goal reached, not an error: on an exFAT / FAT drive macOS keeps each AppleDouble `._x` beside `x`
and drops it when `x` is deleted, so the walk's later unlink of `._x` raised FileNotFoundError and left the folder half deleted"""
if p.is_symlink() or p.is_file(): p.unlink()
- 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])})) # Python 3.13 and later pass these by themselves
+ elif p.exists(): shutil.rmtree(p, onexc=_gone) # Python 3.13 and later pass these by themselves
def build_nx_extract(repo, work, logs, env):
@@ -1794,15 +1794,6 @@ 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)"""
@@ -2189,12 +2180,6 @@ 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
@@ -2222,7 +2207,7 @@ def main(args=None):
env.setdefault('DOTNET_CLI_TELEMETRY_OPTOUT', '1')
env.setdefault('DOTNET_NOLOGO', '1')
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)
+ xlate_bin = repo / 'dm/gfx/tools/dmsh_xlate_bin/dmsh_xlate' # the fork's check of the root configure_dotnet chose (fork commit d0ed53df; the fork patch nsp-dotnet-root-verify)
def xlate_answers(root):
e = dict(env)
if root: e['DOTNET_ROOT'] = str(root)
@@ -2356,7 +2341,6 @@ 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/scripts/patches.py b/scripts/patches.py
index a5fdb9cb..46184d0b 100644
--- a/scripts/patches.py
+++ b/scripts/patches.py
@@ -10,8 +10,8 @@ in .upstream-ref, plus the patches in patches/ applied in the order of patches/s
Issue: <repo>#<n>
Subcommands (Python 3.9+, stdlib and git):
- apply [--ref SHA] build the vendored tree from upstream at the ref plus the series (a temporary worktree), copy it
- into the checkout, and write dm/fork_patches.txt
+ apply [--ref SHA] build the vendored tree from upstream at the ref plus the series (a temporary worktree), regenerate
+ the generated indexes (GENERATED), copy it into the checkout, and write dm/fork_patches.txt
bump --to SHA move the pin: re-apply the series on SHA, drop the patches that come out empty (upstream has them)
and report them, refresh the rest; on a conflict stop, naming the patch, its Reason and its
Upstream-Status, and leave the conflict in a worktree for a human. --dry changes nothing and
@@ -19,7 +19,8 @@ Subcommands (Python 3.9+, stdlib and git):
export <commit|range> turn local commits on the vendored tree into patches with the header template
status a table of the patches: Upstream-Status, Reason, age
check the headers are valid, no patch touches the shader chain, the series applies to the pinned ref and
- reproduces the vendored tree of the checkout byte for byte
+ reproduces the vendored tree of the checkout byte for byte (after
+ the generated indexes are regenerated on it)
Scratch worktrees go under $PATCHES_TMP (or --tmp), else the system temporary folder.
"""
@@ -31,6 +32,12 @@ VENDORED = ('dm', 'scripts', 'docs', 'AGENTS.md', 'ref')
# Inside the vendored paths but not part of the generated tree: the tool, its test, and the list it writes.
OWN = ('scripts/patches.py', 'scripts/tests/test_patches.py', 'dm/fork_patches.txt')
FORK_PATCHES = 'dm/fork_patches.txt'
+# Generated files inside the vendored paths: upstream's tests require each to equal what its tool writes from the tree
+# (test_docs.py), and the tree differs from upstream's once the series is in, so a patch cannot carry them (they would
+# conflict on every bump). apply, bump and check run the tools on the patched tree and commit the result; export and check
+# keep patches away from these paths.
+GENERATED = (('docs/agents/game-patches.md', 'dm/tools/docs_patches.py'),
+ ('docs/agents/symptoms.md', 'dm/tools/docs_symptoms.py'))
KINDS = ('forwarded', 'pending', 'fork-only', 'backport')
# The shader chain and the tool pins (AGENTS.md: the DMSH_CHAIN paragraph names them; chain_paths() reads it).
# Used only when AGENTS.md has no such paragraph.
@@ -195,6 +202,19 @@ def apply_series(wt, patches, stop=True):
return applied, landed, conflicts
+def generate(wt):
+ """Run the generators of GENERATED on the patched tree and commit what they changed (no commit when nothing changed)."""
+ for out, tool in GENERATED:
+ if not (wt / tool).is_file(): continue
+ r = subprocess.run([sys.executable, str(wt / tool)], cwd=wt, capture_output=True, text=True)
+ if r.returncode:
+ raise Fail(f'{tool} failed on the patched tree: {(r.stderr.strip().splitlines() or [str(r.returncode)])[-1]}')
+ if git('status', '--porcelain', '--', *(o for o, _ in GENERATED), cwd=wt).stdout.strip():
+ git('add', '--', *(o for o, _ in GENERATED), cwd=wt)
+ git('-c', 'user.name=patches.py', '-c', 'user.email=patches@localhost', '-c', 'commit.gpgsign=false',
+ 'commit', '-q', '-m', 'Regenerated indexes: ' + ', '.join(o for o, _ in GENERATED), cwd=wt)
+
+
def tree_files(wt):
"""{path: (mode, blob)} of the vendored paths at HEAD of a worktree, without the tool's own files."""
out = git('ls-tree', '-r', '-z', 'HEAD', '--', *VENDORED, cwd=wt).stdout
@@ -260,6 +280,8 @@ def cmd_check(a):
if stray: bad.append('patch files not in patches/series: ' + ', '.join(stray))
for p in patches:
for m in p.problems(): bad.append(f'{p.file}: {m}')
+ gen = sorted(f for f in p.files if f in {o for o, _ in GENERATED})
+ if gen: bad.append(f'{p.file}: touches generated files ({", ".join(gen)}); apply, bump and check regenerate them, so a patch must not carry them')
hits = chain_hits(p.files, root)
if hits: bad.append(f'{p.file}: touches the shader chain or the tool pins, which patches must not change ({", ".join(hits)}); see patches/README.md, Patch policy')
if bad:
@@ -273,6 +295,7 @@ def cmd_check(a):
say(f'patch queue: {p.file} does not apply to the pinned upstream {sha[:12]}\n Reason: {p.reason}\n Upstream-Status: {p.status}\n {msg}'); return 1
if landed:
say('patch queue: patches that are empty on the pinned upstream (it has them already; run bump to drop them): ' + ', '.join(p.file for p in landed)); return 1
+ generate(s.dir)
want = tree_files(s.dir)
diff = diff_trees(want, local_files(root))
expect = fork_patch_list(patches)
@@ -297,6 +320,7 @@ def cmd_apply(a):
if conflicts:
p, msg = conflicts[0]
raise Fail(f'{p.file} does not apply to {sha[:12]}\n Reason: {p.reason}\n Upstream-Status: {p.status}\n {msg}')
+ generate(s.dir)
install(root, s.dir, [p for p, _ in applied])
if landed: say('empty at this ref (upstream has them): ' + ', '.join(p.file for p in landed) + ' (patches.py bump drops them)')
say(f'applied {len(applied)} patches to upstream {sha[:12]}; the vendored tree is written')
@@ -325,6 +349,7 @@ def cmd_bump(a):
return 0
write_series(root, s.dir, applied, landed, patches)
(root / '.upstream-ref').write_text(sha + '\n')
+ generate(s.dir)
install(root, s.dir, [p for p, _ in applied])
s.close()
return 0
@@ -374,6 +399,7 @@ def cmd_refresh(a):
say('landed upstream, dropped: ' + (', '.join(p.name for p in landed) or 'none'))
write_series(root, wt, applied, landed, old)
(root / '.upstream-ref').write_text(sha + '\n')
+ generate(wt)
install(root, wt, [p for p, _ in applied])
return 0
@@ -395,7 +421,7 @@ def cmd_export(a):
made = []
for c in commits:
text = git('format-patch', '--binary', '--zero-commit', '--no-signature', '--no-numbered', '--stdout', f'{c}^..{c}', '--', *VENDORED,
- *(f':(exclude){o}' for o in OWN), cwd=root, binary=True).stdout.decode(errors='surrogateescape')
+ *(f':(exclude){o}' for o in (*OWN, *(g for g, _ in GENERATED))), cwd=root, binary=True).stdout.decode(errors='surrogateescape')
if not re.search(r'(?m)^diff --git ', text):
say(f'skipped {c[:10]}: no change under the vendored paths'); continue
files = sorted({f for m in re.finditer(r'(?m)^diff --git a/(\S+) b/(\S+)$', text) for f in m.groups()})
diff --git a/scripts/tests/test_patches.py b/scripts/tests/test_patches.py
index 22bae4da..2cf8b781 100644
--- a/scripts/tests/test_patches.py
+++ b/scripts/tests/test_patches.py
@@ -1,6 +1,6 @@
"""scripts/patches.py on a fixture repository: the series reproduces the vendored tree, a patch that upstream took drops on a bump,
a conflict names its patch, export writes the header, a patch that touches the shader chain is rejected, and the list of carried
-patches is generated. No game files, no network: upstream is a branch of the fixture."""
+patches is generated, and the generated indexes are regenerated on the patched tree. No game files, no network: upstream is a branch of the fixture."""
import importlib.util, os, shutil, subprocess, sys, tempfile, unittest
from pathlib import Path
@@ -224,7 +224,7 @@ class ForkPatchList(Fixture):
self.assertEqual(mod.fork_patches(), '')
(self.tmp / 'dm/fork_patches.txt').write_text('runtime-profile\nbc-cpu-decode\n')
self.assertEqual(mod.fork_patches(), 'runtime-profile,bc-cpu-decode')
- args = type('A', (), dict(name='G', bundle_id=None, title_id='0100000000000000', version=None, category=None, marker=None, lang=None))()
+ args = type('A', (), dict(name='G', bundle_id=None, title_id='0100000000000000', version=None, category=None, marker=None, lang=None, settings=None))()
self.assertEqual(mod.info_plist(args, '26.0', False)['DMForkPatches'], 'runtime-profile,bc-cpu-decode')
def test_the_first_log_line_and_the_ios_key_are_in_the_sources(self):
@@ -234,5 +234,40 @@ class ForkPatchList(Fixture):
self.assertIn('DMForkPatches: ${DM_FORK_PATCHES}', (REPO / 'dm/ios/project.yml').read_text())
+class GeneratedIndexes(Fixture):
+ """docs/agents/game-patches.md and symptoms.md are written by upstream's tools from the tree: bump, apply and check regenerate them
+ on the patched tree, and a patch must not carry them."""
+ GEN = ("import pathlib\nr = pathlib.Path(__file__).resolve().parents[2]\n(r / 'docs/agents').mkdir(parents=True, exist_ok=True)\n"
+ "(r / 'docs/agents/%s').write_text('fork=%%d\\n' %% ('fork' in (r / 'dm/a.c').read_text()))\n")
+
+ def with_tools(self):
+ return self.upstream_commit({'dm/tools/docs_patches.py': self.GEN % 'game-patches.md', 'dm/tools/docs_symptoms.py': self.GEN % 'symptoms.md',
+ 'docs/agents/game-patches.md': 'fork=0\n', 'docs/agents/symptoms.md': 'fork=0\n'}, 'upstream: the index tools')
+
+ def test_bump_writes_the_indexes_from_the_patched_tree(self):
+ sha = self.with_tools()
+ self.run_tool('bump', '--to', sha)
+ for f in ('game-patches.md', 'symptoms.md'): self.assertEqual((self.r / 'docs/agents' / f).read_text(), 'fork=1\n')
+ self.assertIn('ok.', self.run_tool('check'))
+
+ def test_check_fails_on_a_stale_index_and_apply_restores_it(self):
+ self.run_tool('bump', '--to', self.with_tools())
+ (self.r / 'docs/agents/symptoms.md').write_text('stale\n')
+ self.assertIn('docs/agents/symptoms.md', self.run_tool('check', expect=1))
+ self.run_tool('apply')
+ self.run_tool('check')
+
+ def test_a_patch_that_carries_a_generated_file_is_rejected(self):
+ self.run_tool('bump', '--to', self.with_tools())
+ git(self.r, 'add', '-A'); git(self.r, 'commit', '-q', '-m', 'bump')
+ self.w('docs/agents/game-patches.md', 'hand edit\n'); git(self.r, 'add', '-A'); git(self.r, 'commit', '-q', '-m', 'Edit the index by hand')
+ self.assertIn('no change under the vendored paths', self.run_tool('export', 'HEAD'))
+ text = git(self.r, 'format-patch', '--stdout', '-1', 'HEAD').replace('\n---\n', '\nUpstream-Status: fork-only\nReason: r\nIssue: LNPANDY/NX2Apple#1\n---\n', 1)
+ (self.r / 'patches/0002-index.patch').write_text(text + '\n')
+ s = self.r / 'patches/series'; s.write_text(s.read_text() + '0002-index.patch\n')
+ out = self.run_tool('check', expect=1)
+ self.assertIn('0002-index.patch', out); self.assertIn('generated', out)
+
+
if __name__ == '__main__':
unittest.main()