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

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 (107) hide show
  1. package/package.json +2 -2
  2. package/skills/c64-assembler/SKILL.md +28 -14
  3. package/skills/c64-assembler/scripts/assembler.ts +28 -15
  4. package/skills/c64-development/SKILL.md +4 -4
  5. package/skills/c64-docs/SKILL.md +9 -7
  6. package/skills/c64-docs/scripts/docs.ts +24 -11
  7. package/skills/c64-docs/scripts/lib/reference.ts +119 -33
  8. package/skills/c64-docs/scripts/lib/source-map.ts +23 -4
  9. package/skills/c64-knowledge/SKILL.md +67 -42
  10. package/skills/c64-knowledge/scripts/knowledge.ts +90 -67
  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 +17 -11
  17. package/skills/c64-source/SKILL.md +71 -47
  18. package/skills/c64-source/scripts/lib/export.ts +89 -34
  19. package/skills/c64-source/scripts/lib/loader.ts +79 -36
  20. package/skills/c64-source/scripts/lib/source.ts +38 -32
  21. package/skills/c64-source/scripts/lib/stage.ts +11 -5
  22. package/skills/c64-source/scripts/lib/start-screen.asm +4 -2
  23. package/skills/c64-source/scripts/source.ts +278 -145
  24. package/skills/c64-static-analysis/SKILL.md +29 -25
  25. package/skills/c64-static-analysis/scripts/lib/coverage.ts +2 -25
  26. package/skills/c64-static-analysis/scripts/lib/findings.ts +11 -11
  27. package/skills/c64-static-analysis/scripts/lib/instructions.ts +26 -24
  28. package/skills/c64-static-analysis/scripts/lib/macros.ts +3 -1
  29. package/skills/c64-static-analysis/scripts/static-analysis.ts +69 -67
  30. package/skills/c64-testing/SKILL.md +15 -5
  31. package/skills/c64-testing/references/recording-format.md +26 -5
  32. package/skills/c64-testing/references/scenario-format.md +11 -8
  33. package/skills/c64-testing/scripts/lib/diff-files.ts +4 -18
  34. package/skills/c64-testing/scripts/lib/play.ts +39 -41
  35. package/skills/c64-testing/scripts/lib/recording.ts +220 -46
  36. package/skills/c64-testing/scripts/lib/replay.ts +32 -6
  37. package/skills/c64-testing/scripts/lib/runs.ts +8 -3
  38. package/skills/c64-testing/scripts/lib/scenario.ts +18 -11
  39. package/skills/c64-testing/scripts/testing.ts +23 -2
  40. package/skills/c64-unpacker/SKILL.md +10 -5
  41. package/skills/c64-unpacker/scripts/lib/loads.ts +34 -13
  42. package/skills/c64-unpacker/scripts/lib/machine.ts +7 -3
  43. package/skills/c64-unpacker/scripts/lib/stages.ts +18 -3
  44. package/skills/c64-unpacker/scripts/unpacker.ts +43 -9
  45. package/skills/emulator/SKILL.md +7 -12
  46. package/src/build-name.ts +55 -0
  47. package/src/c64-keys.ts +98 -0
  48. package/src/c64.ts +22 -2
  49. package/src/cli/main.ts +3 -29
  50. package/src/host/main.ts +3 -3
  51. package/src/host/server.ts +3 -1
  52. package/src/host/tools/index.ts +2 -7
  53. package/src/host/vice/process.ts +34 -17
  54. package/src/host/vice/session.ts +138 -31
  55. package/src/host-client/steps.ts +21 -18
  56. package/src/host-client/tools.ts +2 -7
  57. package/src/host-client/vice-session.ts +7 -1
  58. package/src/knowledge/evidence.ts +66 -0
  59. package/src/knowledge/history.ts +5 -5
  60. package/src/knowledge/import.ts +12 -5
  61. package/src/knowledge/program.ts +123 -32
  62. package/src/knowledge/read.ts +36 -13
  63. package/src/knowledge/schema.ts +43 -17
  64. package/src/knowledge/start-screen.ts +70 -0
  65. package/src/knowledge/text.ts +33 -5
  66. package/src/knowledge/write.ts +75 -36
  67. package/src/mcp/inputs.ts +12 -0
  68. package/src/mcp/server.ts +1 -1
  69. package/src/mcp/tools/debug.ts +23 -21
  70. package/src/mcp/tools/input.ts +38 -5
  71. package/src/mcp/tools/machine.ts +3 -42
  72. package/src/mcp/tools/media.ts +1 -1
  73. package/src/mcp/tools/memory.ts +12 -9
  74. package/src/native/acme.ts +1 -1
  75. package/src/native/c64run.ts +7 -4
  76. package/src/native/decompiler/analyze.ts +98 -0
  77. package/src/native/decompiler/c64rt-wasm.ts +4 -0
  78. package/src/native/decompiler/language/c64rt_6510.sla +0 -0
  79. package/src/native/{ghidra → decompiler}/language/c64rt_6510.slaspec +1 -1
  80. package/src/native/decompiler/pcode.ts +222 -0
  81. package/src/native/decompiler/walk.ts +205 -0
  82. package/src/native/decompiler/wasm.ts +98 -0
  83. package/src/native/discover.ts +3 -3
  84. package/src/native/dxa.ts +12 -1
  85. package/src/native/processes.ts +4 -4
  86. package/src/native/types.ts +27 -27
  87. package/src/opcodes.ts +1 -1
  88. package/src/platform.ts +30 -1
  89. package/src/project.ts +17 -4
  90. package/src/protocol/tools.ts +1 -45
  91. package/src/protocol/vice.ts +47 -0
  92. package/src/reference-pages.ts +64 -0
  93. package/src/script.ts +4 -4
  94. package/src/vsf.ts +98 -0
  95. package/tools/c64run.c +158 -15
  96. package/tools/install-container.sh +1 -2
  97. package/src/cli/status.ts +0 -127
  98. package/src/host/tools/status.ts +0 -47
  99. package/src/native/ghidra/analyze.ts +0 -87
  100. package/src/native/ghidra/index.ts +0 -170
  101. package/src/native/ghidra/scripts/C64Export.java +0 -274
  102. package/src/native/ghidra/scripts/C64Prepare.java +0 -66
  103. package/src/native/status.ts +0 -135
  104. package/tools/install-ghidra.sh +0 -40
  105. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.cspec +0 -0
  106. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.ldefs +0 -0
  107. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.pspec +0 -0
