@henols/c64-re-tools 2.8.0-rc.2 → 2.8.0-rc.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 (119) hide show
  1. package/package.json +1 -1
  2. package/skills/c64-assembler/SKILL.md +5 -2
  3. package/skills/c64-assembler/scripts/assembler.ts +55 -48
  4. package/skills/c64-disk/scripts/disk.ts +3 -3
  5. package/skills/c64-disk/scripts/lib/containers.ts +2 -2
  6. package/skills/c64-docs/SKILL.md +1 -1
  7. package/skills/c64-docs/scripts/docs.ts +12 -20
  8. package/skills/c64-docs/scripts/lib/links.ts +1 -1
  9. package/skills/c64-docs/scripts/lib/markdown.ts +1 -1
  10. package/skills/c64-docs/scripts/lib/reference.ts +59 -13
  11. package/skills/c64-knowledge/SKILL.md +17 -8
  12. package/skills/c64-knowledge/scripts/knowledge.ts +200 -218
  13. package/skills/c64-knowledge/scripts/lib/check.ts +2 -3
  14. package/skills/c64-knowledge/scripts/lib/listing.ts +56 -24
  15. package/skills/c64-packer/scripts/packer.ts +3 -3
  16. package/skills/c64-provenance/SKILL.md +25 -16
  17. package/skills/c64-provenance/scripts/lib/compare.ts +31 -21
  18. package/skills/c64-provenance/scripts/lib/leftovers.ts +17 -35
  19. package/skills/c64-provenance/scripts/lib/library.ts +10 -10
  20. package/skills/c64-provenance/scripts/lib/runtime.ts +3 -14
  21. package/skills/c64-provenance/scripts/provenance.ts +129 -98
  22. package/skills/c64-source/references/loader.md +2 -1
  23. package/skills/c64-source/scripts/lib/export.ts +54 -303
  24. package/skills/c64-source/scripts/lib/loader.ts +31 -51
  25. package/skills/c64-source/scripts/lib/source.ts +51 -41
  26. package/skills/c64-source/scripts/lib/stage.ts +9 -25
  27. package/skills/c64-source/scripts/source.ts +134 -294
  28. package/skills/c64-static-analysis/SKILL.md +12 -7
  29. package/skills/c64-static-analysis/scripts/lib/coverage.ts +1 -3
  30. package/skills/c64-static-analysis/scripts/lib/findings.ts +16 -3
  31. package/skills/c64-static-analysis/scripts/lib/idioms.ts +82 -10
  32. package/skills/c64-static-analysis/scripts/lib/triage.ts +112 -0
  33. package/skills/c64-static-analysis/scripts/static-analysis.ts +239 -147
  34. package/skills/c64-testing/SKILL.md +13 -7
  35. package/skills/c64-testing/scripts/lib/diff-files.ts +6 -13
  36. package/skills/c64-testing/scripts/lib/recording.ts +47 -66
  37. package/skills/c64-testing/scripts/lib/replay.ts +53 -9
  38. package/skills/c64-testing/scripts/lib/runs.ts +11 -29
  39. package/skills/c64-testing/scripts/lib/scenario.ts +30 -31
  40. package/skills/c64-testing/scripts/lib/start-screen.ts +42 -5
  41. package/skills/c64-testing/scripts/testing.ts +32 -7
  42. package/skills/c64-unpacker/SKILL.md +10 -7
  43. package/skills/c64-unpacker/scripts/lib/evidence.ts +23 -38
  44. package/skills/c64-unpacker/scripts/lib/loads.ts +24 -39
  45. package/skills/c64-unpacker/scripts/lib/machine.ts +38 -18
  46. package/skills/c64-unpacker/scripts/lib/stages.ts +142 -41
  47. package/skills/c64-unpacker/scripts/unpacker.ts +85 -68
  48. package/skills/emulator/SKILL.md +1 -0
  49. package/src/c64.ts +117 -10
  50. package/src/cli/ap-sdk.ts +1 -1
  51. package/src/cli/cleanup.ts +4 -2
  52. package/src/compare.ts +36 -16
  53. package/src/errors.ts +10 -1
  54. package/src/host/main.ts +2 -1
  55. package/src/host/server.ts +7 -11
  56. package/src/host/tools/c1541.ts +9 -3
  57. package/src/host/vice/adapter.ts +20 -43
  58. package/src/host/vice/binary-monitor.ts +22 -21
  59. package/src/host/vice/process.ts +31 -40
  60. package/src/host/vice/session.ts +187 -247
  61. package/src/host/vice/text-monitor.ts +3 -3
  62. package/src/host-client/autostart.ts +1 -1
  63. package/src/host-client/connect.ts +2 -1
  64. package/src/host-client/coverage.ts +0 -3
  65. package/src/host-client/entry-state.ts +4 -11
  66. package/src/host-client/image.ts +6 -11
  67. package/src/host-client/steps.ts +13 -113
  68. package/src/host-client/tools.ts +4 -4
  69. package/src/host-client/transfer.ts +10 -0
  70. package/src/host-client/vice-session.ts +10 -6
  71. package/src/knowledge/code-reach.ts +364 -0
  72. package/src/knowledge/conflicts.ts +34 -72
  73. package/src/knowledge/database.ts +40 -28
  74. package/src/knowledge/evidence.ts +2 -2
  75. package/src/knowledge/graph.ts +3 -3
  76. package/src/knowledge/history.ts +50 -90
  77. package/src/knowledge/import.ts +43 -71
  78. package/src/knowledge/join.ts +1 -1
  79. package/src/knowledge/names.ts +12 -7
  80. package/src/knowledge/program.ts +25 -46
  81. package/src/knowledge/read.ts +104 -100
  82. package/src/knowledge/schema.ts +9 -3
  83. package/src/knowledge/separate.ts +47 -19
  84. package/src/knowledge/start-screen.ts +7 -5
  85. package/src/knowledge/text.ts +56 -33
  86. package/src/knowledge/write.ts +274 -515
  87. package/src/loader.ts +7 -25
  88. package/src/mcp/inputs.ts +3 -3
  89. package/src/mcp/server.ts +19 -38
  90. package/src/mcp/session-source.ts +2 -1
  91. package/src/mcp/tools/debug.ts +97 -24
  92. package/src/mcp/tools/execution.ts +1 -1
  93. package/src/mcp/tools/input.ts +3 -3
  94. package/src/mcp/tools/machine.ts +3 -3
  95. package/src/mcp/tools/media.ts +4 -4
  96. package/src/mcp/tools/memory.ts +13 -17
  97. package/src/mcp/tools/video.ts +11 -25
  98. package/src/native/acme.ts +3 -3
  99. package/src/native/c64run.ts +2 -1
  100. package/src/native/decompiler/analyze.ts +10 -7
  101. package/src/native/decompiler/walk.ts +3 -4
  102. package/src/native/decompiler/wasm.ts +2 -2
  103. package/src/native/discover.ts +1 -1
  104. package/src/native/dxa.ts +9 -11
  105. package/src/native/exomizer.ts +1 -1
  106. package/src/native/processes.ts +4 -1
  107. package/src/native/run.ts +3 -3
  108. package/src/native/types.ts +5 -6
  109. package/src/opcodes.ts +3 -0
  110. package/src/platform.ts +9 -10
  111. package/src/program-code.ts +151 -0
  112. package/src/project.ts +8 -5
  113. package/src/protocol/framing.ts +51 -18
  114. package/src/protocol/messages.ts +1 -11
  115. package/src/protocol/tools.ts +0 -3
  116. package/src/protocol/vice.ts +588 -773
  117. package/src/script.ts +9 -14
  118. package/src/time.ts +1 -1
  119. package/src/trace.ts +3 -2
