@henols/c64-re-tools 2.5.0 → 2.5.1-rc.2

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.
@@ -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";
@@ -44,7 +44,9 @@ import {
44
44
  LOADER_JUMP,
45
45
  loaderLimits,
46
46
  packLoader,
47
+ packParts,
47
48
  planLoader,
49
+ startScreenPlan,
48
50
  rasterLine,
49
51
  loaderState,
50
52
  simulate,
@@ -57,8 +59,11 @@ import {
57
59
  type EntryState,
58
60
  type LoaderPlan,
59
61
  type PackedLoader,
62
+ type StartScreenPlan,
60
63
  } from "./lib/loader.ts";
61
64
  import { instructionWith, OPCODES } from "#src/opcodes.ts";
65
+ import { capturedColourRam } from "#src/knowledge/start-screen.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 is of the C64: drive code and banks have none.
94
- coverage: space === DEFAULT_SPACE ? programCoverage(db)?.map : undefined,
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[]; colourRam?: Uint8Array; 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, image: ProgramImage, state: EntryState, run: LoaderRunPlan, expected: (address: number) => number): Promise<LoaderRun> {
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,60 @@ 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
- const stopped = async (pc: number, copied: boolean, what: string): Promise<LoaderRun> => {
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
- if (run.startScreen !== undefined && plan.startScreen !== undefined) {
570
- const labels = { wait: formatC64Address(run.startScreen.wait), continue: formatC64Address(run.startScreen.continue) };
571
- const atWait = await client.runUntil({ target: { kind: "address", address: run.startScreen.wait, space: "c64" }, timeoutFrames: LOADER_FRAMES });
572
- if (!atWait.reached) return await stopped(atWait.pc, true, `its start screen at ${labels.wait}`);
573
- const held = await client.runUntil({ target: { kind: "address", address: run.startScreen.continue, space: "c64" }, timeoutFrames: START_SCREEN_FRAMES });
575
+ const showScreen = async (at: { wait: number; continue: number }, wanted: StartScreenPlan, frames: number, copied: boolean, parts: readonly StagePart[] = [], colourRam?: Uint8Array): 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 wanted = plan.startScreen;
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 = { shown: screenDifferences.length === 0, waits: !held.reached, ...labels };
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
+ // The colour RAM of a captured stage: the first wrong colour.
596
+ if (colourRam !== undefined) {
597
+ const colours = Buffer.from((await client.ioRead(0xd800, colourRam.length)).data, "hex");
598
+ const wrong = colourRam.findIndex((value, offset) => (colours[offset]! & 0x0f) !== value);
599
+ if (wrong >= 0) screenDifferences.push(`the colour RAM has ${colours[wrong]! & 0x0f} at ${formatC64Address(0xd800 + wrong)}, not ${colourRam[wrong]}`);
600
+ }
601
+ screen = { shown: screenDifferences.length === before, waits: !held.reached, ...labels, ...(run.stage === undefined ? {} : { stage: run.stage.name }) };
584
602
  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: run.startScreen.continue });
603
+ if (!held.reached) await client.registersSet("c64", { pc: at.continue });
604
+ return undefined;
605
+ };
606
+ // The show stage of a captured stage runs before the loader.
607
+ if (run.stage !== undefined) {
608
+ const stop = await showScreen(run.stage, run.stage.screen, run.stage.frames, false, run.stage.parts, run.stage.colourRam);
609
+ if (stop !== undefined) return stop;
610
+ }
611
+ const copier = await client.runUntil({ target: { kind: "address", address: plan.copier, space: "c64" }, timeoutFrames: run.copierFrames });
612
+ if (!copier.reached) return await stopped(copier.pc, false, `its copier at ${formatC64Address(plan.copier)}`);
613
+ if (run.startScreen !== undefined && plan.startScreen !== undefined) {
614
+ const stop = await showScreen(run.startScreen, plan.startScreen, LOADER_FRAMES, true);
615
+ if (stop !== undefined) return stop;
586
616
  }
587
617
  const atJump = await client.runUntil({ target: { kind: "address", address: jump, space: "c64" }, timeoutFrames: LOADER_FRAMES });
588
618
  if (!atJump.reached) return await stopped(atJump.pc, true, `its jump to the entry at ${formatC64Address(jump)}`);
