@henols/c64-re-tools 2.4.0-rc.1 → 2.4.0-rc.3

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 (42) hide show
  1. package/package.json +1 -1
  2. package/skills/c64-assembler/SKILL.md +6 -3
  3. package/skills/c64-assembler/scripts/assembler.ts +6 -16
  4. package/skills/c64-disk/SKILL.md +19 -4
  5. package/skills/c64-disk/scripts/disk.ts +43 -3
  6. package/skills/c64-docs/SKILL.md +3 -2
  7. package/skills/c64-docs/references/page-types.md +13 -2
  8. package/skills/c64-provenance/SKILL.md +8 -4
  9. package/skills/c64-provenance/scripts/lib/library.ts +85 -11
  10. package/skills/c64-provenance/scripts/provenance.ts +4 -3
  11. package/skills/c64-source/SKILL.md +8 -2
  12. package/skills/c64-source/scripts/lib/export.ts +3 -3
  13. package/skills/c64-source/scripts/lib/source.ts +80 -24
  14. package/skills/c64-source/scripts/source.ts +49 -8
  15. package/skills/c64-static-analysis/SKILL.md +1 -1
  16. package/skills/c64-testing/SKILL.md +11 -1
  17. package/skills/c64-testing/references/recording-format.md +5 -1
  18. package/skills/c64-testing/references/scenario-format.md +5 -3
  19. package/skills/c64-testing/scripts/lib/recording.ts +32 -6
  20. package/skills/c64-testing/scripts/lib/runs.ts +13 -7
  21. package/skills/c64-testing/scripts/lib/scenario.ts +13 -6
  22. package/skills/c64-testing/scripts/testing.ts +6 -3
  23. package/src/host/server.ts +31 -6
  24. package/src/host/tools/c1541.ts +32 -8
  25. package/src/host/vice/binary-monitor.ts +19 -7
  26. package/src/host/vice/session.ts +6 -2
  27. package/src/host-client/connect.ts +12 -2
  28. package/src/host-client/tools.ts +9 -4
  29. package/src/host-client/transfer.ts +54 -1
  30. package/src/host-client/vice-session.ts +10 -3
  31. package/src/knowledge/import.ts +28 -5
  32. package/src/knowledge/write.ts +4 -0
  33. package/src/mcp/main.ts +4 -66
  34. package/src/mcp/session-source.ts +76 -0
  35. package/src/native/acme.ts +45 -12
  36. package/src/native/c64run.ts +1 -1
  37. package/src/native/types.ts +5 -2
  38. package/src/protocol/framing.ts +15 -2
  39. package/src/protocol/messages.ts +77 -25
  40. package/src/protocol/tools.ts +33 -4
  41. package/src/protocol/vice.ts +40 -20
  42. package/tools/c64run.c +48 -12
@@ -1,6 +1,7 @@
1
1
  // ACME source from an image, current knowledge and Ghidra's instruction
2
2
  // boundaries. The same input gives the same text. Names come from
3
- // knowledge; a target that knowledge does not name gets l_xxxx. Data is
3
+ // knowledge; a target that knowledge does not name gets l_xxxx. A read or
4
+ // write in the I/O area names the register, also where the image holds RAM. Data is
4
5
  // written by its region type. The source assembles to the same bytes: the
5
6
  // generator forces operand sizes, and writes an opcode form that ACME
6
7
  // encodes differently as bytes (see the probe in source.ts). An operand