@@ -6,27 +6,24 @@
6
6
  // writes the memory into the project. "loads" captures each part of a
7
7
  // multi-load program. No native unpack tool is used.
8
8
 
9
- import { type AddressRange, COVERAGE, EXECUTE, formatC64Address, READ, WRITE } from "#src/c64.ts";
9
+ import { type AddressRange, COVERAGE, EXECUTE, formatC64Address, formatC64Range, formatC64RangeFields, inRanges, parseC64Address } from "#src/c64.ts";
10
10
  import { autostartLoaded, LOAD_LIMIT_FRAMES, RUN_LIMIT_FRAMES, typeRun } from "#src/host-client/autostart.ts";
11
11
  import { IO_RAM, markIoRamWrites, readCoverage, writtenBlocks } from "#src/host-client/coverage.ts";
12
12
  import { readActionSteps, runActionStep, type ActionStep } from "#src/host-client/steps.ts";
13
13
  import { WireFailure } from "#src/host-client/tools.ts";
14
14
  import { readPrg } from "#src/host-client/image.ts";
15
- import { writeReported, type Written } from "#src/host-client/transfer.ts";
16
- import { ViceSessionClient } from "#src/host-client/vice-session.ts";
15
+ import { readMemoryInParts, ViceSessionClient } from "#src/host-client/vice-session.ts";
17
16
  import { knowledgeAt, knowledgeNames } from "#src/knowledge/names.ts";
18
17
  import { PAL_FRAME_CYCLES } from "#src/native/c64run.ts";
19
18
  import { listed, OPTIONS, reply, runScript, UsageError, type Call, type CommandSpec, type OptionSpec } from "#src/script.ts";
20
- import { basicStart, inspect, readMemoryMap, underRom, writtenThenExecuted } from "./lib/evidence.ts";
19
+ import { basicStart, inspect, writtenThenExecuted } from "./lib/evidence.ts";
21
20
  import { loads, readLoadSteps } from "./lib/loads.ts";
22
- import { callReturn, captureSegments, executedIn, inRanges, mergeMaps, stageCandidates, stagePoints, withoutRanges } from "./lib/stages.ts";
23
- import { entryStateFile, machineState, readRam, readyState, removeStaleFiles, vectorsOf } from "./lib/machine.ts";
21
+ import { callReturn, captureSegments, droppedRanges, executedIn, mergeMaps, notExecutedUnderIo, stageCandidates, stagePoints, usedAfterEntry, withoutRanges } from "./lib/stages.ts";
22
+ import { entryStateFile, machineState, readyState, vectorsOf, writeCapture } from "./lib/machine.ts";
24
23
 
25
24
  /** Written-then-executed bytes from this many on are unpacking, decrypting or relocating, not self-changing code. */
26
25
  const UNPACKED_BYTES = 256;
27
26
  const MAX_ADVANCE = 10_000;
28
- /** The most ranges one memory map read gives. */
29
- const MAX_RANGES = 1000;
30
27
 
31
28
  /** Runs the steps; the reason when a runUntil step did not reach its target. */
