mirror of
https://github.com/valentderah/totk-pc-recomp.git
synced 2026-11-25 14:05:57 +00:00
A plugin's write into main's data that points at no plugin code is matched by place only at start (#1437, #1388)
The expect line of such a word says `* *` (tools/exefs_plugins.py plugin_lines), recomp/patches.py carries it into RT_PLUGIN_WRITES as a flag, and runtime/plugin_init.c check_writes accepts any value there through runtime/plugin_writes.h plugin_write_find. Hook branches in .text and pointers into a plugin's .text keep the exact match. Zonai Fieldworks' Self Recall takes its storage off a pool size at main+0x3ad6eb8 that grows with the texture heap of render_scale, so its plugin went off at every start with a grown heap. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
7da078d1ab
commit
cc749d8679
6 files changed
+139
-25
No files matched your search
+4
-2
@@ -112,8 +112,10 @@ ahead of time, after the design in [#845](https://github.com/valentderah/totk-pc
|
||||
reason, and the other plugins are built in.
|
||||
2. At every start each plugin's start-up runs again, before the game's own start-up code, in the same setting: it
|
||||
sees the game's own instructions, as in its service run. Its redirects are compared with the record of the
|
||||
rebuild. When they match, the mod's code sites go on. When they do not, the plugin stays off for this run, the
|
||||
mod's row says why, and the next start runs the rebuild.
|
||||
rebuild. A value it writes into the game's data that redirects nothing (a size, a counter) only has to land at
|
||||
the recorded place, since the game may hold another value there at this start, for example a memory pool that
|
||||
grows with `render_scale`. When they match, the mod's code sites go on. When they do not, the plugin stays off for
|
||||
this run, the mod's row says why, and the next start runs the rebuild, which runs the plugin's service run again.
|
||||
3. The plugin keeps what its start-up made (its memory, its tables), so its code works as on the Switch. The start
|
||||
costs about 50 ms per plugin; the game runs no differently without a plugin.
|
||||
4. Removing a plugin mod from the mods folder starts the rebuild at the next start, which builds the game without
|
||||
|
||||
+13
-6
@@ -60,7 +60,8 @@ run's record; the design follows #845 by itaskaev2):
|
||||
sha256> is that .text's hash: the runtime compares it with the .text its own run of the init leaves, and keeps the
|
||||
set off when they differ.
|
||||
- `expect`: one word the init writes into a game module (the hook branches into main's .text); the runtime compares
|
||||
the words its run of the init wrote with these, all or nothing per plugin.
|
||||
the words its run of the init wrote with these, all or nothing per plugin. `*` for <old> and <new> matches the word
|
||||
by place only: a word of main's .data or .bss that shapes no lifted code and may differ at play.
|
||||
- `stub`: an exlaunch inline-hook entry stub (stur x30; bl impl; ldur x30; b trampoline; .quad callback). Its fourth
|
||||
word is lifted as a `ret`: the generated site calls the stub and runs its own original instruction after it
|
||||
(`@call` below), so the trampoline (the original relocated, b site+4) never runs.
|
||||
@@ -119,7 +120,8 @@ class Table:
|
||||
self.spins = spins or {} # {module: {back-edge offset: head offset}}
|
||||
self.hooks = hooks or {} # {module: {function offset}}; empty: FN_ENTER in every function
|
||||
self.ordered = set(ordered)
|
||||
# {module: {'set', 'sha256', 'image', 'expect': [(module, offset, old, new)], 'stubs': {offset},
|
||||
# {module: {'set', 'sha256', 'image', 'expect': [(module, offset, old, new)] (old and new None for `* *`),
|
||||
# 'stubs': {offset},
|
||||
# 'seeds': {offset}, 'origs': {trampoline offset: (function module, function offset)}}}; empty without
|
||||
# plugin lines
|
||||
self.plugins = plugins or {}
|
||||
@@ -296,7 +298,10 @@ def plugin_line(f, where, index, bases, plugins):
|
||||
owner = [p for p in plugins.values() if p['set'] == index[f[1]]]
|
||||
if not owner:
|
||||
raise PatchError(f'{where}: set {f[1]} owns no plugin')
|
||||
owner[0]['expect'].append((f[2], int(f[3], 16), int(f[4], 16), int(f[5], 16)))
|
||||
if (f[4] == '*') != (f[5] == '*'):
|
||||
raise PatchError(f'{where}: `*` for one of old and new only')
|
||||
words = (None, None) if f[4] == '*' else (int(f[4], 16), int(f[5], 16))
|
||||
owner[0]['expect'].append((f[2], int(f[3], 16), *words))
|
||||
elif f[0] == 'stub' and len(f) == 3:
|
||||
plugin(f[1])['stubs'].add(int(f[2], 16))
|
||||
elif f[0] == 'seed' and len(f) >= 3:
|
||||
@@ -345,14 +350,16 @@ def header_text(table, marker):
|
||||
enumerate(table.sets)), '']
|
||||
if table.plugins: # none: the header is what it was before plugins
|
||||
names = sorted(table.plugins)
|
||||
writes = [f'X({i}, "{m}", {o:#x}, {old:#010x}u, {new:#010x}u)' for i, n in enumerate(names)
|
||||
for m, o, old, new in sorted(table.plugins[n]['expect'])]
|
||||
writes = [f'X({i}, "{m}", {o:#x}, {old or 0:#010x}u, {new or 0:#010x}u, {int(old is None)})'
|
||||
for i, n in enumerate(names)
|
||||
for m, o, old, new in sorted(table.plugins[n]['expect'], key=lambda e: e[:2])]
|
||||
lines += [f'#define RT_PLUGIN_COUNT {len(names)}',
|
||||
'// X(index, module, its set, SHA-256 of its .text after the init)',
|
||||
'#define RT_PLUGINS(X) ' + ' '.join(f'X({i}, "{n}", {table.plugins[n]["set"]}, '
|
||||
f'"{table.plugins[n]["sha256"]}")' for i, n in enumerate(names)),
|
||||
f'#define RT_PLUGIN_WRITE_COUNT {len(writes)}',
|
||||
'// X(plugin index, module, offset, old word, new word): what the init writes into game modules',
|
||||
'// X(plugin index, module, offset, old word, new word, 1: any words, matched by place only): what '
|
||||
'the init writes into game modules',
|
||||
'#define RT_PLUGIN_WRITES(X) ' + ' '.join(writes),
|
||||
'// X(module, offset): the hook entries (seed lines) TOTK_PLUGIN_TRACE counts (runtime/plugin_init.c)',
|
||||
'#define RT_PLUGIN_ROOTS(X) ' + ' '.join(f'X("{n}", {o:#x})' for n in names
|
||||
|
||||
+8
-13
@@ -62,6 +62,7 @@
|
||||
#include "kernel.h"
|
||||
#include "mods.h"
|
||||
#include "platform/platform.h"
|
||||
#include "plugin_writes.h"
|
||||
|
||||
#if __has_include("patches.h")
|
||||
#include "patches.h"
|
||||
@@ -523,11 +524,7 @@ static const struct { const char *module; int set; const char *sha256; } plugin_
|
||||
RT_PLUGINS(X)
|
||||
#undef X
|
||||
};
|
||||
static const struct { int plugin; const char *module; uint64_t off; uint32_t old, now; } write_tab[] = {
|
||||
#define X(p, mod, off, old, now) {p, mod, off, old, now},
|
||||
RT_PLUGIN_WRITES(X)
|
||||
#undef X
|
||||
};
|
||||
static const PluginWrite write_tab[] = {RT_PLUGIN_WRITES(PLUGIN_WRITE)};
|
||||
#define NWRITES ((int)(sizeof write_tab / sizeof *write_tab))
|
||||
#ifdef RT_PLUGIN_ROOTS
|
||||
static const struct { const char *module; uint64_t off; } root_tab[] = {
|
||||
@@ -590,7 +587,9 @@ static void restore_page(const RtLoaded *m, uint64_t off, const uint8_t *was) {
|
||||
}
|
||||
|
||||
// After plugin i's init: what it wrote into the game modules, word by word, against the record of the build (its
|
||||
// entries of RT_PLUGIN_WRITES). The first difference goes into why (unless a reason is there already). Then the game
|
||||
// entries of RT_PLUGIN_WRITES, plugin_writes.h plugin_write_find). A recorded word the init did not change counts as
|
||||
// missing, unless the record takes any value there (the init may have written the value the word held). The first
|
||||
// difference goes into why (unless a reason is there already). Then the game
|
||||
// modules are made what they were before the init: the sealed part (.text, .rodata) gets the game's bytes back, a
|
||||
// write elsewhere stays and goes into pre, so the next plugin's init is compared only with what it writes itself.
|
||||
// The aliases this init mapped (from first_alias on) are flushed first; an earlier init's were flushed after it.
|
||||
@@ -612,12 +611,8 @@ static void check_writes(int plugin, int first_alias, char *why, size_t cap) {
|
||||
memcpy(&a, pre[i] + w, 4);
|
||||
memcpy(&b, now + w, 4);
|
||||
if (a == b) continue;
|
||||
int k = 0;
|
||||
while (k < NWRITES && !(write_tab[k].plugin == plugin && write_tab[k].off == w &&
|
||||
!strcmp(write_tab[k].module, m->name) && write_tab[k].old == a &&
|
||||
write_tab[k].now == b))
|
||||
k++;
|
||||
if (k < NWRITES) {
|
||||
int k = plugin_write_find(write_tab, NWRITES, plugin, m->name, w, a, b);
|
||||
if (k >= 0) {
|
||||
seen[k] = 1;
|
||||
} else if (!unexpected++) {
|
||||
snprintf(first, sizeof first, "%s+%#llx %08x -> %08x", m->name, (unsigned long long)w, a, b);
|
||||
@@ -627,7 +622,7 @@ static void check_writes(int plugin, int first_alias, char *why, size_t cap) {
|
||||
else memcpy(pre[i] + off, now + off, PAGE);
|
||||
}
|
||||
}
|
||||
for (int k = 0; k < NWRITES; k++) missing += write_tab[k].plugin == plugin && !seen[k];
|
||||
for (int k = 0; k < NWRITES; k++) missing += write_tab[k].plugin == plugin && !seen[k] && !write_tab[k].any;
|
||||
if (why[0]) return;
|
||||
if (unexpected)
|
||||
snprintf(why, cap, "its init wrote %d words the build did not record (first %s)", unexpected, first);
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
// The build's record of what a mod plugin's init writes into the game modules (patches.h RT_PLUGIN_WRITES, from the
|
||||
// `expect` lines of recomp/patches.py), and the lookup plugin_init.c check_writes makes for every word an init changed
|
||||
// at the start of the game.
|
||||
#pragma once
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
|
||||
// any: the expect line said `* *`, a word of main's .data or .bss that shapes no lifted code (tools/exefs_plugins.py
|
||||
// plugin_lines). The game may hold another value there at play than in the service run (Zonai Fieldworks' Self Recall
|
||||
// takes its storage off a pool size that grows with the resolution's texture heap), so it matches by place only. A
|
||||
// hook branch in .text and a pointer into a plugin's .text match by place and both words.
|
||||
typedef struct {
|
||||
int plugin;
|
||||
const char *module;
|
||||
uint64_t off;
|
||||
uint32_t old, now;
|
||||
int any;
|
||||
} PluginWrite;
|
||||
|
||||
// The X of RT_PLUGIN_WRITES for a table of PluginWrite.
|
||||
#define PLUGIN_WRITE(p, mod, off, old, now, any) {p, mod, off, old, now, any},
|
||||
|
||||
// The index of the entry of plugin that records the write of module+off from old to now, or -1.
|
||||
static inline int plugin_write_find(const PluginWrite *tab, int n, int plugin, const char *module, uint64_t off,
|
||||
uint32_t old, uint32_t now) {
|
||||
for (int k = 0; k < n; k++)
|
||||
if (tab[k].plugin == plugin && tab[k].off == off && !strcmp(tab[k].module, module) &&
|
||||
(tab[k].any || (tab[k].old == old && tab[k].now == now)))
|
||||
return k;
|
||||
return -1;
|
||||
}
|
||||
@@ -9,6 +9,8 @@ Run with .venv (lz4 and numpy, as recomp/): python tests/exefs_plugins_test.py
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
@@ -588,6 +590,27 @@ class Lines(unittest.TestCase):
|
||||
self.assertIn(f'site mod_x main {SITE_OFF:x} 94000010 {new:08x}', out)
|
||||
self.assertFalse(any(x.startswith(('orig', 'stub')) for x in out))
|
||||
|
||||
def test_data_word_matches_by_place(self):
|
||||
# Zonai Fieldworks' Self Recall takes its storage off a pool size in main's .bss (1.4.3 main+0x3ad6eb8): the
|
||||
# service run recorded 84800000 -> 7f1c0000, a start whose resolution grew the texture heap has
|
||||
# 87a00000 -> 823c0000 there. The word shapes no lifted code, so its expect line takes any value.
|
||||
rec = record(writes=[{'module': 'main', 'offset': 0x3ad6eb8, 'old': 0x84800000, 'new': 0x7F1C0000}])
|
||||
rec['modules'][0]['size'] = 0x3adf000
|
||||
out = self.lines(rec)
|
||||
self.assertIn('expect mod_x main 3ad6eb8 * *', out)
|
||||
self.assertFalse(any('84800000' in x or '7f1c0000' in x for x in out), out)
|
||||
|
||||
def test_pointer_swap_keeps_its_words(self):
|
||||
# a table entry that now points at a plugin function is a seed of the lift: both its words stay exact
|
||||
new = PLUGIN + THUNK_OFF
|
||||
w = [{'module': 'main', 'offset': 0x180010, 'old': 0x00001000, 'new': new & 0xFFFFFFFF},
|
||||
{'module': 'main', 'offset': 0x180014, 'old': 0, 'new': new >> 32},
|
||||
{'module': 'main', 'offset': 0x180020, 'old': 5, 'new': 6}]
|
||||
out = self.lines(record(writes=w))
|
||||
self.assertIn(f'expect mod_x main 180010 00001000 {new & 0xFFFFFFFF:08x}', out)
|
||||
self.assertIn(f'expect mod_x main 180014 00000000 {new >> 32:08x}', out)
|
||||
self.assertIn('expect mod_x main 180020 * *', out)
|
||||
|
||||
|
||||
# ---- one service run per plugin
|
||||
class PerPlugin(unittest.TestCase):
|
||||
@@ -691,6 +714,10 @@ def code_nso(words_at, size_text=0x5000):
|
||||
|
||||
|
||||
FN = 0x100 # the hooked main function: mov x19, x0; mov x0, x19; ret
|
||||
MSYS_BIN = Path(r'C:\msys64\ucrt64\bin') # clang for the start-up lookup below, as tests/flags_check.py
|
||||
CC = (str(MSYS_BIN / 'clang.exe') if os.name == 'nt' and (MSYS_BIN / 'clang.exe').exists() else
|
||||
os.environ.get('CC') or shutil.which('clang'))
|
||||
CC_ENV = dict(os.environ, PATH=str(MSYS_BIN) + os.pathsep + os.environ.get('PATH', '')) if os.name == 'nt' else None
|
||||
|
||||
|
||||
class Generator(unittest.TestCase):
|
||||
@@ -767,9 +794,22 @@ class Generator(unittest.TestCase):
|
||||
self.assertIn(f'void f_{stub:x}(Cpu *c);', c)
|
||||
h = patches.header_text(t, 'MARK')
|
||||
self.assertIn('#define RT_PLUGIN_COUNT 1', h)
|
||||
self.assertIn(f'X(0, "main", {FN:#x}, 0xaa0003f3u, 0x14000000u)', h)
|
||||
self.assertIn(f'X(0, "main", {FN:#x}, 0xaa0003f3u, 0x14000000u, 0)', h)
|
||||
self.assertIn('X("plugin0", 0x4100) X("plugin0", 0x4200)', h)
|
||||
|
||||
def test_any_value_expect_line(self):
|
||||
# `*` for both words: runtime/plugin_init.c check_writes matches the word by place only
|
||||
t = self.table(f'site mod_x main {FN:x} aa0003f3 @call:plugin0+4000 aa0003f3',
|
||||
['stub plugin0 4000', 'expect mod_x main 3ad6eb8 * *'])
|
||||
self.assertIn(('main', 0x3ad6eb8, None, None), t.plugins['plugin0']['expect'])
|
||||
h = patches.header_text(t, 'MARK')
|
||||
self.assertIn('X(0, "main", 0x3ad6eb8, 0x00000000u, 0x00000000u, 1)', h)
|
||||
self.assertIn(f'X(0, "main", {FN:#x}, 0xaa0003f3u, 0x14000000u, 0)', h)
|
||||
for half in ('* 7f1c0000', '84800000 *'):
|
||||
with self.subTest(half=half), self.assertRaises(patches.PatchError):
|
||||
self.table(f'site mod_x main {FN:x} aa0003f3 @call:plugin0+4000 aa0003f3',
|
||||
['stub plugin0 4000', f'expect mod_x main 3ad6eb8 {half}'])
|
||||
|
||||
# exlaunch's hook impl saves no NZCV: flags pass from the site to the callback and back (recomp/flags.py)
|
||||
def code(self, main_words, plugin_words=None):
|
||||
"""Main's hooked function and the plugin image's words replaced; the plugin hash follows."""
|
||||
@@ -882,6 +922,34 @@ class Generator(unittest.TestCase):
|
||||
capture_output=True, text=True, timeout=30)
|
||||
self.assertEqual(run.returncode, 0, run.stdout + run.stderr)
|
||||
|
||||
@unittest.skipUnless(CC, 'no clang')
|
||||
def test_start_matches_the_record(self):
|
||||
# runtime/plugin_writes.h plugin_write_find on this table's patches.h, as runtime/plugin_init.c check_writes
|
||||
# looks up each word an init changed: Self Recall's pool size at main+0x3ad6eb8, recorded by the service run as
|
||||
# 84800000 -> 7f1c0000 and written at a start with a grown texture heap as 87a00000 -> 823c0000
|
||||
site = f'site mod_x main {FN:x} aa0003f3 @call:plugin0+4000 aa0003f3'
|
||||
cases = [(FN, 0xAA0003F3, 0x14000000, 0), (FN, 0xAA0003F3, 0x14000001, -1),
|
||||
(0x3AD6EB8, 0x84800000, 0x7F1C0000, 1), (0x3AD6EB8, 0x87A00000, 0x823C0000, 1),
|
||||
(0x3AD6EBC, 0x87A00000, 0x823C0000, -1)]
|
||||
main = ['#include "patches.h"', '#include "plugin_writes.h"',
|
||||
'static const PluginWrite tab[] = {RT_PLUGIN_WRITES(PLUGIN_WRITE)};',
|
||||
'int main(void) {', ' int n = sizeof tab / sizeof *tab, bad = 0;']
|
||||
for i, (off, old, new, want) in enumerate(cases):
|
||||
main.append(f' bad |= (plugin_write_find(tab, n, 0, "main", {off:#x}, {old:#x}u, {new:#x}u) != {want}) '
|
||||
f'<< {i};')
|
||||
main += [' return bad;', '}']
|
||||
(self.d / 'start.c').write_text('\n'.join(main) + '\n')
|
||||
exe = self.d / 'start.exe'
|
||||
for record, failed in (('expect mod_x main 3ad6eb8 84800000 7f1c0000', 1 << 3),
|
||||
('expect mod_x main 3ad6eb8 * *', 0)):
|
||||
with self.subTest(record=record):
|
||||
(self.d / 'patches.h').write_text(patches.header_text(self.table(site, ['stub plugin0 4000', record]),
|
||||
'MARK'))
|
||||
subprocess.run([CC, '-std=gnu11', '-Wall', '-Werror', '-I', str(self.d), '-I', str(ROOT / 'runtime'),
|
||||
str(self.d / 'start.c'), '-o', str(exe)], check=True, env=CC_ENV, timeout=60)
|
||||
# the exact record misses only the play-time write
|
||||
self.assertEqual(subprocess.run([str(exe)], env=CC_ENV, timeout=60).returncode, failed)
|
||||
|
||||
def test_image_must_match_its_hash(self):
|
||||
t = self.table(f'site mod_x main {FN:x} aa0003f3 @call:plugin0+4000 aa0003f3', ['stub plugin0 4000'])
|
||||
t.plugins['plugin0']['sha256'] = '0' * 64
|
||||
|
||||
+14
-3
@@ -377,7 +377,8 @@ def check_record(rec, impls, game=frozenset()):
|
||||
# words as it left them here (runtime/plugin_init.c check_writes keeps data pages, compared word by word
|
||||
# with the expect lines). .rodata holds what the lift read as constants (the jump tables), so no write
|
||||
# goes there. A word that makes a pointer into a plugin's .text (a table entry swapped for a plugin
|
||||
# function: Zonai Fieldworks, Material Columns) names a function start of that plugin's lift.
|
||||
# function: Zonai Fieldworks, Material Columns) names a function start of that plugin's lift; any other
|
||||
# word is compared by place only (plugin_lines).
|
||||
if w['offset'] < main['data_off']:
|
||||
reasons.append(f"a write into main's .rodata: {where} {w['old']:#010x} -> {w['new']:#010x}")
|
||||
continue
|
||||
@@ -633,10 +634,20 @@ def plugin_lines(rec, hooks, name, record_dir, module):
|
||||
text_sha = hashlib.sha256(img[:p['text_end']]).hexdigest()
|
||||
image = json.dumps((Path(record_dir) / p['image']).resolve().as_posix(), ensure_ascii=False)
|
||||
lines.append(f'plugin {name} {p["name"]} {text_sha} {image}')
|
||||
own = {int(h['site'].split('+')[1], 16) for h in hooks}
|
||||
own = {int(h['site'].split('+')[1], 16): h for h in hooks}
|
||||
# A word of main's .data or .bss that is no pointer into a plugin's .text (a data hook without a target, and not
|
||||
# the upper half of one with a target) shapes no lifted code, and the game may hold another value there at play
|
||||
# than in the service run: Self Recall of Zonai Fieldworks takes its storage off a pool size that grows with the
|
||||
# resolution's texture heap. Its expect line says `* *`: the start matches it by place only
|
||||
# (runtime/plugin_init.c check_writes), and the word keeps what the init wrote at play.
|
||||
pointers = {o for o, h in own.items() if h['kind'] == 'data' and h.get('target')}
|
||||
for w in rec['writes']:
|
||||
if w['module'] == 'main' and w['offset'] in own:
|
||||
lines.append(f'expect {name} {w["module"]} {w["offset"]:x} {w["old"]:08x} {w["new"]:08x}')
|
||||
h, o = own[w['offset']], w['offset']
|
||||
if h['kind'] == 'data' and o not in pointers and o - 4 not in pointers:
|
||||
lines.append(f'expect {name} {w["module"]} {o:x} * *')
|
||||
else:
|
||||
lines.append(f'expect {name} {w["module"]} {o:x} {w["old"]:08x} {w["new"]:08x}')
|
||||
seeds, stubs = {}, {}
|
||||
|
||||
def at(ref):
|
||||
|
||||
Reference in new issue
Block a user