@henols/c64-re-tools 2.5.0 → 2.6.0-rc.1
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-knowledge/SKILL.md +19 -4
- package/skills/c64-knowledge/scripts/knowledge.ts +10 -2
- package/skills/c64-reverse-engineering/SKILL.md +4 -1
- package/skills/c64-source/SKILL.md +46 -11
- package/skills/c64-source/scripts/lib/loader.ts +41 -16
- package/skills/c64-source/scripts/lib/source.ts +47 -14
- package/skills/c64-source/scripts/lib/stage.ts +268 -0
- package/skills/c64-source/scripts/lib/start-screen.asm +28 -2
- package/skills/c64-source/scripts/source.ts +351 -104
- package/skills/c64-unpacker/SKILL.md +1 -0
- package/src/knowledge/read.ts +8 -1
- package/src/knowledge/schema.ts +10 -2
- package/src/knowledge/text.ts +2 -0
- package/src/knowledge/write.ts +36 -6
|
@@ -26,8 +26,8 @@ import { conflicts } from "#src/knowledge/conflicts.ts";
|
|
|
26
26
|
import { openForRead, withWrite } from "#src/knowledge/database.ts";
|
|
27
27
|
import { identifiers } from "#src/knowledge/expression.ts";
|
|
28
28
|
import { analyzedBytes, memoryRows, programCoverage, requireProgram, type ProgramImage } from "#src/knowledge/program.ts";
|
|
29
|
-
import { ANALYZER_NAME_ORDER, baseValue, currentRevision, currentStartScreen, startScreenRanges, listAnalyzerNames, listComments, listMacros, listMacroUses, listModules, listOperands, listPatches, listReferences, listRegions, listReleases, listSpaces, listSwitches, listSymbols, type ReleaseRow, type SymbolRow } from "#src/knowledge/read.ts";
|
|
30
|
-
import { CODE_REGION_TYPES, DEFAULT_SPACE, isSemantic, RELEASE_DEFINE, START_SCREEN_SWITCH, type Space } from "#src/knowledge/schema.ts";
|
|
29
|
+
import { ANALYZER_NAME_ORDER, baseValue, currentRevision, currentStartScreen, startScreenRanges, type StartScreenRow, listAnalyzerNames, listComments, listMacros, listMacroUses, listModules, listOperands, listPatches, listReferences, listRegions, listReleases, listSpaces, listSwitches, listSymbols, type ReleaseRow, type SymbolRow } from "#src/knowledge/read.ts";
|
|
30
|
+
import { CODE_REGION_TYPES, DEFAULT_SPACE, isSemantic, LEFTOVERS_SWITCH, RELEASE_DEFINE, START_SCREEN_SWITCH, type Space } from "#src/knowledge/schema.ts";
|
|
31
31
|
import { subtract, write } from "#src/knowledge/write.ts";
|
|
32
32
|
import { assemble, symbolsFileText } from "#src/native/acme.ts";
|
|
33
33
|
import { analyze } from "#src/native/ghidra/analyze.ts";
|
|
@@ -43,8 +43,11 @@ import {
|
|
|
43
43
|
COPIER_SOURCE,
|
|
44
44
|
LOADER_JUMP,
|
|
45
45
|
loaderLimits,
|
|
46
|
+
packedParts,
|
|
46
47
|
packLoader,
|
|
48
|
+
packParts,
|
|
47
49
|
planLoader,
|
|
50
|
+
startScreenPlan,
|
|
48
51
|
rasterLine,
|
|
49
52
|
loaderState,
|
|
50
53
|
simulate,
|
|
@@ -57,8 +60,10 @@ import {
|
|
|
57
60
|
type EntryState,
|
|
58
61
|
type LoaderPlan,
|
|
59
62
|
type PackedLoader,
|
|
63
|
+
type StartScreenPlan,
|
|
60
64
|
} from "./lib/loader.ts";
|
|
61
65
|
import { instructionWith, OPCODES } from "#src/opcodes.ts";
|
|
66
|
+
import { planStage, STAGE_CODE_END, STAGE_FILE, STAGE_START, stageParts, stageText, type StageInput, type StagePart, type StagePlan } from "./lib/stage.ts";
|
|
62
67
|
import { freeName, planDrops, readmeText, rewriteTest } from "./lib/export.ts";
|
|
63
68
|
import { CONFIG_FILE, configText, configValues, entriesInData, entryOutsideImage, hasConfigFile, hasSwitchFile, layout, literalOperand, probeForms, render, switchesOf, type Layout, type PatchBlock, type Rendered, type SourceSwitch } from "./lib/source.ts";
|
|
64
69
|
|
|
@@ -90,8 +95,8 @@ function readKnowledge(space: Space, analyzerNames = false) {
|
|
|
90
95
|
return {
|
|
91
96
|
revision: currentRevision(db),
|
|
92
97
|
program: requireProgram(db, space),
|
|
93
|
-
// The coverage
|
|
94
|
-
coverage:
|
|
98
|
+
// The coverage of the space: a run of the C64, or of a captured stage that coverage put into that space.
|
|
99
|
+
coverage: programCoverage(db, space)?.map,
|
|
95
100
|
symbols: analyzerNames ? withAnalyzerNames(symbols, second) : symbols,
|
|
96
101
|
// Analyzer routines are entry points for the decode, also without --analyzer-names.
|
|
97
102
|
routines: [...symbols, ...second].filter((symbol) => symbol.kind === "routine").map((symbol) => symbol.address),
|
|
@@ -429,7 +434,7 @@ function compareBuilds(built: Assembled, ranges: readonly AddressRange[], base:
|
|
|
429
434
|
* from config.asm: a define of a switch is an error, because config.asm also
|
|
430
435
|
* gives it a value. A switch without a value has its default.
|
|
431
436
|
*/
|
|
432
|
-
function withValues(files: Array<{ name: string; text: string }>, laid: Pick<Layout, "switches" | "patches" | "startScreen">, values: ReadonlyMap<string, number>): Array<{ name: string; text: string }> {
|
|
437
|
+
function withValues(files: Array<{ name: string; text: string }>, laid: Pick<Layout, "switches" | "patches" | "startScreen" | "leftovers">, values: ReadonlyMap<string, number>): Array<{ name: string; text: string }> {
|
|
433
438
|
return files.map((file) => (file.name === CONFIG_FILE ? { ...file, text: configText(laid, values) } : file));
|
|
434
439
|
}
|
|
435
440
|
|
|
@@ -524,8 +529,8 @@ interface LoaderRun {
|
|
|
524
529
|
verified: boolean;
|
|
525
530
|
differences: string[];
|
|
526
531
|
stop?: { pc: string; port: string; cause?: string; history: string[] };
|
|
527
|
-
/** The start screen: shown with its VIC-II values, and still waiting after START_SCREEN_FRAMES frames. */
|
|
528
|
-
startScreen?: { shown: boolean; waits: boolean; wait: string; continue: string };
|
|
532
|
+
/** The start screen: shown with its VIC-II values, and still waiting after START_SCREEN_FRAMES frames. A start screen of a stage also has the bytes of the stage. */
|
|
533
|
+
startScreen?: { shown: boolean; waits: boolean; wait: string; continue: string; stage?: string };
|
|
529
534
|
}
|
|
530
535
|
|
|
531
536
|
/** The frames that the check of the loader lets the start screen wait without a key. */
|
|
@@ -539,12 +544,14 @@ interface LoaderRunPlan {
|
|
|
539
544
|
jump: number;
|
|
540
545
|
/** The wait of the start screen and the code after it, when the loader has a start screen. */
|
|
541
546
|
startScreen?: { wait: number; continue: number };
|
|
547
|
+
/** The show stage of a start screen from a captured stage, which runs before the loader: its wait, the code after it, its VIC-II values and the bytes of the stage. */
|
|
548
|
+
stage?: { name: string; wait: number; continue: number; screen: StartScreenPlan; parts: StagePart[]; frames: number };
|
|
542
549
|
copierSource: number;
|
|
543
550
|
fileByte: (address: number) => number;
|
|
544
551
|
copierFrames: number;
|
|
545
552
|
}
|
|
546
553
|
|
|
547
|
-
async function runLoader(path: string, program: Buffer, plan: LoaderPlan,
|
|
554
|
+
async function runLoader(path: string, program: Buffer, plan: LoaderPlan, state: EntryState, run: LoaderRunPlan, expected: (address: number) => number): Promise<LoaderRun> {
|
|
548
555
|
const { jump, copierSource, fileByte } = run;
|
|
549
556
|
const client = await ViceSessionClient.open({ videoStandard: "pal" });
|
|
550
557
|
try {
|
|
@@ -552,37 +559,54 @@ async function runLoader(path: string, program: Buffer, plan: LoaderPlan, image:
|
|
|
552
559
|
if (!(await autostartLoaded(client, path, program))) return { verified: false, differences: ["The loader was not in memory after autostart."] };
|
|
553
560
|
await client.keyboard(textToPetscii("RUN\n"));
|
|
554
561
|
// A stop before the copier or the jump gives $01, the last instructions and the first byte that is not as planned.
|
|
555
|
-
|
|
562
|
+
// Before the show stage moves on, the copier is not in place yet: then the stop has no cause from it.
|
|
563
|
+
const stopped = async (pc: number, copied: boolean, what: string, loaderRan = true): Promise<LoaderRun> => {
|
|
556
564
|
const ram = await readRam(client, 0x0000, 0x10000);
|
|
557
565
|
const port = Buffer.from((await client.memoryRead({ address: 0x0001, size: 1, space: "c64", view: "cpu" })).data, "hex")[0]!;
|
|
558
566
|
const history = (await client.cpuHistory({ limit: STOP_HISTORY, space: "c64" })).entries.map((entry) => `${formatC64Address(entry.address)} ${entry.text}`);
|
|
559
|
-
const cause = stopCause(ram, plan, copierSource, fileByte, copied, expected);
|
|
567
|
+
const cause = loaderRan ? stopCause(ram, plan, copierSource, fileByte, copied, expected) : undefined;
|
|
560
568
|
const port01 = `$${port.toString(16).padStart(2, "0")}`;
|
|
561
569
|
return { verified: false, differences: [`The loader did not get to ${what}; it stopped at ${formatC64Address(pc)}.`], stop: { pc: formatC64Address(pc), port: port01, ...(cause === undefined ? {} : { cause }), history } };
|
|
562
570
|
};
|
|
563
|
-
const copier = await client.runUntil({ target: { kind: "address", address: plan.copier, space: "c64" }, timeoutFrames: run.copierFrames });
|
|
564
|
-
if (!copier.reached) return await stopped(copier.pc, false, `its copier at ${formatC64Address(plan.copier)}`);
|
|
565
571
|
// The start screen waits for a key or a fire button. The emulator cannot press a key of the keyboard matrix
|
|
566
572
|
// on each VICE, so the check lets it wait, then sets the PC to the code after the wait.
|
|
567
573
|
let screen: LoaderRun["startScreen"];
|
|
568
574
|
const screenDifferences: string[] = [];
|
|
569
|
-
|
|
570
|
-
const labels = { wait: formatC64Address(
|
|
571
|
-
const atWait = await client.runUntil({ target: { kind: "address", address:
|
|
572
|
-
if (!atWait.reached) return await stopped(atWait.pc,
|
|
573
|
-
const held = await client.runUntil({ target: { kind: "address", address:
|
|
575
|
+
const showScreen = async (at: { wait: number; continue: number }, wanted: StartScreenPlan, frames: number, copied: boolean, parts: readonly StagePart[] = []): Promise<LoaderRun | undefined> => {
|
|
576
|
+
const labels = { wait: formatC64Address(at.wait), continue: formatC64Address(at.continue) };
|
|
577
|
+
const atWait = await client.runUntil({ target: { kind: "address", address: at.wait, space: "c64" }, timeoutFrames: frames });
|
|
578
|
+
if (!atWait.reached) return await stopped(atWait.pc, copied, `its start screen at ${labels.wait}`, parts.length === 0);
|
|
579
|
+
const held = await client.runUntil({ target: { kind: "address", address: at.continue, space: "c64" }, timeoutFrames: START_SCREEN_FRAMES });
|
|
574
580
|
const vic = Buffer.from((await client.ioRead(0xd000, 0x2f)).data, "hex");
|
|
575
581
|
const bank = 3 - (Buffer.from((await client.ioRead(0xdd00, 1)).data, "hex")[0]! & 0x03);
|
|
576
|
-
const
|
|
582
|
+
const before = screenDifferences.length;
|
|
577
583
|
const shown: Array<[number, number]> = [[0x11, wanted.d011], [0x15, 0], [0x16, wanted.d016], [0x18, wanted.d018], [0x20, wanted.border], [0x21, wanted.background]];
|
|
578
584
|
for (const [register, value] of shown) {
|
|
579
585
|
const mask = VIC_DISPLAY_REGISTERS.find((item) => item.register === register)!.mask;
|
|
580
586
|
if ((vic[register]! & mask) !== (value & mask)) screenDifferences.push(`the start screen has ${formatC64Address(0xd000 + register)} = $${(vic[register]! & mask).toString(16).padStart(2, "0")}, not $${(value & mask).toString(16).padStart(2, "0")}`);
|
|
581
587
|
}
|
|
582
588
|
if (bank !== wanted.bank) screenDifferences.push(`the start screen is in VIC bank ${bank}, not ${wanted.bank}`);
|
|
583
|
-
screen
|
|
589
|
+
// The bytes of the screen of a stage: the first wrong byte of each part.
|
|
590
|
+
for (const part of parts) {
|
|
591
|
+
const ram = await readRam(client, part.start, part.body.length);
|
|
592
|
+
const wrong = part.body.findIndex((byte, offset) => ram[offset] !== byte);
|
|
593
|
+
if (wrong >= 0) screenDifferences.push(`the stage has $${ram[wrong]!.toString(16).padStart(2, "0")} at ${formatC64Address(part.start + wrong)}, not $${part.body[wrong]!.toString(16).padStart(2, "0")}`);
|
|
594
|
+
}
|
|
595
|
+
screen = { shown: screenDifferences.length === before, waits: !held.reached, ...labels, ...(run.stage === undefined ? {} : { stage: run.stage.name }) };
|
|
584
596
|
if (held.reached) screenDifferences.push(`the start screen did not wait: it got to ${labels.continue} without a key or a fire button`);
|
|
585
|
-
if (!held.reached) await client.registersSet("c64", { pc:
|
|
597
|
+
if (!held.reached) await client.registersSet("c64", { pc: at.continue });
|
|
598
|
+
return undefined;
|
|
599
|
+
};
|
|
600
|
+
// The show stage of a captured stage runs before the loader.
|
|
601
|
+
if (run.stage !== undefined) {
|
|
602
|
+
const stop = await showScreen(run.stage, run.stage.screen, run.stage.frames, false, run.stage.parts);
|
|
603
|
+
if (stop !== undefined) return stop;
|
|
604
|
+
}
|
|
605
|
+
const copier = await client.runUntil({ target: { kind: "address", address: plan.copier, space: "c64" }, timeoutFrames: run.copierFrames });
|
|
606
|
+
if (!copier.reached) return await stopped(copier.pc, false, `its copier at ${formatC64Address(plan.copier)}`);
|
|
607
|
+
if (run.startScreen !== undefined && plan.startScreen !== undefined) {
|
|
608
|
+
const stop = await showScreen(run.startScreen, plan.startScreen, LOADER_FRAMES, true);
|
|
609
|
+
if (stop !== undefined) return stop;
|
|
586
610
|
}
|
|
587
611
|
const atJump = await client.runUntil({ target: { kind: "address", address: jump, space: "c64" }, timeoutFrames: LOADER_FRAMES });
|
|
588
612
|
if (!atJump.reached) return await stopped(atJump.pc, true, `its jump to the entry at ${formatC64Address(jump)}`);
|
|
@@ -595,8 +619,9 @@ async function runLoader(path: string, program: Buffer, plan: LoaderPlan, image:
|
|
|
595
619
|
const differences: string[] = [];
|
|
596
620
|
const byte = (value: number) => `$${value.toString(16).padStart(2, "0")}`;
|
|
597
621
|
const differ = (what: string, got: number, wanted: number) => got !== wanted && differences.push(`${what} is ${byte(got)}, not ${byte(wanted)}`);
|
|
598
|
-
|
|
599
|
-
|
|
622
|
+
// The leftovers are not loaded: only the loaded ranges have the bytes of the build.
|
|
623
|
+
for (const part of plan.loaded) {
|
|
624
|
+
for (let address = Math.max(part.start, 2); address <= part.end; address++) differ(formatC64Address(address), memory[address]!, expected(address));
|
|
600
625
|
}
|
|
601
626
|
for (let address = 2; address < 0x400; address++) if (address !== plan.stackByte) differ(formatC64Address(address), memory[address]!, state.pages[address]!);
|
|
602
627
|
differ("$00", port[0]!, state.port[0]);
|
|
@@ -667,7 +692,7 @@ function sourceMapText(rendered: Rendered, space: string, revision: string | nul
|
|
|
667
692
|
const LOADER_CHECK_DIRECTORY = "loader-check";
|
|
668
693
|
|
|
669
694
|
/** The files of the loader. Only a run with --loader writes them, so only such a run removes them. */
|
|
670
|
-
const LOADER_FILES: ReadonlySet<string> = new Set(["loader.asm", "loader.prg", START_SCREEN_FILE]);
|
|
695
|
+
const LOADER_FILES: ReadonlySet<string> = new Set(["loader.asm", "loader.prg", START_SCREEN_FILE, STAGE_FILE]);
|
|
671
696
|
|
|
672
697
|
/** The start of the line of loader.asm that gives the knowledge revision of the loader. */
|
|
673
698
|
const LOADER_REVISION = "Loader generated by c64-source from knowledge revision ";
|
|
@@ -736,6 +761,10 @@ interface SourceOptions {
|
|
|
736
761
|
loaderHeader?: string[];
|
|
737
762
|
/** The source of an export: no config.asm, so START_SCREEN has the default of start_screen.asm. */
|
|
738
763
|
exported?: boolean;
|
|
764
|
+
/** Put the free ranges of the program into leftover files, which only LEFTOVERS = 1 builds. */
|
|
765
|
+
leftovers?: boolean;
|
|
766
|
+
/** The switch values of the build that the loader loads. The default is `values`. */
|
|
767
|
+
loaderValues?: ReadonlyMap<string, number>;
|
|
739
768
|
}
|
|
740
769
|
|
|
741
770
|
/**
|
|
@@ -751,6 +780,7 @@ async function buildSource(knowledge: SourceKnowledge, options: SourceOptions) {
|
|
|
751
780
|
const romUse = romUseOfProgram(coverage, image.state);
|
|
752
781
|
const platform = platformNamesFor(romUse);
|
|
753
782
|
const { instructions, dataOnly } = options.decoded ?? (await decode(image, knowledge, options.entries, coverage));
|
|
783
|
+
const leftovers = options.leftovers === true && !dataOnly ? leftoversOf(knowledge, instructions) : [];
|
|
754
784
|
const laid = layout({
|
|
755
785
|
segments: image.segments,
|
|
756
786
|
byteAt: image.byteAt,
|
|
@@ -768,50 +798,23 @@ async function buildSource(knowledge: SourceKnowledge, options: SourceOptions) {
|
|
|
768
798
|
macros: knowledge.macros,
|
|
769
799
|
macroUses: knowledge.macroUses,
|
|
770
800
|
startScreen: knowledge.startScreen !== undefined && options.exported !== true,
|
|
801
|
+
leftovers,
|
|
771
802
|
...(coverage === undefined || !options.notExecutedMarks ? {} : { coverage }),
|
|
772
803
|
// The platform names are C64 names: drive code and banks get none. A ROM that the program does not use gives none.
|
|
773
804
|
...(space === DEFAULT_SPACE ? { platform, platformLeftOut: leftOutNames(platform), describe: describeAddress, decode: decodeRegister, io: IO_RAM } : {}),
|
|
774
805
|
});
|
|
775
806
|
const asBytes = await probe(laid);
|
|
776
807
|
const { header } = options;
|
|
777
|
-
let loader: LoaderPlan | undefined;
|
|
778
|
-
// An image without its entry has no program: the source is still written and checked, but the run fails.
|
|
779
|
-
const missingEntry = entryOutsideImage(image.entry, image.segments);
|
|
780
|
-
// A loader that cannot be planned does not stop the source: the source is written and checked, and the result says why.
|
|
781
|
-
const { state } = options;
|
|
782
|
-
let loaderRefused: string | undefined = state === undefined ? undefined : missingEntry;
|
|
783
|
-
if (state !== undefined && missingEntry === undefined) {
|
|
784
|
-
const segments = image.segments.map((segment) => ({ ...segment, files: laid.pieces.filter((piece) => piece.start >= segment.start && piece.start <= segment.end).map((piece) => piece.file) }));
|
|
785
|
-
try {
|
|
786
|
-
const entryName = laid.names.get(image.entry!);
|
|
787
|
-
loader = planLoader({
|
|
788
|
-
segments,
|
|
789
|
-
byteAt: image.byteAt,
|
|
790
|
-
state,
|
|
791
|
-
entry: image.entry!,
|
|
792
|
-
...(entryName === undefined ? {} : { entryName }),
|
|
793
|
-
switches: hasSwitchFile(laid),
|
|
794
|
-
config: hasConfigFile(laid),
|
|
795
|
-
macros: laid.macros.length > 0,
|
|
796
|
-
header: options.loaderHeader ?? [],
|
|
797
|
-
...(knowledge.startScreen === undefined ? {} : { startScreen: knowledge.startScreen }),
|
|
798
|
-
});
|
|
799
|
-
} catch (error) {
|
|
800
|
-
if (!isRefusal(error)) throw error;
|
|
801
|
-
loaderRefused = error.message;
|
|
802
|
-
}
|
|
803
|
-
}
|
|
804
808
|
// With a mark, every file starts with it.
|
|
805
809
|
const { mark } = options;
|
|
806
810
|
const marked = (list: Array<{ name: string; text: string }>) => (mark === undefined ? list : list.map((file) => (file.name === CONFIG_FILE ? file : { ...file, text: `${mark}\n${file.text}` })));
|
|
807
811
|
const markLines = mark === undefined ? 0 : 1;
|
|
808
|
-
const loaderFiles = loader === undefined ? [] : [{ name: "loader.asm", text: loader.text }, ...(loader.startScreen === undefined ? [] : [{ name: START_SCREEN_FILE, text: START_SCREEN_CODE }])];
|
|
809
812
|
const numbers = new Map<number, string>();
|
|
810
813
|
const asInstructions = new Map<number, string>();
|
|
811
814
|
let rendered = render(laid, asBytes, header, numbers, asInstructions);
|
|
812
815
|
if (laid.macroUses.size > 0) for (const [start, reason] of await probeUses(laid, rendered, image)) asInstructions.set(start, reason);
|
|
813
816
|
if (asInstructions.size > 0) rendered = render(laid, asBytes, header, numbers, asInstructions);
|
|
814
|
-
let files = marked(
|
|
817
|
+
let files = marked(rendered.files);
|
|
815
818
|
let built = await assembleFiles(withValues(files, laid, options.values), "main.asm");
|
|
816
819
|
for (let round = 0; round < ROUNDS && (rendered.expressions.length > 0 || rendered.uses.length > 0); round++) {
|
|
817
820
|
const blamed = blame(rendered, built, image, markLines);
|
|
@@ -819,22 +822,83 @@ async function buildSource(knowledge: SourceKnowledge, options: SourceOptions) {
|
|
|
819
822
|
for (const [address, reason] of blamed.numbers) numbers.set(address, reason);
|
|
820
823
|
for (const [start, reason] of blamed.uses) asInstructions.set(start, reason);
|
|
821
824
|
rendered = render(laid, asBytes, header, numbers, asInstructions);
|
|
822
|
-
files = marked(
|
|
825
|
+
files = marked(rendered.files);
|
|
823
826
|
built = await assembleFiles(withValues(files, laid, options.values), "main.asm");
|
|
824
827
|
}
|
|
825
|
-
|
|
828
|
+
|
|
829
|
+
let loader: LoaderPlan | undefined;
|
|
830
|
+
/** The build of main.asm that the loader loads: the switch values of the loader. */
|
|
831
|
+
let loaderMain: { program: Buffer; start: number } | undefined;
|
|
832
|
+
// An image without its entry has no program: the source is still written and checked, but the run fails.
|
|
833
|
+
const missingEntry = entryOutsideImage(image.entry, image.segments);
|
|
834
|
+
// A loader that cannot be planned does not stop the source: the source is written and checked, and the result says why.
|
|
835
|
+
const { state } = options;
|
|
836
|
+
let loaderRefused: string | undefined = state === undefined ? undefined : missingEntry;
|
|
837
|
+
if (state !== undefined && missingEntry === undefined) {
|
|
838
|
+
const main = options.loaderValues === undefined ? built : await assembleFiles(withValues(files, laid, options.loaderValues), "main.asm");
|
|
839
|
+
if (main.program === undefined) loaderRefused = "The source does not assemble with the switch values of the loader.";
|
|
840
|
+
else {
|
|
841
|
+
const program = main.program;
|
|
842
|
+
const start = main.start!;
|
|
843
|
+
loaderMain = { program, start };
|
|
844
|
+
try {
|
|
845
|
+
const entryName = laid.names.get(image.entry!);
|
|
846
|
+
loader = planLoader({
|
|
847
|
+
segments: loadedParts(laid, image.segments),
|
|
848
|
+
byteAt: (address) => program[2 + address - start]!,
|
|
849
|
+
state,
|
|
850
|
+
entry: image.entry!,
|
|
851
|
+
...(entryName === undefined ? {} : { entryName }),
|
|
852
|
+
switches: hasSwitchFile(laid),
|
|
853
|
+
config: hasConfigFile(laid),
|
|
854
|
+
macros: laid.macros.length > 0,
|
|
855
|
+
header: options.loaderHeader ?? [],
|
|
856
|
+
// A start screen of a stage shows before the loader, in the show stage: the copier has none.
|
|
857
|
+
...(knowledge.startScreen === undefined || knowledge.startScreen.stage !== undefined ? {} : { startScreen: knowledge.startScreen }),
|
|
858
|
+
});
|
|
859
|
+
} catch (error) {
|
|
860
|
+
if (!isRefusal(error)) throw error;
|
|
861
|
+
loaderRefused = error.message;
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
if (loader !== undefined) files = [...files, ...marked([{ name: "loader.asm", text: loader.text }, ...(loader.startScreen === undefined ? [] : [{ name: START_SCREEN_FILE, text: START_SCREEN_CODE }])])];
|
|
866
|
+
return { romUse, instructions, dataOnly, laid, rendered, files, built, loader, loaderMain, missingEntry, loaderRefused };
|
|
867
|
+
}
|
|
868
|
+
|
|
869
|
+
/** The ranges that the loader loads, each with its files: the segments without the leftovers. */
|
|
870
|
+
function loadedParts(laid: Pick<Layout, "pieces">, segments: readonly AddressRange[]): Array<AddressRange & { files: string[] }> {
|
|
871
|
+
const parts: Array<AddressRange & { files: string[] }> = [];
|
|
872
|
+
for (const segment of segments) {
|
|
873
|
+
let open: (AddressRange & { files: string[] }) | undefined;
|
|
874
|
+
for (const piece of laid.pieces.filter((item) => item.start >= segment.start && item.start <= segment.end)) {
|
|
875
|
+
if (piece.leftover) {
|
|
876
|
+
open = undefined;
|
|
877
|
+
continue;
|
|
878
|
+
}
|
|
879
|
+
if (open === undefined) {
|
|
880
|
+
open = { start: piece.start, end: piece.end, files: [piece.file] };
|
|
881
|
+
parts.push(open);
|
|
882
|
+
} else {
|
|
883
|
+
open.end = piece.end;
|
|
884
|
+
open.files.push(piece.file);
|
|
885
|
+
}
|
|
886
|
+
}
|
|
887
|
+
}
|
|
888
|
+
return parts;
|
|
826
889
|
}
|
|
827
890
|
|
|
828
891
|
/**
|
|
829
892
|
* Assembles loader.asm with the switch values and simulates its copies: the
|
|
830
|
-
* loader as it loads, then every copy in its order, byte by byte.
|
|
831
|
-
*
|
|
893
|
+
* loader as it loads, then every copy in its order, byte by byte. `main` is
|
|
894
|
+
* the build of main.asm with the same values: the loaded ranges must get its
|
|
895
|
+
* bytes. A layout other than the plan is a defect of the script.
|
|
832
896
|
*/
|
|
833
897
|
async function buildLoader(
|
|
834
898
|
files: Array<{ name: string; text: string }>,
|
|
835
899
|
laid: Layout,
|
|
836
900
|
loader: LoaderPlan,
|
|
837
|
-
|
|
901
|
+
main: { program: Buffer; start: number },
|
|
838
902
|
state: EntryState,
|
|
839
903
|
values: ReadonlyMap<string, number>,
|
|
840
904
|
): Promise<{ program: Buffer; symbols: AssembledSymbol[]; jump: number; copierSource: number; expected: (address: number) => number; startScreen?: { wait: number; continue: number } } | { diagnostics: Diagnostic[] }> {
|
|
@@ -843,7 +907,7 @@ async function buildLoader(
|
|
|
843
907
|
const program = loaderBuilt.program;
|
|
844
908
|
const memory = new Int16Array(0x10000).fill(-1);
|
|
845
909
|
program.subarray(2).forEach((byte, offset) => (memory[loaderBuilt.start! + offset] = byte));
|
|
846
|
-
const expected = (address: number) => (
|
|
910
|
+
const expected = (address: number) => (loader.loaded.some((part) => address >= part.start && address <= part.end) ? main.program[2 + address - main.start]! : state.pages[address]!);
|
|
847
911
|
const wrongPacking = loader.blocks.find((block) => {
|
|
848
912
|
for (let address = block.range.start; address <= block.range.end; address++) if (memory[block.packedAt + address - block.range.start] !== block.bytes(address)) return true;
|
|
849
913
|
return false;
|
|
@@ -863,6 +927,108 @@ async function buildLoader(
|
|
|
863
927
|
return { program, symbols: loaderBuilt.symbols ?? [], jump, copierSource: symbolValue(COPIER_SOURCE), expected, ...(startScreen === undefined ? {} : { startScreen }) };
|
|
864
928
|
}
|
|
865
929
|
|
|
930
|
+
/**
|
|
931
|
+
* The bytes of a captured stage that its start screen uses: the parts of the
|
|
932
|
+
* screen, and with a call every byte of the stage that is not free when the
|
|
933
|
+
* call is the entry (freeRanges, from the coverage of the stage). Each patch
|
|
934
|
+
* of the stage whose switch default is not its base value is in, as in the
|
|
935
|
+
* default build. Pages 0-3 are left out: the unpacker of Exomizer uses them.
|
|
936
|
+
*/
|
|
937
|
+
async function stageBytes(row: StartScreenRow): Promise<StagePart[]> {
|
|
938
|
+
const stage = row.stage!;
|
|
939
|
+
const knowledge = readKnowledge(stage);
|
|
940
|
+
const image = knowledge.program;
|
|
941
|
+
const memory = Uint8Array.from(image.memory);
|
|
942
|
+
const addresses = knowledge.symbols.map((symbol) => `${symbol.name} = ${formatC64Address(symbol.address)}`);
|
|
943
|
+
for (const patch of knowledge.patches) {
|
|
944
|
+
const owner = knowledge.switches.find((item) => item.name === patch.switch);
|
|
945
|
+
if (owner === undefined || owner.default === owner.base) continue;
|
|
946
|
+
const length = patch.end - patch.start + 1;
|
|
947
|
+
const text = ["!cpu 6510", ...addresses, `* = ${formatC64Address(patch.start)}`, ...patch.code.split(/\r?\n/), `!fill ${length} - (* - ${formatC64Address(patch.start)}), $ea`].join("\n");
|
|
948
|
+
const built = await assembleFiles([{ name: "patch.asm", text: `${text}\n` }], "patch.asm");
|
|
949
|
+
if (built.program === undefined || built.start !== patch.start || built.program.length - 2 !== length) {
|
|
950
|
+
throw new Refusal("invalid-input", `The patch of ${patch.switch} at ${formatC64Address(patch.start)}-${formatC64Address(patch.end)} in ${stage} does not assemble to ${length} bytes: ${built.diagnostics.map((diagnostic) => diagnostic.message).join("; ") || "it is longer than its range"}. Correct the patch in the project knowledge.`);
|
|
951
|
+
}
|
|
952
|
+
memory.set(built.program.subarray(2), patch.start);
|
|
953
|
+
}
|
|
954
|
+
const screen = startScreenRanges(row).map((part) => part.range);
|
|
955
|
+
let ranges = screen;
|
|
956
|
+
if (row.call !== undefined) {
|
|
957
|
+
if (knowledge.coverage === undefined) {
|
|
958
|
+
throw new Refusal("not-found", `The start screen calls ${formatC64Address(row.call)} of ${stage}, and the knowledge has no coverage in ${stage}. Run the stage with coverage while it calls ${formatC64Address(row.call)} and plays, and put the map into the project knowledge with coverage --space ${stage}. Then generate again.`);
|
|
959
|
+
}
|
|
960
|
+
// The call is the entry of the stage: what it does not reach and its run did not touch stays out.
|
|
961
|
+
const called = { ...knowledge, program: { ...image, entry: row.call } };
|
|
962
|
+
const { instructions } = await decode(called.program, called, [row.call], knowledge.coverage);
|
|
963
|
+
const free = leftoversOf(called, instructions, screen);
|
|
964
|
+
ranges = [...screen, ...image.segments.flatMap((segment) => subtract(segment, free))];
|
|
965
|
+
}
|
|
966
|
+
const parts: AddressRange[] = [];
|
|
967
|
+
for (const range of ranges.map((item) => ({ start: Math.max(item.start, 0x0400), end: item.end })).filter((item) => item.start <= item.end).sort((a, b) => a.start - b.start)) {
|
|
968
|
+
const last = parts.at(-1);
|
|
969
|
+
if (last !== undefined && range.start <= last.end + 1) last.end = Math.max(last.end, range.end);
|
|
970
|
+
else parts.push({ ...range });
|
|
971
|
+
}
|
|
972
|
+
return parts.map((range) => ({ start: range.start, body: memory.slice(range.start, range.end + 1) }));
|
|
973
|
+
}
|
|
974
|
+
|
|
975
|
+
/** What the show stage gives: loader.prg, the source of the stage, and what its check needs. */
|
|
976
|
+
interface BuiltStage {
|
|
977
|
+
program: Buffer;
|
|
978
|
+
text: string;
|
|
979
|
+
plan: StagePlan;
|
|
980
|
+
parts: StagePart[];
|
|
981
|
+
packed: PackedLoader;
|
|
982
|
+
wait: number;
|
|
983
|
+
continue: number;
|
|
984
|
+
screen: StartScreenPlan;
|
|
985
|
+
}
|
|
986
|
+
|
|
987
|
+
/**
|
|
988
|
+
* Builds the show stage of a start screen from a captured stage: plans it,
|
|
989
|
+
* assembles start_screen_stage.asm and packs it with the loader as the loader
|
|
990
|
+
* is in memory before it starts. Refuses by name.
|
|
991
|
+
*/
|
|
992
|
+
async function buildStage(files: Array<{ name: string; text: string }>, laid: Layout, loader: LoaderPlan, main: { program: Buffer; start: number }, copierBuild: Buffer, row: StartScreenRow, values: ReadonlyMap<string, number>, header: string[], mark: string): Promise<BuiltStage> {
|
|
993
|
+
const stage = await stageBytes(row);
|
|
994
|
+
const inner: StagePart[] = loader.packed === undefined ? [{ start: 0x0801, body: copierBuild.subarray(2) }] : packedParts(main.program, copierBuild, loader).map((part) => ({ start: part.start, body: part.body }));
|
|
995
|
+
const screen = startScreenPlan(row);
|
|
996
|
+
const input: StageInput = {
|
|
997
|
+
inner,
|
|
998
|
+
innerStart: loader.packed === undefined ? 0x080d : loader.copier,
|
|
999
|
+
innerPort: loader.packed === undefined ? 0x37 : 0x34,
|
|
1000
|
+
stage,
|
|
1001
|
+
row,
|
|
1002
|
+
plan: screen,
|
|
1003
|
+
settings: hasSwitchFile(laid) ? ['!source "switches.asm"'] : hasConfigFile(laid) ? ['!source "config.asm"'] : [],
|
|
1004
|
+
header,
|
|
1005
|
+
codeSize: 0,
|
|
1006
|
+
};
|
|
1007
|
+
const support = [...withValues(files, laid, values).filter((file) => file.name === CONFIG_FILE || file.name === "switches.asm"), { name: START_SCREEN_FILE, text: START_SCREEN_CODE }];
|
|
1008
|
+
const assembleStage = async (text: string) => {
|
|
1009
|
+
const built = await assembleFiles([...support, { name: STAGE_FILE, text }], STAGE_FILE);
|
|
1010
|
+
if (built.program === undefined) throw new WireFailure("operation-failed", `${STAGE_FILE} does not assemble: ${built.diagnostics.map((diagnostic) => diagnostic.message).join("; ")}. This is a defect of the script.`);
|
|
1011
|
+
const labels = new Map((built.symbols ?? []).map((symbol) => [symbol.name, symbol.kind === "address" ? symbol.address : symbol.value]));
|
|
1012
|
+
const label = (name: string) => {
|
|
1013
|
+
const value = labels.get(name);
|
|
1014
|
+
if (value === undefined) throw new WireFailure("operation-failed", `The build of ${STAGE_FILE} has no ${name} label. This is a defect of the script.`);
|
|
1015
|
+
return value;
|
|
1016
|
+
};
|
|
1017
|
+
return { program: built.program, label };
|
|
1018
|
+
};
|
|
1019
|
+
// The size of the show code does not depend on its address: one build without a stash gives it.
|
|
1020
|
+
const probe = await assembleStage(stageText(input, 0x1000, []));
|
|
1021
|
+
input.codeSize = probe.label(STAGE_CODE_END) - probe.label(STAGE_START) - 2;
|
|
1022
|
+
const plan = planStage(input);
|
|
1023
|
+
const built = await assembleStage(plan.text);
|
|
1024
|
+
if (built.label(STAGE_START) !== plan.code || built.label(STAGE_CODE_END) - plan.code !== input.codeSize + 6 * plan.stash.length + 2) throw new WireFailure("operation-failed", `The build of ${STAGE_FILE} does not have the planned layout. This is a defect of the script.`);
|
|
1025
|
+
const parts = stageParts(input, plan, built.program, built.label);
|
|
1026
|
+
const packed = await packParts(parts, plan.code, 0x37, "the loader and the start screen of the stage", "the show stage", localToolContext());
|
|
1027
|
+
const end = 0x0801 + packed.program.length - 3;
|
|
1028
|
+
if (end > 0xcfff) throw new Refusal("invalid-input", `loader.prg with the start screen of ${row.stage} would end at ${formatC64Address(end)}, after $cfff: loading it would write the I/O area. Capture the stage with less memory, so that its program holds only the start screen and the routine of the call.`);
|
|
1029
|
+
return { program: packed.program, text: `${mark}\n${plan.text}`, plan, parts: stage, packed, wait: built.label(START_SCREEN_WAIT), continue: built.label(START_SCREEN_CONTINUE), screen };
|
|
1030
|
+
}
|
|
1031
|
+
|
|
866
1032
|
/** The first line of each file that generate writes. */
|
|
867
1033
|
const GENERATED_LINE = `${GENERATED_MARK}. Do not edit: change the knowledge and generate again.`;
|
|
868
1034
|
|
|
@@ -880,24 +1046,27 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
|
|
|
880
1046
|
}
|
|
881
1047
|
// Read the entry state before the long steps, so a bad state stops the run at once.
|
|
882
1048
|
const state = loaderWanted ? loaderState(image.state, "the entry state of the knowledge") : undefined;
|
|
883
|
-
// Every build that is compared with the program is the build of the base release: each switch at its base value.
|
|
884
|
-
const baseValues = new Map(knowledge.switches.map((row) => [row.name, row.base]));
|
|
1049
|
+
// Every build that is compared with the program is the build of the base release: each switch at its base value, with the leftovers.
|
|
1050
|
+
const baseValues = new Map<string, number>([...knowledge.switches.map((row) => [row.name, row.base] as const), [LEFTOVERS_SWITCH, 1]]);
|
|
1051
|
+
// config.asm keeps the value of each switch that it already has: the user sets the switches there. The loader loads that build.
|
|
1052
|
+
const configPath = resolveProjectPath(`${out}/${CONFIG_FILE}`);
|
|
1053
|
+
const given = existsSync(configPath) ? configValues(readFileSync(configPath, "utf8")) : new Map<string, 0 | 1>();
|
|
1054
|
+
const configNames = new Set([...knowledge.switches.map((row) => row.name), START_SCREEN_SWITCH, LEFTOVERS_SWITCH]);
|
|
1055
|
+
const loaderValues = new Map([...given].filter(([name]) => configNames.has(name)));
|
|
885
1056
|
const header = [`Generated by c64-source from knowledge revision ${knowledge.revision}${space === DEFAULT_SPACE ? "" : ` in space ${space}`}.`, "Change names, comments, regions and modules in knowledge, then generate again."];
|
|
886
1057
|
const loaderHeader = [`${LOADER_REVISION}${knowledge.revision}.`, "It copies the segments into place, sets the entry state and jumps to the entry."];
|
|
887
|
-
const { romUse, dataOnly, laid, rendered, files, built, loader, missingEntry, loaderRefused } = await buildSource(knowledge, {
|
|
1058
|
+
const { romUse, dataOnly, laid, rendered, files, built, loader, loaderMain, missingEntry, loaderRefused } = await buildSource(knowledge, {
|
|
888
1059
|
space,
|
|
889
1060
|
entries,
|
|
890
1061
|
header,
|
|
891
1062
|
mark: GENERATED_LINE,
|
|
892
1063
|
values: baseValues,
|
|
893
1064
|
notExecutedMarks: true,
|
|
894
|
-
|
|
1065
|
+
leftovers: true,
|
|
1066
|
+
...(state === undefined ? {} : { state, loaderHeader, loaderValues }),
|
|
895
1067
|
});
|
|
896
|
-
//
|
|
897
|
-
const
|
|
898
|
-
const given = existsSync(configPath) ? configValues(readFileSync(configPath, "utf8")) : new Map<string, 0 | 1>();
|
|
899
|
-
// START_SCREEN is a switch of the start screen, with the default 1.
|
|
900
|
-
const configured = [...laid.switches, ...(laid.startScreen ? [{ name: START_SCREEN_SWITCH, default: 1 }] : [])];
|
|
1068
|
+
// START_SCREEN is a switch of the start screen, with the default 1. LEFTOVERS has the default 0: the default build is the clean program.
|
|
1069
|
+
const configured = [...laid.switches, ...(laid.startScreen ? [{ name: START_SCREEN_SWITCH, default: 1 }] : []), ...(laid.leftovers.length > 0 ? [{ name: LEFTOVERS_SWITCH, default: 0 }] : [])];
|
|
901
1070
|
const kept = new Map(configured.flatMap((row) => (given.has(row.name) ? [[row.name, given.get(row.name)!] as const] : [])));
|
|
902
1071
|
const notDefault = configured.flatMap((row) => (kept.has(row.name) && kept.get(row.name) !== row.default ? [{ name: row.name, value: kept.get(row.name)!, default: row.default }] : []));
|
|
903
1072
|
const removed = removeOldFiles(out, new Set(files.map((file) => file.name)), loaderWanted).map((name) => `${out}/${name}`);
|
|
@@ -950,6 +1119,12 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
|
|
|
950
1119
|
notExecuted: { instructions: rendered.notExecuted.instructions, ...listed(rendered.notExecuted.ranges, max, showRange, `${out}/${NOT_EXECUTED_FILE}`) },
|
|
951
1120
|
}),
|
|
952
1121
|
...(laid.unusedModules.length === 0 ? {} : { unusedModules: laid.unusedModules.map((module) => ({ start: formatC64Address(module.start), file: module.file })) }),
|
|
1122
|
+
// The bytes that nothing uses: in leftover files, which the default build and the loader leave out.
|
|
1123
|
+
...(laid.leftovers.length === 0
|
|
1124
|
+
? knowledge.coverage === undefined && space === DEFAULT_SPACE
|
|
1125
|
+
? { leftovers: { bytes: 0, noCoverage: "The knowledge has no coverage, so no range is a leftover, and the default build and the loader have every byte of the program." } }
|
|
1126
|
+
: {}
|
|
1127
|
+
: { leftovers: { bytes: laid.leftovers.reduce((sum, range) => sum + range.end - range.start + 1, 0), ...listed(laid.leftovers, max, (range) => ({ ...showRange(range), bytes: range.end - range.start + 1, file: `leftover_${range.start.toString(16).padStart(4, "0")}.asm` })) } }),
|
|
953
1128
|
...(rendered.expressions.length === 0 && rendered.operandsAsNumbers.length === 0 ? {} : { operandExpressions: rendered.expressions.length }),
|
|
954
1129
|
...(rendered.operandsAsNumbers.length === 0
|
|
955
1130
|
? {}
|
|
@@ -993,9 +1168,10 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
|
|
|
993
1168
|
if (switches.length > 0) output.switches = switches;
|
|
994
1169
|
// The default build: the patches of each switch whose default is not its base value are in, and nothing else changes.
|
|
995
1170
|
let defaultFailed = false;
|
|
996
|
-
if (laid.switches.length > 0) {
|
|
1171
|
+
if (laid.switches.length > 0 || laid.leftovers.length > 0) {
|
|
997
1172
|
const changed = laid.switches.filter((row) => row.default !== row.base);
|
|
998
|
-
|
|
1173
|
+
// The default build also leaves out the leftovers.
|
|
1174
|
+
const ranges = [...changed.flatMap((row) => withPatches.get(row.name) ?? []), ...laid.leftovers];
|
|
999
1175
|
const built = await checkBuild(withValues(files, laid, new Map()), ranges, baseBuild);
|
|
1000
1176
|
output.default = { in: changed.map((row) => row.name), ...built };
|
|
1001
1177
|
defaultFailed = built.result !== "fits";
|
|
@@ -1007,25 +1183,36 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
|
|
|
1007
1183
|
const releasesFailed = releases.some((item) => item.result !== "identical" && (item.base || item.result !== "layout differs"));
|
|
1008
1184
|
const sourceFailed = laid.patchesNotWritten.length > 0 || switches.some((item) => item.result !== "fits") || defaultFailed || releasesFailed;
|
|
1009
1185
|
if (loaderRefused !== undefined) return { output: { ...output, loader: notVerified({ reason: loaderRefused }) }, removed, failed: true };
|
|
1010
|
-
if (loader === undefined || state === undefined) return { output, removed, failed: missingEntry !== undefined || sourceFailed };
|
|
1186
|
+
if (loader === undefined || loaderMain === undefined || state === undefined) return { output, removed, failed: missingEntry !== undefined || sourceFailed };
|
|
1011
1187
|
|
|
1012
|
-
// The
|
|
1013
|
-
const loaderBuilt = await buildLoader(files, laid, loader,
|
|
1188
|
+
// The loader loads the build with the values of config.asm, without the leftovers. The entry state is the state of the base release.
|
|
1189
|
+
const loaderBuilt = await buildLoader(files, laid, loader, loaderMain, state, loaderValues);
|
|
1014
1190
|
if ("diagnostics" in loaderBuilt) return { output: { ...output, loader: notVerified({ reason: "loader.asm does not assemble.", diagnostics: loaderBuilt.diagnostics }) }, removed, failed: true };
|
|
1015
1191
|
const { jump, copierSource, expected, startScreen } = loaderBuilt;
|
|
1016
1192
|
const copierBuild = loaderBuilt.program;
|
|
1017
1193
|
const fileByte = (address: number) => copierBuild[2 + address - (loader.packed?.start ?? 0x0801)]!;
|
|
1194
|
+
// A start screen of a captured stage: the show stage packs the loader with it, so the packed form is not packed alone.
|
|
1195
|
+
const stageRow = knowledge.startScreen?.stage === undefined ? undefined : knowledge.startScreen;
|
|
1018
1196
|
// The packed form: Exomizer packs the build of main.asm with the copier. Without Exomizer, or when its check fails, there is no new loader.prg.
|
|
1019
1197
|
let packed: PackedLoader | undefined;
|
|
1020
|
-
if (loader.packed !== undefined) {
|
|
1198
|
+
if (loader.packed !== undefined && stageRow === undefined) {
|
|
1021
1199
|
try {
|
|
1022
|
-
packed = await packLoader(
|
|
1200
|
+
packed = await packLoader(loaderMain.program, copierBuild, loader, localToolContext());
|
|
1023
1201
|
} catch (error) {
|
|
1024
1202
|
if (!isRefusal(error)) throw error;
|
|
1025
1203
|
return { output: { ...output, loader: notVerified({ reason: `loader.asm has the packed form, and the pack with Exomizer failed. ${error.message}` }) }, removed, failed: true };
|
|
1026
1204
|
}
|
|
1027
1205
|
}
|
|
1028
|
-
|
|
1206
|
+
let stage: BuiltStage | undefined;
|
|
1207
|
+
if (stageRow !== undefined) {
|
|
1208
|
+
try {
|
|
1209
|
+
stage = await buildStage(files, laid, loader, loaderMain, copierBuild, stageRow, loaderValues, loaderHeader, GENERATED_LINE);
|
|
1210
|
+
} catch (error) {
|
|
1211
|
+
if (!isRefusal(error)) throw error;
|
|
1212
|
+
return { output: { ...output, loader: notVerified({ reason: `The show stage of the start screen from ${stageRow.stage} cannot be built. ${error.message}` }) }, removed, failed: true };
|
|
1213
|
+
}
|
|
1214
|
+
}
|
|
1215
|
+
const program = stage?.program ?? packed?.program ?? copierBuild;
|
|
1029
1216
|
// The check runs the new loader from a scratch file. Only a loader whose check ran goes to --out, so a check
|
|
1030
1217
|
// that cannot run (no host, or a host of another release) keeps the loader.prg of an earlier run.
|
|
1031
1218
|
ensureLocal(projectRoot());
|
|
@@ -1033,11 +1220,19 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
|
|
|
1033
1220
|
mkdirSync(resolveProjectPath(scratch), { recursive: true });
|
|
1034
1221
|
const checkPath = `${scratch}/loader.prg`;
|
|
1035
1222
|
writeFileSync(resolveProjectPath(checkPath), program);
|
|
1036
|
-
// The unpack runs before the copier.
|
|
1037
|
-
const
|
|
1223
|
+
// The unpack runs before the copier, or before the show stage, which then starts the loader.
|
|
1224
|
+
const unpackFrames = (cycles: number | undefined) => (cycles === undefined ? LOADER_FRAMES : RUN_LIMIT_FRAMES + Math.ceil(cycles / PAL_FRAME_CYCLES));
|
|
1225
|
+
const copierFrames = stage !== undefined || packed === undefined ? RUN_LIMIT_FRAMES : unpackFrames(packed.cycles);
|
|
1226
|
+
// The check compares the bytes of the screen of the stage: a routine of the stage can change its other bytes.
|
|
1227
|
+
const stageByte = (address: number) => {
|
|
1228
|
+
const part = stage!.parts.find((item) => address >= item.start && address < item.start + item.body.length)!;
|
|
1229
|
+
return part.body[address - part.start]!;
|
|
1230
|
+
};
|
|
1231
|
+
const screenParts = stage === undefined ? [] : startScreenRanges(stageRow!).map(({ range }) => ({ start: range.start, body: Uint8Array.from({ length: range.end - range.start + 1 }, (_, offset) => stageByte(range.start + offset)) }));
|
|
1232
|
+
const stageRun = stage === undefined ? {} : { stage: { name: stageRow!.stage!, wait: stage.wait, continue: stage.continue, screen: stage.screen, parts: screenParts, frames: unpackFrames(stage.packed.cycles) + LOADER_FRAMES } };
|
|
1038
1233
|
let ran: LoaderRun;
|
|
1039
1234
|
try {
|
|
1040
|
-
ran = await runLoader(checkPath, program, loader,
|
|
1235
|
+
ran = await runLoader(checkPath, program, loader, state, { jump, copierSource, fileByte, copierFrames, ...(startScreen === undefined ? {} : { startScreen }), ...stageRun }, expected);
|
|
1041
1236
|
} catch (error) {
|
|
1042
1237
|
if (!isRefusal(error)) throw error;
|
|
1043
1238
|
const what = existsSync(resolveProjectPath(loaderPath)) ? "kept the loader.prg of an earlier run" : "wrote no loader.prg";
|
|
@@ -1046,9 +1241,22 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
|
|
|
1046
1241
|
rmSync(resolveProjectPath(scratch), { recursive: true, force: true });
|
|
1047
1242
|
}
|
|
1048
1243
|
written.push(writeReported(loaderPath, program, { what: "--out" }));
|
|
1244
|
+
if (stage !== undefined) written.push(writeReported(`${out}/${STAGE_FILE}`, stage.text, { what: "--out" }), writeReported(`${out}/${START_SCREEN_FILE}`, `${GENERATED_LINE}\n${START_SCREEN_CODE}`, { what: "--out" }));
|
|
1049
1245
|
output.loader = {
|
|
1050
1246
|
program: loaderPath,
|
|
1051
1247
|
...(packed === undefined ? {} : { packed: { packedBytes: packed.packedBytes, unpackedBytes: packed.unpackedBytes } }),
|
|
1248
|
+
...(stage === undefined
|
|
1249
|
+
? {}
|
|
1250
|
+
: {
|
|
1251
|
+
stage: {
|
|
1252
|
+
space: stageRow!.stage,
|
|
1253
|
+
code: formatC64Address(stage.plan.code),
|
|
1254
|
+
bytes: stage.parts.reduce((sum, part) => sum + part.body.length, 0),
|
|
1255
|
+
stash: stage.plan.stash.map((item) => ({ from: formatC64Address(item.at), to: `${formatC64Address(item.target.start)}-${formatC64Address(item.target.end)}` })),
|
|
1256
|
+
packedBytes: stage.packed.packedBytes,
|
|
1257
|
+
unpackedBytes: stage.packed.unpackedBytes,
|
|
1258
|
+
},
|
|
1259
|
+
}),
|
|
1052
1260
|
copies: loader.copies.map((copy) => ({ what: copy.what, to: `${formatC64Address(copy.target.start)}-${formatC64Address(copy.target.end)}` })),
|
|
1053
1261
|
copier: formatC64Address(loader.copier),
|
|
1054
1262
|
stackByte: formatC64Address(loader.stackByte),
|
|
@@ -1095,6 +1303,61 @@ function effectiveRegions(regions: SourceKnowledge["regions"]): SourceKnowledge[
|
|
|
1095
1303
|
return [...semantic, ...regions.filter((region) => !isSemantic(region.origin)).flatMap((region) => clipped(region, holes))].sort((a, b) => a.start - b.start);
|
|
1096
1304
|
}
|
|
1097
1305
|
|
|
1306
|
+
/** The names and the four-digit hex addresses that the code of a patch has: a switch can go to them, so they stay. */
|
|
1307
|
+
function patchTargets(code: string, addressOf: ReadonlyMap<string, number>): number[] {
|
|
1308
|
+
const words = code.replace(/;.*$/gm, "").match(/\$[0-9a-fA-F]{4}\b|[A-Za-z_][A-Za-z0-9_]*/g) ?? [];
|
|
1309
|
+
return words.flatMap((word) => (word.startsWith("$") ? [Number.parseInt(word.slice(1), 16)] : addressOf.has(word) ? [addressOf.get(word)!] : []));
|
|
1310
|
+
}
|
|
1311
|
+
|
|
1312
|
+
/**
|
|
1313
|
+
* The free ranges of a program: code that no run executed and that nothing
|
|
1314
|
+
* reaches, and data that no run touched and that nothing names (planDrops).
|
|
1315
|
+
* The export makes them $00; generate makes them the leftovers. `memory` and
|
|
1316
|
+
* `instructions` are of the build that the ranges are free in.
|
|
1317
|
+
*/
|
|
1318
|
+
function freeRanges(knowledge: SourceKnowledge, memory: Uint8Array, instructions: ReadonlyMap<number, number>, ranges: { changed: readonly AddressRange[]; keep: readonly AddressRange[]; drop: readonly AddressRange[] }) {
|
|
1319
|
+
const image = knowledge.program;
|
|
1320
|
+
const addressOf = new Map(knowledge.symbols.map((symbol) => [symbol.name, symbol.address]));
|
|
1321
|
+
const operandTargets = new Map<number, number[]>();
|
|
1322
|
+
for (const operand of knowledge.operands) {
|
|
1323
|
+
const names = operand.symbol !== undefined ? [operand.symbol] : identifiers(operand.expression ?? "");
|
|
1324
|
+
const targets = names.flatMap((item) => (addressOf.has(item) ? [(addressOf.get(item)! + (operand.symbol !== undefined ? operand.offset : 0)) & 0xffff] : []));
|
|
1325
|
+
if (targets.length > 0) operandTargets.set(operand.address, targets);
|
|
1326
|
+
}
|
|
1327
|
+
const entry = image.entry ?? basicEntry(image);
|
|
1328
|
+
return planDrops({
|
|
1329
|
+
segments: image.segments,
|
|
1330
|
+
memory,
|
|
1331
|
+
...(entry === undefined ? {} : { entry }),
|
|
1332
|
+
instructions,
|
|
1333
|
+
...(knowledge.coverage === undefined ? {} : { coverage: knowledge.coverage }),
|
|
1334
|
+
regions: effectiveRegions(knowledge.regions),
|
|
1335
|
+
references: knowledge.references,
|
|
1336
|
+
operandTargets,
|
|
1337
|
+
changed: [...ranges.changed],
|
|
1338
|
+
keep: [...ranges.keep],
|
|
1339
|
+
drop: [...ranges.drop],
|
|
1340
|
+
routines: knowledge.symbols.filter((symbol) => symbol.kind === "routine"),
|
|
1341
|
+
});
|
|
1342
|
+
}
|
|
1343
|
+
|
|
1344
|
+
/**
|
|
1345
|
+
* The leftovers of generate: the free ranges of the program as it is. The
|
|
1346
|
+
* start screen in the program, the patches, the macro uses, what the code of a
|
|
1347
|
+
* patch names and the ranges of `keep` stay, so each switch builds with
|
|
1348
|
+
* LEFTOVERS = 0.
|
|
1349
|
+
*/
|
|
1350
|
+
function leftoversOf(knowledge: SourceKnowledge, instructions: ReadonlyMap<number, number>, kept: readonly AddressRange[] = []): AddressRange[] {
|
|
1351
|
+
const image = knowledge.program;
|
|
1352
|
+
const inImage = (range: AddressRange) => image.segments.some((segment) => range.start >= segment.start && range.end <= segment.end);
|
|
1353
|
+
const addressOf = new Map(knowledge.symbols.map((symbol) => [symbol.name, symbol.address]));
|
|
1354
|
+
const screenParts = knowledge.startScreen === undefined || knowledge.startScreen.stage !== undefined ? [] : startScreenRanges(knowledge.startScreen).map((part) => part.range);
|
|
1355
|
+
const named = knowledge.patches.flatMap((patch) => patchTargets(patch.code, addressOf)).map((address) => ({ start: address, end: address }));
|
|
1356
|
+
const keep = [...screenParts, ...kept, ...knowledge.macroUses, ...named].map((range) => ({ start: range.start, end: range.end })).filter(inImage);
|
|
1357
|
+
const changed = knowledge.patches.map((patch) => ({ start: patch.start, end: patch.end })).filter(inImage);
|
|
1358
|
+
return freeRanges(knowledge, image.memory, instructions, { changed, keep, drop: [] }).free.map((range) => ({ start: range.start, end: range.end }));
|
|
1359
|
+
}
|
|
1360
|
+
|
|
1098
1361
|
/** Every file in a folder with its path in it, with / between the parts, in path order. `skip` leaves out a folder by its path. */
|
|
1099
1362
|
function filesIn(root: string, skip: (path: string) => boolean, folder = ""): Array<{ path: string; bytes: Buffer }> {
|
|
1100
1363
|
const found: Array<{ path: string; bytes: Buffer }> = [];
|
|
@@ -1134,7 +1397,10 @@ async function exportProject(call: Call): Promise<Record<string, unknown>> {
|
|
|
1134
1397
|
db?.close();
|
|
1135
1398
|
}
|
|
1136
1399
|
})();
|
|
1137
|
-
const
|
|
1400
|
+
const read = readKnowledge(DEFAULT_SPACE);
|
|
1401
|
+
// The export has only the space c64: a start screen of a captured stage stays out with that space.
|
|
1402
|
+
const stageLeftOut = read.startScreen?.stage;
|
|
1403
|
+
const knowledge = stageLeftOut === undefined ? read : { ...read, startScreen: undefined };
|
|
1138
1404
|
const image = knowledge.program;
|
|
1139
1405
|
// The VIC-II reads the start screen, and the coverage does not show those reads: it stays.
|
|
1140
1406
|
const screenParts = knowledge.startScreen === undefined ? [] : startScreenRanges(knowledge.startScreen).map((part) => part.range);
|
|
@@ -1179,29 +1445,8 @@ async function exportProject(call: Call): Promise<Record<string, unknown>> {
|
|
|
1179
1445
|
const decoded = await decode(bakedImage, knowledge, [], knowledge.coverage);
|
|
1180
1446
|
|
|
1181
1447
|
// 4. The free ranges.
|
|
1182
|
-
const addressOf = new Map(knowledge.symbols.map((symbol) => [symbol.name, symbol.address]));
|
|
1183
|
-
const operandTargets = new Map<number, number[]>();
|
|
1184
|
-
for (const operand of knowledge.operands) {
|
|
1185
|
-
const names = operand.symbol !== undefined ? [operand.symbol] : identifiers(operand.expression ?? "");
|
|
1186
|
-
const targets = names.flatMap((item) => (addressOf.has(item) ? [(addressOf.get(item)! + (operand.symbol !== undefined ? operand.offset : 0)) & 0xffff] : []));
|
|
1187
|
-
if (targets.length > 0) operandTargets.set(operand.address, targets);
|
|
1188
|
-
}
|
|
1189
1448
|
const regions = effectiveRegions(knowledge.regions);
|
|
1190
|
-
const
|
|
1191
|
-
const plan = planDrops({
|
|
1192
|
-
segments: image.segments,
|
|
1193
|
-
memory,
|
|
1194
|
-
...(entry === undefined ? {} : { entry }),
|
|
1195
|
-
instructions: decoded.instructions,
|
|
1196
|
-
...(knowledge.coverage === undefined ? {} : { coverage: knowledge.coverage }),
|
|
1197
|
-
regions,
|
|
1198
|
-
references: knowledge.references,
|
|
1199
|
-
operandTargets,
|
|
1200
|
-
changed,
|
|
1201
|
-
keep,
|
|
1202
|
-
drop,
|
|
1203
|
-
routines: knowledge.symbols.filter((symbol) => symbol.kind === "routine"),
|
|
1204
|
-
});
|
|
1449
|
+
const plan = freeRanges(knowledge, memory, decoded.instructions, { changed, keep, drop });
|
|
1205
1450
|
const free = plan.free;
|
|
1206
1451
|
const inFree = (address: number) => free.some((range) => address >= range.start && address <= range.end);
|
|
1207
1452
|
const overlapsAny = (start: number, end: number, ranges: readonly AddressRange[]) => ranges.some((range) => start <= range.end && range.start <= end);
|
|
@@ -1265,7 +1510,7 @@ async function exportProject(call: Call): Promise<Record<string, unknown>> {
|
|
|
1265
1510
|
if (state !== undefined) {
|
|
1266
1511
|
if (exported.loader === undefined) return { result: "FAIL", stage: "loader", reason: exported.loaderRefused ?? "The loader could not be planned." };
|
|
1267
1512
|
if (exported.loader.packed !== undefined) return { result: "FAIL", stage: "loader", reason: "The program is too large for one loader file, and export does not make the packed form of the loader." };
|
|
1268
|
-
const loaderBuilt = await buildLoader(exported.files, exported.laid, exported.loader,
|
|
1513
|
+
const loaderBuilt = await buildLoader(exported.files, exported.laid, exported.loader, exported.loaderMain!, state, new Map());
|
|
1269
1514
|
if ("diagnostics" in loaderBuilt) return { result: "FAIL", stage: "loader", reason: "loader.asm does not assemble. This is a defect of the script.", diagnostics: loaderBuilt.diagnostics };
|
|
1270
1515
|
baseline = { program: loaderBuilt.program, symbols: loaderBuilt.symbols, entryFile: "loader.asm" };
|
|
1271
1516
|
loaderOutput = {
|
|
@@ -1343,6 +1588,7 @@ async function exportProject(call: Call): Promise<Record<string, unknown>> {
|
|
|
1343
1588
|
knowledge: kept,
|
|
1344
1589
|
tests: { written: tests.map((test) => test.file), leftOut: listed(testsLeftOut, max, (item) => item) },
|
|
1345
1590
|
...(spacesLeftOut.length === 0 ? {} : { spacesLeftOut }),
|
|
1591
|
+
...(stageLeftOut === undefined ? {} : { startScreenLeftOut: `The start screen is of the captured stage in ${stageLeftOut}, and the export has only the space c64.` }),
|
|
1346
1592
|
...(exported.rendered.operandsAsNumbers.length === 0 ? {} : { operandsAsNumbers: listed(exported.rendered.operandsAsNumbers, max, (item) => ({ address: formatC64Address(item.address), expression: item.expression, reason: item.reason })) }),
|
|
1347
1593
|
...(exported.rendered.macrosAsInstructions.length === 0 ? {} : { macrosAsInstructions: listed(exported.rendered.macrosAsInstructions, max, (item) => ({ start: formatC64Address(item.start), end: formatC64Address(item.end), macro: item.macro, reason: item.reason })) }),
|
|
1348
1594
|
};
|
|
@@ -1398,6 +1644,7 @@ function generateReply(call: Call, body: Record<string, unknown>): Reply {
|
|
|
1398
1644
|
again = true;
|
|
1399
1645
|
}
|
|
1400
1646
|
if ((body.loader as { verified?: boolean } | undefined)?.verified === false) steps.push("The loader is not verified. Read loader.reason, loader.differences and loader.stop.");
|
|
1647
|
+
if ((body.leftovers as { noCoverage?: string } | undefined)?.noCoverage !== undefined && call.flag("loader")) steps.push("To leave out the bytes that nothing uses, put the coverage of the runs into the project knowledge. Then generate again.");
|
|
1401
1648
|
if (body.dataOnly !== undefined) {
|
|
1402
1649
|
steps.push("The source has only data. If the space has code, give --entry, or record a code region in the project knowledge.");
|
|
1403
1650
|
again = true;
|
|
@@ -1452,8 +1699,8 @@ await runScript({
|
|
|
1452
1699
|
options: {
|
|
1453
1700
|
out: { ...OPTIONS.out, output: "folder", value: "<dir>", help: "the folder for the source files, relative to the project folder", required: true },
|
|
1454
1701
|
entry: { ...OPTIONS.entry, multiple: true, help: "an address where code starts. The entry of the program, the routines and the code regions of the knowledge are entry points too" },
|
|
1455
|
-
space: { ...OPTIONS.space, help: "the knowledge space of the program: c64 (the default), drive8, or bank0 to bank255.
|
|
1456
|
-
loader: { kind: "flag", help: "also write loader.asm and loader.prg: the loader copies the segments into place, sets the entry state of the knowledge, and jumps to the entry. It is checked in the emulator. When the check cannot run, the script
|
|
1702
|
+
space: { ...OPTIONS.space, help: "the knowledge space of the program: c64 (the default), drive8, or bank0 to bank255. --loader is for c64 only" },
|
|
1703
|
+
loader: { kind: "flag", help: "also write loader.asm and loader.prg: the loader copies the segments into place, sets the entry state of the knowledge, and jumps to the entry. It is checked in the emulator. The loader leaves out the leftovers. When the check cannot run, the script keeps the loader.prg of an earlier run" },
|
|
1457
1704
|
"analyzer-names": { kind: "flag", help: "name an address that has no name of the user or the LLM, and no platform name, with its analyzer name" },
|
|
1458
1705
|
"max-listed": OPTIONS["max-listed"],
|
|
1459
1706
|
},
|