@henols/c64-re-tools 2.1.8 → 2.2.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.
@@ -5,13 +5,14 @@
5
5
  // generator forces operand sizes, and writes an opcode form that ACME
6
6
  // encodes differently as bytes (see the probe in source.ts). An operand
7
7
  // expression of the knowledge is written in place of its number. A
8
- // patch is written as !if SWITCH { code } else { original }, and a
9
- // macro use as one +name args line.
8
+ // patch is written as !if SWITCH { code } else { original }, with the
9
+ // condition of the state that the program does not have, and a macro use as
10
+ // one +name args line. switches.asm holds every switch and release.
10
11
 
11
12
  import { type AddressRange, COVERAGE, formatC64Address, formatC64Byte, POINTER_TABLE_TYPES, pointerTableEntries, type PointerTableType } from "#src/c64.ts";
12
13
  import { WireFailure } from "#src/host-client/tools.ts";
13
14
  import { identifiers, operandText, replaceIdentifiers, type OperandExpression } from "#src/knowledge/expression.ts";
14
- import { type CommentPlacement, isAnalyzer, isGeneratedFile, type Origin, type RegionType } from "#src/knowledge/schema.ts";
15
+ import { type CommentPlacement, isAnalyzer, isGeneratedFile, RELEASE_DEFINE, type Origin, type RegionType, type SwitchKind } from "#src/knowledge/schema.ts";
15
16
  import type { Area } from "#src/platform.ts";
16
17
  import { hasZeroPageForm, instructionWith, labelProblem, MODE_LENGTH, OPCODES, takesAddress, USE_KINDS, useKind, type UseKind } from "#src/opcodes.ts";
17
18
 
@@ -42,8 +43,12 @@ export interface SourceInput {
42
43
  decode?: (register: number, value: number) => Record<string, unknown>;
43
44
  /** Operand expressions of the knowledge, by instruction address. */
44
45
  operands?: ReadonlyArray<OperandExpression & { address: number }>;
45
- /** Patches of the knowledge: code that replaces a range when the build defines the switch. */
46
+ /** Patches of the knowledge: code for a range in the state of the switch that the program does not have. */
46
47
  patches?: ReadonlyArray<{ start: number; end: number; switch: string; code: string; comment?: string }>;
48
+ /** The switches of the knowledge, each with its value in the program. switches.asm holds them all. */
49
+ switches?: ReadonlyArray<SourceSwitch>;
50
+ /** The releases of the knowledge: switches.asm gives each one its switch values. */
51
+ releases?: ReadonlyArray<SourceRelease>;
47
52
  /** Macros of the knowledge, written to macros.asm. */
48
53
  macros?: ReadonlyArray<{ name: string; params: readonly string[]; body: string; comment?: string }>;
49
54
  /** Macro uses of the knowledge: the instructions of a range, written as one use of a macro. */
@@ -66,13 +71,41 @@ export interface MacroAsInstructions {
66
71
  reason: string;
67
72
  }
68
73
 
69
- /** A patch that the source writes, with the addresses inside it that have a name. */
70
- export interface PatchBlock {
71
- start: number;
72
- end: number;
74
+ /** A switch: its kind, its default, its value in the program (`base`) and the releases that have it on. */
75
+ export interface SourceSwitch {
76
+ name: string;
77
+ kind: SwitchKind;
78
+ default: 0 | 1;
79
+ base: 0 | 1;
80
+ releases: readonly string[];
81
+ comment?: string;
82
+ }
83
+
84
+ /** A release: the build with RELEASE_<label> gives each switch the value of this release. */
85
+ export interface SourceRelease {
86
+ label: string;
87
+ file: string;
88
+ base: boolean;
89
+ comment?: string;
90
+ }
91
+
92
+ /** The code of one switch in a patch: it is in when the switch does not have its base value. */
93
+ export interface PatchAlternative {
73
94
  switch: string;
74
95
  code: string;
75
96
  comment?: string;
97
+ base: 0 | 1;
98
+ }
99
+
100
+ /**
101
+ * A patch that the source writes, with the addresses inside it that have a
102
+ * name. Two or more alternatives are patches of different switches at the
103
+ * same range: at most one of them is in.
104
+ */
105
+ export interface PatchBlock {
106
+ start: number;
107
+ end: number;
108
+ alternatives: PatchAlternative[];
76
109
  /** Named addresses after the start of the range: the source defines them before the patch, so both builds have them. */
77
110
  inner: number[];
78
111
  }
@@ -201,6 +234,9 @@ export interface Layout {
201
234
  /** The patches that the source writes, by start. */
202
235
  patches: Map<number, PatchBlock>;
203
236
  patchesNotWritten: PatchNotWritten[];
237
+ /** Every switch of the knowledge, by name, and the releases, the base release first. */
238
+ switches: SourceSwitch[];
239
+ releases: SourceRelease[];
204
240
  /** The macros, by name. */
205
241
  macros: NonNullable<SourceInput["macros"]>;
206
242
  /** The macro uses that the source can write, by start. */
@@ -481,12 +517,24 @@ export function layout(input: SourceInput): Layout {
481
517
  names.set(address, name);
482
518
  generatedLabels++;
483
519
  }
484
- // A patch is written when its range is whole items of one file and its switch is no name of the source.
520
+ // A patch is written when its range is whole items of one file and its switch is a switch of the knowledge and no name of the source.
485
521
  const blocks = new Map<number, PatchBlock>();
486
522
  const patchesNotWritten: PatchNotWritten[] = [];
487
523
  const sourceNames = new Set([...names.values(), ...taken]);
488
- for (const patch of patches) {
524
+ const switches = new Map((input.switches ?? []).map((row) => [row.name, row]));
525
+ for (const patch of [...patches].sort((a, b) => a.start - b.start || (a.switch < b.switch ? -1 : 1))) {
489
526
  const refuse = (reason: string) => patchesNotWritten.push({ start: patch.start, end: patch.end, switch: patch.switch, reason });
527
+ const owner = switches.get(patch.switch);
528
+ if (owner === undefined) {
529
+ refuse(`The switch ${patch.switch} is not a switch of the knowledge.`);
530
+ continue;
531
+ }
532
+ const known = blocks.get(patch.start);
533
+ if (known !== undefined) {
534
+ if (known.end !== patch.end) refuse(`The range overlaps the patch of ${known.alternatives[0]!.switch} at ${formatC64Address(known.start)}-${formatC64Address(known.end)}: alternatives have the same range.`);
535
+ else known.alternatives.push({ switch: patch.switch, code: patch.code, ...(patch.comment === undefined ? {} : { comment: patch.comment }), base: owner.base });
536
+ continue;
537
+ }
490
538
  const piece = pieces.find((row) => patch.start >= row.start && patch.start <= row.end);
491
539
  if (piece === undefined) {
492
540
  refuse("The range is not in the image.");
@@ -508,7 +556,7 @@ export function layout(input: SourceInput): Layout {
508
556
  continue;
509
557
  }
510
558
  const inner = [...names.keys()].filter((address) => address > patch.start && address <= patch.end).sort((a, b) => a - b);
511
- blocks.set(patch.start, { start: patch.start, end: patch.end, switch: patch.switch, code: patch.code, ...(patch.comment === undefined ? {} : { comment: patch.comment }), inner });
559
+ blocks.set(patch.start, { start: patch.start, end: patch.end, alternatives: [{ switch: patch.switch, code: patch.code, ...(patch.comment === undefined ? {} : { comment: patch.comment }), base: owner.base }], inner });
512
560
  }
513
561
  // The high byte of a vector is NMINV+1. A zero-page entry keeps zero-page instructions: its constant has two digits.
514
562
  // An address inside a table keeps its own label when the source needs one there anyway, for example as the entry.
@@ -549,6 +597,8 @@ export function layout(input: SourceInput): Layout {
549
597
  operandsAsNumbers: operandsAsNumbers.sort((a, b) => a.address - b.address),
550
598
  patches: blocks,
551
599
  patchesNotWritten,
600
+ switches: [...(input.switches ?? [])].sort((a, b) => (a.name < b.name ? -1 : 1)),
601
+ releases: [...(input.releases ?? [])].sort((a, b) => Number(b.base) - Number(a.base) || (a.label < b.label ? -1 : 1)),
552
602
  macros: [...(input.macros ?? [])].sort((a, b) => (a.name < b.name ? -1 : 1)),
553
603
  macroUses: usesWritten,
554
604
  macrosAsInstructions: macrosAsInstructions.sort((a, b) => a.start - b.start),
@@ -772,23 +822,67 @@ function usageText(kinds: ReadonlyMap<UseKind, number> | undefined): string | un
772
822
  return parts.length === 0 ? undefined : `Used: ${parts.join(", ")}.`;
773
823
  }
774
824
 
775
- /** The switches of the patches, each 0 unless the build defines it, with the ranges of its patches. */
825
+ /** The patches of each switch that has one, by switch name. */
776
826
  export function switchesOf(layout: Pick<Layout, "patches">): Map<string, PatchBlock[]> {
777
827
  const switches = new Map<string, PatchBlock[]>();
778
- for (const patch of [...layout.patches.values()].sort((a, b) => a.start - b.start)) switches.set(patch.switch, [...(switches.get(patch.switch) ?? []), patch]);
828
+ for (const patch of [...layout.patches.values()].sort((a, b) => a.start - b.start)) {
829
+ for (const alternative of patch.alternatives) switches.set(alternative.switch, [...(switches.get(alternative.switch) ?? []), patch]);
830
+ }
779
831
  return new Map([...switches].sort(([a], [b]) => (a < b ? -1 : 1)));
780
832
  }
781
833
 
782
- function switchLines(layout: Layout): string[] {
783
- const switches = switchesOf(layout);
784
- if (switches.size === 0) return [];
785
- const width = Math.max(...[...switches.keys()].map((name) => name.length));
786
- const lines = ["; Switches: each is 0 unless the build defines it. Assemble with -DNAME=1", "; (c64-assembler --define NAME=1) to put in the patches of NAME."];
787
- for (const [name, patches] of switches) {
788
- const ranges = patches.map((patch) => `${formatC64Address(patch.start)}-${formatC64Address(patch.end)}`).join(", ");
789
- lines.push(`!ifndef ${name} { ${name} = 0 }${" ".repeat(width - name.length)} ; ${patches.length} patch${patches.length === 1 ? "" : "es"}: ${ranges}`);
834
+ /** The groups of switches.asm, in order, with the default of each group. */
835
+ const SWITCH_GROUPS: ReadonlyArray<{ kind: SwitchKind; title: string }> = [
836
+ { kind: "protection", title: "Copy protection: off by default" },
837
+ { kind: "trainer", title: "Trainers: off by default" },
838
+ { kind: "cheat", title: "Cheats: off by default" },
839
+ { kind: "crack", title: "Changes of a crack: off by default" },
840
+ { kind: "fix", title: "Fixes of the releases: on by default" },
841
+ { kind: "change", title: "Other changes" },
842
+ ];
843
+
844
+ /** True when the source has switches.asm: the knowledge has switches or releases. */
845
+ export const hasSwitchFile = (layout: Pick<Layout, "switches" | "releases">) => layout.switches.length > 0 || layout.releases.length > 0;
846
+
847
+ /**
848
+ * switches.asm: every switch of the knowledge in one place. A release block
849
+ * gives each switch the value of that release when the build defines
850
+ * RELEASE_<label>; then each switch gets its default unless the build defines
851
+ * it. A comment tells the releases that have the switch on, and its patches.
852
+ */
853
+ function switchesText(layout: Layout): string {
854
+ const patches = switchesOf(layout);
855
+ const out = [
856
+ "; The switches of the patches. Each switch is 0 or 1.",
857
+ "; The default build is the clean program: copy protection, trainers, cheats",
858
+ "; and changes of a crack are off, and the fixes of the releases are on.",
859
+ `; Build a release with -D${RELEASE_DEFINE}<label>=1 (c64-assembler --release <label>).`,
860
+ "; Set one switch with -DNAME=0 or -DNAME=1 (c64-assembler --define NAME=1).",
861
+ ];
862
+ if (layout.releases.length > 0) out.push("", "; Releases");
863
+ for (const release of layout.releases) {
864
+ out.push(`; ${release.label}${release.base ? " (the program of the knowledge)" : ""}: ${release.file}${release.comment === undefined ? "" : `. ${release.comment.replace(/\s*\r?\n\s*/g, " ")}`}`);
865
+ out.push(`!ifdef ${RELEASE_DEFINE}${release.label} {`);
866
+ for (const row of layout.switches) out.push(`${INDENT}!ifndef ${row.name} { ${row.name} = ${row.releases.includes(release.label) ? 1 : 0} }`);
867
+ out.push("}");
790
868
  }
791
- return [...lines, ""];
869
+ const line = (row: SourceSwitch) => `!ifndef ${row.name} { ${row.name} = ${row.default} }`;
870
+ const width = Math.max(0, ...layout.switches.map((row) => line(row).length));
871
+ for (const group of SWITCH_GROUPS) {
872
+ const rows = layout.switches.filter((row) => row.kind === group.kind);
873
+ if (rows.length === 0) continue;
874
+ out.push("", `; ${group.title}`);
875
+ for (const row of rows) {
876
+ const ranges = (patches.get(row.name) ?? []).map((patch) => `${formatC64Address(patch.start)}-${formatC64Address(patch.end)}`);
877
+ const parts = [
878
+ row.releases.length === 0 ? "on in no release" : `on in ${row.releases.join(", ")}`,
879
+ ranges.length === 0 ? "no patch" : ranges.join(", "),
880
+ ...(row.comment === undefined ? [] : [row.comment.replace(/\s*\r?\n\s*/g, " ")]),
881
+ ];
882
+ out.push(`${line(row).padEnd(width)} ; ${parts.join(". ")}`);
883
+ }
884
+ }
885
+ return `${out.join("\n")}\n`;
792
886
  }
793
887
 
794
888
  /** constants.asm: the names outside the image by platform area, each with what it is and how the source uses it. */
@@ -801,7 +895,7 @@ function constantsText(layout: Layout): { text: string; labels: SourceLabel[] }
801
895
  });
802
896
  const nameColumn = Math.min(MAX_NAME_COLUMN, Math.max(0, ...rows.map((row) => row.name.length)));
803
897
  const valueColumn = Math.max(0, ...rows.map((row) => row.value.length));
804
- const out = [...switchLines(layout)];
898
+ const out: string[] = [];
805
899
  out.push(
806
900
  describe === undefined ? "; Names of addresses outside the image." : "; Names of addresses outside the image, by memory area.",
807
901
  '; "Used" counts the instructions and table entries of this source that use the name.',
@@ -881,23 +975,42 @@ function macrosText(layout: Layout): { text: string; lines: Map<string, { first:
881
975
  return { text: `${out.join("\n")}\n`, lines };
882
976
  }
883
977
 
884
- /** The lines that open a patch: its zone, the switch, the code, and the guard that stops a patch longer than its range. */
978
+ /** The condition that puts in the code of a switch: the switch has the value that the program does not have. */
979
+ const patchCondition = (alternative: PatchAlternative) => (alternative.base === 0 ? alternative.switch : `${alternative.switch} = 0`);
980
+
981
+ /**
982
+ * The lines that open a patch: its zone, a guard that stops two alternatives
983
+ * together, then for each switch its condition, its code and the guard that
984
+ * stops code longer than the range. The original code follows in the last
985
+ * else; the patch closes with closingBraces.
986
+ */
885
987
  function patchOpening(patch: PatchBlock): string[] {
886
988
  const bytes = patch.end - patch.start + 1;
887
989
  const range = `${formatC64Address(patch.start)}-${formatC64Address(patch.end)}`;
888
- const comment = patch.comment === undefined ? [] : patch.comment.split(/\r?\n/).map((line) => `${INDENT}; ${line}`.trimEnd());
889
- return [
890
- `!zone patch_${patch.switch}_${patch.start.toString(16).padStart(4, "0")} {`,
891
- ".patch_start",
892
- `!if ${patch.switch} {`,
893
- `${INDENT}; ${patch.switch} on: ${bytes} byte${bytes === 1 ? "" : "s"} at ${range}, NOP after the code`,
894
- ...comment,
895
- ...(patch.code === "" ? [] : patch.code.split(/\r?\n/)),
896
- `${INDENT}!if * - .patch_start > ${bytes} { !error "The patch ${patch.switch} at ${formatC64Address(patch.start)} has ", * - .patch_start, " bytes; the range has ${bytes}." } else { !fill ${bytes} - (* - .patch_start), $ea }`,
897
- "} else {",
898
- ];
990
+ const out = [`!zone patch_${patch.alternatives[0]!.switch}_${patch.start.toString(16).padStart(4, "0")} {`, ".patch_start"];
991
+ patch.alternatives.forEach((first, index) => {
992
+ for (const second of patch.alternatives.slice(index + 1)) {
993
+ out.push(`!if ${patchCondition(first)} { !if ${patchCondition(second)} { !error "${first.switch} and ${second.switch} change ${range}: turn on one of them." } }`);
994
+ }
995
+ });
996
+ patch.alternatives.forEach((alternative, index) => {
997
+ const state = alternative.base === 0 ? "on" : "off";
998
+ const comment = alternative.comment === undefined ? [] : alternative.comment.split(/\r?\n/).map((line) => `${INDENT}; ${line}`.trimEnd());
999
+ out.push(
1000
+ `${index === 0 ? "" : "} else { "}!if ${patchCondition(alternative)} {`,
1001
+ `${INDENT}; ${alternative.switch} ${state}: ${bytes} byte${bytes === 1 ? "" : "s"} at ${range}, NOP after the code`,
1002
+ ...comment,
1003
+ ...(alternative.code === "" ? [] : alternative.code.split(/\r?\n/)),
1004
+ `${INDENT}!if * - .patch_start > ${bytes} { !error "The patch ${alternative.switch} at ${formatC64Address(patch.start)} has ", * - .patch_start, " bytes; the range has ${bytes}." } else { !fill ${bytes} - (* - .patch_start), $ea }`,
1005
+ );
1006
+ });
1007
+ out.push("} else {");
1008
+ return out;
899
1009
  }
900
1010
 
1011
+ /** The braces that close a patch: one for each alternative, then the zone. */
1012
+ const closingBraces = (patch: PatchBlock) => ["}".repeat(patch.alternatives.length), "}"];
1013
+
901
1014
  const withSide = (text: string, side: string | undefined) => (side === undefined ? text : `${text.padEnd(SIDE_COLUMN - 1)} ; ${side}`);
902
1015
 
903
1016
  /**
@@ -996,7 +1109,7 @@ export function render(layout: Layout, asBytes: ReadonlySet<string>, header: str
996
1109
  const close = () => {
997
1110
  const itemEnd = item.kind === "instruction" ? item.address + item.length - 1 : item.end;
998
1111
  if (patch === undefined || itemEnd !== patch.end) return;
999
- out.push("}", "}");
1112
+ out.push(...closingBraces(patch));
1000
1113
  patch = undefined;
1001
1114
  };
1002
1115
  if (item.kind === "instruction" && item.address <= useEnd) {
@@ -1084,6 +1197,7 @@ export function render(layout: Layout, asBytes: ReadonlySet<string>, header: str
1084
1197
  result.files.push({ name: piece.file, text: `${out.join("\n")}\n` });
1085
1198
  }
1086
1199
 
1200
+ if (hasSwitchFile(layout)) result.files.push({ name: "switches.asm", text: switchesText(layout) });
1087
1201
  const constants = constantsText(layout);
1088
1202
  result.files.push({ name: "constants.asm", text: constants.text });
1089
1203
  result.labels.push(...constants.labels);
@@ -1092,7 +1206,7 @@ export function render(layout: Layout, asBytes: ReadonlySet<string>, header: str
1092
1206
  result.files.push({ name: "macros.asm", text: macros.text });
1093
1207
  result.macroLines = macros.lines;
1094
1208
  }
1095
- const main = [...header.map((line) => `; ${line}`), "", "!cpu 6510", '!source "constants.asm"', ...(layout.macros.length > 0 ? ['!source "macros.asm"'] : [])];
1209
+ const main = [...header.map((line) => `; ${line}`), "", "!cpu 6510", ...(hasSwitchFile(layout) ? ['!source "switches.asm"'] : []), '!source "constants.asm"', ...(layout.macros.length > 0 ? ['!source "macros.asm"'] : [])];
1096
1210
  for (const piece of layout.pieces) {
1097
1211
  if (piece.segmentStart) main.push("", `* = ${formatC64Address(piece.start)}`);
1098
1212
  main.push(`!source "${piece.file}"`);
@@ -1,18 +1,23 @@
1
1
  // The c64-source script: generates ACME source from the program and the
2
2
  // knowledge and Ghidra's instructions, which it runs itself, and checks
3
- // with ACME that the source assembles to the program byte by byte. With --loader it
4
- // also writes a loader that recreates the entry state, simulates it, and
5
- // checks it in the emulator. Each switch of the patches is built on
6
- // alone and checked. A macro use that does not give the bytes of the
7
- // image is written as its instructions. result is PASS when every check
8
- // passes, else FAIL.
3
+ // with ACME that the build of the base release assembles to the program byte
4
+ // by byte. With --loader it also writes a loader that recreates the entry
5
+ // state, simulates it, and checks it in the emulator. The default build may
6
+ // differ from the program only in the patches that it puts in; each release
7
+ // builds to the bytes of its file; each switch is built alone against the
8
+ // base release. A macro use that does not give the bytes of the image is
9
+ // written as its instructions. result is PASS when every check passes, else
10
+ // FAIL.
9
11
 
12
+ import { createHash } from "node:crypto";
10
13
  import { existsSync, readdirSync, readFileSync, rmSync } from "node:fs";
11
14
  import { join } from "node:path";
12
15
 
13
16
  import { Refusal } from "#src/errors.ts";
14
17
  import { type AddressRange, coverageSeedKinds, formatC64Address, textToPetscii } from "#src/c64.ts";
15
18
  import { autostartLoaded, RUN_LIMIT_FRAMES } from "#src/host-client/autostart.ts";
19
+ import { readImage, type Image } from "#src/host-client/image.ts";
20
+ import { readProjectFile } from "#src/host-client/transfer.ts";
16
21
  import { MAX_MEMORY_READ, WireFailure } from "#src/host-client/tools.ts";
17
22
  import { writeReported, type Written } from "#src/host-client/transfer.ts";
18
23
  import { ViceSessionClient } from "#src/host-client/vice-session.ts";
@@ -20,8 +25,8 @@ import { conflicts } from "#src/knowledge/conflicts.ts";
20
25
  import { openForRead } from "#src/knowledge/database.ts";
21
26
  import { identifiers } from "#src/knowledge/expression.ts";
22
27
  import { analyzedBytes, programCoverage, requireProgram, type ProgramImage } from "#src/knowledge/program.ts";
23
- import { ANALYZER_NAME_ORDER, currentRevision, listAnalyzerNames, listComments, listMacros, listMacroUses, listModules, listOperands, listPatches, listReferences, listRegions, listSymbols, type SymbolRow } from "#src/knowledge/read.ts";
24
- import { CODE_REGION_TYPES, DEFAULT_SPACE, type Space } from "#src/knowledge/schema.ts";
28
+ import { ANALYZER_NAME_ORDER, baseValue, currentRevision, listAnalyzerNames, listComments, listMacros, listMacroUses, listModules, listOperands, listPatches, listReferences, listRegions, listReleases, listSwitches, listSymbols, type ReleaseRow, type SymbolRow } from "#src/knowledge/read.ts";
29
+ import { CODE_REGION_TYPES, DEFAULT_SPACE, RELEASE_DEFINE, type Space } from "#src/knowledge/schema.ts";
25
30
  import { assemble } from "#src/native/acme.ts";
26
31
  import { analyze } from "#src/native/ghidra/analyze.ts";
27
32
  import { localToolContext } from "#src/native/local.ts";
@@ -32,7 +37,7 @@ import { listed, OPTIONS, runScript, UsageError, type Call } from "#src/script.t
32
37
  import { knowledgeNames } from "#src/knowledge/names.ts";
33
38
  import { COPIER_SOURCE, LOADER_JUMP, loaderLimits, planLoader, rasterLine, loaderState, simulate, stopCause, VIC_DISPLAY_REGISTERS, type EntryState, type LoaderPlan } from "./lib/loader.ts";
34
39
  import { instructionWith, OPCODES } from "#src/opcodes.ts";
35
- import { entriesInData, entryOutsideImage, layout, literalOperand, probeForms, render, switchesOf, type Layout, type PatchBlock, type Rendered } from "./lib/source.ts";
40
+ import { entriesInData, entryOutsideImage, hasSwitchFile, layout, literalOperand, probeForms, render, switchesOf, type Layout, type PatchBlock, type Rendered, type SourceSwitch } from "./lib/source.ts";
36
41
 
37
42
  /** At most this many diagnostics or differences of one check. */
38
43
  const MAX_DIAGNOSTICS = 20;
@@ -55,6 +60,8 @@ function readKnowledge(space: Space, analyzerNames = false) {
55
60
  if (found > 0) throw new Refusal("conflict", `The knowledge has ${found} conflict${found === 1 ? "" : "s"} from a git merge. Nothing was generated. Run c64-knowledge's knowledge.ts merge, then generate again.`);
56
61
  const symbols = listSymbols(db, undefined, undefined, undefined, space);
57
62
  const second = listAnalyzerNames(db, undefined, undefined, undefined, space);
63
+ const releases = listReleases(db, undefined, space);
64
+ const base = releases.find((release) => release.base)?.label;
58
65
  return {
59
66
  revision: currentRevision(db),
60
67
  program: requireProgram(db, space),
@@ -69,6 +76,8 @@ function readKnowledge(space: Space, analyzerNames = false) {
69
76
  references: listReferences(db, undefined, undefined, undefined, space),
70
77
  operands: listOperands(db, undefined, undefined, space),
71
78
  patches: listPatches(db, undefined, undefined, undefined, space),
79
+ switches: listSwitches(db, undefined, space).map((row): SourceSwitch => ({ name: row.name, kind: row.kind, default: row.default, base: baseValue(row, base), releases: row.releases, ...(row.comment === undefined ? {} : { comment: row.comment }) })),
80
+ releases,
72
81
  macros: listMacros(db, undefined, space),
73
82
  macroUses: listMacroUses(db, undefined, undefined, undefined, space),
74
83
  };
@@ -326,7 +335,7 @@ interface SegmentCheck {
326
335
  }
327
336
 
328
337
  /** Compares the assembled program with the image, segment by segment. */
329
- function check(program: Buffer, start: number, image: ProgramImage): { identical: boolean; segments: SegmentCheck[] } {
338
+ function check(program: Buffer, start: number, image: Pick<ProgramImage, "segments" | "byteAt">): { identical: boolean; segments: SegmentCheck[] } {
330
339
  const end = start + program.length - 3;
331
340
  const segments = image.segments.map((segment): SegmentCheck => {
332
341
  const shown = { start: formatC64Address(segment.start), end: formatC64Address(segment.end) };
@@ -344,45 +353,34 @@ function check(program: Buffer, start: number, image: ProgramImage): { identical
344
353
  return { identical: segments.every((segment) => segment.result === "identical"), segments };
345
354
  }
346
355
 
347
- /** What a build with one switch on gives. */
348
- interface SwitchCheck {
349
- name: string;
350
- define: string;
351
- patches: Array<{ start: string; end: string; bytes: number; insideNames?: string[] }>;
356
+ /** What a build with other switch values gives, against the build of the base release. */
357
+ interface BuildCheck {
352
358
  result: "fits" | "overflow" | "changes outside" | "does not assemble";
353
359
  changedBytes?: number;
354
- outside?: { count: number; first: { address: string; built: number; default: number } };
360
+ outside?: { count: number; first: { address: string; built: number; base: number } };
355
361
  overflow?: Array<{ start: string; message: string }>;
356
362
  diagnostics?: Diagnostic[];
357
363
  }
358
364
 
359
365
  /**
360
- * Builds the source with one switch on and compares it with the default
361
- * build: only the ranges of its patches may change, and the program keeps its
362
- * start and length. A patch longer than its range stops ACME with !error.
366
+ * Builds the source with the defines and compares it with the build of the
367
+ * base release: only the ranges may change, and the program keeps its start
368
+ * and length. A patch longer than its range, or two alternatives together,
369
+ * stop ACME with !error.
363
370
  */
364
- async function checkSwitch(name: string, patches: PatchBlock[], files: Array<{ name: string; text: string }>, base: { program: Buffer; start: number }, names: Layout["names"]): Promise<SwitchCheck> {
365
- const shown: SwitchCheck = {
366
- name,
367
- define: `--define ${name}=1`,
368
- patches: patches.map((patch) => {
369
- const inside = patch.inner.map((address) => names.get(address)!);
370
- return { start: formatC64Address(patch.start), end: formatC64Address(patch.end), bytes: patch.end - patch.start + 1, ...(inside.length === 0 ? {} : { insideNames: inside }) };
371
- }),
372
- result: "fits",
373
- };
374
- const built = await assembleFiles(files, "main.asm", { [name]: 1 });
371
+ async function checkBuild(files: Array<{ name: string; text: string }>, defines: Record<string, number>, ranges: readonly AddressRange[], base: { program: Buffer; start: number }): Promise<BuildCheck> {
372
+ const built = await assembleFiles(files, "main.asm", defines);
375
373
  if (built.program === undefined) {
376
374
  const overflow = built.diagnostics.flatMap((diagnostic) => {
377
- const found = /The patch \S+ at (\$[0-9a-f]{4}) has .*/.exec(diagnostic.message);
378
- return found === null ? [] : [{ start: found[1]!, message: found[0] }];
375
+ const found = /The patch \S+ at (\$[0-9a-f]{4}) has .*|\S+ and \S+ change (\$[0-9a-f]{4})-\$[0-9a-f]{4}: turn on one of them\./.exec(diagnostic.message);
376
+ return found === null ? [] : [{ start: (found[1] ?? found[2])!, message: found[0] }];
379
377
  });
380
- if (overflow.length > 0) return { ...shown, result: "overflow", overflow };
381
- return { ...shown, result: "does not assemble", diagnostics: built.diagnostics.slice(0, MAX_DIAGNOSTICS) };
378
+ if (overflow.length > 0) return { result: "overflow", overflow };
379
+ return { result: "does not assemble", diagnostics: built.diagnostics.slice(0, MAX_DIAGNOSTICS) };
382
380
  }
383
- const inside = (address: number) => patches.some((patch) => address >= patch.start && address <= patch.end);
381
+ const inside = (address: number) => ranges.some((range) => address >= range.start && address <= range.end);
384
382
  let changed = 0;
385
- let outside: SwitchCheck["outside"];
383
+ let outside: BuildCheck["outside"];
386
384
  const end = Math.max(base.start + base.program.length, built.start! + built.program.length) - 2;
387
385
  for (let address = Math.min(base.start, built.start!); address < end; address++) {
388
386
  const at = (program: Buffer, start: number) => (address >= start && address < start + program.length - 2 ? program[2 + address - start]! : -1);
@@ -390,9 +388,77 @@ async function checkSwitch(name: string, patches: PatchBlock[], files: Array<{ n
390
388
  const before = at(base.program, base.start);
391
389
  if (now === before) continue;
392
390
  if (inside(address)) changed++;
393
- else outside = { count: (outside?.count ?? 0) + 1, first: outside?.first ?? { address: formatC64Address(address), built: now, default: before } };
391
+ else outside = { count: (outside?.count ?? 0) + 1, first: outside?.first ?? { address: formatC64Address(address), built: now, base: before } };
392
+ }
393
+ return outside === undefined ? { result: "fits", changedBytes: changed } : { result: "changes outside", changedBytes: changed, outside };
394
+ }
395
+
396
+ /** What a build with one switch at the value that the base release does not have gives. */
397
+ type SwitchCheck = BuildCheck & {
398
+ name: string;
399
+ kind: string;
400
+ default: number;
401
+ base: number;
402
+ define: string;
403
+ patches: Array<{ start: string; end: string; bytes: number; insideNames?: string[] }>;
404
+ };
405
+
406
+ /** Builds the source with one switch changed from its base value; only the ranges of its patches may change. */
407
+ async function checkSwitch(row: SourceSwitch, patches: PatchBlock[], files: Array<{ name: string; text: string }>, defines: Record<string, number>, base: { program: Buffer; start: number }, names: Layout["names"]): Promise<SwitchCheck> {
408
+ const value = 1 - row.base;
409
+ const built = await checkBuild(files, { ...defines, [row.name]: value }, patches, base);
410
+ return {
411
+ name: row.name,
412
+ kind: row.kind,
413
+ default: row.default,
414
+ base: row.base,
415
+ define: `--define ${row.name}=${value}`,
416
+ patches: patches.map((patch) => {
417
+ const inside = patch.inner.map((address) => names.get(address)!);
418
+ return { start: formatC64Address(patch.start), end: formatC64Address(patch.end), bytes: patch.end - patch.start + 1, ...(inside.length === 0 ? {} : { insideNames: inside }) };
419
+ }),
420
+ ...built,
421
+ };
422
+ }
423
+
424
+ /** What the build of a release gives against the bytes of its file. */
425
+ interface ReleaseCheck {
426
+ label: string;
427
+ base: boolean;
428
+ file: string;
429
+ define: string;
430
+ result: "identical" | "different" | "layout differs" | "file changed" | "does not assemble";
431
+ reason?: string;
432
+ segments?: SegmentCheck[];
433
+ diagnostics?: Diagnostic[];
434
+ }
435
+
436
+ /**
437
+ * Builds a release with RELEASE_<label> and compares it with its file. A
438
+ * release whose segments are not the segments of the program has moved code,
439
+ * which patches cannot give: it is shown and does not fail the run.
440
+ */
441
+ async function checkRelease(release: ReleaseRow, files: Array<{ name: string; text: string }>, program: ProgramImage): Promise<ReleaseCheck> {
442
+ const shown = { label: release.label, base: release.base, file: release.file, define: `--define ${RELEASE_DEFINE}${release.label}=1` };
443
+ let image: Image;
444
+ try {
445
+ const bytes = readProjectFile(release.file).bytes;
446
+ if (createHash("sha256").update(bytes).digest("hex") !== release.sha256) {
447
+ return { ...shown, result: "file changed", reason: `The SHA-256 of ${release.file} is not the one that the knowledge has. Record the release again (knowledge.ts release), or put back the file.` };
448
+ }
449
+ image = readImage(release.file);
450
+ } catch (error) {
451
+ if (!(error instanceof Refusal || error instanceof WireFailure)) throw error;
452
+ return { ...shown, result: "file changed", reason: error.message };
394
453
  }
395
- return outside === undefined ? { ...shown, changedBytes: changed } : { ...shown, result: "changes outside", changedBytes: changed, outside };
454
+ if (JSON.stringify(image.segments) !== JSON.stringify(program.segments)) {
455
+ const segments = (list: readonly AddressRange[]) => list.map((segment) => `${formatC64Address(segment.start)}-${formatC64Address(segment.end)}`).join(", ");
456
+ return { ...shown, result: "layout differs", reason: `The release has the segments ${segments(image.segments)}, and the program has ${segments(program.segments)}. Patches change bytes in place; they cannot move code.` };
457
+ }
458
+ const built = await assembleFiles(files, "main.asm", { [`${RELEASE_DEFINE}${release.label}`]: 1 });
459
+ if (built.program === undefined) return { ...shown, result: "does not assemble", diagnostics: built.diagnostics.slice(0, MAX_DIAGNOSTICS) };
460
+ const checked = check(built.program, built.start!, image);
461
+ return { ...shown, result: checked.identical ? "identical" : "different", ...(checked.identical ? {} : { segments: checked.segments.filter((segment) => segment.result !== "identical") }) };
396
462
  }
397
463
 
398
464
  /** Reads RAM in parts. */
@@ -560,6 +626,8 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
560
626
  const romUse = romUseOfProgram(coverage, image.state);
561
627
  const platform = platformNamesFor(romUse);
562
628
  const { instructions, dataOnly } = await decode(image, knowledge, entries, coverage);
629
+ // Every build that is compared with the program is the build of the base release: each switch at its base value.
630
+ const baseDefines = Object.fromEntries(knowledge.switches.map((row) => [row.name, row.base]));
563
631
  const laid = layout({
564
632
  segments: image.segments,
565
633
  byteAt: image.byteAt,
@@ -572,6 +640,8 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
572
640
  referenceTargets: knowledge.references.map((reference) => reference.to),
573
641
  operands: knowledge.operands,
574
642
  patches: knowledge.patches,
643
+ switches: knowledge.switches,
644
+ releases: knowledge.releases.map((release) => ({ label: release.label, file: release.file, base: release.base, ...(release.comment === undefined ? {} : { comment: release.comment }) })),
575
645
  macros: knowledge.macros,
576
646
  macroUses: knowledge.macroUses,
577
647
  ...(coverage === undefined ? {} : { coverage }),
@@ -589,7 +659,7 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
589
659
  const segments = image.segments.map((segment) => ({ ...segment, files: laid.pieces.filter((piece) => piece.start >= segment.start && piece.start <= segment.end).map((piece) => piece.file) }));
590
660
  try {
591
661
  const entryName = laid.names.get(image.entry!);
592
- loader = planLoader({ segments, byteAt: image.byteAt, state, entry: image.entry!, ...(entryName === undefined ? {} : { entryName }), macros: laid.macros.length > 0, header: [`Loader generated by c64-source from knowledge revision ${knowledge.revision}.`, "It copies the segments into place, sets the entry state and jumps to the entry."] });
662
+ loader = planLoader({ segments, byteAt: image.byteAt, state, entry: image.entry!, ...(entryName === undefined ? {} : { entryName }), switches: hasSwitchFile(laid), macros: laid.macros.length > 0, header: [`Loader generated by c64-source from knowledge revision ${knowledge.revision}.`, "It copies the segments into place, sets the entry state and jumps to the entry."] });
593
663
  } catch (error) {
594
664
  if (!(error instanceof WireFailure)) throw error;
595
665
  loaderRefused = error.message;
@@ -606,7 +676,7 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
606
676
  if (laid.macroUses.size > 0) for (const [start, reason] of await probeUses(laid, rendered, image)) asInstructions.set(start, reason);
607
677
  if (asInstructions.size > 0) rendered = render(laid, asBytes, header, numbers, asInstructions);
608
678
  let files = marked([...rendered.files, ...loaderFiles]);
609
- let built = await assembleFiles(files, "main.asm");
679
+ let built = await assembleFiles(files, "main.asm", baseDefines);
610
680
  for (let round = 0; round < ROUNDS && (rendered.expressions.length > 0 || rendered.uses.length > 0); round++) {
611
681
  const blamed = blame(rendered, built, image, 1);
612
682
  if (blamed.numbers.size === 0 && blamed.uses.size === 0) break;
@@ -614,7 +684,7 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
614
684
  for (const [start, reason] of blamed.uses) asInstructions.set(start, reason);
615
685
  rendered = render(laid, asBytes, header, numbers, asInstructions);
616
686
  files = marked([...rendered.files, ...loaderFiles]);
617
- built = await assembleFiles(files, "main.asm");
687
+ built = await assembleFiles(files, "main.asm", baseDefines);
618
688
  }
619
689
  const removed = removeOldFiles(out, new Set(files.map((file) => file.name)), loaderWanted).map((name) => `${out}/${name}`);
620
690
  const written: Written[] = files.map((file) => writeReported(`${out}/${file.name}`, file.text, { what: "--out" }));
@@ -689,15 +759,35 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
689
759
  const checked = check(built.program, built.start!, image);
690
760
  output.check = checked;
691
761
  if (!checked.identical) return { output: { ...output, ...notBuilt("The source does not assemble to the image, and the loader includes it.") }, removed, failed: true };
692
- // Each switch on alone, against the default build; combinations are not built.
762
+ const baseBuild = { program: built.program, start: built.start! };
763
+ // Each switch alone at the value that the base release does not have, against the base release.
693
764
  const switches: SwitchCheck[] = [];
694
- for (const [name, patches] of switchesOf(laid)) switches.push(await checkSwitch(name, patches, files, { program: built.program, start: built.start! }, laid.names));
765
+ const withPatches = switchesOf(laid);
766
+ for (const row of laid.switches) {
767
+ const patches = withPatches.get(row.name);
768
+ if (patches !== undefined) switches.push(await checkSwitch(row, patches, files, baseDefines, baseBuild, laid.names));
769
+ }
695
770
  if (switches.length > 0) output.switches = switches;
696
- const sourceFailed = laid.patchesNotWritten.length > 0 || switches.some((item) => item.result !== "fits");
771
+ // The default build: the patches of each switch whose default is not its base value are in, and nothing else changes.
772
+ let defaultFailed = false;
773
+ if (laid.switches.length > 0) {
774
+ const changed = laid.switches.filter((row) => row.default !== row.base);
775
+ const ranges = changed.flatMap((row) => withPatches.get(row.name) ?? []);
776
+ const built = await checkBuild(files, {}, ranges, baseBuild);
777
+ output.default = { in: changed.map((row) => row.name), ...built };
778
+ defaultFailed = built.result !== "fits";
779
+ }
780
+ // Each release built with its switch values, against its file.
781
+ const releases: ReleaseCheck[] = [];
782
+ for (const release of knowledge.releases) releases.push(await checkRelease(release, files, image));
783
+ if (releases.length > 0) output.releases = releases;
784
+ const releasesFailed = releases.some((item) => item.result !== "identical" && (item.base || item.result !== "layout differs"));
785
+ const sourceFailed = laid.patchesNotWritten.length > 0 || switches.some((item) => item.result !== "fits") || defaultFailed || releasesFailed;
697
786
  if (loaderRefused !== undefined) return { output: { ...output, loader: { verified: false, reason: loaderRefused } }, removed, failed: true };
698
787
  if (loader === undefined || state === undefined) return { output, removed, failed: missingEntry !== undefined || sourceFailed };
699
788
 
700
- const loaderBuilt = await assembleFiles(files, "loader.asm");
789
+ // The entry state is the state of the base release: the loader is built and checked with it.
790
+ const loaderBuilt = await assembleFiles(files, "loader.asm", baseDefines);
701
791
  if (loaderBuilt.program === undefined) return { output: { ...output, loader: { verified: false, reason: "loader.asm does not assemble.", diagnostics: loaderBuilt.diagnostics.slice(0, MAX_DIAGNOSTICS) } }, removed, failed: true };
702
792
  const program = loaderBuilt.program;
703
793
  // The simulation: the loader in memory as it loads, then every copy in its order, byte by byte.