@henols/c64-re-tools 2.6.0-rc.9 → 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 (68) hide show
  1. package/package.json +1 -1
  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 +5 -3
  6. package/skills/c64-docs/scripts/docs.ts +17 -4
  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 +8 -7
  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 +11 -8
  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 -17
  16. package/skills/c64-source/scripts/source.ts +51 -36
  17. package/skills/c64-static-analysis/SKILL.md +23 -21
  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 +36 -27
  22. package/skills/c64-testing/SKILL.md +10 -3
  23. package/skills/c64-testing/references/recording-format.md +8 -2
  24. package/skills/c64-testing/references/scenario-format.md +4 -2
  25. package/skills/c64-testing/scripts/lib/recording.ts +193 -28
  26. package/skills/c64-testing/scripts/lib/replay.ts +31 -5
  27. package/skills/c64-testing/scripts/lib/runs.ts +7 -2
  28. package/skills/c64-testing/scripts/lib/scenario.ts +3 -3
  29. package/skills/c64-testing/scripts/testing.ts +23 -2
  30. package/skills/c64-unpacker/SKILL.md +4 -2
  31. package/skills/c64-unpacker/scripts/lib/stages.ts +18 -3
  32. package/skills/c64-unpacker/scripts/unpacker.ts +38 -6
  33. package/src/build-name.ts +9 -4
  34. package/src/c64.ts +1 -1
  35. package/src/host/main.ts +2 -2
  36. package/src/host/server.ts +3 -1
  37. package/src/host/tools/index.ts +1 -1
  38. package/src/host/vice/process.ts +34 -17
  39. package/src/host/vice/session.ts +55 -27
  40. package/src/host-client/steps.ts +4 -1
  41. package/src/host-client/tools.ts +1 -1
  42. package/src/knowledge/evidence.ts +66 -0
  43. package/src/knowledge/history.ts +5 -5
  44. package/src/knowledge/import.ts +12 -5
  45. package/src/knowledge/program.ts +81 -33
  46. package/src/knowledge/read.ts +3 -3
  47. package/src/knowledge/schema.ts +7 -7
  48. package/src/knowledge/start-screen.ts +2 -0
  49. package/src/knowledge/text.ts +28 -3
  50. package/src/knowledge/write.ts +6 -6
  51. package/src/mcp/tools/debug.ts +23 -21
  52. package/src/mcp/tools/memory.ts +12 -9
  53. package/src/native/c64run.ts +7 -4
  54. package/src/native/{ghidra → decompiler}/analyze.ts +17 -17
  55. package/src/native/{ghidra → decompiler}/language/c64rt_6510.slaspec +1 -1
  56. package/src/native/{ghidra → decompiler}/walk.ts +6 -6
  57. package/src/native/types.ts +25 -25
  58. package/src/opcodes.ts +1 -1
  59. package/src/reference-pages.ts +64 -0
  60. package/src/script.ts +1 -1
  61. package/tools/c64run.c +150 -4
  62. /package/src/native/{ghidra → decompiler}/c64rt-wasm.ts +0 -0
  63. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.cspec +0 -0
  64. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.ldefs +0 -0
  65. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.pspec +0 -0
  66. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.sla +0 -0
  67. /package/src/native/{ghidra → decompiler}/pcode.ts +0 -0
  68. /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;
@@ -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.
@@ -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/tools/c64run.c CHANGED
@@ -27,7 +27,7 @@
27
27
  #include "systems/c1541.h"
28
28
  #include "systems/c64.h"
29
29
 
30
- #define C64RUN_PROTOCOL 4
30
+ #define C64RUN_PROTOCOL 7
31
31
  // The key code of matrix place 0 (row 0, column 0); place n has code 0x80 + n.
32
32
  #define C64RUN_KEY_PLACE 0x80
33
33
  #ifndef CHIPS_COMMIT
@@ -226,6 +226,80 @@ static void sample(void) {
226
226
  if (sample_stop && samples >= sample_stop) halted = 1;
227
227
  }
228
228
 
