@henols/c64-re-tools 2.1.8 → 2.2.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.
@@ -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.
@@ -111,7 +111,10 @@ The scripts refuse a step in the form of version 2.0, for example `{ "runUntil":
111
111
  - `image.json`: the entry, the segments, the vectors and the stages. A segment is a block that a stage wrote, also a small block. A block is not a segment when it holds the entry of a later stage before the program, and no stage wrote over that entry. A block that a stage before the program wrote in such a block is also not a segment, for example a variable of a loader. A block that is fully in pages 0 to 3 is not a segment, because `entry_state.json` holds these pages. The block with the capture entry is always a segment. Segments do not overlap. `writtenBy` tells the last stage that wrote into the segment.
112
112
  - One PRG for each segment. A capture into a directory that has a capture removes the segment PRGs that the new `image.json` does not list. `removed` in the result names them. The capture keeps all other files.
113
113
  - `entry_state.json`: the registers, `$00` and `$01`, pages 0 to 3, the VIC, SID and CIA registers, and the vectors. `cia` gives the CIA timer latches and interrupt masks. `differsFromReset` lists the bytes that are not as a clean C64 has them at READY. A rebuild must make these bytes the same, because the program can read them.
114
- 5. Make sure that the result is the application: the code at the entry must not be the unpacker again. A segment can be data that a loader left, for example intro graphics. Keep it until other evidence shows that the program does not use it. Then capture again with `--exclude` for that range. Thus the source and the loader do not include the range.
114
+ 5. Make sure that the result is the application: the code at the entry must not be the unpacker again. A segment can be data that a loader or a cracktro left, for example intro graphics. Keep it until other evidence shows that the program does not use it. Then capture again with `--exclude` for that range. Thus the source and the loader do not include the range.
115
+ - Cut each range of a cracktro that the program does not read. A rebuild has no cracktro.
116
+ - Do not cut other unused bytes, for example leftovers of the development or an old copy of a routine. A rebuild keeps them.
117
+ - A crack change that the program reads, for example a credit text in the game, stays. Record it as a `crack` switch with the c64-knowledge skill.
115
118
  6. Put the capture into the knowledge with `image <out>/image.json` of the c64-knowledge skill. The knowledge keeps the segments, the entry, the entry state and the stages. The other skills read them there. The files in `<out>` are not necessary after that.
116
119
  7. Use `--range` only when you know the area of the program. Then the capture writes that one segment.
117
120
 
@@ -15,6 +15,8 @@ import {
15
15
  OPERAND_COLUMNS,
16
16
  PATCH_COLUMNS,
17
17
  REFERENCE_COLUMNS,
18
+ RELEASE_COLUMNS,
19
+ SWITCH_COLUMNS,
18
20
  REGION_COLUMNS,
19
21
  SUPPRESSION_COLUMNS,
20
22
  SYMBOL_COLUMNS,
@@ -25,6 +27,8 @@ import {
25
27
  toOperand,
26
28
  toPatch,
27
29
  toReference,
30
+ toRelease,
31
+ toSwitch,
28
32
  toRegion,
29
33
  toSuppression,
30
34
  toSymbol,
@@ -47,7 +51,11 @@ export const CONFLICT_RULES = {
47
51
  "suppression-symbol": "the same symbol suppression two times",
48
52
  "suppression-reference": "the same reference suppression two times",
49
53
  "suppression-region": "region suppressions that overlap",
50
- patch: "patches that overlap",
54
+ patch: "patches that overlap and do not have the same range",
55
+ "patch-switch": "two patches of one switch at one range",
56
+ switch: "two switches with one name",
57
+ release: "two releases with one label",
58
+ "release-base": "two base releases",
51
59
  macro: "two macros with one name",
52
60
  "macro-use": "macro uses that overlap",
53
61
  } as const;
@@ -71,8 +79,11 @@ interface TableRule {
71
79
  entity: HistoryEntry["entity"];
72
80
  columns: string;
73
81
  map: (raw: Raw) => HistoryEntry["row"];
74
- /** The columns that must differ between current rows, or "overlap" for address ranges. */
75
- key: readonly string[] | "overlap";
82
+ /**
83
+ * The columns that must differ between current rows, "overlap" for address
84
+ * ranges, or "partial" for ranges that may only overlap when they are equal.
85
+ */
86
+ key: readonly string[] | "overlap" | "partial";
76
87
  /** Rows of the table that the rule is about. */
77
88
  where?: string;
78
89
  }
@@ -99,7 +110,12 @@ const RULES: readonly TableRule[] = [
99
110
  where: "entity = 'reference'",
100
111
  },
101
112
  { rule: "suppression-region", table: "suppressions", entity: "suppression", columns: SUPPRESSION_COLUMNS, map: toSuppression, key: "overlap", where: "entity = 'region'" },
102
- { rule: "patch", table: "patches", entity: "patch", columns: PATCH_COLUMNS, map: toPatch, key: "overlap" },
113
+ // Patches of different switches at the same range are alternatives; any other overlap is a conflict.
114
+ { rule: "patch", table: "patches", entity: "patch", columns: PATCH_COLUMNS, map: toPatch, key: "partial" },
115
+ { rule: "patch-switch", table: "patches", entity: "patch", columns: PATCH_COLUMNS, map: toPatch, key: ["start_address", "end_address", "switch_name"] },
116
+ { rule: "switch", table: "switches", entity: "switch", columns: SWITCH_COLUMNS, map: toSwitch, key: ["name"] },
117
+ { rule: "release", table: "releases", entity: "release", columns: RELEASE_COLUMNS, map: toRelease, key: ["label"] },
118
+ { rule: "release-base", table: "releases", entity: "release", columns: RELEASE_COLUMNS, map: toRelease, key: ["base"], where: "base = 1" },
103
119
  { rule: "macro", table: "macros", entity: "macro", columns: MACRO_COLUMNS, map: toMacro, key: ["name"] },
104
120
  { rule: "macro-use", table: "macro_uses", entity: "macro-use", columns: MACRO_USE_COLUMNS, map: toMacroUse, key: "overlap" },
105
121
  ];
@@ -127,8 +143,12 @@ function sameKey(db: DatabaseSync, rule: TableRule, key: readonly string[]): Con
127
143
  return [...groups.values()];
128
144
  }
129
145
 
130
- /** The current rows of one rule whose address ranges overlap, in groups of rows that overlap in a chain. */
131
- function overlapping(db: DatabaseSync, rule: TableRule): Conflict[] {
146
+ /**
147
+ * The current rows of one rule whose address ranges overlap, in groups of rows
148
+ * that overlap in a chain. With `sameRange`, a group whose rows all have one
149
+ * range is no conflict.
150
+ */
151
+ function overlapping(db: DatabaseSync, rule: TableRule, sameRange = false): Conflict[] {
132
152
  const rows = db
133
153
  .prepare(`SELECT ${rule.columns}, id FROM ${sqlName(rule.table)} WHERE valid_to_revision IS NULL${rule.where === undefined ? "" : ` AND ${rule.where}`} ORDER BY space, start_address, end_address`)
134
154
  .all() as Raw[];
@@ -146,13 +166,17 @@ function overlapping(db: DatabaseSync, rule: TableRule): Conflict[] {
146
166
  end = raw.end_address as number;
147
167
  }
148
168
  if (group !== undefined && group.rows.length > 1) conflicts.push(group);
149
- return conflicts;
169
+ if (!sameRange) return conflicts;
170
+ return conflicts.filter((conflict) => {
171
+ const [first, ...rest] = conflict.rows.map((entry) => entry.row as { start: number; end: number });
172
+ return rest.some((row) => row.start !== first!.start || row.end !== first!.end);
173
+ });
150
174
  }
151
175
 
152
176
  /** Every conflict of the knowledge, rule by rule; the rows of each, oldest first. */
153
177
  export function conflicts(db: DatabaseSync | undefined): Conflict[] {
154
178
  if (db === undefined) return [];
155
- return RULES.flatMap((rule) => (rule.key === "overlap" ? overlapping(db, rule) : sameKey(db, rule, rule.key))).map((conflict) => ({ ...conflict, rows: conflict.rows.sort(byAge) }));
179
+ return RULES.flatMap((rule) => (rule.key === "overlap" || rule.key === "partial" ? overlapping(db, rule, rule.key === "partial") : sameKey(db, rule, rule.key))).map((conflict) => ({ ...conflict, rows: conflict.rows.sort(byAge) }));
156
180
  }
157
181
 
158
182
  /** The table of a conflict rule. */
@@ -12,6 +12,8 @@ import {
12
12
  OPERAND_COLUMNS,
13
13
  PATCH_COLUMNS,
14
14
  REFERENCE_COLUMNS,
15
+ RELEASE_COLUMNS,
16
+ SWITCH_COLUMNS,
15
17
  REGION_COLUMNS,
16
18
  resolveRevision,
17
19
  SUPPRESSION_COLUMNS,
@@ -23,6 +25,8 @@ import {
23
25
  toOperand,
24
26
  toPatch,
25
27
  toReference,
28
+ toRelease,
29
+ toSwitch,
26
30
  toRegion,
27
31
  toSuppression,
28
32
  toSymbol,
@@ -33,6 +37,8 @@ import {
33
37
  type OperandRow,
34
38
  type PatchRow,
35
39
  type ReferenceRow,
40
+ type ReleaseRow,
41
+ type SwitchRow,
36
42
  type RegionRow,
37
43
  type SuppressionRow,
38
44
  type SymbolRow,
@@ -101,6 +107,8 @@ export type HistoryEntry =
101
107
  | { entity: "module"; row: ModuleRow; from: string; to?: string }
102
108
  | { entity: "operand"; row: OperandRow; from: string; to?: string }
103
109
  | { entity: "patch"; row: PatchRow; from: string; to?: string }
110
+ | { entity: "switch"; row: SwitchRow; from: string; to?: string }
111
+ | { entity: "release"; row: ReleaseRow; from: string; to?: string }
104
112
  | { entity: "macro"; row: MacroRow; from: string; to?: string }
105
113
  | { entity: "macro-use"; row: MacroUseRow; from: string; to?: string };
106
114
 
@@ -170,6 +178,14 @@ export function historyOfMacro(db: DatabaseSync | undefined, name: string, space
170
178
  return [...macros, ...uses].sort(bySequence);
171
179
  }
172
180
 
181
+ /** Every row of a switch with this name and every patch of it, oldest first. */
182
+ export function historyOfSwitch(db: DatabaseSync | undefined, name: string, space: Space = DEFAULT_SPACE): HistoryEntry[] {
183
+ if (db === undefined) return [];
184
+ const switches = (db.prepare(`SELECT ${SWITCH_COLUMNS}, valid_to_revision FROM switches WHERE space = ? AND name = ?`).all(space, name) as Raw[]).map((raw) => entry("switch", toSwitch(raw), raw));
185
+ const patches = (db.prepare(`SELECT ${PATCH_COLUMNS}, valid_to_revision FROM patches WHERE space = ? AND switch_name = ?`).all(space, name) as Raw[]).map((raw) => entry("patch", toPatch(raw), raw));
186
+ return [...switches, ...patches].sort(bySequence);
187
+ }
188
+
173
189
  /** Every symbol row of a space that ever had this name, oldest first: a name can move between addresses. */
174
190
  export function historyNamed(db: DatabaseSync | undefined, name: string, space: Space = DEFAULT_SPACE): HistoryEntry[] {
175
191
  if (db === undefined) return [];
@@ -247,6 +263,8 @@ export function revision(db: DatabaseSync | undefined, text: string): RevisionCh
247
263
  ["module", "modules", MODULE_COLUMNS, toModule],
248
264
  ["operand", "operands", OPERAND_COLUMNS, toOperand],
249
265
  ["patch", "patches", PATCH_COLUMNS, toPatch],
266
+ ["switch", "switches", SWITCH_COLUMNS, toSwitch],
267
+ ["release", "releases", RELEASE_COLUMNS, toRelease],
250
268
  ["macro", "macros", MACRO_COLUMNS, toMacro],
251
269
  ["macro-use", "macro_uses", MACRO_USE_COLUMNS, toMacroUse],
252
270
  ] as const;
@@ -6,7 +6,7 @@ import type { DatabaseSync } from "node:sqlite";
6
6
 
7
7
  import type { AddressRange } from "../c64.ts";
8
8
  import { Refusal } from "../errors.ts";
9
- import { DEFAULT_SPACE, type CommentPlacement, type OperandSelect, type Origin, type ReferenceKind, type RegionType, type Space, type SuppressionEntity, type SymbolKind } from "./schema.ts";
9
+ import { DEFAULT_SPACE, type CommentPlacement, type OperandSelect, type Origin, type ReferenceKind, type RegionType, type Space, type SuppressionEntity, type SwitchKind, type SymbolKind } from "./schema.ts";
10
10
  import { NO_REVISION } from "./text.ts";
11
11
 
12
12
  export interface SymbolRow {
@@ -86,8 +86,10 @@ export interface OperandRow {
86
86
  }
87
87
 
88
88
  /**
89
- * Code that replaces [start, end] when the build defines the switch as 1
90
- *. The code fits the range; NOP fills the rest. Empty code is only NOP.
89
+ * Code that replaces [start, end] when its switch does not have its base value:
90
+ * the program bytes are the base release, so the code is the other state. The
91
+ * code fits the range; NOP fills the rest. Empty code is only NOP. Patches of
92
+ * different switches can have the same range: they are alternatives.
91
93
  */
92
94
  export interface PatchRow {
93
95
  space: Space;
@@ -100,6 +102,30 @@ export interface PatchRow {
100
102
  revision: string;
101
103
  }
102
104
 
105
+ /** A switch of the patches: what it changes, its value in the default build, and the releases that have it on. */
106
+ export interface SwitchRow {
107
+ space: Space;
108
+ name: string;
109
+ kind: SwitchKind;
110
+ default: 0 | 1;
111
+ releases: string[];
112
+ comment?: string;
113
+ origin: Extract<Origin, "user" | "llm">;
114
+ revision: string;
115
+ }
116
+
117
+ /** A release of the program: its project file with the SHA-256, and whether its bytes are the program of the knowledge. */
118
+ export interface ReleaseRow {
119
+ space: Space;
120
+ label: string;
121
+ file: string;
122
+ sha256: string;
123
+ base: boolean;
124
+ comment?: string;
125
+ origin: Extract<Origin, "user" | "llm">;
126
+ revision: string;
127
+ }
128
+
103
129
  /** An ACME macro of the generated source. The body names a parameter with a dot in front: .dst. */
104
130
  export interface MacroRow {
105
131
  space: Space;
@@ -136,6 +162,8 @@ export const SUPPRESSION_COLUMNS = "space, entity, start_address, end_address, t
136
162
  export const MODULE_COLUMNS = "space, start_address, file, title, origin, valid_from_revision";
137
163
  export const OPERAND_COLUMNS = "space, address, selector, symbol, offset, expression, origin, valid_from_revision";
138
164
  export const PATCH_COLUMNS = "space, start_address, end_address, switch_name, code, comment, origin, valid_from_revision";
165
+ export const SWITCH_COLUMNS = "space, name, kind, default_value, releases, comment, origin, valid_from_revision";
166
+ export const RELEASE_COLUMNS = "space, label, file, sha256, base, comment, origin, valid_from_revision";
139
167
  export const MACRO_COLUMNS = "space, name, params, body, comment, origin, valid_from_revision";
140
168
  export const MACRO_USE_COLUMNS = "space, start_address, end_address, macro, args, origin, valid_from_revision";
141
169
 
@@ -219,6 +247,34 @@ export function toPatch(row: Raw): PatchRow {
219
247
  return patch;
220
248
  }
221
249
 
250
+ export function toSwitch(row: Raw): SwitchRow {
251
+ const value: SwitchRow = {
252
+ space: row.space as Space,
253
+ name: row.name as string,
254
+ kind: row.kind as SwitchKind,
255
+ default: row.default_value === 1 ? 1 : 0,
256
+ releases: items(row.releases as string),
257
+ origin: row.origin as SwitchRow["origin"],
258
+ revision: row.valid_from_revision as string,
259
+ };
260
+ if (row.comment !== null && row.comment !== undefined) value.comment = row.comment as string;
261
+ return value;
262
+ }
263
+
264
+ export function toRelease(row: Raw): ReleaseRow {
265
+ const release: ReleaseRow = {
266
+ space: row.space as Space,
267
+ label: row.label as string,
268
+ file: row.file as string,
269
+ sha256: row.sha256 as string,
270
+ base: row.base === 1,
271
+ origin: row.origin as ReleaseRow["origin"],
272
+ revision: row.valid_from_revision as string,
273
+ };
274
+ if (row.comment !== null && row.comment !== undefined) release.comment = row.comment as string;
275
+ return release;
276
+ }
277
+
222
278
  export function toMacro(row: Raw): MacroRow {
223
279
  const macro: MacroRow = { space: row.space as Space, name: row.name as string, params: items(row.params as string), body: row.body as string, origin: row.origin as MacroRow["origin"], revision: row.valid_from_revision as string };
224
280
  if (row.comment !== null && row.comment !== undefined) macro.comment = row.comment as string;
@@ -437,6 +493,44 @@ export function macroUsesOverlapping(db: DatabaseSync | undefined, start: number
437
493
  .map((row) => toMacroUse(row as Raw));
438
494
  }
439
495
 
496
+ export function switchNamed(db: DatabaseSync | undefined, name: string, space: Space = DEFAULT_SPACE): SwitchRow | undefined {
497
+ const row = db?.prepare(`SELECT ${SWITCH_COLUMNS} FROM current_switches WHERE space = ? AND name = ?`).get(space, name) as Raw | undefined;
498
+ return row === undefined ? undefined : toSwitch(row);
499
+ }
500
+
501
+ /** Current switches of a space, by name. */
502
+ export function listSwitches(db: DatabaseSync | undefined, origins?: OriginFilter, space: Space = DEFAULT_SPACE): SwitchRow[] {
503
+ if (db === undefined) return [];
504
+ return db
505
+ .prepare(`SELECT ${SWITCH_COLUMNS} FROM current_switches WHERE space = ? ORDER BY name`)
506
+ .all(space)
507
+ .map((row) => toSwitch(row as Raw))
508
+ .filter(kept(origins));
509
+ }
510
+
511
+ export function releaseLabeled(db: DatabaseSync | undefined, label: string, space: Space = DEFAULT_SPACE): ReleaseRow | undefined {
512
+ const row = db?.prepare(`SELECT ${RELEASE_COLUMNS} FROM current_releases WHERE space = ? AND label = ?`).get(space, label) as Raw | undefined;
513
+ return row === undefined ? undefined : toRelease(row);
514
+ }
515
+
516
+ /** Current releases of a space: the base release first, then by label. */
517
+ export function listReleases(db: DatabaseSync | undefined, origins?: OriginFilter, space: Space = DEFAULT_SPACE): ReleaseRow[] {
518
+ if (db === undefined) return [];
519
+ return db
520
+ .prepare(`SELECT ${RELEASE_COLUMNS} FROM current_releases WHERE space = ? ORDER BY base DESC, label`)
521
+ .all(space)
522
+ .map((row) => toRelease(row as Raw))
523
+ .filter(kept(origins));
524
+ }
525
+
526
+ /**
527
+ * The value of a switch in the program of the knowledge: 1 when the base
528
+ * release has it on. A patch holds the code of the other value.
529
+ */
530
+ export function baseValue(row: Pick<SwitchRow, "releases">, base: string | undefined): 0 | 1 {
531
+ return base !== undefined && row.releases.includes(base) ? 1 : 0;
532
+ }
533
+
440
534
  export function macroNamed(db: DatabaseSync | undefined, name: string, space: Space = DEFAULT_SPACE): MacroRow | undefined {
441
535
  const row = db?.prepare(`SELECT ${MACRO_COLUMNS} FROM current_macros WHERE space = ? AND name = ?`).get(space, name) as Raw | undefined;
442
536
  return row === undefined ? undefined : toMacro(row);
@@ -585,7 +679,7 @@ export function listSpaces(db: DatabaseSync | undefined): Space[] {
585
679
  if (db === undefined) return [];
586
680
  const rows = db
587
681
  .prepare(
588
- `SELECT space FROM current_symbols UNION SELECT space FROM current_analyzer_names UNION SELECT space FROM current_regions UNION SELECT space FROM current_comments UNION SELECT space FROM current_references UNION SELECT space FROM current_suppressions UNION SELECT space FROM current_modules UNION SELECT space FROM current_operands UNION SELECT space FROM current_patches UNION SELECT space FROM current_macros UNION SELECT space FROM current_macro_uses UNION SELECT space FROM current_memory UNION SELECT space FROM current_entries UNION SELECT space FROM current_coverage`,
682
+ `SELECT space FROM current_symbols UNION SELECT space FROM current_analyzer_names UNION SELECT space FROM current_regions UNION SELECT space FROM current_comments UNION SELECT space FROM current_references UNION SELECT space FROM current_suppressions UNION SELECT space FROM current_modules UNION SELECT space FROM current_operands UNION SELECT space FROM current_patches UNION SELECT space FROM current_switches UNION SELECT space FROM current_releases UNION SELECT space FROM current_macros UNION SELECT space FROM current_macro_uses UNION SELECT space FROM current_memory UNION SELECT space FROM current_entries UNION SELECT space FROM current_coverage`,
589
683
  )
590
684
  .all() as Array<{ space: Space }>;
591
685
  const order = (space: Space) => (space === "c64" ? -2 : space === "drive8" ? -1 : Number(space.slice(4)));