@henols/c64-re-tools 2.8.0-rc.4 → 2.8.0-rc.6

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 (67) hide show
  1. package/package.json +1 -1
  2. package/skills/c64-assembler/SKILL.md +1 -1
  3. package/skills/c64-assembler/scripts/assembler.ts +78 -24
  4. package/skills/c64-docs/scripts/docs.ts +31 -10
  5. package/skills/c64-knowledge/SKILL.md +11 -7
  6. package/skills/c64-knowledge/references/batches.md +2 -1
  7. package/skills/c64-knowledge/references/source-knowledge.md +1 -1
  8. package/skills/c64-knowledge/scripts/knowledge.ts +46 -29
  9. package/skills/c64-packer/scripts/packer.ts +9 -2
  10. package/skills/c64-provenance/SKILL.md +2 -2
  11. package/skills/c64-provenance/scripts/lib/runtime.ts +45 -10
  12. package/skills/c64-provenance/scripts/provenance.ts +10 -3
  13. package/skills/c64-source/references/loader.md +8 -7
  14. package/skills/c64-source/scripts/lib/loader.ts +4 -111
  15. package/skills/c64-source/scripts/lib/source.ts +3 -1
  16. package/skills/c64-source/scripts/source.ts +49 -78
  17. package/skills/c64-static-analysis/SKILL.md +2 -2
  18. package/skills/c64-static-analysis/scripts/lib/coverage.ts +56 -4
  19. package/skills/c64-static-analysis/scripts/lib/idioms.ts +92 -42
  20. package/skills/c64-static-analysis/scripts/static-analysis.ts +32 -21
  21. package/skills/c64-testing/SKILL.md +7 -0
  22. package/skills/c64-testing/scripts/lib/play.ts +8 -7
  23. package/skills/c64-testing/scripts/lib/recording.ts +278 -27
  24. package/skills/c64-testing/scripts/lib/replay.ts +9 -8
  25. package/skills/c64-testing/scripts/lib/runs.ts +5 -1
  26. package/skills/c64-testing/scripts/lib/scenario.ts +4 -0
  27. package/skills/c64-testing/scripts/testing.ts +30 -11
  28. package/skills/c64-unpacker/SKILL.md +13 -11
  29. package/skills/c64-unpacker/scripts/lib/loads.ts +10 -5
  30. package/skills/c64-unpacker/scripts/lib/machine.ts +163 -3
  31. package/skills/c64-unpacker/scripts/lib/stages.ts +13 -6
  32. package/skills/c64-unpacker/scripts/unpacker.ts +34 -15
  33. package/skills/emulator/SKILL.md +2 -2
  34. package/src/c64.ts +21 -0
  35. package/src/host/vice/adapter.ts +2 -1
  36. package/src/host/vice/chips.ts +6 -9
  37. package/src/host/vice/session.ts +2 -2
  38. package/src/host-client/image.ts +40 -4
  39. package/src/host-client/tools.ts +1 -1
  40. package/src/host-client/transfer.ts +48 -26
  41. package/src/host-client/vice-session.ts +15 -0
  42. package/src/knowledge/database.ts +72 -19
  43. package/src/knowledge/import.ts +32 -7
  44. package/src/knowledge/join.ts +50 -2
  45. package/src/knowledge/names.ts +2 -2
  46. package/src/knowledge/program.ts +103 -24
  47. package/src/knowledge/schema.ts +6 -0
  48. package/src/knowledge/start-screen.ts +57 -7
  49. package/src/knowledge/write.ts +20 -13
  50. package/src/loader.ts +101 -33
  51. package/src/mcp/output.ts +13 -12
  52. package/src/mcp/server.ts +33 -22
  53. package/src/mcp/tools/debug.ts +21 -24
  54. package/src/mcp/tools/media.ts +27 -27
  55. package/src/mcp/tools/memory.ts +13 -17
  56. package/src/mcp/tools/video.ts +10 -12
  57. package/src/native/c64run.ts +39 -1
  58. package/src/native/decompiler/analyze.ts +1 -1
  59. package/src/native/dxa.ts +2 -2
  60. package/src/native/types.ts +26 -7
  61. package/src/opcodes.ts +5 -0
  62. package/src/program-code.ts +4 -2
  63. package/src/project.ts +224 -71
  64. package/src/protocol/vice.ts +5 -3
  65. package/src/script.ts +60 -15
  66. package/{skills/c64-source/scripts/lib → src}/stage.ts +142 -11
  67. package/tools/c64run.c +18 -5
@@ -5,6 +5,8 @@
5
5
  // show tells what a recording holds; diff shows what changed between two
6
6
  // states; checklist gives the Markdown list for a human tester.
7
7
 
8
+ import { basename } from "node:path";
9
+
8
10
  import { symbolsPath } from "#src/build-name.ts";
9
11
  import { COVERAGE, formatC64Address } from "#src/c64.ts";
10
12
  import { isRefusal, Refusal } from "#src/errors.ts";
@@ -17,13 +19,14 @@ import { localToolContext } from "#src/native/local.ts";
17
19
  import { Workspace } from "#src/native/staging.ts";
18
20
  import { openForRead } from "#src/knowledge/database.ts";
19
21
  import { changedEvidence } from "#src/knowledge/evidence.ts";
22
+ import { programEntry } from "#src/knowledge/program.ts";
20
23
  import { knowledgeNames } from "#src/knowledge/names.ts";
21
24
  import { RECORDING_FILES } from "#src/knowledge/recording-files.ts";
22
25
  import { LOCAL_DIRECTORY, PROJECT_DIRECTORY, projectRelative, projectRoot } from "#src/project.ts";
23
26
  import { OPTIONS, reply, runScript, UsageError, type Call, type CommandSpec, type Reply } from "#src/script.ts";
24
27
  import { diffFiles } from "./lib/diff-files.ts";
25
28
  import { CANCELLED, play } from "./lib/play.ts";
26
- import { readRecordFile, record, showRecording } from "./lib/recording.ts";
29
+ import { entryStateCheck, loaderEntryState, readRecordFile, record, showRecording } from "./lib/recording.ts";
27
30
  import { replay, replayAll } from "./lib/replay.ts";
28
31
  import { keepRun, runFile } from "./lib/runs.ts";
29
32
  import { namesOf, readScenario, runScenario, scenarioNames, type Scenario, type ScenarioResult } from "./lib/scenario.ts";
