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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@henols/c64-re-tools",
3
- "version": "2.8.0-rc.4",
3
+ "version": "2.8.0-rc.5",
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",
@@ -39,7 +39,7 @@ Commit the folder `.c64-re-tools/knowledge/` of the project with git.
39
39
  | Record the verdict of one comment of a check | `verdict 4711 '$2100' wrong --class callers --why 'JSR at $1f00 calls it too' --text 'Moves the player.'` |
40
40
  | Write all knowledge to one file | `export --out .c64-re-tools/local/knowledge.json` |
41
41
  | Find what the knowledge holds of the program | `program` |
42
- | Put a captured program into the knowledge | `image .c64-re-tools/local/capture/image.json` |
42
+ | Put a captured program into the knowledge | `image .c64-re-tools/local/capture/releases/game/image.json` |
43
43
  | Put a PRG into the knowledge | `image releases/game.prg` |
44
44
  | Add the coverage of runs | `coverage .c64-re-tools/local/runs/rooms/room0.bin` |
45
45
  | Add the coverage of a recording | `coverage tests/recordings/walk` |
@@ -63,6 +63,7 @@ Commit the folder `.c64-re-tools/knowledge/` of the project with git.
63
63
  | Write a macro | `macro inc16 --params dst --body-file inc16.asm` |
64
64
  | Write instructions as one use of a macro | `use '$1005-$100a' inc16 --args ptr` |
65
65
  | Do many writes as one revision | `apply .c64-re-tools/local/batch.json` |
66
+ | Check the batch of one agent | `join batch.json` |
66
67
  | Show the batches of parallel agents as one list of writes | `join a.json b.json` |
67
68
  | Write the batches of parallel agents as one revision | `join a.json b.json --apply` |
68
69
  | Read the history of an address or a name | `history '$2100'` |
@@ -235,7 +236,7 @@ When a git merge left conflicts in the knowledge, each read body also has `confl
235
236
  ### `releases`
236
237
 
237
238
  - `body.releases` lists the releases, the base release first. Each item has `label`, `base`, `define`, `file` and `sha256`. `define` is the assembler define that builds the release.
238
- - `file` is the path of the file of the release, and `sha256` is the SHA-256 of that file. Use them for the facts of a release, for example in a README. Do not calculate a SHA-256 yourself.
239
+ - `file` is the path of the program file of the release, and `sha256` is the SHA-256 of that file. For a release from the `image.json` of a capture, this file is the program file that the capture ran. This file can hold packed bytes, or a disk with more parts. Use them for the facts of a release, for example in a README. Do not calculate a SHA-256 yourself.
239
240
 
240
241
  ### `macros`
241
242
 
@@ -269,7 +270,8 @@ When a git merge left conflicts in the knowledge, each read body also has `confl
269
270
  - A line comment is a line of its own before its line, for example `; Draws the room.`.
270
271
  - The ACME line is the instruction with the names of its target. An operand expression of the knowledge replaces the operand. A table of addresses or words shows its values as `!word` lines, with the name of each target. A split table and the other bytes show as `!byte` lines.
271
272
  - The names are the names of the generated source. A platform name of a ROM shows only when the program uses that ROM. A line in the I/O area (`$D000-$DFFF`) gets no platform name, because that name is the name of the register and not of the RAM. A target inside a data region shows as `<name>+<offset>` only when a symbol is at the start of the region.
272
- - A range outside the program has no lines. Then the `hint` gives the ranges where the program has bytes.
273
+ - The lines show the bytes of the segments. When the knowledge has the entry state of a capture, the lines also show the bytes of the entry state at $0002-$03ff. The analyzers read the same bytes.
274
+ - A range outside these bytes has no lines. Then the `hint` gives the ranges that have bytes.
273
275
  - With `--code`, `lines` has only the instructions of the code regions and their line comments.
274
276
  - With `--out`, the text file has the lines, one on each line. `body.lines` is the number of lines, and the body has `out`, `bytes` and `sha256` of the text file.
275
277
  - Use `listing` in place of your own disassembler. To find the targets of a table, classify the table with its type. Then read its listing. Do not decode the bytes of a table yourself.
@@ -401,7 +403,7 @@ An operand expression tells the generated source how to write the operand of one
401
403
 
402
404
  ### `release <label>`
403
405
 
404
- - `body.release` gives the release, with its `define`, `file` and `sha256`. `body.bytes` gives the number of bytes of the file.
406
+ - `body.release` gives the release, with its `define`, `file` and `sha256`. `body.bytes` gives the number of bytes of the release.
405
407
  - See "Releases" of `<skill>/references/source-knowledge.md`.
406
408
 
407
409
  ### `unrelease <label>`
@@ -473,6 +475,7 @@ An operand expression tells the generated source how to write the operand of one
473
475
  ### `join <batch>...`
474
476
 
475
477
  - `join` joins the batches of agents that name the program at the same time. See "Batches of parallel agents" of `<skill>/references/batches.md`.
478
+ - `join` also takes one batch. Then `writes` shows the writes of that batch, and `join` checks the batch as it checks more batches.
476
479
  - Without `--apply`, `join` writes no knowledge. `body` holds `writes`, `repeated` and `choices`. `writes` lists the joined writes. `choices` lists each place where the batches gave different values, with the value that stays.
477
480
  - Examine `choices` and `writes`. `nextAction` is the same `join` with `--apply`. Run it when the choices agree with your task.
478
481
  - With `--apply`, `join` writes the joined writes as one revision, or nothing when the knowledge refuses one write. Then `body` holds `revision`, `writes`, `replaced`, `repeated` and `choices`, as for `apply`.
