diff --git a/dm/gfx/nvn/hle_nvn.c b/dm/gfx/nvn/hle_nvn.c index b374fbd..d64e95f 100644 --- a/dm/gfx/nvn/hle_nvn.c +++ b/dm/gfx/nvn/hle_nvn.c @@ -906,7 +906,8 @@ static void dump_frame(void) { // Every 300 frames read resident memory and hand it to the graphics layer to print the memory readout line (mtl_mem_stat, low frequency, capped). Memory watchdog: when resident memory exceeds the cap, log a failure and exit on its own. On by default only on the Mac host (24 GB: runaway host memory // drags the whole machine into a kernel panic, which happened twice with other programs on the same machine), or set for tests with DM_MEM_CAP_GB=; the player's iOS app has no cap (exiting before the system kills it is pointless and only adds another kind of crash) if (g_frame % 300 == 0) { task_vm_info_data_t vi; mach_msg_type_number_t cnt = TASK_VM_INFO_COUNT; - if (task_info(mach_task_self(), TASK_VM_INFO, (task_info_t)&vi, &cnt) == KERN_SUCCESS) { unsigned long long mb = (unsigned long long)(vi.phys_footprint >> 20); void mtl_mem_stat(unsigned long long, unsigned long long); mtl_mem_stat(g_frame, mb); + if (task_info(mach_task_self(), TASK_VM_INFO, (task_info_t)&vi, &cnt) == KERN_SUCCESS) { unsigned long long mb = (unsigned long long)(vi.phys_footprint >> 20); unsigned long long ht = 0, hf = 0, hm = 0; int dm_guest_heap_stat(unsigned long long *, unsigned long long *, unsigned long long *); int hok = dm_guest_heap_stat(&ht, &hf, &hm); + void mtl_mem_stat(unsigned long long, unsigned long long, int, unsigned long long, unsigned long long, unsigned long long); mtl_mem_stat(g_frame, mb, hok, ht, hf, hm); static long cap = -1; if (cap < 0) { const char *e = getenv("DM_MEM_CAP_GB"); cap = e ? atol(e) : DM_MEM_CAP_DEFAULT_GB; } if (cap > 0 && mb > (unsigned long long)cap * 1024) { LOG("【红】内存看门狗:常驻 %llu MB 超过上限 %ld GB(帧 %llu),自行退出", mb, cap, (unsigned long long)g_frame); _exit(86); } } } dm_guest_frame_tick(); // 确定性客体时钟(DM_DETCLOCK,宿主 hle_os.c):每次出图推进固定步长;未开为空操作 | Deterministic guest clock (DM_DETCLOCK, host hle_os.c): each present advances a fixed step; a no-op when not enabled diff --git a/dm/gfx/nvn/nvn_mtl.m b/dm/gfx/nvn/nvn_mtl.m index e8e6965..e4679c3 100644 --- a/dm/gfx/nvn/nvn_mtl.m +++ b/dm/gfx/nvn/nvn_mtl.m @@ -6,6 +6,10 @@ #import #import #include +#include +#if TARGET_OS_IPHONE +#include +#endif #include #include #include @@ -1215,20 +1219,27 @@ static id tex_mtl(const tex_t *ct) { serial_put(t->serial, mt); return mt; } -// 内存读数行(常开、低频、封顶):常驻内存、显卡已分配、延迟释放队列、驻留集对象数、在册内存池数 / 峰值 / 跟踪表容量、贴图重传累计。 +// 内存读数行(常开、低频、封顶):常驻内存、显卡已分配、延迟释放队列、驻留集对象数、在册内存池数 / 峰值 / 跟踪表容量、贴图重传累计、游戏堆总量 / 余量 / 最大可分配块(宿主 dm_guest_heap_stat)、离系统内存上限还有多少(仅 iOS)。 // 用途:定「没有日志的闪退」——系统按内存杀进程前不给任何通知,只有事先留下的读数能说明是哪个数一路往上涨。 -// 每 300 帧由帧钩子调一次;常驻或显卡已分配比上一行变了 ≥ 64 MB 才打,否则每 3000 帧打一行;一局封顶 400 行。全是整数(帧钩子在客体线程的小栈上,不用浮点格式) -// Memory readout line (always on, low frequency, capped): resident memory, GPU allocated, deferred-release queue, residency set object count, registered memory pools / peak / tracking table capacity, cumulative texture re-uploads. -// Purpose: pin down "crashes with no log". The system gives no notice before killing a process for memory, so only readouts left beforehand can show which number kept climbing. -// Called by the frame hook every 300 frames; printed only when resident or GPU allocated changed by ≥ 64 MB since the last line, otherwise one line every 3000 frames; capped at 400 lines per game. All integers (the frame hook runs on the guest thread's small stack, so no floating-point formatting) -void mtl_mem_stat(unsigned long long frame, unsigned long long rss_mb) { - static unsigned long long last_rss, last_gpu, last_frame; static int lines; unsigned long long gpu = (unsigned long long)(g_dev.currentAllocatedSize >> 20); +// 每 300 帧由帧钩子调一次;常驻、显卡已分配变了 ≥ 64 MB,或游戏堆余量、最大可分配块变了 ≥ 16 MB(主堆平时只剩约 100 MB)才打,否则每 3000 帧打一行;一局封顶 400 行。全是整数(帧钩子在客体线程的小栈上,不用浮点格式) +// Memory readout line (always on, low frequency, capped): resident memory, GPU allocated, deferred release queue, residency set object count, registered memory pool count / peak / tracking table capacity, cumulative texture re-uploads, game heap total / free / largest allocatable block (host dm_guest_heap_stat), and how far from the system memory limit (iOS only). +// Purpose: to pin down "crashes with no log" -- the system gives no notice before killing a process for memory, and only readouts left beforehand can show which number kept climbing. +// Called by the frame hook every 300 frames; printed when resident or GPU allocated changed by >= 64 MB, or game heap free space or largest allocatable block changed by >= 16 MB (the main heap normally has only about 100 MB left), otherwise one line every 3000 frames; capped at 400 lines per run. All integers (the frame hook runs on the small stack of a guest thread, so no floating-point formatting) +void mtl_mem_stat(unsigned long long frame, unsigned long long rss_mb, int heap_ok, unsigned long long heap_mb, unsigned long long heap_free_mb, unsigned long long heap_maxblk_kb) { + static unsigned long long last_rss, last_gpu, last_frame, last_hfree, last_hmax; static int lines; unsigned long long gpu = (unsigned long long)(g_dev.currentAllocatedSize >> 20); unsigned long long dr = rss_mb > last_rss ? rss_mb - last_rss : last_rss - rss_mb, dg = gpu > last_gpu ? gpu - last_gpu : last_gpu - gpu; - if (lines >= 400 || (lines && dr < 64 && dg < 64 && frame - last_frame < 3000)) return; lines++; last_rss = rss_mb; last_gpu = gpu; last_frame = frame; + unsigned long long dh = heap_free_mb > last_hfree ? heap_free_mb - last_hfree : last_hfree - heap_free_mb, hmax_mb = heap_maxblk_kb >> 10, dm = hmax_mb > last_hmax ? hmax_mb - last_hmax : last_hmax - hmax_mb; + static int all = -1; if (all < 0) all = getenv("DM_MEM_STAT_ALL") != NULL; // 量测用:每次都打、不封顶 | For measurement: printed every time, uncapped + if (!all && (lines >= 400 || (lines && dr < 64 && dg < 64 && dh < 16 && dm < 16 && frame - last_frame < 3000))) return; lines++; last_rss = rss_mb; last_gpu = gpu; last_frame = frame; last_hfree = heap_free_mb; last_hmax = hmax_mb; pthread_mutex_lock(&g_deferred_mu); unsigned long nd = (unsigned long)g_deferred.count; pthread_mutex_unlock(&g_deferred_mu); pthread_mutex_lock(&g_res_mu); unsigned long nr = (unsigned long)g_res_objects.count; pthread_mutex_unlock(&g_res_mu); int live = 0, peak = 0, cap = 0; nvn_dirty_stat(&live, &peak, &cap); - MLOG("内存 至帧 %llu:常驻 %llu MB,显卡已分配 %llu MB,延迟释放队列 %lu,驻留集 %lu 个,内存池 %d 个(峰值 %d / 跟踪表容量 %d),贴图重传累计 %llu 次", frame, rss_mb, gpu, nd, nr, live, peak, cap, (unsigned long long)g_pkg_reuploads); + char avail[32] = "无"; // os_proc_available_memory:本进程离被系统按内存终止还差多少,只有 iOS 有;Mac 宿主写「无」 | os_proc_available_memory: how far this process is from being terminated by the system for memory, iOS only; the Mac host writes "none" +#if TARGET_OS_IPHONE + snprintf(avail, sizeof avail, "%llu MB", (unsigned long long)(os_proc_available_memory() >> 20)); +#endif + MLOG("内存 至帧 %llu:常驻 %llu MB,显卡已分配 %llu MB,延迟释放队列 %lu,驻留集 %lu 个,内存池 %d 个(峰值 %d / 跟踪表容量 %d),贴图重传累计 %llu 次;游戏堆 %llu MB,余量 %llu MB,最大可分配块 %llu KB%s;离系统内存上限还有 %s", frame, rss_mb, gpu, nd, nr, live, peak, cap, (unsigned long long)g_pkg_reuploads, + heap_mb, heap_free_mb, heap_maxblk_kb, heap_ok ? "" : "(未读到)", avail); } void mtl_pkg_stats(uint64_t *uploads, uint64_t *reuploads) { *uploads = g_pkg_uploads; *reuploads = g_pkg_reuploads; } uint64_t mtl_pkg_miss(void) { return g_pkg_miss; } @@ -1305,6 +1316,7 @@ static void blit_note(void) { if (g_enc) PD("E %llu 拷贝 / 缓冲更新结束 // For intersecting with the inflate output ranges (which data decompressed before character select is really used by the character select screen). Columns: kind guest_addr len first_frame tex_id fmt w×h __attribute__((weak)) uint64_t dm_prof_ribbon_ns(void) { return 0; } // diag.c 提供强定义;未合入时恒 0 → 时间窗不开,结束时报红 | diag.c provides the strong definition; when not merged it is always 0 → the time window does not open, and a failure is reported at the end __attribute__((weak)) void dm_shot_written(const char *path, int ok) { (void)path; (void)ok; } +__attribute__((weak)) int dm_guest_heap_stat(unsigned long long *t, unsigned long long *f, unsigned long long *m) { (void)t; (void)f; (void)m; return 0; } // hle_svc.c 提供强定义(游戏主堆读数);图形单测不链宿主时读不到 | hle_svc.c provides the strong definition (game main heap readout); the graphics unit tests do not link the host and cannot read it __attribute__((weak)) void dm_guest_frame_tick(void) {} // hle_os.c 提供强定义(DM_DETCLOCK 确定性客体时钟);图形单测不链宿主时为空操作 // diag.c 提供强定义(DM_TICK_HOLD=E:SHOT 解冻);图形单测不链宿主时为空操作 | hle_os.c provides the strong definition (DM_DETCLOCK deterministic guest clock); a no-op when graphics unit tests do not link the host // diag.c provides the strong definition (DM_TICK_HOLD=E:SHOT unfreeze); a no-op when graphics unit tests do not link the host __attribute__((weak)) int dm_detclock_enabled(void) { return 0; } // 同上:宿主 hle_os.c 提供强定义;图形单测不链宿主时确定性时钟视为关闭 | Same as above: the host's hle_os.c provides the strong definition; when graphics unit tests do not link the host, the deterministic clock is treated as off __attribute__((weak)) uint64_t guest_ns(void) { return 0; } // 同上:仅在确定性时钟开启时被读,图形单测里不会走到 | Same as above: read only when the deterministic clock is on; never reached in graphics unit tests diff --git a/dm/host/hle_svc.c b/dm/host/hle_svc.c index 1d08600..cb6a7f7 100644 --- a/dm/host/hle_svc.c +++ b/dm/host/hle_svc.c @@ -3,6 +3,8 @@ // Horizon kernel system calls (triggered by the SDK runtime once the SDK is loaded). Only what the P1 boot chain needs is implemented: memory layout + heap + query + debug output + timing. // Register convention: inputs w1.. / outputs w0=Result, x1=value (GetInfo / SetHeapSize), consistent with the public Horizon ABI. #include "dm.h" +#include "hle.h" +#include #include #include #include @@ -22,7 +24,7 @@ // with an 8 GB reservation, builds from developer accounts that cannot sign that entitlement (free accounts) would exit at this step. #define RESERVE (5ull << 30) static uint8_t *g_as; // ASLR 区基址 = 整块 | ASLR region base = the whole block -static uint8_t *g_heap; static size_t g_heap_cur, g_heap_cap; +static uint8_t *g_heap; static size_t g_heap_cur, g_heap_cap; static int g_heap_rejects; // 地址段整个落在客体堆当前已开放(可读写)的范围内:这种读不用陷内核核对,直接 memcpy(diag.c tk_rd 等每拍读客体内存的地方用) // 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) int dm_guest_heap_readable(uint64_t a, size_t n) { uint64_t b = (uint64_t)(uintptr_t)g_heap; size_t cur = g_heap_cur; return g_heap && a >= b && n <= cur && a - b <= cur - n; } @@ -50,8 +52,44 @@ static void mem_init(void) { // 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 0xCD500000ull +// 报给游戏的池 = Switch 的 3285 MB + 512 MB(DM_APP_POOL_ADD_MB=<整数> 可调,可为负——往小调用来造「主堆用尽」的现场)。 +// 为什么多给:游戏自己固定划走约 3.08 GB,主堆余量进局只有 100–180 MB、换图时地板三四十 MB、最大可分配块二十几 MB;用尽时原版多处不判空直接写 +// (公开仓库,另见下面 dm_guest_heap_stat)。实测多给的量一比一变成主堆余量(138 → 649 MB),游戏划走的不跟着变; +// 没碰过的堆页不计入常驻内存,余量真被用掉时常驻才涨。堆区上限是预留里的 4 GB(mem_init),3728 MB 放得下;再加要先动预留。 +// 取 +512 而不是更大:给 6 GB 内存的机型留余地,真机上限有读数后再定。 +// Pool reported to the game = the Switch's 3285 MB + 512 MB (adjustable with DM_APP_POOL_ADD_MB=, may be negative -- lowering it is how to stage a "main heap exhausted" scene). +// Why more is given: the game carves out a fixed 3.08 GB or so for itself, leaving the main heap only 100–180 MB of free space on entering a game, a floor of thirty to forty MB when changing maps and a largest allocatable block of twenty-odd MB; when it runs out the original game writes through null without checking in many places +// (see also dm_guest_heap_stat below). Measured: the extra amount turns one-to-one into main heap free space (138 -> 649 MB), while what the game carves out does not change with it; +// heap pages never touched do not count toward resident memory, which grows only when the free space is actually used. The heap region limit is the 4 GB in the reservation (mem_init), which fits 3728 MB; adding more means changing the reservation first. +// +512 rather than more: to leave room for devices with 6 GB of RAM; to be revisited once there are readings of the limit on real devices. +static uint64_t app_pool(void) { static uint64_t v; if (!v) { const char *e = getenv("DM_APP_POOL_ADD_MB"); long add = e ? atol(e) : 512; v = APP_POOL + ((uint64_t)add << 20); if (e) LOG("DM_APP_POOL_ADD_MB:应用内存池报 %llu MB(Switch 的 3285 MB %+ld)", (unsigned long long)(v >> 20), add); } return v; } static size_t image_bytes(void) { size_t n = 0; for (int i = 0; i < g_nmod; i++) n += g_mod[i].size; return (n + 0x1fffff) & ~(size_t)0x1fffff; } +// 游戏主堆读数:主堆 = main+0x32137a0 那个 nn::mem::StandardAllocator(启动时把整块堆交给它)。申请失败返回空,原版多处不判空直接写 +// (公开仓库 连战 82 分钟后异步读盘回调 main+0x27ecdc 要 765 KB 连续块得空,memset 写 0 地址;进程常驻内存看不出这件事)。 +// 余量 / 最大可分配块调的是分配器自己的查询(sdk+0x2f9d78 / +0x2f9dbc,内部走 CentralHeap::Query、自己加锁),只许在客体线程上调。 +// 读到的数留一份在 g_gheap_last 里,分配返回空时的报红直接带上次读数(那一刻不再进分配器)。单位:总量 / 余量 MB,最大块 KB +// Game main heap readout: the main heap = the nn::mem::StandardAllocator at main+0x32137a0 (the whole heap block is handed to it at startup). A failed allocation returns null, and the original game writes through it without a null check in many places +// (after 82 minutes of boss rush, the asynchronous disk-read callback main+0x27ecdc asked for a contiguous 765 KB block, got null, and memset wrote to address 0; the process resident memory does not show this). +// Free space / largest allocatable block call the allocator's own queries (sdk+0x2f9d78 / +0x2f9dbc, which go through CentralHeap::Query and take their own lock) and may only be called on a guest thread. +// The values read are kept in g_gheap_last, and the red report on a null allocation carries the last readout directly (the allocator is not entered again at that moment). Units: total / free in MB, largest block in KB +static module_t *mod_named(const char *n) { for (int i = 0; i < g_nmod; i++) if (!strcmp(g_mod[i].name, n)) return &g_mod[i]; return NULL; } +static _Atomic unsigned long long g_gheap_last[3]; +int dm_guest_heap_stat(unsigned long long *total_mb, unsigned long long *free_mb, unsigned long long *maxblk_kb) { + module_t *mm = mod_named("main"), *ms = mod_named("sdk"); if (!mm || !ms || !g_heap_cur) return 0; + uint8_t *al = mm->base + 0x32137a0; if (!al[0]) return 0; // 首字节 = 已初始化(sdk+0x2f9898 写) | First byte = initialized (written by sdk+0x2f9898) + uint64_t fr = ((uint64_t (*)(void *))(ms->base + 0x2f9d78))(al), mx = ((uint64_t (*)(void *))(ms->base + 0x2f9dbc))(al); + *total_mb = g_heap_cur >> 20; *free_mb = fr >> 20; *maxblk_kb = mx >> 10; + g_gheap_last[0] = *total_mb; g_gheap_last[1] = *free_mb; g_gheap_last[2] = *maxblk_kb; return 1; +} +HLE_FORCE("_ZN2nn3mem17StandardAllocator8AllocateEmm", "照原版分配,只在返回空时报红(原版调用方多处不判空)", void *, hle_stdalloc_allocate, void *self, size_t size, size_t align) { + static void *(*orig)(void *, size_t, size_t); if (!orig) { module_t *ms = mod_named("sdk"); orig = (void *(*)(void *, size_t, size_t))(ms->base + 0x2f9974); } + void *p = orig(self, size, align); + if (!p && size) { static _Atomic int n; if (atomic_fetch_add(&n, 1) < 8) LOG("【红】游戏堆分配返回空:申请 %zu 字节(对齐 %zu),分配器 %p;上次读数 主堆 %llu MB、余量 %llu MB、最大可分配块 %llu KB", size, align, self, + (unsigned long long)g_gheap_last[0], (unsigned long long)g_gheap_last[1], (unsigned long long)g_gheap_last[2]); } + return p; +} + // 内存账(memstat.m)用:客体地址空间整块范围(未初始化时 base = NULL) // For memory accounting (memstat.m): the range of the whole guest address space block (base = NULL when not initialized) void svc_guest_range(uint8_t **base, size_t *size) { *base = g_as; *size = RESERVE; } @@ -92,11 +130,12 @@ uint64_t svc_dispatch(int num, uint64_t *regs, uint64_t orig_addr) { case 0x01: { // SetHeapSize(out_addr*, size) → x1 = heap base size_t size = regs[1]; if (size > g_heap_cap) { LOG("SetHeapSize OOM: req %#zx > cap %#zx", size, g_heap_cap); regs[0] = 0xD401; return 0; } - if (size + image_bytes() > APP_POOL) { regs[0] = 0x10801; return 0; } // 超出应用内存池:ResultLimitReached。游戏启动时按 2 MB 递减重试直到放得下(main+0x1b66184) | exceeds the application memory pool: ResultLimitReached. At startup the game retries in 2 MB decrements until it fits (main+0x1b66184) + if (size + image_bytes() > app_pool()) { g_heap_rejects++; regs[0] = 0x10801; return 0; } // 超出应用内存池:ResultLimitReached。游戏启动时按 2 MB 递减重试直到放得下(main+0x1b66184) | exceeds the application memory pool: ResultLimitReached. At startup the game retries in 2 MB decrements until it fits (main+0x1b66184) int rc = 0; if (size > g_heap_cur) rc = mprotect(g_heap + g_heap_cur, size - g_heap_cur, PROT_READ | PROT_WRITE); else if (size < g_heap_cur) rc = mprotect(g_heap + size, g_heap_cur - size, PROT_NONE); if (g_flag.svc) LOG("SetHeapSize %#zx -> base %p mprotect=%d errno=%d", size, g_heap, rc, errno); + { static int said; if (!said && size) { said = 1; LOG("SetHeapSize:首次设堆成功 %zu MB(应用内存池 %llu MB − 映像 %zu MB;此前被拒 %d 次)", size >> 20, (unsigned long long)(app_pool() >> 20), image_bytes() >> 20, g_heap_rejects); } } g_heap_cur = size; regs[0] = 0; regs[1] = (uint64_t)g_heap; return 0; } @@ -189,8 +228,10 @@ uint64_t svc_dispatch(int num, uint64_t *regs, uint64_t orig_addr) { case I_HeapAddr: v = (uint64_t)g_heap; break; case I_HeapSize: v = g_heap_cap; break; case I_AslrAddr: v = (uint64_t)g_as; break; case I_AslrSize: v = RESERVE; break; 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: v = g_heap_cur + 0x4000000; break; + case I_TotalMem: case I_TotalNonSys: v = app_pool(); break; + case I_UsedMem: case I_UsedNonSys: v = g_heap_cur + image_bytes(); break; // 已用 = 堆 + 映像,与 SetHeapSize 的核对同一口径(原先写死 64 MB)。sdk 的 QueryMemoryInfo(sdk+0x34f4ec)只拿它算「程序占用」那一格; | Used = heap + image, the same accounting as the check in SetHeapSize (it used to be hard-coded to 64 MB). The sdk's QueryMemoryInfo (sdk+0x34f4ec) only uses it to compute the "program usage" field; + // 「可用总量」那一格直接是池总量,所以游戏启动设堆仍要从整池起按 2 MB 往下减到 池 − 映像(约 34 次被拒)——这是原版在真机上的走法,不是我们的口径错 + // The "total available" field is simply the pool total, so at startup the game still has to step down from the whole pool by 2 MB at a time until pool - image (about 34 refusals) when setting its heap -- this is how the original behaves on the real device, not a mistake in our accounting case I_SysResTotal: v = 0x2000000; break; case I_SysResUsed: v = 0x400000; break; case I_DebuggerAttached: v = 0; break; case I_RandomEntropy: { uint64_t dm_entropy64(void); v = dm_entropy64(); break; } // DM_DETCLOCK 开时为确定流(hle_os.c) | a deterministic stream when DM_DETCLOCK is on (hle_os.c)