@henols/c64-re-tools 2.6.0-rc.17 → 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.17",
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,8 @@ 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";
26
+ import { romUseOfPort } from "#src/platform.ts";
25
27
  import { WireFailure } from "#src/host-client/tools.ts";
26
28
  import { pack } from "#src/native/exomizer.ts";
27
29
  import type { ToolContext } from "#src/native/run.ts";
@@ -138,9 +140,7 @@ export function loaderLimits(plan: { cia?: CiaPlan }): string[] {
138
140
  return plan.cia.limits;
139
141
  }
140
142
 
141
- /** The label of the loader's jump to the entry, in ACME's symbol list. */
142
- export const LOADER_JUMP = "c64_source_loader_jump";
143
- 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";
144
144
  /** The file of the start screen in the generated source. */
145
145
  export const START_SCREEN_FILE = "start_screen.asm";
146
146
  /** The code of the start screen: the same for each program. loader.asm sets its values. */
@@ -217,11 +217,12 @@ const COPY_ENTRY = 7;
217
217
  const TABLE_COPIES = Math.floor((256 - 2) / COPY_ENTRY);
218
218
  /** A loader that loads into $d000 or higher would write the I/O area. */
219
219
  const LOAD_LIMIT = 0xcfff;
220
- const COPIER_PAGES = [...Array.from({ length: 15 }, (_, index) => 0xc000 + index * 0x100), ...Array.from({ length: 0x9b }, (_, index) => 0x9e00 - index * 0x100)];
221
- /** 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. */
222
- const COPIER_AREAS: readonly AddressRange[] = [
223
- { start: 0x0400, end: 0x9fff },
224
- { 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),
225
226
  ];
226
227
 
227
228
  const overlaps = (a: AddressRange, b: AddressRange) => a.start <= b.end && b.start <= a.end;
@@ -565,13 +566,14 @@ export function planLoader(input: LoaderInput): LoaderPlan {
565
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.`);
566
567
  }
567
568
  const loaded = { start: LOAD, end };
569
+ const areas = copierAreas(state.port);
568
570
  const copier = COPIER_PAGES.find((page) => {
569
571
  const pages = { start: page, end: page + copierBytes - 1 };
570
- 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));
571
573
  });
572
574
  if (copier === undefined) {
573
575
  const count = copierPages === 2 ? "two" : "three";
574
- 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(", ")}.`);
575
577
  }
