Skip to content

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

nn::ro: full dynamic-module (NRO) support, adapted from Jhaizhou-ops/nx-port

LNPANDYf073ae2068fa
diff --git a/dm/host/dm.h b/dm/host/dm.h
index 796629ce..59542958 100644
--- a/dm/host/dm.h
+++ b/dm/host/dm.h
@@ -42,6 +42,7 @@ typedef struct {
unsigned nsym;
uint32_t *symh; unsigned symh_mask; // Name hash table of defined symbols (open addressing, stores symbol indices; for a duplicated name only the smallest index is kept = the first hit of a linear scan)
uint64_t init, init_array, init_arraysz; // init = DT_INIT (the module's _init: registers the DSO and runs this module's init_array)
+ int late; // 1 = a dynamic module (NRO) preloaded like main / sdk: its DT_INIT runs at nn::ro::LoadModule, not with the others (hle_ro.c)
} module_t;
extern module_t g_mod[MAX_MOD];
@@ -55,6 +56,7 @@ extern pthread_key_t g_keyres[2], g_keyaspect, g_keyaspectui;
void load_modules(const char *dir, const char **names, int n);
void run_module_inits(void);
+void run_module_init_one(void *m); // one module's DT_INIT (hle_ro.c calls it at nn::ro::LoadModule for a preloaded NRO; module_t * cast inside)
void *module_sym(module_t *m, const char *name);
void *guest_sym(const char *name);
module_t *module_of(const void *p);
diff --git a/dm/host/hle_ro.c b/dm/host/hle_ro.c
index 46b79333..9252e51a 100644
--- a/dm/host/hle_ro.c
+++ b/dm/host/hle_ro.c
@@ -1,37 +1,91 @@
-// nn::ro (loading NRO modules at run time): on the real device it connects to the ldr:ro service. The host has no such service; running the SDK's Initialize as is reads a null session in InitializeWithPortName and crashes (Engage).
-// Engage (Unity) imports 8 ro interfaces but its RomFS has no .nro / .nrr: at startup it only calls Initialize, and symbol lookups go through LookupSymbol.
-// Takeover: Initialize is a no-op; LookupSymbol finds the definition by name in the loaded modules (main / subsdk* / sdk); loading / unloading / registering modules always fails and reports red once (there is nothing to load).
-// Only success matters: the game checks IsSuccess only, so the failure code is a non-zero value under the ro module number 22.
+// nn::ro dynamic modules (NRO): on a real device the game reads the .nro into memory and hands it to
+// nn::ro::LoadModule, and the system maps it as executable code. Apple platforms do not allow
+// executing code written at run time, so dynamic modules are rewritten offline like main / sdk,
+// loaded with the host and relocated across modules (just give more module names on the command
+// line); here the nn::ro interface is taken over as "recognize the already-loaded copy by build
+// ID", and its global constructors run only at this point.
+// Thread-local variables (R_AARCH64_TLSDESC): one zeroed block per thread per module; the resolver
+// returns "variable address − thread pointer".
+// Known limitation: the non-zero initial-value template of .tdata is not fetched (an NRO has no
+// program headers; the template location is yet to be located), so a thread_local with a non-zero
+// constant initializer reads 0.
+// Adapted from Jhaizhou-ops/nx-port (MIT), which proved the design on a second title.
#include "hle.h"
-#define RO_FAIL ((Result)(22 | (1 << 9))) // a failure under ro module 22
+#define RO_TLS_SIZE 0x10000
+static pthread_key_t g_rotls[MAX_MOD];
+static pthread_once_t g_rotls_once = PTHREAD_ONCE_INIT;
+static void rotls_keys(void) { for (int i = 0; i < MAX_MOD; i++) if (pthread_key_create(&g_rotls[i], free)) die("nn::ro: cannot create the thread-local storage keys"); }
-HLE_FORCE("_ZN2nn2ro10InitializeEv", "connect to the ldr:ro service; the host has none, symbol lookups search the loaded modules directly", Result, h_ro_Initialize, void) { LOG("init takeover: ro::Initialize (no-op)"); return 0; }
-
-HLE_FORCE("_ZN2nn2ro12LookupSymbolEPmPKc", "look up a definition by name in the loaded modules", Result, h_ro_LookupSymbol, uintptr_t *out, const char *name) {
- void *p = name ? guest_sym(name) : NULL;
- static int n; if (n++ < 40) LOG("ro::LookupSymbol %s → %p", name ? name : "(null)", p);
- if (!p) { static int red; if (!red++) LOG("[RED] ro::LookupSymbol cannot find %s (first case)", name ? name : "(null)"); return RO_FAIL; }
- if (out) *out = (uintptr_t)p;
- return 0;
+// Second word of the descriptor: top 8 bits module index, low 56 bits the variable's offset inside
+// that module's thread-local segment
+uint64_t ro_tlsdesc_c(const uint64_t *desc) {
+ unsigned mi = (unsigned)(desc[1] >> 56); uint64_t off = desc[1] & 0x00ffffffffffffffull;
+ uint8_t *blk = pthread_getspecific(g_rotls[mi]);
+ if (!blk) { blk = calloc(1, RO_TLS_SIZE); if (!blk) die("nn::ro: thread-local storage allocation failed"); pthread_setspecific(g_rotls[mi], blk); }
+ return (uint64_t)(blk + off) - (uint64_t)pthread_getspecific(g_keytls);
}
-
-HLE_FORCE("_ZN2nn2ro18LookupModuleSymbolEPmPKNS0_6ModuleEPKc", "no NRO loaded: every per-module lookup finds nothing", Result, h_ro_LookupModuleSymbol, uintptr_t *out, const void *m, const char *name) {
- (void)out; (void)m; static int red; if (!red++) LOG("[RED] ro::LookupModuleSymbol %s: no NRO loaded", name ? name : "(null)"); return RO_FAIL;
+// TLSDESC calling convention: x0 = descriptor address, result in x0; every register other than
+// x0, x1, x30 (floating point included) must be preserved, so everything is saved here before entering C
+__attribute__((naked)) static void ro_tlsdesc_entry(void) {
+ __asm__ volatile(
+ "sub sp, sp, #0x2c0\n"
+ "stp x2, x3, [sp, #0x00]\n stp x4, x5, [sp, #0x10]\n stp x6, x7, [sp, #0x20]\n stp x8, x9, [sp, #0x30]\n"
+ "stp x10, x11, [sp, #0x40]\n stp x12, x13, [sp, #0x50]\n stp x14, x15, [sp, #0x60]\n stp x16, x17, [sp, #0x70]\n"
+ "stp x29, x30, [sp, #0x80]\n str x1, [sp, #0x90]\n"
+ "stp q0, q1, [sp, #0xa0]\n stp q2, q3, [sp, #0xc0]\n stp q4, q5, [sp, #0xe0]\n stp q6, q7, [sp, #0x100]\n"
+ "stp q16, q17, [sp, #0x120]\n stp q18, q19, [sp, #0x140]\n stp q20, q21, [sp, #0x160]\n stp q22, q23, [sp, #0x180]\n"
+ "stp q24, q25, [sp, #0x1a0]\n stp q26, q27, [sp, #0x1c0]\n stp q28, q29, [sp, #0x1e0]\n stp q30, q31, [sp, #0x200]\n"
+ "bl _ro_tlsdesc_c\n"
+ "ldp q30, q31, [sp, #0x200]\n ldp q28, q29, [sp, #0x1e0]\n ldp q26, q27, [sp, #0x1c0]\n ldp q24, q25, [sp, #0x1a0]\n"
+ "ldp q22, q23, [sp, #0x180]\n ldp q20, q21, [sp, #0x160]\n ldp q18, q19, [sp, #0x140]\n ldp q16, q17, [sp, #0x120]\n"
+ "ldp q6, q7, [sp, #0x100]\n ldp q4, q5, [sp, #0xe0]\n ldp q2, q3, [sp, #0xc0]\n ldp q0, q1, [sp, #0xa0]\n"
+ "ldr x1, [sp, #0x90]\n ldp x29, x30, [sp, #0x80]\n"
+ "ldp x16, x17, [sp, #0x70]\n ldp x14, x15, [sp, #0x60]\n ldp x12, x13, [sp, #0x50]\n ldp x10, x11, [sp, #0x40]\n"
+ "ldp x8, x9, [sp, #0x30]\n ldp x6, x7, [sp, #0x20]\n ldp x4, x5, [sp, #0x10]\n ldp x2, x3, [sp, #0x00]\n"
+ "add sp, sp, #0x2c0\n ret\n");
}
-
-HLE_FORCE("_ZN2nn2ro13GetBufferSizeEPmPKv", "NROs are not loaded", Result, h_ro_GetBufferSize, size_t *out, const void *image) {
- (void)image; if (out) *out = 0; static int red; if (!red++) LOG("[RED] ro::GetBufferSize: the host does not load NROs"); return RO_FAIL;
+void ro_tlsdesc_fill(module_t *m, uint64_t *where, uint64_t off) {
+ pthread_once(&g_rotls_once, rotls_keys);
+ if (off >= RO_TLS_SIZE) die("%s: thread-local variable offset %#llx exceeds the reserved %#x", m->name, (unsigned long long)off, RO_TLS_SIZE);
+ where[0] = (uint64_t)ro_tlsdesc_entry; where[1] = (uint64_t)(m - g_mod) << 56 | off;
}
-HLE_FORCE("_ZN2nn2ro10LoadModuleEPNS0_6ModuleEPKvPvmi", "NROs are not loaded", Result, h_ro_LoadModule, void *m, const void *image, void *buf, size_t size, int flag) {
- (void)m; (void)image; (void)buf; (void)flag; static int red; if (!red++) LOG("[RED] ro::LoadModule: the host does not load NROs (buffer %#zx)", size); return RO_FAIL;
+// nn::ro::Module: only the first two words are used (loaded-module pointer, state 1 = loaded); every interface that reads it is taken over in this file
+typedef struct { module_t *mod; uint32_t state; } ro_module;
+static module_t *ro_find(const uint8_t *image) {
+ if (!image || memcmp(image + 0x10, "NRO0", 4)) return NULL;
+ for (int i = 0; i < g_nmod; i++) if (g_mod[i].late && !memcmp(g_mod[i].base + 0x40, image + 0x40, 0x20)) return &g_mod[i];
+ return NULL;
}
-
-HLE_FORCE("_ZN2nn2ro12UnloadModuleEPNS0_6ModuleE", "NROs are not loaded", void, h_ro_UnloadModule, void *m) { (void)m; }
-
-HLE_FORCE("_ZN2nn2ro18RegisterModuleInfoEPNS0_16RegistrationInfoEPKv", "NRRs are not registered", Result, h_ro_RegisterModuleInfo, void *info, const void *nrr) {
- (void)info; (void)nrr; static int red; if (!red++) LOG("[RED] ro::RegisterModuleInfo: the host does not register NRRs"); return RO_FAIL;
+HLE_FORCE("_ZN2nn2ro10InitializeEv", "dynamic modules are preloaded by the host, no ldr:ro service", void, h_ro_Initialize, void) { LOG("nn::ro::Initialize"); }
+HLE_FORCE("_ZN2nn2ro8FinalizeEv", "dynamic modules are preloaded by the host", void, h_ro_Finalize, void) {}
+HLE_FORCE("_ZN2nn2ro18RegisterModuleInfoEPNS0_16RegistrationInfoEPKv", "signature registration (NRR): the host does not verify", Result, h_ro_RegisterModuleInfo, void *info, const void *nrr) { (void)info; (void)nrr; LOG("nn::ro::RegisterModuleInfo"); return RES_OK; }
+HLE_FORCE("_ZN2nn2ro18RegisterModuleInfoEPNS0_16RegistrationInfoEPKvj", "signature registration (NRR): the host does not verify", Result, h_ro_RegisterModuleInfo2, void *info, const void *nrr, uint32_t n) { (void)info; (void)nrr; (void)n; return RES_OK; }
+HLE_FORCE("_ZN2nn2ro20UnregisterModuleInfoEPNS0_16RegistrationInfoE", "signature registration (NRR): the host does not verify", void, h_ro_UnregisterModuleInfo, void *info) { (void)info; }
+HLE_FORCE("_ZN2nn2ro13GetBufferSizeEPmPKv", "bss size from the NRO header; the actual bss is already in the preloaded image", Result, h_ro_GetBufferSize, uint64_t *out, const uint8_t *image) {
+ uint32_t bss = 0; if (image && !memcmp(image + 0x10, "NRO0", 4)) memcpy(&bss, image + 0x38, 4);
+ *out = ((uint64_t)bss + 0xfff) & ~0xfffull; return RES_OK;
}
-
-HLE_FORCE("_ZN2nn2ro20UnregisterModuleInfoEPNS0_16RegistrationInfoE", "NRRs are not registered", void, h_ro_UnregisterModuleInfo, void *info) { (void)info; }
+HLE_FORCE("_ZN2nn2ro10LoadModuleEPNS0_6ModuleEPKvPvmi", "recognize the host-preloaded copy by build ID, and run its global constructors at this point", Result, h_ro_LoadModule, ro_module *out, const uint8_t *image, void *bss, uint64_t bss_size, int flag) {
+ (void)bss; (void)bss_size;
+ module_t *m = ro_find(image);
+ if (!m) { LOG("[RED] nn::ro::LoadModule: the dynamic module the game wants is not preloaded (rewrite it offline and add its name to the host's module list)"); return RES_FAIL; }
+ LOG("nn::ro::LoadModule → %s (base %p, flag %d)", m->name, m->base, flag);
+ out->mod = m; out->state = 1;
+ static uint8_t inited[MAX_MOD];
+ if (!inited[m - g_mod]) { inited[m - g_mod] = 1; run_module_init_one(m); }
+ LOG("nn::ro::LoadModule ← %s global constructors done", m->name);
+ return RES_OK;
+}
+HLE_FORCE("_ZN2nn2ro12UnloadModuleEPNS0_6ModuleE", "preloaded modules are not unloaded", void, h_ro_UnloadModule, ro_module *mod) { if (mod) mod->state = 0; }
+HLE_FORCE("_ZN2nn2ro12LookupSymbolEPmPKc", "search all loaded modules by name", Result, h_ro_LookupSymbol, uint64_t *out, const char *name) {
+ void *p = guest_sym(name); if (!p) { LOG("nn::ro::LookupSymbol cannot find %s", name); return RES_FAIL; }
+ *out = (uint64_t)p; return RES_OK;
+}
+HLE_FORCE("_ZN2nn2ro18LookupModuleSymbolEPmPKNS0_6ModuleEPKc", "search the named preloaded module", Result, h_ro_LookupModuleSymbol, uint64_t *out, const ro_module *mod, const char *name) {
+ void *p = mod && mod->mod ? module_sym(mod->mod, name) : NULL; if (!p) { LOG("nn::ro::LookupModuleSymbol cannot find %s", name); return RES_FAIL; }
+ *out = (uint64_t)p; return RES_OK;
+}
+HLE_FORCE("_ZN2nn2ro12ProtectRelroEPKvS2_S2_S2_S2_", "read-only relocation protection: the host does not change page permissions", void, h_ro_ProtectRelro, const void *a, const void *b, const void *c, const void *d, const void *e) { (void)a; (void)b; (void)c; (void)d; (void)e; }
+HLE_FORCE("_ZN2nn2ro29ProtectFullRelroForAllModulesEv", "read-only relocation protection: the host does not change page permissions", void, h_ro_ProtectFullRelro, void) {}
diff --git a/dm/host/loader.c b/dm/host/loader.c
index 41bf4e16..61e853a8 100644
--- a/dm/host/loader.c
+++ b/dm/host/loader.c
@@ -278,6 +278,15 @@ static void relocate(module_t *m) {
if (v != self && nint++ < 8) LOG("%s: %s bound to an earlier module's definition (%s)", m->name, m->strtab + s->st_name, module_of((void *)v) ? module_of((void *)v)->name : "?");
}
if (!v) v = resolve_sym(m, m->strtab + s->st_name);
+ if (type == 1031) { // R_AARCH64_TLSDESC: thread-local variable descriptor {resolver, argument}; resolved in hle_ro.c
+ void ro_tlsdesc_fill(module_t *, uint64_t *, uint64_t); ro_tlsdesc_fill(m, where, (si ? s->st_value : 0) + (uint64_t)r->r_addend); cnt[1]++; continue;
+ }
+ // A global symbol that a late module (a preloaded NRO) also defines itself: a real
+ // device resolves it in global lookup order, so a definition of the same name in the
+ // main program / sdk wins (symbol preemption). This makes template static members
+ // (singleton pointers instantiated once per module) the same object.
+ if (!v && m->late && s->st_shndx && !(s->st_other & 3) && (s->st_info >> 4) != 0)
+ for (int k = 0; k < g_nmod && !v; k++) if (!g_mod[k].late) v = (uint64_t)module_sym(&g_mod[k], m->strtab + s->st_name);
if (type == R_AARCH64_JUMP_SLOT) { *where = v; cnt[2]++; }
else { *where = v + r->r_addend; cnt[1]++; } // ABS64 / GLOB_DAT
}
@@ -432,6 +441,7 @@ void load_modules(const char *dir, const char **names, int n) {
for (int i = 0; i < n; i++) {
module_t *m = &g_mod[i];
strlcpy(m->name, names[i], sizeof m->name);
+ m->late = strcmp(m->name, "main") && strcmp(m->name, "game") && strcmp(m->name, "sdk") && strncmp(m->name, "subsdk", 6); // a dynamic module (NRO) preloaded: its DT_INIT runs at nn::ro::LoadModule (hle_ro.c)
read_layout(m, dir);
}
create_keys();
@@ -481,11 +491,12 @@ void load_modules(const char *dir, const char **names, int n) {
// Plays the role of rtld's InitModules (rtld+0x830): call each module's DT_INIT in forward order of the load list.
// The timing is decided by nn::init::Start: after nninitStartup and _init_libc2, before nnMain (the 4th argument callback of Start).
+// A late module (a preloaded NRO) has its DT_INIT run at nn::ro::LoadModule instead (hle_ro.c).
+void run_module_init_one(void *vm) {
+ module_t *m = vm; if (!m->init) return;
+ LOG("%s: DT_INIT +%#llx (init_array %llu entries)", m->name, m->init, m->init_arraysz / 8);
+ ((void (*)(void))(m->base + m->init))();
+}
void run_module_inits(void) {
- for (int i = 0; i < g_nmod; i++) {
- module_t *m = &g_mod[i];
- if (!m->init) continue;
- LOG("%s: DT_INIT +%#llx (init_array %llu entries)", m->name, m->init, m->init_arraysz / 8);
- ((void (*)(void))(m->base + m->init))();
- }
+ for (int i = 0; i < g_nmod; i++) if (!g_mod[i].late) run_module_init_one(&g_mod[i]);
}