@henols/c64-re-tools 2.6.0-rc.9 → 2.6.0

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 (68) hide show
  1. package/package.json +1 -1
  2. package/skills/c64-assembler/SKILL.md +3 -3
  3. package/skills/c64-assembler/scripts/assembler.ts +4 -3
  4. package/skills/c64-development/SKILL.md +3 -3
  5. package/skills/c64-docs/SKILL.md +5 -3
  6. package/skills/c64-docs/scripts/docs.ts +17 -4
  7. package/skills/c64-docs/scripts/lib/reference.ts +117 -31
  8. package/skills/c64-docs/scripts/lib/source-map.ts +14 -0
  9. package/skills/c64-knowledge/SKILL.md +8 -7
  10. package/skills/c64-knowledge/scripts/knowledge.ts +16 -9
  11. package/skills/c64-reverse-engineering/SKILL.md +9 -3
  12. package/skills/c64-source/SKILL.md +11 -8
  13. package/skills/c64-source/scripts/lib/export.ts +13 -2
  14. package/skills/c64-source/scripts/lib/loader.ts +51 -28
  15. package/skills/c64-source/scripts/lib/source.ts +24 -17
  16. package/skills/c64-source/scripts/source.ts +51 -36
  17. package/skills/c64-static-analysis/SKILL.md +23 -21
  18. package/skills/c64-static-analysis/scripts/lib/findings.ts +11 -11
  19. package/skills/c64-static-analysis/scripts/lib/instructions.ts +4 -4
  20. package/skills/c64-static-analysis/scripts/lib/macros.ts +3 -1
  21. package/skills/c64-static-analysis/scripts/static-analysis.ts +36 -27
  22. package/skills/c64-testing/SKILL.md +10 -3
  23. package/skills/c64-testing/references/recording-format.md +8 -2
  24. package/skills/c64-testing/references/scenario-format.md +4 -2
  25. package/skills/c64-testing/scripts/lib/recording.ts +193 -28
  26. package/skills/c64-testing/scripts/lib/replay.ts +31 -5
  27. package/skills/c64-testing/scripts/lib/runs.ts +7 -2
  28. package/skills/c64-testing/scripts/lib/scenario.ts +3 -3
  29. package/skills/c64-testing/scripts/testing.ts +23 -2
  30. package/skills/c64-unpacker/SKILL.md +4 -2
  31. package/skills/c64-unpacker/scripts/lib/stages.ts +18 -3
  32. package/skills/c64-unpacker/scripts/unpacker.ts +38 -6
  33. package/src/build-name.ts +9 -4
  34. package/src/c64.ts +1 -1
  35. package/src/host/main.ts +2 -2
  36. package/src/host/server.ts +3 -1
  37. package/src/host/tools/index.ts +1 -1
  38. package/src/host/vice/process.ts +34 -17
  39. package/src/host/vice/session.ts +55 -27
  40. package/src/host-client/steps.ts +4 -1
  41. package/src/host-client/tools.ts +1 -1
  42. package/src/knowledge/evidence.ts +66 -0
  43. package/src/knowledge/history.ts +5 -5
  44. package/src/knowledge/import.ts +12 -5
  45. package/src/knowledge/program.ts +81 -33
  46. package/src/knowledge/read.ts +3 -3
  47. package/src/knowledge/schema.ts +7 -7
  48. package/src/knowledge/start-screen.ts +2 -0
  49. package/src/knowledge/text.ts +28 -3
  50. package/src/knowledge/write.ts +6 -6
  51. package/src/mcp/tools/debug.ts +23 -21
  52. package/src/mcp/tools/memory.ts +12 -9
  53. package/src/native/c64run.ts +7 -4
  54. package/src/native/{ghidra → decompiler}/analyze.ts +17 -17
  55. package/src/native/{ghidra → decompiler}/language/c64rt_6510.slaspec +1 -1
  56. package/src/native/{ghidra → decompiler}/walk.ts +6 -6
  57. package/src/native/types.ts +25 -25
  58. package/src/opcodes.ts +1 -1
  59. package/src/reference-pages.ts +64 -0
  60. package/src/script.ts +1 -1
  61. package/tools/c64run.c +150 -4
  62. /package/src/native/{ghidra → decompiler}/c64rt-wasm.ts +0 -0
  63. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.cspec +0 -0
  64. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.ldefs +0 -0
  65. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.pspec +0 -0
  66. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.sla +0 -0
  67. /package/src/native/{ghidra → decompiler}/pcode.ts +0 -0
  68. /package/src/native/{ghidra → decompiler}/wasm.ts +0 -0
@@ -15,6 +15,7 @@ import { readPrg } from "#src/host-client/image.ts";
15
15
  import { writeReported, type Written } from "#src/host-client/transfer.ts";
16
16
  import { ViceSessionClient } from "#src/host-client/vice-session.ts";
17
17
  import { knowledgeAt, knowledgeNames } from "#src/knowledge/names.ts";
18
+ import { PAL_FRAME_CYCLES } from "#src/native/c64run.ts";
18
19
  import { listed, OPTIONS, reply, runScript, UsageError, type Call, type CommandSpec, type OptionSpec } from "#src/script.ts";
19
20
  import { basicStart, inspect, readMemoryMap, underRom, writtenThenExecuted } from "./lib/evidence.ts";
20
21
  import { loads, readLoadSteps } from "./lib/loads.ts";