576
578
  const copies: Copy[] = order.map((index) => {
577
579
  const copy = plain[index]!;
@@ -641,11 +643,21 @@ export function planLoader(input: LoaderInput): LoaderPlan {
641
643
  };
642
644
  }
643
645
 
644
- /** Where the packed form puts its copier with the bytes of pages 0-3: the copier sets $01 to $35 and to the entry's value, so it is not under a ROM or the I/O area. */
645
- const PACKED_AREAS: readonly AddressRange[] = [
646
- { start: 0x0400, end: 0x9fff },
647
- { start: 0xc000, end: 0xcfff },
648
- ];
646
+ /** The hardware vectors at $fffa-$ffff: the copier and the pieces of pages 0-3 stay below them. */
647
+ const BELOW_VECTORS = 0xfff9;
648
+ /** Where the packed form puts the bytes of pages 0-3: the copier reads them with all RAM visible ($01 = $34). */
649
+ const PIECE_AREA: AddressRange = { start: 0x0400, end: BELOW_VECTORS };
650
+
651
+ /**
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.
655
+ */
656
+ export function copierAreas(port: readonly [number, number]): AddressRange[] {
657
+ const rom = romUseOfPort((port[1] | ~port[0]) & 0x07);
658
+ if (rom.basic) return [{ start: 0x0400, end: 0x9fff }, { start: 0xc000, end: 0xcfff }];
659
+ return [{ start: 0x0400, end: 0xcfff }, ...(rom.kernal ? [] : [{ start: 0xe000, end: BELOW_VECTORS }])];
660
+ }
649
661
  /** The free ranges that a refusal of the packed form names. */
650
662
  const SHOWN_FREE = 8;
651
663
 
@@ -659,8 +671,10 @@ const SHOWN_FREE = 8;
659
671
  * writes them after the unpack. Between its ranges, loader.asm holds the
660
672
  * bytes of the image, so its build does not change a segment.
661
673
  */
662
- 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 {
663
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;
664
678
  // The parts below $0400 without $00/$01, which the loader sets last.
665
679
  const low = blocks.flatMap((block) => {
666
680
  const range = { start: Math.max(block.range.start, 0x0002), end: Math.min(block.range.end, 0x03ff) };
@@ -669,16 +683,21 @@ function planPacked(input: LoaderInput, blocks: Block[], cia: ReturnType<typeof
669
683
  return [{ what: cut ? `${block.what}, part ${show(range)}` : block.what, range, bytes: block.bytes }];
670
684
  });
671
685
  const lowBytes = low.reduce((sum, block) => sum + block.range.end - block.range.start + 1, 0);
672
- const free = PACKED_AREAS.flatMap((area) => subtract(area, input.segments));
673
- const placed = placePacked(free, low, codeSize);
686
+ const areas = copierAreas(state.port);
687
+ const free = subtract(PIECE_AREA, input.segments);
688
+ const copierFree = areas.flatMap((area) => subtract(area, input.segments));
689
+ const placed = placePacked(copierFree, free, low, codeSize);
674
690
  if ("refusal" in placed) {
675
- const largest = [...free].sort((a, b) => b.end - b.start - (a.end - a.start)).slice(0, SHOWN_FREE);
676
- 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)}.`;
677
696
  const why =
678
697
  placed.refusal === "copies"
679
698
  ? `A packed loader needs more than ${MAX_PACKED_COPIES} copies for the ${lowBytes} bytes of pages 0-3 in the free ranges.`
680
- : `A packed loader needs one free range of ${codeSize + COPY_ENTRY * Math.max(low.length, 1) + 2} bytes or more for its copier, and ${lowBytes} more free bytes for pages 0-3, in $0400-$9fff or $c000-$cfff outside the segments.${screen === undefined ? "" : ` The start screen takes ${START_SCREEN_SIZES[screen.colourMode]} bytes of the copier: without it (unstart-screen), the copier is smaller.`}`;
681
- 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.`);
682
701
  }
683
702
  const { copier, pieces } = placed;
684
703
  const copierEnd = copier + codeSize + COPY_ENTRY * pieces.length + 2 - 1;
@@ -704,6 +723,7 @@ function planPacked(input: LoaderInput, blocks: Block[], cia: ReturnType<typeof
704
723
  `; The copier runs at ${formatC64Address(copier)}. The flags pass through ${formatC64Address(stackByte)}, the free stack byte below the stack pointer.`,
705
724
  `* = ${formatC64Address(copier)}`,
706
725
  COPIER_SOURCE,
726
+ " sei",
707
727
  // The entry by its address: main.asm, which has its label, is not in this build.
708
728
  ...copierLines(state, cia, stackByte, `${formatC64Address(input.entry)}${input.entryName === undefined ? "" : ` ; ${input.entryName} in main.asm`}`, screen !== undefined),
709
729
  ];
