@henols/c64-re-tools 2.8.0-rc.2 → 2.8.0-rc.3

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.
Files changed (119) hide show
  1. package/package.json +1 -1
  2. package/skills/c64-assembler/SKILL.md +5 -2
  3. package/skills/c64-assembler/scripts/assembler.ts +55 -48
  4. package/skills/c64-disk/scripts/disk.ts +3 -3
  5. package/skills/c64-disk/scripts/lib/containers.ts +2 -2
  6. package/skills/c64-docs/SKILL.md +1 -1
  7. package/skills/c64-docs/scripts/docs.ts +12 -20
  8. package/skills/c64-docs/scripts/lib/links.ts +1 -1
  9. package/skills/c64-docs/scripts/lib/markdown.ts +1 -1
  10. package/skills/c64-docs/scripts/lib/reference.ts +59 -13
  11. package/skills/c64-knowledge/SKILL.md +17 -8
  12. package/skills/c64-knowledge/scripts/knowledge.ts +200 -218
  13. package/skills/c64-knowledge/scripts/lib/check.ts +2 -3
  14. package/skills/c64-knowledge/scripts/lib/listing.ts +56 -24
  15. package/skills/c64-packer/scripts/packer.ts +3 -3
  16. package/skills/c64-provenance/SKILL.md +25 -16
  17. package/skills/c64-provenance/scripts/lib/compare.ts +31 -21
  18. package/skills/c64-provenance/scripts/lib/leftovers.ts +17 -35
  19. package/skills/c64-provenance/scripts/lib/library.ts +10 -10
  20. package/skills/c64-provenance/scripts/lib/runtime.ts +3 -14
  21. package/skills/c64-provenance/scripts/provenance.ts +129 -98
  22. package/skills/c64-source/references/loader.md +2 -1
  23. package/skills/c64-source/scripts/lib/export.ts +54 -303
  24. package/skills/c64-source/scripts/lib/loader.ts +31 -51
  25. package/skills/c64-source/scripts/lib/source.ts +51 -41
  26. package/skills/c64-source/scripts/lib/stage.ts +9 -25
  27. package/skills/c64-source/scripts/source.ts +134 -294
  28. package/skills/c64-static-analysis/SKILL.md +10 -5
  29. package/skills/c64-static-analysis/scripts/lib/coverage.ts +1 -3
  30. package/skills/c64-static-analysis/scripts/lib/findings.ts +16 -3
  31. package/skills/c64-static-analysis/scripts/lib/idioms.ts +82 -10
  32. package/skills/c64-static-analysis/scripts/lib/triage.ts +112 -0
  33. package/skills/c64-static-analysis/scripts/static-analysis.ts +239 -147
  34. package/skills/c64-testing/SKILL.md +13 -7
  35. package/skills/c64-testing/scripts/lib/diff-files.ts +6 -13
  36. package/skills/c64-testing/scripts/lib/recording.ts +47 -66
  37. package/skills/c64-testing/scripts/lib/replay.ts +53 -9
  38. package/skills/c64-testing/scripts/lib/runs.ts +11 -29
  39. package/skills/c64-testing/scripts/lib/scenario.ts +30 -31
  40. package/skills/c64-testing/scripts/lib/start-screen.ts +42 -5
  41. package/skills/c64-testing/scripts/testing.ts +32 -7
  42. package/skills/c64-unpacker/SKILL.md +9 -7
  43. package/skills/c64-unpacker/scripts/lib/evidence.ts +23 -38
  44. package/skills/c64-unpacker/scripts/lib/loads.ts +24 -39
  45. package/skills/c64-unpacker/scripts/lib/machine.ts +38 -18
  46. package/skills/c64-unpacker/scripts/lib/stages.ts +124 -40
  47. package/skills/c64-unpacker/scripts/unpacker.ts +81 -68
  48. package/skills/emulator/SKILL.md +1 -0
  49. package/src/c64.ts +117 -10
  50. package/src/cli/ap-sdk.ts +1 -1
  51. package/src/cli/cleanup.ts +4 -2
  52. package/src/compare.ts +36 -16
  53. package/src/errors.ts +10 -1
  54. package/src/host/main.ts +2 -1
  55. package/src/host/server.ts +7 -11
  56. package/src/host/tools/c1541.ts +9 -3
  57. package/src/host/vice/adapter.ts +20 -43
  58. package/src/host/vice/binary-monitor.ts +22 -21
  59. package/src/host/vice/process.ts +31 -40
  60. package/src/host/vice/session.ts +187 -247
  61. package/src/host/vice/text-monitor.ts +3 -3
  62. package/src/host-client/autostart.ts +1 -1
  63. package/src/host-client/connect.ts +2 -1
  64. package/src/host-client/coverage.ts +0 -3
  65. package/src/host-client/entry-state.ts +4 -11
  66. package/src/host-client/image.ts +6 -11
  67. package/src/host-client/steps.ts +13 -113
  68. package/src/host-client/tools.ts +4 -4
  69. package/src/host-client/transfer.ts +10 -0
  70. package/src/host-client/vice-session.ts +10 -6
  71. package/src/knowledge/code-reach.ts +364 -0
  72. package/src/knowledge/conflicts.ts +34 -72
  73. package/src/knowledge/database.ts +40 -28
  74. package/src/knowledge/evidence.ts +2 -2
  75. package/src/knowledge/graph.ts +3 -3
  76. package/src/knowledge/history.ts +50 -90
  77. package/src/knowledge/import.ts +28 -68
  78. package/src/knowledge/join.ts +1 -1
  79. package/src/knowledge/names.ts +12 -7
  80. package/src/knowledge/program.ts +25 -46
  81. package/src/knowledge/read.ts +104 -100
  82. package/src/knowledge/schema.ts +9 -3
  83. package/src/knowledge/separate.ts +47 -19
  84. package/src/knowledge/start-screen.ts +7 -5
  85. package/src/knowledge/text.ts +56 -33
  86. package/src/knowledge/write.ts +274 -515
  87. package/src/loader.ts +7 -25
  88. package/src/mcp/inputs.ts +3 -3
  89. package/src/mcp/server.ts +19 -38
  90. package/src/mcp/session-source.ts +2 -1
  91. package/src/mcp/tools/debug.ts +97 -24
  92. package/src/mcp/tools/execution.ts +1 -1
  93. package/src/mcp/tools/input.ts +3 -3
  94. package/src/mcp/tools/machine.ts +3 -3
  95. package/src/mcp/tools/media.ts +4 -4
  96. package/src/mcp/tools/memory.ts +13 -17
  97. package/src/mcp/tools/video.ts +11 -25
  98. package/src/native/acme.ts +3 -3
  99. package/src/native/c64run.ts +2 -1
  100. package/src/native/decompiler/analyze.ts +10 -7
  101. package/src/native/decompiler/walk.ts +3 -4
  102. package/src/native/decompiler/wasm.ts +2 -2
  103. package/src/native/discover.ts +1 -1
  104. package/src/native/dxa.ts +9 -11
  105. package/src/native/exomizer.ts +1 -1
  106. package/src/native/processes.ts +4 -1
  107. package/src/native/run.ts +3 -3
  108. package/src/native/types.ts +5 -6
  109. package/src/opcodes.ts +3 -0
  110. package/src/platform.ts +9 -10
  111. package/src/program-code.ts +151 -0
  112. package/src/project.ts +8 -5
  113. package/src/protocol/framing.ts +51 -18
  114. package/src/protocol/messages.ts +1 -11
  115. package/src/protocol/tools.ts +0 -3
  116. package/src/protocol/vice.ts +588 -773
  117. package/src/script.ts +9 -14
  118. package/src/time.ts +1 -1
  119. package/src/trace.ts +3 -2
