@henols/c64-re-tools 2.6.0-rc.8 → 2.6.0

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 (82) hide show
  1. package/package.json +2 -2
  2. package/skills/c64-assembler/SKILL.md +3 -3
  3. package/skills/c64-assembler/scripts/assembler.ts +4 -3
  4. package/skills/c64-development/SKILL.md +3 -3
  5. package/skills/c64-docs/SKILL.md +6 -4
  6. package/skills/c64-docs/scripts/docs.ts +23 -10
  7. package/skills/c64-docs/scripts/lib/reference.ts +117 -31
  8. package/skills/c64-docs/scripts/lib/source-map.ts +14 -0
  9. package/skills/c64-knowledge/SKILL.md +10 -9
  10. package/skills/c64-knowledge/scripts/knowledge.ts +16 -9
  11. package/skills/c64-reverse-engineering/SKILL.md +9 -3
  12. package/skills/c64-source/SKILL.md +13 -10
  13. package/skills/c64-source/scripts/lib/export.ts +13 -2
  14. package/skills/c64-source/scripts/lib/loader.ts +51 -28
  15. package/skills/c64-source/scripts/lib/source.ts +24 -7
  16. package/skills/c64-source/scripts/source.ts +65 -47
  17. package/skills/c64-static-analysis/SKILL.md +26 -22
  18. package/skills/c64-static-analysis/scripts/lib/findings.ts +11 -11
  19. package/skills/c64-static-analysis/scripts/lib/instructions.ts +4 -4
  20. package/skills/c64-static-analysis/scripts/lib/macros.ts +3 -1
  21. package/skills/c64-static-analysis/scripts/static-analysis.ts +51 -35
  22. package/skills/c64-testing/SKILL.md +11 -4
  23. package/skills/c64-testing/references/recording-format.md +19 -7
  24. package/skills/c64-testing/references/scenario-format.md +6 -5
  25. package/skills/c64-testing/scripts/lib/diff-files.ts +4 -18
  26. package/skills/c64-testing/scripts/lib/play.ts +39 -37
  27. package/skills/c64-testing/scripts/lib/recording.ts +213 -65
  28. package/skills/c64-testing/scripts/lib/replay.ts +31 -5
  29. package/skills/c64-testing/scripts/lib/runs.ts +8 -3
  30. package/skills/c64-testing/scripts/lib/scenario.ts +4 -6
  31. package/skills/c64-testing/scripts/testing.ts +23 -2
  32. package/skills/c64-unpacker/SKILL.md +6 -3
  33. package/skills/c64-unpacker/scripts/lib/loads.ts +2 -2
  34. package/skills/c64-unpacker/scripts/lib/stages.ts +18 -3
  35. package/skills/c64-unpacker/scripts/unpacker.ts +38 -6
  36. package/skills/emulator/SKILL.md +2 -5
  37. package/src/build-name.ts +9 -4
  38. package/src/c64-keys.ts +98 -0
  39. package/src/c64.ts +1 -1
  40. package/src/host/main.ts +2 -2
  41. package/src/host/server.ts +3 -1
  42. package/src/host/tools/index.ts +1 -1
  43. package/src/host/vice/process.ts +34 -17
  44. package/src/host/vice/session.ts +132 -30
  45. package/src/host-client/steps.ts +21 -18
  46. package/src/host-client/tools.ts +1 -1
  47. package/src/host-client/vice-session.ts +7 -1
  48. package/src/knowledge/evidence.ts +66 -0
  49. package/src/knowledge/history.ts +5 -5
  50. package/src/knowledge/import.ts +12 -5
  51. package/src/knowledge/program.ts +81 -33
  52. package/src/knowledge/read.ts +12 -3
  53. package/src/knowledge/schema.ts +7 -7
  54. package/src/knowledge/start-screen.ts +2 -0
  55. package/src/knowledge/text.ts +28 -3
  56. package/src/knowledge/write.ts +6 -6
  57. package/src/mcp/inputs.ts +12 -0
  58. package/src/mcp/server.ts +1 -0
  59. package/src/mcp/tools/debug.ts +23 -21
  60. package/src/mcp/tools/input.ts +38 -5
  61. package/src/mcp/tools/memory.ts +12 -9
  62. package/src/native/c64run.ts +7 -4
  63. package/src/native/{ghidra → decompiler}/analyze.ts +17 -17
  64. package/src/native/{ghidra → decompiler}/language/c64rt_6510.slaspec +1 -1
  65. package/src/native/{ghidra → decompiler}/walk.ts +6 -6
  66. package/src/native/discover.ts +3 -3
  67. package/src/native/processes.ts +3 -3
  68. package/src/native/types.ts +25 -25
  69. package/src/opcodes.ts +1 -1
  70. package/src/protocol/vice.ts +47 -0
  71. package/src/reference-pages.ts +64 -0
  72. package/src/script.ts +1 -1
  73. package/src/vsf.ts +98 -0
  74. package/tools/c64run.c +158 -15
  75. package/skills/c64-testing/scripts/lib/keys.ts +0 -36
  76. /package/src/native/{ghidra → decompiler}/c64rt-wasm.ts +0 -0
  77. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.cspec +0 -0
  78. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.ldefs +0 -0
  79. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.pspec +0 -0
  80. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.sla +0 -0
  81. /package/src/native/{ghidra → decompiler}/pcode.ts +0 -0
  82. /package/src/native/{ghidra → decompiler}/wasm.ts +0 -0
