@henols/c64-re-tools 2.6.0-rc.2 → 2.6.0-rc.20

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 (107) hide show
  1. package/package.json +2 -2
  2. package/skills/c64-assembler/SKILL.md +28 -14
  3. package/skills/c64-assembler/scripts/assembler.ts +28 -15
  4. package/skills/c64-development/SKILL.md +4 -4
  5. package/skills/c64-docs/SKILL.md +9 -7
  6. package/skills/c64-docs/scripts/docs.ts +24 -11
  7. package/skills/c64-docs/scripts/lib/reference.ts +119 -33
  8. package/skills/c64-docs/scripts/lib/source-map.ts +23 -4
  9. package/skills/c64-knowledge/SKILL.md +67 -42
  10. package/skills/c64-knowledge/scripts/knowledge.ts +90 -67
  11. package/skills/c64-knowledge/scripts/lib/listing.ts +18 -3
  12. package/skills/c64-packer/SKILL.md +1 -1
  13. package/skills/c64-provenance/SKILL.md +11 -10
  14. package/skills/c64-provenance/scripts/lib/library.ts +16 -16
  15. package/skills/c64-provenance/scripts/provenance.ts +33 -23
  16. package/skills/c64-reverse-engineering/SKILL.md +17 -11
  17. package/skills/c64-source/SKILL.md +71 -47
  18. package/skills/c64-source/scripts/lib/export.ts +89 -34
  19. package/skills/c64-source/scripts/lib/loader.ts +79 -36
  20. package/skills/c64-source/scripts/lib/source.ts +38 -32
  21. package/skills/c64-source/scripts/lib/stage.ts +11 -5
  22. package/skills/c64-source/scripts/lib/start-screen.asm +4 -2
  23. package/skills/c64-source/scripts/source.ts +278 -145
  24. package/skills/c64-static-analysis/SKILL.md +29 -25
  25. package/skills/c64-static-analysis/scripts/lib/coverage.ts +2 -25
  26. package/skills/c64-static-analysis/scripts/lib/findings.ts +11 -11
  27. package/skills/c64-static-analysis/scripts/lib/instructions.ts +26 -24
  28. package/skills/c64-static-analysis/scripts/lib/macros.ts +3 -1
  29. package/skills/c64-static-analysis/scripts/static-analysis.ts +69 -67
  30. package/skills/c64-testing/SKILL.md +15 -5
  31. package/skills/c64-testing/references/recording-format.md +26 -5
  32. package/skills/c64-testing/references/scenario-format.md +11 -8
  33. package/skills/c64-testing/scripts/lib/diff-files.ts +4 -18
  34. package/skills/c64-testing/scripts/lib/play.ts +39 -41
  35. package/skills/c64-testing/scripts/lib/recording.ts +220 -46
  36. package/skills/c64-testing/scripts/lib/replay.ts +32 -6
  37. package/skills/c64-testing/scripts/lib/runs.ts +8 -3
  38. package/skills/c64-testing/scripts/lib/scenario.ts +18 -11
  39. package/skills/c64-testing/scripts/testing.ts +23 -2
  40. package/skills/c64-unpacker/SKILL.md +10 -5
  41. package/skills/c64-unpacker/scripts/lib/loads.ts +34 -13
  42. package/skills/c64-unpacker/scripts/lib/machine.ts +7 -3
  43. package/skills/c64-unpacker/scripts/lib/stages.ts +18 -3
  44. package/skills/c64-unpacker/scripts/unpacker.ts +43 -9
  45. package/skills/emulator/SKILL.md +7 -12
  46. package/src/build-name.ts +55 -0
  47. package/src/c64-keys.ts +98 -0
  48. package/src/c64.ts +22 -2
  49. package/src/cli/main.ts +3 -29
  50. package/src/host/main.ts +3 -3
  51. package/src/host/server.ts +3 -1
  52. package/src/host/tools/index.ts +2 -7
  53. package/src/host/vice/process.ts +34 -17
  54. package/src/host/vice/session.ts +138 -31
  55. package/src/host-client/steps.ts +21 -18
  56. package/src/host-client/tools.ts +2 -7
  57. package/src/host-client/vice-session.ts +7 -1
  58. package/src/knowledge/evidence.ts +66 -0
  59. package/src/knowledge/history.ts +5 -5
  60. package/src/knowledge/import.ts +12 -5
  61. package/src/knowledge/program.ts +123 -32
  62. package/src/knowledge/read.ts +36 -13
  63. package/src/knowledge/schema.ts +43 -17
  64. package/src/knowledge/start-screen.ts +70 -0
  65. package/src/knowledge/text.ts +33 -5
  66. package/src/knowledge/write.ts +75 -36
  67. package/src/mcp/inputs.ts +12 -0
  68. package/src/mcp/server.ts +1 -1
  69. package/src/mcp/tools/debug.ts +23 -21
  70. package/src/mcp/tools/input.ts +38 -5
  71. package/src/mcp/tools/machine.ts +3 -42
  72. package/src/mcp/tools/media.ts +1 -1
  73. package/src/mcp/tools/memory.ts +12 -9
  74. package/src/native/acme.ts +1 -1
  75. package/src/native/c64run.ts +7 -4
  76. package/src/native/decompiler/analyze.ts +98 -0
  77. package/src/native/decompiler/c64rt-wasm.ts +4 -0
  78. package/src/native/decompiler/language/c64rt_6510.sla +0 -0
  79. package/src/native/{ghidra → decompiler}/language/c64rt_6510.slaspec +1 -1
  80. package/src/native/decompiler/pcode.ts +222 -0
  81. package/src/native/decompiler/walk.ts +205 -0
  82. package/src/native/decompiler/wasm.ts +98 -0
  83. package/src/native/discover.ts +3 -3
  84. package/src/native/dxa.ts +12 -1
  85. package/src/native/processes.ts +4 -4
  86. package/src/native/types.ts +27 -27
  87. package/src/opcodes.ts +1 -1
  88. package/src/platform.ts +30 -1
  89. package/src/project.ts +17 -4
  90. package/src/protocol/tools.ts +1 -45
  91. package/src/protocol/vice.ts +47 -0
  92. package/src/reference-pages.ts +64 -0
  93. package/src/script.ts +4 -4
  94. package/src/vsf.ts +98 -0
  95. package/tools/c64run.c +158 -15
  96. package/tools/install-container.sh +1 -2
  97. package/src/cli/status.ts +0 -127
  98. package/src/host/tools/status.ts +0 -47
  99. package/src/native/ghidra/analyze.ts +0 -87
  100. package/src/native/ghidra/index.ts +0 -170
  101. package/src/native/ghidra/scripts/C64Export.java +0 -274
  102. package/src/native/ghidra/scripts/C64Prepare.java +0 -66
  103. package/src/native/status.ts +0 -135
  104. package/tools/install-ghidra.sh +0 -40
  105. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.cspec +0 -0
  106. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.ldefs +0 -0
  107. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.pspec +0 -0