@@ -43,6 +43,7 @@ When more agents name the program at the same time, give each agent one range of
43
43
  `join` makes one list of writes from the batches:
44
44
 
45
45
  - At an address in the owner range of a batch, the name, the comment, the operand and the module of that batch stay. At an address that no batch owns, the first batch in the command stays.
46
- - A batch can give an address a name that `join` replaces. Then `join` also replaces that name in the operand expressions and macro arguments of that batch.
46
+ - A batch can give an address a name that `join` replaces. Then `join` also replaces that name in the operand expressions, the macro arguments, the patch code, the macro bodies and the comments of that batch. In a comment, `join` replaces only the full word. For example, a replaced `x_pos` does not change `x_pos_hi`.
47
+ - A name with no underscore, no digit and no capital letter after a small letter can be an English word, for example `score`. `join` does not replace this name in a comment, because the comment can use the word as text.
47
48
  - The regions of the owner come after the regions of the other batches. Thus the regions of the owner stay where they overlap.
48
49
  - A name from a batch stays when another batch removes the symbol at that address.
@@ -7,7 +7,7 @@ This file gives the rules of the releases, the switches, the patches, the macros
7
7
  A release is one version of the program, for example the original or a crack. Record each release with `release <label> --file <file>`.
8
8
 
9
9
  - A label is upper case, for example `FIRESTAR`, `TBC` or `V2`.
10
- - `--file` is a PRG or the `image.json` of a capture. The project knowledge keeps the bytes of the release, the path of the file and its SHA-256. After the write, the project does not need the file. A file can stay in `.c64-re-tools/local/`.
10
+ - `--file` is a PRG or the `image.json` of a capture. The project knowledge keeps the bytes of the release, and the path and the SHA-256 of the program file. For an `image.json`, the bytes come from the capture, and the program file is the file that the capture ran. After the write, the project does not need the file. A file can stay in `.c64-re-tools/local/`.
11
11
  - The base release is the release whose bytes are the program of the knowledge. Record it with `--base`. The script refuses `--base` when the segments or the bytes of the file are not the program.
12
12
  - A space has one base release. Record the base release before the first switch.
13
13
  - To change the bytes of a release, record the release again with its new file.
@@ -18,7 +18,7 @@ import { OPERAND_SELECTS, operandText, type OperandSelect } from "#src/knowledge
18
18
  import { historyAt, historyNamed, historyOfMacro, historyOfSwitch, revision, revisionCounts, revisionNote, revisions, type HistoryEntry } from "#src/knowledge/history.ts";
19
19
  import { joinBatches, type Batch, type JoinChoice, type JoinClash } from "#src/knowledge/join.ts";
20
20
  import { knowledgeNames } from "#src/knowledge/names.ts";
21
- import { addCoverage, coverageAccess, coverageRangeCounts, memoryRows, operandImages as programImages, programCoverage, programImage, releaseCode, requireProgram, setImage, type ImageRequest, type ProgramImage } from "#src/knowledge/program.ts";
21
+ import { addCoverage, coverageAccess, coverageRangeCounts, entryMemory, isProgram, memoryRows, operandImages as programImages, programCoverage, programImage, releaseCode, requireProgram, setImage, type ImageRequest, type ProgramImage } from "#src/knowledge/program.ts";
22
22
  import { coloursOfCapture, startScreenOfCapture, startScreenOfStage } from "#src/knowledge/start-screen.ts";