@@ -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,18 +58,18 @@ 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;
65
65
  mnemonic: string;
66
- /** Ghidra's text of the operands, empty for an implied operand. */
66
+ /** The decoder's text of the operands, empty for an implied operand. */
67
67
  operands: string;
68
68
  /** Where the flow goes besides the next instruction: a branch, jump or call target. */
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
- /** The version of the Ghidra that made the result, for example "Ghidra 12.1.3". */
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.
package/src/platform.ts CHANGED
@@ -3,7 +3,7 @@
3
3
  // Names follow "Mapping the Commodore 64". Only platform facts live here:
4
4
  // an address without one belongs to the application.
5
5
 
6
- import { COVERAGE, d018Offsets, formatC64Address, vicBankBase } from "./c64.ts";
6
+ import { type AddressRange, COVERAGE, d018Offsets, formatC64Address, romOnlyRanges, vicBankBase } from "./c64.ts";
7
7
  import { Refusal } from "./errors.ts";
8
8
 
9
9
  export interface Entry {
@@ -433,6 +433,35 @@ export function romUseOfProgram(coverage: Uint8Array | undefined, state: Record<
433
433
  return { basic: true, kernal: true, from: "none" };
434
434
  }
435
435
 
436
+ /** The ROMs as the CPU sees them. */
437
+ const BASIC_ROM: AddressRange = { start: 0xa000, end: 0xbfff };
438
+ const KERNAL_ROM: AddressRange = { start: 0xe000, end: 0xffff };
439
+
440
+ /**
441
+ * The ranges of an image where the CPU sees ROM and not the RAM of the
442
+ * image, so a JSR there runs the ROM: with coverage, the image bytes that the
443
+ * runs used only as ROM; without coverage, the ROMs that $01 of the entry
444
+ * state switches in. A range with known code (`known`) in it is left out:
445
+ * that code stays code.
446
+ */
447
+ export function romRanges(coverage: Uint8Array | undefined, state: Record<string, unknown> | undefined, image: (address: number) => number | undefined, known: readonly number[]): AddressRange[] {
448
+ let ranges: AddressRange[] = [];
449
+ if (coverage !== undefined) ranges = romOnlyRanges(coverage, image);
450
+ else {
451
+ const port = (state?.cpuPort as Record<string, unknown> | undefined)?.$01;
452
+ const use = typeof port === "number" ? romUseOfPort(port) : { basic: false, kernal: false };
453
+ for (const rom of [...(use.basic ? [BASIC_ROM] : []), ...(use.kernal ? [KERNAL_ROM] : [])]) {
454
+ for (let address = rom.start; address <= rom.end; address++) {
455
+ if (image(address) === undefined) continue;
456
+ const last = ranges.at(-1);
457
+ if (last !== undefined && last.end === address - 1) last.end = address;
458
+ else ranges.push({ start: address, end: address });
459
+ }
460
+ }
461
+ }
462
+ return ranges.filter((range) => !known.some((address) => address >= range.start && address <= range.end));
463
+ }
464
+
436
465
  export type Decoded = Record<string, unknown>;
437
466
 
438
467
  const bits = (value: number) => [0, 1, 2, 3, 4, 5, 6, 7].filter((bit) => (value & (1 << bit)) !== 0);
package/src/project.ts CHANGED
@@ -7,7 +7,7 @@
7
7
  import { Refusal } from "./errors.ts";
8
8
  import { accessSync, constants, existsSync, lstatSync, mkdirSync, readdirSync, realpathSync, statSync, writeFileSync } from "node:fs";
9
9
  import { homedir } from "node:os";
10
- import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
10
+ import { basename, dirname, isAbsolute, join, posix, relative, resolve, sep } from "node:path";
11
11
 
12
12
  /** The folder that marks a project and holds its knowledge. */
13
13
  export const PROJECT_DIRECTORY = ".c64-re-tools";
@@ -15,6 +15,18 @@ export const PROJECT_DIRECTORY = ".c64-re-tools";
15
15
  /** The folder for machine-local scratch: saved results, batches and step files. */
16
16
  export const LOCAL_DIRECTORY = "local";
17
17
 
18
+ /** The folder in LOCAL_DIRECTORY for the reports of a generated source: its source map and the code that no run executed. */
19
+ export const GENERATED_DIRECTORY = "generated";
20
+
21
+ /**
22
+ * The folder of the reports of the source that was generated into `out`, relative
23
+ * to the project folder: .c64-re-tools/local/generated/<out>. The source folder
24
+ * then holds only source files.
25
+ */
26
+ export function generatedDirectory(out: string): string {
27
+ return posix.join(PROJECT_DIRECTORY, LOCAL_DIRECTORY, GENERATED_DIRECTORY, posix.normalize(out.split("\\").join("/")).replace(/\/+$/, ""));
28
+ }
29
+
18
30
  /** The .gitignore of LOCAL_DIRECTORY: git ignores everything in it, the .gitignore too. */
19
31
  const LOCAL_GITIGNORE = "# Machine-local scratch of c64-re-tools (saved results, batches, step files). Never committed.\n*\n";
20
32
 
@@ -145,7 +157,7 @@ export function namedProject(folder: string, cwd: string = process.cwd()): strin
145
157
  }
