@henols/c64-re-tools 2.6.0-rc.15 → 2.6.0-rc.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@henols/c64-re-tools",
3
- "version": "2.6.0-rc.15",
3
+ "version": "2.6.0-rc.17",
4
4
  "description": "Agent-friendly Commodore 64 engineering toolkit for reverse engineering, debugging, development and testing.",
5
5
  "license": "MIT",
6
6
  "author": "Henrik Olsson",
@@ -109,9 +109,9 @@ A rebuilt program gets its source from the project knowledge. A change is a swit
109
109
  - Build the base release and compare it with the original. This build must be identical to the original.
110
110
  - Build the default build.
111
111
  - When the default build does not have the switch, set the switch to 1 in `src/config.asm`. Then build the default build. After the test, set the value back to the default if the user did not ask for the change.
112
- 8. Test the build that has the switch:
113
- - When the behavior must stay the same as the original, replay a recording that executes the changed code. Run a test scenario in `tests/` only when no recording executes that code.
114
- - Run a run file with `expect` steps that show the feature or the fix.
112
+ 8. Test the builds:
113
+ - When the behavior must stay the same as the original, replay each recording on the default build `build/clean.prg`. Do not replay a build with a switch that is not at its default. Run a test scenario in `tests/` only when no recording executes the changed code.
114
+ - On the build that has the switch, run a run file with `expect` steps that show the feature or the fix.
115
115
 
116
116
  ### The answer
117
117
 
@@ -85,7 +85,7 @@ Do the stages in this sequence. Go to the next stage only when its exit check is
85
85
 
86
86
  | Stage | Work | Exit check |
87
87
  |---|---|---|
88
- | 1. Acceptance | Ask the user for the criteria of the rebuild. Offer these criteria: a base release that is identical to the original, and a passed replay of the default build. Also offer a replay of each recording, test scenarios and a list of the code that no run executed. Also offer documentation of the flows, tables, formats and graphics. | The user gave the criteria. |
88
+ | 1. Acceptance | Ask the user for the criteria of the rebuild. Offer these criteria: a base release that is identical to the original, and a passed replay of each recording on the default build. Also offer test scenarios and a list of the code that no run executed. Also offer documentation of the flows, tables, formats and graphics. | The user gave the criteria. |
89
89
  | 2. Get | List the disk image. Extract the start file into `original/`. | The start file is in the project. |
90
90
  | 3. Start | Find the SYS address of the BASIC start. | You have the entry address. |
91
91
  | 4. Unpack | Examine the program for a packer. Trace it and find its stages. Capture a packed program into `.c64-re-tools/local/`. When a segment is the data of a cracktro and the program does not read it, capture again and exclude that range. Put the capture, or the PRG of a program without a packer, into the project knowledge. | The program in the project knowledge has the segments and the entry. |
@@ -94,15 +94,15 @@ Do the stages in this sequence. Go to the next stage only when its exit check is
94
94
  | 7. Name | If the workspace has a routine library, match the program against it. Write the names of the matches to the project knowledge. Then name each routine in the scope and give it a comment. Find the platform addresses in the memory map of the C64. Record the modules. Put the modules of one part of the program in one folder, for example `music/`, `irq/` or `graphics/`. When the scope has hundreds of routines, ask the user which routines to name. The source gives the other routines an `l_xxxx` label. | Each routine that the user selected has a name and a comment. |
95
95
  | 8. Releases and switches | Record the original file, or the capture of it, as the base release in the project knowledge. The project knowledge keeps the bytes of each release. Record each other release. Compare the releases. Find the leftovers. Record a switch for each copy protection, trainer, cheat, crack change and correction. Record a patch for each range of a switch. Record each leftover as a region with a comment. | The project knowledge lists each switch. Each difference between the releases is in a patch, or the answer gives it as an exception. |
96
96
  | 9. Generate | Generate the source from the project knowledge into `src`. For an unpacked program, also generate the loader. | The result of the generation is PASS. A release whose code is at other addresses is a version with a project of its own, or an exception in the answer. See "Versions of one program". |
97
- | 10. Build and test | Build the base release into `build/`, and compare it with the original. Build the default build. Replay one recording on the default build. For each replay, give the checkpoint routine, the state and the random state with the names of stage 7. Then do only the tests that the next paragraph gives. | The criteria of stage 1 are true. |
97
+ | 10. Build and test | Build the base release into `build/`, and compare it with the original. Build the default build `build/clean.prg`. Replay each recording on it. For each replay, give the checkpoint routine, the state and the random state with the names of stage 7. Then do only the tests that the next paragraph gives. | The criteria of stage 1 are true. |
98
98
  | 11. Document | When the criteria ask for documentation, generate it into `README.md` and `docs/`. For versions in a group folder, also write the shared pages of the group folder. Then link the pages. | The link check of the documentation gives PASS. |
99
99
  | 12. Hand over | Find each file that you made outside `.c64-re-tools/local/` and that is not a deliverable. Move it into `.c64-re-tools/local/`. Then give the answer (below). | Each file that you made outside `.c64-re-tools/local/` is a deliverable. |
100
100
 
101
101
  In stage 5, make the recordings before you change the program. A recording needs no names, and its coverage gives the analysis of stage 6 more code. If you cannot get to a part of the program, ask the user how to get to it. Do stages 7 to 9 again until the source is clear. Each generation writes the source again.
102
102
 
103
- In stage 10, a base release that is identical to the original proves the source. Do not test the base release more. The default build is different from the base release only in its patches, its leftovers and its loader. Thus test only these differences:
103
+ In stage 10, a base release that is identical to the original proves the source. Do not test the base release more. The default build is different from the base release only in its patches, its leftovers and its loader. The replays on the default build test these differences:
104
104
 