23
23
  import {
24
24
  at,
@@ -315,12 +315,13 @@ function byAddress<T extends { address: number }>(rows: readonly T[]): Map<numbe
315
315
 
316
316
  /**
317
317
  * The lookups of a listing of a range: the program and the coverage in the knowledge, the knowledge of the space and the platform names of the ROMs that the program uses.
318
+ * The lines show `memory`, the bytes that the analyzers read (entryMemory); a target outside the segments is named as c64-source names it.
318
319
  * The rows of the range are read once: a listing asks for each line.
319
320
  */
320
- function listingSource(db: DatabaseSync | undefined, image: ProgramImage, range: AddressRange): ListingSource {
321
+ function listingSource(db: DatabaseSync | undefined, image: ProgramImage, memory: Pick<ProgramImage, "segments" | "byteAt">, range: AddressRange): ListingSource {
321
322
  const space = image.space;
322
323
  const coverage = programCoverage(db, space)?.map;
323
- const byteAt = programBytes(image);
324
+ const byteAt = programBytes(memory);
324
325
  const platform = programPlatform(space, coverage, image.state);
325
326
  const entries = platform.filter((entry) => entry.end > entry.address);
326
327
  const secondNames = byAddress(listAnalyzerNames(db, range, undefined, undefined, space));
@@ -335,7 +336,7 @@ function listingSource(db: DatabaseSync | undefined, image: ProgramImage, range:
335
336
  }
336
337
  return {
337
338
  byteAt,
338
- entryStart: (at) => (byteAt(at) !== undefined ? undefined : entries.find((entry) => at > entry.address && at <= entry.end)?.address),
339
+ entryStart: (at) => (inRanges(image.segments, at) ? undefined : entries.find((entry) => at > entry.address && at <= entry.end)?.address),
339
340
  ...namesOf(db, space, platform),
340
341
  ...(space === DEFAULT_SPACE ? { io: IO_RAM } : {}),
341
342
  secondNames: (at) => (secondNames.get(at) ?? []).map((row) => row.name),
@@ -848,12 +849,14 @@ const READ_COMMANDS: CommandSpec[] = [
848
849
  (db, call) => {
849
850
  const range = call.parseRange(call.subject(0), "<range>");
850
851
  const image = requireProgram(db, call.space);
851
- const lines = listingLines(listing(listingSource(db, image, range), range.start, range.end, { code: call.flag("code") }));
852
+ const memory = entryMemory(image);
853
+ const lines = listingLines(listing(listingSource(db, image, memory, range), range.start, range.end, { code: call.flag("code") }));
852
854
  const out = call.string("out");
853
855
  const body = out !== undefined ? { lines: lines.length, ...writeReported(out, lines.map((line) => `${line}\n`).join(""), { what: "--out" }) } : { lines: list(call, lines, (line) => line, "a larger --max-listed, a smaller <range>, or --out <file> for all lines") };
854
- // A range outside the program has no lines: the hint names the segments that have them.
855
- if (image.segments.some((segment) => rangesOverlap(segment, range))) return body;
856
- return reply(body, { hint: `The range ${formatC64Range(range)} is outside the program. The program has bytes only in ${image.segments.map(formatC64Range).join(", ")}. Give a range in one of them.` });
856
+ // A range outside the program has no lines: the hint names the ranges that have them.
857
+ if (memory.segments.some((part) => rangesOverlap(part, range))) return body;
858
+ const held = `${memory.segments.map(formatC64Range).join(", ")}${memory.fromState.length === 0 ? "" : ` (the segments, and ${memory.fromState.map(formatC64Range).join(", ")} of the entry state)`}`;
859
+ return reply(body, { hint: `The range ${formatC64Range(range)} is outside the program. The program has bytes only in ${held}. Give a range in one of them.` });
857
860
  },
858
861
  ),
859
862
  ];
@@ -1025,7 +1028,7 @@ const WRITE_COMMANDS: CommandSpec[] = [
1025
1028
  writeCommand(
1026
1029
  {
1027
1030
  name: "release",
1028
- summary: "Records a release of the program from its PRG or the image.json of its capture: the knowledge keeps the bytes of the release, and the path and the SHA-256 of the file. The base release is the one whose bytes are the program of the knowledge.",
1031
+ summary: "Records a release of the program from its PRG or the image.json of its capture: the knowledge keeps the bytes of the release, and the path and the SHA-256 of the program file. For an image.json, the program file is the file that the capture ran. The base release is the one whose bytes are the program of the knowledge.",
1029
1032
  subjects: [{ name: "<label>", help: "the release label, for example FIRESTAR or V2" }],
1030
1033
  options: {
1031
1034
  file: { kind: "path", value: "<file>", help: "the PRG or image.json of the release. After the write, the knowledge does not need the file", required: true },
@@ -1039,23 +1042,19 @@ const WRITE_COMMANDS: CommandSpec[] = [
1039
1042
  const image = readImage(file);
1040
1043
  const commentText = call.string("comment");
1041
1044
  const base = call.flag("base");
1045
+ // The image.json of a capture names the program file that the capture ran: the release cites that file, as git ignores a capture in local/.
1046
+ const cited = image.program === undefined ? { file, sha256: sha256(readProjectFile(file).bytes) } : { file: knowledgePath(image.program.file, `The program of ${file}`), sha256: image.program.sha256 };
1042
1047
  // The base release has no bytes of its own: its bytes are the program.
1043
1048
  const request = {
1044
1049
  space: call.space,
1045
1050
  label: call.subject(0),
1046
- file,
1047
- sha256: sha256(readProjectFile(file).bytes),
1051
+ ...cited,
1048
1052
  ...(base ? { base } : { rows: memoryRows(image.segments, image.byteAt) }),
1049
1053
  ...(commentText === undefined ? {} : { comment: commentText }),
1050
1054
  };
1051
1055
  return (db) => {
1052
1056
  if (base) {
1053
- const program = requireProgram(db, call.space);
1054
- const same = JSON.stringify(program.segments) === JSON.stringify(image.segments) && program.segments.every((segment) => {
1055
- for (let address = segment.start; address <= segment.end; address++) if (program.byteAt(address) !== image.byteAt(address)) return false;
1056
- return true;
1057
- });
1058
- if (!same) throw new Refusal("invalid-input", `The bytes of ${file} are not the program of the knowledge. Give --base only to the release whose file image put into the knowledge.`);
1057
+ if (!isProgram(requireProgram(db, call.space), image)) throw new Refusal("invalid-input", `The bytes of ${file} are not the program of the knowledge. Give --base only to the release whose file image put into the knowledge.`);
1059
1058
  }
1060
1059
  const bytes = image.segments.reduce((sum, segment) => sum + segment.end - segment.start + 1, 0);
1061
1060
  return { ...shown(setRelease(db, context, request), "release", release), bytes };
@@ -1333,12 +1332,11 @@ const CHECKS: CommandSpec = {
1333
1332
  /** join: the batches of agents that worked in parallel, as one list of writes. With --apply, it writes them as one revision. */
1334
1333
  const JOIN: CommandSpec = {
1335
1334
  name: "join",
1336
- summary: "Joins the batches of agents that worked in parallel into one list of writes, and shows it. With --apply, it writes the list as one revision, or nothing when one write is refused.",
1335
+ summary: "Joins the batches of agents that worked in parallel into one list of writes, and shows it. One batch shows its own writes. With --apply, it writes the list as one revision, or nothing when one write is refused.",
1337
1336
  subjects: [{ name: "<batch>", help: 'a batch: a list of writes, or {"owner": {"start": "$1000", "end": "$1fff"}, "ops": [...]}', list: true }],
1338
1337
  options: { ...WRITE, apply: { kind: "flag", help: "write the joined writes to the project knowledge as one revision. Without it, the result only shows them" }, ...LIST },
1339
1338
  notes: "At an address in the owner range of a batch, its name, comment, operand and module win, and its regions come last. One name or one module file at two addresses writes nothing.",
1340
1339
  run: (call) => {
1341
- if (call.subjects.length < 2) throw new UsageError("join needs two or more batch files.");
1342
1340
  const batches: Batch[] = call.subjects.map((file) => {
1343
1341
  const value = readProjectJson(file);
1344
1342
  const shaped = Array.isArray(value) ? { ops: value } : (value as { owner?: unknown; ops?: unknown });
@@ -45,7 +45,7 @@ To get the command list, run the script with no arguments.
45
45
 
46
46
  - `compare` takes two or more releases. A release is one of these:
47
47
  - `knowledge`: the program in the project knowledge.
48
- - The label of a release in the project knowledge, for example `V2`. The base release is the program in the project knowledge. For another release, the project knowledge keeps only its bytes. Thus `--frames` cannot start it. To run that release, give its file. A label that is not a release gets error `not-found`, with the labels of the releases.
48
+ - The label of a release in the project knowledge, for example `V2`. The base release is the program in the project knowledge. For another release, the project knowledge keeps only its bytes. Thus `--frames` cannot start it. To run that release, give its PRG when the PRG holds the bytes of the release. Else, give the `image.json` of a capture of the release. The error tells you which file to give. A label that is not a release gets error `not-found`, with the labels of the releases.
49
49
  - A PRG file. The script puts it at its load address.
50
50
  - The `image.json` of a capture folder. Keep all files of the capture folder together. Without them, `--frames` cannot start the release.
51
51
  - Get a PRG out of a disk image before you compare it. The script refuses a disk image, a tape image and a cartridge image.
@@ -125,7 +125,7 @@ With `--shift`, the addresses of `segments`, `common` and `differences` are the
125
125
  With `--frames`, the body also holds:
126
126
 
127
127
  - `runtime` in each difference: one item for each release that started, by the number of the release. `start` and `end` are the addresses in the release, without the shift.
128
- - `first`: the first access in that release: `read`, `write`, `execute` or `none`. An instruction that reads and then writes the same byte, for example INC, counts as `read`. The operand bytes of an executed instruction count as `execute`, for example the `$03` of `LDA #$03`.
128
+ - `first`: the first access in that release: `read`, `write`, `execute` or `none`. An instruction that reads and then writes the same byte, for example INC, counts as `read`. A store counts as `write`, also an indexed store that first makes a dummy read of the byte, for example `STA ($06),Y`. The operand bytes of an executed instruction count as `execute`, for example the `$03` of `LDA #$03`. During a `press` step, no access stops the run. Thus a range that the program reads and writes during a `press` step counts as `read`.
129
129
  - `changed`: `true` when the bytes at the end of the run are not the bytes of the release.
130
130
  - `run`: `frames`, `steps` and `releases`. `releases` tells for each release, by its number, if it started, or the `reason` that it did not start. `skipped` tells that the releases have no differences, so no release ran.
131
131
 
@@ -2,14 +2,17 @@
2
2
  // runs in its own emulator, and each differing range gets its first access
3
3
  // (read, write, execute or none) and whether its bytes changed by the end.
4
4
  // Watchpoints and range breakpoints stop the run at an access; the coverage
5
- // map then tells which range and which access it was.
5
+ // map then tells which range and which access it was, and the CPU history
6
+ // tells which instruction made a read and a write.
6
7
 
7
8
  import { type AddressRange, COVERAGE, EXECUTE, instructionLength, READ, WRITE } from "#src/c64.ts";
9
+ import { isRefusal } from "#src/errors.ts";
8
10
  import { runProgram } from "#src/host-client/autostart.ts";
9
11
  import { readCoverage } from "#src/host-client/coverage.ts";
10
12
  import { startAtEntry, type EntryState } from "#src/host-client/entry-state.ts";
11
13
  import { runActionStep, type ActionStep } from "#src/host-client/steps.ts";
12
14
  import { knowledgeAt } from "#src/knowledge/names.ts";
15
+ import { isStore } from "#src/opcodes.ts";
13
16
  import { readProjectFile } from "#src/host-client/transfer.ts";
14
17
  import { readMemoryInParts, type ViceSessionClient } from "#src/host-client/vice-session.ts";
15
18
 
@@ -28,14 +31,31 @@ export type Start =
28
31
 
29
32
  const MAX_WATCH = 256;
30
33
 
31
- /** The first access that coverage flags show; a read-modify-write reads first. */
32
- export function accessOf(flags: number): FirstAccess {
34
+ /**
35
+ * The first access that coverage flags show. A read and a write at one stop
36
+ * are of the instruction that made the access (`opcode`, when the CPU history
37
+ * gives it): an indexed store makes a dummy read before its write, and a
38
+ * read-modify-write reads first. Without the instruction, the read is first.
39
+ */
40
+ export function accessOf(flags: number, opcode?: number): FirstAccess {
33
41
  if ((flags & EXECUTE) !== 0) return "execute";
42
+ if ((flags & READ) !== 0 && (flags & WRITE) !== 0 && opcode !== undefined && isStore(opcode)) return "write";
34
43
  if ((flags & READ) !== 0) return "read";
35
44
  if ((flags & WRITE) !== 0) return "write";
36
45
  return "none";
37
46
  }
38
47
 
48
+ /** The opcode of the last instruction in the CPU history, or undefined when the session gives no history (after a JAM, or none since a restore). */
49
+ async function lastOpcode(client: ViceSessionClient): Promise<number | undefined> {
50
+ try {
51
+ const [entry] = (await client.cpuHistory({ limit: 1, space: "c64" })).entries;
52
+ return entry === undefined ? undefined : Buffer.from(entry.bytes, "hex")[0];
53
+ } catch (error) {
54
+ if (isRefusal(error) && error.code === "operation-failed") return undefined;
55
+ throw error;
56
+ }
57
+ }
58
+
39
59
  /** Starts the release; returns why it did not start, or undefined. */
40
60
  async function start(client: ViceSessionClient, how: Start): Promise<string | undefined> {
41
61
  if (how.kind === "program") {
@@ -76,16 +96,30 @@ export async function watchRelease(
76
96
  points.set(index, ids);
77
97
  }
78
98
  await client.memmap({ action: "clear" });
99
+ /** Switches each point that has not settled on or off. */
100
+ const switchPoints = async (action: "enable" | "disable") => {
101
+ for (const ids of points.values()) {
102
+ for (const point of ids) {
103
+ if (point.kind === "watch") await client.watchpoint({ action, id: point.id });
104
+ else await client.breakpoint({ action, id: point.id });
105
+ }
106
+ }
107
+ };
79
108
 
80
109
  /**
81
110
  * After a stop: the ranges that the coverage shows accessed get their first
82
111
  * access, and lose their points. VICE marks only the opcode byte of an
83
112
  * executed instruction, so an instruction that starts up to two bytes before
84
- * a range, or in it, executes its operand bytes too.
113
+ * a range, or in it, executes its operand bytes too. A stop at a watchpoint
114
+ * comes after the instruction that made the access, so at a stop (`atPoint`)
115
+ * the last entry of the CPU history is that instruction. Each stop settles
116
+ * before the run goes on, so the flags of a range that has not settled are
117
+ * of the accesses since the last stop.
85
118
  */
86
- const settle = async (): Promise<boolean> => {
119
+ const settle = async (atPoint = true): Promise<boolean> => {
87
120
  const map = await readCoverage(client);
88
121
  let found = false;
122
+ let instruction: Promise<number | undefined> | undefined;
89
123
  for (const [index, ids] of points) {
90
124
  const range = ranges[index]!;
91
125
  let flags = 0;
@@ -98,7 +132,8 @@ export async function watchRelease(
98
132
  }
99
133
  }
100
134
  if (accessOf(flags) === "none") continue;
101
- first[index] = accessOf(flags);
135
+ const both = (flags & READ) !== 0 && (flags & WRITE) !== 0;
136
+ first[index] = accessOf(flags, atPoint && both ? await (instruction ??= lastOpcode(client)) : undefined);
102
137
  for (const point of ids) {
103
138
  if (point.kind === "watch") await client.watchpoint({ action: "remove", id: point.id });
104
139
  else await client.breakpoint({ action: "remove", id: point.id });
@@ -117,7 +152,9 @@ export async function watchRelease(
117
152
  while (left > 0 && guard-- > 0) {
118
153
  const ran = await client.execution({ action: "advance-frames", count: left, space: "c64" });
119
154
  left -= ran.advancedFrames ?? left;
120
- if (left > 0 && !(await settle())) left--;
155
+ // A stop at a point settles, also in the last frame.
156
+ const settled = ran.stopReason === "watchpoint" || ran.stopReason === "breakpoint" ? await settle() : false;
157
+ if (left > 0 && !settled) left--;
121
158
  }
122
159
  };
123
160
  const at = knowledgeAt();
@@ -135,10 +172,19 @@ export async function watchRelease(
135
172
  }
136
173
  continue;
137
174
  }
175
+ if ("press" in step) {
176
+ // A stop at a point ends the taps early and lets the keys go: the points are off for the taps, and the coverage of the taps gives the first access.
177
+ await switchPoints("disable");
178
+ await runActionStep(client, step, at);
179
+ await switchPoints("enable");
180
+ await settle(false);
181
+ continue;
182
+ }
183
+ // The other steps do not run the CPU.
138
184
  await runActionStep(client, step, at);
139
185
  }
140
186
  await runFrames(run.frames);
141
- if (points.size > 0) await settle();
187
+ if (points.size > 0) await settle(false);
142
188
 
143
189
  const accesses: RangeAccess[] = [];
144
190
  for (const [index, range] of ranges.entries()) {
@@ -11,7 +11,7 @@
11
11
  import { basename } from "node:path";
12
12
  import type { DatabaseSync } from "node:sqlite";
13
13
 
14
- import { type AddressRange, c64AddressOf, formatC64Address, formatC64Byte, formatC64Range, formatC64RangeFields, parseC64Address } from "#src/c64.ts";
14
+ import { type AddressRange, c64AddressOf, formatC64Address, formatC64Byte, formatC64Range, formatC64RangeFields, parseC64Address, prgOf } from "#src/c64.ts";
15
15
  import { Refusal } from "#src/errors.ts";
16
16
  import { parseEntryState, type EntryState } from "#src/host-client/entry-state.ts";
17
17
  import { readImage } from "#src/host-client/image.ts";
@@ -44,6 +44,7 @@ import {
44
44
  symbolSuppressed,
45
45
  } from "#src/knowledge/read.ts";
46
46
  import { CODE_REGION_TYPES, DEFAULT_SPACE, RELEASE_LABEL, SEMANTIC_ORIGINS } from "#src/knowledge/schema.ts";
47
+ import { sha256 } from "#src/knowledge/text.ts";
47
48
  import { platformAddresses } from "#src/platform.ts";
48
49
  import { decodeProgram, leftoverInput } from "#src/program-code.ts";
49
50
  import { projectRoot } from "#src/project.ts";
@@ -92,8 +93,14 @@ function labeledRelease(label: string): { image: ReleaseImage; noState: string }
92
93
  throw new Refusal("not-found", `There is no release ${label} in the project knowledge. ${known}`, { hint: `Give a release label, knowledge, or the path of a file. For a file with the name ${label}, give ./${label}.` });
93
94
  }
94
95
  if (release.base) return knowledgeProgram(db);
95
- const file = release.file === undefined ? "its file" : `its file ${release.file}`;
96
- return { image: releaseImage(db, label)!, noState: `The knowledge keeps only the bytes of the release ${label}, not its entry state. To run the release, give ${file} in place of ${label}.` };
96
+ const image = releaseImage(db, label)!;
97
+ // A PRG with the bytes of the release runs in its place. The program file that a capture ran holds other bytes, for example packed ones.
98
+ const [segment] = image.segments;
99
+ const runs = release.file !== undefined && image.segments.length === 1 && release.sha256 === sha256(prgOf(segment!.start, Uint8Array.from({ length: segment!.end - segment!.start + 1 }, (_, offset) => image.byteAt(segment!.start + offset))));
100
+ const remedy = runs
101
+ ? `give its file ${release.file} in place of ${label}`
102
+ : `capture the unpacked program${release.file === undefined ? "" : ` of ${release.file}`} with its entry state, and give the image.json of that capture in place of ${label}`;
103
+ return { image, noState: `The knowledge keeps only the bytes of the release ${label}, not its entry state. To run the release, ${remedy}.` };
97
104
  });
98
105
  }
99
106
 
@@ -438,7 +438,9 @@ export function layout(input: SourceInput): Layout {
438
438
  const use = (address: number, kind: UseKind) => {
439
439
  if (inImage(address)) {
440
440
  const table = tableStart(address);
441
- wanted.add(table ?? address);
441
+ // A table that starts outside the image is a constant: a label there has no line.
442
+ if (table !== undefined && !inImage(table)) count(table, kind);
443
+ else wanted.add(table ?? address);
442
444
  if (table !== undefined) insideEntry.set(address, table);
443
445
  } else if (symbols.has(address) || platform.has(address)) count(address, kind);
444
446
  else {
@@ -5,11 +5,21 @@
5
5
  // gives its two start vectors as entry points. A self-modified opcode is one that one run wrote
6
6
  // and executed, in either order, since a coverage file holds no order:
7
7
  // a copier's writes in one run and their execution in another do not count. A table's length is not known statically: entries
8
- // count while each target is a plausible instruction in the program.
8
+ // count while each target is a plausible instruction in the program. An RTS
9
+ // table ends before the low or the high bytes of another RTS dispatch start,
10
+ // but not one entry in: a table of one entry is no dispatch, so there the
11
+ // other dispatch reads the same table with an index one higher. An RTS table
12
+ // also ends before an entry that a run wrote when no run wrote its first
13
+ // entry: there the program holds other bytes than the dispatch reads. A JMP
14
+ // table ends before a JMP that a run wrote and no run executed, when no run
15
+ // executed a JMP of the table that a run wrote: the program wrote other bytes
16
+ // over it. A coverage map holds no order, so the writes of an unpacker or a
17
+ // copier, which write the whole table before its use, tell nothing.
9
18
  // The knowledge of the user and the LLM wins: an idiom gives no region, no
10
19
  // reference and no entry point where their region has another type or a
11
- // removal holds the bytes, and a table ends where their region ends. A $2c in
12
- // an instruction that a run executed is an operand, not a BIT.
20
+ // removal holds the bytes, and a table ends where their region ends. A BIT
21
+ // skip hides whole instructions in its 2 operand bytes: one of 2 bytes or two
22
+ // of 1 byte. A $2c in an instruction that a run executed is an operand, not a BIT.
13
23
 
14
24
  import { COVERAGE, instructionLength, type ReferenceKind } from "#src/c64.ts";
15
25
  import type { NormalizedFindings } from "#src/knowledge/import.ts";
@@ -118,6 +128,10 @@ export function findIdioms(byteAt: ImageByte, range: { start: number; end: numbe
118
128
  }
119
129
  return false;
120
130
  };
131
+ /** True when a run wrote the byte at the address; never without coverage. */
132
+ const written = (address: number) => coverage !== undefined && (coverage[address]! & COVERAGE.ramWrite) !== 0;
133
+ /** True when a run executed an instruction at the address; never without coverage. */
134
+ const executed = (address: number) => coverage !== undefined && (coverage[address]! & COVERAGE.ramExecute) !== 0;
121
135
  const regions: NormalizedFindings["regions"] = [];
122
136
  const references: NormalizedFindings["references"] = [];
123
137
  const entryPoints = new Set<number>();
@@ -145,54 +159,81 @@ export function findIdioms(byteAt: ImageByte, range: { start: number; end: numbe
145
159
  }
146
160
  }
147
161
 
162
+ // RTS dispatches: LDA high,X / PHA / LDA low,X / PHA / RTS. A table is data: it ends where the decided range at its start ends.
163
+ const dispatches: Array<{ rts: number; low: number; high: number }> = [];
148
164
  for (let at = range.start; at + 8 <= range.end; at++) {
149
- // RTS dispatch: LDA high,X / PHA / LDA low,X / PHA / RTS.
150
165
  if (LDA_INDEXED.has(byteAt(at)!) && byteAt(at + 3) === 0x48 && LDA_INDEXED.has(byteAt(at + 4)!) && byteAt(at + 7) === 0x48 && byteAt(at + 8) === 0x60) {
151
166
  const high = word(byteAt, at + 1)!;
152
167
  const low = word(byteAt, at + 5)!;
153
- const interleaved = high === low + 1;
154
- const step = interleaved ? 2 : 1;
155
- // A table is data: it ends where the decided range at its start ends.
156
- if (!fits(low, low, "bytes") || !fits(high, high, "bytes")) continue;
157
- const lowRange = decidedAt(low);
158
- const highRange = decidedAt(high);
159
- const targets: number[] = [];
160
- for (let index = 0; index < MAX_TABLE; index++) {
161
- if (decidedAt(low + index * step) !== lowRange || decidedAt(high + index * step) !== highRange) break;
162
- const lowByte = byteAt(low + index * step);
163
- const highByte = byteAt(high + index * step);
164
- if (lowByte === undefined || highByte === undefined) break;
165
- const target = ((highByte << 8) | lowByte) + 1;
166
- if (!plausible(byteAt, target, range)) break;
167
- targets.push(target);
168
- }
169
- if (targets.length === 0) continue;
170
- const n = targets.length;
171
- const parts: Parameters<typeof addRegions>[1] = interleaved
172
- ? [{ start: low, end: low + 2 * n - 1, type: "rts-addresses" }]
173
- : low + n === high
174
- ? [{ start: low, end: high + n - 1, type: "rts-addresses-split" }]
175
- : [{ start: low, end: low + n - 1, type: "bytes" }, { start: high, end: high + n - 1, type: "bytes" }];
176
- // Another dispatch through the same table: the table is recorded, and this RTS goes to its targets too.
177
- const known = parts.every((part) => regions.some((region) => region.start === part.start && region.end === part.end && region.type === part.type));
178
- if (!known) {
179
- if (!addRegions("rts-table", parts)) continue;
180
- counts.rtsTables++;
181
- }
182
- // A target in data of the user or the LLM, or a reference that they removed, gives no reference and no entry point.
183
- for (const target of targets) {
184
- const reference = { from: at + 8, to: target, kind: "jump" as const };
185
- if (!mayBeCode(target) || decided.removedReference(reference)) continue;
186
- references.push(reference);
187
- entryPoints.add(target);
188
- }
168
+ if (fits(low, low, "bytes") && fits(high, high, "bytes")) dispatches.push({ rts: at + 8, low, high });
169
+ }
170
+ }
171
+ /** The target of the entry with these bytes, or undefined when a byte is outside the program. */
172
+ const targetAt = (lowAt: number, highAt: number) => {
173
+ const lowByte = byteAt(lowAt);
174
+ const highByte = byteAt(highAt);
175
+ return lowByte === undefined || highByte === undefined ? undefined : ((highByte << 8) | lowByte) + 1;
176
+ };
177
+ // Where the low and the high bytes of each table start whose first entry is a plausible target: a table ends before one of them.
178
+ const tableStarts = new Set(dispatches.flatMap(({ low, high }) => {
179
+ const target = targetAt(low, high);
180
+ return target !== undefined && plausible(byteAt, target, range) ? [low, high] : [];
181
+ }));
182
+ // The lowest table first: a dispatch that reads it from a later entry then finds it recorded.
183
+ dispatches.sort((a, b) => a.low - b.low);
184
+ const rtsRegions: Array<{ start: number; end: number }> = [];
185
+ for (const { rts, low, high } of dispatches) {
186
+ const interleaved = high === low + 1;
187
+ const step = interleaved ? 2 : 1;
188
+ const lowRange = decidedAt(low);
189
+ const highRange = decidedAt(high);
190
+ // A run that wrote the first entry wrote the table before its use.
191
+ const writesTell = !written(low) && !written(high);
192
+ const targets: number[] = [];
193
+ for (let index = 0; index < MAX_TABLE; index++) {
194
+ const lowAt = low + index * step;
195
+ const highAt = high + index * step;
196
+ if (decidedAt(lowAt) !== lowRange || decidedAt(highAt) !== highRange) break;
197
+ if (index > 1 && (tableStarts.has(lowAt) || tableStarts.has(highAt))) break;
198
+ if (writesTell && (written(lowAt) || written(highAt))) break;
199
+ const target = targetAt(lowAt, highAt);
200
+ if (target === undefined || !plausible(byteAt, target, range)) break;
201
+ targets.push(target);
202
+ }
203
+ if (targets.length === 0) continue;
204
+ const n = targets.length;
205
+ const parts: Parameters<typeof addRegions>[1] = interleaved
206
+ ? [{ start: low, end: low + 2 * n - 1, type: "rts-addresses" }]
207
+ : low + n === high
208
+ ? [{ start: low, end: high + n - 1, type: "rts-addresses-split" }]
209
+ : [{ start: low, end: low + n - 1, type: "bytes" }, { start: high, end: high + n - 1, type: "bytes" }];
210
+ // Another dispatch through the same table, or from a later entry of it: the table is recorded, and this RTS goes to its targets too.
211
+ const known = parts.every((part) => rtsRegions.some((region) => region.start <= part.start && part.end <= region.end));
212
+ if (!known) {
213
+ if (!addRegions("rts-table", parts)) continue;
214
+ rtsRegions.push(...parts);
215
+ counts.rtsTables++;
216
+ }
217
+ // A target in data of the user or the LLM, or a reference that they removed, gives no reference and no entry point.
218
+ for (const target of targets) {
219
+ const reference = { from: rts, to: target, kind: "jump" as const };
220
+ if (!mayBeCode(target) || decided.removedReference(reference)) continue;
221
+ references.push(reference);
222
+ entryPoints.add(target);
189
223
  }
190
224
  }
191
225
 
192
226
  // JMP tables: at least three JMP abs in a row.
227
+ const writtenJmp = (jmp: number) => written(jmp) && written(jmp + 1) && written(jmp + 2);
193
228
  for (let at = range.start; at + 3 * MIN_JUMPS - 1 <= range.end; at++) {
194
229
  let n = 0;
195
230
  while (at + 3 * n + 2 <= range.end && byteAt(at + 3 * n) === 0x4c) n++;
231
+ // A JMP that a run wrote and then executed: the code that wrote the table put it there.
232
+ const jmps = Array.from({ length: n }, (_, index) => at + 3 * index);
233
+ if (!jmps.some((jmp) => writtenJmp(jmp) && executed(jmp))) {
234
+ const stale = jmps.findIndex((jmp) => writtenJmp(jmp) && !executed(jmp));
235
+ if (stale !== -1) n = stale;
236
+ }
196
237
  if (n < MIN_JUMPS) continue;
197
238
  // The JMPs inside the run are the same table: a run that is left out is left out once.
198
239
  const run = n;
@@ -210,15 +251,24 @@ export function findIdioms(byteAt: ImageByte, range: { start: number; end: numbe
210
251
  at += 3 * run - 1;
211
252
  }
212
253
 
213
- // BIT skips: BIT abs ($2c) whose operand bytes are an instruction that a JMP, a JSR or the coverage enters.
254
+ // BIT skips: BIT abs ($2c) whose operand bytes are whole instructions that a JMP, a JSR or the coverage enters.
214
255
  // A $2c in an executed instruction is its operand; the BIT is code and its operand bytes are dual-use.
256
+ /** True when the 2 operand bytes of the BIT at the address are one instruction of 2 bytes or two of 1 byte, with no JAM. */
257
+ const hidesInstructions = (bit: number) => {
258
+ let next = bit + 1;
259
+ while (next < bit + 3) {
260
+ if (!plausible(byteAt, next, range)) return false;
261
+ next += instructionLength(byteAt(next)!);
262
+ }
263
+ return next === bit + 3;
264
+ };
215
265
  const entered = new Set<number>();
216
266
  for (let at = range.start; at + 2 <= range.end; at++) {
217
267
  if (byteAt(at) === 0x4c || byteAt(at) === 0x20) entered.add(word(byteAt, at + 1)!);
218
268
  }
219
269
  if (coverage !== undefined) for (let address = range.start; address <= range.end; address++) if ((coverage[address]! & COVERAGE.ramExecute) !== 0) entered.add(address);
220
270
  for (let at = range.start; at + 2 <= range.end; at++) {
221
- if (byteAt(at) !== 0x2c || !entered.has(at + 1) || !plausible(byteAt, at + 1, range) || inExecutedOperand(at)) continue;
271
+ if (byteAt(at) !== 0x2c || !entered.has(at + 1) || !hidesInstructions(at) || inExecutedOperand(at)) continue;
222
272
  if (!fits(at, at, "code") || !fits(at + 1, at + 2, "dual-use")) continue;
223
273
  if (!addRegions("bit-skip", [{ start: at + 1, end: at + 2, type: "dual-use" }])) continue;
224
274
  counts.bitSkips++;
@@ -233,6 +233,7 @@ The script does the steps of the record file on the reference program. Then it w
233
233
  Do this for each result:
234
234
 
235
235
  - `PASS`: for a folder in `tests/recordings/`, `hint` tells you to commit the folder and to add its coverage map to the project knowledge as coverage. Git ignores `.c64-re-tools/local/`, thus the project knowledge must not name a file in it. For a folder there, `hint` tells you to record again with `--out tests/recordings/<name>`. `nextAction` replays the recording on the reference. Run it to make sure that the recording replays.
236
+ - `PASS`, and `hint` names a step that "ran before the program came to its entry", or tells that "the program did not come to its entry". The entry is the entry in the project knowledge, where the loader of a rebuild starts the program. Thus `replay` on a rebuild with a loader gives `INCONCLUSIVE`. A `replay` on the reference, or on a rebuild without a loader, can use the recording. For a rebuild with a loader, make the steps of the record file start after the entry. Make the session continue until the program runs from its entry. Then record the session again. The script examines the entry only when `symbols` of the record file is `knowledge` or `none`.
236
237
  - `PASS` with `evidence`: you recorded into the folder of an earlier recording. Put the new coverage map into the project knowledge as coverage, as `hint` tells. It replaces the map of the earlier recording. For another file in `evidence`, examine the facts of its revisions against the new recording.
237
238
  - `FAIL` after a cancel on the page: `hint` tells you to ask the user what to do. Do not record a session from steps in place of the session of the user.
238
239
  - Another `FAIL`: `reason` names the step that did not complete. Examples are a `runUntil` step that did not get to its target, and a `type` step with too many keys. Change the step, then run `record` again.