@henols/c64-re-tools 2.1.2 → 2.1.4

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 (50) hide show
  1. package/package.json +1 -1
  2. package/skills/c64-assembler/SKILL.md +1 -1
  3. package/skills/c64-assembler/scripts/assembler.ts +2 -2
  4. package/skills/c64-disk/scripts/lib/containers.ts +2 -1
  5. package/skills/c64-docs/SKILL.md +1 -1
  6. package/skills/c64-docs/scripts/docs.ts +5 -3
  7. package/skills/c64-emulator/SKILL.md +4 -0
  8. package/skills/c64-knowledge/SKILL.md +7 -2
  9. package/skills/c64-knowledge/scripts/knowledge.ts +6 -12
  10. package/skills/c64-knowledge/scripts/lib/listing.ts +8 -1
  11. package/skills/c64-memory-map/SKILL.md +3 -1
  12. package/skills/c64-memory-map/scripts/memory-map.ts +26 -5
  13. package/skills/c64-provenance/SKILL.md +5 -4
  14. package/skills/c64-provenance/scripts/lib/compare.ts +12 -0
  15. package/skills/c64-provenance/scripts/lib/library.ts +33 -5
  16. package/skills/c64-provenance/scripts/lib/separate.ts +34 -6
  17. package/skills/c64-provenance/scripts/provenance.ts +26 -11
  18. package/skills/c64-source/SKILL.md +3 -2
  19. package/skills/c64-source/scripts/lib/source.ts +18 -4
  20. package/skills/c64-source/scripts/source.ts +40 -28
  21. package/skills/c64-static-analysis/SKILL.md +4 -3
  22. package/skills/c64-static-analysis/scripts/lib/findings.ts +47 -10
  23. package/skills/c64-static-analysis/scripts/lib/pointers.ts +38 -25
  24. package/skills/c64-static-analysis/scripts/static-analysis.ts +17 -14
  25. package/skills/c64-testing/SKILL.md +6 -3
  26. package/skills/c64-testing/references/scenario-format.md +7 -3
  27. package/skills/c64-testing/scripts/lib/diff-files.ts +27 -8
  28. package/skills/c64-testing/scripts/lib/runs.ts +24 -8
  29. package/skills/c64-testing/scripts/lib/scenario.ts +133 -83
  30. package/skills/c64-testing/scripts/testing.ts +6 -3
  31. package/skills/c64-unpacker/SKILL.md +5 -4
  32. package/skills/c64-unpacker/scripts/lib/loads.ts +9 -3
  33. package/skills/c64-unpacker/scripts/lib/machine.ts +31 -0
  34. package/skills/c64-unpacker/scripts/unpacker.ts +4 -1
  35. package/src/host/vice/session.ts +118 -11
  36. package/src/host-client/image.ts +22 -8
  37. package/src/host-client/steps.ts +2 -2
  38. package/src/host-client/tools.ts +4 -3
  39. package/src/host-client/transfer.ts +8 -3
  40. package/src/host-client/vice-session.ts +3 -3
  41. package/src/knowledge/write.ts +110 -29
  42. package/src/mcp/output.ts +1 -1
  43. package/src/mcp/server.ts +7 -0
  44. package/src/mcp/tools/debug.ts +2 -1
  45. package/src/mcp/tools/media.ts +8 -5
  46. package/src/media.ts +18 -0
  47. package/src/opcodes.ts +31 -1
  48. package/src/platform.ts +14 -1
  49. package/src/project.ts +14 -3
  50. package/src/script.ts +71 -2
@@ -31,7 +31,7 @@ node <skill>/scripts/source.ts generate --out src --loader
31
31
 
32
32
  | Option | Meaning |
33
33
  |---|---|
34
- | `--out src` | The directory for the source files. The script writes over the files that it generated before. |
34
+ | `--out src` | The directory for the source files. The script writes over the files that it generated before. It removes a generated `.asm` file that this run does not write. A run without `--loader` keeps `loader.asm` and `loader.prg` of an earlier run. |
35
35
  | `--entry '$080d'` | An entry point for Ghidra. Use it again for more entry points. The entry of the program, the routines and the code regions in the knowledge are entry points too. |
36
36
  | `--analyzer-names` | Name an address that has no symbol and no platform name with its analyzer name, for example `FUN_17e2`. The order is heuristic, Ghidra, then DXA. Without it, the source makes its own names, for example `l_17e2`. |
37
37
  | `--space drive8` | Generate the source of drive code or a cartridge bank from the knowledge of that space. The coverage, `--loader` and the platform names are only for `c64`. |