@@ -197,6 +198,8 @@ interface Followed {
197
198
  failed?: string;
198
199
  /** What stopped the CPU before the frames ran: a JAM or a point of the program. */
199
200
  halted?: { stopReason: string; pc: number };
201
+ /** The first step (1 = the first) in which the CPU executed `until`, before the run waited for it. */
202
+ untilRan?: number;
200
203
  }
201
204
 
202
205
  type RunUntilStep = Extract<ActionStep, { runUntil: unknown }>;
@@ -250,9 +253,16 @@ async function follow(
250
253
  const atTarget = (pc: number) => stopAt !== undefined && pc === stopAt;
251
254
  // The current stage: its memory map since it started, chunk by chunk, its own code, and the written code it calls.
252
255
  let stage = { map: new Uint8Array(0x10000), own: new Set<number>(), called: [] as AddressRange[] };
256
+ // A step that runs frames can pass until: the run then waits for it in vain.
257
+ let running = 0;
258
+ let untilRan: number | undefined;
259
+ const noteUntil = (map: Uint8Array) => {
260
+ if (options.until !== undefined && running > 0 && untilRan === undefined && (map[options.until]! & EXECUTE) !== 0) untilRan = running;
261
+ };
253
262
  const startStage = async (next: number, last: Uint8Array) => {
254
263
  mergeMaps(stage.map, last);
255
264
  await markIoRam(stage.map);
265
+ noteUntil(stage.map);
256
266
  found.push({ entry, firstFrame, frames: total - firstFrame, wrote: stageWrote(stage.map), next });
257
267
  entry = next;
258
268
  firstFrame = total;
@@ -426,8 +436,11 @@ async function follow(
426
436
  stopAt = undefined;
427
437
  }
428
438
  };
439
+ // Stage 0 starts at the program, whatever the first step is: RUN and the BASIC line before it are no part of it.
440
+ await client.memmap({ action: "clear" });
429
441
  // The steps run first and in the tracked time: a frames step and a runUntil step to an address. The others act between two chunks.
430
442
  for (const [index, step] of options.steps.entries()) {
443
+ running = index + 1;
431
444
  if ("frames" in step) await track(step.frames);
432
445
  else if (trackedRunUntil(step)) {
433
446
  if (!(await trackTo(knowledgeAt()(step.runUntil.target.address), step.runUntil.timeoutFrames))) {
@@ -435,8 +448,21 @@ async function follow(
435
448
  const why = halted === undefined ? "" : ` ${stoppedEarly(halted.stopReason, halted.pc, total, step.runUntil.timeoutFrames)}`;
436
449
  return { stages: found, frames: total, reached: false, failed: `Step ${index + 1} did not reach its target in ${step.runUntil.timeoutFrames} frames. It is at ${formatC64Address(pc)}.${why}` };
437
450
  }
438
- } else await runActionStep(client, step, knowledgeAt());
451
+ } else {
452
+ // A press or a runUntil to memory or the raster runs frames outside the chunks. The stopwatch of the session gives them,
453
+ // also for a run that a point stops early. What the step wrote and ran is in the stage before the next chunk clears the memory map.
454
+ await client.timing("start");
455
+ const notReached = await runActionStep(client, step, knowledgeAt());
456
+ const timed = await client.timing("read");
457
+ total += Math.round(Number("cycles" in timed ? timed.cycles : 0) / PAL_FRAME_CYCLES);
458
+ mergeMaps(stage.map, await readCoverage(client));
459
+ if (notReached !== undefined && "runUntil" in step) {
460
+ return { stages: found, frames: total, reached: false, failed: `Step ${index + 1} did not reach its target in ${step.runUntil.timeoutFrames} frames. It stopped by ${notReached.stopReason} at ${formatC64Address(notReached.pc)}.` };
461
+ }
462
+ }
463
+ noteUntil(stage.map);
439
464
  }
465
+ running = 0;
440
466
  const left = Math.max(0, options.frames - total);
441
467
  let reached = false;
442
468
  if (options.until === undefined) await track(left);
@@ -445,7 +471,7 @@ async function follow(
445
471
  mergeMaps(stage.map, await readCoverage(client));
446
472
  await markIoRam(stage.map);
447
473
  found.push({ entry, firstFrame, frames: total - firstFrame, wrote: stageWrote(stage.map) });
448
- return { stages: found, frames: total, reached, ...(halted === undefined ? {} : { halted }) };
474
+ return { stages: found, frames: total, reached, ...(halted === undefined ? {} : { halted }), ...(untilRan === undefined ? {} : { untilRan }) };
449
475
  }
450
476
 
451
477
  const showRange = (range: { start: number; end: number }) => ({ start: formatC64Address(range.start), end: formatC64Address(range.end) });
@@ -490,6 +516,11 @@ async function stages(program: string, options: { frames: number; entry?: number
490
516
  }
491
517
  }
492
518
 
519
+ /** Why a capture can wait for --until in vain: a step ran over it. */
520
+ function passedInStep(until: number, step: number): string {
521
+ 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.`;
522
+ }
523
+
493
524
  async function capture(
494
525
  program: string,
495
526
  options: { until: number; out: string; range?: AddressRange; exclude: AddressRange[]; timeoutFrames: number; entry?: number; steps: ActionStep[]; minStage: number },
@@ -504,7 +535,7 @@ async function capture(
504
535
  return {
505
536
  output: {
506
537
  captured: false,
507
- reason: `The program did not get to ${formatC64Address(options.until)} in ${options.timeoutFrames} frames. It is at ${formatC64Address(registers.pc)}.${followed.halted === undefined ? "" : ` ${stoppedEarly(followed.halted.stopReason, followed.halted.pc, followed.frames, options.timeoutFrames)}`}`,
538
+ reason: `The program did not get to ${formatC64Address(options.until)} in ${options.timeoutFrames} frames. It is at ${formatC64Address(registers.pc)}.${followed.halted === undefined ? "" : ` ${stoppedEarly(followed.halted.stopReason, followed.halted.pc, followed.frames, options.timeoutFrames)}`}${followed.untilRan === undefined ? "" : ` ${passedInStep(options.until, followed.untilRan)}`}`,
508
539
  ...(followed.halted === undefined ? {} : { stopReason: followed.halted.stopReason }),
509
540
  stages: showStages(followed.stages),
510
541
  },
@@ -515,7 +546,8 @@ async function capture(
515
546
  const memory = await readRam(client, 0x0000, 0x10000);
516
547
  const state = await machineState(client);
517
548
  // The segments: what the stages wrote, without loader leftovers, with no overlap.
518
- const found = options.range !== undefined ? [options.range] : captureSegments(followed.stages, registers.pc);
549
+ 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) });
519
551
  const segments = withoutRanges(found, options.exclude);
520
552
  const file = (path: string) => `${options.out}/${path}`;
521
553
  const written: Written[] = [];
@@ -533,7 +565,7 @@ async function capture(
533
565
  `${JSON.stringify(
534
566
  {
535
567
  entry: formatC64Address(registers.pc),
536
- segments: segments.map((segment, index) => ({ ...showRange(segment), ...("writtenBy" in segment ? { writtenBy: segment.writtenBy } : {}), file: files[index] })),
568
+ segments: segments.map((segment, index) => ({ ...showRange(segment), ...("writtenBy" in segment ? { writtenBy: segment.writtenBy } : {}), ...("loaded" in segment ? { loaded: true } : {}), file: files[index] })),
537
569
  ...(options.exclude.length === 0 ? {} : { excluded: options.exclude.map(showRange) }),
538
570
  vectors,
539
571
  stages: showStages(followed.stages),
@@ -556,7 +588,7 @@ async function capture(
556
588
  out: options.out,
557
589
  files: written,
558
590
  ...(removed.length === 0 ? {} : { removed }),
559
- segments: segments.map(showRange),
591
+ segments: segments.map((segment) => ({ ...showRange(segment), ...("loaded" in segment ? { loaded: true } : {}) })),
560
592
  ...(options.exclude.length === 0 ? {} : { excluded: options.exclude.map(showRange) }),
561
593
  stages: followed.stages.length,
562
594
  differsFromReset: entry.differsFromReset,
package/src/build-name.ts CHANGED
@@ -2,7 +2,9 @@
2
2
  // A release build is release_<label>. A build of config.asm is clean when each
3
3
  // switch has its default, else custom_ with each switch that differs: its
4
4
  // name when it is on, no_<name> when it is off. A build of an entry other
5
- // than main.asm adds the entry, for example clean_loader. A source without
5
+ // than main.asm adds the entry, for example clean_loader. The loader of the
6
+ // packed form alone is only its copier, so its build is clean_copier: the loader
7
+ // program, which generate packs, keeps clean_loader. A source without
6
8
  // config.asm and without a release keeps the name of its entry. The symbols
7
9
  // of a build go into symbols/ next to the program, so the program folder
8
10
  // holds only programs.
@@ -31,9 +33,12 @@ export function configValues(text: string): Map<string, 0 | 1> {
31
33
  /** What a build is made of: a release, or the values of config.asm with the default of each switch (0 when the defaults do not have it). */
32
34
  export type BuildKind = { release: string } | { values: ReadonlyMap<string, number>; defaults: ReadonlyMap<string, number> };
33
35
 
34
- /** The name of a build of `entry`, without an extension. */
35
- export function buildName(entry: string, kind: BuildKind | undefined): string {
36
- const base = basename(entry, extname(entry));
36
+ /** The line of a generated loader.asm of the packed form. Its build alone is only the copier, not the loader program. */
37
+ export const COPIER_LINE = "; A build of this file alone is only the copier: its build name has copier in place of loader.";
38
+
39
+ /** The name of a build of `entry`, without an extension. `source` is the text of the entry: COPIER_LINE in it gives the name copier. */
40
+ export function buildName(entry: string, kind: BuildKind | undefined, source?: string): string {
41
+ const base = source?.split(/\r?\n/).includes(COPIER_LINE) ? "copier" : basename(entry, extname(entry));
37
42
  if (kind === undefined) return base;
38
43
  let type: string;
39
44
  if ("release" in kind) type = `release_${kind.release}`;
package/src/c64.ts CHANGED
@@ -511,7 +511,7 @@ const BRANCHES = new Set([0x10, 0x30, 0x50, 0x70, 0x90, 0xb0, 0xd0, 0xf0]);
511
511
  const NO_FALL = new Set([0x00, 0x40, 0x4c, 0x60, 0x6c]);
512
512
 
513
513
  /**
514
- * The coverage flow starts split for Ghidra. A start is a code start, a
514
+ * The coverage flow starts split for the decompiler. A start is a code start, a
515
515
  * place in a routine, when it follows an executed JSR, or when an executed
516
516
  * branch or JMP from outside its own flow reaches it (the loop of a routine
517
517
  * that jumps back to its own start does not count). Any other start, for
package/src/host/main.ts CHANGED
@@ -121,8 +121,8 @@ async function main(): Promise<number> {
121
121
  log,
122
122
  flaws,
123
123
  // c1541 lists the disk, so an autostart index selects a program.
124
- directory: async (imageType, image) => {
125
- const { result } = await inspect({ action: "directory", imageType }, image, { supervisor, signal: new AbortController().signal, log });
124
+ directory: async (imageType, image, signal) => {
125
+ const { result } = await inspect({ action: "directory", imageType }, image, { supervisor, signal, log });
126
126
  return result.action === "directory" ? result.entries : [];
127
127
  },
128
128
  }),
@@ -263,7 +263,7 @@ class Connection {
263
263
  const record = (outcome: Record<string, unknown>) => {
264
264
  const ms = elapsedMs(started);
265
265
  trace().event("request", { connection: this.#id, op: request.op, id: request.id, params: request.params, attachments: attachments.length, ms, ...outcome });
266
- // A call from a skill script (c1541, petcat, status) is always logged; the many calls of a VICE session only in the trace.
266
+ // A call from a skill script (c1541, petcat) is always logged; the many calls of a VICE session only in the trace.
267
267
  if (this.#isTool) {
268
268
  const what = outcome.ok === true ? "ok" : `${String(outcome.code)}: ${String(outcome.message)}`;
269
269
  this.#log(`${request.op} ${JSON.stringify(summarize(request.params) ?? {})}: ${what} (${ms} ms)`);
@@ -387,6 +387,8 @@ export async function startHostServer(options: HostServerOptions): Promise<HostS
387
387
  server.once("error", failed);
388
388
  server.listen({ host: address, port, exclusive: true }, () => {
389
389
  server.off("error", failed);
390
+ // A failed accept (for example EMFILE) fails only that connection; the listener goes on.
391
+ server.on("error", (error) => log(`listener on ${address} port ${port}: ${error.message}`));
390
392
  const bound = server.address();
391
393
  if (bound === null || typeof bound === "string") reject(new Error("listener has no TCP address"));
392
394
  else resolve(bound.port);
@@ -1,6 +1,6 @@
1
1
  // The typed tool dispatcher of the Host Runtime. The host runs only
2
2
  // VICE and the tools that come with it (c1541, petcat); skill scripts run
3
- // ACME, DXA and Ghidra themselves. One entry per operation, never a
3
+ // ACME, DXA and the decompiler themselves. One entry per operation, never a
4
4
  // generic executable route.
5
5
 
6
6
  import type { ProcessSupervisor } from "../../native/processes.ts";
@@ -25,7 +25,7 @@
25
25
  // A headless VICE plays no sound: `-sounddev dummy` keeps the SID emulated.
26
26
 
27
27
  import { mkdtempSync, readFileSync, rmSync } from "node:fs";
28
- import { createServer } from "node:net";
28
+ import { createServer, type Server } from "node:net";
29
29
  import { tmpdir } from "node:os";
30
30
  import { join } from "node:path";
31
31
  import { setTimeout as sleep } from "node:timers/promises";
@@ -49,18 +49,33 @@ export function findVice(env: NodeJS.ProcessEnv = process.env): string {
49
49
  }
50
50
 
51
51
  /** Asks the OS for a free loopback port. Another process can still take it before VICE binds. */
52
- export function freePort(): Promise<number> {
53
- return new Promise((resolve, reject) => {
54
- const server = createServer();
55
- server.once("error", reject);
56
- server.listen(0, "127.0.0.1", () => {
57
- const address = server.address();
58
- server.close(() => {
59
- if (address === null || typeof address === "string") reject(new Error("no TCP address"));
60
- else resolve(address.port);
61
- });
62
- });
63
- });
52
+ export async function freePort(): Promise<number> {
53
+ return (await freePorts(1))[0]!;
54
+ }
55
+
56
+ /** Asks the OS for `count` different free loopback ports: each probe stays bound until all are known. */
57
+ export async function freePorts(count: number): Promise<number[]> {
58
+ const servers: Server[] = [];
59
+ try {
60
+ const ports: number[] = [];
61
+ for (let index = 0; index < count; index++) {
62
+ const server = createServer();
63
+ servers.push(server);
64
+ ports.push(
65
+ await new Promise<number>((resolve, reject) => {
66
+ server.once("error", reject);
67
+ server.listen(0, "127.0.0.1", () => {
68
+ const address = server.address();
69
+ if (address === null || typeof address === "string") reject(new Error("no TCP address"));
70
+ else resolve(address.port);
71
+ });
72
+ }),
73
+ );
74
+ }
75
+ return ports;
76
+ } finally {
77
+ await Promise.all(servers.map((server) => new Promise<void>((resolve) => server.close(() => resolve()))));
78
+ }
64
79
  }
65
80
 
66
81
  /** A VICE with no window (the default) or one with a window the user can use. */
@@ -254,8 +269,7 @@ async function launchOnce(options: LaunchOptions): Promise<ViceProcess> {
254
269
  const env = options.env ?? process.env;
255
270
  const log = options.log ?? (() => {});
256
271
  const binary = findVice(env);
257
- const port = await freePort();
258
- const textPort = await freePort();
272
+ const [port, textPort] = (await freePorts(2)) as [number, number];
259
273
  const scratch = mkdtempSync(join(tmpdir(), "c64-re-tools-vice-"));
260
274
  // Owned by the supervisor: its exit guard and the watchdog remove it if this process dies.
261
275
  const releaseScratch = options.supervisor.ownPath(scratch);
@@ -384,9 +398,12 @@ async function checkSameMachine(monitor: BinaryMonitor, text: TextMonitor): Prom
384
398
  if (seen === null || Number.parseInt(seen[1]!, 16) !== marker) {
385
399
  throw new WireFailure("machine-unavailable", "The emulator's two monitor connections reached different machines.");
386
400
  }
387
- } finally {
388
- await write(original);
401
+ } catch (error) {
402
+ // The first failure tells why the launch failed; a failed restore after it would hide it.
403
+ await write(original).catch(() => {});
404
+ throw error;
389
405
  }
406
+ await write(original);
390
407
  }
391
408
 
392
409
  /** Connects the binary monitor and proves it answers a ping, until `deadline`. */
@@ -82,7 +82,6 @@ const WINDOW_CLOSED =
82
82
  "Breakpoints and watchpoints are kept. Check the machine state before you continue.";
83
83
 
84
84
  /** Emulator state that a move to another VICE cannot carry. */
85
- /** The first bytes of every VICE snapshot file. */
86
85
  const NOT_CARRIED = ["cpu history", "memory map", "profile", "keyboard input not yet typed"];
87
86
 
88
87
  /** Starts another VICE for this session; `log` also gets that launch's lines. */
@@ -141,7 +140,8 @@ const BROKEN_MESSAGES: Record<ViceFeature, string> = {
141
140
  keyboard: "Keys of the keyboard matrix are not implemented in this setup. Do not press keys in this task. Give this message to the user.",
142
141
  };
143
142
 
144
- export type DiskDirectory = (type: DiskImageType, image: Buffer) => Promise<DiskFile[]>;
143
+ /** `signal` aborts when the session closes. */
144
+ export type DiskDirectory = (type: DiskImageType, image: Buffer, signal: AbortSignal) => Promise<DiskFile[]>;
145
145
 
146
146
  /**
147
147
  * Where VICE keeps a staged file: an autostarted disk stays in drive 8, a tape
@@ -170,6 +170,8 @@ export class ViceSession implements ViceSessionHandle {
170
170
  readonly #stepLimitMs: number;
171
171
  readonly #launch: ViceLauncher | undefined;
172
172
  readonly #directory: DiskDirectory | undefined;
173
+ /** Stops the host tool runs of this session when it closes. */
174
+ readonly #abort = new AbortController();
173
175
  /** Session files that outlive one VICE: snapshots, staged media, handovers. */
174
176
  readonly #workDir: string;
175
177
  readonly #releaseWorkDir: () => void;
@@ -373,6 +375,7 @@ export class ViceSession implements ViceSessionHandle {
373
375
 
374
376
  async close(): Promise<void> {
375
377
  this.#closed = true;
378
+ this.#abort.abort();
376
379
  try {
377
380
  await this.#vice.stop();
378
381
  } finally {
@@ -436,7 +439,7 @@ export class ViceSession implements ViceSessionHandle {
436
439
  if (type === "tap") this.#refuseBroken("tape", "c64_autostart of a tape image");
437
440
  const bytes = onlyAttachment(attachments);
438
441
  checkMedia(type, bytes);
439
- if (index > 0 && this.#directory !== undefined && isOneOf(DISK_IMAGE_TYPES, type)) checkDirectoryEntry(await this.#directory(type, bytes), index);
442
+ if (index > 0 && this.#directory !== undefined && isOneOf(DISK_IMAGE_TYPES, type)) checkDirectoryEntry(await this.#directory(type, bytes, this.#abort.signal), index);
440
443
  const file = this.#stage(bytes, type);
441
444
  // VICE keeps a cartridge through every reset and autostart, as a real C64 does.
442
445
  if (type !== "crt" && this.#cartridge) {
@@ -475,7 +478,7 @@ export class ViceSession implements ViceSessionHandle {
475
478
  return this.#reset(params as ViceOperations["reset"]["params"]);
476
479
  case "keyboard": {
477
480
  const bytes = Buffer.from((params as ViceOperations["keyboard"]["params"]).data, "hex");
478
- await this.#refuseWhileAutostartLoads("type");
481
+ await this.#refuseWhileAutostartLoads("a key now stops it before RUN", "type");
479
482
  await this.#observe(() => this.#machine.feedKeyboard(bytes));
480
483
  return { queuedBytes: bytes.length };
481
484
  }
@@ -718,12 +721,16 @@ export class ViceSession implements ViceSessionHandle {
718
721
  // running, and only a stop caused by this breakpoint counts.
719
722
  const vector = await this.#machine.resetVector();
720
723
  const checkpoint = await this.#machine.addCheckpoint({ start: vector, end: vector, operation: 0x04, space: "c64" });
721
- await this.#resume();
722
- const stopped = this.#nextStop(RESET_STOP_LIMIT_MS, checkpoint);
723
- await this.#resumingCommand(() => this.#machine.reset(params.mode));
724
- const reached = (await stopped) !== undefined;
725
- if (!reached) await this.#stop();
726
- await this.#machine.deleteCheckpoint(checkpoint);
724
+ let reached: boolean;
725
+ try {
726
+ await this.#resume();
727
+ const stopped = this.#nextStop(RESET_STOP_LIMIT_MS, checkpoint);
728
+ await this.#resumingCommand(() => this.#machine.reset(params.mode));
729
+ reached = (await stopped) !== undefined;
730
+ if (!reached) await this.#stop();
731
+ } finally {
732
+ await this.#machine.deleteCheckpoint(checkpoint);
733
+ }
727
734
  if (!reached) throw new WireFailure("operation-failed", "The C64 did not reach its reset vector after the reset.");
728
735
  this.#atResetStop = true;
729
736
  return { state: "stopped", pc: vector };
@@ -847,6 +854,9 @@ export class ViceSession implements ViceSessionHandle {
847
854
  hits.push(await this.#traceHit(index, params.points[index]!.kind, frames));
848
855
  if (hits.length >= params.maxHits) return { hits, frames, end: "hits", pc: stop.pc };
849
856
  }
857
+ // A user point ends the trace, also when a trace point or the clock hit in the same stop.
858
+ const point = this.#userPoint(stop.hits);
859
+ if (point !== undefined) return { hits, frames, end: point.stopReason, pc: stop.pc };
850
860
  if (stop.hits.includes(clock)) {
851
861
  if (stop.pc === clockPc && (await this.#jamAt(stop.pc))) return { hits, frames, end: "jam", pc: stop.pc };
852
862
  clockPc = stop.pc;
@@ -860,8 +870,6 @@ export class ViceSession implements ViceSessionHandle {
860
870
  continue;
861
871
  }
862
872
  if (traced.length > 0) continue;
863
- const point = this.#userPoint(stop.hits);
864
- if (point !== undefined) return { hits, frames, end: point.stopReason, pc: stop.pc };
865
873
  if (await this.#jamAt(stop.pc)) return { hits, frames, end: "jam", pc: stop.pc };
866
874
  if (this.#pendingStep) {
867
875
  this.#pendingStep = false;
@@ -1184,16 +1192,29 @@ export class ViceSession implements ViceSessionHandle {
1184
1192
  return publicView(point);
1185
1193
  }
1186
1194
 
1187
- /** VICE turns warp on for an autostart and off when it types RUN. A key in between ends the autostart with no message. */
1188
- async #refuseWhileAutostartLoads(verb: string): Promise<void> {
1195
+ /**
1196
+ * VICE turns warp on for an autostart and off when it types RUN. A key in
1197
+ * between ends the autostart with no message, and another VICE does not go on with it.
1198
+ */
1199
+ async #refuseWhileAutostartLoads(effect: string, verb: string): Promise<void> {
1189
1200
  if (this.#autostarting && !this.#userWarp && (await this.#observe(() => this.#machine.warp()))) {
1190
1201
  throw new WireFailure(
1191
1202
  "operation-failed",
1192
- `The autostart still loads the program, and a key now stops it before RUN. Run frames with c64_execution advance-frames, then ${verb} again.`,
1203
+ `The autostart still loads the program, and ${effect}. Run frames with c64_execution advance-frames, then ${verb} again.`,
1193
1204
  );
1194
1205
  }
1195
1206
  }
1196
1207
 
1208
+ /** VICE (3.9, 3.10) stops answering at the restore of a snapshot saved at the reset stop while the disk drive was busy. */
1209
+ #refuseAtResetStop(verb: string): void {
1210
+ if (!this.#atResetStop) return;
1211
+ throw new WireFailure(
1212
+ "operation-failed",
1213
+ "The CPU stands at the reset stop of c64_reset with run false. The emulator stops answering at the restore of a snapshot saved here when the disk drive was busy. " +
1214
+ `Step one instruction with c64_execution, then ${verb}.`,
1215
+ );
1216
+ }
1217
+
1197
1218
  /**
1198
1219
  * Presses keys of the keyboard matrix and RESTORE. VICE has no command for
1199
1220
  * that: a snapshot gets the keys in its keyboard module, and RESTORE as a
@@ -1204,7 +1225,7 @@ export class ViceSession implements ViceSessionHandle {
1204
1225
  */
1205
1226
  async #press(params: ViceOperations["press"]["params"]): Promise<PressResult> {
1206
1227
  this.#refuseBroken("keyboard", "c64_press");
1207
- await this.#refuseWhileAutostartLoads("press the keys");
1228
+ await this.#refuseWhileAutostartLoads("a key now stops it before RUN", "press the keys");
1208
1229
  if (this.#atResetStop) {
1209
1230
  throw new WireFailure(
1210
1231
  "operation-failed",
@@ -1411,13 +1432,7 @@ export class ViceSession implements ViceSessionHandle {
1411
1432
  if (params.action === "list") return { snapshots: [...this.#snapshots.keys()] };
1412
1433
  const existing = this.#snapshots.get(params.name);
1413
1434
  if (params.action === "save") {
1414
- if (this.#atResetStop) {
1415
- throw new WireFailure(
1416
- "operation-failed",
1417
- "The CPU stands at the reset stop of c64_reset with run false. The emulator stops answering at the restore of a snapshot saved here when the disk drive was busy. " +
1418
- "Step one instruction with c64_execution, then save the snapshot.",
1419
- );
1420
- }
1435
+ this.#refuseAtResetStop("save the snapshot");
1421
1436
  if (existing === undefined && this.#snapshots.size >= MAX_SNAPSHOTS) {
1422
1437
  throw new WireFailure("limit-exceeded", `A session keeps at most ${MAX_SNAPSHOTS} snapshots. Remove one first with action remove.`);
1423
1438
  }
@@ -1443,6 +1458,8 @@ export class ViceSession implements ViceSessionHandle {
1443
1458
  if (this.#autostarting) await this.#reset({ mode: "soft", run: false });
1444
1459
  await this.#machine.restoreSnapshot(file);
1445
1460
  this.#historySince = await this.#machine.clock();
1461
+ // A save at the reset stop is refused, so no restored machine stands there.
1462
+ this.#atResetStop = false;
1446
1463
  // A restore starts a jammed CPU again, but VICE still records no CPU history.
1447
1464
  this.#jammed = undefined;
1448
1465
  if (this.#historyStopped) this.#historyOld = true;
@@ -1466,12 +1483,19 @@ export class ViceSession implements ViceSessionHandle {
1466
1483
  if (!hasSignature("vsf", bytes)) throw new WireFailure("invalid-input", "The file is not a VICE snapshot file (.vsf). Give a file that c64_snapshot save wrote.");
1467
1484
  const file = this.#stage(bytes, "vsf");
1468
1485
  // VICE resets the machine after a snapshot file that it cannot read: a backup keeps the state before the restore.
1469
- const backup = join(this.#workDir, "before-restore.vsf");
1486
+ // At the reset stop there is none: VICE can stop answering at the restore of a snapshot saved there (#atResetStop).
1487
+ const backup = this.#atResetStop ? undefined : join(this.#workDir, "before-restore.vsf");
1470
1488
  await this.#stop();
1471
- await this.#machine.saveSnapshot(backup);
1489
+ if (backup !== undefined) await this.#machine.saveSnapshot(backup);
1472
1490
  try {
1473
1491
  return await this.#restoreFrom(file);
1474
1492
  } catch (error) {
1493
+ if (backup === undefined) {
1494
+ throw new WireFailure(
1495
+ "machine-state-lost",
1496
+ "The emulator did not restore this snapshot file, and it reset the machine. A snapshot file restores only in the emulator version and with the machine settings that saved it. Use c64_reset with run false to stop at the reset again.",
1497
+ );
1498
+ }
1475
1499
  const kept = await this.#restoreFrom(backup).then(
1476
1500
  () => true,
1477
1501
  () => false,
@@ -1489,7 +1513,7 @@ export class ViceSession implements ViceSessionHandle {
1489
1513
  );
1490
1514
  } finally {
1491
1515
  rmSync(file, { force: true });
1492
- rmSync(backup, { force: true });
1516
+ if (backup !== undefined) rmSync(backup, { force: true });
1493
1517
  }
1494
1518
  }
1495
1519
 
@@ -1506,13 +1530,17 @@ export class ViceSession implements ViceSessionHandle {
1506
1530
  if (this.#mode === mode) return { window: mode === "window", state: this.#state, notCarried: [] };
1507
1531
  if (this.#held !== undefined) throw new WireFailure("machine-unavailable", this.#heldWhy);
1508
1532
  if (this.#launch === undefined) throw new WireFailure("operation-failed", "This session cannot start another emulator.");
1533
+ const verb = mode === "window" ? "open the window" : "close the window";
1534
+ this.#refuseAtResetStop(verb);
1535
+ await this.#refuseWhileAutostartLoads("a move to another emulator now stops it before RUN", verb);
1509
1536
  const running = this.#state === "running";
1510
1537
  this.#log(mode === "window" ? "moving the machine to a VICE with a window" : "moving the machine back to a headless VICE");
1511
1538
  await this.#stop();
1512
1539
  const handover: Handover = {
1513
1540
  file: join(this.#workDir, mode === "window" ? "window-open.vsf" : "window-close.vsf"),
1514
1541
  running,
1515
- warp: await this.#machine.warp(),
1542
+ // VICE's own warp can be the one of a loading autostart.
1543
+ warp: this.#userWarp,
1516
1544
  elapsed: (await this.#machine.clock()) - this.#timingStart,
1517
1545
  };
1518
1546
  await this.#machine.saveSnapshot(handover.file);
@@ -344,6 +344,9 @@ export function newStepForm(kind: string, step: Record<string, unknown>): { fiel
344
344
  }
345
345
  }
346
346
 
347
+ /** "a write step", "an observe step": the step kind with its article, for a refusal. */
348
+ export const aStep = (kind: string): string => `${/^[aeiou]/.test(kind) ? "an" : "a"} ${kind} step`;
349
+
347
350
  /** Refuses a step in a form of the 2.0 files: the message names its 2.0 fields and gives the step to write. */
348
351
  export function refuseOldStep(kind: string, step: Record<string, unknown>, at: string, fail: (message: string) => never): void {
349
352
  const found = newStepForm(kind, step);
@@ -359,7 +362,7 @@ export function refuseOldStep(kind: string, step: Record<string, unknown>, at: s
359
362
  */
360
363
  export function checkActionStep(kind: ActionStepKind, step: Record<string, unknown>, at: string, fail: (message: string) => never): ActionStep {
361
364
  refuseOldStep(kind, step, at, fail);
362
- for (const key of Object.keys(step)) if (key !== kind) fail(`${at} has the key ${key}, which a ${kind} step does not have`);
365
+ for (const key of Object.keys(step)) if (key !== kind) fail(`${at} has the key ${key}, which ${aStep(kind)} does not have`);
363
366
  return checkInput(kind, step[kind], at, fail);
364
367
  }
365
368
 
@@ -1,7 +1,7 @@
1
1
  // Short-lived typed requests to the Host Runtime for skill scripts:
2
2
  // VICE's own tools (c1541, petcat) and the host tool status. Each request
3
3
  // opens its own "tool" connection, sends bytes, and closes. Skill scripts run
4
- // ACME, DXA and Ghidra themselves through src/native (Ghidra in process).
4
+ // ACME, DXA and the decompiler themselves through src/native (the decompiler in process).
5
5
 
6
6
  import { ProtocolError, WireFailure } from "../protocol/messages.ts";
7
7
  import { DISK_IMAGE_TYPES, validateToolResult, type C1541Result, type DiskAction, type DiskImageType, type DiskSector, type PetcatResult, type ToolOperation, type ToolOperations } from "../protocol/tools.ts";
@@ -0,0 +1,66 @@
1
+ // The files that the knowledge gives as evidence, against the project as it
2
+ // is now. A revision keeps the SHA-256 of each file that it rests on, so a
3
+ // file that is gone or that changed since then shows here.
4
+
5
+ import { createHash } from "node:crypto";
6
+ import { readFileSync } from "node:fs";
7
+ import type { DatabaseSync } from "node:sqlite";
8
+
9
+ import { LOCAL_DIRECTORY, PROJECT_DIRECTORY, resolveProjectFile } from "../project.ts";
10
+ import { coverageRuns } from "./read.ts";
11
+
12
+ /** A file of the evidence that is not as the knowledge gives it: missing, or with other bytes. */
13
+ export interface EvidenceChange {
14
+ /** The project path of the file. */
15
+ file: string;
16
+ state: "missing" | "changed";
17
+ /** The revisions that give the file with the SHA-256 that the file no longer has, oldest first. */
18
+ revisions: string[];
19
+ }
20
+
21
+ /** The SHA-256 of a project file, or undefined when it is not there. */
22
+ function fileHash(root: string, path: string): string | undefined {
23
+ try {
24
+ return createHash("sha256").update(readFileSync(resolveProjectFile(path, root))).digest("hex");
25
+ } catch {
26
+ return undefined;
27
+ }
28
+ }
29
+
30
+ /**
31
+ * The evidence files that are missing or changed. A file counts with its
32
+ * latest SHA-256 in the knowledge: for a coverage map, its latest import
33
+ * into each space; for another file, the latest revision that gives it. An
34
+ * earlier SHA-256 of the same file is history. A file in
35
+ * .c64-re-tools/local/ does not count: git does not keep it, and the
36
+ * knowledge keeps what it needs of it. `only` limits the check to some files.
37
+ */
38
+ export function changedEvidence(db: DatabaseSync | undefined, root: string, only?: (file: string) => boolean): EvidenceChange[] {
39
+ if (db === undefined) return [];
40
+ const rows = db.prepare("SELECT revision, kind, ref, sha256 FROM evidence WHERE sha256 IS NOT NULL ORDER BY revision, id").all() as Array<{ revision: string; kind: string; ref: string; sha256: string }>;
41
+ const local = `${PROJECT_DIRECTORY}/${LOCAL_DIRECTORY}/`;
42
+ const wanted = (file: string) => !file.startsWith(local) && (only === undefined || only(file));
43
+ // The SHA-256 values that each file must have now.
44
+ const expected = new Map<string, Set<string>>();
45
+ const expect = (file: string, sha256: string) => {
46
+ if (!wanted(file)) return;
47
+ if (!expected.has(file)) expected.set(file, new Set());
48
+ expected.get(file)!.add(sha256);
49
+ };
50
+ const latest = new Map<string, string>();
51
+ for (const row of rows) if (row.kind !== "coverage") latest.set(row.ref, row.sha256);
52
+ for (const [file, sha256] of latest) expect(file, sha256);
53
+ // The runs of a name are oldest first: the last run in each space is the map that the knowledge has.
54
+ const maps = new Map(coverageRuns(db).map((run) => [`${run.space}\n${run.name}`, run]));
55
+ for (const run of maps.values()) expect(run.name, run.sha256);
56
+ const changes: EvidenceChange[] = [];
57
+ for (const [file, hashes] of [...expected].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) {
58
+ const now = fileHash(root, file);
59
+ for (const sha256 of hashes) {
60
+ if (now === sha256) continue;
61
+ const revisions = [...new Set(rows.filter((row) => row.ref === file && row.sha256 === sha256).map((row) => row.revision))];
62
+ changes.push({ file, state: now === undefined ? "missing" : "changed", revisions });
63
+ }
64
+ }
65
+ return changes;
66
+ }
@@ -86,12 +86,12 @@ export interface EntryRow {
86
86
  revision: string;
87
87
  }
88
88
 
89
- /** A coverage range of one kind. */
89
+ /** The ranges of one kind of the coverage map at a project path: their number. */
90
90
  export interface CoverageRow {
91
91
  space: Space;
92
+ map: string;
92
93
  kind: CoverageKind;
93
- start: number;
94
- end: number;
94
+ ranges: number;
95
95
  origin: Origin;
96
96
  revision: string;
97
97
  }
@@ -285,8 +285,8 @@ export function revision(db: DatabaseSync | undefined, text: string): RevisionCh
285
285
  [
286
286
  "coverage",
287
287
  "coverage",
288
- "space, kind, start_address, end_address, origin, valid_from_revision",
289
- (row: Raw): CoverageRow => ({ space: row.space as Space, kind: row.kind as CoverageKind, start: row.start_address as number, end: row.end_address as number, origin: row.origin as Origin, revision: row.valid_from_revision as string }),
288
+ "space, map, kind, length(ranges) - length(replace(ranges, ' ', '')) + 1 AS ranges, origin, valid_from_revision",
289
+ (row: Raw): CoverageRow => ({ space: row.space as Space, map: row.map as string, kind: row.kind as CoverageKind, ranges: row.ranges as number, origin: row.origin as Origin, revision: row.valid_from_revision as string }),
290
290
  ],
291
291
  ] as const;
292
292
  const added: HistoryEntry[] = [];