@@ -8,6 +8,7 @@
8
8
 
9
9
  import { createServer, type ServerResponse } from "node:http";
10
10
 
11
+ import { keyTaps, type KeyTap } from "#src/c64-keys.ts";
11
12
  import { PAL_FRAME_CYCLES, type C64RunSession } from "#src/native/c64run.ts";
12
13
 
13
14
  const FRAME_MS = 20;
@@ -26,50 +27,46 @@ export interface PlayOptions {
26
27
  restore: () => Promise<string | undefined>;
27
28
  }
28
29
 
29
- /** The key codes of the replay core: chips c64.h, and 11, 12 and 5e of c64run. */
30
- const C64 = {
31
- del: 0x01, clr: 0x02, stop: 0x03, leftArrow: 0x04, run: 0x07, csrLeft: 0x08, csrRight: 0x09, csrDown: 0x0a, csrUp: 0x0b,
32
- home: 0x0c, return: 0x0d, ctrl: 0x0e, cbm: 0x0f, inst: 0x10, leftShift: 0x11, rightShift: 0x12, space: 0x20, upArrow: 0x5e, pound: 0x7e,
33
- } as const;
34
- const F_KEYS = [0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8];
35
30
  const LETTERS = [..."ABCDEFGHIJKLMNOPQRSTUVWXYZ"];
36
31
  const DIGITS = [..."0123456789"];
37
- const code = (character: string) => character.charCodeAt(0);
32
+ const F_KEYS = [1, 2, 3, 4, 5, 6, 7, 8].map((number) => `{F${number}}`);
33
+ /** The matrix places of one key, as a press step names it: a character, or a name in braces. */
34
+ const places = (key: string) => (keyTaps(key) as KeyTap[])[0]!.keys;
38
35
 
39
36
  /**
40
- * The key maps of the page. Each one maps a KeyboardEvent property to a key code.
41
- * The symbolic map (event.key) gives the character on the PC key; the positional
42
- * map (event.code) gives the C64 key at the place of the PC key, with each SHIFT alone.
37
+ * The key maps of the page. Each one maps a KeyboardEvent property to the matrix places
38
+ * that go down together. The symbolic map (event.key) gives the character on the PC key;
39
+ * the positional map (event.code) gives the C64 key at the place of the PC key, with each SHIFT alone.
43
40
  */
44
41
  export const KEY_MAPS = {
45
42
  /** event.code, in both maps. */
46
- both: { Tab: C64.ctrl, AltLeft: C64.cbm },
43
+ both: { Tab: places("{CTRL}"), AltLeft: places("{CBM}") },
47
44
  /** event.code, when the arrow keys and space are keyboard keys. */
48
- arrows: { ArrowUp: C64.csrUp, ArrowDown: C64.csrDown, ArrowLeft: C64.csrLeft, ArrowRight: C64.csrRight, Space: C64.space },
45
+ arrows: { ArrowUp: places("{UP}"), ArrowDown: places("{DOWN}"), ArrowLeft: places("{LEFT}"), ArrowRight: places("{RIGHT}"), Space: places(" ") },
49
46
  /** event.code */
50
47
  positional: {
51
- ...Object.fromEntries(LETTERS.map((letter) => ["Key" + letter, code(letter)])),
52
- ...Object.fromEntries(DIGITS.map((digit) => ["Digit" + digit, code(digit)])),
53
- ...Object.fromEntries(F_KEYS.map((key, index) => ["F" + (index + 1), key])),
54
- Backquote: C64.leftArrow, Minus: code("+"), Equal: code("-"), Insert: C64.pound, Home: C64.home, Backspace: C64.del,
55
- BracketLeft: code("@"), BracketRight: code("*"), Delete: C64.upArrow,
56
- Escape: C64.stop, Semicolon: code(":"), Quote: code(";"), Backslash: code("="), Enter: C64.return,
57
- ShiftLeft: C64.leftShift, ShiftRight: C64.rightShift, Comma: code(","), Period: code("."), Slash: code("/"),
58
- } as Record<string, number>,
48
+ ...Object.fromEntries(LETTERS.map((letter) => ["Key" + letter, places(letter)])),
49
+ ...Object.fromEntries(DIGITS.map((digit) => ["Digit" + digit, places(digit)])),
50
+ ...Object.fromEntries(F_KEYS.map((key, index) => ["F" + (index + 1), places(key)])),
51
+ Backquote: places("{LEFTARROW}"), Minus: places("+"), Equal: places("-"), Insert: places("{POUND}"), Home: places("{HOME}"), Backspace: places("{DEL}"),
52
+ BracketLeft: places("@"), BracketRight: places("*"), Delete: places("{UPARROW}"),
53
+ Escape: places("{STOP}"), Semicolon: places(":"), Quote: places(";"), Backslash: places("="), Enter: places("{RETURN}"),
54
+ ShiftLeft: places("{LSHIFT}"), ShiftRight: places("{RSHIFT}"), Comma: places(","), Period: places("."), Slash: places("/"),
55
+ } as Record<string, number[]>,
59
56
  /** event.key; a-z are the C64 letters, A-Z the letters with SHIFT. */
