@gameslate/sdk 0.3.7 → 0.3.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +24 -0
- package/bin/gameslate-plugin.mjs +63 -2
- package/build/verify-effects.mjs +75 -7
- package/lib/host/addresses.d.ts +110 -0
- package/lib/host/addresses.js +164 -0
- package/lib/host/index.d.ts +1 -0
- package/lib/host/index.js +1 -0
- package/lib/host/inspect.js +1 -1
- package/lib/host/live-sandbox.d.ts +11 -2
- package/lib/host/live-sandbox.js +40 -6
- package/lib/host/verify.d.ts +1019 -8
- package/lib/host/verify.js +204 -14
- package/package.json +1 -1
- package/template/claude/skills/build-gameslate-plugin/SKILL.md +130 -3
- package/template/claude/skills/verify-gameslate-plugin/SKILL.md +97 -24
- package/template/gitignore +5 -0
package/README.md
CHANGED
|
@@ -18,6 +18,7 @@ runs the plugin in a QuickJS sandbox, validates everything it returns, and owns
|
|
|
18
18
|
| `gameslate-plugin build` | Builds a plugin folder into what the core loads |
|
|
19
19
|
| `gameslate-plugin validate` | Checks a built plugin exactly as the core does: manifest, contract, hashes, and its code loaded in the sandbox |
|
|
20
20
|
| `gameslate-plugin verify` | Runs the game to a known moment (an emulator save state) and checks what a local GameSlate daemon reports, plus the emulator's own memory reads, against a `verify.json` |
|
|
21
|
+
| `gameslate-plugin addresses` | A game's address table from its decompilation: globals from its symbol maps (less a revision delta when it builds another revision), struct offsets, sizes and constants from a clang probe of its headers |
|
|
21
22
|
|
|
22
23
|
New plugin repos also get two agent skills in `.claude/skills/`: `build-gameslate-plugin` (from
|
|
23
24
|
choosing a state source to release) and `verify-gameslate-plugin`.
|
|
@@ -60,6 +61,29 @@ validates it and writes every file.
|
|
|
60
61
|
|
|
61
62
|
`0.3.x` speaks plugin contract (`sdkApi`) 3: new 0.3 versions add tools, never change the contract. The core refuses a plugin built for another contract.
|
|
62
63
|
|
|
64
|
+
- **0.3.9** (not yet published): `gameslate-plugin addresses` takes `expectSizes` and fails
|
|
65
|
+
when the probe disagrees with a size the decomp states. `verify.json`'s `expect` also checks the inventory (`has`,
|
|
66
|
+
`lacks`, `exactly`), the equipped item (`null` for nothing) and flags; a flag the state doesn't
|
|
67
|
+
report is a mismatch, not false.
|
|
68
|
+
- **0.3.8:** `verify.json` `steps` drive an emulator to its moment through GameSlate's
|
|
69
|
+
`gameslate drive`, with any `emulator` command:
|
|
70
|
+
- `press` once, until a check matches, or taking turns between keys;
|
|
71
|
+
- `waitFor` a check;
|
|
72
|
+
- `waitMs`;
|
|
73
|
+
- `frame`.
|
|
74
|
+
|
|
75
|
+
A check is a peeked value or the plugin's own state, and `times` requires that many matching
|
|
76
|
+
reads in a row.
|
|
77
|
+
|
|
78
|
+
Also in 0.3.8:
|
|
79
|
+
- `gameslate-plugin addresses <spec.json>`: a decomp's addresses, offsets and sizes as a
|
|
80
|
+
TypeScript table that names its sources;
|
|
81
|
+
- `verify.json`'s `ui` screenshots each of the app's tabs (Map, Inventory, Missions, Ref) at a
|
|
82
|
+
phone's width, or the tabs you list;
|
|
83
|
+
- a live plugin that broke a sandbox limit gets a fresh runtime for its next session (at most
|
|
84
|
+
3 times an hour);
|
|
85
|
+
- `new PluginSandbox(quickJs, code, name, { log })` now takes its log in an options object.
|
|
86
|
+
The plugin contract is unchanged.
|
|
63
87
|
- **0.3.7:**
|
|
64
88
|
- image outputs carry a `purpose` (atlas, map, icon, actor) and an `encoding` (PNG or WebP);
|
|
65
89
|
- asset extractors can be up to 10 minutes per asset, and run across builder threads;
|
package/bin/gameslate-plugin.mjs
CHANGED
|
@@ -16,6 +16,9 @@ import { initPlugin } from '../build/init-plugin.mjs';
|
|
|
16
16
|
* gameslate-plugin verify <verify.json>
|
|
17
17
|
* Runs the game to a known moment (RetroArch on a save state) and checks what a local
|
|
18
18
|
* GameSlate daemon reports, and the emulator's own memory reads, against the file.
|
|
19
|
+
* gameslate-plugin addresses <spec.json> [--out <file.ts>]
|
|
20
|
+
* A game's address table from its decompilation: symbols from its maps, struct offsets,
|
|
21
|
+
* sizes and constants from a clang probe against its headers (src/host/addresses.ts).
|
|
19
22
|
*/
|
|
20
23
|
const { values, positionals } = parseArgs({
|
|
21
24
|
options: {
|
|
@@ -33,6 +36,7 @@ const USAGE = [
|
|
|
33
36
|
' gameslate-plugin build <pluginDir> --out <dir> [--tested-with <version>]',
|
|
34
37
|
' gameslate-plugin validate <builtDir> [--core-version <version>]',
|
|
35
38
|
' gameslate-plugin verify <verify.json>',
|
|
39
|
+
' gameslate-plugin addresses <spec.json> [--out <file.ts>]',
|
|
36
40
|
].join('\n');
|
|
37
41
|
|
|
38
42
|
async function validate(builtDir) {
|
|
@@ -81,15 +85,72 @@ if (command === 'build' && dir && values.out) {
|
|
|
81
85
|
for (const p of problems) console.error(`refused: ${p}`);
|
|
82
86
|
process.exit(problems.length ? 1 : 0);
|
|
83
87
|
} else if (command === 'verify' && dir) {
|
|
84
|
-
const { runVerify, VerifySpecSchema } = await import('../lib/host/index.js');
|
|
88
|
+
const { expandEnv, runVerify, VerifySpecSchema } = await import('../lib/host/index.js');
|
|
85
89
|
const { verifyEffects } = await import('../build/verify-effects.mjs');
|
|
86
90
|
const file = path.resolve(dir);
|
|
87
|
-
const spec = VerifySpecSchema.parse(
|
|
91
|
+
const spec = VerifySpecSchema.parse(
|
|
92
|
+
expandEnv(JSON.parse(fs.readFileSync(file, 'utf8')), process.env),
|
|
93
|
+
);
|
|
88
94
|
const result = await runVerify(spec, verifyEffects(path.dirname(file)));
|
|
89
95
|
console.log(result.ok ? `${spec.game}: verified` : `${spec.game}: NOT verified`);
|
|
90
96
|
for (const p of result.problems) console.log(` ${p}`);
|
|
91
97
|
for (const s of result.screenshots) console.log(` screenshot: ${s}`);
|
|
92
98
|
process.exit(result.ok ? 0 : 1);
|
|
99
|
+
} else if (command === 'addresses' && dir) {
|
|
100
|
+
const { addressModule, AddressSpecSchema, buildAddressTable, expandEnv } =
|
|
101
|
+
await import('../lib/host/index.js');
|
|
102
|
+
const { execFileSync } = await import('node:child_process');
|
|
103
|
+
const os = await import('node:os');
|
|
104
|
+
const specFile = path.resolve(dir);
|
|
105
|
+
const spec = AddressSpecSchema.parse(
|
|
106
|
+
expandEnv(JSON.parse(fs.readFileSync(specFile, 'utf8')), process.env),
|
|
107
|
+
);
|
|
108
|
+
const decomp = path.resolve(path.dirname(specFile), spec.decomp);
|
|
109
|
+
const table = buildAddressTable(spec, {
|
|
110
|
+
read: file => fs.readFileSync(path.join(decomp, file), 'utf8'),
|
|
111
|
+
compile: source => {
|
|
112
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gs-probe-'));
|
|
113
|
+
const probe = path.join(dir, 'probe.c');
|
|
114
|
+
fs.writeFileSync(probe, source);
|
|
115
|
+
const stubs = path.join(dir, 'stubs');
|
|
116
|
+
for (const h of spec.stubHeaders) {
|
|
117
|
+
fs.mkdirSync(path.dirname(path.join(stubs, h)), { recursive: true });
|
|
118
|
+
fs.writeFileSync(
|
|
119
|
+
path.join(stubs, h),
|
|
120
|
+
'/* stub: generated by the decomp build */\n',
|
|
121
|
+
);
|
|
122
|
+
}
|
|
123
|
+
/* after the decomp's own include paths: a real header wins over a stub */
|
|
124
|
+
const args = [
|
|
125
|
+
...spec.clang.args,
|
|
126
|
+
...(spec.stubHeaders.length ? ['-idirafter', stubs] : []),
|
|
127
|
+
];
|
|
128
|
+
return execFileSync(spec.clang.binary, [...args, '-S', '-o', '-', probe], {
|
|
129
|
+
cwd: decomp,
|
|
130
|
+
encoding: 'utf8',
|
|
131
|
+
maxBuffer: 64 * 1024 * 1024,
|
|
132
|
+
});
|
|
133
|
+
},
|
|
134
|
+
});
|
|
135
|
+
const commit = (() => {
|
|
136
|
+
try {
|
|
137
|
+
return execFileSync('git', ['-C', decomp, 'rev-parse', '--short', 'HEAD'], {
|
|
138
|
+
encoding: 'utf8',
|
|
139
|
+
}).trim();
|
|
140
|
+
} catch {
|
|
141
|
+
return 'not a git checkout';
|
|
142
|
+
}
|
|
143
|
+
})();
|
|
144
|
+
const provenance = [
|
|
145
|
+
`Addresses from the ${path.basename(decomp)} decompilation (commit ${commit}), by`,
|
|
146
|
+
`gameslate-plugin addresses ${path.basename(specFile)}:`,
|
|
147
|
+
`- symbols from ${spec.symbolFiles.join(', ')}${spec.subtract ? `, less 0x${spec.subtract.toString(16)} (another revision)` : ''};`,
|
|
148
|
+
`- offsets, sizes and constants from a probe of ${spec.includes.join(', ') || 'no headers'},`,
|
|
149
|
+
` compiled by ${spec.clang.binary} ${spec.clang.args.filter(a => !a.startsWith('-I')).join(' ')}.`,
|
|
150
|
+
].join('\n');
|
|
151
|
+
const text = addressModule(table, provenance);
|
|
152
|
+
if (values.out) fs.writeFileSync(path.resolve(values.out), text);
|
|
153
|
+
else process.stdout.write(text);
|
|
93
154
|
} else {
|
|
94
155
|
console.error(USAGE);
|
|
95
156
|
process.exit(1);
|
package/build/verify-effects.mjs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { spawn } from 'node:child_process';
|
|
1
|
+
import { execFile, spawn } from 'node:child_process';
|
|
2
2
|
import dgram from 'node:dgram';
|
|
3
|
+
import fs from 'node:fs';
|
|
3
4
|
import path from 'node:path';
|
|
4
5
|
|
|
5
6
|
/*
|
|
@@ -16,7 +17,9 @@ const COMMAND_TIMEOUT_MS = 2000;
|
|
|
16
17
|
export function verifyEffects(specDir, log = line => console.error(line)) {
|
|
17
18
|
const at = p => path.resolve(specDir, p);
|
|
18
19
|
return {
|
|
19
|
-
launch: spec =>
|
|
20
|
+
launch: spec =>
|
|
21
|
+
spec.emulator ? launchEmulator(spec, at, log) : launchRetroArch(spec, at, log),
|
|
22
|
+
drive: (spec, args) => drive(spec, at, args),
|
|
20
23
|
wait: ms => new Promise(resolve => setTimeout(resolve, ms)),
|
|
21
24
|
state: spec => nextState(spec),
|
|
22
25
|
command: (spec, line) => retroArchCommand(spec.retroarch?.port ?? 55355, line),
|
|
@@ -24,6 +27,56 @@ export function verifyEffects(specDir, log = line => console.error(line)) {
|
|
|
24
27
|
};
|
|
25
28
|
}
|
|
26
29
|
|
|
30
|
+
/* a started process, once it has run STARTUP_MS without exiting */
|
|
31
|
+
function started(child, stop) {
|
|
32
|
+
return new Promise((resolve, reject) => {
|
|
33
|
+
child.once('error', reject);
|
|
34
|
+
child.once('exit', code =>
|
|
35
|
+
reject(new Error(`the emulator exited (${code}) while starting`)),
|
|
36
|
+
);
|
|
37
|
+
setTimeout(() => {
|
|
38
|
+
child.removeAllListeners('exit');
|
|
39
|
+
resolve(stop);
|
|
40
|
+
}, STARTUP_MS);
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/* The emulator's own pid: the child, or the launch wrapper's child when there's a prefix. */
|
|
45
|
+
function emulatorPid(child, wrapped) {
|
|
46
|
+
if (!wrapped) return child.pid;
|
|
47
|
+
const children = `/proc/${child.pid}/task/${child.pid}/children`;
|
|
48
|
+
const pid = Number(fs.readFileSync(children, 'utf8').trim().split(/\s+/)[0]);
|
|
49
|
+
if (!pid) throw new Error('the launch wrapper started no emulator');
|
|
50
|
+
return pid;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
async function launchEmulator(spec, at, log) {
|
|
54
|
+
const { command, launchPrefix } = spec.emulator;
|
|
55
|
+
const [first, ...rest] = [...launchPrefix, ...command];
|
|
56
|
+
const child = spawn(first, rest, { stdio: 'ignore', cwd: at('.') });
|
|
57
|
+
log(`started ${path.basename(command[0])} (pid ${child.pid})`);
|
|
58
|
+
await started(child, null);
|
|
59
|
+
return { pid: emulatorPid(child, launchPrefix.length > 0), stop: () => child.kill('SIGTERM') };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/* a `gameslate drive` command; a frame's file goes beside the spec */
|
|
63
|
+
function drive(spec, at, args) {
|
|
64
|
+
if (!spec.gameslate) throw new Error('steps need "gameslate": the path to dist/gameslate.mjs');
|
|
65
|
+
const resolved = args[0] === 'frame' ? [args[0], args[1], at(args[2])] : args;
|
|
66
|
+
return new Promise((resolve, reject) => {
|
|
67
|
+
execFile(
|
|
68
|
+
process.execPath,
|
|
69
|
+
[at(spec.gameslate), 'drive', ...resolved],
|
|
70
|
+
(err, stdout, stderr) =>
|
|
71
|
+
err
|
|
72
|
+
? reject(
|
|
73
|
+
new Error(`gameslate drive ${args[0]}: ${stderr.trim() || err.message}`),
|
|
74
|
+
)
|
|
75
|
+
: resolve(stdout),
|
|
76
|
+
);
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
|
|
27
80
|
function launchRetroArch(spec, at, log) {
|
|
28
81
|
const ra = spec.retroarch;
|
|
29
82
|
if (!ra) return Promise.resolve({ stop: () => undefined });
|
|
@@ -106,12 +159,27 @@ async function screenshots(spec, at, log) {
|
|
|
106
159
|
}
|
|
107
160
|
const browser = await playwright.chromium.launch();
|
|
108
161
|
try {
|
|
109
|
-
|
|
110
|
-
await
|
|
162
|
+
/* a phone's viewport: the app is laid out for one */
|
|
163
|
+
const page = await browser.newPage({ viewport: { width: 430, height: 900 } });
|
|
164
|
+
await page.goto(spec.ui.url);
|
|
111
165
|
await page.waitForTimeout(2000);
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
166
|
+
if (spec.ui.tabs.length === 0) {
|
|
167
|
+
const file = at(`verify-${spec.game}-ui.png`);
|
|
168
|
+
await page.screenshot({ path: file });
|
|
169
|
+
files.push(file);
|
|
170
|
+
}
|
|
171
|
+
for (const tab of spec.ui.tabs) {
|
|
172
|
+
const button = page.locator(`.fm-tab:has-text(${JSON.stringify(tab)})`);
|
|
173
|
+
if ((await button.count()) === 0) {
|
|
174
|
+
log(`the GameSlate page has no "${tab}" tab for ${spec.game}`);
|
|
175
|
+
continue;
|
|
176
|
+
}
|
|
177
|
+
await button.first().click();
|
|
178
|
+
await page.waitForTimeout(2500);
|
|
179
|
+
const file = at(`verify-${spec.game}-${tab.toLowerCase()}.png`);
|
|
180
|
+
await page.screenshot({ path: file });
|
|
181
|
+
files.push(file);
|
|
182
|
+
}
|
|
115
183
|
} finally {
|
|
116
184
|
await browser.close();
|
|
117
185
|
}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
export declare const AddressSpecSchema: z.ZodObject<{
|
|
3
|
+
/** the decomp checkout: maps, headers and clang run from here */
|
|
4
|
+
decomp: z.ZodString;
|
|
5
|
+
/** symbol files, relative to the decomp: an ld `.map`, or splat `symbol_addrs*.txt` */
|
|
6
|
+
symbolFiles: z.ZodArray<z.ZodString, "many">;
|
|
7
|
+
/** the decomp builds another revision: subtract this from every symbol (check it against
|
|
8
|
+
* verified leads first: build-gameslate-plugin § 4) */
|
|
9
|
+
subtract: z.ZodDefault<z.ZodUnion<[z.ZodNumber, z.ZodEffects<z.ZodString, number, string>]>>;
|
|
10
|
+
/** headers the probe includes, in order */
|
|
11
|
+
includes: z.ZodDefault<z.ZodArray<z.ZodString, "many">>;
|
|
12
|
+
/** headers the decomp generates at build time, given as empty files so an unbuilt checkout
|
|
13
|
+
* compiles; a layout that really needs one still fails to compile, loudly */
|
|
14
|
+
stubHeaders: z.ZodDefault<z.ZodArray<z.ZodString, "many">>;
|
|
15
|
+
/** clang's arguments besides the probe itself (target, ABI, defines, include paths) */
|
|
16
|
+
clang: z.ZodObject<{
|
|
17
|
+
binary: z.ZodDefault<z.ZodString>;
|
|
18
|
+
args: z.ZodArray<z.ZodString, "many">;
|
|
19
|
+
}, "strip", z.ZodTypeAny, {
|
|
20
|
+
binary: string;
|
|
21
|
+
args: string[];
|
|
22
|
+
}, {
|
|
23
|
+
args: string[];
|
|
24
|
+
binary?: string | undefined;
|
|
25
|
+
}>;
|
|
26
|
+
symbols: z.ZodDefault<z.ZodArray<z.ZodString, "many">>;
|
|
27
|
+
/** `Type.field.path` (a type may be `struct Name`) */
|
|
28
|
+
offsets: z.ZodDefault<z.ZodArray<z.ZodString, "many">>;
|
|
29
|
+
sizes: z.ZodDefault<z.ZodArray<z.ZodString, "many">>;
|
|
30
|
+
/** any integer constant expression: enum values, macros */
|
|
31
|
+
constants: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodString>>;
|
|
32
|
+
/** sizes the decomp states (a `// size = 0x3C4` comment, a symbol's `size:` over its count):
|
|
33
|
+
* the probe must agree, or the run fails. A probe compiled in the wrong language standard
|
|
34
|
+
* (C17's 1-byte bool against the game's C89 4-byte enum) shifts every later offset while
|
|
35
|
+
* looking fine; this catches it. */
|
|
36
|
+
expectSizes: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodUnion<[z.ZodNumber, z.ZodEffects<z.ZodString, number, string>]>>>;
|
|
37
|
+
}, "strip", z.ZodTypeAny, {
|
|
38
|
+
includes: string[];
|
|
39
|
+
decomp: string;
|
|
40
|
+
symbolFiles: string[];
|
|
41
|
+
subtract: number;
|
|
42
|
+
stubHeaders: string[];
|
|
43
|
+
clang: {
|
|
44
|
+
binary: string;
|
|
45
|
+
args: string[];
|
|
46
|
+
};
|
|
47
|
+
symbols: string[];
|
|
48
|
+
offsets: string[];
|
|
49
|
+
sizes: string[];
|
|
50
|
+
constants: Record<string, string>;
|
|
51
|
+
expectSizes: Record<string, number>;
|
|
52
|
+
}, {
|
|
53
|
+
decomp: string;
|
|
54
|
+
symbolFiles: string[];
|
|
55
|
+
clang: {
|
|
56
|
+
args: string[];
|
|
57
|
+
binary?: string | undefined;
|
|
58
|
+
};
|
|
59
|
+
includes?: string[] | undefined;
|
|
60
|
+
subtract?: string | number | undefined;
|
|
61
|
+
stubHeaders?: string[] | undefined;
|
|
62
|
+
symbols?: string[] | undefined;
|
|
63
|
+
offsets?: string[] | undefined;
|
|
64
|
+
sizes?: string[] | undefined;
|
|
65
|
+
constants?: Record<string, string> | undefined;
|
|
66
|
+
expectSizes?: Record<string, string | number> | undefined;
|
|
67
|
+
}>;
|
|
68
|
+
export type AddressSpec = z.infer<typeof AddressSpecSchema>;
|
|
69
|
+
/** Symbols from an ld map (` 0x800dc50c gGamestate`) or a splat file (`gGameState = 0x80177834;`). */
|
|
70
|
+
export declare function parseSymbolFile(text: string): Map<string, number>;
|
|
71
|
+
/** `struct CourseTable.vertexStart` → the type and the member path. */
|
|
72
|
+
export declare function splitMember(spec: string): {
|
|
73
|
+
type: string;
|
|
74
|
+
member: string;
|
|
75
|
+
};
|
|
76
|
+
/** One probe entry per value: `const long probe_N = (expr);`. */
|
|
77
|
+
export declare function probeEntries(spec: Pick<AddressSpec, 'offsets' | 'sizes' | 'constants'> & Partial<Pick<AddressSpec, 'expectSizes'>>): ({
|
|
78
|
+
kind: "offsets";
|
|
79
|
+
name: string;
|
|
80
|
+
expr: string;
|
|
81
|
+
} | {
|
|
82
|
+
kind: "sizes";
|
|
83
|
+
name: string;
|
|
84
|
+
expr: string;
|
|
85
|
+
} | {
|
|
86
|
+
kind: "constants";
|
|
87
|
+
name: string;
|
|
88
|
+
expr: string;
|
|
89
|
+
})[];
|
|
90
|
+
export declare function probeSource(includes: readonly string[], entries: ReadonlyArray<{
|
|
91
|
+
expr: string;
|
|
92
|
+
}>): string;
|
|
93
|
+
/** probe_N's value from clang's assembly (`probe_3:` then `.4byte 612` or `.word 612`). */
|
|
94
|
+
export declare function parseProbeAssembly(asm: string, count: number): number[];
|
|
95
|
+
export interface AddressTable {
|
|
96
|
+
symbols: Record<string, number>;
|
|
97
|
+
offsets: Record<string, number>;
|
|
98
|
+
sizes: Record<string, number>;
|
|
99
|
+
constants: Record<string, number>;
|
|
100
|
+
}
|
|
101
|
+
export interface AddressEffects {
|
|
102
|
+
/** a file under the decomp, as text */
|
|
103
|
+
read(file: string): string;
|
|
104
|
+
/** clang over the probe source; its assembly */
|
|
105
|
+
compile(source: string): string;
|
|
106
|
+
}
|
|
107
|
+
/** The table a spec names; throws on any symbol the maps don't have or value clang didn't fold. */
|
|
108
|
+
export declare function buildAddressTable(spec: AddressSpec, effects: AddressEffects): AddressTable;
|
|
109
|
+
/** The table as a TypeScript module, with where every number came from. */
|
|
110
|
+
export declare function addressModule(table: AddressTable, provenance: string): string;
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
/*
|
|
3
|
+
* `gameslate-plugin addresses <spec.json>`: a game's address table from its decompilation, so a
|
|
4
|
+
* plugin's addresses have a source instead of being typed in. Globals come from the build's
|
|
5
|
+
* symbol map (a GNU ld map, or splat's `symbol_addrs` files), less a constant when the decomp
|
|
6
|
+
* builds another revision than the player's ROM. Struct offsets, sizes and constants come from a
|
|
7
|
+
* probe compiled with clang against the decomp's own headers for the console's ABI: no code runs,
|
|
8
|
+
* the compiler folds each value into the assembly. The effects (files, clang) are parameters.
|
|
9
|
+
*/
|
|
10
|
+
const Hex = z.union([
|
|
11
|
+
z.number().int(),
|
|
12
|
+
z
|
|
13
|
+
.string()
|
|
14
|
+
.regex(/^-?0x[0-9a-fA-F]+$/, 'a hex number such as 0xA190')
|
|
15
|
+
.transform(h => Number.parseInt(h, 16)),
|
|
16
|
+
]);
|
|
17
|
+
export const AddressSpecSchema = z.object({
|
|
18
|
+
/** the decomp checkout: maps, headers and clang run from here */
|
|
19
|
+
decomp: z.string(),
|
|
20
|
+
/** symbol files, relative to the decomp: an ld `.map`, or splat `symbol_addrs*.txt` */
|
|
21
|
+
symbolFiles: z.array(z.string()).min(1),
|
|
22
|
+
/** the decomp builds another revision: subtract this from every symbol (check it against
|
|
23
|
+
* verified leads first: build-gameslate-plugin § 4) */
|
|
24
|
+
subtract: Hex.default(0),
|
|
25
|
+
/** headers the probe includes, in order */
|
|
26
|
+
includes: z.array(z.string()).default([]),
|
|
27
|
+
/** headers the decomp generates at build time, given as empty files so an unbuilt checkout
|
|
28
|
+
* compiles; a layout that really needs one still fails to compile, loudly */
|
|
29
|
+
stubHeaders: z.array(z.string().regex(/^[A-Za-z0-9_./-]+\.h$/)).default([]),
|
|
30
|
+
/** clang's arguments besides the probe itself (target, ABI, defines, include paths) */
|
|
31
|
+
clang: z.object({ binary: z.string().default('clang-18'), args: z.array(z.string()) }),
|
|
32
|
+
symbols: z.array(z.string()).default([]),
|
|
33
|
+
/** `Type.field.path` (a type may be `struct Name`) */
|
|
34
|
+
offsets: z.array(z.string()).default([]),
|
|
35
|
+
sizes: z.array(z.string()).default([]),
|
|
36
|
+
/** any integer constant expression: enum values, macros */
|
|
37
|
+
constants: z.record(z.string(), z.string()).default({}),
|
|
38
|
+
/** sizes the decomp states (a `// size = 0x3C4` comment, a symbol's `size:` over its count):
|
|
39
|
+
* the probe must agree, or the run fails. A probe compiled in the wrong language standard
|
|
40
|
+
* (C17's 1-byte bool against the game's C89 4-byte enum) shifts every later offset while
|
|
41
|
+
* looking fine; this catches it. */
|
|
42
|
+
expectSizes: z.record(z.string(), Hex).default({}),
|
|
43
|
+
});
|
|
44
|
+
const LD_MAP_LINE = /^\s+0x([0-9a-fA-F]{8,16})\s+([A-Za-z_][A-Za-z0-9_]*)\s*$/;
|
|
45
|
+
const SPLAT_LINE = /^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*0x([0-9a-fA-F]+)\s*;/;
|
|
46
|
+
/** Symbols from an ld map (` 0x800dc50c gGamestate`) or a splat file (`gGameState = 0x80177834;`). */
|
|
47
|
+
export function parseSymbolFile(text) {
|
|
48
|
+
const out = new Map();
|
|
49
|
+
for (const line of text.split('\n')) {
|
|
50
|
+
const ld = LD_MAP_LINE.exec(line);
|
|
51
|
+
if (ld?.[1] && ld[2]) {
|
|
52
|
+
out.set(ld[2], Number.parseInt(ld[1].slice(-8), 16));
|
|
53
|
+
continue;
|
|
54
|
+
}
|
|
55
|
+
const splat = SPLAT_LINE.exec(line);
|
|
56
|
+
if (splat?.[1] && splat[2])
|
|
57
|
+
out.set(splat[1], Number.parseInt(splat[2], 16));
|
|
58
|
+
}
|
|
59
|
+
return out;
|
|
60
|
+
}
|
|
61
|
+
/** `struct CourseTable.vertexStart` → the type and the member path. */
|
|
62
|
+
export function splitMember(spec) {
|
|
63
|
+
const m = /^((?:struct |union )?[A-Za-z_][A-Za-z0-9_]*)\.(.+)$/.exec(spec);
|
|
64
|
+
if (!m?.[1] || !m[2])
|
|
65
|
+
throw new Error(`"${spec}" isn't Type.member`);
|
|
66
|
+
return { type: m[1], member: m[2] };
|
|
67
|
+
}
|
|
68
|
+
/** One probe entry per value: `const long probe_N = (expr);`. */
|
|
69
|
+
export function probeEntries(spec) {
|
|
70
|
+
return [
|
|
71
|
+
...spec.offsets.map(o => {
|
|
72
|
+
const { type, member } = splitMember(o);
|
|
73
|
+
return {
|
|
74
|
+
kind: 'offsets',
|
|
75
|
+
name: o,
|
|
76
|
+
expr: `__builtin_offsetof(${type}, ${member})`,
|
|
77
|
+
};
|
|
78
|
+
}),
|
|
79
|
+
...[...new Set([...spec.sizes, ...Object.keys(spec.expectSizes ?? {})])].map(t => ({
|
|
80
|
+
kind: 'sizes',
|
|
81
|
+
name: t,
|
|
82
|
+
expr: `sizeof(${t})`,
|
|
83
|
+
})),
|
|
84
|
+
...Object.entries(spec.constants).map(([name, expr]) => ({
|
|
85
|
+
kind: 'constants',
|
|
86
|
+
name,
|
|
87
|
+
expr,
|
|
88
|
+
})),
|
|
89
|
+
];
|
|
90
|
+
}
|
|
91
|
+
export function probeSource(includes, entries) {
|
|
92
|
+
return [
|
|
93
|
+
'/* generated by gameslate-plugin addresses: each value folds into the assembly */',
|
|
94
|
+
...includes.map(h => `#include ${h.startsWith('<') ? h : `"${h}"`}`),
|
|
95
|
+
...entries.map((e, i) => `const long probe_${i} = (long)(${e.expr});`),
|
|
96
|
+
'',
|
|
97
|
+
].join('\n');
|
|
98
|
+
}
|
|
99
|
+
/** probe_N's value from clang's assembly (`probe_3:` then `.4byte 612` or `.word 612`). */
|
|
100
|
+
export function parseProbeAssembly(asm, count) {
|
|
101
|
+
const values = new Map();
|
|
102
|
+
const lines = asm.split('\n');
|
|
103
|
+
lines.forEach((line, i) => {
|
|
104
|
+
const label = /^probe_(\d+):/.exec(line);
|
|
105
|
+
const data = /^\s*\.(?:4byte|word|long)\s+(-?\d+)/.exec(lines[i + 1] ?? '');
|
|
106
|
+
/* clang writes a word's bits unsigned (-103 as 4294967193): read them as a signed long */
|
|
107
|
+
if (label?.[1] && data?.[1])
|
|
108
|
+
values.set(Number(label[1]), Number(data[1]) | 0);
|
|
109
|
+
});
|
|
110
|
+
return Array.from({ length: count }, (_, i) => {
|
|
111
|
+
const v = values.get(i);
|
|
112
|
+
if (v === undefined)
|
|
113
|
+
throw new Error(`clang's output has no value for probe_${i}`);
|
|
114
|
+
return v;
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
/** The table a spec names; throws on any symbol the maps don't have or value clang didn't fold. */
|
|
118
|
+
export function buildAddressTable(spec, effects) {
|
|
119
|
+
const known = new Map();
|
|
120
|
+
for (const f of spec.symbolFiles)
|
|
121
|
+
for (const [k, v] of parseSymbolFile(effects.read(f)))
|
|
122
|
+
known.set(k, v);
|
|
123
|
+
const missing = spec.symbols.filter(s => !known.has(s));
|
|
124
|
+
if (missing.length)
|
|
125
|
+
throw new Error(`not in ${spec.symbolFiles.join(', ')}: ${missing.join(', ')}`);
|
|
126
|
+
const table = { symbols: {}, offsets: {}, sizes: {}, constants: {} };
|
|
127
|
+
for (const s of spec.symbols)
|
|
128
|
+
table.symbols[s] = ((known.get(s) ?? 0) - spec.subtract) >>> 0;
|
|
129
|
+
const entries = probeEntries(spec);
|
|
130
|
+
if (entries.length) {
|
|
131
|
+
const values = parseProbeAssembly(effects.compile(probeSource(spec.includes, entries)), entries.length);
|
|
132
|
+
entries.forEach((e, i) => {
|
|
133
|
+
table[e.kind][e.name] = values[i] ?? 0;
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
const wrong = Object.entries(spec.expectSizes).filter(([t, size]) => table.sizes[t] !== size);
|
|
137
|
+
if (wrong.length)
|
|
138
|
+
throw new Error(`the probe disagrees with the decomp on ${wrong
|
|
139
|
+
.map(([t, size]) => `sizeof(${t}): 0x${(table.sizes[t] ?? 0).toString(16)}, expected 0x${size.toString(16)}`)
|
|
140
|
+
.join('; ')} (check the language standard and defines)`);
|
|
141
|
+
return table;
|
|
142
|
+
}
|
|
143
|
+
const hex = (n) => (n < 0 ? `-0x${(-n).toString(16)}` : `0x${n.toString(16)}`);
|
|
144
|
+
const key = (k) => (/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(k) ? k : JSON.stringify(k));
|
|
145
|
+
/** The table as a TypeScript module, with where every number came from. */
|
|
146
|
+
export function addressModule(table, provenance) {
|
|
147
|
+
const block = (name, values, asHex) => [
|
|
148
|
+
`export const ${name} = {`,
|
|
149
|
+
...Object.entries(values).map(([k, v]) => ` ${key(k)}: ${asHex ? hex(v) : String(v)},`),
|
|
150
|
+
'} as const;',
|
|
151
|
+
'',
|
|
152
|
+
];
|
|
153
|
+
return [
|
|
154
|
+
'/*',
|
|
155
|
+
...provenance.split('\n').map(l => ` * ${l}`.trimEnd()),
|
|
156
|
+
' * Generated: rerun `gameslate-plugin addresses` rather than editing.',
|
|
157
|
+
' */',
|
|
158
|
+
'',
|
|
159
|
+
...block('SYMBOLS', table.symbols, true),
|
|
160
|
+
...block('OFFSETS', table.offsets, true),
|
|
161
|
+
...block('SIZES', table.sizes, true),
|
|
162
|
+
...block('CONSTANTS', table.constants, false),
|
|
163
|
+
].join('\n');
|
|
164
|
+
}
|
package/lib/host/index.d.ts
CHANGED
package/lib/host/index.js
CHANGED
package/lib/host/inspect.js
CHANGED
|
@@ -39,7 +39,7 @@ function describedProblem(manifest, d) {
|
|
|
39
39
|
}
|
|
40
40
|
function loadLive(quickJs, dir, manifest, log) {
|
|
41
41
|
const code = fs.readFileSync(path.join(dir, manifest.code.file), 'utf8');
|
|
42
|
-
const sandbox = new PluginSandbox(quickJs, code, manifest.id, log);
|
|
42
|
+
const sandbox = new PluginSandbox(quickJs, code, manifest.id, { log });
|
|
43
43
|
try {
|
|
44
44
|
const description = sandbox.describe();
|
|
45
45
|
const problem = describedProblem(manifest, description);
|
|
@@ -12,13 +12,22 @@ export declare const SANDBOX_LIMITS: {
|
|
|
12
12
|
};
|
|
13
13
|
/** One plugin's live code in its own runtime. */
|
|
14
14
|
export declare class PluginSandbox {
|
|
15
|
+
private readonly quickJs;
|
|
16
|
+
private readonly code;
|
|
15
17
|
private readonly name;
|
|
18
|
+
private guest;
|
|
19
|
+
private readonly restarts;
|
|
16
20
|
private readonly log;
|
|
17
|
-
private readonly
|
|
21
|
+
private readonly now;
|
|
18
22
|
private readonly memories;
|
|
19
23
|
private nextHandle;
|
|
20
24
|
private readonly viewsCache;
|
|
21
|
-
constructor(quickJs: QuickJSWASMModule, code: string, name: string,
|
|
25
|
+
constructor(quickJs: QuickJSWASMModule, code: string, name: string, opts: {
|
|
26
|
+
log: (line: string) => void;
|
|
27
|
+
now?: () => number;
|
|
28
|
+
});
|
|
29
|
+
private newGuest;
|
|
30
|
+
private restartIfSwitchedOff;
|
|
22
31
|
describe(): SandboxDescription;
|
|
23
32
|
/** The plugin as the core uses it: sources and packs whose code runs in here. */
|
|
24
33
|
module(description: SandboxDescription): PluginModule;
|
package/lib/host/live-sandbox.js
CHANGED
|
@@ -8,9 +8,15 @@ export { loadQuickJs } from './quickjs-guest.js';
|
|
|
8
8
|
* validated before the core uses it.
|
|
9
9
|
*
|
|
10
10
|
* Calls run on the daemon's thread: a poll costs well under a millisecond (the spike measured
|
|
11
|
-
* 0.26 ms) and the budget bounds the worst case. A plugin that breaks a limit is switched off
|
|
12
|
-
* a
|
|
11
|
+
* 0.26 ms) and the budget bounds the worst case. A plugin that breaks a limit is switched off; the
|
|
12
|
+
* next game session it's asked for gets it a fresh runtime, a few times an hour at most. One
|
|
13
|
+
* stalled poll on a loaded machine (seen 2026-11-30, with an emulator at 270% CPU) then costs a
|
|
14
|
+
* session, not live reading for the rest of the day, and a runaway plugin still stalls the
|
|
15
|
+
* daemon only a few times an hour.
|
|
13
16
|
*/
|
|
17
|
+
/* fresh runtimes after a plugin broke a limit, per plugin, within RESTART_WINDOW_MS */
|
|
18
|
+
const MAX_RESTARTS = 3;
|
|
19
|
+
const RESTART_WINDOW_MS = 60 * 60 * 1000;
|
|
14
20
|
export const SANDBOX_LIMITS = {
|
|
15
21
|
/* the real plugins use about 3.5 MB after loading */
|
|
16
22
|
memoryBytes: 32 * 1024 * 1024,
|
|
@@ -22,17 +28,28 @@ export const SANDBOX_LIMITS = {
|
|
|
22
28
|
};
|
|
23
29
|
/** One plugin's live code in its own runtime. */
|
|
24
30
|
export class PluginSandbox {
|
|
31
|
+
quickJs;
|
|
32
|
+
code;
|
|
25
33
|
name;
|
|
26
|
-
log;
|
|
27
34
|
guest;
|
|
35
|
+
restarts = [];
|
|
36
|
+
log;
|
|
37
|
+
now;
|
|
28
38
|
memories = new Map();
|
|
29
39
|
nextHandle = 1;
|
|
30
40
|
/* each state's views, so a pack's three view accessors cost one call */
|
|
31
41
|
viewsCache = new WeakMap();
|
|
32
|
-
constructor(quickJs, code, name,
|
|
42
|
+
constructor(quickJs, code, name, opts) {
|
|
43
|
+
this.quickJs = quickJs;
|
|
44
|
+
this.code = code;
|
|
33
45
|
this.name = name;
|
|
34
|
-
this.log = log;
|
|
35
|
-
this.
|
|
46
|
+
this.log = opts.log;
|
|
47
|
+
this.now = opts.now ?? Date.now;
|
|
48
|
+
this.guest = this.newGuest();
|
|
49
|
+
}
|
|
50
|
+
newGuest() {
|
|
51
|
+
const { quickJs, code, name, log } = this;
|
|
52
|
+
return new QuickJsGuest(quickJs, {
|
|
36
53
|
name,
|
|
37
54
|
code,
|
|
38
55
|
file: 'live.js',
|
|
@@ -42,6 +59,22 @@ export class PluginSandbox {
|
|
|
42
59
|
log,
|
|
43
60
|
});
|
|
44
61
|
}
|
|
62
|
+
/* A fresh runtime for a plugin that broke a limit, unless it has used up its restarts. Its
|
|
63
|
+
* old sessions die with the old runtime (they already failed every call). */
|
|
64
|
+
restartIfSwitchedOff() {
|
|
65
|
+
if (!this.guest.switchedOff)
|
|
66
|
+
return;
|
|
67
|
+
const now = this.now();
|
|
68
|
+
while (this.restarts.length && now - (this.restarts[0] ?? 0) > RESTART_WINDOW_MS)
|
|
69
|
+
this.restarts.shift();
|
|
70
|
+
if (this.restarts.length >= MAX_RESTARTS)
|
|
71
|
+
return;
|
|
72
|
+
this.restarts.push(now);
|
|
73
|
+
this.guest.dispose();
|
|
74
|
+
this.memories.clear();
|
|
75
|
+
this.guest = this.newGuest();
|
|
76
|
+
this.log(`[plugins] ${this.name}: restarted after breaking a sandbox limit`);
|
|
77
|
+
}
|
|
45
78
|
describe() {
|
|
46
79
|
const raw = this.call('describe', []);
|
|
47
80
|
if (typeof raw !== 'string')
|
|
@@ -88,6 +121,7 @@ export class PluginSandbox {
|
|
|
88
121
|
};
|
|
89
122
|
}
|
|
90
123
|
createSession(gameId, memory) {
|
|
124
|
+
this.restartIfSwitchedOff();
|
|
91
125
|
const handle = this.nextHandle++;
|
|
92
126
|
this.memories.set(handle, memory);
|
|
93
127
|
const info = {
|