@henols/c64-re-tools 2.6.0-rc.13 → 2.6.0-rc.15

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 (41) 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-docs/SKILL.md +1 -1
  5. package/skills/c64-docs/scripts/lib/reference.ts +29 -7
  6. package/skills/c64-docs/scripts/lib/source-map.ts +14 -0
  7. package/skills/c64-knowledge/SKILL.md +5 -5
  8. package/skills/c64-knowledge/scripts/knowledge.ts +11 -3
  9. package/skills/c64-source/SKILL.md +2 -2
  10. package/skills/c64-source/scripts/lib/export.ts +1 -1
  11. package/skills/c64-source/scripts/lib/loader.ts +2 -0
  12. package/skills/c64-source/scripts/lib/source.ts +4 -4
  13. package/skills/c64-source/scripts/source.ts +22 -17
  14. package/skills/c64-static-analysis/SKILL.md +21 -20
  15. package/skills/c64-static-analysis/scripts/lib/findings.ts +11 -11
  16. package/skills/c64-static-analysis/scripts/lib/instructions.ts +4 -4
  17. package/skills/c64-static-analysis/scripts/static-analysis.ts +28 -26
  18. package/skills/c64-testing/scripts/testing.ts +5 -3
  19. package/src/build-name.ts +9 -4
  20. package/src/c64.ts +1 -1
  21. package/src/host/tools/index.ts +1 -1
  22. package/src/host-client/tools.ts +1 -1
  23. package/src/knowledge/import.ts +5 -5
  24. package/src/knowledge/program.ts +1 -1
  25. package/src/knowledge/read.ts +3 -3
  26. package/src/knowledge/schema.ts +3 -3
  27. package/src/native/c64run.ts +1 -1
  28. package/src/native/{ghidra → decompiler}/analyze.ts +17 -17
  29. package/src/native/{ghidra → decompiler}/language/c64rt_6510.slaspec +1 -1
  30. package/src/native/{ghidra → decompiler}/walk.ts +6 -6
  31. package/src/native/types.ts +25 -25
  32. package/src/opcodes.ts +1 -1
  33. package/src/script.ts +1 -1
  34. package/tools/c64run.c +8 -1
  35. /package/src/native/{ghidra → decompiler}/c64rt-wasm.ts +0 -0
  36. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.cspec +0 -0
  37. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.ldefs +0 -0
  38. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.pspec +0 -0
  39. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.sla +0 -0
  40. /package/src/native/{ghidra → decompiler}/pcode.ts +0 -0
  41. /package/src/native/{ghidra → decompiler}/wasm.ts +0 -0
@@ -1,4 +1,4 @@
1
- // Knowledge seeds for an analyzer, and the mapping of a Ghidra result to the
1
+ // Knowledge seeds for an analyzer, and the mapping of a decompiler result to the
2
2
  // common normalized findings.
3
3
 
4
4
  import type { DatabaseSync } from "node:sqlite";
@@ -6,9 +6,9 @@ import type { DatabaseSync } from "node:sqlite";
6
6
  import type { NormalizedFindings } from "#src/knowledge/import.ts";
7
7
  import { listRegions, listSymbols } from "#src/knowledge/read.ts";
8
8
  import { CODE_REGION_TYPES, DEFAULT_SPACE, isSemantic, type Space } from "#src/knowledge/schema.ts";
9
- import type { DxaResult, GhidraParams, GhidraResult } from "#src/native/types.ts";
9
+ import type { DxaResult, DecompilerParams, DecompilerResult } from "#src/native/types.ts";
10
10
 
11
- export type Seeds = Pick<GhidraParams, "entryPoints" | "dataRanges" | "labels">;
11
+ export type Seeds = Pick<DecompilerParams, "entryPoints" | "dataRanges" | "labels">;
12
12
 
13
13
  const semantic = (row: { origin: string }) => isSemantic(row.origin);
14
14
 
@@ -49,12 +49,12 @@ export function seedsFromKnowledge(db: DatabaseSync | undefined, extraEntryPoint
49
49
 
50
50
  /**
51
51
  * The 6510 opcodes with a low nibble of 1 or 3 use (zp,x) or (zp),y, also the
52
- * undocumented ones. Ghidra gives such an instruction a reference to the target
52
+ * undocumented ones. The decompiler gives such an instruction a reference to the target
53
53
  * that it computes from the pointer value at the entry state: a guess, because
54
54
  * the program sets the pointer at run time. Only the reference to the pointer
55
55
  * itself (zp or zp+1) is a fact.
56
56
  */
57
- function guessedIndirectTarget(instructions: GhidraResult["instructions"]): (reference: { from: number; to: number }) => boolean {
57
+ function guessedIndirectTarget(instructions: DecompilerResult["instructions"]): (reference: { from: number; to: number }) => boolean {
58
58
  const pointers = new Map<number, number>();
59
59
  for (const instruction of instructions) {
60
60
  const opcode = Number.parseInt(instruction.bytes.slice(0, 2), 16);
@@ -67,28 +67,28 @@ function guessedIndirectTarget(instructions: GhidraResult["instructions"]): (ref
67
67
  }
68
68
 
69
69
  /**
70
- * Ghidra's result as normalized findings. A reference from a (zp,x) or (zp),y
70
+ * The decompiler's result as normalized findings. A reference from a (zp,x) or (zp),y
71
71
  * instruction to a computed target is not a finding (see guessedIndirectTarget).
72
72
  * A function named by an echoed seed
73
73
  * stays in the snapshot: its address holds the seed's semantic symbol, which
74
74
  * the importer never replaces, so the name keeps its owner,
75
75
  * and a code/data disagreement with that symbol is still reported.
76
76
  */
77
- export function ghidraFindings(result: GhidraResult): NormalizedFindings {
78
- // Ghidra can give one generated name to two functions, for example
77
+ export function decompilerFindings(result: DecompilerResult): NormalizedFindings {
78
+ // The decompiler can give one generated name to two functions, for example
79
79
  // thunk_FUN_e434 to two thunks of one routine. A name
80
80
  // must have one address, so a repeated name that is not a seed gets its address.
81
81
  const uses = new Map<string, number>();
82
82
  for (const fn of result.functions) uses.set(fn.name, (uses.get(fn.name) ?? 0) + 1);
83
- const nameOf = (fn: GhidraResult["functions"][number]) =>
83
+ const nameOf = (fn: DecompilerResult["functions"][number]) =>
84
84
  fn.nameSource !== "seed" && uses.get(fn.name)! > 1 ? `${fn.name}_${fn.entry.toString(16).padStart(4, "0")}` : fn.name;
85
85
  // A function that branches and jumps reach, and no call, is a place in a routine: a label.
86
86
  const called = new Set(result.references.filter((reference) => reference.type === "call").map((reference) => reference.to));
87
87
  const jumped = new Set(result.references.filter((reference) => reference.type === "jump").map((reference) => reference.to));
88
88
  const guessed = guessedIndirectTarget(result.instructions);
89
- const kindOf = (fn: GhidraResult["functions"][number]) => (jumped.has(fn.entry) && !called.has(fn.entry) ? ("label" as const) : ("routine" as const));
89
+ const kindOf = (fn: DecompilerResult["functions"][number]) => (jumped.has(fn.entry) && !called.has(fn.entry) ? ("label" as const) : ("routine" as const));
90
90
  return {
91
- analyzer: "ghidra",
91
+ analyzer: "decompiler",
92
92
  coverage: result.coverage,
93
93
  authoritative: { symbols: result.completeness.functions, regions: result.completeness.regions, references: result.completeness.references },
94
94
  symbols: result.functions.map((fn) => ({ address: fn.entry, name: nameOf(fn), kind: kindOf(fn) })),
@@ -1,10 +1,10 @@
1
- // The structured instruction list: Ghidra's decoded instructions with
1
+ // The structured instruction list: the decompiler's decoded instructions with
2
2
  // the addressing mode, the operand in 6502 syntax, the flow target and,
3
3
  // with a coverage file, whether the instruction ran.
4
4
 
5
5
  import { COVERAGE, formatC64Address } from "#src/c64.ts";
6
6
  import { OPCODES, type Mode as OpcodeMode } from "#src/opcodes.ts";
7
- import type { GhidraInstruction } from "#src/native/types.ts";
7
+ import type { DecompilerInstruction } from "#src/native/types.ts";
8
8
 
9
9
  export type Mode =
10
10
  | "implied"
@@ -88,8 +88,8 @@ export interface ListedInstruction {
88
88
  executed?: boolean;
89
89
  }
90
90
 
91
- /** Ghidra's instructions as the list that --out-instructions writes. */
92
- export function instructionList(instructions: GhidraInstruction[], coverage?: Uint8Array): ListedInstruction[] {
91
+ /** The decompiler's instructions as the list that --out-instructions writes. */
92
+ export function instructionList(instructions: DecompilerInstruction[], coverage?: Uint8Array): ListedInstruction[] {
93
93
  return instructions.map((instruction) => {
94
94
  const bytes = Buffer.from(instruction.bytes, "hex");
95
95
  const mode = modeOf(bytes[0]!);
@@ -1,5 +1,5 @@
1
1
  // The c64-static-analysis script: analyzes the program in the knowledge
2
- // with DXA (fast first pass) or Ghidra (deeper), which it runs itself, seeded
2
+ // with DXA (fast first pass) or the decompiler (deeper), which it runs itself, seeded
3
3
  // from current knowledge and the coverage of the knowledge, and imports the
4
4
  // structural findings into .c64-re-tools/knowledge/.
5
5
 
@@ -9,9 +9,9 @@ import { WireFailure } from "#src/host-client/tools.ts";
9
9
  import { writeReported } from "#src/host-client/transfer.ts";
10
10
  import { knowledgeNames } from "#src/knowledge/names.ts";
11
11
  import { analyze as analyzeWithDxa } from "#src/native/dxa.ts";
12
- import { analyze as analyzeWithGhidra } from "#src/native/ghidra/analyze.ts";
12
+ import { analyze as analyzeWithDecompiler } from "#src/native/decompiler/analyze.ts";
13
13
  import { localToolContext } from "#src/native/local.ts";
14
- import { GHIDRA_LIMITS } from "#src/native/types.ts";
14
+ import { DECOMPILER_LIMITS } from "#src/native/types.ts";
15
15
  import { openForRead, withWrite } from "#src/knowledge/database.ts";
16
16
  import { analyzedBytes, operandImages, programCoverage, requireProgram } from "#src/knowledge/program.ts";
17
17
  import { applyBatch, type BatchOperation } from "#src/knowledge/write.ts";
@@ -21,7 +21,7 @@ import { DEFAULT_SPACE, SEMANTIC_ORIGINS, type Analyzer } from "#src/knowledge/s
21
21
  import { platformNames, platformNamesFor, romUseOfProgram, type RomUse } from "#src/platform.ts";
22
22
  import { listed, OPTIONS, reply, runScript, UsageError, type Call } from "#src/script.ts";
23
23
  import { codeEntries, coverageConflicts, coverageEntries, coverageSeedKinds, executedStarts, imageReader, romOnlyRanges, type ImageByte } from "./lib/coverage.ts";
24
- import { dxaFindings, ghidraFindings, seedsFromKnowledge } from "./lib/findings.ts";
24
+ import { dxaFindings, decompilerFindings, seedsFromKnowledge } from "./lib/findings.ts";
25
25
  import { findIdioms } from "./lib/idioms.ts";
26
26
  import { instructionList } from "./lib/instructions.ts";
27
27
  import { CATALOGUE, findMacroUses, type MacroCandidate } from "./lib/macros.ts";
@@ -36,11 +36,13 @@ const ALL_NAMES = "a larger --max-listed. The project knowledge has all of them
36
36
  * analyzer data over executed code to classify, and macro candidates to write.
37
37
  * The envelope adds the sentence for a cut list.
38
38
  */
39
- function withHint(body: Record<string, unknown>, conflicts: number, coverageConflicts: number, macros: { candidates: number; applied: boolean; revision: string | null | undefined }, version: { now: string | undefined; last: string | undefined; revision: string | null }) {
39
+ function withHint(body: Record<string, unknown>, conflicts: number, coverageConflicts: number, macros: { candidates: number; applied: boolean; revision: string | null | undefined }, version: { now: string | undefined; last: string | undefined; revision: string | null }, retiredReferences: number) {
40
40
  const hints: string[] = [];
41
41
  if (version.revision !== null && version.now !== undefined && version.last !== undefined && version.now !== version.last) {
42
42
  hints.push(`The last analysis of this program used ${version.last}. Thus a change in revision ${version.revision} can come from the new analyzer version, and not from the program or the project knowledge.`);
43
43
  }
44
+ // A leftover is data that no reference reads: a retired reference can make one.
45
+ if (retiredReferences > 0) hints.push("The analysis retired references. A data range that only a retired reference used can be a leftover now. Generate the source again, and examine the leftovers that changed.");
44
46
  if (conflicts > 0) hints.push("The analysis and the project knowledge disagree at each place in conflicts. Find the correct answer in the emulator. Then correct the project knowledge.");
45
47
  if (coverageConflicts > 0) hints.push("The coverage shows executed code in each range of coverageConflicts. Classify each range as code, or as dual-use when its bytes are also data, in the project knowledge.");
46
48
  if (typeof macros.revision === "string") hints.push("The project knowledge has the macro candidates now. Generate the source again.");
@@ -178,15 +180,15 @@ async function analyze(call: Call): Promise<unknown> {
178
180
  const decompile = call.addresses("decompile");
179
181
  if (decompile.length > 32) throw new UsageError("--decompile takes at most 32 routines");
180
182
  const max = call.count("max-listed")!;
181
- const analyzer = call.string("analyzer") as "dxa" | "ghidra";
183
+ const analyzer = call.string("analyzer") as "dxa" | "decompiler";
182
184
  const listingPath = call.string("out-listing");
183
185
  const instructionsPath = call.string("out-instructions");
184
186
  const applyMacros = call.flag("apply-macros");
185
187
  const skip = new Set(call.addresses("skip"));
186
188
  if (skip.size > 0 && !applyMacros) throw new UsageError("--skip works only with --apply-macros: it names a macro candidate that the run does not write");
187
- if (analyzer === "dxa" && decompile.length > 0) throw new UsageError("--decompile works only with --analyzer ghidra");
188
- if (analyzer === "ghidra" && listingPath !== undefined) throw new UsageError("--out-listing works only with --analyzer dxa");
189
- if (analyzer === "dxa" && instructionsPath !== undefined) throw new UsageError("--out-instructions works only with --analyzer ghidra");
189
+ if (analyzer === "dxa" && decompile.length > 0) throw new UsageError("--decompile works only with --analyzer decompiler");
190
+ if (analyzer === "decompiler" && listingPath !== undefined) throw new UsageError("--out-listing works only with --analyzer dxa");
191
+ if (analyzer === "dxa" && instructionsPath !== undefined) throw new UsageError("--out-instructions works only with --analyzer decompiler");
190
192
  const space = call.space;
191
193
  const reader = openForRead();
192
194
  const program = requireProgram(reader, space);
@@ -206,21 +208,21 @@ async function analyze(call: Call): Promise<unknown> {
206
208
  const revision = currentRevision(reader);
207
209
  const seeds = seedsFromKnowledge(reader, entries, space, executed.executed);
208
210
  // Knowledge routines and --entry first, then code regions and JMP tables, then idioms, then coverage, up to the seed bound:
209
- // at most GHIDRA_LIMITS.entryPoints (1024) entry points for both analyzers, and for Ghidra at most
210
- // GHIDRA_LIMITS.codeStarts (8192) coverage flow starts that are code in a routine. coverageSeeds gives what was used.
211
+ // at most DECOMPILER_LIMITS.entryPoints (1024) entry points for both analyzers, and for the decompiler at most
212
+ // DECOMPILER_LIMITS.codeStarts (8192) coverage flow starts that are code in a routine. coverageSeeds gives what was used.
211
213
  const fromCoverage = coverage === undefined ? [] : coverageEntries(coverage, inProgram);
212
214
  const known = [...seeds.entryPoints, ...codeEntries(reader, byteAt, space)];
213
- // Ghidra takes the coverage as code starts without a function; DXA has one list.
215
+ // The decompiler takes the coverage as code starts without a function; DXA has one list.
214
216
  const kinds = analyzer === "dxa" || coverage === undefined ? { routines: fromCoverage, codeStarts: [] } : coverageSeedKinds(coverage, inProgram);
215
217
  const ordered = [...new Set([...known, ...idioms.entryPoints, ...kinds.routines])];
216
- seeds.entryPoints = ordered.slice(0, GHIDRA_LIMITS.entryPoints).sort((a, b) => a - b);
217
- const codeStarts = kinds.codeStarts.filter((entry) => !seeds.entryPoints.includes(entry)).slice(0, GHIDRA_LIMITS.codeStarts);
218
+ seeds.entryPoints = ordered.slice(0, DECOMPILER_LIMITS.entryPoints).sort((a, b) => a - b);
219
+ const codeStarts = kinds.codeStarts.filter((entry) => !seeds.entryPoints.includes(entry)).slice(0, DECOMPILER_LIMITS.codeStarts);
218
220
  // Idiom tables and the RAM under ROM that the runs never used are data for this run too; semantic data ranges come first.
219
221
  // A range with an entry point of the knowledge or --entry in it is left out: that code stays code.
220
222
  const fromRom = coverage === undefined ? [] : romOnlyRanges(coverage, byteAt).filter((range) => !known.some((entry) => entry >= range.start && entry <= range.end));
221
223
  const dataRanges = [...seeds.dataRanges];
222
224
  for (const range of [...idioms.dataRanges, ...fromRom]) if (!dataRanges.some((seed) => range.start <= seed.end && range.end >= seed.start)) dataRanges.push(range);
223
- seeds.dataRanges = dataRanges.slice(0, GHIDRA_LIMITS.dataRanges);
225
+ seeds.dataRanges = dataRanges.slice(0, DECOMPILER_LIMITS.dataRanges);
224
226
  const romUsed = fromRom.filter((range) => seeds.dataRanges.includes(range)).length;
225
227
  const coverageUsed = fromCoverage.filter((entry) => seeds.entryPoints.includes(entry) || codeStarts.includes(entry)).length;
226
228
  // Platform names are C64 names: drive code and banks get none.
@@ -313,13 +315,13 @@ async function analyze(call: Call): Promise<unknown> {
313
315
  labels: listed(result.labels, max, (label) => ({ address: formatC64Address(label.address), name: label.name }), ALL_NAMES),
314
316
  ...(written === undefined ? {} : { listing: written }),
315
317
  };
316
- return withHint(body, imported.conflicts.length + found.idioms.conflicts.length, body.coverageConflicts?.length ?? 0, { candidates: found.idioms.candidates.macros.count, applied: applyMacros, revision: found.idioms.candidates.macros.revision }, { now: result.toolVersion, last: lastVersion, revision: imported.revision });
318
+ return withHint(body, imported.conflicts.length + found.idioms.conflicts.length, body.coverageConflicts?.length ?? 0, { candidates: found.idioms.candidates.macros.count, applied: applyMacros, revision: found.idioms.candidates.macros.revision }, { now: result.toolVersion, last: lastVersion, revision: imported.revision }, imported.changes.references.retired);
317
319
  }
318
320
 
319
- const { result } = await analyzeWithGhidra({ imageKind, ...seeds, codeStarts, decompile }, bytes, localToolContext());
320
- // Executed instruction starts that Ghidra did not decode: the instruction list and the source miss them.
321
+ const { result } = await analyzeWithDecompiler({ imageKind, ...seeds, codeStarts, decompile }, bytes, localToolContext());
322
+ // Executed instruction starts that the decompiler did not decode: the instruction list and the source miss them.
321
323
  const decoded = new Set(result.instructions.map((instruction) => instruction.address));
322
- const imported = record({ ...ghidraFindings(result), space, ...executed }, revision, "Ghidra analysis of the program", runProvenance(bytes, result.toolVersion));
324
+ const imported = record({ ...decompilerFindings(result), space, ...executed }, revision, "Decompiler analysis of the program", runProvenance(bytes, result.toolVersion));
323
325
  const found = idiomsResult();
324
326
  // A start inside a dual-use region is a known overlap, for example the second instruction of a BIT skip: one list cannot hold both.
325
327
  // Read after the idioms, which write those regions.
@@ -333,7 +335,7 @@ async function analyze(call: Call): Promise<unknown> {
333
335
  instructions = { count: list.length, ...writeReported(instructionsPath, `${JSON.stringify(list, null, 1)}\n`, { what: "--out-instructions" }) };
334
336
  }
335
337
  const body = {
336
- analyzer: "ghidra",
338
+ analyzer: "decompiler",
337
339
  ...(result.toolVersion === undefined ? {} : { analyzerVersion: result.toolVersion }),
338
340
  ...(space === DEFAULT_SPACE ? {} : { space }),
339
341
  ...(instructions === undefined ? {} : { instructions }),
@@ -348,29 +350,29 @@ async function analyze(call: Call): Promise<unknown> {
348
350
  ? {}
349
351
  : { notDecompiled: result.notDecompiled!.map((item) => ({ entry: formatC64Address(item.entry), reason: item.reason })) }),
350
352
  };
351
- return withHint(body, imported.conflicts.length + found.idioms.conflicts.length, body.coverageConflicts?.length ?? 0, { candidates: found.idioms.candidates.macros.count, applied: applyMacros, revision: found.idioms.candidates.macros.revision }, { now: result.toolVersion, last: lastVersion, revision: imported.revision });
353
+ return withHint(body, imported.conflicts.length + found.idioms.conflicts.length, body.coverageConflicts?.length ?? 0, { candidates: found.idioms.candidates.macros.count, applied: applyMacros, revision: found.idioms.candidates.macros.revision }, { now: result.toolVersion, last: lastVersion, revision: imported.revision }, imported.changes.references.retired);
352
354
  }
353
355
 
354
356
  await runScript({
355
357
  name: "static-analysis",
356
- summary: "Analyzes the program in the knowledge with DXA or Ghidra, seeded from the knowledge and its coverage, and imports the structural findings into the knowledge.",
358
+ summary: "Analyzes the program in the knowledge with DXA or the decompiler, seeded from the knowledge and its coverage, and imports the structural findings into the knowledge.",
357
359
  names: knowledgeNames,
358
360
  commands: [
359
361
  {
360
362
  name: "analyze",
361
363
  summary: "Runs the analyzer over the program in the knowledge and imports what it finds as one revision, then the 6502 idioms as a second one.",
362
364
  options: {
363
- analyzer: { kind: "choice", value: "<dxa|ghidra>", choices: ["dxa", "ghidra"], default: "ghidra", help: "dxa (a fast first pass) or ghidra (deeper, the default)" },
365
+ analyzer: { kind: "choice", value: "<dxa|decompiler>", choices: ["dxa", "decompiler"], default: "decompiler", help: "dxa (a fast first pass) or decompiler (deeper, the default)" },
364
366
  entry: { ...OPTIONS.entry, multiple: true, help: "an entry point of the program" },
365
- decompile: { kind: "address", value: "<address>", multiple: true, help: "ghidra: a routine to decompile, at most 32" },
367
+ decompile: { kind: "address", value: "<address>", multiple: true, help: "decompiler: a routine to decompile, at most 32" },
366
368
  space: OPTIONS.space,
367
369
  "max-listed": { ...OPTIONS["max-listed"], help: "list at most n labels, functions or candidates (default 50, 0 for none). The counts are always given, and the knowledge has all labels and functions" },
368
370
  "out-listing": { kind: "path", output: "file", value: "<file>", help: "dxa: write the disassembly listing to this project file" },
369
- "out-instructions": { kind: "path", output: "file", value: "<file>", help: "ghidra: write every instruction (address, bytes, mnemonic, mode, operand, target, executed) to this project file as JSON" },
371
+ "out-instructions": { kind: "path", output: "file", value: "<file>", help: "decompiler: write every instruction (address, bytes, mnemonic, mode, operand, target, executed) to this project file as JSON" },
370
372
  "apply-macros": { kind: "flag", help: "write the macro candidates (the macros and their uses) to the project knowledge as one revision of the LLM" },
371
373
  skip: { kind: "address", value: "<address>", multiple: true, help: "with --apply-macros: the start of a macro candidate that is not correct. The run does not write it" },
372
374
  },
373
- notes: "The program and the coverage come from the project knowledge: put them into the project knowledge first. The executed code of the coverage gives entry points. Routine symbols in the knowledge are entry points too. Ghidra needs at least one entry point. DXA finds the SYS of a BASIC start by itself.",
375
+ notes: "The program and the coverage come from the project knowledge: put them into the project knowledge first. The executed code of the coverage gives entry points. Routine symbols in the knowledge are entry points too. The decompiler needs at least one entry point. DXA finds the SYS of a BASIC start by itself.",
374
376
  run: analyze,
375
377
  },
376
378
  ],
@@ -105,13 +105,15 @@ async function recordCommand(call: Call): Promise<Reply> {
105
105
  writeReported(`${out}/${RECORDING_FILES.reads}`, outcome.reads, { what: "--out" }),
106
106
  writeReported(`${out}/${RECORDING_FILES.coverage}`, outcome.coverage, { what: "--out" }),
107
107
  ];
108
- // A recording in the local folder is a work file: git ignores it, so it is no test.
109
- const keep = projectRelative(out).startsWith(`${PROJECT_DIRECTORY}/${LOCAL_DIRECTORY}/`)
108
+ // A recording in the local folder is a work file: git ignores it, so it is no test. A record file there is not kept either.
109
+ const local = (path: string) => projectRelative(path).startsWith(`${PROJECT_DIRECTORY}/${LOCAL_DIRECTORY}/`);
110
+ const keep = local(out)
110
111
  ? `Git ignores ${out}. To keep the recording as a test and to add its coverage to the project knowledge, record again with --out tests/recordings/<name>.`
111
112
  : `Commit ${out} with the scenarios. Add ${out}/${RECORDING_FILES.coverage} to the project knowledge as coverage.`;
113
+ const recordFile = local(call.subject(0)) ? ` Git also ignores the record file ${call.subject(0)}. To record again later, keep a copy in a folder that git keeps, for example tests/record/.` : "";
112
114
  return reply(
113
115
  { result: "PASS", recorded: true, out, ...summary, files },
114
- { hint: `${keep} ${summary.coverageFrom === null ? "The coverage did not start: the map is empty." : "The map has no marks for the code that ran before coverageFrom."} To make sure that the recording replays, run nextAction.`, nextAction: call.next("replay", out) },
116
+ { hint: `${keep}${recordFile} ${summary.coverageFrom === null ? "The coverage did not start: the map is empty." : "The map has no marks for the code that ran before coverageFrom."} To make sure that the recording replays, run nextAction.`, nextAction: call.next("replay", out) },
115
117
  );
116
118
  } finally {
117
119
  await core.close();
package/src/build-name.ts CHANGED
@@ -2,7 +2,9 @@
2
2
  // A release build is release_<label>. A build of config.asm is clean when each
3
3
  // switch has its default, else custom_ with each switch that differs: its
4
4
  // name when it is on, no_<name> when it is off. A build of an entry other
5
- // than main.asm adds the entry, for example clean_loader. A source without
5
+ // than main.asm adds the entry, for example clean_loader. The loader of the
6
+ // packed form alone is only its copier, so its build is clean_copier: the loader
7
+ // program, which generate packs, keeps clean_loader. A source without
6
8
  // config.asm and without a release keeps the name of its entry. The symbols
7
9
  // of a build go into symbols/ next to the program, so the program folder
8
10
  // holds only programs.
@@ -31,9 +33,12 @@ export function configValues(text: string): Map<string, 0 | 1> {
31
33
  /** What a build is made of: a release, or the values of config.asm with the default of each switch (0 when the defaults do not have it). */
32
34
  export type BuildKind = { release: string } | { values: ReadonlyMap<string, number>; defaults: ReadonlyMap<string, number> };
33
35
 
34
- /** The name of a build of `entry`, without an extension. */
35
- export function buildName(entry: string, kind: BuildKind | undefined): string {
36
- const base = basename(entry, extname(entry));
36
+ /** The line of a generated loader.asm of the packed form. Its build alone is only the copier, not the loader program. */
37
+ export const COPIER_LINE = "; A build of this file alone is only the copier: its build name has copier in place of loader.";
38
+
39
+ /** The name of a build of `entry`, without an extension. `source` is the text of the entry: COPIER_LINE in it gives the name copier. */
40
+ export function buildName(entry: string, kind: BuildKind | undefined, source?: string): string {
41
+ const base = source?.split(/\r?\n/).includes(COPIER_LINE) ? "copier" : basename(entry, extname(entry));
37
42
  if (kind === undefined) return base;
38
43
  let type: string;
39
44
  if ("release" in kind) type = `release_${kind.release}`;
package/src/c64.ts CHANGED
@@ -511,7 +511,7 @@ const BRANCHES = new Set([0x10, 0x30, 0x50, 0x70, 0x90, 0xb0, 0xd0, 0xf0]);
511
511
  const NO_FALL = new Set([0x00, 0x40, 0x4c, 0x60, 0x6c]);
512
512
 
513
513
  /**
514
- * The coverage flow starts split for Ghidra. A start is a code start, a
514
+ * The coverage flow starts split for the decompiler. A start is a code start, a
515
515
  * place in a routine, when it follows an executed JSR, or when an executed
516
516
  * branch or JMP from outside its own flow reaches it (the loop of a routine
517
517
  * that jumps back to its own start does not count). Any other start, for
@@ -1,6 +1,6 @@
1
1
  // The typed tool dispatcher of the Host Runtime. The host runs only
2
2
  // VICE and the tools that come with it (c1541, petcat); skill scripts run
3
- // ACME, DXA and Ghidra themselves. One entry per operation, never a
3
+ // ACME, DXA and the decompiler themselves. One entry per operation, never a
4
4
  // generic executable route.
5
5
 
6
6
  import type { ProcessSupervisor } from "../../native/processes.ts";
@@ -1,7 +1,7 @@
1
1
  // Short-lived typed requests to the Host Runtime for skill scripts:
2
2
  // VICE's own tools (c1541, petcat) and the host tool status. Each request
3
3
  // opens its own "tool" connection, sends bytes, and closes. Skill scripts run
4
- // ACME, DXA and Ghidra themselves through src/native (Ghidra in process).
4
+ // ACME, DXA and the decompiler themselves through src/native (the decompiler in process).
5
5
 
6
6
  import { ProtocolError, WireFailure } from "../protocol/messages.ts";
7
7
  import { DISK_IMAGE_TYPES, validateToolResult, type C1541Result, type DiskAction, type DiskImageType, type DiskSector, type PetcatResult, type ToolOperation, type ToolOperations } from "../protocol/tools.ts";
@@ -268,10 +268,10 @@ function importNames(db: DatabaseSync, change: Change, findings: NormalizedFindi
268
268
  }
269
269
  }
270
270
 
271
- /** Analyzers whose regions a heuristic finding replaces where it lies: user/LLM > heuristic > DXA/Ghidra. */
272
- const YIELDS_TO_HEURISTIC = new Set<Origin>(["dxa", "ghidra"]);
271
+ /** Analyzers whose regions a heuristic finding replaces where it lies: user/LLM > heuristic > DXA/decompiler. */
272
+ const YIELDS_TO_HEURISTIC = new Set<Origin>(["dxa", "decompiler"]);
273
273
  /** Analyzers whose data gives way to a code finding over an executed instruction start. */
274
- const YIELDS_TO_EXECUTED_CODE = new Set<Origin>(["dxa", "ghidra"]);
274
+ const YIELDS_TO_EXECUTED_CODE = new Set<Origin>(["dxa", "decompiler"]);
275
275
 
276
276
  /** The first address in the range that is an executed instruction start, or undefined. */
277
277
  function firstExecuted(findings: NormalizedFindings, start: number, end: number): number | undefined {
@@ -286,7 +286,7 @@ function holdsExecuted(findings: NormalizedFindings, start: number, end: number)
286
286
  }
287
287
 
288
288
  /**
289
- * The data findings of DXA or Ghidra that code evidence contradicts: an
289
+ * The data findings of DXA or the decompiler that code evidence contradicts: an
290
290
  * executed instruction start, or a code name (label or routine) of the user or
291
291
  * the LLM, in the range. Evidence wins over an analyzer guess: such a finding
292
292
  * is not imported, and the analyzer's own code there stays.
@@ -321,7 +321,7 @@ function importRegions(db: DatabaseSync, change: Change, given: NormalizedFindin
321
321
  result.conflicts.push(...contradicted);
322
322
  const findings = { ...given, regions: given.regions.filter((region) => !contradicted.some((item) => item.start === region.start && item.end === region.end)) };
323
323
  if (analyzer === "heuristic") {
324
- // An idiom is specific evidence about its bytes: the DXA or Ghidra region there gives way, its parts outside stay.
324
+ // An idiom is specific evidence about its bytes: the DXA or decompiler region there gives way, its parts outside stay.
325
325
  for (const region of findings.regions) {
326
326
  for (const row of regionsOverlapping(db, region.start, region.end, space).filter((candidate) => YIELDS_TO_HEURISTIC.has(candidate.origin))) {
327
327
  change.close("regions", "space = ? AND start_address = ? AND end_address = ? AND origin = ?", space, row.start, row.end, row.origin);
@@ -250,7 +250,7 @@ export function entryMemory(image: ProgramImage): Uint8Array {
250
250
 
251
251
  /**
252
252
  * The bytes for an analyzer: a PRG for one segment without an entry state,
253
- * else the 64 KiB with the entry-state pages (entryMemory). DXA, Ghidra and
253
+ * else the 64 KiB with the entry-state pages (entryMemory). DXA, the decompiler and
254
254
  * c64-source get the same bytes.
255
255
  */
256
256
  export function analyzedBytes(image: ProgramImage): { bytes: Buffer; kind: "prg" | "flat64k" } {
@@ -451,7 +451,7 @@ export function symbolNamed(db: DatabaseSync | undefined, name: string, space: S
451
451
  return row === undefined ? undefined : toSymbol(row);
452
452
  }
453
453
 
454
- /** The analyzer names at an address: one for each analyzer, in the order heuristic, Ghidra, DXA. */
454
+ /** The analyzer names at an address: one for each analyzer, in the order heuristic, decompiler, DXA. */
455
455
  export function analyzerNamesAt(db: DatabaseSync | undefined, address: number, space: Space = DEFAULT_SPACE): SymbolRow[] {
456
456
  if (db === undefined) return [];
457
457
  return (db.prepare(`SELECT ${SYMBOL_COLUMNS} FROM current_analyzer_names WHERE space = ? AND address = ?`).all(space, address) as Raw[]).map(toSymbol).sort(byAnalyzer);
@@ -464,10 +464,10 @@ export function analyzerNamed(db: DatabaseSync | undefined, name: string, space:
464
464
  }
465
465
 
466
466
  /** The analyzers in the order that their names are used when no other name exists. */
467
- export const ANALYZER_NAME_ORDER: readonly Origin[] = ["heuristic", "ghidra", "dxa"];
467
+ export const ANALYZER_NAME_ORDER: readonly Origin[] = ["heuristic", "decompiler", "dxa"];
468
468
  const byAnalyzer = (a: SymbolRow, b: SymbolRow) => a.address - b.address || ANALYZER_NAME_ORDER.indexOf(a.origin) - ANALYZER_NAME_ORDER.indexOf(b.origin);
469
469
 
470
- /** Current analyzer names in a range, in address order and then heuristic, Ghidra, DXA. */
470
+ /** Current analyzer names in a range, in address order and then heuristic, decompiler, DXA. */
471
471
  export function listAnalyzerNames(db: DatabaseSync | undefined, range: AddressRange = ALL, kind?: SymbolKind, origins?: OriginFilter, space: Space = DEFAULT_SPACE): SymbolRow[] {
472
472
  if (db === undefined) return [];
473
473
  return (db.prepare(`SELECT ${SYMBOL_COLUMNS} FROM current_analyzer_names WHERE space = ? AND address BETWEEN ? AND ?`).all(space, range.start, range.end) as Raw[])
@@ -8,12 +8,12 @@ import { REFERENCE_KINDS, type ReferenceKind } from "../c64.ts";
8
8
  import { OPERAND_SELECTS } from "./expression.ts";
9
9
 
10
10
  /** heuristic: 6502 idioms that the static analysis finds by pattern; an analyzer origin. */
11
- export const ORIGINS = ["user", "llm", "dxa", "ghidra", "heuristic"] as const;
11
+ export const ORIGINS = ["user", "llm", "dxa", "decompiler", "heuristic"] as const;
12
12
  export type Origin = (typeof ORIGINS)[number];
13
13
  /** The origins of semantic knowledge: what the user or the LLM decided. It wins over analyzer facts. */
14
14
  export const SEMANTIC_ORIGINS = ["user", "llm"] as const satisfies readonly Origin[];
15
15
  /** The analyzers: their facts and names give way to semantic knowledge. */
16
- export const ANALYZERS = ["dxa", "ghidra", "heuristic"] as const satisfies readonly Origin[];
16
+ export const ANALYZERS = ["dxa", "decompiler", "heuristic"] as const satisfies readonly Origin[];
17
17
  export type Analyzer = (typeof ANALYZERS)[number];
18
18
  export const isSemantic = (origin: string | undefined): boolean => (SEMANTIC_ORIGINS as readonly (string | undefined)[]).includes(origin);
19
19
  export const isAnalyzer = (origin: string | undefined): boolean => (ANALYZERS as readonly (string | undefined)[]).includes(origin);
@@ -176,7 +176,7 @@ function createSchema(db: DatabaseSync): void {
176
176
  address INTEGER NOT NULL CHECK (address BETWEEN 0 AND 65535),
177
177
  name TEXT NOT NULL CHECK (length(name) > 0),
178
178
  kind TEXT NOT NULL CHECK (kind IN (${list(SYMBOL_KINDS)})),
179
- origin TEXT NOT NULL CHECK (origin IN ('dxa', 'ghidra', 'heuristic')),
179
+ origin TEXT NOT NULL CHECK (origin IN ('dxa', 'decompiler', 'heuristic')),
180
180
  valid_from_revision TEXT NOT NULL REFERENCES revisions (id),
181
181
  valid_to_revision TEXT REFERENCES revisions (id)
182
182
  );
@@ -12,7 +12,7 @@ import type { SupervisedProcess } from "./processes.ts";
12
12
  import type { ToolContext } from "./run.ts";
13
13
 
14
14
  /** The command protocol that this module speaks; c64run --version and version name it. */
15
- export const C64RUN_PROTOCOL = 4;
15
+ export const C64RUN_PROTOCOL = 5;
16
16
 
17
17
  /** CPU cycles in one PAL frame: 312 lines of 63 cycles. */
18
18
  export const PAL_FRAME_CYCLES = 19_656;
@@ -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;