@@ -43,6 +46,11 @@ const ALWAYS = [
43
46
  /** The hint of a test or replay verdict: what to do after a FAIL or an INCONCLUSIVE. */
44
47
  const INCONCLUSIVE_HINT = "reason tells why the script could not compare. This is not a failure of the program. Correct the cause, then run the command again.";
45
48
 
49
+ /** What to do when the reference at its entry is not in the entry state that the loader of a rebuild writes. */
50
+ const RECAPTURE = "Capture the program again with the input of the record file before the entry. Then put the capture into the project knowledge, and generate the loader again.";
51
+ const ENTRY_STATE_REMEDY = `The loader of a rebuild writes the entry state of the project knowledge, so the rebuild starts from another state than the reference. ${RECAPTURE}`;
52
+ const ENTRY_STATE_HINT = `At their entries, the reference and the rebuild have other bytes in entryStateDiffers: the loader of the rebuild wrote another entry state. ${RECAPTURE}`;
53
+
46
54
  async function test(call: Call): Promise<ScenarioResult | Reply> {
47
55
  const scenario = readScenario(call.subject(0));
48
56
  const out = call.string("out");
@@ -95,7 +103,11 @@ async function recordCommand(call: Call): Promise<Reply> {
95
103
  return play(session, { httpPort, joystick, ready, restore });
96
104
  }
97
105
  : undefined;
98
- const outcome = await record(core, file, workspace, person);
106
+ // The loader of a rebuild jumps to the entry of the program in the knowledge. replay finds it in the reference by the names of the
107
+ // knowledge, also for symbols none. With the names of a build, or with load true (no loader entry), record marks no entry.
108
+ const namedAsKnowledge = file.symbols === "knowledge" || file.symbols === "none";
109
+ const entry = file.load || !namedAsKnowledge ? undefined : programEntry(db);
110
+ const outcome = await record(core, file, workspace, person, entry);
99
111
  const summary = {
100
112
  name: file.name,
101
113
  frames: Math.round(outcome.recording.ticks / PAL_FRAME_CYCLES),
@@ -127,9 +139,14 @@ async function recordCommand(call: Call): Promise<Reply> {
127
139
  ...(evidence.some((change) => change.file === map) ? [` Put the coverage of the recording folder ${out} into the project knowledge again: it replaces the map of the earlier recording.`] : []),
128
140
  ...(evidence.some((change) => change.file !== map) ? [" For each other file in evidence, examine the facts of its revisions against the new recording."] : []),
129
141
  ].join("");
142
+ // The recording replays on the reference and on a rebuild without a loader: the event before the entry is no refusal.
143
+ const loader = outcome.loaderProblem === undefined ? "" : `${outcome.loaderProblem}, then record again. Until then, the recording replays on the reference and on a rebuild without a loader, not on a rebuild with a loader. `;
144
+ const state = entry === undefined || outcome.entryRam === undefined ? undefined : loaderEntryState(db, entry);
145
+ const checked = state === undefined ? {} : entryStateCheck(outcome.entryRam!, outcome.recording.input ?? [], state);
146
+ const entryState = checked.entryStateDiffers === undefined ? "" : `At its entry ${formatC64Address(entry!)}, the program has other bytes than the entry state of the project knowledge in entryStateDiffers. ${ENTRY_STATE_REMEDY} `;
130
147
  return reply(
131
- { result: "PASS", recorded: true, out, ...summary, files, ...(evidence.length === 0 ? {} : { evidence }) },
132
- { 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) },
148
+ { result: "PASS", recorded: true, out, ...summary, files, ...(evidence.length === 0 ? {} : { evidence }), ...checked },
149
+ { hint: `${loader}${entryState}${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) },
133
150
  );
134
151
  } finally {
135
152
  db?.close();
@@ -232,7 +249,8 @@ const COMMANDS: CommandSpec[] = [
232
249
  if (screen !== undefined) throw new UsageError("--screen needs one recording. Give one recording, or leave out --screen.");
233
250
  const all = await replayAll(folders, values);
234
251
  const first = all.recordings.find((item) => item.result !== "PASS");
235
- if (first === undefined) return all;
252
+ const entryState = all.recordings.some((item) => item.entryStateDiffers !== undefined) ? ` For each recording with entryStateDiffers: ${ENTRY_STATE_HINT}` : "";
253
+ if (first === undefined) return entryState === "" ? all : reply(all, { hint: entryState.trimStart() });
236
254
  // The same comparison, alone: its own result gives the hint and the nextAction of that recording.
237
255
  const flags = [
238
256
  ...(checkpoint === undefined ? [] : ["--checkpoint", checkpoint]),
@@ -240,24 +258,25 @@ const COMMANDS: CommandSpec[] = [
240
258
  ...values.pin.flatMap((item) => ["--pin", item]),
241
259
  ...(rebuild === undefined ? [] : ["--rebuild", rebuild]),
242
260
  ...(symbols === undefined ? [] : ["--symbols", symbols]),
243
- ...(out === undefined ? [] : ["--out", `${out}/${first.recording.replace(/\/+$/, "").split("/").at(-1)!}`]),
261
+ ...(out === undefined ? [] : ["--out", `${out}/${basename(first.recording)}`]),
244
262
  ];
245
- return reply(all, { hint: "Each item of recordings has the result of one recording. Run nextAction: it replays the first recording that did not pass alone, and its result gives the hint for it.", nextAction: call.next("replay", first.recording, ...flags) });
263
+ return reply(all, { hint: `Each item of recordings has the result of one recording. Run nextAction: it replays the first recording that did not pass alone, and its result gives the hint for it.${entryState}`, nextAction: call.next("replay", first.recording, ...flags) });
246
264
  }
247
265
  const result = await replay({ ...values, folder: call.subject(0), ...(screen === undefined ? {} : { screen }) });
248
266
  if (result.result === "INCONCLUSIVE") return reply(result, { hint: INCONCLUSIVE_HINT });
249
- if (result.result !== "FAIL") return result;
267
+ const entryState = result.entryStateDiffers === undefined ? "" : `${ENTRY_STATE_HINT} `;
268
+ if (result.result !== "FAIL") return entryState === "" ? result : reply(result, { hint: entryState.trimEnd() });
250
269
  const [reference, rebuilt] = result.files ?? [];
251
270
  if (reference !== undefined && rebuilt !== undefined) {
252
- return reply(result, { hint: "files holds the RAM of each side at the first different checkpoint. Run nextAction to compare them. Then examine the first different state item in the emulator.", nextAction: call.next("diff", reference.out, rebuilt.out) });
271
+ return reply(result, { hint: `${entryState}files holds the RAM of each side at the first different checkpoint. Run nextAction to compare them. Then examine the first different state item in the emulator.`, nextAction: call.next("diff", reference.out, rebuilt.out) });
253
272
  }
254
273
  if (result.firstDifference === undefined) {
255
274
  // Without --symbols and without a symbol file of its build, the rebuild has the names of the recording: no loader or start-screen labels.
256
275
  const own = rebuild === undefined ? undefined : symbolsPath(rebuild);
257
276
  const unnamed = symbols === undefined && own !== undefined && result.symbols !== own;
258
- return reply(result, { hint: unnamed ? `The rebuild has the names of the recording, as ${own} does not exist. Give --symbols with the symbol file of the rebuild.` : "reason tells how many checkpoints the rebuild came to. Examine the rebuild in the emulator after its last checkpoint." });
277
+ return reply(result, { hint: `${entryState}${unnamed ? `The rebuild has the names of the recording, as ${own} does not exist. Give --symbols with the symbol file of the rebuild.` : "reason tells how many checkpoints the rebuild came to. Examine the rebuild in the emulator after its last checkpoint."}` });
259
278
  }
260
- return reply(result, { hint: `A difference in a random value with the same input often shows a missing --pin.${out === undefined ? " Give --out to get the RAM of each side at the first different checkpoint." : ""}` });
279
+ return reply(result, { hint: `${entryState}A difference in a random value with the same input often shows a missing --pin.${out === undefined ? " Give --out to get the RAM of each side at the first different checkpoint." : ""}` });
261
280
  },
262
281
  },
263
282
  {
@@ -28,9 +28,9 @@ To get the command list, run the script with no arguments.
28
28
  | Run a program that is not a BASIC program at `$0801` | `trace releases/game.prg --entry '$c000'` |
29
29
  | Give input to an intro or a menu before the evidence starts | `trace releases/game.prg --steps .c64-re-tools/local/input.json` |
30
30
  | Find each stage and the entry of the unpacked program | `stages releases/game.prg` |
31
- | Capture the unpacked program at its entry | `capture releases/game.prg --until '$c000' --out .c64-re-tools/local/capture` |
32
- | Capture again without the bytes of a cracktro | `capture releases/game.prg --until '$c000' --out .c64-re-tools/local/capture --exclude '$a000-$a9ff'` |
33
- | Capture only one known range of the program | `capture releases/game.prg --until '$c000' --out .c64-re-tools/local/capture --range '$c000-$cfff'` |
31
+ | Capture the unpacked program at its entry | `capture releases/game.prg --until '$c000' --out .c64-re-tools/local/capture/releases/game` |
32
+ | Capture again without the bytes of a cracktro | `capture releases/game.prg --until '$c000' --out .c64-re-tools/local/capture/releases/game --exclude '$a000-$a9ff'` |
33
+ | Capture only one known range of the program | `capture releases/game.prg --until '$c000' --out .c64-re-tools/local/capture/releases/game --range '$c000-$cfff'` |
34
34
  | Capture each part of a multi-load program | `loads releases/game.d64 --steps .c64-re-tools/local/parts.json --out .c64-re-tools/local/parts` |
35
35
  | Capture each part and the RAM of the disk drive | `loads releases/game.d64 --steps .c64-re-tools/local/parts.json --out .c64-re-tools/local/parts --drive` |
36
36
 
@@ -46,10 +46,10 @@ To get the command list, run the script with no arguments.
46
46
 
47
47
  ### Steps files
48
48
 
49
- A steps file is a JSON list of steps. The steps run right after the program starts. Use a steps file when an intro waits for a key or a menu waits for a choice. For example, wait 50 frames and type a space:
49
+ A steps file is a JSON list of steps. The steps run right after the program starts. Use a steps file when an intro waits for a key or a menu waits for a choice. For example, wait 50 frames and push the space key:
50
50
 
51
51
  ```json
52
- [{ "frames": 50 }, { "type": { "mode": "text", "text": " " } }]
52
+ [{ "frames": 50 }, { "press": { "keys": " " } }]
53
53
  ```
54
54
 
55
55
  Each step has one of these kinds:
@@ -175,7 +175,7 @@ For `likely` and `unclear`, `nextAction` is `stages` with the same `--entry` and
175
175
  - `stages`: one item for each stage, with `stage`, `entry`, `frames`, `wrote` and `next`. `wrote` lists each block that the stage wrote, also a small block. `next` is the entry of the next stage.
176
176
  - `moreStages: true`: the script followed only the first stages. Then `hint` tells you to give a larger `--min-stage`.
177
177
 
178
- The `entry` of the last stage is usually the start of the program. `nextAction` is `capture` at that entry, into `.c64-re-tools/local/capture`, with the same `--entry` and `--steps`. `hint` tells you to disassemble the code at that entry first.
178
+ The `entry` of the last stage is usually the start of the program. `nextAction` is `capture` at that entry, with the same `--entry` and `--steps`. Its `--out` is a folder for each program: `.c64-re-tools/local/capture/<path>`, where `<path>` is the path of the program in the project without its extension. For a program outside the project, `<path>` is the file name of the program without its extension. `hint` tells you to disassemble the code at that entry first.
179
179
 
180
180
  Traps:
181
181
 
@@ -193,7 +193,9 @@ Traps:
193
193
  - `captured`: true when the CPU got to `--until`. `pc` is that address.
194
194
  - `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.
195
195
  - `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.
196
- - `notExecutedUnderIo`: the segments in the RAM under the I/O area in which the program executed no code in the 250 frames after the entry. The memory map shows a read of this RAM as an I/O read. Thus the script cannot tell if the program reads these bytes. When no segment is of this type, or with `--range`, the body has no `notExecutedUnderIo`.
196
+ - `notExecutedUnderIo`: parts of the segments in the RAM under the I/O area. In the 250 frames after the entry, the program did not execute code in these parts, and it did not read them as RAM. The VIC-II always reads RAM, also under the I/O area. Thus the parts do not hold the RAM that the VIC-II shows at the entry. This RAM is the screen, the bitmap or the charset, and the pointer and the data of each sprite that is on. When no part is of this type, or with `--range`, the body has no `notExecutedUnderIo`.
197
+ - `readUnderIo`: parts of the segments in the RAM under the I/O area that the program read as RAM in the 250 frames after the entry. The program did not execute code in these parts. When no part is of this type, the body has no `readUnderIo`.
198
+ - `undecidedUnderIo`: parts of the segments in the RAM under the I/O area where the check for reads did not complete. Keep these parts in the capture. When no part is of this type, the body has no `undecidedUnderIo`.
197
199
  - `dropped`: the ranges from `$0400` that the stages wrote and that no segment holds. The ranges of `excluded` are not in `dropped`. Each range is in a block that is not a segment because it holds the entry of a later stage. `writtenBy` is the last stage that wrote the range. `stageEntry` is the entry of the later stage. When the capture dropped no byte, or with `--range`, the body has no `dropped`.
198
200
  - `stages`: one item for each stage, as `stages` gives it.
199
201
  - `differsFromReset`: the count of bytes that are not as a clean C64 has them at READY.
@@ -201,7 +203,7 @@ Traps:
201
203
  The folder `--out` gets these files:
202
204
 
203
205
  - `image.bin`: all 64 KiB of RAM at the entry. This RAM includes the RAM under the ROMs and the I/O area. A segment can be in the RAM under the I/O area at `$d000`-`$dfff`.
204
- - `image.json`: the entry, the segments, `excluded`, `dropped`, the vectors, the steps and the stages. `writtenBy` of a segment tells the last stage that wrote into it. `steps` holds the steps of `--steps` with their default values. A steps file with these steps gives the same input to the program again. When the capture ran no steps, `image.json` has no `steps`.
206
+ - `image.json`: `program`, the entry, the segments, `excluded`, `dropped`, the vectors, the steps and the stages. `program` gives `file`, the path in the project of the program file that the capture ran, and `sha256`, the SHA-256 of that file. A release that the project knowledge records from `image.json` gets this path and this SHA-256. For a program outside the project, `image.json` has no `program`. `writtenBy` of a segment tells the last stage that wrote into it. `steps` holds the steps of `--steps` with their default values. A steps file with these steps gives the same input to the program again. When the capture ran no steps, `image.json` has no `steps`.
205
207
  - One PRG for each segment.
206
208
  - `entry_state.json`: the registers, `$00` and `$01`, pages 0 to 3, the VIC, SID and CIA registers, the colour RAM, and the vectors. `io.colour` holds the 1000 colours at $d800. `cia` gives the CIA timer latches and interrupt masks. `differsFromReset` lists the bytes that are not as a clean C64 has them at READY. A rebuild must make these bytes the same, because the program can read them.
207
209
 
@@ -219,17 +221,17 @@ If no stage wrote the capture entry, the program runs as it loaded. Then the ran
219
221
 
220
222
  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.
221
223
 
222
- On `PASS`, `hint` tells you to disassemble the code at `pc`, and then to put `<out>/image.json` into the project knowledge. When the body has `dropped`, `hint` also gives the count of dropped bytes. When the body has `notExecutedUnderIo`, `hint` also names these segments.
224
+ On `PASS`, `hint` tells you to disassemble the code at `pc`, and then to put `<out>/image.json` into the project knowledge. When the body has `dropped`, `hint` also gives the count of dropped bytes. When the body has `notExecutedUnderIo`, `hint` also names these parts.
223
225
 
224
226
  Traps:
225
227
 
226
228
  - 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.
227
229
  - A dropped range can be a part of the program. Make sure that the program does not use the bytes in `dropped`. If the program uses them, tell the user.
228
- - `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.
230
+ - `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 `press` step. If the CPU got to `--until` in a step, the reason names that step.
229
231
 
230
232
  ### `loads <program>`
231
233
 
232
- `loads` runs a multi-load program with the steps file. Each `capture` step writes `<out>/<name>/` with `image.bin`, `image.json`, `entry_state.json` and a PRG for each segment. With `--drive`, it also writes `drive8.prg`: the drive RAM at `$0000`-`$07ff`.
234
+ `loads` runs a multi-load program with the steps file. Each `capture` step writes `<out>/<name>/` with `image.bin`, `image.json`, `entry_state.json` and a PRG for each segment. `image.json` has `program`, as the one of `capture` has: the disk, tape, cartridge or PRG file that `loads` ran. With `--drive`, it also writes `drive8.prg`: the drive RAM at `$0000`-`$07ff`.
233
235
 
234
236
  A segment is a block of RAM from `$0400` that the program changed after the capture before. The first capture also has the program itself.
235
237
 
@@ -15,7 +15,7 @@ import { isObject } from "#src/host-client/tools.ts";
15
15
  import { knowledgeAt } from "#src/knowledge/names.ts";
16
16
  import { readProjectFile, readProjectJson, writeReported } from "#src/host-client/transfer.ts";
17
17
  import { readMemoryInParts, ViceSessionClient } from "#src/host-client/vice-session.ts";
18
- import { entryStateFile, machineState, readyState, vectorsOf, writeCapture } from "./machine.ts";
18
+ import { capturedProgram, entryStateFile, machineState, readyState, vectorsOf, writeCapture } from "./machine.ts";
19
19
  import { FIRST_SEGMENT_ADDRESS } from "./stages.ts";
20
20
 
21
21
 
@@ -105,11 +105,15 @@ export function captureBlocks(before: Uint8Array, after: Uint8Array, map: Uint8A
105
105
 
106
106
  /**
107
107
  * Runs the program and its steps. Each capture step writes <out>/<name>/:
108
- * image.bin, image.json, entry_state.json, a PRG for each segment, and with
109
- * `drive` the drive RAM as drive8.prg. Blocks below `minBlock` bytes are
110
- * counted, not written: a game changes its variables all the time.
108
+ * image.bin, image.json with the program file that it ran, entry_state.json,
109
+ * a PRG for each segment, and with `drive` the drive RAM as drive8.prg.
110
+ * Blocks below `minBlock` bytes are counted, not written: a game changes its
111
+ * variables all the time.
111
112
  */
112
113
  export async function loads(program: string, options: { out: string; steps: LoadStep[]; drive: boolean; minBlock: number; exclude: AddressRange[] }): Promise<{ output: Record<string, unknown>; failed: boolean }> {
114
+ // The file is read once: image.json gets the SHA-256 of the bytes that the emulator ran.
115
+ const file = readProjectFile(program).bytes;
116
+ const ran = capturedProgram(program, file);
113
117
  const client = await ViceSessionClient.open({ videoStandard: "pal" });
114
118
  try {
115
119
  // A clean machine at the READY prompt shows what the program changed at each capture. The run goes on after a capture, so it is read first.
@@ -121,7 +125,7 @@ export async function loads(program: string, options: { out: string; steps: Load
121
125
  /** False while the map holds the writes of the KERNAL RAM test. */
122
126
  let writesKnown = true;
123
127
  if (program.toLowerCase().endsWith(".prg")) {
124
- const { bytes } = readProjectFile(program);
128
+ const bytes = file;
125
129
  if (!(await autostartLoaded(client, program, bytes))) return { output: { loaded: false, reason: `The program was not in memory after ${LOAD_LIMIT_FRAMES} frames.`, captures: [] }, failed: true };
126
130
  // The RAM before RUN, without the program, so the first capture holds the program too.
127
131
  previous = await readMemoryInParts(client, 0x0000, 0x10000, "ram");
@@ -202,6 +206,7 @@ export async function loads(program: string, options: { out: string; steps: Load
202
206
  other,
203
207
  (files) => ({
204
208
  capture: step.capture,
209
+ ...(ran === undefined ? {} : { program: ran }),
205
210
  entry: formatC64Address(registers.pc),
206
211
  segments: segments.map((segment, at) => ({ ...formatC64RangeFields(segment), file: files[at] })),
207
212
  ...(options.exclude.length === 0 ? {} : { excluded: options.exclude.map(formatC64RangeFields) }),
@@ -5,11 +5,16 @@
5
5
  import { readdirSync, rmSync } from "node:fs";
6
6
  import { join } from "node:path";
7
7
 
8
- import { type AddressRange, formatC64Address, hexWord, prgOf } from "#src/c64.ts";
8
+ import { type AddressRange, formatC64Address, hexWord, prgOf, spriteData, spritePointer, vicScreenMemory } from "#src/c64.ts";
9
9
  import { resetToReady } from "#src/host-client/entry-state.ts";
10
10
  import { writeRefusal, writeReported, type Written } from "#src/host-client/transfer.ts";
11
- import { readMemoryInParts, type ViceSessionClient } from "#src/host-client/vice-session.ts";
12
- import { projectRoot, resolveProjectPath } from "#src/project.ts";
11
+ import { isRefusal } from "#src/errors.ts";
12
+ import { MAX_WATCH_SIZE, WireFailure } from "#src/host-client/tools.ts";
13
+ import { lastOpcode, readMemoryInParts, type ViceSessionClient } from "#src/host-client/vice-session.ts";
14
+ import { startScreenRanges } from "#src/knowledge/read.ts";
15
+ import { sha256 } from "#src/knowledge/text.ts";
16
+ import { isStore } from "#src/opcodes.ts";
17
+ import { projectRelative, projectRoot, resolveProjectPath } from "#src/project.ts";
13
18
 
14
19
  type Registers = Awaited<ReturnType<ViceSessionClient["registersGet"]>>;
15
20
 
@@ -47,6 +52,41 @@ export async function machineState(client: ViceSessionClient): Promise<MachineSt
47
52
  return { port, pages, io, cia: { cia1: cia1!, cia2: cia2! }, romVectors };
48
53
  }
49
54
 
55
+ /**
56
+ * The RAM that the VIC-II shows in a machine state, from the VIC-II and CIA 2
57
+ * of `io`: the screen, the bitmap in bitmap mode or else the charset when it
58
+ * is RAM (startScreenRanges), and for each sprite that $d015 enables its
59
+ * pointer at the end of the screen and its 64 data bytes in `memory`. The
60
+ * VIC-II always reads RAM, also under the I/O area.
61
+ */
62
+ export function vicRam(io: { vic: Uint8Array; cia2: Uint8Array }, memory: Uint8Array): AddressRange[] {
63
+ const shown = vicScreenMemory(io.vic, io.cia2);
64
+ const ranges = startScreenRanges(shown).map((part) => part.range);
65
+ for (let sprite = 0; sprite < 8; sprite++) {
66
+ if ((io.vic[0x15]! & (1 << sprite)) === 0) continue;
67
+ const pointer = spritePointer(shown.screen, sprite);
68
+ const data = spriteData(io.cia2, memory[pointer]!);
69
+ ranges.push({ start: pointer, end: pointer }, { start: data, end: data + 63 });
70
+ }
71
+ return ranges;
72
+ }
73
+
74
+ /**
75
+ * The program file that a capture ran, for its image.json: the path in the
76
+ * project in one spelling, and the SHA-256 of `bytes`, the bytes that ran. A release of the
77
+ * capture cites them, because git ignores the capture in local/. A file
78
+ * outside the project gives undefined: then a release cites the image.json.
79
+ */
80
+ export function capturedProgram(path: string, bytes: Uint8Array): { file: string; sha256: string } | undefined {
81
+ let file: string;
82
+ try {
83
+ file = projectRelative(path);
84
+ } catch {
85
+ return undefined;
86
+ }
87
+ return { file, sha256: sha256(bytes) };
88
+ }
89
+
50
90
  const word = (bytes: Buffer, offset: number) => formatC64Address(bytes[offset]! | (bytes[offset + 1]! << 8));
51
91
 
52
92
  /** The KERNAL vectors in page 3, the hardware vectors in RAM, and the ROM's own. */
@@ -158,3 +198,123 @@ export function writeCapture(
158
198
  const removed = removeStaleFiles(folder, [...files, ...other.map((file) => file.name)]);
159
199
  return { written, files, removed };
160
200
  }
201
+
202
+ /**
203
+ * The CPU reads the RAM under the I/O area when bits 0 and 1 of $01 (LORAM and HIRAM) are clear; else a read there gives
204
+ * an I/O register or the character ROM. As the condition of a watchpoint, the emulator tests it at each read, so the
205
+ * reads of I/O registers (a raster wait, an interrupt acknowledge) do not stop the run.
206
+ */
207
+ const RAM_UNDER_IO = { kind: "memory", address: 0x0001, operator: "eq", value: 0, mask: 0x03, space: "c64", view: "cpu" } as const;
208
+ /** The most stops at a store that the RAM check runs on after: a guard, as the emulator gives the dummy read of a store to a watchpoint only on request. */
209
+ const MAX_STORE_STOPS = 256;
210
+ /** The RAM check runs in parts of this many frames, and ends when its time is over between two parts. */
211
+ const CHECK_PART_FRAMES = 25;
212
+ /** The most time of the RAM check. A condition on each read of the watched I/O area makes the emulator slower. */
213
+ export const MAX_CHECK_MS = 30_000;
214
+ const ENTRY_SNAPSHOT = "capture-entry";
215
+
216
+ /**
217
+ * Runs `work` from where the machine is, and then puts the machine back there, also when `work` fails. The snapshot is
218
+ * removed also when the restore fails. The first failure is thrown: of `work`, with a failed restore named in it, else
219
+ * of the restore, else of the remove.
220
+ */
221
+ export async function fromHere<T>(client: Pick<ViceSessionClient, "snapshot">, work: () => Promise<T>): Promise<T> {
222
+ await client.snapshot({ action: "save", name: ENTRY_SNAPSHOT });
223
+ const attempt = async <U>(run: () => Promise<U>): Promise<{ value: U } | { error: unknown }> => {
224
+ try {
225
+ return { value: await run() };
226
+ } catch (error) {
227
+ return { error };
228
+ }
229
+ };
230
+ const done = await attempt(work);
231
+ const restored = await attempt(() => client.snapshot({ action: "restore", name: ENTRY_SNAPSHOT }));
232
+ const removed = await attempt(() => client.snapshot({ action: "remove", name: ENTRY_SNAPSHOT }));
233
+ if ("error" in done) {
234
+ if (!("error" in restored)) throw done.error;
235
+ // The failed restore is in the error of the work, also when the work threw no Error.
236
+ const error = done.error instanceof Error ? done.error : new Error(String(done.error));
237
+ const why = restored.error instanceof Error ? restored.error.message : String(restored.error);
238
+ error.message = `${error.message.replace(/\.?$/, ".")} The machine did not go back to the snapshot: ${why}`;
239
+ throw error;
240
+ }
241
+ if ("error" in restored) throw restored.error;
242
+ if ("error" in removed) throw removed.error;
243
+ return done.value;
244
+ }
245
+
246
+ /**
247
+ * Runs the program on from where it is for `frames` frames, with read watchpoints that stop only at a read of the RAM
248
+ * under the I/O area, and gives the ranges that the program read there as RAM. The memory map gives each of these
249
+ * reads as an I/O read. The first read of a range removes the watchpoints of the range, so the run stops at most once
250
+ * for each range. A stop comes after the instruction that made the access: an indexed store reads its address before
251
+ * it writes it, and that read is no read of the program, so the run goes on. A check that ends before its frames (after
252
+ * MAX_STORE_STOPS such stops, a JAM, another stop, a frame that the emulator did not give in time, or after `limitMs`)
253
+ * gives the ranges without a read as `undecided`, not unread: the check never fails the capture. The machine then goes back to where it was.
254
+ */
255
+ export async function readAsRam<T extends AddressRange>(
256
+ client: Pick<ViceSessionClient, "snapshot" | "watchpoint" | "observe" | "execution" | "cpuHistory">,
257
+ ranges: readonly T[],
258
+ frames: number,
259
+ limitMs = MAX_CHECK_MS,
260
+ ): Promise<{ read: T[]; undecided: T[] }> {
261
+ // The watchpoint ids of each range: a watchpoint covers at most MAX_WATCH_SIZE bytes.
262
+ const points = new Map<number, number>();
263
+ const read = new Set<number>();
264
+ // Only a check that ran all its frames, or found a read in each range, tells which ranges the program did not read.
265
+ let complete = false;
266
+ await fromHere(client, async () => {
267
+ try {
268
+ for (const [index, range] of ranges.entries()) {
269
+ for (let address = range.start; address <= range.end; address += MAX_WATCH_SIZE) {
270
+ const size = Math.min(MAX_WATCH_SIZE, range.end - address + 1);
271
+ points.set((await client.watchpoint({ action: "add", address, size, access: "read", space: "c64", condition: RAM_UNDER_IO })).id, index);
272
+ }
273
+ }
274
+ // The frames end at the raster position where the check starts, after a stop too.
275
+ const { timing } = await client.observe({ timing: true });
276
+ if (timing === undefined) throw new WireFailure("operation-failed", "the emulator gave no raster position");
277
+ const anchor = { line: timing.rasterLine, cycle: timing.rasterCycle };
278
+ let left = frames;
279
+ let storeStops = 0;
280
+ const deadline = Date.now() + limitMs;
281
+ for (;;) {
282
+ if (left <= 0 || read.size === ranges.length) {
283
+ complete = true;
284
+ break;
285
+ }
286
+ if (Date.now() >= deadline) break;
287
+ const count = Math.min(left, CHECK_PART_FRAMES);
288
+ const run = await client.execution({ action: "advance-frames", count, space: "c64", anchor });
289
+ // "frames": the frames of the part ran. A stop in its last frame still counts.
290
+ if (run.stopReason === "frames") {
291
+ left -= count;
292
+ continue;
293
+ }
294
+ left -= run.advancedFrames ?? 0;
295
+ const index = run.pointId === undefined ? undefined : points.get(run.pointId);
296
+ if (run.stopReason !== "watchpoint" || index === undefined) break;
297
+ const opcode = await lastOpcode(client);
298
+ if (opcode !== undefined && isStore(opcode)) {
299
+ if (++storeStops > MAX_STORE_STOPS) break;
300
+ continue;
301
+ }
302
+ read.add(index);
303
+ for (const [id, of] of [...points]) {
304
+ if (of !== index) continue;
305
+ await client.watchpoint({ action: "remove", id });
306
+ points.delete(id);
307
+ }
308
+ }
309
+ } catch (error) {
310
+ // A refusal (a point or a condition that the emulator does not take, a frame that does not come in time) ends the
311
+ // check with the unread ranges undecided, and the capture goes on. A lost session fails.
312
+ if (!isRefusal(error) || error.code === "machine-unavailable") throw error;
313
+ } finally {
314
+ for (const id of points.keys()) await client.watchpoint({ action: "remove", id }).catch((error: unknown) => {
315
+ if (!isRefusal(error) || error.code === "machine-unavailable") throw error;
316
+ });
317
+ }
318
+ });
319
+ return { read: ranges.filter((_, index) => read.has(index)), undecided: complete ? [] : ranges.filter((_, index) => !read.has(index)) };
320
+ }
@@ -188,11 +188,15 @@ export function captureSegments(
188
188
  const joined = { start: loaded.start, end: loaded.end, loaded: true as const };
189
189
  const apart = segments.filter((segment) => {
190
190
  if (segment.end + 1 < joined.start || segment.start > joined.end + 1) return true;
191
+ // A segment that only touches the PRG joins it as a block joins a block: never across a bound of the I/O area.
192
+ if (segment.start === joined.end + 1 && ioSide(segment.start) !== ioSide(joined.end)) return true;
193
+ if (segment.end + 1 === joined.start && ioSide(segment.end) !== ioSide(joined.start)) return true;
191
194
  joined.start = Math.min(joined.start, segment.start);
192
195
  joined.end = Math.max(joined.end, segment.end);
193
196
  return false;
194
197
  });
195
- return [...apart, joined].sort((a, b) => a.start - b.start);
198
+ // A join over a bound of the I/O area is cut there: the RAM under it stays a segment of its own.
199
+ return [...apart, ...cutAtIoArea(joined).map((piece) => ({ ...piece, loaded: true as const }))].sort((a, b) => a.start - b.start);
196
200
  }
197
201
 
198
202
  /**
@@ -216,16 +220,19 @@ export function droppedRanges(stages: Stages, entry: number, kept: readonly Addr
216
220
  }
217
221
 
218
222
  /**
219
- * The segments in the RAM under the I/O area in which the program executed
220
- * no code after its entry. The map gives a read there as an I/O read, so only
221
- * code that ran shows that the program uses that RAM.
223
+ * The parts of the segments in the RAM under the I/O area in which the
224
+ * program executed no code after its entry, without `shown`, the RAM that
225
+ * the VIC-II shows (vicRam). The map gives a read there as an I/O read, so
226
+ * only code that ran shows that the program uses that RAM. The VIC-II reads
227
+ * the RAM there, so a screen there is in use.
222
228
  */
223
- export function notExecutedUnderIo<T extends AddressRange>(segments: readonly T[], used: (address: number) => boolean): T[] {
224
- return segments.filter((segment) => {
229
+ export function notExecutedUnderIo<T extends AddressRange>(segments: readonly T[], used: (address: number) => boolean, shown: readonly AddressRange[]): T[] {
230
+ const notExecuted = segments.filter((segment) => {
225
231
  if (ioSide(segment.start) !== 1 || ioSide(segment.end) !== 1) return false;
226
232
  for (let address = segment.start; address <= segment.end; address++) if (used(address)) return false;
227
233
  return true;
228
234
  });
235
+ return withoutRanges(notExecuted, shown);
229
236
  }
230
237
 
231
238
  /** For each address, the last stage that wrote it, or -1. */
@@ -6,6 +6,8 @@
6
6
  // writes the memory into the project. "loads" captures each part of a
7
7
  // multi-load program. No native unpack tool is used.
8
8
 
9
+ import { basename, extname } from "node:path";
10
+
9
11
  import { type AddressRange, COVERAGE, EXECUTE, formatC64Address, formatC64Range, formatC64RangeFields, inRanges, parseC64Address } from "#src/c64.ts";
10
12
  import { autostartLoaded, LOAD_LIMIT_FRAMES, RUN_LIMIT_FRAMES, typeRun } from "#src/host-client/autostart.ts";
11
13
  import { IO_RAM, markIoRamWrites, readCoverage, writtenBlocks } from "#src/host-client/coverage.ts";
@@ -15,11 +17,12 @@ import { readPrg } from "#src/host-client/image.ts";
15
17
  import { readMemoryInParts, ViceSessionClient } from "#src/host-client/vice-session.ts";
16
18
  import { knowledgeAt, knowledgeNames } from "#src/knowledge/names.ts";
17
19
  import { PAL_FRAME_CYCLES } from "#src/native/c64run.ts";
20
+ import { projectRelative } from "#src/project.ts";
18
21
  import { listed, OPTIONS, reply, runScript, UsageError, type Call, type CommandSpec, type OptionSpec } from "#src/script.ts";
19
22
  import { basicStart, inspect, writtenThenExecuted } from "./lib/evidence.ts";
20
23
  import { loads, readLoadSteps } from "./lib/loads.ts";
21
24
  import { callReturn, captureSegments, droppedRanges, executedIn, mergeMaps, notExecutedUnderIo, stageCandidates, stagePoints, usedAfterEntry, withoutRanges } from "./lib/stages.ts";
22
- import { entryStateFile, machineState, readyState, vectorsOf, writeCapture } from "./lib/machine.ts";
25
+ import { capturedProgram, entryStateFile, fromHere, machineState, readAsRam, readyState, vectorsOf, vicRam, writeCapture } from "./lib/machine.ts";
23
26
 
24
27
  /** Written-then-executed bytes from this many on are unpacking, decrypting or relocating, not self-changing code. */
25
28
  const UNPACKED_BYTES = 256;
@@ -505,23 +508,17 @@ async function stages(program: string, options: { frames: number; entry?: number
505
508
  /** Frames that the program runs after its entry to show the memory that it uses. */
506
509
  const AFTER_ENTRY_FRAMES = 250;
507
510
 
508
- const ENTRY_SNAPSHOT = "capture-entry";
509
-
510
511
  /**
511
512
  * Runs the program on from its entry and gives the RAM that it used: the
512
513
  * evidence that a block that a loader or a stage left is part of the
513
514
  * program. The machine then goes back to the entry.
514
515
  */
515
516
  async function usedAfter(client: ViceSessionClient): Promise<(address: number) => boolean> {
516
- await client.snapshot({ action: "save", name: ENTRY_SNAPSHOT });
517
- try {
517
+ return fromHere(client, async () => {
518
518
  await client.memmap({ action: "clear" });
519
519
  await client.execution({ action: "advance-frames", count: AFTER_ENTRY_FRAMES, space: "c64" });
520
520
  return usedAfterEntry(await readCoverage(client));
521
- } finally {
522
- await client.snapshot({ action: "restore", name: ENTRY_SNAPSHOT });
523
- await client.snapshot({ action: "remove", name: ENTRY_SNAPSHOT });
524
- }
521
+ });
525
522
  }
526
523
 
527
524
  /** Why a capture can wait for --until in vain: a step ran over it. */
@@ -558,7 +555,10 @@ async function capture(
558
555
  const used = options.range === undefined ? await usedAfter(client) : undefined;
559
556
  const found = used === undefined ? [options.range!] : captureSegments(followed.stages, registers.pc, { loaded: { start: load, end: Math.min(0xffff, load + bytes.length - 3) }, used });
560
557
  const segments = withoutRanges(found, options.exclude);
561
- const underIo = used === undefined ? [] : notExecutedUnderIo(segments, used).map(formatC64RangeFields);
558
+ // The memory map cannot show a read of the RAM under the I/O area: a run with watchpoints finds the parts that the program read as RAM.
559
+ const notExecuted = used === undefined ? [] : notExecutedUnderIo(segments, used, vicRam(state.io, memory));
560
+ const { read: readUnderIo, undecided } = notExecuted.length === 0 ? { read: [], undecided: [] } : await readAsRam(client, notExecuted, AFTER_ENTRY_FRAMES);
561
+ const underIo = notExecuted.filter((range) => !readUnderIo.includes(range) && !undecided.includes(range)).map(formatC64RangeFields);
562
562
  // The written ranges that the leftover rule took out of the segments. A --range takes no rule.
563
563
  const dropped = (options.range === undefined ? droppedRanges(followed.stages, registers.pc, [...found, ...options.exclude]) : []).map((range) => ({
564
564
  ...formatC64RangeFields(range),
@@ -568,12 +568,14 @@ async function capture(
568
568
  const vectors = vectorsOf(state, memory);
569
569
  // A clean machine at the READY prompt shows what the loader and the stages changed.
570
570
  const entry = entryStateFile(registers, state, vectors, await readyState(client));
571
+ const ran = capturedProgram(program, bytes);
571
572
  const { written, removed } = writeCapture(
572
573
  options.out,
573
574
  memory,
574
575
  segments,
575
576
  [],
576
577
  (files) => ({
578
+ ...(ran === undefined ? {} : { program: ran }),
577
579
  entry: formatC64Address(registers.pc),
578
580
  segments: segments.map((segment, index) => ({ ...formatC64RangeFields(segment), ...("writtenBy" in segment ? { writtenBy: segment.writtenBy } : {}), ...("loaded" in segment ? { loaded: true } : {}), file: files[index] })),
579
581
  ...(options.exclude.length === 0 ? {} : { excluded: options.exclude.map(formatC64RangeFields) }),
@@ -595,6 +597,8 @@ async function capture(
595
597
  ...(removed.length === 0 ? {} : { removed }),
596
598
  segments: segments.map((segment) => ({ ...formatC64RangeFields(segment), ...("loaded" in segment ? { loaded: true } : {}) })),
597
599
  ...(underIo.length === 0 ? {} : { notExecutedUnderIo: underIo }),
600
+ ...(readUnderIo.length === 0 ? {} : { readUnderIo: readUnderIo.map(formatC64RangeFields) }),
601
+ ...(undecided.length === 0 ? {} : { undecidedUnderIo: undecided.map(formatC64RangeFields) }),
598
602
  ...(options.exclude.length === 0 ? {} : { excluded: options.exclude.map(formatC64RangeFields) }),
599
603
  ...(dropped.length === 0 ? {} : { dropped }),
600
604
  stages: showStages(followed.stages),
@@ -635,8 +639,21 @@ const joined = (hints: Array<string | undefined>) => {
635
639
  const given = hints.filter((hint): hint is string => hint !== undefined);
636
640
  return given.length === 0 ? undefined : given.join(" ");
637
641
  };
638
- /** The folder that a capture writes when the agent follows the nextAction of stages. */
639
- const CAPTURE_OUT = ".c64-re-tools/local/capture";
642
+ /**
643
+ * The folder that a capture writes when the agent follows the nextAction of
644
+ * stages: one for each program, by its path in the project without the
645
+ * extension, so programs with the same name in two folders get two folders.
646
+ * A program outside the project gets the folder of its file name.
647
+ */
648
+ function captureOut(program: string): string {
649
+ let path: string;
650
+ try {
651
+ path = projectRelative(program);
652
+ } catch {
653
+ path = basename(program);
654
+ }
655
+ return `.c64-re-tools/local/capture/${path.slice(0, path.length - extname(path).length)}`;
656
+ }
640
657
 
641
658
  /** inspect: the next step is a run of the program with trace. A program without a BASIC start needs --entry for it. */
642
659
  function inspected(call: Call) {
@@ -664,7 +681,7 @@ function staged(call: Call, { output, failed }: { output: Record<string, unknown
664
681
  const more = output.moreStages === true ? `The script followed only the first ${MAX_STAGES} stages. Give a larger --min-stage, so that small stages join.` : undefined;
665
682
  return reply(result, {
666
683
  hint: joined([more, `Disassemble the code at ${last}, the entry of the last stage. Make sure that it is the start of the program and not a second unpacker. Then capture at that address.`]),
667
- nextAction: call.next("capture", call.subject(0), "--until", last, "--out", CAPTURE_OUT, ...sameStart(call)),
684
+ nextAction: call.next("capture", call.subject(0), "--until", last, "--out", captureOut(call.subject(0)), ...sameStart(call)),
668
685
  });
669
686
  }
670
687
 
@@ -674,13 +691,15 @@ function captured(call: Call, { output, failed }: { output: Record<string, unkno
674
691
  if (failed) return result;
675
692
  const dropped = ((output.dropped ?? []) as Array<{ start: string; end: string }>).reduce((sum, range) => sum + parseC64Address(range.end) - parseC64Address(range.start) + 1, 0);
676
693
  const underIo = ((output.notExecutedUnderIo ?? []) as Array<{ start: string; end: string }>).map((range) => `${range.start}-${range.end}`);
694
+ const undecided = ((output.undecidedUnderIo ?? []) as Array<{ start: string; end: string }>).map((range) => `${range.start}-${range.end}`);
677
695
  return reply(result, {
678
696
  hint: joined([
679
697
  `Disassemble the code at ${output.pc as string}. Make sure that it is the program and not the unpacker again.`,
680
698
  dropped === 0 ? undefined : `The segments do not hold ${dropped} bytes that the stages wrote, because they are in blocks with the entry of a later stage. dropped gives their ranges. Make sure that the program does not use these bytes.`,
681
699
  underIo.length === 0
682
700
  ? undefined
683
- : `In the RAM under the I/O area, the program executed no code in ${underIo.join(", ")} after the entry. The memory map cannot show reads of this RAM. Make sure that the program uses these bytes. If it does not, give each of these ranges as --exclude and capture again.`,
701
+ : `In the RAM under the I/O area, the program did not execute or read ${underIo.join(", ")} in the ${AFTER_ENTRY_FRAMES} frames after the entry. Make sure that the program does not use these bytes later. If it does not, give each of these ranges as --exclude and capture again.`,
702
+ undecided.length === 0 ? undefined : `In the RAM under the I/O area, the check for reads of ${undecided.join(", ")} did not complete. Keep these ranges in the capture.`,
684
703
  `Then put the capture ${call.string("out")!}/image.json into the project knowledge.`,
685
704
  ]),
686
705
  });
@@ -727,7 +746,7 @@ const COMMANDS: CommandSpec[] = [
727
746
  },
728
747
  {
729
748
  name: "capture",
730
- summary: "Runs the program until the CPU gets to --until after the steps, and writes into --out: image.bin (64 KiB of RAM), image.json (the entry, the segments that the stages wrote, the written ranges that it dropped, the vectors, the steps, the stages), a PRG for each segment, and entry_state.json.",
749
+ summary: "Runs the program until the CPU gets to --until after the steps, and writes into --out: image.bin (64 KiB of RAM), image.json (the program file and its SHA-256, the entry, the segments that the stages wrote, the written ranges that it dropped, the vectors, the steps, the stages), a PRG for each segment, and entry_state.json.",
731
750
  subjects: [PROGRAM],
732
751
  options: {
733
752
  until: { kind: "address", value: "<address>", required: true, help: "the unpacked entry point" },