@henols/c64-re-tools 2.6.0-rc.16 → 2.6.0-rc.18

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@henols/c64-re-tools",
3
- "version": "2.6.0-rc.16",
3
+ "version": "2.6.0-rc.18",
4
4
  "description": "Agent-friendly Commodore 64 engineering toolkit for reverse engineering, debugging, development and testing.",
5
5
  "license": "MIT",
6
6
  "author": "Henrik Olsson",
@@ -109,9 +109,9 @@ A rebuilt program gets its source from the project knowledge. A change is a swit
109
109
  - Build the base release and compare it with the original. This build must be identical to the original.
110
110
  - Build the default build.
111
111
  - When the default build does not have the switch, set the switch to 1 in `src/config.asm`. Then build the default build. After the test, set the value back to the default if the user did not ask for the change.
112
- 8. Test the build that has the switch:
113
- - When the behavior must stay the same as the original, replay a recording that executes the changed code. Run a test scenario in `tests/` only when no recording executes that code.
114
- - Run a run file with `expect` steps that show the feature or the fix.
112
+ 8. Test the builds:
113
+ - When the behavior must stay the same as the original, replay each recording on the default build `build/clean.prg`. Do not replay a build with a switch that is not at its default. Run a test scenario in `tests/` only when no recording executes the changed code.
114
+ - On the build that has the switch, run a run file with `expect` steps that show the feature or the fix.
115
115
 
116
116
  ### The answer
117
117
 
@@ -85,7 +85,7 @@ Do the stages in this sequence. Go to the next stage only when its exit check is
85
85
 
86
86
  | Stage | Work | Exit check |
87
87
  |---|---|---|
88
- | 1. Acceptance | Ask the user for the criteria of the rebuild. Offer these criteria: a base release that is identical to the original, and a passed replay of the default build. Also offer a replay of each recording, test scenarios and a list of the code that no run executed. Also offer documentation of the flows, tables, formats and graphics. | The user gave the criteria. |
88
+ | 1. Acceptance | Ask the user for the criteria of the rebuild. Offer these criteria: a base release that is identical to the original, and a passed replay of each recording on the default build. Also offer test scenarios and a list of the code that no run executed. Also offer documentation of the flows, tables, formats and graphics. | The user gave the criteria. |
89
89
  | 2. Get | List the disk image. Extract the start file into `original/`. | The start file is in the project. |
90
90
  | 3. Start | Find the SYS address of the BASIC start. | You have the entry address. |
91
91
  | 4. Unpack | Examine the program for a packer. Trace it and find its stages. Capture a packed program into `.c64-re-tools/local/`. When a segment is the data of a cracktro and the program does not read it, capture again and exclude that range. Put the capture, or the PRG of a program without a packer, into the project knowledge. | The program in the project knowledge has the segments and the entry. |
@@ -94,15 +94,15 @@ Do the stages in this sequence. Go to the next stage only when its exit check is
94
94
  | 7. Name | If the workspace has a routine library, match the program against it. Write the names of the matches to the project knowledge. Then name each routine in the scope and give it a comment. Find the platform addresses in the memory map of the C64. Record the modules. Put the modules of one part of the program in one folder, for example `music/`, `irq/` or `graphics/`. When the scope has hundreds of routines, ask the user which routines to name. The source gives the other routines an `l_xxxx` label. | Each routine that the user selected has a name and a comment. |
95
95
  | 8. Releases and switches | Record the original file, or the capture of it, as the base release in the project knowledge. The project knowledge keeps the bytes of each release. Record each other release. Compare the releases. Find the leftovers. Record a switch for each copy protection, trainer, cheat, crack change and correction. Record a patch for each range of a switch. Record each leftover as a region with a comment. | The project knowledge lists each switch. Each difference between the releases is in a patch, or the answer gives it as an exception. |
96
96
  | 9. Generate | Generate the source from the project knowledge into `src`. For an unpacked program, also generate the loader. | The result of the generation is PASS. A release whose code is at other addresses is a version with a project of its own, or an exception in the answer. See "Versions of one program". |