146
158
 
147
159
  /**
148
- * A group folder: a folder of a git repository, in no project, that holds
160
+ * A group folder: a folder of a git repository, in no project, that holds two or more
149
161
  * projects, for example one project for each version of a game. Its pages can
150
162
  * link into each project, and a page of a project into the other projects.
151
163
  */
@@ -163,7 +175,7 @@ function inRepository(folder: string): boolean {
163
175
  /**
164
176
  * The group at `folder`: its folders that are projects and are not a git
165
177
  * repository of their own. Undefined when `folder` is the home folder, is in a
166
- * project, is in no git repository, or holds no project.
178
+ * project, is in no git repository, or holds fewer than two projects.
167
179
  */
168
180
  export function groupAt(folder: string): ProjectGroup | undefined {
169
181
  const root = resolve(folder);
@@ -181,7 +193,8 @@ export function groupAt(folder: string): ProjectGroup | undefined {
181
193
  const path = join(root, entry.name);
182
194
  if (isProject(path) && !existsSync(join(path, ".git"))) projects.set(entry.name, path);
183
195
  }
184
- return projects.size === 0 ? undefined : { root, projects };
196
+ // One project alone is no group: a group holds the versions of one program.
197
+ return projects.size < 2 ? undefined : { root, projects };
185
198
  }
186
199
 
187
200
  /** The group of the project `root`: the folder above it, when that is a group that holds the project. */
@@ -79,38 +79,12 @@ export type PetcatResult =
79
79
  handoffs: BasicHandoff[];
80
80
  };