@@ -80,7 +80,7 @@ When the knowledge has coverage, code that no run executed gets the line `; not
80
80
  - `constants.asm` holds the names of addresses outside the program, for example `EXTCOL = $d020`. The file puts the names in groups by memory area, for example zero page, VIC-II registers or CIA 1 registers. Each group is in address order. Drive code and banks have one group only. The side comment of a name tells what the address is. This text is the knowledge comment of the address. Without a comment, the text is the platform meaning. When the knowledge name is not the platform name, the platform name comes first. For an I/O mirror without a meaning, the text gives the register that the mirror repeats. Then `Used:` counts how the source uses the name. The kinds are `read`, `written`, `modified`, `called`, `jumped to`, `jumped through`, `branched to`, `pointer`, `address`, `table` and `macro argument`. `address` is an immediate operand expression. `table` is an entry in a table of addresses.
81
81
  - The top of `constants.asm` sets each switch to 0, for example `!ifndef CRACK { CRACK = 0 }`. A build that defines the switch as 1 uses the patches of that switch.
82
82
  - A label or a constant gets the name of the address in the knowledge. Without a knowledge name, it gets the platform name of the c64-memory-map skill, for example `EXTCOL` or `CHROUT`. A platform name wins over a name from an analyzer (`dxa`, `ghidra` or `heuristic`), for example `EXTCOL` over `ld020`. A `user` or `llm` name wins over a platform name. An address in the program without a name gets `l_xxxx`.
83
- - The source uses the names of a ROM only when the program uses that ROM. When the knowledge has coverage, a ROM is in use when a run executed code of it. A read of ROM bytes as data does not count. Without coverage, `$01` of the entry state tells which ROMs are in. When the program uses neither ROM, the zero page and pages 2 and 3 get no system names. `romNamesLeftOut` gives the ROMs that the source did not name, and the evidence.
83
+ - The source uses the names of a ROM only when the program uses that ROM. When the knowledge has coverage, a ROM is in use when a run executed code of it. A read of ROM bytes as data does not count. Without coverage, `$01` of the entry state tells which ROMs are in. When the program uses neither ROM, the zero page and pages 2 and 3 get no system names. `romNamesLeftOut` gives the ROMs that the source did not name, and the evidence. An operand expression or a macro use with such a name gets that reason.
84
84
  - `sta $d011 ; $d011: yScroll 3, rows 25, displayEnabled` is a store of an immediate to a register that the c64-memory-map skill decodes. The side comment gives the decoded value. A side comment in the knowledge replaces it.
85
85
  - Code regions, and the instructions that Ghidra decodes outside of data regions, become instructions.
86
86
  - Data regions become data by their type: `!byte`, `!word`, `!pet`, `!scr`, `!fill`, tables of labels, and sprite bytes in binary.
@@ -143,6 +143,7 @@ Do not store:
143
143
 
144
144
  - `result`: `PASS` when every check passes, else `FAIL`.
145
145
  - `files`: the files that the script wrote in `--out`, each with `out`, `bytes` and `sha256`. `sourceMap` names `source-map.json`.
146
+ - `removed`: the files of an earlier run that the script removed from `--out` and did not write again.
146
147
  - `instructions`, `dataBytes` and `undecodedBytes`.
147
148
  - `labels`: `named` labels from the knowledge and `generated` labels `l_xxxx`.
148
149
  - `entriesInData`: each `--entry` in a data region of the knowledge, with the `region` and its `origin`. Ghidra does not decode an entry in a data region.
@@ -34,6 +34,8 @@ export interface SourceInput {
34
34
  coverage?: Uint8Array;
35
35
  /** Platform names: the name of an address that knowledge does not name, the last address of its entry, and what it is. */
36
36
  platform?: ReadonlyArray<{ address: number; end: number; name: string; meaning?: string }>;
37
+ /** The platform names that `platform` leaves out, because the program does not use their ROM: the reason of an expression that names one tells it. */
38
+ platformLeftOut?: ReadonlySet<string>;
37
39
  /** The platform area of an address, and the register that an I/O mirror repeats: constants.asm groups and describes its names with them. */
38
40
  describe?: (address: number) => { area: Area; mirrorOf?: number };
39
41
  /** What a value in a platform register means (c64-memory-map): an immediate stored to such a register gets it as a side comment. Throws for a register without a decoder. */
@@ -355,6 +357,17 @@ export function layout(input: SourceInput): Layout {
355
357
  for (const row of input.platform ?? []) if (!byName.has(row.name)) byName.set(row.name, row.address);
356
358
  for (const symbol of input.symbols) byName.set(symbol.name, symbol.address);
357
359
  const instructionAt = new Map(pieces.flatMap((piece) => piece.items.flatMap((item) => (item.kind === "instruction" ? [[item.address, item] as const] : []))));
360
+ /** Why names of an expression are not names of the source: not known, or platform names of a ROM that the program does not use. */
361
+ const unknownNames = (missing: readonly string[], remedy: string) => {
362
+ const leftOut = missing.filter((name) => input.platformLeftOut?.has(name) === true);
363
+ const unknown = missing.filter((name) => !leftOut.includes(name));
364
+ const are = (names: readonly string[]) => `${names.join(", ")} ${names.length === 1 ? "is" : "are"}`;
365
+ return [
366
+ ...(unknown.length === 0 ? [] : [`${are(unknown)} not a symbol of the knowledge or a platform name.`]),
367
+ ...(leftOut.length === 0 ? [] : [`${are(leftOut)} a platform name of a ROM that the program does not use, so the source leaves ${leftOut.length === 1 ? "it" : "them"} out (romNamesLeftOut).`]),
368
+ remedy,
369
+ ].join(" ");
370
+ };
358
371
  // A macro use is a run of whole instructions of one file, of a macro with one param for each arg, whose args name known names.
359
372
  const macrosByName = new Map((input.macros ?? []).map((macro) => [macro.name, macro]));
360
373
  const macrosAsInstructions: MacroAsInstructions[] = [];
@@ -384,7 +397,7 @@ export function layout(input: SourceInput): Layout {
384
397
  }
385
398
  const missing = [...new Set(use.args.flatMap((arg) => identifiers(arg)))].filter((name) => !byName.has(name));
386
399
  if (missing.length > 0) {
387
- fallBack(`${missing.join(", ")} ${missing.length === 1 ? "is" : "are"} not a symbol of the knowledge or a platform name. Name the address with knowledge.ts rename, or give other args with knowledge.ts use.`);
400
+ fallBack(unknownNames(missing, "Name the address with knowledge.ts rename, or give other args with knowledge.ts use."));
388
401
  continue;
389
402
  }
390
403
  candidates.push({ use, items: run as InstructionItem[] });
@@ -403,7 +416,7 @@ export function layout(input: SourceInput): Layout {
403
416
  }
404
417
  const missing = identifiers(expression).filter((name) => !byName.has(name));
405
418
  if (missing.length > 0) {
406
- operandsAsNumbers.push({ address: operand.address, expression, reason: `${missing.join(", ")} ${missing.length === 1 ? "is" : "are"} not a symbol of the knowledge or a platform name. Name the address with knowledge.ts rename, or write the operand again with knowledge.ts operand.` });
419
+ operandsAsNumbers.push({ address: operand.address, expression, reason: unknownNames(missing, "Name the address with knowledge.ts rename, or write the operand again with knowledge.ts operand.") });
407
420
  continue;
408
421
  }
409
422
  // An immediate operand builds the address of a name; any other operand uses the address as the instruction does.
@@ -1020,8 +1033,9 @@ export function render(layout: Layout, asBytes: ReadonlySet<string>, header: str
1020
1033
  out.push(`${label} = * + ${offset}`);
1021
1034
  result.labels.push({ address: inside, name: label, file: piece.file, line: out.length });
1022
1035
  }
1023
- for (const text of lineComments.get(inside) ?? []) sides.push(text);
1024
- if (sideComments.has(inside)) sides.push(sideComments.get(inside)!);
1036
+ // A comment at an operand byte (knowledge of an older version) shows with its address, as in the listing of c64-knowledge.
1037
+ for (const text of lineComments.get(inside) ?? []) sides.push(`${formatC64Address(inside)}: ${text}`);
1038
+ if (sideComments.has(inside)) sides.push(`${formatC64Address(inside)}: ${sideComments.get(inside)!}`);
1025
1039
  }
1026
1040
  const form = formOf(layout, item);
1027
1041
  const { mode } = OPCODES[item.opcode]!;
@@ -11,7 +11,7 @@ import { existsSync, readdirSync, readFileSync, rmSync } from "node:fs";
11
11
  import { join } from "node:path";
12
12
 
13
13
  import { Refusal } from "#src/errors.ts";
14
- import { type AddressRange, COVERAGE, coverageSeedKinds, formatC64Address, textToPetscii } from "#src/c64.ts";
14
+ import { type AddressRange, coverageSeedKinds, formatC64Address, textToPetscii } from "#src/c64.ts";
15
15
  import { autostartLoaded, RUN_LIMIT_FRAMES } from "#src/host-client/autostart.ts";
16
16
  import { MAX_MEMORY_READ, WireFailure } from "#src/host-client/tools.ts";
17
17
  import { writeReported, type Written } from "#src/host-client/transfer.ts";
@@ -26,7 +26,7 @@ import { assemble } from "#src/native/acme.ts";
26
26
  import { analyze } from "#src/native/ghidra/analyze.ts";
27
27
  import { localToolContext } from "#src/native/local.ts";
28
28
  import { GHIDRA_LIMITS, type AssembledSymbol, type Diagnostic } from "#src/native/types.ts";
29
- import { decode as decodeRegister, describeAddress, platformNamesFor, romUseOf, romUseOfPort, type RomUse } from "#src/platform.ts";
29
+ import { decode as decodeRegister, describeAddress, platformNames, platformNamesFor, romUseOfProgram } from "#src/platform.ts";
30
30
  import { resolveProjectPath } from "#src/project.ts";
31
31
  import { listed, OPTIONS, runScript, UsageError, type Call } from "#src/script.ts";
32
32
  import { knowledgeNames } from "#src/knowledge/names.ts";
@@ -491,15 +491,10 @@ async function runLoader(path: string, program: Buffer, plan: LoaderPlan, image:
491
491
  }
492
492
  }
493
493
 
494
- /**
495
- * The ROMs the program uses: from the coverage when the knowledge has
496
- * it, else from $01 of the entry state, else both.
497
- */
498
- function romsInUse(image: ProgramImage, coverage: Uint8Array | undefined): RomUse & { from: "coverage" | "entry state" | "none" } {
499
- if (coverage !== undefined) return { ...romUseOf(coverage, COVERAGE.romExecute), from: "coverage" };
500
- const port = (image.state?.cpuPort as Record<string, unknown> | undefined)?.$01;
501
- if (typeof port === "number") return { ...romUseOfPort(port), from: "entry state" };
502
- return { basic: true, kernal: true, from: "none" };
494
+ /** The platform names that `used` leaves out: the names of the ROMs that the program does not use. */
495
+ function leftOutNames(used: ReadonlyArray<{ name: string }>): Set<string> {
496
+ const kept = new Set(used.map((entry) => entry.name));
497
+ return new Set(platformNames().flatMap((entry) => (kept.has(entry.name) ? [] : [entry.name])));
503
498
  }
504
499
 
505
500
  /** The first words of every file that the script writes. */
@@ -509,7 +504,6 @@ const NOT_EXECUTED_FILE = "not_executed.json";
509
504
  /** The line of each name and address in the source, for links from the documentation. */
510
505
  const SOURCE_MAP_FILE = "source-map.json";
511
506
 
512
- /** Removes the .asm files of an earlier run that this run does not write, and an earlier loader.prg and not_executed.json; other files stay. */
513
507
  /**
514
508
  * source-map.json: the line of each name and of each address that the
515
509
  * files write, after the mark line. One entry per line of the file, so a diff
@@ -522,19 +516,33 @@ function sourceMapText(rendered: Rendered, space: string, revision: string | nul
522
516
  return `${head},\n"labels": [\n${labels.join(",\n")}\n],\n"items": [\n${items.join(",\n")}\n]}\n`;
523
517
  }
524
518
 
525
- function removeOldFiles(out: string, keep: ReadonlySet<string>): void {
519
+ /** The files of the loader. Only a run with --loader writes them, so only such a run removes them. */
520
+ const LOADER_FILES: ReadonlySet<string> = new Set(["loader.asm", "loader.prg"]);
521
+
522
+ /**
523
+ * Removes the generated .asm files of an earlier run that this run does not
524
+ * write, and an earlier not_executed.json and source-map.json. An earlier
525
+ * loader.asm and loader.prg stay unless this run has --loader: a source of the
526
+ * user can include loader.asm. Other files stay. Gives the names it removed.
527
+ */
528
+ function removeOldFiles(out: string, keep: ReadonlySet<string>, loaderRun: boolean): string[] {
526
529
  const directory = resolveProjectPath(out);
527
- if (!existsSync(directory)) return;
530
+ if (!existsSync(directory)) return [];
531
+ const removed: string[] = [];
528
532
  for (const entry of readdirSync(directory, { withFileTypes: true })) {
529
533
  if (!entry.isFile()) continue;
530
534
  const name = entry.name;
531
535
  const path = join(directory, name);
532
- if (name === "loader.prg" || name === NOT_EXECUTED_FILE || name === SOURCE_MAP_FILE) rmSync(path, { force: true });
533
- else if (name.endsWith(".asm") && !keep.has(name) && readFileSync(path, "utf8").startsWith(GENERATED_MARK)) rmSync(path, { force: true });
536
+ if (LOADER_FILES.has(name) && !loaderRun) continue;
537
+ const old = name === "loader.prg" || name === NOT_EXECUTED_FILE || name === SOURCE_MAP_FILE || (name.endsWith(".asm") && !keep.has(name) && readFileSync(path, "utf8").startsWith(GENERATED_MARK));
538
+ if (!old) continue;
539
+ rmSync(path, { force: true });
540
+ removed.push(name);
534
541
  }
542
+ return removed;
535
543
  }
536
544
 
537
- async function generate(call: Call): Promise<{ output: Record<string, unknown>; failed: boolean }> {
545
+ async function generate(call: Call): Promise<{ output: Record<string, unknown>; failed: boolean; removed: string[] }> {
538
546
  const out = call.string("out")!;
539
547
  const entries = call.addresses("entry");
540
548
  const max = call.count("max-listed")!;
@@ -549,7 +557,8 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
549
557
  }
550
558
  // Read the entry state before the long steps, so a bad state stops the run at once.
551
559
  const state = loaderWanted ? loaderState(image.state, "the entry state of the knowledge") : undefined;
552
- const romUse = romsInUse(image, coverage);
560
+ const romUse = romUseOfProgram(coverage, image.state);
561
+ const platform = platformNamesFor(romUse);
553
562
  const { instructions, dataOnly } = await decode(image, knowledge, entries, coverage);
554
563
  const laid = layout({
555
564
  segments: image.segments,
@@ -567,7 +576,7 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
567
576
  macroUses: knowledge.macroUses,
568
577
  ...(coverage === undefined ? {} : { coverage }),
569
578
  // The platform names are C64 names: drive code and banks get none. A ROM that the program does not use gives none.
570
- ...(space === DEFAULT_SPACE ? { platform: platformNamesFor(romUse), describe: describeAddress, decode: decodeRegister } : {}),
579
+ ...(space === DEFAULT_SPACE ? { platform, platformLeftOut: leftOutNames(platform), describe: describeAddress, decode: decodeRegister } : {}),
571
580
  });
572
581
  const asBytes = await probe(laid);
573
582
  const header = [`Generated by c64-source from knowledge revision ${knowledge.revision}${space === DEFAULT_SPACE ? "" : ` in space ${space}`}.`, "Change names, comments, regions and modules in knowledge, then generate again."];
@@ -607,7 +616,7 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
607
616
  files = marked([...rendered.files, ...loaderFiles]);
608
617
  built = await assembleFiles(files, "main.asm");
609
618
  }
610
- removeOldFiles(out, new Set(files.map((file) => file.name)));
619
+ const removed = removeOldFiles(out, new Set(files.map((file) => file.name)), loaderWanted).map((name) => `${out}/${name}`);
611
620
  const written: Written[] = files.map((file) => writeReported(`${out}/${file.name}`, file.text, { what: "--out" }));
612
621
  written.push(writeReported(`${out}/${SOURCE_MAP_FILE}`, sourceMapText(rendered, space, knowledge.revision, files), { what: "--out" }));
613
622
  const showRange = (range: AddressRange) => ({ start: formatC64Address(range.start), end: formatC64Address(range.end) });
@@ -675,21 +684,21 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
675
684
  // The loader includes the source, so it is built only from a source that is identical to the image.
676
685
  const notBuilt = (reason: string) => (state === undefined ? {} : { loader: { verified: false, reason: loaderRefused ?? reason } });
677
686
  if (built.program === undefined) {
678
- return { output: { ...output, check: { identical: false, diagnostics: built.diagnostics.slice(0, MAX_DIAGNOSTICS) }, ...notBuilt("The source does not assemble, and the loader includes it.") }, failed: true };
687
+ return { output: { ...output, check: { identical: false, diagnostics: built.diagnostics.slice(0, MAX_DIAGNOSTICS) }, ...notBuilt("The source does not assemble, and the loader includes it.") }, removed, failed: true };
679
688
  }
680
689
  const checked = check(built.program, built.start!, image);
681
690
  output.check = checked;
682
- if (!checked.identical) return { output: { ...output, ...notBuilt("The source does not assemble to the image, and the loader includes it.") }, failed: true };
691
+ if (!checked.identical) return { output: { ...output, ...notBuilt("The source does not assemble to the image, and the loader includes it.") }, removed, failed: true };
683
692
  // Each switch on alone, against the default build; combinations are not built.
684
693
  const switches: SwitchCheck[] = [];
685
694
  for (const [name, patches] of switchesOf(laid)) switches.push(await checkSwitch(name, patches, files, { program: built.program, start: built.start! }, laid.names));
686
695
  if (switches.length > 0) output.switches = switches;
687
696
  const sourceFailed = laid.patchesNotWritten.length > 0 || switches.some((item) => item.result !== "fits");
688
- if (loaderRefused !== undefined) return { output: { ...output, loader: { verified: false, reason: loaderRefused } }, failed: true };
689
- if (loader === undefined || state === undefined) return { output, failed: missingEntry !== undefined || sourceFailed };
697
+ if (loaderRefused !== undefined) return { output: { ...output, loader: { verified: false, reason: loaderRefused } }, removed, failed: true };
698
+ if (loader === undefined || state === undefined) return { output, removed, failed: missingEntry !== undefined || sourceFailed };
690
699
 
691
700
  const loaderBuilt = await assembleFiles(files, "loader.asm");
692
- if (loaderBuilt.program === undefined) return { output: { ...output, loader: { verified: false, reason: "loader.asm does not assemble.", diagnostics: loaderBuilt.diagnostics.slice(0, MAX_DIAGNOSTICS) } }, failed: true };
701
+ if (loaderBuilt.program === undefined) return { output: { ...output, loader: { verified: false, reason: "loader.asm does not assemble.", diagnostics: loaderBuilt.diagnostics.slice(0, MAX_DIAGNOSTICS) } }, removed, failed: true };
693
702
  const program = loaderBuilt.program;
694
703
  // The simulation: the loader in memory as it loads, then every copy in its order, byte by byte.
695
704
  const memory = new Int16Array(0x10000).fill(-1);
@@ -722,7 +731,7 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
722
731
  // What the loader cannot set as it was at the entry.
723
732
  ...(loaderLimits(loader).length === 0 ? {} : { limits: loaderLimits(loader) }),
724
733
  };
725
- return { output, failed: !ran.verified || sourceFailed };
734
+ return { output, removed, failed: !ran.verified || sourceFailed };
726
735
  }
727
736
 
728
737
  await runScript({
@@ -743,8 +752,11 @@ await runScript({
743
752
  },
744
753
  notes: "The program, its entry state and the coverage come from the knowledge: put them in with knowledge.ts image and coverage of the c64-knowledge skill. Code that no imported run executed is marked and listed, and <dir>/not_executed.json has all of its ranges. Without --analyzer-names, an address without a name gets a name of the source, for example l_17e2.",
745
754
  run: async (call) => {
746
- const { output, failed } = await generate(call);
747
- return { result: failed ? "FAIL" : "PASS", ...output };
755
+ const { output, failed, removed } = await generate(call);
756
+ // A file of an earlier run that this run removed and did not write again.
757
+ const written = new Set((output.files as Written[]).map((file) => file.out));
758
+ const gone = removed.filter((path) => !written.has(path));
759
+ return { result: failed ? "FAIL" : "PASS", ...output, ...(gone.length === 0 ? {} : { removed: gone }) };
748
760
  },
749
761
  },
750
762
  ],
@@ -40,9 +40,10 @@ Both analyzers use the knowledge from the user and the LLM as seeds:
40
40
 
41
41
  - Each routine is an entry point.
42
42
  - Each region that is not code stays data.
43
+ - Each symbol of the kind `data` or `variable` stays data. The region that is not code and that holds the symbol stays data, also a region of an analyzer. Without such a region, the byte of the symbol stays data. A symbol in a code region or at an executed address is not data. When the region holds an entry point or an executed address, only the byte of the symbol stays data.
43
44
  - Each name is a label. The listing, Ghidra and the decompiler show that name.
44
45
 
45
- Facts that an analyzer found are not seeds. A new analysis can then correct or remove them.
46
+ Facts that an analyzer found are not seeds alone. A new analysis can then correct or remove them.
46
47
 
47
48
  More seeds come from evidence:
48
49
 
@@ -90,9 +91,9 @@ The analyzers take at most 1024 entry points. Knowledge routines and `--entry` c
90
91
  - `conflicts` lists the places where the analyzer and the current knowledge disagree.
91
92
  - DXA or Ghidra can find data where a run executed an instruction start (`executed`), or where a `user` or `llm` symbol of kind `label` or `routine` is (`knowledge`). Then the script does not write that data region, and the earlier region of the analyzer stays. `conflicts` lists each such place. Executed code and your names have priority over the guess of an analyzer.
92
93
  - `idioms` tells what the script found by pattern: RTS dispatch tables (`rtsTables`), JMP tables (`jumpTables`) and BIT skips (`bitSkips`). It also finds the `CBM80` header of a cartridge bank at `$8000` (`cartridgeHeaders`). The two start vectors of the header become entry points. The script writes them as knowledge with the origin `heuristic`, and seeds their targets into the same analysis. `candidates` gives DOP padding (`dop`) and opcodes that the program wrote and executed (`selfModified`). For `selfModified`, the write and the execution must be in one coverage file. A coverage file does not record the order. Thus a candidate can also be code that ran first, and that the program then wrote over. To prevent this, save one coverage file for each part of the program, for example the intro and the game. A loader that copies relocated code is also such a part. Clear the memory map between the parts. Each list has a `count`. The script does not write the candidates. Look at them and decide.
93
- - `candidates.pointers` gives code that makes an address from immediates. A `vector` or a `zero-page pointer` candidate stores a low byte (`low`) and a high byte (`high`) to a vector or to a zero-page pair that `(zp),y` uses. Its `target` is in the program or has a platform name. A `sprite pointer` candidate stores an immediate (`at`) to a sprite pointer of the screen at $0400 in VIC bank 0. Its `target` (the value × 64) is in a `sprite` region. For each candidate that you confirm, write operand expressions with `operand` of the c64-knowledge skill, for example `operand '<low>' --lo <target name>` and `operand '<high>' --hi <target name>`. Then a rebuild can move the target.
94
+ - `candidates.pointers` gives code that makes an address from immediates. The script reads only the instructions of the code regions, from the start of each region. A `vector` or a `zero-page pointer` candidate stores a low byte (`low`) and a high byte (`high`) to a vector or to a zero-page pair. A `(zp),y` instruction of the code uses the zero-page pair. Its `target` is in the program or has a platform name. A `sprite pointer` candidate stores an immediate (`at`) to a sprite pointer of the screen at $0400 in VIC bank 0. Its `target` (the value × 64) is in a `sprite` region. For each candidate that you confirm, write operand expressions with `operand` of the c64-knowledge skill, for example `operand '<low>' --lo <target name>` and `operand '<high>' --hi <target name>`. Then a rebuild can move the target.
94
95
  - `candidates.pitfalls` gives code that a C64 runs in a different way than it reads. `raster-bit-8`: the instruction at `at` reads $D011, and the instruction at `store` writes the value back. A read of $D011 gives bit 8 of the raster line in bit 7. Thus the write can move the raster interrupt to line 256 or later, and on PAL past line 311 the interrupt never comes. Examine each candidate. Where the code must not keep bit 7, add a comment and test the program.
95
- - `candidates.macros` gives runs of instructions that a macro writes as one line, for example `+inc16 ptr`. The script knows these 6502 idioms: `inc16`, `dec16`, `add16_8`, `add16`, `sub16`, `set16`, `mov16` and `wait_line`. It reads the code regions after the analysis. An arg has the name of a `user` or `llm` symbol or a platform name. Each candidate has `macro`, `start`, `end`, `args` and `text`. `known` counts the uses that the knowledge has. `leftOut` counts the candidates with a label inside, or with a patch or a use over them. The c64-source skill writes such a candidate as instructions. With `--out-macro-batch`, `batch` gives the file, the count of writes (`writes`) and the `apply` command. The batch holds the macros that the knowledge does not have, and the uses. When the knowledge has a macro with the same name and another body, `otherMacros` tells that the batch does not have its uses. The script does not write the candidates. Apply the batch, then generate the source again.
96
+ - `candidates.macros` gives runs of instructions that a macro writes as one line, for example `+inc16 ptr`. The script knows these 6502 idioms: `inc16`, `dec16`, `add16_8`, `add16`, `sub16`, `set16`, `mov16` and `wait_line`. It reads the code regions after the analysis. An arg has the name of a `user` or `llm` symbol or a platform name. A platform name of a ROM that the program does not use is not an arg, because the c64-source skill does not use it. Each candidate has `macro`, `start`, `end`, `args` and `text`. `known` counts the uses that the knowledge has. `leftOut` counts the candidates with a label inside, or with a patch or a use over them. The c64-source skill writes such a candidate as instructions. With `--out-macro-batch`, `batch` gives the file, the count of writes (`writes`) and the `apply` command. The batch holds the macros that the knowledge does not have, and the uses. When the knowledge has a macro with the same name and another body, `otherMacros` tells that the batch does not have its uses. The script does not write the candidates. Apply the batch, then generate the source again.
96
97
  - When the knowledge has coverage, a code finding replaces the DXA or Ghidra data where a run executed an instruction start. `coverageConflicts` lists the analyzer data regions where the coverage still shows executed code. Classify them as code with the c64-knowledge skill, or as `dual-use` when the bytes are also data. For many conflicts, write all classifications in one `apply` batch of the c64-knowledge skill.
97
98
  6. Give each important routine a name with the c64-knowledge skill. Then run the analysis again. The analyzers use the new names.
98
99
 
@@ -15,25 +15,61 @@ const semantic = (row: { origin: string }) => isSemantic(row.origin);
15
15
  /**
16
16
  * Seeds from current semantic knowledge: routines from the user or
17
17
  * the LLM are entry points, their non-code regions are data, and their names
18
- * are labels. Analyzer facts are never seeds: fed back, an analyzer's own
19
- * earlier guess would force the same answer again, and a re-analysis could
20
- * not retire it.
18
+ * are labels. Analyzer facts are never seeds alone: fed back, an analyzer's
19
+ * own earlier guess would force the same answer again, and a re-analysis
20
+ * could not retire it. A data or variable symbol of the user or the LLM is a
21
+ * decision that its address is data: the non-code region that holds it is
22
+ * data, also a region of an analyzer, else the byte of the symbol. Where a
23
+ * code region holds the symbol (a variable in the operand of self-modifying
24
+ * code) or the address executed, the symbol gives no data. A region with an
25
+ * executed address or an entry point in it gives only the byte of the symbol.
21
26
  */
22
- export function seedsFromKnowledge(db: DatabaseSync | undefined, extraEntryPoints: number[] = [], space: Space = DEFAULT_SPACE): Seeds {
27
+ export function seedsFromKnowledge(db: DatabaseSync | undefined, extraEntryPoints: number[] = [], space: Space = DEFAULT_SPACE, executed: (address: number) => boolean = () => false): Seeds {
23
28
  const symbols = listSymbols(db, undefined, undefined, undefined, space).filter(semantic);
24
29
  const entryPoints = [...new Set([...extraEntryPoints, ...symbols.filter((symbol) => symbol.kind === "routine").map((symbol) => symbol.address)])].sort((a, b) => a - b);
30
+ const regions = listRegions(db, undefined, undefined, undefined, space);
31
+ // A JMP table is code and dual-use bytes are both: neither is a data range.
32
+ const isData = (region: { type: string }) => !CODE_REGION_TYPES.includes(region.type as never) && region.type !== "dual-use";
33
+ const dataRanges = regions.filter((region) => semantic(region) && isData(region)).map((region) => ({ start: region.start, end: region.end }));
34
+ const covered = (range: { start: number; end: number }) => dataRanges.some((seed) => seed.start <= range.end && range.start <= seed.end);
35
+ const holdsCode = (range: { start: number; end: number }) => entryPoints.some((entry) => entry >= range.start && entry <= range.end) || Array.from({ length: range.end - range.start + 1 }, (_, offset) => range.start + offset).some(executed);
36
+ for (const symbol of symbols.filter((row) => row.kind === "data" || row.kind === "variable").sort((a, b) => a.address - b.address)) {
37
+ const own = { start: symbol.address, end: symbol.address };
38
+ const region = regions.find((row) => row.start <= symbol.address && symbol.address <= row.end);
39
+ if ((region !== undefined && !isData(region)) || holdsCode(own) || covered(own)) continue;
40
+ const range = region !== undefined && !holdsCode(region) ? { start: region.start, end: region.end } : own;
41
+ dataRanges.push(range);
42
+ }
25
43
  return {
26
44
  entryPoints,
27
- dataRanges: listRegions(db, undefined, undefined, undefined, space)
28
- // A JMP table is code and dual-use bytes are both: neither is a data range.
29
- .filter((region) => semantic(region) && !CODE_REGION_TYPES.includes(region.type) && region.type !== "dual-use")
30
- .map((region) => ({ start: region.start, end: region.end })),
45
+ dataRanges: dataRanges.sort((a, b) => a.start - b.start),
31
46
  labels: symbols.map((symbol) => ({ address: symbol.address, name: symbol.name })),
32
47
  };
33
48
  }
34
49
 
35
50
  /**
36
- * Ghidra's result as normalized findings. A function named by an echoed seed
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
53
+ * that it computes from the pointer value at the entry state: a guess, because
54
+ * the program sets the pointer at run time. Only the reference to the pointer
55
+ * itself (zp or zp+1) is a fact.
56
+ */
57
+ function guessedIndirectTarget(instructions: GhidraResult["instructions"]): (reference: { from: number; to: number }) => boolean {
58
+ const pointers = new Map<number, number>();
59
+ for (const instruction of instructions) {
60
+ const opcode = Number.parseInt(instruction.bytes.slice(0, 2), 16);
61
+ if (instruction.bytes.length === 4 && ((opcode & 0x0f) === 0x01 || (opcode & 0x0f) === 0x03)) pointers.set(instruction.address, Number.parseInt(instruction.bytes.slice(2, 4), 16));
62
+ }
63
+ return (reference) => {
64
+ const pointer = pointers.get(reference.from);
65
+ return pointer !== undefined && reference.to !== pointer && reference.to !== ((pointer + 1) & 0xff);
66
+ };
67
+ }
68
+
69
+ /**
70
+ * Ghidra's result as normalized findings. A reference from a (zp,x) or (zp),y
71
+ * instruction to a computed target is not a finding (see guessedIndirectTarget).
72
+ * A function named by an echoed seed
37
73
  * stays in the snapshot: its address holds the seed's semantic symbol, which
38
74
  * the importer never replaces, so the name keeps its owner,
39
75
  * and a code/data disagreement with that symbol is still reported.
@@ -49,6 +85,7 @@ export function ghidraFindings(result: GhidraResult): NormalizedFindings {
49
85
  // A function that branches and jumps reach, and no call, is a place in a routine: a label.
50
86
  const called = new Set(result.references.filter((reference) => reference.type === "call").map((reference) => reference.to));
51
87
  const jumped = new Set(result.references.filter((reference) => reference.type === "jump").map((reference) => reference.to));
88
+ const guessed = guessedIndirectTarget(result.instructions);
52
89
  const kindOf = (fn: GhidraResult["functions"][number]) => (jumped.has(fn.entry) && !called.has(fn.entry) ? ("label" as const) : ("routine" as const));
53
90
  return {
54
91
  analyzer: "ghidra",
@@ -56,7 +93,7 @@ export function ghidraFindings(result: GhidraResult): NormalizedFindings {
56
93
  authoritative: { symbols: result.completeness.functions, regions: result.completeness.regions, references: result.completeness.references },
57
94
  symbols: result.functions.map((fn) => ({ address: fn.entry, name: nameOf(fn), kind: kindOf(fn) })),
58
95
  regions: result.regions.map((region) => ({ start: region.start, end: region.end, type: region.classification === "code" ? ("code" as const) : ("bytes" as const) })),
59
- references: result.references.map((reference) => ({ from: reference.from, to: reference.to, kind: reference.type })),
96
+ references: result.references.filter((reference) => !guessed(reference)).map((reference) => ({ from: reference.from, to: reference.to, kind: reference.type })),
60
97
  };
61
98
  }
62
99
 
@@ -3,12 +3,14 @@
3
3
  // that moves the address needs an operand expression there. They are only
4
4
  // reported, never written: the LLM records the expressions with c64-knowledge.
5
5
  //
6
- // The scan reads short straight runs of instructions: LDA/LDX/LDY #imm and
7
- // STA/STX/STY to zero page or absolute, plus SEI, CLI, CLC, SEC and NOP. Any
8
- // other instruction ends the run, so no register value is guessed across it.
6
+ // The scan reads the instructions of the code regions, decoded from the start
7
+ // of each region: bytes of data are never read as an instruction. It reads
8
+ // short straight runs: LDA/LDX/LDY #imm and STA/STX/STY to zero page or
9
+ // absolute, plus SEI, CLI, CLC, SEC and NOP. Any other instruction ends the
10
+ // run, so no register value is guessed across it.
9
11
 
10
- import { instructionLength } from "#src/c64.ts";
11
12
  import type { ImageByte } from "./coverage.ts";
13
+ import { instructionAt, type Instruction } from "./macros.ts";
12
14
 
13
15
  const LOADS: Record<number, "a" | "x" | "y"> = { 0xa9: "a", 0xa2: "x", 0xa0: "y" };
14
16
  const STORES: Record<number, "a" | "x" | "y"> = { 0x85: "a", 0x8d: "a", 0x86: "x", 0x8e: "x", 0x84: "y", 0x8c: "y" };
@@ -50,46 +52,57 @@ interface Store {
50
52
  to: number;
51
53
  }
52
54
 
53
- /** The stores of immediates in the straight run that starts at `start`. */
54
- function storesFrom(byteAt: ImageByte, start: number, range: { start: number; end: number }): Store[] {
55
+ /** The stores of immediates in the straight run of decoded instructions that starts at `start`. */
56
+ function storesFrom(run: ReadonlyArray<Instruction & { at: number }>, start: number): Store[] {
55
57
  const last: Partial<Record<"a" | "x" | "y", { load: number; value: number }>> = {};
56
58
  const stores: Store[] = [];
57
- let at = start;
58
- for (let count = 0; count < MAX_RUN; count++) {
59
- const opcode = byteAt(at);
60
- if (opcode === undefined) break;
61
- const length = instructionLength(opcode);
62
- if (at + length - 1 > range.end) break;
63
- const operand = length === 2 ? byteAt(at + 1)! : length === 3 ? byteAt(at + 1)! | (byteAt(at + 2)! << 8) : 0;
64
- if (LOADS[opcode] !== undefined) last[LOADS[opcode]] = { load: at, value: operand };
59
+ for (const { opcode, value, at } of run.slice(start, start + MAX_RUN)) {
60
+ if (LOADS[opcode] !== undefined) last[LOADS[opcode]] = { load: at, value };
65
61
  else if (STORES[opcode] !== undefined) {
66
62
  const loaded = last[STORES[opcode]];
67
63
  if (loaded === undefined) break;
68
- stores.push({ ...loaded, to: operand });
64
+ stores.push({ ...loaded, to: value });
69
65
  } else if (!NEUTRAL.has(opcode)) break;
70
- at += length;
71
66
  }
72
67
  return stores;
73
68
  }
74
69
 
70
+ /** The instructions of each code region, decoded from its start, up to a byte that is no instruction. */
71
+ function decoded(byteAt: ImageByte, code: ReadonlyArray<{ start: number; end: number }>): Array<Array<Instruction & { at: number }>> {
72
+ return [...code]
73
+ .sort((a, b) => a.start - b.start)
74
+ .map((region) => {
75
+ const run: Array<Instruction & { at: number }> = [];
76
+ for (let at = region.start; at <= region.end; ) {
77
+ const instruction = instructionAt(byteAt, at, region.end);
78
+ if (instruction === undefined) break;
79
+ run.push({ ...instruction, at });
80
+ at += instruction.length;
81
+ }
82
+ return run;
83
+ });
84
+ }
85
+
75
86
  /**
76
- * Finds the pointer candidates in the image: an immediate pair stored to a
77
- * vector or to a zero-page pair that (zp),y uses, where the pair makes an
78
- * address in the image or a platform name; and an immediate stored to a sprite
79
- * pointer of the default screen whose sprite data is in a sprite region.
87
+ * Finds the pointer candidates in the code regions of the image: an immediate
88
+ * pair stored to a vector or to a zero-page pair that a (zp),y instruction of
89
+ * the code uses, where the pair makes an address in the image or a platform
90
+ * name; and an immediate stored to a sprite pointer of the default screen whose
91
+ * sprite data is in a sprite region.
80
92
  */
81
93
  export function findPointers(
82
94
  byteAt: ImageByte,
83
95
  range: { start: number; end: number },
96
+ code: ReadonlyArray<{ start: number; end: number }>,
84
97
  known: { platform: (address: number) => boolean; sprites: ReadonlyArray<{ start: number; end: number }> },
85
98
  ): PointerCandidate[] {
86
- const indirect = new Set<number>();
87
- for (let at = range.start; at < range.end; at++) if (INDIRECT_Y.has(byteAt(at)!)) indirect.add(byteAt(at + 1)!);
99
+ const runs = decoded(byteAt, code);
100
+ const indirect = new Set(runs.flatMap((run) => run.filter((instruction) => INDIRECT_Y.has(instruction.opcode)).map((instruction) => instruction.value)));
88
101
  const inImage = (address: number) => address >= range.start && address <= range.end && byteAt(address) !== undefined;
89
102
  const found = new Map<string, PointerCandidate>();
90
- for (let at = range.start; at <= range.end; at++) {
91
- if (LOADS[byteAt(at)!] === undefined) continue;
92
- const stores = storesFrom(byteAt, at, range);
103
+ for (const [run, index] of runs.flatMap((run) => run.map((_, index) => [run, index] as const))) {
104
+ if (LOADS[run[index]!.opcode] === undefined) continue;
105
+ const stores = storesFrom(run, index);
93
106
  for (const low of stores) {
94
107
  const high = stores.find((store) => store.to === low.to + 1);
95
108
  const target = high === undefined ? undefined : low.value | (high.value << 8);
@@ -17,7 +17,7 @@ import { analyzedBytes, programCoverage, requireProgram } from "#src/knowledge/p
17
17
  import { importFindings, runProvenance, type ImportConflict, type ImportContext, type ImportResult, type NormalizedFindings } from "#src/knowledge/import.ts";
18
18
  import { currentRevision, listMacros, listMacroUses, listPatches, listReferences, listRegions, listSymbols } from "#src/knowledge/read.ts";
19
19
  import { DEFAULT_SPACE, SEMANTIC_ORIGINS, type Analyzer } from "#src/knowledge/schema.ts";
20
- import { platformNames } from "#src/platform.ts";
20
+ import { platformNames, platformNamesFor, romUseOfProgram, type RomUse } from "#src/platform.ts";
21
21
  import { listed, OPTIONS, runScript, UsageError, type Call } from "#src/script.ts";
22
22
  import { codeEntries, coverageConflicts, coverageEntries, coverageSeedKinds, executedStarts, imageReader, romOnlyRanges, type ImageByte } from "./lib/coverage.ts";
23
23
  import { dxaFindings, ghidraFindings, seedsFromKnowledge } from "./lib/findings.ts";
@@ -52,17 +52,19 @@ function showMacro(candidate: MacroCandidate) {
52
52
 
53
53
  /**
54
54
  * The macro candidates in the current code regions of every origin,
55
- * with the names of the knowledge in their args. A candidate is left out when
55
+ * with the names of the knowledge in their args, else the platform names of
56
+ * the ROMs that the program uses, as c64-source names them. A candidate is left out when
56
57
  * a name or a reference target is inside it, or a patch or a use overlaps it:
57
58
  * c64-source would write its instructions. The same use in the knowledge is
58
59
  * known. With `batchPath`, the candidates go to an apply batch with the
59
60
  * macros they need; a macro of the catalogue that the knowledge has with
60
61
  * another body leaves its candidates out of the batch.
61
62
  */
62
- function macroCandidates(space: string, byteAt: ImageByte, batchPath: string | undefined) {
63
+ function macroCandidates(space: string, byteAt: ImageByte, batchPath: string | undefined, romUse: RomUse) {
63
64
  const db = openForRead();
64
65
  try {
65
- const platform = space === DEFAULT_SPACE ? new Map(platformNames().map((entry) => [entry.address, entry.name])) : new Map<number, string>();
66
+ // The platform names that c64-source uses: a name of a ROM that the program does not use is no arg.
67
+ const platform = space === DEFAULT_SPACE ? new Map(platformNamesFor(romUse).map((entry) => [entry.address, entry.name])) : new Map<number, string>();
66
68
  const semantic = new Map(listSymbols(db, undefined, undefined, [...SEMANTIC_ORIGINS], space).map((symbol) => [symbol.address, symbol.name]));
67
69
  const code = listRegions(db, undefined, "code", undefined, space);
68
70
  const found = findMacroUses(byteAt, code, (address) => semantic.get(address) ?? platform.get(address));
@@ -197,7 +199,7 @@ async function analyze(call: Call): Promise<unknown> {
197
199
  const idioms = findIdioms(inProgram, { start: loaded.start, end: loaded.end }, covered);
198
200
 
199
201
  const revision = currentRevision(reader);
200
- const seeds = seedsFromKnowledge(reader, entries, space);
202
+ const seeds = seedsFromKnowledge(reader, entries, space, executed.executed);
201
203
  // Knowledge routines and --entry first, then code regions and JMP tables, then idioms, then coverage, up to the seed bound.
202
204
  const fromCoverage = coverage === undefined ? [] : coverageEntries(coverage, inProgram);
203
205
  const known = [...seeds.entryPoints, ...codeEntries(reader, byteAt, space)];
@@ -216,20 +218,21 @@ async function analyze(call: Call): Promise<unknown> {
216
218
  const coverageUsed = fromCoverage.filter((entry) => seeds.entryPoints.includes(entry) || codeStarts.includes(entry)).length;
217
219
  // Platform names are C64 names: drive code and banks get none.
218
220
  const platform = space === DEFAULT_SPACE ? platformNames() : [];
219
- const pointers = findPointers(byteAt, { start: loaded.start, end: loaded.end }, {
220
- platform: (address) => platform.some((entry) => address >= entry.address && address <= entry.end),
221
- sprites: listRegions(reader, undefined, "sprite", undefined, space),
222
- });
223
221
  reader?.close();
224
222
  /** Imports the idioms as their own revision, after the analyzer's, and gives their part of the result. */
225
223
  const idiomsResult = () => {
226
224
  const imported = withWrite((db) => importFindings(db, { ...idioms.findings, space }, { description: "Idioms in the program" }));
227
225
  // The macro candidates read the code regions after both imports.
228
- const macros = macroCandidates(space, byteAt, batchPath);
229
- // Platform pitfalls are C64 facts: drive code and banks get none.
230
- const pitfallDb = openForRead();
231
- const pitfalls = space === DEFAULT_SPACE ? findPitfalls(byteAt, listRegions(pitfallDb, undefined, "code", undefined, space)) : [];
232
- pitfallDb?.close();
226
+ const macros = macroCandidates(space, byteAt, batchPath, romUseOfProgram(coverage, program.state));
227
+ // Platform pitfalls are C64 facts: drive code and banks get none. Pitfalls and pointers read the code regions after both imports.
228
+ const codeDb = openForRead();
229
+ const code = listRegions(codeDb, undefined, "code", undefined, space);
230
+ const pitfalls = space === DEFAULT_SPACE ? findPitfalls(byteAt, code) : [];
231
+ const pointers = findPointers(byteAt, { start: loaded.start, end: loaded.end }, code, {
232
+ platform: (address) => platform.some((entry) => address >= entry.address && address <= entry.end),
233
+ sprites: listRegions(codeDb, undefined, "sprite", undefined, space),
234
+ });
235
+ codeDb?.close();
233
236
  return {
234
237
  idioms: {
235
238
  ...idioms.counts,
@@ -26,7 +26,7 @@ node <skill>/scripts/testing.ts test tests/moves-left.json --out .c64-re-tools/l
26
26
  node <skill>/scripts/testing.ts checklist tests/moves-left.json --item 'FIRE starts the game.'
27
27
  ```