105
- - When a patch of the default build changes code that a run executed, replay each recording of the part that has that code. A copy protection check is an example.
105
+ - Replay only the default build `build/clean.prg`. Do not replay a release build or a build with a switch that is not at its default.
106
106
  - Write a test scenario only for a test that a replay cannot do. Examples are a program that loads more files from a disk, and a criterion of the user.
107
107
  - Do the other tests of stage 1 only when the user selected them.
108
108
 
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: c64-testing
3
- description: Tests if a rebuilt or changed C64 program behaves as the original, or if a program has the expected values. It runs a scenario on the original and on the rebuild in an emulator. It compares memory, registers, chip state and the screen with explicit rules, and gives PASS, FAIL or INCONCLUSIVE. Use it when you must show that a rebuild or a correction keeps the behavior of the original. Use it to do many steps on one program and keep the screens, coverage maps, traces and snapshots as files. Use it to test a new program or a correction with expected values. Use it to record a play session of the original and replay it on each rebuild. Use it to find what changed between two machine states, and to make a checklist for a human playtest. It does not find the cause of a difference. It does not build the program.
3
+ description: Tests if a rebuilt or changed C64 program behaves as the original, or if a program has the expected values. It runs a scenario on the original and on the rebuild in an emulator. It compares memory, registers, chip state and the screen with explicit rules, and gives PASS, FAIL or INCONCLUSIVE. Use it when you must show that a rebuild or a correction keeps the behavior of the original. Use it to do many steps on one program and keep the screens, coverage maps, traces and snapshots as files. Use it to test a new program or a correction with expected values. Use it to record a play session of the original and replay it on the default build of the rebuild. Use it to find what changed between two machine states, and to make a checklist for a human playtest. It does not find the cause of a difference. It does not build the program.
4
4
  ---
5
5
 
6
6
  # C64 testing
@@ -48,6 +48,7 @@ To get the command list, run the script with no arguments.
48
48
  - `--state` and `--pin` take a name or a `$` address, with `:size` for more than one byte, for example `room:2`. Use the names that the project knowledge has at the time of the replay.
49
49
  - The joystick port of `--joystick` is the port that the program reads. Port 2 is `$DC00`, and port 1 is `$DC01`. Find the port in the code or in the project knowledge. If you do not know the port, use 2.
50
50
  - `diff` takes two states of one kind. A state is a snapshot file (`.vsf`), a memory file (`.bin`) of a run, or an observation of a run (`results.json:<name>`). A `save` step of a run writes a snapshot file. A snapshot save in the emulator also writes one.
51
+ - Each command starts its own emulator. Thus many commands can run at the same time. For example, other commands can run while a long `record` runs in the background.
51
52
 
52
53
  ### Paths and the project folder
53
54
 
@@ -178,6 +179,7 @@ A recording keeps a session of the original program, for example a play through
178
179
  - Make the recordings early, before you change the program.
179
180
  - Ask the user to play first. Tell the user which parts of the program the recordings must have, for example each room, a fight and a lost life.
180
181
  - Record a session from steps only for a part that the sessions of the user do not have, or when the user cannot play.
182
+ - Replay each recording on the default build `build/clean.prg`. Do not replay a release build or a build with a switch that is not at its default.
181
183
  - Commit the recording folder with the scenarios. Do not put a recording into the project knowledge. Do not put test results, screenshots or playtest results into it.
182
184
  - A finding that a recording shows can go into the project knowledge. Give the `recording.json` of the recording as its test evidence.
183
185
  - The C64 of a recording has no disk drive. For a program that loads more files from a disk, use a scenario with `test`.
@@ -72,7 +72,13 @@ The keyboard queue of the KERNAL holds 10 keys. If the keys of a `type` step and
72
72
 
73
73
  RESTORE starts an NMI and is not a read. The recording keeps each RESTORE of a `press` step as an event of that step. The replay presses RESTORE again at the same read of the program.
74
74
 
75
- `type`, `write`, `registers` and `runUntil` steps are events. The recording keeps a point in the program for each event. The point is the next read at the input site with the most reads. That site is not in ROM. A replay does the event again at the same read. An event that comes directly after another event runs at once after that event.
75
+ `type`, `write`, `registers` and `runUntil` steps are events. The recording keeps a point in the program for each event. A replay does the event again at the same point:
76
+
77
+ - A `runUntil` step to an address: the point is the number of times that the CPU got to that address. This step does not need an input read.
78
+ - An event that comes directly after another event runs at once after that event.
79
+ - Each other event: the point is the next read at the input site with the most reads. That site is not in ROM. If the program does not read input in 600 frames, the session stops.
80
+
81
+ Some parts of a program read no input, for example an intro or a bonus screen. To do an event in such a part, put a `runUntil` step to an address before the event.
76
82
 
77
83
  ## Play
78
84
 
@@ -39,6 +39,10 @@ export function inputsArgument(inputs: string[]): string {
39
39
  /** Frames that a pressed key is held, and then released. */
40
40
  const KEY_FRAMES = 3;
41
41
  const MAX_STATE_ITEMS = 16;
42
+ /** The replay core counts the opcode fetches at this many addresses at most: the targets of the runUntil steps to an address. */
43
+ const MAX_COUNTED_TARGETS = 64;
44
+ /** An event other than a runUntil to an address waits this long for the next input read. */
45
+ const READ_WAIT_FRAMES = 600;
42
46
  const MAX_STATE_BYTES = 4096;
43
47
  /** A replay of a rebuild may take this many times the cycles of the recording before it stops. */
44
48
  const REBUILD_TIME_FACTOR = 2;
@@ -99,9 +103,11 @@ export interface RecordedEvent {
99
103
  /**
100
104
  * The point: the n-th read at the busiest program site, or a tick when no
101
105
  * program site has read yet. An event that follows another event directly
102
- * has { previous: true }: it runs where that one ended.
106
+ * has { previous: true }: it runs where that one ended. A runUntil to an
107
+ * address has { pc, count }: the count-th opcode fetch at its target from the
108
+ * start, which needs no read; the event is done when the point is reached.
103
109
  */
104
- key: { site: Location; addr: Location; count: number } | { tick: number } | { previous: true };
110
+ key: { site: Location; addr: Location; count: number } | { tick: number } | { previous: true } | { pc: Location; count: number };
105
111
  }
106
112
 
107
113
  export interface RecordedSite {
@@ -219,6 +225,7 @@ export function readRecordFile(path: string): RecordFile {
219
225
  checkCoreStep(step, at, fail);
220
226
  return step;
221
227
  });
228
+ if (new Set(steps.flatMap(addressTarget)).size > MAX_COUNTED_TARGETS) fail(`the runUntil steps go to more than ${MAX_COUNTED_TARGETS} addresses`);
222
229
  return {
223
230
  name: value.name as string,
224
231
  program: value.program as string,
@@ -231,6 +238,17 @@ export function readRecordFile(path: string): RecordFile {
231
238
  };
232
239
  }
233
240
 
241
+ /** The target of a runUntil step to an address, as a list of none or one. */
242
+ function addressTarget(step: ActionStep | RestoreAction): Location[] {
243
+ return "runUntil" in step && step.runUntil.target.kind === "address" ? [step.runUntil.target.address] : [];
244
+ }
245
+
246
+ /** Starts the counts of the replay core at the addresses. */
247
+ async function countAt(core: C64RunSession, addresses: number[]): Promise<void> {
248
+ const unique = [...new Set(addresses)];
249
+ if (unique.length > 0) await core.command(`count-pc ${unique.map(hex).join(",")}`);
250
+ }
251
+
234
252
  /** What the replay core cannot do of a step that is right for VICE: it has the C64 alone, no raster wait and no conditions. */
235
253
  function checkCoreStep(step: ActionStep, at: string, fail: (message: string) => never): void {
236
254
  if ("write" in step && step.write.space !== "c64") fail(`${at}: a recording has the C64 alone, not ${step.write.space}`);
@@ -369,8 +387,12 @@ function busiestSite(answer: string): { site: number; addr: number; count: numbe
369
387
  * Runs to the point of an event. `map` moves a site to the rebuild. "halted"
370
388
  * when a sample stop came first, "not-reached" when the point did not come before `until`.
371
389
  */
372
- async function runToKey(core: C64RunSession, key: RecordedEvent["key"], until: number, map: Map<number, number>, skipped: number): Promise<"reached" | "not-reached" | "halted"> {
390
+ async function runToKey(core: C64RunSession, key: RecordedEvent["key"], until: number, map: Map<number, number>, skipped: number, at: SideAddresses): Promise<"reached" | "not-reached" | "halted"> {
373
391
  if ("previous" in key) return (await core.status("status")).word === "halted" ? "halted" : "reached";
392
+ if ("pc" in key) {
393
+ const status = await core.status(`run-pc ${hex(at.code(key.pc))} ${until} ${key.count}`);
394
+ return status.word === "halted" ? "halted" : status.word === "reached" ? "reached" : "not-reached";
395
+ }
374
396
  if ("tick" in key) {
375
397
  const status = await core.status(`run ${key.tick + skipped}`);
376
398
  return status.word === "halted" ? "halted" : "reached";
@@ -474,6 +496,7 @@ export async function record(
474
496
  await core.init();
475
497
  await core.command(`inputs ${inputsArgument(file.inputs)}`);
476
498
  await core.command(`record ${reads}`);
499
+ await countAt(core, file.steps.flatMap(addressTarget).map(at.code));
477
500
  await startProgram(core, prg, file.load ?? false);
478
501
  // From READY on: the start of the C64 itself is never in the map.
479
502
  await core.command(COVERAGE_COMMANDS.get(file.coverage) ?? `coverage on-pc ${hex(parseC64Address(file.coverage))}`);
@@ -485,13 +508,25 @@ export async function record(
485
508
  // replay. An event right after another event runs where that one ended.
486
509
  const runEvent = async (action: ActionStep | RestoreAction, step?: number): Promise<string | undefined> => {
487
510
  const tick = (await core.status("status")).tick;
511
+ if ("runUntil" in action && action.runUntil.target.kind === "address") {
512
+ // The next opcode fetch at the target: its count from the start is the point, on each replay.
513
+ const { address } = action.runUntil.target;
514
+ const pc = hex(at.code(address));
515
+ const count = Number(/count=(\d+)/.exec(await core.command(`hits ${pc}`))![1]) + 1;
516
+ const reached = await core.status(`run-pc ${pc} ${tick + action.runUntil.timeoutFrames * PAL_FRAME_CYCLES} ${count}`);
517
+ if (reached.word !== "reached") return `the program did not reach ${address} within ${action.runUntil.timeoutFrames} frames`;
518
+ events.push({ ...(step === undefined ? {} : { step }), action, key: { pc: address, count } });
519
+ return undefined;
520
+ }
488
521
  const busiest = afterEvent ? undefined : busiestSite(await core.command("sites"));
489
522
  const key: RecordedEvent["key"] = afterEvent
490
523
  ? { previous: true }
491
524
  : busiest === undefined
492
525
  ? { tick: tick + 1 }
493
526
  : { site: formatC64Address(busiest.site), addr: formatC64Address(busiest.addr), count: busiest.count + 1 };
494
- if ((await runToKey(core, key, tick + 600 * PAL_FRAME_CYCLES, new Map(), 0)) !== "reached") return "the program did not read its input again within 600 frames";
527
+ if ((await runToKey(core, key, tick + READ_WAIT_FRAMES * PAL_FRAME_CYCLES, new Map(), 0, at)) !== "reached") {
528
+ 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`;
529
+ }
495
530
  events.push({ ...(step === undefined ? {} : { step }), action, key });
496
531
  return doAction(core, action, at);
497
532
  };
@@ -640,6 +675,7 @@ export async function replaySide(
640
675
  // The samples hold the state, then the pinned items.
641
676
  await core.command(`sample ${hex(at.code(options.compare.checkpoint))} ${samples} ${rangesArgument([...options.compare.state, ...pinned], at)}${stop > 0 ? ` ${stop}` : ""}`);
642
677
  }
678
+ await countAt(core, recording.events.flatMap((event) => ("pc" in event.key ? [at.code(event.key.pc)] : [])));
643
679
  await startProgram(core, prg, recording.load);
644
680
  let limit = original ? recording.ticks : recording.ticks * REBUILD_TIME_FACTOR;
645
681
  let problem: string | undefined;
@@ -658,13 +694,14 @@ export async function replaySide(
658
694
  }
659
695
  for (const event of problem === undefined ? recording.events : []) {
660
696
  const what = event.step === undefined ? "the RESTORE of the play" : "step " + event.step;
661
- const point = await runToKey(core, event.key, limit, map, skipped);
697
+ const point = await runToKey(core, event.key, limit, map, skipped, at);
662
698
  if (point === "halted") break;
663
699
  if (point === "not-reached") {
664
700
  problem = "the program did not come to the point of " + what;
665
701
  break;
666
702
  }
667
- problem = await doAction(core, event.action, at);
703
+ // At the point of a runUntil to an address, its target is reached.
704
+ if (!("pc" in event.key)) problem = await doAction(core, event.action, at);
668
705
  if (problem !== undefined) {
669
706
  problem = what + ": " + problem;
670
707
  break;
@@ -195,7 +195,7 @@ Traps:
195
195
 
196
196
  - `captured`: true when the CPU got to `--until`. `pc` is that address.
197
197
  - `files`: each file that the command wrote, as `{out, bytes, sha256}`. `removed` names the segment files of an earlier capture that the new `image.json` does not list.
198
- - `segments` and `excluded`: the ranges of the segment files, and the ranges that `--exclude` removed.
198
+ - `segments` and `excluded`: the ranges of the segment files, and the ranges that `--exclude` removed. `loaded: true` marks a segment with the bytes that the program loaded.
199
199
  - `stages`: the count of stages.
200
200
  - `differsFromReset`: the count of bytes that are not as a clean C64 has them at READY.
201
201
 
@@ -214,6 +214,8 @@ A segment is a block that a stage wrote, also a small block. These blocks are no
214
214
 
215
215
  The block with the capture entry is always a segment. Segments do not overlap.
216
216
 
217
+ If no stage wrote the capture entry, the program runs as it loaded. Then the range of the PRG is a segment with `loaded: true`. The blocks that touch this range are in the same segment. An example is a memory dump that starts with `SYS`.
218
+
217
219
  A capture into a folder with an earlier capture removes only the segment files that the new `image.json` does not list. It keeps all other files.
218
220
 
219
221
  On `PASS`, `hint` tells you to disassemble the code at `pc`, and then to put `<out>/image.json` into the project knowledge.
@@ -221,7 +223,7 @@ On `PASS`, `hint` tells you to disassemble the code at `pc`, and then to put `<o
221
223
  Traps:
222
224
 
223
225
  - The capture stops at the first arrival at `--until` after the steps. To capture a later arrival, add a `runUntil` step to an address after the first arrival.
224
- - `captured: false`: the program did not get to `--until` in `--timeout-frames`. The reason tells where it stopped. Find a better address, or give more frames. If it stopped in a key wait, give `--steps` with a `type` step.
226
+ - `captured: false`: the program did not get to `--until` in `--timeout-frames`. The reason tells where it stopped. Find a better address, or give more frames. If it stopped in a key wait, give `--steps` with a `type` step. If the CPU got to `--until` in a step, the reason names that step.
225
227
 
226
228
  ### `loads <program>`
227
229
 
@@ -107,9 +107,16 @@ export const FIRST_SEGMENT_ADDRESS = 0x0400;
107
107
  * a segment. A block that an intermediate stage wrote inside a leftover, for
108
108
  * example a variable of the loader, is a leftover too. The filter comes before
109
109
  * the join: a join first would drop the program with a leftover. `writtenBy` is
110
- * the last stage that wrote into the range.
110
+ * the last stage that wrote into the range. When no written block holds the
111
+ * entry, the code there is as the program loaded it: `loaded`, the range of
112
+ * the PRG, is then a segment too (`loaded: true`), joined with the blocks that
113
+ * it overlaps or touches.
111
114
  */
112
- export function captureSegments(stages: ReadonlyArray<{ entry: number; wrote: readonly AddressRange[] }>, entry: number): Array<AddressRange & { writtenBy: number }> {
115
+ export function captureSegments(
116
+ stages: ReadonlyArray<{ entry: number; wrote: readonly AddressRange[] }>,
117
+ entry: number,
118
+ loaded?: AddressRange,
119
+ ): Array<AddressRange & ({ writtenBy: number } | { loaded: true })> {
113
120
  const last = stages.length - 1;
114
121
  const replaced = (from: number, address: number) => stages.slice(from).some((stage) => inRanges(stage.wrote, address));
115
122
  const leftover = (block: AddressRange, writer: number) =>
@@ -129,7 +136,15 @@ export function captureSegments(stages: ReadonlyArray<{ entry: number; wrote: re
129
136
  previous.writtenBy = Math.max(previous.writtenBy, block.writtenBy);
130
137
  } else segments.push({ ...block });
131
138
  }
132
- return segments;
139
+ if (loaded === undefined || !contains(loaded, entry) || segments.some((segment) => contains(segment, entry))) return segments;
140
+ const joined = { start: loaded.start, end: loaded.end, loaded: true as const };
141
+ const apart = segments.filter((segment) => {
142
+ if (segment.end + 1 < joined.start || segment.start > joined.end + 1) return true;
143
+ joined.start = Math.min(joined.start, segment.start);
144
+ joined.end = Math.max(joined.end, segment.end);
145
+ return false;
146
+ });
147
+ return [...apart, joined].sort((a, b) => a.start - b.start);
133
148
  }
134
149
 
135
150
  /** The segments without the bytes of `holes`: a segment that a hole cuts gives its parts, each with the fields of the segment. */
@@ -197,6 +197,8 @@ interface Followed {
197
197
  failed?: string;
198
198
  /** What stopped the CPU before the frames ran: a JAM or a point of the program. */
199
199
  halted?: { stopReason: string; pc: number };
200
+ /** The first step (1 = the first) in which the CPU executed `until`, before the run waited for it. */
201
+ untilRan?: number;
200
202
  }
201
203
 
202
204
  type RunUntilStep = Extract<ActionStep, { runUntil: unknown }>;
@@ -250,9 +252,16 @@ async function follow(
250
252
  const atTarget = (pc: number) => stopAt !== undefined && pc === stopAt;
251
253
  // The current stage: its memory map since it started, chunk by chunk, its own code, and the written code it calls.
252
254
  let stage = { map: new Uint8Array(0x10000), own: new Set<number>(), called: [] as AddressRange[] };
255
+ // A step that runs frames can pass until: the run then waits for it in vain.
256
+ let running = 0;
257
+ let untilRan: number | undefined;
258
+ const noteUntil = (map: Uint8Array) => {
259
+ if (options.until !== undefined && running > 0 && untilRan === undefined && (map[options.until]! & EXECUTE) !== 0) untilRan = running;
260
+ };
253
261
  const startStage = async (next: number, last: Uint8Array) => {
254
262
  mergeMaps(stage.map, last);
255
263
  await markIoRam(stage.map);
264
+ noteUntil(stage.map);
256
265
  found.push({ entry, firstFrame, frames: total - firstFrame, wrote: stageWrote(stage.map), next });
257
266
  entry = next;
258
267
  firstFrame = total;
@@ -428,6 +437,7 @@ async function follow(
428
437
  };
429
438
  // The steps run first and in the tracked time: a frames step and a runUntil step to an address. The others act between two chunks.
430
439
  for (const [index, step] of options.steps.entries()) {
440
+ running = index + 1;
431
441
  if ("frames" in step) await track(step.frames);
432
442
  else if (trackedRunUntil(step)) {
433
443
  if (!(await trackTo(knowledgeAt()(step.runUntil.target.address), step.runUntil.timeoutFrames))) {
@@ -436,7 +446,13 @@ async function follow(
436
446
  return { stages: found, frames: total, reached: false, failed: `Step ${index + 1} did not reach its target in ${step.runUntil.timeoutFrames} frames. It is at ${formatC64Address(pc)}.${why}` };
437
447
  }
438
448
  } else await runActionStep(client, step, knowledgeAt());
449
+ if (options.until !== undefined && untilRan === undefined) {
450
+ const now = Uint8Array.from(stage.map);
451
+ mergeMaps(now, await readCoverage(client));
452
+ noteUntil(now);
453
+ }
439
454
  }
455
+ running = 0;
440
456
  const left = Math.max(0, options.frames - total);
441
457
  let reached = false;
442
458
  if (options.until === undefined) await track(left);
@@ -445,7 +461,7 @@ async function follow(
445
461
  mergeMaps(stage.map, await readCoverage(client));
446
462
  await markIoRam(stage.map);
447
463
  found.push({ entry, firstFrame, frames: total - firstFrame, wrote: stageWrote(stage.map) });
448
- return { stages: found, frames: total, reached, ...(halted === undefined ? {} : { halted }) };
464
+ return { stages: found, frames: total, reached, ...(halted === undefined ? {} : { halted }), ...(untilRan === undefined ? {} : { untilRan }) };
449
465
  }
450
466
 
451
467
  const showRange = (range: { start: number; end: number }) => ({ start: formatC64Address(range.start), end: formatC64Address(range.end) });
@@ -490,6 +506,11 @@ async function stages(program: string, options: { frames: number; entry?: number
490
506
  }
491
507
  }
492
508
 
509
+ /** Why a capture can wait for --until in vain: a step ran over it. */
510
+ function passedInStep(until: number, step: number): string {
511
+ return `The CPU executed ${formatC64Address(until)} in step ${step}, before the wait for --until started. A press step runs frames. Make the steps stop before the program gets to that address, or give an --until address that the program gets to later.`;
512
+ }
513
+
493
514
  async function capture(
494
515
  program: string,
495
516
  options: { until: number; out: string; range?: AddressRange; exclude: AddressRange[]; timeoutFrames: number; entry?: number; steps: ActionStep[]; minStage: number },
@@ -504,7 +525,7 @@ async function capture(
504
525
  return {
505
526
  output: {
506
527
  captured: false,
507
- reason: `The program did not get to ${formatC64Address(options.until)} in ${options.timeoutFrames} frames. It is at ${formatC64Address(registers.pc)}.${followed.halted === undefined ? "" : ` ${stoppedEarly(followed.halted.stopReason, followed.halted.pc, followed.frames, options.timeoutFrames)}`}`,
528
+ reason: `The program did not get to ${formatC64Address(options.until)} in ${options.timeoutFrames} frames. It is at ${formatC64Address(registers.pc)}.${followed.halted === undefined ? "" : ` ${stoppedEarly(followed.halted.stopReason, followed.halted.pc, followed.frames, options.timeoutFrames)}`}${followed.untilRan === undefined ? "" : ` ${passedInStep(options.until, followed.untilRan)}`}`,
508
529
  ...(followed.halted === undefined ? {} : { stopReason: followed.halted.stopReason }),
509
530
  stages: showStages(followed.stages),
510
531
  },
@@ -515,7 +536,8 @@ async function capture(
515
536
  const memory = await readRam(client, 0x0000, 0x10000);
516
537
  const state = await machineState(client);
517
538
  // The segments: what the stages wrote, without loader leftovers, with no overlap.
518
- const found = options.range !== undefined ? [options.range] : captureSegments(followed.stages, registers.pc);
539
+ const load = bytes[0]! | (bytes[1]! << 8);
540
+ const found = options.range !== undefined ? [options.range] : captureSegments(followed.stages, registers.pc, { start: load, end: Math.min(0xffff, load + bytes.length - 3) });
519
541
  const segments = withoutRanges(found, options.exclude);
520
542
  const file = (path: string) => `${options.out}/${path}`;
521
543
  const written: Written[] = [];
@@ -533,7 +555,7 @@ async function capture(
533
555
  `${JSON.stringify(
534
556
  {
535
557
  entry: formatC64Address(registers.pc),
536
- segments: segments.map((segment, index) => ({ ...showRange(segment), ...("writtenBy" in segment ? { writtenBy: segment.writtenBy } : {}), file: files[index] })),
558
+ segments: segments.map((segment, index) => ({ ...showRange(segment), ...("writtenBy" in segment ? { writtenBy: segment.writtenBy } : {}), ...("loaded" in segment ? { loaded: true } : {}), file: files[index] })),
537
559
  ...(options.exclude.length === 0 ? {} : { excluded: options.exclude.map(showRange) }),
538
560
  vectors,
539
561
  stages: showStages(followed.stages),
@@ -556,7 +578,7 @@ async function capture(
556
578
  out: options.out,
557
579
  files: written,
558
580
  ...(removed.length === 0 ? {} : { removed }),
559
- segments: segments.map(showRange),
581
+ segments: segments.map((segment) => ({ ...showRange(segment), ...("loaded" in segment ? { loaded: true } : {}) })),
560
582
  ...(options.exclude.length === 0 ? {} : { excluded: options.exclude.map(showRange) }),
561
583
  stages: followed.stages.length,
562
584
  differsFromReset: entry.differsFromReset,
@@ -176,7 +176,7 @@ export const c64CpuHistory = defineTool({
176
176
  },
177
177
  });
178
178
 
179
- /** The hits that a trace result gives inline; out gives all of them. */
179
+ /** The hits that a trace result gives inline; out gives all of them in the file, and none inline. */
180
180
  const TRACE_LISTED = 200;
181
181
 
182
182
  export const c64Trace = defineTool({
@@ -192,7 +192,7 @@ export const c64Trace = defineTool({
192
192
  "A read or write hit also gives the address that the instruction used, and value, the byte that it read or wrote. " +
193
193
  "At $D000-$DFFF only a load or a store gives value: a read after the access can give another byte. " +
194
194
  `The trace ends after frames frames (1 to ${MAX_TRACE_FRAMES}), at maxHits hits (at most ${MAX_TRACE_HITS}), or at a breakpoint, a watchpoint or a JAM. ` +
195
- `The result lists the first ${TRACE_LISTED} hits. With out, it writes all hits as JSON lines to that project file. ` +
195
+ `The result lists the first ${TRACE_LISTED} hits. With out, it writes all hits as JSON lines to that project file, and the result gives no hits. ` +
196
196
  "Each hit stops the machine for a short time. Thus a point with many hits in each frame makes the trace slow. Use a small range and a maxHits. " +
197
197
  "The machine is stopped after the trace.",
198
198
  inputSchema: z
@@ -209,23 +209,25 @@ export const c64Trace = defineTool({
209
209
  frames: z.number().int().min(0),
210
210
  pc: AddressOutput,
211
211
  count: z.number().int().min(0),
212
- hits: z.array(
213
- z.object({
214
- point: z.number().int().min(0),
215
- pc: AddressOutput,
216
- bytes: HexData,
217
- text: z.string(),
218
- a: Byte,
219
- x: Byte,
220
- y: Byte,
221
- sp: Byte,
222
- frame: z.number().int().min(0),
223
- rasterLine: z.number().int().min(0),
224
- rasterCycle: z.number().int().min(0),
225
- address: AddressOutput.optional(),
226
- value: Byte.optional(),
227
- }),
228
- ),
212
+ hits: z
213
+ .array(
214
+ z.object({
215
+ point: z.number().int().min(0),
216
+ pc: AddressOutput,
217
+ bytes: HexData,
218
+ text: z.string(),
219
+ a: Byte,
220
+ x: Byte,
221
+ y: Byte,
222
+ sp: Byte,
223
+ frame: z.number().int().min(0),
224
+ rasterLine: z.number().int().min(0),
225
+ rasterCycle: z.number().int().min(0),
226
+ address: AddressOutput.optional(),
227
+ value: Byte.optional(),
228
+ }),
229
+ )
230
+ .optional(),
229
231
  ...WrittenOutput,
230
232
  }),
231
233
  readOnly: false,
@@ -236,8 +238,8 @@ export const c64Trace = defineTool({
236
238
  if (ranges.some((point) => point.end < point.start)) throw new WireFailure("invalid-input", "A point end must not be before its start.");
237
239
  const traced = await session.trace({ points: ranges, ...request });
238
240
  const shown = traced.hits.map(({ address, ...hit }) => ({ ...hit, pc: formatC64Address(hit.pc), ...(address === undefined ? {} : { address: formatC64Address(address) }) }));
239
- const summary = { end: traced.end, frames: traced.frames, pc: formatC64Address(traced.pc), count: traced.hits.length, hits: shown.slice(0, TRACE_LISTED) };
240
- if (out === undefined) return summary;
241
+ const summary = { end: traced.end, frames: traced.frames, pc: formatC64Address(traced.pc), count: traced.hits.length };
242
+ if (out === undefined) return { ...summary, hits: shown.slice(0, TRACE_LISTED) };
241
243
  return { ...summary, ...writeOut(out, linesText(shown.map((hit) => JSON.stringify(hit))), project) };
242
244
  },
243
245
  });
@@ -186,7 +186,7 @@ export const c64Disassemble = defineTool({
186
186
  description:
187
187
  `Disassemble count instructions (1 to ${MAX_DISASSEMBLE}) from an address, as the bytes are in the live machine now. ` +
188
188
  "Use it to read code that a program changed or unpacked at run time. It includes the undocumented opcodes. " +
189
- `With out, it disassembles up to ${MAX_DISASSEMBLE_OUT} instructions, or to $ffff, and writes them as a listing to that project file. The result then gives the file in place of the instructions. ` +
189
+ `With out, it disassembles up to ${MAX_DISASSEMBLE_OUT} instructions, or to $ffff, and writes them as a listing to that project file. The result then gives the file in place of the instructions. A file name that ends in .json gets a JSON list of the instructions, as the result without out gives them. ` +
190
190
  "This does not change the run state of the machine.",
191
191
  inputSchema: z
192
192
  .object({
@@ -208,24 +208,27 @@ export const c64Disassemble = defineTool({
208
208
  const result = await session.disassemble(request);
209
209
  return { instructions: result.instructions.map((instruction) => ({ ...instruction, address: formatC64Address(instruction.address) })) };
210
210
  }
211
- const lines: string[] = [];
211
+ const instructions: Array<{ address: string; bytes: string; text: string }> = [];
212
212
  let address = request.address;
213
213
  // Ends at count, or where the disassembly would wrap past $ffff.
214
214
  let wrapped = false;
215
- while (!wrapped && lines.length < request.count && address <= 0xffff) {
216
- const { instructions } = await session.disassemble({ ...request, address, count: Math.min(MAX_DISASSEMBLE, request.count - lines.length) });
217
- if (instructions.length === 0) break;
218
- for (const instruction of instructions) {
219
- if (lines.length === request.count) break;
215
+ while (!wrapped && instructions.length < request.count && address <= 0xffff) {
216
+ const part = await session.disassemble({ ...request, address, count: Math.min(MAX_DISASSEMBLE, request.count - instructions.length) });
217
+ if (part.instructions.length === 0) break;
218
+ for (const instruction of part.instructions) {
219
+ if (instructions.length === request.count) break;
220
220
  if (instruction.address < address) {
221
221
  wrapped = true;
222
222
  break;
223
223
  }
224
- lines.push(`${formatC64Address(instruction.address)} ${spaced(instruction.bytes).padEnd(9)} ${instruction.text}`);
224
+ instructions.push({ ...instruction, address: formatC64Address(instruction.address) });
225
225
  address = instruction.address + instruction.bytes.length / 2;
226
226
  }
227
227
  }
228
- return { count: lines.length, ...writeOut(out, linesText(lines), project) };
228
+ const text = out.toLowerCase().endsWith(".json")
229
+ ? `${JSON.stringify(instructions, null, 1)}\n`
230
+ : linesText(instructions.map((instruction) => `${instruction.address} ${spaced(instruction.bytes).padEnd(9)} ${instruction.text}`));
231
+ return { count: instructions.length, ...writeOut(out, text, project) };
229
232
  },
230
233
  });
231
234
 
@@ -12,7 +12,7 @@ import type { SupervisedProcess } from "./processes.ts";
12
12
  import type { ToolContext } from "./run.ts";
13
13
 
14
14
  /** The command protocol that this module speaks; c64run --version and version name it. */
15
- export const C64RUN_PROTOCOL = 5;
15
+ export const C64RUN_PROTOCOL = 6;
16
16
 
17
17
  /** CPU cycles in one PAL frame: 312 lines of 63 cycles. */
18
18
  export const PAL_FRAME_CYCLES = 19_656;
package/tools/c64run.c CHANGED
@@ -27,7 +27,7 @@
27
27
  #include "systems/c1541.h"
28
28
  #include "systems/c64.h"
29
29
 
30
- #define C64RUN_PROTOCOL 5
30
+ #define C64RUN_PROTOCOL 6
31
31
  // The key code of matrix place 0 (row 0, column 0); place n has code 0x80 + n.
32
32
  #define C64RUN_KEY_PLACE 0x80
33
33
  #ifndef CHIPS_COMMIT
@@ -226,6 +226,24 @@ static void sample(void) {
226
226
  if (sample_stop && samples >= sample_stop) halted = 1;
227
227
  }
228
228
 
229
+ // ---- Counts: the opcode fetches at some pcs, from "count-pc" on ----
230
+
231
+ #define MAX_COUNTED 64
232
+ // 0: the pc is not counted; else the index of its count + 1.
233
+ static uint8_t counted_at[0x10000];
234
+ static uint16_t counted_pc[MAX_COUNTED];
235
+ static uint64_t counted[MAX_COUNTED];
236
+ static int counted_pcs;
237
+
238
+ static void clear_counts(void) {
239
+ for (int i = 0; i < counted_pcs; i++) counted_at[counted_pc[i]] = 0;
240
+ counted_pcs = 0;
241
+ }
242
+
243
+ static uint64_t count_of(uint16_t pc) {
244
+ return counted_at[pc] ? counted[counted_at[pc] - 1] : 0;
245
+ }
246
+
229
247
  // ---- The tick ----
230
248
 
231
249
  static void tick(void) {
@@ -240,6 +258,7 @@ static void tick(void) {
240
258
  last_sync_pc = addr;
241
259
  if (sample_file && addr == sample_pc && decoded) sample();
242
260
  if (coverage_armed_pc && addr == coverage_pc && decoded) { coverage_armed_pc = 0; coverage_start(addr); }
261
+ if (counted_at[addr] && decoded) counted[counted_at[addr] - 1]++;
243
262
  }
244
263
  if (read && !sync && decoded && sys.io_mapped && (addr & 0xFF0F) == 0xDC00) {
245
264
  // chips gives port A of CIA 1 only joystick 2. A key also pulls its line of port A
@@ -444,6 +463,7 @@ int main(int argc, char** argv) {
444
463
  halted = 0;
445
464
  sample_stop = 0;
446
465
  maps = 0;
466
+ clear_counts();
447
467
  coverage_reset();
448
468
  if (pin_file) { fclose(pin_file); pin_file = NULL; }
449
469
  if (record_file) { fclose(record_file); record_file = NULL; }
@@ -493,6 +513,7 @@ int main(int argc, char** argv) {
493
513
  last_sync_pc = pc;
494
514
  // The prefetch is the opcode fetch at pc: it does not pass through tick.
495
515
  if (coverage_armed_pc && pc == coverage_pc) { coverage_armed_pc = 0; coverage_start(pc); }
516
+ if (counted_at[pc]) counted[counted_at[pc] - 1]++;
496
517
  if (coverage_on) cover(pc, 1, 1);
497
518
  status("ok");
498
519
  } else if (!strcmp(cmd, "run")) {
@@ -505,12 +526,39 @@ int main(int argc, char** argv) {
505
526
  do tick(); while (!(pins & M6502_SYNC) && !halted);
506
527
  status("ok");
507
528
  } else if (!strcmp(cmd, "run-pc")) {
508
- // run-pc <pc hex> <until tick>: run to the next opcode fetch at pc
529
+ // run-pc <pc hex> <until tick> [<n>]: run to the next opcode fetch at pc; with n, run
530
+ // until the count of pc ("count-pc") is n
509
531
  unsigned pc;
510
- const unsigned long long until = strtoull(a2, NULL, 10);
511
- if (sscanf(a1, "%x", &pc) != 1) { printf("err run-pc: give a pc and a tick\n"); continue; }
532
+ unsigned long long until, n;
533
+ const int fields = sscanf(line, "%*s %x %llu %llu", &pc, &until, &n);
534
+ if (fields < 2 || pc > 0xFFFF) { printf("err run-pc: give a pc and a tick\n"); continue; }
535
+ if (fields == 3) {
536
+ if (!counted_at[pc]) { printf("err run-pc: give count-pc with %04x first\n", pc); continue; }
537
+ while (count_of((uint16_t)pc) < n && ticks < until && !halted) tick();
538
+ status(count_of((uint16_t)pc) >= n ? "ok reached" : "ok not-reached");
539
+ continue;
540
+ }
512
541
  do tick(); while (!((pins & M6502_SYNC) && M6502_GET_ADDR(pins) == pc) && ticks < until && !halted);
513
542
  status((pins & M6502_SYNC) && M6502_GET_ADDR(pins) == pc ? "ok reached" : "ok not-reached");
543
+ } else if (!strcmp(cmd, "count-pc")) {
544
+ // count-pc <pc hex,...> | off: count the opcode fetches at each pc from 0
545
+ clear_counts();
546
+ if (!strcmp(a1, "off")) { printf("ok counted=0\n"); continue; }
547
+ int bad = 0;
548
+ for (char* part = strtok(a1, ","); part; part = strtok(NULL, ",")) {
549
+ unsigned pc;
550
+ if (sscanf(part, "%x", &pc) != 1 || pc > 0xFFFF || counted_pcs == MAX_COUNTED) { bad = 1; break; }
551
+ if (counted_at[pc]) continue;
552
+ counted_pc[counted_pcs] = (uint16_t)pc;
553
+ counted[counted_pcs] = 0;
554
+ counted_at[pc] = (uint8_t)++counted_pcs;
555
+ }
556
+ if (bad) { clear_counts(); printf("err count-pc: give 1 to %d pcs in hex\n", MAX_COUNTED); } else printf("ok counted=%d\n", counted_pcs);
557
+ } else if (!strcmp(cmd, "hits")) {
558
+ // hits <pc hex>: the count of a pc of count-pc
559
+ unsigned pc;
560
+ if (sscanf(a1, "%x", &pc) != 1 || pc > 0xFFFF) { printf("err hits: give a pc\n"); continue; }
561
+ printf("ok count=%llu\n", (unsigned long long)count_of((uint16_t)pc));
514
562
  } else if (!strcmp(cmd, "run-reads")) {
515
563
  // run-reads <pc hex> <addr hex> <n> <until tick>: run until the site has n reads
516
564
  unsigned pc, addr;