97
- | 10. Build and test | Build the base release into `build/`, and compare it with the original. Build the default build. Replay one recording on the default build. For each replay, give the checkpoint routine, the state and the random state with the names of stage 7. Then do only the tests that the next paragraph gives. | The criteria of stage 1 are true. |
97
+ | 10. Build and test | Build the base release into `build/`, and compare it with the original. Build the default build `build/clean.prg`. Replay each recording on it. For each replay, give the checkpoint routine, the state and the random state with the names of stage 7. Then do only the tests that the next paragraph gives. | The criteria of stage 1 are true. |
98
98
  | 11. Document | When the criteria ask for documentation, generate it into `README.md` and `docs/`. For versions in a group folder, also write the shared pages of the group folder. Then link the pages. | The link check of the documentation gives PASS. |
99
99
  | 12. Hand over | Find each file that you made outside `.c64-re-tools/local/` and that is not a deliverable. Move it into `.c64-re-tools/local/`. Then give the answer (below). | Each file that you made outside `.c64-re-tools/local/` is a deliverable. |
100
100
 
101
101
  In stage 5, make the recordings before you change the program. A recording needs no names, and its coverage gives the analysis of stage 6 more code. If you cannot get to a part of the program, ask the user how to get to it. Do stages 7 to 9 again until the source is clear. Each generation writes the source again.
102
102
 
103
- In stage 10, a base release that is identical to the original proves the source. Do not test the base release more. The default build is different from the base release only in its patches, its leftovers and its loader. Thus test only these differences:
103
+ In stage 10, a base release that is identical to the original proves the source. Do not test the base release more. The default build is different from the base release only in its patches, its leftovers and its loader. The replays on the default build test these differences:
104
104
 
105
- - When a patch of the default build changes code that a run executed, replay each recording of the part that has that code. A copy protection check is an example.
105
+ - Replay only the default build `build/clean.prg`. Do not replay a release build or a build with a switch that is not at its default.
106
106
  - Write a test scenario only for a test that a replay cannot do. Examples are a program that loads more files from a disk, and a criterion of the user.
107
107
  - Do the other tests of stage 1 only when the user selected them.
108
108
 
@@ -22,6 +22,7 @@ import { compareBuild, mergedPrograms } from "#src/compare.ts";
22
22
  import { Refusal } from "#src/errors.ts";
23
23
  import { parseEntryState } from "#src/host-client/entry-state.ts";
24
24
  import { isRomFont, startScreenRanges, type StartScreenRow } from "#src/knowledge/read.ts";
25
+ import { romUseOfPort } from "#src/platform.ts";
25
26
  import { WireFailure } from "#src/host-client/tools.ts";
26
27
  import { pack } from "#src/native/exomizer.ts";
27
28
  import type { ToolContext } from "#src/native/run.ts";
@@ -641,11 +642,19 @@ export function planLoader(input: LoaderInput): LoaderPlan {
641
642
  };
642
643
  }
643
644
 
644
- /** Where the packed form puts its copier with the bytes of pages 0-3: the copier sets $01 to $35 and to the entry's value, so it is not under a ROM or the I/O area. */
645
- const PACKED_AREAS: readonly AddressRange[] = [
646
- { start: 0x0400, end: 0x9fff },
647
- { start: 0xc000, end: 0xcfff },
648
- ];
645
+ /** Where the packed form puts the bytes of pages 0-3: the copier reads them with all RAM visible ($01 = $34). */
646
+ const PIECE_AREA: AddressRange = { start: 0x0400, end: 0xffff };
647
+
648
+ /**
649
+ * Where the packed form puts its copier: the copier sets $01 to $35 and then
650
+ * to the entry's value, so it is in RAM that both show. A port bit that is an
651
+ * input reads 1.
652
+ */
653
+ export function copierAreas(port: readonly [number, number]): AddressRange[] {
654
+ const rom = romUseOfPort((port[1] | ~port[0]) & 0x07);
655
+ if (rom.basic) return [{ start: 0x0400, end: 0x9fff }, { start: 0xc000, end: 0xcfff }];
656
+ return [{ start: 0x0400, end: 0xcfff }, ...(rom.kernal ? [] : [{ start: 0xe000, end: 0xffff }])];
657
+ }
649
658
  /** The free ranges that a refusal of the packed form names. */
650
659
  const SHOWN_FREE = 8;
651
660
 
@@ -669,15 +678,16 @@ function planPacked(input: LoaderInput, blocks: Block[], cia: ReturnType<typeof
669
678
  return [{ what: cut ? `${block.what}, part ${show(range)}` : block.what, range, bytes: block.bytes }];
670
679
  });
