Skip to content

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

Patches: carry route C M1 as 0034 to 0038

v0lumehi43651b4d762e
diff --git a/patches/0034-route-c-loader-image-header.patch b/patches/0034-route-c-loader-image-header.patch
new file mode 100644
index 00000000..08c6c0c0
--- /dev/null
+++ b/patches/0034-route-c-loader-image-header.patch
@@ -0,0 +1,83 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: LNPANDY <[email protected]>
+Date: Thu, 29 Oct 2026 00:08:14 +0800
+Subject: [PATCH] Loader: the image the game's module sections are read from
+ can be set
+
+The iOS loader reads the game's embedded module sections (__TEXT,__dm<mod>x0, __DM<mod>W,__img, __TEXT,__dm<mod>x1 and the
+packed NRO sections) from a fixed &_mh_execute_header, so they must be linked into the app executable. An embedder that links
+them into another image of the app (a framework it dlopen()s from its signed bundle) had no way to say so.
+
+dm_set_game_image_header() (loader_image.h) names that image's mach header. IMAGE_MH, used by map_image() and nro_pieces(),
+reads it, and unset it is still &_mh_execute_header, so every existing build behaves exactly as before. The host's own tables
+(__DATA,swforce in force_init(), __DATA,swhle in hle.c) stay the executable's. Nothing calls the setter in this change.
+
+Checked: make -C dm/host/tests GAME=010015100B514000 run (includes t_nro and t_symbols, which compile loader.c), and
+lint_python.py (no Python touched, 0 new findings).
+
+Upstream-Status: forwarded seedds/nxnative#729
+Reason: carried until seedds/nxnative#729 lands: the game framework (0035) calls the setter it adds
+Issue: LNPANDY/NX2Apple#144
+
+---
+ dm/host/loader.c | 10 +++++++++-
+ dm/host/loader_image.h | 19 +++++++++++++++++++
+ 2 files changed, 28 insertions(+), 1 deletion(-)
+ create mode 100644 dm/host/loader_image.h
+
+diff --git a/dm/host/loader.c b/dm/host/loader.c
+index 0a4a9ee6..efb8814d 100644
+--- a/dm/host/loader.c
++++ b/dm/host/loader.c
+@@ -10,9 +10,15 @@
+ #include <mach-o/getsect.h>
+ #include <mach-o/ldsyms.h>
+ #include "hle.h"
++#include "loader_image.h"
+
+ module_t *g_mod;
+ int g_nmod;
++// The image whose sections carry the game's modules (loader_image.h): the executable itself unless a framework build
++// (build_ipa.sh DM_FRAMEWORK=1) hands in DmGame.framework's header after dlopen, before loading starts. Only the module
++// sections are read from it; the host's own tables (__DATA,swforce in force_init, __DATA,swhle in hle.c) stay in the executable.
++static const void *g_module_image_mh;
++void dm_set_game_image_header(const void *mh) { g_module_image_mh = mh; }
+ // Stable module addresses live in g_mod; lookup order follows activation, including unload/reload.
+ static module_t **g_loaded; static int g_nloaded, g_mod_capacity;
+ static pthread_rwlock_t g_modules_mu = PTHREAD_RWLOCK_INITIALIZER;
+@@ -516,7 +522,9 @@ static void remap_at(module_t *m, vm_address_t to, const void *from, unsigned lo
+ if (kr != KERN_SUCCESS || a != to) die("%s vm_remap %p → %#lx (%#lx bytes) failed: %d", m->name, from, (unsigned long)to, size, kr);
+ if ((cur & need) != need) die("%s permissions after vm_remap %#x, missing %#x", m->name, cur, need);
+ }
+-#define IMAGE_MH (&_mh_execute_header)
++// The image the module sections are read from: the executable's own embedded segments in the default build, or the
++// framework's when dm_set_game_image_header() named one. getsectiondata() works on any loaded image's header
++#define IMAGE_MH ((const struct mach_header_64 *)(g_module_image_mh ? g_module_image_mh : (const void *)&_mh_execute_header))
+ // The NRO modules (loader.c "NRO modules") are packed instead of getting sections of their own: a Mach-O file has at most 255 sections, and Super Smash Bros. Ultimate's 98 NROs would
+ // take 294. gen_embed.py puts their pieces one after another, each 16K aligned, in __TEXT,__dm_nro_x0 / __DM_NRO_W,__img / __TEXT,__dm_nro_x1, and __DATA,__dm_nro_tab lists them:
+ // 32 bytes of name, then the offset and length of its x0, W and x1 pieces in their sections (u64 each). A module name never holds an underscore, so these names meet no module's
+diff --git a/dm/host/loader_image.h b/dm/host/loader_image.h
+new file mode 100644
+index 00000000..1c00a832
+--- /dev/null
++++ b/dm/host/loader_image.h
+@@ -0,0 +1,19 @@
++// The mach header the iOS loader reads the game's embedded module sections from (loader.c: map_image, nro_pieces).
++// The default build compiles those sections into the executable itself and reads &_mh_execute_header. A framework
++// build (DM_FRAMEWORK=1) compiles them into DmIOS.app/Frameworks/DmGame.framework instead:
++// iOS may not map new executable code from disk, so the framework is dlopen()ed from the signed bundle and its
++// header, taken from dladdr of a marker the framework exports, is handed here before dm_host_preload_start() runs.
++// Horizon's own rtld has no such indirection; it exists only because the image that carries the code is chosen at
++// build time (the executable) or at launch (the framework).
++// Set once, before loading starts: the loader reads it on the preload thread and every later module (NRO) load.
++#pragma once
++
++#ifdef __cplusplus
++extern "C" {
++#endif
++
++void dm_set_game_image_header(const void *mh);
++
++#ifdef __cplusplus
++}
++#endif
diff --git a/patches/0035-route-c-game-framework.patch b/patches/0035-route-c-game-framework.patch
new file mode 100644
index 00000000..7772e4c8
--- /dev/null
+++ b/patches/0035-route-c-game-framework.patch
@@ -0,0 +1,346 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: LNPANDY <[email protected]>
+Date: Fri, 30 Oct 2026 16:15:06 +0100
+Subject: [PATCH] DM_FRAMEWORK: DmGame.framework as the app's module container
+
+project-framework.yml is the same app target as project.yml without Gen/embed.S
+(no embedded modules), plus a DmGame framework target that carries Gen/embed.S and
+the marker symbol: embed: true, link: false (the app dlopens it), app rpath
+@executable_path/Frameworks, resources Gen/framework/{dm,profile.tsv,
+game.manifest.json}. Its framework target gets only gen_embed.py's segment
+permissions as link flags (Gen/framework.xcconfig); it links no host framework and
+defines no module (DEFINES_MODULE NO: nothing imports it).
+
+DmGameMarker.m exports dmgame_image_marker, the symbol dlsym/dladdr name the
+image by. FrameworkBootstrap.m dlopens the framework from the app bundle, dlsyms
+the marker, takes the image base with dladdr and hands it to the loader; a failure
+is a [RED] line with the dlerror text. Under DM_FRAMEWORK_BUILD (only this project
+sets it) main.m points DM_PROFILE at the framework's profile.tsv before the first
+dm_profile() call, opens the framework before dm_host_preload_start(), and points
+argv[1] and DM_NVN_SHMAP at <framework>/dm; DM_FONT_DIR stays the app's.
+
+Route C M1, docs/launcher-c-plan.md.
+
+Upstream-Status: fork-only (waits for the runtime profile, seedds/nxnative#492)
+Reason: opt-in game framework for the launcher (route C M1): it carries profile.tsv and sets DM_PROFILE, which exist only with the runtime-profile patch (seedds/nxnative#492 is still a design note), so it goes upstream after that
+Issue: LNPANDY/NX2Apple#144
+
+---
+ dm/ios/Sources/FrameworkBootstrap.h | 25 +++++
+ dm/ios/Sources/FrameworkBootstrap.m | 47 +++++++++
+ dm/ios/Sources/main.m | 26 ++++-
+ dm/ios/framework/DmGameMarker.m | 10 ++
+ dm/ios/project-framework.yml | 144 ++++++++++++++++++++++++++++
+ 5 files changed, 250 insertions(+), 2 deletions(-)
+ create mode 100644 dm/ios/Sources/FrameworkBootstrap.h
+ create mode 100644 dm/ios/Sources/FrameworkBootstrap.m
+ create mode 100644 dm/ios/framework/DmGameMarker.m
+ create mode 100644 dm/ios/project-framework.yml
+
+diff --git a/dm/ios/Sources/FrameworkBootstrap.h b/dm/ios/Sources/FrameworkBootstrap.h
+new file mode 100644
+index 00000000..01f399d0
+--- /dev/null
++++ b/dm/ios/Sources/FrameworkBootstrap.h
+@@ -0,0 +1,25 @@
++// Route C (docs/launcher-c-plan.md M1): the game's modules are in DmIOS.app/Frameworks/DmGame.framework, not in the
++// executable, so the loader needs that image's mach header before it runs. dm_open_game_framework() dlopen()s the framework
++// from the app bundle, finds its marker symbol, takes the image base with dladdr() and hands it to the loader
++// (dm_set_game_image_header, dm/host/loader_image.h). A failure is logged as a [RED] line with the dlerror text and the boot
++// stops: without the framework's sections there are no modules to run.
++// Compiled only into a DM_FRAMEWORK_BUILD app (project-framework.yml). The default build calls none of this.
++#pragma once
++
++// M1 ships one game per app, so the framework has fixed names (build_ipa.sh DM_FRAMEWORK=1, project-framework.yml).
++// M2's shell picks them from game.manifest.json instead (framework / framework_executable / image_marker).
++#define DM_FRAMEWORK_DIRECTORY "DmGame.framework"
++#define DM_FRAMEWORK_EXECUTABLE "DmGame"
++#define DM_FRAMEWORK_MARKER "dmgame_image_marker"
++
++#ifdef __cplusplus
++extern "C" {
++#endif
++
++// dir: the framework's directory inside the app bundle, e.g. <App>/Frameworks/DmGame.framework.
++// 1 when the image header was set, 0 after the [RED] line that says which step failed.
++int dm_open_game_framework(const char *dir);
++
++#ifdef __cplusplus
++}
++#endif
+diff --git a/dm/ios/Sources/FrameworkBootstrap.m b/dm/ios/Sources/FrameworkBootstrap.m
+new file mode 100644
+index 00000000..b354e253
+--- /dev/null
++++ b/dm/ios/Sources/FrameworkBootstrap.m
+@@ -0,0 +1,47 @@
++// Route C (docs/launcher-c-plan.md M1): load the game framework and give the loader its image header. See
++// FrameworkBootstrap.h for the contract; main.m calls this before dm_host_preload_start().
++#import <Foundation/Foundation.h>
++#include <dlfcn.h>
++#include <stdio.h>
++#include "FrameworkBootstrap.h"
++#include "loader_image.h"
++
++#ifndef DM_FRAMEWORK_BUILD
++#define DM_FRAMEWORK_BUILD 0
++#endif
++
++#if DM_FRAMEWORK_BUILD
++int dm_open_game_framework(const char *dir) {
++ NSString *exe = [@(dir) stringByAppendingPathComponent:@DM_FRAMEWORK_EXECUTABLE];
++ const char *path = exe.fileSystemRepresentation;
++ // RTLD_LAZY, as the dlopen probe (docs/probe-dlopen.md) and the design use: only the framework's own sections and the
++ // marker are needed, and its initializers must not run anything (DmGameMarker.m has none).
++ void *h = dlopen(path, RTLD_LAZY);
++ if (!h) {
++ // The dlerror text names the refusal verbatim (code signature, architecture, missing file); the log is the only
++ // channel a sideloaded build has.
++ fprintf(stderr, "[RED] boot: dlopen %s failed: %s\n", path, dlerror() ?: "(no dlerror text)");
++ return 0;
++ }
++ dlerror(); // clear any stale text before dlsym, so a missing marker reports its own dlerror
++ void *marker = dlsym(h, DM_FRAMEWORK_MARKER);
++ if (!marker) {
++ fprintf(stderr, "[RED] boot: %s has no %s symbol: %s\n", path, DM_FRAMEWORK_MARKER, dlerror() ?: "(no dlerror text)");
++ return 0;
++ }
++ Dl_info info;
++ if (!dladdr(marker, &info) || !info.dli_fbase) {
++ fprintf(stderr, "[RED] boot: dladdr(%s) in %s did not name the image\n", DM_FRAMEWORK_MARKER, path);
++ return 0;
++ }
++ // The header stays valid for the process's life: the framework is never dlclose()d (the loader holds its sections)
++ dm_set_game_image_header(info.dli_fbase);
++ fprintf(stderr, "boot: game framework %s (handle %p, image base %p)\n", path, h, info.dli_fbase);
++ return 1;
++}
++#else
++int dm_open_game_framework(const char *dir) {
++ (void)dir;
++ return 0;
++}
++#endif
+diff --git a/dm/ios/Sources/main.m b/dm/ios/Sources/main.m
+index 69ec53ed..ae14c0f5 100644
+--- a/dm/ios/Sources/main.m
++++ b/dm/ios/Sources/main.m
+@@ -16,6 +16,14 @@
+ #ifndef DM_PLAYER_BUILD
+ #define DM_PLAYER_BUILD 0
+ #endif
++// Route C (docs/launcher-c-plan.md M1): DM_FRAMEWORK_BUILD is set by project-framework.yml, whose app carries the game's
++// modules in Frameworks/DmGame.framework instead of Gen/embed.S. The default project never defines it.
++#ifndef DM_FRAMEWORK_BUILD
++#define DM_FRAMEWORK_BUILD 0
++#endif
++#if DM_FRAMEWORK_BUILD
++#include "FrameworkBootstrap.h"
++#endif
+
+ extern char **environ;
+
+@@ -200,6 +208,14 @@ static int boot_env(void) {
+ // First line of the log: the fork's patches this build carries (Info.plist DMForkPatches), so a report says whether it comes from a build beyond upstream's support
+ NSString *fork_patches = [NSBundle.mainBundle objectForInfoDictionaryKey:@"DMForkPatches"];
+ fprintf(stderr, "fork patches: %s\n", [fork_patches isKindOfClass:NSString.class] && fork_patches.length ? fork_patches.UTF8String : "none");
++#if DM_FRAMEWORK_BUILD
++ // Route C: the runtime profile ships inside the game framework, and dm_profile() (hle_profile.c) reads DM_PROFILE on its
++ // first call below (front_hud_env, romfs_locate, the per-game data folders). Before the env files, and forced: the game
++ // this app carries is the framework's, not whatever a diagnostic file names.
++ NSString *fwd = [NSBundle.mainBundle.privateFrameworksURL URLByAppendingPathComponent:@DM_FRAMEWORK_DIRECTORY].path;
++ setenv("DM_PROFILE", [fwd stringByAppendingPathComponent:@"profile.tsv"].fileSystemRepresentation, 1);
++ fprintf(stderr, "boot: game framework %s\n", fwd.fileSystemRepresentation);
++#endif
+ // Environment switch files (for on-device diagnostics: a sideloaded app cannot be given environment variables from outside): one KEY=VALUE per line, # starts a comment; Documents/env.txt takes precedence over dm/env.txt in the bundle (put there by build_ipa.sh's DM_ENV_FILE)
+ NSMutableArray<NSString *> *from_file = [NSMutableArray array], *from_launch = [NSMutableArray array];
+ for (char **e = environ; *e; e++) { // set at launch (Xcode, devicectl): before the env files, and the launcher keeps them
+@@ -242,14 +258,20 @@ static int boot_env(void) {
+ BOOL per_game = [romfs hasPrefix:gdir]; // messaging nil is NO here: no data means the shared layout
+ 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"];
++ NSString *app_dm = [res stringByAppendingPathComponent:@"dm"], *dm = app_dm;
++#if DM_FRAMEWORK_BUILD
++ // Route C: the modules, their rewriter tables and the shader map are the framework's. dlopen + dlsym + dladdr hand its
++ // mach header to the loader here, after the data went to DM_ROMFS and before loading starts (the design's order).
++ if (!dm_open_game_framework(fwd.fileSystemRepresentation)) return 0;
++ dm = [fwd stringByAppendingPathComponent:@"dm"];
++#endif
+ setenv("DM_NVN_SHMAP", [dm stringByAppendingPathComponent:@"shader_map.tsv"].fileSystemRepresentation, 0);
+ // Shader libraries: a game's own <gdir>/msl first (a per-game layout may carry its own), else
+ // the app's shared <App>/msl.
+ NSString *per_game_msl = [gdir stringByAppendingPathComponent:@"msl"];
+ NSString *msl = (per_game && [fm fileExistsAtPath:per_game_msl]) ? per_game_msl : [res stringByAppendingPathComponent:@"msl"];
+ setenv("DM_MSL_DIR", msl.fileSystemRepresentation, 0);
+- setenv("DM_FONT_DIR", [dm stringByAppendingPathComponent:@"font"].fileSystemRepresentation, 0); // Shared-font stand-ins (standard.ttf / nintendo_ext.ttf): iOS lacks the macOS font path
++ setenv("DM_FONT_DIR", [app_dm stringByAppendingPathComponent:@"font"].fileSystemRepresentation, 0); // Shared-font stand-ins (standard.ttf / nintendo_ext.ttf): iOS lacks the macOS font path
+ // Add-on content beside the game data: the launcher's games/<id>/aoc/ holds <index>.img (the layout hle_fs.c aoc_dir reads), because a slim IPA does not carry it. Taken before
+ // <App>/aoc and never over an explicit DM_AOC_DIR. A Documents/aoc folder (seedds/nxnative#486) stays compatible: it only ever fills DM_AOC_DIR when this did not.
+ NSString *per_game_aoc = [gdir stringByAppendingPathComponent:@"aoc"];
+diff --git a/dm/ios/framework/DmGameMarker.m b/dm/ios/framework/DmGameMarker.m
+new file mode 100644
+index 00000000..2f638688
+--- /dev/null
++++ b/dm/ios/framework/DmGameMarker.m
+@@ -0,0 +1,10 @@
++// The DmGame framework's only symbol. The framework carries the game's rewritten modules in Mach-O sections (Gen/embed.S,
++// the same file the default build compiles into the executable) and no host code; dlopen()ing it maps and signs those
++// sections, and dm/ios/Sources/FrameworkBootstrap.m finds this marker with dlsym() and reports the framework's mach header
++// through dladdr(). The loader (dm/host/loader.c, loader_image.h) then reads the module sections from it.
++// Its value is not read: the symbol's address alone names the image, so it must stay externally visible (default visibility,
++// not static) and survive the linker.
++#include <stdint.h>
++
++__attribute__((used, visibility("default")))
++const char dmgame_image_marker[] = "DmGame";
+diff --git a/dm/ios/project-framework.yml b/dm/ios/project-framework.yml
+new file mode 100644
+index 00000000..e1191f79
+--- /dev/null
++++ b/dm/ios/project-framework.yml
+@@ -0,0 +1,144 @@
++# Route C framework project (docs/launcher-c-plan.md M1): the same app as project.yml, except that the game's rewritten
++# modules are not compiled into the executable (no Gen/embed.S) but into DmGame.framework, which the app dlopens at launch.
++# build_ipa.sh DM_FRAMEWORK=1 generates Gen/ and Gen/framework before xcodegen runs; the app source reads the framework's
++# mach header before the loader starts (dm/ios/Sources/FrameworkBootstrap.m, dm/host/loader_image.h).
++# The default project (project.yml) is untouched: without DM_FRAMEWORK the build is what it was.
++name: DmIOS
++options:
++ bundleIdPrefix: ${DM_BUNDLE_ID}
++ deploymentTarget:
++ iOS: "26.0" # Graphics replay uses Metal 4 (MTL4CommandQueue etc., from iOS 26)
++configFiles: # Generated by build_ipa.sh: embedded-segment link flags + header paths and frameworks taken from dm/host/Makefile
++ Release: Gen/dm.xcconfig
++ Debug: Gen/dm.xcconfig
++targets:
++ DmIOS:
++ type: application
++ platform: iOS
++ sources:
++ - path: Sources
++ excludes: [Info.plist] # generated per project under Gen/, so games never share the generated plist
++ # No Gen/embed.S: the modules are the DmGame framework's (below)
++ - path: Gen/dm # Rewriter tables (*.fixups.tsv / gates / cuts / obs) + shader map / c1 list / warm-up list
++ type: folder
++ buildPhase: resources
++ - path: Gen/Assets.xcassets # app icon (generated by build_ipa.sh from the game icon; an empty catalog when there is none, since xcodegen lists it in the project whether or not it exists)
++ - path: Gen/src # Source files from the compile commands of dm/host/Makefile (linked in by tools/gen_build.py)
++ - path: Gen/main/main.c
++ compilerFlags: "-Dmain=dm_main"
++ dependencies: # The framework is dlopen()ed at launch, not linked: embed it, add no load command (link: false)
++ - target: DmGame
++ embed: true
++ link: false
++ postBuildScripts:
++ - name: Copy game resources
++ script: /bin/bash "${SRCROOT}/tools/stage_resources.sh"
++ basedOnDependencyAnalysis: false # rsync checks the game's files; no huge Xcode input/output lists
++ info:
++ path: Gen/Info.plist
++ properties:
++ CFBundleDisplayName: ${DM_DISPLAY_NAME} # the game name in the base NSP (set by build_ipa.sh)
++ CFBundleVersion: $(CURRENT_PROJECT_VERSION)
++ CFBundleShortVersionString: $(MARKETING_VERSION)
++ UILaunchStoryboardName: ""
++ UIFileSharingEnabled: true # Documents (log.txt, saves) visible in the Files app
++ LSSupportsOpeningDocumentsInPlace: true
++ UISupportedInterfaceOrientations:
++ - UIInterfaceOrientationLandscapeRight
++ - UIInterfaceOrientationLandscapeLeft
++ UIRequiresFullScreen: true
++ UIStatusBarHidden: true
++ UIViewControllerBasedStatusBarAppearance: false
++ LSApplicationCategoryType: ${DM_APP_CATEGORY} # game profile app_category
++ DMShowFPS: ${DM_SHOW_FPS} # YES = the frame-rate counter is on (front_ios.m; set by build_ipa.sh)
++ DMLanguage: ${DM_LANG} # the game language code (main.m sets DM_LANG from it; set by build_ipa.sh)
++ LSSupportsGameMode: true
++ GCSupportsControllerUserInteraction: true # Physical controllers (GameController)
++ GCSupportedGameControllers:
++ - ProfileName: ExtendedGamepad
++ CADisableMinimumFrameDurationOnPhone: true
++ UIApplicationSceneManifest:
++ UIApplicationSupportsMultipleScenes: false
++ UISceneConfigurations:
++ UIWindowSceneSessionRoleApplication:
++ - UISceneConfigurationName: Default
++ UISceneDelegateClassName: SceneDelegate
++ settings:
++ PRODUCT_BUNDLE_IDENTIFIER: ${DM_BUNDLE_ID}
++ PRODUCT_NAME: DmIOS
++ MARKETING_VERSION: ${DM_APP_VERSION} # the game's display version: the packed update's, else the base game's (set by build_ipa.sh)
++ CURRENT_PROJECT_VERSION: ${DM_APP_VERSION}
++ DEVELOPMENT_TEAM: ${DM_TEAM_ID}
++ CODE_SIGN_STYLE: Automatic
++ ENABLE_USER_SCRIPT_SANDBOXING: NO # the game's files live on the external drive
++ DM_COPY_GAME_RESOURCES: YES # build_ipa.sh overrides this only for its unsigned archive build
++ SYMROOT: $(DM_XCODE_OUTPUT_ROOT)/Build/Products
++ OBJROOT: $(DM_XCODE_OUTPUT_ROOT)/Build/Intermediates.noindex
++ # Workspaces can override SYMROOT/OBJROOT. Keep app bundles and compiles separate even then.
++ CONFIGURATION_BUILD_DIR: $(DM_XCODE_OUTPUT_ROOT)/Build/Products/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)
++ CONFIGURATION_TEMP_DIR: $(DM_XCODE_OUTPUT_ROOT)/Build/Intermediates.noindex/$(PROJECT_NAME).build/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)
++ ASSETCATALOG_COMPILER_APPICON_NAME: $(DM_APPICON) # Gen/dm.xcconfig sets DM_APPICON = AppIcon when there is a game icon; empty = no icon (xcodegen's default is AppIcon, which fails the build when the catalog lacks it)
++ TARGETED_DEVICE_FAMILY: "1,2"
++ ENABLE_BITCODE: NO
++ GCC_C_LANGUAGE_STANDARD: gnu11
++ OTHER_CFLAGS: $(inherited) -mcpu=apple-a18 -DDM_FRAMEWORK_BUILD=1 # The host assembly contains LSE atomic instructions, which the default baseline does not accept; the framework build compiles main.m's dlopen path
++ LD_RUNPATH_SEARCH_PATHS: $(inherited) @executable_path/Frameworks # where the embedded DmGame.framework is
++ CLANG_ENABLE_OBJC_ARC: YES
++ SWIFT_VERSION: "5.0" # Launcher.swift (SwiftUI)
++ SWIFT_OBJC_BRIDGING_HEADER: Sources/DmIOS-Bridging-Header.h # DataBookmark (the Files app pick)
++ DEBUG_INFORMATION_FORMAT: dwarf
++ GCC_WARN_INHIBIT_ALL_WARNINGS: YES
++ DmGame:
++ type: framework
++ platform: iOS
++ # The framework has no link flags from the app's xcconfig: only the embedded modules' segment permissions, which
++ # build_ipa.sh writes from gen_embed.py's output (Gen/framework.xcconfig)
++ configFiles:
++ Release: Gen/framework.xcconfig
++ Debug: Gen/framework.xcconfig
++ sources:
++ - path: Gen/embed.S
++ - path: framework/DmGameMarker.m # the only symbol: dlsym + dladdr name this image's header (FrameworkBootstrap.m)
++ - path: Gen/framework/dm # the loader's tables (argv[1]): *.fixups.tsv / gates / cuts / obs, shader map, nro.tsv
++ type: folder
++ buildPhase: resources
++ - path: Gen/framework/profile.tsv # the runtime game profile: main.m points DM_PROFILE at it before dm_profile() runs
++ buildPhase: resources
++ - path: Gen/framework/game.manifest.json # the game this framework carries (docs/launcher-c-plan.md, Manifest)
++ buildPhase: resources
++ info:
++ path: Gen/framework/Info.plist
++ properties:
++ CFBundleDisplayName: ${DM_DISPLAY_NAME}
++ CFBundleVersion: $(CURRENT_PROJECT_VERSION)
++ CFBundleShortVersionString: $(MARKETING_VERSION)
++ settings:
++ PRODUCT_BUNDLE_IDENTIFIER: ${DM_BUNDLE_ID}.DmGame
++ PRODUCT_NAME: DmGame
++ MARKETING_VERSION: ${DM_APP_VERSION}
++ CURRENT_PROJECT_VERSION: ${DM_APP_VERSION}
++ DEVELOPMENT_TEAM: ${DM_TEAM_ID}
++ CODE_SIGN_STYLE: Automatic
++ SKIP_INSTALL: YES
++ DYLIB_INSTALL_NAME_BASE: "@rpath"
++ DEFINES_MODULE: NO # no module map: nothing imports this framework, the app dlopen()s it (xcodegen would otherwise want an umbrella header)
++ ENABLE_BITCODE: NO
++ GCC_C_LANGUAGE_STANDARD: gnu11
++ OTHER_CFLAGS: $(inherited) -mcpu=apple-a18
++ CLANG_ENABLE_OBJC_ARC: YES
++ DEBUG_INFORMATION_FORMAT: dwarf
++ GCC_WARN_INHIBIT_ALL_WARNINGS: YES
++ # No SYMROOT/OBJROOT/CONFIGURATION_BUILD_DIR of its own: the framework builds where the app does (xcodebuild's
++ # SYMROOT in build_ipa.sh, the pinned DerivedData of a prepared workspace in Xcode), and the app's embed phase copies
++ # it from there. The app target keeps project.yml's paths, which reference the generated DM_XCODE_OUTPUT_ROOT.
++schemes:
++ ${DM_SCHEME_NAME}:
++ build:
++ targets:
++ DmIOS: all
++ run:
++ config: Release
++ profile:
++ config: Release
++ archive:
++ config: Release
diff --git a/patches/0036-route-c-framework-build.patch b/patches/0036-route-c-framework-build.patch
new file mode 100644
index 00000000..d19418c1
--- /dev/null
+++ b/patches/0036-route-c-framework-build.patch
@@ -0,0 +1,312 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: LNPANDY <[email protected]>
+Date: Fri, 30 Oct 2026 16:15:06 +0100
+Subject: [PATCH] DM_FRAMEWORK=1 in build_ipa.sh, the NSP script and
+ compile_check.py
+
+build_ipa.sh's framework mode generates Gen/framework/{dm,profile.tsv,
+game.manifest.json} and Gen/framework.xcconfig after Gen/dm is complete, runs
+xcodegen with project-framework.yml, checks the app embedded DmGame.framework, and
+signs it ad-hoc before the app's executable (no entitlements on the framework: a
+dylib cannot hold them). Without DM_FRAMEWORK the script runs the same xcodegen
+command as before, and pack_ipa.py is unchanged: the framework rides in the app
+tree walk. gen_manifest.py writes the plan's game.manifest.json schema.
+build_ipa_from_nsp.py --framework sets DM_FRAMEWORK=1 (refused for the Mac
+platforms). compile_check.py compiles every source twice, the second time with
+DM_FRAMEWORK_BUILD=1, so main.m's dlopen path is checked without Xcode.
+
+Route C M1, docs/launcher-c-plan.md.
+
+The manifest block's FW_SLIM is renamed FW_COPY_ROMFS: it holds DM_COPY_ROMFS's value (YES = the RomFS is packed), so the old name read inverted.
+
+Upstream-Status: fork-only (waits for the runtime profile, seedds/nxnative#492)
+Reason: opt-in game framework for the launcher (route C M1): it carries profile.tsv and sets DM_PROFILE, which exist only with the runtime-profile patch (seedds/nxnative#492 is still a design note), so it goes upstream after that
+Issue: LNPANDY/NX2Apple#144
+
+---
+ dm/ios/tools/build_ipa.sh | 53 ++++++++++++++++-
+ dm/ios/tools/compile_check.py | 22 ++++---
+ dm/ios/tools/gen_manifest.py | 105 ++++++++++++++++++++++++++++++++++
+ scripts/build_ipa_from_nsp.py | 3 +
+ 4 files changed, 173 insertions(+), 10 deletions(-)
+ create mode 100644 dm/ios/tools/gen_manifest.py
+
+diff --git a/dm/ios/tools/build_ipa.sh b/dm/ios/tools/build_ipa.sh
+index 92fd85d4..db6471e7 100755
+--- a/dm/ios/tools/build_ipa.sh
++++ b/dm/ios/tools/build_ipa.sh
+@@ -7,6 +7,9 @@
+ # Environment: GAME=game profile (dm/games/<base game title ID>, or one in DM_GAMES_DIR; required), W=the game's work folder (required: <NSP folder>/<title ID>-work, never the home folder), PATCHED / ROMFS / MSL_IOS can each be overridden
+ # DM_COPY_ROMFS=NO leaves the game files (RomFS) out of the IPA, as it does for the Xcode build phase: the package then stays small (a large game's full package can exceed what iOS extracts), and the app takes the files from Documents/romfs.img (scripts/push_romfs.sh); default: they are packed
+ # DM_ENTITLEMENTS=<plist> is the unsigned IPA's entitlements, signed ad-hoc into the executable (default: Increased Memory Limit; an empty string = none)
++# DM_FRAMEWORK=1 (route C, docs/launcher-c-plan.md M1) compiles the game's modules into DmIOS.app/Frameworks/DmGame.framework instead of the executable
++# (project-framework.yml): Gen/framework/ holds the framework's dm/ tables, profile.tsv and game.manifest.json; the framework is signed ad-hoc first
++# (no entitlements: a dylib cannot hold them) and the app's executable second. Default 0: the build above, unchanged.
+ # AOC=add-on content directory (default $W/data/aoc; when it exists it goes to DmIOS.app/aoc/<index>/; an empty string = none), GFXAPI=nvn / vulkan (default: by the shader libraries in MSL_IOS)
+ # The app name is the game name in the base NSP's control data ($W/data/v0/control.nacp, else the one next to the RomFS), the app version is the display version in the packed game's control data (the one next to the RomFS:
+ # nx_extract saves the update's there when an update is packed, else the base game's), the bundle ID is org.nxnative.<base game title ID in lowercase> (DM_DISPLAY_NAME / DM_APP_VERSION / DM_BUNDLE_ID override them);
+@@ -28,6 +31,7 @@ PKG=$(gp package)
+ if [ -z "${ROMFS:-}" ] && [ -f "$W/data/$PKG/RomFS.img" ]; then ROMFS=$W/data/$PKG/RomFS.img; fi
+ PATCHED=${PATCHED:-$W/build/patched_$PKG}; ROMFS=${ROMFS:-$W/data/$PKG/RomFS}; MSL_IOS=${MSL_IOS:-$W/build/ios/dmsh_b}; AOC=${AOC-$W/data/aoc}
+ PREPARE_XCODE=NO; [ "${1:-}" != --prepare-xcode ] || PREPARE_XCODE=YES
++FRAMEWORK=${DM_FRAMEWORK:-0} # 1: the game's modules live in DmGame.framework (route C); 0: in the executable, as always
+ OUT_IPA=${1:-$(dirname "$W")/$(gp ipa)}; O=$W/build/ios/pkg; DD=$O/dd
+ XCODE_DD=${DM_XCODE_DERIVED_DATA:-$W/build/ios/xcode-dd}
+ MODS=$(gp modules); MARKER=$(gp romfs_marker)
+@@ -46,7 +50,10 @@ if [ "$PREPARE_XCODE" = YES ]; then
+ [ "$IOS" != "$IOS_SOURCE" ] || die "the per-game Xcode project must be outside dm/ios"
+ # Source links follow repository edits; generated files and build products belong to this game only. Linked again each time: a project prepared from another checkout (a removed worktree) follows this one
+ for item in Sources tools; do ln -sfn "$IOS_SOURCE/$item" "$IOS/$item" || die "link $item"; done
+- cp "$IOS_SOURCE/project.yml" "$IOS/project.yml" || die "copy project template"
++ # Route C: the framework target's marker source lives in dm/ios/framework, and the template is project-framework.yml
++ [ "$FRAMEWORK" != 1 ] || ln -sfn "$IOS_SOURCE/framework" "$IOS/framework" || die "link framework"
++ PROJECT_TEMPLATE=project.yml; [ "$FRAMEWORK" != 1 ] || PROJECT_TEMPLATE=project-framework.yml
++ cp "$IOS_SOURCE/$PROJECT_TEMPLATE" "$IOS/project.yml" || die "copy project template"
+ cd "$IOS" || die "cd $IOS"
+ DM_SCHEME_NAME="$(echo "$DM_DISPLAY_NAME" | tr '/:' '__') ($GAME)" # the scheme file is named after it
+
+@@ -121,6 +128,33 @@ if [ -f "$ICON" ]; then
+ echo "DM_APPICON = AppIcon" >> Gen/dm.xcconfig
+ t "app icon: $ICON"
+ else t "no app icon ($ICON not found): the home-screen icon stays blank"; fi
++# Route C (DM_FRAMEWORK=1): what project-framework.yml reads from Gen/framework.
++# dm/ the tables the loader reads from argv[1] and every table the shader map's directory holds (DM_NVN_SHMAP):
++# Gen/dm minus font/ (Arial Unicode, tens of MB; the app's dm/font serves DM_FONT_DIR) and the launcher's files
++# profile.tsv the runtime game profile (game.py profile): main.m sets DM_PROFILE to it before dm_profile() runs
++# game.manifest.json the game this framework carries (gen_manifest.py)
++# Info.plist written by xcodegen from project-framework.yml into this directory
++# Gen/framework.xcconfig the embedded modules' segment permissions (gen_embed.py's flags) and nothing else: the framework links no
++# host frameworks, and its ObjC side is one marker symbol (framework/DmGameMarker.m)
++if [ "$FRAMEWORK" = 1 ]; then
++ rm -rf Gen/framework && mkdir -p Gen/framework/dm || die "mkdir Gen/framework"
++ cp -R Gen/dm/. Gen/framework/dm/ || die "copy the framework tables"
++ rm -rf Gen/framework/dm/font Gen/framework/dm/launcher.json Gen/framework/dm/env.txt
++ python3 "$DM/games/game.py" profile "$GAME" Gen/framework/profile.tsv > /dev/null || die "game profile"
++ # The manifest names the game data this framework was built for: the RomFS image's identity (dm/host/romfs_identity.h), as the
++ # pack step's romfs.id does. That step's default is repeated here because the manifest is a build resource and has to exist now.
++ FW_COPY_ROMFS=${DM_COPY_ROMFS:-}
++ if [ -z "$FW_COPY_ROMFS" ] && [ "$PREPARE_XCODE" != YES ]; then [ -n "${DM_FULL_ROMFS:-}" ] && FW_COPY_ROMFS=YES || FW_COPY_ROMFS=NO; fi
++ ROMFS_ID=; if [ "$FW_COPY_ROMFS" = NO ] && [ -f "$ROMFS" ]; then
++ mkdir -p "$O" && ROMFS_ID=$(python3 -I "$DM/tools/romfs_image.py" --identity "$ROMFS" "$GAME" "$DM_APP_VERSION" "${PKG:-}") || die "identity of $ROMFS"
++ fi
++ NRO_TABLE=$PATCHED/nro.tsv; [ -f "$NRO_TABLE" ] || NRO_TABLE= # the NRO modules gen_embed.py packs: nro_count in the manifest
++ python3 tools/gen_manifest.py Gen/framework/game.manifest.json --game "$GAME" --name "$DM_DISPLAY_NAME" \
++ --display-version "$DM_APP_VERSION" --package-version "${PKG:-}" --modules "$MODS" ${NRO_TABLE:+--nro-table "$NRO_TABLE"} \
++ --chain "b-$V" --romfs-marker "$MARKER" --romfs-identity "$ROMFS_ID" > /dev/null || die "game manifest (gen_manifest.py)"
++ printf 'OTHER_LDFLAGS = $(inherited) %s\n' "$F" > Gen/framework.xcconfig || die "framework link flags"
++ t "framework: Gen/framework (modules $MODS, profile.tsv, game.manifest.json)"
++fi
+ # A prepared Xcode project is signed in Xcode, so it asks for the Increased Memory Limit capability the bigger games need (see the README); DM_ENTITLEMENTS=another plist, or empty for none.
+ # The unsigned IPA carries the same request in its executable's ad-hoc signature below; the install tool replaces that signature.
+ if [ "$PREPARE_XCODE" = YES ] && [ -n "${DM_ENTITLEMENTS-default}" ]; then
+@@ -132,7 +166,10 @@ if [ "$PREPARE_XCODE" = YES ] && [ -n "${DM_ENTITLEMENTS-default}" ]; then
+ fi
+ # DM_COPY_ROMFS=NO also for the prepared project: its Copy game resources phase (stage_resources.sh) then leaves the game files out and writes the image's identity; Gen/dm.xcconfig is made again by every run
+ [ "${DM_COPY_ROMFS:-YES}" != NO ] || [ "$PREPARE_XCODE" != YES ] || echo "DM_COPY_ROMFS = NO" >> Gen/dm.xcconfig
+-xcodegen generate -q > /dev/null || die "xcodegen"
++# The framework project is named explicitly. Everything else runs xcodegen exactly as before: a prepared project has its
++# template copied in as project.yml, and the in-place build uses dm/ios/project.yml (the default template is never edited)
++if [ "$PREPARE_XCODE" = YES ] || [ "$FRAMEWORK" != 1 ]; then xcodegen generate -q > /dev/null || die "xcodegen"
++else xcodegen generate -q --spec project-framework.yml > /dev/null || die "xcodegen"; fi
+ # DMCommit / DMChain: the checkout that built the app (+dirty with uncommitted changes to tracked files) and the shader chain it carries, which the host logs at start (main.c)
+ COMMIT=$(git -C "$DM" rev-parse --short=12 HEAD 2> /dev/null) && { [ -z "$(git -C "$DM" status --porcelain --untracked-files=no 2> /dev/null)" ] || COMMIT=$COMMIT+dirty
+ /usr/libexec/PlistBuddy -c "Add :DMCommit string $COMMIT" Gen/Info.plist > /dev/null || die "DMCommit"; t "source: $COMMIT"; }
+@@ -163,6 +200,18 @@ APP=$DD/Build/Products/Release-iphoneos/DmIOS.app
+ # the app sets DM_AOC_DIR at launch, the host reports them as owned and mounts them from it) and the RomFS
+ 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"
++# Route C: the framework is signed first, then the app's executable below, the order build_probe.sh uses for nested code. The
++# framework gets no entitlements: a dylib cannot hold them (the Increased Memory Limit request belongs to the app, below), and
++# the sideloader re-signs nested code. It must still be a valid signature: the packed framework is what the app dlopen()s.
++if [ "$FRAMEWORK" = 1 ]; then
++ FW=$APP/Frameworks/DmGame.framework
++ [ -d "$FW" ] || die "no $FW: project-framework.yml embeds the game framework"
++ xattr -cr "$FW" 2> /dev/null # codesign refuses a bundle whose files carry resource forks, Finder information or quarantine attributes
++ codesign --force --sign - "$FW" || die "ad-hoc signature of the game framework"
++ [ -z "$(codesign -d --entitlements :- "$FW/DmGame" 2>/dev/null)" ] || die "the game framework's signature carries entitlements: a dylib cannot hold them"
++ codesign -vvv --verify --strict "$FW" > /dev/null 2>&1 || die "the game framework's signature does not verify"
++ t "game framework signed ad-hoc, no entitlements: $FW"
++fi
+ # The entitlements of an unsigned IPA: an unsigned build has no signature for a sideloader to read them from, so the Increased Memory Limit request would be lost (AltStore and others carry over
+ # the entitlements of the signature they replace; the Xcode project gets them through CODE_SIGN_ENTITLEMENTS, above). The executable gets an ad-hoc signature that carries them: the sideloader
+ # replaces the signature and keeps the entitlements. Only the executable is signed: the bundle's resources are packed from elsewhere and the signature is replaced anyway
+diff --git a/dm/ios/tools/compile_check.py b/dm/ios/tools/compile_check.py
+index 3f4d547b..11bf1189 100755
+--- a/dm/ios/tools/compile_check.py
++++ b/dm/ios/tools/compile_check.py
+@@ -4,7 +4,9 @@
+ The source list, header paths and -D flags come from the expanded compile commands of dm/host/Makefile, as gen_build.py takes them for the Xcode project:
+ the _mac sources stay out, main.c is compiled with -Dmain=dm_main, and dm/ios/Sources (Objective-C; Launcher.swift is not compiled) is added.
+ Each file is compiled to nothing (-c -o /dev/null), so the assembler sees entry.S and the embedded-segment files (Gen/embed.S) are not needed.
+-Usage: DM_GAME=<base game title ID> compile_check.py (or GAME=) Exit status 1 when any file fails."""
++Two passes: the default build, then the same sources with DM_FRAMEWORK_BUILD=1 (project-framework.yml: main.m's dlopen path and
++FrameworkBootstrap.m's real body), so a change to either build breaks here rather than in a device build.
++Usage: DM_GAME=<base game title ID> compile_check.py (or GAME=) Exit status 1 when any file fails in either pass."""
+ import concurrent.futures, os, shlex, subprocess, sys
+ repo = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../..'))
+ host, ios = f'{repo}/dm/host', f'{repo}/dm/ios'
+@@ -29,14 +31,18 @@ srcs = [s for s in dict.fromkeys(srcs) if not os.path.splitext(s)[0].endswith('_
+ srcs += sorted(os.path.join(ios_src, f) for f in os.listdir(ios_src) if f.endswith(('.c', '.m')))
+ dirs = list(dict.fromkeys(os.path.dirname(s) for s in srcs))
+ flags = ['-arch', 'arm64', '-miphoneos-version-min=26.0', '-mcpu=apple-a18', '-fobjc-arc', '-O1', '-w'] + defs + [f'-I{d}' for d in incs + dirs]
+-def one(s):
+- c = ['xcrun', '-sdk', 'iphoneos', 'clang'] + flags + (['-Dmain=dm_main'] if s == os.path.join(host, 'main.c') else []) + ['-c', s, '-o', '/dev/null']
++def one(s, extra=()):
++ c = ['xcrun', '-sdk', 'iphoneos', 'clang'] + flags + list(extra) + (['-Dmain=dm_main'] if s == os.path.join(host, 'main.c') else []) + ['-c', s, '-o', '/dev/null']
+ if s.endswith('.c'): c[4:4] = ['-std=gnu11']
+ p = subprocess.run(c, capture_output=True, text=True)
+ return s, p.returncode, p.stderr
+-bad = 0
+-with concurrent.futures.ThreadPoolExecutor(os.cpu_count()) as ex:
+- for s, rc, err in ex.map(one, srcs):
+- if rc: bad += 1; print(f'FAIL {os.path.relpath(s, repo)}\n{err}', file=sys.stderr)
+-print(f'iOS compile check: {len(srcs)} files, {bad} failed')
++def check(label, extra=()):
++ bad = 0
++ with concurrent.futures.ThreadPoolExecutor(os.cpu_count()) as ex:
++ for s, rc, err in ex.map(lambda s: one(s, extra), srcs):
++ if rc: bad += 1; print(f'FAIL {os.path.relpath(s, repo)}\n{err}', file=sys.stderr)
++ print(f'iOS compile check ({label}): {len(srcs)} files, {bad} failed')
++ return bad
++# The framework build defines its macro in project-framework.yml's OTHER_CFLAGS, make never sees it: pass it here
++bad = check('default') + check('DM_FRAMEWORK_BUILD=1', ['-DDM_FRAMEWORK_BUILD=1'])
+ sys.exit(1 if bad else 0)
+diff --git a/dm/ios/tools/gen_manifest.py b/dm/ios/tools/gen_manifest.py
+new file mode 100644
+index 00000000..ec2c33be
+--- /dev/null
++++ b/dm/ios/tools/gen_manifest.py
+@@ -0,0 +1,105 @@
++#!/usr/bin/env python3
++"""Write the game.manifest.json that travels inside a route C game framework (docs/launcher-c-plan.md, "Manifest").
++
++build_ipa.sh's DM_FRAMEWORK=1 mode calls this before xcodegen, so the file is a resource of the DmGame framework:
++<framework>/game.manifest.json. M1 builds one game per app and does not read it yet; M2's shell discovers the framework
++through it and M3 validates several (schema, title ID, chain against the shell's DMSH_CHAIN, CFBundleExecutable) and
++cross-checks the sections it names. Writing it now keeps the schema honest, and test_framework_build.py checks it.
++
++Usage:
++ gen_manifest.py <out.json> --game <title ID> --name <name> --display-version <v> --package-version <pkg>
++ --modules "main sdk" [--nro-table <nro.tsv>] --chain b-<hex> --romfs-marker <path>
++ [--romfs-identity "DMROMFSID1 ..."] [--min-os 26.0]
++Exit status 1 on a value the schema cannot carry (a bad title ID, no module, a chain not written b-<hex>).
++"""
++import argparse
++import json
++import re
++import sys
++from pathlib import Path
++
++SCHEMA = 1
++# The M1 framework's fixed names, the same constants project-framework.yml and FrameworkBootstrap.h use
++FRAMEWORK = 'DmGame.framework'
++FRAMEWORK_EXECUTABLE = 'DmGame'
++IMAGE_MARKER = 'dmgame_image_marker'
++PROFILE = 'profile.tsv' # the framework's root: main.m points DM_PROFILE at it
++SHADER_MAP = 'dm/shader_map.tsv' # inside the framework: main.m points DM_NVN_SHMAP at it
++LAUNCHER = 'dm/launcher.json' # the loader's tables and the launcher settings share the framework's dm/
++TITLE_ID = re.compile(r'^[0-9A-F]{16}$')
++CHAIN = re.compile(r'^b-[0-9A-Za-z._-]+$')
++
++
++def nro_count(table):
++ """Rows gen_embed.py embeds: everything but comments, blank lines and the 'refused' ones (an online SDK the host never
++ loads, dm/tools/nro_collect.py). The same filter gen_embed.py applies when it packs the NRO pieces."""
++ if table is None:
++ return 0
++ rows = (line.split('\t')[0] for line in Path(table).read_text(encoding='utf-8').splitlines())
++ return sum(1 for name in rows if name and not name.startswith('#') and name != 'refused')
++
++
++def manifest(args):
++ """The schema's keys in its order; optional ones only when a value is given."""
++ title_id = args.game.upper()
++ modules = args.modules.split()
++ if not TITLE_ID.match(title_id):
++ raise SystemExit(f'[RED] gen_manifest: --game {args.game!r} is not a 16-digit hex title ID')
++ if not modules or any(not re.match(r'^[A-Za-z0-9]+$', m) for m in modules):
++ raise SystemExit(f'[RED] gen_manifest: --modules {args.modules!r} names no module or a module with an underscore '
++ '(the loader\'s embedded section names cannot hold one)')
++ if not CHAIN.match(args.chain):
++ raise SystemExit(f'[RED] gen_manifest: --chain {args.chain!r} is not written b-<version> (dm/gfx/nvn/dmsh_chain.h)')
++ if args.romfs_identity and not args.romfs_identity.startswith('DMROMFSID1 '):
++ raise SystemExit('[RED] gen_manifest: --romfs-identity is not a romfs_image.py identity line (DMROMFSID1 ...)')
++ data = {
++ 'schema': SCHEMA,
++ 'title_id': title_id,
++ 'name': args.name,
++ 'display_version': args.display_version,
++ 'package_version': args.package_version,
++ 'modules': modules,
++ 'nro_count': nro_count(args.nro_table),
++ 'chain': args.chain,
++ 'loader': 'FR', # a pure module container: the shell is the host (design §1.1 FR)
++ 'framework': FRAMEWORK,
++ 'framework_executable': FRAMEWORK_EXECUTABLE,
++ 'image_marker': IMAGE_MARKER,
++ 'profile': PROFILE,
++ 'shader_map': SHADER_MAP,
++ 'launcher': LAUNCHER,
++ 'romfs_marker': args.romfs_marker,
++ 'romfs_identity': args.romfs_identity or '',
++ 'min_os': args.min_os,
++ }
++ if args.built_by:
++ data['built_by'] = args.built_by
++ return data
++
++
++def main(argv=None):
++ ap = argparse.ArgumentParser(description='Write a route C game framework\'s game.manifest.json.')
++ ap.add_argument('out', help='the file to write (<Gen>/framework/game.manifest.json)')
++ ap.add_argument('--game', required=True, help='the base game title ID (16 hex digits)')
++ ap.add_argument('--name', required=True, help='the game name (control.nacp, as build_ipa.sh reads it)')
++ ap.add_argument('--display-version', required=True, help='the packed version\'s display version')
++ ap.add_argument('--package-version', required=True, help='the packed package version (the profile\'s package key)')
++ ap.add_argument('--modules', required=True, help='the game\'s modules, space separated (the profile\'s modules)')
++ ap.add_argument('--nro-table', help='the rewriter\'s nro.tsv, for nro_count; without it the count is 0')
++ ap.add_argument('--chain', required=True, help='the shader chain version, b-<version> (dm/gfx/nvn/dmsh_chain.h)')
++ ap.add_argument('--romfs-marker', required=True, help='the profile\'s romfs_marker: a folder with it is this game\'s data')
++ ap.add_argument('--romfs-identity', default='', help='the RomFS image identity line build_ipa.sh writes (empty for a folder)')
++ ap.add_argument('--min-os', default='26.0', help='the minimum iOS version (project.yml\'s deployment target)')
++ ap.add_argument('--built-by', help='who built it, for a log line (optional; a device or tool name)')
++ args = ap.parse_args(argv)
++ data = manifest(args)
++ out = Path(args.out)
++ out.parent.mkdir(parents=True, exist_ok=True)
++ # Indented and in the schema's order, so a diff between two builds is one line per changed value
++ out.write_text(json.dumps(data, indent=2, ensure_ascii=False) + '\n', encoding='utf-8')
++ print(out)
++ return data
++
++
++if __name__ == '__main__':
++ main()
+diff --git a/scripts/build_ipa_from_nsp.py b/scripts/build_ipa_from_nsp.py
+index bfbacea1..9a53bdbd 100755
+--- a/scripts/build_ipa_from_nsp.py
++++ b/scripts/build_ipa_from_nsp.py
+@@ -2133,6 +2133,7 @@ def parse_args(argv):
+ ap.add_argument('--romfs', choices=('bundle', 'separate'), help='bundle = the game files go into the IPA (default: the ROMFS setting, bundle); separate = they stay out of the IPA and the Xcode app: the build is small and fast, and the RomFS image '
+ 'is copied to the phone once per game version with the scripts/push_romfs.sh command printed at the end (the app refuses an image of another version)')
+ ap.add_argument('--prepare-xcode', action='store_true', help='prepare a per-game Xcode project and add it to the shared workspace instead of packing an IPA (requires keeping extracted files)')
++ ap.add_argument('--framework', action='store_true', help='the game\'s modules go into DmIOS.app/Frameworks/DmGame.framework, which the app dlopens at launch (route C, docs/launcher-c-plan.md M1), instead of the executable; the IPA is otherwise the usual one')
+ ap.add_argument('--platform', choices=('ios', 'mac', 'mac-app'), help='ios = the IPA (or the Xcode project); mac = for development: build only what running the game on this Mac needs (the Mac shaders and the Mac host, '
+ 'no iOS shaders, Xcode project or IPA), keep the extracted files and print the command that runs the game; mac-app = what mac builds, then a self-contained, double-clickable '
+ 'Mac app of the game (default: <game name>.app in the NSP folder, -o names another) (default: the PLATFORM setting, ios)')
+@@ -2233,6 +2234,7 @@ def main(args=None):
+ mac_pack = platform == 'mac-app'
+ if args.mac_sign and not mac_pack: raise BuildError('--mac-sign signs the Mac app: it needs --platform mac-app')
+ if mac and prepare_xcode: raise BuildError(f'--prepare-xcode makes an iPhone project: it cannot be combined with --platform {platform}')
++ if mac and args.framework: raise BuildError(f'--framework builds the iPhone app\'s game framework: it cannot be combined with --platform {platform}')
+ if mac and not apple_silicon(): raise BuildError(f'--platform {platform} runs the game in the Mac host, which runs the game\'s own arm64 code natively: it needs a Mac with Apple silicon, and this Mac has an Intel processor')
+ check_native_python()
+ keep = KEEP_EXTRACTED if args.keep_extracted is None else args.keep_extracted
+@@ -2500,6 +2502,7 @@ def main(args=None):
+ say('preparing the Xcode project' if prepare_xcode else f'building the IPA → {out_ipa}')
+ ipa_env = dict(env, GAME=g.id, W=str(work / 'ipa'), PATCHED=str(patched), ROMFS=str(rfs.source(game)), MSL_IOS=str(ios), GFXAPI=gfx, FONT_PY=py, DM_DISPLAY_NAME=app_name, DM_BUNDLE_ID=bundle_id, AOC=str(aoc or ''), DM_XCODE_DERIVED_DATA=str(work / 'xcode-derived-data'), DM_TEAM_ID=team_id, DM_LANG=lang)
+ if prepare_xcode: ipa_env['DM_XCODE_PROJECT_DIR'] = str(project.parent)
++ if args.framework: ipa_env['DM_FRAMEWORK'] = '1'; say('route C: the game\'s modules go into DmIOS.app/Frameworks/DmGame.framework (DM_FRAMEWORK=1)')
+ separate = romfs_mode == 'separate'
+ if separate: ipa_env['DM_COPY_ROMFS'] = 'NO'; say('game files: separate (DM_COPY_ROMFS=NO), left out of the app; the image stays at ' + str(rfs.source(game)))
+ if app_version: ipa_env['DM_APP_VERSION'] = app_version
diff --git a/patches/0037-route-c-framework-tests.patch b/patches/0037-route-c-framework-tests.patch
new file mode 100644
index 00000000..919a2e2c
--- /dev/null
+++ b/patches/0037-route-c-framework-tests.patch
@@ -0,0 +1,421 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: LNPANDY <[email protected]>
+Date: Fri, 30 Oct 2026 16:15:06 +0100
+Subject: [PATCH] Tests: the framework's packaging, its linked sections, and
+ --prepare-xcode --framework
+
+test_framework_build.py: gen_manifest.py's schema and refusals; build_ipa.sh's
+--prepare-xcode copies project-framework.yml in with DM_FRAMEWORK=1 and project.yml
+without it; on a stand-in app and framework, the framework is packed at
+Frameworks/DmGame.framework with its resources, its signature carries no
+entitlements, the app's keeps the Increased Memory Limit request, and a default
+pack has no Frameworks/ entry.
+
+test_framework_link.py (skipped without XcodeGen and an iPhoneOS SDK) builds the
+DmGame target from a synthetic Gen with two stand-in modules and reads it back with
+otool: __TEXT,__dm<mod>x0, __DM<mod>W,__img, __TEXT,__dm<mod>x1 for each, the NRO
+pieces and __DATA,__dm_nro_tab, install name @rpath/DmGame.framework/DmGame, and
+the tables/profile/manifest at the framework's root. The generated project shows
+the app's Embed Frameworks phase and @executable_path/Frameworks rpath.
+
+test_xcode_workflow.py: --prepare-xcode --framework passes DM_FRAMEWORK=1 to the
+build. CI runs the link test in the ios-build job, which installs XcodeGen.
+
+Route C M1, docs/launcher-c-plan.md.
+
+Upstream-Status: fork-only (waits for the runtime profile, seedds/nxnative#492)
+Reason: opt-in game framework for the launcher (route C M1): it carries profile.tsv and sets DM_PROFILE, which exist only with the runtime-profile patch (seedds/nxnative#492 is still a design note), so it goes upstream after that
+Issue: LNPANDY/NX2Apple#144
+
+---
+ dm/ios/tests/test_framework_build.py | 211 +++++++++++++++++++++++++++
+ dm/ios/tests/test_framework_link.py | 125 ++++++++++++++++
+ dm/ios/tests/test_xcode_workflow.py | 11 +-
+ 3 files changed, 345 insertions(+), 2 deletions(-)
+ create mode 100644 dm/ios/tests/test_framework_build.py
+ create mode 100644 dm/ios/tests/test_framework_link.py
+
+diff --git a/dm/ios/tests/test_framework_build.py b/dm/ios/tests/test_framework_build.py
+new file mode 100644
+index 00000000..fee9e53e
+--- /dev/null
++++ b/dm/ios/tests/test_framework_build.py
+@@ -0,0 +1,211 @@
++"""Route C M1 (docs/launcher-c-plan.md): the opt-in framework build's packaging and signing, off a device.
++
++Three parts, each on synthetic inputs, no game files or Xcode:
++ - gen_manifest.py writes the schema's keys, and refuses values the schema cannot carry;
++ - build_ipa.sh's --prepare-xcode block copies project-framework.yml in as the project when DM_FRAMEWORK=1, and
++ project.yml when it is not (the default template is never edited);
++ - the framework is signed before the app's executable, the framework's signature carries no entitlements, the app's
++ keeps the Increased Memory Limit request, and the packed IPA has the framework where the app dlopens it. A default
++ pack (no DM_FRAMEWORK) still has no Frameworks/ entry at all.
++Only the signing and packing steps run (a stand-in app and framework, no Xcode); codesign is required for the last part.
++"""
++import json
++import os
++from pathlib import Path
++import shutil
++import subprocess
++import sys
++import tempfile
++import unittest
++import zipfile
++
++REPO = Path(__file__).resolve().parents[3]
++sys.path.insert(0, str(REPO / 'dm/games'))
++import game
++
++GAME = '010015100B514000'
++SCRIPT = (REPO / 'dm/ios/tools/build_ipa.sh').read_text()
++# The three steps, each self-contained: the framework's signature, the app executable's entitlements, the pack.
++FRAMEWORK_SIGNING = SCRIPT[SCRIPT.index('# Route C: the framework is signed first'):SCRIPT.index('# The entitlements of an unsigned IPA')]
++SIGNING = SCRIPT[SCRIPT.index('# The entitlements of an unsigned IPA'):SCRIPT.index('\nP=Payload/DmIOS.app\n')]
++PACKING = SCRIPT[SCRIPT.index('\nP=Payload/DmIOS.app\n'):]
++PREPARE = SCRIPT[SCRIPT.index('if [ "$PREPARE_XCODE" = YES ]; then'):SCRIPT.index('\nelse DM_SCHEME_NAME=DmIOS; fi')] + '\nfi\n'
++PREAMBLE = 'set -u\nt() { :; }; die() { echo "$*" >&2; exit 1; }\ngp() { python3 "$PROFILE_TOOL" "$GAME" "$1"; }\n'
++CAN_SIGN = sys.platform == 'darwin' and shutil.which('codesign') and shutil.which('cc')
++
++
++def run_step(script, root, **extra):
++ env = {k: v for k, v in os.environ.items() if not k.startswith('DM_') and k not in ('IOS_PULL', 'AOC', 'PSO', 'FRAMEWORK')}
++ env.update(GAME=GAME, DM=str(root / 'dm'), PROFILE_TOOL=str(REPO / 'dm/games/game.py'), **extra)
++ return subprocess.run(['/bin/bash', '-c', PREAMBLE + script], cwd=root, env=env, capture_output=True, text=True)
++
++
++class ManifestTests(unittest.TestCase):
++ def manifest(self, *extra, nro=True):
++ """gen_manifest.py's output for the fixture's profile; a two-row nro.tsv (one loadable, one refused)."""
++ with tempfile.TemporaryDirectory() as temporary:
++ root = Path(temporary)
++ (root / 'nro.tsv').write_text('# name\tpath\nnrotest\tfixture.nro\nrefused\tonline.nro\n')
++ out = root / 'game.manifest.json'
++ args = [sys.executable, str(REPO / 'dm/ios/tools/gen_manifest.py'), str(out), '--game', GAME, '--name', 'Fixture Game',
++ '--display-version', '1.2.1', '--package-version', 'v327680', '--modules', 'main sdk', '--chain', 'b-fixture',
++ '--romfs-marker', 'System/Resource/marker', '--romfs-identity', 'DMROMFSID1 title=x size=1 index=2', *extra]
++ if nro: args += ['--nro-table', str(root / 'nro.tsv')]
++ result = subprocess.run(args, capture_output=True, text=True)
++ return result, (json.loads(out.read_text()) if out.exists() else None)
++
++ def test_the_schema_keys_and_values(self):
++ result, data = self.manifest()
++ self.assertEqual(result.returncode, 0, result.stderr)
++ self.assertEqual(list(data), ['schema', 'title_id', 'name', 'display_version', 'package_version', 'modules', 'nro_count',
++ 'chain', 'loader', 'framework', 'framework_executable', 'image_marker', 'profile', 'shader_map',
++ 'launcher', 'romfs_marker', 'romfs_identity', 'min_os'])
++ self.assertEqual(data['schema'], 1)
++ self.assertEqual(data['title_id'], GAME)
++ self.assertEqual(data['modules'], ['main', 'sdk'])
++ self.assertEqual(data['nro_count'], 1, 'the refused row is not an NRO gen_embed.py packs')
++ self.assertEqual(data['chain'], 'b-fixture')
++ self.assertEqual(data['loader'], 'FR')
++ self.assertEqual(data['framework'], 'DmGame.framework')
++ self.assertEqual(data['framework_executable'], 'DmGame')
++ self.assertEqual(data['image_marker'], 'dmgame_image_marker')
++ self.assertEqual(data['profile'], 'profile.tsv')
++ self.assertEqual(data['shader_map'], 'dm/shader_map.tsv')
++ self.assertEqual(data['launcher'], 'dm/launcher.json')
++ self.assertEqual(data['romfs_marker'], 'System/Resource/marker')
++ self.assertEqual(data['romfs_identity'], 'DMROMFSID1 title=x size=1 index=2')
++ self.assertEqual(data['min_os'], '26.0')
++
++ def test_a_romfs_folder_has_no_identity_and_no_nro_table_counts_zero(self):
++ result, data = self.manifest('--romfs-identity', '', nro=False)
++ self.assertEqual(result.returncode, 0, result.stderr)
++ self.assertEqual(data['romfs_identity'], '')
++ self.assertEqual(data['nro_count'], 0)
++
++ def test_values_the_schema_cannot_carry_are_refused(self):
++ cases = [('--game', '1234'), ('--modules', ''), ('--modules', 'main_sdk'), ('--chain', 'fixture'),
++ ('--romfs-identity', 'not-an-identity')]
++ for flag, value in cases:
++ with self.subTest(flag=flag, value=value):
++ base = [sys.executable, str(REPO / 'dm/ios/tools/gen_manifest.py'), '/dev/null', '--game', GAME, '--name', 'x',
++ '--display-version', '1', '--package-version', 'v0', '--modules', 'main', '--chain', 'b-1',
++ '--romfs-marker', 'marker', '--romfs-identity', 'DMROMFSID1 title=x size=1 index=2']
++ base[base.index(flag) + 1] = value
++ self.assertNotEqual(subprocess.run(base, capture_output=True).returncode, 0)
++
++
++class ProjectTemplateTests(unittest.TestCase):
++ """build_ipa.sh --prepare-xcode copies the template the build asks for in as project.yml."""
++
++ def prepare(self, framework):
++ with tempfile.TemporaryDirectory() as temporary:
++ root = Path(temporary).resolve()
++ source = root / 'ios'
++ for name in ('Sources', 'tools', 'framework'):
++ (source / name).mkdir(parents=True)
++ (source / 'project.yml').write_text('name: default\n')
++ (source / 'project-framework.yml').write_text('name: framework\n')
++ environment = dict(IOS_SOURCE=str(source), DM_XCODE_PROJECT_DIR=str(root / 'xcode'), W=str(root), GAME=GAME,
++ DM_DISPLAY_NAME='Fixture Game', FRAMEWORK=str(framework))
++ result = subprocess.run(['/bin/bash', '-c', PREAMBLE + 'PREPARE_XCODE=YES\n' + PREPARE], env=environment, capture_output=True, text=True)
++ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
++ copied = (root / 'xcode/project.yml').read_text()
++ linked = (root / 'xcode/framework').is_symlink()
++ return copied, linked
++
++ def test_framework_mode_selects_project_framework_yml(self):
++ self.assertEqual(self.prepare(1), ('name: framework\n', True))
++
++ def test_the_default_mode_still_selects_project_yml(self):
++ self.assertEqual(self.prepare(0), ('name: default\n', False))
++
++
++class FrameworkPackagingTests(unittest.TestCase):
++ """The signing and pack steps on a stand-in app; no Xcode, no game files."""
++
++ def stand_in(self, root, compiled):
++ header = root / 'dm/host/gen' / GAME / 'game_profile.h'
++ header.parent.mkdir(parents=True)
++ header.write_text(game.header(game.Game(REPO / 'dm/games' / GAME)))
++ for folder in ('DmIOS.app', 'shaders/b-fixture', 'romfs', 'aoc/0', 'pkg'): (root / folder).mkdir(parents=True)
++ (root / 'shaders/b-fixture/fixture_b.metallib').write_text('lib')
++ (root / 'romfs/marker').write_text('romfs')
++ (root / 'aoc/0/file').write_text('aoc')
++ (root / 'tools').symlink_to(REPO / 'dm/ios/tools', target_is_directory=True)
++ (root / 'dm/tools').symlink_to(REPO / 'dm/tools', target_is_directory=True)
++ if compiled: # only the signing step needs a Mach-O executable
++ (root / 'main.c').write_text('int main(void) { return 0; }\n')
++ subprocess.run(['cc', '-o', str(root / 'DmIOS.app/DmIOS'), str(root / 'main.c')], check=True)
++ else:
++ (root / 'DmIOS.app/DmIOS').write_text('app')
++ (root / 'DmIOS.app/Info.plist').write_text(
++ '<?xml version="1.0" encoding="UTF-8"?><plist version="1.0"><dict>' +
++ '<key>CFBundleExecutable</key><string>DmIOS</string>' +
++ '<key>CFBundleIdentifier</key><string>org.nxnative.fixture</string></dict></plist>\n')
++
++ def framework(self, root):
++ """What project-framework.yml embeds: the dylib, its Info.plist and the resources at the framework's root."""
++ framework = root / 'DmIOS.app/Frameworks/DmGame.framework'
++ (framework / 'dm').mkdir(parents=True)
++ (root / 'marker.c').write_text('const char dmgame_image_marker[] = "DmGame";\n')
++ subprocess.run(['cc', '-dynamiclib', '-install_name', '@rpath/DmGame.framework/DmGame',
++ '-o', str(framework / 'DmGame'), str(root / 'marker.c')], check=True)
++ (framework / 'Info.plist').write_text(
++ '<?xml version="1.0" encoding="UTF-8"?><plist version="1.0"><dict>' +
++ '<key>CFBundleExecutable</key><string>DmGame</string>' +
++ '<key>CFBundleIdentifier</key><string>org.nxnative.fixture.DmGame</string>' +
++ '<key>CFBundlePackageType</key><string>FMWK</string>' +
++ '<key>CFBundleVersion</key><string>1.0</string></dict></plist>\n')
++ (framework / 'dm/shader_map.tsv').write_text('key\tfixture\n')
++ (framework / 'profile.tsv').write_text('id\t' + GAME + '\n')
++ (framework / 'game.manifest.json').write_text('{"schema": 1}\n')
++ return framework
++
++ def pack(self, framework):
++ """Sign what the build signs and pack a stand-in app; the files outlive the call for the caller's checks."""
++ root = Path(tempfile.mkdtemp()).resolve()
++ self.addCleanup(shutil.rmtree, root)
++ self.stand_in(root, compiled=framework)
++ signing = []
++ if framework:
++ self.framework(root)
++ signing = [(FRAMEWORK_SIGNING, dict(FRAMEWORK='1')), (SIGNING, {})] # the build's order: framework, then the app's executable
++ for script, extra in signing:
++ result = run_step(script, root, APP=str(root / 'DmIOS.app'), O=str(root / 'pkg'), **extra)
++ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
++ result = run_step(PACKING, root, APP=str(root / 'DmIOS.app'), MSL_IOS=str(root / 'shaders'), MSLDIR='b-fixture',
++ ROMFS=str(root / 'romfs'), AOC=str(root / 'aoc'), OUT_IPA=str(root / 'out.ipa'), O=str(root / 'pkg'),
++ DM_APP_VERSION='1.2.1', PKG='v327680')
++ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
++ with zipfile.ZipFile(root / 'out.ipa') as archive:
++ names = set(archive.namelist())
++ archive.extractall(root / 'extracted')
++ return names, root
++
++ def test_the_default_build_has_no_frameworks(self):
++ names, _ = self.pack(framework=False)
++ self.assertFalse([n for n in names if '/Frameworks/' in n], 'the default project has no framework target')
++ self.assertIn('Payload/DmIOS.app/DmIOS', names)
++
++ @unittest.skipUnless(CAN_SIGN, 'needs macOS codesign and a C compiler')
++ def test_the_framework_is_packed_and_signed_without_entitlements(self):
++ names, root = self.pack(framework=True)
++ base = 'Payload/DmIOS.app/Frameworks/DmGame.framework'
++ for name in ('DmGame', 'Info.plist', 'dm/shader_map.tsv', 'profile.tsv', 'game.manifest.json'):
++ self.assertIn(f'{base}/{name}', names)
++ extracted = root / 'extracted/Payload/DmIOS.app'
++
++ def entitlements(path):
++ return subprocess.run(['codesign', '-d', '--entitlements', ':-', str(path)], capture_output=True, text=True).stdout
++
++ self.assertEqual(entitlements(extracted / 'Frameworks/DmGame.framework/DmGame'), '',
++ 'a dylib cannot carry entitlements; the request belongs to the app')
++ self.assertIn('com.apple.developer.kernel.increased-memory-limit', entitlements(extracted / 'DmIOS'),
++ 'the app executable keeps the Increased Memory Limit request')
++ verified = subprocess.run(['codesign', '-vvv', '--verify', '--strict', str(extracted / 'Frameworks/DmGame.framework')],
++ capture_output=True, text=True)
++ self.assertEqual(verified.returncode, 0, verified.stdout + verified.stderr)
++
++
++if __name__ == '__main__':
++ unittest.main()
+diff --git a/dm/ios/tests/test_framework_link.py b/dm/ios/tests/test_framework_link.py
+new file mode 100644
+index 00000000..ccbba80e
+--- /dev/null
++++ b/dm/ios/tests/test_framework_link.py
+@@ -0,0 +1,125 @@
++"""Route C M1 (docs/launcher-c-plan.md): xcodebuild links the game's modules into DmGame.framework, off a device.
++
++Builds the framework target of project-framework.yml from a synthetic Gen/ (two 64 KB stand-in modules: main and one NRO) and
++reads the linked dylib back with otool: the three section blocks of each module are in the framework (__TEXT,__dm<mod>x0,
++__DM<mod>W,__img, __TEXT,__dm<mod>x1), the NRO pieces with them (__TEXT,__dm_nro_x0, __DM_NRO_W,__img, __TEXT,__dm_nro_x1) and
++__DATA,__dm_nro_tab lists them; the install name is @rpath/DmGame.framework/DmGame; the framework carries its dm/ tables,
++profile.tsv and game.manifest.json at its root. The generated project also shows what the app does with it: an Embed Frameworks
++phase and LD_RUNPATH_SEARCH_PATHS @executable_path/Frameworks. No game files, shaders or signing are involved.
++
++Needs macos, XcodeGen and an iPhoneOS SDK; skipped otherwise (CI's tool tests run without a device but with both).
++"""
++import json
++import os
++from pathlib import Path
++import plistlib
++import shutil
++import subprocess
++import sys
++import tempfile
++import unittest
++
++REPO = Path(__file__).resolve().parents[3]
++GAME = '010015100B514000'
++HAS_TOOLS = (sys.platform == 'darwin' and shutil.which('xcodegen') and shutil.which('xcodebuild')
++ and subprocess.run(['xcrun', '--sdk', 'iphoneos', '--show-sdk-path'], capture_output=True).returncode == 0)
++
++
++def run(*command, cwd=None, env=None):
++ return subprocess.run([str(c) for c in command], cwd=cwd, env=env, capture_output=True, text=True)
++
++
++def fail_tail(result):
++ return '\n'.join((result.stdout + result.stderr).splitlines()[-40:])
++
++
++def sections(binary):
++ """(segment, section) pairs from otool -l: a section block names its segment first."""
++ out = run('otool', '-l', binary).stdout
++ pairs, segment = set(), None
++ for line in out.splitlines():
++ words = line.split()
++ if len(words) == 2 and words[0] == 'segname': segment = words[1]
++ elif len(words) == 2 and words[0] == 'sectname' and segment: pairs.add((segment, words[1]))
++ return pairs
++
++
[email protected](HAS_TOOLS, 'needs macOS, XcodeGen and an iPhoneOS SDK')
++class FrameworkLinkTests(unittest.TestCase):
++ def test_the_framework_carries_the_module_sections_and_the_loader_tables(self):
++ root = Path(tempfile.mkdtemp()).resolve()
++ self.addCleanup(shutil.rmtree, root)
++ project, gen = root / 'project', root / 'project/Gen'
++ (gen / 'dm').mkdir(parents=True)
++ (gen / 'src').mkdir()
++ (gen / 'main').mkdir()
++ (gen / 'Assets.xcassets').mkdir()
++ (gen / 'Assets.xcassets/Contents.json').write_text(json.dumps({'info': {'author': 'xcode', 'version': 1}}))
++ (gen / 'src/fixture.c').write_text('/* stand-in: the app target is not built here */\n')
++ (gen / 'main/main.c').write_text('int dm_main(int argc, char **argv) { (void)argc; (void)argv; return 0; }\n')
++ for name in ('Sources', 'tools', 'framework'):
++ (project / name).symlink_to(REPO / 'dm/ios' / name, target_is_directory=True)
++ shutil.copyfile(REPO / 'dm/ios/project-framework.yml', project / 'project.yml')
++
++ # Two stand-in modules with the rewriter's four boundary keys; the NRO is listed in nro.tsv, so gen_embed.py packs it
++ patched = root / 'patched'
++ patched.mkdir()
++ for name in ('main', 'nrotest'):
++ (patched / f'{name}.patched.bin').write_bytes(bytes(0x10000))
++ (patched / f'{name}.fixups.tsv').write_text('# TEXT_END 0x4000\n# PATCH_OFF 0xc000\n# KEY_PAGE_OFF 0x8000\n# KEY_PAGE_SIZE 0x4000\n')
++ (patched / 'nro.tsv').write_text('nrotest\tfixture.nro\n')
++ flags = run(sys.executable, REPO / 'dm/ios/tools/gen_embed.py', patched, gen / 'embed.S', 'main', 'nrotest')
++ self.assertEqual(flags.returncode, 0, fail_tail(flags))
++ # The app target's config is not used by `xcodebuild -target DmGame`; it only has to exist (xcodegen's configFiles)
++ (gen / 'dm.xcconfig').write_text('HEADER_SEARCH_PATHS = $(inherited)\nOTHER_CFLAGS = $(inherited)\nDM_FRAMEWORKS =\nOTHER_LDFLAGS = $(inherited)\n')
++ (gen / 'framework.xcconfig').write_text(f'OTHER_LDFLAGS = $(inherited) {flags.stdout.strip()}\n')
++ (gen / 'framework/dm').mkdir(parents=True)
++ for name in ('main.fixups.tsv', 'nrotest.fixups.tsv', 'nro.tsv'):
++ shutil.copyfile(patched / name, gen / 'dm' / name)
++ (gen / 'dm/shader_map.tsv').write_text('key\tfixture\n')
++ for name in ('main.fixups.tsv', 'nrotest.fixups.tsv', 'nro.tsv', 'shader_map.tsv'):
++ shutil.copyfile(gen / 'dm' / name, gen / 'framework/dm' / name)
++ profile = run(sys.executable, REPO / 'dm/games/game.py', 'profile', GAME, gen / 'framework/profile.tsv')
++ self.assertEqual(profile.returncode, 0, fail_tail(profile))
++ chain = next(line.split('"')[1] for line in (REPO / 'dm/gfx/nvn/dmsh_chain.h').read_text().splitlines()
++ if line.startswith('#define DMSH_CHAIN "'))
++ manifest = run(sys.executable, REPO / 'dm/ios/tools/gen_manifest.py', gen / 'framework/game.manifest.json', '--game', GAME,
++ '--name', 'Fixture Game', '--display-version', '1.0', '--package-version', 'v0', '--modules', 'main',
++ '--nro-table', patched / 'nro.tsv', '--chain', 'b-' + chain, '--romfs-marker', 'marker')
++ self.assertEqual(manifest.returncode, 0, fail_tail(manifest))
++
++ env = dict(os.environ, GAME=GAME, DM_GAME=GAME, DM_BUNDLE_ID='org.nxnative.fixture', DM_DISPLAY_NAME='Fixture Game',
++ DM_APP_VERSION='1.0', DM_APP_CATEGORY='action', DM_TEAM_ID='', DM_SCHEME_NAME='DmIOS', DM_APPICON='',
++ DM_SHOW_FPS='NO', DM_LANG='en-US')
++ generated = run('xcodegen', 'generate', cwd=project, env=env)
++ self.assertEqual(generated.returncode, 0, fail_tail(generated))
++ pbx = (project / 'DmIOS.xcodeproj/project.pbxproj').read_text()
++ self.assertIn('Embed Frameworks', pbx) # the app embeds the framework ...
++ self.assertIn('@executable_path/Frameworks', pbx) # ... and can find it by that path
++ self.assertIn('LD_RUNPATH_SEARCH_PATHS', pbx)
++
++ derived = root / 'derived'
++ built = run('xcodebuild', '-project', project / 'DmIOS.xcodeproj', '-target', 'DmGame', '-configuration', 'Release',
++ '-destination', 'generic/platform=iOS',
++ f'SYMROOT={derived}/Build/Products', f'OBJROOT={derived}/Build/Intermediates.noindex',
++ 'CODE_SIGNING_ALLOWED=NO', 'CODE_SIGNING_REQUIRED=NO', 'CODE_SIGN_IDENTITY=', 'build', cwd=project, env=env)
++ self.assertEqual(built.returncode, 0, fail_tail(built))
++ framework = derived / 'Build/Products/Release-iphoneos/DmGame.framework'
++ binary = framework / 'DmGame'
++ self.assertTrue(binary.is_file(), f'no {binary}')
++ self.assertEqual(plistlib.loads((framework / 'Info.plist').read_bytes())['CFBundleExecutable'], 'DmGame')
++ for name in ('dm/shader_map.tsv', 'dm/nro.tsv', 'dm/main.fixups.tsv', 'profile.tsv', 'game.manifest.json'):
++ self.assertTrue((framework / name).is_file(), f'the framework is missing {name}')
++ self.assertEqual(json.loads((framework / 'game.manifest.json').read_text())['nro_count'], 1)
++
++ got = sections(binary)
++ for pair in [('__TEXT', '__dmmainx0'), ('__DMmainW', '__img'), ('__TEXT', '__dmmainx1'),
++ ('__TEXT', '__dmnrotestx0'), ('__DMnrotestW', '__img'), ('__TEXT', '__dmnrotestx1'),
++ ('__TEXT', '__dm_nro_x0'), ('__DM_NRO_W', '__img'), ('__TEXT', '__dm_nro_x1'),
++ ('__DATA', '__dm_nro_tab')]:
++ self.assertIn(pair, got, f'{pair[0]},{pair[1]} is not a section of the framework')
++ self.assertIn('@rpath/DmGame.framework/DmGame', run('otool', '-D', binary).stdout)
++
++
++if __name__ == '__main__':
++ unittest.main()
+diff --git a/dm/ios/tests/test_xcode_workflow.py b/dm/ios/tests/test_xcode_workflow.py
+index 2881f08c..98b0e62c 100644
+--- a/dm/ios/tests/test_xcode_workflow.py
++++ b/dm/ios/tests/test_xcode_workflow.py
+@@ -29,7 +29,12 @@ class XcodePipelineTests(unittest.TestCase):
+ with self.subTest(graphics=graphics, derived=derived):
+ self.prepare_fixture(graphics, derived)
+
+- def prepare_fixture(self, graphics, derived):
++ def test_prepare_with_framework_asks_for_the_framework_project(self):
++ # --framework (route C, docs/launcher-c-plan.md M1): build_ipa.sh gets DM_FRAMEWORK=1 and copies
++ # project-framework.yml in as the project (test_framework_build.py checks that copy on the script itself)
++ self.prepare_fixture('nvn', False, framework=True)
++
++ def prepare_fixture(self, graphics, derived, framework=False):
+ with tempfile.TemporaryDirectory() as temporary, ExitStack() as stack:
+ root = Path(temporary).resolve()
+ (root / 'prod.keys').touch()
+@@ -75,7 +80,8 @@ class XcodePipelineTests(unittest.TestCase):
+ try:
+ with redirect_stdout(output):
+ code = build.cli([str(root), '-k', str(root / 'prod.keys'), '--prepare-xcode',
+- '--language', 'ja', '--no-show-fps', '--no-motion', '--progress', 'json'])
++ '--language', 'ja', '--no-show-fps', '--no-motion', '--progress', 'json']
++ + (['--framework'] if framework else []))
+ finally:
+ progress.close()
+ self.assertEqual(code, 0)
+@@ -92,6 +98,7 @@ class XcodePipelineTests(unittest.TestCase):
+ self.assertEqual(environment['GFXAPI'], graphics)
+ self.assertEqual(environment['DM_BUNDLE_ID'], 'com.example.saved')
+ self.assertEqual(environment['DM_TEAM_ID'], 'ABCDEFGHIJ')
++ self.assertEqual(environment.get('DM_FRAMEWORK'), '1' if framework else None)
+ self.assertEqual(Path(environment['DM_XCODE_PROJECT_DIR']), root / f'{registered.id}_build/xcode')
+ register.assert_called_once()
+ self.assertEqual(mocks['derive_profile'].call_count, int(derived))
diff --git a/patches/0038-dm-framework-env-switch-row.patch b/patches/0038-dm-framework-env-switch-row.patch
new file mode 100644
index 00000000..ae7a797b
--- /dev/null
+++ b/patches/0038-dm-framework-env-switch-row.patch
@@ -0,0 +1,30 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: LNPANDY <[email protected]>
+Date: Fri, 30 Oct 2026 16:15:06 +0100
+Subject: [PATCH] Docs: DM_FRAMEWORK in the env switches table
+
+`build_ipa.sh` reads DM_FRAMEWORK (and the NSP script sets it), so
+dm/tools/env_switches.py --check lists it as a switch the code reads but
+docs/env_switches.tsv does not describe. One row, class `switch`, with
+what `=1` does and that the default keeps the in-executable build.
+
+Upstream-Status: fork-only (waits for the runtime profile, seedds/nxnative#492)
+Reason: opt-in game framework for the launcher (route C M1): it carries profile.tsv and sets DM_PROFILE, which exist only with the runtime-profile patch (seedds/nxnative#492 is still a design note), so it goes upstream after that
+Issue: LNPANDY/NX2Apple#144
+
+---
+ docs/env_switches.tsv | 1 +
+ 1 file changed, 1 insertion(+)
+
+diff --git a/docs/env_switches.tsv b/docs/env_switches.tsv
+index 6993f8dc..0645b4db 100644
+--- a/docs/env_switches.tsv
++++ b/docs/env_switches.tsv
+@@ -37,6 +37,7 @@ DM_FORCE_STRICT diagnostic `=1` makes the loader fail on forced-hook entries no
+ DM_FPS switch `30` or `60` pins the frame rate the display link and frame pacing aim for; otherwise it follows the game's present interval (60, or 30 when the game asks for 30)
+ DM_FPS_HOLD player `on` / `off` overrides the profile's `fps_hold`: whether late frames may raise the hold above the frame cap's vsyncs (on by default)
+ DM_FPS_TARGET player Frame-rate cap: `30` or `60`, or `0` for the game's own limit; overrides the profile's `fps_target`
++DM_FRAMEWORK switch `=1` (route C M1) compiles the game's modules into `DmIOS.app/Frameworks/DmGame.framework` instead of the executable, which `dlopen`s it at launch (`dm/ios/project-framework.yml`; the NSP script's `--framework` sets it); the default 0 keeps the usual in-executable build
+ DM_FS diagnostic When set, logs file opens, paths not found or not mounted, and a read summary every 64 MiB or 1000 reads
+ 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
diff --git a/patches/series b/patches/series
index bd54ab70..5a00c538 100644
--- a/patches/series
+++ b/patches/series
@@ -26,3 +26,8 @@
0040-nsp-derived-profile-without-frame-step.patch
0041-shared-fonts-a-compact-stand-in-for-a-font-engin.patch
0042-ios-launcher-present-the-document-picker-once-pe.patch
+0034-route-c-loader-image-header.patch
+0035-route-c-game-framework.patch
+0036-route-c-framework-build.patch
+0037-route-c-framework-tests.patch
+0038-dm-framework-env-switch-row.patch