28
28
 
29
- `testing.ts test` gives `result`: PASS, FAIL or INCONCLUSIVE. With `--out`, a FAIL writes files into that directory: both screens and the difference image for each screen difference, and `memory.json` with each byte that differs. `files` in the result names them. A PASS writes no files. To keep the screens of a PASS, use a run (below).
29
+ `testing.ts test` gives `result`: PASS, FAIL or INCONCLUSIVE. With `--out`, a FAIL writes files into that directory: both screens and the difference image for each screen difference, and `memory.json`. `memory.json` has all bytes of each memory item that differs, and each byte that differs. `files` in the result names them. A PASS writes no files. To keep the screens of a PASS, use a run (below).
30
30
 
31
31
  `testing.ts checklist` gives a Markdown checklist for a human tester in `text`.
32
32
 
@@ -40,7 +40,7 @@ A run does steps on one program, with no comparison, and keeps the results as fi
40
40
  node <skill>/scripts/testing.ts run .c64-re-tools/local/runs/rooms/run.json --out .c64-re-tools/local/runs/rooms
41
41
  ```
42
42
 
43
- The run file gives where to start (a program, or a snapshot file), the steps, and optional symbols. To go on from the live emulator, save its state with `c64_snapshot` action `save` and `out`, and start the run from that file. A run has the action steps of a scenario: `write`, `registers`, `joystick`, `type`, `frames` and `runUntil`. It also has these steps:
43
+ The run file gives where to start (a program, or a snapshot file), the steps, and optional symbols. A run file has no names unless it gives `"symbols": "knowledge"` or a JSON file of names. To go on from the live emulator, save its state with `c64_snapshot` action `save` and `out`, and start the run from that file. A run has the action steps of a scenario: `write`, `registers`, `joystick`, `type`, `frames` and `runUntil`. It also has these steps:
44
44
 
45
45
  | Step | Effect |
46
46
  |---|---|
@@ -122,6 +122,8 @@ node <skill>/scripts/testing.ts diff .c64-re-tools/local/runs/rooms/results.json
122
122
  - Two memory files of a run: the changed ranges. For a file of less than 64 KiB, `--address` gives the address of its first byte.
123
123
  - Two observations of runs, also of one run: the changed memory items and registers. `compared` gives the count of items that both observations have. With `compared: 0`, `reason` tells what each observation has. Then the diff compared nothing, and the observations are not equal.
124
124
 
125
+ For two snapshot files, `$00` and `$01` are the CPU port of the snapshot: the direction register and the data register. They are not the RAM under the port. `--ntsc` is only for snapshot files, and `--address` is only for memory files. The script refuses these options for the other kinds.
126
+
125
127
  `registers` gives each changed register and chip value. `cpu.pc` is a `$` address. Each CPU flag is `cpu.flags.<flag>`, for example `cpu.flags.c`, with `true` or `false`.
126
128
 
127
129
  The script refuses a snapshot that does not restore in its emulator. An example is a PAL snapshot with `--ntsc`. Give `--ntsc` only for snapshots of an NTSC machine.
@@ -159,7 +161,7 @@ The script refuses a snapshot that does not restore in its emulator. An example
159
161
  5. Run `testing.ts test`.
160
162
  6. Read the result:
161
163
  - `PASS`: all observations are equal, or the differences are in the allowed tolerance.
162
- - `FAIL`: `differences` lists each difference with the checkpoint, the item, the original value and the rebuild value.
164
+ - `FAIL`: `differences` lists each difference with the checkpoint and the item. A memory item gives `bytes`: the count of the bytes that differ, and the first of these bytes. Each byte has the address, the original value and the rebuild value. `--max-listed` sets how many bytes it lists (default 50). `memory.json` in `--out` has all of them. Another item gives the original value and the rebuild value.
163
165
  - Each value has one form. The pc and each address are `$xxxx`. Memory is lowercase hex. Other register values and chip values are decimal numbers.
164
166
  - `INCONCLUSIVE`: `reason` tells why the script could not compare. This is not a failure of the program.
165
167
  7. For a FAIL, examine the first difference with the c64-emulator skill.
@@ -189,6 +191,7 @@ PASS, FAIL or INCONCLUSIVE, the checkpoints and the smallest differences that ex
189
191
  ## Failure and conflicts
190
192
 
191
193
  - `invalid-input`: the scenario file has an error. The message names the step. Change the step and run the test again.
194
+ - INCONCLUSIVE, `step N (kind): ...`: the step failed on one side. `reason` names the step and why.
192
195
  - `invalid-input` that names the 2.0 form: a step, a memory item or a recording has a form of version 2.0. An example is `"at"` in place of `"address"`. The message gives the form to write. Change the file. Record a recording of version 2.0 again.
193
196
  - `not-found` before the run: a file of the scenario or the run file is missing, for example the rebuild program. Build the rebuild, or change the path.
194
197
  - INCONCLUSIVE, "did not reach the checkpoint": one side did not reach the checkpoint in the frame limit. Find the reason with the c64-emulator skill. Do not report a FAIL.