81
81
 
82
- /** One native tool on the host, as host.status found and ran it. */
83
- export interface ToolStatus {
84
- name: string;
85
- found: boolean;
86
- /** Where it is, when found. */
87
- path?: string;
88
- /** Its version text, when it ran. */
89
- version?: string;
90
- runs: boolean;
91
- /** What is wrong and what to do, when it is missing or does not run. */
92
- problem?: string;
93
- /** Known flaws of this version, each with the version that fixes it. The tool still runs. */
94
- flaws?: string[];
95
- }
96
-
97
- /** The Host Runtime itself: its package version and the system it runs on. */
98
- export interface HostInfo {
99
- version: string;
100
- /** Node's name of the operating system: linux, darwin or win32. */
101
- platform: string;
102
- /** The release of the operating system. */
103
- release: string;
104
- arch: string;
105
- }
106
-
107
82
  export interface ToolOperations {
108
- "host.status": { params: Record<string, never>; result: { host: HostInfo; tools: ToolStatus[] } };
109
83
  "c1541.inspect": { params: C1541Params; result: C1541Result };
110
84
  "petcat.decode": { params: PetcatParams; result: PetcatResult };
111
85
  }
112
86
  export type ToolOperation = keyof ToolOperations;
113
- export const TOOL_OPERATIONS = ["host.status", "c1541.inspect", "petcat.decode"] as const satisfies readonly ToolOperation[];
87
+ export const TOOL_OPERATIONS = ["c1541.inspect", "petcat.decode"] as const satisfies readonly ToolOperation[];
114
88
 
115
89
  const RELATIVE_PATH = /^(?!\/)(?!.*(?:^|\/)\.\.?(?:\/|$))[^\0\\]+$/;
116
90
 
@@ -166,10 +140,6 @@ export function validateToolParams<O extends ToolOperation>(op: O, params: unkno
166
140
  oneFile(attachments, "the program");
167
141
  return {} as ToolOperations[O]["params"];
168
142
  }
169
- case "host.status":
170
- onlyFields(params, []);
171
- if (attachments.length !== 0) invalid("host.status takes no attachment");
172
- return {} as ToolOperations[O]["params"];
173
143
  }
174
144
  return invalid(`unknown tool operation: ${String(op)}`);
175
145
  }
@@ -186,20 +156,6 @@ export function validateToolResult<O extends ToolOperation>(op: O, value: unknow
186
156
  if (!isPetcatResult(value) || attachments.length !== 0) throw new ProtocolError("petcat.decode result is malformed");
187
157
  return value as unknown as ToolOperations[O]["result"];
188
158
  }