60
57
  symbolic: {
61
- ...Object.fromEntries(LETTERS.flatMap((letter) => [[letter.toLowerCase(), code(letter)], [letter, code(letter.toLowerCase())]])),
62
- ...Object.fromEntries([...DIGITS, ..."+-.:@,*;=/!\"#$%&'()[]<>?"].map((character) => [character, code(character)])),
63
- ...Object.fromEntries(F_KEYS.map((key, index) => ["F" + (index + 1), key])),
64
- "£": C64.pound, "^": C64.upArrow, "`": C64.leftArrow,
65
- Enter: C64.return, Backspace: C64.del, Delete: C64.del, Insert: C64.inst, Home: C64.home, Escape: C64.stop,
66
- } as Record<string, number>,
58
+ ...Object.fromEntries(LETTERS.flatMap((letter) => [[letter.toLowerCase(), places(letter)], [letter, places(`{LSHIFT+${letter}}`)]])),
59
+ ...Object.fromEntries([...DIGITS, ..."+-.:@,*;=/!\"#$%&'()[]<>?"].map((character) => [character, places(character)])),
60
+ ...Object.fromEntries(F_KEYS.map((key, index) => ["F" + (index + 1), places(key)])),
61
+ "£": places("{POUND}"), "^": places("{UPARROW}"), "`": places("{LEFTARROW}"),
62
+ Enter: places("{RETURN}"), Backspace: places("{DEL}"), Delete: places("{DEL}"), Insert: places("{INST}"), Home: places("{HOME}"), Escape: places("{STOP}"),
63
+ } as Record<string, number[]>,
67
64
  /** event.key with SHIFT held, in the symbolic map. */
68
- symbolicShift: { Home: C64.clr, Backspace: C64.inst, Escape: C64.run, F1: 0xf2, F3: 0xf4, F5: 0xf6, F7: 0xf8 } as Record<string, number>,
65
+ symbolicShift: { Home: places("{CLR}"), Backspace: places("{INST}"), Escape: places("{RUN}"), F1: places("{F2}"), F3: places("{F4}"), F5: places("{F6}"), F7: places("{F8}") } as Record<string, number[]>,
69
66
  };
70
67
 
71
- /** The key codes that the page can send: every code of the key maps. */
72
- const PAGE_KEYS = new Set(Object.values(KEY_MAPS).flatMap((map) => Object.values(map)));
68
+ /** The matrix places that the page can send: every place of the key maps. */
69
+ const PAGE_KEYS = new Set(Object.values(KEY_MAPS).flatMap((map) => Object.values(map).flat()));
73
70
 
