Play your own Switch games on iPhone/iPad — one-click macOS app, no terminal. | 把 Switch 游戏装进 iPhone:图形界面一键构建,不用命令行。Bring your own game.
Swift apple-siliconcustom-formathomebrewiosipaipadipadosiphonemetalnative-portnintendo-switchnxnativeromfsswitch-games
experiment(stage2): runtime game profile
stage2 experiment73a89fb09fb5
diff --git a/dm/games/game.py b/dm/games/game.pyindex 1e207ea7..4e0af38f 100644--- a/dm/games/game.py+++ b/dm/games/game.py@@ -189,6 +189,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 hosttmp = out.with_name(out.name + '.tmp'); tmp.write_text(text); tmp.replace(out)+ elif len(a) == 3 and a[0] == 'profile': # the runtime profile the host reads from DM_PROFILE (hle_profile.h): the header's values, as the TSV form+ g = load(a[1]); out = Path(a[2]); out.parent.mkdir(parents=True, exist_ok=True)+ M = dict(re.findall(r'^#define (DM_GAME_\w+) (.*)$', header(g), re.M)) # exactly what the compiled profile would hold+ # macro → the runtime profile's key (hle_profile.c set_kv); the header's spelling of the value is the file's+ KEYS = [('title_id', 'ID'), ('program_id', 'PROGRAM_ID'), ('name', 'NAME'), ('romfs_marker', 'ROMFS_MARKER'),+ ('modules', 'MODULES'), ('mem_reserve', 'MEM_RESERVE'), ('mem_alias', 'MEM_ALIAS'), ('mem_stack', 'MEM_STACK'),+ ('app_pool', 'APP_POOL'), ('mem_used', 'MEM_USED'), ('sys_resource', 'SYS_RESOURCE'), ('mem_map_limit', 'MEM_MAP_LIMIT'),+ ('present_interval', 'PRESENT_DISPLAY'), ('core_preempt', 'CORE_PREEMPT'), ('alloc_big_align', 'ALLOC_BIG_ALIGN'),+ ('fps_target', 'FPS_TARGET'), ('fps_hold', 'FPS_HOLD'), ('present_snap', 'PRESENT_SNAP'), ('pso_mtl4', 'PSO_MTL4'),+ ('shared_font', 'SHARED_FONT_TTF'), ('pad_layout', 'PAD_LAYOUT'), ('op_mode', 'OPMODE'), ('perf_mode', 'PERF_BOOST'),+ ('feedback_snap', 'FEEDBACK_SNAP'), ('tex_flush_upload', 'TEX_FLUSH_UPLOAD'), ('render_cond', 'RENDER_COND'),+ ('tex_dirty_upload', 'TEX_DIRTY_UPLOAD'), ('tex_dyn_slots', 'TEX_DYN_SLOTS'), ('gpu_timestamps', 'GPU_TS_SEGMENT'),+ ('vconv_range', 'VCONV_RANGE'), ('game_args', 'ARGS'), ('game_env', 'ENV')]+ def val(macro): # the header's C spelling → the file's plain spelling+ v = M.get('DM_GAME_' + macro)+ if v is None: return None+ v = v.strip()+ if v.startswith('{') and v.endswith('}'): # {"main", "sdk"} → main sdk+ return ' '.join(x.strip().strip('"') for x in v[1:-1].split(',') if x.strip())+ if v.startswith('"'): return v[1:-1]+ return v[:-3] if v.endswith('ull') else v+ L = [f'# Runtime game profile of {g.id} ({g.get("name")}), written by dm/games/game.py profile from {g.dir}/game.tsv',+ '# Read by the host from DM_PROFILE (hle_profile.c set_kv): KEY<TAB>VALUE, # starts a comment. Every value the compiled',+ '# profile would hold is written, so the file alone describes the game.']+ for key, macro in KEYS:+ v = val(macro)+ if v is not None: L.append(f'{key}\t{v}')+ api = [val('NVN_API_MAJOR'), val('NVN_API_MINOR')]+ if api[0] is not None: L.append(f'device_api\t{api[0]}.{api[1] or 0}')+ for b, d in re.findall(r'\{"([0-9a-f]+)", "([^"]*)"\}', M.get('DM_GAME_DISPLAY_VERSIONS', '')):+ L.append(f'display_version\t{b}\t{d}')+ text = '\n'.join(L) + '\n'+ if not (out.exists() and out.read_text() == text): out.write_text(text, encoding='utf-8') # unchanged: keep the mtime+ print(out)elif len(a) == 2 and a[0] == 'dir':print(load(a[1]).dir)elif len(a) == 3 and a[0] == 'link': # link → the profile folder (replaced when it points elsewhere)diff --git a/dm/gfx/nvn/hle_nvn.c b/dm/gfx/nvn/hle_nvn.cindex 222baacf..8f321b83 100644--- a/dm/gfx/nvn/hle_nvn.c+++ b/dm/gfx/nvn/hle_nvn.c@@ -149,11 +149,11 @@ static const int g_devinfo[] = {__attribute__((weak)) int dm_sdk_major(void) { return 0; } // loader.c; graphics unit tests have no loader__attribute__((weak)) int dm_glslc_gpu_code(int *major, int *minor) { *major = *minor = 0; return 0; } // hle_glslc.c: the game's own GLSLC's GPU code versionstatic void nvn_api(int api[2]) {-#ifdef DM_GAME_NVN_API_MAJOR- api[0] = DM_GAME_NVN_API_MAJOR; api[1] = DM_GAME_NVN_API_MINOR; LOG("[nvn] device API %d.%d (game profile device_api)", api[0], api[1]);-#else- int m = dm_sdk_major(); api[0] = DM_SDK_OLD(m) ? 53 : g_devinfo[0]; api[1] = DM_SDK_OLD(m) ? 313 : g_devinfo[1]; LOG("[nvn] device API %d.%d (SDK %d)", api[0], api[1], m);-#endif+ const struct dm_profile *p = dm_profile(); // profile device_api; 0.0 = decide by the SDK version+ if (p->nvn_api_major) { api[0] = p->nvn_api_major; api[1] = p->nvn_api_minor; LOG("[nvn] device API %d.%d (game profile device_api)", api[0], api[1]); }+ else {+ int m = dm_sdk_major(); api[0] = DM_SDK_OLD(m) ? 53 : g_devinfo[0]; api[1] = DM_SDK_OLD(m) ? 313 : g_devinfo[1]; LOG("[nvn] device API %d.%d (SDK %d)", api[0], api[1], m);+ }}NVN(nvnDeviceGetInteger, void, const NVNdevice *d, NVNdeviceInfo what, int *out) {(void)d;@@ -329,16 +329,16 @@ typedef struct { const uint8_t *mem; uint64_t size; tex_t t; uint64_t stamp; constatic flush_tex *g_ft; static size_t g_nft, g_cft; static pthread_mutex_t g_ft_mu = PTHREAD_MUTEX_INITIALIZER;static void ft_add(const tex_t *t) {// Buffer textures are views onto the pool buffer the GPU reads directly (tex_mtl in nvn_mtl.m); an upload would push Age of Calamity's 1,048,576-texel R32F one through tex_desc, past Metal's 2D limit- if (!DM_GAME_TEX_FLUSH_UPLOAD || !t->mem || !t->pool || t->has_layout || t->d.target == NVN_TEXTURE_TARGET_BUFFER || (t->pool->flags & NVN_MEMORY_POOL_FLAGS_CPU_NO_ACCESS) ||+ if (!dm_profile()->tex_flush_upload || !t->mem || !t->pool || t->has_layout || t->d.target == NVN_TEXTURE_TARGET_BUFFER || (t->pool->flags & NVN_MEMORY_POOL_FLAGS_CPU_NO_ACCESS) ||(t->d.flags & (NVN_TEXTURE_FLAGS_LINEAR | NVN_TEXTURE_FLAGS_LINEAR_RENDER_TARGET | NVN_TEXTURE_FLAGS_COMPRESSIBLE))) return;pthread_mutex_lock(&g_ft_mu);if (g_nft == g_cft && !(g_ft = realloc(g_ft, (g_cft = g_cft ? 2 * g_cft : 1024) * sizeof *g_ft))) die("flush_tex allocation failed");- uint64_t st = nvn_dirty_now(); if (DM_GAME_TEX_DIRTY_UPLOAD) nvn_dirty_protect(t->mem, t->L.size); // see nvn_ft_written+ uint64_t st = nvn_dirty_now(); if (dm_profile()->tex_dirty_upload) nvn_dirty_protect(t->mem, t->L.size); // see nvn_ft_writteng_ft[g_nft++] = (flush_tex){t->mem, t->L.size, *t, st, nvn_dirty_span(t->mem, t->L.size)};pthread_mutex_unlock(&g_ft_mu);}static void ft_del(uint64_t serial) {- if (!DM_GAME_TEX_FLUSH_UPLOAD || !serial) return;+ if (!dm_profile()->tex_flush_upload || !serial) return;pthread_mutex_lock(&g_ft_mu);for (size_t i = 0; i < g_nft; i++) if (g_ft[i].t.serial == serial) { g_ft[i] = g_ft[--g_nft]; break; }pthread_mutex_unlock(&g_ft_mu);@@ -347,7 +347,7 @@ static void ft_del(uint64_t serial) {// natively; its 121-layer ASTC terrain material arrays, 42 MB each). They stayed GPU-only textures with content 0, which ASTC decodes as the error colour, and the cave came out magenta.// ft_add write-protects a registered texture's pages, and on its first resolution (tex_mtl, submit thread) a write since then makes it CPU-written like a flushed oneint nvn_ft_written(const tex_t *t) {- if (!DM_GAME_TEX_DIRTY_UPLOAD || !t->serial) return 0;+ if (!dm_profile()->tex_dirty_upload || !t->serial) return 0;int r = 0; pthread_mutex_lock(&g_ft_mu);for (size_t i = 0; i < g_nft; i++) if (g_ft[i].t.serial == t->serial) {if (nvn_dirty_since_span(g_ft[i].span, g_ft[i].mem, g_ft[i].size, g_ft[i].stamp)) { r = 1; g_ft[i] = g_ft[--g_nft]; }@@ -365,7 +365,7 @@ int nvn_ft_written(const tex_t *t) {// Checking every texture at every submission cost TOTK 0.4 ms of submit CPU per frame on the Mac; this way a texture is picked up a few submissions later at mostenum { FT_POLL_BYTES = 128 << 20 };void nvn_ft_poll(void) {- if (!DM_GAME_TEX_DIRTY_UPLOAD) return;+ if (!dm_profile()->tex_dirty_upload) return;static uint64_t gen; static size_t cur, left;static tex_t *hit; static size_t chit; size_t nhit = 0;uint64_t now = nvn_dirty_now(), scanned = 0;@@ -383,7 +383,7 @@ void nvn_ft_poll(void) {for (size_t i = 0; i < nhit; i++) if (!mtl_tex_gpu_owned(hit[i].serial)) mtl_tex_cpu_written(&hit[i]); // outside g_ft_mu: the ownership check takes the replay's serial table lock}static void ft_flush(const uint8_t *a, uint64_t n) {- if (!DM_GAME_TEX_FLUSH_UPLOAD || !a || !n) return;+ if (!dm_profile()->tex_flush_upload || !a || !n) return;pthread_mutex_lock(&g_ft_mu);for (size_t i = 0; i < g_nft;)if (g_ft[i].mem < a + n && a < g_ft[i].mem + g_ft[i].size) { mtl_tex_cpu_written(&g_ft[i].t); g_ft[i] = g_ft[--g_nft]; } else i++;@@ -1590,7 +1590,7 @@ static void present_cfg(const win_t *o) {// with a fixed hard floor of 60 fps; the logic stays at 25 ticks, and the client's frame-counted UI logic is unaffected -// with the same save and the same input, the UI message streams of the two modes match message by message. Proof (before character select): r9 game / display 60 ×3 / display 120 ×2, 6 groups in total, uicmp consistent// (the save indicator is exempted as a timing race), and the timing differences of key messages are within game mode's own noise band; proof after entering a run is still missing, pending action script coverage- const char *m = getenv("DM_PRESENT_INTERVAL"); g_display_mode = m ? !strcmp(m, "display") : DM_GAME_PRESENT_DISPLAY;+ const char *m = getenv("DM_PRESENT_INTERVAL"); g_display_mode = m ? !strcmp(m, "display") : dm_profile()->present_display;LOG("[nvn] present tick %d Hz, interval mode %s (%s; present interval set by the game %d; %s)", g_hz, g_display_mode ? "display (one frame per tick, a cut)" : "game (original semantics)",m ? "DM_PRESENT_INTERVAL" : "game profile present_interval", o->interval, scr > 0 ? "window, fixed 60 Hz" : "no window, fixed 60 Hz");}@@ -1639,7 +1639,7 @@ static int fstep_cpu_slowed(uint64_t presents) {static int fstep_hold(void) {static int h = -1;if (h < 0) {- const char *e = getenv("DM_FPS_HOLD"); h = e ? strcmp(e, "off") != 0 : DM_GAME_FPS_HOLD;+ const char *e = getenv("DM_FPS_HOLD"); h = e ? strcmp(e, "off") != 0 : dm_profile()->fps_hold;if (!h) LOG("[nvn] frame step: frames are not held longer than the cap's vsyncs (%s)", e ? "DM_FPS_HOLD" : "game profile fps_hold");}return h;@@ -1902,8 +1902,11 @@ static struct vpool **g_vp; static int g_nvp, g_cvp; // the pools with a rangestatic pthread_mutex_t g_vp_mu = PTHREAD_MUTEX_INITIALIZER;static _Atomic uint64_t g_vp_gen; // bumped per mapping requeststatic struct vpool *vpool_of(const pool_t *o) { return o->vp; }-static uint8_t *vpool_reserve(pool_t *o) { // → the reserved range, or NULL- if (!(o->flags & 0x200)) return NULL;+static uint8_t *vpool_reserve(pool_t *o) { // → the reserved range, or NULL for a pool that keeps the alias+ // A pool at or below the profile's application pool keeps the alias (the guest maps it whole+ // into the region it was told it has): reserve an own range only for one that can outgrow it.+ // Runtime profile: app_pool comes from the profile now (dm/games/<id>/game.tsv), not a macro.+ if (!(o->flags & 0x200) || o->size <= dm_profile()->app_pool) return NULL;#if TARGET_OS_IPHONE // 1 GB: Monster Hunter Rise's buffers stay under 0x20100000 through its opening, its textures (32 GB in) are read through the page table, and 4 GB guest + 1 GB stays near the 5 GB proven on a phoneuint64_t len = o->size < (1ull << 30) ? o->size : 1ull << 30;#else@@ -1918,7 +1921,7 @@ static uint8_t *vpool_reserve(pool_t *o) { // → the reserved range, or NULLpthread_mutex_lock(&g_vp_mu);if (g_nvp == g_cvp && !(g_vp = realloc(g_vp, (g_cvp = g_cvp ? 2 * g_cvp : 64) * sizeof *g_vp))) die("sparse pool table allocation failed");g_vp[g_nvp++] = v; o->vp = v;- o->vmode = o->size > DM_GAME_APP_POOL ? 2 : 0;+ o->vmode = o->size > dm_profile()->app_pool ? 2 : 0; // runtime profile: the application pool is a profile value nowpthread_mutex_unlock(&g_vp_mu);if (o->vmode == 2) LOG("[nvn] virtual pool %p (%#llx bytes, flags %#x): sparse, own address range %p+%#llx, physical pages are remapped into it", (const void *)o, (unsigned long long)o->size, o->flags, a, (unsigned long long)len);return a;@@ -2329,11 +2332,11 @@ NVN(nvnCommandBufferClearBuffer, void, NVNcommandBuffer *c, NVNbufferAddress a,// State the replay layer does not have yet: logged once (conditional rendering is treated as "always draw")// Render enable (profile render_cond, see OP_RENDER_COND in nvn_mtl.m): recorded and evaluated at replay; without the key everything draws, as beforeNVN(nvnCommandBufferSetRenderEnable, void, NVNcommandBuffer *c, uint32_t en) {- if (DM_GAME_RENDER_COND) *REC(c, OP_RENDER_COND, p_render_cond) = (p_render_cond){(en & 0xff) ? 2 : 3, 0, 0};+ if (dm_profile()->render_cond) *REC(c, OP_RENDER_COND, p_render_cond) = (p_render_cond){(en & 0xff) ? 2 : 3, 0, 0};else if (!(en & 0xff)) ONCE_LOG("[RED] SetRenderEnable(false): the host draws anyway for now");}NVN(nvnCommandBufferSetRenderEnableConditional, void, NVNcommandBuffer *c, NVNconditionalRenderMode m, NVNbufferAddress a) {- if (DM_GAME_RENDER_COND) *REC(c, OP_RENDER_COND, p_render_cond) = (p_render_cond){(int)m & 1, 0, a};+ if (dm_profile()->render_cond) *REC(c, OP_RENDER_COND, p_render_cond) = (p_render_cond){(int)m & 1, 0, a};else ONCE_LOG("[RED] SetRenderEnableConditional: the host draws anyway for now");}// Fire Emblem: Three Houses turns depth clamp on for its scenes; ignored, the ground right under its close-up battle cameras was clipped away and the lighting pass painted the sky's fog colour therediff --git a/dm/gfx/nvn/nvn_mtl.m b/dm/gfx/nvn/nvn_mtl.mindex 5782fbbd..c64be58f 100644--- a/dm/gfx/nvn/nvn_mtl.m+++ b/dm/gfx/nvn/nvn_mtl.m@@ -1210,7 +1210,7 @@ static uint64_t gpu_ticks(void) { uint64_t g = guest_ns(); if (!g) { struct time// so a game that waits for the fence reads one submission's reports together; a segment whose feedback has not arrived by then takes the last segment's times#define SEG_CLK_N 1024struct seg_clk { _Atomic int refs; _Atomic uint64_t t[SEG_CLK_N][2]; }; // per submission (g_sclk, allocated at its first cut): guest ns of each cut segment's GPU start / end (0 = no feedback yet)-static int seg_ts(void) { static int v = -1; if (v < 0) { const char *e = getenv("DM_NVN_GPU_TS"); v = e && *e ? !strcmp(e, "segment") : DM_GAME_GPU_TS_SEGMENT; MLOG("counter timestamps: %s (profile key gpu_timestamps; DM_NVN_GPU_TS=segment / submission)", v ? "GPU start / end time of their segment" : "one time for the whole submission"); } return v; }+static int seg_ts(void) { static int v = -1; if (v < 0) { const char *e = getenv("DM_NVN_GPU_TS"); v = e && *e ? !strcmp(e, "segment") : dm_profile()->gpu_ts_segment; MLOG("counter timestamps: %s (profile key gpu_timestamps; DM_NVN_GPU_TS=segment / submission)", v ? "GPU start / end time of their segment" : "one time for the whole submission"); } return v; }static void seg_clk_put(seg_clk *c) { if (c && atomic_fetch_sub(&c->refs, 1) == 1) free(c); }static uint64_t gpu_s_guest_ns(double s) { // a feedback GPU time (seconds on the mach absolute time base) on the guest clock; 0 when unknownstatic mach_timebase_info_data_t tb; if (!tb.denom) mach_timebase_info(&tb);@@ -1394,7 +1394,7 @@ static void post_run(post_rec *r, uint64_t c0, uint64_t c1) {for (int k = 0; k < l->n; k++) { sum += ((const uint64_t *)((__bridge id<MTLBuffer>)l->s[k].buf).contents)[l->s[k].slot]; CFRelease(l->s[k].buf); }free(l); uint64_t rec[2] = {sum, gpu_ticks()}; memcpy((void *)ops[i].addr, rec, sizeof rec);}- else { uint64_t t = rep_ticks(&ops[i], sc, seg_last, c0, c1), rec[2] = {(ops[i].type == 0 || ops[i].type == 0x10) && !DM_GAME_RENDER_COND ? t : 0, t}; memcpy((void *)ops[i].addr, rec, sizeof rec); } // render_cond: a timestamp report's counter field is 0, as on the GPU (see rc_value)+ else { uint64_t t = rep_ticks(&ops[i], sc, seg_last, c0, c1), rec[2] = {(ops[i].type == 0 || ops[i].type == 0x10) && !dm_profile()->render_cond ? t : 0, t}; memcpy((void *)ops[i].addr, rec, sizeof rec); } // render_cond: a timestamp report's counter field is 0, as on the GPU (see rc_value)}free(ops); seg_clk_put(sc); r->ops = NULL; r->sc = NULL;atomic_store(&r->claimed, 1);@@ -2359,7 +2359,7 @@ static id<MTLTexture> tex_mtl_(const tex_t *ct) {}}id have = tex_get(t->serial);- if (!packaged && !have && DM_GAME_TEX_DIRTY_UPLOAD && t->mem && on_sub_thread()) { int nvn_ft_written(const tex_t *); packaged = nvn_ft_written(t); } // first use of a texture the CPU wrote since init without a flush (hle_nvn.c)+ if (!packaged && !have && dm_profile()->tex_dirty_upload && t->mem && on_sub_thread()) { int nvn_ft_written(const tex_t *); packaged = nvn_ft_written(t); } // first use of a texture the CPU wrote since init without a flush (hle_nvn.c)if (packaged) {NvPkg *pk = [have isKindOfClass:[NvPkg class]] ? have : nil; // resolved as GPU-only before the CPU wrote it: dropped and rebuilt as packagedif (pk) { // Already uploaded: check the covered pages only if there has been a guest write since the last check@@ -3293,7 +3293,7 @@ static NSString *exe_rel(const char *rel) {static void shmap_load(void) {if (g_shmap) return;const char *e = getenv("DM_NVN_SHMAP");- NSString *path = e ? @(e) : exe_rel("../games/" DM_GAME_ID "/shader_map.tsv"); // default: the current game profile folder (Mac: dm/games/<id>; on iOS main.m sets DM_NVN_SHMAP)+ NSString *path = e ? @(e) : exe_rel([NSString stringWithFormat:@"../games/%s/shader_map.tsv", dm_profile()->id].UTF8String); // default: the current game profile folder (Mac: dm/games/<id>; on iOS main.m sets DM_NVN_SHMAP)NSString *txt = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];if (!txt) MDIE("cannot read the shader map %s (DM_NVN_SHMAP can name another)", path.UTF8String);g_shmap = [NSMutableDictionary dictionary];@@ -3315,7 +3315,7 @@ static void shmap_load(void) {if (c.count == 2 && [c[0] isEqual:@"game"]) st_game = c[1]; else if (c.count == 2 && [c[0] isEqual:@"inputs"]) st_inputs = c[1];}if (!st_inputs) MLOG("[RED] shader library %s has no stamp (inputs.tsv): no full dmsh_build.py run made it as it is, so c1_full.tsv and cb_extent.tsv are not taken", g_msl_dir.UTF8String);- else if (st_game && ![st_game isEqual:@DM_GAME_ID]) MLOG("[RED] shader library %s was built for game %s, not " DM_GAME_ID, g_msl_dir.UTF8String, st_game.UTF8String);+ else if (st_game && ![st_game isEqual:@(dm_profile()->id)]) MLOG("[RED] shader library %s was built for game %s, not %s", g_msl_dir.UTF8String, st_game.UTF8String, dm_profile()->id);else MLOG("shader library stamp: game %s, inputs %s", st_game.UTF8String, st_inputs.UTF8String);NSString *cp = [[path stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"c1_full.tsv"]; // Same directory as the mapping table (Mac: dm/games/<id>; iOS: dm/ inside the App, copied along by build_ipa.sh)NSString *ct = cp ? [NSString stringWithContentsOfFile:cp encoding:NSUTF8StringEncoding error:nil] : nil;@@ -3516,7 +3516,7 @@ static NvShader *shader_load(NSString *pc, int stage, int layer) {if (stage == 0 && [j[@"layer_from"] isKindOfClass:[NSDictionary class]]) { o->lay_loc = [j[@"layer_from"][@"loc"] intValue]; o->lay_comp = [[j[@"layer_from"][@"comp"] description] UTF8String][0]; }char err[160];if (nvn_refl_from_json(j, &o->rf, err, sizeof err)) { MLOG("[RED] shader %s reflection conversion failed: %s", pc.UTF8String, err); return nil; }- if (o->rf.dyn && !DM_GAME_TEX_DYN_SLOTS) { // dynamic texture handles (TEXD / SAMPD) only where the profile says the game picks them from c2's tables, as before otherwise+ if (o->rf.dyn && !dm_profile()->tex_dyn_slots) { // dynamic texture handles (TEXD / SAMPD) only where the profile says the game picks them from c2's tables, as before otherwise// (rf.c1 is freed by dealloc when o goes: freeing it here too was a double free, which aborted FINAL FANTASY RESONANCE at its first such shader)MLOG("[RED] shader %s reflection conversion failed: a texture handle the translator could not trace to one slot (profile key tex_dyn_slots off)", pc.UTF8String); return nil; }if (rt_range_on()) o->range_ro=rt_range_bindings_ro(j);@@ -4514,7 +4514,7 @@ typedef struct { uint64_t ibuf; int32_t count, itype; } ir_key;typedef struct { uint32_t mn, mx; uint64_t stamp, seen, lo, n; const void *span; int gpuw; } ir_ent; // gpuw: a GPU write was queued on the indices: never trusted againstatic nvn_hmap g_ir = {.klen = sizeof(ir_key)};static uint64_t g_vc_rgn[VC_RGN / 64], g_vc_stat, g_vc_conv, g_vc_whole, g_vc_checks, g_vc_bad; // g_vc_rgn: 1 MB regions holding a kept index range (hashed); g_vc_conv / g_vc_whole: vertices converted / in the bound ranges-static int vc_on(void) { static int v = -1; if (v < 0) { const char *e = getenv("DM_NVN_VCONV_RANGE"); v = e && *e ? atoi(e) != 0 : DM_GAME_VCONV_RANGE; MLOG("vertex conversion of the draw's vertices only: %s", v ? "on" : "off"); } return v; }+static int vc_on(void) { static int v = -1; if (v < 0) { const char *e = getenv("DM_NVN_VCONV_RANGE"); v = e && *e ? atoi(e) != 0 : dm_profile()->vconv_range; MLOG("vertex conversion of the draw's vertices only: %s", v ? "on" : "off"); } return v; }static int vc_check(void) { static int v = -1; if (v < 0) { const char *e = getenv("DM_NVN_VCONV_CHECK"); v = e && *e && atoi(e); } return v; }static inline uint32_t vc_rgn(uint64_t r) { return (uint32_t)((r * 0x9E3779B97F4A7C15ull) >> 48) & (VC_RGN - 1); }static void vc_rgn_mark(uint64_t lo, uint64_t n) { for (uint64_t r = lo >> 20; r <= (lo + n - 1) >> 20; r++) { uint32_t b = vc_rgn(r); g_vc_rgn[b >> 6] |= 1ull << (b & 63); } }@@ -4796,7 +4796,7 @@ static int pso4_on(void) {if (v < 0) {const char *e = getenv("DM_PSO_MTL4");#if TARGET_OS_IPHONE- v = e ? !strcmp(e, "1") : DM_GAME_PSO_MTL4; // the profile's pso_mtl4+ v = e ? !strcmp(e, "1") : dm_profile()->pso_mtl4; // the profile's pso_mtl4if (!v) MLOG("render pipelines through the MTLDevice (iOS: DM_PSO_MTL4=1 or the profile key pso_mtl4 on turns on the Metal 4 bases, the pipeline archive and the hybrid pipelines)");#elsev = !(e && !strcmp(e, "0"));@@ -7841,7 +7841,7 @@ void ms_after(void) {// Breath of the Wild has over a thousand draws a frame sampling the G-buffer of their own pass (frame time 16.6 -> 36.6 ms) and Mario Wonder's submit time went 1.4 -> 4.0 ms, so only shaders seen to break are listedstatic char g_fb_keys[16][20]; static int g_fb_nk = -1, g_fb_all;static int fb_want(const char *key) {- if (g_fb_nk < 0) { g_fb_nk = 0; const char *e = getenv("DM_NVN_FB_SNAP"), *src = e && *e ? e : DM_GAME_FEEDBACK_SNAP;+ if (g_fb_nk < 0) { g_fb_nk = 0; const char *e = getenv("DM_NVN_FB_SNAP"), *src = e && *e ? e : dm_profile()->feedback_snap;if (!strcmp(src, "all")) g_fb_all = 1;else if (strcmp(src, "0")) for (const char *q = src; *q && g_fb_nk < 16;) { size_t n = strcspn(q, ", "); if (n) { if (n > 16) n = 16; memcpy(g_fb_keys[g_fb_nk], q, n); g_fb_keys[g_fb_nk++][n] = 0; } q += n; q += strspn(q, ", "); }if (g_fb_all || g_fb_nk) MLOG("same-pass feedback sampling snapshot: %s%s", g_fb_all ? "all fragment shaders" : src, e && *e ? " (DM_NVN_FB_SNAP)" : " (profile key feedback_snap)"); }@@ -8896,7 +8896,7 @@ void mtl_read_texels(const tex_t *t, unsigned level, unsigned layer0, const NVNc// textures from the CPU, reads them back with ReadTexels on its own thread before any draw uses them, and copies the blocks into its 5120x5120 roughness atlas. Read from the// never-uploaded host texture they were zeros, the atlas stayed empty, and the opening cave's stone blocks got roughness 0 and no torch lightint nvn_ft_written(const tex_t *);- if ((t->has_layout || tex_cpu_written(t->serial) || (DM_GAME_TEX_DIRTY_UPLOAD && nvn_ft_written(t))) && t->mem) {+ if ((t->has_layout || tex_cpu_written(t->serial) || (dm_profile()->tex_dirty_upload && nvn_ft_written(t))) && t->mem) {uint32_t lw = MAX(t->d.width >> level, 1u), lh = MAX(t->d.height >> level, 1u), lz = is3d ? MAX(t->d.depth >> level, 1u) : 1;size_t lp = (size_t)((lw + bw - 1) / bw) * bpb, lr = (lh + bh - 1) / bh;uint8_t *lin = malloc(lp * lr * lz);@@ -9424,7 +9424,7 @@ void mtl_exec(const uint8_t *p) {PD("Y signal_event cmd=%p dst=%p mode=%u value=%u", p, val, m, v); mtl_sub_event(val, m, v); break; }case OP_REPORT_COUNTER: { uint64_t t, ad; memcpy(&t, a, 8); memcpy(&ad, (const uint8_t *)a + 8, 8); g_cnt_report[t & 31]++;PD("Q report type=%llu cmd=%p dst=%#llx", (unsigned long long)t, p, (unsigned long long)ad);- if (DM_GAME_RENDER_COND) rc_note(ad, t == 0 || t == 0x10 ? 1 : 2);+ if (dm_profile()->render_cond) rc_note(ad, t == 0 || t == 0x10 ? 1 : 2);if (t == NVN_COUNTER_TYPE_SAMPLES_PASSED) { post((post_op){3, NULL, 0, 0, ad, (uint32_t)t, vis_snapshot()}); g_vis_cur = -1; }else mtl_sub_counter(ad, (uint32_t)t);break; }@@ -10449,7 +10449,7 @@ static int g_snap_n = 2;int mtl_snap_on(void) {static int v = -1; if (v >= 0) return v;const char *e = getenv("DM_PRESENT_SNAP");- int n = e ? atoi(e) : DM_GAME_PRESENT_SNAP ? 2 : 0; // the profile's present_snap (a ring of 2)+ int n = e ? atoi(e) : dm_profile()->present_snap ? 2 : 0; // the profile's present_snap (a ring of 2)v = n > 0; g_snap_n = n < 2 ? 2 : n > SNAP_MAX ? SNAP_MAX : n;if (v) MLOG("present snapshots (DM_PRESENT_SNAP=%d): each present is copied into a ring of %d host textures and the game's texture is free at once", n, g_snap_n);return v;diff --git a/dm/host/dm.h b/dm/host/dm.hindex 4afbf96f..e351daa5 100644--- a/dm/host/dm.h+++ b/dm/host/dm.h@@ -5,7 +5,8 @@#include <stdio.h>#include <stdlib.h>#include <string.h>-#include "game_profile.h" // constants of the current game profile (generated from dm/games/<id>/game.tsv, chosen by the Makefile's GAME)+#include "game_profile.h" // the compiled profile: fallback values for hle_profile.h (generated from dm/games/<id>/game.tsv)+#include "hle_profile.h" // the runtime profile: DM_PROFILE / DM_PROF_* override the compiled constants (one IPA, many games)#define MAX_MOD 128 // the profile's modules (up to 8) and the NROs a game loads at run time (Super Smash Bros. Ultimate: 98)#define LOG(...) do { fprintf(stderr, "[dm] " __VA_ARGS__); fputc('\n', stderr); } while (0)diff --git a/dm/host/front_mac.m b/dm/host/front_mac.mindex f83f2dff..68541d49 100644--- a/dm/host/front_mac.m+++ b/dm/host/front_mac.m@@ -315,7 +315,7 @@ void front_run(void (*guest)(void)) {NSWindow *win = [[NSWindow alloc] initWithContentRect:rstyleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskResizablebacking:NSBackingStoreBuffered defer:NO];- win.title = @DM_GAME_NAME; // the game profile's name (game name label)+ win.title = @(dm_profile()->name); // the game profile's name (game name label)// Fullscreen: without FullScreenPrimary the green button only zooms the window. The present path already scales// the game picture to fit the drawable with black bars around it, so fullscreen keeps the game's aspect ratio.win.collectionBehavior = NSWindowCollectionBehaviorFullScreenPrimary;@@ -345,7 +345,7 @@ void front_run(void (*guest)(void)) {// Main menu: AppKit runs ⌘ shortcuts only through menu items, so ⌘Q quits and ⌃⌘F toggles fullscreen from here (AppKit shows the item as Globe-F and keeps ⌃⌘F as a hidden twin)NSMenu *bar = [NSMenu new], *app = [NSMenu new], *wm = [[NSMenu alloc] initWithTitle:@"Window"];[[bar addItemWithTitle:@"" action:nil keyEquivalent:@""] setSubmenu:app];- [app addItemWithTitle:@"Quit " DM_GAME_NAME action:@selector(terminate:) keyEquivalent:@"q"];+ [app addItemWithTitle:[NSString stringWithFormat:@"Quit %s", dm_profile()->name] action:@selector(terminate:) keyEquivalent:@"q"];[[bar addItemWithTitle:@"Window" action:nil keyEquivalent:@""] setSubmenu:wm];[wm addItemWithTitle:@"Enter Full Screen" action:@selector(toggleFullScreen:) keyEquivalent:@"f"].keyEquivalentModifierMask = NSEventModifierFlagControl | NSEventModifierFlagCommand;NSApp.mainMenu = bar;diff --git a/dm/host/hle_fpslock.c b/dm/host/hle_fpslock.cindex be3b6224..23cc22d2 100644--- a/dm/host/hle_fpslock.c+++ b/dm/host/hle_fpslock.c@@ -71,7 +71,7 @@ void dm_fps_lock_tick(void) {for (int i = 0; i < g_nmod; i++) if (!strcmp(g_mod[i].name, "main"))for (int k = 0; k < NLOCKS; k++) if (!strcmp(g_mod[i].build_id, k_locks[k].build)) { rows[nrow++] = k; base = g_mod[i].base; }if (!nrow) return;- const char *e = getenv("DM_FPS_TARGET"); int t = e ? atoi(e) : DM_GAME_FPS_TARGET; src = e ? "DM_FPS_TARGET" : "game profile fps_target";+ const char *e = getenv("DM_FPS_TARGET"); int t = e ? atoi(e) : dm_profile()->fps_target; src = e ? "DM_FPS_TARGET" : "game profile fps_target";if (t != 0 && t != 30 && t != 60) { LOG("[RED] DM_FPS_TARGET=%s: must be 0, 30 or 60; leaving the game's frame limit", e); t = 0; }if (!t) { for (int r = 0; r < nrow; r++) LOG("main: %s left as the game sets it (%s)", k_locks[rows[r]].what, src); return; }target = t; state = 0;diff --git a/dm/host/hle_fs.c b/dm/host/hle_fs.cindex 2b8e0f8b..2285c439 100644--- a/dm/host/hle_fs.c+++ b/dm/host/hle_fs.c@@ -535,7 +535,7 @@ HLE_FORCE("_ZN2nn2fs14ExtendSaveDataERKNS_7account3UidEll", "fsp-srv; extend savHLE_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 mountedHLE_FORCE("_ZN2nn2fs18IsSaveDataExistingENS_13ApplicationIdERKNS_7account3UidE", "fsp-srv; only this game's own save data exists", int, h_fs_SaveExisting, uint64_t app, const void *uid) {- (void)uid; LOG("fs asks whether save data exists: program %016llx → %s", (unsigned long long)app, app == DM_GAME_PROGRAM_ID ? "this game, yes" : "another program, no"); return app == DM_GAME_PROGRAM_ID;+ (void)uid; LOG("fs asks whether save data exists: program %016llx → %s", (unsigned long long)app, app == dm_profile()->program_id ? "this game, yes" : "another program, no"); return app == dm_profile()->program_id;}HLE_FORCE("_ZN2nn2fs21MountSaveDataReadOnlyEPKcNS_13ApplicationIdERKNS_7account3UidE", "fsp-srv; another program's save data: none", Result, h_fs_MountSaveRO, const char *name, uint64_t app, const void *uid) {(void)uid; LOG("[RED] fs read-only mount of another program's save data %s: program %016llx, the host has none", name, (unsigned long long)app); return 0x7d402u; // fs ResultTargetNotFounddiff --git a/dm/host/hle_oe.c b/dm/host/hle_oe.cindex 300413a2..d62b07aa 100644--- a/dm/host/hle_oe.c+++ b/dm/host/hle_oe.c@@ -8,7 +8,7 @@static _Atomic int g_opmode = -1;int dm_opmode(void) {int m = g_opmode;- if (m < 0) { const char *e = getenv("DM_OPMODE"); int v = e ? atoi(e) : DM_GAME_OPMODE; int exp = -1; atomic_compare_exchange_strong(&g_opmode, &exp, v); m = g_opmode; }+ if (m < 0) { const char *e = getenv("DM_OPMODE"); int v = e ? atoi(e) : dm_profile()->opmode; int exp = -1; atomic_compare_exchange_strong(&g_opmode, &exp, v); m = g_opmode; }return m;}// ---------- System notification queue (AppletMessage): front end state changes → fetched by the game every frame with TryPopNotificationMessage ----------@@ -120,7 +120,7 @@ HLE_FORCE("_ZN2nn2oe16GetOperationModeEv", "operation mode query; a fixed value// Profile perf_mode boost: Boost whatever the operation mode, a combination a Switch 1 never reports, so a profile choice and not a default. Rhythm Heaven Groove keeps one flag per mode// (main+0xa764 / main+0xa784): console means a TV, which gets a latency calibration (main+0x20d0, scene script main+0x4c0820), and Boost alone picks its 1920x1080 draw size// (table main+0xada6d0, else 1280x720). Handheld with Boost: no TV calibration on a phone, full-size drawing-HLE_FORCE("_ZN2nn2oe18GetPerformanceModeEv", "performance mode query; same as the operation mode (profile perf_mode boost: Boost)", int, h_oe_GetPerfMode, void) { return DM_GAME_PERF_BOOST ? 1 : opmode(); }+HLE_FORCE("_ZN2nn2oe18GetPerformanceModeEv", "performance mode query; same as the operation mode (profile perf_mode boost: Boost)", int, h_oe_GetPerfMode, void) { return dm_profile()->perf_boost ? 1 : opmode(); }// SDK 11 calls of Monster Hunter Rise: the CPU overclock query reads an apm session the host never opened (null read in sdk+0x35258 at the start of nnMain, main+0x6bc8650);// the default display resolution is the TV's (1080p docked) or the panel's (720p handheld) and only changes with the operation mode// Taiko Risshiden V DX (SDK 12.3.3) turns it on in nnMain (main+0x2e1e4c): the setter goes through the same apm session (null read at sdk+0x362b8). The host does not scale clocks;diff --git a/dm/host/hle_os.c b/dm/host/hle_os.cindex 2d1afec7..14b3ee58 100644--- a/dm/host/hle_os.c+++ b/dm/host/hle_os.c@@ -120,7 +120,7 @@ HLE_FORCE("_ZN2nn6crypto36GenerateCryptographicallyRandomBytesEPvm", "csrng serv// The profile's game_env (KEY=VALUE, separated by spaces; DM_GAME_ENV overrides it, also from Documents/env.txt) answers getenv for those names; any other name goes to the SDK's own getenvstatic const char **g_env_kv; // "KEY=VALUE" strings, NULL-terminatedstatic void game_env_init(void) {- const char *e = getenv("DM_GAME_ENV"); if (!e) e = DM_GAME_ENV;+ const char *e = getenv("DM_GAME_ENV"); if (!e) e = dm_profile()->genv;int n = 0; for (const char *p = e; *p; p++) n += *p == '=';if (!(g_env_kv = calloc((size_t)n + 1, sizeof *g_env_kv))) die("game_env allocation failed");char *s = strdup(e); int k = 0;@@ -152,7 +152,7 @@ static void sa_init(void) {g_sa_alloc = ms ? module_sym(ms, "_ZN2nn3mem17StandardAllocator8AllocateEm") : NULL;g_sa_alloc_al = ms ? module_sym(ms, "_ZN2nn3mem17StandardAllocator8AllocateEmm") : NULL;if (!g_sa_alloc || !g_sa_alloc_al) die("StandardAllocator::Allocate not found in the SDK");- g_sa_big_align = DM_GAME_ALLOC_BIG_ALIGN;+ g_sa_big_align = dm_profile()->alloc_big_align;if (g_sa_big_align) LOG("StandardAllocator::Allocate: allocations ≥ 64 KB are 64 KB aligned (game profile alloc_big_align: memory pool storage, see hle_os.c)");}HLE_FORCE("_ZN2nn3mem17StandardAllocator8AllocateEm", "passed straight to the SDK; with the profile's alloc_big_align (13 Sentinels, Unicorn Overlord) allocations ≥ 64 KB are 64 KB aligned (memory pool start)", void *, h_mem_SAAllocate, void *self, size_t size) {diff --git a/dm/host/hle_profile.c b/dm/host/hle_profile.cnew file mode 100644index 00000000..03ce4268--- /dev/null+++ b/dm/host/hle_profile.c@@ -0,0 +1,242 @@+// Runtime game profile: see hle_profile.h. One IPA for every game reads its layout, switches and tables from DM_PROFILE+// instead of having them compiled in (game_profile.h stays the fallback, so a build without DM_PROFILE is unchanged).+#include "dm.h"+#include "hle_profile.h"+#include <ctype.h>++static struct dm_profile P;+static int g_loaded;++static void copy_str(char *dst, size_t n, const char *src) {+ if (!n) return;+ size_t i = 0;+ for (; src && src[i] && i + 1 < n; i++) dst[i] = src[i];+ dst[i] = 0;+}+static int truthy(const char *v) { // "1", "on", "yes", "true" (case-insensitive) = on; "0", "off", "no", "false", "" = off+ if (!v) return 0;+ return !(v[0] == '0' || !strcasecmp(v, "off") || !strcasecmp(v, "no") || !strcasecmp(v, "false") || !v[0]);+}+static uint64_t num(const char *v, uint64_t dflt) {+ if (!v || !*v) return dflt;+ char *e = NULL;+ uint64_t r = strtoull(v, &e, 0);+ return e && e != v ? r : dflt;+}++// ---- defaults: exactly what game_profile.h (generated from game.tsv) compiles in ----+// A profile header may be partial (the unit tests' synthetic one carries only the memory constants), so every group is guarded:+// a missing macro means "the game does not set this key", which is also what game.py leaves out when game.tsv has no such row.+#ifndef DM_GAME_ID+#define DM_GAME_ID ""+#define DM_GAME_NAME ""+#define DM_GAME_ROMFS_MARKER ""+#define DM_GAME_MODULES {0}+#define DM_GAME_NMOD 0+#endif+#ifndef DM_GAME_PROGRAM_ID+#define DM_GAME_PROGRAM_ID 0ull+#endif+#ifndef DM_GAME_MEM_RESERVE+#define DM_GAME_MEM_RESERVE 0ull+#define DM_GAME_MEM_ALIAS 0ull+#define DM_GAME_MEM_STACK 0ull+#define DM_GAME_APP_POOL 0ull+#define DM_GAME_MEM_USED 0x4000000ull+#define DM_GAME_SYS_RESOURCE 0ull+#define DM_GAME_MEM_MAP_LIMIT 0+#endif+#ifndef DM_GAME_DISPLAY_VERSIONS+#define DM_GAME_DISPLAY_VERSIONS {0, 0}+#endif+#ifndef DM_GAME_PRESENT_DISPLAY+#define DM_GAME_PRESENT_DISPLAY 0+#define DM_GAME_CORE_PREEMPT 0+#define DM_GAME_ALLOC_BIG_ALIGN 0+#define DM_GAME_FPS_TARGET 0+#define DM_GAME_FPS_HOLD 1+#define DM_GAME_PRESENT_SNAP 0+#define DM_GAME_PSO_MTL4 0+#define DM_GAME_PAD_LAYOUT 0+#define DM_GAME_OPMODE 1+#define DM_GAME_PERF_BOOST 0+#define DM_GAME_FEEDBACK_SNAP ""+#define DM_GAME_TEX_FLUSH_UPLOAD 0+#define DM_GAME_RENDER_COND 0+#define DM_GAME_TEX_DIRTY_UPLOAD 0+#define DM_GAME_TEX_DYN_SLOTS 0+#define DM_GAME_GPU_TS_SEGMENT 0+#define DM_GAME_VCONV_RANGE 0+#define DM_GAME_ARGS ""+#define DM_GAME_ENV ""+#endif+static void defaults(void) {+ memset(&P, 0, sizeof P);+ copy_str(P.id, sizeof P.id, DM_GAME_ID);+ copy_str(P.name, sizeof P.name, DM_GAME_NAME);+ copy_str(P.romfs_marker, sizeof P.romfs_marker, DM_GAME_ROMFS_MARKER);+ P.program_id = DM_GAME_PROGRAM_ID;+ { static const char *m[] = DM_GAME_MODULES; int n = DM_GAME_NMOD; if (n > DM_PROF_MAX_MOD) n = DM_PROF_MAX_MOD;+ for (int i = 0; i < n; i++) { copy_str(P.modbuf[i], sizeof P.modbuf[i], m[i]); P.modules[i] = P.modbuf[i]; } P.nmod = n; }+ P.mem_reserve = DM_GAME_MEM_RESERVE; P.mem_alias = DM_GAME_MEM_ALIAS; P.mem_stack = DM_GAME_MEM_STACK;+ P.app_pool = DM_GAME_APP_POOL; P.mem_used = DM_GAME_MEM_USED; P.sys_resource = DM_GAME_SYS_RESOURCE;+ P.mem_map_limit = DM_GAME_MEM_MAP_LIMIT;+ { static const struct { const char *build, *ver; } k[] = {DM_GAME_DISPLAY_VERSIONS};+ int n = (int)(sizeof k / sizeof *k); if (n > DM_PROF_MAX_VER) n = DM_PROF_MAX_VER;+ for (int i = 0; i < n; i++) {+ if (!k[i].build || !k[i].ver) continue; // the placeholder a partial header falls back to+ copy_str(P.ver[P.nver].build, sizeof P.ver[0].build, k[i].build); copy_str(P.ver[P.nver].ver, sizeof P.ver[0].ver, k[i].ver); P.nver++;+ } }+ P.present_display = DM_GAME_PRESENT_DISPLAY; P.core_preempt = DM_GAME_CORE_PREEMPT; P.alloc_big_align = DM_GAME_ALLOC_BIG_ALIGN;+ P.fps_target = DM_GAME_FPS_TARGET; P.fps_hold = DM_GAME_FPS_HOLD; P.present_snap = DM_GAME_PRESENT_SNAP; P.pso_mtl4 = DM_GAME_PSO_MTL4;+#ifdef DM_GAME_SHARED_FONT_TTF+ P.shared_font_ttf = DM_GAME_SHARED_FONT_TTF;+#else+ P.shared_font_ttf = -1;+#endif+ P.pad_layout = DM_GAME_PAD_LAYOUT; P.opmode = DM_GAME_OPMODE; P.perf_boost = DM_GAME_PERF_BOOST;+ copy_str(P.feedback_snap, sizeof P.feedback_snap, DM_GAME_FEEDBACK_SNAP);+ P.tex_flush_upload = DM_GAME_TEX_FLUSH_UPLOAD; P.render_cond = DM_GAME_RENDER_COND; P.tex_dirty_upload = DM_GAME_TEX_DIRTY_UPLOAD;+ P.tex_dyn_slots = DM_GAME_TEX_DYN_SLOTS; P.gpu_ts_segment = DM_GAME_GPU_TS_SEGMENT; P.vconv_range = DM_GAME_VCONV_RANGE;+#ifdef DM_GAME_NVN_API_MAJOR+ P.nvn_api_major = DM_GAME_NVN_API_MAJOR; P.nvn_api_minor = DM_GAME_NVN_API_MINOR;+#else+ P.nvn_api_major = 0; P.nvn_api_minor = 0;+#endif+ copy_str(P.args, sizeof P.args, DM_GAME_ARGS);+ copy_str(P.genv, sizeof P.genv, DM_GAME_ENV);+ copy_str(P.source, sizeof P.source, "compiled game_profile.h");+}++// ---- one key/value: the same key names as game.tsv (so `game.py` can write the file), plus the header's own names ----+static void set_kv(const char *k, const char *v) {+ if (!strcmp(k, "title_id") || !strcmp(k, "id")) copy_str(P.id, sizeof P.id, v);+ else if (!strcmp(k, "name")) copy_str(P.name, sizeof P.name, v);+ else if (!strcmp(k, "romfs_marker")) copy_str(P.romfs_marker, sizeof P.romfs_marker, v);+ else if (!strcmp(k, "program_id")) P.program_id = num(v, P.program_id);+ else if (!strcmp(k, "modules")) {+ P.nmod = 0; const char *p = v;+ while (*p && P.nmod < DM_PROF_MAX_MOD) {+ while (*p == ' ' || *p == '\t' || *p == ',') p++;+ if (!*p) break;+ size_t n = strcspn(p, " \t,");+ if (n >= sizeof P.modbuf[0]) n = sizeof P.modbuf[0] - 1;+ memcpy(P.modbuf[P.nmod], p, n); P.modbuf[P.nmod][n] = 0; P.modules[P.nmod] = P.modbuf[P.nmod];+ P.nmod++; p += n;+ }+ }+ else if (!strcmp(k, "mem_reserve")) P.mem_reserve = num(v, P.mem_reserve);+ else if (!strcmp(k, "mem_alias")) P.mem_alias = num(v, P.mem_alias);+ else if (!strcmp(k, "mem_stack")) P.mem_stack = num(v, P.mem_stack);+ else if (!strcmp(k, "app_pool")) P.app_pool = num(v, P.app_pool);+ else if (!strcmp(k, "mem_used")) P.mem_used = num(v, P.mem_used);+ else if (!strcmp(k, "sys_resource")) P.sys_resource = num(v, P.sys_resource);+ else if (!strcmp(k, "mem_map_limit")) P.mem_map_limit = truthy(v);+ else if (!strcmp(k, "display_version")) { // build<TAB>version; one row per build (game.tsv's build rows give the same)+ const char *t = strchr(v, '\t'); if (t && P.nver < DM_PROF_MAX_VER) {+ size_t n = (size_t)(t - v); if (n >= sizeof P.ver[0].build) n = sizeof P.ver[0].build - 1;+ memcpy(P.ver[P.nver].build, v, n); P.ver[P.nver].build[n] = 0;+ copy_str(P.ver[P.nver].ver, sizeof P.ver[0].ver, t + 1); P.nver++;+ }+ }+ // Some keys have a word form (game.tsv: display / full / console) and a number form (the header: 1 / 0): both are accepted,+ // because game.py writes the header's spelling and a hand-written profile may use either. Numbers are unambiguous: 0/1 for+ // Booleans, 0/1/2 for pad_layout (simple / full / touch) and 1/0 for the console/handheld mode.+ else if (!strcmp(k, "present_interval")) P.present_display = strchr("dD1", *v) != NULL && (!strcmp(v, "display") || isdigit((unsigned char)*v));+ else if (!strcmp(k, "core_preempt")) P.core_preempt = truthy(v);+ else if (!strcmp(k, "alloc_big_align")) P.alloc_big_align = truthy(v);+ else if (!strcmp(k, "fps_target")) P.fps_target = (int)num(v, (uint64_t)P.fps_target);+ else if (!strcmp(k, "fps_hold")) P.fps_hold = truthy(v);+ else if (!strcmp(k, "present_snap")) P.present_snap = truthy(v);+ else if (!strcmp(k, "pso_mtl4")) P.pso_mtl4 = truthy(v);+ else if (!strcmp(k, "shared_font")) P.shared_font_ttf = !strcmp(v, "ttf") || !strcmp(v, "1");+ else if (!strcmp(k, "pad_layout")) P.pad_layout = !strcmp(v, "full") || !strcmp(v, "1") ? 1 : !strcmp(v, "touch") || !strcmp(v, "2") ? 2 : 0;+ else if (!strcmp(k, "op_mode")) P.opmode = !strcmp(v, "console") ? 1 : !strcmp(v, "handheld") ? 0 : truthy(v);+ else if (!strcmp(k, "perf_mode")) P.perf_boost = !strcmp(v, "boost") ? 1 : !strcmp(v, "follow") ? 0 : truthy(v);+ else if (!strcmp(k, "feedback_snap")) copy_str(P.feedback_snap, sizeof P.feedback_snap, v);+ else if (!strcmp(k, "tex_flush_upload")) P.tex_flush_upload = truthy(v);+ else if (!strcmp(k, "render_cond")) P.render_cond = truthy(v);+ else if (!strcmp(k, "tex_dirty_upload")) P.tex_dirty_upload = truthy(v);+ else if (!strcmp(k, "tex_dyn_slots")) P.tex_dyn_slots = truthy(v);+ else if (!strcmp(k, "gpu_timestamps")) P.gpu_ts_segment = !strcmp(v, "segment") || !strcmp(v, "1");+ else if (!strcmp(k, "vconv_range")) P.vconv_range = truthy(v);+ else if (!strcmp(k, "device_api")) { char *e; P.nvn_api_major = (int)strtol(v, &e, 10); if (e && *e == '.') P.nvn_api_minor = atoi(e + 1); }+ else if (!strcmp(k, "game_args")) copy_str(P.args, sizeof P.args, v);+ else if (!strcmp(k, "game_env")) copy_str(P.genv, sizeof P.genv, v);+ // any other key (ipa, zip_store, shader_*, build, package, ...) is not a host constant: ignored+}++// The file: KEY<TAB>VALUE (game.tsv's form) or KEY VALUE, # starts a comment; blank lines are skipped.+static void read_file(const char *path) {+ FILE *f = fopen(path, "r");+ if (!f) { LOG("[RED] DM_PROFILE %s cannot be read; keeping the compiled profile", path); return; }+ char line[4096];+ int rows = 0;+ while (fgets(line, sizeof line, f)) {+ char *s = line; while (*s == ' ' || *s == '\t') s++;+ size_t L = strlen(s); while (L && (s[L-1] == '\n' || s[L-1] == '\r')) s[--L] = 0;+ if (!*s || *s == '#') continue;+ char *sep = strpbrk(s, "\t ");+ if (!sep) continue;+ *sep = 0;+ char *v = sep + 1; while (*v == '\t' || *v == ' ') v++;+ if (!strcmp(s, "build")) { // build<TAB>version<TAB>display<TAB>main=<build id>...: one display-version row+ char *p = v, *cols[4] = {0}; int nc = 0;+ for (char *t = strtok(p, "\t"); t && nc < 4; t = strtok(NULL, "\t")) cols[nc++] = t;+ if (nc >= 2) { char buf[256]; snprintf(buf, sizeof buf, "%s\t%s", cols[0], cols[1]); set_kv("display_version", buf); }+ continue;+ }+ set_kv(s, v); rows++;+ }+ fclose(f);+ LOG("game profile %s: %d rows", path, rows);+}++// Environment: DM_PROF_<KEY> with the game.tsv key upper-cased (DM_PROF_MEM_RESERVE=0x140000000).+static void read_env(void) {+ static const char *keys[] = {"TITLE_ID","NAME","ROMFS_MARKER","PROGRAM_ID","MODULES","MEM_RESERVE","MEM_ALIAS","MEM_STACK","APP_POOL",+ "MEM_USED","SYS_RESOURCE","MEM_MAP_LIMIT","PRESENT_INTERVAL","CORE_PREEMPT","ALLOC_BIG_ALIGN","FPS_TARGET","FPS_HOLD","PRESENT_SNAP",+ "PSO_MTL4","SHARED_FONT","PAD_LAYOUT","OP_MODE","PERF_MODE","FEEDBACK_SNAP","TEX_FLUSH_UPLOAD","RENDER_COND","TEX_DIRTY_UPLOAD",+ "TEX_DYN_SLOTS","GPU_TIMESTAMPS","VCONV_RANGE","DEVICE_API","GAME_ARGS","GAME_ENV", NULL};+ char k[64], name[96];+ for (int i = 0; keys[i]; i++) {+ snprintf(k, sizeof k, "%s", keys[i]);+ for (char *p = k; *p; p++) *p = (char)tolower((unsigned char)*p);+ snprintf(name, sizeof name, "DM_PROF_%s", keys[i]);+ const char *v = getenv(name);+ if (v) set_kv(k, v);+ }+}++static void load(void) {+ defaults();+ const char *path = getenv("DM_PROFILE");+ if (path && *path) { copy_str(P.source, sizeof P.source, path); read_file(path); }+ read_env(); // DM_PROF_* overrides apply on top of the file or of the compiled profile+ if (P.nmod <= 0) { // a profile file that names no modules: the compiled list, which is the one the executable embeds+ static const char *m[] = DM_GAME_MODULES; int n = DM_GAME_NMOD; if (n > DM_PROF_MAX_MOD) n = DM_PROF_MAX_MOD;+ for (int i = 0; i < n; i++) { copy_str(P.modbuf[i], sizeof P.modbuf[i], m[i]); P.modules[i] = P.modbuf[i]; } P.nmod = n;+ }+ g_loaded = 1;+}++const struct dm_profile *dm_profile(void) {+ if (!g_loaded) load();+ return &P;+}++void dm_profile_log(void) {+ const struct dm_profile *p = dm_profile();+ LOG("game profile: %s (%s) from %s", p->id, p->name, p->source);+ LOG(" modules %d%s%s%s program %016llx reserve %#llx alias %#llx stack %#llx pool %#llx used %#llx sysres %#llx map_limit %d",+ p->nmod, p->nmod > 0 ? ":" : "", p->nmod > 0 ? p->modules[0] : "", p->nmod > 1 ? " ..." : "",+ (unsigned long long)p->program_id, (unsigned long long)p->mem_reserve, (unsigned long long)p->mem_alias,+ (unsigned long long)p->mem_stack, (unsigned long long)p->app_pool, (unsigned long long)p->mem_used,+ (unsigned long long)p->sys_resource, p->mem_map_limit);+ LOG(" switches present_display %d core_preempt %d big_align %d fps %d hold %d snap %d pso4 %d font_ttf %d pad %d opmode %d boost %d",+ p->present_display, p->core_preempt, p->alloc_big_align, p->fps_target, p->fps_hold, p->present_snap, p->pso_mtl4,+ p->shared_font_ttf, p->pad_layout, p->opmode, p->perf_boost);+ LOG(" graphics flush %d dirty %d rcond %d dynslots %d gputs %d vconv %d nvn_api %d.%d versions %d",+ p->tex_flush_upload, p->tex_dirty_upload, p->render_cond, p->tex_dyn_slots, p->gpu_ts_segment, p->vconv_range,+ p->nvn_api_major, p->nvn_api_minor, p->nver);+}diff --git a/dm/host/hle_profile.h b/dm/host/hle_profile.hnew file mode 100644index 00000000..a2febeb3--- /dev/null+++ b/dm/host/hle_profile.h@@ -0,0 +1,37 @@+// Runtime game profile: every constant the host used to take from game_profile.h at compile time, read once at start.+// Loading order: the compiled profile (game_profile.h, the macros) → the file DM_PROFILE names (the key/value form of a+// game profile, dm/games/game.py profile <id> <out.tsv>) → DM_PROF_<KEY> environment variables.+// The per-knob switches the host already reads (DM_FPS_TARGET, DM_OPMODE, DM_PRESENT_INTERVAL, DM_NVN_API, ...) still win over+// all of these: each site reads them after the profile.+// A build with no DM_PROFILE set behaves exactly as the compile-time profile did.+#pragma once+#include <stdint.h>++#define DM_PROF_MAX_MOD 8+#define DM_PROF_MAX_VER 64+#define DM_PROF_STR 128++struct dm_profile {+ char id[24]; // base game title ID, hex text+ char name[128];+ char romfs_marker[256];+ uint64_t program_id;+ char modbuf[DM_PROF_MAX_MOD][16];+ const char *modules[DM_PROF_MAX_MOD]; // point into modbuf+ int nmod;+ uint64_t mem_reserve, mem_alias, mem_stack, app_pool, mem_used, sys_resource;+ int mem_map_limit;+ struct { char build[40], ver[40]; } ver[DM_PROF_MAX_VER]; // display version by main build ID+ int nver;+ int present_display, core_preempt, alloc_big_align, fps_target, fps_hold, present_snap, pso_mtl4;+ int shared_font_ttf; // -1 = decide by the SDK version (hle_sdk16.c font_skip)+ int pad_layout, opmode, perf_boost;+ char feedback_snap[DM_PROF_STR];+ int tex_flush_upload, render_cond, tex_dirty_upload, tex_dyn_slots, gpu_ts_segment, vconv_range;+ int nvn_api_major, nvn_api_minor; // major 0 = decide by the SDK version (hle_nvn.c nvn_api)+ char args[512], genv[1024]; // game_args / game_env+ char source[512]; // DM_PROFILE, or "compiled defaults"+};++const struct dm_profile *dm_profile(void); // loaded once; never NULL+void dm_profile_log(void); // one line per differing value (called after loading)diff --git a/dm/host/hle_sdk16.c b/dm/host/hle_sdk16.cindex 74f25982..38b5aec7 100644--- a/dm/host/hle_sdk16.c+++ b/dm/host/hle_sdk16.c@@ -14,10 +14,10 @@HLE_FORCE("_ZN2nn2oe15SetCpuBoostModeENS0_12CpuBoostModeE", "CPU boost mode; the host does not scale clocks", void, h_oe_CpuBoost, int m) { (void)m; }// DisplayVersion = char[16] (the application's display version): the value from that version's control data (NACP), chosen by main's build ID (the game profile's build rows); unknown builds get 1.0.0HLE_FORCE("_ZN2nn2oe17GetDisplayVersionEPNS0_14DisplayVersionE", "display version (by the main build ID)", void, h_oe_DispVer, char *v) {- static const struct { const char *build, *ver; } k[] = {DM_GAME_DISPLAY_VERSIONS};+ const struct dm_profile *p = dm_profile(); // the profile's build → display version rows (hle_profile.h), per gameconst char *ver = "1.0.0";for (int i = 0; i < g_nmod; i++) if (!strcmp(g_mod[i].name, "main"))- for (unsigned j = 0; j < sizeof k / sizeof *k; j++) if (!strcmp(g_mod[i].build_id, k[j].build)) ver = k[j].ver;+ for (int j = 0; j < p->nver; j++) if (!strcmp(g_mod[i].build_id, p->ver[j].build)) ver = p->ver[j].ver;memset(v, 0, 16); strlcpy(v, ver, 16);}HLE_FORCE("_ZN2nn2oe24GetExpectedVolumeBalanceEPfS1_", "system / application volume balance; the host always reports 1:1", void, h_oe_GetVolBal, float *sys, float *app) { *sys = 1.0f; *app = 1.0f; }@@ -124,12 +124,12 @@ HLE_FORCE("_ZN2nn6fontll18ScalableFontEngine8LoadFontEPcPKvjj", "shared font BFTstatic size_t font_skip(void) {static int skip = -1;if (skip < 0) {-#ifdef DM_GAME_SHARED_FONT_TTF- skip = DM_GAME_SHARED_FONT_TTF ? 8 : 0; LOG("shared font: %s (game profile shared_font)", skip ? "the TTF itself" : "BFTTF header + TTF");-#else- int m = dm_sdk_major(), dec = dm_main_imports("_ZN2nn6fontll24ScalableFontEngineHelper6Decode"); skip = DM_SDK_OLD(m) || !dec ? 8 : 0;- LOG("shared font: %s (SDK %d, main %s ScalableFontEngineHelper::Decode)", skip ? "the TTF itself" : "BFTTF header + TTF", m, dec ? "imports" : "does not import");-#endif+ int ttf = dm_profile()->shared_font_ttf; // profile shared_font (bfttf / ttf); -1 = decide by the SDK version, as before+ if (ttf >= 0) { skip = ttf ? 8 : 0; LOG("shared font: %s (game profile shared_font)", skip ? "the TTF itself" : "BFTTF header + TTF"); }+ else {+ int m = dm_sdk_major(), dec = dm_main_imports("_ZN2nn6fontll24ScalableFontEngineHelper6Decode"); skip = DM_SDK_OLD(m) || !dec ? 8 : 0;+ LOG("shared font: %s (SDK %d, main %s ScalableFontEngineHelper::Decode)", skip ? "the TTF itself" : "BFTTF header + TTF", m, dec ? "imports" : "does not import");+ }}return (size_t)skip;}diff --git a/dm/host/hle_svc.c b/dm/host/hle_svc.cindex 2ba7f9fa..c15c00a3 100644--- a/dm/host/hle_svc.c+++ b/dm/host/hle_svc.c@@ -15,7 +15,10 @@// about 4.2 GB in total; on iOS without the "extended virtual addressing" entitlement a single reservation can be at most 6 GB// (read on a real device: 6 GB succeeds, 7 GB fails), so it cannot be made any wider --// with an 8 GB reservation, builds from developer accounts that cannot sign that entitlement (free accounts) would exit at this step.-#define RESERVE DM_GAME_MEM_RESERVE // SMBW: the heap needs only 1.47 GB, so the block stays at 5 GB (the total proven on a real device; a single 6 GB block can be reserved, but Metal etc. still need address space)+// The layout comes from the runtime game profile (hle_profile.h): DM_PROFILE's mem_reserve / mem_alias / mem_stack / app_pool /+// mem_used / sys_resource, else the compiled profile's values. All of them are read once, in mem_init_once().+#define RESERVE g_reserve+static uint64_t g_reserve; // the whole block (profile mem_reserve)static uint8_t *g_as; // ASLR region base = the whole blockstatic uint8_t *g_heap; static _Atomic size_t g_heap_cur; static size_t g_heap_cap;// The address range lies entirely within the currently opened (readable and writable) part of the guest heap: such reads need no kernel trap to check, memcpy directly (used where guest memory is read every tick, such as diag.c tk_rd)@@ -29,10 +32,12 @@ int dm_guest_as_contains(uintptr_t a) { uintptr_t b = (uintptr_t)g_as; return g_static void *alias_windows_thread(void *arg);static void mem_init_once(void) {+ const struct dm_profile *p = dm_profile();size_t pg = (size_t)getpagesize();- if (RESERVE < 0x10000000 || DM_GAME_MEM_ALIAS > RESERVE - 0x10000000 ||- DM_GAME_MEM_STACK > RESERVE - 0x10000000 - DM_GAME_MEM_ALIAS ||- ((RESERVE | DM_GAME_MEM_ALIAS | DM_GAME_MEM_STACK) & (pg - 1)))+ g_reserve = p->mem_reserve;+ if (RESERVE < 0x10000000 || p->mem_alias > RESERVE - 0x10000000 ||+ p->mem_stack > RESERVE - 0x10000000 - p->mem_alias ||+ ((RESERVE | p->mem_alias | p->mem_stack) & (pg - 1)))die("guest address-space profile has invalid native boundaries");g_as = mmap(NULL, RESERVE, PROT_NONE, MAP_PRIVATE | MAP_ANON, -1, 0);if (g_as == MAP_FAILED) die("reserve guest AS");@@ -42,8 +47,8 @@ static void mem_init_once(void) {// and resource loading then MapPhysicalMemory's into the alias region after the node area on demand. With a 1.25 GB alias region only about 256 MB was left there, and 3 MB-class layout archives (WipeCourseIn / WipeWarp)// got no address, were skipped, and crashed on a null pointer when used (main +0x373e04). So alias = node area + 1.75 GB + slack; the heap needs only 1.47 GB, and 2.625 GB is plenty.// The alias and stack sizes come from the game profile (mem_alias / mem_stack), the heap takes the rest; Mario: alias 0xB8000000, stack 0x10000000 → stack at +0xC8000000, heap at +0xD8000000- g_alias = g_as + 0x10000000; g_alias_cap = DM_GAME_MEM_ALIAS;- g_stack = g_alias + g_alias_cap; g_stack_cap = DM_GAME_MEM_STACK;+ g_alias = g_as + 0x10000000; g_alias_cap = p->mem_alias;+ g_stack = g_alias + g_alias_cap; g_stack_cap = p->mem_stack;g_heap = g_stack + g_stack_cap; g_heap_cap = RESERVE - (size_t)(g_heap - g_as);if (!(g_alias_bits = calloc((g_alias_cap >> 18) + 1, sizeof *g_alias_bits))) die("alias region page bitmap calloc");if (!(g_alias_exposed = calloc(g_alias_cap / pg / 64 + 1, sizeof *g_alias_exposed))) die("alias exposure bitmap calloc");@@ -60,7 +65,12 @@ static void mem_init(void) {// and hands the whole block to its own StandardAllocator (main+0x32137a0) -- so heap size = pool − image footprint, it has only as much as the host reports.// Previously 3 GB was reported here and SetHeapSize never failed: the heap was about 150 MB smaller than on the real device, at the run entry peak the main heap had only about 18 MB left, and under high local load a timing shift made a 128 KB request return null,// which the guest writes to without a null check (CRASH main+0x1b36138, re-verified after merge with inv_tap).-#define APP_POOL DM_GAME_APP_POOL // game profile app_pool (Mario 0xCD500000)+#define APP_POOL (dm_profile()->app_pool) // game profile app_pool (Mario 0xCD500000)+// The other memory constants the profile sets (hle_profile.h): read where they are used, so DM_PROFILE can change them per game.+#define MEM_USED (dm_profile()->mem_used) // used memory reported beside the heap (profile mem_used)+#define MEM_MAP_LIMIT (dm_profile()->mem_map_limit) // MapPhysicalMemory refused beyond the application pool+#define SYS_RESOURCE (dm_profile()->sys_resource) // the NPDM's system resource size (0 = no virtual address memory)+#define PROGRAM_ID (dm_profile()->program_id) // this game's program ID (save-data queries)static size_t image_bytes(void) { size_t n = 0; for (int i = 0; i < g_nmod; i++) if (!g_mod[i].nro) n += g_mod[i].size; // an NRO lives in memory the game allocated (its image and bss buffers)return (n + 0x1fffff) & ~(size_t)0x1fffff; }// Giant bss (modules with the patch area before the base, patch_nso.py FAR): the image bytes beyond the file part. Used memory was reported as "heap + 64 MB", where the 64 MB covers ordinary modules' code and data (Mario's two modules are about 74 MB together,@@ -272,11 +282,11 @@ uint64_t svc_dispatch(int num, uint64_t *regs, uint64_t orig_addr) {// Logged once (Mario's retries would repeat it): a game that sizes its heap as pool − used memory and does not retry stops here when its modules are larger than the used memory reported// (profile mem_used; the NSP script's probe boot reads this line, and sets mem_used when no SetHeapSize succeeds afterwards)static int once; if (!once++) LOG("[mem] SetHeapSize %#zx + modules %#zx > app pool %#llx (used memory reported %#llx + bss %#zx)", size, image_bytes() - big_bss_bytes(),- (unsigned long long)APP_POOL, (unsigned long long)DM_GAME_MEM_USED, big_bss_bytes());+ (unsigned long long)APP_POOL, (unsigned long long)MEM_USED, big_bss_bytes());pthread_mutex_unlock(&g_map_lock); regs[0] = 0x10801; return 0;}- uint64_t charged = (uint64_t)DM_GAME_MEM_USED + big_bss_bytes() + atomic_load(&g_alias_mapped);- if (DM_GAME_MEM_MAP_LIMIT && (charged > APP_POOL || size > APP_POOL - charged)) {+ uint64_t charged = (uint64_t)MEM_USED + big_bss_bytes() + atomic_load(&g_alias_mapped);+ if (MEM_MAP_LIMIT && (charged > APP_POOL || size > APP_POOL - charged)) {pthread_mutex_unlock(&g_map_lock); regs[0] = 0x10801; return 0;}int rc = 0;@@ -419,8 +429,8 @@ uint64_t svc_dispatch(int num, uint64_t *regs, uint64_t orig_addr) {// and maps new ones for later allocations, until a map fails: then it unmaps the cached block and retries (measured on the Mac: the refused 4 MB map at +0x43e2c000 was followed by// UnmapPhysicalMemory of the 3.15 GB block and the same map again). Without the limit the mapped total went past the pool in the first minute and the freed block stayed mapped.// Off by default: Ace Attorney Investigations Collection maps a little more than the 1 GB pool its profile reports- if (DM_GAME_MEM_MAP_LIMIT && num == 0x2C) {- int64_t room = (int64_t)APP_POOL - (int64_t)(g_heap_cur + DM_GAME_MEM_USED + big_bss_bytes()) - atomic_load(&g_alias_mapped);+ if (MEM_MAP_LIMIT && num == 0x2C) {+ int64_t room = (int64_t)APP_POOL - (int64_t)(g_heap_cur + MEM_USED + big_bss_bytes()) - atomic_load(&g_alias_mapped);if (need && need > room) {pthread_mutex_unlock(&g_map_lock);static _Atomic int nref; if (atomic_fetch_add(&nref, 1) < 8) LOG("[mem] MapPhysicalMemory +%#zx refused: %.2f GB mapped, the application pool is full (ResultLimitReached, the SDK frees cached pages and retries)",@@ -482,16 +492,16 @@ uint64_t svc_dispatch(int num, uint64_t *regs, uint64_t orig_addr) {case I_StackAddr: v = (uint64_t)g_stack; break; case I_StackSize: v = g_stack_cap; break;case I_TotalMem: case I_TotalNonSys: v = APP_POOL; break;case I_UsedMem: case I_UsedNonSys: pthread_mutex_lock(&g_map_lock);- v = g_heap_cur + DM_GAME_MEM_USED + big_bss_bytes(); // profile mem_used, 64 MB unless the game needs more (see mem_used in dm/games/README.md)+ v = g_heap_cur + MEM_USED + big_bss_bytes(); // profile mem_used, 64 MB unless the game needs more (see mem_used in dm/games/README.md)// with mem_map_limit, the pages mapped in the alias region count too, as on Horizon (the limit in MapPhysicalMemory is the pool less this)- if (DM_GAME_MEM_MAP_LIMIT) v += (uint64_t)atomic_load(&g_alias_mapped);+ if (MEM_MAP_LIMIT) v += (uint64_t)atomic_load(&g_alias_mapped);pthread_mutex_unlock(&g_map_lock); break;// the system resource the NPDM declares (profile sys_resource; 32 MB without the key). The SDK's IsVirtualAddressMemoryEnabled is "total != 0": Big Brain Academy's nninitStartup// asks StandardAllocator for 60 GB of virtual address memory when it is, and sets a heap only when it is not (its NPDM declares none)- case I_SysResTotal: v = DM_GAME_SYS_RESOURCE; break; case I_SysResUsed: v = DM_GAME_SYS_RESOURCE ? 0x400000 : 0; break;+ case I_SysResTotal: v = SYS_RESOURCE; break; case I_SysResUsed: v = SYS_RESOURCE ? 0x400000 : 0; break;case I_DebuggerAttached: v = 0; break;case I_RandomEntropy: { uint64_t dm_entropy64(void); v = dm_entropy64(); break; } // a deterministic stream when DM_DETCLOCK is on (hle_os.c)- case I_ProgramId: { static uint64_t pid; if (!pid) { const char *e = getenv("DM_PROGRAM_ID"); pid = e ? strtoull(e, NULL, 16) : DM_GAME_PROGRAM_ID; } v = pid; break; } // default from the game profile's program_id; DM_PROGRAM_ID=hex overrides+ case I_ProgramId: { static uint64_t pid; if (!pid) { const char *e = getenv("DM_PROGRAM_ID"); pid = e ? strtoull(e, NULL, 16) : PROGRAM_ID; } v = pid; break; } // default from the game profile's program_id; DM_PROGRAM_ID=hex overridescase 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 herediff --git a/dm/host/hle_thread.c b/dm/host/hle_thread.cindex 2dc1bd03..42f918db 100644--- a/dm/host/hle_thread.c+++ b/dm/host/hle_thread.c@@ -455,7 +455,7 @@ static void hitch_init(void) {uint32_t svc_thread_main_init(void) {pthread_key_create(&g_keythr, NULL);qos_map_init();- { const char *e = getenv("DM_PREEMPT"); g_core_preempt = e ? atoi(e) != 0 : DM_GAME_CORE_PREEMPT; }+ { const char *e = getenv("DM_PREEMPT"); g_core_preempt = e ? atoi(e) != 0 : dm_profile()->core_preempt; }pause_install();hitch_init();thr_t *t = calloc(1, sizeof *t);diff --git a/dm/host/loader.c b/dm/host/loader.cindex cd4af6a6..8d82c284 100644--- a/dm/host/loader.c+++ b/dm/host/loader.c@@ -227,7 +227,7 @@ static void install_fps_state(module_t *m) {// DM_RENDER_SCALE (Launcher.swift), and nothing reads the page before the game runsvoid dm_fps_state_apply(void) {if (!dm_fps_state) return;- const char *e = getenv("DM_FPS_TARGET"); int t = e ? atoi(e) : DM_GAME_FPS_TARGET;+ const char *e = getenv("DM_FPS_TARGET"); int t = e ? atoi(e) : dm_profile()->fps_target;if (t != 0 && t != 30 && t != 60) { LOG("[RED] DM_FPS_TARGET=%s: must be 0, 30 or 60; using the game's own frame step", e); t = 0; }float f = (float)t; memcpy(dm_fps_state, &f, sizeof f);// Render scale of the 3D views (the stubs at Tears of the Kingdom's main+0xd5cc0, Breath of the Wild's main+0x1266880): 1.0 keeps the game's own size and dynamic resolution;diff --git a/dm/host/main.c b/dm/host/main.cindex 33d7d98a..a5398c77 100644--- a/dm/host/main.c+++ b/dm/host/main.c@@ -62,6 +62,7 @@ static void *keyrace_thread(void *unused);static void host_preload(int argc, char **argv) {g_t0_ns = proc_start_mono_ns();flags_init();+ dm_profile_log(); // which profile this run uses (DM_PROFILE / DM_PROF_* or the compiled one), before anything reads itif (argc < 2) die("usage: dmhost <dir> [mod...] [-- game arguments...]");// Time zone: the game converts absolute time to local time along two paths, both ending in the host libc -- nn::time::ToCalendarTime (hle_time.c, localtime_r) and the guest libc's// localtime_r / mktime (hle_table.c wires them straight to the host). So only when the host follows the system time zone do the original game's screens (chronicle discovery time etc.) show this machine's time.@@ -87,12 +88,12 @@ static void host_preload(int argc, char **argv) {int i = 2;for (; i < argc && strcmp(argv[i], "--") && n < MAX_MOD; i++) names[n++] = argv[i];if (i < argc && !strcmp(argv[i], "--")) for (i++; i < argc && g_argc < 63; i++) g_argv[g_argc++] = argv[i];- else if (*DM_GAME_ARGS) { // no "--" on the command line (the iOS app, the NSP script's Mac runs): the game profile's game_args, split at spaces- char *s = strdup(DM_GAME_ARGS);+ else if (*dm_profile()->args) { // no "--" on the command line (the iOS app, the NSP script's Mac runs): the game profile's game_args, split at spaces+ char *s = strdup(dm_profile()->args);for (char *t = strtok(s, " "); t && g_argc < 63; t = strtok(NULL, " ")) g_argv[g_argc++] = t;- LOG("game arguments from the game profile: %s", DM_GAME_ARGS);+ LOG("game arguments from the game profile: %s", dm_profile()->args);}- if (!n) { static const char *def[] = DM_GAME_MODULES; for (int k = 0; k < DM_GAME_NMOD && n < MAX_MOD; k++) names[n++] = def[k]; } // default module list from the game profile's modules (Mario: main sdk)+ if (!n) { const struct dm_profile *pf = dm_profile(); for (int k = 0; k < pf->nmod && n < MAX_MOD; k++) names[n++] = pf->modules[k]; } // default module list from the game profile's modules (Mario: main sdk)load_modules(argv[1], names, n);dm_sdk_major(); // logs the SDK version, which SDK-dependent behaviour follows (loader.c)uint64_t ta = now_ns();diff --git a/dm/host/tests/Makefile b/dm/host/tests/Makefileindex 0d2c3a2d..667509a7 100644--- a/dm/host/tests/Makefile+++ b/dm/host/tests/Makefile@@ -46,48 +46,48 @@ symbols: $(B)/t_symbols$(B)/t_symbolsrun: $(B)/t_system_eventrun: $(B)/t_audren_work-$(B)/t_audren_work: t_audren_work.c ../hle_audren.c ../hle.h ../dm.h $(GAME_H) | $(B)+$(B)/t_audren_work: t_audren_work.c ../hle_audren.c ../hle.h ../dm.h $(GAME_H) ../hle_profile.c ../hle_profile.h | $(B)clang -O1 -g -Wall -Werror -Wno-unused-function -I.. $(GINC) -o $@ t_audren_work.c.PHONY: audren-workaudren-work: $(B)/t_audren_work$(B)/t_audren_work-$(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+$(B)/t_system_event: t_system_event.c ../hle_thread.c ../hle_sdk16.c ../hle.h ../dm.h $(GAME_H) ../hle_profile.c ../hle_profile.h | $(B)+ clang -O1 -g -Wall -Werror -Wno-unused-function -Wno-frame-address -I.. $(GINC) -o $@ t_system_event.c ../hle_profile.c.PHONY: system-eventsystem-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+$(B)/t_nro: t_nro.c ../loader.c ../hle_ro.c ../hle.h ../dm.h $(GAME_H) ../hle_profile.c ../hle_profile.h | $(B)+ clang -O1 -g -Wall -Wno-unused-function -Wno-deprecated-declarations -I.. $(GINC) -o $@ t_nro.c ../hle_profile.c.PHONY: nronro: $(B)/t_nro$(B)/t_nro$(GAME_H):$(MAKE) -C .. game_profile GAME=$(GAME)-$(B)/t_heap_size: t_heap_size.c ../hle_svc.c ../dm.h $(GAME_H) | $(B)- clang -O1 -Wall -Werror -Wno-unused-function -fsanitize=undefined -I.. $(GINC) -o $@ t_heap_size.c+$(B)/t_heap_size: t_heap_size.c ../hle_svc.c ../hle_profile.c ../hle_profile.h ../dm.h $(GAME_H) ../hle_profile.c ../hle_profile.h | $(B)+ clang -O1 -Wall -Werror -Wno-unused-function -fsanitize=undefined -I.. $(GINC) -o $@ t_heap_size.c ../hle_profile.c.PHONY: heap_sizeheap_size: $(B)/t_heap_size$(B)/t_heap_size-$(B)/t_touch: t_touch.c ../hle_touch.c ../front.h ../dm.h $(GAME_H) | $(B)- clang -O1 -Wno-unused-function -I.. $(GINC) -o $@ t_touch.c ../hle_touch.c-$(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)+$(B)/t_touch: t_touch.c ../hle_touch.c ../front.h ../dm.h $(GAME_H) ../hle_profile.c ../hle_profile.h | $(B)+ clang -O1 -Wno-unused-function -I.. $(GINC) -o $@ t_touch.c ../hle_touch.c ../hle_profile.c+$(B)/t_gesture: t_gesture.c ../hle_touch.c ../front.h ../dm.h $(GAME_H) ../hle_profile.c ../hle_profile.h | $(B)+ clang -O1 -Wall -Wno-unused-function -I.. $(GINC) -o $@ t_gesture.c ../hle_touch.c ../hle_profile.c+$(B)/t_thread_leak: t_thread_leak.c ../thread.c ../dm.h $(GAME_H) ../hle_profile.c ../hle_profile.h | $(B)clang -O1 -Wno-unused-function -I.. $(GINC) -o $@ t_thread_leak.c-$(B)/t_fs: t_fs.c t_fs_stub.c ../hle_fs.c ../hle_bigstack.c ../romfs_arc.c ../hle.h ../dm.h $(GAME_H) | $(B)+$(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-$(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) | $(B)+$(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-$(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)+$(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) ../hle_profile.c ../hle_profile.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.PHONY: fs-tsanfs-tsan: $(B)/t_fs_commit_list_tsanTMPDIR="$(abspath $(B))" $(B)/t_fs_commit_list_tsan-$(B)/t_fs_case: t_fs_case.c ../hle_fs.c ../hle_bigstack.c ../romfs_arc.c ../hle.h ../dm.h $(GAME_H) | $(B)+$(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$(B)/t_audio: t_audio.c ../hle_audio.c ../hle.h ../dm.h $(GAME_H) | $(B)clang -O1 -Wno-unused-function -I.. $(GINC) -o $@ t_audio.c -framework AudioToolbox-$(B)/t_audio_spsc: t_audio_spsc.c ../hle_audio.c ../hle.h ../dm.h $(GAME_H) | $(B)+$(B)/t_audio_spsc: t_audio_spsc.c ../hle_audio.c ../hle.h ../dm.h $(GAME_H) ../hle_profile.c ../hle_profile.h | $(B)clang -O1 -Wno-unused-function -I.. $(GINC) -o $@ t_audio_spsc.c -framework AudioToolbox$(B)/t_audio_device: t_audio_device.c ../hle_audio.c ../hle.h ../dm.h $(GAME_H) | $(B)clang -O1 -g -Wall -Werror -Wno-unused-function -I.. $(GINC) -o $@ t_audio_device.c -framework AudioToolbox@@ -106,28 +106,28 @@ $(B)/t_altstack: t_altstack.c t_altstack_stub.c ../crash.c ../dm.h $(GAME_H) | $clang -O1 -Wno-unused-function -I.. $(GINC) -o $@ t_altstack.c t_altstack_stub.c ../crash.c$(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-$(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 -g -fsanitize=thread -Wall -Werror -Wno-unused-function -I.. $(GINC) -o $@ t_hid.c ../hle_haptics.c+$(B)/t_shared_font: t_shared_font.c ../hle_sdk16.c ../hle.h ../dm.h $(GAME_H) ../hle_profile.c ../hle_profile.h | $(B)+ 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) ../hle_profile.c ../hle_profile.h | $(B)+ clang -O1 -Wall -Werror -Wno-unused-function -I.. $(GINC) -o $@ t_hid.c ../hle_haptics.c ../hle_profile.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) ../hle_profile.c ../hle_profile.h | $(B)+ clang -O1 -g -fsanitize=thread -Wall -Werror -Wno-unused-function -I.. $(GINC) -o $@ t_hid.c ../hle_haptics.c ../hle_profile.c$(B)/t_haptics: t_haptics.c ../hle_haptics.c ../hle_haptics.h ../dm_input.h | $(B)clang -O1 -g -Wall -Werror -I.. -o $@ t_haptics.c ../hle_haptics.c$(B)/t_touchpad_geometry: t_touchpad_geometry.c ../touchpad_geometry.h ../dm_input.h | $(B)clang -O1 -Wall -I.. $(GINC) -o $@ t_touchpad_geometry.c$(B)/t_haptics_apple: t_haptics_apple.m ../haptics_apple.m ../haptics_apple.h ../hle_haptics.c ../hle_haptics.h | $(B)clang -O1 -g -fobjc-arc -Wall -Werror -I.. -o $@ t_haptics_apple.m ../hle_haptics.c -framework Cocoa -framework GameController -framework CoreHaptics-$(B)/t_time: t_time.c ../hle_time.c ../hle.h ../dm.h $(GAME_H) | $(B)+$(B)/t_time: t_time.c ../hle_time.c ../hle.h ../dm.h $(GAME_H) ../hle_profile.c ../hle_profile.h | $(B)clang -O1 -Wall -Werror -Wno-unused-function -I.. $(GINC) -o $@ t_time.c-$(B)/t_oe: t_oe.c ../hle_oe.c ../hle.h ../dm.h $(GAME_H) | $(B)- clang -O1 -Wno-unused-function -I.. $(GINC) -o $@ t_oe.c-$(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-$(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-$(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+$(B)/t_oe: t_oe.c ../hle_oe.c ../hle.h ../dm.h $(GAME_H) ../hle_profile.c ../hle_profile.h | $(B)+ 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) ../hle_profile.c ../hle_profile.h | $(B)+ 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) ../hle_profile.c ../hle_profile.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 ../hle_profile.c+$(B)/t_preempt: t_preempt.c t_condvar_stub.c ../hle_thread.c ../dm.h $(GAME_H) ../hle_profile.c ../hle_profile.h | $(B)+ clang -O1 -g -Wall -Werror -Wno-unused-function -I.. $(GINC) -o $@ t_preempt.c t_condvar_stub.c ../hle_profile.c.PHONY: preemptpreempt: $(B)/t_preempt$(B)/t_preempt@@ -152,17 +152,17 @@ tsan: $(B)/t_audio_spsc_tsan $(B)/t_hid_tsan$(B)/t_hid_tsanMEM_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_profile.c ../hle_profile.h ../hle.h ../dm.h$(B)/t_svc_memory: $(MEM_DEPS) | $(B)- clang $(MEM_FLAGS) -fsanitize=undefined -o $@ t_svc_memory.c+ clang $(MEM_FLAGS) -fsanitize=undefined -o $@ t_svc_memory.c ../hle_profile.c$(B)/t_svc_memory_unlimited: $(MEM_DEPS) | $(B)- clang $(MEM_FLAGS) -fsanitize=undefined -DDM_GAME_MEM_MAP_LIMIT=0 -o $@ t_svc_memory.c+ clang $(MEM_FLAGS) -fsanitize=undefined -DDM_GAME_MEM_MAP_LIMIT=0 -o $@ t_svc_memory.c ../hle_profile.c$(B)/t_svc_memory_16k: $(MEM_DEPS) | $(B)- clang $(MEM_FLAGS) -fsanitize=address,undefined -DTEST_PAGE_16K -o $@ t_svc_memory.c+ clang $(MEM_FLAGS) -fsanitize=address,undefined -DTEST_PAGE_16K -o $@ t_svc_memory.c ../hle_profile.c$(B)/t_svc_memory_tsan: $(MEM_DEPS) | $(B)- clang $(MEM_FLAGS) -fsanitize=thread -o $@ t_svc_memory.c+ clang $(MEM_FLAGS) -fsanitize=thread -o $@ t_svc_memory.c ../hle_profile.c$(B)/t_svc_memory_dirty: $(MEM_DEPS) ../../gfx/nvn/nvn_dirty.c ../../gfx/nvn/nvn_dirty.h | $(B)- clang $(MEM_FLAGS) -DTEST_REAL_DIRTY -o $@ t_svc_memory.c ../../gfx/nvn/nvn_dirty.c+ clang $(MEM_FLAGS) -DTEST_REAL_DIRTY -o $@ t_svc_memory.c ../../gfx/nvn/nvn_dirty.c ../hle_profile.c.PHONY: memory memory-tsan memory-dirty memory-profilememory: $(B)/t_svc_memory $(B)/t_svc_memory_unlimited $(B)/t_svc_memory_16k$(B)/t_svc_memory@@ -184,3 +184,12 @@ notify-scheduler: $(B)/t_notify_sched$(B)/t_notify_sched$(B)/t_notify_sched --all-peersrun: notify-scheduler++# One binary, several guest memory layouts chosen at run time (the runtime-profile check):+# re-execs itself per layout and boots the production mem_init via GetInfo (hle_svc.c).+$(B)/t_layout_runtime: t_layout_runtime.c ../hle_svc.c ../hle_profile.c ../hle_profile.h ../hle.h ../dm.h $(GAME_H) | $(B)+ clang -O1 -g -Wall -Werror -Wno-unused-function -I.. $(GINC) -o $@ t_layout_runtime.c ../hle_svc.c ../hle_profile.c+.PHONY: layout-runtime+layout-runtime: $(B)/t_layout_runtime+ $(B)/t_layout_runtime+run: layout-runtimediff --git a/dm/host/tests/t_layout_runtime.c b/dm/host/tests/t_layout_runtime.cnew file mode 100644index 00000000..ab581a44--- /dev/null+++ b/dm/host/tests/t_layout_runtime.c@@ -0,0 +1,84 @@+// Stage-2 feasibility check: one binary, several guest memory layouts chosen at run time from DM_PROFILE.+// Each layout runs in its own process (mem_init is once per process, as in the host), so this test re-execs itself+// with LAYOUT set, boots the production dispatcher (hle_svc.c mem_init via GetInfo), and prints what it built.+// Build: clang -O1 -I.. -I../gen/<game> -o build/t_layout_runtime t_layout_runtime.c ../hle_svc.c ../hle_profile.c+#include "../dm.h"+#include "../hle_profile.h"+#include <assert.h>+#include <sys/wait.h>+#include <unistd.h>++module_t g_mod[MAX_MOD];+int g_nmod;+struct dm_flags g_flag;+void hlecount_svc(int num) { (void)num; }+int svc_thread(int num, uint64_t *regs) { (void)num; (void)regs; return 0; }+void dm_backtrace(uint64_t fp) { (void)fp; }+void guest_clock_read_wait(void) {}+uint64_t guest_ns(void) { return 0; }+uint64_t dm_entropy64(void) { return 0; }+int thr_limit_used(void) { return 0; }+int dm_ue_heap_owns(uint64_t a, uint64_t n) { (void)a; (void)n; return 0; }+module_t *module_of(const void *p) { (void)p; return NULL; }+void dm_guest_write_prepare(void *addr, size_t size) { (void)addr; (void)size; }++uint64_t svc_dispatch(int num, uint64_t *regs, uint64_t orig_addr); // hle_svc.c+static uint64_t info(int which) { uint64_t regs[31] = {0}; regs[1] = (uint64_t)which; svc_dispatch(0x29, regs, 0); return regs[1]; } // GetInfo(out, id): id in x1, value out in x1++typedef struct { const char *name, *profile; uint64_t reserve, alias, stack, pool, used, sysres; int limit; } case_t;+static const case_t CASES[] = {+ // Tears of the Kingdom: 5 GB, 2.375 GB alias+ {"totk", "layout_totk.tsv", 0x140000000ull, 0x98000000ull, 0x10000000ull, 0xCD500000ull, 0x4000000ull, 0x2000000ull, 0},+ // Animal Crossing: 4 GB, 256 MB alias, no system resource+ {"acnh", "layout_acnh.tsv", 0x100000000ull, 0x10000000ull, 0x10000000ull, 0xCD500000ull, 0x7a00000ull, 0x0ull, 0},+ // Super Mario Galaxy: 1 GB total (the smallest profile in the repository)+ {"smg", "layout_smg.tsv", 0x40000000ull, 0x10000000ull, 0x10000000ull, 0xCD500000ull, 0x4000000ull, 0ull, 1},+ // Aegis Rim: alias 2.875 GB with the map limit on+ {"13s", "layout_13s.tsv", 0x140000000ull, 0x118000000ull, 0x10000000ull, 0x40000000ull, 0x4000000ull, 0x1000000ull, 1},+};+#define NCASES ((int)(sizeof CASES / sizeof CASES[0]))++static int child(const case_t *c) {+ char path[512]; snprintf(path, sizeof path, "%s/%s", getenv("LAYOUT_DIR") ?: ".", c->profile);+ setenv("DM_PROFILE", path, 1);+ const struct dm_profile *p = dm_profile();+ fprintf(stderr, "[child] %s: profile %s reserve %#llx alias %#llx stack %#llx pool %#llx used %#llx sysres %#llx limit %d\n",+ c->name, p->source, (unsigned long long)p->mem_reserve, (unsigned long long)p->mem_alias,+ (unsigned long long)p->mem_stack, (unsigned long long)p->app_pool, (unsigned long long)p->mem_used,+ (unsigned long long)p->sys_resource, p->mem_map_limit);+ // what the host reports to the guest, built by the production dispatcher+ uint64_t aslr = info(12), aslr_size = info(13), heap_addr = info(4), heap_size = info(5);+ uint64_t alias_addr = info(2), alias_size = info(3), stack_addr = info(14), stack_size = info(15);+ uint64_t total = info(6), used = info(7), sysres = info(16);+ printf("%-6s reserve %#-12llx alias %#-12llx stack %#-12llx heap_region %#-12llx | got aslr %#llx+%#llx alias %#llx+%#llx stack %#llx+%#llx heap@%#llx total %#llx used %#llx sysres %#llx\n",+ c->name, (unsigned long long)aslr_size, (unsigned long long)alias_size, (unsigned long long)stack_size,+ (unsigned long long)heap_size, (unsigned long long)aslr, (unsigned long long)aslr_size,+ (unsigned long long)alias_addr, (unsigned long long)alias_size, (unsigned long long)stack_addr,+ (unsigned long long)stack_size, (unsigned long long)heap_addr, (unsigned long long)total,+ (unsigned long long)used, (unsigned long long)sysres);+ int ok = aslr_size == c->reserve && alias_size == c->alias && stack_size == c->stack && heap_size == c->reserve - 0x10000000ull - c->alias - c->stack+ && alias_addr == aslr + 0x10000000ull && stack_addr == alias_addr + c->alias+ && heap_addr == stack_addr + c->stack && total == c->pool && sysres == c->sysres;+ if (used != c->used) { printf(" [RED] used memory %#llx, profile says %#llx\n", (unsigned long long)used, (unsigned long long)c->used); ok = 0; }+ // SetHeapSize must succeed inside the runtime region+ { uint64_t regs[31] = {0}; regs[1] = heap_size / 2; svc_dispatch(0x01, regs, 0); if (regs[0]) { printf(" [RED] SetHeapSize(%#llx) failed %#llx\n", (unsigned long long)(heap_size / 2), (unsigned long long)regs[0]); ok = 0; } }+ // an explicit-profile mismatch must be visible, not silently ignored+ printf(" %s\n", ok ? "OK" : "[RED] MISMATCH");+ return ok ? 0 : 1;+}++int main(int argc, char **argv) {+ if (argc > 1) { // child mode: LAYOUT names the case+ for (int i = 0; i < NCASES; i++) if (!strcmp(argv[1], CASES[i].name)) return child(&CASES[i]);+ return 2;+ }+ int bad = 0;+ for (int i = 0; i < NCASES; i++) {+ pid_t pid = fork();+ if (!pid) { execl(argv[0], argv[0], CASES[i].name, (char *)NULL); _exit(3); }+ int st = 0; waitpid(pid, &st, 0);+ if (!WIFEXITED(st) || WEXITSTATUS(st)) { printf("%-6s FAILED (%s %d)\n", CASES[i].name, WIFSIGNALED(st) ? "signal" : "status", WIFSIGNALED(st) ? WTERMSIG(st) : WEXITSTATUS(st)); bad++; }+ }+ printf(bad ? "[RED] %d layout(s) failed\n" : "all %d runtime layouts OK\n", bad ? bad : NCASES);+ return bad ? 1 : 0;+}diff --git a/dm/ios/Sources/DmGamepad.m b/dm/ios/Sources/DmGamepad.mindex c3ac8c16..3ac81d95 100644--- a/dm/ios/Sources/DmGamepad.m+++ b/dm/ios/Sources/DmGamepad.m@@ -156,7 +156,7 @@ static BOOL fullOnly(int b) { return b == B_LS || b == B_RS || b >= B_LEFT; }}_swap = shape(_controls); _swapLabel = label(_swap, @"");NSNumber *saved = [NSUserDefaults.standardUserDefaults objectForKey:k_layout_key];- int l = saved ? (int)saved.integerValue : DM_GAME_PAD_LAYOUT;+ int l = saved ? (int)saved.integerValue : dm_profile()->pad_layout;if (l == 2 && dm_opmode() != 0) l = 0; // Tap only in handheld mode (env.txt's DM_OPMODE may have changed it)_full = l == 1; _tap = l == 2;[self applyLayout];diff --git a/dm/ios/Sources/main.m b/dm/ios/Sources/main.mindex 4e9e02ad..7879a70d 100644--- a/dm/ios/Sources/main.m+++ b/dm/ios/Sources/main.m@@ -5,7 +5,7 @@#include <signal.h>#include <stdio.h>#include <unistd.h>-#include "game_profile.h" // game profile constants (the RomFS marker path)+#include "hle_profile.h" // the runtime game profile (DM_PROFILE): the RomFS marker path comes from it#include "front.h"int dm_main(int argc, char **argv); // dm/host/main.c compiled in with -Dmain=dm_main@@ -22,8 +22,9 @@ static BOOL romfs_dir_ok(NSString *d) {// points at the base; the marker check does not apply (there are no directories to walk).if ([fm fileExistsAtPath:[d stringByAppendingPathComponent:@"romfs.idx"]]) return YES;// A plain directory tree: only one containing the game profile's romfs_marker path counts- // (Mario: System/Resource, the resource size table)- return [fm fileExistsAtPath:[d stringByAppendingPathComponent:@DM_GAME_ROMFS_MARKER]];+ // (Mario: System/Resource, the resource size table). Runtime profile: the marker is a profile+ // value now; the compiled macro is only what dm_profile() falls back to without DM_PROFILE.+ return [fm fileExistsAtPath:[d stringByAppendingPathComponent:@(dm_profile()->romfs_marker)]];}// Where one game's data lives under the per-game layout: Documents/games/<title ID>/, holding