@@ -1,10 +1,10 @@
1
- // The Ghidra analysis: the Ghidra SLEIGH decoder and decompiler with the NMOS
1
+ // The decompiler analysis: the Ghidra SLEIGH decoder and decompiler with the NMOS
2
2
  // 6510 language, in this process as a WebAssembly module. Knowledge seeds go
3
3
  // in, the structural result comes out, and the result is checked completely
4
4
  // before the script imports it.
5
5
 
6
6
  import { describeError, WireFailure } from "../../protocol/messages.ts";
7
- import { checkGhidraResult, checkRequestBounds, GHIDRA_LIMITS, imageRange, seedsInside, type GhidraParams, type GhidraResult } from "../types.ts";
7
+ import { checkDecompilerResult, checkRequestBounds, DECOMPILER_LIMITS, imageRange, seedsInside, type DecompilerParams, type DecompilerResult } from "../types.ts";
8
8
  import type { ToolContext } from "../run.ts";
9
9
  import { walk } from "./walk.ts";
10
10
  import { decompile, loadImage, setName, SLEIGH_VERSION } from "./wasm.ts";
@@ -13,10 +13,10 @@ import { decompile, loadImage, setName, SLEIGH_VERSION } from "./wasm.ts";
13
13
  const MAX_REASON = 1000;
14
14
 
15
15
  export async function analyze(
16
- params: GhidraParams,
16
+ params: DecompilerParams,
17
17
  image: Buffer,
18
18
  context: ToolContext,
19
- ): Promise<{ result: GhidraResult }> {
19
+ ): Promise<{ result: DecompilerResult }> {
20
20
  checkRequestBounds(params);
21
21
  const { start, end, body } = imageRange(params.imageKind, image);
22
22
 
@@ -32,25 +32,25 @@ export async function analyze(
32
32
  loadImage(body, start);
33
33
  walked = walk(body, start, end, { entryPoints, codeStarts, dataRanges, labels: params.labels });
34
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.`);
35
+ context.log?.(`The decoder failed: ${describeError(error)}`);
36
+ throw new WireFailure("operation-failed", `The decoder failed: ${describeError(error)}. Nothing was imported.`);
37
37
  }
38
38
  const { decompilations, notDecompiled } = decompileRoutines(params, walked.functions, body, start, context);
39
39
 
40
- let result: GhidraResult;
40
+ let result: DecompilerResult;
41
41
  try {
42
- result = checkGhidraResult({ ...walked, decompilations, notDecompiled, completeness: { functions: true, regions: true, references: true }, toolVersion: SLEIGH_VERSION });
42
+ result = checkDecompilerResult({ ...walked, decompilations, notDecompiled, completeness: { functions: true, regions: true, references: true }, toolVersion: SLEIGH_VERSION });
43
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)}.`);
44
+ context.log?.(`Decompiler result rejected: ${describeError(error)}`);
45
+ throw new WireFailure("operation-failed", `The decompiler returned an incomplete or inconsistent result. Nothing was imported. The check found: ${describeError(error)}.`);
46
46
  }
47
47
  return { result };
48
48
  }
49
49
 
50
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"]> = [];
51
+ function decompileRoutines(params: DecompilerParams, functions: DecompilerResult["functions"], body: Uint8Array, start: number, context: ToolContext): Pick<DecompilerResult, "decompilations" | "notDecompiled"> {
52
+ const decompilations: DecompilerResult["decompilations"] = [];
53
+ const notDecompiled: NonNullable<DecompilerResult["notDecompiled"]> = [];
54
54
  if (params.decompile.length === 0) return { decompilations, notDecompiled };
55
55
  const entries = new Set(functions.map((fn) => fn.entry));
56
56
  // A trap in the decompiler drops its image: the next routine loads it again.
@@ -63,12 +63,12 @@ function decompileRoutines(params: GhidraParams, functions: GhidraResult["functi
63
63
  setName(label.address, label.name, entries.has(label.address) ? "function" : "data");
64
64
  } catch (error) {
65
65
  // The decompiler then prints its own name for the address.
66
- context.log?.(`The Ghidra decompiler refused the name ${label.name}: ${describeError(error)}`);
66
+ context.log?.(`The decompiler refused the name ${label.name}: ${describeError(error)}`);
67
67
  }
68
68
  }
69
69
  prepared = true;
70
70
  };