189
- case "host.status": {
190
- const tools = value.tools;
191
- const isStatus = (tool: unknown) =>
192
- isObject(tool) &&
193
- typeof tool.name === "string" &&
194
- typeof tool.found === "boolean" &&
195
- typeof tool.runs === "boolean" &&
196
- [tool.path, tool.version, tool.problem].every((field) => field === undefined || typeof field === "string") &&
197
- (tool.flaws === undefined || (Array.isArray(tool.flaws) && tool.flaws.every((flaw: unknown) => typeof flaw === "string")));
198
- const host = value.host;
199
- const isHost = isObject(host) && [host.version, host.platform, host.release, host.arch].every((field) => typeof field === "string");
200
- if (!isHost || !Array.isArray(tools) || !tools.every(isStatus) || attachments.length !== 0) throw new ProtocolError("host.status result is malformed");
201
- return value as unknown as ToolOperations[O]["result"];
202
- }
203
159
  }
204
160
  throw new ProtocolError(`unknown tool operation: ${String(op)}`);
205
161
  }
@@ -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
@@ -88,7 +88,7 @@ export type OptionKind =
88
88
  | "number" // a value: $ and hex digits, decimal, or % and binary digits
89
89
  | "address" // $ and 1 to 4 hex digits, or a name
90
90
  | "range" // <start>-<end>, each an address
91
- | "space" // c64, drive8, or bank0 to bank255
91
+ | "space" // c64, drive8, loading, or bank0 to bank255
92
92
  | "choice"; // one of `choices`
93
93
 
94
94
  export interface OptionSpec {
@@ -121,7 +121,7 @@ export interface OptionSpec {
121
121
  /** The options that have one meaning in every script. A command can change the help, the value and whether it is required, never the kind. */
122
122
  export const OPTIONS = {
123
123
  out: { kind: "path", value: "<path>", help: "write the output here, relative to the project folder" },
124
- space: { kind: "space", value: "<space>", help: "the knowledge space: c64 (the default), drive8 for 1541 drive code, or bank0 to bank255 for a cartridge bank", default: "c64" },
124
+ space: { kind: "space", value: "<space>", help: "the knowledge space: c64 (the default), drive8 for 1541 drive code, loading for a captured stage of the loading, or bank0 to bank255 for a cartridge bank or another memory image of the program", default: "c64" },
125
125
  range: { kind: "range", value: "<start>-<end>", help: "only the addresses from start to end, for example '$c000-$cfff'" },
126
126
  entry: { kind: "address", value: "<address>", help: "an entry point of the program" },
127
127
  steps: { kind: "path", value: "<file>", help: "a JSON file of action steps that run after the start" },
@@ -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" },
@@ -608,7 +608,7 @@ export function parseCall(script: ScriptSpec, command: CommandSpec, argv: readon
608
608
  if (text === "") throw new UsageError(`--${name} needs a value`);
609
609
  if (spec.kind === "address" && !isAddressText(text)) throw new UsageError(`--${name} must be ${ADDRESS_FORM}, not ${JSON.stringify(text)}`);
610
610
  if (spec.kind === "range" && rangeParts(text) === undefined) throw new UsageError(`--${name} must be <start>-<end>, each ${ADDRESS_FORM}, for example '$c000-$cfff', not ${JSON.stringify(text)}`);
611
- if (spec.kind === "space" && !SPACE_PATTERN.test(text)) throw new UsageError(`--${name} must be c64, drive8, or bank0 to bank255, not ${JSON.stringify(text)}`);
611
+ if (spec.kind === "space" && !SPACE_PATTERN.test(text)) throw new UsageError(`--${name} must be c64, drive8, loading, or bank0 to bank255, not ${JSON.stringify(text)}`);
612
612
  if (spec.kind === "choice" && !(spec.choices ?? []).includes(text)) throw new UsageError(`--${name} must be one of ${(spec.choices ?? []).join(", ")}, not ${JSON.stringify(text)}`);
613
613
  if (spec.kind === "path") {
614
614
  if (spec.output === undefined) checkPath(text, `--${name}`, true);
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
+ }