@henols/c64-re-tools 2.6.0-rc.17 → 2.6.0-rc.19
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-development/SKILL.md +1 -1
- package/skills/c64-docs/SKILL.md +2 -2
- package/skills/c64-docs/scripts/lib/reference.ts +92 -38
- package/skills/c64-reverse-engineering/SKILL.md +2 -2
- package/skills/c64-source/scripts/lib/loader.ts +49 -28
- package/skills/c64-source/scripts/lib/source.ts +12 -1
- package/skills/c64-source/scripts/source.ts +2 -4
- package/skills/c64-testing/SKILL.md +4 -1
- package/skills/c64-testing/scripts/lib/recording.ts +138 -25
- package/skills/c64-testing/scripts/lib/replay.ts +31 -5
- package/skills/c64-unpacker/scripts/unpacker.ts +15 -5
- package/src/host/main.ts +2 -2
- package/src/host/server.ts +3 -1
- package/src/host/vice/process.ts +34 -17
- package/src/host/vice/session.ts +55 -27
- package/src/knowledge/start-screen.ts +2 -0
- package/tools/c64run.c +33 -4
|
@@ -17,7 +17,7 @@ import { keyTaps, type KeyTap } from "#src/c64-keys.ts";
|
|
|
17
17
|
import { READY_FRAMES } from "#src/host-client/entry-state.ts";
|
|
18
18
|
import { ACTION_STEP_KINDS, checkActionStep, isInteger, isObject, keyboardBytes, renamedField, stepKind, type ActionStep, type Location } from "#src/host-client/steps.ts";
|
|
19
19
|
import { readProjectFile, type Written } from "#src/host-client/transfer.ts";
|
|
20
|
-
import { START_SCREEN_CONTINUE, START_SCREEN_WAIT } from "#src/knowledge/start-screen.ts";
|
|
20
|
+
import { LOADER_JUMP, START_SCREEN_CONTINUE, START_SCREEN_WAIT } from "#src/knowledge/start-screen.ts";
|
|
21
21
|
import { PAL_FRAME_CYCLES, type C64RunSession, type CoreStatus } from "#src/native/c64run.ts";
|
|
22
22
|
import type { Workspace } from "#src/native/staging.ts";
|
|
23
23
|
import { namesOf, type Outcome } from "./scenario.ts";
|
|
@@ -225,7 +225,6 @@ export function readRecordFile(path: string): RecordFile {
|
|
|
225
225
|
checkCoreStep(step, at, fail);
|
|
226
226
|
return step;
|
|
227
227
|
});
|
|
228
|
-
if (new Set(steps.flatMap(addressTarget)).size > MAX_COUNTED_TARGETS) fail(`the runUntil steps go to more than ${MAX_COUNTED_TARGETS} addresses`);
|
|
229
228
|
return {
|
|
230
229
|
name: value.name as string,
|
|
231
230
|
program: value.program as string,
|
|
@@ -354,6 +353,50 @@ export function siteMap(sites: RecordedSite[], from: Map<string, number>, to: Ma
|
|
|
354
353
|
return moved;
|
|
355
354
|
}
|
|
356
355
|
|
|
356
|
+
/** Where the original came to the entry that the loader of a rebuild jumps to. */
|
|
357
|
+
export interface EntryPoint {
|
|
358
|
+
/** The tick of the first opcode fetch at the entry. */
|
|
359
|
+
tick: number;
|
|
360
|
+
/** The count of each pc key, by its target, before that fetch. */
|
|
361
|
+
counts: Map<string, number>;
|
|
362
|
+
/** The number of events of the recording before the entry: always the first ones. */
|
|
363
|
+
eventsBefore: number;
|
|
364
|
+
/** The number of checkpoints before the entry, which the samples of the original leave out. */
|
|
365
|
+
samplesBefore: number;
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
/**
|
|
369
|
+
* A loader with a start screen that RUN starts waits for a key or a fire button that the recording does not have:
|
|
370
|
+
* the rebuild goes on after the wait, as the check of the loader does. Gives the tick of the wait, a problem, or
|
|
371
|
+
* undefined when the rebuild has no start screen.
|
|
372
|
+
*/
|
|
373
|
+
async function passStartScreen(core: C64RunSession, own: Map<string, number>, limit: number): Promise<number | string | undefined> {
|
|
374
|
+
const wait = own.get(START_SCREEN_WAIT);
|
|
375
|
+
const resume = own.get(START_SCREEN_CONTINUE);
|
|
376
|
+
if (wait === undefined || resume === undefined) return undefined;
|
|
377
|
+
const reached = await core.status(`run-pc ${hex(wait)} ${limit}`);
|
|
378
|
+
if (reached.word !== "reached") return `the rebuild did not come to the wait of its start screen at ${formatC64Address(wait)}`;
|
|
379
|
+
await core.status(`goto ${hex(resume)}`);
|
|
380
|
+
return reached.tick;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
/**
|
|
384
|
+
* The entry that the generated loader of a rebuild jumps to: the operand of its jump, from a short run of the
|
|
385
|
+
* rebuild. Gives a problem when the rebuild does not come to the jump.
|
|
386
|
+
*/
|
|
387
|
+
export async function loaderEntry(core: C64RunSession, recording: Recording, subject: ReplaySubject): Promise<number | string> {
|
|
388
|
+
const own = namesOf(subject.symbols);
|
|
389
|
+
const jump = own.get(LOADER_JUMP)!;
|
|
390
|
+
const limit = recording.ticks * REBUILD_TIME_FACTOR;
|
|
391
|
+
await core.init();
|
|
392
|
+
await startProgram(core, readProjectFile(subject.program).bytes, false);
|
|
393
|
+
const screen = await passStartScreen(core, own, limit);
|
|
394
|
+
if (typeof screen === "string") return screen;
|
|
395
|
+
if ((await core.status(`run-pc ${hex(jump)} ${limit}`)).word !== "reached") return `the rebuild did not come to the jump of its loader at ${formatC64Address(jump)}`;
|
|
396
|
+
const operand = await core.peek((jump + 1) & 0xffff, 2);
|
|
397
|
+
return operand[0]! | (operand[1]! << 8);
|
|
398
|
+
}
|
|
399
|
+
|
|
357
400
|
/** Power-on and READY, then the program in memory as a LOAD leaves it, and RUN in the keyboard queue. */
|
|
358
401
|
async function startProgram(core: C64RunSession, prg: Uint8Array, load: boolean): Promise<CoreStatus> {
|
|
359
402
|
if (prg.length < 3) throw new Refusal("invalid-input", "the program is not a PRG file");
|
|
@@ -491,12 +534,15 @@ export async function record(
|
|
|
491
534
|
at.code(file.compare.checkpoint);
|
|
492
535
|
for (const item of file.compare.state) at.data(item.address);
|
|
493
536
|
}
|
|
537
|
+
// Two names can give one address: the replay core counts each address once.
|
|
538
|
+
const targets = [...new Set(file.steps.flatMap(addressTarget).map(at.code))];
|
|
539
|
+
if (targets.length > MAX_COUNTED_TARGETS) throw new Refusal("invalid-input", `record file of ${file.name}: the runUntil steps go to more than ${MAX_COUNTED_TARGETS} addresses`);
|
|
494
540
|
const reads = workspace.path(RECORDING_FILES.reads);
|
|
495
541
|
const coverage = workspace.path(RECORDING_FILES.coverage);
|
|
496
542
|
await core.init();
|
|
497
543
|
await core.command(`inputs ${inputsArgument(file.inputs)}`);
|
|
498
544
|
await core.command(`record ${reads}`);
|
|
499
|
-
await countAt(core,
|
|
545
|
+
await countAt(core, targets);
|
|
500
546
|
await startProgram(core, prg, file.load ?? false);
|
|
501
547
|
// From READY on: the start of the C64 itself is never in the map.
|
|
502
548
|
await core.command(COVERAGE_COMMANDS.get(file.coverage) ?? `coverage on-pc ${hex(parseC64Address(file.coverage))}`);
|
|
@@ -620,6 +666,8 @@ export interface SideRun {
|
|
|
620
666
|
problem?: string;
|
|
621
667
|
/** True when the rebuild went on after the wait of its start screen. */
|
|
622
668
|
startScreenSkipped?: boolean;
|
|
669
|
+
/** The original with an `entry`: where it came to that entry, when it came to it. */
|
|
670
|
+
entryPoint?: EntryPoint;
|
|
623
671
|
/**
|
|
624
672
|
* Input reads that the recording has no value for, which got the fixed idle value:
|
|
625
673
|
* at sites that it does not have, and after its end at a site.
|
|
@@ -640,7 +688,7 @@ export async function replaySide(
|
|
|
640
688
|
folder: string,
|
|
641
689
|
subject: ReplaySubject,
|
|
642
690
|
workspace: Workspace,
|
|
643
|
-
options: { compare?: Comparison; stop?: number; dump?: number; pins?: string[] } = {},
|
|
691
|
+
options: { compare?: Comparison; stop?: number; dump?: number; pins?: string[]; entry?: number; handover?: { entry: number; original: EntryPoint } } = {},
|
|
644
692
|
): Promise<SideRun & { ram?: Uint8Array }> {
|
|
645
693
|
const prg = readProjectFile(subject.program).bytes;
|
|
646
694
|
const original = subject.side === "original";
|
|
@@ -663,9 +711,10 @@ export async function replaySide(
|
|
|
663
711
|
await core.command(`inputs ${inputsArgument(recording.inputs)}`);
|
|
664
712
|
await core.command(`site-map ${mapFile}`);
|
|
665
713
|
await core.command(`replay ${reads}`);
|
|
666
|
-
|
|
714
|
+
let sampling = false;
|
|
715
|
+
const startSampling = async (compare: Comparison) => {
|
|
667
716
|
const stop = options.dump ?? options.stop ?? 0;
|
|
668
|
-
const pinned =
|
|
717
|
+
const pinned = compare.pin ?? [];
|
|
669
718
|
if (options.pins !== undefined && pinned.length > 0) {
|
|
670
719
|
// The rebuild: each checkpoint first gets the original's values of the random state.
|
|
671
720
|
const pinFile = workspace.path(`${subject.side}-pins.txt`);
|
|
@@ -673,33 +722,74 @@ export async function replaySide(
|
|
|
673
722
|
await core.command(`pin ${pinFile} ${rangesArgument(pinned, at)}`);
|
|
674
723
|
}
|
|
675
724
|
// The samples hold the state, then the pinned items.
|
|
676
|
-
await core.command(`sample ${hex(at.code(
|
|
677
|
-
|
|
678
|
-
|
|
725
|
+
await core.command(`sample ${hex(at.code(compare.checkpoint))} ${samples} ${rangesArgument([...compare.state, ...pinned], at)}${stop > 0 ? ` ${stop}` : ""}`);
|
|
726
|
+
sampling = true;
|
|
727
|
+
};
|
|
728
|
+
// A rebuild with a loader takes its checkpoints from its entry on, as the original leaves out those before its own.
|
|
729
|
+
if (options.compare !== undefined && options.handover === undefined) await startSampling(options.compare);
|
|
730
|
+
const targets = recording.events.flatMap((event) => ("pc" in event.key ? [at.code(event.key.pc)] : []));
|
|
731
|
+
await countAt(core, targets);
|
|
732
|
+
if (options.entry !== undefined) await core.command(`mark ${hex(options.entry)}`);
|
|
679
733
|
await startProgram(core, prg, recording.load);
|
|
680
|
-
|
|
734
|
+
const base = original ? recording.ticks : recording.ticks * REBUILD_TIME_FACTOR;
|
|
735
|
+
let limit = base;
|
|
681
736
|
let problem: string | undefined;
|
|
682
|
-
// A
|
|
683
|
-
// the rebuild goes on after the wait, as the check of the loader does. The cycles to the wait do not count.
|
|
684
|
-
const wait = own.get(START_SCREEN_WAIT);
|
|
685
|
-
const resume = own.get(START_SCREEN_CONTINUE);
|
|
737
|
+
// A tick key of the rebuild comes this many cycles later than in the original.
|
|
686
738
|
let skipped = 0;
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
739
|
+
let screenSkipped = false;
|
|
740
|
+
if (!original && !recording.load) {
|
|
741
|
+
// The cycles to the wait of a start screen do not count.
|
|
742
|
+
const screen = await passStartScreen(core, own, limit);
|
|
743
|
+
if (typeof screen === "string") problem = screen;
|
|
744
|
+
else if (screen !== undefined) {
|
|
745
|
+
skipped = screen;
|
|
746
|
+
limit = base + skipped;
|
|
747
|
+
screenSkipped = true;
|
|
748
|
+
}
|
|
749
|
+
}
|
|
750
|
+
// A pc key counts the opcode fetches from the start, also those of the code before the entry: the unpacker of
|
|
751
|
+
// the original, or the loader of the rebuild. The rebuild counts again from the jump of its loader, without those of the original.
|
|
752
|
+
const { handover } = options;
|
|
753
|
+
if (problem === undefined && handover !== undefined) {
|
|
754
|
+
const jump = own.get(LOADER_JUMP)!;
|
|
755
|
+
if ((await core.status(`run-pc ${hex(jump)} ${limit}`)).word !== "reached") problem = `the rebuild did not come to the jump of its loader at ${formatC64Address(jump)}`;
|
|
756
|
+
else {
|
|
757
|
+
await countAt(core, targets);
|
|
758
|
+
const entered = await core.status(`run-pc ${hex(handover.entry)} ${limit}`);
|
|
759
|
+
if (entered.word !== "reached") problem = `the rebuild did not come to its entry at ${formatC64Address(handover.entry)}`;
|
|
760
|
+
else {
|
|
761
|
+
// After the entry, a tick key is as far from the entry as in the original.
|
|
762
|
+
skipped = entered.tick - handover.original.tick;
|
|
763
|
+
limit = base + Math.max(0, skipped);
|
|
764
|
+
if (options.compare !== undefined) await startSampling(options.compare);
|
|
765
|
+
}
|
|
766
|
+
}
|
|
694
767
|
}
|
|
695
|
-
|
|
768
|
+
// The original with an entry: the events before the mark at the entry came.
|
|
769
|
+
let eventsBefore = 0;
|
|
770
|
+
let entryTick: number | undefined;
|
|
771
|
+
const marked = async () => {
|
|
772
|
+
const answer = /tick=(\d+)/.exec(await core.command("marked"));
|
|
773
|
+
if (answer !== null) entryTick = Number(answer[1]);
|
|
774
|
+
};
|
|
775
|
+
for (const [index, event] of (problem === undefined ? recording.events : []).entries()) {
|
|
696
776
|
const what = event.step === undefined ? "the RESTORE of the play" : "step " + event.step;
|
|
697
|
-
|
|
777
|
+
let key = event.key;
|
|
778
|
+
if (handover !== undefined) {
|
|
779
|
+
// The original came to this point before its entry, where the rebuild runs its loader. Each such event is a pc key: replay checks it.
|
|
780
|
+
if (index < handover.original.eventsBefore) continue;
|
|
781
|
+
if ("pc" in key) key = { ...key, count: key.count - (handover.original.counts.get(key.pc) ?? 0) };
|
|
782
|
+
}
|
|
783
|
+
const point = await runToKey(core, key, limit, map, skipped, at);
|
|
698
784
|
if (point === "halted") break;
|
|
699
785
|
if (point === "not-reached") {
|
|
700
786
|
problem = "the program did not come to the point of " + what;
|
|
701
787
|
break;
|
|
702
788
|
}
|
|
789
|
+
if (options.entry !== undefined && entryTick === undefined) {
|
|
790
|
+
await marked();
|
|
791
|
+
if (entryTick === undefined) eventsBefore = index + 1;
|
|
792
|
+
}
|
|
703
793
|
// At the point of a runUntil to an address, its target is reached.
|
|
704
794
|
if (!("pc" in event.key)) problem = await doAction(core, event.action, at);
|
|
705
795
|
if (problem !== undefined) {
|
|
@@ -713,12 +803,35 @@ export async function replaySide(
|
|
|
713
803
|
const misses = sites.split(" ").slice(2).reduce((sum, entry) => sum + Number(entry.split(":")[4] ?? 0), 0);
|
|
714
804
|
const ram = options.dump === undefined ? undefined : await core.peek(0, 0x10000);
|
|
715
805
|
let lines: string[] = [];
|
|
716
|
-
if (
|
|
806
|
+
if (sampling) {
|
|
717
807
|
await core.command("pin off");
|
|
718
808
|
await core.command("sample off");
|
|
719
809
|
lines = readFileSync(samples, "utf8").split("\n").filter((line) => line !== "");
|
|
720
810
|
}
|
|
721
|
-
|
|
811
|
+
let entryPoint: EntryPoint | undefined;
|
|
812
|
+
if (options.entry !== undefined && entryTick === undefined) await marked();
|
|
813
|
+
if (entryTick !== undefined) {
|
|
814
|
+
const counts = new Map<string, number>();
|
|
815
|
+
for (const event of recording.events) {
|
|
816
|
+
if (!("pc" in event.key) || counts.has(event.key.pc)) continue;
|
|
817
|
+
const before = /marked=(\d+)/.exec(await core.command(`hits ${hex(at.code(event.key.pc))}`));
|
|
818
|
+
if (before !== null) counts.set(event.key.pc, Number(before[1]));
|
|
819
|
+
}
|
|
820
|
+
// A checkpoint at the first fetch at the entry has the tick of the mark. The rebuild starts its checkpoints after that fetch.
|
|
821
|
+
const after = lines.filter((line) => Number(line.split(" ")[0]) > entryTick!);
|
|
822
|
+
entryPoint = { tick: entryTick, counts, eventsBefore, samplesBefore: lines.length - after.length };
|
|
823
|
+
lines = after;
|
|
824
|
+
}
|
|
825
|
+
return {
|
|
826
|
+
samples: lines,
|
|
827
|
+
end,
|
|
828
|
+
unknown,
|
|
829
|
+
misses,
|
|
830
|
+
...(problem === undefined ? {} : { problem }),
|
|
831
|
+
...(screenSkipped ? { startScreenSkipped: true } : {}),
|
|
832
|
+
...(entryPoint === undefined ? {} : { entryPoint }),
|
|
833
|
+
...(ram === undefined ? {} : { ram }),
|
|
834
|
+
};
|
|
722
835
|
}
|
|
723
836
|
|
|
724
837
|
export interface CheckpointDifference {
|
|
@@ -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:
|
|
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,7 +113,7 @@ 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
119
|
const base = { checkpoints: expected.length, movedSites, ...(replayed.startScreenSkipped === true ? { startScreen: "skipped" } : {}), ...(replayed.unknown > 0 ? { idleReads: replayed.unknown } : {}) };
|
|
@@ -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
|
-
|
|
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
|
+
|
|
@@ -15,6 +15,7 @@ import { readPrg } from "#src/host-client/image.ts";
|
|
|
15
15
|
import { writeReported, type Written } from "#src/host-client/transfer.ts";
|
|
16
16
|
import { ViceSessionClient } from "#src/host-client/vice-session.ts";
|
|
17
17
|
import { knowledgeAt, knowledgeNames } from "#src/knowledge/names.ts";
|
|
18
|
+
import { PAL_FRAME_CYCLES } from "#src/native/c64run.ts";
|
|
18
19
|
import { listed, OPTIONS, reply, runScript, UsageError, type Call, type CommandSpec, type OptionSpec } from "#src/script.ts";
|
|
19
20
|
import { basicStart, inspect, readMemoryMap, underRom, writtenThenExecuted } from "./lib/evidence.ts";
|
|
20
21
|
import { loads, readLoadSteps } from "./lib/loads.ts";
|
|
@@ -435,6 +436,8 @@ async function follow(
|
|
|
435
436
|
stopAt = undefined;
|
|
436
437
|
}
|
|
437
438
|
};
|
|
439
|
+
// Stage 0 starts at the program, whatever the first step is: RUN and the BASIC line before it are no part of it.
|
|
440
|
+
await client.memmap({ action: "clear" });
|
|
438
441
|
// The steps run first and in the tracked time: a frames step and a runUntil step to an address. The others act between two chunks.
|
|
439
442
|
for (const [index, step] of options.steps.entries()) {
|
|
440
443
|
running = index + 1;
|
|
@@ -445,12 +448,19 @@ async function follow(
|
|
|
445
448
|
const why = halted === undefined ? "" : ` ${stoppedEarly(halted.stopReason, halted.pc, total, step.runUntil.timeoutFrames)}`;
|
|
446
449
|
return { stages: found, frames: total, reached: false, failed: `Step ${index + 1} did not reach its target in ${step.runUntil.timeoutFrames} frames. It is at ${formatC64Address(pc)}.${why}` };
|
|
447
450
|
}
|
|
448
|
-
} else
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
451
|
+
} else {
|
|
452
|
+
// A press or a runUntil to memory or the raster runs frames outside the chunks. The stopwatch of the session gives them,
|
|
453
|
+
// also for a run that a point stops early. What the step wrote and ran is in the stage before the next chunk clears the memory map.
|
|
454
|
+
await client.timing("start");
|
|
455
|
+
const notReached = await runActionStep(client, step, knowledgeAt());
|
|
456
|
+
const timed = await client.timing("read");
|
|
457
|
+
total += Math.round(Number("cycles" in timed ? timed.cycles : 0) / PAL_FRAME_CYCLES);
|
|
458
|
+
mergeMaps(stage.map, await readCoverage(client));
|
|
459
|
+
if (notReached !== undefined && "runUntil" in step) {
|
|
460
|
+
return { stages: found, frames: total, reached: false, failed: `Step ${index + 1} did not reach its target in ${step.runUntil.timeoutFrames} frames. It stopped by ${notReached.stopReason} at ${formatC64Address(notReached.pc)}.` };
|
|
461
|
+
}
|
|
453
462
|
}
|
|
463
|
+
noteUntil(stage.map);
|
|
454
464
|
}
|
|
455
465
|
running = 0;
|
|
456
466
|
const left = Math.max(0, options.frames - total);
|
package/src/host/main.ts
CHANGED
|
@@ -121,8 +121,8 @@ async function main(): Promise<number> {
|
|
|
121
121
|
log,
|
|
122
122
|
flaws,
|
|
123
123
|
// c1541 lists the disk, so an autostart index selects a program.
|
|
124
|
-
directory: async (imageType, image) => {
|
|
125
|
-
const { result } = await inspect({ action: "directory", imageType }, image, { supervisor, signal
|
|
124
|
+
directory: async (imageType, image, signal) => {
|
|
125
|
+
const { result } = await inspect({ action: "directory", imageType }, image, { supervisor, signal, log });
|
|
126
126
|
return result.action === "directory" ? result.entries : [];
|
|
127
127
|
},
|
|
128
128
|
}),
|
package/src/host/server.ts
CHANGED
|
@@ -263,7 +263,7 @@ class Connection {
|
|
|
263
263
|
const record = (outcome: Record<string, unknown>) => {
|
|
264
264
|
const ms = elapsedMs(started);
|
|
265
265
|
trace().event("request", { connection: this.#id, op: request.op, id: request.id, params: request.params, attachments: attachments.length, ms, ...outcome });
|
|
266
|
-
// A call from a skill script (c1541, petcat
|
|
266
|
+
// A call from a skill script (c1541, petcat) is always logged; the many calls of a VICE session only in the trace.
|
|
267
267
|
if (this.#isTool) {
|
|
268
268
|
const what = outcome.ok === true ? "ok" : `${String(outcome.code)}: ${String(outcome.message)}`;
|
|
269
269
|
this.#log(`${request.op} ${JSON.stringify(summarize(request.params) ?? {})}: ${what} (${ms} ms)`);
|
|
@@ -387,6 +387,8 @@ export async function startHostServer(options: HostServerOptions): Promise<HostS
|
|
|
387
387
|
server.once("error", failed);
|
|
388
388
|
server.listen({ host: address, port, exclusive: true }, () => {
|
|
389
389
|
server.off("error", failed);
|
|
390
|
+
// A failed accept (for example EMFILE) fails only that connection; the listener goes on.
|
|
391
|
+
server.on("error", (error) => log(`listener on ${address} port ${port}: ${error.message}`));
|
|
390
392
|
const bound = server.address();
|
|
391
393
|
if (bound === null || typeof bound === "string") reject(new Error("listener has no TCP address"));
|
|
392
394
|
else resolve(bound.port);
|
package/src/host/vice/process.ts
CHANGED
|
@@ -25,7 +25,7 @@
|
|
|
25
25
|
// A headless VICE plays no sound: `-sounddev dummy` keeps the SID emulated.
|
|
26
26
|
|
|
27
27
|
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
|
|
28
|
-
import { createServer } from "node:net";
|
|
28
|
+
import { createServer, type Server } from "node:net";
|
|
29
29
|
import { tmpdir } from "node:os";
|
|
30
30
|
import { join } from "node:path";
|
|
31
31
|
import { setTimeout as sleep } from "node:timers/promises";
|
|
@@ -49,18 +49,33 @@ export function findVice(env: NodeJS.ProcessEnv = process.env): string {
|
|
|
49
49
|
}
|
|
50
50
|
|
|
51
51
|
/** Asks the OS for a free loopback port. Another process can still take it before VICE binds. */
|
|
52
|
-
export function freePort(): Promise<number> {
|
|
53
|
-
return
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
52
|
+
export async function freePort(): Promise<number> {
|
|
53
|
+
return (await freePorts(1))[0]!;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Asks the OS for `count` different free loopback ports: each probe stays bound until all are known. */
|
|
57
|
+
export async function freePorts(count: number): Promise<number[]> {
|
|
58
|
+
const servers: Server[] = [];
|
|
59
|
+
try {
|
|
60
|
+
const ports: number[] = [];
|
|
61
|
+
for (let index = 0; index < count; index++) {
|
|
62
|
+
const server = createServer();
|
|
63
|
+
servers.push(server);
|
|
64
|
+
ports.push(
|
|
65
|
+
await new Promise<number>((resolve, reject) => {
|
|
66
|
+
server.once("error", reject);
|
|
67
|
+
server.listen(0, "127.0.0.1", () => {
|
|
68
|
+
const address = server.address();
|
|
69
|
+
if (address === null || typeof address === "string") reject(new Error("no TCP address"));
|
|
70
|
+
else resolve(address.port);
|
|
71
|
+
});
|
|
72
|
+
}),
|
|
73
|
+
);
|
|
74
|
+
}
|
|
75
|
+
return ports;
|
|
76
|
+
} finally {
|
|
77
|
+
await Promise.all(servers.map((server) => new Promise<void>((resolve) => server.close(() => resolve()))));
|
|
78
|
+
}
|
|
64
79
|
}
|
|
65
80
|
|
|
66
81
|
/** A VICE with no window (the default) or one with a window the user can use. */
|
|
@@ -254,8 +269,7 @@ async function launchOnce(options: LaunchOptions): Promise<ViceProcess> {
|
|
|
254
269
|
const env = options.env ?? process.env;
|
|
255
270
|
const log = options.log ?? (() => {});
|
|
256
271
|
const binary = findVice(env);
|
|
257
|
-
const port = await
|
|
258
|
-
const textPort = await freePort();
|
|
272
|
+
const [port, textPort] = (await freePorts(2)) as [number, number];
|
|
259
273
|
const scratch = mkdtempSync(join(tmpdir(), "c64-re-tools-vice-"));
|
|
260
274
|
// Owned by the supervisor: its exit guard and the watchdog remove it if this process dies.
|
|
261
275
|
const releaseScratch = options.supervisor.ownPath(scratch);
|
|
@@ -384,9 +398,12 @@ async function checkSameMachine(monitor: BinaryMonitor, text: TextMonitor): Prom
|
|
|
384
398
|
if (seen === null || Number.parseInt(seen[1]!, 16) !== marker) {
|
|
385
399
|
throw new WireFailure("machine-unavailable", "The emulator's two monitor connections reached different machines.");
|
|
386
400
|
}
|
|
387
|
-
}
|
|
388
|
-
|
|
401
|
+
} catch (error) {
|
|
402
|
+
// The first failure tells why the launch failed; a failed restore after it would hide it.
|
|
403
|
+
await write(original).catch(() => {});
|
|
404
|
+
throw error;
|
|
389
405
|
}
|
|
406
|
+
await write(original);
|
|
390
407
|
}
|
|
391
408
|
|
|
392
409
|
/** Connects the binary monitor and proves it answers a ping, until `deadline`. */
|