74
71
  const PAGE = String.raw`<!doctype html>
75
72
  <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
@@ -100,7 +97,7 @@ const BITS = { ArrowUp: 1, ArrowDown: 2, ArrowLeft: 4, ArrowRight: 8, Space: 16
100
97
  const $ = (id) => document.getElementById(id);
101
98
  const canvas = $("screen"), context = canvas.getContext("2d"), state = $("state");
102
99
  let palette = [], image = context.createImageData(392, 272), frames = 0, phase = "connecting", port = 2, arrows = "joystick", keyMap = "symbolic", sent = -1;
103
- // The C64 key of each PC key that is down (by event.code), and the joystick keys that are down.
100
+ // The matrix places of each PC key that is down (by event.code), and the joystick keys that are down.
104
101
  const pressed = new Map(), stick = new Set();
105
102
  // One request at a time, so that the core gets each key down before its key up.
106
103
  let queue = Promise.resolve();
@@ -120,7 +117,7 @@ function show() {
120
117
  else state.textContent = phase;
121
118
  }
122
119
  function releaseAll() {
123
- for (const code of pressed.values()) send("key?code=" + code.toString(16) + "&down=0");
120
+ for (const keys of pressed.values()) send("key?keys=" + keys.join(",") + "&down=0");
124
121
  pressed.clear();
125
122
  stick.clear();
126
123
  }
@@ -180,19 +177,19 @@ function key(event, down) {
180
177
  }
181
178
  if (arrows === "joystick" && event.code in BITS) { event.preventDefault(); down ? stick.add(event.code) : stick.delete(event.code); return; }
182
179
  if (!down) {
183
- const code = pressed.get(event.code);
184
- if (code === undefined) return;
180
+ const keys = pressed.get(event.code);
181
+ if (keys === undefined) return;
185
182
  event.preventDefault();
186
183
  pressed.delete(event.code);
187
- send("key?code=" + code.toString(16) + "&down=0");
184
+ send("key?keys=" + keys.join(",") + "&down=0");
188
185
  return;
189
186
  }
190
- const code = c64Key(event);
191
- if (code === undefined) return;
187
+ const keys = c64Key(event);
188
+ if (keys === undefined) return;
192
189
  event.preventDefault();
193
190
  if (event.repeat || phase !== "playing" || pressed.has(event.code)) return;
194
- pressed.set(event.code, code);
195
- send("key?code=" + code.toString(16) + "&down=1");
191
+ pressed.set(event.code, keys);
192
+ send("key?keys=" + keys.join(",") + "&down=1");
196
193
  }
197
194
  addEventListener("keydown", (event) => key(event, true));
198
195
  addEventListener("keyup", (event) => key(event, false));
@@ -262,9 +259,10 @@ export async function play(core: Pick<C64RunSession, "command" | "status">, opti
262
259
  if (phase === "playing") mask = Number(url.searchParams.get("mask")) & 0x1f;
263
260
  answer(phase === "playing");
264
261
  } else if (request.method === "POST" && url.pathname === "/key") {
265
- const key = Number.parseInt(url.searchParams.get("code") ?? "", 16);
266
- if (!PAGE_KEYS.has(key)) return void response.writeHead(400).end();
267
- if (phase === "playing") pending.push("key " + key.toString(16) + " " + (url.searchParams.get("down") === "1" ? "down" : "up"));
262
+ const keys = (url.searchParams.get("keys") ?? "").split(",").map((key) => (/^\d{1,2}$/.test(key) ? Number(key) : -1));
263
+ if (!keys.every((key) => PAGE_KEYS.has(key))) return void response.writeHead(400).end();
264
+ const state = url.searchParams.get("down") === "1" ? "down" : "up";
265
+ if (phase === "playing") for (const key of keys) pending.push("key " + (0x80 + key).toString(16) + " " + state);
268
266
  answer(phase === "playing");
269
267
  } else if (request.method === "POST" && url.pathname === "/restore") {
270
268
  if (phase === "playing") pending.push(RESTORE);
@@ -13,9 +13,11 @@ import { readFileSync, writeFileSync } from "node:fs";
13
13
 
14
14
  import { isRefusal, Refusal } from "#src/errors.ts";
15
15
  import { c64AddressOf, formatC64Address, parseC64Address } from "#src/c64.ts";
16
+ import { keyTaps, type KeyTap } from "#src/c64-keys.ts";
16
17
  import { READY_FRAMES } from "#src/host-client/entry-state.ts";
17
18
  import { ACTION_STEP_KINDS, checkActionStep, isInteger, isObject, keyboardBytes, renamedField, stepKind, type ActionStep, type Location } from "#src/host-client/steps.ts";
18
19
  import { readProjectFile, type Written } from "#src/host-client/transfer.ts";
20
+ import { LOADER_JUMP, START_SCREEN_CONTINUE, START_SCREEN_WAIT } from "#src/knowledge/start-screen.ts";
19
21
  import { PAL_FRAME_CYCLES, type C64RunSession, type CoreStatus } from "#src/native/c64run.ts";
20
22
  import type { Workspace } from "#src/native/staging.ts";
21
23
  import { namesOf, type Outcome } from "./scenario.ts";
@@ -37,6 +39,10 @@ export function inputsArgument(inputs: string[]): string {
37
39
  /** Frames that a pressed key is held, and then released. */
38
40
  const KEY_FRAMES = 3;
39
41
  const MAX_STATE_ITEMS = 16;
42
+ /** The replay core counts the opcode fetches at this many addresses at most: the targets of the runUntil steps to an address. */
43
+ const MAX_COUNTED_TARGETS = 64;
44
+ /** An event other than a runUntil to an address waits this long for the next input read. */
45
+ const READ_WAIT_FRAMES = 600;
40
46
  const MAX_STATE_BYTES = 4096;
41
47
  /** A replay of a rebuild may take this many times the cycles of the recording before it stops. */
42
48
  const REBUILD_TIME_FACTOR = 2;
@@ -97,9 +103,11 @@ export interface RecordedEvent {
97
103
  /**
98
104
  * The point: the n-th read at the busiest program site, or a tick when no
99
105
  * program site has read yet. An event that follows another event directly
100
- * has { previous: true }: it runs where that one ended.
106
+ * has { previous: true }: it runs where that one ended. A runUntil to an
107
+ * address has { pc, count }: the count-th opcode fetch at its target from the
108
+ * start, which needs no read; the event is done when the point is reached.
101
109
  */
102
- key: { site: Location; addr: Location; count: number } | { tick: number } | { previous: true };
110
+ key: { site: Location; addr: Location; count: number } | { tick: number } | { previous: true } | { pc: Location; count: number };
103
111
  }
104
112
 
105
113
  export interface RecordedSite {
@@ -137,20 +145,8 @@ const QUEUE_SIZE = 10;
137
145
 
138
146
  const hex = (address: number) => address.toString(16).padStart(4, "0");
139
147
 
140
- /** The keys of the replay core for the characters that a press step can have. */
141
- const KEY_CODES = new Map<string, number>([
142
- ...[..."ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 +-.:@,*;=/!\"#$%&'()[]<>?"].map((character) => [character, character.charCodeAt(0)] as [string, number]),
143
- ["\n", 0x0d],
144
- ]);
145
-
146
- /** The key codes of a text; a-z type as A-Z, as the C64 shows them after power-on. */
147
- export function keyCodes(text: string): number[] {
148
- return [...text.replace(/\r\n?/g, "\n")].map((character) => {
149
- const code = KEY_CODES.get(character.toUpperCase());
150
- if (code === undefined) throw new Refusal("invalid-input", `press cannot press ${JSON.stringify(character)} on the C64 keyboard`);
151
- return code;
152
- });
153
- }
148
+ /** The key code of the replay core for a matrix place: 80 + the place. RESTORE is ff. */
149
+ const coreKey = (place: number) => (0x80 + place).toString(16);
154
150
 
155
151
  /** The joystick mask of the replay core: 1 up, 2 down, 4 left, 8 right, $10 fire. */
156
152
  export function joystickMask(direction: Extract<ActionStep, { joystick: unknown }>["joystick"]["direction"], fire: boolean): number {
@@ -225,7 +221,7 @@ export function readRecordFile(path: string): RecordFile {
225
221
  if (!Array.isArray(value.steps) || value.steps.length === 0) fail("steps must be a list with at least one step");
226
222
  const steps = (value.steps as unknown[]).map((raw, index) => {
227
223
  const at = `step ${index + 1}`;
228
- const step = checkActionStep(stepKind(raw, ACTION_STEP_KINDS, at, fail), raw as Record<string, unknown>, at, fail, { press: true });
224
+ const step = checkActionStep(stepKind(raw, ACTION_STEP_KINDS, at, fail), raw as Record<string, unknown>, at, fail);
229
225
  checkCoreStep(step, at, fail);
230
226
  return step;
231
227
  });
@@ -241,17 +237,20 @@ export function readRecordFile(path: string): RecordFile {
241
237
  };
242
238
  }
243
239
 
240
+ /** The target of a runUntil step to an address, as a list of none or one. */
241
+ function addressTarget(step: ActionStep | RestoreAction): Location[] {
242
+ return "runUntil" in step && step.runUntil.target.kind === "address" ? [step.runUntil.target.address] : [];
243
+ }
244
+
245
+ /** Starts the counts of the replay core at the addresses. */
246
+ async function countAt(core: C64RunSession, addresses: number[]): Promise<void> {
247
+ const unique = [...new Set(addresses)];
248
+ if (unique.length > 0) await core.command(`count-pc ${unique.map(hex).join(",")}`);
249
+ }
250
+
244
251
  /** What the replay core cannot do of a step that is right for VICE: it has the C64 alone, no raster wait and no conditions. */
245
252
  function checkCoreStep(step: ActionStep, at: string, fail: (message: string) => never): void {
246
253
  if ("write" in step && step.write.space !== "c64") fail(`${at}: a recording has the C64 alone, not ${step.write.space}`);
247
- if ("press" in step) {
248
- try {
249
- keyCodes(step.press);
250
- } catch (error) {
251
- if (isRefusal(error)) fail(`${at}: ${error.message}`);
252
- throw error;
253
- }
254
- }
255
254
  if ("type" in step) {
256
255
  const keys = keyboardBytes(step.type);
257
256
  if (typeof keys !== "string" && keys.length > QUEUE_SIZE) fail(`${at}: the KERNAL keyboard queue holds ${QUEUE_SIZE} keys; give more type steps, or press for keys of the keyboard matrix`);
@@ -297,7 +296,12 @@ export function readRecording(folder: string): Recording {
297
296
  const named = typeof event.step === "number" ? `${at} (step ${event.step})` : at;
298
297
  if (event.action.restore === true && Object.keys(event.action).length === 1) return;
299
298
  // The action with the defaults filled in, as the record file gave it.
300
- event.action = checkActionStep(stepKind(event.action, ACTION_STEP_KINDS, named, where), event.action, named, where, { press: true });
299
+ const action = checkActionStep(stepKind(event.action, ACTION_STEP_KINDS, named, where), event.action, named, where);
300
+ event.action = action;
301
+ // Before 2.6.0-rc.16, a runUntil to an address had the point of another event: a replay cannot find its target again.
302
+ if ("runUntil" in action && action.runUntil.target.kind === "address" && !("pc" in event.key)) {
303
+ fail(`${named}: a runUntil step to an address has a point of an older version, which a replay cannot find. Record the session again with record`);
304
+ }
301
305
  });
302
306
  return value as unknown as Recording;
303
307
  }
@@ -354,6 +358,55 @@ export function siteMap(sites: RecordedSite[], from: Map<string, number>, to: Ma
354
358
  return moved;
355
359
  }
356
360
 
361
+ /** Where the original came to the entry that the loader of a rebuild jumps to. */
362
+ export interface EntryPoint {
363
+ /** The tick of the first opcode fetch at the entry. */
364
+ tick: number;
365
+ /**
366
+ * The phase of the machine at that fetch, as the replay core gives it: the beam position, the CIA timers and
367
+ * the interrupt state. It depends on how the program started, so the rebuild gets it at its own entry.
368
+ */
369
+ phase: string;
370
+ /** The count of each pc key, by its target, before that fetch. */
371
+ counts: Map<string, number>;
372
+ /** The number of events of the recording before the entry: always the first ones. */
373
+ eventsBefore: number;
374
+ /** The number of checkpoints before the entry, which the samples of the original leave out. */
375
+ samplesBefore: number;
376
+ }
377
+
378
+ /**
379
+ * A loader with a start screen that RUN starts waits for a key or a fire button that the recording does not have:
380
+ * the rebuild goes on after the wait, as the check of the loader does. Gives the tick of the wait, a problem, or
381
+ * undefined when the rebuild has no start screen.
382
+ */
383
+ async function passStartScreen(core: C64RunSession, own: Map<string, number>, limit: number): Promise<number | string | undefined> {
384
+ const wait = own.get(START_SCREEN_WAIT);
385
+ const resume = own.get(START_SCREEN_CONTINUE);
386
+ if (wait === undefined || resume === undefined) return undefined;
387
+ const reached = await core.status(`run-pc ${hex(wait)} ${limit}`);
388
+ if (reached.word !== "reached") return `the rebuild did not come to the wait of its start screen at ${formatC64Address(wait)}`;
389
+ await core.status(`goto ${hex(resume)}`);
390
+ return reached.tick;
391
+ }
392
+
393
+ /**
394
+ * The entry that the generated loader of a rebuild jumps to: the operand of its jump, from a short run of the
395
+ * rebuild. Gives a problem when the rebuild does not come to the jump.
396
+ */
397
+ export async function loaderEntry(core: C64RunSession, recording: Recording, subject: ReplaySubject): Promise<number | string> {
398
+ const own = namesOf(subject.symbols);
399
+ const jump = own.get(LOADER_JUMP)!;
400
+ const limit = recording.ticks * REBUILD_TIME_FACTOR;
401
+ await core.init();
402
+ await startProgram(core, readProjectFile(subject.program).bytes, false);
403
+ const screen = await passStartScreen(core, own, limit);
404
+ if (typeof screen === "string") return screen;
405
+ if ((await core.status(`run-pc ${hex(jump)} ${limit}`)).word !== "reached") return `the rebuild did not come to the jump of its loader at ${formatC64Address(jump)}`;
406
+ const operand = await core.peek((jump + 1) & 0xffff, 2);
407
+ return operand[0]! | (operand[1]! << 8);
408
+ }
409
+
357
410
  /** Power-on and READY, then the program in memory as a LOAD leaves it, and RUN in the keyboard queue. */
358
411
  async function startProgram(core: C64RunSession, prg: Uint8Array, load: boolean): Promise<CoreStatus> {
359
412
  if (prg.length < 3) throw new Refusal("invalid-input", "the program is not a PRG file");
@@ -387,10 +440,14 @@ function busiestSite(answer: string): { site: number; addr: number; count: numbe
387
440
  * Runs to the point of an event. `map` moves a site to the rebuild. "halted"
388
441
  * when a sample stop came first, "not-reached" when the point did not come before `until`.
389
442
  */
390
- async function runToKey(core: C64RunSession, key: RecordedEvent["key"], until: number, map: Map<number, number>): Promise<"reached" | "not-reached" | "halted"> {
443
+ async function runToKey(core: C64RunSession, key: RecordedEvent["key"], until: number, map: Map<number, number>, skipped: number, at: SideAddresses): Promise<"reached" | "not-reached" | "halted"> {
391
444
  if ("previous" in key) return (await core.status("status")).word === "halted" ? "halted" : "reached";
445
+ if ("pc" in key) {
446
+ const status = await core.status(`run-pc ${hex(at.code(key.pc))} ${until} ${key.count}`);
447
+ return status.word === "halted" ? "halted" : status.word === "reached" ? "reached" : "not-reached";
448
+ }
392
449
  if ("tick" in key) {
393
- const status = await core.status(`run ${key.tick}`);
450
+ const status = await core.status(`run ${key.tick + skipped}`);
394
451
  return status.word === "halted" ? "halted" : "reached";
395
452
  }
396
453
  const site = parseC64Address(key.site);
@@ -487,11 +544,15 @@ export async function record(
487
544
  at.code(file.compare.checkpoint);
488
545
  for (const item of file.compare.state) at.data(item.address);
489
546
  }
547
+ // Two names can give one address: the replay core counts each address once.
548
+ const targets = [...new Set(file.steps.flatMap(addressTarget).map(at.code))];
549
+ if (targets.length > MAX_COUNTED_TARGETS) throw new Refusal("invalid-input", `record file of ${file.name}: the runUntil steps go to more than ${MAX_COUNTED_TARGETS} addresses`);
490
550
  const reads = workspace.path(RECORDING_FILES.reads);
491
551
  const coverage = workspace.path(RECORDING_FILES.coverage);
492
552
  await core.init();
493
553
  await core.command(`inputs ${inputsArgument(file.inputs)}`);
494
554
  await core.command(`record ${reads}`);
555
+ await countAt(core, targets);
495
556
  await startProgram(core, prg, file.load ?? false);
496
557
  // From READY on: the start of the C64 itself is never in the map.
497
558
  await core.command(COVERAGE_COMMANDS.get(file.coverage) ?? `coverage on-pc ${hex(parseC64Address(file.coverage))}`);
@@ -503,13 +564,25 @@ export async function record(
503
564
  // replay. An event right after another event runs where that one ended.
504
565
  const runEvent = async (action: ActionStep | RestoreAction, step?: number): Promise<string | undefined> => {
505
566
  const tick = (await core.status("status")).tick;
567
+ if ("runUntil" in action && action.runUntil.target.kind === "address") {
568
+ // The next opcode fetch at the target: its count from the start is the point, on each replay.
569
+ const { address } = action.runUntil.target;
570
+ const pc = hex(at.code(address));
571
+ const count = Number(/count=(\d+)/.exec(await core.command(`hits ${pc}`))![1]) + 1;
572
+ const reached = await core.status(`run-pc ${pc} ${tick + action.runUntil.timeoutFrames * PAL_FRAME_CYCLES} ${count}`);
573
+ if (reached.word !== "reached") return `the program did not reach ${address} within ${action.runUntil.timeoutFrames} frames`;
574
+ events.push({ ...(step === undefined ? {} : { step }), action, key: { pc: address, count } });
575
+ return undefined;
576
+ }
506
577
  const busiest = afterEvent ? undefined : busiestSite(await core.command("sites"));
507
578
  const key: RecordedEvent["key"] = afterEvent
508
579
  ? { previous: true }
509
580
  : busiest === undefined
510
581
  ? { tick: tick + 1 }
511
582
  : { site: formatC64Address(busiest.site), addr: formatC64Address(busiest.addr), count: busiest.count + 1 };
512
- if ((await runToKey(core, key, tick + 600 * PAL_FRAME_CYCLES, new Map())) !== "reached") return "the program did not read its input again within 600 frames";
583
+ if ((await runToKey(core, key, tick + READ_WAIT_FRAMES * PAL_FRAME_CYCLES, new Map(), 0, at)) !== "reached") {
584
+ return `the program did not read its input again within ${READ_WAIT_FRAMES} frames. This step runs at the next input read. Put a runUntil step to an address before it: that step needs no input read`;
585
+ }
513
586
  events.push({ ...(step === undefined ? {} : { step }), action, key });
514
587
  return doAction(core, action, at);
515
588
  };
@@ -522,11 +595,22 @@ export async function record(
522
595
  masks[step.joystick.port - 1] = joystickMask(step.joystick.direction, step.joystick.fire ?? false);
523
596
  await core.command(`joy ${masks[0]!.toString(16)} ${masks[1]!.toString(16)}`);
524
597
  } else if ("press" in step) {
525
- for (const code of keyCodes(step.press)) {
526
- await core.command(`key ${code.toString(16)} down`);
527
- await core.status(`run ${(tick += KEY_FRAMES * PAL_FRAME_CYCLES)}`);
528
- await core.command(`key ${code.toString(16)} up`);
529
- await core.status(`run ${(tick += KEY_FRAMES * PAL_FRAME_CYCLES)}`);
598
+ const hold = step.press.frames * PAL_FRAME_CYCLES;
599
+ for (const tap of keyTaps(step.press.keys) as KeyTap[]) {
600
+ for (const place of tap.keys) await core.command(`key ${coreKey(place)} down`);
601
+ // RESTORE is no read: an event at the next read of the program, with the keys of the tap down.
602
+ if (tap.restore) reason = await runEvent({ restore: true }, index + 1);
603
+ if (reason !== undefined) break;
604
+ tick = (await core.status("status")).tick;
605
+ await core.status(`run ${(tick += hold)}`);
606
+ for (const place of tap.keys) await core.command(`key ${coreKey(place)} up`);
607
+ await core.status(`run ${(tick += hold)}`);
608
+ // Frames ran: the next RESTORE is no event right after an event.
609
+ afterEvent = false;
610
+ }
611
+ if (reason !== undefined) {
612
+ reason = `step ${index + 1}: RESTORE: ${reason}`;
613
+ break;
530
614
  }
531
615
  } else {
532
616
  reason = await runEvent(step, index + 1);
@@ -590,6 +674,10 @@ export interface SideRun {
590
674
  end: CoreStatus;
591
675
  /** Why the side stopped before its last checkpoint, if it did. */
592
676
  problem?: string;
677
+ /** True when the rebuild went on after the wait of its start screen. */
678
+ startScreenSkipped?: boolean;
679
+ /** The original with an `entry`: where it came to that entry, when it came to it. */
680
+ entryPoint?: EntryPoint;
593
681
  /**
594
682
  * Input reads that the recording has no value for, which got the fixed idle value:
595
683
  * at sites that it does not have, and after its end at a site.
@@ -610,7 +698,7 @@ export async function replaySide(
610
698
  folder: string,
611
699
  subject: ReplaySubject,
612
700
  workspace: Workspace,
613
- options: { compare?: Comparison; stop?: number; dump?: number; pins?: string[] } = {},
701
+ options: { compare?: Comparison; stop?: number; dump?: number; pins?: string[]; entry?: number; handover?: { entry: number; original: EntryPoint } } = {},
614
702
  ): Promise<SideRun & { ram?: Uint8Array }> {
615
703
  const prg = readProjectFile(subject.program).bytes;
616
704
  const original = subject.side === "original";
@@ -620,7 +708,8 @@ export async function replaySide(
620
708
  const move = original
621
709
  ? { code: same, data: same }
622
710
  : { code: mover(namesOf(names, "code"), namesOf(subject.symbols, "code")), data: mover(namesOf(names), namesOf(subject.symbols)) };
623
- const at = sideAddresses(namesOf(subject.symbols), subject.side, move);
711
+ const own = namesOf(subject.symbols);
712
+ const at = sideAddresses(own, subject.side, move);
624
713
  const moved = original ? [] : siteMap(recording.sites, namesOf(names, "code"), namesOf(subject.symbols, "code"));
625
714
  const map = new Map(moved);
626
715
  const reads = workspace.path(`${subject.side}-${RECORDING_FILES.reads}`);
@@ -632,9 +721,10 @@ export async function replaySide(
632
721
  await core.command(`inputs ${inputsArgument(recording.inputs)}`);
633
722
  await core.command(`site-map ${mapFile}`);
634
723
  await core.command(`replay ${reads}`);
635
- if (options.compare !== undefined) {
724
+ let sampling = false;
725
+ const startSampling = async (compare: Comparison) => {
636
726
  const stop = options.dump ?? options.stop ?? 0;
637
- const pinned = options.compare.pin ?? [];
727
+ const pinned = compare.pin ?? [];
638
728
  if (options.pins !== undefined && pinned.length > 0) {
639
729
  // The rebuild: each checkpoint first gets the original's values of the random state.
640
730
  const pinFile = workspace.path(`${subject.side}-pins.txt`);
@@ -642,20 +732,81 @@ export async function replaySide(
642
732
  await core.command(`pin ${pinFile} ${rangesArgument(pinned, at)}`);
643
733
  }
644
734
  // The samples hold the state, then the pinned items.
645
- await core.command(`sample ${hex(at.code(options.compare.checkpoint))} ${samples} ${rangesArgument([...options.compare.state, ...pinned], at)}${stop > 0 ? ` ${stop}` : ""}`);
646
- }
735
+ await core.command(`sample ${hex(at.code(compare.checkpoint))} ${samples} ${rangesArgument([...compare.state, ...pinned], at)}${stop > 0 ? ` ${stop}` : ""}`);
736
+ sampling = true;
737
+ };
738
+ // A rebuild with a loader takes its checkpoints from its entry on, as the original leaves out those before its own.
739
+ if (options.compare !== undefined && options.handover === undefined) await startSampling(options.compare);
740
+ const targets = recording.events.flatMap((event) => ("pc" in event.key ? [at.code(event.key.pc)] : []));
741
+ await countAt(core, targets);
742
+ if (options.entry !== undefined) await core.command(`mark ${hex(options.entry)}`);
647
743
  await startProgram(core, prg, recording.load);
648
- const limit = original ? recording.ticks : recording.ticks * REBUILD_TIME_FACTOR;
744
+ const base = original ? recording.ticks : recording.ticks * REBUILD_TIME_FACTOR;
745
+ let limit = base;
649
746
  let problem: string | undefined;
650
- for (const event of recording.events) {
747
+ // A tick key of the rebuild comes this many cycles later than in the original.
748
+ let skipped = 0;
749
+ let screenSkipped = false;
750
+ if (!original && !recording.load) {
751
+ // The cycles to the wait of a start screen do not count.
752
+ const screen = await passStartScreen(core, own, limit);
753
+ if (typeof screen === "string") problem = screen;
754
+ else if (screen !== undefined) {
755
+ skipped = screen;
756
+ limit = base + skipped;
757
+ screenSkipped = true;
758
+ }
759
+ }
760
+ // A pc key counts the opcode fetches from the start, also those of the code before the entry: the unpacker of
761
+ // the original, or the loader of the rebuild. The rebuild counts again from the jump of its loader, without those of the original.
762
+ const { handover } = options;
763
+ if (problem === undefined && handover !== undefined) {
764
+ const jump = own.get(LOADER_JUMP)!;
765
+ if ((await core.status(`run-pc ${hex(jump)} ${limit}`)).word !== "reached") problem = `the rebuild did not come to the jump of its loader at ${formatC64Address(jump)}`;
766
+ else {
767
+ await countAt(core, targets);
768
+ const reached = await core.status(`run-pc ${hex(handover.entry)} ${limit}`);
769
+ if (reached.word !== "reached") problem = `the rebuild did not come to its entry at ${formatC64Address(handover.entry)}`;
770
+ else {
771
+ // The loader sets the entry state of the capture, but the phase of the frame and of the CIA timers at the entry
772
+ // depends on how the original started: the rebuild waits at its entry for the beam position of the original, and
773
+ // gets its CIA timers and interrupt state there. A program that starts its timers without a load keeps that phase.
774
+ const entered = await core.status(`align ${handover.original.phase}`);
775
+ // After the entry, a tick key is as far from the entry as in the original.
776
+ skipped = entered.tick - handover.original.tick;
777
+ limit = base + Math.max(0, skipped);
778
+ if (options.compare !== undefined) await startSampling(options.compare);
779
+ }
780
+ }
781
+ }
782
+ // The original with an entry: the events before the mark at the entry came.
783
+ let eventsBefore = 0;
784
+ let entryTick: number | undefined;
785
+ let entryPhase = "";
786
+ const marked = async () => {
787
+ const answer = /tick=(\d+) phase=([0-9a-f]+)/.exec(await core.command("marked"));
788
+ if (answer !== null) [entryTick, entryPhase] = [Number(answer[1]), answer[2]!];
789
+ };
790
+ for (const [index, event] of (problem === undefined ? recording.events : []).entries()) {
651
791
  const what = event.step === undefined ? "the RESTORE of the play" : "step " + event.step;
652
- const point = await runToKey(core, event.key, limit, map);
792
+ let key = event.key;
793
+ if (handover !== undefined) {
794
+ // The original came to this point before its entry, where the rebuild runs its loader. Each such event is a pc key: replay checks it.
795
+ if (index < handover.original.eventsBefore) continue;
796
+ if ("pc" in key) key = { ...key, count: key.count - (handover.original.counts.get(key.pc) ?? 0) };
797
+ }
798
+ const point = await runToKey(core, key, limit, map, skipped, at);
653
799
  if (point === "halted") break;
654
800
  if (point === "not-reached") {
655
801
  problem = "the program did not come to the point of " + what;
656
802
  break;
657
803
  }
658
- problem = await doAction(core, event.action, at);
804
+ if (options.entry !== undefined && entryTick === undefined) {
805
+ await marked();
806
+ if (entryTick === undefined) eventsBefore = index + 1;
807
+ }
808
+ // At the point of a runUntil to an address, its target is reached.
809
+ if (!("pc" in event.key)) problem = await doAction(core, event.action, at);
659
810
  if (problem !== undefined) {
660
811
  problem = what + ": " + problem;
661
812
  break;
@@ -667,12 +818,35 @@ export async function replaySide(
667
818
  const misses = sites.split(" ").slice(2).reduce((sum, entry) => sum + Number(entry.split(":")[4] ?? 0), 0);
668
819
  const ram = options.dump === undefined ? undefined : await core.peek(0, 0x10000);
669
820
  let lines: string[] = [];
670
- if (options.compare !== undefined) {
821
+ if (sampling) {
671
822
  await core.command("pin off");
672
823
  await core.command("sample off");
673
824
  lines = readFileSync(samples, "utf8").split("\n").filter((line) => line !== "");
674
825
  }
675
- return { samples: lines, end, unknown, misses, ...(problem === undefined ? {} : { problem }), ...(ram === undefined ? {} : { ram }) };
826
+ let entryPoint: EntryPoint | undefined;
827
+ if (options.entry !== undefined && entryTick === undefined) await marked();
828
+ if (entryTick !== undefined) {
829
+ const counts = new Map<string, number>();
830
+ for (const event of recording.events) {
831
+ if (!("pc" in event.key) || counts.has(event.key.pc)) continue;
832
+ const before = /marked=(\d+)/.exec(await core.command(`hits ${hex(at.code(event.key.pc))}`));
833
+ if (before !== null) counts.set(event.key.pc, Number(before[1]));
834
+ }
835
+ // A checkpoint at the first fetch at the entry has the tick of the mark. The rebuild starts its checkpoints after that fetch.
836
+ const after = lines.filter((line) => Number(line.split(" ")[0]) > entryTick!);
837
+ entryPoint = { tick: entryTick, phase: entryPhase, counts, eventsBefore, samplesBefore: lines.length - after.length };
838
+ lines = after;
839
+ }
840
+ return {
841
+ samples: lines,
842
+ end,
843
+ unknown,
844
+ misses,
845
+ ...(problem === undefined ? {} : { problem }),
846
+ ...(screenSkipped ? { startScreenSkipped: true } : {}),
847
+ ...(entryPoint === undefined ? {} : { entryPoint }),
848
+ ...(ram === undefined ? {} : { ram }),
849
+ };
676
850
  }
677
851
 
678
852
  export interface CheckpointDifference {