@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
  // 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,18 +9,19 @@ 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
- import { analyzedBytes, programCoverage, requireProgram } from "#src/knowledge/program.ts";
17
- import { importFindings, runProvenance, type ImportConflict, type ImportContext, type ImportResult, type NormalizedFindings } from "#src/knowledge/import.ts";
16
+ import { analyzedBytes, operandImages, programCoverage, requireProgram } from "#src/knowledge/program.ts";
17
+ import { applyBatch, type BatchOperation } from "#src/knowledge/write.ts";
18
+ import { importFindings, lastToolVersion, runProvenance, type ImportConflict, type ImportContext, type ImportResult, type NormalizedFindings } from "#src/knowledge/import.ts";
18
19
  import { currentRevision, listMacros, listMacroUses, listPatches, listReferences, listRegions, listSymbols } from "#src/knowledge/read.ts";
19
20
  import { DEFAULT_SPACE, SEMANTIC_ORIGINS, type Analyzer } from "#src/knowledge/schema.ts";
20
21
  import { platformNames, platformNamesFor, romUseOfProgram, type RomUse } from "#src/platform.ts";
21
22
  import { listed, OPTIONS, reply, runScript, UsageError, type Call } from "#src/script.ts";
22
23
  import { codeEntries, coverageConflicts, coverageEntries, coverageSeedKinds, executedStarts, imageReader, romOnlyRanges, type ImageByte } from "./lib/coverage.ts";
23
- import { dxaFindings, ghidraFindings, seedsFromKnowledge } from "./lib/findings.ts";
24
+ import { dxaFindings, decompilerFindings, seedsFromKnowledge } from "./lib/findings.ts";
24
25
  import { findIdioms } from "./lib/idioms.ts";
25
26
  import { instructionList } from "./lib/instructions.ts";
26
27
  import { CATALOGUE, findMacroUses, type MacroCandidate } from "./lib/macros.ts";
@@ -32,14 +33,20 @@ const ALL_NAMES = "a larger --max-listed. The project knowledge has all of them
32
33
 
33
34
  /**
34
35
  * The result with a hint for what the agent does next: conflicts to examine,
35
- * analyzer data over executed code to classify, and a macro batch to apply.
36
+ * analyzer data over executed code to classify, and macro candidates to write.
36
37
  * The envelope adds the sentence for a cut list.
37
38
  */
38
- function withHint(body: Record<string, unknown>, conflicts: number, coverageConflicts: number, batch: { out: string; writes: number } | undefined) {
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) {
39
40
  const hints: string[] = [];
41
+ if (version.revision !== null && version.now !== undefined && version.last !== undefined && version.now !== version.last) {
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
+ }
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.");
40
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.");
41
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.");
42
- if (batch !== undefined && batch.writes > 0) hints.push(`Apply the changes in ${batch.out} to the project knowledge. Then generate the source again.`);
48
+ if (typeof macros.revision === "string") hints.push("The project knowledge has the macro candidates now. Generate the source again.");
49
+ else if (!macros.applied && macros.candidates > 0) hints.push("Examine idioms.candidates.macros. To write them to the project knowledge, run the analysis again with --apply-macros.");
43
50
  if (hints.length === 0) return body;
44
51
  return reply(body, { hint: hints.join(" ") });
45
52
  }
