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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/package.json +2 -2
  2. package/skills/c64-assembler/SKILL.md +3 -3
  3. package/skills/c64-assembler/scripts/assembler.ts +4 -3
  4. package/skills/c64-development/SKILL.md +3 -3
  5. package/skills/c64-docs/SKILL.md +6 -4
  6. package/skills/c64-docs/scripts/docs.ts +23 -10
  7. package/skills/c64-docs/scripts/lib/reference.ts +117 -31
  8. package/skills/c64-docs/scripts/lib/source-map.ts +14 -0
  9. package/skills/c64-knowledge/SKILL.md +10 -9
  10. package/skills/c64-knowledge/scripts/knowledge.ts +16 -9
  11. package/skills/c64-reverse-engineering/SKILL.md +9 -3
  12. package/skills/c64-source/SKILL.md +13 -10
  13. package/skills/c64-source/scripts/lib/export.ts +13 -2
  14. package/skills/c64-source/scripts/lib/loader.ts +51 -28
  15. package/skills/c64-source/scripts/lib/source.ts +24 -7
  16. package/skills/c64-source/scripts/source.ts +65 -47
  17. package/skills/c64-static-analysis/SKILL.md +26 -22
  18. package/skills/c64-static-analysis/scripts/lib/findings.ts +11 -11
  19. package/skills/c64-static-analysis/scripts/lib/instructions.ts +4 -4
  20. package/skills/c64-static-analysis/scripts/lib/macros.ts +3 -1
  21. package/skills/c64-static-analysis/scripts/static-analysis.ts +51 -35
  22. package/skills/c64-testing/SKILL.md +11 -4
  23. package/skills/c64-testing/references/recording-format.md +19 -7
  24. package/skills/c64-testing/references/scenario-format.md +6 -5
  25. package/skills/c64-testing/scripts/lib/diff-files.ts +4 -18
  26. package/skills/c64-testing/scripts/lib/play.ts +39 -37
  27. package/skills/c64-testing/scripts/lib/recording.ts +213 -65
  28. package/skills/c64-testing/scripts/lib/replay.ts +31 -5
  29. package/skills/c64-testing/scripts/lib/runs.ts +8 -3
  30. package/skills/c64-testing/scripts/lib/scenario.ts +4 -6
  31. package/skills/c64-testing/scripts/testing.ts +23 -2
  32. package/skills/c64-unpacker/SKILL.md +6 -3
  33. package/skills/c64-unpacker/scripts/lib/loads.ts +2 -2
  34. package/skills/c64-unpacker/scripts/lib/stages.ts +18 -3
  35. package/skills/c64-unpacker/scripts/unpacker.ts +38 -6
  36. package/skills/emulator/SKILL.md +2 -5
  37. package/src/build-name.ts +9 -4
  38. package/src/c64-keys.ts +98 -0
  39. package/src/c64.ts +1 -1
  40. package/src/host/main.ts +2 -2
  41. package/src/host/server.ts +3 -1
  42. package/src/host/tools/index.ts +1 -1
  43. package/src/host/vice/process.ts +34 -17
  44. package/src/host/vice/session.ts +132 -30
  45. package/src/host-client/steps.ts +21 -18
  46. package/src/host-client/tools.ts +1 -1
  47. package/src/host-client/vice-session.ts +7 -1
  48. package/src/knowledge/evidence.ts +66 -0
  49. package/src/knowledge/history.ts +5 -5
  50. package/src/knowledge/import.ts +12 -5
  51. package/src/knowledge/program.ts +81 -33
  52. package/src/knowledge/read.ts +12 -3
  53. package/src/knowledge/schema.ts +7 -7
  54. package/src/knowledge/start-screen.ts +2 -0
  55. package/src/knowledge/text.ts +28 -3
  56. package/src/knowledge/write.ts +6 -6
  57. package/src/mcp/inputs.ts +12 -0
  58. package/src/mcp/server.ts +1 -0
  59. package/src/mcp/tools/debug.ts +23 -21
  60. package/src/mcp/tools/input.ts +38 -5
  61. package/src/mcp/tools/memory.ts +12 -9
  62. package/src/native/c64run.ts +7 -4
  63. package/src/native/{ghidra → decompiler}/analyze.ts +17 -17
  64. package/src/native/{ghidra → decompiler}/language/c64rt_6510.slaspec +1 -1
  65. package/src/native/{ghidra → decompiler}/walk.ts +6 -6
  66. package/src/native/discover.ts +3 -3
  67. package/src/native/processes.ts +3 -3
  68. package/src/native/types.ts +25 -25
  69. package/src/opcodes.ts +1 -1
  70. package/src/protocol/vice.ts +47 -0
  71. package/src/reference-pages.ts +64 -0
  72. package/src/script.ts +1 -1
  73. package/src/vsf.ts +98 -0
  74. package/tools/c64run.c +158 -15
  75. package/skills/c64-testing/scripts/lib/keys.ts +0 -36
  76. /package/src/native/{ghidra → decompiler}/c64rt-wasm.ts +0 -0
  77. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.cspec +0 -0
  78. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.ldefs +0 -0
  79. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.pspec +0 -0
  80. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.sla +0 -0
  81. /package/src/native/{ghidra → decompiler}/pcode.ts +0 -0
  82. /package/src/native/{ghidra → decompiler}/wasm.ts +0 -0
@@ -13,7 +13,10 @@ import { ViceSessionClient } from "#src/host-client/vice-session.ts";
13
13
  import { C64RunSession, PAL_FRAME_CYCLES } from "#src/native/c64run.ts";
14
14
  import { localToolContext } from "#src/native/local.ts";
15
15
  import { Workspace } from "#src/native/staging.ts";