@@ -40,6 +41,8 @@ export interface SourceInput {
40
41
  platformLeftOut?: ReadonlySet<string>;
41
42
  /** The platform area of an address, and the register that an I/O mirror repeats: constants.asm groups and describes its names with them. */
42
43
  describe?: (address: number) => { area: Area; mirrorOf?: number };
44
+ /** The I/O area: a code operand there names the register, also when the image holds RAM there. */
45
+ io?: AddressRange;
43
46
  /** 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. */
44
47
  decode?: (register: number, value: number) => Record<string, unknown>;
45
48
  /** Operand expressions of the knowledge, by instruction address. */
@@ -158,7 +161,7 @@ function decodedText(decoded: Record<string, unknown>): string {
158
161
  * register with a decoder, for example "$d011: yScroll 3, rows 25". A knowledge
159
162
  * side comment at the store wins.
160
163
  */
161
- function decodedStores(pieces: readonly Piece[], input: SourceInput): Array<{ address: number; placement: CommentPlacement; text: string }> {
164
+ function decodedStores(pieces: readonly Piece[], input: SourceInput, isRegister: (address: number) => boolean): Array<{ address: number; placement: CommentPlacement; text: string }> {
162
165
  if (input.decode === undefined) return [];
163
166
  const own = new Set(input.comments.filter((comment) => comment.placement === "side").map((comment) => comment.address));
164
167
  const found: Array<{ address: number; placement: CommentPlacement; text: string }> = [];
@@ -170,8 +173,8 @@ function decodedStores(pieces: readonly Piece[], input: SourceInput): Array<{ ad
170
173
  const register = STORES[store.opcode];
171
174
  if (register === undefined || LOADS[load.opcode] !== register || load.address + load.length !== store.address || own.has(store.address)) continue;
172
175
  const target = store.length === 3 ? input.byteAt(store.address + 1) | (input.byteAt(store.address + 2) << 8) : input.byteAt(store.address + 1);
173
- // A register inside the image is RAM of the program, not the register.
174
- if (input.segments.some((segment) => target >= segment.start && target <= segment.end)) continue;
176
+ // A register inside the image is RAM of the program, not the register, unless the source names the register there.
177
+ if (!isRegister(target)) continue;
175
178
  try {
176
179
  const text = decodedText(input.decode(target, input.byteAt(load.address + 1)));
177
180
  if (text !== "") found.push({ address: store.address, placement: "side", text: `${formatC64Address(target)}: ${text}` });
@@ -215,8 +218,12 @@ export interface Layout {
215
218
  pieces: Piece[];
216
219
  /** Names of addresses: inside the image a label, outside it a constant. */
217
220
  names: Map<number, string>;
218
- /** Addresses outside the image that the source names, as constants. */
221
+ /** Addresses that the source names as constants: outside the image, and the registers in `registers`. */
219
222
  constants: number[];
223
+ /** Platform names of addresses inside the image that the source writes as constants, not as labels: a name of an operand expression, and a register of the I/O area. */
224
+ registers: Map<number, string>;
225
+ /** The operand of an instruction without an expression when it is not the name of its target: a register of the I/O area, or the plain address of the I/O area. */
226
+ operandNames: Map<number, string>;
220
227
  /** How the source uses each constant: instructions by kind, and pointer table entries. */
221
228
  uses: Map<number, Map<UseKind, number>>;
222
229
  platform: NonNullable<SourceInput["platform"]>;
@@ -364,12 +371,22 @@ export function layout(input: SourceInput): Layout {
364
371
  /** Addresses outside the image without a name of their own, inside a named platform entry of more bytes: the start of that entry. */
365
372
  const insideEntry = new Map<number, number>();
366
373
  const uses = new Map<number, Map<UseKind, number>>();
367
- const count = (constant: number, kind: UseKind) => {
368
- outside.add(constant);
374
+ const tally = (constant: number, kind: UseKind) => {
369
375
  const kinds = uses.get(constant) ?? new Map<UseKind, number>();
370
376
  kinds.set(kind, (kinds.get(kind) ?? 0) + 1);
371
377
  uses.set(constant, kinds);
372
378
  };
379
+ const count = (constant: number, kind: UseKind) => {
380
+ outside.add(constant);
381
+ tally(constant, kind);
382
+ };
383
+ /** Platform names inside the image that the source writes as constants: the register, not the RAM of the program there. */
384
+ const registers = new Map<number, string>();
385
+ const register = (address: number, name: string, kind: UseKind) => {
386
+ registers.set(address, name);
387
+ tally(address, kind);
388
+ };
389
+ const inIo = (address: number) => input.io !== undefined && address >= input.io.start && address <= input.io.end;
373
390
  /** The start of the named data region that holds an address without a name of its own: the operand is written name+offset. */
374
391
  const tableStart = (address: number) => {
375
392
  if (symbols.has(address)) return undefined;
@@ -393,6 +410,30 @@ export function layout(input: SourceInput): Layout {
393
410
  const byName = new Map<string, number>();
394
411
  for (const row of input.platform ?? []) if (!byName.has(row.name)) byName.set(row.name, row.address);
395
412
  for (const symbol of input.symbols) byName.set(symbol.name, symbol.address);
413
+ /** A platform name of an expression stays as written: inside the image it is a register constant, not the label of the RAM there. */
414
+ const useName = (name: string, kind: UseKind) => {
415
+ const address = byName.get(name)!;
416
+ if (inImage(address) && platform.get(address) === name) register(address, name, kind);
417
+ else use(address, kind);
418
+ };
419
+ /**
420
+ * The operand of an instruction without an expression. A read or a write in the
421
+ * I/O area inside the image, without a knowledge name there, is the register:
422
+ * its platform name, else the plain address. The data label of the RAM there stays.
423
+ */
424
+ const operandNames = new Map<number, string>();
425
+ const useOperand = (item: InstructionItem) => {
426
+ const value = operandValue(item.address, item.opcode, input.byteAt)!;
427
+ const kind = useKind(item.opcode);
428
+ const access = kind === "read" || kind === "written" || kind === "modified";
429
+ if (!inImage(value) || symbols.has(value) || !access) return use(value, kind);
430
+ const name = registers.get(value) ?? (inIo(value) ? platform.get(value) : undefined);
431
+ if (name !== undefined) {
432
+ register(value, name, kind);
433
+ operandNames.set(item.address, name);
434
+ } else if (inIo(value)) operandNames.set(item.address, literalOperand(item.opcode, value));
435
+ else use(value, kind);
436
+ };
396
437
  const instructionAt = new Map(pieces.flatMap((piece) => piece.items.flatMap((item) => (item.kind === "instruction" ? [[item.address, item] as const] : []))));
397
438
  /** 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. */
398
439
  const unknownNames = (missing: readonly string[], remedy: string) => {
@@ -459,19 +500,20 @@ export function layout(input: SourceInput): Layout {
459
500
  // An immediate operand builds the address of a name; any other operand uses the address as the instruction does.
460
501
  expressions.push({ address: operand.address, text: expression, kind: mode === "imm" ? "address" : useKind(item!.opcode) });
461
502
  }
462
- for (const { text: expression, kind } of expressions) for (const name of identifiers(expression)) use(byName.get(name)!, kind);
503
+ // The names of expressions and macro args come first: a platform name there names the register for the plain operands too.
504
+ for (const { text: expression, kind } of expressions) for (const name of identifiers(expression)) useName(name, kind);
505
+ for (const candidate of candidates) for (const arg of candidate.use.args) for (const name of identifiers(arg)) useName(name, "macro argument");
463
506
  // An instruction with an expression names what the expression names, not its plain target.
464
507
  const written = new Set(expressions.map((expression) => expression.address));
465
508
  for (const piece of pieces) {
466
509
  for (const item of piece.items) {
467
510
  if (item.kind === "instruction") {
468
- if (takesAddress(OPCODES[item.opcode]!.mode) && !written.has(item.address) && !inUse.has(item.address)) use(operandValue(item.address, item.opcode, input.byteAt)!, useKind(item.opcode));
511
+ if (takesAddress(OPCODES[item.opcode]!.mode) && !written.has(item.address) && !inUse.has(item.address)) useOperand(item);
469
512
  continue;
470
513
  }
471
514
  for (const pointer of pointersOf(item, input.byteAt)) use(pointer, "table");
472
515
  }
473
516
  }
474
- for (const candidate of candidates) for (const arg of candidate.use.args) for (const name of identifiers(arg)) use(byName.get(name)!, "macro argument");
475
517
  for (const symbol of input.symbols) want(symbol.address);
476
518
  // A reference target inside a named data region without its own name is that region's name plus the offset: it makes no label.
477
519
  for (const target of input.referenceTargets) want(tableStart(target) ?? target);
@@ -488,7 +530,7 @@ export function layout(input: SourceInput): Layout {
488
530
  macrosAsInstructions.push({ start: candidate.use.start, end: candidate.use.end, macro: candidate.use.macro, reason: `The source has a label at ${formatC64Address(inside)}, inside the use.` });
489
531
  for (const item of candidate.items) {
490
532
  inUse.delete(item.address);
491
- if (takesAddress(OPCODES[item.opcode]!.mode) && !written.has(item.address)) use(operandValue(item.address, item.opcode, input.byteAt)!, useKind(item.opcode));
533
+ if (takesAddress(OPCODES[item.opcode]!.mode) && !written.has(item.address)) useOperand(item);
492
534
  }
493
535
  }
494
536
  }
@@ -506,7 +548,8 @@ export function layout(input: SourceInput): Layout {
506
548
  if (inImage(address)) namedLabels++;
507
549
  continue;
508
550
  }
509
- const named = platform.get(address);
551
+ // A platform name in the I/O area, or of a register constant, is the register: the RAM of the program there gets no label of that name.
552
+ const named = inImage(address) && (inIo(address) || registers.has(address)) ? undefined : platform.get(address);
510
553
  if (named !== undefined) {
511
554
  names.set(address, named);
512
555
  if (inImage(address)) namedLabels++;
@@ -562,9 +605,14 @@ export function layout(input: SourceInput): Layout {
562
605
  // The high byte of a vector is NMINV+1. A zero-page entry keeps zero-page instructions: its constant has two digits.
563
606
  // An address inside a table keeps its own label when the source needs one there anyway, for example as the entry.
564
607
  for (const [address, start] of insideEntry) if (!wanted.has(address)) names.set(address, `${names.get(start)!}+${address - start}`);
608
+ /** The name that the source gives a name of an expression: a register constant keeps its platform name. */
609
+ const sourceName = (name: string) => {
610
+ const address = byName.get(name)!;
611
+ return registers.get(address) === name ? name : names.get(address);
612
+ };
565
613
  /** An expression with the names of this source: a name with an offset in brackets, so an operator after it keeps its meaning. */
566
614
  const sourceText = (text: string) => replaceIdentifiers(text, (name) => {
567
- const label = names.get(byName.get(name)!)!;
615
+ const label = sourceName(name)!;
568
616
  return label.includes("+") ? `(${label})` : label;
569
617
  });
570
618
  const usesWritten = new Map<number, MacroUseBlock>();
@@ -573,7 +621,7 @@ export function layout(input: SourceInput): Layout {
573
621
  for (const { address, text } of expressions) {
574
622
  const unnamed: string[] = [];
575
623
  const written = replaceIdentifiers(text, (name) => {
576
- const label = names.get(byName.get(name)!);
624
+ const label = sourceName(name);
577
625
  if (label === undefined) unnamed.push(name);
578
626
  return label === undefined ? name : label.includes("+") ? `(${label})` : label;
579
627
  });
@@ -583,13 +631,15 @@ export function layout(input: SourceInput): Layout {
583
631
  return {
584
632
  pieces,
585
633
  names,
586
- constants: [...outside].sort((a, b) => a - b),
634
+ constants: [...outside, ...registers.keys()].sort((a, b) => a - b),
635
+ registers,
636
+ operandNames,
587
637
  uses,
588
638
  platform: input.platform ?? [],
589
639
  ...(input.describe === undefined ? {} : { describe: input.describe }),
590
640
  inImage,
591
641
  byteAt: input.byteAt,
592
- comments: [...input.comments, ...decodedStores(pieces, input)],
642
+ comments: [...input.comments, ...decodedStores(pieces, input, (address) => !inImage(address) || (registers.has(address) && !symbols.has(address)))],
593
643
  ...(input.coverage === undefined ? {} : { coverage: input.coverage }),
594
644
  generatedLabels,
595
645
  namedLabels,
@@ -800,16 +850,20 @@ function dataLines(item: DataItem, layout: Layout, breaks: Set<number>): Array<{
800
850
  /** A longer name moves only its own comment, not the columns of the file. */
801
851
  const MAX_NAME_COLUMN = 24;
802
852
 
803
- /** What an address outside the image is: the comment of the knowledge, else the platform meaning, else the register that a mirror repeats. */
804
- function describeConstant(layout: Layout, address: number): string | undefined {
805
- const comments = layout.comments.filter((comment) => comment.address === address);
853
+ /**
854
+ * What a constant is: the comment of the knowledge, else the platform meaning,
855
+ * else the register that a mirror repeats. A comment inside the image is of the
856
+ * RAM there, so a register constant has the platform meaning.
857
+ */
858
+ function describeConstant(layout: Layout, address: number, name: string): string | undefined {
859
+ const comments = layout.registers.has(address) ? [] : layout.comments.filter((comment) => comment.address === address);
806
860
  // Line comments come before the side comment, as they do in the code.
807
861
  const own = [...comments.filter((comment) => comment.placement === "line"), ...comments.filter((comment) => comment.placement === "side")];
808
862
  if (own.length > 0) return own.map((comment) => comment.text.replace(/\s*\r?\n\s*/g, " ").trim()).join(" ");
809
863
  const entry = layout.platform.find((row) => address >= row.address && address <= row.end);
810
864
  if (entry?.meaning !== undefined) {
811
865
  const platformName = address === entry.address ? entry.name : `${entry.name}+${address - entry.address}`;
812
- return platformName === layout.names.get(address) ? entry.meaning : `${platformName}: ${entry.meaning}`;
866
+ return platformName === name ? entry.meaning : `${platformName}: ${entry.meaning}`;
813
867
  }
814
868
  const mirrorOf = layout.describe?.(address).mirrorOf;
815
869
  if (mirrorOf === undefined) return undefined;
@@ -918,13 +972,14 @@ function switchesText(layout: Layout): string {
918
972
  return `${out.join("\n")}\n`;
919
973
  }
920
974
 
921
- /** constants.asm: the names outside the image by platform area, each with what it is and how the source uses it. */
975
+ /** constants.asm: the names outside the image and the register constants by platform area, each with what it is and how the source uses it. */
922
976
  function constantsText(layout: Layout): { text: string; labels: SourceLabel[] } {
923
977
  const { describe } = layout;
924
978
  const labels: SourceLabel[] = [];
925
979
  const rows = layout.constants.map((address) => {
926
- const comment = [describeConstant(layout, address), usageText(layout.uses.get(address))].filter((text) => text !== undefined).join(" ");
927
- return { address, name: layout.names.get(address)!, value: constantValue(address), comment };
980
+ const name = layout.registers.get(address) ?? layout.names.get(address)!;
981
+ const comment = [describeConstant(layout, address, name), usageText(layout.uses.get(address))].filter((text) => text !== undefined).join(" ");
982
+ return { address, name, value: constantValue(address), comment };
928
983
  });
929
984
  const nameColumn = Math.min(MAX_NAME_COLUMN, Math.max(0, ...rows.map((row) => row.name.length)));
930
985
  const valueColumn = Math.max(0, ...rows.map((row) => row.value.length));
@@ -932,6 +987,7 @@ function constantsText(layout: Layout): { text: string; labels: SourceLabel[] }
932
987
  out.push(
933
988
  describe === undefined ? "; Names of addresses outside the image." : "; Names of addresses outside the image, by memory area.",
934
989
  '; "Used" counts the instructions and table entries of this source that use the name.',
990
+ ...(layout.registers.size === 0 ? [] : ["; A name of an address inside the image names the register there, not the RAM of the program."]),
935
991
  );
936
992
  // Without platform areas the names form one group.
937
993
  if (describe === undefined && rows.length > 0) out.push("");
@@ -1205,7 +1261,7 @@ export function render(layout: Layout, asBytes: ReadonlySet<string>, header: str
1205
1261
  out.push(withSide(`${INDENT}${instructionWith(item.opcode, written, form.suffix)}`, sides.length === 0 ? undefined : sides.join(" ")));
1206
1262
  result.expressions.push({ address: item.address, length: item.length, file: piece.file, line: out.length });
1207
1263
  } else {
1208
- const expression = takesAddress(mode) ? (layout.names.get(value) ?? literalOperand(item.opcode, value)) : literalOperand(item.opcode, value);
1264
+ const expression = takesAddress(mode) ? (layout.operandNames.get(item.address) ?? layout.names.get(value) ?? literalOperand(item.opcode, value)) : literalOperand(item.opcode, value);
1209
1265
  out.push(withSide(`${INDENT}${instructionWith(item.opcode, expression, form.suffix)}`, sides.length === 0 ? undefined : sides.join(" ")));
1210
1266
  }
1211
1267
  mapLine(item.address, item.address + item.length - 1);
@@ -16,6 +16,7 @@ import { basename, join, relative, sep } from "node:path";
16
16
  import { isRefusal, Refusal } from "#src/errors.ts";
17
17
  import { type AddressRange, coverageSeedKinds, findHandoffs, formatC64Address, parseTokenized, textToPetscii } from "#src/c64.ts";
18
18
  import { autostartLoaded, RUN_LIMIT_FRAMES } from "#src/host-client/autostart.ts";
19
+ import { IO_RAM } from "#src/host-client/coverage.ts";
19
20
  import { readImage, type Image } from "#src/host-client/image.ts";
20
21
  import { readProjectFile } from "#src/host-client/transfer.ts";
21
22
  import { MAX_MEMORY_READ, WireFailure } from "#src/host-client/tools.ts";
@@ -615,6 +616,27 @@ function sourceMapText(rendered: Rendered, space: string, revision: string | nul
615
616
  /** The files of the loader. Only a run with --loader writes them, so only such a run removes them. */
616
617
  const LOADER_FILES: ReadonlySet<string> = new Set(["loader.asm", "loader.prg"]);
617
618
 
619
+ /** The start of the line of loader.asm that gives the knowledge revision of the loader. */
620
+ const LOADER_REVISION = "Loader generated by c64-source from knowledge revision ";
621
+
622
+ /**
623
+ * The loader files of an earlier run that a run without --loader keeps, when
624
+ * the generated loader.asm is of another knowledge revision: the loader can
625
+ * then copy other bytes than the source has. Undefined when there is no
626
+ * generated loader.asm, or it is of this revision.
627
+ */
628
+ function staleLoader(out: string, revision: string): { files: string[]; revision?: string } | undefined {
629
+ const path = resolveProjectPath(`${out}/loader.asm`);
630
+ if (!existsSync(path)) return undefined;
631
+ const text = readFileSync(path, "utf8");
632
+ if (!text.startsWith(GENERATED_MARK)) return undefined;
633
+ const line = text.split(/\r?\n/).find((row) => row.startsWith(`; ${LOADER_REVISION}`));
634
+ const old = line?.slice(`; ${LOADER_REVISION}`.length).replace(/\.$/, "");
635
+ if (old === revision) return undefined;
636
+ const files = [...LOADER_FILES].filter((name) => existsSync(resolveProjectPath(`${out}/${name}`))).map((name) => `${out}/${name}`);
637
+ return { files, ...(old === undefined ? {} : { revision: old }) };
638
+ }
639
+
618
640
  /**
619
641
  * Removes the generated .asm files of an earlier run that this run does not
620
642
  * write, and an earlier not_executed.json and source-map.json. An earlier
@@ -691,7 +713,7 @@ async function buildSource(knowledge: SourceKnowledge, options: SourceOptions) {
691
713
  macroUses: knowledge.macroUses,
692
714
  ...(coverage === undefined || !options.notExecutedMarks ? {} : { coverage }),
693
715
  // The platform names are C64 names: drive code and banks get none. A ROM that the program does not use gives none.
694
- ...(space === DEFAULT_SPACE ? { platform, platformLeftOut: leftOutNames(platform), describe: describeAddress, decode: decodeRegister } : {}),
716
+ ...(space === DEFAULT_SPACE ? { platform, platformLeftOut: leftOutNames(platform), describe: describeAddress, decode: decodeRegister, io: IO_RAM } : {}),
695
717
  });
696
718
  const asBytes = await probe(laid);
697
719
  const { header } = options;
@@ -785,7 +807,7 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
785
807
  // Every build that is compared with the program is the build of the base release: each switch at its base value.
786
808
  const baseValues = new Map(knowledge.switches.map((row) => [row.name, row.base]));
787
809
  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."];
788
- const loaderHeader = [`Loader generated by c64-source from knowledge revision ${knowledge.revision}.`, "It copies the segments into place, sets the entry state and jumps to the entry."];
810
+ const loaderHeader = [`${LOADER_REVISION}${knowledge.revision}.`, "It copies the segments into place, sets the entry state and jumps to the entry."];
789
811
  const { romUse, dataOnly, laid, rendered, files, built, loader, missingEntry, loaderRefused } = await buildSource(knowledge, {
790
812
  space,
791
813
  entries,
@@ -801,6 +823,7 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
801
823
  const kept = new Map(laid.switches.flatMap((row) => (given.has(row.name) ? [[row.name, given.get(row.name)!] as const] : [])));
802
824
  const notDefault = laid.switches.flatMap((row) => (kept.has(row.name) && kept.get(row.name) !== row.default ? [{ name: row.name, value: kept.get(row.name)!, default: row.default }] : []));
803
825
  const removed = removeOldFiles(out, new Set(files.map((file) => file.name)), loaderWanted).map((name) => `${out}/${name}`);
826
+ const stale = loaderWanted || space !== DEFAULT_SPACE ? undefined : staleLoader(out, knowledge.revision);
804
827
  const written: Written[] = withValues(files, laid, kept).map((file) => writeReported(`${out}/${file.name}`, file.text, { what: "--out" }));
805
828
  written.push(writeReported(`${out}/${SOURCE_MAP_FILE}`, sourceMapText(rendered, space, knowledge.revision, files), { what: "--out" }));
806
829
  const showRange = (range: AddressRange) => ({ start: formatC64Address(range.start), end: formatC64Address(range.end) });
@@ -826,6 +849,8 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
826
849
  // The values that config.asm keeps and that are not the default: a build of the source is not the default build.
827
850
  ...(notDefault.length === 0 ? {} : { config: { file: `${out}/${CONFIG_FILE}`, notDefault } }),
828
851
  revision: knowledge.revision,
852
+ // A run without --loader keeps the loader of an earlier run: one of another revision is stale.
853
+ ...(stale === undefined ? {} : { staleLoader: { ...stale, ...(image.state === undefined || image.entry === undefined ? { noEntryState: true } : {}) } }),
829
854
  instructions: rendered.instructions,
830
855
  dataBytes: rendered.dataBytes,
831
856
  ...(rendered.undecodedBytes === 0 ? {} : { undecodedBytes: rendered.undecodedBytes }),
@@ -923,7 +948,16 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
923
948
  written.push(writeReported(loaderPath, program, { what: "--out" }));
924
949
  // The unpack runs before the copier.
925
950
  const copierFrames = packed === undefined ? RUN_LIMIT_FRAMES : packed.cycles === undefined ? LOADER_FRAMES : RUN_LIMIT_FRAMES + Math.ceil(packed.cycles / PAL_FRAME_CYCLES);
926
- const ran = await runLoader(loaderPath, program, loader, image, state, { jump, copierSource, fileByte, copierFrames }, expected);
951
+ let ran: LoaderRun;
952
+ try {
953
+ ran = await runLoader(loaderPath, program, loader, image, state, { jump, copierSource, fileByte, copierFrames }, expected);
954
+ } catch (error) {
955
+ // A loader.prg without its check does not stay: it looks like a checked loader.
956
+ rmSync(resolveProjectPath(loaderPath), { force: true });
957
+ written.splice(written.findIndex((file) => file.out === loaderPath), 1);
958
+ if (!isRefusal(error)) throw error;
959
+ return { output: { ...output, loader: { verified: false, reason: `The check of loader.prg did not run, so the script removed loader.prg. ${error.message}` } }, removed, failed: true };
960
+ }
927
961
  output.loader = {
928
962
  program: loaderPath,
929
963
  ...(packed === undefined ? {} : { packed: { packedBytes: packed.packedBytes, unpackedBytes: packed.unpackedBytes } }),
@@ -1224,7 +1258,7 @@ function isCut(list: unknown): boolean {
1224
1258
  }
1225
1259
 
1226
1260
  /** The same generate command line again, for the run after a change of the knowledge. */
1227
- function generateAgain(call: Call): string {
1261
+ function generateAgain(call: Call, loader = call.flag("loader")): string {
1228
1262
  const max = call.count("max-listed")!;
1229
1263
  return call.next(
1230
1264
  "generate",
@@ -1232,7 +1266,7 @@ function generateAgain(call: Call): string {
1232
1266
  call.string("out")!,
1233
1267
  ...call.addresses("entry").flatMap((entry) => ["--entry", formatC64Address(entry)]),
1234
1268
  ...(call.space === DEFAULT_SPACE ? [] : ["--space", call.space]),
1235
- ...(call.flag("loader") ? ["--loader"] : []),
1269
+ ...(loader ? ["--loader"] : []),
1236
1270
  ...(call.flag("analyzer-names") ? ["--analyzer-names"] : []),
1237
1271
  ...(max === OPTIONS["max-listed"].default ? [] : ["--max-listed", String(max)]),
1238
1272
  );
@@ -1281,9 +1315,16 @@ function generateReply(call: Call, body: Record<string, unknown>): Reply {
1281
1315
  again = true;
1282
1316
  }
1283
1317
  if ([body.asBytes, body.operandsAsNumbers, body.macrosAsInstructions, body.patchesNotWritten].some(isCut)) steps.push("To see all items of a list, give a larger --max-listed.");
1284
- if (steps.length === 0) return reply(body, { hint: "Read the source. Record names, comments, regions and modules in the project knowledge. Then generate again." });
1318
+ const staleLoader = body.staleLoader as { noEntryState?: boolean } | undefined;
1319
+ if (steps.length === 0 && staleLoader === undefined) return reply(body, { hint: "Read the source. Record names, comments, regions and modules in the project knowledge. Then generate again." });
1285
1320
  if (again) steps.push("Then generate again.");
1286
- return reply(body, { hint: steps.join(" "), ...(again ? { nextAction: generateAgain(call) } : {}) });
1321
+ // The run with --loader writes the loader again, so it is the next action also for the other findings.
1322
+ const loaderAgain = staleLoader !== undefined && staleLoader.noEntryState !== true;
1323
+ if (staleLoader !== undefined) {
1324
+ steps.push("The loader files in staleLoader.files are of another knowledge revision, and the run kept them.");
1325
+ steps.push(loaderAgain ? "To write the loader of this revision, generate with --loader." : "The knowledge has no entry state, so --loader cannot write them again. Remove them when the build does not use them.");
1326
+ }
1327
+ return reply(body, { hint: steps.join(" "), ...(again || loaderAgain ? { nextAction: generateAgain(call, call.flag("loader") || loaderAgain) } : {}) });
1287
1328
  }
1288
1329
 
1289
1330
  /** The hint of an export result: the action for a failed stage, or the next steps for the new project. */
@@ -1316,7 +1357,7 @@ await runScript({
1316
1357
  out: { ...OPTIONS.out, output: "folder", value: "<dir>", help: "the folder for the source files, relative to the project folder", required: true },
1317
1358
  entry: { ...OPTIONS.entry, multiple: true, help: "an address where code starts. The entry of the program, the routines and the code regions of the knowledge are entry points too" },
1318
1359
  space: { ...OPTIONS.space, help: "the knowledge space of the program: c64 (the default), drive8, or bank0 to bank255. The coverage and --loader are for c64 only" },
1319
- loader: { kind: "flag", help: "also write loader.asm and loader.prg: the loader copies the segments into place, sets the entry state of the knowledge, and jumps to the entry. It is checked in the emulator" },
1360
+ loader: { kind: "flag", help: "also write loader.asm and loader.prg: the loader copies the segments into place, sets the entry state of the knowledge, and jumps to the entry. It is checked in the emulator. When the check cannot run, the script removes loader.prg" },
1320
1361
  "analyzer-names": { kind: "flag", help: "name an address that has no name of the user or the LLM, and no platform name, with its analyzer name" },
1321
1362
  "max-listed": OPTIONS["max-listed"],
1322
1363
  },
@@ -100,7 +100,7 @@ The script records only structure: code and data regions, analyzer names, and th
100
100
  - `analyzer`: `dxa` or `ghidra`. `space` is in `body` only for a space that is not `c64`.
101
101
  - `revision`: the revision of the findings, or `null` when the knowledge did not change.
102
102
  - `coverage`: the ranges that the analyzer examined.
103
- - `changes`: for analyzer names (`names`), `regions` and `references`, the counts `added`, `changed`, `retired`, `unchanged` and `suppressed`. `suppressed` counts the findings that the script did not record, because the user or the LLM removed a fact at that place. `symbols.retired` counts the old symbols of the analyzer that became analyzer names.
103
+ - `changes`: for analyzer names (`names`), `regions` and `references`, the counts `added`, `changed`, `retired`, `unchanged` and `suppressed`. `suppressed` counts the findings that the script did not record, because the user or the LLM removed a fact at that place. `references.inData` counts the references that the script did not record, because they start in a data region of the user, the LLM or a heuristic. The analyzer decoded these data bytes as code. `symbols.retired` counts the old symbols of the analyzer that became analyzer names.
104
104
  - `conflicts`: each place where the analyzer and the project knowledge disagree. `problem` tells the disagreement.
105
105
  - `coverageSeeds`: only with coverage. `entryPoints` and `used` give how many entry points the coverage gave, and how many the analysis used. `romOnlyRanges` and `romOnlyUsed` give the same counts for the data ranges under ROM.
106
106
  - `coverageConflicts`: only with coverage. Each analyzer data region where the coverage shows executed code.
@@ -136,6 +136,14 @@ Traps:
136
136
 
137
137
  The script does the steps of the run file on one program, with no comparison. It writes the files of the steps and `results.json` into `--out`. One run replaces many emulator calls, for example a visit to each room of a game.
138
138
  The run starts from a program or from a snapshot file. To continue from the state of the emulator, save that state to a snapshot file in the emulator. Then start the run from that file.
139
+
140
+ A run file must have `name`, `start` and `steps`:
141
+
142
+ ```json
143
+ { "name": "rooms", "start": { "program": "game.prg" }, "steps": [{ "frames": 100 }, { "screen": "title" }] }
144
+ ```
145
+
146
+ `symbols` and `videoStandard` are optional. The section "Runs" of `references/scenario-format.md` gives each key and step.
139
147
  Before the run starts, the script examines the run file, each file that it names and each name of the steps. The section "Checks" of `references/scenario-format.md` gives each refusal.
140
148
 
141
149
  `body` holds:
@@ -190,6 +198,7 @@ The script does the steps of the record file on the original program. Then it wr
190
198
  - `out` and `files`: the recording folder and its files.
191
199
  - `frames`, `inputSites` and `events`: the length of the session, the number of instructions that read input, and the number of events.
192
200
  - `executed`: the number of instructions in the coverage map.
201
+ - `coverageFrom`: the `frame` and the `pc` where the coverage map starts. `null` when the coverage did not start.
193
202
  - `reason`: with a FAIL, why the session did not complete.
194
203
 
195
204
  Do this for each result:
@@ -197,7 +206,7 @@ Do this for each result:
197
206
  - `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.
198
207
  - `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.
199
208
  - 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.
200
- - `executed` is 0: the program never read its input from RAM, so the coverage map is empty. The recording can still replay.
209
+ - `coverageFrom` is `null` and `executed` is 0: the coverage did not start, so the coverage map is empty. The recording can still replay.
201
210
 
202
211
  With `--play`, a person plays the program after the steps. The steps can start the program, for example a key for an intro.
203
212
 
@@ -210,6 +219,7 @@ With `--play`, a person plays the program after the steps. The steps can start t
210
219
 
211
220
  Traps:
212
221
 
222
+ - By default, the coverage map starts at the first input read of code in RAM. The start-up code of the program ran before that point, and it has no marks in the map. Do not think that this code did not run. To include it, give `"coverage": "start"` or a `$` address in the record file.
213
223
  - Put a `runUntil` step with the checkpoint routine before a `registers` step. A `registers` step that sets the pc during an interrupt stops the program.
214
224
  - A record file has no `raster` target and no `condition`. The script refuses them.
215
225
 
@@ -26,6 +26,10 @@ A record file is one JSON object in a project file.
26
26
  - `load`: optional. With `false` (default), the program must load at `$0801` with a BASIC start line, and the C64 types `RUN`. With `true`, the program goes into memory and the C64 stays at READY. Then a `registers` step with `pc` starts the program.
27
27
  - `checkpoint`, `state` and `pin`: optional. The comparison that a replay uses when the replay gives none. `checkpoint` is the name or `$` address of a routine. Each entry of the routine is a checkpoint. `state` is 1 to 16 memory items that the checkpoints compare. `pin` is the random state in RAM. An item is a name, a `$` address, or `{ "address", "size" }` with a size from 1 to 4096. Give `checkpoint` and `state` together.
28
28
  - `inputs`: optional. The I/O addresses (or ranges such as `$de00-$dfff`) whose reads are input. The default is `$dc00` and `$dc01`: the joystick ports and the keyboard matrix. It also has `$d419` to `$d41c` (the paddles, and the noise and envelope of SID voice 3), and `$de00-$dfff` (no device: the last byte on the bus). Add `$d012` or a CIA timer only for a program that reads a seed there and does not wait in a loop on it.
29
+ - `coverage`: optional. Where the coverage map starts:
30
+ - `input` (default): at the first input read of code in RAM. The start-up code of the program, for example a loader, a relocation or an initialization, is not in the map.
31
+ - `start`: when the program starts, after `RUN` or at the `registers` step of `load` `true`.
32
+ - A `$` address, for example `"$1aed"`: at the first execution of that address.
29
33
  - `steps`: the steps.
30
34
 
31
35
  ## Steps
@@ -99,7 +103,7 @@ The page sends input only between Start and End. The input of the page goes into
99
103
  |---|---|
100
104
  | `recording.json` | The program and its SHA-256, the symbols, and the comparison of the record file. Also the inputs, the events, the input sites, the cycles of the session and the state hash at its end. |
101
105
  | `reads.txt` | One line `<site> <addr> <from> <value>` for each change of the value at a site. From the read with the index `<from>`, the reads at `<site>` from `<addr>` get `<value>`. One line `end <site> <addr> <count>` for each site gives its number of reads. |
102
- | `coverage.bin` | The coverage map of the session: 65536 bytes, one for each address, in the format of the coverage maps of the emulator. It starts at the first input read of code in RAM, thus after a loader or a relocation. |
106
+ | `coverage.bin` | The coverage map of the session: 65536 bytes, one for each address, in the format of the coverage maps of the emulator. It starts where the key `coverage` of the record file tells. The code before that point has no marks. |
103
107
 
104
108
  A site is the address of the instruction that reads. The values are hex. `<from>` and `<count>` are decimal.
105
109
 
@@ -90,11 +90,11 @@ A `pc` value is an address. Compare `pc` only when both programs have the code a
90
90
 
91
91
  A run file is one JSON object in a project file. It has:
92
92
 
93
- - `name`: a short name.
94
- - `start`: `{ "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" }`.
93
+ - `name`: required. A short name, a non-empty string.
94
+ - `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
95
  - `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
96
  - `videoStandard`: optional, `pal` (default) or `ntsc`.
97
- - `steps`: the steps `write`, `registers`, `joystick`, `type`, `frames` and `runUntil` of a scenario, and the run steps `snapshot`, `save`, `screen`, `coverage`, `trace`, `observe` and `expect`.
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`.
98
98
 
99
99
  The run steps have these effects:
100
100
 
@@ -173,6 +173,8 @@ Example: visit two rooms from the same start.
173
173
 
174
174
  The script checks the scenario before it does a step. A step with an unknown key or a wrong value stops the script with `invalid-input`. The message names the step.
175
175
 
176
+ A scenario file or a run file with an unknown key also stops the script with `invalid-input`. The message names the key and gives the keys of the file. A missing or wrong `name`, `start` or `steps` gives the form of that key.
177
+
176
178
  The script also examines each file before it does a step: the program and the symbols of each side, and each snapshot file. A missing file stops the script with `not-found`. A program that is not a PRG, for example a disk image, stops the script with `invalid-input`. A snapshot file that is not a `.vsf` snapshot file also stops the script with `invalid-input`. The message names the step and the file.
177
179
 
178
180
  A run also examines each name of its steps before it does a step. An unknown name stops the run with `invalid-input`, and the message names the step. In a scenario, a side that does not have a name gives INCONCLUSIVE, and `reason` names the step.
@@ -12,7 +12,7 @@ import { createHash } from "node:crypto";
12
12
  import { readFileSync, writeFileSync } from "node:fs";
13
13
 
14
14
  import { isRefusal, Refusal } from "#src/errors.ts";
15
- import { formatC64Address, parseC64Address } from "#src/c64.ts";
15
+ import { c64AddressOf, formatC64Address, parseC64Address } from "#src/c64.ts";
16
16
  import { READY_FRAMES } from "#src/host-client/entry-state.ts";
17
17
  import { ACTION_STEP_KINDS, checkActionStep, isInteger, isObject, keyboardBytes, renamedField, stepKind, type ActionStep, type Location } from "#src/host-client/steps.ts";
18
18
  import { readProjectFile, type Written } from "#src/host-client/transfer.ts";
@@ -57,9 +57,22 @@ export interface RecordFile {
57
57
  /** The comparison that a replay uses when it gets none: the checkpoint routine and the state. */
58
58
  compare?: Comparison;
59
59
  inputs: string[];
60
+ /** Where the coverage map starts: "input", "start", or a "$xxxx" address (see COVERAGE_COMMANDS). */
61
+ coverage: string;
60
62
  steps: ActionStep[];
61
63
  }
62
64
 
65
+ /**
66
+ * The commands of the replay core that start the coverage map. "input": at the
67
+ * first input read of code in RAM, after a loader or a relocation. "start":
68
+ * when the program starts, with RUN (or the registers step of load true). An
69
+ * address: at the first execution of that address.
70
+ */
71
+ const COVERAGE_COMMANDS = new Map([
72
+ ["input", "coverage on-input"],
73
+ ["start", "coverage on"],
74
+ ]);
75
+
63
76
  /**
64
77
  * What a replay compares: the state at each entry of a routine, for example the
65
78
  * main loop of a game. `pin` is random state in RAM (a seed, a pointer into a
@@ -193,7 +206,7 @@ export function readRecordFile(path: string): RecordFile {
193
206
  return fail((error as Error).message);
194
207
  }
195
208
  if (!isObject(value)) return fail("it must be a JSON object");
196
- const known = ["name", "program", "symbols", "load", "checkpoint", "state", "pin", "inputs", "steps"];
209
+ const known = ["name", "program", "symbols", "load", "checkpoint", "state", "pin", "inputs", "coverage", "steps"];
197
210
  for (const key of Object.keys(value)) if (!known.includes(key)) fail(`it has the key ${key}; a record file has ${known.join(", ")}`);
198
211
  if (typeof value.name !== "string" || value.name === "") fail("name must be a short text");
199
212
  if (typeof value.program !== "string" || value.program === "") fail("program must be a PRG file in the project");
@@ -205,6 +218,10 @@ export function readRecordFile(path: string): RecordFile {
205
218
  const pin = value.pin === undefined ? undefined : checkState(value.pin, fail, "pin");
206
219
  const compare = value.checkpoint === undefined ? undefined : { checkpoint: value.checkpoint as string, state: checkState(value.state, fail), ...(pin === undefined ? {} : { pin }) };
207
220
  const inputs = checkInputs(value.inputs, fail);
221
+ const coverage = value.coverage ?? "input";
222
+ if (typeof coverage !== "string" || (!COVERAGE_COMMANDS.has(coverage) && c64AddressOf(coverage) === undefined)) {
223
+ fail(`coverage must be "input" (default), "start" or a $ address such as "$1aed", not ${JSON.stringify(coverage)}`);
224
+ }
208
225
  if (!Array.isArray(value.steps) || value.steps.length === 0) fail("steps must be a list with at least one step");
209
226
  const steps = (value.steps as unknown[]).map((raw, index) => {
210
227
  const at = `step ${index + 1}`;
@@ -219,6 +236,7 @@ export function readRecordFile(path: string): RecordFile {
219
236
  load: value.load === true,
220
237
  ...(compare === undefined ? {} : { compare }),
221
238
  inputs,
239
+ coverage: coverage as string,
222
240
  steps,
223
241
  };
224
242
  }
@@ -444,6 +462,8 @@ export interface RecordOutcome {
444
462
  recording: Recording;
445
463
  reads: Uint8Array;
446
464
  coverage: Uint8Array;
465
+ /** The cycle and the instruction at which the coverage map started; none when it never started. */
466
+ coverageFrom?: { tick: number; pc: number };
447
467
  /** Why the session did not complete (a runUntil that did not reach its target). */
448
468
  reason?: string;
449
469
  }
@@ -471,11 +491,10 @@ export async function record(
471
491
  const coverage = workspace.path(RECORDING_FILES.coverage);
472
492
  await core.init();
473
493
  await core.command(`inputs ${inputsArgument(file.inputs)}`);
474
- // The coverage starts at the first input read of code in RAM: then the program has done its
475
- // own start (a loader, a relocation), so the map holds the work of the program.
476
- await core.command("coverage on-input");
477
494
  await core.command(`record ${reads}`);
478
495
  await startProgram(core, prg, file.load ?? false);
496
+ // From READY on: the start of the C64 itself is never in the map.
497
+ await core.command(COVERAGE_COMMANDS.get(file.coverage) ?? `coverage on-pc ${hex(parseC64Address(file.coverage))}`);
479
498
  const events: RecordedEvent[] = [];
480
499
  const masks = [0, 0];
481
500
  let reason: string | undefined;
@@ -532,6 +551,7 @@ export async function record(
532
551
  return { site: `$${site}`, addr: `$${addr}`, reads: Number(reads), rom: kind === "rom" };
533
552
  });
534
553
  await core.command("record off");
554
+ const from = /from tick=(\d+) pc=([0-9a-f]{4})/.exec(await core.command("coverage status"));
535
555
  await core.command(`coverage ${coverage}`);
536
556
  const recording: Recording = {
537
557
  format: RECORDING_FORMAT,
@@ -547,7 +567,13 @@ export async function record(
547
567
  ticks: end.tick,
548
568
  hash: end.hash,
549
569
  };
550
- return { recording, reads: readFileSync(reads), coverage: readFileSync(coverage), ...(reason === undefined ? {} : { reason }) };
570
+ return {
571
+ recording,
572
+ reads: readFileSync(reads),
573
+ coverage: readFileSync(coverage),
574
+ ...(from === null ? {} : { coverageFrom: { tick: Number(from[1]), pc: Number.parseInt(from[2]!, 16) } }),
575
+ ...(reason === undefined ? {} : { reason }),
576
+ };
551
577
  }
552
578
 
553
579
  /** One side of a replay. */