@@ -595,8 +625,9 @@ async function runLoader(path: string, program: Buffer, plan: LoaderPlan, image:
595
625
  const differences: string[] = [];
596
626
  const byte = (value: number) => `$${value.toString(16).padStart(2, "0")}`;
597
627
  const differ = (what: string, got: number, wanted: number) => got !== wanted && differences.push(`${what} is ${byte(got)}, not ${byte(wanted)}`);
598
- for (const segment of image.segments) {
599
- for (let address = Math.max(segment.start, 2); address <= segment.end; address++) differ(formatC64Address(address), memory[address]!, image.byteAt(address));
628
+ // The leftovers are not loaded: only the loaded ranges have the bytes of the build.
629
+ for (const part of plan.loaded) {
630
+ for (let address = Math.max(part.start, 2); address <= part.end; address++) differ(formatC64Address(address), memory[address]!, expected(address));
600
631
  }
601
632
  for (let address = 2; address < 0x400; address++) if (address !== plan.stackByte) differ(formatC64Address(address), memory[address]!, state.pages[address]!);
602
633
  differ("$00", port[0]!, state.port[0]);
@@ -667,7 +698,7 @@ function sourceMapText(rendered: Rendered, space: string, revision: string | nul
667
698
  const LOADER_CHECK_DIRECTORY = "loader-check";
668
699
 
669
700
  /** 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]);
701
+ const LOADER_FILES: ReadonlySet<string> = new Set(["loader.asm", "loader.prg", START_SCREEN_FILE, STAGE_FILE]);
671
702
 
672
703
  /** The start of the line of loader.asm that gives the knowledge revision of the loader. */
673
704
  const LOADER_REVISION = "Loader generated by c64-source from knowledge revision ";
@@ -736,6 +767,10 @@ interface SourceOptions {
736
767
  loaderHeader?: string[];
737
768
  /** The source of an export: no config.asm, so START_SCREEN has the default of start_screen.asm. */
738
769
  exported?: boolean;
770
+ /** Put the free ranges of the program into leftover files, which only LEFTOVERS = 1 builds. */
771
+ leftovers?: boolean;
772
+ /** The switch values of the build that the loader loads. The default is `values`. */
773
+ loaderValues?: ReadonlyMap<string, number>;
739
774
  }
740
775
 
741
776
  /**
@@ -751,6 +786,7 @@ async function buildSource(knowledge: SourceKnowledge, options: SourceOptions) {
751
786
  const romUse = romUseOfProgram(coverage, image.state);
752
787
  const platform = platformNamesFor(romUse);
753
788
  const { instructions, dataOnly } = options.decoded ?? (await decode(image, knowledge, options.entries, coverage));
789
+ const leftovers = options.leftovers === true && !dataOnly ? leftoversOf(knowledge, instructions) : [];
754
790
  const laid = layout({
755
791
  segments: image.segments,
756
792
  byteAt: image.byteAt,
@@ -768,50 +804,23 @@ async function buildSource(knowledge: SourceKnowledge, options: SourceOptions) {
768
804
  macros: knowledge.macros,
769
805
  macroUses: knowledge.macroUses,
770
806
  startScreen: knowledge.startScreen !== undefined && options.exported !== true,
807
+ leftovers,
771
808
  ...(coverage === undefined || !options.notExecutedMarks ? {} : { coverage }),
772
809
  // The platform names are C64 names: drive code and banks get none. A ROM that the program does not use gives none.
773
810
  ...(space === DEFAULT_SPACE ? { platform, platformLeftOut: leftOutNames(platform), describe: describeAddress, decode: decodeRegister, io: IO_RAM } : {}),
774
811
  });
775
812
  const asBytes = await probe(laid);
776
813
  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
814
  // With a mark, every file starts with it.
805
815
  const { mark } = options;
806
816
  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
817
  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
818
  const numbers = new Map<number, string>();
810
819
  const asInstructions = new Map<number, string>();
811
820
  let rendered = render(laid, asBytes, header, numbers, asInstructions);
812
821
  if (laid.macroUses.size > 0) for (const [start, reason] of await probeUses(laid, rendered, image)) asInstructions.set(start, reason);
813
822
  if (asInstructions.size > 0) rendered = render(laid, asBytes, header, numbers, asInstructions);
814
- let files = marked([...rendered.files, ...loaderFiles]);
823
+ let files = marked(rendered.files);
815
824
  let built = await assembleFiles(withValues(files, laid, options.values), "main.asm");
816
825
  for (let round = 0; round < ROUNDS && (rendered.expressions.length > 0 || rendered.uses.length > 0); round++) {
817
826
  const blamed = blame(rendered, built, image, markLines);
@@ -819,22 +828,84 @@ async function buildSource(knowledge: SourceKnowledge, options: SourceOptions) {
819
828
  for (const [address, reason] of blamed.numbers) numbers.set(address, reason);
820
829
  for (const [start, reason] of blamed.uses) asInstructions.set(start, reason);
821
830
  rendered = render(laid, asBytes, header, numbers, asInstructions);
822
- files = marked([...rendered.files, ...loaderFiles]);
831
+ files = marked(rendered.files);
823
832
  built = await assembleFiles(withValues(files, laid, options.values), "main.asm");
824
833
  }
825
- return { romUse, instructions, dataOnly, laid, rendered, files, built, loader, missingEntry, loaderRefused };
834
+
835
+ let loader: LoaderPlan | undefined;
836
+ /** The build of main.asm that the loader loads: the switch values of the loader. */
837
+ let loaderMain: { program: Buffer; start: number } | undefined;
838
+ // An image without its entry has no program: the source is still written and checked, but the run fails.
839
+ const missingEntry = entryOutsideImage(image.entry, image.segments);
840
+ // A loader that cannot be planned does not stop the source: the source is written and checked, and the result says why.
841
+ const { state } = options;
842
+ let loaderRefused: string | undefined = state === undefined ? undefined : missingEntry;
843
+ if (state !== undefined && missingEntry === undefined) {
844
+ const main = options.loaderValues === undefined ? built : await assembleFiles(withValues(files, laid, options.loaderValues), "main.asm");
845
+ if (main.program === undefined) loaderRefused = "The source does not assemble with the switch values of the loader.";
846
+ else {
847
+ const program = main.program;
848
+ const start = main.start!;
849
+ loaderMain = { program, start };
850
+ try {
851
+ const entryName = laid.names.get(image.entry!);
852
+ loader = planLoader({
853
+ segments: loadedParts(laid, image.segments),
854
+ byteAt: (address) => program[2 + address - start]!,
855
+ state,
856
+ entry: image.entry!,
857
+ ...(entryName === undefined ? {} : { entryName }),
858
+ switches: hasSwitchFile(laid),
859
+ config: hasConfigFile(laid),
860
+ macros: laid.macros.length > 0,
861
+ header: options.loaderHeader ?? [],
862
+ // A start screen of a stage shows before the loader, in the show stage, while the program is still packed: the copier has none.
863
+ ...(knowledge.startScreen === undefined || knowledge.startScreen.stage !== undefined ? {} : { startScreen: knowledge.startScreen }),
864
+ ...(knowledge.startScreen?.stage === undefined ? {} : { packed: true }),
865
+ });
866
+ } catch (error) {
867
+ if (!isRefusal(error)) throw error;
868
+ loaderRefused = error.message;
869
+ }
870
+ }
871
+ }
872
+ if (loader !== undefined) files = [...files, ...marked([{ name: "loader.asm", text: loader.text }, ...(loader.startScreen === undefined ? [] : [{ name: START_SCREEN_FILE, text: START_SCREEN_CODE }])])];
873
+ return { romUse, instructions, dataOnly, laid, rendered, files, built, loader, loaderMain, missingEntry, loaderRefused };
874
+ }
875
+
876
+ /** The ranges that the loader loads, each with its files: the segments without the leftovers. */
877
+ function loadedParts(laid: Pick<Layout, "pieces">, segments: readonly AddressRange[]): Array<AddressRange & { files: string[] }> {
878
+ const parts: Array<AddressRange & { files: string[] }> = [];
879
+ for (const segment of segments) {
880
+ let open: (AddressRange & { files: string[] }) | undefined;
881
+ for (const piece of laid.pieces.filter((item) => item.start >= segment.start && item.start <= segment.end)) {
882
+ if (piece.leftover) {
883
+ open = undefined;
884
+ continue;
885
+ }
886
+ if (open === undefined) {
887
+ open = { start: piece.start, end: piece.end, files: [piece.file] };
888
+ parts.push(open);
889
+ } else {
890
+ open.end = piece.end;
891
+ open.files.push(piece.file);
892
+ }
893
+ }
894
+ }
895
+ return parts;
826
896
  }
827
897
 
828
898
  /**
829
899
  * 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. A layout
831
- * other than the plan is a defect of the script.
900
+ * loader as it loads, then every copy in its order, byte by byte. `main` is
901
+ * the build of main.asm with the same values: the loaded ranges must get its
902
+ * bytes. A layout other than the plan is a defect of the script.
832
903
  */
833
904
  async function buildLoader(
834
905
  files: Array<{ name: string; text: string }>,
835
906
  laid: Layout,
836
907
  loader: LoaderPlan,
837
- image: ProgramImage,
908
+ main: { program: Buffer; start: number },
838
909
  state: EntryState,
839
910
  values: ReadonlyMap<string, number>,
840
911
  ): Promise<{ program: Buffer; symbols: AssembledSymbol[]; jump: number; copierSource: number; expected: (address: number) => number; startScreen?: { wait: number; continue: number } } | { diagnostics: Diagnostic[] }> {
@@ -843,7 +914,7 @@ async function buildLoader(
843
914
  const program = loaderBuilt.program;
844
915
  const memory = new Int16Array(0x10000).fill(-1);
845
916
  program.subarray(2).forEach((byte, offset) => (memory[loaderBuilt.start! + offset] = byte));
846
- const expected = (address: number) => (image.segments.some((segment) => address >= segment.start && address <= segment.end) ? image.byteAt(address) : state.pages[address]!);
917
+ const expected = (address: number) => (loader.loaded.some((part) => address >= part.start && address <= part.end) ? main.program[2 + address - main.start]! : state.pages[address]!);
847
918
  const wrongPacking = loader.blocks.find((block) => {
848
919
  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
920
  return false;
@@ -863,6 +934,113 @@ async function buildLoader(
863
934
  return { program, symbols: loaderBuilt.symbols ?? [], jump, copierSource: symbolValue(COPIER_SOURCE), expected, ...(startScreen === undefined ? {} : { startScreen }) };
864
935
  }
865
936
 
937
+ /**
938
+ * The bytes of a captured stage that its start screen uses: the parts of the
939
+ * screen, and with a call every byte of the stage that is not free when the
940
+ * call is the entry (freeRanges, from the coverage of the stage). Each patch
941
+ * of the stage whose switch default is not its base value is in, as in the
942
+ * default build. Pages 0-3 are left out: the unpacker of Exomizer uses them.
943
+ */
944
+ async function stageBytes(row: StartScreenRow): Promise<{ parts: StagePart[]; colourRam?: Uint8Array }> {
945
+ const stage = row.stage!;
946
+ const knowledge = readKnowledge(stage);
947
+ const colourRam = row.colourRam === true ? capturedColourRam(knowledge.program.state) : undefined;
948
+ if (row.colourRam === true && colourRam === undefined) throw new Refusal("not-found", `The start screen takes its colours from the colour RAM of the capture in ${stage}, and that capture has none. Capture the stage again while it shows the screen, and put it into the project knowledge with image --space ${stage}.`);
949
+ const image = knowledge.program;
950
+ const memory = Uint8Array.from(image.memory);
951
+ const addresses = knowledge.symbols.map((symbol) => `${symbol.name} = ${formatC64Address(symbol.address)}`);
952
+ for (const patch of knowledge.patches) {
953
+ const owner = knowledge.switches.find((item) => item.name === patch.switch);
954
+ if (owner === undefined || owner.default === owner.base) continue;
955
+ const length = patch.end - patch.start + 1;
956
+ const text = ["!cpu 6510", ...addresses, `* = ${formatC64Address(patch.start)}`, ...patch.code.split(/\r?\n/), `!fill ${length} - (* - ${formatC64Address(patch.start)}), $ea`].join("\n");
957
+ const built = await assembleFiles([{ name: "patch.asm", text: `${text}\n` }], "patch.asm");
958
+ if (built.program === undefined || built.start !== patch.start || built.program.length - 2 !== length) {
959
+ 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.`);
960
+ }
961
+ memory.set(built.program.subarray(2), patch.start);
962
+ }
963
+ const screen = startScreenRanges(row).map((part) => part.range);
964
+ let ranges = screen;
965
+ if (row.call !== undefined) {
966
+ if (knowledge.coverage === undefined) {
967
+ 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.`);
968
+ }
969
+ // The call is the entry of the stage: what it does not reach and its run did not touch stays out.
970
+ const called = { ...knowledge, program: { ...image, entry: row.call } };
971
+ const { instructions } = await decode(called.program, called, [row.call], knowledge.coverage);
972
+ const free = leftoversOf(called, instructions, screen);
973
+ ranges = [...screen, ...image.segments.flatMap((segment) => subtract(segment, free))];
974
+ }
975
+ const parts: AddressRange[] = [];
976
+ 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)) {
977
+ const last = parts.at(-1);
978
+ if (last !== undefined && range.start <= last.end + 1) last.end = Math.max(last.end, range.end);
979
+ else parts.push({ ...range });
980
+ }
981
+ return { parts: parts.map((range) => ({ start: range.start, body: memory.slice(range.start, range.end + 1) })), ...(colourRam === undefined ? {} : { colourRam }) };
982
+ }
983
+
984
+ /** What the show stage gives: loader.prg, the source of the stage, and what its check needs. */
985
+ interface BuiltStage {
986
+ program: Buffer;
987
+ text: string;
988
+ plan: StagePlan;
989
+ parts: StagePart[];
990
+ colourRam?: Uint8Array;
991
+ packed: PackedLoader;
992
+ wait: number;
993
+ continue: number;
994
+ screen: StartScreenPlan;
995
+ }
996
+
997
+ /**
998
+ * Builds the show stage of a start screen from a captured stage: plans it,
999
+ * assembles start_screen_stage.asm and packs it with the loader as the loader
1000
+ * is in memory before it starts. Refuses by name.
1001
+ */
1002
+ async function buildStage(files: Array<{ name: string; text: string }>, laid: Layout, program: PackedLoader, row: StartScreenRow, values: ReadonlyMap<string, number>, header: string[], mark: string): Promise<BuiltStage> {
1003
+ const { parts: stage, colourRam } = await stageBytes(row);
1004
+ // The packed program, as RUN would start it: its unpacker unpacks it over the start screen after the wait.
1005
+ const inner: StagePart[] = [{ start: 0x0801, body: program.program.subarray(2) }];
1006
+ const screen = startScreenPlan(row);
1007
+ const input: StageInput = {
1008
+ inner,
1009
+ innerStart: 0x080d,
1010
+ innerPort: 0x37,
1011
+ stage,
1012
+ ...(colourRam === undefined ? {} : { colourRam }),
1013
+ row,
1014
+ plan: screen,
1015
+ settings: hasSwitchFile(laid) ? ['!source "switches.asm"'] : hasConfigFile(laid) ? ['!source "config.asm"'] : [],
1016
+ header,
1017
+ codeSize: 0,
1018
+ };
1019
+ const support = [...withValues(files, laid, values).filter((file) => file.name === CONFIG_FILE || file.name === "switches.asm"), { name: START_SCREEN_FILE, text: START_SCREEN_CODE }];
1020
+ const assembleStage = async (text: string) => {
1021
+ const built = await assembleFiles([...support, { name: STAGE_FILE, text }], STAGE_FILE);
1022
+ 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.`);
1023
+ const labels = new Map((built.symbols ?? []).map((symbol) => [symbol.name, symbol.kind === "address" ? symbol.address : symbol.value]));
1024
+ const label = (name: string) => {
1025
+ const value = labels.get(name);
1026
+ if (value === undefined) throw new WireFailure("operation-failed", `The build of ${STAGE_FILE} has no ${name} label. This is a defect of the script.`);
1027
+ return value;
1028
+ };
1029
+ return { program: built.program, label };
1030
+ };
1031
+ // The size of the show code does not depend on its address: one build without a stash gives it.
1032
+ const probe = await assembleStage(stageText(input, 0x1000, []));
1033
+ input.codeSize = probe.label(STAGE_CODE_END) - probe.label(STAGE_START) - 2;
1034
+ const plan = planStage(input);
1035
+ const built = await assembleStage(plan.text);
1036
+ 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.`);
1037
+ const parts = stageParts(input, plan, built.program, built.label);
1038
+ const packed = await packParts(parts, plan.code, 0x37, "the loader and the start screen of the stage", "the show stage", localToolContext());
1039
+ const end = 0x0801 + packed.program.length - 3;
1040
+ 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.`);
1041
+ return { program: packed.program, text: `${mark}\n${plan.text}`, plan, parts: stage, ...(colourRam === undefined ? {} : { colourRam }), packed, wait: built.label(START_SCREEN_WAIT), continue: built.label(START_SCREEN_CONTINUE), screen };
1042
+ }
1043
+
866
1044
  /** The first line of each file that generate writes. */
867
1045
  const GENERATED_LINE = `${GENERATED_MARK}. Do not edit: change the knowledge and generate again.`;
868
1046
 
@@ -880,24 +1058,27 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
880
1058
  }
881
1059
  // Read the entry state before the long steps, so a bad state stops the run at once.
882
1060
  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]));
1061
+ // Every build that is compared with the program is the build of the base release: each switch at its base value, with the leftovers.
1062
+ const baseValues = new Map<string, number>([...knowledge.switches.map((row) => [row.name, row.base] as const), [LEFTOVERS_SWITCH, 1]]);
1063
+ // config.asm keeps the value of each switch that it already has: the user sets the switches there. The loader loads that build.
1064
+ const configPath = resolveProjectPath(`${out}/${CONFIG_FILE}`);
1065
+ const given = existsSync(configPath) ? configValues(readFileSync(configPath, "utf8")) : new Map<string, 0 | 1>();
1066
+ const configNames = new Set([...knowledge.switches.map((row) => row.name), START_SCREEN_SWITCH, LEFTOVERS_SWITCH]);
1067
+ const loaderValues = new Map([...given].filter(([name]) => configNames.has(name)));
885
1068
  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
1069
  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, {
1070
+ const { romUse, dataOnly, laid, rendered, files, built, loader, loaderMain, missingEntry, loaderRefused } = await buildSource(knowledge, {
888
1071
  space,
889
1072
  entries,
890
1073
  header,
891
1074
  mark: GENERATED_LINE,
892
1075
  values: baseValues,
893
1076
  notExecutedMarks: true,
894
- ...(state === undefined ? {} : { state, loaderHeader }),
1077
+ leftovers: true,
1078
+ ...(state === undefined ? {} : { state, loaderHeader, loaderValues }),
895
1079
  });
896
- // config.asm keeps the value of each switch that it already has: the user sets the switches there.
897
- const configPath = resolveProjectPath(`${out}/${CONFIG_FILE}`);
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 }] : [])];
1080
+ // 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.
1081
+ const configured = [...laid.switches, ...(laid.startScreen ? [{ name: START_SCREEN_SWITCH, default: 1 }] : []), ...(laid.leftovers.length > 0 ? [{ name: LEFTOVERS_SWITCH, default: 0 }] : [])];
901
1082
  const kept = new Map(configured.flatMap((row) => (given.has(row.name) ? [[row.name, given.get(row.name)!] as const] : [])));
902
1083
  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
1084
  const removed = removeOldFiles(out, new Set(files.map((file) => file.name)), loaderWanted).map((name) => `${out}/${name}`);
@@ -950,6 +1131,12 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
950
1131
  notExecuted: { instructions: rendered.notExecuted.instructions, ...listed(rendered.notExecuted.ranges, max, showRange, `${out}/${NOT_EXECUTED_FILE}`) },
951
1132
  }),
952
1133
  ...(laid.unusedModules.length === 0 ? {} : { unusedModules: laid.unusedModules.map((module) => ({ start: formatC64Address(module.start), file: module.file })) }),
1134
+ // The bytes that nothing uses: in leftover files, which the default build and the loader leave out.
1135
+ ...(laid.leftovers.length === 0
1136
+ ? knowledge.coverage === undefined && space === DEFAULT_SPACE
1137
+ ? { 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." } }
1138
+ : {}
1139
+ : { 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
1140
  ...(rendered.expressions.length === 0 && rendered.operandsAsNumbers.length === 0 ? {} : { operandExpressions: rendered.expressions.length }),
954
1141
  ...(rendered.operandsAsNumbers.length === 0
955
1142
  ? {}
@@ -993,9 +1180,10 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
993
1180
  if (switches.length > 0) output.switches = switches;
994
1181
  // The default build: the patches of each switch whose default is not its base value are in, and nothing else changes.
995
1182
  let defaultFailed = false;
996
- if (laid.switches.length > 0) {
1183
+ if (laid.switches.length > 0 || laid.leftovers.length > 0) {
997
1184
  const changed = laid.switches.filter((row) => row.default !== row.base);
998
- const ranges = changed.flatMap((row) => withPatches.get(row.name) ?? []);
1185
+ // The default build also leaves out the leftovers.
1186
+ const ranges = [...changed.flatMap((row) => withPatches.get(row.name) ?? []), ...laid.leftovers];
999
1187
  const built = await checkBuild(withValues(files, laid, new Map()), ranges, baseBuild);
1000
1188
  output.default = { in: changed.map((row) => row.name), ...built };
1001
1189
  defaultFailed = built.result !== "fits";
@@ -1007,25 +1195,36 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
1007
1195
  const releasesFailed = releases.some((item) => item.result !== "identical" && (item.base || item.result !== "layout differs"));
1008
1196
  const sourceFailed = laid.patchesNotWritten.length > 0 || switches.some((item) => item.result !== "fits") || defaultFailed || releasesFailed;
1009
1197
  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 };
1198
+ if (loader === undefined || loaderMain === undefined || state === undefined) return { output, removed, failed: missingEntry !== undefined || sourceFailed };
1011
1199
 
1012
- // The entry state is the state of the base release: the loader is built and checked with it.
1013
- const loaderBuilt = await buildLoader(files, laid, loader, image, state, baseValues);
1200
+ // The loader loads the build with the values of config.asm, without the leftovers. The entry state is the state of the base release.
1201
+ const loaderBuilt = await buildLoader(files, laid, loader, loaderMain, state, loaderValues);
1014
1202
  if ("diagnostics" in loaderBuilt) return { output: { ...output, loader: notVerified({ reason: "loader.asm does not assemble.", diagnostics: loaderBuilt.diagnostics }) }, removed, failed: true };
1015
1203
  const { jump, copierSource, expected, startScreen } = loaderBuilt;
1016
1204
  const copierBuild = loaderBuilt.program;
1017
1205
  const fileByte = (address: number) => copierBuild[2 + address - (loader.packed?.start ?? 0x0801)]!;
1206
+ // A start screen of a captured stage: the show stage holds the packed program, as a cracktro holds the game.
1207
+ const stageRow = knowledge.startScreen?.stage === undefined ? undefined : knowledge.startScreen;
1018
1208
  // 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
1209
  let packed: PackedLoader | undefined;
1020
1210
  if (loader.packed !== undefined) {
1021
1211
  try {
1022
- packed = await packLoader(built.program, copierBuild, loader, localToolContext());
1212
+ packed = await packLoader(loaderMain.program, copierBuild, loader, localToolContext());
1023
1213
  } catch (error) {
1024
1214
  if (!isRefusal(error)) throw error;
1025
1215
  return { output: { ...output, loader: notVerified({ reason: `loader.asm has the packed form, and the pack with Exomizer failed. ${error.message}` }) }, removed, failed: true };
1026
1216
  }
1027
1217
  }
1028
- const program = packed?.program ?? copierBuild;
1218
+ let stage: BuiltStage | undefined;
1219
+ if (stageRow !== undefined) {
1220
+ try {
1221
+ stage = await buildStage(files, laid, packed!, stageRow, loaderValues, loaderHeader, GENERATED_LINE);
1222
+ } catch (error) {
1223
+ if (!isRefusal(error)) throw error;
1224
+ return { output: { ...output, loader: notVerified({ reason: `The show stage of the start screen from ${stageRow.stage} cannot be built. ${error.message}` }) }, removed, failed: true };
1225
+ }
1226
+ }
1227
+ const program = stage?.program ?? packed?.program ?? copierBuild;
1029
1228
  // The check runs the new loader from a scratch file. Only a loader whose check ran goes to --out, so a check
1030
1229
  // that cannot run (no host, or a host of another release) keeps the loader.prg of an earlier run.
1031
1230
  ensureLocal(projectRoot());
@@ -1033,11 +1232,19 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
1033
1232
  mkdirSync(resolveProjectPath(scratch), { recursive: true });
1034
1233
  const checkPath = `${scratch}/loader.prg`;
1035
1234
  writeFileSync(resolveProjectPath(checkPath), program);
1036
- // The unpack runs before the copier.
1037
- const copierFrames = packed === undefined ? RUN_LIMIT_FRAMES : packed.cycles === undefined ? LOADER_FRAMES : RUN_LIMIT_FRAMES + Math.ceil(packed.cycles / PAL_FRAME_CYCLES);
1235
+ // The unpack runs before the copier, or before the show stage, which then starts the loader.
1236
+ const unpackFrames = (cycles: number | undefined) => (cycles === undefined ? LOADER_FRAMES : RUN_LIMIT_FRAMES + Math.ceil(cycles / PAL_FRAME_CYCLES));
1237
+ const copierFrames = packed === undefined ? RUN_LIMIT_FRAMES : unpackFrames(packed.cycles);
1238
+ // The check compares the bytes of the screen of the stage: a routine of the stage can change its other bytes.
1239
+ const stageByte = (address: number) => {
1240
+ const part = stage!.parts.find((item) => address >= item.start && address < item.start + item.body.length)!;
1241
+ return part.body[address - part.start]!;
1242
+ };
1243
+ 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)) }));
1244
+ const stageRun = stage === undefined ? {} : { stage: { name: stageRow!.stage!, wait: stage.wait, continue: stage.continue, screen: stage.screen, parts: screenParts, ...(stage.colourRam === undefined ? {} : { colourRam: stage.colourRam }), frames: unpackFrames(stage.packed.cycles) + LOADER_FRAMES } };
1038
1245
  let ran: LoaderRun;
1039
1246
  try {
1040
- ran = await runLoader(checkPath, program, loader, image, state, { jump, copierSource, fileByte, copierFrames, ...(startScreen === undefined ? {} : { startScreen }) }, expected);
1247
+ ran = await runLoader(checkPath, program, loader, state, { jump, copierSource, fileByte, copierFrames, ...(startScreen === undefined ? {} : { startScreen }), ...stageRun }, expected);
1041
1248
  } catch (error) {
1042
1249
  if (!isRefusal(error)) throw error;
1043
1250
  const what = existsSync(resolveProjectPath(loaderPath)) ? "kept the loader.prg of an earlier run" : "wrote no loader.prg";
@@ -1046,9 +1253,22 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
1046
1253
  rmSync(resolveProjectPath(scratch), { recursive: true, force: true });
1047
1254
  }
1048
1255
  written.push(writeReported(loaderPath, program, { what: "--out" }));
1256
+ 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
1257
  output.loader = {
1050
1258
  program: loaderPath,
1051
1259
  ...(packed === undefined ? {} : { packed: { packedBytes: packed.packedBytes, unpackedBytes: packed.unpackedBytes } }),
1260
+ ...(stage === undefined
1261
+ ? {}
1262
+ : {
1263
+ stage: {
1264
+ space: stageRow!.stage,
1265
+ code: formatC64Address(stage.plan.code),
1266
+ bytes: stage.parts.reduce((sum, part) => sum + part.body.length, 0),
1267
+ stash: stage.plan.stash.map((item) => ({ from: formatC64Address(item.at), to: `${formatC64Address(item.target.start)}-${formatC64Address(item.target.end)}` })),
1268
+ packedBytes: stage.packed.packedBytes,
1269
+ unpackedBytes: stage.packed.unpackedBytes,
1270
+ },
1271
+ }),
1052
1272
  copies: loader.copies.map((copy) => ({ what: copy.what, to: `${formatC64Address(copy.target.start)}-${formatC64Address(copy.target.end)}` })),
1053
1273
  copier: formatC64Address(loader.copier),
1054
1274
  stackByte: formatC64Address(loader.stackByte),
@@ -1095,6 +1315,61 @@ function effectiveRegions(regions: SourceKnowledge["regions"]): SourceKnowledge[
1095
1315
  return [...semantic, ...regions.filter((region) => !isSemantic(region.origin)).flatMap((region) => clipped(region, holes))].sort((a, b) => a.start - b.start);
1096
1316
  }
1097
1317
 
1318
+ /** The names and the four-digit hex addresses that the code of a patch has: a switch can go to them, so they stay. */
1319
+ function patchTargets(code: string, addressOf: ReadonlyMap<string, number>): number[] {
1320
+ const words = code.replace(/;.*$/gm, "").match(/\$[0-9a-fA-F]{4}\b|[A-Za-z_][A-Za-z0-9_]*/g) ?? [];
1321
+ return words.flatMap((word) => (word.startsWith("$") ? [Number.parseInt(word.slice(1), 16)] : addressOf.has(word) ? [addressOf.get(word)!] : []));
1322
+ }
1323
+
1324
+ /**
1325
+ * The free ranges of a program: code that no run executed and that nothing
1326
+ * reaches, and data that no run touched and that nothing names (planDrops).
1327
+ * The export makes them $00; generate makes them the leftovers. `memory` and
1328
+ * `instructions` are of the build that the ranges are free in.
1329
+ */
1330
+ function freeRanges(knowledge: SourceKnowledge, memory: Uint8Array, instructions: ReadonlyMap<number, number>, ranges: { changed: readonly AddressRange[]; keep: readonly AddressRange[]; drop: readonly AddressRange[] }) {
1331
+ const image = knowledge.program;
1332
+ const addressOf = new Map(knowledge.symbols.map((symbol) => [symbol.name, symbol.address]));
1333
+ const operandTargets = new Map<number, number[]>();
1334
+ for (const operand of knowledge.operands) {
1335
+ const names = operand.symbol !== undefined ? [operand.symbol] : identifiers(operand.expression ?? "");
1336
+ const targets = names.flatMap((item) => (addressOf.has(item) ? [(addressOf.get(item)! + (operand.symbol !== undefined ? operand.offset : 0)) & 0xffff] : []));
1337
+ if (targets.length > 0) operandTargets.set(operand.address, targets);
1338
+ }
1339
+ const entry = image.entry ?? basicEntry(image);
1340
+ return planDrops({
1341
+ segments: image.segments,
1342
+ memory,
1343
+ ...(entry === undefined ? {} : { entry }),
1344
+ instructions,
1345
+ ...(knowledge.coverage === undefined ? {} : { coverage: knowledge.coverage }),
1346
+ regions: effectiveRegions(knowledge.regions),
1347
+ references: knowledge.references,
1348
+ operandTargets,
1349
+ changed: [...ranges.changed],
1350
+ keep: [...ranges.keep],
1351
+ drop: [...ranges.drop],
1352
+ routines: knowledge.symbols.filter((symbol) => symbol.kind === "routine"),
1353
+ });
1354
+ }
1355
+
1356
+ /**
1357
+ * The leftovers of generate: the free ranges of the program as it is. The
1358
+ * start screen in the program, the patches, the macro uses, what the code of a
1359
+ * patch names and the ranges of `keep` stay, so each switch builds with
1360
+ * LEFTOVERS = 0.
1361
+ */
1362
+ function leftoversOf(knowledge: SourceKnowledge, instructions: ReadonlyMap<number, number>, kept: readonly AddressRange[] = []): AddressRange[] {
1363
+ const image = knowledge.program;
1364
+ const inImage = (range: AddressRange) => image.segments.some((segment) => range.start >= segment.start && range.end <= segment.end);
1365
+ const addressOf = new Map(knowledge.symbols.map((symbol) => [symbol.name, symbol.address]));
1366
+ const screenParts = knowledge.startScreen === undefined || knowledge.startScreen.stage !== undefined ? [] : startScreenRanges(knowledge.startScreen).map((part) => part.range);
1367
+ const named = knowledge.patches.flatMap((patch) => patchTargets(patch.code, addressOf)).map((address) => ({ start: address, end: address }));
1368
+ const keep = [...screenParts, ...kept, ...knowledge.macroUses, ...named].map((range) => ({ start: range.start, end: range.end })).filter(inImage);
1369
+ const changed = knowledge.patches.map((patch) => ({ start: patch.start, end: patch.end })).filter(inImage);
1370
+ return freeRanges(knowledge, image.memory, instructions, { changed, keep, drop: [] }).free.map((range) => ({ start: range.start, end: range.end }));
1371
+ }
1372
+
1098
1373
  /** 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
1374
  function filesIn(root: string, skip: (path: string) => boolean, folder = ""): Array<{ path: string; bytes: Buffer }> {
1100
1375
  const found: Array<{ path: string; bytes: Buffer }> = [];
@@ -1134,7 +1409,10 @@ async function exportProject(call: Call): Promise<Record<string, unknown>> {
1134
1409
  db?.close();
1135
1410
  }
1136
1411
  })();
1137
- const knowledge = readKnowledge(DEFAULT_SPACE);
1412
+ const read = readKnowledge(DEFAULT_SPACE);
1413
+ // The export has only the space c64: a start screen of a captured stage stays out with that space.
1414
+ const stageLeftOut = read.startScreen?.stage;
1415
+ const knowledge = stageLeftOut === undefined ? read : { ...read, startScreen: undefined };
1138
1416
  const image = knowledge.program;
1139
1417
  // The VIC-II reads the start screen, and the coverage does not show those reads: it stays.
1140
1418
  const screenParts = knowledge.startScreen === undefined ? [] : startScreenRanges(knowledge.startScreen).map((part) => part.range);
@@ -1179,29 +1457,8 @@ async function exportProject(call: Call): Promise<Record<string, unknown>> {
1179
1457
  const decoded = await decode(bakedImage, knowledge, [], knowledge.coverage);
1180
1458
 
1181
1459
  // 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
1460
  const regions = effectiveRegions(knowledge.regions);
1190
- const entry = image.entry ?? basicEntry(image);
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
- });
1461
+ const plan = freeRanges(knowledge, memory, decoded.instructions, { changed, keep, drop });
1205
1462
  const free = plan.free;
1206
1463
  const inFree = (address: number) => free.some((range) => address >= range.start && address <= range.end);
1207
1464
  const overlapsAny = (start: number, end: number, ranges: readonly AddressRange[]) => ranges.some((range) => start <= range.end && range.start <= end);
@@ -1265,7 +1522,7 @@ async function exportProject(call: Call): Promise<Record<string, unknown>> {
1265
1522
  if (state !== undefined) {
1266
1523
  if (exported.loader === undefined) return { result: "FAIL", stage: "loader", reason: exported.loaderRefused ?? "The loader could not be planned." };
1267
1524
  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, derived.program, state, new Map());
1525
+ const loaderBuilt = await buildLoader(exported.files, exported.laid, exported.loader, exported.loaderMain!, state, new Map());
1269
1526
  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
1527
  baseline = { program: loaderBuilt.program, symbols: loaderBuilt.symbols, entryFile: "loader.asm" };
1271
1528
  loaderOutput = {
@@ -1343,6 +1600,7 @@ async function exportProject(call: Call): Promise<Record<string, unknown>> {
1343
1600
  knowledge: kept,
1344
1601
  tests: { written: tests.map((test) => test.file), leftOut: listed(testsLeftOut, max, (item) => item) },
1345
1602
  ...(spacesLeftOut.length === 0 ? {} : { spacesLeftOut }),
1603
+ ...(stageLeftOut === undefined ? {} : { startScreenLeftOut: `The start screen is of the captured stage in ${stageLeftOut}, and the export has only the space c64.` }),
1346
1604
  ...(exported.rendered.operandsAsNumbers.length === 0 ? {} : { operandsAsNumbers: listed(exported.rendered.operandsAsNumbers, max, (item) => ({ address: formatC64Address(item.address), expression: item.expression, reason: item.reason })) }),
1347
1605
  ...(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
1606
  };
@@ -1398,6 +1656,7 @@ function generateReply(call: Call, body: Record<string, unknown>): Reply {
1398
1656
  again = true;
1399
1657
  }
1400
1658
  if ((body.loader as { verified?: boolean } | undefined)?.verified === false) steps.push("The loader is not verified. Read loader.reason, loader.differences and loader.stop.");
1659
+ 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
1660
  if (body.dataOnly !== undefined) {
1402
1661
  steps.push("The source has only data. If the space has code, give --entry, or record a code region in the project knowledge.");
1403
1662
  again = true;
@@ -1452,8 +1711,8 @@ await runScript({
1452
1711
  options: {
1453
1712
  out: { ...OPTIONS.out, output: "folder", value: "<dir>", help: "the folder for the source files, relative to the project folder", required: true },
1454
1713
  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. The coverage and --loader are for c64 only" },
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 removes loader.prg" },
1714
+ space: { ...OPTIONS.space, help: "the knowledge space of the program: c64 (the default), drive8, loading, or bank0 to bank255. --loader is for c64 only" },
1715
+ 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
1716
  "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
1717
  "max-listed": OPTIONS["max-listed"],
1459
1718
  },