@henols/c64-re-tools 2.5.0 → 2.6.0-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,10 @@ 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 { planStage, STAGE_CODE_END, STAGE_FILE, STAGE_START, stageParts, stageText, type StageInput, type StagePart, type StagePlan } from "./lib/stage.ts";
62
66
  import { freeName, planDrops, readmeText, rewriteTest } from "./lib/export.ts";
63
67
  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
68
 
@@ -90,8 +94,8 @@ function readKnowledge(space: Space, analyzerNames = false) {
90
94
  return {
91
95
  revision: currentRevision(db),
92
96
  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,
97
+ // The coverage of the space: a run of the C64, or of a captured stage that coverage put into that space.
98
+ coverage: programCoverage(db, space)?.map,
95
99
  symbols: analyzerNames ? withAnalyzerNames(symbols, second) : symbols,
96
100
  // Analyzer routines are entry points for the decode, also without --analyzer-names.
97
101
  routines: [...symbols, ...second].filter((symbol) => symbol.kind === "routine").map((symbol) => symbol.address),
@@ -429,7 +433,7 @@ function compareBuilds(built: Assembled, ranges: readonly AddressRange[], base:
429
433
  * from config.asm: a define of a switch is an error, because config.asm also
430
434
  * gives it a value. A switch without a value has its default.
431
435
  */
432
- function withValues(files: Array<{ name: string; text: string }>, laid: Pick<Layout, "switches" | "patches" | "startScreen">, values: ReadonlyMap<string, number>): Array<{ name: string; text: string }> {
436
+ 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
437
  return files.map((file) => (file.name === CONFIG_FILE ? { ...file, text: configText(laid, values) } : file));
434
438
  }
435
439
 
@@ -524,8 +528,8 @@ interface LoaderRun {
524
528
  verified: boolean;
525
529
  differences: string[];
526
530
  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 };
531
+ /** 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. */
532
+ startScreen?: { shown: boolean; waits: boolean; wait: string; continue: string; stage?: string };
529
533
  }
530
534
 
531
535
  /** The frames that the check of the loader lets the start screen wait without a key. */
@@ -539,12 +543,14 @@ interface LoaderRunPlan {
539
543
  jump: number;
540
544
  /** The wait of the start screen and the code after it, when the loader has a start screen. */
541
545
  startScreen?: { wait: number; continue: number };
546
+ /** 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. */
547
+ stage?: { name: string; wait: number; continue: number; screen: StartScreenPlan; parts: StagePart[]; frames: number };
542
548
  copierSource: number;
543
549
  fileByte: (address: number) => number;
544
550
  copierFrames: number;
545
551
  }
546
552
 
547
- async function runLoader(path: string, program: Buffer, plan: LoaderPlan, image: ProgramImage, state: EntryState, run: LoaderRunPlan, expected: (address: number) => number): Promise<LoaderRun> {
553
+ async function runLoader(path: string, program: Buffer, plan: LoaderPlan, state: EntryState, run: LoaderRunPlan, expected: (address: number) => number): Promise<LoaderRun> {
548
554
  const { jump, copierSource, fileByte } = run;
549
555
  const client = await ViceSessionClient.open({ videoStandard: "pal" });
550
556
  try {
@@ -552,37 +558,54 @@ async function runLoader(path: string, program: Buffer, plan: LoaderPlan, image:
552
558
  if (!(await autostartLoaded(client, path, program))) return { verified: false, differences: ["The loader was not in memory after autostart."] };
553
559
  await client.keyboard(textToPetscii("RUN\n"));
554
560
  // 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> => {
561
+ // Before the show stage moves on, the copier is not in place yet: then the stop has no cause from it.
562
+ const stopped = async (pc: number, copied: boolean, what: string, loaderRan = true): Promise<LoaderRun> => {
556
563
  const ram = await readRam(client, 0x0000, 0x10000);
557
564
  const port = Buffer.from((await client.memoryRead({ address: 0x0001, size: 1, space: "c64", view: "cpu" })).data, "hex")[0]!;
558
565
  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);
566
+ const cause = loaderRan ? stopCause(ram, plan, copierSource, fileByte, copied, expected) : undefined;
560
567
  const port01 = `$${port.toString(16).padStart(2, "0")}`;
561
568
  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
569
  };
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
570
  // The start screen waits for a key or a fire button. The emulator cannot press a key of the keyboard matrix
566
571
  // on each VICE, so the check lets it wait, then sets the PC to the code after the wait.
567
572
  let screen: LoaderRun["startScreen"];
568
573
  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 });
574
+ const showScreen = async (at: { wait: number; continue: number }, wanted: StartScreenPlan, frames: number, copied: boolean, parts: readonly StagePart[] = []): Promise<LoaderRun | undefined> => {
575
+ const labels = { wait: formatC64Address(at.wait), continue: formatC64Address(at.continue) };
576
+ const atWait = await client.runUntil({ target: { kind: "address", address: at.wait, space: "c64" }, timeoutFrames: frames });
577
+ if (!atWait.reached) return await stopped(atWait.pc, copied, `its start screen at ${labels.wait}`, parts.length === 0);
578
+ const held = await client.runUntil({ target: { kind: "address", address: at.continue, space: "c64" }, timeoutFrames: START_SCREEN_FRAMES });
574
579
  const vic = Buffer.from((await client.ioRead(0xd000, 0x2f)).data, "hex");
575
580
  const bank = 3 - (Buffer.from((await client.ioRead(0xdd00, 1)).data, "hex")[0]! & 0x03);
576
- const wanted = plan.startScreen;
581
+ const before = screenDifferences.length;
577
582
  const shown: Array<[number, number]> = [[0x11, wanted.d011], [0x15, 0], [0x16, wanted.d016], [0x18, wanted.d018], [0x20, wanted.border], [0x21, wanted.background]];
578
583
  for (const [register, value] of shown) {
579
584
  const mask = VIC_DISPLAY_REGISTERS.find((item) => item.register === register)!.mask;
580
585
  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
586
  }
582
587
  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 };
588
+ // The bytes of the screen of a stage: the first wrong byte of each part.
589
+ for (const part of parts) {
590
+ const ram = await readRam(client, part.start, part.body.length);
591
+ const wrong = part.body.findIndex((byte, offset) => ram[offset] !== byte);
592
+ 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")}`);
593
+ }
594
+ screen = { shown: screenDifferences.length === before, waits: !held.reached, ...labels, ...(run.stage === undefined ? {} : { stage: run.stage.name }) };
584
595
  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 });
596
+ if (!held.reached) await client.registersSet("c64", { pc: at.continue });
597
+ return undefined;
598
+ };
599
+ // The show stage of a captured stage runs before the loader.
600
+ if (run.stage !== undefined) {
601
+ const stop = await showScreen(run.stage, run.stage.screen, run.stage.frames, false, run.stage.parts);
602
+ if (stop !== undefined) return stop;
603
+ }
604
+ const copier = await client.runUntil({ target: { kind: "address", address: plan.copier, space: "c64" }, timeoutFrames: run.copierFrames });
605
+ if (!copier.reached) return await stopped(copier.pc, false, `its copier at ${formatC64Address(plan.copier)}`);
606
+ if (run.startScreen !== undefined && plan.startScreen !== undefined) {
607
+ const stop = await showScreen(run.startScreen, plan.startScreen, LOADER_FRAMES, true);
608
+ if (stop !== undefined) return stop;
586
609
  }