229
+ // ---- Counts: the opcode fetches at some pcs, from "count-pc" on ----
230
+
231
+ #define MAX_COUNTED 64
232
+ // 0: the pc is not counted; else the index of its count + 1.
233
+ static uint8_t counted_at[0x10000];
234
+ static uint16_t counted_pc[MAX_COUNTED];
235
+ static uint64_t counted[MAX_COUNTED];
236
+ static int counted_pcs;
237
+ // "mark": the counts and the tick at the first opcode fetch at mark_pc, before that fetch counts.
238
+ static uint64_t marked[MAX_COUNTED];
239
+ static uint64_t mark_tick;
240
+ static int mark_pc = -1; // -1: no mark waits
241
+ static int mark_set; // marked and mark_tick hold the mark
242
+
243
+ // The phase of the machine at the mark: the beam position, the timers and interrupt
244
+ // state of both CIAs and the interrupt state of the CPU. It depends on how the
245
+ // program was started, and no program can set all of it. "align" gives it to
246
+ // another run at its own entry, so both runs go on from the same phase.
247
+ typedef struct {
248
+ uint16_t line, cycle;
249
+ m6526_timer_t ta[2], tb[2];
250
+ m6526_int_t intr[2];
251
+ uint16_t irq_pip;
252
+ uint32_t nmi_pip;
253
+ uint8_t brk_flags;
254
+ uint64_t pins, cpu_pins; // only the IRQ and NMI lines
255
+ } phase_t;
256
+ static phase_t mark_phase;
257
+
258
+ static void phase_get(phase_t* p) {
259
+ memset(p, 0, sizeof *p);
260
+ p->line = sys.vic.rs.v_count;
261
+ p->cycle = sys.vic.rs.h_count;
262
+ const m6526_t* cia[2] = { &sys.cia_1, &sys.cia_2 };
263
+ for (int i = 0; i < 2; i++) { p->ta[i] = cia[i]->ta; p->tb[i] = cia[i]->tb; p->intr[i] = cia[i]->intr; }
264
+ p->irq_pip = sys.cpu.irq_pip;
265
+ p->nmi_pip = sys.cpu.nmi_pip;
266
+ p->brk_flags = sys.cpu.brk_flags;
267
+ p->pins = pins & (M6502_IRQ | M6502_NMI);
268
+ p->cpu_pins = sys.cpu.PINS & (M6502_IRQ | M6502_NMI);
269
+ }
270
+
271
+ static void phase_set(const phase_t* p) {
272
+ m6526_t* cia[2] = { &sys.cia_1, &sys.cia_2 };
273
+ for (int i = 0; i < 2; i++) { cia[i]->ta = p->ta[i]; cia[i]->tb = p->tb[i]; cia[i]->intr = p->intr[i]; }
274
+ sys.cpu.irq_pip = p->irq_pip;
275
+ sys.cpu.nmi_pip = p->nmi_pip;
276
+ sys.cpu.brk_flags = p->brk_flags;
277
+ pins = (pins & ~(M6502_IRQ | M6502_NMI)) | p->pins;
278
+ sys.cpu.PINS = (sys.cpu.PINS & ~(M6502_IRQ | M6502_NMI)) | p->cpu_pins;
279
+ }
280
+
281
+ static void clear_counts(void) {
282
+ for (int i = 0; i < counted_pcs; i++) counted_at[counted_pc[i]] = 0;
283
+ counted_pcs = 0;
284
+ mark_pc = -1;
285
+ mark_set = 0;
286
+ }
287
+
288
+ static void count_fetch(uint16_t pc) {
289
+ if (mark_pc == pc) {
290
+ for (int i = 0; i < counted_pcs; i++) marked[i] = counted[i];
291
+ mark_tick = ticks;
292
+ phase_get(&mark_phase);
293
+ mark_pc = -1;
294
+ mark_set = 1;
295
+ }
296
+ if (counted_at[pc]) counted[counted_at[pc] - 1]++;
297
+ }
298
+
299
+ static uint64_t count_of(uint16_t pc) {
300
+ return counted_at[pc] ? counted[counted_at[pc] - 1] : 0;
301
+ }
302
+
229
303
  // ---- The tick ----
230
304
 