@@ -788,19 +808,19 @@ export function placePieces(ranges: AddressRange[], low: ReadonlyArray<{ what: s
788
808
 
789
809
  /**
790
810
  * Where the packed form puts its copier and the pieces of pages 0-3: the copier
791
- * in one free range, a free page of the plain copier first, else the start of a
811
+ * in one range of copierFree, a free page of the plain copier first, else the start of a
792
812
  * free range. The placement with the fewest pieces wins, then the one with the
793
813
  * shortest build of loader.asm.
794
814
  */
795
- function placePacked(free: AddressRange[], low: Parameters<typeof placePieces>[1], codeSize: number): { copier: number; pieces: Piece[] } | { refusal: "room" | "copies" } {
796
- const candidates = [...COPIER_PAGES, ...free.map((range) => range.start)];
815
+ function placePacked(copierFree: AddressRange[], free: AddressRange[], low: Parameters<typeof placePieces>[1], codeSize: number): { copier: number; pieces: Piece[] } | { refusal: "room" | "copies" } {
816
+ const candidates = [...COPIER_PAGES, ...copierFree.map((range) => range.start)];
797
817
  // The table has one entry per piece: a split can make the copier larger, so the room for the table grows until it holds every piece.
798
818
  for (let copies = Math.max(low.length, 1); copies <= MAX_PACKED_COPIES; ) {
799
819
  const size = codeSize + COPY_ENTRY * copies + 2;
800
820
  let best: { copier: number; pieces: Piece[]; span: number } | undefined;
801
821
  for (const copier of candidates) {
802
822
  const range = { start: copier, end: copier + size - 1 };
803
- if (!free.some((area) => range.start >= area.start && range.end <= area.end)) continue;
823
+ if (!copierFree.some((area) => range.start >= area.start && range.end <= area.end)) continue;
804
824
  // A piece goes to the start of its range: a range below the copier adds its whole length to the build.
805
825
  const distance = (other: AddressRange) => (other.end < range.start ? range.start - other.start : other.start - range.end);
806
826
  const pieces = placePieces(free.flatMap((area) => subtract(area, [range])), low, distance);
@@ -936,10 +956,11 @@ function copierLines(state: EntryState, cia: ReturnType<typeof ciaSection>, stac
936
956
  // The CIA part runs after the raster wait: the wait ends its whole lines earlier, so the entry comes in its line.
937
957
  ...vicLines(state, Math.floor((cia?.ops.reduce((sum, op) => sum + op.cycles, 0) ?? 0) / LINE_CYCLES)),
938
958
  ...(cia === undefined ? [] : cia.ops.map((op) => ` ${op.text}`)),
939
- ` lda #${formatC64Byte(port0)}`,
940
- " 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.
941
960
  ` lda #${formatC64Byte(port1)}`,
942
961
  " sta $01",
962
+ ` lda #${formatC64Byte(port0)}`,
963
+ " sta $00",
943
964
  ` ldx #${formatC64Byte((state.sp - 1) & 0xff)}`,
944
965
  " txs",
945
966
  ` lda #${formatC64Byte(state.flags)}`,
@@ -1102,6 +1102,17 @@ 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 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
+ }
1115
+
1105
1116
  /** The condition that puts in the code of a switch: the switch has the value that the program does not have. */
1106
1117
  const patchCondition = (alternative: PatchAlternative) => (alternative.base === 0 ? alternative.switch : `${alternative.switch} = 0`);
1107
1118
 
@@ -1128,7 +1139,7 @@ function patchOpening(patch: PatchBlock): string[] {
1128
1139
  `${INDENT}; ${alternative.switch} ${state}: ${bytes} byte${bytes === 1 ? "" : "s"} at ${range}, NOP after the code`,
1129
1140
  ...comment,
1130
1141
  ...(alternative.code === "" ? [] : alternative.code.split(/\r?\n/)),
1131
- `${INDENT}!if * - .patch_start > ${bytes} { !error "The patch ${alternative.switch} at ${formatC64Address(patch.start)} has ", * - .patch_start, " bytes; the range has ${bytes}." } else { !fill ${bytes} - (* - .patch_start), $ea }`,
1142
+ `${INDENT}!if ${LENGTH} > ${bytes} { !error "The patch ${alternative.switch} at ${formatC64Address(patch.start)} has ", ${LENGTH}, " bytes; the range has ${bytes}." } else { !fill ${bytes} - ${LENGTH}, $ea }`,
1132
1143
  );
1133
1144
  });
1134
1145
  out.push("} else {");
@@ -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: