@henols/c64-re-tools 2.5.0-rc.1 → 2.6.0-rc.1

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