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

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.
@@ -355,6 +355,44 @@ export interface EntryPoint {
355
355
  samplesBefore: number;
356
356
  }
357
357
 
358
+ /**
359
+ * The mark of the replay core at the first opcode fetch at an entry. Give it after count-pc, which clears it. `after`
360
+ * comes after the point of each event, before its action: the events before the mark came are the first ones.
361
+ */
362
+ async function markEntry(core: C64RunSession, entry: number) {
363
+ await core.command(`mark ${hexWord(entry)}`);
364
+ const marked = async () => {
365
+ const answer = /tick=(\d+) phase=([0-9a-f]+)/.exec(await core.command("marked"));
366
+ return answer === null ? undefined : { tick: Number(answer[1]), phase: answer[2]! };
367
+ };
368
+ let came: { tick: number; phase: string } | undefined;
369
+ let eventsBefore = 0;
370
+ return {
371
+ /** After the point of event `index` (0 is the first). */
372
+ async after(index: number): Promise<void> {
373
+ if (came !== undefined) return;
374
+ came = await marked();
375
+ if (came === undefined) eventsBefore = index + 1;
376
+ },
377
+ /** Where the program came to the entry, or undefined when it did not come to it. */
378
+ async end(): Promise<{ tick: number; phase: string; eventsBefore: number } | undefined> {
379
+ came ??= await marked();
380
+ return came === undefined ? undefined : { ...came, eventsBefore };
381
+ },
382
+ };
383
+ }
384
+
385
+ /**
386
+ * Why a rebuild with a loader cannot replay the events: the first of the events before the entry that is no runUntil
387
+ * to an address. A rebuild with a loader runs its loader there, so the event has no point in it.
388
+ */
389
+ export function eventBeforeEntry(events: readonly RecordedEvent[], eventsBefore: number, entry: number): string | undefined {
390
+ const early = events.slice(0, eventsBefore).find((event) => !("pc" in event.key));
391
+ if (early === undefined) return undefined;
392
+ const what = early.step === undefined ? "the RESTORE of the play" : `step ${early.step}`;
393
+ return `${what} ran before the program came to its entry ${formatC64Address(entry)}. A rebuild with a loader has no point for it. Make the steps of the record file start after the entry`;
394
+ }
395
+
358
396
  /**
359
397
  * A loader with a start screen that RUN starts waits for a key or a fire button that the recording does not have:
360
398
  * the rebuild goes on after the wait, as the check of the loader does. Gives the tick of the wait, a problem, or
@@ -502,18 +540,24 @@ export interface RecordOutcome {
502
540
  coverageFrom?: { tick: number; pc: number };
503
541
  /** Why the session did not complete (a runUntil that did not reach its target). */
504
542
  reason?: string;
543
+ /** With an entry: why a rebuild with a loader cannot replay the recording, as replay finds it on the reference. */
544
+ loaderProblem?: string;
505
545
  }
506
546
 
507
547
  /**
508
548
  * Plays the steps of a record file in the replay core and records the session.
509
549
  * `input` runs after the steps, with `restore` for a RESTORE press of the play;
510
- * a reason that it gives means no recording.
550
+ * a reason that it gives means no recording. With `entry`, the entry of the
551
+ * program where the loader of a rebuild jumps to, the outcome tells when the
552
+ * program did not come to it, or which event ran before it came to it, as
553
+ * replay finds it on the reference.
511
554
  */