32
29
  async function runSteps(client: ViceSessionClient, steps: ActionStep[]): Promise<string | undefined> {
@@ -65,20 +62,14 @@ async function trace(program: string, options: { frames: number; entry?: number;
65
62
  }
66
63
  }
67
64
  const { pc } = await client.registersGet("c64");
68
- const ranges = await readMemoryMap(async (start) => {
69
- const map = await client.memmap({ action: "read", start, end: 0xffff, maxRanges: MAX_RANGES });
70
- if (!("ranges" in map)) throw new WireFailure("operation-failed", "The emulator did not give the memory map.");
71
- const ranges = map.ranges.map(({ start: from, end, flags }) => ({ start: from, end, read: (flags & READ) !== 0, write: (flags & WRITE) !== 0, execute: (flags & EXECUTE) !== 0 }));
72
- return map.next === undefined ? { ranges } : { ranges, next: map.next };
73
- });
74
- const { written, counted, bytes: count, running: atStop } = writtenThenExecuted(ranges, pc);
65
+ const { written, bytes: count, running: atStop } = writtenThenExecuted(await readCoverage(client), pc);
75
66
  // The run often ends in a KERNAL interrupt: the written code that runs next gives the range and the point after the unpacking.
76
67
  let running = atStop;
77
68
  let until = pc;
78
- if (running === undefined && counted.length > 0) {
79
- const next = await firstPcIn(client, counted);
69
+ if (running === undefined && written.length > 0) {
70
+ const next = await firstPcIn(client, written);
80
71
  if (next !== undefined) {
81
- running = counted.find((range) => next >= range.start && next <= range.end);
72
+ running = written.find((range) => next >= range.start && next <= range.end);
82
73
  until = next;
83
74
  }
84
75
  }
@@ -88,11 +79,7 @@ async function trace(program: string, options: { frames: number; entry?: number;
88
79
  traced: true,
89
80
  frames: ran,
90
81
  pc: formatC64Address(pc),
91
- writtenThenExecuted: listed(written, options.max, (range) => ({
92
- start: formatC64Address(range.start),
93
- end: formatC64Address(range.end),
94
- ...(underRom(range.start) ? { underRom: true } : {}),
95
- })),
82
+ writtenThenExecuted: listed(written, options.max, formatC64RangeFields),
96
83
  bytes: count,
97
84
  packing,
98
85
  evidence:
@@ -230,7 +217,7 @@ async function follow(
230
217
  const notStarted = await startLoaded(client, program, bytes, options.entry);
231
218
  if (notStarted !== undefined) return { stages: [], frames: 0, reached: false, failed: notStarted };
232
219
  // The map gives a write to the RAM under the I/O area as an I/O write: a compare of that RAM at each stage end finds them.
233
- const readIoRam = () => readRam(client, IO_RAM.start, IO_RAM.end - IO_RAM.start + 1);
220
+ const readIoRam = () => readMemoryInParts(client, IO_RAM.start, IO_RAM.end - IO_RAM.start + 1, "ram");
234
221
  let ioRam = await readIoRam();
235
222
  const markIoRam = async (map: Uint8Array) => {
236
223
  const now = await readIoRam();
@@ -301,9 +288,9 @@ async function follow(
301
288
  */
302
289
  const returns = async (map: Uint8Array, frames: number): Promise<number | undefined> => {
303
290
  const { sp } = await client.registersGet("c64");
304
- const stack = await readRam(client, 0x0100, 0x100);
291
+ const stack = await readMemoryInParts(client, 0x0100, 0x100, "ram");
305
292
  const pushed = stack[(sp + 1) & 0xff]! | (stack[(sp + 2) & 0xff]! << 8);
306
- const [opcode] = await readRam(client, (pushed - 2) & 0xffff, 1);
293
+ const [opcode] = await readMemoryInParts(client, (pushed - 2) & 0xffff, 1, "ram");
307
294
  const back = callReturn(stack, sp, () => opcode!, (address) => ((stage.map[address]! | map[address]!) & COVERAGE.ramExecute) !== 0);
308
295
  if (back === undefined) return undefined;
309
296
  await arm({ exec: [], watch: [] });
@@ -474,13 +461,12 @@ async function follow(
474
461
  return { stages: found, frames: total, reached, ...(halted === undefined ? {} : { halted }), ...(untilRan === undefined ? {} : { untilRan }) };
475
462
  }
476
463
 
477
- const showRange = (range: { start: number; end: number }) => ({ start: formatC64Address(range.start), end: formatC64Address(range.end) });
478
464
  const showStages = (stages: Stage[]) =>
479
465
  stages.map((stage, index) => ({
480
466
  stage: index,
481
467
  entry: formatC64Address(stage.entry),
482
468
  frames: stage.frames,
483
- wrote: stage.wrote.map(showRange),
469
+ wrote: stage.wrote.map(formatC64RangeFields),
484
470
  ...(stage.next === undefined ? {} : { next: formatC64Address(stage.next) }),
485
471
  }));
486
472
 
@@ -516,6 +502,28 @@ async function stages(program: string, options: { frames: number; entry?: number
516
502
  }
517
503
  }
518
504
 
505
+ /** Frames that the program runs after its entry to show the memory that it uses. */
506
+ const AFTER_ENTRY_FRAMES = 250;
507
+
508
+ const ENTRY_SNAPSHOT = "capture-entry";
509
+
510
+ /**
511
+ * Runs the program on from its entry and gives the RAM that it used: the
512
+ * evidence that a block that a loader or a stage left is part of the
513
+ * program. The machine then goes back to the entry.
514
+ */
515
+ async function usedAfter(client: ViceSessionClient): Promise<(address: number) => boolean> {
516
+ await client.snapshot({ action: "save", name: ENTRY_SNAPSHOT });
517
+ try {
518
+ await client.memmap({ action: "clear" });
519
+ await client.execution({ action: "advance-frames", count: AFTER_ENTRY_FRAMES, space: "c64" });
520
+ return usedAfterEntry(await readCoverage(client));
521
+ } finally {
522
+ await client.snapshot({ action: "restore", name: ENTRY_SNAPSHOT });
523
+ await client.snapshot({ action: "remove", name: ENTRY_SNAPSHOT });
524
+ }
525
+ }
526
+
519
527
  /** Why a capture can wait for --until in vain: a step ran over it. */
520
528
  function passedInStep(until: number, step: number): string {
521
529
  return `The CPU executed ${formatC64Address(until)} in step ${step}, before the wait for --until started. A press step runs frames. Make the steps stop before the program gets to that address, or give an --until address that the program gets to later.`;
@@ -543,44 +551,41 @@ async function capture(
543
551
  };
544
552
  }
545
553
  // The RAM view: unpacked code is often under the ROMs or the I/O area.
546
- const memory = await readRam(client, 0x0000, 0x10000);
554
+ const memory = await readMemoryInParts(client, 0x0000, 0x10000, "ram");
547
555
  const state = await machineState(client);
548
556
  // The segments: what the stages wrote, without loader leftovers, with no overlap.
549
557
  const load = bytes[0]! | (bytes[1]! << 8);
550
- const found = options.range !== undefined ? [options.range] : captureSegments(followed.stages, registers.pc, { start: load, end: Math.min(0xffff, load + bytes.length - 3) });
558
+ const used = options.range === undefined ? await usedAfter(client) : undefined;
559
+ const found = used === undefined ? [options.range!] : captureSegments(followed.stages, registers.pc, { loaded: { start: load, end: Math.min(0xffff, load + bytes.length - 3) }, used });
551
560
  const segments = withoutRanges(found, options.exclude);
552
- const file = (path: string) => `${options.out}/${path}`;
553
- const written: Written[] = [];
554
- const write = (path: string, bytes: Uint8Array) => written.push(writeReported(file(path), bytes, { what: "--out" }));
555
- write("image.bin", memory);
556
- const files = segments.map((segment) => {
557
- const name = `segment-${segment.start.toString(16).padStart(4, "0")}-${segment.end.toString(16).padStart(4, "0")}.prg`;
558
- write(name, Buffer.concat([Buffer.from([segment.start & 0xff, segment.start >> 8]), memory.subarray(segment.start, segment.end + 1)]));
559
- return name;
560
- });
561
+ const underIo = used === undefined ? [] : notExecutedUnderIo(segments, used).map(formatC64RangeFields);
562
+ // The written ranges that the leftover rule took out of the segments. A --range takes no rule.
563
+ const dropped = (options.range === undefined ? droppedRanges(followed.stages, registers.pc, [...found, ...options.exclude]) : []).map((range) => ({
564
+ ...formatC64RangeFields(range),
565
+ writtenBy: range.writtenBy,
566
+ stageEntry: formatC64Address(range.stageEntry),
567
+ }));
561
568
  const vectors = vectorsOf(state, memory);
562
- write(
563
- "image.json",
564
- Buffer.from(
565
- `${JSON.stringify(
566
- {
567
- entry: formatC64Address(registers.pc),
568
- segments: segments.map((segment, index) => ({ ...showRange(segment), ...("writtenBy" in segment ? { writtenBy: segment.writtenBy } : {}), ...("loaded" in segment ? { loaded: true } : {}), file: files[index] })),
569
- ...(options.exclude.length === 0 ? {} : { excluded: options.exclude.map(showRange) }),
570
- vectors,
571
- stages: showStages(followed.stages),
572
- image: "image.bin",
573
- },
574
- null,
575
- 2,
576
- )}\n`,
577
- ),
578
- );
579
569
  // A clean machine at the READY prompt shows what the loader and the stages changed.
580
570
  const entry = entryStateFile(registers, state, vectors, await readyState(client));
581
- write("entry_state.json", entry.bytes);
582
- // A capture again into the folder: the segment PRGs of the earlier capture that image.json no longer lists go.
583
- const removed = removeStaleFiles(options.out, files);
571
+ const { written, removed } = writeCapture(
572
+ options.out,
573
+ memory,
574
+ segments,
575
+ [],
576
+ (files) => ({
577
+ entry: formatC64Address(registers.pc),
578
+ segments: segments.map((segment, index) => ({ ...formatC64RangeFields(segment), ...("writtenBy" in segment ? { writtenBy: segment.writtenBy } : {}), ...("loaded" in segment ? { loaded: true } : {}), file: files[index] })),
579
+ ...(options.exclude.length === 0 ? {} : { excluded: options.exclude.map(formatC64RangeFields) }),
580
+ ...(dropped.length === 0 ? {} : { dropped }),
581
+ vectors,
582
+ // The steps as the capture ran them, with their defaults: the steps file is usually in local/, which git ignores.
583
+ ...(options.steps.length === 0 ? {} : { steps: options.steps }),
584
+ stages: showStages(followed.stages),
585
+ image: "image.bin",
586
+ }),
587
+ entry.bytes,
588
+ );
584
589
  return {
585
590
  output: {
586
591
  captured: true,
@@ -588,9 +593,11 @@ async function capture(
588
593
  out: options.out,
589
594
  files: written,
590
595
  ...(removed.length === 0 ? {} : { removed }),
591
- segments: segments.map((segment) => ({ ...showRange(segment), ...("loaded" in segment ? { loaded: true } : {}) })),
592
- ...(options.exclude.length === 0 ? {} : { excluded: options.exclude.map(showRange) }),
593
- stages: followed.stages.length,
596
+ segments: segments.map((segment) => ({ ...formatC64RangeFields(segment), ...("loaded" in segment ? { loaded: true } : {}) })),
597
+ ...(underIo.length === 0 ? {} : { notExecutedUnderIo: underIo }),
598
+ ...(options.exclude.length === 0 ? {} : { excluded: options.exclude.map(formatC64RangeFields) }),
599
+ ...(dropped.length === 0 ? {} : { dropped }),
600
+ stages: showStages(followed.stages),
594
601
  differsFromReset: entry.differsFromReset,
595
602
  },
596
603
  failed: false,
@@ -661,11 +668,22 @@ function staged(call: Call, { output, failed }: { output: Record<string, unknown
661
668
  });
662
669
  }
663
670
 
664
- /** capture: the next step is a check of the entry, then the capture goes into the project knowledge. */
671
+ /** capture: the next step is a check of the entry and of the dropped bytes, then the capture goes into the project knowledge. */
665
672
  function captured(call: Call, { output, failed }: { output: Record<string, unknown>; failed: boolean }) {
666
673
  const result = outcome({ output, failed });
667
674
  if (failed) return result;
668
- return reply(result, { hint: `Disassemble the code at ${output.pc as string}. Make sure that it is the program and not the unpacker again. Then put the capture ${call.string("out")!}/image.json into the project knowledge.` });
675
+ const dropped = ((output.dropped ?? []) as Array<{ start: string; end: string }>).reduce((sum, range) => sum + parseC64Address(range.end) - parseC64Address(range.start) + 1, 0);
676
+ const underIo = ((output.notExecutedUnderIo ?? []) as Array<{ start: string; end: string }>).map((range) => `${range.start}-${range.end}`);
677
+ return reply(result, {
678
+ hint: joined([
679
+ `Disassemble the code at ${output.pc as string}. Make sure that it is the program and not the unpacker again.`,
680
+ dropped === 0 ? undefined : `The segments do not hold ${dropped} bytes that the stages wrote, because they are in blocks with the entry of a later stage. dropped gives their ranges. Make sure that the program does not use these bytes.`,
681
+ underIo.length === 0
682
+ ? undefined
683
+ : `In the RAM under the I/O area, the program executed no code in ${underIo.join(", ")} after the entry. The memory map cannot show reads of this RAM. Make sure that the program uses these bytes. If it does not, give each of these ranges as --exclude and capture again.`,
684
+ `Then put the capture ${call.string("out")!}/image.json into the project knowledge.`,
685
+ ]),
686
+ });
669
687
  }
670
688
 
671
689
  /** loads: each capture goes into the project knowledge when the agent works on that part. */
@@ -709,7 +727,7 @@ const COMMANDS: CommandSpec[] = [
709
727
  },
710
728
  {
711
729
  name: "capture",
712
- summary: "Runs the program until the CPU gets to --until after the steps, and writes into --out: image.bin (64 KiB of RAM), image.json (the entry, the segments that the stages wrote, the vectors, the stages), a PRG for each segment, and entry_state.json.",
730
+ summary: "Runs the program until the CPU gets to --until after the steps, and writes into --out: image.bin (64 KiB of RAM), image.json (the entry, the segments that the stages wrote, the written ranges that it dropped, the vectors, the steps, the stages), a PRG for each segment, and entry_state.json.",
713
731
  subjects: [PROGRAM],
714
732
  options: {
715
733
  until: { kind: "address", value: "<address>", required: true, help: "the unpacked entry point" },
@@ -726,11 +744,10 @@ const COMMANDS: CommandSpec[] = [
726
744
  const range = call.range("range");
727
745
  const until = call.address("until")!;
728
746
  // A segment must hold the entry: refused before the emulator runs.
729
- const show = (item: AddressRange) => `${formatC64Address(item.start)}-${formatC64Address(item.end)}`;
730
747
  const holds = (item: AddressRange) => until >= item.start && until <= item.end;
731
748
  const excluded = call.ranges("exclude").find(holds);
732
- if (excluded !== undefined) throw new UsageError(`--exclude ${show(excluded)} holds the entry --until ${formatC64Address(until)}. A segment must hold the entry: give an --exclude range without it.`);
733
- if (range !== undefined && !holds(range)) throw new UsageError(`--range ${show(range)} does not hold the entry --until ${formatC64Address(until)}. Give a --range that holds the entry.`);
749
+ if (excluded !== undefined) throw new UsageError(`--exclude ${formatC64Range(excluded)} holds the entry --until ${formatC64Address(until)}. A segment must hold the entry: give an --exclude range without it.`);
750
+ if (range !== undefined && !holds(range)) throw new UsageError(`--range ${formatC64Range(range)} does not hold the entry --until ${formatC64Address(until)}. Give a --range that holds the entry.`);
734
751
  return captured(call, await capture(call.subject(0), { until, out: call.string("out")!, ...(range === undefined ? {} : { range }), exclude: call.ranges("exclude"), timeoutFrames: call.count("timeout-frames")!, steps: stepsOf(call), minStage: call.count("min-stage")!, ...entryOf(call) }));
735
752
  },
736
753
  },
@@ -28,6 +28,7 @@ A tool takes addresses, not names. The server instructions give the address form
28
28
  | Run until an address, a memory value or a raster position | `c64_run_until` |
29
29
  | Run to a place and read the machine there in one call | `c64_run_until` with `observe` and `history` |
30
30
  | Each access or routine entry over many frames | `c64_trace` |
31
+ | The instructions that write an address most, and the values that they write | `c64_trace` with a write point. Read `summary`. |
31
32
  | Stop on an instruction address, stop on a memory access | `c64_breakpoint`, `c64_watchpoint` |
32
33
  | Find the instruction that reads or writes an address, and when | `c64_watchpoint` with the access, then `c64_execution` or `c64_run_until`. The stop gives `pc`. |
33
34
  | Memory | `c64_memory_read`, `c64_memory_write`, `c64_memory_search`, `c64_memory_compare` |
package/src/c64.ts CHANGED
@@ -26,12 +26,87 @@ export function formatC64Address(value: number): string {
26
26
  return `$${checkAddress(value).toString(16).padStart(4, "0")}`;
27
27
  }
28
28
 
29
+ /** An address as 4 hex digits without $, for labels and file names. */
30
+ export function hexWord(value: number): string {
31
+ return value.toString(16).padStart(4, "0");
32
+ }
33
+
34
+ /** A byte as 2 hex digits without $. */
35
+ export function hexByte(value: number): string {
36
+ return value.toString(16).padStart(2, "0");
37
+ }
38
+
29
39
  /** An inclusive span of C64 addresses. */
30
40
  export interface AddressRange {
31
41
  start: number;
32
42
  end: number;
33
43
  }
34
44
 
45
+ /** A range as $xxxx-$xxxx. */
46
+ export function formatC64Range(range: AddressRange): string {
47
+ return `${formatC64Address(range.start)}-${formatC64Address(range.end)}`;
48
+ }
49
+
50
+ /** A range with its ends as $xxxx. */
51
+ export function formatC64RangeFields(range: AddressRange): { start: string; end: string } {
52
+ return { start: formatC64Address(range.start), end: formatC64Address(range.end) };
53
+ }
54
+
55
+ /** True when the two ranges share an address. */
56
+ export function rangesOverlap(a: AddressRange, b: AddressRange): boolean {
57
+ return a.start <= b.end && b.start <= a.end;
58
+ }
59
+
60
+ /** True when one of the ranges holds the address. */
61
+ export function inRanges(ranges: readonly AddressRange[], address: number): boolean {
62
+ return ranges.some((range) => address >= range.start && address <= range.end);
63
+ }
64
+
65
+ /** The ranges in address order, with each run of touching or overlapping ranges as one. */
66
+ export function mergeRanges(ranges: readonly AddressRange[]): AddressRange[] {
67
+ const merged: AddressRange[] = [];
68
+ for (const range of [...ranges].sort((a, b) => a.start - b.start)) {
69
+ const last = merged.at(-1);
70
+ if (last !== undefined && range.start <= last.end + 1) last.end = Math.max(last.end, range.end);
71
+ else merged.push({ start: range.start, end: range.end });
72
+ }
73
+ return merged;
74
+ }
75
+
76
+ /** The parts of `range` that no range in `holes` covers, in address order. */
77
+ export function subtract(range: AddressRange, holes: readonly AddressRange[]): AddressRange[] {
78
+ let pieces = [range];
79
+ for (const hole of holes) {
80
+ pieces = pieces.flatMap((piece) => {
81
+ if (!rangesOverlap(piece, hole)) return [piece];
82
+ return [...(hole.start > piece.start ? [{ start: piece.start, end: hole.start - 1 }] : []), ...(hole.end < piece.end ? [{ start: hole.end + 1, end: piece.end }] : [])];
83
+ });
84
+ }
85
+ return pieces;
86
+ }
87
+
88
+ /** The address ranges of the C64 space where `has` is true, in address order. */
89
+ export function rangesWhere(has: (address: number) => boolean): AddressRange[] {
90
+ const ranges: AddressRange[] = [];
91
+ for (let address = 0; address < 0x10000; address++) {
92
+ if (!has(address)) continue;
93
+ const start = address;
94
+ while (address + 1 < 0x10000 && has(address + 1)) address++;
95
+ ranges.push({ start, end: address });
96
+ }
97
+ return ranges;
98
+ }
99
+
100
+ /** True when a read of the address with $01 = $37, as RUN leaves it, gives a ROM byte: RAM is below, so a write there and code that runs there are not the same bytes. */
101
+ export function underRom(address: number): boolean {
102
+ return (address >= 0xa000 && address <= 0xbfff) || address >= 0xe000;
103
+ }
104
+
105
+ /** A PRG: the 2-byte load address, then the body. */
106
+ export function prgOf(start: number, body: Uint8Array): Buffer {
107
+ return Buffer.concat([Buffer.from([start & 0xff, start >> 8]), body]);
108
+ }
109
+
35
110
  /** The knowledge spaces: the C64, the 1541 drive in unit 8, and cartridge banks 0 to 255. */
36
111
  export const SPACE_PATTERN = /^(c64|drive8|loading|bank(0|[1-9][0-9]?|1[0-9]{2}|2[0-4][0-9]|25[0-5]))$/;
37
112
 
@@ -102,6 +177,11 @@ export type ReferenceKind = (typeof REFERENCE_KINDS)[number];
102
177
  /** A symbol or label name: assembler label syntax, at most 64 characters; a leading dot marks a local label. */
103
178
  export const SYMBOL_NAME = /^\.?[A-Za-z_][A-Za-z0-9_]{0,63}$/;
104
179
 
180
+ /** True when the text has the form of an address: $ and 1 to 4 hex digits, or a name. */
181
+ export function isAddressText(text: string): boolean {
182
+ return c64AddressOf(text) !== undefined || SYMBOL_NAME.test(text);
183
+ }
184
+
105
185
  /** The VIC-II's 16 KiB bank base, from CIA 2 port A bits 0-1 (inverted); undriven lines read high. */
106
186
  export function vicBankBase(cia2PortA: number, cia2DdrA = 0xff): number {
107
187
  const lines = (cia2PortA | ~cia2DdrA) & 0x03;
@@ -504,14 +584,7 @@ const RAM_USE = COVERAGE.ramRead | COVERAGE.ramExecute;
504
584
  * flat image, so the ranges are data for an analysis run.
505
585
  */
506
586
  export function romOnlyRanges(map: Uint8Array, image: (address: number) => number | undefined): AddressRange[] {
507
- const ranges: AddressRange[] = [];
508
- for (let address = 0; address < 0x10000; address++) {
509
- if ((map[address]! & ROM_ACCESS) === 0 || (map[address]! & RAM_USE) !== 0 || image(address) === undefined) continue;
510
- const last = ranges.at(-1);
511
- if (last !== undefined && last.end === address - 1) last.end = address;
512
- else ranges.push({ start: address, end: address });
513
- }
514
- return ranges;
587
+ return rangesWhere((address) => (map[address]! & ROM_ACCESS) !== 0 && (map[address]! & RAM_USE) === 0 && image(address) !== undefined);
515
588
  }
516
589
 
517
590
  /** Every executed instruction start in RAM inside the image: VICE marks the opcode byte of an instruction as executed, not its operand. */
@@ -523,8 +596,8 @@ export function executedStarts(map: Uint8Array, image: (address: number) => numb
523
596
 
524
597
  const BRANCHES = new Set([0x10, 0x30, 0x50, 0x70, 0x90, 0xb0, 0xd0, 0xf0]);
525
598
 
526
- /** Instructions that never fall through to the next one. */
527
- const NO_FALL = new Set([0x00, 0x40, 0x4c, 0x60, 0x6c]);
599
+ /** Instructions that never fall through to the next one (BRK, RTI, JMP, RTS, JMP indirect); the JAM opcodes are in opcodes.ts. */
600
+ export const NO_FALL = new Set([0x00, 0x40, 0x4c, 0x60, 0x6c]);
528
601
 
529
602
  /**
530
603
  * The coverage flow starts split for the decompiler. A start is a code start, a
@@ -558,3 +631,37 @@ export function coverageSeedKinds(map: Uint8Array, image: (address: number) => n
558
631
  }
559
632
  return { routines: entries.filter((entry) => !inside.has(entry)), codeStarts: entries.filter((entry) => inside.has(entry)) };
560
633
  }
634
+
635
+ /**
636
+ * The executed instruction starts that DXA reaches from `seeds` by
637
+ * fall-through. DXA expects each JSR to return, so it follows the next
638
+ * instruction after a JSR too: a coverage flow start there is no seed that DXA
639
+ * needs. A seed is in the set only when another seed reaches it. The
640
+ * fall-through stops at an instruction that no run executed, at a data range,
641
+ * after a JSR or a branch into a data range (DXA does not follow the next
642
+ * instruction there), and after an instruction whose operand holds another
643
+ * executed start (DXA decodes only one of the two).
644
+ */
645
+ export function dxaFallThrough(seeds: readonly number[], map: Uint8Array, image: (address: number) => number | undefined, dataRanges: readonly AddressRange[]): Set<number> {
646
+ const reached = new Set<number>();
647
+ for (const seed of [...new Set(seeds)].sort((a, b) => a - b)) {
648
+ for (let at = seed; ; ) {
649
+ const opcode = image(at);
650
+ if (opcode === undefined || (map[at]! & COVERAGE.ramExecute) === 0 || inRanges(dataRanges, at)) break;
651
+ if (at !== seed) {
652
+ // The flow from an earlier seed went on from here.
653
+ if (reached.has(at)) break;
654
+ reached.add(at);
655
+ }
656
+ if (NO_FALL.has(opcode)) break;
657
+ const length = instructionLength(opcode);
658
+ const low = image(at + 1);
659
+ const high = image(at + 2);
660
+ if (opcode === 0x20 && low !== undefined && high !== undefined && inRanges(dataRanges, low | (high << 8))) break;
661
+ if (BRANCHES.has(opcode) && low !== undefined && inRanges(dataRanges, (at + 2 + (low < 0x80 ? low : low - 0x100)) & 0xffff)) break;
662
+ if (Array.from({ length: length - 1 }, (_, offset) => at + 1 + offset).some((address) => (map[address]! & COVERAGE.ramExecute) !== 0)) break;
663
+ at += length;
664
+ }
665
+ }
666
+ return reached;
667
+ }
package/src/cli/ap-sdk.ts CHANGED
@@ -9,7 +9,7 @@ import { runToolOrFail, type ToolContext } from "../native/run.ts";
9
9
  import { WireFailure } from "../protocol/messages.ts";
10
10
 
11
11
  /** How long one AP SDK install, update or uninstall may take. */
12
- export const AP_SDK_TIMEOUT_MS = 120_000;
12
+ const AP_SDK_TIMEOUT_MS = 120_000;
13
13
 
14
14
  const PLUGIN = fileURLToPath(new URL("../../distribution/plugin.ts", import.meta.url));
15
15
 
@@ -11,6 +11,8 @@ import { existsSync, readFileSync, rmdirSync, unlinkSync, writeFileSync } from "
11
11
  import { homedir } from "node:os";
12
12
  import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
13
13
 
14
+ import { isObject } from "../protocol/messages.ts";
15
+
14
16
  const PLUGIN_ID = "c64-re-tools";
15
17
 
16
18
  export type Scope = "project" | "global";
@@ -29,7 +31,7 @@ interface Manifest {
29
31
  }
30
32
 
31
33
  /** The directory that the manifest and relative item paths belong to. */
32
- export function scopeRoot(scope: Scope, cwd = process.cwd()): string {
34
+ function scopeRoot(scope: Scope, cwd = process.cwd()): string {
33
35
  return scope === "global" ? homedir() : cwd;
34
36
  }
35
37
 
@@ -63,7 +65,7 @@ const WINDSURF_KEY = "mcpServers";
63
65
  function readJson(path: string): Record<string, unknown> | undefined {
64
66
  try {
65
67
  const value = JSON.parse(readFileSync(path, "utf8")) as unknown;
66
- return typeof value === "object" && value !== null && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined;
68
+ return isObject(value) ? value : undefined;
67
69
  } catch {
68
70
  return undefined;
69
71
  }
package/src/compare.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  // The byte check of a program: a PRG against a reference program, for example
2
2
  // the program in the knowledge, segment by segment.
3
3
 
4
- import { formatC64Address, formatC64Byte, prgRange } from "./c64.ts";
4
+ import { type AddressRange, formatC64Address, formatC64Byte, formatC64RangeFields, prgRange, rangesWhere } from "./c64.ts";
5
5
 
6
6
  export interface SegmentCheck {
7
7
  start: string;
@@ -10,8 +10,15 @@ export interface SegmentCheck {
10
10
  /** Bytes of the segment that the build does not hold. */
11
11
  uncovered?: number;
12
12
  differences?: number;
13
- /** The first address that differs, with its byte in the build and in the knowledge, each as $ and two hex digits. */
13
+ /** The first address that differs and is in no left-out leftover, with its byte in the build and in the knowledge, each as $ and two hex digits. */
14
14
  firstDifference?: { address: string; built: string; reference: string };
15
+ /** The left-out leftovers in the segment where the build is not the reference: differences counts the bytes there that differ or that the build does not hold. */
16
+ leftovers?: Array<{ start: string; end: string; file: string; differences: number }>;
17
+ }
18
+
19
+ /** A leftover that the build leaves out: the range of a leftover file of a generated source that the build skips (LEFTOVERS = 0), with the file. */
20
+ export interface LeftOutLeftover extends AddressRange {
21
+ file: string;
15
22
  }
16
23
 
17
24
  /** The program that the build is checked against: its segments and its bytes in them. */
@@ -20,14 +27,32 @@ export interface Reference {
20
27
  byteAt: (address: number) => number;
21
28
  }
22
29
 
23
- /** Compares the assembled PRG with the reference, segment by segment. */
24
- export function compareBuild(prg: Uint8Array, program: Reference): { identical: boolean; segments: SegmentCheck[] } {
30
+ /**
31
+ * Compares the assembled PRG with the reference, segment by segment. A byte of
32
+ * a left-out leftover that differs or that the build does not hold still
33
+ * counts, but the segment names that leftover in leftovers, and
34
+ * firstDifference is the first different byte outside the leftovers.
35
+ */
36
+ export function compareBuild(prg: Uint8Array, program: Reference, leftOut: readonly LeftOutLeftover[] = []): { identical: boolean; segments: SegmentCheck[] } {
25
37
  const built = prgRange(prg);
38
+ const holds = (address: number) => address >= built.start && address <= built.end;
39
+ /** The left-out leftovers of a segment where a byte differs or is not in the build. */
40
+ const leftOutOf = (segment: AddressRange) =>
41
+ leftOut.flatMap((range) => {
42
+ let differences = 0;
43
+ for (let address = Math.max(range.start, segment.start); address <= Math.min(range.end, segment.end); address++) {
44
+ if (!holds(address) || built.body[address - built.start] !== program.byteAt(address)) differences++;
45
+ }
46
+ return differences === 0 ? [] : [{ start: formatC64Address(range.start), end: formatC64Address(range.end), file: range.file, differences }];
47
+ });
48
+ const isLeftOut = (address: number) => leftOut.some((range) => address >= range.start && address <= range.end);
26
49
  const checks = program.segments.map((segment): SegmentCheck => {
27
50
  const from = Math.max(segment.start, built.start);
28
51
  const to = Math.min(segment.end, built.end);
29
- const shown = { start: formatC64Address(segment.start), end: formatC64Address(segment.end) };
30
- if (from > to) return { ...shown, result: "not covered", uncovered: segment.end - segment.start + 1 };
52
+ const shown = formatC64RangeFields(segment);
53
+ const left = leftOutOf(segment);
54
+ const named = left.length === 0 ? {} : { leftovers: left };
55
+ if (from > to) return { ...shown, result: "not covered", uncovered: segment.end - segment.start + 1, ...named };
31
56
  let differences = 0;
32
57
  let first: SegmentCheck["firstDifference"];
33
58
  for (let address = from; address <= to; address++) {
@@ -35,14 +60,16 @@ export function compareBuild(prg: Uint8Array, program: Reference): { identical:
35
60
  const referenceByte = program.byteAt(address);
36
61
  if (builtByte === referenceByte) continue;
37
62
  differences++;
38
- first ??= { address: formatC64Address(address), built: formatC64Byte(builtByte), reference: formatC64Byte(referenceByte) };
63
+ if (!isLeftOut(address)) first ??= { address: formatC64Address(address), built: formatC64Byte(builtByte), reference: formatC64Byte(referenceByte) };
39
64
  }
40
65
  const uncovered = segment.end - segment.start + 1 - (to - from + 1);
41
66
  return {
42
67
  ...shown,
43
68
  result: differences > 0 ? "different" : uncovered > 0 ? "not covered" : "identical",
44
69
  ...(uncovered > 0 ? { uncovered } : {}),
45
- ...(differences > 0 ? { differences, firstDifference: first! } : {}),
70
+ ...(differences > 0 ? { differences } : {}),
71
+ ...(first === undefined ? {} : { firstDifference: first }),
72
+ ...named,
46
73
  };
47
74
  });
48
75
  return { identical: checks.every((check) => check.result === "identical"), segments: checks };
@@ -56,12 +83,5 @@ export function mergedPrograms(programs: ReadonlyArray<{ start: number; body: Ui
56
83
  memory.set(body, start);
57
84
  loaded.fill(1, start, start + body.length);
58
85
  }
59
- const segments: Array<{ start: number; end: number }> = [];
60
- for (let address = 0; address < 0x10000; address++) {
61
- if (loaded[address] === 0) continue;
62
- const last = segments.at(-1);
63
- if (last !== undefined && last.end === address - 1) last.end = address;
64
- else segments.push({ start: address, end: address });
65
- }
66
- return { segments, byteAt: (address) => memory[address]! };
86
+ return { segments: rangesWhere((address) => loaded[address] !== 0), byteAt: (address) => memory[address]! };
67
87
  }
package/src/errors.ts CHANGED
@@ -16,7 +16,6 @@ export const ERROR_CODES = [
16
16
  "conflict",
17
17
  "stale-revision",
18
18
  "invalid-database",
19
- "unsupported-schema",
20
19
  "not-implemented",
21
20
  ] as const;
22
21
  export type ErrorCode = (typeof ERROR_CODES)[number];
@@ -52,6 +51,16 @@ export function splitMessage(message: string, hint?: string): { error: string; h
52
51
  return rest === "" ? { error } : { error, hint: rest };
53
52
  }
54
53
 
54
+ /** The message of a caught value, which may not be an Error. */
55
+ export function describeError(error: unknown): string {
56
+ return error instanceof Error ? error.message : String(error);
57
+ }
58
+
59
+ /** The stack of a caught Error (its message when it has none), for a log; a value that is not an Error as text. */
60
+ export function describeErrorStack(error: unknown): string {
61
+ return error instanceof Error ? (error.stack ?? error.message) : String(error);
62
+ }
63
+
55
64
  /** True for an Error with a code from ERROR_CODES: a refusal, whatever its class. */
56
65
  export function isRefusal(error: unknown): error is Error & { code: ErrorCode } {
57
66
  const code = (error as { code?: unknown } | undefined)?.code;
package/src/host/main.ts CHANGED
@@ -3,6 +3,7 @@
3
3
  import { constants } from "node:os";
4
4
  import { parseArgs } from "node:util";
5
5
 
6
+ import { describeError } from "../errors.ts";
6
7
  import { DEFAULT_HOST_PORT } from "../protocol/messages.ts";
7
8
  import { ProcessSupervisor } from "../native/processes.ts";
8
9
  import { startTrace, trace } from "../trace.ts";
@@ -53,7 +54,7 @@ async function main(): Promise<number> {
53
54
  strict: true,
54
55
  }));
55
56
  } catch (error) {
56
- process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n\n${HELP}\n`);
57
+ process.stderr.write(`${describeError(error)}\n\n${HELP}\n`);
57
58
  return 2;
58
59
  }
59
60
  if (values.help) {