@henols/c64-re-tools 2.6.0-rc.14 → 2.6.0-rc.16

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.14",
3
+ "version": "2.6.0-rc.16",
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",
@@ -28,7 +28,7 @@ To get the command list, run the script with no arguments.
28
28
  | Build a source that includes a file that you generated into a folder next to the source root | `build src boot.asm --out build/boot.prg --include ../build` |
29
29
  | Build a source that sets no start address | `build src main.a --out build/game.prg --set-pc '$0801'` |
30
30
  | Build a generated source with the values of `config.asm` | `build src main.asm` |
31
- | Build the loader of a generated source | `build src loader.asm` |
31
+ | Build the loader of a generated source. For the packed form, this is only the copier. | `build src loader.asm` |
32
32
  | Check that the rebuild is identical to the program in the project knowledge | `build src main.asm --compare` |
33
33
  | Build a release and check it against the bytes of that release | `build src main.asm --release ORIGINAL --compare` |
34
34
  | Check the rebuild of a program in another space, for example the drive | `build src main.asm --out build/drive.prg --compare --space drive8` |
@@ -68,7 +68,7 @@ Without `--out`, the name of the program tells what the build is:
68
68
  | A value of `config.asm` is not its default | `custom_<switches>.prg`, for example `custom_trainer.prg`. A switch that is off has `no_` before its name, for example `custom_no_start_screen.prg`. |
69
69
  | A source without `config.asm` | the name of the entry, for example `main.prg` |
70
70
 
71
- An entry other than `main.asm` adds its name, for example `clean_loader.prg` for `loader.asm`. With `--plain`, the extension is `.bin`. Do not give `--out` for a build of a generated source. Then the name always tells the build.
71
+ An entry other than `main.asm` adds its name, for example `clean_loader.prg` for `loader.asm`. The `loader.asm` of the packed form holds only the copier, so its build is `clean_copier.prg`. The packed loader program `clean_loader.prg` of the generated source stays. With `--plain`, the extension is `.bin`. Do not give `--out` for a build of a generated source. Then the name always tells the build.
72
72
 
73
73
  ### Paths and the project folder
74
74
 
@@ -136,7 +136,7 @@ Assembles the source and writes the program to `--out`, or to `build/<name>.prg`
136
136
 
137
137
  Do as the result tells:
138
138
 
139
- - `result` is `PASS`: the program is at `out`. To run or debug the program, load the file at `out` into the emulator.
139
+ - `result` is `PASS`: the program is at `out`. To run or debug the program, load the file at `out` into the emulator. A generated source with a loader is different: the build of `main.asm` does not set the entry state, and it can hold bytes for $d000-$dfff. Load the loader program in its place.
140
140
  - `result` is `FAIL` and `assembled` is `false`: the source has errors, and the script wrote no program. `hint` tells you to correct the source. Correct the source at the file and the line of each diagnostic. Then run `build` again.
141
141
  - `result` is `FAIL` and `assembled` is `true`: the program is not identical to the reference. The script wrote the program. Read the first difference of each segment in `compare.segments`. Without `--release`, read the section "Switches" first.
142
142
  - `hint` tells that `symbols` is cut: give a larger `--max-listed`, or read the symbols file for the full list.
@@ -84,12 +84,13 @@ await runScript({
84
84
  }
85
85
  const setPc = call.address("set-pc");
86
86
  const { contents, ...tree } = readSourceTree(sourceRoot, call.strings("include"));
87
- if (!tree.files.some((file) => file.path === (tree.sourceDir === "" ? entry : `${tree.sourceDir}/${entry}`))) throw new Refusal("not-found", `${entry} is not a file in ${sourceRoot}. Give the main source file relative to the source root.`);
87
+ const inSource = (name: string) => tree.files.findIndex((file) => file.path === (tree.sourceDir === "" ? name : `${tree.sourceDir}/${name}`));
88
+ if (inSource(entry) < 0) throw new Refusal("not-found", `${entry} is not a file in ${sourceRoot}. Give the main source file relative to the source root.`);
88
89
  // The name of the build tells what it is: the release, or the switch values of config.asm.
89
- const config = tree.files.findIndex((file) => file.path === (tree.sourceDir === "" ? CONFIG_FILE : `${tree.sourceDir}/${CONFIG_FILE}`));
90
+ const config = inSource(CONFIG_FILE);
90
91
  const kind: BuildKind | undefined = label !== undefined ? { release: label } : config < 0 ? undefined : { values: configValues(contents[config]!.toString("utf8")), defaults: switchDefaults(call.space) };
91
92
  const plain = call.flag("plain");
92
- const out = call.string("out") ?? `${BUILD_DIRECTORY}/${buildName(entry, kind)}.${plain ? "bin" : "prg"}`;
93
+ const out = call.string("out") ?? `${BUILD_DIRECTORY}/${buildName(entry, kind, contents[inSource(entry)]!.toString("utf8"))}.${plain ? "bin" : "prg"}`;
93
94
  const params: AcmeParams = { ...tree, entrySource: entry, defines: { ...releaseDefine, ...Object.fromEntries(call.strings("define").map(parseDefine)) }, ...(setPc === undefined ? {} : { setPc }) };
94
95
 
95
96
  const { result, attachments } = await assemble(params, contents, localToolContext());
@@ -114,7 +114,7 @@ The reference has these pages:
114
114
  - `index.md`: each file of the source, with its range, its title, the count of routines and the count of names.
115
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.
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
- - `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.
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
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.
@@ -145,12 +145,34 @@ export function buildReference(input: ReferenceInput): { files: ReferenceFile[];
145
145
  */
146
146
  const named = new Set(input.symbols.map((symbol) => symbol.address));
147
147
  const dataReferences = input.references.filter((reference) => !(reference.to >= IO_RAM.start && reference.to <= IO_RAM.end && input.image?.inImage(reference.to) === true && !named.has(reference.to)));
148
- /** The routines that read or write a range, each linked to its entry. */
149
- const ownersOf = (page: string, start: number, end: number, kind: string) =>
148
+ /**
149
+ * How the source line of a reference uses a platform name, as the source writes it: "named", "indexed"
150
+ * (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.
152
+ */
153
+ const platformUse = (reference: ReferenceRow, name: string): "named" | "indexed" | undefined => {
154
+ const line = map.lineOf(reference.from);
155
+ 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";
159
+ };
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) =>
150
162
  capped(
151
- [...new Set(dataReferences.filter((reference) => reference.kind === kind && reference.to >= start && reference.to <= end).map((reference) => ownerAt(reference.from)?.name ?? hex(reference.from)))].map((name) =>
152
- entries.has(name) ? entryOfName(page, name, name) : `\`${name}\``,
153
- ),
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
+ ],
154
176
  );
155
177
 
156
178
  // --- The routine graph ----------------------------------------------------