16
+ import { openForRead } from "#src/knowledge/database.ts";
17
+ import { changedEvidence } from "#src/knowledge/evidence.ts";
16
18
  import { knowledgeNames } from "#src/knowledge/names.ts";
19
+ import { LOCAL_DIRECTORY, PROJECT_DIRECTORY, projectRelative, projectRoot } from "#src/project.ts";
17
20
  import { OPTIONS, reply, runScript, UsageError, type Call, type CommandSpec, type Reply } from "#src/script.ts";
18
21
  import { diffFiles } from "./lib/diff-files.ts";
19
22
  import { CANCELLED, play } from "./lib/play.ts";
@@ -78,7 +81,10 @@ async function recordCommand(call: Call): Promise<Reply> {
78
81
  const context = localToolContext();
79
82
  const core = await C64RunSession.open(context);
80
83
  const workspace = Workspace.create(context.supervisor, "c64-re-tools-record-");
84
+ let db: ReturnType<typeof openForRead>;
81
85
  try {
86
+ // The knowledge is read before the session: a record into the folder of an earlier recording can change files that it gives as evidence.
87
+ db = openForRead();
82
88
  const person = playing
83
89
  ? (session: C64RunSession, restore: () => Promise<string | undefined>) => {
84
90
  const ready = (url: string) =>
@@ -104,11 +110,26 @@ async function recordCommand(call: Call): Promise<Reply> {
104
110
  writeReported(`${out}/${RECORDING_FILES.reads}`, outcome.reads, { what: "--out" }),
105
111
  writeReported(`${out}/${RECORDING_FILES.coverage}`, outcome.coverage, { what: "--out" }),
106
112
  ];
113
+ // A recording in the local folder is a work file: git ignores it, so it is no test. A record file there is not kept either.
114
+ const local = (path: string) => projectRelative(path).startsWith(`${PROJECT_DIRECTORY}/${LOCAL_DIRECTORY}/`);
115
+ const keep = local(out)
116
+ ? `Git ignores ${out}. To keep the recording as a test and to add its coverage to the project knowledge, record again with --out tests/recordings/<name>.`
117
+ : `Commit ${out} with the scenarios. Add ${out}/${RECORDING_FILES.coverage} to the project knowledge as coverage.`;
118
+ const recordFile = local(call.subject(0)) ? ` Git also ignores the record file ${call.subject(0)}. To record again later, keep a copy in a folder that git keeps, for example tests/record/.` : "";
119
+ const written = new Set(Object.values(RECORDING_FILES).map((name) => projectRelative(`${out}/${name}`)));
120
+ const evidence = changedEvidence(db, projectRoot(), (file) => written.has(file));
121
+ const map = projectRelative(`${out}/${RECORDING_FILES.coverage}`);
122
+ const cited = [
123
+ ...(evidence.length === 0 ? [] : [" The project knowledge gives the files in evidence as evidence of earlier revisions, and this record changed them."]),
124
+ ...(evidence.some((change) => change.file === map) ? [` Put the new ${RECORDING_FILES.coverage} into the project knowledge as coverage: it replaces the map of the earlier recording.`] : []),
125
+ ...(evidence.some((change) => change.file !== map) ? [` For a file other than ${RECORDING_FILES.coverage}, examine the facts of its revisions against the new recording.`] : []),
126
+ ].join("");
107
127
  return reply(
108
- { result: "PASS", recorded: true, out, ...summary, files },
109
- { hint: `Commit ${out} with the scenarios. Add ${out}/${RECORDING_FILES.coverage} to the project knowledge as coverage. ${summary.coverageFrom === null ? "The coverage did not start: the map is empty." : "The map has no marks for the code that ran before coverageFrom."} To make sure that the recording replays, run nextAction.`, nextAction: call.next("replay", out) },
128
+ { result: "PASS", recorded: true, out, ...summary, files, ...(evidence.length === 0 ? {} : { evidence }) },
129
+ { hint: `${keep}${recordFile}${cited} ${summary.coverageFrom === null ? "The coverage did not start: the map is empty." : "The map has no marks for the code that ran before coverageFrom."} To make sure that the recording replays, run nextAction.`, nextAction: call.next("replay", out) },
110
130
  );
111
131
  } finally {
132
+ db?.close();
112
133
  await core.close();
113
134
  workspace.remove();
114
135
  }
@@ -58,6 +58,7 @@ Each step has one of these kinds:
58
58
  - `{ "registers": { "pc": "start", "a": 1 } }` sets registers. Only `pc` takes a name.
59
59
  - `{ "joystick": { "port": 2, "direction": "up", "fire": false } }` sets a joystick.
60
60
  - `{ "type": { "mode": "text", "text": "RUN\n" } }` or `{ "type": { "mode": "petscii", "bytes": [147] } }` puts keys in the keyboard queue of the KERNAL.
61
+ - `{ "press": { "keys": "{F1}" } }` presses keys of the keyboard matrix. Each character is one tap. A name in braces is a key without a character, for example `{STOP}` or `{RESTORE}`. `+` in braces holds keys together, for example `{LSHIFT+CBM}`. `frames` is 1 to 3000, and 3 by default.
61
62
  - `{ "frames": 50 }` runs 1 to 30000 frames.
62
63
  - `{ "runUntil": { "target": { "kind": "address", "address": "main_loop" }, "timeoutFrames": 300 } }` runs until the target. The target kinds are `address`, `memory` and `raster`. `timeoutFrames` is 1 to 30000. The default is 3000.
63
64
  - `{ "capture": "level1" }` captures a part. Only `loads` takes this step. Give each capture step a different name of 1 to 64 letters, digits, dots, underscores or hyphens.
@@ -65,7 +66,7 @@ Each step has one of these kinds:
65
66
 
66
67
  An address in a step can be a name. The script refuses an unknown name before the program runs. The message gives the file and the step.
67
68
 
68
- The script refuses a `press` step. A program that reads the keyboard matrix does not see the keys of a `type` step. A wait for any key that reads all keyboard columns can end without a key.
69
+ A program that reads the keyboard matrix does not see the keys of a `type` step. Use a `press` step for that program. A wait for any key that reads all keyboard columns can end without a key.
69
70
 
70
71
  The script refuses a step in an old form. The message gives the step to write.
71
72
 
@@ -194,7 +195,7 @@ Traps:
194
195
 
195
196
  - `captured`: true when the CPU got to `--until`. `pc` is that address.
196
197
  - `files`: each file that the command wrote, as `{out, bytes, sha256}`. `removed` names the segment files of an earlier capture that the new `image.json` does not list.
197
- - `segments` and `excluded`: the ranges of the segment files, and the ranges that `--exclude` removed.
198
+ - `segments` and `excluded`: the ranges of the segment files, and the ranges that `--exclude` removed. `loaded: true` marks a segment with the bytes that the program loaded.
198
199
  - `stages`: the count of stages.
199
200
  - `differsFromReset`: the count of bytes that are not as a clean C64 has them at READY.
200
201
 
@@ -213,6 +214,8 @@ A segment is a block that a stage wrote, also a small block. These blocks are no
213
214
 
214
215
  The block with the capture entry is always a segment. Segments do not overlap.
215
216
 
217
+ If no stage wrote the capture entry, the program runs as it loaded. Then the range of the PRG is a segment with `loaded: true`. The blocks that touch this range are in the same segment. An example is a memory dump that starts with `SYS`.
218
+
216
219
  A capture into a folder with an earlier capture removes only the segment files that the new `image.json` does not list. It keeps all other files.
217
220
 
218
221
  On `PASS`, `hint` tells you to disassemble the code at `pc`, and then to put `<out>/image.json` into the project knowledge.
@@ -220,7 +223,7 @@ On `PASS`, `hint` tells you to disassemble the code at `pc`, and then to put `<o
220
223
  Traps:
221
224
 
222
225
  - The capture stops at the first arrival at `--until` after the steps. To capture a later arrival, add a `runUntil` step to an address after the first arrival.
223
- - `captured: false`: the program did not get to `--until` in `--timeout-frames`. The reason tells where it stopped. Find a better address, or give more frames. If it stopped in a key wait, give `--steps` with a `type` step.
226
+ - `captured: false`: the program did not get to `--until` in `--timeout-frames`. The reason tells where it stopped. Find a better address, or give more frames. If it stopped in a key wait, give `--steps` with a `type` step. If the CPU got to `--until` in a step, the reason names that step.
224
227
 
225
228
  ### `loads <program>`
226
229
 
@@ -10,7 +10,7 @@ import { type AddressRange, COVERAGE, formatC64Address } from "#src/c64.ts";
10
10
  import { Refusal } from "#src/errors.ts";
11
11
  import { autostartLoaded, LOAD_LIMIT_FRAMES, RUN_LIMIT_FRAMES, typeRun } from "#src/host-client/autostart.ts";
12
12
  import { IO_RAM, markIoRamWrites, readCoverage } from "#src/host-client/coverage.ts";
13
- import { ACTION_STEP_KINDS, checkActionStep, checkStepNames, isObject, runActionStep, VICE_STEP_KINDS, type ActionStep, type ActionStepKind } from "#src/host-client/steps.ts";
13
+ import { ACTION_STEP_KINDS, checkActionStep, checkStepNames, isObject, runActionStep, type ActionStep, type ActionStepKind } from "#src/host-client/steps.ts";
14
14
  import { knowledgeAt } from "#src/knowledge/names.ts";
15
15
  import { WireFailure } from "#src/host-client/tools.ts";
16
16
  import { readProjectFile, writeReported, type Written } from "#src/host-client/transfer.ts";
@@ -64,7 +64,7 @@ export function readLoadSteps(path: string): LoadStep[] {
64
64
  }
65
65
  const kinds = Object.keys(step).filter((key) => (ACTION_STEP_KINDS as readonly string[]).includes(key));
66
66
  if (kinds.length > 1) return fail(`${at} has ${kinds.length} step kinds: ${kinds.join(", ")}. Give each one its own step`);
67
- if (kinds.length !== 1) return fail(`${at} must have exactly one of ${[...VICE_STEP_KINDS, "capture", "save"].join(", ")}`);
67
+ if (kinds.length !== 1) return fail(`${at} must have exactly one of ${[...ACTION_STEP_KINDS, "capture", "save"].join(", ")}`);
68
68
  // The step with its defaults filled in, as the shared schema of the action steps gives it.
69
69
  const checked = checkActionStep(kinds[0] as ActionStepKind, step, at, fail);
70
70
  // Its names resolve now: an unknown name stops the call before the emulator starts.
@@ -107,9 +107,16 @@ export const FIRST_SEGMENT_ADDRESS = 0x0400;
107
107
  * a segment. A block that an intermediate stage wrote inside a leftover, for
108
108
  * example a variable of the loader, is a leftover too. The filter comes before
109
109
  * the join: a join first would drop the program with a leftover. `writtenBy` is
110
- * the last stage that wrote into the range.
110
+ * the last stage that wrote into the range. When no written block holds the
111
+ * entry, the code there is as the program loaded it: `loaded`, the range of
112
+ * the PRG, is then a segment too (`loaded: true`), joined with the blocks that
113
+ * it overlaps or touches.
111
114
  */
112
- export function captureSegments(stages: ReadonlyArray<{ entry: number; wrote: readonly AddressRange[] }>, entry: number): Array<AddressRange & { writtenBy: number }> {
115
+ export function captureSegments(
116
+ stages: ReadonlyArray<{ entry: number; wrote: readonly AddressRange[] }>,
117
+ entry: number,
118
+ loaded?: AddressRange,
119
+ ): Array<AddressRange & ({ writtenBy: number } | { loaded: true })> {
113
120
  const last = stages.length - 1;
114
121
  const replaced = (from: number, address: number) => stages.slice(from).some((stage) => inRanges(stage.wrote, address));
115
122
  const leftover = (block: AddressRange, writer: number) =>
@@ -129,7 +136,15 @@ export function captureSegments(stages: ReadonlyArray<{ entry: number; wrote: re
129
136
  previous.writtenBy = Math.max(previous.writtenBy, block.writtenBy);
130
137
  } else segments.push({ ...block });
131
138
  }
132
- return segments;
139
+ if (loaded === undefined || !contains(loaded, entry) || segments.some((segment) => contains(segment, entry))) return segments;
140
+ const joined = { start: loaded.start, end: loaded.end, loaded: true as const };
141
+ const apart = segments.filter((segment) => {
142
+ if (segment.end + 1 < joined.start || segment.start > joined.end + 1) return true;
143
+ joined.start = Math.min(joined.start, segment.start);
144
+ joined.end = Math.max(joined.end, segment.end);
145
+ return false;
146
+ });
147
+ return [...apart, joined].sort((a, b) => a.start - b.start);
133
148
  }
134
149
 
135
150
  /** The segments without the bytes of `holes`: a segment that a hole cuts gives its parts, each with the fields of the segment. */
@@ -15,6 +15,7 @@ import { readPrg } from "#src/host-client/image.ts";
15
15
  import { writeReported, type Written } from "#src/host-client/transfer.ts";
16
16
  import { ViceSessionClient } from "#src/host-client/vice-session.ts";
17
17
  import { knowledgeAt, knowledgeNames } from "#src/knowledge/names.ts";
18
+ import { PAL_FRAME_CYCLES } from "#src/native/c64run.ts";
18
19
  import { listed, OPTIONS, reply, runScript, UsageError, type Call, type CommandSpec, type OptionSpec } from "#src/script.ts";
19
20
  import { basicStart, inspect, readMemoryMap, underRom, writtenThenExecuted } from "./lib/evidence.ts";
20
21
  import { loads, readLoadSteps } from "./lib/loads.ts";
@@ -197,6 +198,8 @@ interface Followed {
197
198
  failed?: string;
198
199
  /** What stopped the CPU before the frames ran: a JAM or a point of the program. */
199
200
  halted?: { stopReason: string; pc: number };
201
+ /** The first step (1 = the first) in which the CPU executed `until`, before the run waited for it. */
202
+ untilRan?: number;
200
203
  }
201
204
 
202
205
  type RunUntilStep = Extract<ActionStep, { runUntil: unknown }>;
@@ -250,9 +253,16 @@ async function follow(
250
253
  const atTarget = (pc: number) => stopAt !== undefined && pc === stopAt;
251
254
  // The current stage: its memory map since it started, chunk by chunk, its own code, and the written code it calls.
252
255
  let stage = { map: new Uint8Array(0x10000), own: new Set<number>(), called: [] as AddressRange[] };
256
+ // A step that runs frames can pass until: the run then waits for it in vain.
257
+ let running = 0;
258
+ let untilRan: number | undefined;
259
+ const noteUntil = (map: Uint8Array) => {
260
+ if (options.until !== undefined && running > 0 && untilRan === undefined && (map[options.until]! & EXECUTE) !== 0) untilRan = running;
261
+ };
253
262
  const startStage = async (next: number, last: Uint8Array) => {
254
263
  mergeMaps(stage.map, last);
255
264
  await markIoRam(stage.map);
265
+ noteUntil(stage.map);
256
266
  found.push({ entry, firstFrame, frames: total - firstFrame, wrote: stageWrote(stage.map), next });
257
267
  entry = next;
258
268
  firstFrame = total;
@@ -426,8 +436,11 @@ async function follow(
426
436
  stopAt = undefined;
427
437
  }
428
438
  };
439
+ // Stage 0 starts at the program, whatever the first step is: RUN and the BASIC line before it are no part of it.
440
+ await client.memmap({ action: "clear" });
429
441
  // The steps run first and in the tracked time: a frames step and a runUntil step to an address. The others act between two chunks.
430
442
  for (const [index, step] of options.steps.entries()) {
443
+ running = index + 1;
431
444
  if ("frames" in step) await track(step.frames);
432
445
  else if (trackedRunUntil(step)) {
433
446
  if (!(await trackTo(knowledgeAt()(step.runUntil.target.address), step.runUntil.timeoutFrames))) {
@@ -435,8 +448,21 @@ async function follow(
435
448
  const why = halted === undefined ? "" : ` ${stoppedEarly(halted.stopReason, halted.pc, total, step.runUntil.timeoutFrames)}`;
436
449
  return { stages: found, frames: total, reached: false, failed: `Step ${index + 1} did not reach its target in ${step.runUntil.timeoutFrames} frames. It is at ${formatC64Address(pc)}.${why}` };
437
450
  }
438
- } else await runActionStep(client, step, knowledgeAt());
451
+ } else {
452
+ // A press or a runUntil to memory or the raster runs frames outside the chunks. The stopwatch of the session gives them,
453
+ // also for a run that a point stops early. What the step wrote and ran is in the stage before the next chunk clears the memory map.
454
+ await client.timing("start");
455
+ const notReached = await runActionStep(client, step, knowledgeAt());
456
+ const timed = await client.timing("read");
457
+ total += Math.round(Number("cycles" in timed ? timed.cycles : 0) / PAL_FRAME_CYCLES);
458
+ mergeMaps(stage.map, await readCoverage(client));
459
+ if (notReached !== undefined && "runUntil" in step) {
460
+ return { stages: found, frames: total, reached: false, failed: `Step ${index + 1} did not reach its target in ${step.runUntil.timeoutFrames} frames. It stopped by ${notReached.stopReason} at ${formatC64Address(notReached.pc)}.` };
461
+ }
462
+ }
463
+ noteUntil(stage.map);
439
464
  }
465
+ running = 0;
440
466
  const left = Math.max(0, options.frames - total);
441
467
  let reached = false;
442
468
  if (options.until === undefined) await track(left);
@@ -445,7 +471,7 @@ async function follow(
445
471
  mergeMaps(stage.map, await readCoverage(client));
446
472
  await markIoRam(stage.map);
447
473
  found.push({ entry, firstFrame, frames: total - firstFrame, wrote: stageWrote(stage.map) });
448
- return { stages: found, frames: total, reached, ...(halted === undefined ? {} : { halted }) };
474
+ return { stages: found, frames: total, reached, ...(halted === undefined ? {} : { halted }), ...(untilRan === undefined ? {} : { untilRan }) };
449
475
  }
450
476
 
451
477
  const showRange = (range: { start: number; end: number }) => ({ start: formatC64Address(range.start), end: formatC64Address(range.end) });
@@ -490,6 +516,11 @@ async function stages(program: string, options: { frames: number; entry?: number
490
516
  }
491
517
  }
492
518
 
519
+ /** Why a capture can wait for --until in vain: a step ran over it. */
520
+ function passedInStep(until: number, step: number): string {
521
+ return `The CPU executed ${formatC64Address(until)} in step ${step}, before the wait for --until started. A press step runs frames. Make the steps stop before the program gets to that address, or give an --until address that the program gets to later.`;
522
+ }
523
+
493
524
  async function capture(
494
525
  program: string,
495
526
  options: { until: number; out: string; range?: AddressRange; exclude: AddressRange[]; timeoutFrames: number; entry?: number; steps: ActionStep[]; minStage: number },
@@ -504,7 +535,7 @@ async function capture(
504
535
  return {
505
536
  output: {
506
537
  captured: false,
507
- reason: `The program did not get to ${formatC64Address(options.until)} in ${options.timeoutFrames} frames. It is at ${formatC64Address(registers.pc)}.${followed.halted === undefined ? "" : ` ${stoppedEarly(followed.halted.stopReason, followed.halted.pc, followed.frames, options.timeoutFrames)}`}`,
538
+ reason: `The program did not get to ${formatC64Address(options.until)} in ${options.timeoutFrames} frames. It is at ${formatC64Address(registers.pc)}.${followed.halted === undefined ? "" : ` ${stoppedEarly(followed.halted.stopReason, followed.halted.pc, followed.frames, options.timeoutFrames)}`}${followed.untilRan === undefined ? "" : ` ${passedInStep(options.until, followed.untilRan)}`}`,
508
539
  ...(followed.halted === undefined ? {} : { stopReason: followed.halted.stopReason }),
509
540
  stages: showStages(followed.stages),
510
541
  },
@@ -515,7 +546,8 @@ async function capture(
515
546
  const memory = await readRam(client, 0x0000, 0x10000);
516
547
  const state = await machineState(client);
517
548
  // The segments: what the stages wrote, without loader leftovers, with no overlap.
518
- const found = options.range !== undefined ? [options.range] : captureSegments(followed.stages, registers.pc);
549
+ const load = bytes[0]! | (bytes[1]! << 8);
550
+ const found = options.range !== undefined ? [options.range] : captureSegments(followed.stages, registers.pc, { start: load, end: Math.min(0xffff, load + bytes.length - 3) });
519
551
  const segments = withoutRanges(found, options.exclude);
520
552
  const file = (path: string) => `${options.out}/${path}`;
521
553
  const written: Written[] = [];
@@ -533,7 +565,7 @@ async function capture(
533
565
  `${JSON.stringify(
534
566
  {
535
567
  entry: formatC64Address(registers.pc),
536
- segments: segments.map((segment, index) => ({ ...showRange(segment), ...("writtenBy" in segment ? { writtenBy: segment.writtenBy } : {}), file: files[index] })),
568
+ segments: segments.map((segment, index) => ({ ...showRange(segment), ...("writtenBy" in segment ? { writtenBy: segment.writtenBy } : {}), ...("loaded" in segment ? { loaded: true } : {}), file: files[index] })),
537
569
  ...(options.exclude.length === 0 ? {} : { excluded: options.exclude.map(showRange) }),
538
570
  vectors,
539
571
  stages: showStages(followed.stages),
@@ -556,7 +588,7 @@ async function capture(
556
588
  out: options.out,
557
589
  files: written,
558
590
  ...(removed.length === 0 ? {} : { removed }),
559
- segments: segments.map(showRange),
591
+ segments: segments.map((segment) => ({ ...showRange(segment), ...("loaded" in segment ? { loaded: true } : {}) })),
560
592
  ...(options.exclude.length === 0 ? {} : { excluded: options.exclude.map(showRange) }),
561
593
  stages: followed.stages.length,
562
594
  differsFromReset: entry.differsFromReset,
@@ -43,7 +43,7 @@ Use only the MCP tools. Each MCP session has its own machine. Nothing else can c
43
43
  | Chips of the machine | `c64_vicii`, `c64_sprite`, `c64_cia`, `c64_sid` |
44
44
  | Screen image, screen compare | `c64_screen` |
45
45
  | Several of these from one moment | `c64_observe` |
46
- | Keyboard, joystick | `c64_keyboard`, `c64_joystick` |
46
+ | Keyboard, joystick | `c64_keyboard`, `c64_press`, `c64_joystick` |
47
47
  | Program and disk media | `c64_autostart`, `c64_program_load`, `c64_disk_attach` |
48
48
  | Machine state to go back to, also in a later session | `c64_snapshot` |
49
49
 
@@ -73,10 +73,7 @@ Before a risky experiment, save the state with `c64_snapshot`. Restore it to try
73
73
 
74
74
  ### Input that the tools cannot give
75
75
 
76
- Some programs read input in a way that the input tools cannot give. The tool description tells when. Then use one of these ways:
77
-
78
- - Open the window and ask the user to give the input.
79
- - Record a test session with a `press` step. A `press` step presses one key of the keyboard matrix at a time, for example `{F1}` or `{STOP}`, in a session of a PRG file.
76
+ Some programs read input in a way that the input tools cannot give. The tool description tells when. Then open the window and ask the user to give the input.
80
77
 
81
78
  Do not change the program to make it accept the input.
82
79
 
package/src/build-name.ts CHANGED
@@ -2,7 +2,9 @@
2
2
  // A release build is release_<label>. A build of config.asm is clean when each
3
3
  // switch has its default, else custom_ with each switch that differs: its
4
4
  // name when it is on, no_<name> when it is off. A build of an entry other
5
- // than main.asm adds the entry, for example clean_loader. A source without
5
+ // than main.asm adds the entry, for example clean_loader. The loader of the
6
+ // packed form alone is only its copier, so its build is clean_copier: the loader
7
+ // program, which generate packs, keeps clean_loader. A source without
6
8
  // config.asm and without a release keeps the name of its entry. The symbols
7
9
  // of a build go into symbols/ next to the program, so the program folder
8
10
  // holds only programs.
@@ -31,9 +33,12 @@ export function configValues(text: string): Map<string, 0 | 1> {
31
33
  /** What a build is made of: a release, or the values of config.asm with the default of each switch (0 when the defaults do not have it). */
32
34
  export type BuildKind = { release: string } | { values: ReadonlyMap<string, number>; defaults: ReadonlyMap<string, number> };
33
35
 
34
- /** The name of a build of `entry`, without an extension. */
35
- export function buildName(entry: string, kind: BuildKind | undefined): string {
36
- const base = basename(entry, extname(entry));
36
+ /** The line of a generated loader.asm of the packed form. Its build alone is only the copier, not the loader program. */
37
+ export const COPIER_LINE = "; A build of this file alone is only the copier: its build name has copier in place of loader.";
38
+
39
+ /** The name of a build of `entry`, without an extension. `source` is the text of the entry: COPIER_LINE in it gives the name copier. */
40
+ export function buildName(entry: string, kind: BuildKind | undefined, source?: string): string {
41
+ const base = source?.split(/\r?\n/).includes(COPIER_LINE) ? "copier" : basename(entry, extname(entry));
37
42
  if (kind === undefined) return base;
38
43
  let type: string;
39
44
  if ("release" in kind) type = `release_${kind.release}`;
@@ -0,0 +1,98 @@
1
+ // The keys of the C64 keyboard matrix and RESTORE. A key is its place in the
2
+ // matrix: row * 8 + column, where the row is the line of CIA 1 port A that
3
+ // the scan drives low and the column the bit of port B that reads low. The
4
+ // press of VICE and of the replay core, and the play page, use these numbers.
5
+
6
+ /** A press of keys that go down together and up together. `keys` are matrix places, without repeats, in rising order. */
7
+ export interface KeyTap {
8
+ keys: number[];
9
+ restore: boolean;
10
+ }
11
+
12
+ /** The keys that a tap holds at most, RESTORE included: the replay core has no more. */
13
+ export const MAX_TAP_KEYS = 4;
14
+ /** The taps of one press at most. */
15
+ export const MAX_PRESS_TAPS = 64;
16
+ /** The frames that a tap holds its keys, and then waits with all keys up, when the press gives no frames. */
17
+ export const PRESS_FRAMES = 3;
18
+ /** The frames of a tap at most: one minute of PAL frames. */
19
+ export const MAX_PRESS_FRAMES = 3000;
20
+
21
+ /** The matrix, row by row (port A line 0 to 7), column 0 to 7 in each row. A name has more than one character. */
22
+ const MATRIX = [
23
+ ["DEL", "RETURN", "RIGHT", "F7", "F1", "F3", "F5", "DOWN"],
24
+ ["3", "W", "A", "4", "Z", "S", "E", "LSHIFT"],
25
+ ["5", "R", "D", "6", "C", "F", "T", "X"],
26
+ ["7", "Y", "G", "8", "B", "H", "U", "V"],
27
+ ["9", "I", "J", "0", "M", "K", "O", "N"],
28
+ ["+", "P", "L", "-", ".", ":", "@", ","],
29
+ ["POUND", "*", ";", "HOME", "RSHIFT", "=", "UPARROW", "/"],
30
+ ["1", "LEFTARROW", "CTRL", "2", "SPACE", "CBM", "Q", "STOP"],
31
+ ];
32
+
33
+ /** The matrix place of each key. */
34
+ export const MATRIX_KEYS: Readonly<Record<string, number>> = Object.fromEntries(MATRIX.flatMap((row, line) => row.map((key, column) => [key, line * 8 + column])));
35
+
36
+ const LSHIFT = MATRIX_KEYS.LSHIFT!;
37
+
38
+ /** The names that press a key with the left SHIFT: the second function of the key. */
39
+ const SHIFTED_NAMES: Readonly<Record<string, string>> = { F2: "F1", F4: "F3", F6: "F5", F8: "F7", UP: "DOWN", LEFT: "RIGHT", INST: "DEL", CLR: "HOME", RUN: "STOP" };
40
+ /** The characters that a key gives with SHIFT. */
41
+ const SHIFTED_CHARACTERS: Readonly<Record<string, string>> = { "!": "1", '"': "2", "#": "3", $: "4", "%": "5", "&": "6", "'": "7", "(": "8", ")": "9", "[": ":", "]": ";", "<": ",", ">": ".", "?": "/" };
42
+
43
+ /** The names in braces, in the order that a refusal lists them. */
44
+ export const KEY_NAMES = [
45
+ ...["F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8"],
46
+ ...["RETURN", "SPACE", "DEL", "INST", "HOME", "CLR", "STOP", "RUN", "RESTORE", "CTRL", "CBM", "LSHIFT", "RSHIFT"],
47
+ ...["UP", "DOWN", "LEFT", "RIGHT", "POUND", "UPARROW", "LEFTARROW"],
48
+ ];
49
+
50
+ /** The matrix places of one key: a name, or one character. Undefined when the C64 has no such key. RESTORE has no place: it gives []. */
51
+ function placesOf(key: string): number[] | undefined {
52
+ const upper = key.toUpperCase();
53
+ if (upper === "RESTORE") return [];
54
+ if (key === "\n") return [MATRIX_KEYS.RETURN!];
55
+ if (key === " ") return [MATRIX_KEYS.SPACE!];
56
+ const shifted = SHIFTED_NAMES[upper] ?? SHIFTED_CHARACTERS[key];
57
+ if (shifted !== undefined) return [LSHIFT, MATRIX_KEYS[shifted]!];
58
+ // A character is its own key; a name has more than one character.
59
+ const place = key.length === 1 || KEY_NAMES.includes(upper) ? MATRIX_KEYS[upper] : undefined;
60
+ return place === undefined ? undefined : [place];
61
+ }
62
+
63
+ /**
64
+ * The taps of a text, or why it has no taps. Each character is one tap, and
65
+ * a-z press the same keys as A-Z. A key without a character has its name in
66
+ * braces, for example {F1}. Names joined with + in braces are one tap that
67
+ * holds the keys together, for example {LSHIFT+CBM} or {STOP+RESTORE}.
68
+ */
69
+ export function keyTaps(text: string): KeyTap[] | string {
70
+ const taps: KeyTap[] = [];
71
+ for (const part of text.replace(/\r\n?/g, "\n").match(/\{[^{}]*\}|[^]/g) ?? []) {
72
+ const keys = part.length > 1 ? part.slice(1, -1).split("+") : [part];
73
+ const places = new Set<number>();
74
+ let restore = false;
75
+ for (const key of keys) {
76
+ const found = key === "" ? undefined : placesOf(key);
77
+ if (found === undefined) {
78
+ if (part.length === 1) return `the C64 keyboard has no key ${JSON.stringify(part)}`;
79
+ return `there is no key ${key === "" ? part : `{${key}}`}. The keys in braces are ${KEY_NAMES.map((name) => `{${name}}`).join(", ")}, and each character key, for example {CTRL+3}. + joins the keys of one tap, for example {LSHIFT+CBM}`;
80
+ }
81
+ if (key.toUpperCase() === "RESTORE") restore = true;
82
+ for (const place of found) places.add(place);
83
+ }
84
+ const count = places.size + (restore ? 1 : 0);
85
+ if (count > MAX_TAP_KEYS) return `${part} holds ${count} keys, and one tap holds at most ${MAX_TAP_KEYS} keys, RESTORE included`;
86
+ taps.push({ keys: [...places].sort((a, b) => a - b), restore });
87
+ }
88
+ if (taps.length === 0) return "give at least one key";
89
+ if (taps.length > MAX_PRESS_TAPS) return `one press has at most ${MAX_PRESS_TAPS} taps. This text has ${taps.length}`;
90
+ return taps;
91
+ }
92
+
93
+ /** The 8 rows of the matrix with `keys` down: bit n of row r is the key at column n. */
94
+ export function matrixRows(keys: readonly number[]): number[] {
95
+ const rows = [0, 0, 0, 0, 0, 0, 0, 0];
96
+ for (const key of keys) rows[key >> 3]! |= 1 << (key & 7);
97
+ return rows;
98
+ }
package/src/c64.ts CHANGED
@@ -511,7 +511,7 @@ const BRANCHES = new Set([0x10, 0x30, 0x50, 0x70, 0x90, 0xb0, 0xd0, 0xf0]);
511
511
  const NO_FALL = new Set([0x00, 0x40, 0x4c, 0x60, 0x6c]);
512
512
 
513
513
  /**
514
- * The coverage flow starts split for Ghidra. A start is a code start, a
514
+ * The coverage flow starts split for the decompiler. A start is a code start, a
515
515
  * place in a routine, when it follows an executed JSR, or when an executed
516
516
  * branch or JMP from outside its own flow reaches it (the loop of a routine
517
517
  * that jumps back to its own start does not count). Any other start, for
package/src/host/main.ts CHANGED
@@ -121,8 +121,8 @@ async function main(): Promise<number> {
121
121
  log,
122
122
  flaws,
123
123
  // c1541 lists the disk, so an autostart index selects a program.
124
- directory: async (imageType, image) => {
125
- const { result } = await inspect({ action: "directory", imageType }, image, { supervisor, signal: new AbortController().signal, log });
124
+ directory: async (imageType, image, signal) => {
125
+ const { result } = await inspect({ action: "directory", imageType }, image, { supervisor, signal, log });
126
126
  return result.action === "directory" ? result.entries : [];
127
127
  },
128
128
  }),
@@ -263,7 +263,7 @@ class Connection {
263
263
  const record = (outcome: Record<string, unknown>) => {
264
264
  const ms = elapsedMs(started);
265
265
  trace().event("request", { connection: this.#id, op: request.op, id: request.id, params: request.params, attachments: attachments.length, ms, ...outcome });
266
- // A call from a skill script (c1541, petcat, status) is always logged; the many calls of a VICE session only in the trace.
266
+ // A call from a skill script (c1541, petcat) is always logged; the many calls of a VICE session only in the trace.
267
267
  if (this.#isTool) {
268
268
  const what = outcome.ok === true ? "ok" : `${String(outcome.code)}: ${String(outcome.message)}`;
269
269
  this.#log(`${request.op} ${JSON.stringify(summarize(request.params) ?? {})}: ${what} (${ms} ms)`);
@@ -387,6 +387,8 @@ export async function startHostServer(options: HostServerOptions): Promise<HostS
387
387
  server.once("error", failed);
388
388
  server.listen({ host: address, port, exclusive: true }, () => {
389
389
  server.off("error", failed);
390
+ // A failed accept (for example EMFILE) fails only that connection; the listener goes on.
391
+ server.on("error", (error) => log(`listener on ${address} port ${port}: ${error.message}`));
390
392
  const bound = server.address();
391
393
  if (bound === null || typeof bound === "string") reject(new Error("listener has no TCP address"));
392
394
  else resolve(bound.port);
@@ -1,6 +1,6 @@
1
1
  // The typed tool dispatcher of the Host Runtime. The host runs only
2
2
  // VICE and the tools that come with it (c1541, petcat); skill scripts run
3
- // ACME, DXA and Ghidra themselves. One entry per operation, never a
3
+ // ACME, DXA and the decompiler themselves. One entry per operation, never a
4
4
  // generic executable route.
5
5
 
6
6
  import type { ProcessSupervisor } from "../../native/processes.ts";
@@ -25,7 +25,7 @@
25
25
  // A headless VICE plays no sound: `-sounddev dummy` keeps the SID emulated.
26
26
 
27
27
  import { mkdtempSync, readFileSync, rmSync } from "node:fs";
28
- import { createServer } from "node:net";
28
+ import { createServer, type Server } from "node:net";
29
29
  import { tmpdir } from "node:os";
30
30
  import { join } from "node:path";
31
31
  import { setTimeout as sleep } from "node:timers/promises";
@@ -49,18 +49,33 @@ export function findVice(env: NodeJS.ProcessEnv = process.env): string {
49
49
  }
50
50
 
51
51
  /** Asks the OS for a free loopback port. Another process can still take it before VICE binds. */
52
- export function freePort(): Promise<number> {
53
- return new Promise((resolve, reject) => {
54
- const server = createServer();
55
- server.once("error", reject);
56
- server.listen(0, "127.0.0.1", () => {
57
- const address = server.address();
58
- server.close(() => {
59
- if (address === null || typeof address === "string") reject(new Error("no TCP address"));
60
- else resolve(address.port);
61
- });
62
- });
63
- });
52
+ export async function freePort(): Promise<number> {
53
+ return (await freePorts(1))[0]!;
54
+ }
55
+
56
+ /** Asks the OS for `count` different free loopback ports: each probe stays bound until all are known. */
57
+ export async function freePorts(count: number): Promise<number[]> {
58
+ const servers: Server[] = [];
59
+ try {
60
+ const ports: number[] = [];
61
+ for (let index = 0; index < count; index++) {
62
+ const server = createServer();
63
+ servers.push(server);
64
+ ports.push(
65
+ await new Promise<number>((resolve, reject) => {
66
+ server.once("error", reject);
67
+ server.listen(0, "127.0.0.1", () => {
68
+ const address = server.address();
69
+ if (address === null || typeof address === "string") reject(new Error("no TCP address"));
70
+ else resolve(address.port);
71
+ });
72
+ }),
73
+ );
74
+ }
75
+ return ports;
76
+ } finally {
77
+ await Promise.all(servers.map((server) => new Promise<void>((resolve) => server.close(() => resolve()))));
78
+ }
64
79
  }
65
80
 
66
81
  /** A VICE with no window (the default) or one with a window the user can use. */
@@ -254,8 +269,7 @@ async function launchOnce(options: LaunchOptions): Promise<ViceProcess> {
254
269
  const env = options.env ?? process.env;
255
270
  const log = options.log ?? (() => {});
256
271
  const binary = findVice(env);
257
- const port = await freePort();
258
- const textPort = await freePort();
272
+ const [port, textPort] = (await freePorts(2)) as [number, number];
259
273
  const scratch = mkdtempSync(join(tmpdir(), "c64-re-tools-vice-"));
260
274
  // Owned by the supervisor: its exit guard and the watchdog remove it if this process dies.
261
275
  const releaseScratch = options.supervisor.ownPath(scratch);
@@ -384,9 +398,12 @@ async function checkSameMachine(monitor: BinaryMonitor, text: TextMonitor): Prom
384
398
  if (seen === null || Number.parseInt(seen[1]!, 16) !== marker) {
385
399
  throw new WireFailure("machine-unavailable", "The emulator's two monitor connections reached different machines.");
386
400
  }
387
- } finally {
388
- await write(original);
401
+ } catch (error) {
402
+ // The first failure tells why the launch failed; a failed restore after it would hide it.
403
+ await write(original).catch(() => {});
404
+ throw error;
389
405
  }
406
+ await write(original);
390
407
  }
391
408
 
392
409
  /** Connects the binary monitor and proves it answers a ping, until `deadline`. */