@henols/c64-re-tools 2.8.0-rc.5 → 2.8.0-rc.6
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 +1 -1
- package/skills/c64-assembler/SKILL.md +1 -1
- package/skills/c64-assembler/scripts/assembler.ts +78 -24
- package/skills/c64-docs/scripts/docs.ts +31 -10
- package/skills/c64-knowledge/SKILL.md +4 -3
- package/skills/c64-knowledge/scripts/knowledge.ts +31 -12
- package/skills/c64-packer/scripts/packer.ts +9 -2
- package/skills/c64-provenance/SKILL.md +1 -1
- package/skills/c64-provenance/scripts/lib/runtime.ts +5 -16
- package/skills/c64-source/references/loader.md +8 -7
- package/skills/c64-source/scripts/lib/loader.ts +4 -111
- package/skills/c64-source/scripts/source.ts +49 -78
- package/skills/c64-static-analysis/SKILL.md +2 -2
- package/skills/c64-static-analysis/scripts/lib/coverage.ts +56 -4
- package/skills/c64-static-analysis/scripts/static-analysis.ts +32 -21
- package/skills/c64-testing/SKILL.md +6 -0
- package/skills/c64-testing/scripts/lib/play.ts +8 -7
- package/skills/c64-testing/scripts/lib/recording.ts +218 -12
- package/skills/c64-testing/scripts/lib/replay.ts +7 -3
- package/skills/c64-testing/scripts/lib/runs.ts +5 -1
- package/skills/c64-testing/scripts/lib/scenario.ts +4 -0
- package/skills/c64-testing/scripts/testing.ts +24 -11
- package/skills/c64-unpacker/SKILL.md +6 -4
- package/skills/c64-unpacker/scripts/lib/loads.ts +4 -2
- package/skills/c64-unpacker/scripts/lib/machine.ts +128 -5
- package/skills/c64-unpacker/scripts/lib/stages.ts +5 -1
- package/skills/c64-unpacker/scripts/unpacker.ts +13 -12
- package/skills/emulator/SKILL.md +2 -2
- package/src/host/vice/adapter.ts +2 -1
- package/src/host-client/image.ts +33 -4
- package/src/host-client/tools.ts +1 -1
- package/src/host-client/transfer.ts +48 -26
- package/src/host-client/vice-session.ts +15 -0
- package/src/knowledge/database.ts +72 -19
- package/src/knowledge/import.ts +31 -8
- package/src/knowledge/names.ts +2 -2
- package/src/knowledge/program.ts +67 -7
- package/src/knowledge/schema.ts +6 -0
- package/src/knowledge/start-screen.ts +55 -2
- package/src/knowledge/write.ts +18 -12
- package/src/loader.ts +101 -33
- package/src/mcp/output.ts +13 -12
- package/src/mcp/server.ts +33 -22
- package/src/mcp/tools/debug.ts +21 -24
- package/src/mcp/tools/media.ts +27 -27
- package/src/mcp/tools/memory.ts +13 -17
- package/src/mcp/tools/video.ts +10 -12
- package/src/native/c64run.ts +39 -1
- package/src/native/decompiler/analyze.ts +1 -1
- package/src/native/dxa.ts +2 -2
- package/src/native/types.ts +26 -7
- package/src/program-code.ts +4 -2
- package/src/project.ts +224 -71
- package/src/protocol/vice.ts +5 -3
- package/src/script.ts +60 -15
- package/{skills/c64-source/scripts/lib → src}/stage.ts +142 -11
- package/tools/c64run.c +18 -5
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
// comparison, else the record file gave it.
|
|
6
6
|
|
|
7
7
|
import { existsSync } from "node:fs";
|
|
8
|
+
import { basename } from "node:path";
|
|
8
9
|
|
|
9
10
|
import { symbolsPath } from "#src/build-name.ts";
|
|
10
11
|
import { isRefusal, Refusal } from "#src/errors.ts";
|
|
@@ -19,7 +20,7 @@ import { localToolContext } from "#src/native/local.ts";
|
|
|
19
20
|
import { Workspace } from "#src/native/staging.ts";
|
|
20
21
|
import { resolveProjectPath } from "#src/project.ts";
|
|
21
22
|
import { UsageError } from "#src/script.ts";
|
|
22
|
-
import { eventBeforeEntry, firstDifference, loaderEntry, mover, parseStateItem, pinLines, readRecording, replaySide, siteMap, type Comparison, type ReplayResult, type ReplaySubject } from "./recording.ts";
|
|
23
|
+
import { entryStateCheck, eventBeforeEntry, firstDifference, loaderEntry, mover, parseStateItem, pinLines, readRecording, replaySide, siteMap, type Comparison, type ReplayResult, type ReplaySubject } from "./recording.ts";
|
|
23
24
|
import { cachedNames } from "./scenario.ts";
|
|
24
25
|
|
|
25
26
|
const MAX_STATE_ITEMS = 16;
|
|
@@ -63,7 +64,7 @@ export interface ReplayAll {
|
|
|
63
64
|
export async function replayAll(folders: readonly string[], values: Omit<ReplayOptions, "folder" | "screen">, one: (values: ReplayOptions) => Promise<ReplayResult> = replay): Promise<ReplayAll> {
|
|
64
65
|
const recordings: ReplayResult[] = [];
|
|
65
66
|
for (const folder of folders) {
|
|
66
|
-
const name = folder
|
|
67
|
+
const name = basename(folder);
|
|
67
68
|
try {
|
|
68
69
|
recordings.push(await one({ ...values, folder, ...(values.out === undefined ? {} : { out: `${values.out}/${name}` }) }));
|
|
69
70
|
} catch (error) {
|
|
@@ -170,8 +171,11 @@ export async function replay(values: ReplayOptions): Promise<ReplayResult> {
|
|
|
170
171
|
const pins = pinLines(expected, compare!.state);
|
|
171
172
|
const replayed = await side(rebuild, { compare: compare!, stop: expected.length, pins, ...(handover === undefined ? {} : { handover }) });
|
|
172
173
|
const difference = firstDifference(expected, replayed.samples, compare!.state);
|
|
174
|
+
// The loader of the rebuild writes the entry state of the capture it was made from: the rebuild at its entry has it.
|
|
175
|
+
const { entryRam } = replayed;
|
|
176
|
+
const entryState = handover === undefined || entryRam === undefined ? {} : entryStateCheck(handover.reference, recording.input ?? [], { sp: entryRam.sp, written: [{ start: 0x0002, end: 0x03ff }], byteAt: (address) => entryRam.ram[address]! });
|
|
173
177
|
// A read that the recording has no value for gets the idle value: it is in the result, never silent.
|
|
174
|
-
const base = { checkpoints: expected.length, ...named, movedSites, ...(replayed.startScreenSkipped === true ? { startScreen: "skipped" } : {}), ...(replayed.unknown > 0 ? { idleReads: replayed.unknown } : {}) };
|
|
178
|
+
const base = { checkpoints: expected.length, ...named, movedSites, ...(replayed.startScreenSkipped === true ? { startScreen: "skipped" } : {}), ...(replayed.unknown > 0 ? { idleReads: replayed.unknown } : {}), ...entryState };
|
|
175
179
|
if (difference === undefined && replayed.samples.length >= expected.length) return result("PASS", "rebuild", { ...base, compared: expected.length });
|
|
176
180
|
const reason =
|
|
177
181
|
difference !== undefined
|
|
@@ -18,7 +18,7 @@ import { isInteger, isObject, MAX_MEMORY_READ, MAX_TRACE_FRAMES, MAX_TRACE_HITS,
|
|
|
18
18
|
import { readProjectFile, readProjectJson, writeReported, type Written } from "#src/host-client/transfer.ts";
|
|
19
19
|
import { readMemoryInParts, ViceSessionClient } from "#src/host-client/vice-session.ts";
|
|
20
20
|
import { checkSnapshotFile } from "#src/media.ts";
|
|
21
|
-
import { checkOutputPath, LOCAL_DIRECTORY, PROJECT_DIRECTORY, projectRelative, resolveProjectPath } from "#src/project.ts";
|
|
21
|
+
import { checkOutputPath, LOCAL_DIRECTORY, PROJECT_DIRECTORY, projectRelative, refuseAbsoluteInFile, resolveProjectPath } from "#src/project.ts";
|
|
22
22
|
import { namesOf } from "./scenario.ts";
|
|
23
23
|
import { namesStartScreen, passStartScreen } from "./start-screen.ts";
|
|
24
24
|
|
|
@@ -128,6 +128,9 @@ function readRun(path: string): Run {
|
|
|
128
128
|
for (const key of Object.keys(start)) if (!(typeof start.program === "string" ? ["program", "load"] : ["snapshot"]).includes(key)) fail(`start has the key ${key}. start must be ${START_FORMS}`);
|
|
129
129
|
if (start.load !== undefined && typeof start.load !== "boolean") fail("start.load must be true or false");
|
|
130
130
|
if (value.symbols !== undefined && typeof value.symbols !== "string") fail('symbols must be "knowledge", "none" or a JSON file');
|
|
131
|
+
refuseAbsoluteInFile(start.program, "start.program", fail);
|
|
132
|
+
refuseAbsoluteInFile(start.snapshot, "start.snapshot", fail);
|
|
133
|
+
refuseAbsoluteInFile(value.symbols, "symbols", fail);
|
|
131
134
|
if (!Array.isArray(value.steps) || value.steps.length === 0) fail("steps must be a list with at least one step");
|
|
132
135
|
const labels = new Set<string>();
|
|
133
136
|
(value.steps as unknown[]).forEach((step, index) => {
|
|
@@ -147,6 +150,7 @@ function readRun(path: string): Run {
|
|
|
147
150
|
const name = step[kind];
|
|
148
151
|
if (kind === "snapshot") {
|
|
149
152
|
if (typeof name !== "string" || name === "") fail(`${at}: snapshot needs a project file`);
|
|
153
|
+
refuseAbsoluteInFile(name, `${at}: snapshot`, fail);
|
|
150
154
|
return;
|
|
151
155
|
}
|
|
152
156
|
if (typeof name !== "string" || !NAME.test(name)) fail(`${at}: ${kind} needs a name of 1 to 64 letters, digits, dots, underscores or hyphens`);
|
|
@@ -17,6 +17,7 @@ import { openForRead } from "#src/knowledge/database.ts";
|
|
|
17
17
|
import { nameTable } from "#src/knowledge/names.ts";
|
|
18
18
|
import { DEFAULT_SPACE } from "#src/knowledge/schema.ts";
|
|
19
19
|
import { programImage } from "#src/knowledge/program.ts";
|
|
20
|
+
import { refuseAbsoluteInFile } from "#src/project.ts";
|
|
20
21
|
import { listed } from "#src/script.ts";
|
|
21
22
|
import { namesStartScreen, passStartScreen } from "./start-screen.ts";
|
|
22
23
|
|
|
@@ -139,6 +140,8 @@ export function readScenario(path: string): Scenario {
|
|
|
139
140
|
const form = `${side} must be { "program": "<file.prg>", "symbols": "knowledge" }. symbols can also be "none" or a JSON file`;
|
|
140
141
|
if (!isObject(subject) || typeof subject.program !== "string" || typeof subject.symbols !== "string") return fail(form);
|
|
141
142
|
for (const key of Object.keys(subject)) if (key !== "program" && key !== "symbols") fail(`${side} has the key ${key}. ${form}`);
|
|
143
|
+
refuseAbsoluteInFile(subject.program, `${side}.program`, fail);
|
|
144
|
+
refuseAbsoluteInFile(subject.symbols, `${side}.symbols`, fail);
|
|
142
145
|
}
|
|
143
146
|
if (!Array.isArray(scenario.steps) || scenario.steps.length === 0) fail("steps must be a list with at least one step");
|
|
144
147
|
const labels = new Set<string>();
|
|
@@ -183,6 +186,7 @@ function checkStep(kind: string, step: Record<string, unknown>, at: string, fail
|
|
|
183
186
|
return;
|
|
184
187
|
case "snapshot":
|
|
185
188
|
if (typeof step.snapshot !== "string" || step.snapshot === "") fail(`${at}: snapshot needs a .vsf file in the project`);
|
|
189
|
+
refuseAbsoluteInFile(step.snapshot, `${at}: snapshot`, fail);
|
|
186
190
|
return;
|
|
187
191
|
case "normalize":
|
|
188
192
|
if (step.normalize !== true) fail(`${at}: normalize is true: it writes the entry state of the knowledge`);
|
|
@@ -5,6 +5,8 @@
|
|
|
5
5
|
// show tells what a recording holds; diff shows what changed between two
|
|
6
6
|
// states; checklist gives the Markdown list for a human tester.
|
|
7
7
|
|
|
8
|
+
import { basename } from "node:path";
|
|
9
|
+
|
|
8
10
|
import { symbolsPath } from "#src/build-name.ts";
|
|
9
11
|
import { COVERAGE, formatC64Address } from "#src/c64.ts";
|
|
10
12
|
import { isRefusal, Refusal } from "#src/errors.ts";
|
|
@@ -24,7 +26,7 @@ import { LOCAL_DIRECTORY, PROJECT_DIRECTORY, projectRelative, projectRoot } from
|
|
|
24
26
|
import { OPTIONS, reply, runScript, UsageError, type Call, type CommandSpec, type Reply } from "#src/script.ts";
|
|
25
27
|
import { diffFiles } from "./lib/diff-files.ts";
|
|
26
28
|
import { CANCELLED, play } from "./lib/play.ts";
|
|
27
|
-
import { readRecordFile, record, showRecording } from "./lib/recording.ts";
|
|
29
|
+
import { entryStateCheck, loaderEntryState, readRecordFile, record, showRecording } from "./lib/recording.ts";
|
|
28
30
|
import { replay, replayAll } from "./lib/replay.ts";
|
|
29
31
|
import { keepRun, runFile } from "./lib/runs.ts";
|
|
30
32
|
import { namesOf, readScenario, runScenario, scenarioNames, type Scenario, type ScenarioResult } from "./lib/scenario.ts";
|
|
@@ -44,6 +46,11 @@ const ALWAYS = [
|
|
|
44
46
|
/** The hint of a test or replay verdict: what to do after a FAIL or an INCONCLUSIVE. */
|
|
45
47
|
const INCONCLUSIVE_HINT = "reason tells why the script could not compare. This is not a failure of the program. Correct the cause, then run the command again.";
|
|
46
48
|
|
|
49
|
+
/** What to do when the reference at its entry is not in the entry state that the loader of a rebuild writes. */
|
|
50
|
+
const RECAPTURE = "Capture the program again with the input of the record file before the entry. Then put the capture into the project knowledge, and generate the loader again.";
|
|
51
|
+
const ENTRY_STATE_REMEDY = `The loader of a rebuild writes the entry state of the project knowledge, so the rebuild starts from another state than the reference. ${RECAPTURE}`;
|
|
52
|
+
const ENTRY_STATE_HINT = `At their entries, the reference and the rebuild have other bytes in entryStateDiffers: the loader of the rebuild wrote another entry state. ${RECAPTURE}`;
|
|
53
|
+
|
|
47
54
|
async function test(call: Call): Promise<ScenarioResult | Reply> {
|
|
48
55
|
const scenario = readScenario(call.subject(0));
|
|
49
56
|
const out = call.string("out");
|
|
@@ -99,7 +106,8 @@ async function recordCommand(call: Call): Promise<Reply> {
|
|
|
99
106
|
// The loader of a rebuild jumps to the entry of the program in the knowledge. replay finds it in the reference by the names of the
|
|
100
107
|
// knowledge, also for symbols none. With the names of a build, or with load true (no loader entry), record marks no entry.
|
|
101
108
|
const namedAsKnowledge = file.symbols === "knowledge" || file.symbols === "none";
|
|
102
|
-
const
|
|
109
|
+
const entry = file.load || !namedAsKnowledge ? undefined : programEntry(db);
|
|
110
|
+
const outcome = await record(core, file, workspace, person, entry);
|
|
103
111
|
const summary = {
|
|
104
112
|
name: file.name,
|
|
105
113
|
frames: Math.round(outcome.recording.ticks / PAL_FRAME_CYCLES),
|
|
@@ -133,9 +141,12 @@ async function recordCommand(call: Call): Promise<Reply> {
|
|
|
133
141
|
].join("");
|
|
134
142
|
// The recording replays on the reference and on a rebuild without a loader: the event before the entry is no refusal.
|
|
135
143
|
const loader = outcome.loaderProblem === undefined ? "" : `${outcome.loaderProblem}, then record again. Until then, the recording replays on the reference and on a rebuild without a loader, not on a rebuild with a loader. `;
|
|
144
|
+
const state = entry === undefined || outcome.entryRam === undefined ? undefined : loaderEntryState(db, entry);
|
|
145
|
+
const checked = state === undefined ? {} : entryStateCheck(outcome.entryRam!, outcome.recording.input ?? [], state);
|
|
146
|
+
const entryState = checked.entryStateDiffers === undefined ? "" : `At its entry ${formatC64Address(entry!)}, the program has other bytes than the entry state of the project knowledge in entryStateDiffers. ${ENTRY_STATE_REMEDY} `;
|
|
136
147
|
return reply(
|
|
137
|
-
{ result: "PASS", recorded: true, out, ...summary, files, ...(evidence.length === 0 ? {} : { evidence }) },
|
|
138
|
-
{ hint: `${loader}${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) },
|
|
148
|
+
{ result: "PASS", recorded: true, out, ...summary, files, ...(evidence.length === 0 ? {} : { evidence }), ...checked },
|
|
149
|
+
{ hint: `${loader}${entryState}${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) },
|
|
139
150
|
);
|
|
140
151
|
} finally {
|
|
141
152
|
db?.close();
|
|
@@ -238,7 +249,8 @@ const COMMANDS: CommandSpec[] = [
|
|
|
238
249
|
if (screen !== undefined) throw new UsageError("--screen needs one recording. Give one recording, or leave out --screen.");
|
|
239
250
|
const all = await replayAll(folders, values);
|
|
240
251
|
const first = all.recordings.find((item) => item.result !== "PASS");
|
|
241
|
-
|
|
252
|
+
const entryState = all.recordings.some((item) => item.entryStateDiffers !== undefined) ? ` For each recording with entryStateDiffers: ${ENTRY_STATE_HINT}` : "";
|
|
253
|
+
if (first === undefined) return entryState === "" ? all : reply(all, { hint: entryState.trimStart() });
|
|
242
254
|
// The same comparison, alone: its own result gives the hint and the nextAction of that recording.
|
|
243
255
|
const flags = [
|
|
244
256
|
...(checkpoint === undefined ? [] : ["--checkpoint", checkpoint]),
|
|
@@ -246,24 +258,25 @@ const COMMANDS: CommandSpec[] = [
|
|
|
246
258
|
...values.pin.flatMap((item) => ["--pin", item]),
|
|
247
259
|
...(rebuild === undefined ? [] : ["--rebuild", rebuild]),
|
|
248
260
|
...(symbols === undefined ? [] : ["--symbols", symbols]),
|
|
249
|
-
...(out === undefined ? [] : ["--out", `${out}/${first.recording
|
|
261
|
+
...(out === undefined ? [] : ["--out", `${out}/${basename(first.recording)}`]),
|
|
250
262
|
];
|
|
251
|
-
return reply(all, { hint:
|
|
263
|
+
return reply(all, { hint: `Each item of recordings has the result of one recording. Run nextAction: it replays the first recording that did not pass alone, and its result gives the hint for it.${entryState}`, nextAction: call.next("replay", first.recording, ...flags) });
|
|
252
264
|
}
|
|
253
265
|
const result = await replay({ ...values, folder: call.subject(0), ...(screen === undefined ? {} : { screen }) });
|
|
254
266
|
if (result.result === "INCONCLUSIVE") return reply(result, { hint: INCONCLUSIVE_HINT });
|
|
255
|
-
|
|
267
|
+
const entryState = result.entryStateDiffers === undefined ? "" : `${ENTRY_STATE_HINT} `;
|
|
268
|
+
if (result.result !== "FAIL") return entryState === "" ? result : reply(result, { hint: entryState.trimEnd() });
|
|
256
269
|
const [reference, rebuilt] = result.files ?? [];
|
|
257
270
|
if (reference !== undefined && rebuilt !== undefined) {
|
|
258
|
-
return reply(result, { hint:
|
|
271
|
+
return reply(result, { hint: `${entryState}files holds the RAM of each side at the first different checkpoint. Run nextAction to compare them. Then examine the first different state item in the emulator.`, nextAction: call.next("diff", reference.out, rebuilt.out) });
|
|
259
272
|
}
|
|
260
273
|
if (result.firstDifference === undefined) {
|
|
261
274
|
// Without --symbols and without a symbol file of its build, the rebuild has the names of the recording: no loader or start-screen labels.
|
|
262
275
|
const own = rebuild === undefined ? undefined : symbolsPath(rebuild);
|
|
263
276
|
const unnamed = symbols === undefined && own !== undefined && result.symbols !== own;
|
|
264
|
-
return reply(result, { hint: unnamed ? `The rebuild has the names of the recording, as ${own} does not exist. Give --symbols with the symbol file of the rebuild.` : "reason tells how many checkpoints the rebuild came to. Examine the rebuild in the emulator after its last checkpoint." });
|
|
277
|
+
return reply(result, { hint: `${entryState}${unnamed ? `The rebuild has the names of the recording, as ${own} does not exist. Give --symbols with the symbol file of the rebuild.` : "reason tells how many checkpoints the rebuild came to. Examine the rebuild in the emulator after its last checkpoint."}` });
|
|
265
278
|
}
|
|
266
|
-
return reply(result, { hint:
|
|
279
|
+
return reply(result, { hint: `${entryState}A difference in a random value with the same input often shows a missing --pin.${out === undefined ? " Give --out to get the RAM of each side at the first different checkpoint." : ""}` });
|
|
267
280
|
},
|
|
268
281
|
},
|
|
269
282
|
{
|
|
@@ -46,10 +46,10 @@ To get the command list, run the script with no arguments.
|
|
|
46
46
|
|
|
47
47
|
### Steps files
|
|
48
48
|
|
|
49
|
-
A steps file is a JSON list of steps. The steps run right after the program starts. Use a steps file when an intro waits for a key or a menu waits for a choice. For example, wait 50 frames and
|
|
49
|
+
A steps file is a JSON list of steps. The steps run right after the program starts. Use a steps file when an intro waits for a key or a menu waits for a choice. For example, wait 50 frames and push the space key:
|
|
50
50
|
|
|
51
51
|
```json
|
|
52
|
-
[{ "frames": 50 }, { "
|
|
52
|
+
[{ "frames": 50 }, { "press": { "keys": " " } }]
|
|
53
53
|
```
|
|
54
54
|
|
|
55
55
|
Each step has one of these kinds:
|
|
@@ -193,7 +193,9 @@ Traps:
|
|
|
193
193
|
- `captured`: true when the CPU got to `--until`. `pc` is that address.
|
|
194
194
|
- `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.
|
|
195
195
|
- `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.
|
|
196
|
-
- `notExecutedUnderIo`: parts of the segments in the RAM under the I/O area. In
|
|
196
|
+
- `notExecutedUnderIo`: parts of the segments in the RAM under the I/O area. In the 250 frames after the entry, the program did not execute code in these parts, and it did not read them as RAM. The VIC-II always reads RAM, also under the I/O area. Thus the parts do not hold the RAM that the VIC-II shows at the entry. This RAM is the screen, the bitmap or the charset, and the pointer and the data of each sprite that is on. When no part is of this type, or with `--range`, the body has no `notExecutedUnderIo`.
|
|
197
|
+
- `readUnderIo`: parts of the segments in the RAM under the I/O area that the program read as RAM in the 250 frames after the entry. The program did not execute code in these parts. When no part is of this type, the body has no `readUnderIo`.
|
|
198
|
+
- `undecidedUnderIo`: parts of the segments in the RAM under the I/O area where the check for reads did not complete. Keep these parts in the capture. When no part is of this type, the body has no `undecidedUnderIo`.
|
|
197
199
|
- `dropped`: the ranges from `$0400` that the stages wrote and that no segment holds. The ranges of `excluded` are not in `dropped`. Each range is in a block that is not a segment because it holds the entry of a later stage. `writtenBy` is the last stage that wrote the range. `stageEntry` is the entry of the later stage. When the capture dropped no byte, or with `--range`, the body has no `dropped`.
|
|
198
200
|
- `stages`: one item for each stage, as `stages` gives it.
|
|
199
201
|
- `differsFromReset`: the count of bytes that are not as a clean C64 has them at READY.
|
|
@@ -225,7 +227,7 @@ Traps:
|
|
|
225
227
|
|
|
226
228
|
- 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.
|
|
227
229
|
- A dropped range can be a part of the program. Make sure that the program does not use the bytes in `dropped`. If the program uses them, tell the user.
|
|
228
|
-
- `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 `
|
|
230
|
+
- `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 `press` step. If the CPU got to `--until` in a step, the reason names that step.
|
|
229
231
|
|
|
230
232
|
### `loads <program>`
|
|
231
233
|
|
|
@@ -111,7 +111,9 @@ export function captureBlocks(before: Uint8Array, after: Uint8Array, map: Uint8A
|
|
|
111
111
|
* variables all the time.
|
|
112
112
|
*/
|
|
113
113
|
export async function loads(program: string, options: { out: string; steps: LoadStep[]; drive: boolean; minBlock: number; exclude: AddressRange[] }): Promise<{ output: Record<string, unknown>; failed: boolean }> {
|
|
114
|
-
|
|
114
|
+
// The file is read once: image.json gets the SHA-256 of the bytes that the emulator ran.
|
|
115
|
+
const file = readProjectFile(program).bytes;
|
|
116
|
+
const ran = capturedProgram(program, file);
|
|
115
117
|
const client = await ViceSessionClient.open({ videoStandard: "pal" });
|
|
116
118
|
try {
|
|
117
119
|
// A clean machine at the READY prompt shows what the program changed at each capture. The run goes on after a capture, so it is read first.
|
|
@@ -123,7 +125,7 @@ export async function loads(program: string, options: { out: string; steps: Load
|
|
|
123
125
|
/** False while the map holds the writes of the KERNAL RAM test. */
|
|
124
126
|
let writesKnown = true;
|
|
125
127
|
if (program.toLowerCase().endsWith(".prg")) {
|
|
126
|
-
const
|
|
128
|
+
const bytes = file;
|
|
127
129
|
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 };
|
|
128
130
|
// The RAM before RUN, without the program, so the first capture holds the program too.
|
|
129
131
|
previous = await readMemoryInParts(client, 0x0000, 0x10000, "ram");
|
|
@@ -7,10 +7,13 @@ import { join } from "node:path";
|
|
|
7
7
|
|
|
8
8
|
import { type AddressRange, formatC64Address, hexWord, prgOf, spriteData, spritePointer, vicScreenMemory } from "#src/c64.ts";
|
|
9
9
|
import { resetToReady } from "#src/host-client/entry-state.ts";
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
10
|
+
import { writeRefusal, writeReported, type Written } from "#src/host-client/transfer.ts";
|
|
11
|
+
import { isRefusal } from "#src/errors.ts";
|
|
12
|
+
import { MAX_WATCH_SIZE, WireFailure } from "#src/host-client/tools.ts";
|
|
13
|
+
import { lastOpcode, readMemoryInParts, type ViceSessionClient } from "#src/host-client/vice-session.ts";
|
|
12
14
|
import { startScreenRanges } from "#src/knowledge/read.ts";
|
|
13
15
|
import { sha256 } from "#src/knowledge/text.ts";
|
|
16
|
+
import { isStore } from "#src/opcodes.ts";
|
|
14
17
|
import { projectRelative, projectRoot, resolveProjectPath } from "#src/project.ts";
|
|
15
18
|
|
|
16
19
|
type Registers = Awaited<ReturnType<ViceSessionClient["registersGet"]>>;
|
|
@@ -70,18 +73,18 @@ export function vicRam(io: { vic: Uint8Array; cia2: Uint8Array }, memory: Uint8A
|
|
|
70
73
|
|
|
71
74
|
/**
|
|
72
75
|
* The program file that a capture ran, for its image.json: the path in the
|
|
73
|
-
* project in one spelling, and the SHA-256 of the
|
|
76
|
+
* project in one spelling, and the SHA-256 of `bytes`, the bytes that ran. A release of the
|
|
74
77
|
* capture cites them, because git ignores the capture in local/. A file
|
|
75
78
|
* outside the project gives undefined: then a release cites the image.json.
|
|
76
79
|
*/
|
|
77
|
-
export function capturedProgram(path: string): { file: string; sha256: string } | undefined {
|
|
80
|
+
export function capturedProgram(path: string, bytes: Uint8Array): { file: string; sha256: string } | undefined {
|
|
78
81
|
let file: string;
|
|
79
82
|
try {
|
|
80
83
|
file = projectRelative(path);
|
|
81
84
|
} catch {
|
|
82
85
|
return undefined;
|
|
83
86
|
}
|
|
84
|
-
return { file, sha256: sha256(
|
|
87
|
+
return { file, sha256: sha256(bytes) };
|
|
85
88
|
}
|
|
86
89
|
|
|
87
90
|
const word = (bytes: Buffer, offset: number) => formatC64Address(bytes[offset]! | (bytes[offset + 1]! << 8));
|
|
@@ -195,3 +198,123 @@ export function writeCapture(
|
|
|
195
198
|
const removed = removeStaleFiles(folder, [...files, ...other.map((file) => file.name)]);
|
|
196
199
|
return { written, files, removed };
|
|
197
200
|
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* The CPU reads the RAM under the I/O area when bits 0 and 1 of $01 (LORAM and HIRAM) are clear; else a read there gives
|
|
204
|
+
* an I/O register or the character ROM. As the condition of a watchpoint, the emulator tests it at each read, so the
|
|
205
|
+
* reads of I/O registers (a raster wait, an interrupt acknowledge) do not stop the run.
|
|
206
|
+
*/
|
|
207
|
+
const RAM_UNDER_IO = { kind: "memory", address: 0x0001, operator: "eq", value: 0, mask: 0x03, space: "c64", view: "cpu" } as const;
|
|
208
|
+
/** The most stops at a store that the RAM check runs on after: a guard, as the emulator gives the dummy read of a store to a watchpoint only on request. */
|
|
209
|
+
const MAX_STORE_STOPS = 256;
|
|
210
|
+
/** The RAM check runs in parts of this many frames, and ends when its time is over between two parts. */
|
|
211
|
+
const CHECK_PART_FRAMES = 25;
|
|
212
|
+
/** The most time of the RAM check. A condition on each read of the watched I/O area makes the emulator slower. */
|
|
213
|
+
export const MAX_CHECK_MS = 30_000;
|
|
214
|
+
const ENTRY_SNAPSHOT = "capture-entry";
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* Runs `work` from where the machine is, and then puts the machine back there, also when `work` fails. The snapshot is
|
|
218
|
+
* removed also when the restore fails. The first failure is thrown: of `work`, with a failed restore named in it, else
|
|
219
|
+
* of the restore, else of the remove.
|
|
220
|
+
*/
|
|
221
|
+
export async function fromHere<T>(client: Pick<ViceSessionClient, "snapshot">, work: () => Promise<T>): Promise<T> {
|
|
222
|
+
await client.snapshot({ action: "save", name: ENTRY_SNAPSHOT });
|
|
223
|
+
const attempt = async <U>(run: () => Promise<U>): Promise<{ value: U } | { error: unknown }> => {
|
|
224
|
+
try {
|
|
225
|
+
return { value: await run() };
|
|
226
|
+
} catch (error) {
|
|
227
|
+
return { error };
|
|
228
|
+
}
|
|
229
|
+
};
|
|
230
|
+
const done = await attempt(work);
|
|
231
|
+
const restored = await attempt(() => client.snapshot({ action: "restore", name: ENTRY_SNAPSHOT }));
|
|
232
|
+
const removed = await attempt(() => client.snapshot({ action: "remove", name: ENTRY_SNAPSHOT }));
|
|
233
|
+
if ("error" in done) {
|
|
234
|
+
if (!("error" in restored)) throw done.error;
|
|
235
|
+
// The failed restore is in the error of the work, also when the work threw no Error.
|
|
236
|
+
const error = done.error instanceof Error ? done.error : new Error(String(done.error));
|
|
237
|
+
const why = restored.error instanceof Error ? restored.error.message : String(restored.error);
|
|
238
|
+
error.message = `${error.message.replace(/\.?$/, ".")} The machine did not go back to the snapshot: ${why}`;
|
|
239
|
+
throw error;
|
|
240
|
+
}
|
|
241
|
+
if ("error" in restored) throw restored.error;
|
|
242
|
+
if ("error" in removed) throw removed.error;
|
|
243
|
+
return done.value;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/**
|
|
247
|
+
* Runs the program on from where it is for `frames` frames, with read watchpoints that stop only at a read of the RAM
|
|
248
|
+
* under the I/O area, and gives the ranges that the program read there as RAM. The memory map gives each of these
|
|
249
|
+
* reads as an I/O read. The first read of a range removes the watchpoints of the range, so the run stops at most once
|
|
250
|
+
* for each range. A stop comes after the instruction that made the access: an indexed store reads its address before
|
|
251
|
+
* it writes it, and that read is no read of the program, so the run goes on. A check that ends before its frames (after
|
|
252
|
+
* MAX_STORE_STOPS such stops, a JAM, another stop, a frame that the emulator did not give in time, or after `limitMs`)
|
|
253
|
+
* gives the ranges without a read as `undecided`, not unread: the check never fails the capture. The machine then goes back to where it was.
|
|
254
|
+
*/
|
|
255
|
+
export async function readAsRam<T extends AddressRange>(
|
|
256
|
+
client: Pick<ViceSessionClient, "snapshot" | "watchpoint" | "observe" | "execution" | "cpuHistory">,
|
|
257
|
+
ranges: readonly T[],
|
|
258
|
+
frames: number,
|
|
259
|
+
limitMs = MAX_CHECK_MS,
|
|
260
|
+
): Promise<{ read: T[]; undecided: T[] }> {
|
|
261
|
+
// The watchpoint ids of each range: a watchpoint covers at most MAX_WATCH_SIZE bytes.
|
|
262
|
+
const points = new Map<number, number>();
|
|
263
|
+
const read = new Set<number>();
|
|
264
|
+
// Only a check that ran all its frames, or found a read in each range, tells which ranges the program did not read.
|
|
265
|
+
let complete = false;
|
|
266
|
+
await fromHere(client, async () => {
|
|
267
|
+
try {
|
|
268
|
+
for (const [index, range] of ranges.entries()) {
|
|
269
|
+
for (let address = range.start; address <= range.end; address += MAX_WATCH_SIZE) {
|
|
270
|
+
const size = Math.min(MAX_WATCH_SIZE, range.end - address + 1);
|
|
271
|
+
points.set((await client.watchpoint({ action: "add", address, size, access: "read", space: "c64", condition: RAM_UNDER_IO })).id, index);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
// The frames end at the raster position where the check starts, after a stop too.
|
|
275
|
+
const { timing } = await client.observe({ timing: true });
|
|
276
|
+
if (timing === undefined) throw new WireFailure("operation-failed", "the emulator gave no raster position");
|
|
277
|
+
const anchor = { line: timing.rasterLine, cycle: timing.rasterCycle };
|
|
278
|
+
let left = frames;
|
|
279
|
+
let storeStops = 0;
|
|
280
|
+
const deadline = Date.now() + limitMs;
|
|
281
|
+
for (;;) {
|
|
282
|
+
if (left <= 0 || read.size === ranges.length) {
|
|
283
|
+
complete = true;
|
|
284
|
+
break;
|
|
285
|
+
}
|
|
286
|
+
if (Date.now() >= deadline) break;
|
|
287
|
+
const count = Math.min(left, CHECK_PART_FRAMES);
|
|
288
|
+
const run = await client.execution({ action: "advance-frames", count, space: "c64", anchor });
|
|
289
|
+
// "frames": the frames of the part ran. A stop in its last frame still counts.
|
|
290
|
+
if (run.stopReason === "frames") {
|
|
291
|
+
left -= count;
|
|
292
|
+
continue;
|
|
293
|
+
}
|
|
294
|
+
left -= run.advancedFrames ?? 0;
|
|
295
|
+
const index = run.pointId === undefined ? undefined : points.get(run.pointId);
|
|
296
|
+
if (run.stopReason !== "watchpoint" || index === undefined) break;
|
|
297
|
+
const opcode = await lastOpcode(client);
|
|
298
|
+
if (opcode !== undefined && isStore(opcode)) {
|
|
299
|
+
if (++storeStops > MAX_STORE_STOPS) break;
|
|
300
|
+
continue;
|
|
301
|
+
}
|
|
302
|
+
read.add(index);
|
|
303
|
+
for (const [id, of] of [...points]) {
|
|
304
|
+
if (of !== index) continue;
|
|
305
|
+
await client.watchpoint({ action: "remove", id });
|
|
306
|
+
points.delete(id);
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
} catch (error) {
|
|
310
|
+
// A refusal (a point or a condition that the emulator does not take, a frame that does not come in time) ends the
|
|
311
|
+
// check with the unread ranges undecided, and the capture goes on. A lost session fails.
|
|
312
|
+
if (!isRefusal(error) || error.code === "machine-unavailable") throw error;
|
|
313
|
+
} finally {
|
|
314
|
+
for (const id of points.keys()) await client.watchpoint({ action: "remove", id }).catch((error: unknown) => {
|
|
315
|
+
if (!isRefusal(error) || error.code === "machine-unavailable") throw error;
|
|
316
|
+
});
|
|
317
|
+
}
|
|
318
|
+
});
|
|
319
|
+
return { read: ranges.filter((_, index) => read.has(index)), undecided: complete ? [] : ranges.filter((_, index) => !read.has(index)) };
|
|
320
|
+
}
|
|
@@ -188,11 +188,15 @@ export function captureSegments(
|
|
|
188
188
|
const joined = { start: loaded.start, end: loaded.end, loaded: true as const };
|
|
189
189
|
const apart = segments.filter((segment) => {
|
|
190
190
|
if (segment.end + 1 < joined.start || segment.start > joined.end + 1) return true;
|
|
191
|
+
// A segment that only touches the PRG joins it as a block joins a block: never across a bound of the I/O area.
|
|
192
|
+
if (segment.start === joined.end + 1 && ioSide(segment.start) !== ioSide(joined.end)) return true;
|
|
193
|
+
if (segment.end + 1 === joined.start && ioSide(segment.end) !== ioSide(joined.start)) return true;
|
|
191
194
|
joined.start = Math.min(joined.start, segment.start);
|
|
192
195
|
joined.end = Math.max(joined.end, segment.end);
|
|
193
196
|
return false;
|
|
194
197
|
});
|
|
195
|
-
|
|
198
|
+
// A join over a bound of the I/O area is cut there: the RAM under it stays a segment of its own.
|
|
199
|
+
return [...apart, ...cutAtIoArea(joined).map((piece) => ({ ...piece, loaded: true as const }))].sort((a, b) => a.start - b.start);
|
|
196
200
|
}
|
|
197
201
|
|
|
198
202
|
/**
|
|
@@ -22,7 +22,7 @@ import { listed, OPTIONS, reply, runScript, UsageError, type Call, type CommandS
|
|
|
22
22
|
import { basicStart, inspect, writtenThenExecuted } from "./lib/evidence.ts";
|
|
23
23
|
import { loads, readLoadSteps } from "./lib/loads.ts";
|
|
24
24
|
import { callReturn, captureSegments, droppedRanges, executedIn, mergeMaps, notExecutedUnderIo, stageCandidates, stagePoints, usedAfterEntry, withoutRanges } from "./lib/stages.ts";
|
|
25
|
-
import { capturedProgram, entryStateFile, machineState, readyState, vectorsOf, vicRam, writeCapture } from "./lib/machine.ts";
|
|
25
|
+
import { capturedProgram, entryStateFile, fromHere, machineState, readAsRam, readyState, vectorsOf, vicRam, writeCapture } from "./lib/machine.ts";
|
|
26
26
|
|
|
27
27
|
/** Written-then-executed bytes from this many on are unpacking, decrypting or relocating, not self-changing code. */
|
|
28
28
|
const UNPACKED_BYTES = 256;
|
|
@@ -508,23 +508,17 @@ async function stages(program: string, options: { frames: number; entry?: number
|
|
|
508
508
|
/** Frames that the program runs after its entry to show the memory that it uses. */
|
|
509
509
|
const AFTER_ENTRY_FRAMES = 250;
|
|
510
510
|
|
|
511
|
-
const ENTRY_SNAPSHOT = "capture-entry";
|
|
512
|
-
|
|
513
511
|
/**
|
|
514
512
|
* Runs the program on from its entry and gives the RAM that it used: the
|
|
515
513
|
* evidence that a block that a loader or a stage left is part of the
|
|
516
514
|
* program. The machine then goes back to the entry.
|
|
517
515
|
*/
|
|
518
516
|
async function usedAfter(client: ViceSessionClient): Promise<(address: number) => boolean> {
|
|
519
|
-
|
|
520
|
-
try {
|
|
517
|
+
return fromHere(client, async () => {
|
|
521
518
|
await client.memmap({ action: "clear" });
|
|
522
519
|
await client.execution({ action: "advance-frames", count: AFTER_ENTRY_FRAMES, space: "c64" });
|
|
523
520
|
return usedAfterEntry(await readCoverage(client));
|
|
524
|
-
}
|
|
525
|
-
await client.snapshot({ action: "restore", name: ENTRY_SNAPSHOT });
|
|
526
|
-
await client.snapshot({ action: "remove", name: ENTRY_SNAPSHOT });
|
|
527
|
-
}
|
|
521
|
+
});
|
|
528
522
|
}
|
|
529
523
|
|
|
530
524
|
/** Why a capture can wait for --until in vain: a step ran over it. */
|
|
@@ -561,7 +555,10 @@ async function capture(
|
|
|
561
555
|
const used = options.range === undefined ? await usedAfter(client) : undefined;
|
|
562
556
|
const found = used === undefined ? [options.range!] : captureSegments(followed.stages, registers.pc, { loaded: { start: load, end: Math.min(0xffff, load + bytes.length - 3) }, used });
|
|
563
557
|
const segments = withoutRanges(found, options.exclude);
|
|
564
|
-
|
|
558
|
+
// The memory map cannot show a read of the RAM under the I/O area: a run with watchpoints finds the parts that the program read as RAM.
|
|
559
|
+
const notExecuted = used === undefined ? [] : notExecutedUnderIo(segments, used, vicRam(state.io, memory));
|
|
560
|
+
const { read: readUnderIo, undecided } = notExecuted.length === 0 ? { read: [], undecided: [] } : await readAsRam(client, notExecuted, AFTER_ENTRY_FRAMES);
|
|
561
|
+
const underIo = notExecuted.filter((range) => !readUnderIo.includes(range) && !undecided.includes(range)).map(formatC64RangeFields);
|
|
565
562
|
// The written ranges that the leftover rule took out of the segments. A --range takes no rule.
|
|
566
563
|
const dropped = (options.range === undefined ? droppedRanges(followed.stages, registers.pc, [...found, ...options.exclude]) : []).map((range) => ({
|
|
567
564
|
...formatC64RangeFields(range),
|
|
@@ -571,7 +568,7 @@ async function capture(
|
|
|
571
568
|
const vectors = vectorsOf(state, memory);
|
|
572
569
|
// A clean machine at the READY prompt shows what the loader and the stages changed.
|
|
573
570
|
const entry = entryStateFile(registers, state, vectors, await readyState(client));
|
|
574
|
-
const ran = capturedProgram(program);
|
|
571
|
+
const ran = capturedProgram(program, bytes);
|
|
575
572
|
const { written, removed } = writeCapture(
|
|
576
573
|
options.out,
|
|
577
574
|
memory,
|
|
@@ -600,6 +597,8 @@ async function capture(
|
|
|
600
597
|
...(removed.length === 0 ? {} : { removed }),
|
|
601
598
|
segments: segments.map((segment) => ({ ...formatC64RangeFields(segment), ...("loaded" in segment ? { loaded: true } : {}) })),
|
|
602
599
|
...(underIo.length === 0 ? {} : { notExecutedUnderIo: underIo }),
|
|
600
|
+
...(readUnderIo.length === 0 ? {} : { readUnderIo: readUnderIo.map(formatC64RangeFields) }),
|
|
601
|
+
...(undecided.length === 0 ? {} : { undecidedUnderIo: undecided.map(formatC64RangeFields) }),
|
|
603
602
|
...(options.exclude.length === 0 ? {} : { excluded: options.exclude.map(formatC64RangeFields) }),
|
|
604
603
|
...(dropped.length === 0 ? {} : { dropped }),
|
|
605
604
|
stages: showStages(followed.stages),
|
|
@@ -692,13 +691,15 @@ function captured(call: Call, { output, failed }: { output: Record<string, unkno
|
|
|
692
691
|
if (failed) return result;
|
|
693
692
|
const dropped = ((output.dropped ?? []) as Array<{ start: string; end: string }>).reduce((sum, range) => sum + parseC64Address(range.end) - parseC64Address(range.start) + 1, 0);
|
|
694
693
|
const underIo = ((output.notExecutedUnderIo ?? []) as Array<{ start: string; end: string }>).map((range) => `${range.start}-${range.end}`);
|
|
694
|
+
const undecided = ((output.undecidedUnderIo ?? []) as Array<{ start: string; end: string }>).map((range) => `${range.start}-${range.end}`);
|
|
695
695
|
return reply(result, {
|
|
696
696
|
hint: joined([
|
|
697
697
|
`Disassemble the code at ${output.pc as string}. Make sure that it is the program and not the unpacker again.`,
|
|
698
698
|
dropped === 0 ? undefined : `The segments do not hold ${dropped} bytes that the stages wrote, because they are in blocks with the entry of a later stage. dropped gives their ranges. Make sure that the program does not use these bytes.`,
|
|
699
699
|
underIo.length === 0
|
|
700
700
|
? undefined
|
|
701
|
-
: `In the RAM under the I/O area, the program
|
|
701
|
+
: `In the RAM under the I/O area, the program did not execute or read ${underIo.join(", ")} in the ${AFTER_ENTRY_FRAMES} frames after the entry. Make sure that the program does not use these bytes later. If it does not, give each of these ranges as --exclude and capture again.`,
|
|
702
|
+
undecided.length === 0 ? undefined : `In the RAM under the I/O area, the check for reads of ${undecided.join(", ")} did not complete. Keep these ranges in the capture.`,
|
|
702
703
|
`Then put the capture ${call.string("out")!}/image.json into the project knowledge.`,
|
|
703
704
|
]),
|
|
704
705
|
});
|
package/skills/emulator/SKILL.md
CHANGED
|
@@ -47,13 +47,13 @@ Read the description of a tool before you use it for the first time. It gives th
|
|
|
47
47
|
|
|
48
48
|
A result field `emulatorFlaw` names a known flaw of the emulator. Tell the user about the flaw. Do not use a result that the flaw can make wrong as a fact.
|
|
49
49
|
|
|
50
|
-
For a large result, give `out`. Write a file that is only for your work in `.c64-re-tools/local/` of the project. Git ignores that folder.
|
|
50
|
+
Give each path to a tool as an absolute path, for example `/home/me/game/build/game.prg`. A tool refuses a relative path. For a large result, give `out`. The result then gives the absolute path of the file. Write a file that is only for your work in `.c64-re-tools/local/` of the project. Git ignores that folder.
|
|
51
51
|
|
|
52
52
|
To keep a coverage run:
|
|
53
53
|
|
|
54
54
|
1. Clear the memory map with `c64_memmap` action `clear`.
|
|
55
55
|
2. Run the part of the program that you want to keep.
|
|
56
|
-
3. Read the map with `c64_memmap` action `read` and `out
|
|
56
|
+
3. Read the map with `c64_memmap` action `read` and `out`. Give the absolute path of a file in `.c64-re-tools/local/` of the project, for example `/home/me/game/.c64-re-tools/local/attract.bin`.
|
|
57
57
|
4. Add the file to the coverage of the project knowledge.
|
|
58
58
|
|
|
59
59
|
## Workflow
|
package/src/host/vice/adapter.ts
CHANGED
|
@@ -64,7 +64,8 @@ export function conditionExpression(condition: Condition, space: Space): string
|
|
|
64
64
|
"A memory target or a memory condition tests only space c64 memory. For the drive, use a watchpoint in space drive8, or a c64_run_until address target in space drive8.",
|
|
65
65
|
);
|
|
66
66
|
}
|
|
67
|
-
|
|
67
|
+
const byte = `@${condition.view}:${formatC64Address(condition.address)}`;
|
|
68
|
+
return `(${condition.mask === undefined ? byte : `(${byte} & ${formatC64Byte(condition.mask)})`} ${operator(condition.operator)} ${formatC64Byte(condition.value)})`;
|
|
68
69
|
}
|
|
69
70
|
case "raster": {
|
|
70
71
|
const line = `(RL == $${condition.line.toString(16)})`;
|
package/src/host-client/image.ts
CHANGED
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
// An image.json of the c64-unpacker skill (a 64 KiB memory and its segments)
|
|
2
2
|
// or a PRG, read from the project to put it into the knowledge.
|
|
3
3
|
|
|
4
|
-
import {
|
|
4
|
+
import { createHash } from "node:crypto";
|
|
5
|
+
import { dirname, join } from "node:path";
|
|
5
6
|
|
|
6
7
|
import { isRefusal, Refusal } from "../errors.ts";
|
|
7
8
|
import { formatC64Address, prgRange } from "../c64.ts";
|
|
8
9
|
import { readEntryState, type EntryState } from "./entry-state.ts";
|
|
9
10
|
import { isObject } from "../protocol/messages.ts";
|
|
11
|
+
import { projectRelative } from "../project.ts";
|
|
10
12
|
import { readProjectFile, readProjectJson } from "./transfer.ts";
|
|
11
13
|
|
|
12
14
|
export interface Image {
|
|
@@ -24,6 +26,33 @@ export interface Image {
|
|
|
24
26
|
program?: { file: string; sha256: string };
|
|
25
27
|
}
|
|
26
28
|
|
|
29
|
+
/**
|
|
30
|
+
* The program file that the capture of the image.json at `path` ran, as a
|
|
31
|
+
* citation of the project: its path in one spelling and its SHA-256. Refused
|
|
32
|
+
* when the project has no such file now, or when its bytes are not the bytes
|
|
33
|
+
* that the capture ran: the citation would not be true.
|
|
34
|
+
*/
|
|
35
|
+
export function checkedProgramCitation(path: string, program: { file: string; sha256: string }): { file: string; sha256: string } {
|
|
36
|
+
const remedy = "Capture the program again from its file in this project, then give the new image.json.";
|
|
37
|
+
let file: string;
|
|
38
|
+
try {
|
|
39
|
+
file = projectRelative(program.file);
|
|
40
|
+
} catch {
|
|
41
|
+
throw new Refusal("invalid-input", `${path} names the program file ${program.file}, which is not a path in this project. ${remedy}`);
|
|
42
|
+
}
|
|
43
|
+
let bytes: Uint8Array;
|
|
44
|
+
try {
|
|
45
|
+
bytes = readProjectFile(file).bytes;
|
|
46
|
+
} catch (error) {
|
|
47
|
+
if (isRefusal(error) && error.code === "not-found") throw new Refusal("not-found", `${path} names the program file ${file}, and the project has no file there. ${remedy}`);
|
|
48
|
+
throw error;
|
|
49
|
+
}
|
|
50
|
+
if (createHash("sha256").update(bytes).digest("hex") !== program.sha256) {
|
|
51
|
+
throw new Refusal("conflict", `The program file ${file} changed after the capture in ${path}: its bytes are not the bytes that the capture ran. ${remedy}`);
|
|
52
|
+
}
|
|
53
|
+
return { file, sha256: program.sha256 };
|
|
54
|
+
}
|
|
55
|
+
|
|
27
56
|
/** The kinds of media files that are no PRG, by extension. */
|
|
28
57
|
const MEDIA_KINDS: Record<string, string> = {
|
|
29
58
|
d64: "a disk image",
|
|
@@ -98,11 +127,11 @@ export function readImage(path: string): Image {
|
|
|
98
127
|
if (segment.end < segment.start) fail(`the segment at ${formatC64Address(segment.start)} ends before it starts`);
|
|
99
128
|
if (index > 0 && segment.start <= segments[index - 1]!.end) fail(`the segments at ${formatC64Address(segments[index - 1]!.start)} and ${formatC64Address(segment.start)} overlap`);
|
|
100
129
|
});
|
|
101
|
-
const directory =
|
|
102
|
-
const memory = readProjectFile(
|
|
130
|
+
const directory = dirname(path);
|
|
131
|
+
const memory = readProjectFile(join(directory, manifest.image as string)).bytes;
|
|
103
132
|
if (memory.length !== 0x10000) fail(`its image has ${memory.length} bytes, not 65536`);
|
|
104
133
|
const image: Image = { segments, byteAt: (at) => memory[at]!, memory };
|
|
105
|
-
const state = entryStateNextTo(
|
|
134
|
+
const state = entryStateNextTo(join(directory, "entry_state.json"));
|
|
106
135
|
if (state !== undefined) image.state = state;
|
|
107
136
|
if (manifest.entry !== undefined) image.entry = address(manifest.entry, "entry");
|
|
108
137
|
if (Array.isArray(manifest.stages)) image.stages = manifest.stages.map((stage, index) => (isObject(stage) ? stage : fail(`stage ${index + 1} is not an object`)));
|
package/src/host-client/tools.ts
CHANGED
|
@@ -87,5 +87,5 @@ export async function decodeBasic(request: { program: string }, options: ToolCal
|
|
|
87
87
|
/** Skill scripts see failures, value guards and wire limits through the host-client, never the private protocol module. */
|
|
88
88
|
export { isInteger, isObject, WireFailure } from "../protocol/messages.ts";
|
|
89
89
|
export { DISK_BLOCK_BYTES, DISK_IMAGE_TYPES, MAX_DISK_SECTORS } from "../protocol/tools.ts";
|
|
90
|
-
export { MAX_BASELINES, MAX_EXECUTION_COUNT, MAX_MASK_RECTANGLES, MAX_MEMORY_READ, MAX_MEMORY_WRITE, maskCoversFrame } from "../protocol/vice.ts";
|
|
90
|
+
export { MAX_BASELINES, MAX_EXECUTION_COUNT, MAX_MASK_RECTANGLES, MAX_MEMORY_READ, MAX_MEMORY_WRITE, MAX_WATCH_SIZE, maskCoversFrame } from "../protocol/vice.ts";
|
|
91
91
|
export { MAX_TRACE_FRAMES, MAX_TRACE_HITS, MAX_TRACE_POINTS, TRACE_KINDS, type TraceHit, type TraceKind } from "../protocol/vice.ts";
|