671
680
  const lowBytes = low.reduce((sum, block) => sum + block.range.end - block.range.start + 1, 0);
672
- const free = PACKED_AREAS.flatMap((area) => subtract(area, input.segments));
673
- const placed = placePacked(free, low, codeSize);
681
+ const areas = copierAreas(state.port);
682
+ const free = subtract(PIECE_AREA, input.segments);
683
+ const placed = placePacked(areas.flatMap((area) => subtract(area, input.segments)), free, low, codeSize);
674
684
  if ("refusal" in placed) {
675
685
  const largest = [...free].sort((a, b) => b.end - b.start - (a.end - a.start)).slice(0, SHOWN_FREE);
676
686
  const ranges = largest.length === 0 ? "none" : largest.map((range) => `${show(range)} (${range.end - range.start + 1} bytes)`).join(", ");
677
687
  const why =
678
688
  placed.refusal === "copies"
679
689
  ? `A packed loader needs more than ${MAX_PACKED_COPIES} copies for the ${lowBytes} bytes of pages 0-3 in the free ranges.`
680
- : `A packed loader needs one free range of ${codeSize + COPY_ENTRY * Math.max(low.length, 1) + 2} bytes or more for its copier, and ${lowBytes} more free bytes for pages 0-3, in $0400-$9fff or $c000-$cfff outside the segments.${screen === undefined ? "" : ` The start screen takes ${START_SCREEN_SIZES[screen.colourMode]} bytes of the copier: without it (unstart-screen), the copier is smaller.`}`;
690
+ : `A packed loader needs one free range of ${codeSize + COPY_ENTRY * Math.max(low.length, 1) + 2} bytes or more for its copier in ${areas.map(show).join(" or ")}, and ${lowBytes} more free bytes for pages 0-3 in $0400-$ffff, outside the segments. The copier runs with $01 = $35 and then with the $01 of the entry, so it is in RAM that both show.${screen === undefined ? "" : ` The start screen takes ${START_SCREEN_SIZES[screen.colourMode]} bytes of the copier: without it (unstart-screen), the copier is smaller.`}`;
681
691
  throw new WireFailure("invalid-input", `${tooLarge} ${why} The largest free ranges there: ${ranges}. Write the loader by hand.`);
682
692
  }
683
693
  const { copier, pieces } = placed;
