@henols/c64-re-tools 2.6.0-rc.7 → 2.6.0-rc.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/package.json +2 -2
- package/skills/c64-docs/SKILL.md +1 -1
- package/skills/c64-docs/scripts/docs.ts +6 -6
- package/skills/c64-knowledge/SKILL.md +3 -3
- package/skills/c64-knowledge/scripts/knowledge.ts +2 -0
- package/skills/c64-knowledge/scripts/lib/listing.ts +18 -3
- package/skills/c64-reverse-engineering/SKILL.md +1 -1
- package/skills/c64-source/SKILL.md +7 -7
- package/skills/c64-source/scripts/lib/source.ts +10 -0
- package/skills/c64-source/scripts/source.ts +32 -27
- package/skills/c64-static-analysis/SKILL.md +5 -3
- package/skills/c64-static-analysis/scripts/lib/instructions.ts +22 -20
- package/skills/c64-static-analysis/scripts/static-analysis.ts +16 -16
- package/skills/c64-testing/SKILL.md +2 -1
- package/skills/c64-testing/references/recording-format.md +17 -3
- package/skills/c64-testing/references/scenario-format.md +2 -3
- package/skills/c64-testing/scripts/lib/diff-files.ts +4 -18
- package/skills/c64-testing/scripts/lib/play.ts +39 -41
- package/skills/c64-testing/scripts/lib/recording.ts +21 -29
- package/skills/c64-testing/scripts/lib/runs.ts +2 -2
- package/skills/c64-testing/scripts/lib/scenario.ts +3 -5
- package/skills/c64-unpacker/SKILL.md +2 -1
- package/skills/c64-unpacker/scripts/lib/loads.ts +2 -2
- package/skills/emulator/SKILL.md +2 -5
- package/src/c64-keys.ts +98 -0
- package/src/cli/main.ts +1 -1
- package/src/host/vice/session.ts +82 -8
- package/src/host-client/steps.ts +17 -17
- package/src/host-client/tools.ts +1 -1
- package/src/host-client/vice-session.ts +7 -1
- package/src/knowledge/read.ts +25 -1
- package/src/mcp/inputs.ts +12 -0
- package/src/mcp/server.ts +1 -0
- package/src/mcp/tools/input.ts +38 -5
- package/src/native/c64run.ts +1 -1
- package/src/native/discover.ts +3 -3
- package/src/native/ghidra/analyze.ts +74 -63
- package/src/native/ghidra/c64rt-wasm.ts +4 -0
- package/src/native/ghidra/language/c64rt_6510.sla +0 -0
- package/src/native/ghidra/pcode.ts +222 -0
- package/src/native/ghidra/walk.ts +205 -0
- package/src/native/ghidra/wasm.ts +98 -0
- package/src/native/processes.ts +4 -4
- package/src/native/types.ts +2 -2
- package/src/project.ts +4 -3
- package/src/protocol/vice.ts +47 -0
- package/src/script.ts +1 -1
- package/src/vsf.ts +98 -0
- package/tools/c64run.c +9 -12
- package/tools/install-container.sh +1 -2
- package/src/native/ghidra/index.ts +0 -170
- package/src/native/ghidra/scripts/C64Export.java +0 -274
- package/src/native/ghidra/scripts/C64Prepare.java +0 -66
- package/tools/install-ghidra.sh +0 -40
package/src/host/vice/session.ts
CHANGED
|
@@ -5,13 +5,14 @@
|
|
|
5
5
|
|
|
6
6
|
import { isOneOf, WireFailure, type VideoStandard } from "../../protocol/messages.ts";
|
|
7
7
|
import { DISK_IMAGE_TYPES, type DiskFile, type DiskImageType } from "../../protocol/tools.ts";
|
|
8
|
-
import { MAX_BASELINES, MAX_SNAPSHOTS, MAX_COMPARE_DIFFERENCES, RASTER, type Breakpoint, type BreakpointParams, type PointRemoved, type Condition, type ExecutionParams, type HistoryEntry, type RunTarget, type RunUntilResult, type ScreenComparison, type CiaSelection, type CiaState, type ObserveParams, type ObserveResult, type SidState, type SpriteState, type ViciiState, type JoystickState, type Watchpoint, type WatchpointParams, type ExecutionResult, type MachineStatus, type TraceHit, type TraceKind, type TraceResult, type PointStopReason, type RunState, type ViceOperation, type ViceOperations, type WindowResult } from "../../protocol/vice.ts";
|
|
8
|
+
import { MAX_BASELINES, MAX_SNAPSHOTS, MAX_COMPARE_DIFFERENCES, RASTER, type Breakpoint, type BreakpointParams, type PointRemoved, type Condition, type ExecutionParams, type HistoryEntry, type RunTarget, type RunUntilResult, type ScreenComparison, type CiaSelection, type CiaState, type ObserveParams, type ObserveResult, type SidState, type SpriteState, type ViciiState, type JoystickState, type Watchpoint, type WatchpointParams, type ExecutionResult, type MachineStatus, type TraceHit, type TraceKind, type TraceResult, type PointStopReason, type PressResult, type RunState, type ViceOperation, type ViceOperations, type WindowResult } from "../../protocol/vice.ts";
|
|
9
9
|
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
10
10
|
import { tmpdir } from "node:os";
|
|
11
11
|
import { join } from "node:path";
|
|
12
12
|
import { setTimeout as sleep } from "node:timers/promises";
|
|
13
13
|
|
|
14
14
|
import { formatC64Address, instructionLength } from "../../c64.ts";
|
|
15
|
+
import { matrixRows } from "../../c64-keys.ts";
|
|
15
16
|
import { encodePng, type IndexedFrame } from "../../graphics.ts";
|
|
16
17
|
import { accessedValue, instructionText, operandAddress } from "../../opcodes.ts";
|
|
17
18
|
import type { ProcessSupervisor } from "../../native/processes.ts";
|
|
@@ -33,6 +34,7 @@ import { compareFrames, differenceImage } from "./screen.ts";
|
|
|
33
34
|
import { isRefusal } from "../../errors.ts";
|
|
34
35
|
import type { ViceFeature, ViceFlaw } from "../../native/discover.ts";
|
|
35
36
|
import { checkMedia, hasSignature } from "../../media.ts";
|
|
37
|
+
import { pressSnapshotRestore, setSnapshotMatrix } from "../../vsf.ts";
|
|
36
38
|
import { launchVice, startErrorLines, type ViceMode, type ViceProcess } from "./process.ts";
|
|
37
39
|
import { TextMonitorError, TextMonitorTimeoutError } from "./text-monitor.ts";
|
|
38
40
|
|
|
@@ -136,6 +138,7 @@ export interface SessionOptions {
|
|
|
136
138
|
const BROKEN_MESSAGES: Record<ViceFeature, string> = {
|
|
137
139
|
joystick: "Joystick input is not implemented in this setup. Do not use the joystick in this task. Give this message to the user.",
|
|
138
140
|
tape: "The load of a tape image is not implemented in this setup. Do not load tape images in this task. Give this message to the user.",
|
|
141
|
+
keyboard: "Keys of the keyboard matrix are not implemented in this setup. Do not press keys in this task. Give this message to the user.",
|
|
139
142
|
};
|
|
140
143
|
|
|
141
144
|
export type DiskDirectory = (type: DiskImageType, image: Buffer) => Promise<DiskFile[]>;
|
|
@@ -472,16 +475,12 @@ export class ViceSession implements ViceSessionHandle {
|
|
|
472
475
|
return this.#reset(params as ViceOperations["reset"]["params"]);
|
|
473
476
|
case "keyboard": {
|
|
474
477
|
const bytes = Buffer.from((params as ViceOperations["keyboard"]["params"]).data, "hex");
|
|
475
|
-
|
|
476
|
-
if (this.#autostarting && !this.#userWarp && (await this.#observe(() => this.#machine.warp()))) {
|
|
477
|
-
throw new WireFailure(
|
|
478
|
-
"operation-failed",
|
|
479
|
-
"The autostart still loads the program, and a key now stops it before RUN. Run frames with c64_execution advance-frames, then type again.",
|
|
480
|
-
);
|
|
481
|
-
}
|
|
478
|
+
await this.#refuseWhileAutostartLoads("type");
|
|
482
479
|
await this.#observe(() => this.#machine.feedKeyboard(bytes));
|
|
483
480
|
return { queuedBytes: bytes.length };
|
|
484
481
|
}
|
|
482
|
+
case "press":
|
|
483
|
+
return this.#press(params as ViceOperations["press"]["params"]);
|
|
485
484
|
case "breakpoint":
|
|
486
485
|
return this.#breakpoint(params as BreakpointParams);
|
|
487
486
|
case "watchpoint":
|
|
@@ -1185,6 +1184,81 @@ export class ViceSession implements ViceSessionHandle {
|
|
|
1185
1184
|
return publicView(point);
|
|
1186
1185
|
}
|
|
1187
1186
|
|
|
1187
|
+
/** VICE turns warp on for an autostart and off when it types RUN. A key in between ends the autostart with no message. */
|
|
1188
|
+
async #refuseWhileAutostartLoads(verb: string): Promise<void> {
|
|
1189
|
+
if (this.#autostarting && !this.#userWarp && (await this.#observe(() => this.#machine.warp()))) {
|
|
1190
|
+
throw new WireFailure(
|
|
1191
|
+
"operation-failed",
|
|
1192
|
+
`The autostart still loads the program, and a key now stops it before RUN. Run frames with c64_execution advance-frames, then ${verb} again.`,
|
|
1193
|
+
);
|
|
1194
|
+
}
|
|
1195
|
+
}
|
|
1196
|
+
|
|
1197
|
+
/**
|
|
1198
|
+
* Presses keys of the keyboard matrix and RESTORE. VICE has no command for
|
|
1199
|
+
* that: a snapshot gets the keys in its keyboard module, and RESTORE as a
|
|
1200
|
+
* pending NMI, and is restored at the same cycle. Each tap holds its keys
|
|
1201
|
+
* for `frames` frames, then waits `frames` frames with all keys up. A
|
|
1202
|
+
* breakpoint, watchpoint or JAM ends the taps early, and the machine stays
|
|
1203
|
+
* stopped; else it runs again when it ran before. All keys are up at the end.
|
|
1204
|
+
*/
|
|
1205
|
+
async #press(params: ViceOperations["press"]["params"]): Promise<PressResult> {
|
|
1206
|
+
this.#refuseBroken("keyboard", "c64_press");
|
|
1207
|
+
await this.#refuseWhileAutostartLoads("press the keys");
|
|
1208
|
+
if (this.#atResetStop) {
|
|
1209
|
+
throw new WireFailure(
|
|
1210
|
+
"operation-failed",
|
|
1211
|
+
"The CPU stands at the reset stop of c64_reset with run false. The emulator stops answering when keys are pressed here while the disk drive is busy. " +
|
|
1212
|
+
"Step one instruction with c64_execution, then press the keys.",
|
|
1213
|
+
);
|
|
1214
|
+
}
|
|
1215
|
+
const running = this.#state === "running";
|
|
1216
|
+
await this.#stop();
|
|
1217
|
+
await this.#refuseJammed("press");
|
|
1218
|
+
let taps = 0;
|
|
1219
|
+
for (const tap of params.taps) {
|
|
1220
|
+
await this.#setKeys(matrixRows(tap.keys), tap.restore);
|
|
1221
|
+
const held = await this.#runFrames(params.frames);
|
|
1222
|
+
await this.#setKeys(matrixRows([]), false);
|
|
1223
|
+
const end = held.end === "frames" ? await this.#runFrames(params.frames) : held;
|
|
1224
|
+
if (end.end !== "frames") {
|
|
1225
|
+
this.#stopSpace = end.space;
|
|
1226
|
+
return {
|
|
1227
|
+
taps,
|
|
1228
|
+
state: "stopped",
|
|
1229
|
+
stopReason: end.end as PointStopReason,
|
|
1230
|
+
pc: end.space === "drive8" ? (await this.#machine.readRegisters("drive8")).pc : end.pc,
|
|
1231
|
+
space: end.space,
|
|
1232
|
+
...(end.pointId === undefined ? {} : { pointId: end.pointId }),
|
|
1233
|
+
};
|
|
1234
|
+
}
|
|
1235
|
+
taps++;
|
|
1236
|
+
}
|
|
1237
|
+
if (running) await this.#resume();
|
|
1238
|
+
return { taps, state: this.#state };
|
|
1239
|
+
}
|
|
1240
|
+
|
|
1241
|
+
/** Sets the keyboard matrix (`rows`, bit n of row r for column n), and presses RESTORE, in a snapshot restored at the same cycle. */
|
|
1242
|
+
async #setKeys(rows: number[], restore: boolean): Promise<void> {
|
|
1243
|
+
const file = join(this.#workDir, "press.vsf");
|
|
1244
|
+
try {
|
|
1245
|
+
await this.#machine.saveSnapshot(file);
|
|
1246
|
+
const bytes = readFileSync(file);
|
|
1247
|
+
const why = setSnapshotMatrix(bytes, rows) ?? (restore ? pressSnapshotRestore(bytes) : undefined);
|
|
1248
|
+
if (why !== undefined) {
|
|
1249
|
+
this.#log(`c64_press was used, and this VICE writes snapshots that c64-re-tools does not know: ${why}.`);
|
|
1250
|
+
throw new WireFailure("not-implemented", BROKEN_MESSAGES.keyboard);
|
|
1251
|
+
}
|
|
1252
|
+
writeFileSync(file, bytes);
|
|
1253
|
+
await this.#machine.restoreSnapshot(file);
|
|
1254
|
+
} finally {
|
|
1255
|
+
rmSync(file, { force: true });
|
|
1256
|
+
}
|
|
1257
|
+
// A restore starts the CPU history of VICE again.
|
|
1258
|
+
this.#historySince = await this.#machine.clock();
|
|
1259
|
+
if (this.#historyStopped) this.#historyOld = true;
|
|
1260
|
+
}
|
|
1261
|
+
|
|
1188
1262
|
/**
|
|
1189
1263
|
* Refuses a tool that a known flaw of this VICE breaks: not-implemented for
|
|
1190
1264
|
* the caller, without the VICE version, and the flaw on the host console.
|
package/src/host-client/steps.ts
CHANGED
|
@@ -7,13 +7,14 @@
|
|
|
7
7
|
// type c64_keyboard { mode: "text", text } or { mode: "petscii", bytes }: the KERNAL keyboard queue
|
|
8
8
|
// frames c64_execution the count of advance-frames
|
|
9
9
|
// runUntil c64_run_until { target, timeoutFrames? }
|
|
10
|
-
// press
|
|
10
|
+
// press c64_press { keys, frames? }: keys of the keyboard matrix and RESTORE
|
|
11
11
|
//
|
|
12
12
|
// An address in a step is $ and 1 to 4 hex digits, or a name that the script resolves.
|
|
13
13
|
// The scripts install without packages, so this checker has no zod: the MCP
|
|
14
14
|
// tools keep their zod schemas, and a test checks that both take the same inputs.
|
|
15
15
|
|
|
16
16
|
import { c64AddressOf, SYMBOL_NAME, textToPetscii } from "../c64.ts";
|
|
17
|
+
import { keyTaps, MAX_PRESS_FRAMES, PRESS_FRAMES, type KeyTap } from "../c64-keys.ts";
|
|
17
18
|
import { isRefusal, Refusal } from "../errors.ts";
|
|
18
19
|
import {
|
|
19
20
|
COMPARISONS,
|
|
@@ -57,14 +58,12 @@ export type ActionStep =
|
|
|
57
58
|
| { registers: { pc?: Location; a?: number; x?: number; y?: number; sp?: number; flags?: Flags } }
|
|
58
59
|
| { joystick: { port: 1 | 2; direction: (typeof JOYSTICK_DIRECTIONS)[number]; fire: boolean } }
|
|
59
60
|
| { type: KeyboardInput }
|
|
60
|
-
| { press: string }
|
|
61
|
+
| { press: { keys: string; frames: number } }
|
|
61
62
|
| { frames: number }
|
|
62
63
|
| { runUntil: { target: StepTarget; timeoutFrames: number } };
|
|
63
64
|
|
|
64
65
|
export const ACTION_STEP_KINDS = ["write", "registers", "joystick", "type", "press", "frames", "runUntil"] as const;
|
|
65
66
|
export type ActionStepKind = (typeof ACTION_STEP_KINDS)[number];
|
|
66
|
-
/** The step kinds that VICE runs: all but press, which only the replay core has. */
|
|
67
|
-
export const VICE_STEP_KINDS = ACTION_STEP_KINDS.filter((kind) => kind !== "press");
|
|
68
67
|
|
|
69
68
|
/** The fields of each object of the steps: the same as the inputs of the MCP tools. */
|
|
70
69
|
export const STEP_FIELDS = {
|
|
@@ -72,6 +71,7 @@ export const STEP_FIELDS = {
|
|
|
72
71
|
registers: ["pc", "a", "x", "y", "sp", "flags"],
|
|
73
72
|
joystick: ["port", "direction", "fire"],
|
|
74
73
|
type: ["mode", "text", "bytes"],
|
|
74
|
+
press: ["keys", "frames"],
|
|
75
75
|
runUntil: ["target", "timeoutFrames"],
|
|
76
76
|
addressTarget: ["kind", "address", "space", "condition"],
|
|
77
77
|
memoryTarget: ["kind", "address", "operator", "value", "space", "view"],
|
|
@@ -228,9 +228,6 @@ function checkTarget(value: unknown, where: string, fail: (message: string) => n
|
|
|
228
228
|
return fail(`${where}.kind must be one of address, memory, raster`);
|
|
229
229
|
}
|
|
230
230
|
|
|
231
|
-
/** What a step of a script without the replay core gets for press: the scripts that read these steps run without a window. */
|
|
232
|
-
const PRESS_REMEDY = "press pushes keys of the keyboard matrix, and only the replay of a record file has them. Use type for the KERNAL keyboard queue, or put the press step in a record file and play the record file";
|
|
233
|
-
|
|
234
231
|
/** Checks the input of one step kind and returns it with the defaults of its MCP tool. */
|
|
235
232
|
function checkInput(kind: ActionStepKind, value: unknown, at: string, fail: (message: string) => never): ActionStep {
|
|
236
233
|
const where = `${at}: ${kind}`;
|
|
@@ -275,9 +272,14 @@ function checkInput(kind: ActionStepKind, value: unknown, at: string, fail: (mes
|
|
|
275
272
|
else if (keys.length > MAX_KEYBOARD_BYTES) fail(`${where}: the keyboard queue takes at most ${MAX_KEYBOARD_BYTES} keys at once. This input has ${keys.length} keys`);
|
|
276
273
|
return { type: input };
|
|
277
274
|
}
|
|
278
|
-
case "press":
|
|
279
|
-
|
|
280
|
-
|
|
275
|
+
case "press": {
|
|
276
|
+
const fields = new Fields(value, where, STEP_FIELDS.press, fail);
|
|
277
|
+
const keys = fields.get("keys");
|
|
278
|
+
if (typeof keys !== "string") fields.fail("keys", "must be the keys as text, for example {F1} or {LSHIFT+CBM}");
|
|
279
|
+
const taps = keyTaps(keys as string);
|
|
280
|
+
if (typeof taps === "string") fail(`${where}.keys: ${taps}`);
|
|
281
|
+
return { press: { keys: keys as string, frames: fields.integer("frames", 1, MAX_PRESS_FRAMES, PRESS_FRAMES) } };
|
|
282
|
+
}
|
|
281
283
|
case "frames":
|
|
282
284
|
if (!isInteger(value, 1, MAX_TIMEOUT_FRAMES)) fail(`${where} must be a frame count from 1 to ${MAX_TIMEOUT_FRAMES}`);
|
|
283
285
|
return { frames: value as number };
|
|
@@ -352,14 +354,12 @@ export function refuseOldStep(kind: string, step: Record<string, unknown>, at: s
|
|
|
352
354
|
|
|
353
355
|
/**
|
|
354
356
|
* Checks one action step of the given kind and returns it with the defaults
|
|
355
|
-
* filled in. The step has no other key.
|
|
356
|
-
* runs the steps on the replay core. A step in a form of the 2.0 files is
|
|
357
|
+
* filled in. The step has no other key. A step in a form of the 2.0 files is
|
|
357
358
|
* refused with the step to write.
|
|
358
359
|
*/
|
|
359
|
-
export function checkActionStep(kind: ActionStepKind, step: Record<string, unknown>, at: string, fail: (message: string) => never
|
|
360
|
+
export function checkActionStep(kind: ActionStepKind, step: Record<string, unknown>, at: string, fail: (message: string) => never): ActionStep {
|
|
360
361
|
refuseOldStep(kind, step, at, fail);
|
|
361
362
|
for (const key of Object.keys(step)) if (key !== kind) fail(`${at} has the key ${key}, which a ${kind} step does not have`);
|
|
362
|
-
if (kind === "press" && options.press !== true) fail(`${at}: ${PRESS_REMEDY}`);
|
|
363
363
|
return checkInput(kind, step[kind], at, fail);
|
|
364
364
|
}
|
|
365
365
|
|
|
@@ -376,11 +376,11 @@ export function stepKind<K extends string>(step: unknown, kinds: readonly K[], a
|
|
|
376
376
|
}
|
|
377
377
|
|
|
378
378
|
/** Checks a list of action steps and returns them with the defaults filled in. */
|
|
379
|
-
export function checkActionSteps(value: unknown, fail: (message: string) => never
|
|
379
|
+
export function checkActionSteps(value: unknown, fail: (message: string) => never): ActionStep[] {
|
|
380
380
|
if (!Array.isArray(value) || value.length === 0) return fail("the steps are a JSON list with at least one step");
|
|
381
381
|
return value.map((step: unknown, index) => {
|
|
382
382
|
const at = `step ${index + 1}`;
|
|
383
|
-
return checkActionStep(stepKind(step, ACTION_STEP_KINDS, at, fail
|
|
383
|
+
return checkActionStep(stepKind(step, ACTION_STEP_KINDS, at, fail), step as Record<string, unknown>, at, fail);
|
|
384
384
|
});
|
|
385
385
|
}
|
|
386
386
|
|
|
@@ -471,7 +471,7 @@ export async function runActionStep(client: ViceSessionClient, step: ActionStep,
|
|
|
471
471
|
} else if ("type" in step) {
|
|
472
472
|
await client.keyboard(keyboardBytes(step.type) as Uint8Array);
|
|
473
473
|
} else if ("press" in step) {
|
|
474
|
-
|
|
474
|
+
await client.press(keyTaps(step.press.keys) as KeyTap[], step.press.frames);
|
|
475
475
|
} else if ("frames" in step) {
|
|
476
476
|
await stop(client);
|
|
477
477
|
// One advance-frames runs at most MAX_EXECUTION_COUNT frames. Each part ends at the raster position
|
package/src/host-client/tools.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// Short-lived typed requests to the Host Runtime for skill scripts:
|
|
2
2
|
// VICE's own tools (c1541, petcat) and the host tool status. Each request
|
|
3
3
|
// opens its own "tool" connection, sends bytes, and closes. Skill scripts run
|
|
4
|
-
// ACME, DXA and Ghidra themselves through src/native.
|
|
4
|
+
// ACME, DXA and Ghidra themselves through src/native (Ghidra in process).
|
|
5
5
|
|
|
6
6
|
import { ProtocolError, WireFailure } from "../protocol/messages.ts";
|
|
7
7
|
import { DISK_IMAGE_TYPES, validateToolResult, type C1541Result, type DiskAction, type DiskImageType, type DiskSector, type PetcatResult, type ToolOperation, type ToolOperations } from "../protocol/tools.ts";
|
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
// one VICE. Exposes C64-domain operations only.
|
|
3
3
|
|
|
4
4
|
import { ProtocolError, WireFailure, type VideoStandard } from "../protocol/messages.ts";
|
|
5
|
-
import { MAX_MEMORY_READ, traceHitsFromAttachment, validateViceResult, type TraceResult, type Breakpoint, type BreakpointParams, type PointRemoved, type Watchpoint, type WatchpointParams, type ExecutionParams, type ExecutionResult, type JoystickState, type MachineStatus, type MemmapRange, type MemoryWriteParams, type ProfileEntry, type RegisterValues, type ResetMode, type RunState, type RunTarget, type RunUntilResult, type MemoryReadParams, type MemoryReadResult, type Registers, type Space, type ViceOperation, type ViceOperations } from "../protocol/vice.ts";
|
|
5
|
+
import { MAX_MEMORY_READ, traceHitsFromAttachment, validateViceResult, type TraceResult, type Breakpoint, type BreakpointParams, type PointRemoved, type Watchpoint, type WatchpointParams, type ExecutionParams, type ExecutionResult, type JoystickState, type MachineStatus, type PressResult, type MemmapRange, type MemoryWriteParams, type ProfileEntry, type RegisterValues, type ResetMode, type RunState, type RunTarget, type RunUntilResult, type MemoryReadParams, type MemoryReadResult, type Registers, type Space, type ViceOperation, type ViceOperations } from "../protocol/vice.ts";
|
|
6
|
+
import type { KeyTap } from "../c64-keys.ts";
|
|
6
7
|
import { HostConnection } from "./connect.ts";
|
|
7
8
|
import { readProjectFile } from "./transfer.ts";
|
|
8
9
|
|
|
@@ -158,6 +159,11 @@ export class ViceSessionClient {
|
|
|
158
159
|
return this.#request("joystick", state);
|
|
159
160
|
}
|
|
160
161
|
|
|
162
|
+
/** Presses keys of the keyboard matrix and RESTORE: each tap holds its keys `frames` frames, then waits `frames` frames with all keys up. */
|
|
163
|
+
press(taps: KeyTap[], frames: number): Promise<PressResult> {
|
|
164
|
+
return this.#request("press", { taps, frames });
|
|
165
|
+
}
|
|
166
|
+
|
|
161
167
|
/** Action list gives all breakpoints, remove gives `{removed, id}`; add, enable and disable give the one breakpoint. */
|
|
162
168
|
breakpoint(params: Extract<BreakpointParams, { action: "list" }>): Promise<{ breakpoints: Breakpoint[] }>;
|
|
163
169
|
breakpoint(params: Extract<BreakpointParams, { action: "remove" }>): Promise<PointRemoved>;
|
package/src/knowledge/read.ts
CHANGED
|
@@ -7,7 +7,7 @@ import type { DatabaseSync } from "node:sqlite";
|
|
|
7
7
|
import type { AddressRange } from "../c64.ts";
|
|
8
8
|
import { Refusal } from "../errors.ts";
|
|
9
9
|
import { DEFAULT_SPACE, type CommentPlacement, type OperandSelect, type Origin, type ReferenceKind, type RegionType, type Space, type StartScreenMode, type SuppressionEntity, type SwitchKind, type SymbolKind } from "./schema.ts";
|
|
10
|
-
import { NO_REVISION } from "./text.ts";
|
|
10
|
+
import { compareText, NO_REVISION, sqlName, TABLES } from "./text.ts";
|
|
11
11
|
|
|
12
12
|
export interface SymbolRow {
|
|
13
13
|
space: Space;
|
|
@@ -352,6 +352,30 @@ export function currentRevision(db: DatabaseSync | undefined): string {
|
|
|
352
352
|
return (db.prepare("SELECT max(id) AS id FROM revisions").get() as { id: string | null }).id ?? "0";
|
|
353
353
|
}
|
|
354
354
|
|
|
355
|
+
/**
|
|
356
|
+
* The newest revision that changed a row in one of `spaces`, or the revision
|
|
357
|
+
* of no knowledge when none did. A change in another space does not change it.
|
|
358
|
+
*/
|
|
359
|
+
export function spacesRevision(db: DatabaseSync | undefined, spaces: readonly Space[]): string {
|
|
360
|
+
if (db === undefined || spaces.length === 0) return NO_REVISION;
|
|
361
|
+
const marks = spaces.map(() => "?").join(", ");
|
|
362
|
+
let newest = NO_REVISION;
|
|
363
|
+
for (const spec of TABLES) {
|
|
364
|
+
const row = db.prepare(`SELECT max(valid_from_revision) AS added, max(valid_to_revision) AS closed FROM ${sqlName(spec.table)} WHERE space IN (${marks})`).get(...spaces) as { added: string | null; closed: string | null };
|
|
365
|
+
for (const id of [row.added, row.closed]) if (id !== null && compareText(id, newest) > 0) newest = id;
|
|
366
|
+
}
|
|
367
|
+
return newest;
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/**
|
|
371
|
+
* The revision of the source of a space: the newest revision of that space and
|
|
372
|
+
* of the stage of its start screen. A change in another space does not change it.
|
|
373
|
+
*/
|
|
374
|
+
export function sourceRevision(db: DatabaseSync | undefined, space: Space = DEFAULT_SPACE): string {
|
|
375
|
+
const stage = space === DEFAULT_SPACE ? currentStartScreen(db, space)?.stage : undefined;
|
|
376
|
+
return spacesRevision(db, [space, ...(stage === undefined ? [] : [stage])]);
|
|
377
|
+
}
|
|
378
|
+
|
|
355
379
|
/** One import of a coverage map: its project path, its SHA-256, the space it went into and the revision. */
|
|
356
380
|
export interface CoverageRun {
|
|
357
381
|
name: string;
|
package/src/mcp/inputs.ts
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
import { z } from "zod";
|
|
7
7
|
|
|
8
8
|
import { c64AddressOf } from "../c64.ts";
|
|
9
|
+
import { keyTaps, MAX_PRESS_FRAMES, PRESS_FRAMES } from "../c64-keys.ts";
|
|
9
10
|
import { DEFAULT_TIMEOUT_FRAMES, keyboardBytes, MAX_RASTER_LINE } from "../host-client/steps.ts";
|
|
10
11
|
import { COMPARISONS, CONDITION_REGISTERS, JOYSTICK_DIRECTIONS, MAX_KEYBOARD_BYTES, MAX_MEMORY_WRITE, MAX_TIMEOUT_FRAMES, MEMORY_VIEWS, SPACES } from "../protocol/vice.ts";
|
|
11
12
|
|
|
@@ -91,6 +92,17 @@ export const TOOL_INPUTS = {
|
|
|
91
92
|
})
|
|
92
93
|
.strict(),
|
|
93
94
|
|
|
95
|
+
press: z
|
|
96
|
+
.object({
|
|
97
|
+
keys: z.string().min(1).describe("the keys: each character is one tap, a name in braces is one key, for example {F1}, and + in braces holds keys together, for example {LSHIFT+CBM}"),
|
|
98
|
+
frames: z.number().int().min(1).max(MAX_PRESS_FRAMES).default(PRESS_FRAMES).describe("the frames that each tap holds its keys, and then waits with all keys up"),
|
|
99
|
+
})
|
|
100
|
+
.strict()
|
|
101
|
+
.superRefine((value, context) => {
|
|
102
|
+
const taps = keyTaps(value.keys);
|
|
103
|
+
if (typeof taps === "string") context.addIssue({ code: "custom", message: taps, path: ["keys"] });
|
|
104
|
+
}),
|
|
105
|
+
|
|
94
106
|
keyboard: z
|
|
95
107
|
.object({
|
|
96
108
|
mode: z.enum(["text", "petscii"]),
|
package/src/mcp/server.ts
CHANGED
package/src/mcp/tools/input.ts
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
|
-
// Input tools: c64_keyboard and c64_joystick.
|
|
1
|
+
// Input tools: c64_keyboard, c64_press and c64_joystick.
|
|
2
2
|
|
|
3
3
|
import { z } from "zod";
|
|
4
4
|
|
|
5
|
-
import {
|
|
5
|
+
import { formatC64Address } from "../../c64.ts";
|
|
6
|
+
import { keyTaps, MAX_PRESS_TAPS, MAX_TAP_KEYS, PRESS_FRAMES, type KeyTap } from "../../c64-keys.ts";
|
|
7
|
+
import { JOYSTICK_DIRECTIONS, MAX_KEYBOARD_BYTES, POINT_STOP_REASONS, RUN_STATES, SPACES } from "../../protocol/vice.ts";
|
|
6
8
|
import { keyboardBytes } from "../../host-client/steps.ts";
|
|
7
9
|
import { TOOL_INPUTS } from "../inputs.ts";
|
|
8
|
-
import { defineTool } from "../server.ts";
|
|
10
|
+
import { AddressOutput, defineTool } from "../server.ts";
|
|
9
11
|
|
|
10
12
|
|
|
11
13
|
export const c64Keyboard = defineTool({
|
|
@@ -14,7 +16,7 @@ export const c64Keyboard = defineTool({
|
|
|
14
16
|
description:
|
|
15
17
|
`Type up to ${MAX_KEYBOARD_BYTES} keys into the C64 keyboard queue. The C64 reads them while it runs. ` +
|
|
16
18
|
"Only a program that reads keys through the KERNAL sees them. A program that reads the keyboard hardware directly does not see them. Many games do that. " +
|
|
17
|
-
"
|
|
19
|
+
"For keys that a program reads from the keyboard hardware, use c64_press. " +
|
|
18
20
|
'Mode text types text, for example "RUN\\n". Letters of either case type the normal (unshifted) key. A line break types RETURN. ' +
|
|
19
21
|
"Mode petscii types PETSCII codes 1 to 255 in bytes, for example [147] to clear the screen. " +
|
|
20
22
|
"While c64_autostart loads a program, this tool refuses keys: see c64_autostart. " +
|
|
@@ -29,6 +31,37 @@ export const c64Keyboard = defineTool({
|
|
|
29
31
|
},
|
|
30
32
|
});
|
|
31
33
|
|
|
34
|
+
export const c64Press = defineTool({
|
|
35
|
+
name: "c64_press",
|
|
36
|
+
title: "Press keys of the C64 keyboard",
|
|
37
|
+
description:
|
|
38
|
+
"Press keys of the C64 keyboard matrix, and RESTORE. A program that reads the keyboard hardware directly sees these keys. Many games do that. " +
|
|
39
|
+
"Each character of keys is one tap: the key goes down, then up. Letters of either case press the same key. A line break presses RETURN. " +
|
|
40
|
+
"A key without a character has its name in braces: {F1} to {F8}, {RETURN}, {SPACE}, {DEL}, {INST}, {HOME}, {CLR}, {STOP}, {RUN} and {RESTORE}. " +
|
|
41
|
+
"The other names are {CTRL}, {CBM}, {LSHIFT}, {RSHIFT}, {UP}, {DOWN}, {LEFT}, {RIGHT}, {POUND}, {UPARROW} and {LEFTARROW}. " +
|
|
42
|
+
"{F2}, {RUN}, {CLR}, {INST}, {UP} and {LEFT} also press the left SHIFT. " +
|
|
43
|
+
`Join keys with + in braces to hold them together in one tap, for example {LSHIFT+CBM}, {CTRL+3} or {STOP+RESTORE}. One tap holds at most ${MAX_TAP_KEYS} keys, RESTORE included. One call has at most ${MAX_PRESS_TAPS} taps. ` +
|
|
44
|
+
`Each tap holds its keys for frames frames (default ${PRESS_FRAMES}). Then all keys are up for frames frames. The machine runs during the taps, and it runs again after them when it ran before. ` +
|
|
45
|
+
"A breakpoint, watchpoint or JAM stops the taps early. Then stopReason tells why, taps tells how many taps were complete, and the machine stays stopped. All keys are up at the end. " +
|
|
46
|
+
"The CPU history starts again at each tap. " +
|
|
47
|
+
"To type text through the KERNAL keyboard queue, use c64_keyboard.",
|
|
48
|
+
inputSchema: TOOL_INPUTS.press,
|
|
49
|
+
outputSchema: z.object({
|
|
50
|
+
taps: z.number().int().min(0).max(MAX_PRESS_TAPS).describe("the taps that were complete"),
|
|
51
|
+
state: z.enum(RUN_STATES),
|
|
52
|
+
stopReason: z.enum(POINT_STOP_REASONS).optional().describe("why the taps stopped early"),
|
|
53
|
+
pc: AddressOutput.optional(),
|
|
54
|
+
pointId: z.number().int().min(1).optional().describe("the id of the breakpoint or watchpoint that stopped the taps"),
|
|
55
|
+
space: z.enum(SPACES).optional().describe("the CPU that stopped, c64 or drive8. pc is the address in that space"),
|
|
56
|
+
}),
|
|
57
|
+
readOnly: false,
|
|
58
|
+
async run(input, session) {
|
|
59
|
+
// The schema checked the keys: keyTaps gives taps here.
|
|
60
|
+
const { pc, ...result } = await session.press(keyTaps(input.keys) as KeyTap[], input.frames);
|
|
61
|
+
return { ...result, ...(pc === undefined ? {} : { pc: formatC64Address(pc) }) };
|
|
62
|
+
},
|
|
63
|
+
});
|
|
64
|
+
|
|
32
65
|
export const c64Joystick = defineTool({
|
|
33
66
|
name: "c64_joystick",
|
|
34
67
|
title: "Move a joystick",
|
|
@@ -44,4 +77,4 @@ export const c64Joystick = defineTool({
|
|
|
44
77
|
},
|
|
45
78
|
});
|
|
46
79
|
|
|
47
|
-
export const inputTools = [c64Keyboard, c64Joystick];
|
|
80
|
+
export const inputTools = [c64Keyboard, c64Press, c64Joystick];
|
package/src/native/c64run.ts
CHANGED
|
@@ -12,7 +12,7 @@ import type { SupervisedProcess } from "./processes.ts";
|
|
|
12
12
|
import type { ToolContext } from "./run.ts";
|
|
13
13
|
|
|
14
14
|
/** The command protocol that this module speaks; c64run --version and version name it. */
|
|
15
|
-
export const C64RUN_PROTOCOL =
|
|
15
|
+
export const C64RUN_PROTOCOL = 4;
|
|
16
16
|
|
|
17
17
|
/** CPU cycles in one PAL frame: 312 lines of 63 cycles. */
|
|
18
18
|
export const PAL_FRAME_CYCLES = 19_656;
|
package/src/native/discover.ts
CHANGED
|
@@ -99,8 +99,8 @@ export function viceVersionOf(text: string): ViceVersion | undefined {
|
|
|
99
99
|
return { major: Number(match[1]), minor: Number(match[2]), ...(match[3] === undefined ? {} : { revision: Number(match[3]) }) };
|
|
100
100
|
}
|
|
101
101
|
|
|
102
|
-
/** What a VICE flaw stops from working: joystick input,
|
|
103
|
-
export type ViceFeature = "joystick" | "tape";
|
|
102
|
+
/** What a VICE flaw stops from working: joystick input, the load of a tape image, or keys of the keyboard matrix. */
|
|
103
|
+
export type ViceFeature = "joystick" | "tape" | "keyboard";
|
|
104
104
|
|
|
105
105
|
/** A known VICE flaw: the text for the person at the host, and what it stops from working. */
|
|
106
106
|
export interface ViceFlaw {
|
|
@@ -120,7 +120,7 @@ const VICE_FLAWS = [
|
|
|
120
120
|
{
|
|
121
121
|
upTo: { major: 3, minor: 10 },
|
|
122
122
|
fixedRevision: 45971,
|
|
123
|
-
breaks: ["joystick", "tape"],
|
|
123
|
+
breaks: ["joystick", "tape", "keyboard"],
|
|
124
124
|
text:
|
|
125
125
|
"VICE 3.10 and older hold bits 5-7 of CIA 1 ports A and B low with the joystick device that c64-re-tools uses (VICE bug #2202). " +
|
|
126
126
|
"$DC00 and $DC01 read $1F with no input. A program that waits for one key of the keyboard matrix (for example LDA $DC01 / CMP #$EF for SPACE) waits forever. " +
|
|
@@ -1,19 +1,16 @@
|
|
|
1
|
-
// The Ghidra analysis:
|
|
2
|
-
// 6510 language,
|
|
3
|
-
//
|
|
1
|
+
// The Ghidra analysis: the Ghidra SLEIGH decoder and decompiler with the NMOS
|
|
2
|
+
// 6510 language, in this process as a WebAssembly module. Knowledge seeds go
|
|
3
|
+
// in, the structural result comes out, and the result is checked completely
|
|
4
|
+
// before the script imports it.
|
|
4
5
|
|
|
5
|
-
import {
|
|
6
|
-
|
|
7
|
-
import { Refusal } from "../../errors.ts";
|
|
8
|
-
import { describeError, isObject, WireFailure } from "../../protocol/messages.ts";
|
|
6
|
+
import { describeError, WireFailure } from "../../protocol/messages.ts";
|
|
9
7
|
import { checkGhidraResult, checkRequestBounds, GHIDRA_LIMITS, imageRange, seedsInside, type GhidraParams, type GhidraResult } from "../types.ts";
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
8
|
+
import type { ToolContext } from "../run.ts";
|
|
9
|
+
import { walk } from "./walk.ts";
|
|
10
|
+
import { decompile, loadImage, setName, SLEIGH_VERSION } from "./wasm.ts";
|
|
13
11
|
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
const AFTER_DECOMPILE_MS = 30_000;
|
|
12
|
+
/** The longest reason that the result check accepts. */
|
|
13
|
+
const MAX_REASON = 1000;
|
|
17
14
|
|
|
18
15
|
export async function analyze(
|
|
19
16
|
params: GhidraParams,
|
|
@@ -21,67 +18,81 @@ export async function analyze(
|
|
|
21
18
|
context: ToolContext,
|
|
22
19
|
): Promise<{ result: GhidraResult }> {
|
|
23
20
|
checkRequestBounds(params);
|
|
24
|
-
const ghidra = findGhidra(context.env);
|
|
25
21
|
const { start, end, body } = imageRange(params.imageKind, image);
|
|
26
|
-
const base = start;
|
|
27
22
|
|
|
28
|
-
//
|
|
23
|
+
// The decoder sees only the loaded bytes; labels may name any address.
|
|
29
24
|
const { entryPoints, codeStarts, dataRanges } = seedsInside(params, start, end);
|
|
30
25
|
if (entryPoints.length === 0) {
|
|
31
26
|
throw new WireFailure("invalid-input", "Give at least one entry point inside the program, for example the SYS address of its BASIC loader.");
|
|
32
27
|
}
|
|
28
|
+
context.signal.throwIfAborted();
|
|
33
29
|
|
|
34
|
-
|
|
30
|
+
let walked: ReturnType<typeof walk>;
|
|
35
31
|
try {
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
);
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
32
|
+
loadImage(body, start);
|
|
33
|
+
walked = walk(body, start, end, { entryPoints, codeStarts, dataRanges, labels: params.labels });
|
|
34
|
+
} catch (error) {
|
|
35
|
+
context.log?.(`The Ghidra decoder failed: ${describeError(error)}`);
|
|
36
|
+
throw new WireFailure("operation-failed", `The Ghidra decoder failed: ${describeError(error)}. Nothing was imported.`);
|
|
37
|
+
}
|
|
38
|
+
const { decompilations, notDecompiled } = decompileRoutines(params, walked.functions, body, start, context);
|
|
39
|
+
|
|
40
|
+
let result: GhidraResult;
|
|
41
|
+
try {
|
|
42
|
+
result = checkGhidraResult({ ...walked, decompilations, notDecompiled, completeness: { functions: true, regions: true, references: true }, toolVersion: SLEIGH_VERSION });
|
|
43
|
+
} catch (error) {
|
|
44
|
+
context.log?.(`Ghidra result rejected: ${describeError(error)}`);
|
|
45
|
+
throw new WireFailure("operation-failed", `Ghidra returned an incomplete or inconsistent result. Nothing was imported. The check found: ${describeError(error)}.`);
|
|
46
|
+
}
|
|
47
|
+
return { result };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** The requested routines as C text, within the character bounds; the labels name routines and data. */
|
|
51
|
+
function decompileRoutines(params: GhidraParams, functions: GhidraResult["functions"], body: Uint8Array, start: number, context: ToolContext): Pick<GhidraResult, "decompilations" | "notDecompiled"> {
|
|
52
|
+
const decompilations: GhidraResult["decompilations"] = [];
|
|
53
|
+
const notDecompiled: NonNullable<GhidraResult["notDecompiled"]> = [];
|
|
54
|
+
if (params.decompile.length === 0) return { decompilations, notDecompiled };
|
|
55
|
+
const entries = new Set(functions.map((fn) => fn.entry));
|
|
56
|
+
// A trap in the decompiler drops its image: the next routine loads it again.
|
|
57
|
+
let prepared = false;
|
|
58
|
+
const prepare = () => {
|
|
59
|
+
if (prepared) return;
|
|
60
|
+
loadImage(body, start);
|
|
61
|
+
for (const label of params.labels) {
|
|
62
|
+
try {
|
|
63
|
+
setName(label.address, label.name, entries.has(label.address) ? "function" : "data");
|
|
64
|
+
} catch (error) {
|
|
65
|
+
// The decompiler then prints its own name for the address.
|
|
66
|
+
context.log?.(`The Ghidra decompiler refused the name ${label.name}: ${describeError(error)}`);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
prepared = true;
|
|
70
|
+
};
|
|
71
|
+
let remaining = GHIDRA_LIMITS.decompiledTotalChars;
|
|
72
|
+
for (const entry of params.decompile) {
|
|
73
|
+
if (!entries.has(entry)) {
|
|
74
|
+
notDecompiled.push({ entry, reason: "no function starts at this address" });
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
if (remaining <= 0) {
|
|
78
|
+
notDecompiled.push({ entry, reason: "the decompiled text of the other routines used the whole limit" });
|
|
79
|
+
continue;
|
|
71
80
|
}
|
|
72
|
-
let
|
|
81
|
+
let text: string;
|
|
73
82
|
try {
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
result = checkGhidraResult(isObject(exported) ? { ...exported, toolVersion: ghidraVersion(ghidra) } : exported);
|
|
77
|
-
const [range] = result.coverage;
|
|
78
|
-
if (result.coverage.length !== 1 || range === undefined || range.start !== start || range.end !== end) throw new Refusal("operation-failed", "the coverage is not the loaded program");
|
|
83
|
+
prepare();
|
|
84
|
+
text = decompile(entry);
|
|
79
85
|
} catch (error) {
|
|
80
|
-
|
|
81
|
-
|
|
86
|
+
prepared = false;
|
|
87
|
+
context.log?.(`The Ghidra decompiler failed at ${entry}: ${describeError(error)}`);
|
|
88
|
+
notDecompiled.push({ entry, reason: describeError(error).slice(0, MAX_REASON) || "the decompiler gave no reason" });
|
|
89
|
+
continue;
|
|
82
90
|
}
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
91
|
+
const limit = Math.min(GHIDRA_LIMITS.decompiledChars, remaining);
|
|
92
|
+
const truncated = text.length > limit;
|
|
93
|
+
if (truncated) text = text.slice(0, limit);
|
|
94
|
+
remaining -= text.length;
|
|
95
|
+
decompilations.push({ entry, text, truncated });
|
|
86
96
|
}
|
|
97
|
+
return { decompilations, notDecompiled };
|
|
87
98
|
}
|