512
555
  export async function record(
513
556
  core: C64RunSession,
514
557
  file: RecordFile,
515
558
  workspace: Workspace,
516
559
  input?: (core: C64RunSession, restore: () => Promise<string | undefined>) => Promise<string | undefined>,
560
+ entry?: number,
517
561
  ): Promise<RecordOutcome> {
518
562
  const prg = readProjectFile(file.program).bytes;
519
563
  const same = (address: number) => address;
@@ -532,6 +576,7 @@ export async function record(
532
576
  await core.command(`inputs ${inputsArgument(file.inputs)}`);
533
577
  await core.command(`record ${reads}`);
534
578
  await countAt(core, targets);
579
+ const mark = entry === undefined ? undefined : await markEntry(core, entry);
535
580
  await startProgram(core, prg, file.load);
536
581
  // From READY on: the start of the C64 itself is never in the map.
537
582
  await core.command(COVERAGE_COMMANDS.get(file.coverage) ?? `coverage on-pc ${hexWord(parseC64Address(file.coverage))}`);
@@ -551,6 +596,7 @@ export async function record(
551
596
  const reached = await core.status(`run-pc ${pc} ${tick + action.runUntil.timeoutFrames * PAL_FRAME_CYCLES} ${count}`);
552
597
  if (reached.word !== "reached") return `the program did not reach ${address} within ${action.runUntil.timeoutFrames} frames`;
553
598
  events.push({ ...(step === undefined ? {} : { step }), action, key: { pc: address, count } });
599
+ await mark?.after(events.length - 1);
554
600
  return undefined;
555
601
  }
556
602
  const busiest = afterEvent ? undefined : busiestSite(await core.command("sites"));
@@ -563,6 +609,7 @@ export async function record(
563
609
  return `the program did not read its input again within ${READ_WAIT_FRAMES} frames. This step runs at the next input read. Put a runUntil step to an address before it: that step needs no input read`;
564
610
  }
565
611
  events.push({ ...(step === undefined ? {} : { step }), action, key });
612
+ await mark?.after(events.length - 1);
566
613
  return doAction(core, action, at);
567
614
  };
568
615
  for (const [index, step] of file.steps.entries()) {
@@ -607,6 +654,13 @@ export async function record(
607
654
  return failed === undefined ? undefined : "RESTORE: " + failed;
608
655
  };
609
656
  if (input !== undefined && reason === undefined) reason = await input(core, restore);
657
+ const came = await mark?.end();
658
+ const loaderProblem =
659
+ entry === undefined
660
+ ? undefined
661
+ : came === undefined
662
+ ? `the program did not come to its entry ${formatC64Address(entry)} in the session, where the loader of a rebuild jumps. Make the session go on until the program runs from its entry`
663
+ : eventBeforeEntry(events, came.eventsBefore, entry);
610
664
  const end = await core.status("status");
611
665
  const sites = (await core.command("sites")).split(" ").slice(2).map((entry): RecordedSite => {
612
666
  const [where, reads, kind] = entry.split(":");
@@ -636,6 +690,7 @@ export async function record(
636
690
  coverage: readFileSync(coverage),
637
691
  ...(from === null ? {} : { coverageFrom: { tick: Number(from[1]), pc: Number.parseInt(from[2]!, 16) } }),
638
692
  ...(reason === undefined ? {} : { reason }),
693
+ ...(loaderProblem === undefined ? {} : { loaderProblem }),
639
694
  };
640
695
  }
641
696
 
@@ -719,7 +774,7 @@ export async function replaySide(
719
774
  if (options.compare !== undefined && options.handover === undefined) await startSampling(options.compare);
720
775
  const targets = recording.events.flatMap((event) => ("pc" in event.key ? [at.code(event.key.pc)] : []));
721
776
  await countAt(core, targets);
722
- if (options.entry !== undefined) await core.command(`mark ${hexWord(options.entry)}`);
777
+ const mark = options.entry === undefined ? undefined : await markEntry(core, options.entry);
723
778
  await startProgram(core, prg, recording.load);
724
779
  const base = reference ? recording.ticks : recording.ticks * REBUILD_TIME_FACTOR;
725
780
  let limit = base;
@@ -759,14 +814,6 @@ export async function replaySide(
759
814
  }
760
815
  }
761
816
  }
762
- // The reference with an entry: the events before the mark at the entry came.
763
- let eventsBefore = 0;
764
- let entryTick: number | undefined;
765
- let entryPhase = "";
766
- const marked = async () => {
767
- const answer = /tick=(\d+) phase=([0-9a-f]+)/.exec(await core.command("marked"));
768
- if (answer !== null) [entryTick, entryPhase] = [Number(answer[1]), answer[2]!];
769
- };
770
817
  for (const [index, event] of (problem === undefined ? recording.events : []).entries()) {
771
818
  const what = event.step === undefined ? "the RESTORE of the play" : "step " + event.step;
772
819
  let key = event.key;
@@ -781,10 +828,8 @@ export async function replaySide(
781
828
  problem = "the program did not come to the point of " + what;
782
829
  break;
783
830
  }
784
- if (options.entry !== undefined && entryTick === undefined) {
785
- await marked();
786
- if (entryTick === undefined) eventsBefore = index + 1;
787
- }
831
+ // The reference with an entry: the events before the mark at the entry came.
832
+ await mark?.after(index);
788
833
  // At the point of a runUntil to an address, its target is reached.
789
834
  if (!("pc" in event.key)) problem = await doAction(core, event.action, at);
790
835
  if (problem !== undefined) {
@@ -804,8 +849,8 @@ export async function replaySide(
804
849
  lines = readFileSync(samples, "utf8").split("\n").filter((line) => line !== "");
805
850
  }
806
851
  let entryPoint: EntryPoint | undefined;
807
- if (options.entry !== undefined && entryTick === undefined) await marked();
808
- if (entryTick !== undefined) {
852
+ const came = await mark?.end();
853
+ if (came !== undefined) {
809
854
  const counts = new Map<string, number>();
810
855
  for (const event of recording.events) {
811
856
  if (!("pc" in event.key) || counts.has(event.key.pc)) continue;
@@ -813,8 +858,8 @@ export async function replaySide(
813
858
  if (before !== null) counts.set(event.key.pc, Number(before[1]));
814
859
  }
815
860
  // A checkpoint at the first fetch at the entry has the tick of the mark. The rebuild starts its checkpoints after that fetch.
816
- const after = lines.filter((line) => Number(line.split(" ")[0]) > entryTick!);
817
- entryPoint = { tick: entryTick, phase: entryPhase, counts, eventsBefore, samplesBefore: lines.length - after.length };
861
+ const after = lines.filter((line) => Number(line.split(" ")[0]) > came.tick);
862
+ entryPoint = { ...came, counts, samplesBefore: lines.length - after.length };
818
863
  lines = after;
819
864
  }
820
865
  return {
@@ -19,7 +19,7 @@ import { localToolContext } from "#src/native/local.ts";
19
19
  import { Workspace } from "#src/native/staging.ts";
20
20
  import { resolveProjectPath } from "#src/project.ts";
21
21
  import { UsageError } from "#src/script.ts";
22
- import { firstDifference, loaderEntry, mover, parseStateItem, pinLines, readRecording, replaySide, siteMap, type Comparison, type ReplayResult, type ReplaySubject } from "./recording.ts";
22
+ import { eventBeforeEntry, firstDifference, loaderEntry, mover, parseStateItem, pinLines, readRecording, replaySide, siteMap, type Comparison, type ReplayResult, type ReplaySubject } from "./recording.ts";
23
23
  import { cachedNames } from "./scenario.ts";
24
24
 
25
25
  const MAX_STATE_ITEMS = 16;
@@ -155,11 +155,8 @@ export async function replay(values: ReplayOptions): Promise<ReplayResult> {
155
155
  const at = formatC64Address(loader.reference);
156
156
  if (entered === undefined) return result("INCONCLUSIVE", "reference", { reason: `the reference never came to ${at}, where the loader of the rebuild jumps` });
157
157
  // An event before the entry has no point in a rebuild with a loader. A runUntil to an address there does nothing, and the rebuild leaves it out.
158
- const early = recording.events.slice(0, entered.eventsBefore).find((event) => !("pc" in event.key));
159
- if (early !== undefined) {
160
- const what = early.step === undefined ? "the RESTORE of the play" : `step ${early.step}`;
161
- return result("INCONCLUSIVE", "reference", { reason: `${what} ran before the program came to its entry ${at}. A rebuild with a loader has no point for it. Make the steps of the record file start after the entry` });
162
- }
158
+ const early = eventBeforeEntry(recording.events, entered.eventsBefore, loader.reference);
159
+ if (early !== undefined) return result("INCONCLUSIVE", "reference", { reason: early });
163
160
  handover = { entry: loader.entry, reference: entered };
164
161
  }
165
162
 
@@ -17,6 +17,7 @@ import { localToolContext } from "#src/native/local.ts";
17
17
  import { Workspace } from "#src/native/staging.ts";
18
18
  import { openForRead } from "#src/knowledge/database.ts";
19
19
  import { changedEvidence } from "#src/knowledge/evidence.ts";
20
+ import { programEntry } from "#src/knowledge/program.ts";
20
21
  import { knowledgeNames } from "#src/knowledge/names.ts";
21
22
  import { RECORDING_FILES } from "#src/knowledge/recording-files.ts";
22
23
  import { LOCAL_DIRECTORY, PROJECT_DIRECTORY, projectRelative, projectRoot } from "#src/project.ts";
@@ -95,7 +96,10 @@ async function recordCommand(call: Call): Promise<Reply> {
95
96
  return play(session, { httpPort, joystick, ready, restore });
96
97
  }
97
98
  : undefined;
98
- const outcome = await record(core, file, workspace, person);
99
+ // 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
100
+ // knowledge, also for symbols none. With the names of a build, or with load true (no loader entry), record marks no entry.
101
+ const namedAsKnowledge = file.symbols === "knowledge" || file.symbols === "none";
102
+ const outcome = await record(core, file, workspace, person, file.load || !namedAsKnowledge ? undefined : programEntry(db));
99
103
  const summary = {
100
104
  name: file.name,
101
105
  frames: Math.round(outcome.recording.ticks / PAL_FRAME_CYCLES),
@@ -127,9 +131,11 @@ async function recordCommand(call: Call): Promise<Reply> {
127
131
  ...(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
132
  ...(evidence.some((change) => change.file !== map) ? [" For each other file in evidence, examine the facts of its revisions against the new recording."] : []),
129
133
  ].join("");
134
+ // The recording replays on the reference and on a rebuild without a loader: the event before the entry is no refusal.
135
+ 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. `;
130
136
  return reply(
131
137
  { 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) },
138
+ { hint: `${loader}${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
139
  );
134
140
  } finally {
135
141
  db?.close();
@@ -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
 
@@ -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,7 @@ 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 these segments, 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. 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
197
  - `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
198
  - `stages`: one item for each stage, as `stages` gives it.
199
199
  - `differsFromReset`: the count of bytes that are not as a clean C64 has them at READY.
@@ -201,7 +201,7 @@ Traps:
201
201
  The folder `--out` gets these files:
202
202
 
203
203
  - `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`.
204
+ - `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
205
  - One PRG for each segment.
206
206
  - `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
207
 
@@ -219,7 +219,7 @@ If no stage wrote the capture entry, the program runs as it loaded. Then the ran
219
219
 
220
220
  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
221
 
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.
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 parts.
223
223
 
224
224
  Traps:
225
225
 
@@ -229,7 +229,7 @@ Traps:
229
229
 
230
230
  ### `loads <program>`
231
231
 
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`.
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. `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
233
 
234
234
  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
235
 
@@ -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,13 @@ 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
+ const ran = capturedProgram(program);
113
115
  const client = await ViceSessionClient.open({ videoStandard: "pal" });
114
116
  try {
115
117
  // 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.
@@ -202,6 +204,7 @@ export async function loads(program: string, options: { out: string; steps: Load
202
204
  other,
203
205
  (files) => ({
204
206
  capture: step.capture,
207
+ ...(ran === undefined ? {} : { program: ran }),
205
208
  entry: formatC64Address(registers.pc),
206
209
  segments: segments.map((segment, at) => ({ ...formatC64RangeFields(segment), file: files[at] })),
207
210
  ...(options.exclude.length === 0 ? {} : { excluded: options.exclude.map(formatC64RangeFields) }),
@@ -5,11 +5,13 @@
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
- import { writeRefusal, writeReported, type Written } from "#src/host-client/transfer.ts";
10
+ import { readProjectFile, writeRefusal, writeReported, type Written } from "#src/host-client/transfer.ts";
11
11
  import { readMemoryInParts, type ViceSessionClient } from "#src/host-client/vice-session.ts";
12
- import { projectRoot, resolveProjectPath } from "#src/project.ts";
12
+ import { startScreenRanges } from "#src/knowledge/read.ts";
13
+ import { sha256 } from "#src/knowledge/text.ts";
14
+ import { projectRelative, projectRoot, resolveProjectPath } from "#src/project.ts";
13
15
 
14
16
  type Registers = Awaited<ReturnType<ViceSessionClient["registersGet"]>>;
15
17
 
@@ -47,6 +49,41 @@ export async function machineState(client: ViceSessionClient): Promise<MachineSt
47
49
  return { port, pages, io, cia: { cia1: cia1!, cia2: cia2! }, romVectors };
48
50
  }
49
51
 
52
+ /**
53
+ * The RAM that the VIC-II shows in a machine state, from the VIC-II and CIA 2
54
+ * of `io`: the screen, the bitmap in bitmap mode or else the charset when it
55
+ * is RAM (startScreenRanges), and for each sprite that $d015 enables its
56
+ * pointer at the end of the screen and its 64 data bytes in `memory`. The
57
+ * VIC-II always reads RAM, also under the I/O area.
58
+ */
59
+ export function vicRam(io: { vic: Uint8Array; cia2: Uint8Array }, memory: Uint8Array): AddressRange[] {
60
+ const shown = vicScreenMemory(io.vic, io.cia2);
61
+ const ranges = startScreenRanges(shown).map((part) => part.range);
62
+ for (let sprite = 0; sprite < 8; sprite++) {
63
+ if ((io.vic[0x15]! & (1 << sprite)) === 0) continue;
64
+ const pointer = spritePointer(shown.screen, sprite);
65
+ const data = spriteData(io.cia2, memory[pointer]!);
66
+ ranges.push({ start: pointer, end: pointer }, { start: data, end: data + 63 });
67
+ }
68
+ return ranges;
69
+ }
70
+
71
+ /**
72
+ * The program file that a capture ran, for its image.json: the path in the
73
+ * project in one spelling, and the SHA-256 of the file. A release of the
74
+ * capture cites them, because git ignores the capture in local/. A file
75
+ * outside the project gives undefined: then a release cites the image.json.
76
+ */
77
+ export function capturedProgram(path: string): { file: string; sha256: string } | undefined {
78
+ let file: string;
79
+ try {
80
+ file = projectRelative(path);
81
+ } catch {
82
+ return undefined;
83
+ }
84
+ return { file, sha256: sha256(readProjectFile(path).bytes) };
85
+ }
86
+
50
87
  const word = (bytes: Buffer, offset: number) => formatC64Address(bytes[offset]! | (bytes[offset + 1]! << 8));
51
88
 
52
89
  /** The KERNAL vectors in page 3, the hardware vectors in RAM, and the ROM's own. */
@@ -216,16 +216,19 @@ export function droppedRanges(stages: Stages, entry: number, kept: readonly Addr
216
216
  }
217
217
 
218
218
  /**
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.
219
+ * The parts of the segments in the RAM under the I/O area in which the
220
+ * program executed no code after its entry, without `shown`, the RAM that
221
+ * the VIC-II shows (vicRam). The map gives a read there as an I/O read, so
222
+ * only code that ran shows that the program uses that RAM. The VIC-II reads
223
+ * the RAM there, so a screen there is in use.
222
224
  */
223
- export function notExecutedUnderIo<T extends AddressRange>(segments: readonly T[], used: (address: number) => boolean): T[] {
224
- return segments.filter((segment) => {
225
+ export function notExecutedUnderIo<T extends AddressRange>(segments: readonly T[], used: (address: number) => boolean, shown: readonly AddressRange[]): T[] {
226
+ const notExecuted = segments.filter((segment) => {
225
227
  if (ioSide(segment.start) !== 1 || ioSide(segment.end) !== 1) return false;
226
228
  for (let address = segment.start; address <= segment.end; address++) if (used(address)) return false;
227
229
  return true;
228
230
  });
231
+ return withoutRanges(notExecuted, shown);
229
232
  }
230
233
 
231
234
  /** 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, machineState, 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;
@@ -558,7 +561,7 @@ async function capture(
558
561
  const used = options.range === undefined ? await usedAfter(client) : undefined;
559
562
  const found = used === undefined ? [options.range!] : captureSegments(followed.stages, registers.pc, { loaded: { start: load, end: Math.min(0xffff, load + bytes.length - 3) }, used });
560
563
  const segments = withoutRanges(found, options.exclude);
561
- const underIo = used === undefined ? [] : notExecutedUnderIo(segments, used).map(formatC64RangeFields);
564
+ const underIo = used === undefined ? [] : notExecutedUnderIo(segments, used, vicRam(state.io, memory)).map(formatC64RangeFields);
562
565
  // The written ranges that the leftover rule took out of the segments. A --range takes no rule.
563
566
  const dropped = (options.range === undefined ? droppedRanges(followed.stages, registers.pc, [...found, ...options.exclude]) : []).map((range) => ({
564
567
  ...formatC64RangeFields(range),
@@ -568,12 +571,14 @@ async function capture(
568
571
  const vectors = vectorsOf(state, memory);
569
572
  // A clean machine at the READY prompt shows what the loader and the stages changed.
570
573
  const entry = entryStateFile(registers, state, vectors, await readyState(client));
574
+ const ran = capturedProgram(program);
571
575
  const { written, removed } = writeCapture(
572
576
  options.out,
573
577
  memory,
574
578
  segments,
575
579
  [],
576
580
  (files) => ({
581
+ ...(ran === undefined ? {} : { program: ran }),
577
582
  entry: formatC64Address(registers.pc),
578
583
  segments: segments.map((segment, index) => ({ ...formatC64RangeFields(segment), ...("writtenBy" in segment ? { writtenBy: segment.writtenBy } : {}), ...("loaded" in segment ? { loaded: true } : {}), file: files[index] })),
579
584
  ...(options.exclude.length === 0 ? {} : { excluded: options.exclude.map(formatC64RangeFields) }),
@@ -635,8 +640,21 @@ const joined = (hints: Array<string | undefined>) => {
635
640
  const given = hints.filter((hint): hint is string => hint !== undefined);
636
641
  return given.length === 0 ? undefined : given.join(" ");
637
642
  };
638
- /** The folder that a capture writes when the agent follows the nextAction of stages. */
639
- const CAPTURE_OUT = ".c64-re-tools/local/capture";
643
+ /**
644
+ * The folder that a capture writes when the agent follows the nextAction of
645
+ * stages: one for each program, by its path in the project without the
646
+ * extension, so programs with the same name in two folders get two folders.
647
+ * A program outside the project gets the folder of its file name.
648
+ */
649
+ function captureOut(program: string): string {
650
+ let path: string;
651
+ try {
652
+ path = projectRelative(program);
653
+ } catch {
654
+ path = basename(program);
655
+ }
656
+ return `.c64-re-tools/local/capture/${path.slice(0, path.length - extname(path).length)}`;
657
+ }
640
658
 
641
659
  /** inspect: the next step is a run of the program with trace. A program without a BASIC start needs --entry for it. */
642
660
  function inspected(call: Call) {
@@ -664,7 +682,7 @@ function staged(call: Call, { output, failed }: { output: Record<string, unknown
664
682
  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
683
  return reply(result, {
666
684
  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)),
685
+ nextAction: call.next("capture", call.subject(0), "--until", last, "--out", captureOut(call.subject(0)), ...sameStart(call)),
668
686
  });
669
687
  }
670
688
 
@@ -727,7 +745,7 @@ const COMMANDS: CommandSpec[] = [
727
745
  },
728
746
  {
729
747
  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.",
748
+ 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
749
  subjects: [PROGRAM],
732
750
  options: {
733
751
  until: { kind: "address", value: "<address>", required: true, help: "the unpacked entry point" },
package/src/c64.ts CHANGED
@@ -193,6 +193,27 @@ export function d018Offsets(d018: number): { screen: number; characters: number;
193
193
  return { screen: ((d018 >> 4) & 0x0f) * 0x400, characters: ((d018 >> 1) & 0x07) * 0x800, bitmap: (d018 & 0x08) !== 0 ? 0x2000 : 0 };
194
194
  }
195
195
 
196
+ /**
197
+ * The screen memory that the VIC-II reads, from its registers ($d000-$d02e)
198
+ * and the ports of CIA 2 ($dd00-$dd0f): the screen, and the bitmap in bitmap
199
+ * mode or else the charset.
200
+ */
201
+ export function vicScreenMemory(vic: Uint8Array, cia2: Uint8Array): { screen: number; bitmap: number } | { screen: number; charset: number } {
202
+ const bank = vicBankBase(cia2[0]!, cia2[2]);
203
+ const offsets = d018Offsets(vic[0x18]!);
204
+ return { screen: bank + offsets.screen, ...((vic[0x11]! & 0x20) !== 0 ? { bitmap: bank + offsets.bitmap } : { charset: bank + offsets.characters }) };
205
+ }
206
+
207
+ /** The address of the pointer of a sprite (0-7): the last 8 bytes of the 1 KiB of screen memory. */
208
+ export function spritePointer(screen: number, sprite: number): number {
209
+ return screen + 0x3f8 + sprite;
210
+ }
211
+
212
+ /** The address of the 64 data bytes of a sprite, from its pointer value and the bank that the ports of CIA 2 ($dd00-$dd0f) select. */
213
+ export function spriteData(cia2: Uint8Array, pointer: number): number {
214
+ return vicBankBase(cia2[0]!, cia2[2]) + pointer * 64;
215
+ }
216
+
196
217
  /**
197
218
  * Converts text to the PETSCII bytes the C64 keyboard types after a reset
198
219
  * (upper case/graphics mode). Letters of either case type the unshifted key,
@@ -3,7 +3,7 @@
3
3
  // bank without side effects; the SID's write-only registers read back as
4
4
  // last written.
5
5
 
6
- import { d018Offsets, vicBankBase } from "../../c64.ts";
6
+ import { spriteData, vicScreenMemory } from "../../c64.ts";
7
7
  import type { CiaState, SidState, SpriteState, ViciiMode, ViciiState } from "../../protocol/vice.ts";
8
8
 
9
9
  export function viciiMode(d011: number, d016: number): ViciiMode {
@@ -20,15 +20,12 @@ export function viciiMode(d011: number, d016: number): ViciiMode {
20
20
  export function decodeVicii(vic: Uint8Array, cia2: Uint8Array): ViciiState {
21
21
  const d011 = vic[0x11]!;
22
22
  const d016 = vic[0x16]!;
23
- const offsets = d018Offsets(vic[0x18]!);
24
- const mode = viciiMode(d011, d016);
25
- const base = vicBankBase(cia2[0x00]!, cia2[0x02]!);
26
- const bitmap = mode === "bitmap" || mode === "multicolor-bitmap";
23
+ const shown = vicScreenMemory(vic, cia2);
27
24
  return {
28
25
  rasterLine: ((d011 & 0x80) << 1) | vic[0x12]!,
29
- mode,
30
- screenAddress: base + offsets.screen,
31
- graphicsAddress: base + (bitmap ? offsets.bitmap : offsets.characters),
26
+ mode: viciiMode(d011, d016),
27
+ screenAddress: shown.screen,
28
+ graphicsAddress: "bitmap" in shown ? shown.bitmap : shown.charset,
32
29
  scrollX: d016 & 0x07,
33
30
  scrollY: d011 & 0x07,
34
31
  borderColor: vic[0x20]! & 0x0f,
@@ -49,7 +46,7 @@ export function decodeSprite(index: number, vic: Uint8Array, cia2: Uint8Array, p
49
46
  expandX: bit(0x1d),
50
47
  expandY: bit(0x17),
51
48
  behindBackground: bit(0x1b),
52
- dataAddress: vicBankBase(cia2[0x00]!, cia2[0x02]!) + pointers[index]! * 64,
49
+ dataAddress: spriteData(cia2, pointers[index]!),
53
50
  };
54
51
  }
55
52
 
@@ -11,7 +11,7 @@ import { tmpdir } from "node:os";
11
11
  import { join } from "node:path";
12
12
  import { setTimeout as sleep } from "node:timers/promises";
13
13
 
14
- import { formatC64Address, instructionLength } from "../../c64.ts";
14
+ import { formatC64Address, instructionLength, spritePointer } from "../../c64.ts";
15
15
  import { matrixRows } from "../../c64-keys.ts";
16
16
  import { encodePng, type IndexedFrame } from "../../graphics.ts";
17
17
  import { accessedValue, instructionText, JAM_OPCODES, OPCODES, operandAddress } from "../../opcodes.ts";
@@ -1325,7 +1325,7 @@ export class ViceSession implements ViceSessionHandle {
1325
1325
  const cia2 = await this.#machine.readIo(0xdd00, 0x10);
1326
1326
  // Sprite pointers sit in the RAM the VIC-II reads, at the end of screen memory.
1327
1327
  const screen = decodeVicii(vic, cia2).screenAddress;
1328
- const pointers = Buffer.from(await this.#machine.readMemory({ address: screen + 0x3f8, size: 8, space: "c64", view: "ram" }), "hex");
1328
+ const pointers = Buffer.from(await this.#machine.readMemory({ address: spritePointer(screen, 0), size: 8, space: "c64", view: "ram" }), "hex");
1329
1329
  const wanted = indexes.length === 0 ? [0, 1, 2, 3, 4, 5, 6, 7] : indexes;
1330
1330
  return wanted.map((index) => decodeSprite(index, vic, cia2, pointers));
1331
1331
  }
@@ -20,6 +20,8 @@ export interface Image {
20
20
  state?: EntryState;
21
21
  /** The stages of the capture in image.json, as the unpacker wrote them. */
22
22
  stages?: Array<Record<string, unknown>>;
23
+ /** The PRG that the capture in image.json ran, as the project path that the capture got, and the SHA-256 of that file. */
24
+ program?: { file: string; sha256: string };
23
25
  }
24
26
 
25
27
  /** The kinds of media files that are no PRG, by extension. */
@@ -104,6 +106,11 @@ export function readImage(path: string): Image {
104
106
  if (state !== undefined) image.state = state;
105
107
  if (manifest.entry !== undefined) image.entry = address(manifest.entry, "entry");
106
108
  if (Array.isArray(manifest.stages)) image.stages = manifest.stages.map((stage, index) => (isObject(stage) ? stage : fail(`stage ${index + 1} is not an object`)));
109
+ if (manifest.program !== undefined) {
110
+ const program = isObject(manifest.program) ? manifest.program : fail("its program is not an object");
111
+ if (typeof program.file !== "string" || program.file === "" || typeof program.sha256 !== "string" || !/^[0-9a-f]{64}$/.test(program.sha256)) fail("its program has no file and SHA-256");
112
+ image.program = { file: program.file as string, sha256: program.sha256 as string };
113
+ }
107
114
  return image;
108
115
  }
109
116
 
@@ -183,7 +183,8 @@ function ownNames(db: DatabaseSync, analyzer: Analyzer, range: AddressRange, spa
183
183
  * one for each analyzer at an address, and never to symbols. A run replaces
184
184
  * the analyzer's own names in its coverage. A name that the user or the LLM
185
185
  * gave the address already is not kept twice. A code or data kind that
186
- * disagrees with the name of the address is a conflict.
186
+ * disagrees with the name of the address is a conflict, except on dual-use
187
+ * bytes: they are code at one time and data at another.
187
188
  */
188
189
  function importNames(db: DatabaseSync, change: Change, findings: NormalizedFindings, coverage: AddressRange[], result: ImportResult): void {
189
190
  const { analyzer } = findings;
@@ -206,9 +207,10 @@ function importNames(db: DatabaseSync, change: Change, findings: NormalizedFindi
206
207
  else replaced.add(own.address);
207
208
  }
208
209
  }
210
+ const dualUse = (address: number) => regionsOverlapping(db, address, address, space).some((row) => row.type === "dual-use");
209
211
  for (const finding of findings.symbols) {
210
212
  const current = symbolAt(db, finding.address, space);
211
- if (current !== undefined && isCode(current.kind) !== isCode(finding.kind)) {
213
+ if (current !== undefined && isCode(current.kind) !== isCode(finding.kind) && !dualUse(finding.address)) {
212
214
  result.conflicts.push({ category: "symbol", address: finding.address, reason: "kind", current, finding: { name: finding.name, kind: finding.kind } });
213
215
  }
214
216
  if (settled.has(finding.address)) continue;