@@ -381,7 +403,7 @@ export function buildReference(input: ReferenceInput): { files: ReferenceFile[];
381
403
  lines.push("", "## Variables outside the program", "", "| Address | Name | Comment | Read by | Written by |", "|---|---|---|---|---|");
382
404
  for (const entry of outside) {
383
405
  const at = `\`${entry.spanEnd > entry.address ? range(entry.address, entry.spanEnd) : hex(entry.address)}\``;
384
- const owners = (kind: string) => ownersOf(page, entry.address, entry.spanEnd, kind);
406
+ const owners = (kind: string) => ownersOf(page, entry.address, entry.spanEnd, kind, entry.kind === "platform" ? entry.name : undefined);
385
407
  lines.push(`| ${at} | <a id="${entry.name}"></a>${codeOfName(page, entry.name)} | ${commentLines(entry.address).join(" ").replace(/\|/g, "\\|")} | ${owners("read")} | ${owners("write")} |`);
386
408
  }
387
409
  counts.entries += outside.length;
@@ -32,6 +32,8 @@ export interface SourceMap {
32
32
  lineOf: (address: number) => SourceLine | undefined;
33
33
  /** The project path of a source file. */
34
34
  pathOf: (file: string) => string;
35
+ /** The text of a source line, without its comment; undefined when the file or the line is not there. */
36
+ textOf?: (line: SourceLine) => string | undefined;
35
37
  }
36
38
 
37
39
  /** Reads the source map of the source in `directory` of the project `root`. A missing map is a refusal with the remedy. */
@@ -61,6 +63,7 @@ export function readSourceMap(directory: string, root?: string): SourceMap {
61
63
  .map((item) => ({ start: parseC64Address(String(item.start)), end: parseC64Address(String(item.end)), file: String(item.file), line: Number(item.line) }))
62
64
  .sort((a, b) => a.start - b.start);
63
65
  const byName = new Map(labels.map((label) => [label.name, label]));
66
+ const texts = new Map<string, string[] | undefined>();
64
67
  return {
65
68
  directory,
66
69
  mapPath: path,
@@ -82,5 +85,16 @@ export function readSourceMap(directory: string, root?: string): SourceMap {
82
85
  return undefined;
83
86
  },
84
87
  pathOf: (file) => posix.join(directory, file),
88
+ textOf: (line) => {
89
+ if (!texts.has(line.file)) {
90
+ try {
91
+ texts.set(line.file, readProjectFile(posix.join(directory, line.file), root === undefined ? {} : { root }).bytes.toString("utf8").split(/\r?\n/));
92
+ } catch {
93
+ texts.set(line.file, undefined);
94
+ }
95
+ }
96
+ const text = texts.get(line.file)?.[line.line - 1];
97
+ return text?.replace(/;.*$/, "");
98
+ },
85
99
  };
86
100
  }
@@ -251,7 +251,7 @@ When a git merge left conflicts in the knowledge, each read body also has `confl
251
251
  - `body.lines` has `count` and `listed`. `listed` holds one line for each instruction of a code region, and one `!byte` line for other bytes.
252
252
  - Each line has `address`, `bytes`, `text`, `referencesIn` and `referencesOut`. It can also have `label`, `analyzerNames`, `lineComments` and `comment`. `lineComments` are the line comments before the line. `comment` is the side comment.
253
253
  - `text` is the instruction with the names of its target. An operand expression of the knowledge replaces the operand.
254
- - `access` is there when the knowledge has coverage. It tells if a run executed (`x`), read (`r`) or wrote (`w`) the bytes of the line. `-` tells that no run did. An `r` on code can come from a read of the 6502 that the program does not do. Examples are the byte after an RTS and the opcode after a branch that the CPU takes. Another example is the opcode at the PC when an interrupt starts.
254
+ - `access` is there when the knowledge has coverage. It tells if a run executed (`x`), read (`r`) or wrote (`w`) the bytes of the line. `-` tells that no run did. An `r` on code can come from a read of the 6502 that the program does not do. Examples are the third byte of a JSR and the opcode after a branch that the CPU takes. Another example is the opcode at the PC when an interrupt starts. An indexed read (`lda table,x`) that crosses a page also reads the byte $100 below its target. A read watchpoint does not stop at these reads.
255
255
  - With `--out`, the body has `lines` as a number, and `out`, `bytes` and `sha256` of the text file.
256
256
  - If the knowledge has no program in the space, the script refuses. Put the program in with `image` first.
257
257
  - Use `listing` in place of your own disassembler.
@@ -540,7 +540,7 @@ A macro writes a run of instructions as one line of the source, for example `+in
540
540
  ### `coverage <map>...`
541
541
 
542
542
  - `<map>` is a 64 KiB coverage map of a run. Write each map in `.c64-re-tools/local/`.
543
- - `body` holds `revision`, `imported`, `known` and `ranges`. `imported` lists the new maps. `known` lists the maps that the space has already.
543
+ - `body` holds `revision`, `imported`, `known` and `ranges`. `imported` lists the new maps. `known` lists the maps that the space has already. `ranges` counts the new ranges of accesses that no earlier map has. When `ranges` is 0, the source and the reference do not change.
544
544
  - `coverage` joins the maps. It keeps each address that a run executed, read or wrote. It also keeps each address that one run wrote and executed: self-modified code.
545
545
  - `coverage` puts each map into the space of `--space`. You can add the same map to each space.
546
546
  - `--evidence coverage:<map>` names a map by its path at the import. It refers to the last import of that map into the space of the write.
@@ -1069,7 +1069,15 @@ const WRITE_COMMANDS: CommandSpec[] = [
1069
1069
  const maps = call.subjects.map((path) => ({ bytes: readProjectFile(path).bytes, name: knowledgePath(path, "<map>") }));
1070
1070
  return (db) => {
1071
1071
  const { revision, current } = addCoverage(db, context, { space: call.space, maps });
1072
- return { revision, ...spaceOf(current), imported: current.imported, known: current.known, ranges: current.ranges };
1072
+ const body = { revision, ...spaceOf(current), imported: current.imported, known: current.known, ranges: current.ranges };
1073
+ // ranges counts the accesses that no earlier map had: only they change the source and the reference.
1074
+ const hint =
1075
+ revision === null
1076
+ ? "The knowledge has each map already. Nothing changed."
1077
+ : current.ranges === 0
1078
+ ? "The maps add no access that the knowledge did not have. The knowledge keeps them as evidence. The source and the reference do not change."
1079
+ : `The maps add ${current.ranges} ranges of accesses. They can change the leftovers and the code that no run executed. Generate the source again, then the reference.`;
1080
+ return reply(body, { hint });
1073
1081
  };
1074
1082
  },
1075
1083
  ),
@@ -335,7 +335,7 @@ A loader file that loads into $d000 or higher writes the I/O area. When the prog
335
335
  To make the packed loader for other switch values, do these steps:
336
336
 
337
337
  1. Assemble `main.asm` without an output path. The build name of the program tells the switch values, for example `build/custom_trainer.prg`. The leftovers are $00 in this build.
338
- 2. Assemble `loader.asm` without an output path, for example to `build/custom_trainer_loader.prg`. This is the copier.
338
+ 2. Assemble `loader.asm` without an output path, for example to `build/custom_trainer_copier.prg`. This is the copier. The build name has `copier` in place of `loader`, so the build does not write over the loader program.
339
339
  3. Pack the two files into `build/custom_trainer_packed.prg`. The start address is the copier address in the comment at the start of `loader.asm`. The memory configuration at the exit is `$34`.
340
340
 
341
341
  These steps do not work when a segment starts below $0400. They also do not work when a patch is between the free ranges of `loader.asm`. In these cases, use `generate --loader` for the base release.
@@ -16,6 +16,7 @@
16
16
  import { readFileSync } from "node:fs";
17
17
  import { fileURLToPath } from "node:url";
18
18
 
19
+ import { COPIER_LINE } from "#src/build-name.ts";
19
20
  import { type AddressRange, formatC64Address, formatC64Byte, prgRange } from "#src/c64.ts";
20
21
  import { compareBuild, mergedPrograms } from "#src/compare.ts";
21
22
  import { Refusal } from "#src/errors.ts";
@@ -691,6 +692,7 @@ function planPacked(input: LoaderInput, blocks: Block[], cia: ReturnType<typeof
691
692
  "; The image is too large for one loader file, so this is the packed form. Exomizer packs the",
692
693
  `; build of main.asm and the build of this file into the loader program, with --entry '${formatC64Address(copier)}' and --exit-memory '$34'.`,
693
694
  "; The unpacker of Exomizer uses the zero page and $0334-$03ff, so the copier writes pages $0002-$03ff after the unpack.",
695
+ COPIER_LINE,
694
696
  "",
695
697
  "!cpu 6510",
696
698
  ...settingsLines(input),
@@ -703,6 +703,9 @@ const LOADER_CHECK_DIRECTORY = "loader-check";
703
703
  /** The source files of the loader. Only a run with --loader writes them, so only such a run removes them. */
704
704
  const LOADER_FILES: ReadonlySet<string> = new Set(["loader.asm", START_SCREEN_FILE, STAGE_FILE]);
705
705
 
706
+ /** The source files of the show stage. A run writes them only with a loader program whose check ran, so only such a run removes them. */
707
+ const STAGE_FILES: ReadonlySet<string> = new Set([START_SCREEN_FILE, STAGE_FILE]);
708
+
706
709
  /** A loader program that generate wrote: its build name, as buildName gives it for loader.asm. */
707
710
  const LOADER_PROGRAM = /^(clean|custom_[a-z0-9_]+|release_[A-Za-z0-9_]+)_loader\.prg$/;
708
711
 
@@ -802,7 +805,7 @@ function removeOldFiles(out: string, keep: ReadonlySet<string>, loaderRun: boole
802
805
  }
803
806
  if (!entry.isFile()) continue;
804
807
  const path = join(directory, entry.name);
805
- if (LOADER_FILES.has(name) && !loaderRun) continue;
808
+ if ((LOADER_FILES.has(name) && !loaderRun) || STAGE_FILES.has(name)) continue;
806
809
  if (!name.endsWith(".asm") || keep.has(name) || !readFileSync(path, "utf8").startsWith(GENERATED_MARK)) continue;
807
810
  rmSync(path, { force: true });
808
811
  removed.push(`${out}/${name}`);
@@ -1216,7 +1219,7 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
1216
1219
  ...(rendered.notExecuted === undefined
1217
1220
  ? {}
1218
1221
  : {
1219
- notExecuted: { instructions: rendered.notExecuted.instructions, ...listed(rendered.notExecuted.ranges, max, showRange, `${reports}/${NOT_EXECUTED_FILE}`) },
1222
+ notExecuted: { instructions: rendered.notExecuted.instructions, ...listed(rendered.notExecuted.ranges, max, showRange, `a larger --max-listed, or read ${reports}/${NOT_EXECUTED_FILE}`) },
1220
1223
  }),
1221
1224
  ...(laid.unusedModules.length === 0 ? {} : { unusedModules: laid.unusedModules.map((module) => ({ start: formatC64Address(module.start), file: module.file })) }),
1222
1225
  // The bytes that nothing uses: in leftover files, which the default build and the loader leave out.
@@ -1346,7 +1349,9 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
1346
1349
  rmSync(resolveProjectPath(scratch), { recursive: true, force: true });
1347
1350
  }
