@henols/c64-re-tools 2.5.1-rc.2 → 2.6.0-rc.10

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.
Files changed (87) hide show
  1. package/package.json +2 -2
  2. package/skills/c64-assembler/SKILL.md +26 -12
  3. package/skills/c64-assembler/scripts/assembler.ts +25 -13
  4. package/skills/c64-development/SKILL.md +2 -2
  5. package/skills/c64-docs/SKILL.md +4 -4
  6. package/skills/c64-docs/scripts/docs.ts +7 -7
  7. package/skills/c64-docs/scripts/lib/reference.ts +3 -3
  8. package/skills/c64-docs/scripts/lib/source-map.ts +9 -4
  9. package/skills/c64-knowledge/SKILL.md +29 -20
  10. package/skills/c64-knowledge/scripts/knowledge.ts +33 -39
  11. package/skills/c64-knowledge/scripts/lib/listing.ts +18 -3
  12. package/skills/c64-packer/SKILL.md +1 -1
  13. package/skills/c64-provenance/SKILL.md +11 -10
  14. package/skills/c64-provenance/scripts/lib/library.ts +16 -16
  15. package/skills/c64-provenance/scripts/provenance.ts +33 -23
  16. package/skills/c64-reverse-engineering/SKILL.md +16 -10
  17. package/skills/c64-source/SKILL.md +60 -42
  18. package/skills/c64-source/scripts/lib/export.ts +76 -32
  19. package/skills/c64-source/scripts/lib/loader.ts +26 -7
  20. package/skills/c64-source/scripts/lib/source.ts +21 -24
  21. package/skills/c64-source/scripts/lib/stage.ts +6 -5
  22. package/skills/c64-source/scripts/source.ts +213 -106
  23. package/skills/c64-static-analysis/SKILL.md +7 -5
  24. package/skills/c64-static-analysis/scripts/lib/coverage.ts +2 -25
  25. package/skills/c64-static-analysis/scripts/lib/instructions.ts +22 -20
  26. package/skills/c64-static-analysis/scripts/static-analysis.ts +36 -43
  27. package/skills/c64-testing/SKILL.md +5 -2
  28. package/skills/c64-testing/references/recording-format.md +18 -3
  29. package/skills/c64-testing/references/scenario-format.md +7 -6
  30. package/skills/c64-testing/scripts/lib/diff-files.ts +4 -18
  31. package/skills/c64-testing/scripts/lib/play.ts +39 -41
  32. package/skills/c64-testing/scripts/lib/recording.ts +46 -37
  33. package/skills/c64-testing/scripts/lib/replay.ts +1 -1
  34. package/skills/c64-testing/scripts/lib/runs.ts +2 -2
  35. package/skills/c64-testing/scripts/lib/scenario.ts +17 -10
  36. package/skills/c64-unpacker/SKILL.md +4 -1
  37. package/skills/c64-unpacker/scripts/lib/loads.ts +34 -13
  38. package/skills/c64-unpacker/scripts/unpacker.ts +5 -3
  39. package/skills/emulator/SKILL.md +7 -12
  40. package/src/build-name.ts +50 -0
  41. package/src/c64-keys.ts +98 -0
  42. package/src/c64.ts +20 -0
  43. package/src/cli/main.ts +3 -29
  44. package/src/host/main.ts +1 -1
  45. package/src/host/tools/index.ts +1 -6
  46. package/src/host/vice/session.ts +88 -9
  47. package/src/host-client/steps.ts +17 -17
  48. package/src/host-client/tools.ts +2 -7
  49. package/src/host-client/vice-session.ts +7 -1
  50. package/src/knowledge/program.ts +44 -1
  51. package/src/knowledge/read.ts +28 -8
  52. package/src/knowledge/schema.ts +33 -9
  53. package/src/knowledge/start-screen.ts +4 -0
  54. package/src/knowledge/text.ts +4 -2
  55. package/src/knowledge/write.ts +59 -25
  56. package/src/mcp/inputs.ts +12 -0
  57. package/src/mcp/server.ts +1 -1
  58. package/src/mcp/tools/input.ts +38 -5
  59. package/src/mcp/tools/machine.ts +3 -42
  60. package/src/mcp/tools/media.ts +1 -1
  61. package/src/native/acme.ts +1 -1
  62. package/src/native/c64run.ts +1 -1
  63. package/src/native/discover.ts +3 -3
  64. package/src/native/dxa.ts +12 -1
  65. package/src/native/ghidra/analyze.ts +74 -63
  66. package/src/native/ghidra/c64rt-wasm.ts +4 -0
  67. package/src/native/ghidra/language/c64rt_6510.sla +0 -0
  68. package/src/native/ghidra/pcode.ts +222 -0
  69. package/src/native/ghidra/walk.ts +205 -0
  70. package/src/native/ghidra/wasm.ts +98 -0
  71. package/src/native/processes.ts +4 -4
  72. package/src/native/types.ts +2 -2
  73. package/src/platform.ts +30 -1
  74. package/src/project.ts +17 -4
  75. package/src/protocol/tools.ts +1 -45
  76. package/src/protocol/vice.ts +47 -0
  77. package/src/script.ts +1 -1
  78. package/src/vsf.ts +98 -0
  79. package/tools/c64run.c +9 -12
  80. package/tools/install-container.sh +1 -2
  81. package/src/cli/status.ts +0 -127
  82. package/src/host/tools/status.ts +0 -47
  83. package/src/native/ghidra/index.ts +0 -170
  84. package/src/native/ghidra/scripts/C64Export.java +0 -274
  85. package/src/native/ghidra/scripts/C64Prepare.java +0 -66
  86. package/src/native/status.ts +0 -135
  87. package/tools/install-ghidra.sh +0 -40