71
- let remaining = GHIDRA_LIMITS.decompiledTotalChars;
71
+ let remaining = DECOMPILER_LIMITS.decompiledTotalChars;
72
72
  for (const entry of params.decompile) {
73
73
  if (!entries.has(entry)) {
74
74
  notDecompiled.push({ entry, reason: "no function starts at this address" });
@@ -84,11 +84,11 @@ function decompileRoutines(params: GhidraParams, functions: GhidraResult["functi
84
84
  text = decompile(entry);
85
85
  } catch (error) {
86
86
  prepared = false;
87
- context.log?.(`The Ghidra decompiler failed at ${entry}: ${describeError(error)}`);
87
+ context.log?.(`The decompiler failed at ${entry}: ${describeError(error)}`);
88
88
  notDecompiled.push({ entry, reason: describeError(error).slice(0, MAX_REASON) || "the decompiler gave no reason" });
89
89
  continue;
90
90
  }
91
- const limit = Math.min(GHIDRA_LIMITS.decompiledChars, remaining);
91
+ const limit = Math.min(DECOMPILER_LIMITS.decompiledChars, remaining);
92
92
  const truncated = text.length > limit;
93
93
  if (truncated) text = text.slice(0, limit);
94
94
  remaining -= text.length;
@@ -264,7 +264,7 @@ REL: target is rel [ target = inst_next + rel; ] { export *:2 target; }
264
264
 
265
265
  # BRK skips its padding byte: the return address is two bytes on.
266
266
  # The vector at $FFFE is in ROM unless the program banks the KERNAL out, and
267
- # the analysis cannot know the banking. Thus BRK ends the flow, and Ghidra
267
+ # the analysis cannot know the banking. Thus BRK ends the flow, and the decompiler
268
268
  # does not follow the RAM bytes at $FFFE of a flat image.
269
269
  :BRK is op=0x00 {
270
270
  *:2 (SP - 1) = inst_next + 1;
@@ -6,7 +6,7 @@
6
6
  // code before it, or else from the pointer in the image.
7
7
 
8
8
  import { SYMBOL_NAME } from "../../c64.ts";
9
- import type { GhidraInstruction, GhidraResult } from "../types.ts";
9
+ import type { DecompilerInstruction, DecompilerResult } from "../types.ts";
10
10
  import { PcodeState } from "./pcode.ts";
11
11
  import { decode, type Decoded, type Varnode } from "./wasm.ts";
12
12
 
@@ -39,7 +39,7 @@ function operandValue(bytes: readonly number[]): number | undefined {
39
39
  }
40
40
 
41
41
  /** Decodes [start, end] from the seeds; the image bytes are already loaded at start. */
42
- export function walk(image: Uint8Array, start: number, end: number, seeds: WalkSeeds): Omit<GhidraResult, "decompilations" | "completeness" | "toolVersion"> {
42
+ export function walk(image: Uint8Array, start: number, end: number, seeds: WalkSeeds): Omit<DecompilerResult, "decompilations" | "completeness" | "toolVersion"> {
43
43
  const isData = new Uint8Array(0x10000);
44
44
  for (const range of seeds.dataRanges) isData.fill(1, range.start, range.end + 1);
45
45
  const imageByte = (address: number) => (address >= start && address <= end ? image[address - start] : undefined);
@@ -147,7 +147,7 @@ export function walk(image: Uint8Array, start: number, end: number, seeds: WalkS
147
147
  const labels = new Map(seeds.labels.map((label) => [label.address, label.name]));
148
148
  const sorted = [...instructions.keys()].sort((a, b) => a - b);
149
149
  const seen = new Set<string>();
150
- const references: GhidraResult["references"] = [];
150
+ const references: DecompilerResult["references"] = [];
151
151
  for (const from of sorted) {
152
152
  for (const { to, type } of instructions.get(from)!.references) {
153
153
  const id = `${from}:${to}:${type}`;
@@ -167,7 +167,7 @@ export function walk(image: Uint8Array, start: number, end: number, seeds: WalkS
167
167
  }),
168
168
  regions: regions(start, end, (address) => (owner[address] !== -1 ? "code" : isData[address] ? "data" : undefined)),
169
169
  references,
170
- instructions: sorted.map((address): GhidraInstruction => {
170
+ instructions: sorted.map((address): DecompilerInstruction => {
171
171
  const { decoded, flows } = instructions.get(address)!;
172
172
  return { address, bytes: decoded.bytes.map((byte) => byte.toString(16).padStart(2, "0")).join(""), mnemonic: decoded.mnemonic.toLowerCase(), operands: decoded.operands, flows };
173
173
  }),
@@ -190,8 +190,8 @@ function indirectTarget(address: number, decoded: Decoded, instructions: Map<num
190
190
  return exit.kind === "indirect" && exit.next !== undefined && exit.next !== 0 ? exit.next : undefined;
191
191
  }
192
192
 
193
- function regions(start: number, end: number, kind: (address: number) => "code" | "data" | undefined): GhidraResult["regions"] {
194
- const result: GhidraResult["regions"] = [];
193
+ function regions(start: number, end: number, kind: (address: number) => "code" | "data" | undefined): DecompilerResult["regions"] {
194
+ const result: DecompilerResult["regions"] = [];
195
195
  for (let address = start; address <= end; address++) {
196
196
  const classification = kind(address);
197
197
  if (classification === undefined) continue;
@@ -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. " +
@@ -350,7 +350,7 @@ export class ProcessSupervisor {
350
350
  } catch {
351
351
  // The leader has ended already.
352
352
  }
353
- await Promise.race([exited, sleep(this.#graceMs)]);
353
+ await Promise.race([exited, sleep(this.#graceMs, undefined, { ref: false })]);
354
354
  if (!hasExited(child)) throw new Refusal("operation-failed", `process ${pid} did not end${failure === undefined ? "" : `: ${failure}`}`);
355
355
  return;
356
356
  }
@@ -362,7 +362,7 @@ export class ProcessSupervisor {
362
362
  }
363
363
  }
364
364
  // A group of zombies counts as gone before Node reaps the leader and reports its exit;
365
- // stopped means that Node has seen that exit.
366
- await Promise.race([exited, sleep(KILL_WAIT_MS)]);
365
+ // stopped means that Node has seen that exit. The limit does not keep this process running.
366
+ await Promise.race([exited, sleep(KILL_WAIT_MS, undefined, { ref: false })]);
367
367
  }
368
368
  }
@@ -1,5 +1,5 @@
1
1
  // Types of the native tools that skill scripts run directly (ACME, DXA,
2
- // Ghidra), and the checks of their complete results. The skill script runs
2
+ // the decompiler), and the checks of their complete results. The skill script runs
3
3
  // these tools itself: nothing here crosses the Host Runtime wire. Bytes
4
4
  // (a program, an image, a listing) go next to these values as attachments.
5
5
 
@@ -43,14 +43,14 @@ export interface AcmeResult {
43
43
  export const IMAGE_KINDS = ["prg", "flat64k"] as const;
44
44
  export type ImageKind = (typeof IMAGE_KINDS)[number];
45
45
 
46
- export const GHIDRA_LIMITS = { entryPoints: 1024, codeStarts: 8192, dataRanges: 1024, labels: 4096, decompile: 32, decompiledChars: 16_000, decompiledTotalChars: 128_000 } as const;
46
+ export const DECOMPILER_LIMITS = { entryPoints: 1024, codeStarts: 8192, dataRanges: 1024, labels: 4096, decompile: 32, decompiledChars: 16_000, decompiledTotalChars: 128_000 } as const;
47
47
 
48
- /** The Ghidra analysis. Its image is given next to these fields: a PRG, or 64 KiB from $0000. */
49
- export interface GhidraParams {
48
+ /** The analysis. Its image is given next to these fields: a PRG, or 64 KiB from $0000. */
49
+ export interface DecompilerParams {
50
50
  imageKind: ImageKind;
51
51
  /** Seeds from current knowledge. */
52
52
  entryPoints: number[];
53
- /** Executed instruction starts that Ghidra disassembles without making a function: a branch target is no routine. */
53
+ /** Executed instruction starts that the decompiler disassembles without making a function: a branch target is no routine. */
54
54
  codeStarts?: number[];
55
55
  dataRanges: Array<{ start: number; end: number }>;
56
56
  labels: Array<{ address: number; name: string }>;
@@ -58,7 +58,7 @@ export interface GhidraParams {
58
58
  decompile: number[];
59
59
  }
60
60
 
61
- export interface GhidraInstruction {
61
+ export interface DecompilerInstruction {
62
62
  address: number;
63
63
  /** Lowercase hex, 1 to 3 bytes. */
64
64
  bytes: string;
@@ -69,7 +69,7 @@ export interface GhidraInstruction {
69
69
  flows: number[];
70
70
  }
71
71
 
72
- export interface GhidraResult {
72
+ export interface DecompilerResult {
73
73
  coverage: Array<{ start: number; end: number }>;
74
74
  functions: Array<{ entry: number; name: string; nameSource: "seed" | "generated" | "native" }>;
75
75
  regions: Array<{ start: number; end: number; classification: "code" | "data" }>;
@@ -77,30 +77,30 @@ export interface GhidraResult {
77
77
  decompilations: Array<{ entry: number; text: string; truncated: boolean }>;
78
78
  /** Requested routines without decompiled code, with the decompiler's reason. */
79
79
  notDecompiled?: Array<{ entry: number; reason: string }>;
80
- /** Every instruction in the coverage, as Ghidra decoded it. */
81
- instructions: GhidraInstruction[];
80
+ /** Every instruction in the coverage, as the decompiler decoded it. */
81
+ instructions: DecompilerInstruction[];
82
82
  /** Which categories are complete inside the coverage; private to the importer. */
83
83
  completeness: { functions: boolean; regions: boolean; references: boolean };
84
84
  /** The version of the Ghidra port that made the result, for example "ghidra-decompiler 2.1.0". */
85
85
  toolVersion?: string;
86
86
  }
87
87
 
88
- /** Refuses a DXA or Ghidra request with more seeds or decompilations than the request bounds allow, by name. */
88
+ /** Refuses a DXA or decompiler request with more seeds or decompilations than the request bounds allow, by name. */
89
89
  export function checkRequestBounds(params: DxaParams & { decompile?: number[]; codeStarts?: number[] }): void {
90
90
  const bounds = [
91
- ["entry points", params.entryPoints.length, GHIDRA_LIMITS.entryPoints],
92
- ["code starts", params.codeStarts?.length ?? 0, GHIDRA_LIMITS.codeStarts],
93
- ["data ranges", params.dataRanges.length, GHIDRA_LIMITS.dataRanges],
94
- ["labels", params.labels.length, GHIDRA_LIMITS.labels],
95
- ["routines to decompile", params.decompile?.length ?? 0, GHIDRA_LIMITS.decompile],
91
+ ["entry points", params.entryPoints.length, DECOMPILER_LIMITS.entryPoints],
92
+ ["code starts", params.codeStarts?.length ?? 0, DECOMPILER_LIMITS.codeStarts],
93
+ ["data ranges", params.dataRanges.length, DECOMPILER_LIMITS.dataRanges],
94
+ ["labels", params.labels.length, DECOMPILER_LIMITS.labels],
95
+ ["routines to decompile", params.decompile?.length ?? 0, DECOMPILER_LIMITS.decompile],
96
96
  ] as const;
97
97
  for (const [name, count, limit] of bounds) {
98
98
  if (count > limit) throw new WireFailure("invalid-input", `The request has ${count} ${name}. Give at most ${limit} ${name}.`);
99
99
  }
100
100
  }
101
101
 
102
- /** The DXA analysis: the same image and seeds as Ghidra, without decompilation. */
103
- export type DxaParams = Omit<GhidraParams, "decompile" | "codeStarts">;
102
+ /** The DXA analysis: the same image and seeds as the decompiler, without decompilation. */
103
+ export type DxaParams = Omit<DecompilerParams, "decompile" | "codeStarts">;
104
104
 
105
105
  export interface DxaResult {
106
106
  coverage: Array<{ start: number; end: number }>;
@@ -129,11 +129,11 @@ function fail(message: string): never {
129
129
  const isList = (value: unknown): value is unknown[] => Array.isArray(value);
130
130
 
131
131
  /**
132
- * Checks a complete Ghidra result: every field typed and in range, every
132
+ * Checks a complete decompiler result: every field typed and in range, every
133
133
  * function, region and reference source inside the coverage, regions sorted
134
134
  * and without overlap. Throws an Error naming the first problem.
135
135
  */
136
- export function checkGhidraResult(value: unknown): GhidraResult {
136
+ export function checkDecompilerResult(value: unknown): DecompilerResult {
137
137
  if (!isObject(value)) fail("not an object");
138
138
  const { coverage, functions, regions, references, decompilations, notDecompiled, completeness, toolVersion, instructions } = value;
139
139
  if (!isList(coverage) || coverage.length === 0) fail("no coverage");
@@ -179,16 +179,16 @@ export function checkGhidraResult(value: unknown): GhidraResult {
179
179
  if (!isObject(reference) || !isInteger(reference.from, 0, 0xffff) || !isInteger(reference.to, 0, 0xffff) || !isOneOf(REFERENCE_KINDS, reference.type)) fail("bad reference");
180
180
  if (!covered(reference.from)) fail("a reference source lies outside the coverage");
181
181
  }
182
- if (!isList(decompilations) || decompilations.length > GHIDRA_LIMITS.decompile) fail("bad decompilations");
182
+ if (!isList(decompilations) || decompilations.length > DECOMPILER_LIMITS.decompile) fail("bad decompilations");
183
183
  let total = 0;
184
184
  for (const item of decompilations) {
185
185
  if (!isObject(item) || !isInteger(item.entry, 0, 0xffff) || typeof item.text !== "string" || typeof item.truncated !== "boolean") fail("bad decompilation");
186
- if (item.text.length > GHIDRA_LIMITS.decompiledChars) fail("a decompilation is too long");
186
+ if (item.text.length > DECOMPILER_LIMITS.decompiledChars) fail("a decompilation is too long");
187
187
  total += item.text.length;
188
188
  }
189
- if (total > GHIDRA_LIMITS.decompiledTotalChars) fail("the decompilations are too long together");
189
+ if (total > DECOMPILER_LIMITS.decompiledTotalChars) fail("the decompilations are too long together");
190
190
  if (notDecompiled !== undefined) {
191
- if (!isList(notDecompiled) || notDecompiled.length > GHIDRA_LIMITS.decompile) fail("bad list of routines that were not decompiled");
191
+ if (!isList(notDecompiled) || notDecompiled.length > DECOMPILER_LIMITS.decompile) fail("bad list of routines that were not decompiled");
192
192
  for (const item of notDecompiled) {
193
193
  if (!isObject(item) || !isInteger(item.entry, 0, 0xffff) || typeof item.reason !== "string" || item.reason.length > 1000) fail("bad routine that was not decompiled");
194
194
  }
@@ -196,7 +196,7 @@ export function checkGhidraResult(value: unknown): GhidraResult {
196
196
  if (!isObject(completeness) || typeof completeness.functions !== "boolean" || typeof completeness.regions !== "boolean" || typeof completeness.references !== "boolean") fail("no completeness");
197
197
  if (!isToolVersion(toolVersion)) fail("bad tool version");
198
198
  // Every field is checked: the object is the result as it is.
199
- return value as unknown as GhidraResult;
199
+ return value as unknown as DecompilerResult;
200
200
  }
201
201
 
202
202
  /**
@@ -249,7 +249,7 @@ export function imageRange(kind: ImageKind, image: Uint8Array): { start: number;
249
249
  * it, and the data ranges cut to it. A data range that holds an entry point
250
250
  * is left out, so that the entry point is disassembled.
251
251
  */
252
- export function seedsInside(params: Pick<GhidraParams, "entryPoints" | "dataRanges" | "codeStarts">, start: number, end: number): { entryPoints: number[]; codeStarts: number[]; dataRanges: GhidraParams["dataRanges"] } {
252
+ export function seedsInside(params: Pick<DecompilerParams, "entryPoints" | "dataRanges" | "codeStarts">, start: number, end: number): { entryPoints: number[]; codeStarts: number[]; dataRanges: DecompilerParams["dataRanges"] } {
253
253
  const inside = (address: number) => address >= start && address <= end;
254
254
  const entryPoints = params.entryPoints.filter(inside);
255
255
  const codeStarts = (params.codeStarts ?? []).filter(inside);
package/src/opcodes.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  // The ACME spelling of each 6510 opcode: the mnemonic and the addressing
2
- // mode, undocumented opcodes included. Ghidra gives the instruction
2
+ // mode, undocumented opcodes included. The decompiler gives the instruction
3
3
  // boundaries; this table gives the text. Where several opcodes share one
4
4
  // spelling, ACME writes only one of them: the generator finds those with a
5
5
  // probe and writes the others as bytes.
@@ -1,5 +1,6 @@
1
1
  // The VICE-session operations of the Host Runtime wire: their vocabulary, shapes and validators.
2
2
 
3
+ import { MAX_PRESS_FRAMES, MAX_PRESS_TAPS, MAX_TAP_KEYS, type KeyTap } from "../c64-keys.ts";
3
4
  import { invalid, isInteger, isObject, isOneOf, onlyFields, ProtocolError, VIDEO_STANDARDS, type VideoStandard } from "./messages.ts";
4
5
 
5
6
  export const SPACES = ["c64", "drive8"] as const;
@@ -475,6 +476,20 @@ export interface ExecutionResult {
475
476
  space?: "c64" | "drive8";
476
477
  }
477
478
 
479
+ /**
480
+ * The end of a press: `taps` taps were done. A breakpoint, watchpoint or JAM
481
+ * can stop the taps early; then `stopReason` tells which, and the machine
482
+ * stays stopped. All keys are up again in both cases.
483
+ */
484
+ export interface PressResult {
485
+ taps: number;
486
+ state: RunState;
487
+ stopReason?: PointStopReason;
488
+ pc?: number;
489
+ pointId?: number;
490
+ space?: "c64" | "drive8";
491
+ }
492
+
478
493
  /** c64_run_until targets. */
479
494
  export type RunTarget =
480
495
  | { kind: "address"; address: number; space: Space; condition?: Condition }
@@ -528,6 +543,8 @@ export interface ViceOperations {
528
543
  /** `data`: PETSCII bytes as lowercase hex. */
529
544
  keyboard: { params: { data: string }; result: { queuedBytes: number } };
530
545
  joystick: { params: JoystickState; result: JoystickState };
546
+ /** Each tap holds its keys for `frames` frames, then waits `frames` frames with all keys up. */
547
+ press: { params: { taps: KeyTap[]; frames: number }; result: PressResult };
531
548
  breakpoint: { params: BreakpointParams; result: Breakpoint | PointRemoved | { breakpoints: Breakpoint[] } };
532
549
  watchpoint: { params: WatchpointParams; result: Watchpoint | PointRemoved | { watchpoints: Watchpoint[] } };
533
550
  cpuHistory: { params: { limit: number; space: Space }; result: { entries: HistoryEntry[] } };
@@ -589,6 +606,7 @@ export const VICE_OPERATIONS = [
589
606
  "reset",
590
607
  "keyboard",
591
608
  "joystick",
609
+ "press",
592
610
  "breakpoint",
593
611
  "watchpoint",
594
612
  "screenCapture",
@@ -915,6 +933,24 @@ export function validateViceParams<O extends ViceOperation>(op: O, params: unkno
915
933
  if (/^(?:..)*?00/.test(params.data)) invalid("PETSCII byte 0 cannot be typed");
916
934
  return { data: params.data } as ViceOperations[O]["params"];
917
935
  }
936
+ case "press": {
937
+ onlyFields(params, ["taps", "frames"]);
938
+ if (!Array.isArray(params.taps) || params.taps.length === 0 || params.taps.length > MAX_PRESS_TAPS) invalid(`taps must be a list of 1 to ${MAX_PRESS_TAPS} taps`);
939
+ const taps = (params.taps as unknown[]).map((tap): KeyTap => {
940
+ if (!isObject(tap)) invalid("each tap must be an object with keys and restore");
941
+ onlyFields(tap, ["keys", "restore"], "a tap");
942
+ const { keys, restore } = tap;
943
+ if (!Array.isArray(keys) || !keys.every((key, index) => isInteger(key, 0, 63) && (index === 0 || key > (keys[index - 1] as number)))) {
944
+ invalid("keys of a tap must be matrix places from 0 to 63, each once, in rising order");
945
+ }
946
+ if (typeof restore !== "boolean") invalid("restore of a tap must be true or false");
947
+ const count = keys.length + (restore ? 1 : 0);
948
+ if (count === 0 || count > MAX_TAP_KEYS) invalid(`a tap holds 1 to ${MAX_TAP_KEYS} keys, RESTORE included`);
949
+ return { keys: keys as number[], restore };
950
+ });
951
+ if (!isInteger(params.frames, 1, MAX_PRESS_FRAMES)) invalid(`frames must be a whole number from 1 to ${MAX_PRESS_FRAMES}`);
952
+ return { taps, frames: params.frames } as ViceOperations[O]["params"];
953
+ }
918
954
  case "joystick": {
919
955
  onlyFields(params, ["port", "direction", "fire"]);
920
956
  if (params.port !== 1 && params.port !== 2) invalid("port must be 1 or 2");
@@ -1206,6 +1242,17 @@ export function validateViceResult<O extends ViceOperation>(op: O, value: unknow
1206
1242
  if (!isInteger(value.queuedBytes, 1, MAX_KEYBOARD_BYTES)) throw new ProtocolError("keyboard result is malformed");
1207
1243
  break;
1208
1244
  }
1245
+ case "press": {
1246
+ const ok =
1247
+ isInteger(value.taps, 0, MAX_PRESS_TAPS) &&
1248
+ isOneOf(RUN_STATES, value.state) &&
1249
+ (value.stopReason === undefined || isOneOf(POINT_STOP_REASONS, value.stopReason)) &&
1250
+ (value.pc === undefined || isInteger(value.pc, 0, 0xffff)) &&
1251
+ (value.pointId === undefined || isInteger(value.pointId, 1, Number.MAX_SAFE_INTEGER)) &&
1252
+ (value.space === undefined || isOneOf(SPACES, value.space));
1253
+ if (!ok) throw new ProtocolError("press result is malformed");
1254
+ break;
1255
+ }
1209
1256
  case "breakpoint": {
1210
1257
  const ok = Array.isArray(value.breakpoints) ? value.breakpoints.every(isBreakpoint) : isRemoved(value) || isBreakpoint(value);
1211
1258
  if (!ok) throw new ProtocolError("breakpoint result is malformed");
@@ -0,0 +1,64 @@
1
+ // The first line of each reference page that c64-docs generates: it names
2
+ // the knowledge revision and the source map that the page was made from. The
3
+ // docs script writes and checks it; the generation of the source reads it to
4
+ // tell when a reference of the project is older than the source.
5
+
6
+ import { closeSync, openSync, readdirSync, readSync } from "node:fs";
7
+ import { join, posix } from "node:path";
8
+
9
+ /** The start of every generated page. A page without it is a page of a person, and the generation never writes over it. */
10
+ export const GENERATED_MARK = "<!-- Generated by c64-docs";
11
+
12
+ /** The first line of a generated page: the knowledge revision and the source map of the source that it was made from. */
13
+ export function referenceHeader(revision: string, mapPath: string): string {
14
+ return `${GENERATED_MARK} from knowledge revision ${revision} and ${mapPath}. Do not edit: change the knowledge, generate the source again, then run docs.ts generate. -->`;
15
+ }
16
+
17
+ const STAMP = /^<!-- Generated by c64-docs from knowledge revision (\S+) and (.+?)\. Do not edit/;
18
+
19
+ /** The revision and the source map that a generated page names, or undefined for a page of a person. */
20
+ export function referenceStamp(text: string): { revision: string; mapPath: string } | undefined {
21
+ const found = STAMP.exec(text);
22
+ return found === null ? undefined : { revision: found[1]!, mapPath: posix.normalize(found[2]!) };
23
+ }
24
+
25
+ /** The first bytes of a file: enough for the first line of a page. */
26
+ function head(path: string): string {
27
+ const descriptor = openSync(path, "r");
28
+ try {
29
+ const buffer = Buffer.alloc(512);
30
+ return buffer.subarray(0, readSync(descriptor, buffer, 0, buffer.length, 0)).toString("utf8");
31
+ } catch {
32
+ return "";
33
+ } finally {
34
+ closeSync(descriptor);
35
+ }
36
+ }
37
+
38
+ /**
39
+ * The generated references in a project folder: each folder with a
40
+ * generated index.md, relative to the project with /, and the revision and
41
+ * source map of its index. Folders that start with a dot are not searched.
42
+ */
43
+ export function generatedReferences(root: string): Array<{ folder: string; revision: string; mapPath: string }> {
44
+ const found: Array<{ folder: string; revision: string; mapPath: string }> = [];
45
+ const walk = (relative: string) => {
46
+ let entries;
47
+ try {
48
+ entries = readdirSync(join(root, relative), { withFileTypes: true });
49
+ } catch {
50
+ return;
51
+ }
52
+ for (const entry of entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))) {
53
+ if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
54
+ const path = posix.join(relative, entry.name);
55
+ if (entry.isDirectory()) walk(path);
56
+ else if (entry.isFile() && entry.name === "index.md") {
57
+ const stamp = referenceStamp(head(join(root, path)));
58
+ if (stamp !== undefined) found.push({ folder: relative === "" ? "." : relative, ...stamp });
59
+ }
60
+ }
61
+ };
62
+ walk("");
63
+ return found;
64
+ }
package/src/script.ts CHANGED
@@ -129,7 +129,7 @@ export const OPTIONS = {
129
129
  "timeout-frames": { kind: "count", value: "<n>", help: "stop a wait after this number of video frames", min: 1, max: 1_000_000 },
130
130
  "max-listed": { kind: "count", value: "<n>", help: "list at most n items of each list (default 50). The counts are always given", min: 0, max: 100_000, default: 50 },
131
131
  symbols: { kind: "path", value: "<file>", help: "the symbols of a build: the symbols file of the assembler, or a JSON map of name to $ address" },
132
- origin: { kind: "text", value: "<origin>", help: "user, llm, dxa, ghidra, heuristic, semantic (user and llm) or analyzer (dxa, ghidra and heuristic), or a comma list" },
132
+ origin: { kind: "text", value: "<origin>", help: "user, llm, dxa, decompiler, heuristic, semantic (user and llm) or analyzer (dxa, decompiler and heuristic), or a comma list" },
133
133
  reason: { kind: "text", value: "<text>", help: "why: kept with the revision" },
134
134
  evidence: { kind: "text", value: "<kind:ref>", help: "what the change rests on: coverage:<map>, test:<file>, file:<file> or note:<text>", multiple: true },
135
135
  "expect-revision": { kind: "text", value: "<revision>", help: "refuse the write when the knowledge changed after this revision" },
package/src/vsf.ts ADDED
@@ -0,0 +1,98 @@
1
+ // The modules of a VICE snapshot file (.vsf), and the two changes that press
2
+ // keys in it: the keyboard matrix and a RESTORE. VICE saves a module as its
3
+ // name (16 bytes), its version (major, minor), its size with this header
4
+ // (4 bytes) and its data; every number is little-endian.
5
+
6
+ import { hasSignature, VSF_SIGNATURE } from "./media.ts";
7
+
8
+ /** The size of the header of a module: the name (16 bytes), the version (2 bytes) and the size (4 bytes). */
9
+ const MODULE_HEADER = 22;
10
+ const VSF_VERSION = "VICE Version\x1a";
11
+
12
+ export interface SnapshotModule {
13
+ major: number;
14
+ minor: number;
15
+ /** The data of the module: a view into the file, so a change to it changes the file. */
16
+ data: Buffer;
17
+ }
18
+
19
+ /** The module `name` of a snapshot file. Undefined when the file is no snapshot or has no such module. */
20
+ export function snapshotModule(file: Buffer, name: string): SnapshotModule | undefined {
21
+ if (!hasSignature("vsf", file)) return undefined;
22
+ // The magic, the version (2 bytes) and the machine name (16 bytes); a newer VICE adds its own version (8 bytes).
23
+ let at = VSF_SIGNATURE.length + 2 + 16;
24
+ if (file.subarray(at, at + VSF_VERSION.length).toString("latin1") === VSF_VERSION) at += VSF_VERSION.length + 8;
25
+ while (at + MODULE_HEADER <= file.length) {
26
+ const size = file.readUInt32LE(at + 18);
27
+ if (size < MODULE_HEADER || at + size > file.length) return undefined;
28
+ if (file.subarray(at, at + 16).toString("latin1").replace(/\0+$/, "") === name) {
29
+ return { major: file[at + 16]!, minor: file[at + 17]!, data: file.subarray(at + MODULE_HEADER, at + size) };
30
+ }
31
+ at += size;
32
+ }
33
+ return undefined;
34
+ }
35
+
36
+ /** VICE's keyboard module: keyarr (16 rows) and rev_keyarr (8 columns), each a DWORD. */
37
+ const KEYBOARD = { name: "KEYBOARD", major: 1, minor: 1, size: (16 + 8) * 4 };
38
+
39
+ /**
40
+ * The CPU module of x64sc. VICE r46088 renamed MAINCPU 1.4 to MAINC64CPU 1.5;
41
+ * the data is the same: the clock (8 bytes), A, X, Y, SP, PC (2), P, five
42
+ * DWORDs, five clocks (irq_clk, nmi_clk, ...), then nirq, nnmi and
43
+ * global_pending_int, then two clocks.
44
+ */
45
+ const CPU = [
46
+ { name: "MAINC64CPU", major: 1, minor: 5 },
47
+ { name: "MAINCPU", major: 1, minor: 4 },
48
+ ];
49
+ const CPU_SIZE = 103;
50
+ const NMI_CLK = 43;
51
+ const NNMI = 79;
52
+ const PENDING = 83;
53
+ /** IK_NMI of global_pending_int. */
54
+ const PENDING_NMI = 1;
55
+
56
+ /** A module of a version that the patch knows, or why there is none. */
57
+ function known(file: Buffer, versions: Array<{ name: string; major: number; minor: number }>, size: number): Buffer | string {
58
+ for (const version of versions) {
59
+ const module = snapshotModule(file, version.name);
60
+ if (module === undefined) continue;
61
+ if (module.major !== version.major || module.minor !== version.minor || module.data.length < size) {
62
+ return `the snapshot has ${version.name} ${module.major}.${module.minor} with ${module.data.length} bytes, and c64-re-tools knows ${version.major}.${version.minor} with ${size}`;
63
+ }
64
+ return module.data;
65
+ }
66
+ return `the snapshot has no module ${versions.map((version) => version.name).join(" or ")}`;
67
+ }
68
+
69
+ /**
70
+ * Sets the keyboard matrix of a snapshot file: bit n of rows[r] is the key at
71
+ * row r, column n. Gives why it cannot, for a snapshot of another layout.
72
+ */
73
+ export function setSnapshotMatrix(file: Buffer, rows: readonly number[]): string | undefined {
74
+ const data = known(file, [KEYBOARD], KEYBOARD.size);
75
+ if (typeof data === "string") return data;
76
+ for (let row = 0; row < 16; row++) data.writeUInt32LE(rows[row] ?? 0, row * 4);
77
+ for (let column = 0; column < 8; column++) {
78
+ let lines = 0;
79
+ for (let row = 0; row < 8; row++) if (((rows[row] ?? 0) >> column) & 1) lines |= 1 << row;
80
+ data.writeUInt32LE(lines, 64 + column * 4);
81
+ }
82
+ return undefined;
83
+ }
84
+
85
+ /**
86
+ * Presses RESTORE in a snapshot file, as VICE does: an NMI from now on, unless
87
+ * another source holds the NMI line or an NMI is pending already, which gives
88
+ * no new edge. Gives why it cannot, for a snapshot of another layout.
89
+ */
90
+ export function pressSnapshotRestore(file: Buffer): string | undefined {
91
+ const data = known(file, CPU, CPU_SIZE);
92
+ if (typeof data === "string") return data;
93
+ const pending = data.readUInt32LE(PENDING);
94
+ if (data.readUInt32LE(NNMI) !== 0 || (pending & PENDING_NMI) !== 0) return undefined;
95
+ data.writeUInt32LE(pending | PENDING_NMI, PENDING);
96
+ data.writeBigUInt64LE(data.readBigUInt64LE(0), NMI_CLK);
97
+ return undefined;
98
+ }