1348
1351
  // A loader program of an earlier run with another build name goes: config.asm has other values now.
1349
- for (const path of loaderPrograms().filter((item) => item !== loaderPath && item !== symbolsPath(loaderPath))) {
1352
+ // The files of an earlier show stage go when this loader has no stage and this run did not write them.
1353
+ const stageFiles = stage === undefined ? [...STAGE_FILES].filter((name) => !files.some((file) => file.name === name)).map((name) => `${out}/${name}`).filter((path) => existsSync(resolveProjectPath(path)) && readFileSync(resolveProjectPath(path), "utf8").startsWith(GENERATED_MARK)) : [];
1354
+ for (const path of [...loaderPrograms().filter((item) => item !== loaderPath && item !== symbolsPath(loaderPath)), ...stageFiles]) {
1350
1355
  rmSync(resolveProjectPath(path), { force: true });
1351
1356
  removed.push(path);
1352
1357
  }
@@ -1700,7 +1705,7 @@ async function exportProject(call: Call): Promise<Record<string, unknown>> {
1700
1705
  to: fromProject(to),
1701
1706
  zip: zipWritten,
1702
1707
  source: { project: basename(project), revision: knowledge.revision },
1703
- files: listed(files.map((file) => ({ ...file, out: fromProject(join(to, file.out)) })), max, (file) => file, "the folder of the new project"),
1708
+ files: listed(files.map((file) => ({ ...file, out: fromProject(join(to, file.out)) })), max, (file) => file, "a larger --max-listed, or list the folder of the new project"),
1704
1709
  switches,
1705
1710
  check: exportCheck,
1706
1711
  ...(loaderOutput === undefined ? {} : { loader: loaderOutput }),
@@ -131,6 +131,7 @@ The `hint` gives each of these cases:
131
131
  - `coverageConflicts` is not empty. Classify each range as code in the project knowledge, or as `dual-use` when its bytes are also data. For many ranges, write all classifications in one batch of changes.
132
132
  - `idioms.candidates.macros` has candidates, and the run had no `--apply-macros`. Examine the candidates. To write the correct candidates to the project knowledge, run the analysis again with `--apply-macros`. Give `--skip` with the start of each candidate that is not correct. Then generate the source again.
133
133
  - The last analysis of the same program bytes used another analyzer version. Thus a change in `revision` can come from the new analyzer, and not from the program or the project knowledge.
134
+ - `changes.references.retired` is more than 0. A data range that only a retired reference used can be a leftover now. Generate the source again, and examine the leftovers that changed.
134
135
  - A list is cut. Give a larger `--max-listed`. The project knowledge has all `labels` and `functions` as analyzer names.
135
136
 
136
137
  There is no `nextAction`.
@@ -36,11 +36,13 @@ const ALL_NAMES = "a larger --max-listed. The project knowledge has all of them
36
36
  * analyzer data over executed code to classify, and macro candidates to write.
37
37
  * The envelope adds the sentence for a cut list.
38
38
  */
39
- function withHint(body: Record<string, unknown>, conflicts: number, coverageConflicts: number, macros: { candidates: number; applied: boolean; revision: string | null | undefined }, version: { now: string | undefined; last: string | undefined; revision: string | null }) {
39
+ function withHint(body: Record<string, unknown>, conflicts: number, coverageConflicts: number, macros: { candidates: number; applied: boolean; revision: string | null | undefined }, version: { now: string | undefined; last: string | undefined; revision: string | null }, retiredReferences: number) {
40
40
  const hints: string[] = [];
41
41
  if (version.revision !== null && version.now !== undefined && version.last !== undefined && version.now !== version.last) {
42
42
  hints.push(`The last analysis of this program used ${version.last}. Thus a change in revision ${version.revision} can come from the new analyzer version, and not from the program or the project knowledge.`);
43
43
  }
44
+ // A leftover is data that no reference reads: a retired reference can make one.
45
+ if (retiredReferences > 0) hints.push("The analysis retired references. A data range that only a retired reference used can be a leftover now. Generate the source again, and examine the leftovers that changed.");
44
46
  if (conflicts > 0) hints.push("The analysis and the project knowledge disagree at each place in conflicts. Find the correct answer in the emulator. Then correct the project knowledge.");
45
47
  if (coverageConflicts > 0) hints.push("The coverage shows executed code in each range of coverageConflicts. Classify each range as code, or as dual-use when its bytes are also data, in the project knowledge.");
46
48
  if (typeof macros.revision === "string") hints.push("The project knowledge has the macro candidates now. Generate the source again.");
@@ -313,7 +315,7 @@ async function analyze(call: Call): Promise<unknown> {
313
315
  labels: listed(result.labels, max, (label) => ({ address: formatC64Address(label.address), name: label.name }), ALL_NAMES),
314
316
  ...(written === undefined ? {} : { listing: written }),
315
317
  };
316
- return withHint(body, imported.conflicts.length + found.idioms.conflicts.length, body.coverageConflicts?.length ?? 0, { candidates: found.idioms.candidates.macros.count, applied: applyMacros, revision: found.idioms.candidates.macros.revision }, { now: result.toolVersion, last: lastVersion, revision: imported.revision });
318
+ return withHint(body, imported.conflicts.length + found.idioms.conflicts.length, body.coverageConflicts?.length ?? 0, { candidates: found.idioms.candidates.macros.count, applied: applyMacros, revision: found.idioms.candidates.macros.revision }, { now: result.toolVersion, last: lastVersion, revision: imported.revision }, imported.changes.references.retired);
317
319
  }
318
320
 
319
321
  const { result } = await analyzeWithDecompiler({ imageKind, ...seeds, codeStarts, decompile }, bytes, localToolContext());
@@ -348,7 +350,7 @@ async function analyze(call: Call): Promise<unknown> {
348
350
  ? {}
349
351
  : { notDecompiled: result.notDecompiled!.map((item) => ({ entry: formatC64Address(item.entry), reason: item.reason })) }),
350
352
  };
351
- return withHint(body, imported.conflicts.length + found.idioms.conflicts.length, body.coverageConflicts?.length ?? 0, { candidates: found.idioms.candidates.macros.count, applied: applyMacros, revision: found.idioms.candidates.macros.revision }, { now: result.toolVersion, last: lastVersion, revision: imported.revision });
353
+ return withHint(body, imported.conflicts.length + found.idioms.conflicts.length, body.coverageConflicts?.length ?? 0, { candidates: found.idioms.candidates.macros.count, applied: applyMacros, revision: found.idioms.candidates.macros.revision }, { now: result.toolVersion, last: lastVersion, revision: imported.revision }, imported.changes.references.retired);
352
354
  }
353
355
 
354
356
  await runScript({
@@ -48,6 +48,7 @@ To get the command list, run the script with no arguments.
48
48
  - `--state` and `--pin` take a name or a `$` address, with `:size` for more than one byte, for example `room:2`. Use the names that the project knowledge has at the time of the replay.
49
49
  - The joystick port of `--joystick` is the port that the program reads. Port 2 is `$DC00`, and port 1 is `$DC01`. Find the port in the code or in the project knowledge. If you do not know the port, use 2.
50
50
  - `diff` takes two states of one kind. A state is a snapshot file (`.vsf`), a memory file (`.bin`) of a run, or an observation of a run (`results.json:<name>`). A `save` step of a run writes a snapshot file. A snapshot save in the emulator also writes one.
51
+ - Each command starts its own emulator. Thus many commands can run at the same time. For example, other commands can run while a long `record` runs in the background.
51
52
 
52
53
  ### Paths and the project folder
53
54
 
@@ -72,7 +72,13 @@ The keyboard queue of the KERNAL holds 10 keys. If the keys of a `type` step and
72
72
 
73
73
  RESTORE starts an NMI and is not a read. The recording keeps each RESTORE of a `press` step as an event of that step. The replay presses RESTORE again at the same read of the program.
74
74
 
75
- `type`, `write`, `registers` and `runUntil` steps are events. The recording keeps a point in the program for each event. The point is the next read at the input site with the most reads. That site is not in ROM. A replay does the event again at the same read. An event that comes directly after another event runs at once after that event.
75
+ `type`, `write`, `registers` and `runUntil` steps are events. The recording keeps a point in the program for each event. A replay does the event again at the same point:
76
+
77
+ - A `runUntil` step to an address: the point is the number of times that the CPU got to that address. This step does not need an input read.
78
+ - An event that comes directly after another event runs at once after that event.
79
+ - Each other event: the point is the next read at the input site with the most reads. That site is not in ROM. If the program does not read input in 600 frames, the session stops.
80
+
81
+ Some parts of a program read no input, for example an intro or a bonus screen. To do an event in such a part, put a `runUntil` step to an address before the event.
76
82
 
77
83
  ## Play
78
84
 
@@ -39,6 +39,10 @@ export function inputsArgument(inputs: string[]): string {
39
39
  /** Frames that a pressed key is held, and then released. */
40
40
  const KEY_FRAMES = 3;
41
41
  const MAX_STATE_ITEMS = 16;
42
+ /** The replay core counts the opcode fetches at this many addresses at most: the targets of the runUntil steps to an address. */
43
+ const MAX_COUNTED_TARGETS = 64;
44
+ /** An event other than a runUntil to an address waits this long for the next input read. */
45
+ const READ_WAIT_FRAMES = 600;
42
46
  const MAX_STATE_BYTES = 4096;
43
47
  /** A replay of a rebuild may take this many times the cycles of the recording before it stops. */
44
48
  const REBUILD_TIME_FACTOR = 2;
@@ -99,9 +103,11 @@ export interface RecordedEvent {
99
103
  /**
100
104
  * The point: the n-th read at the busiest program site, or a tick when no
101
105
  * program site has read yet. An event that follows another event directly
102
- * has { previous: true }: it runs where that one ended.
106
+ * has { previous: true }: it runs where that one ended. A runUntil to an
107
+ * address has { pc, count }: the count-th opcode fetch at its target from the
108
+ * start, which needs no read; the event is done when the point is reached.
103
109
  */
104
- key: { site: Location; addr: Location; count: number } | { tick: number } | { previous: true };
110
+ key: { site: Location; addr: Location; count: number } | { tick: number } | { previous: true } | { pc: Location; count: number };
105
111
  }
106
112
 
107
113
  export interface RecordedSite {
@@ -219,6 +225,7 @@ export function readRecordFile(path: string): RecordFile {
219
225
  checkCoreStep(step, at, fail);
220
226
  return step;
221
227
  });
228
+ if (new Set(steps.flatMap(addressTarget)).size > MAX_COUNTED_TARGETS) fail(`the runUntil steps go to more than ${MAX_COUNTED_TARGETS} addresses`);
222
229
  return {
223
230
  name: value.name as string,
224
231
  program: value.program as string,
@@ -231,6 +238,17 @@ export function readRecordFile(path: string): RecordFile {
231
238
  };
232
239
  }
233
240
 
241
+ /** The target of a runUntil step to an address, as a list of none or one. */
242
+ function addressTarget(step: ActionStep | RestoreAction): Location[] {
243
+ return "runUntil" in step && step.runUntil.target.kind === "address" ? [step.runUntil.target.address] : [];
244
+ }
245
+
246
+ /** Starts the counts of the replay core at the addresses. */
247
+ async function countAt(core: C64RunSession, addresses: number[]): Promise<void> {
248
+ const unique = [...new Set(addresses)];
249
+ if (unique.length > 0) await core.command(`count-pc ${unique.map(hex).join(",")}`);
250
+ }
251
+
234
252
  /** What the replay core cannot do of a step that is right for VICE: it has the C64 alone, no raster wait and no conditions. */
235
253
  function checkCoreStep(step: ActionStep, at: string, fail: (message: string) => never): void {
236
254
  if ("write" in step && step.write.space !== "c64") fail(`${at}: a recording has the C64 alone, not ${step.write.space}`);
@@ -369,8 +387,12 @@ function busiestSite(answer: string): { site: number; addr: number; count: numbe
369
387
  * Runs to the point of an event. `map` moves a site to the rebuild. "halted"
370
388
  * when a sample stop came first, "not-reached" when the point did not come before `until`.
371
389
  */
372
- async function runToKey(core: C64RunSession, key: RecordedEvent["key"], until: number, map: Map<number, number>, skipped: number): Promise<"reached" | "not-reached" | "halted"> {
390
+ async function runToKey(core: C64RunSession, key: RecordedEvent["key"], until: number, map: Map<number, number>, skipped: number, at: SideAddresses): Promise<"reached" | "not-reached" | "halted"> {
373
391
  if ("previous" in key) return (await core.status("status")).word === "halted" ? "halted" : "reached";
392
+ if ("pc" in key) {
393
+ const status = await core.status(`run-pc ${hex(at.code(key.pc))} ${until} ${key.count}`);
394
+ return status.word === "halted" ? "halted" : status.word === "reached" ? "reached" : "not-reached";
395
+ }
374
396
  if ("tick" in key) {
375
397
  const status = await core.status(`run ${key.tick + skipped}`);
376
398
  return status.word === "halted" ? "halted" : "reached";
@@ -474,6 +496,7 @@ export async function record(
474
496
  await core.init();
475
497
  await core.command(`inputs ${inputsArgument(file.inputs)}`);
476
498
  await core.command(`record ${reads}`);
499
+ await countAt(core, file.steps.flatMap(addressTarget).map(at.code));
477
500
  await startProgram(core, prg, file.load ?? false);
478
501
  // From READY on: the start of the C64 itself is never in the map.
479
502
  await core.command(COVERAGE_COMMANDS.get(file.coverage) ?? `coverage on-pc ${hex(parseC64Address(file.coverage))}`);
@@ -485,13 +508,25 @@ export async function record(
485
508
  // replay. An event right after another event runs where that one ended.
486
509
  const runEvent = async (action: ActionStep | RestoreAction, step?: number): Promise<string | undefined> => {
487
510
  const tick = (await core.status("status")).tick;
511
+ if ("runUntil" in action && action.runUntil.target.kind === "address") {
512
+ // The next opcode fetch at the target: its count from the start is the point, on each replay.
513
+ const { address } = action.runUntil.target;
514
+ const pc = hex(at.code(address));
515
+ const count = Number(/count=(\d+)/.exec(await core.command(`hits ${pc}`))![1]) + 1;
516
+ const reached = await core.status(`run-pc ${pc} ${tick + action.runUntil.timeoutFrames * PAL_FRAME_CYCLES} ${count}`);
517
+ if (reached.word !== "reached") return `the program did not reach ${address} within ${action.runUntil.timeoutFrames} frames`;
518
+ events.push({ ...(step === undefined ? {} : { step }), action, key: { pc: address, count } });
519
+ return undefined;
520
+ }
488
521
  const busiest = afterEvent ? undefined : busiestSite(await core.command("sites"));
489
522
  const key: RecordedEvent["key"] = afterEvent
490
523
  ? { previous: true }
491
524
  : busiest === undefined
492
525
  ? { tick: tick + 1 }
493
526
  : { site: formatC64Address(busiest.site), addr: formatC64Address(busiest.addr), count: busiest.count + 1 };
494
- if ((await runToKey(core, key, tick + 600 * PAL_FRAME_CYCLES, new Map(), 0)) !== "reached") return "the program did not read its input again within 600 frames";
527
+ if ((await runToKey(core, key, tick + READ_WAIT_FRAMES * PAL_FRAME_CYCLES, new Map(), 0, at)) !== "reached") {
528
+ return `the program did not read its input again within ${READ_WAIT_FRAMES} frames. This step runs at the next input read. Put a runUntil step to an address before it: that step needs no input read`;
529
+ }
495
530
  events.push({ ...(step === undefined ? {} : { step }), action, key });
496
531
  return doAction(core, action, at);
497
532
  };
@@ -640,6 +675,7 @@ export async function replaySide(
640
675
  // The samples hold the state, then the pinned items.
641
676
  await core.command(`sample ${hex(at.code(options.compare.checkpoint))} ${samples} ${rangesArgument([...options.compare.state, ...pinned], at)}${stop > 0 ? ` ${stop}` : ""}`);
642
677
  }
678
+ await countAt(core, recording.events.flatMap((event) => ("pc" in event.key ? [at.code(event.key.pc)] : [])));
643
679
  await startProgram(core, prg, recording.load);
644
680
  let limit = original ? recording.ticks : recording.ticks * REBUILD_TIME_FACTOR;
645
681
  let problem: string | undefined;
@@ -658,13 +694,14 @@ export async function replaySide(
658
694
  }
659
695
  for (const event of problem === undefined ? recording.events : []) {
660
696
  const what = event.step === undefined ? "the RESTORE of the play" : "step " + event.step;
661
- const point = await runToKey(core, event.key, limit, map, skipped);
697
+ const point = await runToKey(core, event.key, limit, map, skipped, at);
662
698
  if (point === "halted") break;
663
699
  if (point === "not-reached") {
664
700
  problem = "the program did not come to the point of " + what;
665
701
  break;
666
702
  }
667
- problem = await doAction(core, event.action, at);
703
+ // At the point of a runUntil to an address, its target is reached.
704
+ if (!("pc" in event.key)) problem = await doAction(core, event.action, at);
668
705
  if (problem !== undefined) {
669
706
  problem = what + ": " + problem;
670
707
  break;
@@ -105,13 +105,15 @@ async function recordCommand(call: Call): Promise<Reply> {
105
105
  writeReported(`${out}/${RECORDING_FILES.reads}`, outcome.reads, { what: "--out" }),
106
106
  writeReported(`${out}/${RECORDING_FILES.coverage}`, outcome.coverage, { what: "--out" }),
107
107
  ];
108
- // A recording in the local folder is a work file: git ignores it, so it is no test.
109
- const keep = projectRelative(out).startsWith(`${PROJECT_DIRECTORY}/${LOCAL_DIRECTORY}/`)
108
+ // A recording in the local folder is a work file: git ignores it, so it is no test. A record file there is not kept either.
109
+ const local = (path: string) => projectRelative(path).startsWith(`${PROJECT_DIRECTORY}/${LOCAL_DIRECTORY}/`);
110
+ const keep = local(out)
110
111
  ? `Git ignores ${out}. To keep the recording as a test and to add its coverage to the project knowledge, record again with --out tests/recordings/<name>.`
111
112
  : `Commit ${out} with the scenarios. Add ${out}/${RECORDING_FILES.coverage} to the project knowledge as coverage.`;
113
+ const recordFile = local(call.subject(0)) ? ` Git also ignores the record file ${call.subject(0)}. To record again later, keep a copy in a folder that git keeps, for example tests/record/.` : "";
112
114
  return reply(
113
115
  { result: "PASS", recorded: true, out, ...summary, files },
114
- { hint: `${keep} ${summary.coverageFrom === null ? "The coverage did not start: the map is empty." : "The map has no marks for the code that ran before coverageFrom."} To make sure that the recording replays, run nextAction.`, nextAction: call.next("replay", out) },
116
+ { hint: `${keep}${recordFile} ${summary.coverageFrom === null ? "The coverage did not start: the map is empty." : "The map has no marks for the code that ran before coverageFrom."} To make sure that the recording replays, run nextAction.`, nextAction: call.next("replay", out) },
115
117
  );
116
118
  } finally {
117
119
  await core.close();
@@ -195,7 +195,7 @@ Traps:
195
195
 
196
196
  - `captured`: true when the CPU got to `--until`. `pc` is that address.
197
197
  - `files`: each file that the command wrote, as `{out, bytes, sha256}`. `removed` names the segment files of an earlier capture that the new `image.json` does not list.
198
- - `segments` and `excluded`: the ranges of the segment files, and the ranges that `--exclude` removed.
198
+ - `segments` and `excluded`: the ranges of the segment files, and the ranges that `--exclude` removed. `loaded: true` marks a segment with the bytes that the program loaded.
199
199
  - `stages`: the count of stages.
200
200
  - `differsFromReset`: the count of bytes that are not as a clean C64 has them at READY.
201
201
 
@@ -214,6 +214,8 @@ A segment is a block that a stage wrote, also a small block. These blocks are no
214
214
 
215
215
  The block with the capture entry is always a segment. Segments do not overlap.
216
216
 
217
+ If no stage wrote the capture entry, the program runs as it loaded. Then the range of the PRG is a segment with `loaded: true`. The blocks that touch this range are in the same segment. An example is a memory dump that starts with `SYS`.
218
+
217
219
  A capture into a folder with an earlier capture removes only the segment files that the new `image.json` does not list. It keeps all other files.
218
220
 
219
221
  On `PASS`, `hint` tells you to disassemble the code at `pc`, and then to put `<out>/image.json` into the project knowledge.
@@ -221,7 +223,7 @@ On `PASS`, `hint` tells you to disassemble the code at `pc`, and then to put `<o
221
223
  Traps:
222
224
 
223
225
  - The capture stops at the first arrival at `--until` after the steps. To capture a later arrival, add a `runUntil` step to an address after the first arrival.
224
- - `captured: false`: the program did not get to `--until` in `--timeout-frames`. The reason tells where it stopped. Find a better address, or give more frames. If it stopped in a key wait, give `--steps` with a `type` step.
226
+ - `captured: false`: the program did not get to `--until` in `--timeout-frames`. The reason tells where it stopped. Find a better address, or give more frames. If it stopped in a key wait, give `--steps` with a `type` step. If the CPU got to `--until` in a step, the reason names that step.
225
227
 
226
228
  ### `loads <program>`
227
229
 
@@ -107,9 +107,16 @@ export const FIRST_SEGMENT_ADDRESS = 0x0400;
107
107
  * a segment. A block that an intermediate stage wrote inside a leftover, for
108
108
  * example a variable of the loader, is a leftover too. The filter comes before
109
109
  * the join: a join first would drop the program with a leftover. `writtenBy` is
110
- * the last stage that wrote into the range.
110
+ * the last stage that wrote into the range. When no written block holds the
111
+ * entry, the code there is as the program loaded it: `loaded`, the range of
112
+ * the PRG, is then a segment too (`loaded: true`), joined with the blocks that
113
+ * it overlaps or touches.
111
114
  */
112
- export function captureSegments(stages: ReadonlyArray<{ entry: number; wrote: readonly AddressRange[] }>, entry: number): Array<AddressRange & { writtenBy: number }> {
115
+ export function captureSegments(
116
+ stages: ReadonlyArray<{ entry: number; wrote: readonly AddressRange[] }>,
117
+ entry: number,
118
+ loaded?: AddressRange,
119
+ ): Array<AddressRange & ({ writtenBy: number } | { loaded: true })> {
113
120
  const last = stages.length - 1;
114
121
  const replaced = (from: number, address: number) => stages.slice(from).some((stage) => inRanges(stage.wrote, address));
115
122
  const leftover = (block: AddressRange, writer: number) =>
@@ -129,7 +136,15 @@ export function captureSegments(stages: ReadonlyArray<{ entry: number; wrote: re
129
136
  previous.writtenBy = Math.max(previous.writtenBy, block.writtenBy);
130
137
  } else segments.push({ ...block });
131
138
  }
132
- return segments;
139
+ if (loaded === undefined || !contains(loaded, entry) || segments.some((segment) => contains(segment, entry))) return segments;
140
+ const joined = { start: loaded.start, end: loaded.end, loaded: true as const };
141
+ const apart = segments.filter((segment) => {
142
+ if (segment.end + 1 < joined.start || segment.start > joined.end + 1) return true;
143
+ joined.start = Math.min(joined.start, segment.start);
144
+ joined.end = Math.max(joined.end, segment.end);
145
+ return false;
146
+ });
147
+ return [...apart, joined].sort((a, b) => a.start - b.start);
133
148
  }
134
149
 
135
150
  /** The segments without the bytes of `holes`: a segment that a hole cuts gives its parts, each with the fields of the segment. */
@@ -197,6 +197,8 @@ interface Followed {
197
197
  failed?: string;
198
198
  /** What stopped the CPU before the frames ran: a JAM or a point of the program. */
199
199
  halted?: { stopReason: string; pc: number };
200
+ /** The first step (1 = the first) in which the CPU executed `until`, before the run waited for it. */
201
+ untilRan?: number;
200
202
  }
201
203
 
202
204
  type RunUntilStep = Extract<ActionStep, { runUntil: unknown }>;
@@ -250,9 +252,16 @@ async function follow(
250
252
  const atTarget = (pc: number) => stopAt !== undefined && pc === stopAt;
251
253
  // The current stage: its memory map since it started, chunk by chunk, its own code, and the written code it calls.
252
254
  let stage = { map: new Uint8Array(0x10000), own: new Set<number>(), called: [] as AddressRange[] };
255
+ // A step that runs frames can pass until: the run then waits for it in vain.
256
+ let running = 0;
257
+ let untilRan: number | undefined;
258
+ const noteUntil = (map: Uint8Array) => {
259
+ if (options.until !== undefined && running > 0 && untilRan === undefined && (map[options.until]! & EXECUTE) !== 0) untilRan = running;
260
+ };
253
261
  const startStage = async (next: number, last: Uint8Array) => {
254
262
  mergeMaps(stage.map, last);
255
263
  await markIoRam(stage.map);
264
+ noteUntil(stage.map);
256
265
  found.push({ entry, firstFrame, frames: total - firstFrame, wrote: stageWrote(stage.map), next });
257
266
  entry = next;
258
267
  firstFrame = total;
@@ -428,6 +437,7 @@ async function follow(
428
437
  };
429
438
  // The steps run first and in the tracked time: a frames step and a runUntil step to an address. The others act between two chunks.
430
439
  for (const [index, step] of options.steps.entries()) {
440
+ running = index + 1;
431
441
  if ("frames" in step) await track(step.frames);
432
442
  else if (trackedRunUntil(step)) {
433
443
  if (!(await trackTo(knowledgeAt()(step.runUntil.target.address), step.runUntil.timeoutFrames))) {
@@ -436,7 +446,13 @@ async function follow(
436
446
  return { stages: found, frames: total, reached: false, failed: `Step ${index + 1} did not reach its target in ${step.runUntil.timeoutFrames} frames. It is at ${formatC64Address(pc)}.${why}` };
437
447
  }
438
448
  } else await runActionStep(client, step, knowledgeAt());
449
+ if (options.until !== undefined && untilRan === undefined) {
450
+ const now = Uint8Array.from(stage.map);
451
+ mergeMaps(now, await readCoverage(client));
452
+ noteUntil(now);
453
+ }
439
454
  }
455
+ running = 0;
440
456
  const left = Math.max(0, options.frames - total);
441
457
  let reached = false;
442
458
  if (options.until === undefined) await track(left);
@@ -445,7 +461,7 @@ async function follow(
445
461
  mergeMaps(stage.map, await readCoverage(client));
446
462
  await markIoRam(stage.map);
447
463
  found.push({ entry, firstFrame, frames: total - firstFrame, wrote: stageWrote(stage.map) });
448
- return { stages: found, frames: total, reached, ...(halted === undefined ? {} : { halted }) };
464
+ return { stages: found, frames: total, reached, ...(halted === undefined ? {} : { halted }), ...(untilRan === undefined ? {} : { untilRan }) };
449
465
  }
450
466
 
451
467
  const showRange = (range: { start: number; end: number }) => ({ start: formatC64Address(range.start), end: formatC64Address(range.end) });
@@ -490,6 +506,11 @@ async function stages(program: string, options: { frames: number; entry?: number
490
506
  }
491
507
  }
492
508
 
509
+ /** Why a capture can wait for --until in vain: a step ran over it. */
510
+ function passedInStep(until: number, step: number): string {
511
+ return `The CPU executed ${formatC64Address(until)} in step ${step}, before the wait for --until started. A press step runs frames. Make the steps stop before the program gets to that address, or give an --until address that the program gets to later.`;
512
+ }
513
+
493
514
  async function capture(
494
515
  program: string,
495
516
  options: { until: number; out: string; range?: AddressRange; exclude: AddressRange[]; timeoutFrames: number; entry?: number; steps: ActionStep[]; minStage: number },
@@ -504,7 +525,7 @@ async function capture(
504
525
  return {
505
526
  output: {
506
527
  captured: false,
507
- reason: `The program did not get to ${formatC64Address(options.until)} in ${options.timeoutFrames} frames. It is at ${formatC64Address(registers.pc)}.${followed.halted === undefined ? "" : ` ${stoppedEarly(followed.halted.stopReason, followed.halted.pc, followed.frames, options.timeoutFrames)}`}`,
528
+ reason: `The program did not get to ${formatC64Address(options.until)} in ${options.timeoutFrames} frames. It is at ${formatC64Address(registers.pc)}.${followed.halted === undefined ? "" : ` ${stoppedEarly(followed.halted.stopReason, followed.halted.pc, followed.frames, options.timeoutFrames)}`}${followed.untilRan === undefined ? "" : ` ${passedInStep(options.until, followed.untilRan)}`}`,
508
529
  ...(followed.halted === undefined ? {} : { stopReason: followed.halted.stopReason }),
509
530
  stages: showStages(followed.stages),
510
531
  },
@@ -515,7 +536,8 @@ async function capture(
515
536
  const memory = await readRam(client, 0x0000, 0x10000);
516
537
  const state = await machineState(client);
517
538
  // The segments: what the stages wrote, without loader leftovers, with no overlap.
518
- const found = options.range !== undefined ? [options.range] : captureSegments(followed.stages, registers.pc);
539
+ const load = bytes[0]! | (bytes[1]! << 8);
540
+ const found = options.range !== undefined ? [options.range] : captureSegments(followed.stages, registers.pc, { start: load, end: Math.min(0xffff, load + bytes.length - 3) });
519
541
  const segments = withoutRanges(found, options.exclude);
520
542
  const file = (path: string) => `${options.out}/${path}`;
521
543
  const written: Written[] = [];
@@ -533,7 +555,7 @@ async function capture(
533
555
  `${JSON.stringify(
534
556
  {
535
557
  entry: formatC64Address(registers.pc),
536
- segments: segments.map((segment, index) => ({ ...showRange(segment), ...("writtenBy" in segment ? { writtenBy: segment.writtenBy } : {}), file: files[index] })),
558
+ segments: segments.map((segment, index) => ({ ...showRange(segment), ...("writtenBy" in segment ? { writtenBy: segment.writtenBy } : {}), ...("loaded" in segment ? { loaded: true } : {}), file: files[index] })),
537
559
  ...(options.exclude.length === 0 ? {} : { excluded: options.exclude.map(showRange) }),
538
560
  vectors,
539
561
  stages: showStages(followed.stages),
@@ -556,7 +578,7 @@ async function capture(
556
578
  out: options.out,
557
579
  files: written,
558
580
  ...(removed.length === 0 ? {} : { removed }),
559
- segments: segments.map(showRange),
581
+ segments: segments.map((segment) => ({ ...showRange(segment), ...("loaded" in segment ? { loaded: true } : {}) })),
560
582
  ...(options.exclude.length === 0 ? {} : { excluded: options.exclude.map(showRange) }),
561
583
  stages: followed.stages.length,
562
584
  differsFromReset: entry.differsFromReset,
package/src/build-name.ts CHANGED
@@ -2,7 +2,9 @@
2
2
  // A release build is release_<label>. A build of config.asm is clean when each
3
3
  // switch has its default, else custom_ with each switch that differs: its
4
4
  // name when it is on, no_<name> when it is off. A build of an entry other
5
- // than main.asm adds the entry, for example clean_loader. A source without
5
+ // than main.asm adds the entry, for example clean_loader. The loader of the
6
+ // packed form alone is only its copier, so its build is clean_copier: the loader
7
+ // program, which generate packs, keeps clean_loader. A source without
6
8
  // config.asm and without a release keeps the name of its entry. The symbols
7
9
  // of a build go into symbols/ next to the program, so the program folder
8
10
  // holds only programs.
@@ -31,9 +33,12 @@ export function configValues(text: string): Map<string, 0 | 1> {
31
33
  /** What a build is made of: a release, or the values of config.asm with the default of each switch (0 when the defaults do not have it). */
32
34
  export type BuildKind = { release: string } | { values: ReadonlyMap<string, number>; defaults: ReadonlyMap<string, number> };
33
35
 
34
- /** The name of a build of `entry`, without an extension. */
35
- export function buildName(entry: string, kind: BuildKind | undefined): string {
36
- const base = basename(entry, extname(entry));
36
+ /** The line of a generated loader.asm of the packed form. Its build alone is only the copier, not the loader program. */
37
+ export const COPIER_LINE = "; A build of this file alone is only the copier: its build name has copier in place of loader.";
38
+
39
+ /** The name of a build of `entry`, without an extension. `source` is the text of the entry: COPIER_LINE in it gives the name copier. */
40
+ export function buildName(entry: string, kind: BuildKind | undefined, source?: string): string {
41
+ const base = source?.split(/\r?\n/).includes(COPIER_LINE) ? "copier" : basename(entry, extname(entry));
37
42
  if (kind === undefined) return base;
38
43
  let type: string;
39
44
  if ("release" in kind) type = `release_${kind.release}`;
@@ -176,7 +176,7 @@ export const c64CpuHistory = defineTool({
176
176
  },
177
177
  });
178
178
 
179
- /** The hits that a trace result gives inline; out gives all of them. */
179
+ /** The hits that a trace result gives inline; out gives all of them in the file, and none inline. */
180
180
  const TRACE_LISTED = 200;
181
181
 
182
182
  export const c64Trace = defineTool({
@@ -192,7 +192,7 @@ export const c64Trace = defineTool({
192
192
  "A read or write hit also gives the address that the instruction used, and value, the byte that it read or wrote. " +
193
193
  "At $D000-$DFFF only a load or a store gives value: a read after the access can give another byte. " +
194
194
  `The trace ends after frames frames (1 to ${MAX_TRACE_FRAMES}), at maxHits hits (at most ${MAX_TRACE_HITS}), or at a breakpoint, a watchpoint or a JAM. ` +
195
- `The result lists the first ${TRACE_LISTED} hits. With out, it writes all hits as JSON lines to that project file. ` +
195
+ `The result lists the first ${TRACE_LISTED} hits. With out, it writes all hits as JSON lines to that project file, and the result gives no hits. ` +
196
196
  "Each hit stops the machine for a short time. Thus a point with many hits in each frame makes the trace slow. Use a small range and a maxHits. " +
197
197
  "The machine is stopped after the trace.",
198
198
  inputSchema: z
@@ -209,23 +209,25 @@ export const c64Trace = defineTool({
209
209
  frames: z.number().int().min(0),
210
210
  pc: AddressOutput,
211
211
  count: z.number().int().min(0),
212
- hits: z.array(
213
- z.object({
214
- point: z.number().int().min(0),
215
- pc: AddressOutput,
216
- bytes: HexData,
217
- text: z.string(),
218
- a: Byte,
219
- x: Byte,
220
- y: Byte,
221
- sp: Byte,
222
- frame: z.number().int().min(0),
223
- rasterLine: z.number().int().min(0),
224
- rasterCycle: z.number().int().min(0),
225
- address: AddressOutput.optional(),
226
- value: Byte.optional(),
227
- }),
228
- ),
212
+ hits: z
213
+ .array(
214
+ z.object({
215
+ point: z.number().int().min(0),
216
+ pc: AddressOutput,
217
+ bytes: HexData,
218
+ text: z.string(),
219
+ a: Byte,
220
+ x: Byte,
221
+ y: Byte,
222
+ sp: Byte,
223
+ frame: z.number().int().min(0),
224
+ rasterLine: z.number().int().min(0),
225
+ rasterCycle: z.number().int().min(0),
226
+ address: AddressOutput.optional(),
227
+ value: Byte.optional(),
228
+ }),
229
+ )
230
+ .optional(),
229
231
  ...WrittenOutput,
230
232
  }),
231
233
  readOnly: false,
@@ -236,8 +238,8 @@ export const c64Trace = defineTool({
236
238
  if (ranges.some((point) => point.end < point.start)) throw new WireFailure("invalid-input", "A point end must not be before its start.");
237
239
  const traced = await session.trace({ points: ranges, ...request });
238
240
  const shown = traced.hits.map(({ address, ...hit }) => ({ ...hit, pc: formatC64Address(hit.pc), ...(address === undefined ? {} : { address: formatC64Address(address) }) }));
239
- const summary = { end: traced.end, frames: traced.frames, pc: formatC64Address(traced.pc), count: traced.hits.length, hits: shown.slice(0, TRACE_LISTED) };
240
- if (out === undefined) return summary;
241
+ const summary = { end: traced.end, frames: traced.frames, pc: formatC64Address(traced.pc), count: traced.hits.length };
242
+ if (out === undefined) return { ...summary, hits: shown.slice(0, TRACE_LISTED) };
241
243
  return { ...summary, ...writeOut(out, linesText(shown.map((hit) => JSON.stringify(hit))), project) };
242
244
  },
243
245
  });
@@ -186,7 +186,7 @@ export const c64Disassemble = defineTool({
186
186
  description:
187
187
  `Disassemble count instructions (1 to ${MAX_DISASSEMBLE}) from an address, as the bytes are in the live machine now. ` +
188
188
  "Use it to read code that a program changed or unpacked at run time. It includes the undocumented opcodes. " +
189
- `With out, it disassembles up to ${MAX_DISASSEMBLE_OUT} instructions, or to $ffff, and writes them as a listing to that project file. The result then gives the file in place of the instructions. ` +
189
+ `With out, it disassembles up to ${MAX_DISASSEMBLE_OUT} instructions, or to $ffff, and writes them as a listing to that project file. The result then gives the file in place of the instructions. A file name that ends in .json gets a JSON list of the instructions, as the result without out gives them. ` +
190
190
  "This does not change the run state of the machine.",
191
191
  inputSchema: z
192
192
  .object({
@@ -208,24 +208,27 @@ export const c64Disassemble = defineTool({
208
208
  const result = await session.disassemble(request);
209
209
  return { instructions: result.instructions.map((instruction) => ({ ...instruction, address: formatC64Address(instruction.address) })) };
210
210
  }
211
- const lines: string[] = [];
211
+ const instructions: Array<{ address: string; bytes: string; text: string }> = [];
212
212
  let address = request.address;
213
213
  // Ends at count, or where the disassembly would wrap past $ffff.
214
214
  let wrapped = false;
215
- while (!wrapped && lines.length < request.count && address <= 0xffff) {
216
- const { instructions } = await session.disassemble({ ...request, address, count: Math.min(MAX_DISASSEMBLE, request.count - lines.length) });
217
- if (instructions.length === 0) break;
218
- for (const instruction of instructions) {
219
- if (lines.length === request.count) break;
215
+ while (!wrapped && instructions.length < request.count && address <= 0xffff) {
216
+ const part = await session.disassemble({ ...request, address, count: Math.min(MAX_DISASSEMBLE, request.count - instructions.length) });
217
+ if (part.instructions.length === 0) break;
218
+ for (const instruction of part.instructions) {
219
+ if (instructions.length === request.count) break;
220
220
  if (instruction.address < address) {
221
221
  wrapped = true;
222
222
  break;
223
223
  }
224
- lines.push(`${formatC64Address(instruction.address)} ${spaced(instruction.bytes).padEnd(9)} ${instruction.text}`);
224
+ instructions.push({ ...instruction, address: formatC64Address(instruction.address) });
225
225
  address = instruction.address + instruction.bytes.length / 2;
226
226
  }
227
227
  }
228
- return { count: lines.length, ...writeOut(out, linesText(lines), project) };
228
+ const text = out.toLowerCase().endsWith(".json")
229
+ ? `${JSON.stringify(instructions, null, 1)}\n`
230
+ : linesText(instructions.map((instruction) => `${instruction.address} ${spaced(instruction.bytes).padEnd(9)} ${instruction.text}`));
231
+ return { count: instructions.length, ...writeOut(out, text, project) };
229
232
  },
230
233
  });
231
234
 
@@ -12,7 +12,7 @@ import type { SupervisedProcess } from "./processes.ts";
12
12
  import type { ToolContext } from "./run.ts";
13
13
 
14
14
  /** The command protocol that this module speaks; c64run --version and version name it. */
15
- export const C64RUN_PROTOCOL = 4;
15
+ export const C64RUN_PROTOCOL = 6;
16
16
 
17
17
  /** CPU cycles in one PAL frame: 312 lines of 63 cycles. */
18
18
  export const PAL_FRAME_CYCLES = 19_656;
package/tools/c64run.c CHANGED
@@ -27,7 +27,7 @@
27
27
  #include "systems/c1541.h"
28
28
  #include "systems/c64.h"
29
29
 
30
- #define C64RUN_PROTOCOL 4
30
+ #define C64RUN_PROTOCOL 6
31
31
  // The key code of matrix place 0 (row 0, column 0); place n has code 0x80 + n.
32
32
  #define C64RUN_KEY_PLACE 0x80
33
33
  #ifndef CHIPS_COMMIT
@@ -226,6 +226,24 @@ static void sample(void) {
226
226
  if (sample_stop && samples >= sample_stop) halted = 1;
227
227
  }
228
228
 
229
+ // ---- Counts: the opcode fetches at some pcs, from "count-pc" on ----
230
+
231
+ #define MAX_COUNTED 64
232
+ // 0: the pc is not counted; else the index of its count + 1.
233
+ static uint8_t counted_at[0x10000];
234
+ static uint16_t counted_pc[MAX_COUNTED];
235
+ static uint64_t counted[MAX_COUNTED];
236
+ static int counted_pcs;
237
+
238
+ static void clear_counts(void) {
239
+ for (int i = 0; i < counted_pcs; i++) counted_at[counted_pc[i]] = 0;
240
+ counted_pcs = 0;
241
+ }
242
+
243
+ static uint64_t count_of(uint16_t pc) {
244
+ return counted_at[pc] ? counted[counted_at[pc] - 1] : 0;
245
+ }
246
+
229
247
  // ---- The tick ----
230
248
 
231
249
  static void tick(void) {
@@ -240,6 +258,14 @@ static void tick(void) {
240
258
  last_sync_pc = addr;
241
259
  if (sample_file && addr == sample_pc && decoded) sample();
242
260
  if (coverage_armed_pc && addr == coverage_pc && decoded) { coverage_armed_pc = 0; coverage_start(addr); }
261
+ if (counted_at[addr] && decoded) counted[counted_at[addr] - 1]++;
262
+ }
263
+ if (read && !sync && decoded && sys.io_mapped && (addr & 0xFF0F) == 0xDC00) {
264
+ // chips gives port A of CIA 1 only joystick 2. A key also pulls its line of port A
265
+ // low while port B drives its column low: the scan from port B that some games use.
266
+ const m6526_port_t* pb = &sys.cia_1.pb;
267
+ const uint8_t low_columns = (uint8_t)~(pb->reg | ~pb->ddr);
268
+ if (low_columns) M6502_SET_DATA(pins, M6502_GET_DATA(pins) & (uint8_t)~kbd_test_lines(&sys.kbd, low_columns));
243
269
  }
244
270
  if (read && !sync && decoded && sys.io_mapped && (addr & 0xF000) == 0xD000 && input_addr[addr & 0x0FFF]) {
245
271
  input_read(last_sync_pc, addr);
@@ -437,6 +463,7 @@ int main(int argc, char** argv) {
437
463
  halted = 0;
438
464
  sample_stop = 0;
439
465
  maps = 0;
466
+ clear_counts();
440
467
  coverage_reset();
441
468
  if (pin_file) { fclose(pin_file); pin_file = NULL; }
442
469
  if (record_file) { fclose(record_file); record_file = NULL; }
@@ -486,6 +513,7 @@ int main(int argc, char** argv) {
486
513
  last_sync_pc = pc;
487
514
  // The prefetch is the opcode fetch at pc: it does not pass through tick.
488
515
  if (coverage_armed_pc && pc == coverage_pc) { coverage_armed_pc = 0; coverage_start(pc); }
516
+ if (counted_at[pc]) counted[counted_at[pc] - 1]++;
489
517
  if (coverage_on) cover(pc, 1, 1);
490
518
  status("ok");
491
519
  } else if (!strcmp(cmd, "run")) {
@@ -498,12 +526,39 @@ int main(int argc, char** argv) {
498
526
  do tick(); while (!(pins & M6502_SYNC) && !halted);
499
527
  status("ok");
500
528
  } else if (!strcmp(cmd, "run-pc")) {
501
- // run-pc <pc hex> <until tick>: run to the next opcode fetch at pc
529
+ // run-pc <pc hex> <until tick> [<n>]: run to the next opcode fetch at pc; with n, run
530
+ // until the count of pc ("count-pc") is n
502
531
  unsigned pc;
503
- const unsigned long long until = strtoull(a2, NULL, 10);
504
- if (sscanf(a1, "%x", &pc) != 1) { printf("err run-pc: give a pc and a tick\n"); continue; }
532
+ unsigned long long until, n;
533
+ const int fields = sscanf(line, "%*s %x %llu %llu", &pc, &until, &n);
534
+ if (fields < 2 || pc > 0xFFFF) { printf("err run-pc: give a pc and a tick\n"); continue; }
535
+ if (fields == 3) {
536
+ if (!counted_at[pc]) { printf("err run-pc: give count-pc with %04x first\n", pc); continue; }
537
+ while (count_of((uint16_t)pc) < n && ticks < until && !halted) tick();
538
+ status(count_of((uint16_t)pc) >= n ? "ok reached" : "ok not-reached");
539
+ continue;
540
+ }
505
541
  do tick(); while (!((pins & M6502_SYNC) && M6502_GET_ADDR(pins) == pc) && ticks < until && !halted);
506
542
  status((pins & M6502_SYNC) && M6502_GET_ADDR(pins) == pc ? "ok reached" : "ok not-reached");
543
+ } else if (!strcmp(cmd, "count-pc")) {
544
+ // count-pc <pc hex,...> | off: count the opcode fetches at each pc from 0
545
+ clear_counts();
546
+ if (!strcmp(a1, "off")) { printf("ok counted=0\n"); continue; }
547
+ int bad = 0;
548
+ for (char* part = strtok(a1, ","); part; part = strtok(NULL, ",")) {
549
+ unsigned pc;
550
+ if (sscanf(part, "%x", &pc) != 1 || pc > 0xFFFF || counted_pcs == MAX_COUNTED) { bad = 1; break; }
551
+ if (counted_at[pc]) continue;
552
+ counted_pc[counted_pcs] = (uint16_t)pc;
553
+ counted[counted_pcs] = 0;
554
+ counted_at[pc] = (uint8_t)++counted_pcs;
555
+ }
556
+ if (bad) { clear_counts(); printf("err count-pc: give 1 to %d pcs in hex\n", MAX_COUNTED); } else printf("ok counted=%d\n", counted_pcs);
557
+ } else if (!strcmp(cmd, "hits")) {
558
+ // hits <pc hex>: the count of a pc of count-pc
559
+ unsigned pc;
560
+ if (sscanf(a1, "%x", &pc) != 1 || pc > 0xFFFF) { printf("err hits: give a pc\n"); continue; }
561
+ printf("ok count=%llu\n", (unsigned long long)count_of((uint16_t)pc));
507
562
  } else if (!strcmp(cmd, "run-reads")) {
508
563
  // run-reads <pc hex> <addr hex> <n> <until tick>: run until the site has n reads
509
564
  unsigned pc, addr;