@henols/c64-re-tools 2.6.0-rc.18 → 2.6.0-rc.19

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.18",
3
+ "version": "2.6.0-rc.19",
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",
@@ -110,7 +110,7 @@ A rebuilt program gets its source from the project knowledge. A change is a swit
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
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.
113
+ - When the behavior must stay the same as the original, replay each recording on the default build. For a source with a loader, this is `build/clean_loader.prg`, else `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
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
@@ -112,12 +112,12 @@ Writes the reference pages from the project knowledge, the source map and the pr
112
112
  The reference has these pages:
113
113
 
114
114
  - `index.md`: each file of the source, with its range, its title, the count of routines and the count of names.
115
- - `modules/<file>.md`: a call graph of the file, its data regions with their readers and writers, and an entry for each name. An entry has the comment, the callers and the table that holds the name. For a routine, it also has the calls, the jumps, the reads and the writes.
115
+ - `modules/<file>.md`: first a table of the routines of the file. Each row has the callers and the first sentence of the comment. Then the data regions with their readers and writers, and a call graph. Then an entry for each routine and each data name. An entry has the comment, the callers and the table that holds the name. For a routine, it also has the calls, the jumps, the reads and the writes. A label that only code of its own file goes to is a row in a table under its routine.
116
116
  - `tables.md`: each table of addresses, jumps and words, entry by entry, with its target. An RTS table holds each target minus 1. The page gives the target.
117
117
  - `memory-map.md`: each region in address order. Then each variable outside the program, with its comment and the routines that read it and write it. A platform name, for example a chip register, has a routine only where the source line uses that name. `(indexed)` after a routine tells that the line adds X or Y to the address. That access can also go to the addresses after it, which can have no row.
118
118
  - `graphics.md`: each `sprite`, `bitmap`, `charset` and `screen` region. The project knowledge has no graphics mode. Thus a sprite, a bitmap or a charset shows in hires and in multicolour. A charset shows 16 characters in each row. A screen shows as text.
119
119
 
120
- In a call graph, a solid arrow is a call, a thick arrow is a table entry, and a dotted arrow is a jump. A table entry goes from each routine that reads the table to each target in code. A table of data addresses gives no arrow.
120
+ In a call graph, a solid arrow is a call, and a thick arrow is a table entry. The graph does not show the jumps. A table entry goes from each routine that reads the table to each target in code. A table of data addresses gives no arrow.
121
121
 
122
122
  Errors and their actions:
123
123
 
@@ -42,10 +42,14 @@ const TABLE_TYPES: readonly RegionType[] = [...POINTER_TABLE_TYPES, "jumps", "wo
42
42
  const GRAPHICS_TYPES: readonly RegionType[] = ["sprite", "bitmap", "charset", "screen"];
43
43
  /** A list longer than this ends with the number of the rest. */
44
44
  const MAX_LISTED = 40;
45
+ /** A list of one entry of a module page is shorter: the reader scans it. */
46
+ const MAX_FACTS = 12;
45
47
  /** A call graph with more edges is not readable: then it shows the calls only, and at most this many. */
46
- const MAX_EDGES = 60;
48
+ const MAX_EDGES = 30;
47
49
  /** A name outside the image covers the addresses that references use up to the next name, at most this many. */
48
50
  const MAX_SPAN = 256;
51
+ /** A source line that uses an ACME macro: +name, after a label or not. An anonymous label (+ alone) is no use. */
52
+ const MACRO_USE = /^\s*(?:[\w.]+\s+)?\+[A-Za-z_]/;
49
53
  /** The kinds of a reference that reads a table: the decompiler gives an indexed read (lda table,x) as "reference". */
50
54
  const TABLE_READS: readonly string[] = ["read", "reference", "pointer"];
51
55
 
@@ -137,7 +141,13 @@ export function buildReference(input: ReferenceInput): { files: ReferenceFile[];
137
141
  const shown = named.base === address ? named.name : `${named.name}+${address - named.base}`;
138
142
  return entries.has(named.name) ? entryOfName(page, named.name, shown) : codeOfName(page, named.name).replace(`\`${named.name}\``, `\`${shown}\``);
139
143
  };
140
- const capped = (items: string[]) => (items.length <= MAX_LISTED ? items.join(", ") : `${items.slice(0, MAX_LISTED).join(", ")} and ${items.length - MAX_LISTED} more`);
144
+ /** An address as the name that holds it, without the offset: a list names actor_queue once, not actor_queue+3 and actor_queue+6. */
145
+ const baseTarget = (page: string, address: number) => {
146
+ const named = nameFor(address);
147
+ if (named === undefined) return codeOfAddress(page, address);
148
+ return entries.has(named.name) ? entryOfName(page, named.name, named.name) : codeOfName(page, named.name);
149
+ };
150
+ const capped = (items: string[], limit = MAX_LISTED) => (items.length <= limit ? items.join(", ") : `${items.slice(0, limit).join(", ")} and ${items.length - limit} more`);
141
151
  /**
142
152
  * The references that use the data at their target. An access to the I/O area inside the image is the
143
153
  * register, as the source writes it: it uses no data of the RAM under it, unless the knowledge names that
@@ -148,32 +158,35 @@ export function buildReference(input: ReferenceInput): { files: ReferenceFile[];
148
158
  /**
149
159
  * How the source line of a reference uses a platform name, as the source writes it: "named", "indexed"
150
160
  * (name,x or name,y: the index can reach the registers after it), or undefined when the line does not
151
- * name it, for example lda $d000,x with the character ROM in. "named" when the source text is not there.
161
+ * name it, for example lda $d000,x with the character ROM in. "named" when the source text is not there,
162
+ * and for a macro use (+name): each byte of the macro maps to that line, which does not show its body.
152
163
  */
153
- const platformUse = (reference: ReferenceRow, name: string): "named" | "indexed" | undefined => {
164
+ const platformUse = (reference: ReferenceRow, use: RegExp): "named" | "indexed" | undefined => {
154
165
  const line = map.lineOf(reference.from);
155
166
  const text = line === undefined ? undefined : map.textOf?.(line);
156
- if (text === undefined) return "named";
157
- const use = new RegExp(`(?<![\\w.])${name}(?!\\w)([^,)]*,\\s*[xXyY]\\b)?`).exec(text);
158
- return use === null ? undefined : use[1] === undefined ? "named" : "indexed";
167
+ if (text === undefined || MACRO_USE.test(text)) return "named";
168
+ const found = use.exec(text);
169
+ return found === null ? undefined : found[1] === undefined ? "named" : "indexed";
159
170
  };
160
- /** The routines that read or write a range, each linked to its entry. `platform` is the platform name of the range. */
161
- const ownersOf = (page: string, start: number, end: number, kind: string, platform?: string) =>
162
- capped(
163
- [
164
- ...new Set(
165
- dataReferences
166
- .filter((reference) => reference.kind === kind && reference.to >= start && reference.to <= end)
167
- .flatMap((reference) => {
168
- const use = platform === undefined ? "named" : platformUse(reference, platform);
169
- if (use === undefined) return [];
170
- const name = ownerAt(reference.from)?.name ?? hex(reference.from);
171
- const shown = entries.has(name) ? entryOfName(page, name, name) : `\`${name}\``;
172
- return [use === "indexed" ? `${shown} (indexed)` : shown];
173
- }),
174
- ),
175
- ],
171
+ /** The routines that read or write a range, each once and linked to its entry. `platform` is the platform name of the range. */
172
+ const ownersOf = (page: string, start: number, end: number, kind: string, platform?: string) => {
173
+ const use = platform === undefined ? undefined : new RegExp(`(?<![\\w.])${platform}(?!\\w)([^,)]*,\\s*[xXyY]\\b)?`);
174
+ // A routine with an indexed use and a direct use shows once, as indexed.
175
+ const owners = new Map<string, boolean>();
176
+ for (const reference of dataReferences) {
177
+ if (reference.kind !== kind || reference.to < start || reference.to > end) continue;
178
+ const how = use === undefined ? "named" : platformUse(reference, use);
179
+ if (how === undefined) continue;
180
+ const name = ownerAt(reference.from)?.name ?? hex(reference.from);
181
+ owners.set(name, (owners.get(name) ?? false) || how === "indexed");
182
+ }
183
+ return capped(
184
+ [...owners].map(([name, indexed]) => {
185
+ const shown = entries.has(name) ? entryOfName(page, name, name) : `\`${name}\``;
186
+ return indexed ? `${shown} (indexed)` : shown;
187
+ }),
176
188
  );
189
+ };
177
190
 
178
191
  // --- The routine graph ----------------------------------------------------
179
192
  const tableReferences: GraphReference[] = [];
@@ -216,6 +229,12 @@ export function buildReference(input: ReferenceInput): { files: ReferenceFile[];
216
229
  return named === undefined ? codeOfAddress(page, from) : `${named} ${codeOfAddress(page, from)}`;
217
230
  };
218
231
  const edges = routineEdges(heads, boundaries, graphReferences);
232
+ /** The routine that holds an address, linked to its entry; the address when no routine holds it. */
233
+ const ownerLink = (page: string, from: number) => {
234
+ const owner = ownerAt(from);
235
+ if (owner === undefined) return codeOfAddress(page, from);
236
+ return entries.has(owner.name) ? entryOfName(page, owner.name, owner.name) : codeOfName(page, owner.name);
237
+ };
219
238
 
220
239
  // --- File ranges ----------------------------------------------------------
221
240
  const fileRanges = new Map<string, { start: number; end: number }>();
@@ -240,7 +259,7 @@ export function buildReference(input: ReferenceInput): { files: ReferenceFile[];
240
259
  .map((comment) => comment.text.replace(/\s*\r?\n\s*/g, " ").trim());
241
260
  const incoming = (entry: Entry) => dataReferences.filter((reference) => reference.to >= entry.address && reference.to <= entry.spanEnd);
242
261
  const outgoing = (head: RoutineHead) => input.references.filter((reference) => ownerAt(reference.from)?.address === head.address);
243
- const entryText = (page: string, entry: Entry): string[] => {
262
+ const entryText = (page: string, entry: Entry, labels: readonly Entry[]): string[] => {
244
263
  const lines = ["", `<a id="${entry.name}"></a>`, `### ${codeOfName(page, entry.name)} \`${entry.spanEnd > entry.address ? range(entry.address, entry.spanEnd) : hex(entry.address)}\``, "", `*${entry.kind}*`];
245
264
  const comments = commentLines(entry.address);
246
265
  if (comments.length > 0) lines.push("", ...comments);
@@ -252,9 +271,9 @@ export function buildReference(input: ReferenceInput): { files: ReferenceFile[];
252
271
  const by = (kinds: readonly string[]) =>
253
272
  fromOthers
254
273
  .filter((reference) => kinds.includes(reference.kind) && !((reference.kind === "reference" || reference.kind === "pointer") && strong.has(reference.from)))
255
- .map((reference) => site(page, reference.from) + (reference.to === entry.address ? "" : ` (+${reference.to - entry.address})`));
274
+ .map((reference) => ownerLink(page, reference.from));
256
275
  const add = (label: string, items: string[]) => {
257
- if (items.length > 0) facts.push(`- **${label}:** ${capped([...new Set(items)])}`);
276
+ if (items.length > 0) facts.push(`- **${label}:** ${capped([...new Set(items)], MAX_FACTS)}`);
258
277
  };
259
278
  add("Called from", by(["call"]));
260
279
  add("Jumped to from", by(["jump"]));
@@ -271,7 +290,7 @@ export function buildReference(input: ReferenceInput): { files: ReferenceFile[];
271
290
  const all = outgoing(head);
272
291
  const named = new Set(all.filter((reference) => reference.kind !== "reference" && reference.kind !== "pointer").map((reference) => `${reference.from}:${reference.to}`));
273
292
  const from = all.filter((reference) => !((reference.kind === "reference" || reference.kind === "pointer") && named.has(`${reference.from}:${reference.to}`)));
274
- const to = (kinds: readonly string[]) => from.filter((reference) => kinds.includes(reference.kind) && ownerAt(reference.to)?.address !== head.address).map((reference) => target(page, reference.to));
293
+ const to = (kinds: readonly string[]) => from.filter((reference) => kinds.includes(reference.kind) && ownerAt(reference.to)?.address !== head.address).map((reference) => baseTarget(page, reference.to));
275
294
  add("Calls", to(["call"]));
276
295
  add("Jumps to", to(["jump"]));
277
296
  add("Reads", to(["read"]));
@@ -279,8 +298,17 @@ export function buildReference(input: ReferenceInput): { files: ReferenceFile[];
279
298
  add("Refers to", to(["reference", "pointer"]));
280
299
  }
281
300
  if (facts.length > 0) lines.push("", ...facts);
282
- return lines;
301
+ return [...lines, ...labelTable(page, labels)];
283
302
  };
303
+ /** The labels that only code of their own file reaches: one row each, with the anchor that links to the label. */
304
+ const labelTable = (page: string, labels: readonly Entry[]) =>
305
+ labels.length === 0
306
+ ? []
307
+ : ["", "| Label | Address | Comment |", "|---|---|---|", ...labels.map((label) => `| <a id="${label.name}"></a>${codeOfName(page, label.name)} | \`${hex(label.address)}\` | ${commentLines(label.address).join(" ").replace(/\|/g, "\\|")} |`)];
308
+ const entersAt = new Map<number, ReferenceRow[]>();
309
+ for (const reference of input.references) if (reference.kind === "call" || reference.kind === "jump") entersAt.set(reference.to, [...(entersAt.get(reference.to) ?? []), reference]);
310
+ // A pointer to code (lda #<irq_handler) is a vector: the CPU enters there from no file.
311
+ const pointedAt = new Set(input.references.filter((reference) => reference.kind === "pointer").map((reference) => reference.to));
284
312
  const tableAnchor = (table: RegionRow) => entryAt.get(table.start)?.name ?? `table_${table.start.toString(16).padStart(4, "0")}`;
285
313
  function tableLink(page: string, table: RegionRow): string {
286
314
  return `[\`${entryAt.get(table.start)?.name ?? range(table.start, table.end)}\`](${rel(page, posix.join(out, "tables.md"))}#${tableAnchor(table)})`;
@@ -300,16 +328,31 @@ export function buildReference(input: ReferenceInput): { files: ReferenceFile[];
300
328
  const own = (pieceEntries.get(file) ?? []).sort((a, b) => a.address - b.address);
301
329
  const title = titleOf(file);
302
330
  const lines = [`# ${file}${title === undefined ? "" : `: ${title}`}`, "", `Range \`${span === undefined ? "-" : range(span.start, span.end)}\`. Source: [${file}](${rel(page, map.pathOf(file))}). Index: [the reference](${rel(page, posix.join(out, "index.md"))}).`];
331
+ // A label that only code of this file enters is a row: under the routine that holds it, else in the labels of the page.
332
+ const headAt = new Set(heads.map((head) => head.address));
333
+ const fromOtherFiles = (address: number) => (entersAt.get(address) ?? []).filter((reference) => map.lineOf(reference.from)?.file !== file);
334
+ const mains = new Set(own.filter((entry) => entry.kind !== "label" || headAt.has(entry.address) || pointedAt.has(entry.address) || fromOtherFiles(entry.address).length > 0).map((entry) => entry.address));
335
+ const labelsOf = new Map<number | undefined, Entry[]>();
336
+ for (const entry of own) {
337
+ if (mains.has(entry.address)) continue;
338
+ const owner = ownerAt(entry.address)?.address;
339
+ const group = owner !== undefined && mains.has(owner) ? owner : undefined;
340
+ labelsOf.set(group, [...(labelsOf.get(group) ?? []), entry]);
341
+ }
303
342
  if (span !== undefined) {
304
343
  const inside = (address: number) => address >= span.start && address <= span.end;
305
- const ownHeads = new Set(heads.filter((head) => inside(head.address)).map((head) => head.address));
306
- let shown = edges.filter((edge) => ownHeads.has(edge.from) || ownHeads.has(edge.to));
307
- const all = shown.length;
308
- if (shown.length > MAX_EDGES) shown = shown.filter((edge) => edge.kind === "call").slice(0, MAX_EDGES);
309
- if (shown.length > 0) {
310
- lines.push("", "## Call graph", "", "A solid arrow is a call, a thick arrow a table entry, a dotted arrow a jump. Rounded nodes are in this file.");
311
- if (shown.length < all) lines.push("", `The graph shows ${shown.length} of the ${all} edges: the calls only.`);
312
- lines.push("", "```mermaid", mermaidGraph(heads, shown, ownHeads), "```");
344
+ const ownHeads = heads.filter((head) => inside(head.address));
345
+ // The overview: each routine, and each label that code of another file enters.
346
+ const starts = [...new Set([...ownHeads.map((head) => head.address), ...own.filter((entry) => mains.has(entry.address) && (entry.kind === "routine" || entry.kind === "label")).map((entry) => entry.address)])].sort((a, b) => a - b);
347
+ if (starts.length > 0) {
348
+ lines.push("", "## Routines", "", "| Routine | Address | Reached from | Summary |", "|---|---|---|---|");
349
+ for (const start of starts) {
350
+ const name = entryAt.get(start)?.name ?? ownHeads.find((head) => head.address === start)!.name;
351
+ const shown = entries.has(name) ? entryOfName(page, name, name) : codeOfName(page, name);
352
+ const callers = [...new Set([...edges.filter((edge) => edge.to === start && edge.kind !== "jump").map((edge) => edge.from), ...fromOtherFiles(start).map((reference) => reference.from)].map((from) => ownerLink(page, from)))];
353
+ const summary = /^.*?[.!?](?=\s|$)|^.*$/.exec(commentLines(start).join(" "))![0].replace(/\|/g, "\\|");
354
+ lines.push(`| ${shown} | \`${hex(start)}\` | ${capped(callers, MAX_FACTS)} | ${summary} |`);
355
+ }
313
356
  }
314
357
  const regions = input.regions.filter((region) => region.start <= span.end && region.end >= span.start && region.type !== "code");
315
358
  if (regions.length > 0) {
@@ -320,9 +363,20 @@ export function buildReference(input: ReferenceInput): { files: ReferenceFile[];
320
363
  lines.push(`| ${codeOfAddress(page, region.start)}${region.end === region.start ? "" : `-\`${hex(region.end)}\``} | ${region.type}${region.element === undefined ? "" : ` of ${region.element}`} | ${name === undefined ? "" : codeOfName(page, name.name)} | ${owners("read")} | ${owners("write")} |`);
321
364
  }
322
365
  }
366
+ // Jumps are the control flow inside a group of routines: the graph draws the calls and the table entries only.
367
+ const ownAt = new Set(ownHeads.map((head) => head.address));
368
+ const reaching = edges.filter((edge) => edge.kind !== "jump" && (ownAt.has(edge.from) || ownAt.has(edge.to)));
369
+ const shown = reaching.slice(0, MAX_EDGES);
370
+ if (shown.length > 0) {
371
+ lines.push("", "## Call graph", "", "A solid arrow is a call, a thick arrow a table entry. Rounded nodes are in this file.");
372
+ if (shown.length < reaching.length) lines.push("", `The graph shows ${shown.length} of the ${reaching.length} edges.`);
373
+ lines.push("", "```mermaid", mermaidGraph(heads, shown, ownAt), "```");
374
+ }
323
375
  }
324
- if (own.length > 0) lines.push("", "## Names");
325
- for (const entry of own) lines.push(...entryText(page, entry));
376
+ if (own.length > 0) lines.push("", "## Details");
377
+ for (const entry of own) if (mains.has(entry.address)) lines.push(...entryText(page, entry, labelsOf.get(entry.address) ?? []));
378
+ const loose = labelsOf.get(undefined) ?? [];
379
+ if (loose.length > 0) lines.push("", "## Labels", ...labelTable(page, loose));
326
380
  counts.entries += own.length;
327
381
  write(page, lines);
328
382
  }
@@ -94,7 +94,7 @@ 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 `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. |
97
+ | 10. Build and test | Build the base release into `build/`, and compare it with the original. Build the default build. For a generated source with a loader, the default build is `build/clean_loader.prg`. Else it is `build/clean.prg`. Replay each 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. |
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
 
@@ -102,7 +102,7 @@ In stage 5, make the recordings before you change the program. A recording needs
102
102
 
103
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
- - 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.
105
+ - Replay only the default build: `build/clean_loader.prg` for a source with a loader, else `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
 
@@ -22,6 +22,7 @@ import { compareBuild, mergedPrograms } from "#src/compare.ts";
22
22
  import { Refusal } from "#src/errors.ts";
23
23
  import { parseEntryState } from "#src/host-client/entry-state.ts";
24
24
  import { isRomFont, startScreenRanges, type StartScreenRow } from "#src/knowledge/read.ts";
25
+ import { LOADER_JUMP } from "#src/knowledge/start-screen.ts";
25
26
  import { romUseOfPort } from "#src/platform.ts";
26
27
  import { WireFailure } from "#src/host-client/tools.ts";
27
28
  import { pack } from "#src/native/exomizer.ts";
@@ -139,9 +140,7 @@ export function loaderLimits(plan: { cia?: CiaPlan }): string[] {
139
140
  return plan.cia.limits;
140
141
  }
141
142
 
142
- /** The label of the loader's jump to the entry, in ACME's symbol list. */
143
- export const LOADER_JUMP = "c64_source_loader_jump";
144
- export { START_SCREEN_CONTINUE, START_SCREEN_WAIT } from "#src/knowledge/start-screen.ts";
143
+ export { LOADER_JUMP, START_SCREEN_CONTINUE, START_SCREEN_WAIT } from "#src/knowledge/start-screen.ts";
145
144
  /** The file of the start screen in the generated source. */
146
145
  export const START_SCREEN_FILE = "start_screen.asm";
147
146
  /** The code of the start screen: the same for each program. loader.asm sets its values. */
@@ -218,11 +217,12 @@ const COPY_ENTRY = 7;
218
217
  const TABLE_COPIES = Math.floor((256 - 2) / COPY_ENTRY);
219
218
  /** A loader that loads into $d000 or higher would write the I/O area. */
220
219
  const LOAD_LIMIT = 0xcfff;
221
- const COPIER_PAGES = [...Array.from({ length: 15 }, (_, index) => 0xc000 + index * 0x100), ...Array.from({ length: 0x9b }, (_, index) => 0x9e00 - index * 0x100)];
222
- /** The areas where the copier can run: RAM that no ROM and no I/O hides when $01 is $34 or $35, above the screen at $0400. */
223
- const COPIER_AREAS: readonly AddressRange[] = [
224
- { start: 0x0400, end: 0x9fff },
225
- { start: 0xc000, end: 0xcfff },
220
+ /** The pages where the plain copier can start, the first one that is free: then the RAM that a ROM can hide, as copierAreas allows. */
221
+ const COPIER_PAGES = [
222
+ ...Array.from({ length: 15 }, (_, index) => 0xc000 + index * 0x100),
223
+ ...Array.from({ length: 0x9b }, (_, index) => 0x9e00 - index * 0x100),
224
+ ...Array.from({ length: 0x20 }, (_, index) => 0xa000 + index * 0x100),
225
+ ...Array.from({ length: 0x20 }, (_, index) => 0xe000 + index * 0x100),
226
226
  ];
227
227
 
228
228
  const overlaps = (a: AddressRange, b: AddressRange) => a.start <= b.end && b.start <= a.end;
@@ -566,13 +566,14 @@ export function planLoader(input: LoaderInput): LoaderPlan {
566
566
  throw new WireFailure("invalid-input", `No copy order exists: each of these copies writes over the packed bytes of another one: ${clashing.join(", ")}. Write the loader by hand.`);
567
567
  }
568
568
  const loaded = { start: LOAD, end };
569
+ const areas = copierAreas(state.port);
569
570
  const copier = COPIER_PAGES.find((page) => {
570
571
  const pages = { start: page, end: page + copierBytes - 1 };
571
- return COPIER_AREAS.some((area) => pages.start >= area.start && pages.end <= area.end) && !overlaps(pages, loaded) && plain.every((copy) => !overlaps(pages, copy.target));
572
+ return areas.some((area) => pages.start >= area.start && pages.end <= area.end) && !overlaps(pages, loaded) && plain.every((copy) => !overlaps(pages, copy.target));
572
573
  });
573
574
  if (copier === undefined) {
574
575
  const count = copierPages === 2 ? "two" : "three";
575
- throw new WireFailure("invalid-input", `No ${count} free pages exist for the copier in $0400-$9fff or $c000-$cfff outside the loader (${show(loaded)}) and the targets: ${plain.map((copy) => show(copy.target)).join(", ")}.`);
576
+ throw new WireFailure("invalid-input", `No ${count} free pages exist for the copier in ${areas.map(show).join(" or ")} outside the loader (${show(loaded)}) and the targets: ${plain.map((copy) => show(copy.target)).join(", ")}.`);
576
577
  }
577
578
  const copies: Copy[] = order.map((index) => {
578
579
  const copy = plain[index]!;
@@ -642,18 +643,20 @@ export function planLoader(input: LoaderInput): LoaderPlan {
642
643
  };
643
644
  }
644
645
 
646
+ /** The hardware vectors at $fffa-$ffff: the copier and the pieces of pages 0-3 stay below them. */
647
+ const BELOW_VECTORS = 0xfff9;
645
648
  /** Where the packed form puts the bytes of pages 0-3: the copier reads them with all RAM visible ($01 = $34). */
646
- const PIECE_AREA: AddressRange = { start: 0x0400, end: 0xffff };
649
+ const PIECE_AREA: AddressRange = { start: 0x0400, end: BELOW_VECTORS };
647
650
 
648
651
  /**
649
- * Where the packed form puts its copier: the copier sets $01 to $35 and then
650
- * to the entry's value, so it is in RAM that both show. A port bit that is an
651
- * input reads 1.
652
+ * Where a loader puts its copier: the copier sets $01 to $35 and then to the
653
+ * entry's value, so it is in RAM that both show. A port bit that is an input
654
+ * reads 1.
652
655
  */
653
656
  export function copierAreas(port: readonly [number, number]): AddressRange[] {
654
657
  const rom = romUseOfPort((port[1] | ~port[0]) & 0x07);
655
658
  if (rom.basic) return [{ start: 0x0400, end: 0x9fff }, { start: 0xc000, end: 0xcfff }];
656
- return [{ start: 0x0400, end: 0xcfff }, ...(rom.kernal ? [] : [{ start: 0xe000, end: 0xffff }])];
659
+ return [{ start: 0x0400, end: 0xcfff }, ...(rom.kernal ? [] : [{ start: 0xe000, end: BELOW_VECTORS }])];
657
660
  }
658
661
  /** The free ranges that a refusal of the packed form names. */
659
662
  const SHOWN_FREE = 8;
@@ -668,8 +671,10 @@ const SHOWN_FREE = 8;
668
671
  * writes them after the unpack. Between its ranges, loader.asm holds the
669
672
  * bytes of the image, so its build does not change a segment.
670
673
  */
671
- function planPacked(input: LoaderInput, blocks: Block[], cia: ReturnType<typeof ciaSection>, codeSize: number, screen: StartScreenPlan | undefined, tooLarge: string): LoaderPlan {
674
+ function planPacked(input: LoaderInput, blocks: Block[], cia: ReturnType<typeof ciaSection>, copierCode: number, screen: StartScreenPlan | undefined, tooLarge: string): LoaderPlan {
672
675
  const { state } = input;
676
+ // The packed copier starts with SEI, as the stub of the plain form does: an interrupt in the copies would go through the vectors in RAM.
677
+ const codeSize = copierCode + 1;
673
678
  // The parts below $0400 without $00/$01, which the loader sets last.
674
679
  const low = blocks.flatMap((block) => {
675
680
  const range = { start: Math.max(block.range.start, 0x0002), end: Math.min(block.range.end, 0x03ff) };
@@ -680,15 +685,19 @@ function planPacked(input: LoaderInput, blocks: Block[], cia: ReturnType<typeof
680
685
  const lowBytes = low.reduce((sum, block) => sum + block.range.end - block.range.start + 1, 0);
681
686
  const areas = copierAreas(state.port);
682
687
  const free = subtract(PIECE_AREA, input.segments);
683
- const placed = placePacked(areas.flatMap((area) => subtract(area, input.segments)), free, low, codeSize);
688
+ const copierFree = areas.flatMap((area) => subtract(area, input.segments));
689
+ const placed = placePacked(copierFree, free, low, codeSize);
684
690
  if ("refusal" in placed) {
685
- const largest = [...free].sort((a, b) => b.end - b.start - (a.end - a.start)).slice(0, SHOWN_FREE);
686
- const ranges = largest.length === 0 ? "none" : largest.map((range) => `${show(range)} (${range.end - range.start + 1} bytes)`).join(", ");
691
+ const largest = (ranges: AddressRange[]) => {
692
+ const shown = [...ranges].sort((a, b) => b.end - b.start - (a.end - a.start)).slice(0, SHOWN_FREE);
693
+ return shown.length === 0 ? "none" : shown.map((range) => `${show(range)} (${range.end - range.start + 1} bytes)`).join(", ");
694
+ };
695
+ const ranges = placed.refusal === "copies" ? `The largest free ranges for pages 0-3: ${largest(free)}.` : `The largest free ranges for the copier: ${largest(copierFree)}. The largest free ranges for pages 0-3: ${largest(free)}.`;
687
696
  const why =
688
697
  placed.refusal === "copies"
689
698
  ? `A packed loader needs more than ${MAX_PACKED_COPIES} copies for the ${lowBytes} bytes of pages 0-3 in the free ranges.`
690
- : `A packed loader needs one free range of ${codeSize + COPY_ENTRY * Math.max(low.length, 1) + 2} bytes or more for its copier in ${areas.map(show).join(" or ")}, and ${lowBytes} more free bytes for pages 0-3 in $0400-$ffff, outside the segments. The copier runs with $01 = $35 and then with the $01 of the entry, so it is in RAM that both show.${screen === undefined ? "" : ` The start screen takes ${START_SCREEN_SIZES[screen.colourMode]} bytes of the copier: without it (unstart-screen), the copier is smaller.`}`;
691
- throw new WireFailure("invalid-input", `${tooLarge} ${why} The largest free ranges there: ${ranges}. Write the loader by hand.`);
699
+ : `A packed loader needs one free range of ${codeSize + COPY_ENTRY * Math.max(low.length, 1) + 2} bytes or more for its copier in ${areas.map(show).join(" or ")}, and ${lowBytes} more free bytes for pages 0-3 in ${show(PIECE_AREA)}, outside the segments. The copier runs with $01 = $35 and then with the $01 of the entry, so it is in RAM that both show.${screen === undefined ? "" : ` The start screen takes ${START_SCREEN_SIZES[screen.colourMode]} bytes of the copier: without it (unstart-screen), the copier is smaller.`}`;
700
+ throw new WireFailure("invalid-input", `${tooLarge} ${why} ${ranges} Write the loader by hand.`);
692
701
  }
693
702
  const { copier, pieces } = placed;
694
703
  const copierEnd = copier + codeSize + COPY_ENTRY * pieces.length + 2 - 1;
@@ -714,6 +723,7 @@ function planPacked(input: LoaderInput, blocks: Block[], cia: ReturnType<typeof
714
723
  `; The copier runs at ${formatC64Address(copier)}. The flags pass through ${formatC64Address(stackByte)}, the free stack byte below the stack pointer.`,
715
724
  `* = ${formatC64Address(copier)}`,
716
725
  COPIER_SOURCE,
726
+ " sei",
717
727
  // The entry by its address: main.asm, which has its label, is not in this build.
718
728
  ...copierLines(state, cia, stackByte, `${formatC64Address(input.entry)}${input.entryName === undefined ? "" : ` ; ${input.entryName} in main.asm`}`, screen !== undefined),
719
729
  ];
@@ -946,10 +956,11 @@ function copierLines(state: EntryState, cia: ReturnType<typeof ciaSection>, stac
946
956
  // The CIA part runs after the raster wait: the wait ends its whole lines earlier, so the entry comes in its line.
947
957
  ...vicLines(state, Math.floor((cia?.ops.reduce((sum, op) => sum + op.cycles, 0) ?? 0) / LINE_CYCLES)),
948
958
  ...(cia === undefined ? [] : cia.ops.map((op) => ` ${op.text}`)),
949
- ` lda #${formatC64Byte(port0)}`,
950
- " sta $00",
959
+ // $01 before $00: with the port bits still outputs, $01 shows no ROM that the port of the entry does not show.
951
960
  ` lda #${formatC64Byte(port1)}`,
952
961
  " sta $01",
962
+ ` lda #${formatC64Byte(port0)}`,
963
+ " sta $00",
953
964
  ` ldx #${formatC64Byte((state.sp - 1) & 0xff)}`,
954
965
  " txs",
955
966
  ` lda #${formatC64Byte(state.flags)}`,
@@ -1102,8 +1102,16 @@ function macrosText(layout: Layout): { text: string; lines: Map<string, { first:
1102
1102
  return { text: `${out.join("\n")}\n`, lines };
1103
1103
  }
1104
1104
 
1105
- /** The bytes of the patch code so far: after a byte at $ffff, ACME sets * to $0000. */
1106
- const LENGTH = "((* - .patch_start) & $ffff)";
1105
+ /** The bytes of patch code from `start` so far: after a byte at $ffff, ACME sets * to $0000. */
1106
+ const patchLength = (start: string) => `((* - ${start}) & $ffff)`;
1107
+ const LENGTH = patchLength(".patch_start");
1108
+
1109
+ /** The source of one patch of a captured stage on its own: the names of the stage, the code, and NOP to the end of its range. */
1110
+ export function stagePatchText(names: ReadonlyArray<{ name: string; address: number }>, patch: { start: number; end: number; code: string }): string {
1111
+ const start = formatC64Address(patch.start);
1112
+ const lines = ["!cpu 6510", ...names.map((symbol) => `${symbol.name} = ${formatC64Address(symbol.address)}`), `* = ${start}`, ...patch.code.split(/\r?\n/)];
1113
+ return `${[...lines, `!fill ${patch.end - patch.start + 1} - ${patchLength(start)}, $ea`].join("\n")}\n`;
1114
+ }
1107
1115
 
1108
1116
  /** The condition that puts in the code of a switch: the switch has the value that the program does not have. */
1109
1117
  const patchCondition = (alternative: PatchAlternative) => (alternative.base === 0 ? alternative.switch : `${alternative.switch} = 0`);
@@ -66,7 +66,7 @@ import { instructionWith, OPCODES } from "#src/opcodes.ts";
66
66
  import { capturedColourRam } from "#src/knowledge/start-screen.ts";
67
67
  import { planStage, STAGE_CODE_END, STAGE_FILE, STAGE_START, stageParts, stageText, type StageInput, type StagePart, type StagePlan } from "./lib/stage.ts";
68
68
  import { freeName, planDrops, readmeText, rewriteTest } from "./lib/export.ts";
69
- import { CONFIG_FILE, configText, configValues, entriesInData, entryOutsideImage, hasConfigFile, hasSwitchFile, layout, literalOperand, probeForms, render, switchesOf, type Layout, type PatchBlock, type Rendered, type SourceSwitch } from "./lib/source.ts";
69
+ import { CONFIG_FILE, configText, configValues, entriesInData, entryOutsideImage, hasConfigFile, hasSwitchFile, layout, literalOperand, probeForms, render, stagePatchText, switchesOf, type Layout, type PatchBlock, type Rendered, type SourceSwitch } from "./lib/source.ts";
70
70
 
71
71
  /** At most this many diagnostics or differences of one check. */
72
72
  const MAX_DIAGNOSTICS = 20;
@@ -1020,13 +1020,11 @@ async function stageBytes(row: StartScreenRow): Promise<{ parts: StagePart[]; co
1020
1020
  if (row.colourRam === true && colourRam === undefined) throw new Refusal("not-found", `The start screen takes its colours from the colour RAM of the capture in ${stage}, and that capture has none. Capture the stage again while it shows the screen, and put it into the project knowledge with image --space ${stage}.`);
1021
1021
  const image = knowledge.program;
1022
1022
  const memory = Uint8Array.from(image.memory);
1023
- const addresses = knowledge.symbols.map((symbol) => `${symbol.name} = ${formatC64Address(symbol.address)}`);
1024
1023
  for (const patch of knowledge.patches) {
1025
1024
  const owner = knowledge.switches.find((item) => item.name === patch.switch);
1026
1025
  if (owner === undefined || owner.default === owner.base) continue;
1027
1026
  const length = patch.end - patch.start + 1;
1028
- const text = ["!cpu 6510", ...addresses, `* = ${formatC64Address(patch.start)}`, ...patch.code.split(/\r?\n/), `!fill ${length} - (* - ${formatC64Address(patch.start)}), $ea`].join("\n");
1029
- const built = await assembleFiles([{ name: "patch.asm", text: `${text}\n` }], "patch.asm");
1027
+ const built = await assembleFiles([{ name: "patch.asm", text: stagePatchText(knowledge.symbols, patch) }], "patch.asm");
1030
1028
  if (built.program === undefined || built.start !== patch.start || built.program.length - 2 !== length) {
1031
1029
  throw new Refusal("invalid-input", `The patch of ${patch.switch} at ${formatC64Address(patch.start)}-${formatC64Address(patch.end)} in ${stage} does not assemble to ${length} bytes: ${built.diagnostics.map((diagnostic) => diagnostic.message).join("; ") || "it is longer than its range"}. Correct the patch in the project knowledge.`);
1032
1030
  }
@@ -179,7 +179,8 @@ A recording keeps a session of the original program, for example a play through
179
179
  - Make the recordings early, before you change the program.
180
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.
181
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.
182
+ - Replay each recording on the default build. Do not replay a release build or a build with a switch that is not at its default.
183
+ - When the generated source has a loader, the default build is `build/clean_loader.prg`. Give `--symbols build/symbols/clean_loader.json` with it. Else the default build is `build/clean.prg`, with `--symbols build/symbols/clean.json`.
183
184
  - 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.
184
185
  - A finding that a recording shows can go into the project knowledge. Give the `recording.json` of the recording as its test evidence.
185
186
  - The C64 of a recording has no disk drive. For a program that loads more files from a disk, use a scenario with `test`.
@@ -238,6 +239,8 @@ A `$` address is an address of the original. On the rebuild, it moves with the n
238
239
 
239
240
  A rebuild can be a loader with a start screen that RUN starts. If the symbols of the rebuild have `loader_start_screen_wait` and `loader_start_screen_continue`, the script runs the rebuild to the wait. Then it sets the PC to `loader_start_screen_continue`. The cycles before the wait do not count.
240
241
 
242
+ A rebuild can be the loader program of a generated source. Give its symbols. Then the replay counts from the entry of the program, where the loader jumps to. The checkpoints of both sides start at that entry. A runUntil step to an address does not count the code of the loader, or the code that the original runs before that entry. If another step of the recording runs before the entry, the result is INCONCLUSIVE. Then start the steps of the record file after the entry.
243
+
241
244
  `body` holds `result`, `side`, `firstDifference`, `reason` and `files`. The section "Replay" of `references/recording-format.md` gives each field.
242
245
 
243
246
  Do this for each result:
@@ -17,7 +17,7 @@ import { keyTaps, type KeyTap } from "#src/c64-keys.ts";
17
17
  import { READY_FRAMES } from "#src/host-client/entry-state.ts";
18
18
  import { ACTION_STEP_KINDS, checkActionStep, isInteger, isObject, keyboardBytes, renamedField, stepKind, type ActionStep, type Location } from "#src/host-client/steps.ts";
19
19
  import { readProjectFile, type Written } from "#src/host-client/transfer.ts";
20
- import { START_SCREEN_CONTINUE, START_SCREEN_WAIT } from "#src/knowledge/start-screen.ts";
20
+ import { LOADER_JUMP, START_SCREEN_CONTINUE, START_SCREEN_WAIT } from "#src/knowledge/start-screen.ts";
21
21
  import { PAL_FRAME_CYCLES, type C64RunSession, type CoreStatus } from "#src/native/c64run.ts";
22
22
  import type { Workspace } from "#src/native/staging.ts";
23
23
  import { namesOf, type Outcome } from "./scenario.ts";
@@ -225,7 +225,6 @@ export function readRecordFile(path: string): RecordFile {
225
225
  checkCoreStep(step, at, fail);
226
226
  return step;
227
227
  });
228
- if (new Set(steps.flatMap(addressTarget)).size > MAX_COUNTED_TARGETS) fail(`the runUntil steps go to more than ${MAX_COUNTED_TARGETS} addresses`);
229
228
  return {
230
229
  name: value.name as string,
231
230
  program: value.program as string,
@@ -354,6 +353,50 @@ export function siteMap(sites: RecordedSite[], from: Map<string, number>, to: Ma
354
353
  return moved;
355
354
  }
356
355
 
356
+ /** Where the original came to the entry that the loader of a rebuild jumps to. */
357
+ export interface EntryPoint {
358
+ /** The tick of the first opcode fetch at the entry. */
359
+ tick: number;
360
+ /** The count of each pc key, by its target, before that fetch. */
361
+ counts: Map<string, number>;
362
+ /** The number of events of the recording before the entry: always the first ones. */
363
+ eventsBefore: number;
364
+ /** The number of checkpoints before the entry, which the samples of the original leave out. */
365
+ samplesBefore: number;
366
+ }
367
+
368
+ /**
369
+ * A loader with a start screen that RUN starts waits for a key or a fire button that the recording does not have:
370
+ * the rebuild goes on after the wait, as the check of the loader does. Gives the tick of the wait, a problem, or
371
+ * undefined when the rebuild has no start screen.
372
+ */
373
+ async function passStartScreen(core: C64RunSession, own: Map<string, number>, limit: number): Promise<number | string | undefined> {
374
+ const wait = own.get(START_SCREEN_WAIT);
375
+ const resume = own.get(START_SCREEN_CONTINUE);
376
+ if (wait === undefined || resume === undefined) return undefined;
377
+ const reached = await core.status(`run-pc ${hex(wait)} ${limit}`);
378
+ if (reached.word !== "reached") return `the rebuild did not come to the wait of its start screen at ${formatC64Address(wait)}`;
379
+ await core.status(`goto ${hex(resume)}`);
380
+ return reached.tick;
381
+ }
382
+
383
+ /**
384
+ * The entry that the generated loader of a rebuild jumps to: the operand of its jump, from a short run of the
385
+ * rebuild. Gives a problem when the rebuild does not come to the jump.
386
+ */
387
+ export async function loaderEntry(core: C64RunSession, recording: Recording, subject: ReplaySubject): Promise<number | string> {
388
+ const own = namesOf(subject.symbols);
389
+ const jump = own.get(LOADER_JUMP)!;
390
+ const limit = recording.ticks * REBUILD_TIME_FACTOR;
391
+ await core.init();
392
+ await startProgram(core, readProjectFile(subject.program).bytes, false);
393
+ const screen = await passStartScreen(core, own, limit);
394
+ if (typeof screen === "string") return screen;
395
+ if ((await core.status(`run-pc ${hex(jump)} ${limit}`)).word !== "reached") return `the rebuild did not come to the jump of its loader at ${formatC64Address(jump)}`;
396
+ const operand = await core.peek((jump + 1) & 0xffff, 2);
397
+ return operand[0]! | (operand[1]! << 8);
398
+ }
399
+
357
400
  /** Power-on and READY, then the program in memory as a LOAD leaves it, and RUN in the keyboard queue. */
358
401
  async function startProgram(core: C64RunSession, prg: Uint8Array, load: boolean): Promise<CoreStatus> {
359
402
  if (prg.length < 3) throw new Refusal("invalid-input", "the program is not a PRG file");
@@ -491,12 +534,15 @@ export async function record(
491
534
  at.code(file.compare.checkpoint);
492
535
  for (const item of file.compare.state) at.data(item.address);
493
536
  }
537
+ // Two names can give one address: the replay core counts each address once.
538
+ const targets = [...new Set(file.steps.flatMap(addressTarget).map(at.code))];
539
+ if (targets.length > MAX_COUNTED_TARGETS) throw new Refusal("invalid-input", `record file of ${file.name}: the runUntil steps go to more than ${MAX_COUNTED_TARGETS} addresses`);
494
540
  const reads = workspace.path(RECORDING_FILES.reads);
495
541
  const coverage = workspace.path(RECORDING_FILES.coverage);
496
542
  await core.init();
497
543
  await core.command(`inputs ${inputsArgument(file.inputs)}`);
498
544
  await core.command(`record ${reads}`);
499
- await countAt(core, file.steps.flatMap(addressTarget).map(at.code));
545
+ await countAt(core, targets);
500
546
  await startProgram(core, prg, file.load ?? false);
501
547
  // From READY on: the start of the C64 itself is never in the map.
502
548
  await core.command(COVERAGE_COMMANDS.get(file.coverage) ?? `coverage on-pc ${hex(parseC64Address(file.coverage))}`);
@@ -620,6 +666,8 @@ export interface SideRun {
620
666
  problem?: string;
621
667
  /** True when the rebuild went on after the wait of its start screen. */
622
668
  startScreenSkipped?: boolean;
669
+ /** The original with an `entry`: where it came to that entry, when it came to it. */
670
+ entryPoint?: EntryPoint;
623
671
  /**
624
672
  * Input reads that the recording has no value for, which got the fixed idle value:
625
673
  * at sites that it does not have, and after its end at a site.
@@ -640,7 +688,7 @@ export async function replaySide(
640
688
  folder: string,
641
689
  subject: ReplaySubject,
642
690
  workspace: Workspace,
643
- options: { compare?: Comparison; stop?: number; dump?: number; pins?: string[] } = {},
691
+ options: { compare?: Comparison; stop?: number; dump?: number; pins?: string[]; entry?: number; handover?: { entry: number; original: EntryPoint } } = {},
644
692
  ): Promise<SideRun & { ram?: Uint8Array }> {
645
693
  const prg = readProjectFile(subject.program).bytes;
646
694
  const original = subject.side === "original";
@@ -663,9 +711,10 @@ export async function replaySide(
663
711
  await core.command(`inputs ${inputsArgument(recording.inputs)}`);
664
712
  await core.command(`site-map ${mapFile}`);
665
713
  await core.command(`replay ${reads}`);
666
- if (options.compare !== undefined) {
714
+ let sampling = false;
715
+ const startSampling = async (compare: Comparison) => {
667
716
  const stop = options.dump ?? options.stop ?? 0;
668
- const pinned = options.compare.pin ?? [];
717
+ const pinned = compare.pin ?? [];
669
718
  if (options.pins !== undefined && pinned.length > 0) {
670
719
  // The rebuild: each checkpoint first gets the original's values of the random state.
671
720
  const pinFile = workspace.path(`${subject.side}-pins.txt`);
@@ -673,33 +722,74 @@ export async function replaySide(
673
722
  await core.command(`pin ${pinFile} ${rangesArgument(pinned, at)}`);
674
723
  }
675
724
  // The samples hold the state, then the pinned items.
676
- await core.command(`sample ${hex(at.code(options.compare.checkpoint))} ${samples} ${rangesArgument([...options.compare.state, ...pinned], at)}${stop > 0 ? ` ${stop}` : ""}`);
677
- }
678
- await countAt(core, recording.events.flatMap((event) => ("pc" in event.key ? [at.code(event.key.pc)] : [])));
725
+ await core.command(`sample ${hex(at.code(compare.checkpoint))} ${samples} ${rangesArgument([...compare.state, ...pinned], at)}${stop > 0 ? ` ${stop}` : ""}`);
726
+ sampling = true;
727
+ };
728
+ // A rebuild with a loader takes its checkpoints from its entry on, as the original leaves out those before its own.
729
+ if (options.compare !== undefined && options.handover === undefined) await startSampling(options.compare);
730
+ const targets = recording.events.flatMap((event) => ("pc" in event.key ? [at.code(event.key.pc)] : []));
731
+ await countAt(core, targets);
732
+ if (options.entry !== undefined) await core.command(`mark ${hex(options.entry)}`);
679
733
  await startProgram(core, prg, recording.load);
680
- let limit = original ? recording.ticks : recording.ticks * REBUILD_TIME_FACTOR;
734
+ const base = original ? recording.ticks : recording.ticks * REBUILD_TIME_FACTOR;
735
+ let limit = base;
681
736
  let problem: string | undefined;
682
- // A loader with a start screen that RUN starts waits for a key or a fire button that the recording does not have:
683
- // the rebuild goes on after the wait, as the check of the loader does. The cycles to the wait do not count.
684
- const wait = own.get(START_SCREEN_WAIT);
685
- const resume = own.get(START_SCREEN_CONTINUE);
737
+ // A tick key of the rebuild comes this many cycles later than in the original.
686
738
  let skipped = 0;
687
- if (!original && !recording.load && wait !== undefined && resume !== undefined) {
688
- const reached = await core.status(`run-pc ${hex(wait)} ${limit}`);
689
- if (reached.word === "reached") {
690
- skipped = reached.tick;
691
- limit += skipped;
692
- await core.status(`goto ${hex(resume)}`);
693
- } else problem = `the rebuild did not come to the wait of its start screen at ${formatC64Address(wait)}`;
739
+ let screenSkipped = false;
740
+ if (!original && !recording.load) {
741
+ // The cycles to the wait of a start screen do not count.
742
+ const screen = await passStartScreen(core, own, limit);
743
+ if (typeof screen === "string") problem = screen;
744
+ else if (screen !== undefined) {
745
+ skipped = screen;
746
+ limit = base + skipped;
747
+ screenSkipped = true;
748
+ }
749
+ }
750
+ // A pc key counts the opcode fetches from the start, also those of the code before the entry: the unpacker of
751
+ // the original, or the loader of the rebuild. The rebuild counts again from the jump of its loader, without those of the original.
752
+ const { handover } = options;
753
+ if (problem === undefined && handover !== undefined) {
754
+ const jump = own.get(LOADER_JUMP)!;
755
+ if ((await core.status(`run-pc ${hex(jump)} ${limit}`)).word !== "reached") problem = `the rebuild did not come to the jump of its loader at ${formatC64Address(jump)}`;
756
+ else {
757
+ await countAt(core, targets);
758
+ const entered = await core.status(`run-pc ${hex(handover.entry)} ${limit}`);
759
+ if (entered.word !== "reached") problem = `the rebuild did not come to its entry at ${formatC64Address(handover.entry)}`;
760
+ else {
761
+ // After the entry, a tick key is as far from the entry as in the original.
762
+ skipped = entered.tick - handover.original.tick;
763
+ limit = base + Math.max(0, skipped);
764
+ if (options.compare !== undefined) await startSampling(options.compare);
765
+ }
766
+ }
694
767
  }
695
- for (const event of problem === undefined ? recording.events : []) {
768
+ // The original with an entry: the events before the mark at the entry came.
769
+ let eventsBefore = 0;
770
+ let entryTick: number | undefined;
771
+ const marked = async () => {
772
+ const answer = /tick=(\d+)/.exec(await core.command("marked"));
773
+ if (answer !== null) entryTick = Number(answer[1]);
774
+ };
775
+ for (const [index, event] of (problem === undefined ? recording.events : []).entries()) {
696
776
  const what = event.step === undefined ? "the RESTORE of the play" : "step " + event.step;
697
- const point = await runToKey(core, event.key, limit, map, skipped, at);
777
+ let key = event.key;
778
+ if (handover !== undefined) {
779
+ // The original came to this point before its entry, where the rebuild runs its loader. Each such event is a pc key: replay checks it.
780
+ if (index < handover.original.eventsBefore) continue;
781
+ if ("pc" in key) key = { ...key, count: key.count - (handover.original.counts.get(key.pc) ?? 0) };
782
+ }
783
+ const point = await runToKey(core, key, limit, map, skipped, at);
698
784
  if (point === "halted") break;
699
785
  if (point === "not-reached") {
700
786
  problem = "the program did not come to the point of " + what;
701
787
  break;
702
788
  }
789
+ if (options.entry !== undefined && entryTick === undefined) {
790
+ await marked();
791
+ if (entryTick === undefined) eventsBefore = index + 1;
792
+ }
703
793
  // At the point of a runUntil to an address, its target is reached.
704
794
  if (!("pc" in event.key)) problem = await doAction(core, event.action, at);
705
795
  if (problem !== undefined) {
@@ -713,12 +803,35 @@ export async function replaySide(
713
803
  const misses = sites.split(" ").slice(2).reduce((sum, entry) => sum + Number(entry.split(":")[4] ?? 0), 0);
714
804
  const ram = options.dump === undefined ? undefined : await core.peek(0, 0x10000);
715
805
  let lines: string[] = [];
716
- if (options.compare !== undefined) {
806
+ if (sampling) {
717
807
  await core.command("pin off");
718
808
  await core.command("sample off");
719
809
  lines = readFileSync(samples, "utf8").split("\n").filter((line) => line !== "");
720
810
  }
721
- return { samples: lines, end, unknown, misses, ...(problem === undefined ? {} : { problem }), ...(skipped > 0 ? { startScreenSkipped: true } : {}), ...(ram === undefined ? {} : { ram }) };
811
+ let entryPoint: EntryPoint | undefined;
812
+ if (options.entry !== undefined && entryTick === undefined) await marked();
813
+ if (entryTick !== undefined) {
814
+ const counts = new Map<string, number>();
815
+ for (const event of recording.events) {
816
+ if (!("pc" in event.key) || counts.has(event.key.pc)) continue;
817
+ const before = /marked=(\d+)/.exec(await core.command(`hits ${hex(at.code(event.key.pc))}`));
818
+ if (before !== null) counts.set(event.key.pc, Number(before[1]));
819
+ }
820
+ // A checkpoint at the first fetch at the entry has the tick of the mark. The rebuild starts its checkpoints after that fetch.
821
+ const after = lines.filter((line) => Number(line.split(" ")[0]) > entryTick!);
822
+ entryPoint = { tick: entryTick, counts, eventsBefore, samplesBefore: lines.length - after.length };
823
+ lines = after;
824
+ }
825
+ return {
826
+ samples: lines,
827
+ end,
828
+ unknown,
829
+ misses,
830
+ ...(problem === undefined ? {} : { problem }),
831
+ ...(screenSkipped ? { startScreenSkipped: true } : {}),
832
+ ...(entryPoint === undefined ? {} : { entryPoint }),
833
+ ...(ram === undefined ? {} : { ram }),
834
+ };
722
835
  }
723
836
 
724
837
  export interface CheckpointDifference {
@@ -9,11 +9,13 @@ import { createHash } from "node:crypto";
9
9
  import { isRefusal, Refusal } from "#src/errors.ts";
10
10
  import { readPrg } from "#src/host-client/image.ts";
11
11
  import { readProjectFile, writeReported, type Written } from "#src/host-client/transfer.ts";
12
+ import { formatC64Address } from "#src/c64.ts";
13
+ import { LOADER_JUMP } from "#src/knowledge/start-screen.ts";
12
14
  import { C64RunSession } from "#src/native/c64run.ts";
13
15
  import { localToolContext } from "#src/native/local.ts";
14
16
  import { Workspace } from "#src/native/staging.ts";
15
17
  import { UsageError } from "#src/script.ts";
16
- import { firstDifference, parseStateItem, pinLines, readRecording, replaySide, siteMap, type Comparison, type ReplayResult, type ReplaySubject } from "./recording.ts";
18
+ import { firstDifference, loaderEntry, mover, parseStateItem, pinLines, readRecording, replaySide, siteMap, type Comparison, type ReplayResult, type ReplaySubject } from "./recording.ts";
17
19
  import { namesOf } from "./scenario.ts";
18
20
 
19
21
  const MAX_STATE_ITEMS = 16;
@@ -69,8 +71,16 @@ export async function replay(values: ReplayOptions): Promise<ReplayResult> {
69
71
  const originalSymbols = recording.symbols === "none" ? "knowledge" : recording.symbols;
70
72
  const original: ReplaySubject = { side: "original", program: recording.program, symbols: originalSymbols };
71
73
  const side = (subject: ReplaySubject, options: Parameters<typeof replaySide>[5]) => replaySide(core, recording, folder, subject, workspace, options);
74
+ const rebuildSymbols = values.symbols ?? originalSymbols;
75
+ // A rebuild with a generated loader starts the program where its loader jumps to. The original comes to that entry by the same name.
76
+ let loader: { entry: number; original: number } | undefined;
77
+ if (values.rebuild !== undefined && !recording.load && namesOf(rebuildSymbols).has(LOADER_JUMP)) {
78
+ const entry = await loaderEntry(core, recording, { side: "rebuild", program: values.rebuild, symbols: rebuildSymbols });
79
+ if (typeof entry === "string") return result("FAIL", "rebuild", { reason: entry });
80
+ loader = { entry, original: mover(namesOf(rebuildSymbols, "code"), namesOf(originalSymbols, "code"))(entry) };
81
+ }
72
82
  // The self-check: the original ends the session with the recorded state, to the cycle.
73
- const self = await side(original, { ...(compare === undefined ? {} : { compare }) });
83
+ const self = await side(original, { ...(compare === undefined ? {} : { compare }), ...(loader === undefined ? {} : { entry: loader.original }) });
74
84
  if (self.problem !== undefined) return result("INCONCLUSIVE", "original", { reason: `the recording does not reproduce on the original: ${self.problem}` });
75
85
  if (self.unknown > 0 || self.misses > 0) {
76
86
  return result("INCONCLUSIVE", "original", { reason: `the recording does not reproduce on the original: ${self.unknown + self.misses} input reads had no recorded value; record the session again with this version of the toolkit` });
@@ -81,8 +91,21 @@ export async function replay(values: ReplayOptions): Promise<ReplayResult> {
81
91
  const expected = self.samples;
82
92
  if (compare !== undefined && expected.length === 0) return result("INCONCLUSIVE", "original", { reason: `the original never came to the checkpoint ${compare.checkpoint} in the session` });
83
93
  if (values.rebuild === undefined) return result("PASS", "original", { checkpoints: expected.length });
94
+ let handover: { entry: number; original: NonNullable<typeof self.entryPoint> } | undefined;
95
+ if (loader !== undefined) {
96
+ const entered = self.entryPoint;
97
+ const at = formatC64Address(loader.original);
98
+ if (entered === undefined) return result("INCONCLUSIVE", "original", { reason: `the original never came to ${at}, where the loader of the rebuild jumps` });
99
+ // 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.
100
+ const early = recording.events.slice(0, entered.eventsBefore).find((event) => !("pc" in event.key));
101
+ if (early !== undefined) {
102
+ const what = early.step === undefined ? "the RESTORE of the play" : `step ${early.step}`;
103
+ return result("INCONCLUSIVE", "original", { 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` });
104
+ }
105
+ handover = { entry: loader.entry, original: entered };
106
+ }
84
107
 
85
- const rebuild: ReplaySubject = { side: "rebuild", program: values.rebuild, symbols: values.symbols ?? originalSymbols };
108
+ const rebuild: ReplaySubject = { side: "rebuild", program: values.rebuild, symbols: rebuildSymbols };
86
109
  let movedSites: number;
87
110
  try {
88
111
  movedSites = siteMap(recording.sites, namesOf(originalSymbols, "code"), namesOf(rebuild.symbols, "code")).length;
@@ -90,7 +113,7 @@ export async function replay(values: ReplayOptions): Promise<ReplayResult> {
90
113
  throw new UsageError(`--symbols ${rebuild.symbols}: ${(error as Error).message}`);
91
114
  }
92
115
  const pins = pinLines(expected, compare!.state);
93
- const replayed = await side(rebuild, { compare: compare!, stop: expected.length, pins });
116
+ const replayed = await side(rebuild, { compare: compare!, stop: expected.length, pins, ...(handover === undefined ? {} : { handover }) });
94
117
  const difference = firstDifference(expected, replayed.samples, compare!.state);
95
118
  // A read that the recording has no value for gets the idle value: it is in the result, never silent.
96
119
  const base = { checkpoints: expected.length, movedSites, ...(replayed.startScreenSkipped === true ? { startScreen: "skipped" } : {}), ...(replayed.unknown > 0 ? { idleReads: replayed.unknown } : {}) };
@@ -103,7 +126,9 @@ export async function replay(values: ReplayOptions): Promise<ReplayResult> {
103
126
  if (values.out !== undefined && difference !== undefined) {
104
127
  const files: Written[] = [];
105
128
  for (const subject of [original, rebuild]) {
106
- const dumped = await side(subject, { compare: compare!, dump: difference.checkpoint, ...(subject.side === "rebuild" ? { pins } : {}) });
129
+ // The original also stops at the checkpoints before its entry, which its samples leave out.
130
+ const dump = difference.checkpoint + (subject.side === "original" ? (handover?.original.samplesBefore ?? 0) : 0);
131
+ const dumped = await side(subject, { compare: compare!, dump, ...(subject.side === "rebuild" ? { pins, ...(handover === undefined ? {} : { handover }) } : {}) });
107
132
  files.push(writeReported(`${values.out}/${subject.side}-${difference.checkpoint}.bin`, dumped.ram!, { what: "--out" }));
108
133
  }
109
134
  failed.files = files;
@@ -114,3 +139,4 @@ export async function replay(values: ReplayOptions): Promise<ReplayResult> {
114
139
  workspace.remove();
115
140
  }
116
141
  }
142
+
@@ -15,6 +15,7 @@ import { readPrg } from "#src/host-client/image.ts";
15
15
  import { writeReported, type Written } from "#src/host-client/transfer.ts";
16
16
  import { ViceSessionClient } from "#src/host-client/vice-session.ts";
17
17
  import { knowledgeAt, knowledgeNames } from "#src/knowledge/names.ts";
18
+ import { PAL_FRAME_CYCLES } from "#src/native/c64run.ts";
18
19
  import { listed, OPTIONS, reply, runScript, UsageError, type Call, type CommandSpec, type OptionSpec } from "#src/script.ts";
19
20
  import { basicStart, inspect, readMemoryMap, underRom, writtenThenExecuted } from "./lib/evidence.ts";
20
21
  import { loads, readLoadSteps } from "./lib/loads.ts";
@@ -435,6 +436,8 @@ async function follow(
435
436
  stopAt = undefined;
436
437
  }
437
438
  };
439
+ // Stage 0 starts at the program, whatever the first step is: RUN and the BASIC line before it are no part of it.
440
+ await client.memmap({ action: "clear" });
438
441
  // The steps run first and in the tracked time: a frames step and a runUntil step to an address. The others act between two chunks.
439
442
  for (const [index, step] of options.steps.entries()) {
440
443
  running = index + 1;
@@ -445,12 +448,19 @@ async function follow(
445
448
  const why = halted === undefined ? "" : ` ${stoppedEarly(halted.stopReason, halted.pc, total, step.runUntil.timeoutFrames)}`;
446
449
  return { stages: found, frames: total, reached: false, failed: `Step ${index + 1} did not reach its target in ${step.runUntil.timeoutFrames} frames. It is at ${formatC64Address(pc)}.${why}` };
447
450
  }
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);
451
+ } else {
452
+ // A press or a runUntil to memory or the raster runs frames outside the chunks. The stopwatch of the session gives them,
453
+ // also for a run that a point stops early. What the step wrote and ran is in the stage before the next chunk clears the memory map.
454
+ await client.timing("start");
455
+ const notReached = await runActionStep(client, step, knowledgeAt());
456
+ const timed = await client.timing("read");
457
+ total += Math.round(Number("cycles" in timed ? timed.cycles : 0) / PAL_FRAME_CYCLES);
458
+ mergeMaps(stage.map, await readCoverage(client));
459
+ if (notReached !== undefined && "runUntil" in step) {
460
+ return { stages: found, frames: total, reached: false, failed: `Step ${index + 1} did not reach its target in ${step.runUntil.timeoutFrames} frames. It stopped by ${notReached.stopReason} at ${formatC64Address(notReached.pc)}.` };
461
+ }
453
462
  }
463
+ noteUntil(stage.map);
454
464
  }
455
465
  running = 0;
456
466
  const left = Math.max(0, options.frames - total);
@@ -9,6 +9,8 @@ import type { StartScreenMode } from "./schema.ts";
9
9
  /** The labels of the start screen in a generated loader: its wait for a key or a fire button, and the code after the wait. */
10
10
  export const START_SCREEN_WAIT = "loader_start_screen_wait";
11
11
  export const START_SCREEN_CONTINUE = "loader_start_screen_continue";
12
+ /** The label of the loader's jump to the entry, in ACME's symbol list. */
13
+ export const LOADER_JUMP = "c64_source_loader_jump";
12
14
 
13
15
  /** The fields of a start screen that the capture of a stage gives. */
14
16
  export interface StageScreen {
package/tools/c64run.c CHANGED
@@ -234,10 +234,27 @@ static uint8_t counted_at[0x10000];
234
234
  static uint16_t counted_pc[MAX_COUNTED];
235
235
  static uint64_t counted[MAX_COUNTED];
236
236
  static int counted_pcs;
237
+ // "mark": the counts and the tick at the first opcode fetch at mark_pc, before that fetch counts.
238
+ static uint64_t marked[MAX_COUNTED];
239
+ static uint64_t mark_tick;
240
+ static int mark_pc = -1; // -1: no mark waits
241
+ static int mark_set; // marked and mark_tick hold the mark
237
242
 
238
243
  static void clear_counts(void) {
239
244
  for (int i = 0; i < counted_pcs; i++) counted_at[counted_pc[i]] = 0;
240
245
  counted_pcs = 0;
246
+ mark_pc = -1;
247
+ mark_set = 0;
248
+ }
249
+
250
+ static void count_fetch(uint16_t pc) {
251
+ if (mark_pc == pc) {
252
+ for (int i = 0; i < counted_pcs; i++) marked[i] = counted[i];
253
+ mark_tick = ticks;
254
+ mark_pc = -1;
255
+ mark_set = 1;
256
+ }
257
+ if (counted_at[pc]) counted[counted_at[pc] - 1]++;
241
258
  }
242
259
 
243
260
  static uint64_t count_of(uint16_t pc) {
@@ -258,7 +275,7 @@ static void tick(void) {
258
275
  last_sync_pc = addr;
259
276
  if (sample_file && addr == sample_pc && decoded) sample();
260
277
  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]++;
278
+ if (decoded) count_fetch(addr);
262
279
  }
263
280
  if (read && !sync && decoded && sys.io_mapped && (addr & 0xFF0F) == 0xDC00) {
264
281
  // chips gives port A of CIA 1 only joystick 2. A key also pulls its line of port A
@@ -513,7 +530,7 @@ int main(int argc, char** argv) {
513
530
  last_sync_pc = pc;
514
531
  // The prefetch is the opcode fetch at pc: it does not pass through tick.
515
532
  if (coverage_armed_pc && pc == coverage_pc) { coverage_armed_pc = 0; coverage_start(pc); }
516
- if (counted_at[pc]) counted[counted_at[pc] - 1]++;
533
+ count_fetch((uint16_t)pc);
517
534
  if (coverage_on) cover(pc, 1, 1);
518
535
  status("ok");
519
536
  } else if (!strcmp(cmd, "run")) {
@@ -554,11 +571,23 @@ int main(int argc, char** argv) {
554
571
  counted_at[pc] = (uint8_t)++counted_pcs;
555
572
  }
556
573
  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);
574
+ } else if (!strcmp(cmd, "mark")) {
575
+ // mark <pc hex>: keep the counts of count-pc at the next opcode fetch at pc, before it counts
576
+ unsigned pc;
577
+ if (sscanf(a1, "%x", &pc) != 1 || pc > 0xFFFF) { printf("err mark: give a pc\n"); continue; }
578
+ mark_pc = (int)pc;
579
+ mark_set = 0;
580
+ printf("ok\n");
581
+ } else if (!strcmp(cmd, "marked")) {
582
+ // marked: the tick of the mark when it came, else none
583
+ if (mark_set) printf("ok tick=%llu\n", (unsigned long long)mark_tick);
584
+ else printf("ok none\n");
557
585
  } else if (!strcmp(cmd, "hits")) {
558
- // hits <pc hex>: the count of a pc of count-pc
586
+ // hits <pc hex>: the count of a pc of count-pc, and its count at the mark when the mark came
559
587
  unsigned pc;
560
588
  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));
589
+ if (mark_set && counted_at[pc]) printf("ok count=%llu marked=%llu\n", (unsigned long long)count_of((uint16_t)pc), (unsigned long long)marked[counted_at[pc] - 1]);
590
+ else printf("ok count=%llu\n", (unsigned long long)count_of((uint16_t)pc));
562
591
  } else if (!strcmp(cmd, "run-reads")) {
563
592
  // run-reads <pc hex> <addr hex> <n> <until tick>: run until the site has n reads
564
593
  unsigned pc, addr;