@@ -6,16 +6,16 @@
6
6
  // snapshot file, which a run can start from. No tool guesses where a load
7
7
  // ends: the steps decide.
8
8
 
9
- import { type AddressRange, COVERAGE, formatC64Address } from "#src/c64.ts";
9
+ import { type AddressRange, COVERAGE, formatC64Address, formatC64RangeFields, prgOf } from "#src/c64.ts";
10
10
  import { Refusal } from "#src/errors.ts";
11
11
  import { autostartLoaded, LOAD_LIMIT_FRAMES, RUN_LIMIT_FRAMES, typeRun } from "#src/host-client/autostart.ts";
12
12
  import { IO_RAM, markIoRamWrites, readCoverage } from "#src/host-client/coverage.ts";
13
- import { ACTION_STEP_KINDS, checkActionStep, checkStepNames, isObject, runActionStep, type ActionStep, type ActionStepKind } from "#src/host-client/steps.ts";
13
+ import { ACTION_STEP_KINDS, checkActionStep, checkStepNames, runActionStep, type ActionStep, type ActionStepKind } from "#src/host-client/steps.ts";
14
+ import { isObject } from "#src/host-client/tools.ts";
14
15
  import { knowledgeAt } from "#src/knowledge/names.ts";
15
- import { WireFailure } from "#src/host-client/tools.ts";
16
- import { readProjectFile, writeReported, type Written } from "#src/host-client/transfer.ts";
17
- import { ViceSessionClient } from "#src/host-client/vice-session.ts";
18
- import { entryStateFile, json, machineState, readRam, readyState, removeStaleFiles, vectorsOf } from "./machine.ts";
16
+ import { readProjectFile, readProjectJson, writeReported } from "#src/host-client/transfer.ts";
17
+ import { readMemoryInParts, ViceSessionClient } from "#src/host-client/vice-session.ts";
18
+ import { entryStateFile, machineState, readyState, vectorsOf, writeCapture } from "./machine.ts";
19
19
  import { FIRST_SEGMENT_ADDRESS } from "./stages.ts";
