@henols/c64-re-tools 2.6.0-rc.2 → 2.6.0-rc.20

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 (107) hide show
  1. package/package.json +2 -2
  2. package/skills/c64-assembler/SKILL.md +28 -14
  3. package/skills/c64-assembler/scripts/assembler.ts +28 -15
  4. package/skills/c64-development/SKILL.md +4 -4
  5. package/skills/c64-docs/SKILL.md +9 -7
  6. package/skills/c64-docs/scripts/docs.ts +24 -11
  7. package/skills/c64-docs/scripts/lib/reference.ts +119 -33
  8. package/skills/c64-docs/scripts/lib/source-map.ts +23 -4
  9. package/skills/c64-knowledge/SKILL.md +67 -42
  10. package/skills/c64-knowledge/scripts/knowledge.ts +90 -67
  11. package/skills/c64-knowledge/scripts/lib/listing.ts +18 -3
  12. package/skills/c64-packer/SKILL.md +1 -1
  13. package/skills/c64-provenance/SKILL.md +11 -10
  14. package/skills/c64-provenance/scripts/lib/library.ts +16 -16
  15. package/skills/c64-provenance/scripts/provenance.ts +33 -23
  16. package/skills/c64-reverse-engineering/SKILL.md +17 -11
  17. package/skills/c64-source/SKILL.md +71 -47
  18. package/skills/c64-source/scripts/lib/export.ts +89 -34
  19. package/skills/c64-source/scripts/lib/loader.ts +79 -36
  20. package/skills/c64-source/scripts/lib/source.ts +38 -32
  21. package/skills/c64-source/scripts/lib/stage.ts +11 -5
  22. package/skills/c64-source/scripts/lib/start-screen.asm +4 -2
  23. package/skills/c64-source/scripts/source.ts +278 -145
  24. package/skills/c64-static-analysis/SKILL.md +29 -25
  25. package/skills/c64-static-analysis/scripts/lib/coverage.ts +2 -25
  26. package/skills/c64-static-analysis/scripts/lib/findings.ts +11 -11
  27. package/skills/c64-static-analysis/scripts/lib/instructions.ts +26 -24
  28. package/skills/c64-static-analysis/scripts/lib/macros.ts +3 -1
  29. package/skills/c64-static-analysis/scripts/static-analysis.ts +69 -67
  30. package/skills/c64-testing/SKILL.md +15 -5
  31. package/skills/c64-testing/references/recording-format.md +26 -5
  32. package/skills/c64-testing/references/scenario-format.md +11 -8
  33. package/skills/c64-testing/scripts/lib/diff-files.ts +4 -18
  34. package/skills/c64-testing/scripts/lib/play.ts +39 -41
  35. package/skills/c64-testing/scripts/lib/recording.ts +220 -46
  36. package/skills/c64-testing/scripts/lib/replay.ts +32 -6
  37. package/skills/c64-testing/scripts/lib/runs.ts +8 -3
  38. package/skills/c64-testing/scripts/lib/scenario.ts +18 -11
  39. package/skills/c64-testing/scripts/testing.ts +23 -2
  40. package/skills/c64-unpacker/SKILL.md +10 -5
  41. package/skills/c64-unpacker/scripts/lib/loads.ts +34 -13
  42. package/skills/c64-unpacker/scripts/lib/machine.ts +7 -3
  43. package/skills/c64-unpacker/scripts/lib/stages.ts +18 -3
  44. package/skills/c64-unpacker/scripts/unpacker.ts +43 -9
  45. package/skills/emulator/SKILL.md +7 -12
  46. package/src/build-name.ts +55 -0
  47. package/src/c64-keys.ts +98 -0
  48. package/src/c64.ts +22 -2
  49. package/src/cli/main.ts +3 -29
  50. package/src/host/main.ts +3 -3
  51. package/src/host/server.ts +3 -1
  52. package/src/host/tools/index.ts +2 -7
  53. package/src/host/vice/process.ts +34 -17
  54. package/src/host/vice/session.ts +138 -31
  55. package/src/host-client/steps.ts +21 -18
  56. package/src/host-client/tools.ts +2 -7
  57. package/src/host-client/vice-session.ts +7 -1
  58. package/src/knowledge/evidence.ts +66 -0
  59. package/src/knowledge/history.ts +5 -5
  60. package/src/knowledge/import.ts +12 -5
  61. package/src/knowledge/program.ts +123 -32
  62. package/src/knowledge/read.ts +36 -13
  63. package/src/knowledge/schema.ts +43 -17
  64. package/src/knowledge/start-screen.ts +70 -0
  65. package/src/knowledge/text.ts +33 -5
  66. package/src/knowledge/write.ts +75 -36
  67. package/src/mcp/inputs.ts +12 -0
  68. package/src/mcp/server.ts +1 -1
  69. package/src/mcp/tools/debug.ts +23 -21
  70. package/src/mcp/tools/input.ts +38 -5
  71. package/src/mcp/tools/machine.ts +3 -42
  72. package/src/mcp/tools/media.ts +1 -1
  73. package/src/mcp/tools/memory.ts +12 -9
  74. package/src/native/acme.ts +1 -1
  75. package/src/native/c64run.ts +7 -4
  76. package/src/native/decompiler/analyze.ts +98 -0
  77. package/src/native/decompiler/c64rt-wasm.ts +4 -0
  78. package/src/native/decompiler/language/c64rt_6510.sla +0 -0
  79. package/src/native/{ghidra → decompiler}/language/c64rt_6510.slaspec +1 -1
  80. package/src/native/decompiler/pcode.ts +222 -0
  81. package/src/native/decompiler/walk.ts +205 -0
  82. package/src/native/decompiler/wasm.ts +98 -0
  83. package/src/native/discover.ts +3 -3
  84. package/src/native/dxa.ts +12 -1
  85. package/src/native/processes.ts +4 -4
  86. package/src/native/types.ts +27 -27
  87. package/src/opcodes.ts +1 -1
  88. package/src/platform.ts +30 -1
  89. package/src/project.ts +17 -4
  90. package/src/protocol/tools.ts +1 -45
  91. package/src/protocol/vice.ts +47 -0
  92. package/src/reference-pages.ts +64 -0
  93. package/src/script.ts +4 -4
  94. package/src/vsf.ts +98 -0
  95. package/tools/c64run.c +158 -15
  96. package/tools/install-container.sh +1 -2
  97. package/src/cli/status.ts +0 -127
  98. package/src/host/tools/status.ts +0 -47
  99. package/src/native/ghidra/analyze.ts +0 -87
  100. package/src/native/ghidra/index.ts +0 -170
  101. package/src/native/ghidra/scripts/C64Export.java +0 -274
  102. package/src/native/ghidra/scripts/C64Prepare.java +0 -66
  103. package/src/native/status.ts +0 -135
  104. package/tools/install-ghidra.sh +0 -40
  105. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.cspec +0 -0
  106. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.ldefs +0 -0
  107. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.pspec +0 -0