@@ -788,19 +798,19 @@ export function placePieces(ranges: AddressRange[], low: ReadonlyArray<{ what: s
788
798
 
789
799
  /**
790
800
  * Where the packed form puts its copier and the pieces of pages 0-3: the copier
791
- * in one free range, a free page of the plain copier first, else the start of a
801
+ * in one range of copierFree, a free page of the plain copier first, else the start of a
792
802
  * free range. The placement with the fewest pieces wins, then the one with the
793
803
  * shortest build of loader.asm.
794
804
  */
795
- function placePacked(free: AddressRange[], low: Parameters<typeof placePieces>[1], codeSize: number): { copier: number; pieces: Piece[] } | { refusal: "room" | "copies" } {
796
- const candidates = [...COPIER_PAGES, ...free.map((range) => range.start)];
805
+ function placePacked(copierFree: AddressRange[], free: AddressRange[], low: Parameters<typeof placePieces>[1], codeSize: number): { copier: number; pieces: Piece[] } | { refusal: "room" | "copies" } {
806
+ const candidates = [...COPIER_PAGES, ...copierFree.map((range) => range.start)];
797
807
  // The table has one entry per piece: a split can make the copier larger, so the room for the table grows until it holds every piece.
798
808
  for (let copies = Math.max(low.length, 1); copies <= MAX_PACKED_COPIES; ) {
799
809
  const size = codeSize + COPY_ENTRY * copies + 2;
800
810
  let best: { copier: number; pieces: Piece[]; span: number } | undefined;
801
811
  for (const copier of candidates) {
802
812
  const range = { start: copier, end: copier + size - 1 };
803
- if (!free.some((area) => range.start >= area.start && range.end <= area.end)) continue;
813
+ if (!copierFree.some((area) => range.start >= area.start && range.end <= area.end)) continue;
804
814
  // A piece goes to the start of its range: a range below the copier adds its whole length to the build.
805
815
  const distance = (other: AddressRange) => (other.end < range.start ? range.start - other.start : other.start - range.end);
806
816
  const pieces = placePieces(free.flatMap((area) => subtract(area, [range])), low, distance);
@@ -1102,6 +1102,9 @@ function macrosText(layout: Layout): { text: string; lines: Map<string, { first:
1102
1102
  return { text: `${out.join("\n")}\n`, lines };
1103
1103
  }
1104
1104
 
1105
+ /** The bytes of the patch code so far: after a byte at $ffff, ACME sets * to $0000. */
1106
+ const LENGTH = "((* - .patch_start) & $ffff)";
1107
+
1105
1108
  /** The condition that puts in the code of a switch: the switch has the value that the program does not have. */
1106
1109
  const patchCondition = (alternative: PatchAlternative) => (alternative.base === 0 ? alternative.switch : `${alternative.switch} = 0`);
1107
1110
 
@@ -1128,7 +1131,7 @@ function patchOpening(patch: PatchBlock): string[] {
1128
1131
  `${INDENT}; ${alternative.switch} ${state}: ${bytes} byte${bytes === 1 ? "" : "s"} at ${range}, NOP after the code`,
1129
1132
  ...comment,
1130
1133
  ...(alternative.code === "" ? [] : alternative.code.split(/\r?\n/)),
1131
- `${INDENT}!if * - .patch_start > ${bytes} { !error "The patch ${alternative.switch} at ${formatC64Address(patch.start)} has ", * - .patch_start, " bytes; the range has ${bytes}." } else { !fill ${bytes} - (* - .patch_start), $ea }`,
1134
+ `${INDENT}!if ${LENGTH} > ${bytes} { !error "The patch ${alternative.switch} at ${formatC64Address(patch.start)} has ", ${LENGTH}, " bytes; the range has ${bytes}." } else { !fill ${bytes} - ${LENGTH}, $ea }`,
1132
1135
  );
1133
1136
  });
1134
1137
  out.push("} else {");
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: c64-testing
3
- description: Tests if a rebuilt or changed C64 program behaves as the original, or if a program has the expected values. It runs a scenario on the original and on the rebuild in an emulator. It compares memory, registers, chip state and the screen with explicit rules, and gives PASS, FAIL or INCONCLUSIVE. Use it when you must show that a rebuild or a correction keeps the behavior of the original. Use it to do many steps on one program and keep the screens, coverage maps, traces and snapshots as files. Use it to test a new program or a correction with expected values. Use it to record a play session of the original and replay it on each rebuild. Use it to find what changed between two machine states, and to make a checklist for a human playtest. It does not find the cause of a difference. It does not build the program.
3
+ description: Tests if a rebuilt or changed C64 program behaves as the original, or if a program has the expected values. It runs a scenario on the original and on the rebuild in an emulator. It compares memory, registers, chip state and the screen with explicit rules, and gives PASS, FAIL or INCONCLUSIVE. Use it when you must show that a rebuild or a correction keeps the behavior of the original. Use it to do many steps on one program and keep the screens, coverage maps, traces and snapshots as files. Use it to test a new program or a correction with expected values. Use it to record a play session of the original and replay it on the default build of the rebuild. Use it to find what changed between two machine states, and to make a checklist for a human playtest. It does not find the cause of a difference. It does not build the program.
4
4
  ---
5
5
 
6
6
  # C64 testing
@@ -179,6 +179,7 @@ A recording keeps a session of the original program, for example a play through
179
179
  - Make the recordings early, before you change the program.
180
180
  - Ask the user to play first. Tell the user which parts of the program the recordings must have, for example each room, a fight and a lost life.
181
181
  - Record a session from steps only for a part that the sessions of the user do not have, or when the user cannot play.
182
+ - Replay each recording on the default build `build/clean.prg`. Do not replay a release build or a build with a switch that is not at its default.
182
183
  - Commit the recording folder with the scenarios. Do not put a recording into the project knowledge. Do not put test results, screenshots or playtest results into it.
183
184
  - A finding that a recording shows can go into the project knowledge. Give the `recording.json` of the recording as its test evidence.
184
185
  - The C64 of a recording has no disk drive. For a program that loads more files from a disk, use a scenario with `test`.
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);
@@ -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);