@@ -1,50 +1,11 @@
1
- // Machine tools: c64_status, c64_reset, c64_warp and c64_window.
1
+ // Machine tools: c64_reset, c64_warp and c64_window.
2
2
 
3
3
  import { z } from "zod";
4
4
 
5
5
  import { formatC64Address } from "../../c64.ts";
6
- import { VIDEO_STANDARDS } from "../../protocol/messages.ts";
7
- import { POINT_STOP_REASONS, RESET_MODES, RUN_STATES, SPACES, WINDOW_ACTIONS } from "../../protocol/vice.ts";
6
+ import { RESET_MODES, RUN_STATES, WINDOW_ACTIONS } from "../../protocol/vice.ts";
8
7
  import { AddressOutput, defineTool } from "../server.ts";
9
8
 
10
- export const c64Status = defineTool({
11
- name: "c64_status",
12
- title: "C64 status",
13
- description:
14
- "Get the state of the C64. The result tells if the CPU runs or has stopped, the video standard (pal or ntsc), " +
15
- "and if warp mode is on. It also tells if the emulator window is open (window). " +
16
- "When the CPU has stopped, the result also gives the program counter (pc). " +
17
- "When a breakpoint, a watchpoint or a JAM opcode stopped the CPU, stopReason tells which, and pointId gives the id of the breakpoint or watchpoint. " +
18
- "cartridge is true while a cartridge from c64_autostart is attached: a reset keeps it, and an autostart of another file detaches it.",
19
- inputSchema: z.object({}).strict(),
20
- outputSchema: z.object({
21
- state: z.enum(RUN_STATES),
22
- videoStandard: z.enum(VIDEO_STANDARDS),
23
- warp: z.boolean(),
24
- window: z.boolean().describe("true when the emulator window is open (c64_window)"),
25
- pc: AddressOutput.optional().describe("program counter. Only when the CPU is stopped"),
26
- stopReason: z.enum(POINT_STOP_REASONS).optional().describe("what stopped the CPU. Only when a breakpoint, a watchpoint or a JAM opcode stopped it"),
27
- pointId: z.number().int().min(1).optional().describe("the id of the breakpoint or watchpoint that stopped the CPU"),
28
- space: z.enum(SPACES).optional().describe("with pc: c64, or drive8 when a breakpoint or watchpoint in the disk drive stopped the CPU. pc is the address in that space"),
29
- cartridge: z.boolean().describe("true while a cartridge from c64_autostart is attached"),
30
- }),
31
- readOnly: true,
32
- async run(_input, session) {
33
- const status = await session.status();
34
- return {
35
- state: status.state,
36
- videoStandard: status.videoStandard,
37
- warp: status.warp,
38
- window: status.window,
39
- cartridge: status.cartridge,
40
- ...(status.pc === undefined ? {} : { pc: formatC64Address(status.pc) }),
41
- ...(status.stopReason === undefined ? {} : { stopReason: status.stopReason }),
42
- ...(status.pointId === undefined ? {} : { pointId: status.pointId }),
43
- ...(status.space === undefined ? {} : { space: status.space }),
44
- };
45
- },
46
- });
47
-
48
9
  export const c64Window = defineTool({
49
10
  name: "c64_window",
50
11
  title: "Emulator window",
@@ -104,4 +65,4 @@ export const c64Warp = defineTool({
104
65
  },
105
66
  });
106
67
 
107
- export const machineTools = [c64Status, c64Reset, c64Warp, c64Window];
68
+ export const machineTools = [c64Reset, c64Warp, c64Window];
@@ -30,7 +30,7 @@ export const c64Autostart = defineTool({
30
30
  "Without index, a disk image loads like LOAD\"*\",8,1. index selects one directory entry by its number in the directory list of the disk (0 is the first entry). " +
31
31
  "The tool refuses an index of a DEL entry, or an index after the last entry. " +
32
32
  "The machine runs when this tool returns, and the load continues. The emulator keeps warp mode on until it types RUN. " +
33
- "A key in that time stops the autostart, so c64_keyboard refuses keys until then. Run frames with c64_execution advance-frames until c64_status gives warp false. " +
33
+ "A key in that time stops the autostart, so c64_keyboard refuses keys until then. Run frames with c64_execution advance-frames, then type again. " +
34
34
  "The c64_timing stopwatch starts again from zero.",
35
35
  inputSchema: z
36
36
  .object({
@@ -19,7 +19,7 @@ export function showSymbol(symbol: AssembledSymbol) {
19
19
  : { name: symbol.name, kind: "constant", value: `$${symbol.value.toString(16).padStart(4, "0")}`, used: symbol.used };
20
20
  }
21
21
 
22
- /** The text of a symbols file (--out-symbols): the symbols of a build, which c64-testing reads for the names of a program. */
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. */
23
23
  export const symbolsFileText = (symbols: readonly AssembledSymbol[]) => `${JSON.stringify({ symbols: symbols.map(showSymbol) }, null, 1)}\n`;
24
24
 
25
25
  const PROGRAM = "program.prg";
@@ -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 = 3;
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;
@@ -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, or the load of a tape image. */
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. " +
package/src/native/dxa.ts CHANGED
@@ -6,6 +6,7 @@
6
6
  // changed listing is refused instead of half imported.
7
7
 
8
8
  import { writeFileSync } from "node:fs";
9
+ import { stripVTControlCharacters } from "node:util";
9
10
 
10
11
  import { Refusal } from "../errors.ts";
11
12
  import { SYMBOL_NAME } from "../c64.ts";
@@ -14,7 +15,17 @@ import { checkDxaResult, checkRequestBounds, imageRange, seedsInside, type DxaPa
14
15
  import { Workspace } from "./staging.ts";
15
16
  import { DXA, findTool } from "./discover.ts";
16
17
  import { outputTail, runTool, runToolOrFail, type ToolContext } from "./run.ts";
17
- import { DXA_VERSION, versionLine } from "./status.ts";
18
+
19
+ /** dxa's version line, also as "D:\\tools\\dxa.exe v0.1.5 -- symbolic 65xx disassembler" on Windows. */
20
+ export const DXA_VERSION = /^(?:.*[\\/])?dxa(?:\.exe)? v\d/i;
21
+
22
+ /** The first output line that matches, without terminal color codes. */
23
+ export function versionLine(output: string, pattern: RegExp): string | undefined {
24
+ return stripVTControlCharacters(output)
25
+ .split(/\r?\n/)
26
+ .map((line) => line.trim())
27
+ .find((line) => pattern.test(line));
28
+ }
18
29
 
19
30
  const TIMEOUT_MS = 120_000;
20
31
  /** The listing is returned as an attachment; larger output is refused. */
@@ -1,19 +1,16 @@
1
- // The Ghidra analysis: one disposable headless run with the NMOS
2
- // 6510 language, knowledge seeds before analysis, and the structural export
3
- // after it. The result is checked completely before the script imports it.
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 { existsSync, readFileSync, writeFileSync } from "node:fs";
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 { outputTail, type ToolContext } from "../run.ts";
11
- import { Workspace } from "../staging.ts";
12
- import { findGhidra, ghidraVersion, runHeadless, SCRIPT_DIRECTORY } from "./index.ts";
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
- const TIMEOUT_MS = 600_000;
15
- /** The part of the run that the decompilations leave for the export, the project removal and the end of Ghidra. */
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
- // Ghidra disassembles and defines data only in the loaded bytes; labels may name any address.
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
- const workspace = Workspace.create(context.supervisor);
30
+ let walked: ReturnType<typeof walk>;
35
31
  try {
36
- workspace.materialize("input", [{ path: "image.bin", size: body.length }], [body]);
37
- writeFileSync(workspace.path("seeds.json"), JSON.stringify({ start, end, entryPoints, codeStarts, dataRanges, labels: params.labels }));
38
- writeFileSync(
39
- workspace.path("request.json"),
40
- JSON.stringify({
41
- start,
42
- end,
43
- decompile: params.decompile,
44
- maxChars: GHIDRA_LIMITS.decompiledChars,
45
- maxTotalChars: GHIDRA_LIMITS.decompiledTotalChars,
46
- decompileDeadline: Date.now() + TIMEOUT_MS - AFTER_DECOMPILE_MS,
47
- }),
48
- );
49
- const run = await runHeadless({
50
- ghidra,
51
- workspace,
52
- file: "input/image.bin",
53
- baseAddress: base,
54
- scriptDirectories: [SCRIPT_DIRECTORY],
55
- preScripts: [{ name: "C64Prepare.java", args: [workspace.path("seeds.json")] }],
56
- postScripts: [{ name: "C64Export.java", args: [workspace.path("request.json"), workspace.path("out.json")] }],
57
- analyze: true,
58
- timeoutMs: TIMEOUT_MS,
59
- supervisor: context.supervisor,
60
- signal: context.signal,
61
- ...(context.env === undefined ? {} : { env: context.env }),
62
- }).catch((error: unknown) => {
63
- context.log?.(`Ghidra failed: ${describeError(error)}`);
64
- throw error;
65
- });
66
- const outPath = workspace.path("out.json");
67
- if (!existsSync(outPath)) {
68
- context.log?.(`Ghidra wrote no result:\n${run.stdout.slice(-4000)}\n${run.stderr.slice(-4000)}`);
69
- // Ghidra's own warnings and errors say why its export script wrote nothing.
70
- throw new WireFailure("operation-failed", `Ghidra finished without a result.${outputTail("Ghidra", run, workspace.root, /ERROR|WARN|Exception|Error:|SCRIPT/)}`);
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 result: GhidraResult;
81
+ let text: string;
73
82
  try {
74
- const exported: unknown = JSON.parse(readFileSync(outPath, "utf8"));
75
- // The version comes from the installation's application.properties, which findGhidra read.
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
- context.log?.(`Ghidra result rejected: ${describeError(error)}`);
81
- throw new WireFailure("operation-failed", `Ghidra returned an incomplete or inconsistent result. Nothing was imported. The check found: ${describeError(error)}.`);
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
- return { result };
84
- } finally {
85
- workspace.remove();
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
  }