From 6f97dca93a612d3d72207d799e15fce0b5d4cfc7 Mon Sep 17 00:00:00 2001 From: Valiantsin Dzerakh Date: Wed, 25 Nov 2026 16:06:54 +0300 Subject: [PATCH 1/6] A plugin's call to a function it defines itself is its own code, not an import (#1422, #1461) A plugin built with default visibility calls its own exported functions through its PLT. Challenge Mode's Enemy Health Regeneration plugin (exefs subsdk8) does so for the std::vector constructor it carries, and the service run counted that as a library call outside the reviewed list, so the plugin was refused and its whole mod stayed off. runtime/loader.c resolve binds such a JUMP_SLOT straight to the plugin's own definition (a host override still wins and stays counted), and tools/exefs_plugins.py plt_imports maps the PLT stub to that code, so the reach check follows into it instead of naming an import. Co-Authored-By: Claude Opus 5.5 --- docs/mods.md | 4 +++- runtime/loader.c | 8 +++++++- tests/exefs_plugins_test.py | 20 ++++++++++++++++++++ tools/exefs_plugins.py | 15 +++++++++++++-- 4 files changed, 43 insertions(+), 4 deletions(-) diff --git a/docs/mods.md b/docs/mods.md index 3d4ba533..6b65f716 100644 --- a/docs/mods.md +++ b/docs/mods.md @@ -128,7 +128,9 @@ The rebuild refuses a plugin when its start-up or the code its redirects reach n system calls other than the few its start-up needs (memory queries and maps, the heap size, the clock, debug output), or a library call the game itself never makes and a reviewed list does not hold (memory and string functions, the heap, text formatting, mutexes, the clock, the system language, the SD card's files), such as network sockets or the module -loader. A library call the game makes (threads, input, time, its files) runs on the path the game runs on. A start-up +loader. A library call the game makes (threads, input, time, its files) runs on the path the game runs on. A call to a +function the plugin itself holds counts as its own code, even when it goes through the plugin's import table (C++ +library templates such as `std::vector` built into it). A start-up still gets only the system calls above, so it cannot start a thread or open a service; a redirect that is not one of exlaunch's hook shapes (inline hook, replace hook, call-site rewrite, a branch into its code from inside a game function, a pointer in the game's data swapped for one into its code); a write into the game's read-only data or into another module; two runs of diff --git a/runtime/loader.c b/runtime/loader.c index 635d4313..3051eb9e 100644 --- a/runtime/loader.c +++ b/runtime/loader.c @@ -397,7 +397,13 @@ static Res resolve(Mod *m, uint32_t si, int jump) { uint64_t guest = sym_defined(m, si) ? m->pub.base + m->syms[si].value : find_symbol(name, NULL); GuestFn f; Res r; - if (jump && m->pub.plugin && ldr_plugin_import) { // the plugin service run counts the plugin's calls by name + // A plugin's calls out of its own code are counted by name (plugin_init.c plugin_import), so the plugin check can + // judge what its init reached. A JUMP_SLOT whose symbol the plugin defines itself is no call out: a plugin built + // with default visibility calls its own exported functions through its PLT, such as the std::vector + // constructor of Challenge Mode's Enemy Health Regeneration (exefs subsdk8), and it binds to that definition as + // any other own symbol. A host override of the name still wins and stays counted. + int own_code = sym_defined(m, si) && !hostfn_override(name); + if (jump && m->pub.plugin && ldr_plugin_import && !own_code) { uint64_t to = (f = hostfn_override(name)) ? hostfn_register(name, f) : guest; if (!to) to = hostfn_register(name, unresolved_stub); r = (Res){hostfn_register_observer(name, ldr_plugin_import, to), RES_OBSERVER}; diff --git a/tests/exefs_plugins_test.py b/tests/exefs_plugins_test.py index 727b161c..318500e5 100644 --- a/tests/exefs_plugins_test.py +++ b/tests/exefs_plugins_test.py @@ -452,6 +452,26 @@ class Reach(unittest.TestCase): svcs, imports, _, _, _ = xp.reach(img, self.BASE, 0x200, [self.BASE], {self.BASE + 0x80: 'malloc'}) self.assertEqual((svcs, imports), (set(), {'malloc': 1})) + def test_own_function_through_plt_is_followed(self): + # bl plt; ret. The PLT stub at 0x80 binds to the plugin's own function at 0x100: svc 0x40; ret + img = bytearray(code([b(self.BASE, self.BASE + 0x80, True), RET_W])) + struct.pack_into(' constructor of Challenge Mode's Enemy Health Regeneration).""" + slots = {} + for off, typ, sym, _ in nso.relocs: + if typ == R_AARCH64_JUMP_SLOT: + name, _, shndx, value, _ = nso.syms[sym] + slots[off] = base + value if shndx else name out = {} for o in range(0, text_end - 16, 4): w0, w1, _, w3 = struct.unpack_from('<4I', img, o) @@ -499,6 +506,10 @@ def reach(img, base, text_end, roots, plt, stubs=()): if a in seen: break if a in plt: + if isinstance(plt[a], int): # the plugin's own function behind its PLT: the path goes on there + seen.add(a) + a = plt[a] + continue imports[plt[a]] = imports.get(plt[a], 0) + 1 break if not base <= a < base + text_end: From 5c5c6d1dd048d062f90155c8415ebd778631f5fe Mon Sep 17 00:00:00 2001 From: Valiantsin Dzerakh Date: Wed, 25 Nov 2026 21:06:27 +0300 Subject: [PATCH 2/6] With a mod plugin on, read-only module data stays writable on the host, so Zonai Fieldworks can swap main's RELRO entries when a member is switched on in play (#1451) QueryMemory still reports the permission the game asked for. Material Columns swaps 11 dispatch slots in main's RELRO from its own code at switch time; on the platforms the mod is made for that write goes through, here it faulted. Co-Authored-By: Claude Opus 5.5 --- runtime/host.h | 2 ++ runtime/memory.c | 14 +++++++++++--- runtime/plugin_init.c | 1 + 3 files changed, 14 insertions(+), 3 deletions(-) diff --git a/runtime/host.h b/runtime/host.h index ef721106..7c7b4ceb 100644 --- a/runtime/host.h +++ b/runtime/host.h @@ -148,6 +148,8 @@ void mem_init(void); // reserve every regi const RtGuestLayout *mem_layout(void); uint32_t mem_set_heap_size(uint64_t size, uint64_t *addr); // 0x01 uint32_t mem_set_permission(uint64_t a, uint64_t n, uint32_t perm); // 0x02 +extern int mem_plugin_writes; // plugin_init.c plugins_start: a mod plugin is on; read-only module data stays writable + // on the host (mem_set_permission) uint32_t mem_set_attribute(uint64_t a, uint64_t n, uint32_t mask, uint32_t at); // 0x03 uint32_t mem_map(uint64_t dst, uint64_t src, uint64_t n); // 0x04 uint32_t mem_unmap(uint64_t dst, uint64_t src, uint64_t n); // 0x05 diff --git a/runtime/memory.c b/runtime/memory.c index 12cc2c3d..82562a34 100644 --- a/runtime/memory.c +++ b/runtime/memory.c @@ -500,6 +500,8 @@ static int module_data(uint64_t a, uint64_t n) { return off >= m->data_off && n <= m->size - off ? i : -1; } +int mem_plugin_writes; + uint32_t mem_set_permission(uint64_t a, uint64_t n, uint32_t perm) { if (a & (PAGE - 1)) return R_INVALID_ADDRESS; if (!n || (n & (PAGE - 1))) return R_INVALID_SIZE; @@ -515,10 +517,16 @@ uint32_t mem_set_permission(uint64_t a, uint64_t n, uint32_t perm) { return R_INVALID_STATE; } memset(t, (int)perm, n / PAGE); - protect(a, n, perm == PERM_RW ? PLAT_PROT_RW : perm == PERM_R ? PLAT_PROT_READ : PLAT_PROT_NONE, "module data"); + // With a mod plugin on, a read-only run (the RELRO the SDK seals in each module's DT_INIT, after the plugins' + // inits) stays writable on the host while QueryMemory reports what the game asked. Zonai Fieldworks swaps entries + // of main's RELRO tables from its own code when a member is switched on in play (#1451), writing main's address + // directly; on the platforms the mod is made for that write goes through, here it faulted. + int keep_rw = perm == PERM_R && mem_plugin_writes; + protect(a, n, perm == PERM_RW || keep_rw ? PLAT_PROT_RW : perm == PERM_R ? PLAT_PROT_READ : PLAT_PROT_NONE, + "module data"); plat_mutex_unlock(&lock); - rt_log("%s data permission +%#llx size %#llx perm %u", m->name, (unsigned long long)(a - m->base), - (unsigned long long)n, perm); + rt_log("%s data permission +%#llx size %#llx perm %u%s", m->name, (unsigned long long)(a - m->base), + (unsigned long long)n, perm, keep_rw ? " (kept writable on the host: a mod plugin is on)" : ""); return R_OK; } diff --git a/runtime/plugin_init.c b/runtime/plugin_init.c index 7554da83..af7e8778 100644 --- a/runtime/plugin_init.c +++ b/runtime/plugin_init.c @@ -708,6 +708,7 @@ int plugins_start(Cpu *c, const RtLoaded *sdk) { for (int i = 0; i < naliases; i++) live += aliases[i].live; rt_log("plugins: %d of %d plugins on in %llu ms (%d process-memory maps, %d kept)", on, nrun, (unsigned long long)(plat_now_ms() - t0), naliases, live); + mem_plugin_writes = on > 0; // before main's DT_INIT seals its RELRO (memory.c mem_set_permission) if (on && cfg_bool("TOTK_PLUGIN_TRACE")) trace_entries(); return 1; #else From 340da7c6e6d6c1f01f078c3ea99c2336bf5ff886 Mon Sep 17 00:00:00 2001 From: Valiantsin Dzerakh Date: Wed, 25 Nov 2026 21:06:28 +0300 Subject: [PATCH 3/6] A plugin hook on main's module header gets only its expect line, not a lift site (#1422, #1461) exlaunch adds a table offset to main's base, so an update the plugin's table lacks hooks main+0x0 (Challenge Mode's Enemy Health Regeneration names 1.0.0 to 1.4.1). Nothing runs there, on the Switch either; the site line made the generator refuse the lift ("patched instruction is a trap") and the installer dropped every plugin. The report notes such a hook. Co-Authored-By: Claude Opus 5.5 --- tests/exefs_plugins_test.py | 14 ++++++++++++++ tools/exefs_plugins.py | 14 ++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/tests/exefs_plugins_test.py b/tests/exefs_plugins_test.py index 318500e5..6a891929 100644 --- a/tests/exefs_plugins_test.py +++ b/tests/exefs_plugins_test.py @@ -603,6 +603,20 @@ class Lines(unittest.TestCase): self.assertIn(f'orig mod_x plugin0 {TRAMP_OFF:x} main {SITE_OFF:x}', out) self.assertIn(f'seed plugin0 {THUNK_OFF:x}', out) + def test_hook_on_main_header_keeps_only_its_expect(self): + # Challenge Mode's Enemy Health Regeneration on an update its table lacks: a replace hook at main+0x0, whose + # word 1 is main's module header. The write is checked at start; the lift gets no site, orig or seed for it. + new = b(MAIN, PLUGIN + THUNK_OFF) + rec = record(writes=[{'module': 'main', 'offset': 0, 'old': 1, 'new': new}]) + hook = {'kind': 'replace', 'site': 'main+0x0', 'original': '0x00000001', 'target': f'plugin0+{THUNK_OFF:#x}', + 'trampoline': f'plugin0+{TRAMP_OFF:#x}'} + with tempfile.TemporaryDirectory() as d: + (Path(d) / 'plugin0.img').write_bytes(rec['images']['plugin0']) + rec['modules'][2]['image'] = 'plugin0.img' + out = xp.plugin_lines(rec, [hook], 'mod_x', d, 'plugin0') + self.assertIn(f'expect mod_x main 0 00000001 {new:08x}', out) + self.assertFalse(any(x.startswith(('site', 'orig', 'seed', 'entry')) for x in out), out) + def test_call(self): new = b(MAIN + SITE_OFF, PLUGIN + THUNK_OFF, True) w = [{'module': 'main', 'offset': SITE_OFF, 'old': 0x94000010, 'new': new}] diff --git a/tools/exefs_plugins.py b/tools/exefs_plugins.py index 6e913bd2..1fceea2b 100644 --- a/tools/exefs_plugins.py +++ b/tools/exefs_plugins.py @@ -132,6 +132,14 @@ def u(v): return int(v, 16) if isinstance(v, str) else v +def header_site(h): + """The hook sits on main's module header, not on code. exlaunch adds a table offset to main's base, and a game + update the plugin's table lacks gives offset 0 (Challenge Mode's Enemy Health Regeneration names 1.0.0 to 1.4.1). + Nothing runs there, on the Switch either: the write is kept and checked, and the lift gets no site for it (its + first word, 1, decodes as a trap the generator refuses to patch).""" + return h['site'] == 'main+0x0' + + def ran_view(rec): """The record as seen from the plugins whose inits ran: a plugin that only stayed loaded (TOTK_PLUGIN_ONLY) counts as a module that is no plugin, so its exports and code are not checked as this record's. A record without "ran" @@ -621,6 +629,7 @@ def entries(rec, hooks, module): back there too.""" mods = {m['name']: m for m in rec['modules']} main, p = mods['main'], mods[module] + hooks = [h for h in hooks if not header_site(h)] # never run: no way back into main, no code to seed out = {int(h['site'].split('+')[1], 16) + 4 for h in hooks if h['kind'] == 'branch' or h['kind'] == 'replace' and not h.get('trampoline')} base, img = p['base'], rec['images'][module] @@ -667,6 +676,8 @@ def plugin_lines(rec, hooks, name, record_dir, module): for h in hooks: site = int(h['site'].split('+')[1], 16) + if header_site(h): + continue if h['kind'] == 'inline': sm, so = at(h['stub']) stubs.setdefault(sm, set()).add(so) @@ -853,6 +864,9 @@ def report(rec, label, game=frozenset()): else: print(f' {h["kind"]} {h["site"]} (was {h["original"]}) -> {"bl" if h["kind"] == "call" else "b"} ' f'{h["target"]}' + (f', Orig trampoline {h["trampoline"]}' if h.get('trampoline') else '')) + if header_site(h): + print(f' note: {h["site"]} is main\'s module header, not code: the plugin has no address for this game ' + f'update there, and this hook does nothing, as on the Switch') for r in reasons: print(f' REFUSED: {r}') if not reasons: From 4fccaa5bef88bf4a2d2e179d7dc4c42c51d9cc54 Mon Sep 17 00:00:00 2001 From: Valiantsin Dzerakh Date: Wed, 25 Nov 2026 21:19:50 +0300 Subject: [PATCH 4/6] Each exlaunch inline stub a plugin writes back to back at init is a lift entry, with its callback (#1388, #1451) Zonai Fieldworks writes one stub per member hook in a row at init and points a gate slot at it when the player switches the member on. init_code took only the first stub of the row as a start and read the 8-byte callback after it as more code, so the other stubs (Hookshot at plugin2+0x135048, Fleet Sync at plugin2+0x1350f0) were never lifted and switching them on ended the game with "no function at guest pc". Co-Authored-By: Claude Opus 5.5 --- tests/exefs_plugins_test.py | 16 ++++++++++++++++ tools/exefs_plugins.py | 22 +++++++++++++++++++--- 2 files changed, 35 insertions(+), 3 deletions(-) diff --git a/tests/exefs_plugins_test.py b/tests/exefs_plugins_test.py index 6a891929..d9587806 100644 --- a/tests/exefs_plugins_test.py +++ b/tests/exefs_plugins_test.py @@ -603,6 +603,22 @@ class Lines(unittest.TestCase): self.assertIn(f'orig mod_x plugin0 {TRAMP_OFF:x} main {SITE_OFF:x}', out) self.assertIn(f'seed plugin0 {THUNK_OFF:x}', out) + def test_stubs_written_back_to_back_are_each_a_start(self): + # Zonai Fieldworks writes an inline-hook stub per member hook at init, back to back; a member switched on at + # play points its gate at one (1.4.3 plugin+0x135048, the 4th). The .quad callback after each stub is data. + rec = record() + img, row = bytearray(rec['images']['plugin0']), 0x8000 + for k in range(3): + at = row + 0x18 * k + struct.pack_into('<4IQ', img, at, xp.STUR_X30, b(PLUGIN + at + 4, PLUGIN + IMPL_OFF, True), xp.LDUR_X30, + b(PLUGIN + at + 12, PLUGIN + TRAMP_OFF), PLUGIN + CB_OFF) + rec['images']['plugin0'] = bytes(img) + pre = bytearray(img) + pre[row:row + 0x48] = bytes(0x48) + rec['pre_images'] = {'plugin0': bytes(pre)} + starts = xp.init_code(rec, [], 'plugin0') + self.assertEqual(starts, {PLUGIN + row, PLUGIN + row + 0x18, PLUGIN + row + 0x30, PLUGIN + CB_OFF}) + def test_hook_on_main_header_keeps_only_its_expect(self): # Challenge Mode's Enemy Health Regeneration on an update its table lacks: a replace hook at main+0x0, whose # word 1 is main's module header. The write is checked at start; the lift gets no site, orig or seed for it. diff --git a/tools/exefs_plugins.py b/tools/exefs_plugins.py index 1fceea2b..0de35e49 100644 --- a/tools/exefs_plugins.py +++ b/tools/exefs_plugins.py @@ -602,7 +602,12 @@ def init_code(rec, hooks, module): trampolines of its far hooks (the moved original words and a branch back). The plugin may point a veneer at any of them at play (Zonai Fieldworks turns its features' hooks on and off), so each is a root of the reach check and a seed of the lift. The trampolines of inline hooks (never run) and the Orig trampolines of replace hooks (the lift - serves them with the function's unpatched copy) are left out: their way back would split main's functions.""" + serves them with the function's unpatched copy) are left out: their way back would split main's functions. + + An exlaunch inline-hook stub the init writes (stur x30; bl impl; ldur x30; b trampoline; .quad callback) may be the + target of a hook the plugin turns on at play: Zonai Fieldworks writes one per member hook at init, back to back, + and a member switched on points its gate's pointer at it (the 4th of a row is plugin+0x135048 on 1.4.3). Each stub + and its callback are starts; the .quad is data, not code running on into the next stub.""" p = {m['name']: m for m in rec['modules']}[module] img, pre = rec['images'].get(module), rec.get('pre_images', {}).get(module) if img is None or pre is None: @@ -611,13 +616,24 @@ def init_code(rec, hooks, module): now, old = struct.unpack_from(f'<{n}I', img), struct.unpack_from(f'<{n}I', pre) known = {p['base'] + int(h['trampoline'].split('+')[1], 16) for h in hooks if (h.get('trampoline') or '').startswith(module + '+')} - out, inside = set(), False # inside: the word before is a written word that goes on to this one - for i in range(n): + text = range(p['base'], p['base'] + p['text_end']) + out, inside, i = set(), False, 0 # inside: the word before is a written word that goes on to this one + while i < n: new = old[i] == 0 and now[i] != 0 + if (new and i + 5 < n and now[i] == STUR_X30 and now[i + 1] & 0xFC000000 == 0x94000000 + and now[i + 2] == LDUR_X30 and now[i + 3] & 0xFC000000 == 0x14000000): + stub = p['base'] + 4 * i + callback = now[i + 4] | now[i + 5] << 32 + out.add(stub) + if callback in text: + out.add(callback) + inside, i = False, i + 6 + continue if new and not inside: out.add(p['base'] + 4 * i) # b, br, ret end a trampoline; one may follow right after inside = new and now[i] & 0xFC000000 != 0x14000000 and now[i] & 0xFFFFFC1F not in (0xD61F0000, 0xD65F0000) + i += 1 return out - known From fc2863a15c8bf321dde971c7c2ac3b8ed46b1b1d Mon Sep 17 00:00:00 2001 From: Valiantsin Dzerakh Date: Wed, 25 Nov 2026 21:23:19 +0300 Subject: [PATCH 5/6] nvnCommandBufferFenceSync is implemented: the sync waits for the fence of the submit that carries the record (#1388) Zonai Fieldworks' native-font renderer (Cryonis in its BotW Abilities member) records it, and the weak stub ended the game with "NVN nvnCommandBufferFenceSync is not implemented". The record is a new op, OP_FENCE_SYNC, that every replay skips; at QueueSubmitCommands the syncs named in the submitted handles get that submit's fence value, which completes no earlier than the console's point. The game itself never records the op, so its submits pay one flag load. Co-Authored-By: Claude Opus 5.5 --- runtime/nvn_api.h | 7 +++++++ runtime/nvn_api_cmd.c | 35 +++++++++++++++++++++++++++++++---- runtime/nvn_api_core.c | 11 ++++++++++- runtime/nvn_obj.h | 2 +- runtime/nvn_probe.c | 16 +++++++++++++++- runtime/vk_exec.c | 4 ++-- runtime/vk_exec_probe.c | 5 +++++ 7 files changed, 71 insertions(+), 9 deletions(-) diff --git a/runtime/nvn_api.h b/runtime/nvn_api.h index 09626c0b..9773f88c 100644 --- a/runtime/nvn_api.h +++ b/runtime/nvn_api.h @@ -72,6 +72,10 @@ void nvn_submit_prepare(const uint64_t *handles, int n); // weak no-op; the co // Asynchronous replay: as nvn_submit_prepare, writing the handles to replay to out (a clone where a still queued // submission uses the same recording with other deferred binds) void nvn_submit_prepare_async(const uint64_t *handles, uint64_t *out, int n); +// After the back end took a submission as fence value `fence`: every sync an OP_FENCE_SYNC of the game's handles names +// is fenced at that value. Returns at once while no recording ever held the op (the game records none; mod plugins do). +void nvn_submit_fence_syncs(const uint64_t *handles, int n, uint64_t fence); +void nvn_sync_fence(sync_t *s, uint64_t fence); // nvn_api_core.c: an initialized sync now waits for fence int gfx_replay_async(void); // 1: the back end replays submissions on its own thread uint64_t gfx_replayed_submits(void); // newest submit number (nvn_submit_count) replayed #define NVN_HANDLE_TEX(h) ((int)((h) & 0xfffff)) // combined texture handle = texture id | sampler id << 20 @@ -110,6 +114,9 @@ typedef struct { int32_t prim, itype; uint64_t ibuf, ind; } p_draw_idx_ind; typedef struct { uint64_t ind, caller; } p_dispatch_ind; // OP_DISPATCH_IND: ind = GPU address of the 3 group counts // OP_CLEAR_BUF: size bytes at addr filled with the 32-bit value in GPU order (ClearBuffer; ReportValue is a 4-byte one) typedef struct { uint64_t addr, size; uint32_t value, pad; } p_clear_buf; +// OP_FENCE_SYNC: CommandBufferFenceSync. The front end, not the replay, signals the sync: at the submit that carries +// the record it gets that submit's fence value (nvn_submit_fence_syncs). Every replay skips the record. +typedef struct { sync_t *sync; } p_fence_sync; _Static_assert(sizeof(p_signal_event) == 16 && sizeof(p_report_counter) == 16 && sizeof(p_copy_b2b) == 24 && sizeof(p_update_ub) == 16, "op payload layouts of hle_nvn.c"); static inline const op_hdr *nvn_op_first(uint64_t handle) { return (const op_hdr *)(uintptr_t)handle; } // OP_BEGIN diff --git a/runtime/nvn_api_cmd.c b/runtime/nvn_api_cmd.c index 5662b965..444de683 100644 --- a/runtime/nvn_api_cmd.c +++ b/runtime/nvn_api_cmd.c @@ -414,8 +414,9 @@ void nvn_pins_stats(uint64_t *live, uint64_t *freed) { // deferred: 0 unknown, 1 none, 2 some; pins: texture pins its ops name, counted in their refs; pin_v: those pins, in // record order, or NULL (then pin_refs walks the records); cap: bytes of the block from the large-block cache // (copy_block), 0 for a plain heap block; hw: the recording's command memory as the real driver counts it (set at -// EndRecording), what CopyCommands of it adds to nvnCommandBufferGetCommandMemoryUsed (inline_recording) -typedef struct { uint64_t magic, bytes, made_at, used_at, deferred, pins, cap, hw; const tex_t **pin_v; } copy_prefix; +// EndRecording), what CopyCommands of it adds to nvnCommandBufferGetCommandMemoryUsed (inline_recording); fsync: 1 when +// the records hold an OP_FENCE_SYNC (flatten_recording), which nvn_submit_fence_syncs signals at submit +typedef struct { uint64_t magic, bytes, made_at, used_at, deferred, pins, cap, hw, fsync; const tex_t **pin_v; } copy_prefix; _Static_assert(sizeof(copy_prefix) % 8 == 0, "records stay 8-byte aligned"); typedef struct { uintptr_t lo, hi; uint8_t *copy; } cmd_copy; typedef struct { cmd_copy *v; uint32_t n, cap; } copy_bucket; @@ -423,6 +424,7 @@ static PlatMutex copy_lock = PLAT_MUTEX_INIT; // guards the two maps, the cou static nvn_hmap copy_pages = {.klen = 8}; // page -> copy_bucket static nvn_hmap copy_live = {.klen = 8}; // handle -> copy_prefix of a live copy static uint64_t ncopies, copy_bytes, copies_made; +static int fence_sync_recorded; // 1 once nvnCommandBufferFenceSync recorded an op (never set by the game itself) // Asynchronous replay: copies released by the game, and per-submission clones, that a queued submission still reads. // Freed once gfx_replayed_submits() reaches their used_at. Empty with synchronous replay. static copy_prefix **zombies; @@ -598,6 +600,8 @@ static uint8_t *flatten_recording(const uint8_t *p, size_t n) { static __thread struct { const tex_t **v; uint64_t cap; } named; // the pins of this recording, reused uint64_t pins_named = 0; int listed = 1; // 0 after a failed growth: the copy goes without a list + // Looked for only once some recording held the op (fence_sync_recorded): the game's own recordings never do. + int find_fsync = __atomic_load_n(&fence_sync_recorded, __ATOMIC_RELAXED), fsync = 0; for (size_t at = 0;;) { // the records stay checked: a corrupt one stops here, not in the replay op_hdr h; memcpy(&h, p + at, sizeof h); @@ -616,6 +620,7 @@ static uint8_t *flatten_recording(const uint8_t *p, size_t n) { } if (k && listed) memcpy((void *)(named.v + pins_named), pinned, sizeof *pinned * (size_t)k); pins_named += (uint64_t)k; + fsync |= find_fsync && h.op == OP_FENCE_SYNC; at += h.size; if (h.op == OP_END) { if (at != n) rt_fatal("nvn: recording at %p ends at %zu of %zu bytes", (const void *)p, at, n); @@ -625,7 +630,8 @@ static uint8_t *flatten_recording(const uint8_t *p, size_t n) { const tex_t **pin_v = NULL; if (pins_named && listed && (pin_v = malloc(sizeof *pin_v * pins_named))) memcpy((void *)pin_v, (const void *)named.v, sizeof *pin_v * pins_named); - *block = (copy_prefix){.magic = COPY_MAGIC, .bytes = n, .pins = pins_named, .cap = block->cap, .pin_v = pin_v}; + *block = (copy_prefix){.magic = COPY_MAGIC, .bytes = n, .pins = pins_named, .cap = block->cap, .fsync = (uint64_t)fsync, + .pin_v = pin_v}; return out + sizeof(copy_prefix); } @@ -1260,6 +1266,15 @@ NVN_API(nvnCommandBufferWaitEvent) { (void)c; } NVN_API(nvnCommandBufferSetShaderScratchMemory) { (void)c; } NVN_API(nvnCommandBufferSetPatchSize) { (void)c; } +// void nvnCommandBufferFenceSync(NVNcommandBuffer *cmd, NVNsync *sync, NVNsyncCondition condition, int flags): the sync +// is signaled once the GPU ran every command before it. Here it is fenced at the value of the whole submit that carries +// the record (nvn_submit_fence_syncs), which completes no earlier than the console's point. The game never calls it; +// mod plugins do (Zonai Fieldworks' native-font renderer). +NVN_API(nvnCommandBufferFenceSync) { + __atomic_store_n(&fence_sync_recorded, 1, __ATOMIC_RELAXED); + REC(cmd_of(c), OP_FENCE_SYNC, p_fence_sync)->sync = arg_p(c, 1); +} + // ---------- submit // What the console reads at the submit call is read here, on the game thread: every handle must be a live recording, // and deferred binds take the handles the game's arrays hold now (the game fills its tables for the next frame as soon @@ -1353,6 +1368,18 @@ void nvn_submit_prepare_async(const uint64_t *handles, uint64_t *out, int n) { (unsigned long long)now, (unsigned long long)__atomic_load_n(&n_clones, __ATOMIC_RELAXED), nzombies); } +// The game's handles, not the per-submission clones of nvn_submit_prepare_async: a clone may be freed as soon as the +// replay is done with it, and the handles stay live while the game is in QueueSubmitCommands. Copies hold no OP_CALL +// or OP_JUMP (flatten_recording), so each is one run of records to OP_END. +void nvn_submit_fence_syncs(const uint64_t *handles, int n, uint64_t fence) { + if (!__atomic_load_n(&fence_sync_recorded, __ATOMIC_RELAXED)) return; + for (int i = 0; i < n; i++) { + if (!((const copy_prefix *)(uintptr_t)handles[i] - 1)->fsync) continue; + for (const op_hdr *h = nvn_op_first(handles[i]); h->op != OP_END; h = nvn_op_next(h)) + if (h->op == OP_FENCE_SYNC) nvn_sync_fence(((const p_fence_sync *)nvn_op_payload(h))->sync, fence); + } +} + uint64_t nvn_submit_count(void) { return __atomic_load_n(&nsubmits, __ATOMIC_RELAXED); } const char *nvn_op_name(uint32_t op) { @@ -1362,7 +1389,7 @@ const char *nvn_op_name(uint32_t op) { "BIND_VSTREAM", "BIND_VBUF", "BIND_UBO", "BIND_SSBO", "BIND_TEX", "BIND_SAMP", "STENCIL", "POLY_OFFSET", "DRAW", "DRAW_IDX", "DISPATCH", "BARRIER", "SET_TEX_POOL", "SET_SAMP_POOL", "COPY_B2T", "COPY_STRIDE", "BLEND_COLOR", "COPY_T2B", "BIND_IMG", "COPY_T2T", "RESET_COUNTER", "CLEAR_TEX", "DEPTH_CLAMP", "RENDER_ENABLE", - "RASTER_DISCARD", "RENDER_COND", "PRIM_RESTART", "DRAW_IDX_IND", "DISPATCH_IND", "CLEAR_BUF", + "RASTER_DISCARD", "RENDER_COND", "PRIM_RESTART", "DRAW_IDX_IND", "DISPATCH_IND", "CLEAR_BUF", "FENCE_SYNC", }; _Static_assert(sizeof names / sizeof *names == OP_COUNT_, "one name per op"); return op < OP_COUNT_ ? names[op] : "?"; diff --git a/runtime/nvn_api_core.c b/runtime/nvn_api_core.c index d1abf097..99ab4ade 100644 --- a/runtime/nvn_api_core.c +++ b/runtime/nvn_api_core.c @@ -463,7 +463,8 @@ NVN_API(nvnBufferFlushMappedRange) { } // ---------- Sync and events -// A sync is a fence value: fenced = 1 after QueueFenceSync (the newest submit), 3 after WindowAcquireTexture (fence 0). +// A sync is a fence value: fenced = 1 after QueueFenceSync (the newest submit) or the submit of a CommandBufferFenceSync +// record (that submit), 3 after WindowAcquireTexture (fence 0). // NVNboolean nvnSyncInitialize(NVNsync *s, NVNdevice *d) NVN_API(nvnSyncInitialize) { *(sync_t *)arg_p(c, 0) = (sync_t){SYNC_MAGIC, 0, 0}; @@ -478,6 +479,13 @@ NVN_API(nvnQueueFenceSync) { s->fenced = 1; s->fence = nvn_fence_last(); } +// CommandBufferFenceSync at its submit (nvn_api_cmd.c nvn_submit_fence_syncs): the value first, then fenced, so a +// thread that sees fenced waits for this value or a newer one. A sync finalized since the record is left alone. +void nvn_sync_fence(sync_t *s, uint64_t fence) { + if (!s || s->magic != SYNC_MAGIC) return; + __atomic_store_n(&s->fence, fence, __ATOMIC_RELAXED); + __atomic_store_n(&s->fenced, 1, __ATOMIC_RELEASE); +} // TOTK_SYNC_AHEAD=1: one more frame in flight. Each frame the game waits (one nvnSyncWait, frame_wait_lr) for // the frame it presented last; on the Switch that work is long done by then, here it is still in the replay and on the // GPU (about 11 ms from the submit), and the wait sets the frame time. With the switch on, that wait, and only that @@ -720,6 +728,7 @@ NVN_API(nvnQueueSubmitCommands) { nvn_submit_prepare(h, n); f = gfx_backend()->submit(h, n); } + nvn_submit_fence_syncs(h, n, f); // the syncs this submit's CommandBufferFenceSync records name wait for f uint64_t prev = __atomic_load_n(&last_fence, __ATOMIC_RELAXED); while (f > prev && !__atomic_compare_exchange_n(&last_fence, &prev, f, 1, __ATOMIC_RELEASE, __ATOMIC_RELAXED)) {} __atomic_store_n(&lod_fence[no % LOD_RING], f, __ATOMIC_RELAXED); diff --git a/runtime/nvn_obj.h b/runtime/nvn_obj.h index 7b81c6ec..7c8ba354 100644 --- a/runtime/nvn_obj.h +++ b/runtime/nvn_obj.h @@ -128,7 +128,7 @@ enum { OP_BIND_PROGRAM, OP_BIND_STATE, OP_BIND_VATTR, OP_BIND_VSTREAM, OP_BIND_VBUF, OP_BIND_UBO, OP_BIND_SSBO, OP_BIND_TEX, OP_BIND_SAMP, OP_STENCIL, OP_POLY_OFFSET, OP_DRAW, OP_DRAW_IDX, OP_DISPATCH, OP_BARRIER, - OP_SET_TEX_POOL, OP_SET_SAMP_POOL, OP_COPY_B2T, OP_COPY_STRIDE, OP_BLEND_COLOR, OP_COPY_T2B, OP_BIND_IMG, OP_COPY_T2T, OP_RESET_COUNTER, OP_CLEAR_TEX, OP_DEPTH_CLAMP, OP_RENDER_ENABLE, OP_RASTER_DISCARD, OP_RENDER_COND, OP_PRIM_RESTART, OP_DRAW_IDX_IND, OP_DISPATCH_IND, OP_CLEAR_BUF, OP_COUNT_ + OP_SET_TEX_POOL, OP_SET_SAMP_POOL, OP_COPY_B2T, OP_COPY_STRIDE, OP_BLEND_COLOR, OP_COPY_T2B, OP_BIND_IMG, OP_COPY_T2T, OP_RESET_COUNTER, OP_CLEAR_TEX, OP_DEPTH_CLAMP, OP_RENDER_ENABLE, OP_RASTER_DISCARD, OP_RENDER_COND, OP_PRIM_RESTART, OP_DRAW_IDX_IND, OP_DISPATCH_IND, OP_CLEAR_BUF, OP_FENCE_SYNC, OP_COUNT_ }; // Payload (immediately follows op_hdr) typedef struct { int32_t n; const tex_t *color[8]; view_t cview[8]; uint8_t has_cview[8]; const tex_t *depth; view_t dview; uint8_t has_dview; } p_set_rt; diff --git a/runtime/nvn_probe.c b/runtime/nvn_probe.c index 43107407..7b80b268 100644 --- a/runtime/nvn_probe.c +++ b/runtime/nvn_probe.c @@ -319,6 +319,7 @@ static void probe_samplers(void) { // ---- sync and events OBJ(NVNsync, syncs); OBJ(NVNsync, sync_future); +OBJ(NVNsync, sync_cmd); // CommandBufferFenceSync's sync (record_all, probe_null_effects) OBJ(NVNevent, ev); OBJ(NVNevent, ev2); OBJ(NVNeventBuilder, evb); @@ -326,6 +327,7 @@ OBJ(NVNeventBuilder, evb); static void probe_sync_events(void) { CHECK((uint8_t)CALL(nvnSyncInitialize, U(&syncs), U(&dev)) == 1, "SyncInitialize"); CHECK(CALL(nvnSyncWait, U(&syncs), 1000) == NVN_SYNC_WAIT_RESULT_TIMEOUT_EXPIRED, "a sync never fenced times out at once"); + CALL(nvnSyncInitialize, U(&sync_cmd), U(&dev)); CALL(nvnSyncInitialize, U(&sync_future), U(&dev)); sync_t *sf = (sync_t *)(void *)&sync_future; sf->fenced = 1; @@ -461,6 +463,7 @@ static uint64_t record_all(void) { CALL(nvnCommandBufferSetColorReductionEnable, U(c), 1); // hints: nothing recorded CALL(nvnCommandBufferSetColorReductionThresholds, U(c), 0, U(thresholds)); REC(OP_COPY_T2T, CALL(nvnCommandBufferDownsample, U(c), U(&tex1), U(&tex2))); + REC(OP_FENCE_SYNC, CALL(nvnCommandBufferFenceSync, U(c), U(&sync_cmd), NVN_SYNC_CONDITION_ALL_GPU_COMMANDS_COMPLETE, 0)); CHECK((uint8_t)CALL(nvnCommandBufferIsRecording, U(c)) == 1, "IsRecording while recording"); uint64_t h = CALL(nvnCommandBufferEndRecording, U(c)); CHECK((uint8_t)CALL(nvnCommandBufferIsRecording, U(c)) == 0, "IsRecording after EndRecording"); @@ -681,6 +684,7 @@ static void parse_all(uint64_t h) { (p->addr == 0xc300 && p->size == 4 && p->value == 0x1234), "CLEAR_BUF payload (ClearBuffer, ReportValue)"); break; } + case OP_FENCE_SYNC: CHECK(((const p_fence_sync *)a)->sync == (sync_t *)(void *)&sync_cmd, "FENCE_SYNC payload"); break; default: CHECK(0, "unexpected op %s", nvn_op_name(o->op)); break; } } @@ -815,6 +819,7 @@ static void probe_null_effects(void) { CALL(nvnCommandBufferUpdateUniformBuffer, U(c), gbase, 64, 8, 8, U(d2)); CALL(nvnCommandBufferDrawArrays, U(c), NVN_DRAW_PRIMITIVE_TRIANGLES, 0, 3); // ignored CALL(nvnCommandBufferBarrier, U(c), 1); + CALL(nvnCommandBufferFenceSync, U(c), U(&sync_cmd), NVN_SYNC_CONDITION_ALL_GPU_COMMANDS_COMPLETE, 0); uint64_t ha = CALL(nvnCommandBufferEndRecording, U(c)); begin(&cmd2, ctlmem2, 0x38000); @@ -824,6 +829,9 @@ static void probe_null_effects(void) { CHECK(*(uint32_t *)ev_val == 0 && !pmem[OFF_UB + 4] && !pmem[OFF_DST] && pmem[OFF_COUNTER_B] == 0xaa, "recording has no side effects"); + // record_all and the call that inlined it recorded a FenceSync of sync_cmd too, and neither was submitted + CHECK(CALL(nvnSyncWait, U(&sync_cmd), 1000) == NVN_SYNC_WAIT_RESULT_TIMEOUT_EXPIRED, + "a CommandBufferFenceSync recorded but not submitted leaves the sync unsignaled"); uint64_t t0 = rt_ticks(), subs = nvn_submit_count(), fence0 = nvn_fence_last(); uint64_t hs[2] = {ha, hb}; @@ -835,6 +843,12 @@ static void probe_null_effects(void) { (unsigned long long)wait); CHECK(nvn_submit_count() == subs + 1 && nvn_fence_last() == fence0 + 1 && gfx_backend()->fence_done() == nvn_fence_last(), "one submit advances the fence once (%llu -> %llu)", (unsigned long long)fence0, (unsigned long long)nvn_fence_last()); + const sync_t *sc = (const sync_t *)(const void *)&sync_cmd; + uint64_t wait_cmd = CALL(nvnSyncWait, U(&sync_cmd), 1000000000ull); + CHECK(sc->fenced == 1 && sc->fence == nvn_fence_last() && + (wait_cmd == NVN_SYNC_WAIT_RESULT_ALREADY_SIGNALED || wait_cmd == NVN_SYNC_WAIT_RESULT_CONDITION_SATISFIED), + "CommandBufferFenceSync: the submit fenced the sync at its value (fenced %u, fence %llu of %llu), SyncWait %llu", + sc->fenced, (unsigned long long)sc->fence, (unsigned long long)nvn_fence_last(), (unsigned long long)wait_cmd); // event: WRITE 0x11, ADD 5, then handle 2's WRITE 0x99 CHECK((uint32_t)CALL(nvnEventGetValue, U(&ev)) == 0x99, "event value %#x after the stream, expected 0x99", *(uint32_t *)ev_val); @@ -852,7 +866,7 @@ static void probe_null_effects(void) { CHECK(cb[0] == 0 && cb[1] + 1 >= t0 && cb[1] <= t1 + 1, "samples-passed counter {%llu, %llu}", (unsigned long long)cb[0], (unsigned long long)cb[1]); CHECK(!memcmp(pmem + OFF_B2B_DST, keep, 16), "a copy out of the GPU window left the target alone"); - n_effects = 6; + n_effects = 7; CALL(nvnCommandBufferFinalize, U(&cmd2)); CALL(nvnCommandBufferFinalize, U(&cmd)); diff --git a/runtime/vk_exec.c b/runtime/vk_exec.c index e971c92c..f54ba178 100644 --- a/runtime/vk_exec.c +++ b/runtime/vk_exec.c @@ -1175,7 +1175,7 @@ static int walk(VkExec *ex, const op_hdr *h, int depth, const op_hdr *stop) { if (ex->wpos_i < ex->wpos_end && ex->wpos[ex->wpos_i] == ex->pos) ex->drop_n++, ex->wpos_i++; } switch (h->op) { - case OP_BEGIN: break; + case OP_BEGIN: case OP_FENCE_SYNC: break; // FENCE_SYNC: the front end signals it at submit (p_fence_sync) case OP_JUMP: h = (const op_hdr *)(uintptr_t)((const p_jump *)a)->target; continue; case OP_CALL: if (depth >= CALL_DEPTH) rt_fatal("vk: command buffer calls nested deeper than %d", CALL_DEPTH); @@ -1749,7 +1749,7 @@ static void scan(VkExec *s, int hi, const op_hdr *h, int depth) { if (vk_exec_xfer_revive(h->op, a, s->pos)) scan_hold(HOLD_TEX); SC.open = 0; break; - case OP_SIGNAL_EVENT: break; + case OP_SIGNAL_EVENT: case OP_FENCE_SYNC: break; case OP_RENDER_COND: SC.cond[SC.ncond++] = (uint8_t)vk_exec_xfer_scan(s, h->op, a); break; case OP_REPORT_COUNTER: case OP_RESET_COUNTER: case OP_RENDER_ENABLE: vk_exec_xfer_scan(s, h->op, a); break; default: state_op(s, h->op, a); // walk stops on an op without a handler diff --git a/runtime/vk_exec_probe.c b/runtime/vk_exec_probe.c index 37db3fba..e28571d9 100644 --- a/runtime/vk_exec_probe.c +++ b/runtime/vk_exec_probe.c @@ -758,6 +758,10 @@ static int test_xfer(const GfxBackend *b, uint8_t *guest, int *bytes) { p = put(p, OP_CLEAR_TEX, &ct, sizeof ct); const p_signal_event ev1 = {event, NVN_EVENT_SIGNAL_MODE_WRITE, 7}, ev2 = {event, NVN_EVENT_SIGNAL_MODE_ADD, 5}; p = put(p, OP_SIGNAL_EVENT, &ev1, sizeof ev1); + // CommandBufferFenceSync's record: the replay passes over it (the front end signals the sync at submit) + static sync_t fs_sync; + const p_fence_sync fs = {&fs_sync}; + p = put(p, OP_FENCE_SYNC, &fs, sizeof fs); p = put(p, OP_SIGNAL_EVENT, &ev2, sizeof ev2); const p_report_counter rc = {NVN_COUNTER_TYPE_TIMESTAMP, (uint64_t)(uintptr_t)ctr}; p = put(p, OP_REPORT_COUNTER, &rc, sizeof rc); @@ -786,6 +790,7 @@ static int test_xfer(const GfxBackend *b, uint8_t *guest, int *bytes) { memcpy(&clv, cl, 4); for (int i = 0; i < XF_W * XF_H; i++) CHECK(px[i] == clv, "CLEAR_TEX texel %d is %08x, expected %08x", i, px[i], clv); CHECK(*event == 12, "event word is %u after WRITE 7 and ADD 5", *event); + CHECK(!fs_sync.fenced && !fs_sync.fence, "the replay left the FENCE_SYNC record's sync alone"); CHECK(ctr->counter == 0 && ctr->timestamp != 0, "counter report is {%llu, %llu}", (unsigned long long)ctr->counter, (unsigned long long)ctr->timestamp); CHECK(sp->counter == 0 && sp->timestamp != 0, "samples-passed report after a reset and no draw is {%llu, %llu}", From 9cf4d060d1d9e4fd261b987e79e6e000f1539548 Mon Sep 17 00:00:00 2001 From: Valiantsin Dzerakh Date: Wed, 25 Nov 2026 22:11:19 +0300 Subject: [PATCH 6/6] A plugin loop that spins on a yield with no call in its body gets a spin line, so its back-edges go through rt_spin_gate and hand the virtual core to a waiting thread (#1388) Zonai Fieldworks guards its hook wrappers with an exclusive byte lock (plugin+0xe3ff4 on 1.4.3). On the Switch the holder has its own core; here a spinner kept the virtual core the holder waited for, and the game froze when a member was switched off. exefs_plugins.py now finds such loops by word (a direct back-edge of at most 512 bytes to a head whose body holds a yield and no bl, blr or svc): 21 in Fieldworks. Co-Authored-By: Claude Opus 5.5 --- tests/exefs_plugins_test.py | 11 +++++++++++ tools/exefs_plugins.py | 30 ++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/tests/exefs_plugins_test.py b/tests/exefs_plugins_test.py index d9587806..91f1c942 100644 --- a/tests/exefs_plugins_test.py +++ b/tests/exefs_plugins_test.py @@ -619,6 +619,17 @@ class Lines(unittest.TestCase): starts = xp.init_code(rec, [], 'plugin0') self.assertEqual(starts, {PLUGIN + row, PLUGIN + row + 0x18, PLUGIN + row + 0x30, PLUGIN + CB_OFF}) + def test_yield_loops_are_spin_waits(self): + # Zonai Fieldworks' hook wrapper takes a byte lock (plugin+0xe3ff4 on 1.4.3): yield; ldaxrb; stxrb; cbnz; tbnz + # back to the yield. A loop with a yield and a call in it, or a back branch with no yield, is no spin wait. + ldaxrb, stxrb = 0x085FFC40, 0x08037C41 + words = [xp.NOP] * 64 + words[1:6] = [xp.YIELD, ldaxrb, stxrb, 0x35FFFFC3, 0x3707FF80] # cbnz w3, -8; tbnz w0, #0, -16 + words[10:14] = [xp.YIELD, 0x94000100, xp.NOP, 0x17FFFFFD] # yield; bl; nop; b -12 + words[20:23] = [xp.NOP, xp.NOP, 0x17FFFFFE] # b -8 + img = struct.pack('<64I', *words) + self.assertEqual(xp.yield_spins(img, len(img)), {4: [20]}) + def test_hook_on_main_header_keeps_only_its_expect(self): # Challenge Mode's Enemy Health Regeneration on an update its table lacks: a replace hook at main+0x0, whose # word 1 is main's module header. The write is checked at start; the lift gets no site, orig or seed for it. diff --git a/tools/exefs_plugins.py b/tools/exefs_plugins.py index 0de35e49..392cc7fc 100644 --- a/tools/exefs_plugins.py +++ b/tools/exefs_plugins.py @@ -206,6 +206,8 @@ def relocated(orig, site, word, at): # hook's site calls the stub and runs main's own original after it, recomp/patches.py @call; a replace hook's Orig # reaches an unpatched copy of the function, `orig`), so these forms only tell an exlaunch hook from other code. NOP = 0xD503201F +YIELD = 0xD503203F +SPIN_WIN = 512 # bytes from a spin wait's back-edge back to its head (tools/spin_waits.py SPIN_WIN) LDR_X17_8 = 0x58000051 # ldr x17, #8 LDR_X17_12 = 0x58000071 # ldr x17, #12 ADR_X30_16 = 0x1000009E # adr x30, #16 @@ -637,6 +639,32 @@ def init_code(rec, hooks, module): return out - known +def yield_spins(img, text_end): + """{loop head offset: [back-edge offsets]} of the plugin's spin waits: a direct branch back at most SPIN_WIN bytes + to a head whose loop body holds a `yield` and no call or SVC; the yield is the hint code puts in a loop that waits + for another thread (an exclusive + byte lock in Zonai Fieldworks' hook wrappers, plugin+0xe3ff4 on 1.4.3). On the Switch the lock holder runs on its own + core; here both hold one of the three virtual cores (runtime/kernel.c), and a holder preempted for the spinner + waits for that core while the spinner, which makes no SVC, keeps it: the game froze when Zonai Fieldworks turned a + member off. A `spin` line sends each back-edge through rt_spin_gate, which hands the core to a waiting thread + (tools/spin_waits.py finds the game's own waits; the installer has no disassembler, so this test is by word).""" + n = text_end // 4 + words = struct.unpack_from(f'<{n}I', img) + out = {} + for j, w in enumerate(words): + pr = pc_relative(w, 4 * j) + if pr is None or pr[0][0] not in ('b', 'b.cond', 'cbz', 'tbz') or w & 0xFC000000 == 0x94000000: + continue + head = pr[1] + if not 4 * j - SPIN_WIN <= head <= 4 * j or head % 4: + continue + body = words[head // 4:j] + if YIELD in body and not any(x & 0x7C000000 == 0x14000000 and x >> 31 or x & 0xFFFFFC1F == 0xD63F0000 + or x & 0xFFE0001F == 0xD4000001 for x in body): # bl, blr, svc: a call + out.setdefault(head, []).append(4 * j) + return out + + def entries(rec, hooks, module): """(main offsets, plugin offsets): where module's hook code comes back into main's .text, which the lift makes function starts (recomp/patches.py `entry`), and the code its veneers lead to, seeds of its lift. The site + 4 of a @@ -724,6 +752,8 @@ def plugin_lines(rec, hooks, name, record_dir, module): lines.append(f'seed {m} ' + ' '.join(f'{o:x}' for o in sorted(seeds[m]))) if back: lines.append('entry main ' + ' '.join(f'{o:x}' for o in back)) + for head, edges in sorted(yield_spins(img, p['text_end']).items()): + lines.append(f'spin {module} {head:x} ' + ' '.join(f'{b:x}' for b in edges) + ' # a loop with a yield') return lines