Merge task/plugself: Zonai Fieldworks switches its members on and off in play without a crash or freeze, and Challenge Mode's plugins that call their own functions build in (#1388, #1451, #1422, #1461)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Valiantsin DzerakhandClaude Opus 5.5 committed 2026-11-25 22:12:09 +03:00
commit a81324ce51
14 files changed
+232 -19

No files matched your search

+3 -1
View File
@@ -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
+2
View File
@@ -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
+7 -1
View File
@@ -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<const char*>
// 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};
+11 -3
View File
@@ -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;
}
+7
View File
@@ -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
+31 -4
View File
@@ -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] : "?";
+10 -1
View File
@@ -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);
+1 -1
View File
@@ -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;
+15 -1
View File
@@ -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));
+1
View File
@@ -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
+2 -2
View File
@@ -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
+5
View File
@@ -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}",
+61
View File
@@ -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('<II', img, 0x100, SVC_40, RET_W)
svcs, imports, _, _, _ = xp.reach(bytes(img), self.BASE, 0x200, [self.BASE],
{self.BASE + 0x80: self.BASE + 0x100})
self.assertEqual((svcs, imports), ({0x40}, {}))
def test_plt_slot_of_own_symbol_maps_to_its_code(self):
# Two PLT stubs (adrp x16, page 0; ldr x17, [x16, #slot]; add x16, x16, #slot; br x17) over GOT slots 0x180
# and 0x188: the first binds an import, the second a symbol the plugin defines at +0x40.
def stub(slot):
return [0x90000010, 0xF9400211 | (slot // 8) << 10, 0x91000210 | slot << 10, 0xD61F0220]
img = code(stub(0x180) + stub(0x188))
nso = mock.Mock(relocs=[(0x180, xp.R_AARCH64_JUMP_SLOT, 1, 0), (0x188, xp.R_AARCH64_JUMP_SLOT, 2, 0)],
syms=[('', 0, 0, 0, 0), ('malloc', 0x12, 0, 0, 0),
('_ZNSt6vectorIPKcSaIS1_EEC1ESt16initializer_listIS1_ERKS2_', 0x22, 7, 0x40, 8)])
self.assertEqual(xp.plt_imports(nso, img, self.BASE, 0x200),
{self.BASE: 'malloc', self.BASE + 0x10: self.BASE + 0x40})
def test_stub_returns_at_its_trampoline_branch(self):
# stur; bl impl; ldur; b trampoline (where an svc sits): the b is the stub's return
stub = [xp.STUR_X30, b(self.BASE + 4, self.BASE + 0x40, True), xp.LDUR_X30, b(self.BASE + 12, self.BASE + 0x100)]
@@ -583,6 +603,47 @@ 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_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.
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}]
+76 -5
View File
@@ -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"
@@ -198,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
@@ -457,8 +467,15 @@ def check_record(rec, impls, game=frozenset()):
# ---- the code the hooks reach
def plt_imports(nso, img, base, text_end):
"""{absolute address of a PLT stub: the import its GOT slot binds} (adrp x16; ldr x17, [x16, #slot]; add x16, x16,
#slot; br x17), from the JUMP_SLOT relocations."""
slots = {off: nso.syms[sym][0] for off, typ, sym, _ in nso.relocs if typ == R_AARCH64_JUMP_SLOT}
#slot; br x17), from the JUMP_SLOT relocations. A slot whose symbol the plugin defines itself binds to that
definition (runtime/loader.c resolve), so its stub maps to the absolute address of the plugin's own code instead of
a name: a plugin built with default visibility calls its own exported functions through its PLT (the
std::vector<const char*> 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 +516,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:
@@ -583,7 +604,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:
@@ -592,16 +618,53 @@ 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
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
@@ -610,6 +673,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]
@@ -656,6 +720,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)
@@ -686,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
@@ -842,6 +910,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: