@henols/c64-re-tools 2.8.0-rc.2 → 2.8.0-rc.3
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/package.json +1 -1
- package/skills/c64-assembler/SKILL.md +5 -2
- package/skills/c64-assembler/scripts/assembler.ts +55 -48
- package/skills/c64-disk/scripts/disk.ts +3 -3
- package/skills/c64-disk/scripts/lib/containers.ts +2 -2
- package/skills/c64-docs/SKILL.md +1 -1
- package/skills/c64-docs/scripts/docs.ts +12 -20
- package/skills/c64-docs/scripts/lib/links.ts +1 -1
- package/skills/c64-docs/scripts/lib/markdown.ts +1 -1
- package/skills/c64-docs/scripts/lib/reference.ts +59 -13
- package/skills/c64-knowledge/SKILL.md +17 -8
- package/skills/c64-knowledge/scripts/knowledge.ts +200 -218
- package/skills/c64-knowledge/scripts/lib/check.ts +2 -3
- package/skills/c64-knowledge/scripts/lib/listing.ts +56 -24
- package/skills/c64-packer/scripts/packer.ts +3 -3
- package/skills/c64-provenance/SKILL.md +25 -16
- package/skills/c64-provenance/scripts/lib/compare.ts +31 -21
- package/skills/c64-provenance/scripts/lib/leftovers.ts +17 -35
- package/skills/c64-provenance/scripts/lib/library.ts +10 -10
- package/skills/c64-provenance/scripts/lib/runtime.ts +3 -14
- package/skills/c64-provenance/scripts/provenance.ts +129 -98
- package/skills/c64-source/references/loader.md +2 -1
- package/skills/c64-source/scripts/lib/export.ts +54 -303
- package/skills/c64-source/scripts/lib/loader.ts +31 -51
- package/skills/c64-source/scripts/lib/source.ts +51 -41
- package/skills/c64-source/scripts/lib/stage.ts +9 -25
- package/skills/c64-source/scripts/source.ts +134 -294
- package/skills/c64-static-analysis/SKILL.md +10 -5
- package/skills/c64-static-analysis/scripts/lib/coverage.ts +1 -3
- package/skills/c64-static-analysis/scripts/lib/findings.ts +16 -3
- package/skills/c64-static-analysis/scripts/lib/idioms.ts +82 -10
- package/skills/c64-static-analysis/scripts/lib/triage.ts +112 -0
- package/skills/c64-static-analysis/scripts/static-analysis.ts +239 -147
- package/skills/c64-testing/SKILL.md +13 -7
- package/skills/c64-testing/scripts/lib/diff-files.ts +6 -13
- package/skills/c64-testing/scripts/lib/recording.ts +47 -66
- package/skills/c64-testing/scripts/lib/replay.ts +53 -9
- package/skills/c64-testing/scripts/lib/runs.ts +11 -29
- package/skills/c64-testing/scripts/lib/scenario.ts +30 -31
- package/skills/c64-testing/scripts/lib/start-screen.ts +42 -5
- package/skills/c64-testing/scripts/testing.ts +32 -7
- package/skills/c64-unpacker/SKILL.md +9 -7
- package/skills/c64-unpacker/scripts/lib/evidence.ts +23 -38
- package/skills/c64-unpacker/scripts/lib/loads.ts +24 -39
- package/skills/c64-unpacker/scripts/lib/machine.ts +38 -18
- package/skills/c64-unpacker/scripts/lib/stages.ts +124 -40
- package/skills/c64-unpacker/scripts/unpacker.ts +81 -68
- package/skills/emulator/SKILL.md +1 -0
- package/src/c64.ts +117 -10
- package/src/cli/ap-sdk.ts +1 -1
- package/src/cli/cleanup.ts +4 -2
- package/src/compare.ts +36 -16
- package/src/errors.ts +10 -1
- package/src/host/main.ts +2 -1
- package/src/host/server.ts +7 -11
- package/src/host/tools/c1541.ts +9 -3
- package/src/host/vice/adapter.ts +20 -43
- package/src/host/vice/binary-monitor.ts +22 -21
- package/src/host/vice/process.ts +31 -40
- package/src/host/vice/session.ts +187 -247
- package/src/host/vice/text-monitor.ts +3 -3
- package/src/host-client/autostart.ts +1 -1
- package/src/host-client/connect.ts +2 -1
- package/src/host-client/coverage.ts +0 -3
- package/src/host-client/entry-state.ts +4 -11
- package/src/host-client/image.ts +6 -11
- package/src/host-client/steps.ts +13 -113
- package/src/host-client/tools.ts +4 -4
- package/src/host-client/transfer.ts +10 -0
- package/src/host-client/vice-session.ts +10 -6
- package/src/knowledge/code-reach.ts +364 -0
- package/src/knowledge/conflicts.ts +34 -72
- package/src/knowledge/database.ts +40 -28
- package/src/knowledge/evidence.ts +2 -2
- package/src/knowledge/graph.ts +3 -3
- package/src/knowledge/history.ts +50 -90
- package/src/knowledge/import.ts +28 -68
- package/src/knowledge/join.ts +1 -1
- package/src/knowledge/names.ts +12 -7
- package/src/knowledge/program.ts +25 -46
- package/src/knowledge/read.ts +104 -100
- package/src/knowledge/schema.ts +9 -3
- package/src/knowledge/separate.ts +47 -19
- package/src/knowledge/start-screen.ts +7 -5
- package/src/knowledge/text.ts +56 -33
- package/src/knowledge/write.ts +274 -515
- package/src/loader.ts +7 -25
- package/src/mcp/inputs.ts +3 -3
- package/src/mcp/server.ts +19 -38
- package/src/mcp/session-source.ts +2 -1
- package/src/mcp/tools/debug.ts +97 -24
- package/src/mcp/tools/execution.ts +1 -1
- package/src/mcp/tools/input.ts +3 -3
- package/src/mcp/tools/machine.ts +3 -3
- package/src/mcp/tools/media.ts +4 -4
- package/src/mcp/tools/memory.ts +13 -17
- package/src/mcp/tools/video.ts +11 -25
- package/src/native/acme.ts +3 -3
- package/src/native/c64run.ts +2 -1
- package/src/native/decompiler/analyze.ts +10 -7
- package/src/native/decompiler/walk.ts +3 -4
- package/src/native/decompiler/wasm.ts +2 -2
- package/src/native/discover.ts +1 -1
- package/src/native/dxa.ts +9 -11
- package/src/native/exomizer.ts +1 -1
- package/src/native/processes.ts +4 -1
- package/src/native/run.ts +3 -3
- package/src/native/types.ts +5 -6
- package/src/opcodes.ts +3 -0
- package/src/platform.ts +9 -10
- package/src/program-code.ts +151 -0
- package/src/project.ts +8 -5
- package/src/protocol/framing.ts +51 -18
- package/src/protocol/messages.ts +1 -11
- package/src/protocol/tools.ts +0 -3
- package/src/protocol/vice.ts +588 -773
- package/src/script.ts +9 -14
- package/src/time.ts +1 -1
- package/src/trace.ts +3 -2
package/src/mcp/tools/video.ts
CHANGED
|
@@ -9,11 +9,12 @@ import { CIA_SELECTIONS, MAX_MASK_RECTANGLES, MAX_MEMORY_READ, MAX_OBSERVE_BYTES
|
|
|
9
9
|
import { OutInput, ProjectInput, writeOut, WrittenOutput } from "../output.ts";
|
|
10
10
|
import { AddressInput, Byte, MemoryViewInput, SpaceInput } from "../inputs.ts";
|
|
11
11
|
import { AddressOutput, defineTool, HexData, requireFields, requireOut, ToolOutput, TransientName } from "../server.ts";
|
|
12
|
+
import { c64Registers } from "./memory.ts";
|
|
12
13
|
|
|
13
14
|
const Color = z.number().int().min(0).max(15);
|
|
14
15
|
const NO_CHANGE = "This does not change the run state of the machine.";
|
|
15
16
|
|
|
16
|
-
|
|
17
|
+
const c64Vicii = defineTool({
|
|
17
18
|
name: "c64_vicii",
|
|
18
19
|
title: "VIC-II state",
|
|
19
20
|
description:
|
|
@@ -49,7 +50,7 @@ const SpriteOutput = z.object({
|
|
|
49
50
|
dataAddress: AddressOutput,
|
|
50
51
|
});
|
|
51
52
|
|
|
52
|
-
|
|
53
|
+
const c64Sprite = defineTool({
|
|
53
54
|
name: "c64_sprite",
|
|
54
55
|
title: "Sprite state",
|
|
55
56
|
description:
|
|
@@ -83,7 +84,7 @@ const CiaOutput = z.object({
|
|
|
83
84
|
tod: z.object({ hours: z.number().int(), minutes: z.number().int(), seconds: z.number().int(), tenths: z.number().int() }),
|
|
84
85
|
});
|
|
85
86
|
|
|
86
|
-
|
|
87
|
+
const c64Cia = defineTool({
|
|
87
88
|
name: "c64_cia",
|
|
88
89
|
title: "CIA state",
|
|
89
90
|
description:
|
|
@@ -97,7 +98,7 @@ export const c64Cia = defineTool({
|
|
|
97
98
|
},
|
|
98
99
|
});
|
|
99
100
|
|
|
100
|
-
|
|
101
|
+
const c64Sid = defineTool({
|
|
101
102
|
name: "c64_sid",
|
|
102
103
|
title: "SID state",
|
|
103
104
|
description:
|
|
@@ -128,7 +129,7 @@ const Rectangle = z
|
|
|
128
129
|
.object({ x: z.number().int().min(0), y: z.number().int().min(0), width: z.number().int().min(1), height: z.number().int().min(1) })
|
|
129
130
|
.strict();
|
|
130
131
|
|
|
131
|
-
|
|
132
|
+
const c64Screen = defineTool({
|
|
132
133
|
name: "c64_screen",
|
|
133
134
|
title: "Capture and compare the C64 screen",
|
|
134
135
|
description:
|
|
@@ -198,8 +199,6 @@ export const c64Screen = defineTool({
|
|
|
198
199
|
},
|
|
199
200
|
});
|
|
200
201
|
|
|
201
|
-
const FlagsOutput = z.object({ n: z.boolean(), v: z.boolean(), b: z.boolean(), d: z.boolean(), i: z.boolean(), z: z.boolean(), c: z.boolean() });
|
|
202
|
-
|
|
203
202
|
export const c64Observe = defineTool({
|
|
204
203
|
name: "c64_observe",
|
|
205
204
|
title: "Observe several things at one moment",
|
|
@@ -229,7 +228,7 @@ export const c64Observe = defineTool({
|
|
|
229
228
|
})
|
|
230
229
|
.strict(),
|
|
231
230
|
outputSchema: z.object({
|
|
232
|
-
registers:
|
|
231
|
+
registers: c64Registers.outputSchema.optional(),
|
|
233
232
|
memory: z.array(z.object({ address: AddressOutput, data: HexData })).optional(),
|
|
234
233
|
vicii: c64Vicii.outputSchema.optional(),
|
|
235
234
|
sprites: z.array(SpriteOutput).optional(),
|
|
@@ -240,28 +239,15 @@ export const c64Observe = defineTool({
|
|
|
240
239
|
}),
|
|
241
240
|
readOnly: true,
|
|
242
241
|
async run(input, session) {
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
if (input.memory !== undefined) params.memory = input.memory;
|
|
246
|
-
if (input.vicii === true) params.vicii = true;
|
|
247
|
-
if (input.sprites !== undefined) params.sprites = input.sprites;
|
|
248
|
-
if (input.cia !== undefined) params.cia = input.cia;
|
|
249
|
-
if (input.sid === true) params.sid = true;
|
|
250
|
-
if (input.screen === true) params.screen = true;
|
|
251
|
-
if (input.timing === true) params.timing = true;
|
|
242
|
+
// The parts asked for: a flag that is false asks for nothing.
|
|
243
|
+
const params = Object.fromEntries(Object.entries(input).filter(([, value]) => value !== undefined && value !== false)) as ObserveParams;
|
|
252
244
|
if (Object.keys(params).length === 0) throw new WireFailure("invalid-input", "Ask for at least one observation.");
|
|
253
245
|
const observed = await session.observe(params);
|
|
254
246
|
const result: Record<string, unknown> = {};
|
|
255
247
|
if (observed.registers !== undefined) result.registers = { ...observed.registers, pc: formatC64Address(observed.registers.pc) };
|
|
256
248
|
if (observed.memory !== undefined) result.memory = observed.memory.map((range) => ({ ...range, address: formatC64Address(range.address) }));
|
|
257
|
-
if (observed.vicii !== undefined)
|
|
258
|
-
|
|
259
|
-
...observed.vicii,
|
|
260
|
-
screenAddress: formatC64Address(observed.vicii.screenAddress),
|
|
261
|
-
graphicsAddress: formatC64Address(observed.vicii.graphicsAddress),
|
|
262
|
-
};
|
|
263
|
-
}
|
|
264
|
-
if (observed.sprites !== undefined) result.sprites = observed.sprites.map((sprite) => ({ ...sprite, dataAddress: formatC64Address(sprite.dataAddress) }));
|
|
249
|
+
if (observed.vicii !== undefined) result.vicii = formatVicii(observed.vicii);
|
|
250
|
+
if (observed.sprites !== undefined) result.sprites = observed.sprites.map(formatSprite);
|
|
265
251
|
if (observed.cia !== undefined) result.cia = observed.cia;
|
|
266
252
|
if (observed.sid !== undefined) result.sid = observed.sid;
|
|
267
253
|
if (observed.timing !== undefined) result.timing = observed.timing;
|
package/src/native/acme.ts
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
import { existsSync, readFileSync } from "node:fs";
|
|
5
5
|
import { isAbsolute, join, posix, relative, sep } from "node:path";
|
|
6
6
|
|
|
7
|
-
import { formatC64Address } from "../c64.ts";
|
|
7
|
+
import { formatC64Address, hexWord } from "../c64.ts";
|
|
8
8
|
import { WireFailure } from "../protocol/messages.ts";
|
|
9
9
|
import { isRelativePath } from "../protocol/tools.ts";
|
|
10
10
|
import type { AcmeParams, AcmeResult, AssembledSymbol, Diagnostic } from "./types.ts";
|
|
@@ -16,7 +16,7 @@ import { outputTail, runToolOrFail, type ToolContext } from "./run.ts";
|
|
|
16
16
|
export function showSymbol(symbol: AssembledSymbol) {
|
|
17
17
|
return symbol.kind === "address"
|
|
18
18
|
? { name: symbol.name, kind: "address", address: formatC64Address(symbol.address), used: symbol.used }
|
|
19
|
-
: { name: symbol.name, kind: "constant", value: `$${symbol.value
|
|
19
|
+
: { name: symbol.name, kind: "constant", value: `$${hexWord(symbol.value)}`, used: symbol.used };
|
|
20
20
|
}
|
|
21
21
|
|
|
22
22
|
/** The text of a symbols file (symbols/<build>.json next to the program): the symbols of a build, which c64-testing reads for the names of a program. */
|
|
@@ -47,7 +47,7 @@ function insideTree(sourceDir: string, path: string): boolean {
|
|
|
47
47
|
}
|
|
48
48
|
|
|
49
49
|
/** Refuses an entry source or include directory that ACME could read outside the staged tree, by name. */
|
|
50
|
-
|
|
50
|
+
function checkAcmeParams(params: AcmeParams): void {
|
|
51
51
|
const sourceDir = params.sourceDir ?? "";
|
|
52
52
|
if (sourceDir !== "" && !insideSourceRoot(sourceDir)) throw new WireFailure("invalid-input", `The source directory ${sourceDir} is not a relative path inside the staged tree.`);
|
|
53
53
|
if (!insideSourceRoot(params.entrySource)) throw new WireFailure("invalid-input", `The entry source ${params.entrySource} is not a relative path inside the source root.`);
|
package/src/native/c64run.ts
CHANGED
|
@@ -130,7 +130,8 @@ export class C64RunSession {
|
|
|
130
130
|
if (this.#ended !== undefined) return Promise.reject(this.#ended);
|
|
131
131
|
const answer = new Promise<string>((resolve, reject) => {
|
|
132
132
|
const timer = setTimeout(() => {
|
|
133
|
-
|
|
133
|
+
// The limit assumes the slowest core speed of an idle machine; other programs on the processor make the core slower.
|
|
134
|
+
this.#ended = new WireFailure("operation-failed", `c64run ${text.split(" ")[0]} did not answer in ${Math.ceil(limitMs / 1000)} s; the core is stopped. Other commands that run at the same time can make it this slow: run the command again alone.`);
|
|
134
135
|
for (const waiting of this.#waiting.splice(0)) waiting.reject(this.#ended);
|
|
135
136
|
void this.#process.stop().catch(() => {});
|
|
136
137
|
}, limitMs);
|
|
@@ -3,11 +3,12 @@
|
|
|
3
3
|
// in, the structural result comes out, and the result is checked completely
|
|
4
4
|
// before the script imports it.
|
|
5
5
|
|
|
6
|
-
import { describeError
|
|
6
|
+
import { describeError } from "../../errors.ts";
|
|
7
|
+
import { WireFailure } from "../../protocol/messages.ts";
|
|
7
8
|
import { checkDecompilerResult, checkRequestBounds, DECOMPILER_LIMITS, imageRange, seedsInside, type DecompilerParams, type DecompilerResult, type SeedReport } from "../types.ts";
|
|
8
9
|
import type { ToolContext } from "../run.ts";
|
|
9
|
-
|
|
10
|
-
|
|
10
|
+
|
|
11
|
+
type Wasm = typeof import("./wasm.ts");
|
|
11
12
|
|
|
12
13
|
/** The longest reason that the result check accepts. */
|
|
13
14
|
const MAX_REASON = 1000;
|
|
@@ -26,21 +27,23 @@ export async function analyze(
|
|
|
26
27
|
throw new WireFailure("invalid-input", "Give at least one entry point inside the program, for example the SYS address of its BASIC loader.");
|
|
27
28
|
}
|
|
28
29
|
context.signal.throwIfAborted();
|
|
30
|
+
// The decoder module (4.7 MB) loads when an analysis runs, not when a script that can run one starts.
|
|
31
|
+
const [{ walk }, wasm] = await Promise.all([import("./walk.ts"), import("./wasm.ts")]);
|
|
29
32
|
|
|
30
33
|
let walked: Omit<ReturnType<typeof walk>, "refusedSeeds">;
|
|
31
34
|
let refusedSeeds: ReturnType<typeof walk>["refusedSeeds"];
|
|
32
35
|
try {
|
|
33
|
-
loadImage(body, start);
|
|
36
|
+
wasm.loadImage(body, start);
|
|
34
37
|
({ refusedSeeds, ...walked } = walk(body, start, end, { entryPoints, codeStarts, dataRanges, labels: params.labels }));
|
|
35
38
|
} catch (error) {
|
|
36
39
|
context.log?.(`The decoder failed: ${describeError(error)}`);
|
|
37
40
|
throw new WireFailure("operation-failed", `The decoder failed: ${describeError(error)}. Nothing was imported.`);
|
|
38
41
|
}
|
|
39
|
-
const { decompilations, notDecompiled } = decompileRoutines(params, walked.functions, body, start, context);
|
|
42
|
+
const { decompilations, notDecompiled } = decompileRoutines(params, walked.functions, body, start, context, wasm);
|
|
40
43
|
|
|
41
44
|
let result: DecompilerResult;
|
|
42
45
|
try {
|
|
43
|
-
result = checkDecompilerResult({ ...walked, decompilations, notDecompiled, completeness: { functions: true, regions: true, references: true }, toolVersion: SLEIGH_VERSION });
|
|
46
|
+
result = checkDecompilerResult({ ...walked, decompilations, notDecompiled, completeness: { functions: true, regions: true, references: true }, toolVersion: wasm.SLEIGH_VERSION });
|
|
44
47
|
} catch (error) {
|
|
45
48
|
context.log?.(`Decompiler result rejected: ${describeError(error)}`);
|
|
46
49
|
throw new WireFailure("operation-failed", `The decompiler returned an incomplete or inconsistent result. Nothing was imported. The check found: ${describeError(error)}.`);
|
|
@@ -49,7 +52,7 @@ export async function analyze(
|
|
|
49
52
|
}
|
|
50
53
|
|
|
51
54
|
/** The requested routines as C text, within the character bounds; the labels name routines and data. */
|
|
52
|
-
function decompileRoutines(params: DecompilerParams, functions: DecompilerResult["functions"], body: Uint8Array, start: number, context: ToolContext): Pick<DecompilerResult, "decompilations" | "notDecompiled"> {
|
|
55
|
+
function decompileRoutines(params: DecompilerParams, functions: DecompilerResult["functions"], body: Uint8Array, start: number, context: ToolContext, { decompile, loadImage, setName }: Wasm): Pick<DecompilerResult, "decompilations" | "notDecompiled"> {
|
|
53
56
|
const decompilations: DecompilerResult["decompilations"] = [];
|
|
54
57
|
const notDecompiled: NonNullable<DecompilerResult["notDecompiled"]> = [];
|
|
55
58
|
if (params.decompile.length === 0) return { decompilations, notDecompiled };
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
// The target of an indirect jump comes from the stores of the straight-line
|
|
6
6
|
// code before it, or else from the pointer in the image.
|
|
7
7
|
|
|
8
|
-
import { SYMBOL_NAME } from "../../c64.ts";
|
|
8
|
+
import { hexByte, hexWord, SYMBOL_NAME } from "../../c64.ts";
|
|
9
9
|
import type { DecompilerInstruction, DecompilerResult, RefusedSeed } from "../types.ts";
|
|
10
10
|
import { PcodeState } from "./pcode.ts";
|
|
11
11
|
import { decode, type Decoded, type Varnode } from "./wasm.ts";
|
|
@@ -170,13 +170,13 @@ export function walk(image: Uint8Array, start: number, end: number, seeds: WalkS
|
|
|
170
170
|
.sort((a, b) => a - b)
|
|
171
171
|
.map((entry) => {
|
|
172
172
|
const name = labels.get(entry);
|
|
173
|
-
return name !== undefined && SYMBOL_NAME.test(name) ? { entry, name, nameSource: "seed" as const } : { entry, name: `FUN_${
|
|
173
|
+
return name !== undefined && SYMBOL_NAME.test(name) ? { entry, name, nameSource: "seed" as const } : { entry, name: `FUN_${hexWord(entry)}`, nameSource: "generated" as const };
|
|
174
174
|
}),
|
|
175
175
|
regions: regions(start, end, (address) => (owner[address] !== -1 ? "code" : isData[address] ? "data" : undefined)),
|
|
176
176
|
references,
|
|
177
177
|
instructions: sorted.map((address): DecompilerInstruction => {
|
|
178
178
|
const { decoded, flows } = instructions.get(address)!;
|
|
179
|
-
return { address, bytes: decoded.bytes.map(
|
|
179
|
+
return { address, bytes: decoded.bytes.map(hexByte).join(""), mnemonic: decoded.mnemonic.toLowerCase(), operands: decoded.operands, flows };
|
|
180
180
|
}),
|
|
181
181
|
};
|
|
182
182
|
}
|
|
@@ -232,4 +232,3 @@ function regions(start: number, end: number, kind: (address: number) => "code" |
|
|
|
232
232
|
return result;
|
|
233
233
|
}
|
|
234
234
|
|
|
235
|
-
const hex4 = (value: number) => value.toString(16).padStart(4, "0");
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
// A panic in the module traps: the instance is then dropped and the next
|
|
4
4
|
// load makes a new one.
|
|
5
5
|
|
|
6
|
-
import { Refusal } from "../../errors.ts";
|
|
6
|
+
import { describeError, Refusal } from "../../errors.ts";
|
|
7
7
|
import { C64RT_WASM } from "./c64rt-wasm.ts";
|
|
8
8
|
|
|
9
9
|
/** The decoder and decompiler, as a result names its tool. */
|
|
@@ -62,7 +62,7 @@ function call<T>(run: (wasm: Exports) => number): T {
|
|
|
62
62
|
length = run(wasm);
|
|
63
63
|
} catch (error) {
|
|
64
64
|
instance = undefined;
|
|
65
|
-
throw new Refusal("operation-failed", `the decompiler stopped: ${
|
|
65
|
+
throw new Refusal("operation-failed", `the decompiler stopped: ${describeError(error)}`);
|
|
66
66
|
}
|
|
67
67
|
const reply = JSON.parse(utf8.decode(new Uint8Array(wasm.memory.buffer, wasm.out_ptr(), length))) as T & { error?: string };
|
|
68
68
|
if (reply.error !== undefined) throw new Refusal("operation-failed", reply.error);
|
package/src/native/discover.ts
CHANGED
|
@@ -153,7 +153,7 @@ export function isOlderThanMinimum(version: { major: number; minor: number }): b
|
|
|
153
153
|
}
|
|
154
154
|
|
|
155
155
|
/** A file this process may run. Windows has no execute permission (X_OK checks nothing there): a file is enough. */
|
|
156
|
-
|
|
156
|
+
function isExecutableFile(path: string): boolean {
|
|
157
157
|
try {
|
|
158
158
|
if (!statSync(path).isFile()) return false;
|
|
159
159
|
if (process.platform !== "win32") accessSync(path, constants.X_OK);
|
package/src/native/dxa.ts
CHANGED
|
@@ -8,9 +8,9 @@
|
|
|
8
8
|
import { writeFileSync } from "node:fs";
|
|
9
9
|
import { stripVTControlCharacters } from "node:util";
|
|
10
10
|
|
|
11
|
-
import { Refusal } from "../errors.ts";
|
|
12
|
-
import { SYMBOL_NAME } from "../c64.ts";
|
|
13
|
-
import {
|
|
11
|
+
import { describeError, Refusal } from "../errors.ts";
|
|
12
|
+
import { hexWord, SYMBOL_NAME } from "../c64.ts";
|
|
13
|
+
import { WireFailure } from "../protocol/messages.ts";
|
|
14
14
|
import { checkDxaResult, checkRequestBounds, imageRange, seedsInside, type DxaParams, type DxaResult, type SeedReport } from "./types.ts";
|
|
15
15
|
import { Workspace } from "./staging.ts";
|
|
16
16
|
import { DXA, findTool } from "./discover.ts";
|
|
@@ -33,8 +33,6 @@ const MAX_LISTING = 8 * 1024 * 1024;
|
|
|
33
33
|
const VERSION_TIMEOUT_MS = 20_000;
|
|
34
34
|
const MAX_VERSION_OUTPUT = 64 * 1024;
|
|
35
35
|
|
|
36
|
-
const hex = (value: number) => value.toString(16).padStart(4, "0");
|
|
37
|
-
|
|
38
36
|
/**
|
|
39
37
|
* The options for one run; every value comes from the validated request. A
|
|
40
38
|
* seed file is passed only when it has lines: dxa refuses an empty one.
|
|
@@ -85,16 +83,16 @@ export function parseListing(listing: string, start: number, end: number): Pick<
|
|
|
85
83
|
const first = statements[0];
|
|
86
84
|
const last = statements.at(-1);
|
|
87
85
|
if (first === undefined || last === undefined) throw new Refusal("operation-failed", "the listing has no statements");
|
|
88
|
-
if (first.address !== start) throw new Refusal("operation-failed", `the listing starts at $${
|
|
86
|
+
if (first.address !== start) throw new Refusal("operation-failed", `the listing starts at $${hexWord(first.address)}, not at $${hexWord(start)}`);
|
|
89
87
|
if (last.address > end) throw new Refusal("operation-failed", "the listing runs past the end of the program");
|
|
90
88
|
const regions: DxaResult["regions"] = [];
|
|
91
89
|
statements.forEach((statement, index) => {
|
|
92
90
|
const next = statements[index + 1]?.address ?? end + 1;
|
|
93
91
|
const size = next - statement.address;
|
|
94
|
-
if (size <= 0) throw new Refusal("operation-failed", `the listing goes back at $${
|
|
92
|
+
if (size <= 0) throw new Refusal("operation-failed", `the listing goes back at $${hexWord(next)}`);
|
|
95
93
|
// Data lines count their items; an instruction line dumps exactly its bytes.
|
|
96
94
|
const expected = statement.data ?? statement.dumped;
|
|
97
|
-
if (expected !== size) throw new Refusal("operation-failed", `the line at $${
|
|
95
|
+
if (expected !== size) throw new Refusal("operation-failed", `the line at $${hexWord(statement.address)} holds ${expected} bytes, but the next line is ${size} bytes later`);
|
|
98
96
|
const classification = statement.data === undefined ? "code" : "data";
|
|
99
97
|
const last = regions.at(-1);
|
|
100
98
|
if (last?.classification === classification) last.end = next - 1;
|
|
@@ -135,10 +133,10 @@ export async function analyze(
|
|
|
135
133
|
writeFileSync(workspace.path(`${name}.txt`), lines.join(""));
|
|
136
134
|
files[name] = `${name}.txt`;
|
|
137
135
|
};
|
|
138
|
-
seed("routines", entryPoints.map((address) => `${
|
|
139
|
-
seed("blocks", dataRanges.map((range) => `${
|
|
136
|
+
seed("routines", entryPoints.map((address) => `${hexWord(address)}\n`));
|
|
137
|
+
seed("blocks", dataRanges.map((range) => `${hexWord(range.start)}-${hexWord(range.end)}\n`));
|
|
140
138
|
// The xa label file format: name, address, flags. dxa reads the name up to the first blank, so a leading dot stays.
|
|
141
|
-
seed("labels", params.labels.filter((label) => SYMBOL_NAME.test(label.name)).map((label) => `${label.name}, 0x${
|
|
139
|
+
seed("labels", params.labels.filter((label) => SYMBOL_NAME.test(label.name)).map((label) => `${label.name}, 0x${hexWord(label.address)}, 0x0000\n`));
|
|
142
140
|
const run = await runToolOrFail(
|
|
143
141
|
"dxa",
|
|
144
142
|
"The DXA analysis",
|
package/src/native/exomizer.ts
CHANGED
|
@@ -18,7 +18,7 @@ const PACKED = "packed.prg";
|
|
|
18
18
|
const UNPACKED = "unpacked.prg";
|
|
19
19
|
|
|
20
20
|
/** The unpacker of Exomizer runs below $0400; the emulator of desfx stops when the program counter leaves that area. */
|
|
21
|
-
|
|
21
|
+
const MIN_ENTRY = 0x0400;
|
|
22
22
|
|
|
23
23
|
export interface PackParams {
|
|
24
24
|
/** The PRG files in load order: where two overlap, the later one wins. */
|
package/src/native/processes.ts
CHANGED
|
@@ -10,7 +10,7 @@ import { Refusal } from "../errors.ts";
|
|
|
10
10
|
import { WireFailure } from "../protocol/messages.ts";
|
|
11
11
|
|
|
12
12
|
/** How long a process group gets between SIGTERM and SIGKILL. */
|
|
13
|
-
|
|
13
|
+
const STOP_GRACE_MS = 5_000;
|
|
14
14
|
/** How long to wait for the group to vanish after SIGKILL before giving up. */
|
|
15
15
|
const KILL_WAIT_MS = 2_000;
|
|
16
16
|
const POLL_MS = 25;
|
|
@@ -72,6 +72,9 @@ export function isAlive(pid: number): boolean {
|
|
|
72
72
|
|
|
73
73
|
/** Linux: true while a member of the process group runs; zombies do not count. */
|
|
74
74
|
function groupRuns(pgid: number): boolean {
|
|
75
|
+
// The leader has the pid of the group: while it runs in the group, no scan of /proc is needed.
|
|
76
|
+
const leader = linuxProcess(pgid);
|
|
77
|
+
if (leader !== undefined && leader.group === pgid && !exitedState(leader.state)) return true;
|
|
75
78
|
for (const entry of readdirSync("/proc")) {
|
|
76
79
|
if (!/^\d+$/.test(entry)) continue;
|
|
77
80
|
const found = linuxProcess(entry);
|
package/src/native/run.ts
CHANGED
|
@@ -9,8 +9,8 @@ import { WireFailure } from "../protocol/messages.ts";
|
|
|
9
9
|
import { elapsedMs, trace } from "../trace.ts";
|
|
10
10
|
import type { ProcessSupervisor } from "./processes.ts";
|
|
11
11
|
|
|
12
|
-
|
|
13
|
-
|
|
12
|
+
const DEFAULT_TOOL_TIMEOUT_MS = 60_000;
|
|
13
|
+
const DEFAULT_OUTPUT_LIMIT = 1024 * 1024;
|
|
14
14
|
|
|
15
15
|
/** What running a native tool needs from its caller: the supervisor that owns it, the request's abort signal, and optionally its environment and a log. */
|
|
16
16
|
export interface ToolContext {
|
|
@@ -136,7 +136,7 @@ export async function runTool(options: {
|
|
|
136
136
|
await closed;
|
|
137
137
|
output.stdout += decoders.stdout.end();
|
|
138
138
|
output.stderr += decoders.stderr.end();
|
|
139
|
-
trace().event("tool.run", { argv: options.argv, cwd: options.cwd, pid: child.pid, ms: elapsedMs(started), ...status, timedOut, aborted, truncated: output.truncated, stdout: lastLines(output.stdout), stderr: lastLines(output.stderr) });
|
|
139
|
+
if (trace().on) trace().event("tool.run", { argv: options.argv, cwd: options.cwd, pid: child.pid, ms: elapsedMs(started), ...status, timedOut, aborted, truncated: output.truncated, stdout: lastLines(output.stdout), stderr: lastLines(output.stderr) });
|
|
140
140
|
return { ...status, ...output, timedOut, aborted };
|
|
141
141
|
} finally {
|
|
142
142
|
clearTimeout(timer);
|
package/src/native/types.ts
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
// (a program, an image, a listing) go next to these values as attachments.
|
|
5
5
|
|
|
6
6
|
import { Refusal } from "../errors.ts";
|
|
7
|
-
import { prgRange, REFERENCE_KINDS, SYMBOL_NAME, type ReferenceKind } from "../c64.ts";
|
|
7
|
+
import { inRanges, prgRange, REFERENCE_KINDS, SYMBOL_NAME, type ReferenceKind } from "../c64.ts";
|
|
8
8
|
import { isInteger, isObject, isOneOf, WireFailure } from "../protocol/messages.ts";
|
|
9
9
|
import { type SourceTree } from "../protocol/tools.ts";
|
|
10
10
|
|
|
@@ -40,7 +40,7 @@ export interface AcmeResult {
|
|
|
40
40
|
diagnostics: Diagnostic[];
|
|
41
41
|
}
|
|
42
42
|
|
|
43
|
-
|
|
43
|
+
const IMAGE_KINDS = ["prg", "flat64k"] as const;
|
|
44
44
|
export type ImageKind = (typeof IMAGE_KINDS)[number];
|
|
45
45
|
|
|
46
46
|
export const DECOMPILER_LIMITS = { entryPoints: 1024, codeStarts: 8192, dataRanges: 1024, labels: 4096, decompile: 32, decompiledChars: 16_000, decompiledTotalChars: 128_000 } as const;
|
|
@@ -142,11 +142,10 @@ export function checkDecompilerResult(value: unknown): DecompilerResult {
|
|
|
142
142
|
if (!isObject(range) || !isInteger(range.start, 0, 0xffff) || !isInteger(range.end, range.start, 0xffff)) fail("bad coverage range");
|
|
143
143
|
ranges.push({ start: range.start, end: range.end });
|
|
144
144
|
}
|
|
145
|
-
const covered = (address: number) => ranges.some((range) => range.start <= address && address <= range.end);
|
|
146
145
|
if (!isList(functions)) fail("no functions");
|
|
147
146
|
for (const fn of functions) {
|
|
148
147
|
if (!isObject(fn) || !isInteger(fn.entry, 0, 0xffff) || typeof fn.name !== "string" || !SYMBOL_NAME.test(fn.name) || !isOneOf(["seed", "generated", "native"] as const, fn.nameSource)) fail("bad function");
|
|
149
|
-
if (!
|
|
148
|
+
if (!inRanges(ranges, fn.entry)) fail("a function lies outside the coverage");
|
|
150
149
|
}
|
|
151
150
|
if (!isList(regions)) fail("no regions");
|
|
152
151
|
let previousEnd = -1;
|
|
@@ -172,12 +171,12 @@ export function checkDecompilerResult(value: unknown): DecompilerResult {
|
|
|
172
171
|
) {
|
|
173
172
|
fail("bad instruction");
|
|
174
173
|
}
|
|
175
|
-
if (!
|
|
174
|
+
if (!inRanges(ranges, instruction.address)) fail("an instruction lies outside the coverage");
|
|
176
175
|
}
|
|
177
176
|
if (!isList(references)) fail("no references");
|
|
178
177
|
for (const reference of references) {
|
|
179
178
|
if (!isObject(reference) || !isInteger(reference.from, 0, 0xffff) || !isInteger(reference.to, 0, 0xffff) || !isOneOf(REFERENCE_KINDS, reference.type)) fail("bad reference");
|
|
180
|
-
if (!
|
|
179
|
+
if (!inRanges(ranges, reference.from)) fail("a reference source lies outside the coverage");
|
|
181
180
|
}
|
|
182
181
|
if (!isList(decompilations) || decompilations.length > DECOMPILER_LIMITS.decompile) fail("bad decompilations");
|
|
183
182
|
let total = 0;
|
package/src/opcodes.ts
CHANGED
|
@@ -42,6 +42,9 @@ export const OPCODES: readonly Opcode[] = (() => {
|
|
|
42
42
|
|
|
43
43
|
export const MODE_LENGTH: Record<Mode, 1 | 2 | 3> = { imp: 1, imm: 2, zp: 2, zpx: 2, zpy: 2, izx: 2, izy: 2, rel: 2, abs: 3, abx: 3, aby: 3, ind: 3 };
|
|
44
44
|
|
|
45
|
+
/** The 12 opcodes that jam an NMOS 6502/6510. */
|
|
46
|
+
export const JAM_OPCODES: ReadonlySet<number> = new Set(OPCODES.flatMap((opcode, code) => (opcode.mnemonic === "jam" ? [code] : [])));
|
|
47
|
+
|
|
45
48
|
/** Every mnemonic in the table: a symbol with one of these names would read as an instruction. */
|
|
46
49
|
export const MNEMONICS: ReadonlySet<string> = new Set(OPCODES.map((opcode) => opcode.mnemonic));
|
|
47
50
|
|
package/src/platform.ts
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
// Names follow "Mapping the Commodore 64". Only platform facts live here:
|
|
4
4
|
// an address without one belongs to the application.
|
|
5
5
|
|
|
6
|
-
import { type AddressRange, COVERAGE, d018Offsets, formatC64Address, romOnlyRanges, vicBankBase } from "./c64.ts";
|
|
6
|
+
import { type AddressRange, COVERAGE, d018Offsets, formatC64Address, inRanges, rangesWhere, romOnlyRanges, vicBankBase } from "./c64.ts";
|
|
7
7
|
import { Refusal } from "./errors.ts";
|
|
8
8
|
|
|
9
9
|
export interface Entry {
|
|
@@ -380,6 +380,11 @@ export function platformNames(): Array<{ address: number; end: number; name: str
|
|
|
380
380
|
.filter((entry) => !seen.has(entry.name) && seen.add(entry.name) !== undefined);
|
|
381
381
|
}
|
|
382
382
|
|
|
383
|
+
/** The address of each platform name: the operand images of the knowledge read a name in an expression with it. */
|
|
384
|
+
export function platformAddresses(): Map<string, number> {
|
|
385
|
+
return new Map(platformNames().map((entry) => [entry.name, entry.address]));
|
|
386
|
+
}
|
|
387
|
+
|
|
383
388
|
/** Which ROMs a program uses: a ROM it does not use gives no names, and without both the system area gives none. */
|
|
384
389
|
export interface RomUse {
|
|
385
390
|
basic: boolean;
|
|
@@ -445,19 +450,13 @@ const KERNAL_ROM: AddressRange = { start: 0xe000, end: 0xffff };
|
|
|
445
450
|
* that code stays code.
|
|
446
451
|
*/
|
|
447
452
|
export function romRanges(coverage: Uint8Array | undefined, state: Record<string, unknown> | undefined, image: (address: number) => number | undefined, known: readonly number[]): AddressRange[] {
|
|
448
|
-
let ranges: AddressRange[]
|
|
453
|
+
let ranges: AddressRange[];
|
|
449
454
|
if (coverage !== undefined) ranges = romOnlyRanges(coverage, image);
|
|
450
455
|
else {
|
|
451
456
|
const port = (state?.cpuPort as Record<string, unknown> | undefined)?.$01;
|
|
452
457
|
const use = typeof port === "number" ? romUseOfPort(port) : { basic: false, kernal: false };
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
if (image(address) === undefined) continue;
|
|
456
|
-
const last = ranges.at(-1);
|
|
457
|
-
if (last !== undefined && last.end === address - 1) last.end = address;
|
|
458
|
-
else ranges.push({ start: address, end: address });
|
|
459
|
-
}
|
|
460
|
-
}
|
|
458
|
+
const roms = [...(use.basic ? [BASIC_ROM] : []), ...(use.kernal ? [KERNAL_ROM] : [])];
|
|
459
|
+
ranges = rangesWhere((address) => inRanges(roms, address) && image(address) !== undefined);
|
|
461
460
|
}
|
|
462
461
|
return ranges.filter((range) => !known.some((address) => address >= range.start && address <= range.end));
|
|
463
462
|
}
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
// The code of a program from the knowledge: the decode of the decompiler, and
|
|
2
|
+
// the input of the code reach (src/knowledge/code-reach.ts). It joins the
|
|
3
|
+
// knowledge with the native decompiler and the ROM map of the platform, for
|
|
4
|
+
// c64-source and c64-provenance.
|
|
5
|
+
|
|
6
|
+
import { type AddressRange, coverageSeedKinds, findHandoffs, inRanges, parseTokenized, rangesOverlap } from "./c64.ts";
|
|
7
|
+
import { type CodeKnowledge, type CodeReachInput, effectiveRegions } from "./knowledge/code-reach.ts";
|
|
8
|
+
import { identifiers } from "./knowledge/expression.ts";
|
|
9
|
+
import { analyzedBytes, type ProgramImage } from "./knowledge/program.ts";
|
|
10
|
+
import { startScreenRanges } from "./knowledge/read.ts";
|
|
11
|
+
import { CODE_REGION_TYPES, INSTRUCTION_REGION_TYPES } from "./knowledge/schema.ts";
|
|
12
|
+
import { analyze } from "./native/decompiler/analyze.ts";
|
|
13
|
+
import { localToolContext } from "./native/local.ts";
|
|
14
|
+
import { DECOMPILER_LIMITS } from "./native/types.ts";
|
|
15
|
+
import { romRanges } from "./platform.ts";
|
|
16
|
+
|
|
17
|
+
/** The byte of the image at an address, or undefined outside its segments. */
|
|
18
|
+
const imageByte = (image: ProgramImage) => (address: number) => (inRanges(image.segments, address) ? image.byteAt(address) : undefined);
|
|
19
|
+
|
|
20
|
+
/** Where the CPU sees ROM in the image (romRanges): the entry, the routines, the code regions and `entries` stay code. */
|
|
21
|
+
function romOf(image: ProgramImage, knowledge: Pick<CodeKnowledge, "routines" | "regions">, entries: readonly number[], coverage: Uint8Array | undefined): AddressRange[] {
|
|
22
|
+
const code = knowledge.regions.filter((region) => INSTRUCTION_REGION_TYPES.includes(region.type)).map((region) => region.start);
|
|
23
|
+
const known = [...(image.entry === undefined ? [] : [image.entry]), ...entries, ...knowledge.routines, ...code];
|
|
24
|
+
return romRanges(coverage, image.state, imageByte(image), known);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* The decompiler's instruction starts and lengths inside the image, seeded from the
|
|
29
|
+
* entry, from knowledge of any origin, and from the coverage: a run's flow
|
|
30
|
+
* starts, also after a JSR, so code that an analyzer does not reach by itself
|
|
31
|
+
* is in the source. A program without a seed has no known code: it is data
|
|
32
|
+
* only, and the decompiler does not run.
|
|
33
|
+
*/
|
|
34
|
+
export async function decodeProgram(image: ProgramImage, knowledge: Pick<CodeKnowledge, "routines" | "regions">, entries: readonly number[], coverage: Uint8Array | undefined): Promise<{ instructions: Map<number, number>; dataOnly: boolean }> {
|
|
35
|
+
const inImage = (address: number) => inRanges(image.segments, address);
|
|
36
|
+
const seeds = new Set<number>([...(image.entry === undefined ? [] : [image.entry]), ...entries]);
|
|
37
|
+
for (const address of knowledge.routines) seeds.add(address);
|
|
38
|
+
const flows = coverage === undefined ? { routines: [], codeStarts: [] } : coverageSeedKinds(coverage, imageByte(image));
|
|
39
|
+
for (const address of flows.routines) seeds.add(address);
|
|
40
|
+
for (const region of knowledge.regions) {
|
|
41
|
+
if (CODE_REGION_TYPES.includes(region.type)) seeds.add(region.start);
|
|
42
|
+
if (region.type === "jumps") for (let at = region.start; at + 2 <= region.end; at += 3) seeds.add(at);
|
|
43
|
+
}
|
|
44
|
+
const entryPoints = [...seeds].filter(inImage).sort((a, b) => a - b);
|
|
45
|
+
if (entryPoints.length === 0) {
|
|
46
|
+
// An entry in no segment is a capture fault: the image is data only, and the result says entryOutside.
|
|
47
|
+
return { instructions: new Map(), dataOnly: image.entry === undefined || inImage(image.entry) };
|
|
48
|
+
}
|
|
49
|
+
const dataRanges = knowledge.regions
|
|
50
|
+
.filter((region) => !INSTRUCTION_REGION_TYPES.includes(region.type))
|
|
51
|
+
.flatMap((region) => image.segments.filter((segment) => rangesOverlap(region, segment)).map((segment) => ({ start: Math.max(region.start, segment.start), end: Math.min(region.end, segment.end) })));
|
|
52
|
+
// A JSR into ROM runs the ROM: the RAM bytes of the image under it are data, not the code of the call.
|
|
53
|
+
for (const range of romOf(image, knowledge, entries, coverage)) if (!dataRanges.some((data) => rangesOverlap(range, data))) dataRanges.push(range);
|
|
54
|
+
const { result } = await analyze(
|
|
55
|
+
{
|
|
56
|
+
imageKind: analyzedBytes(image).kind,
|
|
57
|
+
entryPoints: entryPoints.slice(0, DECOMPILER_LIMITS.entryPoints),
|
|
58
|
+
codeStarts: flows.codeStarts.filter((address) => !seeds.has(address)).slice(0, DECOMPILER_LIMITS.codeStarts),
|
|
59
|
+
dataRanges: dataRanges.slice(0, DECOMPILER_LIMITS.dataRanges),
|
|
60
|
+
labels: [],
|
|
61
|
+
decompile: [],
|
|
62
|
+
},
|
|
63
|
+
analyzedBytes(image).bytes,
|
|
64
|
+
localToolContext(),
|
|
65
|
+
);
|
|
66
|
+
const instructions = new Map<number, number>();
|
|
67
|
+
for (const instruction of result.instructions) {
|
|
68
|
+
const bytes = Buffer.from(instruction.bytes, "hex");
|
|
69
|
+
const inside = Array.from({ length: bytes.length }, (_, offset) => instruction.address + offset).every((address, offset) => inImage(address) && image.byteAt(address) === bytes[offset]);
|
|
70
|
+
if (inside) instructions.set(instruction.address, bytes.length);
|
|
71
|
+
}
|
|
72
|
+
return { instructions, dataOnly: false };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* The BASIC line that starts a PRG: its bytes, and the address of its first
|
|
77
|
+
* SYS when the image holds it (the entry of a PRG without one in the
|
|
78
|
+
* knowledge). Undefined when the first segment holds no BASIC line with a SYS.
|
|
79
|
+
*/
|
|
80
|
+
function basicStart(image: ProgramImage): { line: AddressRange; entry?: number } | undefined {
|
|
81
|
+
const first = image.segments[0];
|
|
82
|
+
if (first === undefined) return undefined;
|
|
83
|
+
const tokenized = parseTokenized(Uint8Array.from([first.start & 0xff, first.start >> 8, ...image.memory.subarray(first.start, first.end + 1)]));
|
|
84
|
+
if ("reason" in tokenized) return undefined;
|
|
85
|
+
const sys = findHandoffs(tokenized.lines).find((handoff) => handoff.kind === "sys");
|
|
86
|
+
if (sys === undefined) return undefined;
|
|
87
|
+
const line = { start: first.start, end: Math.min(first.end, tokenized.basicEnd - 1) };
|
|
88
|
+
const address = "address" in sys ? sys.address : undefined;
|
|
89
|
+
return address !== undefined && inRanges(image.segments, address) ? { line, entry: address } : { line };
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* The input of the code reach of a program from the knowledge. `memory` and
|
|
94
|
+
* `instructions` are of the build that the code is in. `basic` is the BASIC
|
|
95
|
+
* line that starts the program: RUN reads it, which no coverage from the entry
|
|
96
|
+
* shows.
|
|
97
|
+
*/
|
|
98
|
+
export function reachInput(
|
|
99
|
+
knowledge: Pick<CodeKnowledge, "program" | "coverage" | "symbols" | "routines" | "regions" | "references" | "operands">,
|
|
100
|
+
memory: Uint8Array,
|
|
101
|
+
instructions: ReadonlyMap<number, number>,
|
|
102
|
+
ranges: { changed: readonly AddressRange[]; keep: readonly AddressRange[]; drop: readonly AddressRange[] },
|
|
103
|
+
): CodeReachInput & { basic?: AddressRange } {
|
|
104
|
+
const image = knowledge.program;
|
|
105
|
+
const addressOf = new Map(knowledge.symbols.map((symbol) => [symbol.name, symbol.address]));
|
|
106
|
+
const operandTargets = new Map<number, number[]>();
|
|
107
|
+
for (const operand of knowledge.operands) {
|
|
108
|
+
const names = operand.symbol !== undefined ? [operand.symbol] : identifiers(operand.expression ?? "");
|
|
109
|
+
const targets = names.flatMap((item) => (addressOf.has(item) ? [(addressOf.get(item)! + (operand.symbol !== undefined ? operand.offset : 0)) & 0xffff] : []));
|
|
110
|
+
operandTargets.set(operand.address, targets);
|
|
111
|
+
}
|
|
112
|
+
const basic = basicStart(image);
|
|
113
|
+
const entry = image.entry ?? basic?.entry;
|
|
114
|
+
return {
|
|
115
|
+
segments: image.segments,
|
|
116
|
+
memory,
|
|
117
|
+
...(entry === undefined ? {} : { entry }),
|
|
118
|
+
instructions,
|
|
119
|
+
...(knowledge.coverage === undefined ? {} : { coverage: knowledge.coverage }),
|
|
120
|
+
regions: effectiveRegions(knowledge.regions),
|
|
121
|
+
references: knowledge.references,
|
|
122
|
+
operandTargets,
|
|
123
|
+
rom: romOf(image, knowledge, [], knowledge.coverage),
|
|
124
|
+
...(basic === undefined ? {} : { basic: basic.line }),
|
|
125
|
+
changed: [...ranges.changed],
|
|
126
|
+
keep: [...ranges.keep],
|
|
127
|
+
drop: [...ranges.drop],
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** The names and the four-digit hex addresses that the code of a patch has: a switch can go to them, so they stay. */
|
|
132
|
+
function patchTargets(code: string, addressOf: ReadonlyMap<string, number>): number[] {
|
|
133
|
+
const words = code.replace(/;.*$/gm, "").match(/\$[0-9a-fA-F]{4}\b|[A-Za-z_][A-Za-z0-9_]*/g) ?? [];
|
|
134
|
+
return words.flatMap((word) => (word.startsWith("$") ? [Number.parseInt(word.slice(1), 16)] : addressOf.has(word) ? [addressOf.get(word)!] : []));
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* The input of the code reach for the leftovers of the program as it is. The
|
|
139
|
+
* start screen in the program, the patches, what the code of a patch names
|
|
140
|
+
* and the ranges of `kept` stay, so each switch builds without the leftovers.
|
|
141
|
+
*/
|
|
142
|
+
export function leftoverInput(knowledge: CodeKnowledge, instructions: ReadonlyMap<number, number>, kept: readonly AddressRange[] = []): CodeReachInput & { basic?: AddressRange } {
|
|
143
|
+
const image = knowledge.program;
|
|
144
|
+
const inImage = (range: AddressRange) => image.segments.some((segment) => range.start >= segment.start && range.end <= segment.end);
|
|
145
|
+
const addressOf = new Map(knowledge.symbols.map((symbol) => [symbol.name, symbol.address]));
|
|
146
|
+
const screenParts = knowledge.startScreen === undefined || knowledge.startScreen.stage !== undefined ? [] : startScreenRanges(knowledge.startScreen).map((part) => part.range);
|
|
147
|
+
const named = knowledge.patches.flatMap((patch) => patchTargets(patch.code, addressOf)).map((address) => ({ start: address, end: address }));
|
|
148
|
+
const keep = [...screenParts, ...kept, ...named].map((range) => ({ start: range.start, end: range.end })).filter(inImage);
|
|
149
|
+
const changed = knowledge.patches.map((patch) => ({ start: patch.start, end: patch.end })).filter(inImage);
|
|
150
|
+
return reachInput(knowledge, image.memory, instructions, { changed, keep, drop: [] });
|
|
151
|
+
}
|