@@ -9,11 +9,13 @@ import { createHash } from "node:crypto";
9
9
  import { isRefusal, Refusal } from "#src/errors.ts";
10
10
  import { readPrg } from "#src/host-client/image.ts";
11
11
  import { readProjectFile, writeReported, type Written } from "#src/host-client/transfer.ts";
12
+ import { formatC64Address } from "#src/c64.ts";
13
+ import { LOADER_JUMP } from "#src/knowledge/start-screen.ts";
12
14
  import { C64RunSession } from "#src/native/c64run.ts";
13
15
  import { localToolContext } from "#src/native/local.ts";
14
16
  import { Workspace } from "#src/native/staging.ts";
15
17
  import { UsageError } from "#src/script.ts";
16
- import { firstDifference, parseStateItem, pinLines, readRecording, replaySide, siteMap, type Comparison, type ReplayResult, type ReplaySubject } from "./recording.ts";
18
+ import { firstDifference, loaderEntry, mover, parseStateItem, pinLines, readRecording, replaySide, siteMap, type Comparison, type ReplayResult, type ReplaySubject } from "./recording.ts";
17
19
  import { namesOf } from "./scenario.ts";
18
20
 
19
21
  const MAX_STATE_ITEMS = 16;
@@ -69,8 +71,16 @@ export async function replay(values: ReplayOptions): Promise<ReplayResult> {
69
71
  const originalSymbols = recording.symbols === "none" ? "knowledge" : recording.symbols;
70
72
  const original: ReplaySubject = { side: "original", program: recording.program, symbols: originalSymbols };
71
73
  const side = (subject: ReplaySubject, options: Parameters<typeof replaySide>[5]) => replaySide(core, recording, folder, subject, workspace, options);
74
+ const rebuildSymbols = values.symbols ?? originalSymbols;
75
+ // A rebuild with a generated loader starts the program where its loader jumps to. The original comes to that entry by the same name.
76
+ let loader: { entry: number; original: number } | undefined;
77
+ if (values.rebuild !== undefined && !recording.load && namesOf(rebuildSymbols).has(LOADER_JUMP)) {
78
+ const entry = await loaderEntry(core, recording, { side: "rebuild", program: values.rebuild, symbols: rebuildSymbols });
79
+ if (typeof entry === "string") return result("FAIL", "rebuild", { reason: entry });
80
+ loader = { entry, original: mover(namesOf(rebuildSymbols, "code"), namesOf(originalSymbols, "code"))(entry) };
81
+ }
72
82
  // The self-check: the original ends the session with the recorded state, to the cycle.
73
- const self = await side(original, { ...(compare === undefined ? {} : { compare }) });
83
+ const self = await side(original, { ...(compare === undefined ? {} : { compare }), ...(loader === undefined ? {} : { entry: loader.original }) });
74
84
  if (self.problem !== undefined) return result("INCONCLUSIVE", "original", { reason: `the recording does not reproduce on the original: ${self.problem}` });
75
85
  if (self.unknown > 0 || self.misses > 0) {
76
86
  return result("INCONCLUSIVE", "original", { reason: `the recording does not reproduce on the original: ${self.unknown + self.misses} input reads had no recorded value; record the session again with this version of the toolkit` });
@@ -81,8 +91,21 @@ export async function replay(values: ReplayOptions): Promise<ReplayResult> {
81
91
  const expected = self.samples;
82
92
  if (compare !== undefined && expected.length === 0) return result("INCONCLUSIVE", "original", { reason: `the original never came to the checkpoint ${compare.checkpoint} in the session` });
83
93
  if (values.rebuild === undefined) return result("PASS", "original", { checkpoints: expected.length });
94
+ let handover: { entry: number; original: NonNullable<typeof self.entryPoint> } | undefined;
95
+ if (loader !== undefined) {
96
+ const entered = self.entryPoint;
97
+ const at = formatC64Address(loader.original);
98
+ if (entered === undefined) return result("INCONCLUSIVE", "original", { reason: `the original never came to ${at}, where the loader of the rebuild jumps` });
99
+ // An event before the entry has no point in a rebuild with a loader. A runUntil to an address there does nothing, and the rebuild leaves it out.
100
+ const early = recording.events.slice(0, entered.eventsBefore).find((event) => !("pc" in event.key));
101
+ if (early !== undefined) {
102
+ const what = early.step === undefined ? "the RESTORE of the play" : `step ${early.step}`;
103
+ return result("INCONCLUSIVE", "original", { reason: `${what} ran before the program came to its entry ${at}. A rebuild with a loader has no point for it. Make the steps of the record file start after the entry` });
104
+ }
105
+ handover = { entry: loader.entry, original: entered };
106
+ }
84
107
 
85
- const rebuild: ReplaySubject = { side: "rebuild", program: values.rebuild, symbols: values.symbols ?? originalSymbols };
108
+ const rebuild: ReplaySubject = { side: "rebuild", program: values.rebuild, symbols: rebuildSymbols };
86
109
  let movedSites: number;
87
110
  try {
88
111
  movedSites = siteMap(recording.sites, namesOf(originalSymbols, "code"), namesOf(rebuild.symbols, "code")).length;
@@ -90,10 +113,10 @@ export async function replay(values: ReplayOptions): Promise<ReplayResult> {
90
113
  throw new UsageError(`--symbols ${rebuild.symbols}: ${(error as Error).message}`);
91
114
  }
92
115
  const pins = pinLines(expected, compare!.state);
93
- const replayed = await side(rebuild, { compare: compare!, stop: expected.length, pins });
116
+ const replayed = await side(rebuild, { compare: compare!, stop: expected.length, pins, ...(handover === undefined ? {} : { handover }) });
94
117
  const difference = firstDifference(expected, replayed.samples, compare!.state);
95
118
  // A read that the recording has no value for gets the idle value: it is in the result, never silent.
96
- const base = { checkpoints: expected.length, movedSites, ...(replayed.unknown > 0 ? { idleReads: replayed.unknown } : {}) };
119
+ const base = { checkpoints: expected.length, movedSites, ...(replayed.startScreenSkipped === true ? { startScreen: "skipped" } : {}), ...(replayed.unknown > 0 ? { idleReads: replayed.unknown } : {}) };
97
120
  if (difference === undefined && replayed.samples.length >= expected.length) return result("PASS", "rebuild", { ...base, compared: expected.length });
98
121
  const reason =
99
122
  difference !== undefined
@@ -103,7 +126,9 @@ export async function replay(values: ReplayOptions): Promise<ReplayResult> {
103
126
  if (values.out !== undefined && difference !== undefined) {
104
127
  const files: Written[] = [];
105
128
  for (const subject of [original, rebuild]) {
106
- const dumped = await side(subject, { compare: compare!, dump: difference.checkpoint, ...(subject.side === "rebuild" ? { pins } : {}) });
129
+ // The original also stops at the checkpoints before its entry, which its samples leave out.
130
+ const dump = difference.checkpoint + (subject.side === "original" ? (handover?.original.samplesBefore ?? 0) : 0);
131
+ const dumped = await side(subject, { compare: compare!, dump, ...(subject.side === "rebuild" ? { pins, ...(handover === undefined ? {} : { handover }) } : {}) });
107
132
  files.push(writeReported(`${values.out}/${subject.side}-${difference.checkpoint}.bin`, dumped.ram!, { what: "--out" }));
108
133
  }
109
134
  failed.files = files;
@@ -114,3 +139,4 @@ export async function replay(values: ReplayOptions): Promise<ReplayResult> {
114
139
  workspace.remove();
115
140
  }
116
141
  }
142
+
@@ -9,7 +9,7 @@ import { screenText } from "#src/graphics.ts";
9
9
  import { runProgram } from "#src/host-client/autostart.ts";
10
10
  import { isRefusal, Refusal } from "#src/errors.ts";
11
11
  import { readCoverage } from "#src/host-client/coverage.ts";
12
- import { ACTION_STEP_KINDS, checkActionStep, checkLocation, checkStepNames, isInteger, isObject, refuseOldStep, renamedField, runActionStep, VICE_STEP_KINDS, type ActionStep, type ActionStepKind } from "#src/host-client/steps.ts";
12
+ import { ACTION_STEP_KINDS, aStep, checkActionStep, checkLocation, checkStepNames, isInteger, isObject, refuseOldStep, renamedField, runActionStep, type ActionStep, type ActionStepKind } from "#src/host-client/steps.ts";
13
13
  import { readPrg } from "#src/host-client/image.ts";
14
14
  import { MAX_MEMORY_READ, MAX_TRACE_FRAMES, MAX_TRACE_HITS, MAX_TRACE_POINTS, TRACE_KINDS, WireFailure, type TraceHit, type TraceKind } from "#src/host-client/tools.ts";
15
15
  import { readProjectFile, writeReported, type Written } from "#src/host-client/transfer.ts";
@@ -61,6 +61,11 @@ const RUN_FIELDS = "A run file has name, start and steps, and optionally symbols
61
61
  const START_FORMS = '{ "program": "<file.prg>" }, { "program": "<file.prg>", "load": true } or { "snapshot": "<file.vsf>" }';
62
62
  const TRACE_KEYS = ["trace", "points", "frames", "maxHits"];
63
63
  const OBSERVE_KEYS = ["observe", "memory", "registers", "vicii", "sprites"];
64
+ /** The fix for a key that the same step of a scenario has, or none. */
65
+ function scenarioKeyFix(key: string, step: Record<string, unknown>): string {
66
+ if (key === "screen" && "observe" in step) return `. A run writes the screen with its own step: {"screen": "${typeof step.observe === "string" ? step.observe : "<name>"}"}`;
67
+ return key === "side" ? ". A run has one program. Remove side" : "";
68
+ }
64
69
  const EXPECT_KEYS = ["expect", "memory", "registers"];
65
70
  const EXPECTED_MEMORY_KEYS = ["address", "data", "text", "mask", "view"];
66
71
  /** The characters that screenText gives for the screen codes 0 to 63; a graphics code gives a dot. */
@@ -131,11 +136,11 @@ function readRun(path: string): Run {
131
136
  if (!isObject(step)) return fail(`${at} must be an object`);
132
137
  const kinds = "observe" in step ? ["observe"] : "expect" in step ? ["expect"] : "trace" in step ? ["trace"] : Object.keys(step).filter((key) => (ACTION_STEP_KINDS as readonly string[]).includes(key) || (OWN_KINDS as readonly string[]).includes(key));
133
138
  if (kinds.length > 1) return fail(`${at} has ${kinds.length} step kinds: ${kinds.join(", ")}. Give each one its own step`);
134
- if (kinds.length !== 1) return fail(`${at} must have exactly one of ${[...VICE_STEP_KINDS, ...OWN_KINDS].join(", ")}`);
139
+ if (kinds.length !== 1) return fail(`${at} must have exactly one of ${[...ACTION_STEP_KINDS, ...OWN_KINDS].join(", ")}`);
135
140
  const kind = kinds[0]!;
136
141
  refuseOldStep(kind, step, at, fail);
137
142
  const allowed = kind === "observe" ? OBSERVE_KEYS : kind === "expect" ? EXPECT_KEYS : kind === "trace" ? TRACE_KEYS : [kind];
138
- for (const key of Object.keys(step)) if (!allowed.includes(key)) fail(`${at} has the key ${key}, which a ${kind} step does not have`);
143
+ for (const key of Object.keys(step)) if (!allowed.includes(key)) fail(`${at} has the key ${key}, which ${aStep(kind)} of a run does not have${scenarioKeyFix(key, step)}`);
139
144
  if ((ACTION_STEP_KINDS as readonly string[]).includes(kind)) {
140
145
  // The step with its defaults filled in, as the shared schema of the action steps gives it.
141
146
  (value.steps as unknown[])[index] = checkActionStep(kind as ActionStepKind, step, at, fail);
@@ -7,7 +7,7 @@ import { isRefusal, Refusal } from "#src/errors.ts";
7
7
  import { c64AddressOf, formatC64Address, formatSprite, formatVicii, parseC64Address } from "#src/c64.ts";
8
8
  import { MAX_BASELINES, MAX_MASK_RECTANGLES, maskCoversFrame, WireFailure } from "#src/host-client/tools.ts";
9
9
  import { LOAD_LIMIT_FRAMES, RUN_LIMIT_FRAMES, runProgram } from "#src/host-client/autostart.ts";
10
- import { ACTION_STEP_KINDS, checkActionStep, checkLocation, isInteger, isObject, refuseOldStep, renamedField, runActionStep, VICE_STEP_KINDS, type ActionStep, type ActionStepKind, type Location } from "#src/host-client/steps.ts";
10
+ import { ACTION_STEP_KINDS, aStep, checkActionStep, checkLocation, isInteger, isObject, refuseOldStep, renamedField, runActionStep, type ActionStep, type ActionStepKind, type Location } from "#src/host-client/steps.ts";
11
11
  import { applyEntryState, parseEntryState } from "#src/host-client/entry-state.ts";
12
12
  import { readPrg } from "#src/host-client/image.ts";
13
13
  import { readProjectFile, writeReported, type Written } from "#src/host-client/transfer.ts";
@@ -33,6 +33,8 @@ export interface MemoryObservation {
33
33
  view?: "cpu" | "ram";
34
34
  /** The largest allowed difference per byte; 0 when not given. */
35
35
  tolerance?: number;
36
+ /** Hex bits that the comparison uses: one byte for each byte, or one byte per byte of the range; all bits when not given. */
37
+ mask?: string;
36
38
  /** Bytes in the range that the comparison leaves out, each with the reason. */
37
39
  exclude?: Array<{ address: Location; reason: string }>;
38
40
  }
@@ -50,7 +52,7 @@ type StepBody =
50
52
  | { autostart: true }
51
53
  | { snapshot: string }
52
54
  | { normalize: true }
53
- | Exclude<ActionStep, { press: string }>
55
+ | ActionStep
54
56
  | { observe: string; memory?: Array<Location | MemoryObservation>; registers?: ObservedRegister[]; screen?: ScreenPolicy; vicii?: boolean; sprites?: number[] };
55
57
 
56
58
  /** A step; with side, only that side does it. An observe step has no side: it compares both. */
@@ -106,8 +108,6 @@ export interface ScenarioResult {
106
108
  }
107
109
 
108
110
  const STEP_KINDS = ["reset", "load", "autostart", "snapshot", "normalize", ...ACTION_STEP_KINDS, "observe"];
109
- /** The step kinds that a scenario runs: press is for the replay core only. */
110
- const SHOWN_KINDS = ["reset", "load", "autostart", "snapshot", "normalize", ...VICE_STEP_KINDS, "observe"];
111
111
 
112
112
  /** The keys of a scenario file: all but videoStandard are required. */
113
113
  const SCENARIO_KEYS = ["name", "original", "rebuild", "steps", "videoStandard"];
@@ -154,11 +154,11 @@ export function readScenario(path: string): Scenario {
154
154
  // An observe step names what it observes with "memory" and "registers" too.
155
155
  const kinds = "observe" in step ? ["observe"] : Object.keys(step).filter((key) => STEP_KINDS.includes(key));
156
156
  if (kinds.length > 1) return fail(`${at} has ${kinds.length} step kinds: ${kinds.join(", ")}. Give each one its own step`);
157
- if (kinds.length !== 1) return fail(`${at} must have exactly one of ${SHOWN_KINDS.join(", ")}`);
157
+ if (kinds.length !== 1) return fail(`${at} must have exactly one of ${STEP_KINDS.join(", ")}${typeof step.screen === "string" ? `. A scenario compares the screen in an observe step: {"observe": "${step.screen}", "screen": {}}` : ""}`);
158
158
  const kind = kinds[0]!;
159
159
  refuseOldStep(kind, step, at, fail);
160
160
  const allowed = [...(STEP_KEYS[kind] ?? [kind]), ...(kind === "observe" ? [] : ["side"])];
161
- for (const key of Object.keys(step)) if (!allowed.includes(key)) fail(`${at} has the key ${key}, which a ${kind} step does not have`);
161
+ for (const key of Object.keys(step)) if (!allowed.includes(key)) fail(`${at} has the key ${key}, which ${aStep(kind)} does not have`);
162
162
  if (step.side !== undefined && !(SIDES as unknown[]).includes(step.side)) fail(`${at}: side must be original or rebuild`);
163
163
  if ((ACTION_STEP_KINDS as readonly string[]).includes(kind)) {
164
164
  // The step with its defaults filled in, as the shared schema of the action steps gives it.
@@ -207,7 +207,7 @@ function checkObserve(step: Record<string, unknown>, at: string, fail: (message:
207
207
  checkLocation(item, `${at}: memory`, fail);
208
208
  continue;
209
209
  }
210
- const itemFields = ["address", "size", "view", "tolerance", "exclude"];
210
+ const itemFields = ["address", "size", "view", "tolerance", "mask", "exclude"];
211
211
  if (!isObject(item)) return fail(`${at}: memory must be a list of names, $ addresses or objects with address`);
212
212
  for (const key of Object.keys(item)) if (!itemFields.includes(key)) fail(`${at}: a memory object has the field ${key}. ${renamedField(key, itemFields) ?? `It has ${itemFields.join(", ")}, and nothing else`}`);
213
213
  if (item.view !== undefined && item.view !== "cpu" && item.view !== "ram") fail(`${at}: memory.view must be cpu or ram`);
@@ -223,6 +223,12 @@ function checkObserve(step: Record<string, unknown>, at: string, fail: (message:
223
223
  checkLocation(item.address, `${at}: memory.address`, fail);
224
224
  if (item.size !== undefined && !isInteger(item.size, 1, 0x10000)) fail(`${at}: memory.size must be a number from 1 to 65536`);
225
225
  if (item.tolerance !== undefined && !isInteger(item.tolerance, 0, 0xff)) fail(`${at}: memory.tolerance must be a number from 0 to 255`);
226
+ if (item.mask !== undefined) {
227
+ const size = isInteger(item.size, 1, 0x10000) ? item.size : 1;
228
+ if (typeof item.mask !== "string" || !/^(?:[0-9a-fA-F]{2})+$/.test(item.mask) || (item.mask.length !== 2 && item.mask.length !== size * 2)) {
229
+ fail(`${at}: memory.mask must be hex bits, one byte for each byte (for example 0f) or one byte per byte of size`);
230
+ }
231
+ }
226
232
  }
227
233
  }
228
234
  if (step.registers !== undefined) {
@@ -354,7 +360,7 @@ export function resolve(location: Location, symbols: Map<string, number>, side:
354
360
  }
355
361
 
356
362
  interface Observation {
357
- memory: Array<{ label: string; address: number; bytes: number[]; tolerance: number; excluded: Array<{ offset: number; address: Location; reason: string }> }>;
363
+ memory: Array<{ label: string; address: number; bytes: number[]; tolerance: number; mask?: number[]; excluded: Array<{ offset: number; address: Location; reason: string }> }>;
358
364
  registers: Partial<Record<ObservedRegister, unknown>>;
359
365
  screen?: { match: boolean; mismatchingPixels: number; comparedPixels: number; mismatchRatio: number; bounds?: unknown };
360
366
  vicii?: unknown;
@@ -444,7 +450,7 @@ async function runStep(client: ViceSessionClient, scenario: Scenario, side: Side
444
450
  if (offset < 0 || offset >= size) throw new Refusal("invalid-input", `the exclude ${exclude.address} lies outside the observed ${spec.address} (${size} bytes)`);
445
451
  return { offset, address: exclude.address, reason: exclude.reason };
446
452
  });
447
- observation.memory.push({ label: size > 1 ? `${spec.address} (${size} bytes)` : spec.address, address, bytes: [...Buffer.from(read.data, "hex")], tolerance: spec.tolerance ?? 0, excluded });
453
+ observation.memory.push({ label: size > 1 ? `${spec.address} (${size} bytes)` : spec.address, address, bytes: [...Buffer.from(read.data, "hex")], tolerance: spec.tolerance ?? 0, ...(spec.mask === undefined ? {} : { mask: [...Buffer.from(spec.mask, "hex")] }), excluded });
448
454
  }
449
455
  if (step.registers !== undefined) {
450
456
  const registers = await client.registersGet("c64");
@@ -495,11 +501,12 @@ async function runStep(client: ViceSessionClient, scenario: Scenario, side: Side
495
501
 
496
502
  type MemoryItem = Observation["memory"][number];
497
503
 
498
- /** The bytes of a memory item that differ by more than its tolerance, without the excluded bytes. */
504
+ /** The bytes of a memory item whose bits of the mask differ by more than its tolerance, without the excluded bytes. */
499
505
  function differingBytes(item: MemoryItem, other: MemoryItem): DifferingByte[] {
500
506
  const hex = (byte: number) => byte.toString(16).padStart(2, "0");
501
507
  const skipped = new Set(item.excluded.map((excluded) => excluded.offset));
502
- return item.bytes.flatMap((byte, offset) => (!skipped.has(offset) && Math.abs(byte - other.bytes[offset]!) > item.tolerance ? [{ address: formatC64Address(item.address + offset), original: hex(byte), rebuild: hex(other.bytes[offset]!) }] : []));
508
+ const bits = (offset: number) => (item.mask === undefined ? 0xff : item.mask.length === 1 ? item.mask[0]! : item.mask[offset]!);
509
+ return item.bytes.flatMap((byte, offset) => (!skipped.has(offset) && Math.abs((byte & bits(offset)) - (other.bytes[offset]! & bits(offset))) > item.tolerance ? [{ address: formatC64Address(item.address + offset), original: hex(byte), rebuild: hex(other.bytes[offset]!) }] : []));
503
510
  }
504
511
 
505
512
  /** The most differing bytes of one memory item that a result lists when no --max-listed is given. */
@@ -13,7 +13,10 @@ import { ViceSessionClient } from "#src/host-client/vice-session.ts";
13
13
  import { C64RunSession, PAL_FRAME_CYCLES } from "#src/native/c64run.ts";
14
14
  import { localToolContext } from "#src/native/local.ts";
15
15
  import { Workspace } from "#src/native/staging.ts";
16
+ import { openForRead } from "#src/knowledge/database.ts";
17
+ import { changedEvidence } from "#src/knowledge/evidence.ts";
16
18
  import { knowledgeNames } from "#src/knowledge/names.ts";
19
+ import { LOCAL_DIRECTORY, PROJECT_DIRECTORY, projectRelative, projectRoot } from "#src/project.ts";
17
20
  import { OPTIONS, reply, runScript, UsageError, type Call, type CommandSpec, type Reply } from "#src/script.ts";
18
21
  import { diffFiles } from "./lib/diff-files.ts";
19
22
  import { CANCELLED, play } from "./lib/play.ts";
@@ -78,7 +81,10 @@ async function recordCommand(call: Call): Promise<Reply> {
78
81
  const context = localToolContext();
79
82
  const core = await C64RunSession.open(context);
80
83
  const workspace = Workspace.create(context.supervisor, "c64-re-tools-record-");
84
+ let db: ReturnType<typeof openForRead>;
81
85
  try {
86
+ // The knowledge is read before the session: a record into the folder of an earlier recording can change files that it gives as evidence.
87
+ db = openForRead();
82
88
  const person = playing
83
89
  ? (session: C64RunSession, restore: () => Promise<string | undefined>) => {
84
90
  const ready = (url: string) =>
@@ -104,11 +110,26 @@ async function recordCommand(call: Call): Promise<Reply> {
104
110
  writeReported(`${out}/${RECORDING_FILES.reads}`, outcome.reads, { what: "--out" }),
105
111
  writeReported(`${out}/${RECORDING_FILES.coverage}`, outcome.coverage, { what: "--out" }),
106
112
  ];
113
+ // 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.
114
+ const local = (path: string) => projectRelative(path).startsWith(`${PROJECT_DIRECTORY}/${LOCAL_DIRECTORY}/`);
115
+ const keep = local(out)
116
+ ? `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>.`
117
+ : `Commit ${out} with the scenarios. Add ${out}/${RECORDING_FILES.coverage} to the project knowledge as coverage.`;
118
+ 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/.` : "";
119
+ const written = new Set(Object.values(RECORDING_FILES).map((name) => projectRelative(`${out}/${name}`)));
120
+ const evidence = changedEvidence(db, projectRoot(), (file) => written.has(file));
121
+ const map = projectRelative(`${out}/${RECORDING_FILES.coverage}`);
122
+ const cited = [
123
+ ...(evidence.length === 0 ? [] : [" The project knowledge gives the files in evidence as evidence of earlier revisions, and this record changed them."]),
124
+ ...(evidence.some((change) => change.file === map) ? [` Put the new ${RECORDING_FILES.coverage} into the project knowledge as coverage: it replaces the map of the earlier recording.`] : []),
125
+ ...(evidence.some((change) => change.file !== map) ? [` For a file other than ${RECORDING_FILES.coverage}, examine the facts of its revisions against the new recording.`] : []),
126
+ ].join("");
107
127
  return reply(
108
- { result: "PASS", recorded: true, out, ...summary, files },
109
- { hint: `Commit ${out} with the scenarios. Add ${out}/${RECORDING_FILES.coverage} to the project knowledge as coverage. ${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) },
128
+ { result: "PASS", recorded: true, out, ...summary, files, ...(evidence.length === 0 ? {} : { evidence }) },
129
+ { hint: `${keep}${recordFile}${cited} ${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) },
110
130
  );
111
131
  } finally {
132
+ db?.close();
112
133
  await core.close();
113
134
  workspace.remove();
114
135
  }
@@ -58,13 +58,15 @@ Each step has one of these kinds:
58
58
  - `{ "registers": { "pc": "start", "a": 1 } }` sets registers. Only `pc` takes a name.
59
59
  - `{ "joystick": { "port": 2, "direction": "up", "fire": false } }` sets a joystick.
60
60
  - `{ "type": { "mode": "text", "text": "RUN\n" } }` or `{ "type": { "mode": "petscii", "bytes": [147] } }` puts keys in the keyboard queue of the KERNAL.
61
+ - `{ "press": { "keys": "{F1}" } }` presses keys of the keyboard matrix. Each character is one tap. A name in braces is a key without a character, for example `{STOP}` or `{RESTORE}`. `+` in braces holds keys together, for example `{LSHIFT+CBM}`. `frames` is 1 to 3000, and 3 by default.
61
62
  - `{ "frames": 50 }` runs 1 to 30000 frames.
62
63
  - `{ "runUntil": { "target": { "kind": "address", "address": "main_loop" }, "timeoutFrames": 300 } }` runs until the target. The target kinds are `address`, `memory` and `raster`. `timeoutFrames` is 1 to 30000. The default is 3000.
63
64
  - `{ "capture": "level1" }` captures a part. Only `loads` takes this step. Give each capture step a different name of 1 to 64 letters, digits, dots, underscores or hyphens.
65
+ - `{ "save": "at-call" }` writes the machine state to `<out>/at-call.vsf`. Only `loads` takes this step. A run of the program can start from this snapshot file, for example at the call of a routine of a loading stage. Give each save step a different name.
64
66
 
65
67
  An address in a step can be a name. The script refuses an unknown name before the program runs. The message gives the file and the step.
66
68
 
67
- The script refuses a `press` step. A program that reads the keyboard matrix does not see the keys of a `type` step. A wait for any key that reads all keyboard columns can end without a key.
69
+ A program that reads the keyboard matrix does not see the keys of a `type` step. Use a `press` step for that program. A wait for any key that reads all keyboard columns can end without a key.
68
70
 
69
71
  The script refuses a step in an old form. The message gives the step to write.
70
72
 
@@ -193,7 +195,7 @@ Traps:
193
195
 
194
196
  - `captured`: true when the CPU got to `--until`. `pc` is that address.
195
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.
196
- - `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.
197
199
  - `stages`: the count of stages.
198
200
  - `differsFromReset`: the count of bytes that are not as a clean C64 has them at READY.
199
201
 
@@ -202,7 +204,7 @@ The folder `--out` gets these files:
202
204
  - `image.bin`: all 64 KiB of RAM at the entry. This RAM includes the RAM under the ROMs and the I/O area. A segment can be in the RAM under the I/O area at `$d000`-`$dfff`.
203
205
  - `image.json`: the entry, the segments, the vectors and the stages. `writtenBy` of a segment tells the last stage that wrote into it.
204
206
  - One PRG for each segment.
205
- - `entry_state.json`: the registers, `$00` and `$01`, pages 0 to 3, the VIC, SID and CIA registers, and the vectors. `cia` gives the CIA timer latches and interrupt masks. `differsFromReset` lists the bytes that are not as a clean C64 has them at READY. A rebuild must make these bytes the same, because the program can read them.
207
+ - `entry_state.json`: the registers, `$00` and `$01`, pages 0 to 3, the VIC, SID and CIA registers, the colour RAM, and the vectors. `io.colour` holds the 1000 colours at $d800. `cia` gives the CIA timer latches and interrupt masks. `differsFromReset` lists the bytes that are not as a clean C64 has them at READY. A rebuild must make these bytes the same, because the program can read them.
206
208
 
207
209
  A segment is a block that a stage wrote, also a small block. These blocks are not segments:
208
210
 
@@ -212,6 +214,8 @@ A segment is a block that a stage wrote, also a small block. These blocks are no
212
214
 
213
215
  The block with the capture entry is always a segment. Segments do not overlap.
214
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
+
215
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.
216
220
 
217
221
  On `PASS`, `hint` tells you to disassemble the code at `pc`, and then to put `<out>/image.json` into the project knowledge.
@@ -219,7 +223,7 @@ On `PASS`, `hint` tells you to disassemble the code at `pc`, and then to put `<o
219
223
  Traps:
220
224
 
221
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.
222
- - `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.
223
227
 
224
228
  ### `loads <program>`
225
229
 
@@ -231,6 +235,7 @@ A segment is a block of RAM from `$0400` that the program changed after the capt
231
235
 
232
236
  - `loaded`: true when a capture has a segment.
233
237
  - `captures`: one item for each capture step, with `capture`, `out`, `files`, `removed`, `pc`, `segments`, `excluded`, `differsFromReset`, `smallChanges` and `drive`.
238
+ - `saved`: one item for each save step, with `save`, `file` and `pc`.
234
239
  - `smallChanges`: the count of changed bytes in blocks that are smaller than `--min-block`.
235
240
  - `keyWait: true`: the CPU was in the KERNAL wait for a key, at READY or at an INPUT statement.
236
241
  - `drive`: the name of the drive file, with `--drive`.
@@ -260,7 +265,7 @@ Traps:
260
265
  5. Make sure that the result is the program. The code at the entry must not be the unpacker again. A segment can be data that a loader or a cracktro left, for example intro graphics. Keep it until other evidence shows that the program does not use it. Then capture again with `--exclude` for that range.
261
266
  - Exclude each range of a cracktro that the program does not read. A rebuild has no cracktro. Also exclude a picture, an intro or a credit screen of a crack.
262
267
  - Do not exclude the start screen of the program, also when the program does not read it. An example is the loading picture of the publisher. Record it as the start screen in the project knowledge. The loader of the rebuild shows it.
263
- - When the start screen is only in an earlier stage of the loading, capture that stage too, while it shows the screen. Do not exclude the memory of the screen in that capture. Put it into the project knowledge in a space of its own, for example `bank1`.
268
+ - When the start screen is only in an earlier stage of the loading, capture that stage too, while it shows the screen. Do not exclude the memory of the screen in that capture. Put it into the project knowledge in the space `loading`. The capture holds the VIC-II registers and the colour RAM, so the start screen needs nothing more.
264
269
  - Do not exclude other unused bytes, for example leftovers of the development or an old copy of a routine. A rebuild keeps them.
265
270
  - Keep a crack change that the program reads, for example a credit text in the game. Record it as a `crack` switch in the project knowledge.
266
271
  6. Put `<out>/image.json` into the project knowledge. The knowledge keeps the segments, the entry, the entry state and the stages. After that, you do not need the files in `<out>`.
@@ -1,14 +1,16 @@
1
1
  // The loads command of c64-unpacker: one capture for each part of a
2
- // multi-load program. The steps file has action steps and capture steps; a
3
- // capture writes what the C64 side changed since the previous capture as an
4
- // image with its entry state, and with --drive the drive RAM as a PRG for
5
- // knowledge space drive8. No tool guesses where a load ends: the steps decide.
2
+ // multi-load program. The steps file has action steps, capture steps and save
3
+ // steps; a capture writes what the C64 side changed since the previous
4
+ // capture as an image with its entry state, and with --drive the drive RAM as
5
+ // a PRG for knowledge space drive8. A save writes the machine state as a
6
+ // snapshot file, which a run can start from. No tool guesses where a load
7
+ // ends: the steps decide.
6
8
 
7
9
  import { type AddressRange, COVERAGE, formatC64Address } from "#src/c64.ts";
8
10
  import { Refusal } from "#src/errors.ts";
9
11
  import { autostartLoaded, LOAD_LIMIT_FRAMES, RUN_LIMIT_FRAMES, typeRun } from "#src/host-client/autostart.ts";
10
12
  import { IO_RAM, markIoRamWrites, readCoverage } from "#src/host-client/coverage.ts";
11
- import { ACTION_STEP_KINDS, checkActionStep, checkStepNames, isObject, runActionStep, VICE_STEP_KINDS, type ActionStep, type ActionStepKind } from "#src/host-client/steps.ts";
13
+ import { ACTION_STEP_KINDS, checkActionStep, checkStepNames, isObject, runActionStep, type ActionStep, type ActionStepKind } from "#src/host-client/steps.ts";
12
14
  import { knowledgeAt } from "#src/knowledge/names.ts";
13
15
  import { WireFailure } from "#src/host-client/tools.ts";
14
16
  import { readProjectFile, writeReported, type Written } from "#src/host-client/transfer.ts";
@@ -17,9 +19,9 @@ import { entryStateFile, json, machineState, readRam, readyState, removeStaleFil
17
19
  import { FIRST_SEGMENT_ADDRESS } from "./stages.ts";
18
20
 
19
21
 
20
- export type LoadStep = ActionStep | { capture: string };
22
+ export type LoadStep = ActionStep | { capture: string } | { save: string };
21
23
 
22
- /** A capture name: letters, digits, dots, underscores or hyphens. */
24
+ /** A capture or save name: letters, digits, dots, underscores or hyphens. */
23
25
  const NAME = /^[A-Za-z0-9._-]{1,64}$/;
24
26
  /** The drive RAM of a 1541. */
25
27
  const DRIVE_RAM = 0x0800;
@@ -28,7 +30,7 @@ const KERNAL_LOAD = 0xffd5;
28
30
  /** The KERNAL loop that waits for a key at READY. or at an INPUT statement. */
29
31
  const KERNAL_KEY_WAIT = { start: 0xe5cd, end: 0xe5d5 };
30
32
 
31
- /** Reads and checks the steps file of loads: action steps with $ addresses, and capture steps with new names. */
33
+ /** Reads and checks the steps file of loads: action steps with $ addresses, and capture and save steps with new names. */
32
34
  export function readLoadSteps(path: string): LoadStep[] {
33
35
  let value: unknown;
34
36
  try {
@@ -42,9 +44,17 @@ export function readLoadSteps(path: string): LoadStep[] {
42
44
  };
43
45
  if (!Array.isArray(value) || value.length === 0) return fail("the steps are a JSON list with at least one step");
44
46
  const names = new Set<string>();
47
+ const saves = new Set<string>();
45
48
  value.forEach((step: unknown, index) => {
46
49
  const at = `step ${index + 1}`;
47
50
  if (!isObject(step)) return fail(`${at} must be an object`);
51
+ if ("save" in step) {
52
+ if (Object.keys(step).length !== 1) fail(`${at}: a save step has only save`);
53
+ if (typeof step.save !== "string" || !NAME.test(step.save)) fail(`${at}: save needs a name of 1 to 64 letters, digits, dots, underscores or hyphens`);
54
+ if (saves.has(step.save as string)) fail(`${at}: the save name ${step.save as string} is used before`);
55
+ saves.add(step.save as string);
56
+ return;
57
+ }
48
58
  if ("capture" in step) {
49
59
  if (Object.keys(step).length !== 1) fail(`${at}: a capture step has only capture`);
50
60
  if (typeof step.capture !== "string" || !NAME.test(step.capture)) fail(`${at}: capture needs a name of 1 to 64 letters, digits, dots, underscores or hyphens`);
@@ -54,14 +64,14 @@ export function readLoadSteps(path: string): LoadStep[] {
54
64
  }
55
65
  const kinds = Object.keys(step).filter((key) => (ACTION_STEP_KINDS as readonly string[]).includes(key));
56
66
  if (kinds.length > 1) return fail(`${at} has ${kinds.length} step kinds: ${kinds.join(", ")}. Give each one its own step`);
57
- if (kinds.length !== 1) return fail(`${at} must have exactly one of ${[...VICE_STEP_KINDS, "capture"].join(", ")}`);
67
+ if (kinds.length !== 1) return fail(`${at} must have exactly one of ${[...ACTION_STEP_KINDS, "capture", "save"].join(", ")}`);
58
68
  // The step with its defaults filled in, as the shared schema of the action steps gives it.
59
69
  const checked = checkActionStep(kinds[0] as ActionStepKind, step, at, fail);
60
70
  // Its names resolve now: an unknown name stops the call before the emulator starts.
61
71
  checkStepNames([checked], knowledgeAt(), `--steps ${path}`, index + 1);
62
72
  (value as unknown[])[index] = checked;
63
73
  });
64
- if (names.size === 0) fail("the steps have no capture step");
74
+ if (names.size === 0 && saves.size === 0) fail("the steps have no capture step and no save step");
65
75
  return value as LoadStep[];
66
76
  }
67
77
 
@@ -149,12 +159,23 @@ export async function loads(program: string, options: { out: string; steps: Load
149
159
  }
150
160
 
151
161
  const captures: Array<Record<string, unknown>> = [];
162
+ const saved: Array<Record<string, unknown>> = [];
152
163
  for (const [index, step] of options.steps.entries()) {
164
+ if ("save" in step) {
165
+ // The machine state as a snapshot file: a run starts from it, for example at the call of a loading stage.
166
+ if ((await client.status()).state === "running") await client.execution({ action: "pause", space: "c64" });
167
+ await client.snapshot({ action: "save", name: "loads-save" });
168
+ const path = `${options.out}/${step.save}.vsf`;
169
+ const file = writeReported(path, await client.snapshotExport("loads-save"), { what: "--out" });
170
+ await client.snapshot({ action: "remove", name: "loads-save" });
171
+ saved.push({ save: step.save, file, pc: formatC64Address((await client.registersGet("c64")).pc) });
172
+ continue;
173
+ }
153
174
  if (!("capture" in step)) {
154
175
  const notReached = await runActionStep(client, step, knowledgeAt());
155
176
  if (notReached !== undefined && "runUntil" in step) {
156
177
  const reason = `Step ${index + 1} did not reach its target in ${step.runUntil.timeoutFrames} frames. It stopped by ${notReached.stopReason} at ${formatC64Address(notReached.pc)}.`;
157
- return { output: { loaded: false, reason, captures }, failed: true };
178
+ return { output: { loaded: false, reason, captures, ...(saved.length === 0 ? {} : { saved }) }, failed: true };
158
179
  }
159
180
  continue;
160
181
  }
@@ -226,9 +247,9 @@ export async function loads(program: string, options: { out: string; steps: Load
226
247
  if (captures.length > 0 && captures.every((capture) => (capture.segments as unknown[]).length === 0)) {
227
248
  const waits = captures.some((capture) => capture.keyWait === true) ? " The C64 waited for a key at READY. or at an INPUT statement, so the load ended or did not start." : "";
228
249
  const reason = `No capture has a segment: the program changed no block of RAM from ${formatC64Address(FIRST_SEGMENT_ADDRESS)} on.${waits}`;
229
- return { output: { loaded: false, reason, captures }, failed: true };
250
+ return { output: { loaded: false, reason, captures, ...(saved.length === 0 ? {} : { saved }) }, failed: true };
230
251
  }
231
- return { output: { loaded: true, captures }, failed: false };
252
+ return { output: { loaded: true, captures, ...(saved.length === 0 ? {} : { saved }) }, failed: false };
232
253
  } finally {
233
254
  await client.close();
234
255
  }
@@ -15,8 +15,10 @@ type Registers = Awaited<ReturnType<ViceSessionClient["registersGet"]>>;
15
15
 
16
16
  const MAX_READ = 4096;
17
17
 
18
- /** The I/O areas of the entry state, read without side effects. */
19
- export const IO_AREAS = { vic: [0xd000, 0x2f], sid: [0xd400, 0x1d], cia1: [0xdc00, 0x10], cia2: [0xdd00, 0x10] } as const;
18
+ /** 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;
20
+ /** 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
+ const CHIP_AREAS = ["vic", "sid", "cia1", "cia2"] as const;
20
22
 
21
23
  /** What no register read of a CIA gives. */
22
24
  export interface CiaHidden {
@@ -49,6 +51,8 @@ export async function machineState(client: ViceSessionClient): Promise<MachineSt
49
51
  const pages = await readRam(client, 0x0000, 0x400);
50
52
  const io = {} as Record<keyof typeof IO_AREAS, Buffer>;
51
53
  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
+ // The colour RAM has 4 bits: a read gives other bits above them.
55
+ io.colour = Buffer.from(io.colour.map((value) => value & 0x0f));
52
56
  const [cia1, cia2] = (await client.cia("both")).chips.map(({ latchA, latchB, interruptMask }) => ({ latchA, latchB, interruptMask }));
53
57
  const romVectors = Buffer.from((await client.memoryRead({ address: 0xfffa, size: 6, space: "c64", view: "cpu" })).data, "hex");
54
58
  return { port, pages, io, cia: { cia1: cia1!, cia2: cia2! }, romVectors };
@@ -79,7 +83,7 @@ export function differsFrom(state: MachineState, clean: MachineState): Array<{ a
79
83
  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]! }));
80
84
  compare(0x0000, state.port, clean.port);
81
85
  compare(0x0002, state.pages.subarray(2), clean.pages.subarray(2));
82
- for (const [name, [address]] of Object.entries(IO_AREAS)) compare(address, state.io[name as keyof typeof IO_AREAS], clean.io[name as keyof typeof IO_AREAS]);
86
+ for (const name of CHIP_AREAS) compare(IO_AREAS[name][0], state.io[name], clean.io[name]);
83
87
  return differs;
84
88
  }
85
89
 
@@ -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. */