@henols/c64-re-tools 2.6.0-rc.17 → 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.17",
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",
@@ -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 {");
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);