231
305
  static void tick(void) {
@@ -240,6 +314,14 @@ static void tick(void) {
240
314
  last_sync_pc = addr;
241
315
  if (sample_file && addr == sample_pc && decoded) sample();
242
316
  if (coverage_armed_pc && addr == coverage_pc && decoded) { coverage_armed_pc = 0; coverage_start(addr); }
317
+ if (decoded) count_fetch(addr);
318
+ }
319
+ if (read && !sync && decoded && sys.io_mapped && (addr & 0xFF0F) == 0xDC00) {
320
+ // chips gives port A of CIA 1 only joystick 2. A key also pulls its line of port A
321
+ // low while port B drives its column low: the scan from port B that some games use.
322
+ const m6526_port_t* pb = &sys.cia_1.pb;
323
+ const uint8_t low_columns = (uint8_t)~(pb->reg | ~pb->ddr);
324
+ if (low_columns) M6502_SET_DATA(pins, M6502_GET_DATA(pins) & (uint8_t)~kbd_test_lines(&sys.kbd, low_columns));
243
325
  }
244
326
  if (read && !sync && decoded && sys.io_mapped && (addr & 0xF000) == 0xD000 && input_addr[addr & 0x0FFF]) {
245
327
  input_read(last_sync_pc, addr);
@@ -437,6 +519,7 @@ int main(int argc, char** argv) {
437
519
  halted = 0;
438
520
  sample_stop = 0;
439
521
  maps = 0;
522
+ clear_counts();
440
523
  coverage_reset();
441
524
  if (pin_file) { fclose(pin_file); pin_file = NULL; }
442
525
  if (record_file) { fclose(record_file); record_file = NULL; }
@@ -486,6 +569,7 @@ int main(int argc, char** argv) {
486
569
  last_sync_pc = pc;
487
570
  // The prefetch is the opcode fetch at pc: it does not pass through tick.
488
571
  if (coverage_armed_pc && pc == coverage_pc) { coverage_armed_pc = 0; coverage_start(pc); }
572
+ count_fetch((uint16_t)pc);
489
573
  if (coverage_on) cover(pc, 1, 1);
490
574
  status("ok");
491
575
  } else if (!strcmp(cmd, "run")) {
@@ -498,12 +582,74 @@ int main(int argc, char** argv) {
498
582
  do tick(); while (!(pins & M6502_SYNC) && !halted);
499
583
  status("ok");
500
584
  } else if (!strcmp(cmd, "run-pc")) {
501
- // run-pc <pc hex> <until tick>: run to the next opcode fetch at pc
585
+ // run-pc <pc hex> <until tick> [<n>]: run to the next opcode fetch at pc; with n, run
586
+ // until the count of pc ("count-pc") is n
502
587
  unsigned pc;
503
- const unsigned long long until = strtoull(a2, NULL, 10);
504
- if (sscanf(a1, "%x", &pc) != 1) { printf("err run-pc: give a pc and a tick\n"); continue; }
588
+ unsigned long long until, n;
589
+ const int fields = sscanf(line, "%*s %x %llu %llu", &pc, &until, &n);
590
+ if (fields < 2 || pc > 0xFFFF) { printf("err run-pc: give a pc and a tick\n"); continue; }
591
+ if (fields == 3) {
592
+ if (!counted_at[pc]) { printf("err run-pc: give count-pc with %04x first\n", pc); continue; }
593
+ while (count_of((uint16_t)pc) < n && ticks < until && !halted) tick();
594
+ status(count_of((uint16_t)pc) >= n ? "ok reached" : "ok not-reached");
595
+ continue;
596
+ }
505
597
  do tick(); while (!((pins & M6502_SYNC) && M6502_GET_ADDR(pins) == pc) && ticks < until && !halted);
506
598
  status((pins & M6502_SYNC) && M6502_GET_ADDR(pins) == pc ? "ok reached" : "ok not-reached");
599
+ } else if (!strcmp(cmd, "count-pc")) {
600
+ // count-pc <pc hex,...> | off: count the opcode fetches at each pc from 0
601
+ clear_counts();
602
+ if (!strcmp(a1, "off")) { printf("ok counted=0\n"); continue; }
603
+ int bad = 0;
604
+ for (char* part = strtok(a1, ","); part; part = strtok(NULL, ",")) {
605
+ unsigned pc;
606
+ if (sscanf(part, "%x", &pc) != 1 || pc > 0xFFFF || counted_pcs == MAX_COUNTED) { bad = 1; break; }
607
+ if (counted_at[pc]) continue;
608
+ counted_pc[counted_pcs] = (uint16_t)pc;
609
+ counted[counted_pcs] = 0;
610
+ counted_at[pc] = (uint8_t)++counted_pcs;
611
+ }
612
+ if (bad) { clear_counts(); printf("err count-pc: give 1 to %d pcs in hex\n", MAX_COUNTED); } else printf("ok counted=%d\n", counted_pcs);
613
+ } else if (!strcmp(cmd, "mark")) {
614
+ // mark <pc hex>: keep the counts of count-pc at the next opcode fetch at pc, before it counts
615
+ unsigned pc;
616
+ if (sscanf(a1, "%x", &pc) != 1 || pc > 0xFFFF) { printf("err mark: give a pc\n"); continue; }
617
+ mark_pc = (int)pc;
618
+ mark_set = 0;
619
+ printf("ok\n");
620
+ } else if (!strcmp(cmd, "marked")) {
621
+ // marked: the tick and the phase (hex) of the mark when it came, else none
622
+ if (mark_set) {
623
+ printf("ok tick=%llu phase=", (unsigned long long)mark_tick);
624
+ for (size_t i = 0; i < sizeof mark_phase; i++) printf("%02x", ((const uint8_t*)&mark_phase)[i]);
625
+ printf("\n");
626
+ }
627
+ else printf("ok none\n");
628
+ } else if (!strcmp(cmd, "align")) {
629
+ // align <phase hex>: at an opcode fetch, hold the CPU on the fetch (RDY, as the VIC-II
630
+ // does on a bad line) until the beam is at the position of the phase, then give the
631
+ // CIAs and the CPU the timers and interrupt state of the phase (from "marked")
632
+ phase_t p;
633
+ if (strlen(a1) != 2 * sizeof p || !(pins & M6502_SYNC)) { printf("err align: give the phase of marked, at an opcode fetch\n"); continue; }
634
+ for (size_t i = 0; i < sizeof p; i++) ((uint8_t*)&p)[i] = (uint8_t)hexbyte(a1 + 2 * i);
635
+ // A PAL frame holds each beam position one time.
636
+ uint64_t held = 0;
637
+ while ((sys.vic.rs.v_count != p.line || sys.vic.rs.h_count != p.cycle) && held <= 312 * 63) {
638
+ pins = _c64_tick(&sys, pins | M6502_RDY);
639
+ ticks++;
640
+ held++;
641
+ }
642
+ if (sys.vic.rs.v_count != p.line || sys.vic.rs.h_count != p.cycle) { printf("err align: the beam never came to line %u cycle %u\n", p.line, p.cycle); continue; }
643
+ phase_set(&p);
644
+ char prefix[64];
645
+ snprintf(prefix, sizeof prefix, "ok held=%llu", (unsigned long long)held);
646
+ status(prefix);
647
+ } else if (!strcmp(cmd, "hits")) {
648
+ // hits <pc hex>: the count of a pc of count-pc, and its count at the mark when the mark came
649
+ unsigned pc;
650
+ if (sscanf(a1, "%x", &pc) != 1 || pc > 0xFFFF) { printf("err hits: give a pc\n"); continue; }
651
+ if (mark_set && counted_at[pc]) printf("ok count=%llu marked=%llu\n", (unsigned long long)count_of((uint16_t)pc), (unsigned long long)marked[counted_at[pc] - 1]);
652
+ else printf("ok count=%llu\n", (unsigned long long)count_of((uint16_t)pc));
507
653
  } else if (!strcmp(cmd, "run-reads")) {
508
654
  // run-reads <pc hex> <addr hex> <n> <until tick>: run until the site has n reads
509
655
  unsigned pc, addr;
File without changes
File without changes
File without changes