@@ -73,11 +80,11 @@ function showMacro(candidate: MacroCandidate) {
73
80
  * the ROMs that the program uses, as c64-source names them. A candidate is left out when
74
81
  * a name or a reference target is inside it, or a patch or a use overlaps it:
75
82
  * c64-source would write its instructions. The same use in the knowledge is
76
- * known. With `batchPath`, the candidates go to an apply batch with the
77
- * macros they need; a macro of the catalogue that the knowledge has with
78
- * another body leaves its candidates out of the batch.
83
+ * known. The writes are the candidates with the macros they need, without the
84
+ * candidates that start at an address of `skip`. A macro of the catalogue that
85
+ * the knowledge has with another body leaves its candidates out of the writes.
79
86
  */
80
- function macroCandidates(space: string, byteAt: ImageByte, batchPath: string | undefined, romUse: RomUse) {
87
+ function macroCandidates(space: string, byteAt: ImageByte, romUse: RomUse, skip: ReadonlySet<number>) {
81
88
  const db = openForRead();
82
89
  try {
83
90
  // The platform names that c64-source uses: a name of a ROM that the program does not use is no arg.
@@ -98,45 +105,27 @@ function macroCandidates(space: string, byteAt: ImageByte, batchPath: string | u
98
105
  else if ([...named].some((address) => address > candidate.start && address <= candidate.end) || patches.some((patch) => overlaps(patch, candidate)) || uses.some((use) => overlaps(use, candidate))) leftOut++;
99
106
  else candidates.push(candidate);
100
107
  }
101
- if (batchPath === undefined) return { candidates, known, leftOut };
102
- // A macro of the catalogue goes into the batch unless the knowledge has it; with another body, its uses stay out.
108
+ // A macro of the catalogue goes into the writes unless the knowledge has it; with another body, its uses stay out.
103
109
  const macros = new Map(listMacros(db, undefined, space).map((macro) => [macro.name, macro]));
104
- const batch: Array<Record<string, unknown>> = [];
105
- const batched: MacroCandidate[] = [];
110
+ const writes: BatchOperation[] = [];
106
111
  const other = new Set<string>();
107
- for (const idiom of CATALOGUE.filter((item) => candidates.some((candidate) => candidate.macro === item.name))) {
112
+ const chosen = candidates.filter((candidate) => !skip.has(candidate.start));
113
+ for (const idiom of CATALOGUE.filter((item) => chosen.some((candidate) => candidate.macro === item.name))) {
108
114
  const existing = macros.get(idiom.name);
109
- if (existing === undefined) batch.push({ op: "macro", name: idiom.name, params: idiom.params, body: idiom.body, comment: idiom.comment, ...(space === DEFAULT_SPACE ? {} : { space }) });
115
+ if (existing === undefined) writes.push({ op: "macro", space, name: idiom.name, params: [...idiom.params], body: idiom.body, comment: idiom.comment });
110
116
  else if (existing.params.join(",") !== idiom.params.join(",") || existing.body !== idiom.body) other.add(idiom.name);
111
117
  }
112
- for (const candidate of candidates) {
118
+ for (const candidate of chosen) {
113
119
  if (other.has(candidate.macro)) continue;
114
- batched.push(candidate);
115
- batch.push({ op: "use", start: formatC64Address(candidate.start), end: formatC64Address(candidate.end), macro: candidate.macro, args: candidate.args, ...(space === DEFAULT_SPACE ? {} : { space }) });
120
+ writes.push({ op: "use", space, start: candidate.start, end: candidate.end, macro: candidate.macro, args: candidate.args });
116
121
  }
117
- const written = batch.length > 0 ? writeReported(batchPath, `${JSON.stringify(batch, null, 1)}\n`, { what: "--out-macro-batch" }) : { out: batchPath };
118
- return {
119
- candidates,
120
- known,
121
- leftOut,
122
- batch: {
123
- ...written,
124
- writes: batch.length,
125
- ...(other.size === 0 ? {} : { otherMacros: [...other].map((name) => `The knowledge has another macro ${name}: its candidates are not in the batch.`) }),
126
- },
127
- };
122
+ const notCandidates = [...skip].filter((address) => !candidates.some((candidate) => candidate.start === address)).sort((a, b) => a - b);
123
+ return { candidates, known, leftOut, writes, skipped: candidates.length - chosen.length, notCandidates, otherMacros: [...other].map((name) => `The knowledge has another macro ${name}: its candidates are not written.`) };
128
124
  } finally {
129
125
  db?.close();
130
126
  }
131
127
  }
132
128
 
133
- /** A decompiler that did not start gets the remedy: Ghidra ships no native decompiler for macOS. */
134
- function withRemedy(reason: string): string {
135
- return reason.startsWith("the Ghidra decompiler did not start")
136
- ? `${reason} On macOS, build the native decompiler once: in <Ghidra>/support/gradle run ./gradlew buildNatives.`
137
- : reason;
138
- }
139
-
140
129
  /** One conflict: what the knowledge has, and what the analyzer found, under the analyzer's name. */
141
130
  function showConflict(conflict: ImportConflict, analyzer: Analyzer): Record<string, unknown> {
142
131
  if (conflict.category === "code-evidence") {
@@ -191,13 +180,15 @@ async function analyze(call: Call): Promise<unknown> {
191
180
  const decompile = call.addresses("decompile");
192
181
  if (decompile.length > 32) throw new UsageError("--decompile takes at most 32 routines");
193
182
  const max = call.count("max-listed")!;
194
- const analyzer = call.string("analyzer") as "dxa" | "ghidra";
183
+ const analyzer = call.string("analyzer") as "dxa" | "decompiler";
195
184
  const listingPath = call.string("out-listing");
196
185
  const instructionsPath = call.string("out-instructions");
197
- const batchPath = call.string("out-macro-batch");
198
- if (analyzer === "dxa" && decompile.length > 0) throw new UsageError("--decompile works only with --analyzer ghidra");
199
- if (analyzer === "ghidra" && listingPath !== undefined) throw new UsageError("--out-listing works only with --analyzer dxa");
200
- if (analyzer === "dxa" && instructionsPath !== undefined) throw new UsageError("--out-instructions works only with --analyzer ghidra");
186
+ const applyMacros = call.flag("apply-macros");
187
+ const skip = new Set(call.addresses("skip"));
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");
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");
201
192
  const space = call.space;
202
193
  const reader = openForRead();
203
194
  const program = requireProgram(reader, space);
@@ -217,31 +208,36 @@ async function analyze(call: Call): Promise<unknown> {
217
208
  const revision = currentRevision(reader);
218
209
  const seeds = seedsFromKnowledge(reader, entries, space, executed.executed);
219
210
  // Knowledge routines and --entry first, then code regions and JMP tables, then idioms, then coverage, up to the seed bound:
220
- // at most GHIDRA_LIMITS.entryPoints (1024) entry points for both analyzers, and for Ghidra at most
221
- // 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.
222
213
  const fromCoverage = coverage === undefined ? [] : coverageEntries(coverage, inProgram);
223
214
  const known = [...seeds.entryPoints, ...codeEntries(reader, byteAt, space)];
224
- // 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.
225
216
  const kinds = analyzer === "dxa" || coverage === undefined ? { routines: fromCoverage, codeStarts: [] } : coverageSeedKinds(coverage, inProgram);
226
217
  const ordered = [...new Set([...known, ...idioms.entryPoints, ...kinds.routines])];
227
- seeds.entryPoints = ordered.slice(0, GHIDRA_LIMITS.entryPoints).sort((a, b) => a - b);
228
- 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);
229
220
  // Idiom tables and the RAM under ROM that the runs never used are data for this run too; semantic data ranges come first.
230
221
  // A range with an entry point of the knowledge or --entry in it is left out: that code stays code.
231
222
  const fromRom = coverage === undefined ? [] : romOnlyRanges(coverage, byteAt).filter((range) => !known.some((entry) => entry >= range.start && entry <= range.end));
232
223
  const dataRanges = [...seeds.dataRanges];
233
224
  for (const range of [...idioms.dataRanges, ...fromRom]) if (!dataRanges.some((seed) => range.start <= seed.end && range.end >= seed.start)) dataRanges.push(range);
234
- seeds.dataRanges = dataRanges.slice(0, GHIDRA_LIMITS.dataRanges);
225
+ seeds.dataRanges = dataRanges.slice(0, DECOMPILER_LIMITS.dataRanges);
235
226
  const romUsed = fromRom.filter((range) => seeds.dataRanges.includes(range)).length;
236
227
  const coverageUsed = fromCoverage.filter((entry) => seeds.entryPoints.includes(entry) || codeStarts.includes(entry)).length;
237
228
  // Platform names are C64 names: drive code and banks get none.
238
229
  const platform = space === DEFAULT_SPACE ? platformNames() : [];
230
+ /** The analyzer version of the last analysis of these bytes: a new version can change the findings by itself. */
231
+ const lastVersion = reader === undefined ? undefined : lastToolVersion(reader, analyzer, bytes);
239
232
  reader?.close();
240
233
  /** Imports the idioms as their own revision, after the analyzer's, and gives their part of the result. */
241
234
  const idiomsResult = () => {
242
235
  const imported = withWrite((db) => importFindings(db, { ...idioms.findings, space }, { description: "Idioms in the program" }));
243
236
  // The macro candidates read the code regions after both imports.
244
- const macros = macroCandidates(space, byteAt, batchPath, romUseOfProgram(coverage, program.state));
237
+ const macros = macroCandidates(space, byteAt, romUseOfProgram(coverage, program.state), skip);
238
+ // With --apply-macros, the candidates and their macros are a third revision of the LLM.
239
+ const platformNamed = new Map(platformNames().map((entry) => [entry.name, entry.address]));
240
+ const written = applyMacros && macros.writes.length > 0 ? withWrite((db) => applyBatch(db, { origin: "llm", description: "Macro candidates in the program", image: operandImages(db, platformNamed) }, macros.writes)) : undefined;
245
241
  // Platform pitfalls are C64 facts: drive code and banks get none. Pitfalls and pointers read the code regions after both imports.
246
242
  const codeDb = openForRead();
247
243
  const code = listRegions(codeDb, undefined, "code", undefined, space);
@@ -264,10 +260,13 @@ async function analyze(call: Call): Promise<unknown> {
264
260
  pointers: listed(pointers, max, showPointer, "a larger --max-listed"),
265
261
  pitfalls: listed(pitfalls, max, showPitfall, "a larger --max-listed"),
266
262
  macros: {
267
- ...listed(macros.candidates, max, showMacro, "a larger --max-listed, or --out-macro-batch <file>"),
263
+ ...listed(macros.candidates, max, showMacro, "a larger --max-listed"),
268
264
  ...(macros.known === 0 ? {} : { known: macros.known }),
269
265
  ...(macros.leftOut === 0 ? {} : { leftOut: macros.leftOut }),
270
- ...(macros.batch === undefined ? {} : { batch: macros.batch }),
266
+ ...(written === undefined ? {} : { revision: written.revision, writes: macros.writes.length }),
267
+ ...(macros.skipped === 0 ? {} : { skipped: macros.skipped }),
268
+ ...(macros.notCandidates.length === 0 ? {} : { notCandidates: macros.notCandidates.map(formatC64Address) }),
269
+ ...(macros.otherMacros.length === 0 ? {} : { otherMacros: macros.otherMacros }),
271
270
  },
272
271
  },
273
272
  },
@@ -306,6 +305,7 @@ async function analyze(call: Call): Promise<unknown> {
306
305
  const found = idiomsResult();
307
306
  const body = {
308
307
  analyzer: "dxa",
308
+ ...(result.toolVersion === undefined ? {} : { analyzerVersion: result.toolVersion }),
309
309
  ...(space === DEFAULT_SPACE ? {} : { space }),
310
310
  ...found,
311
311
  ...coverageResult(),
@@ -315,13 +315,13 @@ async function analyze(call: Call): Promise<unknown> {
315
315
  labels: listed(result.labels, max, (label) => ({ address: formatC64Address(label.address), name: label.name }), ALL_NAMES),
316
316
  ...(written === undefined ? {} : { listing: written }),
317
317
  };
318
- return withHint(body, imported.conflicts.length + found.idioms.conflicts.length, body.coverageConflicts?.length ?? 0, found.idioms.candidates.macros.batch);
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);
319
319
  }
320
320
 
321
- const { result } = await analyzeWithGhidra({ imageKind, ...seeds, codeStarts, decompile }, bytes, localToolContext());
322
- // 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.
323
323
  const decoded = new Set(result.instructions.map((instruction) => instruction.address));
324
- 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));
325
325
  const found = idiomsResult();
326
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.
327
327
  // Read after the idioms, which write those regions.
@@ -335,7 +335,8 @@ async function analyze(call: Call): Promise<unknown> {
335
335
  instructions = { count: list.length, ...writeReported(instructionsPath, `${JSON.stringify(list, null, 1)}\n`, { what: "--out-instructions" }) };
336
336
  }
337
337
  const body = {
338
- analyzer: "ghidra",
338
+ analyzer: "decompiler",
339
+ ...(result.toolVersion === undefined ? {} : { analyzerVersion: result.toolVersion }),
339
340
  ...(space === DEFAULT_SPACE ? {} : { space }),
340
341
  ...(instructions === undefined ? {} : { instructions }),
341
342
  ...found,
@@ -347,30 +348,31 @@ async function analyze(call: Call): Promise<unknown> {
347
348
  decompilations: result.decompilations.map((item) => ({ entry: formatC64Address(item.entry), text: item.text, ...(item.truncated ? { truncated: true } : {}) })),
348
349
  ...((result.notDecompiled ?? []).length === 0
349
350
  ? {}
350
- : { notDecompiled: result.notDecompiled!.map((item) => ({ entry: formatC64Address(item.entry), reason: withRemedy(item.reason) })) }),
351
+ : { notDecompiled: result.notDecompiled!.map((item) => ({ entry: formatC64Address(item.entry), reason: item.reason })) }),
351
352
  };
352
- return withHint(body, imported.conflicts.length + found.idioms.conflicts.length, body.coverageConflicts?.length ?? 0, found.idioms.candidates.macros.batch);
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);
353
354
  }
354
355
 
355
356
  await runScript({
356
357
  name: "static-analysis",
357
- 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.",
358
359
  names: knowledgeNames,
359
360
  commands: [
360
361
  {
361
362
  name: "analyze",
362
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.",
363
364
  options: {
364
- 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)" },
365
366
  entry: { ...OPTIONS.entry, multiple: true, help: "an entry point of the program" },
366
- 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" },
367
368
  space: OPTIONS.space,
368
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" },
369
370
  "out-listing": { kind: "path", output: "file", value: "<file>", help: "dxa: write the disassembly listing to this project file" },
370
- "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-macro-batch": { kind: "path", output: "file", value: "<file>", help: "write the macro candidates (the macros and their uses) to this project file as a batch of changes to the project knowledge" },
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" },
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" },
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
  ],
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: c64-testing
3
- description: Tests if a rebuilt or changed C64 program behaves as the original, or if a program has the expected values. It runs a scenario on the original and on the rebuild in an emulator. It compares memory, registers, chip state and the screen with explicit rules, and gives PASS, FAIL or INCONCLUSIVE. Use it when you must show that a rebuild or a correction keeps the behavior of the original. Use it to do many steps on one program and keep the screens, coverage maps, traces and snapshots as files. Use it to test a new program or a correction with expected values. Use it to record a play session of the original and replay it on each rebuild. Use it to find what changed between two machine states, and to make a checklist for a human playtest. It does not find the cause of a difference. It does not build the program.
3
+ description: Tests if a rebuilt or changed C64 program behaves as the original, or if a program has the expected values. It runs a scenario on the original and on the rebuild in an emulator. It compares memory, registers, chip state and the screen with explicit rules, and gives PASS, FAIL or INCONCLUSIVE. Use it when you must show that a rebuild or a correction keeps the behavior of the original. Use it to do many steps on one program and keep the screens, coverage maps, traces and snapshots as files. Use it to test a new program or a correction with expected values. Use it to record a play session of the original and replay it on the default build of the rebuild. Use it to find what changed between two machine states, and to make a checklist for a human playtest. It does not find the cause of a difference. It does not build the program.
4
4
  ---
5
5
 
6
6
  # C64 testing
@@ -30,7 +30,7 @@ To get the command list, run the script with no arguments.
30
30
  | Record a play session of a person on the original | `record tests/record/start.json --out tests/recordings/play1 --play --joystick 1` |
31
31
  | Record a session from steps only | `record tests/record/rooms.json --out tests/recordings/rooms` |
32
32
  | Make sure that a recording replays on the original | `replay tests/recordings/rooms` |
33
- | Compare the rebuild with a recording | `replay tests/recordings/rooms --checkpoint main_loop --state room --state lives --pin random_ptr:2 --rebuild build/game.prg --symbols build/game.json --out .c64-re-tools/local/results/rooms` |
33
+ | Compare the rebuild with a recording | `replay tests/recordings/rooms --checkpoint main_loop --state room --state lives --pin random_ptr:2 --rebuild build/clean.prg --symbols build/symbols/clean.json --out .c64-re-tools/local/results/rooms` |
34
34
  | Find what changed between two snapshot files | `diff .c64-re-tools/local/runs/rooms/before.vsf .c64-re-tools/local/runs/rooms/after.vsf` |
35
35
  | Find what changed between two observations of runs | `diff .c64-re-tools/local/runs/rooms/results.json:room0 .c64-re-tools/local/runs/rooms/results.json:room3` |
36
36
  | Find what changed between two memory files of runs | `diff .c64-re-tools/local/runs/a/all.bin .c64-re-tools/local/runs/b/all.bin --gap 4` |
@@ -42,11 +42,13 @@ To get the command list, run the script with no arguments.
42
42
  - The original gets its names from the project knowledge. Give `"symbols": "knowledge"` for the original.
43
43
  - The rebuild gets its names from the symbol file of its build. Build the rebuild with a symbol file that has all symbols, also the constants that the source does not use.
44
44
  - You write the scenario file, the run file and the record file. Their formats are in the files of the section "Reference".
45
+ - A file in `tests/` is a scenario or a run file with expected values. Give a scenario to `test` and a run file to `run`. `test` refuses a run file.
45
46
  - `<recording>` is the `--out` folder of `record`.
46
47
  - `--checkpoint` is a routine that the program executes one time in each pass of its game logic, for example the main loop. Do not use an interrupt handler. Get the name from the project knowledge.
47
48
  - `--state` and `--pin` take a name or a `$` address, with `:size` for more than one byte, for example `room:2`. Use the names that the project knowledge has at the time of the replay.
48
49
  - The joystick port of `--joystick` is the port that the program reads. Port 2 is `$DC00`, and port 1 is `$DC01`. Find the port in the code or in the project knowledge. If you do not know the port, use 2.
49
50
  - `diff` takes two states of one kind. A state is a snapshot file (`.vsf`), a memory file (`.bin`) of a run, or an observation of a run (`results.json:<name>`). A `save` step of a run writes a snapshot file. A snapshot save in the emulator also writes one.
51
+ - Each command starts its own emulator. Thus many commands can run at the same time. For example, other commands can run while a long `record` runs in the background.
50
52
 
51
53
  ### Paths and the project folder
52
54
 
@@ -177,6 +179,8 @@ A recording keeps a session of the original program, for example a play through
177
179
  - Make the recordings early, before you change the program.
178
180
  - Ask the user to play first. Tell the user which parts of the program the recordings must have, for example each room, a fight and a lost life.
179
181
  - Record a session from steps only for a part that the sessions of the user do not have, or when the user cannot play.
182
+ - Replay each recording on the default build. Do not replay a release build or a build with a switch that is not at its default.
183
+ - When the generated source has a loader, the default build is `build/clean_loader.prg`. Give `--symbols build/symbols/clean_loader.json` with it. Else the default build is `build/clean.prg`, with `--symbols build/symbols/clean.json`.
180
184
  - Commit the recording folder with the scenarios. Do not put a recording into the project knowledge. Do not put test results, screenshots or playtest results into it.
181
185
  - A finding that a recording shows can go into the project knowledge. Give the `recording.json` of the recording as its test evidence.
182
186
  - The C64 of a recording has no disk drive. For a program that loads more files from a disk, use a scenario with `test`.
@@ -203,10 +207,12 @@ The script does the steps of the record file on the original program. Then it wr
203
207
  - `executed`: the number of instructions in the coverage map.
204
208
  - `coverageFrom`: the `frame` and the `pc` where the coverage map starts. `null` when the coverage did not start.
205
209
  - `reason`: with a FAIL, why the session did not complete.
210
+ - `evidence`: only when the project knowledge gives a file of `--out` as evidence, and this record changed the file. Each item has the `file`, its `state` and the `revisions` that give the file.
206
211
 
207
212
  Do this for each result:
208
213
 
209
- - `PASS`: `hint` tells you to commit the folder and to add its `coverage.bin` to the project knowledge as coverage. `nextAction` replays the recording on the original. Run it to make sure that the recording replays.
214
+ - `PASS`: for a folder in `tests/recordings/`, `hint` tells you to commit the folder and to add its `coverage.bin` to the project knowledge as coverage. Git ignores `.c64-re-tools/local/`, thus the project knowledge must not name a file in it. For a folder there, `hint` tells you to record again with `--out tests/recordings/<name>`. `nextAction` replays the recording on the original. Run it to make sure that the recording replays.
215
+ - `PASS` with `evidence`: you recorded into the folder of an earlier recording. Put the new `coverage.bin` into the project knowledge as coverage. It replaces the map of the earlier recording. For another file in `evidence`, examine the facts of its revisions against the new recording.
210
216
  - `FAIL` after a cancel on the page: `hint` tells you to ask the user what to do. Do not record a session from steps in place of the session of the user.
211
217
  - Another `FAIL`: `reason` names the step that did not complete. Examples are a `runUntil` step that did not get to its target, and a `type` step with too many keys. Change the step, then run `record` again.
212
218
  - `coverageFrom` is `null` and `executed` is 0: the coverage did not start, so the coverage map is empty. The recording can still replay.
@@ -233,6 +239,10 @@ The script first replays the recording on the original. The original must end th
233
239
  `--checkpoint` and `--state` go together. `--pin` needs both of them. `--symbols` needs `--rebuild`. Give at most 16 `--state` and `--pin` items. Without `--checkpoint`, the script uses the comparison of the record file.
234
240
  A `$` address is an address of the original. On the rebuild, it moves with the name before it.
235
241
 
242
+ A rebuild can be a loader with a start screen that RUN starts. If the symbols of the rebuild have `loader_start_screen_wait` and `loader_start_screen_continue`, the script runs the rebuild to the wait. Then it sets the PC to `loader_start_screen_continue`. The cycles before the wait do not count.
243
+
244
+ A rebuild can be the loader program of a generated source. Give its symbols. Then the replay counts from the entry of the program, where the loader jumps to. The checkpoints of both sides start at that entry. At the entry, the rebuild gets the raster position, the CIA timers and the interrupt state of the original. The loader cannot set them as the original has them in the replay. A runUntil step to an address does not count the code of the loader, or the code that the original runs before that entry. If another step of the recording runs before the entry, the result is INCONCLUSIVE. Then start the steps of the record file after the entry.
245
+
236
246
  `body` holds `result`, `side`, `firstDifference`, `reason` and `files`. The section "Replay" of `references/recording-format.md` gives each field.
237
247
 
238
248
  Do this for each result:
@@ -248,8 +258,8 @@ Do this for each result:
248
258
 
249
259
  Traps:
250
260
 
251
- - `idleReads` counts the input reads of the rebuild that the recording had no value for. On the original, such a read makes the result INCONCLUSIVE.
252
- - The script refuses a recording of version 2.0 with `invalid-input`. Record the session again.
261
+ - `idleReads` counts the input reads of the rebuild that the recording had no value for. On the original, such a read makes the result INCONCLUSIVE. The rebuild can read input where the original does not, for example in its loader before the start screen. Such reads do not change a PASS of the rebuild.
262
+ - The script refuses a recording of an older version in an old form with `invalid-input`. Record the session again.
253
263
 
254
264
  ---
255
265
 
@@ -37,7 +37,7 @@ A record file is one JSON object in a project file.
37
37
  The steps have the form of the steps of a scenario. Two steps behave differently:
38
38
 
39
39
  - `type` puts at most 10 keys into the keyboard queue of the KERNAL. It is an event: a replay does it again.
40
- - `press` pushes keys of the keyboard matrix. It is input. A scenario has no `press` step.
40
+ - `press` pushes keys of the keyboard matrix. It is input.
41
41
 
42
42
  A record file has no `raster` target and no `condition`. `write` and `runUntil` have only the space `c64`.
43
43
 
@@ -45,20 +45,40 @@ A record file has no `raster` target and no `condition`. `write` and `runUntil`
45
45
  |---|---|
46
46
  | `{ "frames": 300 }` | Run 300 frames (19656 cycles each). |
47
47
  | `{ "joystick": { "port": 2, "direction": "left", "fire": true } }` | Set a joystick. It stays in this state until the next joystick step. |
48
- | `{ "press": "RUN\n" }` | Press each key of the text on the keyboard matrix for 3 frames, then release it for 3 frames. |
48
+ | `{ "press": { "keys": "RUN\n" } }` | Press the keys of the keyboard matrix. Each tap holds its keys for 3 frames, then releases them for 3 frames. `frames` sets a different number, from 1 to 3000. |
49
49
  | `{ "type": { "mode": "text", "text": "RUN\n" } }` | Put at most 10 keys into the keyboard queue of the KERNAL, after the keys that wait there. |
50
50
  | `{ "write": { "address": "next_room", "data": "01" } }` | Write bytes into RAM. |
51
51
  | `{ "registers": { "pc": "change_room", "a": 16 } }` | Set registers at the next instruction. `pc` continues the program at that address. |
52
52
  | `{ "runUntil": { "target": { "kind": "address", "address": "main_loop" }, "timeoutFrames": 300 } }` | Run until the CPU gets to an address. |
53
53
  | `{ "runUntil": { "target": { "kind": "memory", "address": "room", "operator": "eq", "value": 2 }, "timeoutFrames": 600 } }` | Run until a byte compares true with `value`. The script reads the byte at the end of each frame. |
54
54
 
55
- A `press` step can press A to Z, 0 to 9, space, return (`\n`) and `+-.:@,*;=/!"#$%&'()[]<>?`. It presses a to z as A to Z.
55
+ Each character of `keys` is one tap. a to z press the same keys as A to Z. `\n` presses RETURN. A character with SHIFT, for example `!`, also presses the left SHIFT.
56
+
57
+ The program runs while a `press` step taps its keys. An event in these frames is past when the next step starts. After a `press` step, run until an address that the program gets to later. For example, after F1 starts a game, run until the main loop of the game, not until the routine that starts the game.
58
+
59
+ A key without a character has its name in braces, in upper or lower case. `{STOP}` is RUN/STOP, and `{CBM}` is the Commodore key. The names are:
60
+
61
+ - `{F1}` to `{F8}`, `{RETURN}`, `{SPACE}`, `{DEL}`, `{INST}`, `{HOME}`, `{CLR}`
62
+ - `{STOP}`, `{RUN}`, `{RESTORE}`, `{CTRL}`, `{CBM}`, `{LSHIFT}`, `{RSHIFT}`
63
+ - `{UP}`, `{DOWN}`, `{LEFT}`, `{RIGHT}`, `{POUND}`, `{UPARROW}`, `{LEFTARROW}`
64
+
65
+ `{F2}`, `{F4}`, `{F6}`, `{F8}`, `{RUN}`, `{CLR}`, `{INST}`, `{UP}` and `{LEFT}` also press the left SHIFT.
66
+
67
+ To hold keys together in one tap, join them with `+` in braces. For example, `{ "press": { "keys": "{LSHIFT+CBM}" } }` holds the left SHIFT and the Commodore key together. One tap holds at most 4 keys. RESTORE counts as a key.
56
68
 
57
69
  The keyboard queue of the KERNAL holds 10 keys. If the keys of a `type` step and the keys that wait in the queue do not fit, the session stops. A program that reads the keyboard hardware does not see the keys of a `type` step. Use `press` for that program.
58
70
 
59
71
  `joystick`, `press` and `frames` steps are input and time. The recording keeps their effect in the reads, so a replay does not do these steps again.
60
72
 
61
- `type`, `write`, `registers` and `runUntil` steps are events. The recording keeps a point in the program for each event. The point is the next read at the input site with the most reads. That site is not in ROM. A replay does the event again at the same read. An event that comes directly after another event runs at once after that event.
73
+ RESTORE starts an NMI and is not a read. The recording keeps each RESTORE of a `press` step as an event of that step. The replay presses RESTORE again at the same read of the program.
74
+
75
+ `type`, `write`, `registers` and `runUntil` steps are events. The recording keeps a point in the program for each event. A replay does the event again at the same point:
76
+
77
+ - A `runUntil` step to an address: the point is the number of times that the CPU got to that address. This step does not need an input read.
78
+ - An event that comes directly after another event runs at once after that event.
79
+ - Each other event: the point is the next read at the input site with the most reads. That site is not in ROM. If the program does not read input in 600 frames, the session stops.
80
+
81
+ Some parts of a program read no input, for example an intro or a bonus screen. To do an event in such a part, put a `runUntil` step to an address before the event.
62
82
 
63
83
  ## Play
64
84
 
@@ -107,7 +127,7 @@ The page sends input only between Start and End. The input of the page goes into
107
127
 
108
128
  A site is the address of the instruction that reads. The values are hex. `<from>` and `<count>` are decimal.
109
129
 
110
- `replay` examines `recording.json` before the replay starts. A recording of version 2.0 can have events or a comparison in the old form, for example `"at"` in place of `"address"`. The script refuses it with `invalid-input`. The message names the event, the old field and the form to write. Record the session again.
130
+ `replay` examines `recording.json` before the replay starts. A recording of an older version can have events or a comparison in an old form. For example, `"at"` is in place of `"address"`, or a `runUntil` step to an address has no count of the CPU at its target. The script refuses such a recording with `invalid-input`, and the message names the event. Record the session again.
111
131
 
112
132
  ## Replay
113
133
 
@@ -126,5 +146,6 @@ The body of the envelope of `replay` has these fields:
126
146
  - `firstDifference`: on a FAIL, the checkpoint (1 is the first), the cycle on each side, and each state item that is different. An item has `address`, and the `original` and `rebuild` values as hex.
127
147
  - `reason`: why the result is FAIL or INCONCLUSIVE.
128
148
  - `movedSites`: the number of sites at a different address in the rebuild.
149
+ - `startScreen`: `skipped` when the rebuild went past the wait of its start screen.
129
150
  - `idleReads`: the input reads of the rebuild that the recording had no value for. Such a read is at a site that the recording does not have, or after its end. Each got the fixed value `$FF` (joystick, keyboard, paddles) or `$00`. An input site that the site map did not find shows here.
130
151
  - `files`: with `--out`, the RAM of each side at the first different checkpoint, `original-<n>.bin` and `rebuild-<n>.bin`.
@@ -8,7 +8,7 @@ A scenario is one JSON object in a project file.
8
8
  {
9
9
  "name": "player moves left",
10
10
  "original": { "program": "original/game.prg", "symbols": "knowledge" },
11
- "rebuild": { "program": "build/game.prg", "symbols": "build/game.json" },
11
+ "rebuild": { "program": "build/clean.prg", "symbols": "build/symbols/clean.json" },
12
12
  "steps": [
13
13
  { "frames": 150 },
14
14
  { "load": true },
@@ -46,8 +46,9 @@ Before the first step of each side, the script does a hard reset. The CPU stops
46
46
  | `{ "write": { "address": "seed", "data": "0102" } }` | Write 1 to 4096 bytes into memory. Optional: `space` (`c64` or `drive8`, default `c64`) and `view` (`cpu` or `ram`, default `cpu`). |
47
47
  | `{ "registers": { "pc": "start", "a": 0, "flags": { "i": true } } }` | Set registers: `pc`, `a`, `x`, `y`, `sp` and `flags` (`n`, `v`, `b`, `d`, `i`, `z`, `c`). Only `pc` can be a name. |
48
48
  | `{ "joystick": { "port": 2, "direction": "left", "fire": true } }` | Set a joystick. `fire` is `false` by default. The joystick stays in this state until the next joystick step. |
49
- | `{ "type": { "mode": "text", "text": "RUN\n" } }` | Put at most 1024 keys into the keyboard queue of the KERNAL. A program that reads the keyboard hardware does not see them. |
49
+ | `{ "type": { "mode": "text", "text": "RUN\n" } }` | Put at most 1024 keys into the keyboard queue of the KERNAL. A program that reads the keyboard hardware does not see them. Use `press` for that program. |
50
50
  | `{ "type": { "mode": "petscii", "bytes": [147] } }` | Put PETSCII codes from 1 to 255 into the keyboard queue of the KERNAL. Use it for keys that mode `text` does not have. |
51
+ | `{ "press": { "keys": "{F1}" } }` | Press keys of the keyboard matrix and RESTORE. A program that reads the keyboard hardware sees them. Each tap holds its keys for 3 frames, then releases them for 3 frames. Optional: `frames` from 1 to 3000. The keys are the same as the keys of a `press` step of a record file. |
51
52
  | `{ "runUntil": { "target": { "kind": "address", "address": "main_loop" }, "timeoutFrames": 600 } }` | Run until the CPU gets to an address. |
52
53
  | `{ "runUntil": { "target": { "kind": "memory", "address": "game_state", "operator": "eq", "value": 2 }, "timeoutFrames": 600 } }` | Run until a write to the byte makes the comparison with `value` true. `operator` is `eq`, `ne`, `lt`, `lte`, `gt` or `gte`. The run does not stop for a byte that is already true at the start. It also does not stop for a register that the hardware changes, for example `$d012`. For a raster line, use a `raster` target. |
53
54
  | `{ "runUntil": { "target": { "kind": "raster", "line": 250 }, "timeoutFrames": 5 } }` | Run until the raster beam gets to a line (0 to 311 for PAL, 0 to 262 for NTSC). Optional: `cycle` from 0 to 64. |
@@ -56,14 +57,14 @@ Before the first step of each side, the script does a hard reset. The CPU stops
56
57
  | `{ "normalize": true }` | Write pages 0 to 3 and `$00`/`$01` from the entry state in the project knowledge. The entry state comes from a capture of the unpacked program. Then both sides have the same zero page, stack and KERNAL work area. |
57
58
  | `{ "observe": "moved", ... }` | Record a checkpoint. |
58
59
 
60
+ The `timeoutFrames` of a `runUntil` step is from 1 to 30000. The default is 3000. For a longer wait, put `frames` steps before the `runUntil` step.
61
+
59
62
  The `port` of a joystick is 1 or 2. The `direction` is `center`, `up`, `down`, `left`, `right`, `up-left`, `up-right`, `down-left` or `down-right`.
60
63
 
61
64
  A `condition` has the `kind` `register`, `memory` or `raster`. A `register` condition has `register` (`a`, `x`, `y` or `sp`), `operator` and `value`. A `memory` condition has `address`, `operator` and `value`. A `raster` condition has `line` and an optional `cycle`.
62
65
 
63
66
  `timeoutFrames` is from 1 to 30000, and 3000 by default. A `runUntil` that does not get to its target in `timeoutFrames` frames makes the result INCONCLUSIVE.
64
67
 
65
- A scenario has no `press` step. Only a record file has `press` for keys of the keyboard matrix.
66
-
67
68
  Each step except `observe` can have `"side": "original"` or `"side": "rebuild"`. Then only that side does the step. Use it when only one side needs a step, for example a key for the intro of the original. An `observe` step has no `side`, because it compares both sides.
68
69
 
69
70
  Each side finds a name in its own symbols.
@@ -74,13 +75,15 @@ An `observe` step has a checkpoint name. A scenario can have each name only one
74
75
 
75
76
  | Key | What the script compares |
76
77
  |---|---|
77
- | `memory` | A list of names, `$` addresses, or objects. An object has `address`, `size` (1 to 65536, default 1), `view` (`cpu` or `ram`, default `cpu`), `tolerance` (0 to 255, default 0) and `exclude`. The view `ram` reads the RAM under the ROMs and the I/O area. |
78
+ | `memory` | A list of names, `$` addresses, or objects. An object has `address`, `size` (1 to 65536, default 1), `view` (`cpu` or `ram`, default `cpu`), `tolerance` (0 to 255, default 0), `mask` and `exclude`. The view `ram` reads the RAM under the ROMs and the I/O area. |
78
79
  | `registers` | A list of register names: `pc`, `a`, `x`, `y`, `sp`, `flags`. |
79
80
  | `screen` | The screen of the rebuild against the screen of the original. `maxMismatchRatio` (default 0) is the largest permitted part of different pixels. `mask` is a list of rectangles (`x`, `y`, `width`, `height`) that the comparison does not include. |
80
81
  | `vicii` | The VIC-II state: mode, screen address, scroll and colors. |
81
82
  | `sprites` | A list of sprite numbers from 0 to 7. The script compares their position, color and flags. |
82
83
 
83
- A `tolerance` is the largest permitted difference for each byte. A `mask` has at most 64 rectangles. A `mask` must not cover all of the screen: PAL is 384×272 pixels and NTSC is 384×247 pixels. A scenario can observe the screen at most at 64 checkpoints.
84
+ A `tolerance` is the largest permitted difference for each byte. A screen `mask` has at most 64 rectangles. A `mask` must not cover all of the screen: PAL is 384×272 pixels and NTSC is 384×247 pixels. A scenario can observe the screen at most at 64 checkpoints.
85
+
86
+ The `mask` of a memory object gives the bits that the comparison uses, as hex. It is one byte for all bytes of the range, for example `0f`, or one byte for each byte of the range. The comparison applies the mask first and then the `tolerance`. The colour RAM at $d800 has only 4 bits, and its other 4 bits are not stable. Thus observe the colour RAM with the mask `0f`.
84
87
 
85
88
  `exclude` is a list of bytes in the observed range that the comparison does not include. Each has `address` and a `reason`, for example `{ "address": "$d01e", "reason": "latched sprite collision, not writable" }`. The result lists each excluded byte with its `address` and `reason`.
86
89
 
@@ -94,7 +97,7 @@ A run file is one JSON object in a project file. It has:
94
97
  - `start`: required. `{ "program": "game.prg" }` to autostart a program with a BASIC start line, `{ "program": "game.prg", "load": true }` to load it with the CPU stopped (set `pc` in a step), or `{ "snapshot": ".c64-re-tools/local/snapshots/room0.vsf" }`.
95
98
  - `symbols`: optional, `knowledge`, `none` (default), or a JSON file as for a subject. Without `symbols`, a run has no names: give `"symbols": "knowledge"` to use the names of the knowledge.
96
99
  - `videoStandard`: optional, `pal` (default) or `ntsc`.
97
- - `steps`: required. At least one step. The steps `write`, `registers`, `joystick`, `type`, `frames` and `runUntil` of a scenario, and the run steps `snapshot`, `save`, `screen`, `coverage`, `trace`, `observe` and `expect`.
100
+ - `steps`: required. At least one step. The steps `write`, `registers`, `joystick`, `type`, `press`, `frames` and `runUntil` of a scenario, and the run steps `snapshot`, `save`, `screen`, `coverage`, `trace`, `observe` and `expect`.
98
101
 
99
102
  The run steps have these effects:
100
103
 
@@ -111,7 +114,7 @@ The run steps have these effects:
111
114
 
112
115
  A `trace` step has a name, `points` (1 to 8), `frames` (1 to 3000) and an optional `maxHits` (at most 20000). A point has `kind` (`exec`, `read` or `write`), `start` and an optional `end`. The step writes `<name>.json` with each hit. `results.json` gives the file, the count of hits, the frames and why the trace ended. A trace that a breakpoint, a watchpoint or a JAM ends also ends the run.
113
116
 
114
- In a run, an `observe` step can have `memory`, `registers`, `vicii` and `sprites`. `registers` and `vicii` are `true` or `false`, not a list. `"registers": true` gives all registers. A scenario takes a list of register names, a run does not. `sprites` is a list of sprite numbers from 0 to 7.
117
+ In a run, an `observe` step can have `memory`, `registers`, `vicii` and `sprites`. `registers` and `vicii` are `true` or `false`, not a list. `"registers": true` gives all registers. A scenario takes a list of register names, a run does not. `sprites` is a list of sprite numbers from 0 to 7. In a run, the screen is not a key of `observe`. Write it with a `screen` step, for example `{ "screen": "room3" }`.
115
118
 
116
119
  In a run, a memory item has `address`, `size` (1 to 65536) and `view`. An item larger than 4096 bytes goes into the file `<observe>-<address>.bin`, without the `$`. `results.json` gives the file name.
117
120
 
@@ -10,8 +10,9 @@ import { isObject } from "#src/host-client/steps.ts";
10
10
  import { WireFailure } from "#src/host-client/tools.ts";
11
11
  import { readProjectFile, writeReported } from "#src/host-client/transfer.ts";
12
12
  import { readMemoryInParts, ViceSessionClient } from "#src/host-client/vice-session.ts";
13
- import { checkSnapshotFile, hasSignature, VSF_SIGNATURE } from "#src/media.ts";
13
+ import { checkSnapshotFile } from "#src/media.ts";
14
14
  import { listed, UsageError } from "#src/script.ts";
15
+ import { snapshotModule } from "#src/vsf.ts";
15
16
  import { diffStates, type ChangedRange, type MachineState } from "./diff.ts";
16
17
 
17
18
  type Kind = "snapshot" | "memory" | "observation";
@@ -58,29 +59,14 @@ function cpuValues(registers: Record<string, unknown>): Record<string, number |
58
59
  return values;
59
60
  }
60
61
 
61
- /** The size of the header of a module in a VICE snapshot file: the name (16 bytes), the version (2 bytes) and the size (4 bytes). */
62
- const MODULE_HEADER = 22;
63
- const VSF_VERSION = "VICE Version\x1a";
64
-
65
62
  /**
66
63
  * The data of the C64MEM module of a VICE snapshot file: the data and the
67
64
  * direction register of the CPU port, the cartridge lines (2 bytes), then
68
65
  * the 64 KiB of RAM. Undefined when the file has no such module.
69
66
  */
70
67
  function c64Memory(file: Uint8Array): Buffer | undefined {
71
- const bytes = Buffer.from(file);
72
- if (!hasSignature("vsf", bytes)) return undefined;
73
- // The magic, the version (2 bytes) and the machine name (16 bytes); a newer VICE adds its own version (8 bytes).
74
- let at = VSF_SIGNATURE.length + 2 + 16;
75
- if (bytes.subarray(at, at + VSF_VERSION.length).toString("latin1") === VSF_VERSION) at += VSF_VERSION.length + 8;
76
- while (at + MODULE_HEADER <= bytes.length) {
77
- const name = bytes.subarray(at, at + 16).toString("latin1").replace(/\0+$/, "");
78
- const size = bytes.readUInt32LE(at + 18);
79
- if (size < MODULE_HEADER) return undefined;
80
- if (name === "C64MEM") return at + MODULE_HEADER + 4 + 0x10000 <= bytes.length ? bytes.subarray(at + MODULE_HEADER, at + MODULE_HEADER + 4 + 0x10000) : undefined;
81
- at += size;
82
- }
83
- return undefined;
68
+ const data = snapshotModule(Buffer.from(file), "C64MEM")?.data;
69
+ return data !== undefined && data.length >= 4 + 0x10000 ? data.subarray(0, 4 + 0x10000) : undefined;
84
70
  }
85
71
 
86
72
  /** The 64 KiB of C64 RAM that a VICE snapshot file holds, also the RAM under the CPU port at $00/$01. Undefined when the file has no C64MEM module. */