20
20
 
21
21
 
@@ -32,13 +32,7 @@ const KERNAL_KEY_WAIT = { start: 0xe5cd, end: 0xe5d5 };
32
32
 
33
33
  /** Reads and checks the steps file of loads: action steps with $ addresses, and capture and save steps with new names. */
34
34
  export function readLoadSteps(path: string): LoadStep[] {
35
- let value: unknown;
36
- try {
37
- value = JSON.parse(readProjectFile(path).bytes.toString("utf8"));
38
- } catch (error) {
39
- if (error instanceof WireFailure) throw error;
40
- throw new Refusal("invalid-input", `--steps ${path} is not JSON: ${(error as Error).message}`);
41
- }
35
+ const value = readProjectJson(path, (message) => `--steps ${path} is not JSON: ${message}`);
42
36
  const fail = (message: string): never => {
43
37
  throw new Refusal("invalid-input", `--steps ${path}: ${message}`);
44
38
  };
@@ -109,8 +103,6 @@ export function captureBlocks(before: Uint8Array, after: Uint8Array, map: Uint8A
109
103
  return changedBlocks(before, after, map, 16, writesKnown);
110
104
  }
111
105
 
112
- const hex4 = (value: number) => value.toString(16).padStart(4, "0");
113
-
114
106
  /**
115
107
  * Runs the program and its steps. Each capture step writes <out>/<name>/:
116
108
  * image.bin, image.json, entry_state.json, a PRG for each segment, and with
@@ -132,7 +124,7 @@ export async function loads(program: string, options: { out: string; steps: Load
132
124
  const { bytes } = readProjectFile(program);
133
125
  if (!(await autostartLoaded(client, program, bytes))) return { output: { loaded: false, reason: `The program was not in memory after ${LOAD_LIMIT_FRAMES} frames.`, captures: [] }, failed: true };
134
126
  // The RAM before RUN, without the program, so the first capture holds the program too.
135
- previous = await readRam(client, 0x0000, 0x10000);
127
+ previous = await readMemoryInParts(client, 0x0000, 0x10000, "ram");
136
128
  const load = bytes[0]! | (bytes[1]! << 8);
137
129
  previous.fill(0, load, Math.min(0x10000, load + bytes.length - 2));
138
130
  loadedProgram = bytes;
@@ -144,7 +136,7 @@ export async function loads(program: string, options: { out: string; steps: Load
144
136
  }
145
137
  } else {
146
138
  // A disk, tape or cartridge: VICE loads and starts it. The RAM test of the KERNAL puts back what it writes.
147
- previous = await readRam(client, 0x0000, 0x10000);
139
+ previous = await readMemoryInParts(client, 0x0000, 0x10000, "ram");
148
140
  await client.memmap({ action: "clear" });
149
141
  await client.autostart({ path: program, index: 0, run: true });
150
142
  writesKnown = false;
@@ -181,7 +173,7 @@ export async function loads(program: string, options: { out: string; steps: Load
181
173
  }
182
174
  if ((await client.status()).state === "running") await client.execution({ action: "pause", space: "c64" });
183
175
  const registers = await client.registersGet("c64");
184
- const memory = await readRam(client, 0x0000, 0x10000);
176
+ const memory = await readMemoryInParts(client, 0x0000, 0x10000, "ram");
185
177
  const map = await readCoverage(client);
186
178
  if (loadedProgram !== undefined) {
187
179
  // The PRG itself is part of the first capture.
@@ -195,37 +187,30 @@ export async function loads(program: string, options: { out: string; steps: Load
195
187
  const state = await machineState(client);
196
188
  const vectors = vectorsOf(state, memory);
197
189
  const directory = `${options.out}/${step.capture}`;
198
- const written: Written[] = [];
199
- const write = (name: string, bytes: Uint8Array) => written.push(writeReported(`${directory}/${name}`, bytes, { what: "--out" }));
200
- write("image.bin", memory);
201
- const files = segments.map((segment) => {
202
- const name = `segment-${hex4(segment.start)}-${hex4(segment.end)}.prg`;
203
- write(name, Buffer.concat([Buffer.from([segment.start & 0xff, segment.start >> 8]), memory.subarray(segment.start, segment.end + 1)]));
204
- return name;
205
- });
206
190
  let drive: Record<string, unknown> | undefined;
191
+ const other: Array<{ name: string; bytes: Uint8Array }> = [];
207
192
  if (options.drive) {
208
193
  const ram = Buffer.from((await client.memoryRead({ address: 0x0000, size: DRIVE_RAM, space: "drive8", view: "cpu" })).data, "hex");
209
- write("drive8.prg", Buffer.concat([Buffer.from([0x00, 0x00]), ram]));
194
+ other.push({ name: "drive8.prg", bytes: prgOf(0x0000, ram) });
210
195
  drive = { file: "drive8.prg", pc: formatC64Address((await client.registersGet("drive8")).pc), space: "drive8" };
211
196
  }
212
- const showRange = (range: { start: number; end: number }) => ({ start: formatC64Address(range.start), end: formatC64Address(range.end) });
213
- write(
214
- "image.json",
215
- json({
197
+ const entry = entryStateFile(registers, state, vectors, clean);
198
+ const { written, removed } = writeCapture(
199
+ directory,
200
+ memory,
201
+ segments,
202
+ other,
203
+ (files) => ({
216
204
  capture: step.capture,
217
205
  entry: formatC64Address(registers.pc),
218
- segments: segments.map((segment, at) => ({ ...showRange(segment), file: files[at] })),
219
- ...(options.exclude.length === 0 ? {} : { excluded: options.exclude.map(showRange) }),
206
+ segments: segments.map((segment, at) => ({ ...formatC64RangeFields(segment), file: files[at] })),
207
+ ...(options.exclude.length === 0 ? {} : { excluded: options.exclude.map(formatC64RangeFields) }),
220
208
  vectors,
221
209
  image: "image.bin",
222
210
  ...(drive === undefined ? {} : { drive }),
223
211
  }),
212
+ entry.bytes,
224
213
  );
225
- const entry = entryStateFile(registers, state, vectors, clean);
226
- write("entry_state.json", entry.bytes);
227
- // A capture again into the folder: the files of the earlier capture that image.json no longer lists go.
228
- const removed = removeStaleFiles(directory, [...files, ...(drive === undefined ? [] : ["drive8.prg"])]);
229
214
  const keyWait = registers.pc >= KERNAL_KEY_WAIT.start && registers.pc <= KERNAL_KEY_WAIT.end;
230
215
  captures.push({
231
216
  capture: step.capture,
@@ -234,8 +219,8 @@ export async function loads(program: string, options: { out: string; steps: Load
234
219
  ...(removed.length === 0 ? {} : { removed }),
235
220
  pc: formatC64Address(registers.pc),
236
221
  ...(keyWait ? { keyWait: true } : {}),
237
- segments: segments.map(showRange),
238
- ...(options.exclude.length === 0 ? {} : { excluded: options.exclude.map(showRange) }),
222
+ segments: segments.map(formatC64RangeFields),
223
+ ...(options.exclude.length === 0 ? {} : { excluded: options.exclude.map(formatC64RangeFields) }),
239
224
  differsFromReset: entry.differsFromReset,
240
225
  ...(small === 0 ? {} : { smallChanges: small }),
241
226
  ...(drive === undefined ? {} : { drive: drive.file }),
@@ -5,18 +5,16 @@
5
5
  import { readdirSync, rmSync } from "node:fs";
6
6
  import { join } from "node:path";
7
7
 
8
- import { formatC64Address } from "#src/c64.ts";
8
+ import { type AddressRange, formatC64Address, hexWord, prgOf } from "#src/c64.ts";
9
9
  import { resetToReady } from "#src/host-client/entry-state.ts";
10
- import { writeRefusal } from "#src/host-client/transfer.ts";
11
- import type { ViceSessionClient } from "#src/host-client/vice-session.ts";
10
+ import { writeRefusal, writeReported, type Written } from "#src/host-client/transfer.ts";
11
+ import { readMemoryInParts, type ViceSessionClient } from "#src/host-client/vice-session.ts";
12
12
  import { projectRoot, resolveProjectPath } from "#src/project.ts";
13
13
 
14
14
  type Registers = Awaited<ReturnType<ViceSessionClient["registersGet"]>>;
15
15
 
16
- const MAX_READ = 4096;
17
-
18
16
  /** The I/O areas of the entry state, read without side effects. The colour RAM is the colours of the screen: a start screen of a captured stage uses them. */
19
- export const IO_AREAS = { vic: [0xd000, 0x2f], sid: [0xd400, 0x1d], cia1: [0xdc00, 0x10], cia2: [0xdd00, 0x10], colour: [0xd800, 1000] } as const;
17
+ const IO_AREAS = { vic: [0xd000, 0x2f], sid: [0xd400, 0x1d], cia1: [0xdc00, 0x10], cia2: [0xdd00, 0x10], colour: [0xd800, 1000] } as const;
20
18
  /** The I/O areas of chips: what differsFrom compares. The colour RAM is the content of the screen, not the state of the machine. */
21
19
  const CHIP_AREAS = ["vic", "sid", "cia1", "cia2"] as const;
22
20
 
@@ -36,19 +34,10 @@ export interface MachineState {
36
34
  romVectors: Buffer;
37
35
  }
38
36
 
39
- /** Reads `size` bytes from `address` in the RAM view, in parts. */
40
- export async function readRam(client: ViceSessionClient, address: number, size: number): Promise<Buffer> {
41
- const parts: Buffer[] = [];
42
- for (let at = address; at < address + size; at += MAX_READ) {
43
- parts.push(Buffer.from((await client.memoryRead({ address: at, size: Math.min(MAX_READ, address + size - at), space: "c64", view: "ram" })).data, "hex"));
44
- }
45
- return Buffer.concat(parts);
46
- }
47
-
48
37
  /** The state the program finds at its entry: what a rebuild's loader must recreate. */
49
38
  export async function machineState(client: ViceSessionClient): Promise<MachineState> {
50
39
  const port = Buffer.from((await client.memoryRead({ address: 0x0000, size: 2, space: "c64", view: "cpu" })).data, "hex");
51
- const pages = await readRam(client, 0x0000, 0x400);
40
+ const pages = await readMemoryInParts(client, 0x0000, 0x400, "ram");
52
41
  const io = {} as Record<keyof typeof IO_AREAS, Buffer>;
53
42
  for (const [name, [address, size]] of Object.entries(IO_AREAS)) io[name as keyof typeof IO_AREAS] = Buffer.from((await client.ioRead(address, size)).data, "hex");
54
43
  // The colour RAM has 4 bits: a read gives other bits above them.
@@ -78,7 +67,7 @@ export async function readyState(client: ViceSessionClient): Promise<MachineStat
78
67
  }
79
68
 
80
69
  /** The bytes that differ from a clean machine: the CPU port, pages 0-3 from $0002, and the I/O areas. */
81
- export function differsFrom(state: MachineState, clean: MachineState): Array<{ address: string; entry: number; reset: number }> {
70
+ function differsFrom(state: MachineState, clean: MachineState): Array<{ address: string; entry: number; reset: number }> {
82
71
  const differs: Array<{ address: string; entry: number; reset: number }> = [];
83
72
  const compare = (base: number, entry: Buffer, reset: Buffer) => entry.forEach((value, offset) => value !== reset[offset] && differs.push({ address: formatC64Address(base + offset), entry: value, reset: reset[offset]! }));
84
73
  compare(0x0000, state.port, clean.port);
@@ -137,4 +126,35 @@ export function removeStaleFiles(folder: string, written: readonly string[]): st
137
126
  return removed.sort();
138
127
  }
139
128
 
140
- export const json = (value: unknown) => Buffer.from(`${JSON.stringify(value, null, 2)}\n`);
129
+ const json = (value: unknown) => Buffer.from(`${JSON.stringify(value, null, 2)}\n`);
130
+
131
+ /**
132
+ * Writes a capture into `folder` (a project path): image.bin with all of
133
+ * `memory`, a PRG for each segment, the other files, image.json (`image` of
134
+ * the names of the segment PRGs) and entry_state.json. Then removes the files
135
+ * of an earlier capture there that this one did not write. Gives the written
136
+ * files, the names of the segment PRGs and the removed files.
137
+ */
138
+ export function writeCapture(
139
+ folder: string,
140
+ memory: Buffer,
141
+ segments: readonly AddressRange[],
142
+ other: ReadonlyArray<{ name: string; bytes: Uint8Array }>,
143
+ image: (files: string[]) => Record<string, unknown>,
144
+ entryState: Buffer,
145
+ ): { written: Written[]; files: string[]; removed: string[] } {
146
+ const written: Written[] = [];
147
+ const write = (name: string, bytes: Uint8Array) => written.push(writeReported(`${folder}/${name}`, bytes, { what: "--out" }));
148
+ write("image.bin", memory);
149
+ const files = segments.map((segment) => {
150
+ const name = `segment-${hexWord(segment.start)}-${hexWord(segment.end)}.prg`;
151
+ write(name, prgOf(segment.start, memory.subarray(segment.start, segment.end + 1)));
152
+ return name;
153
+ });
154
+ for (const file of other) write(file.name, file.bytes);
155
+ write("image.json", json(image(files)));
156
+ write("entry_state.json", entryState);
157
+ // A capture again into the folder: the files of the earlier capture that image.json no longer lists go.
158
+ const removed = removeStaleFiles(folder, [...files, ...other.map((file) => file.name)]);
159
+ return { written, files, removed };
160
+ }
@@ -8,8 +8,8 @@
8
8
  // to the stage, is the stage's own code too: a packer hands off by JMP,
9
9
  // RTS or RTI and never runs its own code again.
10
10
 
11
- import { type AddressRange, COVERAGE } from "#src/c64.ts";
12
- import { writtenBlocks } from "#src/host-client/coverage.ts";
11
+ import { type AddressRange, COVERAGE, inRanges, rangesOverlap, subtract } from "#src/c64.ts";
12
+ import { IO_RAM, writtenBlocks } from "#src/host-client/coverage.ts";
13
13
 
14
14
  const contains = (range: AddressRange, address: number) => address >= range.start && address <= range.end;
15
15
 
@@ -60,11 +60,6 @@ export function stagePoints(blocks: readonly AddressRange[], own: ReadonlySet<nu
60
60
  return { exec, watch };
61
61
  }
62
62
 
63
- /** True when the address lies in one of the ranges. */
64
- export function inRanges(ranges: readonly AddressRange[], address: number): boolean {
65
- return ranges.some((range) => contains(range, address));
66
- }
67
-
68
63
  /**
69
64
  * Where a call returns to the stage: the return address on top of the
70
65
  * stack, when a JSR that the stage executed pushed it. `stack` is page 1.
@@ -96,37 +91,86 @@ export function executedIn(map: Uint8Array, block: AddressRange): AddressRange[]
96
91
  /** Pages 0-3 ($0000-$03ff) are in entry_state.json: a written block that is all in them is no segment. */
97
92
  export const FIRST_SEGMENT_ADDRESS = 0x0400;
98
93
 
94
+ /**
95
+ * The RAM that a program used after its entry, from the coverage map of a
96
+ * run from the entry: the RAM that it executed, and the RAM that it read and
97
+ * did not write. The map keeps no order, so a read of RAM that the run also
98
+ * wrote can be a read of the program's own value, not of a captured byte. In
99
+ * the I/O area, the map gives each access as an I/O access: an execution
100
+ * there is RAM code, but a read can be a chip register.
101
+ */
102
+ export function usedAfterEntry(map: Uint8Array): (address: number) => boolean {
103
+ return (address) => {
104
+ const flags = map[address]!;
105
+ if (address >= IO_RAM.start && address <= IO_RAM.end) return (flags & (COVERAGE.ramExecute | COVERAGE.ioExecute)) !== 0;
106
+ return (flags & COVERAGE.ramExecute) !== 0 || ((flags & COVERAGE.ramRead) !== 0 && (flags & COVERAGE.ramWrite) === 0);
107
+ };
108
+ }
109
+
110
+ type Stages = ReadonlyArray<{ entry: number; wrote: readonly AddressRange[] }>;
111
+ type WrittenBlock = AddressRange & { writtenBy: number };
112
+ type DroppedRange = WrittenBlock & { stageEntry: number };
113
+
114
+ /** A range cut at the bounds of the I/O area: the RAM there that a stage changed never joins the blocks on its two sides. */
115
+ function cutAtIoArea(range: AddressRange): AddressRange[] {
116
+ if (!rangesOverlap(range, IO_RAM)) return [range];
117
+ const inside = { start: Math.max(range.start, IO_RAM.start), end: Math.min(range.end, IO_RAM.end) };
118
+ return [...subtract(range, [IO_RAM]), inside].sort((a, b) => a.start - b.start);
119
+ }
120
+
121
+ /**
122
+ * The blocks that the stages wrote, each cut at the bounds of the I/O area,
123
+ * with the leftover rule. A block is a leftover when it holds the entry of an
124
+ * intermediate stage that started after the block's writer, and no write from
125
+ * that stage on replaced the code at that entry. Code that a stage ran before
126
+ * a later stage wrote over it never drops a block, and the block that holds
127
+ * the capture entry is never a leftover. A block that an intermediate stage
128
+ * wrote inside a leftover, for example a variable of the loader, is a leftover
129
+ * too. `stageEntry` of a leftover is the entry of the later stage that makes
130
+ * it one.
131
+ */
132
+ function stageBlocks(stages: Stages, entry: number): Array<WrittenBlock & { stageEntry?: number }> {
133
+ const last = stages.length - 1;
134
+ const replaced = (from: number, address: number) => stages.slice(from).some((stage) => inRanges(stage.wrote, address));
135
+ const laterEntry = (block: WrittenBlock) =>
136
+ contains(block, entry) ? undefined : stages.find((stage, index) => index > block.writtenBy && index < last && contains(block, stage.entry) && !replaced(index, stage.entry))?.entry;
137
+ const written = stages.flatMap((stage, index) => stage.wrote.flatMap(cutAtIoArea).map((range) => ({ start: range.start, end: range.end, writtenBy: index })));
138
+ const leftovers = written.flatMap((block) => {
139
+ const at = laterEntry(block);
140
+ return at === undefined ? [] : [{ ...block, at }];
141
+ });
142
+ const inLeftover = (block: WrittenBlock) =>
143
+ block.writtenBy < last && !contains(block, entry) ? leftovers.find((left) => block.start >= left.start && block.end <= left.end)?.at : undefined;
144
+ return written.map((block) => {
145
+ const at = laterEntry(block) ?? inLeftover(block);
146
+ return at === undefined ? block : { ...block, stageEntry: at };
147
+ });
148
+ }
149
+
99
150
  /**
100
151
  * The segments of a capture: the blocks that the stages wrote, without loader
101
- * leftovers and without blocks that are all in pages 0-3 (the entry state
102
- * holds them), joined into ranges that do not overlap or touch. A block
103
- * is a leftover when it holds the entry of an intermediate stage that started
104
- * after the block's writer, and no write from that stage on replaced the code
105
- * at that entry. Code that a stage ran before a later stage wrote over
106
- * it never drops a block, and the block that holds the capture entry is always
107
- * a segment. A block that an intermediate stage wrote inside a leftover, for
108
- * example a variable of the loader, is a leftover too. The filter comes before
109
- * the join: a join first would drop the program with a leftover. `writtenBy` is
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.
152
+ * leftovers (stageBlocks) and without blocks that are all in pages 0-3
153
+ * (the entry state holds them), joined into ranges that do not overlap or
154
+ * touch. The filter comes before the join: a join first would drop the
155
+ * program with a leftover. `used` tells the addresses that the program used
156
+ * after its entry: a part of a leftover that no later stage wrote is a segment
157
+ * when the program used an address in it, as a stage can copy code of the
158
+ * program into a leftover. `writtenBy` is the last stage that wrote into the
159
+ * range. When no written block holds the entry, the code there is as the
160
+ * program loaded it: `loaded`, the range of the PRG, is then a segment too
161
+ * (`loaded: true`), joined with the blocks that it overlaps or touches.
114
162
  */
115
163
  export function captureSegments(
116
- stages: ReadonlyArray<{ entry: number; wrote: readonly AddressRange[] }>,
164
+ stages: Stages,
117
165
  entry: number,
118
- loaded?: AddressRange,
166
+ options: { loaded?: AddressRange; used?: (address: number) => boolean } = {},
119
167
  ): Array<AddressRange & ({ writtenBy: number } | { loaded: true })> {
120
- const last = stages.length - 1;
121
- const replaced = (from: number, address: number) => stages.slice(from).some((stage) => inRanges(stage.wrote, address));
122
- const leftover = (block: AddressRange, writer: number) =>
123
- !contains(block, entry) && stages.some((stage, index) => index > writer && index < last && contains(block, stage.entry) && !replaced(index, stage.entry));
124
- const written = stages.flatMap((stage, index) => stage.wrote.map((range) => ({ start: range.start, end: range.end, writtenBy: index })));
125
- const leftovers = written.filter((block) => leftover(block, block.writtenBy));
126
- const inLeftover = (block: AddressRange & { writtenBy: number }) =>
127
- block.writtenBy < last && !contains(block, entry) && leftovers.some((left) => block.start >= left.start && block.end <= left.end);
128
- const blocks = written
129
- .filter((block) => !leftover(block, block.writtenBy) && !inLeftover(block) && (block.end >= FIRST_SEGMENT_ADDRESS || contains(block, entry)))
168
+ const { loaded, used } = options;
169
+ const written = stageBlocks(stages, entry);
170
+ const dropped = (block: { stageEntry?: number }) => block.stageEntry !== undefined;
171
+ const usedLeftovers = used === undefined ? [] : usedParts(written.filter(dropped), lastWriters(stages), used);
172
+ const blocks = [...written.filter((block) => !dropped(block)), ...usedLeftovers]
173
+ .filter((block) => block.end >= FIRST_SEGMENT_ADDRESS || contains(block, entry))
130
174
  .sort((a, b) => a.start - b.start);
131
175
  const segments: Array<AddressRange & { writtenBy: number }> = [];
132
176
  for (const block of blocks) {
@@ -147,14 +191,54 @@ export function captureSegments(
147
191
  return [...apart, joined].sort((a, b) => a.start - b.start);
148
192
  }
149
193
 
194
+ /**
195
+ * What a capture drops: the parts from FIRST_SEGMENT_ADDRESS on of the
196
+ * leftover blocks (stageBlocks) that no range of `kept`, the segments and
197
+ * the excluded ranges, holds. `writtenBy` is the stage that wrote the block,
198
+ * and `stageEntry` the entry of the later stage that makes it a leftover. A
199
+ * byte in the blocks of more than one stage is given once, with the first
200
+ * stage that wrote it.
201
+ */
202
+ export function droppedRanges(stages: Stages, entry: number, kept: readonly AddressRange[]): DroppedRange[] {
203
+ const parts: DroppedRange[] = [];
204
+ const given: AddressRange[] = [];
205
+ for (const block of stageBlocks(stages, entry)) {
206
+ if (block.stageEntry === undefined || block.end < FIRST_SEGMENT_ADDRESS) continue;
207
+ const range = { start: Math.max(block.start, FIRST_SEGMENT_ADDRESS), end: block.end };
208
+ for (const piece of subtract(range, [...kept, ...given])) parts.push({ ...piece, writtenBy: block.writtenBy, stageEntry: block.stageEntry });
209
+ given.push(range);
210
+ }
211
+ return parts.sort((a, b) => a.start - b.start);
212
+ }
213
+
214
+ /** For each address, the last stage that wrote it, or -1. */
215
+ function lastWriters(stages: ReadonlyArray<{ wrote: readonly AddressRange[] }>): Int8Array {
216
+ const writers = new Int8Array(0x10000).fill(-1);
217
+ stages.forEach((stage, index) => {
218
+ for (const range of stage.wrote) writers.fill(index, range.start, range.end + 1);
219
+ });
220
+ return writers;
221
+ }
222
+
223
+ /** The parts of the blocks that hold the bytes of their writer, each when the program used an address in it. */
224
+ function usedParts(blocks: ReadonlyArray<AddressRange & { writtenBy: number }>, writers: Int8Array, used: (address: number) => boolean): Array<AddressRange & { writtenBy: number }> {
225
+ const parts: Array<AddressRange & { writtenBy: number; used: boolean }> = [];
226
+ for (const block of blocks) {
227
+ let part: (AddressRange & { writtenBy: number; used: boolean }) | undefined;
228
+ for (let address = block.start; address <= block.end; address++) {
229
+ if (writers[address] !== block.writtenBy) {
230
+ part = undefined;
231
+ continue;
232
+ }
233
+ if (part === undefined) parts.push((part = { start: address, end: address, writtenBy: block.writtenBy, used: false }));
234
+ part.end = address;
235
+ part.used ||= used(address);
236
+ }
237
+ }
238
+ return parts.filter((part) => part.used).map(({ start, end, writtenBy }) => ({ start, end, writtenBy }));
239
+ }
240
+
150
241
  /** The segments without the bytes of `holes`: a segment that a hole cuts gives its parts, each with the fields of the segment. */
151
242
  export function withoutRanges<T extends AddressRange>(segments: readonly T[], holes: readonly AddressRange[]): T[] {
152
- let pieces = [...segments];
153
- for (const hole of holes) {
154
- pieces = pieces.flatMap((piece) => {
155
- if (hole.end < piece.start || hole.start > piece.end) return [piece];
156
- return [...(hole.start > piece.start ? [{ ...piece, end: hole.start - 1 }] : []), ...(hole.end < piece.end ? [{ ...piece, start: hole.end + 1 }] : [])];
157
- });
158
- }
159
- return pieces;
243
+ return segments.flatMap((segment) => subtract(segment, holes).map((piece) => ({ ...segment, ...piece })));
160
244
  }