587
610
  const atJump = await client.runUntil({ target: { kind: "address", address: jump, space: "c64" }, timeoutFrames: LOADER_FRAMES });
588
611
  if (!atJump.reached) return await stopped(atJump.pc, true, `its jump to the entry at ${formatC64Address(jump)}`);
@@ -595,8 +618,9 @@ async function runLoader(path: string, program: Buffer, plan: LoaderPlan, image:
595
618
  const differences: string[] = [];
596
619
  const byte = (value: number) => `$${value.toString(16).padStart(2, "0")}`;
597
620
  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));
621
+ // The leftovers are not loaded: only the loaded ranges have the bytes of the build.
622
+ for (const part of plan.loaded) {
623
+ for (let address = Math.max(part.start, 2); address <= part.end; address++) differ(formatC64Address(address), memory[address]!, expected(address));
600
624
  }
601
625
  for (let address = 2; address < 0x400; address++) if (address !== plan.stackByte) differ(formatC64Address(address), memory[address]!, state.pages[address]!);
602
626
  differ("$00", port[0]!, state.port[0]);
@@ -667,7 +691,7 @@ function sourceMapText(rendered: Rendered, space: string, revision: string | nul
667
691
  const LOADER_CHECK_DIRECTORY = "loader-check";
668
692
 
669
693
  /** 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]);
694
+ const LOADER_FILES: ReadonlySet<string> = new Set(["loader.asm", "loader.prg", START_SCREEN_FILE, STAGE_FILE]);
671
695
 
672
696
  /** The start of the line of loader.asm that gives the knowledge revision of the loader. */
673
697
  const LOADER_REVISION = "Loader generated by c64-source from knowledge revision ";
@@ -736,6 +760,10 @@ interface SourceOptions {
736
760
  loaderHeader?: string[];
737
761
  /** The source of an export: no config.asm, so START_SCREEN has the default of start_screen.asm. */
738
762
  exported?: boolean;
763
+ /** Put the free ranges of the program into leftover files, which only LEFTOVERS = 1 builds. */
764
+ leftovers?: boolean;
765
+ /** The switch values of the build that the loader loads. The default is `values`. */
766
+ loaderValues?: ReadonlyMap<string, number>;
739
767
  }
740
768
 
741
769
  /**
@@ -751,6 +779,7 @@ async function buildSource(knowledge: SourceKnowledge, options: SourceOptions) {
751
779
  const romUse = romUseOfProgram(coverage, image.state);
752
780
  const platform = platformNamesFor(romUse);
753
781
  const { instructions, dataOnly } = options.decoded ?? (await decode(image, knowledge, options.entries, coverage));
782
+ const leftovers = options.leftovers === true && !dataOnly ? leftoversOf(knowledge, instructions) : [];
754
783
  const laid = layout({
755
784
  segments: image.segments,
756
785
  byteAt: image.byteAt,
@@ -768,50 +797,23 @@ async function buildSource(knowledge: SourceKnowledge, options: SourceOptions) {
768
797
  macros: knowledge.macros,
769
798
  macroUses: knowledge.macroUses,
770
799
  startScreen: knowledge.startScreen !== undefined && options.exported !== true,
800
+ leftovers,
771
801
  ...(coverage === undefined || !options.notExecutedMarks ? {} : { coverage }),
772
802
  // The platform names are C64 names: drive code and banks get none. A ROM that the program does not use gives none.
773
803
  ...(space === DEFAULT_SPACE ? { platform, platformLeftOut: leftOutNames(platform), describe: describeAddress, decode: decodeRegister, io: IO_RAM } : {}),
774
804
  });
775
805
  const asBytes = await probe(laid);
776
806
  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
807
  // With a mark, every file starts with it.
805
808
  const { mark } = options;
806
809
  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
810
  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
811
  const numbers = new Map<number, string>();
810
812
  const asInstructions = new Map<number, string>();
811
813
  let rendered = render(laid, asBytes, header, numbers, asInstructions);
812
814
  if (laid.macroUses.size > 0) for (const [start, reason] of await probeUses(laid, rendered, image)) asInstructions.set(start, reason);
813
815
  if (asInstructions.size > 0) rendered = render(laid, asBytes, header, numbers, asInstructions);
814
- let files = marked([...rendered.files, ...loaderFiles]);
816
+ let files = marked(rendered.files);
815
817
  let built = await assembleFiles(withValues(files, laid, options.values), "main.asm");
816
818
  for (let round = 0; round < ROUNDS && (rendered.expressions.length > 0 || rendered.uses.length > 0); round++) {
817
819
  const blamed = blame(rendered, built, image, markLines);
@@ -819,22 +821,84 @@ async function buildSource(knowledge: SourceKnowledge, options: SourceOptions) {
819
821
  for (const [address, reason] of blamed.numbers) numbers.set(address, reason);
820
822
  for (const [start, reason] of blamed.uses) asInstructions.set(start, reason);
821
823
  rendered = render(laid, asBytes, header, numbers, asInstructions);
822
- files = marked([...rendered.files, ...loaderFiles]);
824
+ files = marked(rendered.files);
823
825
  built = await assembleFiles(withValues(files, laid, options.values), "main.asm");
824
826
  }
825
- return { romUse, instructions, dataOnly, laid, rendered, files, built, loader, missingEntry, loaderRefused };
827
+
828
+ let loader: LoaderPlan | undefined;
829
+ /** The build of main.asm that the loader loads: the switch values of the loader. */
830
+ let loaderMain: { program: Buffer; start: number } | undefined;
831
+ // An image without its entry has no program: the source is still written and checked, but the run fails.
832
+ const missingEntry = entryOutsideImage(image.entry, image.segments);
833
+ // A loader that cannot be planned does not stop the source: the source is written and checked, and the result says why.
834
+ const { state } = options;
835
+ let loaderRefused: string | undefined = state === undefined ? undefined : missingEntry;
836
+ if (state !== undefined && missingEntry === undefined) {
837
+ const main = options.loaderValues === undefined ? built : await assembleFiles(withValues(files, laid, options.loaderValues), "main.asm");
838
+ if (main.program === undefined) loaderRefused = "The source does not assemble with the switch values of the loader.";
839
+ else {
840
+ const program = main.program;
841
+ const start = main.start!;
842
+ loaderMain = { program, start };
843
+ try {
844
+ const entryName = laid.names.get(image.entry!);
845
+ loader = planLoader({
846
+ segments: loadedParts(laid, image.segments),
847
+ byteAt: (address) => program[2 + address - start]!,
848
+ state,
849
+ entry: image.entry!,
850
+ ...(entryName === undefined ? {} : { entryName }),
851
+ switches: hasSwitchFile(laid),
852
+ config: hasConfigFile(laid),
853
+ macros: laid.macros.length > 0,
854
+ header: options.loaderHeader ?? [],
855
+ // A start screen of a stage shows before the loader, in the show stage, while the program is still packed: the copier has none.
856
+ ...(knowledge.startScreen === undefined || knowledge.startScreen.stage !== undefined ? {} : { startScreen: knowledge.startScreen }),
857
+ ...(knowledge.startScreen?.stage === undefined ? {} : { packed: true }),
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. A layout
831
- * other than the plan is a defect of the script.
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
- image: ProgramImage,
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) => (image.segments.some((segment) => address >= segment.start && address <= segment.end) ? image.byteAt(address) : state.pages[address]!);
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,109 @@ 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, program: PackedLoader, row: StartScreenRow, values: ReadonlyMap<string, number>, header: string[], mark: string): Promise<BuiltStage> {
993
+ const stage = await stageBytes(row);
994
+ // The packed program, as RUN would start it: its unpacker unpacks it over the start screen after the wait.
995
+ const inner: StagePart[] = [{ start: 0x0801, body: program.program.subarray(2) }];
996
+ const screen = startScreenPlan(row);
997
+ const input: StageInput = {
998
+ inner,
999
+ innerStart: 0x080d,
1000
+ innerPort: 0x37,
1001
+ stage,
1002
+ row,
1003
+ plan: screen,
1004
+ settings: hasSwitchFile(laid) ? ['!source "switches.asm"'] : hasConfigFile(laid) ? ['!source "config.asm"'] : [],
1005
+ header,
1006
+ codeSize: 0,
1007
+ };
1008
+ const support = [...withValues(files, laid, values).filter((file) => file.name === CONFIG_FILE || file.name === "switches.asm"), { name: START_SCREEN_FILE, text: START_SCREEN_CODE }];
1009
+ const assembleStage = async (text: string) => {
1010
+ const built = await assembleFiles([...support, { name: STAGE_FILE, text }], STAGE_FILE);
1011
+ 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.`);
1012
+ const labels = new Map((built.symbols ?? []).map((symbol) => [symbol.name, symbol.kind === "address" ? symbol.address : symbol.value]));
1013
+ const label = (name: string) => {
1014
+ const value = labels.get(name);
1015
+ if (value === undefined) throw new WireFailure("operation-failed", `The build of ${STAGE_FILE} has no ${name} label. This is a defect of the script.`);
1016
+ return value;
1017
+ };
1018
+ return { program: built.program, label };
1019
+ };
1020
+ // The size of the show code does not depend on its address: one build without a stash gives it.
1021
+ const probe = await assembleStage(stageText(input, 0x1000, []));
1022
+ input.codeSize = probe.label(STAGE_CODE_END) - probe.label(STAGE_START) - 2;
1023
+ const plan = planStage(input);
1024
+ const built = await assembleStage(plan.text);
1025
+ 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.`);
1026
+ const parts = stageParts(input, plan, built.program, built.label);
1027
+ const packed = await packParts(parts, plan.code, 0x37, "the loader and the start screen of the stage", "the show stage", localToolContext());
1028
+ const end = 0x0801 + packed.program.length - 3;
1029
+ 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.`);
1030
+ 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 };
1031
+ }
1032
+
866
1033
  /** The first line of each file that generate writes. */
867
1034
  const GENERATED_LINE = `${GENERATED_MARK}. Do not edit: change the knowledge and generate again.`;
868
1035
 
@@ -880,24 +1047,27 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
880
1047
  }
881
1048
  // Read the entry state before the long steps, so a bad state stops the run at once.
882
1049
  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]));
1050
+ // Every build that is compared with the program is the build of the base release: each switch at its base value, with the leftovers.
1051
+ const baseValues = new Map<string, number>([...knowledge.switches.map((row) => [row.name, row.base] as const), [LEFTOVERS_SWITCH, 1]]);
1052
+ // config.asm keeps the value of each switch that it already has: the user sets the switches there. The loader loads that build.
1053
+ const configPath = resolveProjectPath(`${out}/${CONFIG_FILE}`);
1054
+ const given = existsSync(configPath) ? configValues(readFileSync(configPath, "utf8")) : new Map<string, 0 | 1>();
1055
+ const configNames = new Set([...knowledge.switches.map((row) => row.name), START_SCREEN_SWITCH, LEFTOVERS_SWITCH]);
1056
+ const loaderValues = new Map([...given].filter(([name]) => configNames.has(name)));
885
1057
  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
1058
  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, {
1059
+ const { romUse, dataOnly, laid, rendered, files, built, loader, loaderMain, missingEntry, loaderRefused } = await buildSource(knowledge, {
888
1060
  space,
889
1061
  entries,
890
1062
  header,
891
1063
  mark: GENERATED_LINE,
892
1064
  values: baseValues,
893
1065
  notExecutedMarks: true,
894
- ...(state === undefined ? {} : { state, loaderHeader }),
1066
+ leftovers: true,
1067
+ ...(state === undefined ? {} : { state, loaderHeader, loaderValues }),
895
1068
  });
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 }] : [])];
1069
+ // 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.
1070
+ const configured = [...laid.switches, ...(laid.startScreen ? [{ name: START_SCREEN_SWITCH, default: 1 }] : []), ...(laid.leftovers.length > 0 ? [{ name: LEFTOVERS_SWITCH, default: 0 }] : [])];
901
1071
  const kept = new Map(configured.flatMap((row) => (given.has(row.name) ? [[row.name, given.get(row.name)!] as const] : [])));
902
1072
  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
1073
  const removed = removeOldFiles(out, new Set(files.map((file) => file.name)), loaderWanted).map((name) => `${out}/${name}`);
@@ -950,6 +1120,12 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
950
1120
  notExecuted: { instructions: rendered.notExecuted.instructions, ...listed(rendered.notExecuted.ranges, max, showRange, `${out}/${NOT_EXECUTED_FILE}`) },
951
1121
  }),
952
1122
  ...(laid.unusedModules.length === 0 ? {} : { unusedModules: laid.unusedModules.map((module) => ({ start: formatC64Address(module.start), file: module.file })) }),
1123
+ // The bytes that nothing uses: in leftover files, which the default build and the loader leave out.
1124
+ ...(laid.leftovers.length === 0
1125
+ ? knowledge.coverage === undefined && space === DEFAULT_SPACE
1126
+ ? { 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." } }
1127
+ : {}
1128
+ : { 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
1129
  ...(rendered.expressions.length === 0 && rendered.operandsAsNumbers.length === 0 ? {} : { operandExpressions: rendered.expressions.length }),
954
1130
  ...(rendered.operandsAsNumbers.length === 0
955
1131
  ? {}
@@ -993,9 +1169,10 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
993
1169
  if (switches.length > 0) output.switches = switches;
994
1170
  // The default build: the patches of each switch whose default is not its base value are in, and nothing else changes.
995
1171
  let defaultFailed = false;
996
- if (laid.switches.length > 0) {
1172
+ if (laid.switches.length > 0 || laid.leftovers.length > 0) {
997
1173
  const changed = laid.switches.filter((row) => row.default !== row.base);
998
- const ranges = changed.flatMap((row) => withPatches.get(row.name) ?? []);
1174
+ // The default build also leaves out the leftovers.
1175
+ const ranges = [...changed.flatMap((row) => withPatches.get(row.name) ?? []), ...laid.leftovers];
999
1176
  const built = await checkBuild(withValues(files, laid, new Map()), ranges, baseBuild);
1000
1177
  output.default = { in: changed.map((row) => row.name), ...built };
1001
1178
  defaultFailed = built.result !== "fits";
@@ -1007,25 +1184,36 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
1007
1184
  const releasesFailed = releases.some((item) => item.result !== "identical" && (item.base || item.result !== "layout differs"));
1008
1185
  const sourceFailed = laid.patchesNotWritten.length > 0 || switches.some((item) => item.result !== "fits") || defaultFailed || releasesFailed;
1009
1186
  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 };
1187
+ if (loader === undefined || loaderMain === undefined || state === undefined) return { output, removed, failed: missingEntry !== undefined || sourceFailed };
1011
1188
 
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);
1189
+ // The loader loads the build with the values of config.asm, without the leftovers. The entry state is the state of the base release.
1190
+ const loaderBuilt = await buildLoader(files, laid, loader, loaderMain, state, loaderValues);
1014
1191
  if ("diagnostics" in loaderBuilt) return { output: { ...output, loader: notVerified({ reason: "loader.asm does not assemble.", diagnostics: loaderBuilt.diagnostics }) }, removed, failed: true };
1015
1192
  const { jump, copierSource, expected, startScreen } = loaderBuilt;
1016
1193
  const copierBuild = loaderBuilt.program;
1017
1194
  const fileByte = (address: number) => copierBuild[2 + address - (loader.packed?.start ?? 0x0801)]!;
1195
+ // A start screen of a captured stage: the show stage holds the packed program, as a cracktro holds the game.
1196
+ const stageRow = knowledge.startScreen?.stage === undefined ? undefined : knowledge.startScreen;
1018
1197
  // 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
1198
  let packed: PackedLoader | undefined;
1020
1199
  if (loader.packed !== undefined) {
1021
1200
  try {
1022
- packed = await packLoader(built.program, copierBuild, loader, localToolContext());
1201
+ packed = await packLoader(loaderMain.program, copierBuild, loader, localToolContext());
1023
1202
  } catch (error) {
1024
1203
  if (!isRefusal(error)) throw error;
1025
1204
  return { output: { ...output, loader: notVerified({ reason: `loader.asm has the packed form, and the pack with Exomizer failed. ${error.message}` }) }, removed, failed: true };
1026
1205
  }
1027
1206
  }
1028
- const program = packed?.program ?? copierBuild;
1207
+ let stage: BuiltStage | undefined;
1208
+ if (stageRow !== undefined) {
1209
+ try {
1210
+ stage = await buildStage(files, laid, packed!, stageRow, loaderValues, loaderHeader, GENERATED_LINE);
1211
+ } catch (error) {
1212
+ if (!isRefusal(error)) throw error;
1213
+ return { output: { ...output, loader: notVerified({ reason: `The show stage of the start screen from ${stageRow.stage} cannot be built. ${error.message}` }) }, removed, failed: true };
1214
+ }
1215
+ }
1216
+ const program = stage?.program ?? packed?.program ?? copierBuild;
1029
1217
  // The check runs the new loader from a scratch file. Only a loader whose check ran goes to --out, so a check
1030
1218
  // that cannot run (no host, or a host of another release) keeps the loader.prg of an earlier run.
1031
1219
  ensureLocal(projectRoot());
@@ -1033,11 +1221,19 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
1033
1221
  mkdirSync(resolveProjectPath(scratch), { recursive: true });
1034
1222
  const checkPath = `${scratch}/loader.prg`;
1035
1223
  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);
1224
+ // The unpack runs before the copier, or before the show stage, which then starts the loader.
1225
+ const unpackFrames = (cycles: number | undefined) => (cycles === undefined ? LOADER_FRAMES : RUN_LIMIT_FRAMES + Math.ceil(cycles / PAL_FRAME_CYCLES));
1226
+ const copierFrames = packed === undefined ? RUN_LIMIT_FRAMES : unpackFrames(packed.cycles);
1227
+ // The check compares the bytes of the screen of the stage: a routine of the stage can change its other bytes.
1228
+ const stageByte = (address: number) => {
1229
+ const part = stage!.parts.find((item) => address >= item.start && address < item.start + item.body.length)!;
1230
+ return part.body[address - part.start]!;
1231
+ };
1232
+ 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)) }));
1233
+ 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
1234
  let ran: LoaderRun;
1039
1235
  try {
1040
- ran = await runLoader(checkPath, program, loader, image, state, { jump, copierSource, fileByte, copierFrames, ...(startScreen === undefined ? {} : { startScreen }) }, expected);
1236
+ ran = await runLoader(checkPath, program, loader, state, { jump, copierSource, fileByte, copierFrames, ...(startScreen === undefined ? {} : { startScreen }), ...stageRun }, expected);
1041
1237
  } catch (error) {
1042
1238
  if (!isRefusal(error)) throw error;
1043
1239
  const what = existsSync(resolveProjectPath(loaderPath)) ? "kept the loader.prg of an earlier run" : "wrote no loader.prg";
@@ -1046,9 +1242,22 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
1046
1242
  rmSync(resolveProjectPath(scratch), { recursive: true, force: true });
1047
1243
  }
1048
1244
  written.push(writeReported(loaderPath, program, { what: "--out" }));
1245
+ 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
1246
  output.loader = {
1050
1247
  program: loaderPath,
1051
1248
  ...(packed === undefined ? {} : { packed: { packedBytes: packed.packedBytes, unpackedBytes: packed.unpackedBytes } }),
1249
+ ...(stage === undefined
1250
+ ? {}
1251
+ : {
1252
+ stage: {
1253
+ space: stageRow!.stage,
1254
+ code: formatC64Address(stage.plan.code),
1255
+ bytes: stage.parts.reduce((sum, part) => sum + part.body.length, 0),
1256
+ stash: stage.plan.stash.map((item) => ({ from: formatC64Address(item.at), to: `${formatC64Address(item.target.start)}-${formatC64Address(item.target.end)}` })),
1257
+ packedBytes: stage.packed.packedBytes,
1258
+ unpackedBytes: stage.packed.unpackedBytes,
1259
+ },
1260
+ }),
1052
1261
  copies: loader.copies.map((copy) => ({ what: copy.what, to: `${formatC64Address(copy.target.start)}-${formatC64Address(copy.target.end)}` })),
1053
1262
  copier: formatC64Address(loader.copier),
1054
1263
  stackByte: formatC64Address(loader.stackByte),
@@ -1095,6 +1304,61 @@ function effectiveRegions(regions: SourceKnowledge["regions"]): SourceKnowledge[
1095
1304
  return [...semantic, ...regions.filter((region) => !isSemantic(region.origin)).flatMap((region) => clipped(region, holes))].sort((a, b) => a.start - b.start);
1096
1305
  }
1097
1306
 
1307
+ /** The names and the four-digit hex addresses that the code of a patch has: a switch can go to them, so they stay. */
1308
+ function patchTargets(code: string, addressOf: ReadonlyMap<string, number>): number[] {
1309
+ const words = code.replace(/;.*$/gm, "").match(/\$[0-9a-fA-F]{4}\b|[A-Za-z_][A-Za-z0-9_]*/g) ?? [];
1310
+ return words.flatMap((word) => (word.startsWith("$") ? [Number.parseInt(word.slice(1), 16)] : addressOf.has(word) ? [addressOf.get(word)!] : []));
1311
+ }
1312
+
1313
+ /**
1314
+ * The free ranges of a program: code that no run executed and that nothing
1315
+ * reaches, and data that no run touched and that nothing names (planDrops).
1316
+ * The export makes them $00; generate makes them the leftovers. `memory` and
1317
+ * `instructions` are of the build that the ranges are free in.
1318
+ */
1319
+ function freeRanges(knowledge: SourceKnowledge, memory: Uint8Array, instructions: ReadonlyMap<number, number>, ranges: { changed: readonly AddressRange[]; keep: readonly AddressRange[]; drop: readonly AddressRange[] }) {
1320
+ const image = knowledge.program;
1321
+ const addressOf = new Map(knowledge.symbols.map((symbol) => [symbol.name, symbol.address]));
1322
+ const operandTargets = new Map<number, number[]>();
1323
+ for (const operand of knowledge.operands) {
1324
+ const names = operand.symbol !== undefined ? [operand.symbol] : identifiers(operand.expression ?? "");
1325
+ const targets = names.flatMap((item) => (addressOf.has(item) ? [(addressOf.get(item)! + (operand.symbol !== undefined ? operand.offset : 0)) & 0xffff] : []));
1326
+ if (targets.length > 0) operandTargets.set(operand.address, targets);
1327
+ }
1328
+ const entry = image.entry ?? basicEntry(image);
1329
+ return planDrops({
1330
+ segments: image.segments,
1331
+ memory,
1332
+ ...(entry === undefined ? {} : { entry }),
1333
+ instructions,
1334
+ ...(knowledge.coverage === undefined ? {} : { coverage: knowledge.coverage }),
1335
+ regions: effectiveRegions(knowledge.regions),
1336
+ references: knowledge.references,
1337
+ operandTargets,
1338
+ changed: [...ranges.changed],
1339
+ keep: [...ranges.keep],
1340
+ drop: [...ranges.drop],
1341
+ routines: knowledge.symbols.filter((symbol) => symbol.kind === "routine"),
1342
+ });
1343
+ }
1344
+
1345
+ /**
1346
+ * The leftovers of generate: the free ranges of the program as it is. The
1347
+ * start screen in the program, the patches, the macro uses, what the code of a
1348
+ * patch names and the ranges of `keep` stay, so each switch builds with
1349
+ * LEFTOVERS = 0.
1350
+ */
1351
+ function leftoversOf(knowledge: SourceKnowledge, instructions: ReadonlyMap<number, number>, kept: readonly AddressRange[] = []): AddressRange[] {
1352
+ const image = knowledge.program;
1353
+ const inImage = (range: AddressRange) => image.segments.some((segment) => range.start >= segment.start && range.end <= segment.end);
1354
+ const addressOf = new Map(knowledge.symbols.map((symbol) => [symbol.name, symbol.address]));
1355
+ const screenParts = knowledge.startScreen === undefined || knowledge.startScreen.stage !== undefined ? [] : startScreenRanges(knowledge.startScreen).map((part) => part.range);
1356
+ const named = knowledge.patches.flatMap((patch) => patchTargets(patch.code, addressOf)).map((address) => ({ start: address, end: address }));
1357
+ const keep = [...screenParts, ...kept, ...knowledge.macroUses, ...named].map((range) => ({ start: range.start, end: range.end })).filter(inImage);
1358
+ const changed = knowledge.patches.map((patch) => ({ start: patch.start, end: patch.end })).filter(inImage);
1359
+ return freeRanges(knowledge, image.memory, instructions, { changed, keep, drop: [] }).free.map((range) => ({ start: range.start, end: range.end }));
1360
+ }
1361
+
1098
1362
  /** 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
1363
  function filesIn(root: string, skip: (path: string) => boolean, folder = ""): Array<{ path: string; bytes: Buffer }> {
1100
1364
  const found: Array<{ path: string; bytes: Buffer }> = [];
@@ -1134,7 +1398,10 @@ async function exportProject(call: Call): Promise<Record<string, unknown>> {
1134
1398
  db?.close();
1135
1399
  }
1136
1400
  })();
1137
- const knowledge = readKnowledge(DEFAULT_SPACE);
1401
+ const read = readKnowledge(DEFAULT_SPACE);
1402
+ // The export has only the space c64: a start screen of a captured stage stays out with that space.
1403
+ const stageLeftOut = read.startScreen?.stage;
1404
+ const knowledge = stageLeftOut === undefined ? read : { ...read, startScreen: undefined };
1138
1405
  const image = knowledge.program;
1139
1406
  // The VIC-II reads the start screen, and the coverage does not show those reads: it stays.
1140
1407
  const screenParts = knowledge.startScreen === undefined ? [] : startScreenRanges(knowledge.startScreen).map((part) => part.range);
@@ -1179,29 +1446,8 @@ async function exportProject(call: Call): Promise<Record<string, unknown>> {
1179
1446
  const decoded = await decode(bakedImage, knowledge, [], knowledge.coverage);
1180
1447
 
1181
1448
  // 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
1449
  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
- });
1450
+ const plan = freeRanges(knowledge, memory, decoded.instructions, { changed, keep, drop });
1205
1451
  const free = plan.free;
1206
1452
  const inFree = (address: number) => free.some((range) => address >= range.start && address <= range.end);
1207
1453
  const overlapsAny = (start: number, end: number, ranges: readonly AddressRange[]) => ranges.some((range) => start <= range.end && range.start <= end);
@@ -1265,7 +1511,7 @@ async function exportProject(call: Call): Promise<Record<string, unknown>> {
1265
1511
  if (state !== undefined) {
1266
1512
  if (exported.loader === undefined) return { result: "FAIL", stage: "loader", reason: exported.loaderRefused ?? "The loader could not be planned." };
1267
1513
  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());
1514
+ const loaderBuilt = await buildLoader(exported.files, exported.laid, exported.loader, exported.loaderMain!, state, new Map());
1269
1515
  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
1516
  baseline = { program: loaderBuilt.program, symbols: loaderBuilt.symbols, entryFile: "loader.asm" };
1271
1517
  loaderOutput = {
@@ -1343,6 +1589,7 @@ async function exportProject(call: Call): Promise<Record<string, unknown>> {
1343
1589
  knowledge: kept,
1344
1590
  tests: { written: tests.map((test) => test.file), leftOut: listed(testsLeftOut, max, (item) => item) },
1345
1591
  ...(spacesLeftOut.length === 0 ? {} : { spacesLeftOut }),
1592
+ ...(stageLeftOut === undefined ? {} : { startScreenLeftOut: `The start screen is of the captured stage in ${stageLeftOut}, and the export has only the space c64.` }),
1346
1593
  ...(exported.rendered.operandsAsNumbers.length === 0 ? {} : { operandsAsNumbers: listed(exported.rendered.operandsAsNumbers, max, (item) => ({ address: formatC64Address(item.address), expression: item.expression, reason: item.reason })) }),
1347
1594
  ...(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
1595
  };
@@ -1398,6 +1645,7 @@ function generateReply(call: Call, body: Record<string, unknown>): Reply {
1398
1645
  again = true;
1399
1646
  }
1400
1647
  if ((body.loader as { verified?: boolean } | undefined)?.verified === false) steps.push("The loader is not verified. Read loader.reason, loader.differences and loader.stop.");
1648
+ 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
1649
  if (body.dataOnly !== undefined) {
1402
1650
  steps.push("The source has only data. If the space has code, give --entry, or record a code region in the project knowledge.");
1403
1651
  again = true;
@@ -1452,8 +1700,8 @@ await runScript({
1452
1700
  options: {
1453
1701
  out: { ...OPTIONS.out, output: "folder", value: "<dir>", help: "the folder for the source files, relative to the project folder", required: true },
1454
1702
  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" },
1703
+ space: { ...OPTIONS.space, help: "the knowledge space of the program: c64 (the default), drive8, or bank0 to bank255. --loader is for c64 only" },
1704
+ 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
1705
  "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
1706
  "max-listed": OPTIONS["max-listed"],
1459
1707
  },