@henols/c64-re-tools 2.7.0 → 2.8.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.
Files changed (69) hide show
  1. package/package.json +1 -1
  2. package/skills/c64-assembler/SKILL.md +23 -38
  3. package/skills/c64-assembler/scripts/assembler.ts +114 -16
  4. package/skills/c64-basic/SKILL.md +11 -31
  5. package/skills/c64-basic/scripts/basic.ts +4 -1
  6. package/skills/c64-development/SKILL.md +2 -2
  7. package/skills/c64-disk/SKILL.md +11 -32
  8. package/skills/c64-docs/SKILL.md +27 -45
  9. package/skills/c64-docs/references/page-types.md +20 -18
  10. package/skills/c64-docs/references/style.md +10 -4
  11. package/skills/c64-docs/scripts/docs.ts +13 -2
  12. package/skills/c64-docs/scripts/lib/reference.ts +47 -5
  13. package/skills/c64-knowledge/SKILL.md +138 -267
  14. package/skills/c64-knowledge/references/batches.md +48 -0
  15. package/skills/c64-knowledge/references/coverage.md +29 -0
  16. package/skills/c64-knowledge/references/source-knowledge.md +72 -0
  17. package/skills/c64-knowledge/references/start-screen.md +44 -0
  18. package/skills/c64-knowledge/scripts/knowledge.ts +266 -61
  19. package/skills/c64-knowledge/scripts/lib/check.ts +133 -0
  20. package/skills/c64-knowledge/scripts/lib/listing.ts +72 -8
  21. package/skills/c64-memory-map/SKILL.md +11 -32
  22. package/skills/c64-packer/SKILL.md +11 -31
  23. package/skills/c64-provenance/SKILL.md +40 -62
  24. package/skills/c64-provenance/scripts/lib/leftovers.ts +8 -3
  25. package/skills/c64-provenance/scripts/provenance.ts +64 -55
  26. package/skills/c64-reverse-engineering/SKILL.md +20 -47
  27. package/skills/c64-reverse-engineering/references/comment-check.md +42 -0
  28. package/skills/c64-reverse-engineering/references/versions.md +47 -0
  29. package/skills/c64-source/SKILL.md +43 -235
  30. package/skills/c64-source/references/export.md +50 -0
  31. package/skills/c64-source/references/loader.md +78 -0
  32. package/skills/c64-source/references/source-format.md +46 -0
  33. package/skills/c64-source/scripts/lib/export.ts +20 -7
  34. package/skills/c64-source/scripts/lib/loader.ts +116 -104
  35. package/skills/c64-source/scripts/source.ts +62 -52
  36. package/skills/c64-static-analysis/SKILL.md +51 -52
  37. package/skills/c64-static-analysis/scripts/lib/coverage.ts +55 -2
  38. package/skills/c64-static-analysis/scripts/lib/idioms.ts +28 -9
  39. package/skills/c64-static-analysis/scripts/static-analysis.ts +69 -15
  40. package/skills/c64-testing/SKILL.md +77 -59
  41. package/skills/c64-testing/references/recording-format.md +5 -79
  42. package/skills/c64-testing/references/scenario-format.md +4 -12
  43. package/skills/c64-testing/scripts/lib/play.ts +16 -8
  44. package/skills/c64-testing/scripts/lib/recording.ts +76 -9
  45. package/skills/c64-testing/scripts/lib/replay.ts +14 -0
  46. package/skills/c64-testing/scripts/lib/runs.ts +112 -1
  47. package/skills/c64-testing/scripts/lib/scenario.ts +12 -6
  48. package/skills/c64-testing/scripts/lib/start-screen.ts +27 -0
  49. package/skills/c64-testing/scripts/testing.ts +37 -15
  50. package/skills/c64-unpacker/SKILL.md +10 -30
  51. package/skills/emulator/SKILL.md +7 -36
  52. package/src/build-name.ts +12 -1
  53. package/src/knowledge/history.ts +8 -0
  54. package/src/knowledge/program.ts +73 -1
  55. package/src/knowledge/read.ts +46 -2
  56. package/src/knowledge/recording-files.ts +32 -0
  57. package/src/knowledge/schema.ts +3 -1
  58. package/src/knowledge/separate.ts +90 -3
  59. package/src/knowledge/start-screen.ts +99 -17
  60. package/src/knowledge/text.ts +2 -1
  61. package/src/knowledge/write.ts +15 -8
  62. package/src/loader.ts +167 -0
  63. package/src/native/c64run.ts +11 -0
  64. package/src/native/decompiler/analyze.ts +7 -6
  65. package/src/native/decompiler/walk.ts +32 -2
  66. package/src/native/dxa.ts +4 -4
  67. package/src/native/types.ts +32 -4
  68. package/src/script.ts +87 -17
  69. package/skills/c64-export/SKILL.md +0 -63
@@ -3,7 +3,9 @@
3
3
  // region of knowledge, whether call and jump references or the run on from
4
4
  // its last instruction reach it from a root (the entry, and the NMI, RESET
5
5
  // and IRQ vectors at $fffa-$ffff when the image holds them); and what the program reads
6
- // or executes outside the image. Evidence only: nothing here decides which
6
+ // or executes outside the image. A region that nothing reaches is unknown, not
7
+ // dead, while the program has a flow whose targets the knowledge does not give,
8
+ // or when no coverage shows what ran. Evidence only: nothing here decides which
7
9
  // bytes the publisher shipped.
8
10
 
9
11
  import { type AddressRange, COVERAGE, executedRamCode, instructionLength } from "../c64.ts";
@@ -21,6 +23,8 @@ export interface SeparationInput {
21
23
  coverage?: Uint8Array;
22
24
  codeRegions: Array<AddressRange & { type: string }>;
23
25
  references: Array<{ from: number; to: number; kind: string }>;
26
+ /** The instructions with a reference of the user or the LLM from them: the LLM recorded the targets of their flows. */
27
+ resolvedSites?: ReadonlySet<number>;
24
28
  /** More roots after the entry and the hardware vectors, for example code that a run executed. */
25
29
  roots?: Root[];
26
30
  }
@@ -37,6 +41,18 @@ export interface CodeRegionEvidence extends AddressRange {
37
41
  reachable?: boolean;
38
42
  /** Absent without coverage. */
39
43
  executed?: boolean;
44
+ /** Not reached and not executed, but an unresolved flow can go there, or no coverage shows that it did not run. */
45
+ unknown?: true;
46
+ }
47
+
48
+ /**
49
+ * A flow whose targets the knowledge does not give: a JMP (indirect) through
50
+ * a vector that a run wrote or that is not in the image, or a JMP or JSR whose
51
+ * address bytes a run wrote.
52
+ */
53
+ export interface UnresolvedFlow {
54
+ at: number;
55
+ kind: "indirect-jump" | "written-operand";
40
56
  }
41
57
 
42
58
  /** An address where the reachability starts, and why: the entry, a hardware vector in the image, or a root that the caller gives. */
@@ -57,6 +73,8 @@ export interface Separation {
57
73
  * pieces of code with gaps of up to two operand bytes.
58
74
  */
59
75
  outside: { read: AddressRange[]; executed: AddressRange[]; generated: AddressRange[] };
76
+ /** The unresolved flows of the code regions: while one exists, an unreached code region is unknown. */
77
+ unresolved: UnresolvedFlow[];
60
78
  }
61
79
 
62
80
  const SYSTEM_PAGES_END = 0x03ff;
@@ -97,6 +115,73 @@ export function fallThrough(region: AddressRange, memory: Uint8Array): number |
97
115
  return NO_FALL_THROUGH.has(memory[last]!) || at > 0xffff ? undefined : at;
98
116
  }
99
117
 
118
+ /** The instruction starts of code regions: each region runs from its start, one instruction after the other. */
119
+ export function regionStarts(regions: readonly AddressRange[], memory: Uint8Array): number[] {
120
+ const starts: number[] = [];
121
+ for (const region of regions) for (let at = region.start; at <= region.end; at += instructionLength(memory[at]!)) starts.push(at);
122
+ return starts.sort((a, b) => a - b);
123
+ }
124
+
125
+ /**
126
+ * The vectors that the program sets with its own immediates: an LDA, LDX or
127
+ * LDY # and a store to N, and the same to N + 1, in one run of instructions.
128
+ * A JMP (N) then goes where those immediates point, which the flows of the
129
+ * stores give.
130
+ */
131
+ export function immediateVectors(starts: readonly number[], memory: Uint8Array): Set<number> {
132
+ const stored = new Set<number>();
133
+ let registers: { a?: number | undefined; x?: number | undefined; y?: number | undefined } = {};
134
+ let previousEnd = -2;
135
+ for (const at of [...starts].sort((a, b) => a - b)) {
136
+ if (at > previousEnd + 1) registers = {};
137
+ const opcode = memory[at]!;
138
+ const length = instructionLength(opcode);
139
+ previousEnd = at + length - 1;
140
+ const operand = length === 3 ? memory[at + 1]! | (memory[(at + 2) & 0xffff]! << 8) : memory[(at + 1) & 0xffff]!;
141
+ const store = (value: number | undefined) => {
142
+ if (value !== undefined) stored.add(operand);
143
+ };
144
+ switch (opcode) {
145
+ case 0xa9: registers.a = operand; break;
146
+ case 0xa2: registers.x = operand; break;
147
+ case 0xa0: registers.y = operand; break;
148
+ case 0x85: case 0x8d: store(registers.a); break;
149
+ case 0x86: case 0x8e: store(registers.x); break;
150
+ case 0x84: case 0x8c: store(registers.y); break;
151
+ case 0xaa: registers.x = registers.a; break;
152
+ case 0xa8: registers.y = registers.a; break;
153
+ case 0x8a: registers.a = registers.x; break;
154
+ case 0x98: registers.a = registers.y; break;
155
+ default: registers = {};
156
+ }
157
+ if (NO_FALL_THROUGH.has(opcode)) registers = {};
158
+ }
159
+ return new Set([...stored].filter((address) => stored.has((address + 1) & 0xffff)));
160
+ }
161
+
162
+ /**
163
+ * The unresolved flows of the instructions at `starts`. A flow is resolved
164
+ * when a reference of the user or the LLM goes from it. An indirect jump is
165
+ * also resolved when the program's own immediates set its vector, or when the
166
+ * vector is in the image and no run wrote it.
167
+ */
168
+ export function unresolvedFlows(input: { starts: readonly number[]; memory: Uint8Array; inImage: (address: number) => boolean; coverage?: Uint8Array | undefined; resolvedSites?: ReadonlySet<number> | undefined }): UnresolvedFlow[] {
169
+ const written = (address: number) => input.coverage !== undefined && (input.coverage[address & 0xffff]! & COVERAGE.ramWrite) !== 0;
170
+ const vectors = immediateVectors(input.starts, input.memory);
171
+ const flows: UnresolvedFlow[] = [];
172
+ for (const at of input.starts) {
173
+ if (input.resolvedSites?.has(at) === true) continue;
174
+ const opcode = input.memory[at]!;
175
+ if (opcode === 0x6c) {
176
+ const vector = input.memory[(at + 1) & 0xffff]! | (input.memory[(at + 2) & 0xffff]! << 8);
177
+ if (vectors.has(vector)) continue;
178
+ if (input.inImage(vector) && input.inImage((vector + 1) & 0xffff) && !written(vector) && !written(vector + 1)) continue;
179
+ flows.push({ at, kind: "indirect-jump" });
180
+ } else if ((opcode === 0x4c || opcode === 0x20) && (written(at + 1) || written(at + 2))) flows.push({ at, kind: "written-operand" });
181
+ }
182
+ return flows;
183
+ }
184
+
100
185
  /** The most instructions outside the code regions that the run on from a region goes through, for example an instruction in a dual-use region. */
101
186
  const MAX_RUN_ON = 16;
102
187
 
@@ -190,13 +275,15 @@ export function separate(input: SeparationInput): Separation {
190
275
  queue.push(to);
191
276
  }
192
277
  }
278
+ const unresolved = unresolvedFlows({ starts: regionStarts(regions, input.memory), memory: input.memory, inImage, coverage: input.coverage, resolvedSites: input.resolvedSites });
193
279
  const codeRegions = regions.map((region, index): CodeRegionEvidence => {
194
280
  let ran: boolean | undefined;
195
281
  if (input.coverage !== undefined) {
196
282
  ran = false;
197
283
  for (let address = region.start; address <= region.end && !ran; address++) ran = executed[address] === 1;
198
284
  }
199
- return { start: region.start, end: region.end, type: region.type, ...(roots.length === 0 ? {} : { reachable: reached.has(index) }), ...(ran === undefined ? {} : { executed: ran }) };
285
+ const unreached = roots.length > 0 && !reached.has(index) && ran !== true;
286
+ return { start: region.start, end: region.end, type: region.type, ...(roots.length === 0 ? {} : { reachable: reached.has(index) }), ...(ran === undefined ? {} : { executed: ran }), ...(unreached && (unresolved.length > 0 || input.coverage === undefined) ? { unknown: true as const } : {}) };
200
287
  });
201
288
 
202
289
  const read: number[] = [];
@@ -216,5 +303,5 @@ export function separate(input: SeparationInput): Separation {
216
303
  for (let address = from + 1; address < to; address++) if (inImage(address)) return false;
217
304
  return true;
218
305
  };
219
- return { roots, ranges, codeRegions, outside: { read: merge(read), executed: merge(ranOutside), generated: merge(generated, 2, outsideImage) } };
306
+ return { roots, ranges, codeRegions, outside: { read: merge(read), executed: merge(ranOutside), generated: merge(generated, 2, outsideImage) }, unresolved };
220
307
  }
@@ -4,7 +4,7 @@
4
4
  // stage needs no address from the user.
5
5
 
6
6
  import { Refusal } from "../errors.ts";
7
- import type { StartScreenMode } from "./schema.ts";
7
+ import { LEFTOVERS_SWITCH, START_SCREEN_SWITCH, type StartScreenMode } from "./schema.ts";
8
8
 
9
9
  /** The labels of the start screen in a generated loader: its wait for a key or a fire button, and the code after the wait. */
10
10
  export const START_SCREEN_WAIT = "loader_start_screen_wait";
@@ -12,6 +12,21 @@ export const START_SCREEN_CONTINUE = "loader_start_screen_continue";
12
12
  /** The label of the loader's jump to the entry, in ACME's symbol list. */
13
13
  export const LOADER_JUMP = "c64_source_loader_jump";
14
14
 
15
+ /**
16
+ * The wait and the code after the wait of the start screen that a build shows,
17
+ * from the symbols of the build; undefined when the build shows none. A build
18
+ * with START_SCREEN = 0 or LEFTOVERS = 1 has both labels but skips the screen
19
+ * (the start screen code of the generated source). A symbol file without the
20
+ * constants is a build with the default values: the screen is on.
21
+ */
22
+ export function startScreenLabels(symbols: ReadonlyMap<string, number>): { wait: number; continue: number } | undefined {
23
+ const wait = symbols.get(START_SCREEN_WAIT);
24
+ const resume = symbols.get(START_SCREEN_CONTINUE);
25
+ if (wait === undefined || resume === undefined) return undefined;
26
+ if ((symbols.get(START_SCREEN_SWITCH) ?? 1) === 0 || (symbols.get(LEFTOVERS_SWITCH) ?? 0) !== 0) return undefined;
27
+ return { wait, continue: resume };
28
+ }
29
+
15
30
  /** The fields of a start screen that the capture of a stage gives. */
16
31
  export interface StageScreen {
17
32
  mode: StartScreenMode;
@@ -37,34 +52,101 @@ export function capturedColourRam(state: Record<string, unknown> | undefined): U
37
52
  return bytes === undefined || bytes.length !== 1000 ? undefined : Uint8Array.from(bytes, (value) => value & 0x0f);
38
53
  }
39
54
 
55
+ /** How a refusal names the capture: the program that has no entry state, the capture, and how to capture it again. */
56
+ interface Named {
57
+ program: string;
58
+ capture: string;
59
+ again: string;
60
+ }
61
+
40
62
  /**
41
- * The start screen that the capture of a stage shows: its mode, its screen,
42
- * its bitmap or charset, its colours and the colour RAM. Refuses by name when
43
- * the capture does not show a start screen that the loader can show.
63
+ * The screen that the VIC-II of an entry state shows: its mode, its screen, its
64
+ * bitmap or charset and its colours of the border and the background, from the
65
+ * VIC-II registers and the VIC bank of CIA 2. Refuses by name when the capture
66
+ * does not show a screen that the loader can show.
44
67
  */
45
- export function startScreenOfStage(state: Record<string, unknown> | undefined, stage: string): StageScreen {
46
- const again = `Capture the stage again while it shows the screen, and put the capture into the project knowledge with image --space ${stage}.`;
68
+ function vicScreen(state: Record<string, unknown> | undefined, named: Named): Omit<StageScreen, "colourRam"> {
47
69
  const vic = ioBytes(state, "vic");
48
70
  const cia2 = ioBytes(state, "cia2");
49
- if (state === undefined || vic === undefined || vic.length < 0x2f || cia2 === undefined) throw new Refusal("not-found", `The program in ${stage} has no entry state with the VIC-II and CIA 2. ${again}`);
71
+ if (state === undefined || vic === undefined || vic.length < 0x2f || cia2 === undefined) throw new Refusal("not-found", `${named.program} has no entry state with the VIC-II and CIA 2. ${named.again}`);
50
72
  const [d011, d016, d018] = [vic[0x11]!, vic[0x16]!, vic[0x18]!];
51
- if ((d011 & 0x10) === 0) throw new Refusal("invalid-input", `The capture in ${stage} has the display off ($d011 = $${d011.toString(16).padStart(2, "0")}). ${again}`);
52
- if ((d011 & 0x40) !== 0) throw new Refusal("invalid-input", `The capture in ${stage} shows a screen in the extended colour mode, which a start screen does not have.`);
73
+ if ((d011 & 0x10) === 0) throw new Refusal("invalid-input", `${named.capture} has the display off ($d011 = $${d011.toString(16).padStart(2, "0")}). ${named.again}`);
74
+ if ((d011 & 0x40) !== 0) throw new Refusal("invalid-input", `${named.capture} shows a screen in the extended colour mode, which a start screen does not have.`);
53
75
  const bitmap = (d011 & 0x20) !== 0;
54
76
  const multicolour = (d016 & 0x10) !== 0;
55
- if (!bitmap && multicolour) throw new Refusal("invalid-input", `The capture in ${stage} shows a multicolour text screen, which a start screen does not have.`);
77
+ if (!bitmap && multicolour) throw new Refusal("invalid-input", `${named.capture} shows a multicolour text screen, which a start screen does not have.`);
56
78
  const bank = (3 - (cia2[0]! & 0x03)) << 14;
57
- const mode: StartScreenMode = bitmap ? (multicolour ? "multicolour" : "hires") : "text";
58
- const screen = bank + ((d018 >> 4) & 0x0f) * 0x400;
59
- const colourRam = mode === "hires" ? undefined : capturedColourRam(state);
60
- if (mode !== "hires" && colourRam === undefined) throw new Refusal("not-found", `The capture in ${stage} has no colour RAM: it is from an older version. ${again}`);
61
79
  return {
62
- mode,
63
- screen,
80
+ mode: bitmap ? (multicolour ? "multicolour" : "hires") : "text",
81
+ screen: bank + ((d018 >> 4) & 0x0f) * 0x400,
64
82
  ...(bitmap ? { bitmap: bank + ((d018 >> 3) & 1) * 0x2000 } : { charset: bank + ((d018 >> 1) & 7) * 0x800 }),
65
83
  border: vic[0x20]! & 0x0f,
66
84
  background: vic[0x21]! & 0x0f,
67
- ...(colourRam === undefined ? {} : { colourRam: true as const }),
68
85
  };
69
86
  }
70
87
 
88
+ /**
89
+ * The start screen that the capture of a stage shows: its mode, its screen,
90
+ * its bitmap or charset, its colours and the colour RAM. Refuses by name when
91
+ * the capture does not show a start screen that the loader can show.
92
+ */
93
+ export function startScreenOfStage(state: Record<string, unknown> | undefined, stage: string): StageScreen {
94
+ const again = `Capture the stage again while it shows the screen, and put the capture into the project knowledge with image --space ${stage}.`;
95
+ const shown = vicScreen(state, { program: `The program in ${stage}`, capture: `The capture in ${stage}`, again });
96
+ const colourRam = shown.mode === "hires" ? undefined : capturedColourRam(state);
97
+ if (shown.mode !== "hires" && colourRam === undefined) throw new Refusal("not-found", `The capture in ${stage} has no colour RAM: it is from an older version. ${again}`);
98
+ return { ...shown, ...(colourRam === undefined ? {} : { colourRam: true as const }) };
99
+ }
100
+
101
+ /** The bytes of the colour RAM. */
102
+ const COLOURS = 1000;
103
+
104
+ /**
105
+ * The first address of the program from $0400 where 1000 bytes hold the
106
+ * colours (the low 4 bits of each byte), outside $d000-$dfff, where the loader
107
+ * sees the I/O area. Undefined when the program has no such bytes.
108
+ */
109
+ export function findColours(colours: Uint8Array, byteAt: (address: number) => number | undefined): number | undefined {
110
+ for (let start = 0x0400; start + COLOURS - 1 <= 0xffff; start++) {
111
+ if (start <= 0xdfff && start + COLOURS - 1 >= 0xd000) continue;
112
+ let offset = 0;
113
+ while (offset < COLOURS) {
114
+ const byte = byteAt(start + offset);
115
+ if (byte === undefined || (byte & 0x0f) !== colours[offset]) break;
116
+ offset++;
117
+ }
118
+ if (offset === COLOURS) return start;
119
+ }
120
+ return undefined;
121
+ }
122
+
123
+ const CAPTURE_AGAIN = "Capture the program again while it shows the screen. Then give the image.json of that capture.";
124
+
125
+ /**
126
+ * The start screen in the program that a capture of the program shows: the
127
+ * mode, the addresses and the border and background colours from the VIC-II
128
+ * and CIA 2 of the capture. Refuses by name when the capture does not show a
129
+ * start screen that the loader can show.
130
+ */
131
+ export function startScreenOfCapture(state: Record<string, unknown> | undefined, path: string): Omit<StageScreen, "colourRam"> {
132
+ return vicScreen(state, { program: `The capture ${path}`, capture: `The capture ${path}`, again: CAPTURE_AGAIN });
133
+ }
134
+
135
+ /**
136
+ * The colour RAM of a capture as the program gives it: one colour, or the
137
+ * address of 1000 bytes that the program has (findColours). Refuses with the
138
+ * reason when the program cannot give the colours.
139
+ */
140
+ export function coloursOfCapture(state: Record<string, unknown> | undefined, path: string, byteAt: (address: number) => number | undefined): { colour: number } | { colours: number } {
141
+ const colours = capturedColourRam(state);
142
+ if (colours === undefined) throw new Refusal("not-found", `The capture ${path} has no colour RAM: it is from an older version. ${CAPTURE_AGAIN}`);
143
+ if (colours.every((colour) => colour === colours[0])) return { colour: colours[0]! };
144
+ const found = findColours(colours, byteAt);
145
+ if (found === undefined) {
146
+ throw new Refusal(
147
+ "not-found",
148
+ `The colour RAM of the capture ${path} has more than one colour, and the program of the knowledge has no 1000 bytes with these colours from $0400, outside $d000-$dfff. Thus the loader cannot set the colours. If a stage of the loading shows the screen, record the start screen of that stage.`,
149
+ );
150
+ }
151
+ return { colours: found };
152
+ }
@@ -172,11 +172,12 @@ export const TABLES: readonly TableSpec[] = [
172
172
  ],
173
173
  },
174
174
  // The releases of the program, and the one whose bytes are the program. The bytes of the other releases are in release_memory.jsonl.
175
+ // file and sha256 are the file that recorded the release and its SHA-256; a release of an earlier toolkit version has neither.
175
176
  {
176
177
  table: "releases",
177
178
  file: "releases.jsonl",
178
179
  sort: "label",
179
- fields: [space, field("label", "label", "text"), field("base", "base", "integer"), field("comment", "comment", "text", true), origin],
180
+ fields: [space, field("label", "label", "text"), field("base", "base", "integer"), field("file", "file", "text", true), field("sha256", "sha256", "text", true), field("comment", "comment", "text", true), origin],
180
181
  },
181
182
  {
182
183
  table: "macros",
@@ -281,8 +281,8 @@ export class Change {
281
281
 
282
282
  insertRelease(row: Omit<ReleaseRow, "revision">): void {
283
283
  this.#db
284
- .prepare("INSERT INTO releases (id, space, label, base, comment, origin, valid_from_revision) VALUES (?, ?, ?, ?, ?, ?, ?)")
285
- .run(this.#rowId(), row.space, row.label, row.base ? 1 : 0, row.comment ?? null, row.origin, this.id());
284
+ .prepare("INSERT INTO releases (id, space, label, base, file, sha256, comment, origin, valid_from_revision) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)")
285
+ .run(this.#rowId(), row.space, row.label, row.base ? 1 : 0, row.file ?? null, row.sha256 ?? null, row.comment ?? null, row.origin, this.id());
286
286
  }
287
287
 
288
288
  /** Bytes of a release other than the base release, as a memory row of the program holds them. */
@@ -1032,9 +1032,10 @@ function unswitchStep(db: DatabaseSync, change: Change, _origin: Origin, request
1032
1032
  /**
1033
1033
  * A release. `rows` are the bytes of a release other than the base release,
1034
1034
  * as memoryRows gives them: the address of each row and its bytes as hex. The
1035
- * base release has no bytes of its own: its bytes are the program.
1035
+ * base release has no bytes of its own: its bytes are the program. `file` and
1036
+ * `sha256` are the project file that the bytes come from and its SHA-256.
1036
1037
  */
1037
- type ReleaseRequest = InSpace & { label: string; base?: boolean; comment?: string; rows?: ReadonlyMap<number, string> };
1038
+ type ReleaseRequest = InSpace & { label: string; base?: boolean; file?: string; sha256?: string; comment?: string; rows?: ReadonlyMap<number, string> };
1038
1039
 
1039
1040
  function checkRelease(request: ReleaseRequest): void {
1040
1041
  checkSpace(request);
@@ -1046,6 +1047,8 @@ function checkRelease(request: ReleaseRequest): void {
1046
1047
  throw new Refusal("invalid-input", `The bytes of a release at ${formatC64Address(address & 0xffff)} are not a memory row.`);
1047
1048
  }
1048
1049
  }
1050
+ if (request.file !== undefined && (typeof request.file !== "string" || request.file.length === 0)) throw new Refusal("invalid-input", "The file of a release is a project path.");
1051
+ if (request.sha256 !== undefined && (typeof request.sha256 !== "string" || !/^[0-9a-f]{64}$/.test(request.sha256))) throw new Refusal("invalid-input", "The SHA-256 of a release file is 64 lowercase hex digits.");
1049
1052
  checkCommentText(request.comment, "A release comment");
1050
1053
  }
1051
1054
 
@@ -1054,12 +1057,16 @@ function releaseStep(db: DatabaseSync, change: Change, origin: Origin, request:
1054
1057
  const existing = releaseLabeled(db, request.label, space);
1055
1058
  const base = request.base ?? existing?.base ?? false;
1056
1059
  const comment = request.comment === undefined ? existing?.comment : request.comment.trim();
1060
+ // A release that is recorded again without its file keeps the file that it has.
1061
+ const file = request.file ?? existing?.file;
1062
+ const sha256 = request.file === undefined ? existing?.sha256 : request.sha256;
1063
+ const sameFile = existing?.file === file && existing?.sha256 === sha256;
1057
1064
  const held = db.prepare("SELECT id, address, bytes FROM current_release_memory WHERE space = ? AND label = ?").all(space, request.label) as Array<{ id: string; address: number; bytes: string }>;
1058
1065
  // A release without new bytes keeps its bytes. The base release has none: its bytes are the program.
1059
1066
  const wanted = base ? new Map<number, string>() : (request.rows ?? new Map(held.map((row) => [row.address, row.bytes])));
1060
1067
  if (!base && wanted.size === 0) throw new Refusal("invalid-input", `The release ${request.label} has no bytes. Give the file of the release.`);
1061
1068
  const sameBytes = held.length === wanted.size && held.every((row) => wanted.get(row.address) === row.bytes);
1062
- if (existing !== undefined && existing.base === base && existing.comment === comment && sameBytes && !confirms(existing.origin, origin)) return { current: existing };
1069
+ if (existing !== undefined && existing.base === base && existing.comment === comment && sameFile && sameBytes && !confirms(existing.origin, origin)) return { current: existing };
1063
1070
  const other = baseLabel(db, space);
1064
1071
  if (base && other !== undefined && other !== request.label) throw new Refusal("conflict", `The release ${other} is the base release. A space has one base release.`);
1065
1072
  // Every switch takes its base value from the base release: it cannot change under them.
@@ -1069,9 +1076,9 @@ function releaseStep(db: DatabaseSync, change: Change, origin: Origin, request:
1069
1076
  }
1070
1077
  const symbol = symbolNamed(db, `${RELEASE_DEFINE}${request.label}`, space);
1071
1078
  if (symbol !== undefined) throw new Refusal("conflict", `The build of the release defines ${RELEASE_DEFINE}${request.label}, and that is the name of the symbol at ${formatC64Address(symbol.address)}. Give the release another label.`);
1072
- if (existing === undefined || existing.base !== base || existing.comment !== comment || confirms(existing.origin, origin)) {
1079
+ if (existing === undefined || existing.base !== base || existing.comment !== comment || !sameFile || confirms(existing.origin, origin)) {
1073
1080
  if (existing !== undefined) change.close("releases", "space = ? AND label = ?", space, request.label);
1074
- change.insertRelease({ space, label: request.label, base, ...(comment === undefined ? {} : { comment }), origin: origin as ReleaseRow["origin"] });
1081
+ change.insertRelease({ space, label: request.label, base, ...(file === undefined ? {} : { file }), ...(sha256 === undefined ? {} : { sha256 }), ...(comment === undefined ? {} : { comment }), origin: origin as ReleaseRow["origin"] });
1075
1082
  }
1076
1083
  // Only the rows that changed: a changed byte changes one short line of the text.
1077
1084
  const kept = new Set<number>();
@@ -1667,7 +1674,7 @@ const KEYS = {
1667
1674
  releases: {
1668
1675
  columns: RELEASE_COLUMNS,
1669
1676
  map: toRelease,
1670
- key: (row: ReleaseRow) => `${row.space}|${row.label}|${row.base}|${row.comment ?? ""}|${row.origin}`,
1677
+ key: (row: ReleaseRow) => `${row.space}|${row.label}|${row.base}|${row.file ?? ""}|${row.sha256 ?? ""}|${row.comment ?? ""}|${row.origin}`,
1671
1678
  },
1672
1679
  start_screens: {
1673
1680
  columns: START_SCREEN_COLUMNS,
package/src/loader.ts ADDED
@@ -0,0 +1,167 @@
1
+ // The packed loader program of a generated source. Exomizer packs the loaded
2
+ // ranges of the build of main.asm (from $0400) and the build of loader.asm,
3
+ // which holds the copier and the bytes of pages 0-3, into one program that
4
+ // unpacks itself and starts the copier with all RAM visible ($01 = $34).
5
+ // c64-source packs it for the loader that it checks; c64-assembler packs it
6
+ // for other switch values, from the same files and with the same parts. The
7
+ // loaded ranges are the segments of the program without the leftovers: a
8
+ // leftover file of the source gives its range in its first line.
9
+
10
+ import { type AddressRange, formatC64Address, prgRange } from "./c64.ts";
11
+ import { compareBuild, mergedPrograms } from "./compare.ts";
12
+ import { Refusal } from "./errors.ts";
13
+ import { pack } from "./native/exomizer.ts";
14
+ import type { ToolContext } from "./native/run.ts";
15
+ import type { AssembledSymbol } from "./native/types.ts";
16
+
17
+ /** The label of the copier in loader.asm. In the packed form, its address is the copier address, where the unpack jumps. */
18
+ export const COPIER_SOURCE = "loader_copier_src";
19
+
20
+ /** The memory configuration at the start of the copier of the packed form: all RAM visible. */
21
+ export const PACKED_EXIT_MEMORY = 0x34;
22
+
23
+ /** The pages that the unpacker of Exomizer uses: the copier of the packed form writes them, so main.asm is packed from here. */
24
+ const PACKED_FROM = 0x0400;
25
+
26
+ /** The first line of a leftover file: `; Leftovers $xxxx-$yyyy: ...`. */
27
+ const LEFTOVER_RANGE = /^; Leftovers (\$[0-9a-f]{4})-(\$[0-9a-f]{4}):/m;
28
+
29
+ /** The range of a leftover file of a generated source, from its first line. Undefined for a text without that line. */
30
+ export function leftoverRange(text: string): AddressRange | undefined {
31
+ const found = LEFTOVER_RANGE.exec(text);
32
+ return found === null ? undefined : { start: Number.parseInt(found[1]!.slice(1), 16), end: Number.parseInt(found[2]!.slice(1), 16) };
33
+ }
34
+
35
+ const show = (range: AddressRange) => `${formatC64Address(range.start)}-${formatC64Address(range.end)}`;
36
+
37
+ /** The parts of `range` outside every hole, in address order. */
38
+ function without(range: AddressRange, holes: readonly AddressRange[]): AddressRange[] {
39
+ let pieces = [range];
40
+ for (const hole of holes) {
41
+ pieces = pieces.flatMap((piece) => {
42
+ if (hole.end < piece.start || hole.start > piece.end) return [piece];
43
+ return [
44
+ ...(hole.start > piece.start ? [{ start: piece.start, end: hole.start - 1 }] : []),
45
+ ...(hole.end < piece.end ? [{ start: hole.end + 1, end: piece.end }] : []),
46
+ ];
47
+ });
48
+ }
49
+ return pieces;
50
+ }
51
+
52
+ /**
53
+ * The ranges that the packed loader loads from a build of main.asm: the
54
+ * segments of the program without the leftovers. Refuses what only the loader
55
+ * of generate can have: a start screen of a captured stage, which is a program
56
+ * of its own in front of the packed loader, and a segment below $0400, whose
57
+ * bytes loader.asm holds with the switch values of generate.
58
+ */
59
+ export function packedRanges(segments: readonly AddressRange[], leftovers: readonly AddressRange[], stage: string | undefined): AddressRange[] {
60
+ if (stage !== undefined) {
61
+ throw new Refusal("invalid-input", `The start screen is of the captured stage ${stage}, and only the generation of the source with the loader makes that loader program. Set the switch values in config.asm, and generate the source with the loader.`);
62
+ }
63
+ const loaded = [...segments].sort((a, b) => a.start - b.start).flatMap((segment) => without(segment, leftovers));
64
+ const low = loaded.find((range) => range.start < PACKED_FROM);
65
+ if (low !== undefined) {
66
+ throw new Refusal("invalid-input", `The segment ${show(low)} starts below $0400, and loader.asm holds its bytes there with the switch values of generate. Set the switch values in config.asm, and generate the source with the loader.`);
67
+ }
68
+ return loaded;
69
+ }
70
+
71
+ /**
72
+ * Checks the two builds of the packed form before the pack: the build of
73
+ * main.asm holds each loaded range, and the build of loader.asm, which holds
74
+ * the bytes of the program between its free ranges, has the bytes of the build
75
+ * of main.asm there. A patch of a switch between the free ranges changes them,
76
+ * and the copier build would put the old bytes back. Refuses by name.
77
+ */
78
+ export function checkPackedBuilds(main: Uint8Array, copier: Uint8Array, loaded: readonly AddressRange[]): void {
79
+ const program = prgRange(main);
80
+ const outside = loaded.find((range) => range.start < program.start || range.end > program.end);
81
+ if (outside !== undefined) {
82
+ throw new Refusal("invalid-input", `The build of main.asm does not hold ${show(outside)} of the program in the knowledge. Generate the source again from the knowledge.`);
83
+ }
84
+ const build = prgRange(copier);
85
+ for (const range of loaded) {
86
+ for (let address = Math.max(range.start, build.start); address <= Math.min(range.end, build.end); address++) {
87
+ if (build.body[address - build.start] === program.body[address - program.start]) continue;
88
+ throw new Refusal(
89
+ "invalid-input",
90
+ `These switch values change the byte at ${formatC64Address(address)}, between the free ranges of loader.asm (${show(build)}), and loader.asm holds the byte of generate there. Set the switch values in config.asm, and generate the source with the loader.`,
91
+ );
92
+ }
93
+ }
94
+ }
95
+
96
+ /** What Exomizer makes of a packed loader. */
97
+ export interface PackedLoader {
98
+ /** The loader program: it loads at $0801 and starts with RUN. */
99
+ program: Buffer;
100
+ packedBytes: number;
101
+ unpackedBytes: number;
102
+ /** The CPU cycles of the unpack, when Exomizer gives them. */
103
+ cycles?: number;
104
+ }
105
+
106
+ /**
107
+ * Packs the loaded ranges of the build of main.asm from $0400 and the build of
108
+ * loader.asm (the copier wins where they overlap) with the entry at the copier
109
+ * and $01 = $34, and checks the unpack in the emulator of Exomizer: every byte
110
+ * of the two builds, and the jump to the copier. Refuses by name when it does
111
+ * not hold.
112
+ */
113
+ export async function packLoader(main: Uint8Array, copier: Uint8Array, plan: { loaded: readonly AddressRange[]; copier: number }, context: ToolContext): Promise<PackedLoader> {
114
+ return packParts(packedParts(main, copier, plan.loaded), plan.copier, PACKED_EXIT_MEMORY, "main.asm and loader.asm", "the copier", context);
115
+ }
116
+
117
+ /** What Exomizer packs in the packed form: the loaded ranges of the build of main.asm from $0400, and the build of loader.asm. */
118
+ function packedParts(main: Uint8Array, copier: Uint8Array, loaded: readonly AddressRange[]): Array<{ start: number; body: Uint8Array }> {
119
+ // The unpacker uses pages 0-3; the copier writes them. The leftovers between the loaded ranges are not packed.
120
+ const program = prgRange(main);
121
+ const ranges = loaded.flatMap((range) => {
122
+ const start = Math.max(range.start, PACKED_FROM, program.start);
123
+ const end = Math.min(range.end, program.end);
124
+ return start <= end ? [{ start, body: program.body.subarray(start - program.start, end - program.start + 1) }] : [];
125
+ });
126
+ return [...ranges, prgRange(copier)];
127
+ }
128
+
129
+ /**
130
+ * Packs parts (a later one wins where they overlap) into one program that
131
+ * unpacks itself, starts at `entry` with $01 = `exitMemory`, and checks the
132
+ * unpack in the emulator of Exomizer: every byte of the parts, and the jump
133
+ * to the entry. Refuses by name when it does not hold.
134
+ */
135
+ export async function packParts(parts: ReadonlyArray<{ start: number; body: Uint8Array }>, entry: number, exitMemory: number, what: string, entryName: string, context: ToolContext): Promise<PackedLoader> {
136
+ const prg = (part: { start: number; body: Uint8Array }) => Buffer.concat([Buffer.from([part.start & 0xff, part.start >> 8]), part.body]);
137
+ const packed = await pack({ programs: parts.map(prg), entry, exitMemory }, context);
138
+ if (packed.entry !== entry) throw new Refusal("operation-failed", `The unpack in the emulator of Exomizer jumps to ${formatC64Address(packed.entry)}, not to ${entryName} at ${formatC64Address(entry)}.`);
139
+ const reference = mergedPrograms(parts);
140
+ const wrong = compareBuild(packed.unpacked, reference).segments.find((segment) => segment.result !== "identical");
141
+ if (wrong !== undefined) {
142
+ const first = wrong.firstDifference === undefined ? "" : `: the first is ${wrong.firstDifference.address}, ${wrong.firstDifference.built} and not ${wrong.firstDifference.reference}`;
143
+ throw new Refusal("operation-failed", `The unpack in the emulator of Exomizer does not give ${wrong.start}-${wrong.end} of ${what} (${wrong.result}${first}).`);
144
+ }
145
+ const unpackedBytes = reference.segments.reduce((sum, segment) => sum + segment.end - segment.start + 1, 0);
146
+ return { program: packed.program, packedBytes: packed.program.length, unpackedBytes, ...(packed.cycles === undefined ? {} : { cycles: packed.cycles }) };
147
+ }
148
+
149
+ /**
150
+ * The symbols of the loader program: the labels of the build of loader.asm,
151
+ * of the build of main.asm, and of start_screen_stage.asm when the loader has
152
+ * a show stage. A test takes one symbols file. Refuses a name with two values.
153
+ */
154
+ export function loaderSymbols(...builds: ReadonlyArray<readonly AssembledSymbol[]>): AssembledSymbol[] {
155
+ const valueOf = (symbol: AssembledSymbol) => (symbol.kind === "address" ? symbol.address : symbol.value);
156
+ const byName = new Map<string, AssembledSymbol>();
157
+ for (const symbol of builds.flat()) {
158
+ const known = byName.get(symbol.name);
159
+ if (known !== undefined && valueOf(known) !== valueOf(symbol)) {
160
+ throw new Refusal("operation-failed", `The builds of the loader program give ${symbol.name} two values, ${valueOf(known)} and ${valueOf(symbol)}. This is a defect of the script.`);
161
+ }
162
+ // An address in one build can be outside the load range of the other build, where it is a constant.
163
+ const kept = known === undefined || (known.kind === "constant" && symbol.kind === "address") ? symbol : known;
164
+ byName.set(symbol.name, { ...kept, used: symbol.used || (known?.used ?? false) });
165
+ }
166
+ return [...byName.values()].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
167
+ }
@@ -184,6 +184,17 @@ export class C64RunSession {
184
184
  return Buffer.concat(parts);
185
185
  }
186
186
 
187
+ /** The visible screen now, as palette indices, with the 16 colours of the palette. */
188
+ async screen(): Promise<{ frame: { width: number; height: number; pixels: Uint8Array }; palette: Array<[number, number, number]> }> {
189
+ const [, width, height, pixels] = (await this.command("frame")).split(" ");
190
+ const byte = (hex: string, at: number) => Number.parseInt(hex.slice(at, at + 2), 16);
191
+ const palette = (await this.command("palette"))
192
+ .split(" ")
193
+ .slice(1)
194
+ .map((hex): [number, number, number] => [byte(hex, 0), byte(hex, 2), byte(hex, 4)]);
195
+ return { frame: { width: Number(width), height: Number(height), pixels: Buffer.from(pixels ?? "", "base64") }, palette };
196
+ }
197
+
187
198
  /** Ends c64run: quit, then the stop of its process group (at once when it ended, else after STOP_MS). */
188
199
  async close(): Promise<void> {
189
200
  if (this.#ended === undefined) {
@@ -4,7 +4,7 @@
4
4
  // before the script imports it.
5
5
 
6
6
  import { describeError, WireFailure } from "../../protocol/messages.ts";
7
- import { checkDecompilerResult, checkRequestBounds, DECOMPILER_LIMITS, imageRange, seedsInside, type DecompilerParams, type DecompilerResult } from "../types.ts";
7
+ import { checkDecompilerResult, checkRequestBounds, DECOMPILER_LIMITS, imageRange, seedsInside, type DecompilerParams, type DecompilerResult, type SeedReport } from "../types.ts";
8
8
  import type { ToolContext } from "../run.ts";
9
9
  import { walk } from "./walk.ts";
10
10
  import { decompile, loadImage, setName, SLEIGH_VERSION } from "./wasm.ts";
@@ -16,21 +16,22 @@ export async function analyze(
16
16
  params: DecompilerParams,
17
17
  image: Buffer,
18
18
  context: ToolContext,
19
- ): Promise<{ result: DecompilerResult }> {
19
+ ): Promise<{ result: DecompilerResult; seeds: SeedReport }> {
20
20
  checkRequestBounds(params);
21
21
  const { start, end, body } = imageRange(params.imageKind, image);
22
22
 
23
23
  // The decoder sees only the loaded bytes; labels may name any address.
24
- const { entryPoints, codeStarts, dataRanges } = seedsInside(params, start, end);
24
+ const { entryPoints, codeStarts, dataRanges, report } = seedsInside(params, start, end);
25
25
  if (entryPoints.length === 0) {
26
26
  throw new WireFailure("invalid-input", "Give at least one entry point inside the program, for example the SYS address of its BASIC loader.");
27
27
  }
28
28
  context.signal.throwIfAborted();
29
29
 
30
- let walked: ReturnType<typeof walk>;
30
+ let walked: Omit<ReturnType<typeof walk>, "refusedSeeds">;
31
+ let refusedSeeds: ReturnType<typeof walk>["refusedSeeds"];
31
32
  try {
32
33
  loadImage(body, start);
33
- walked = walk(body, start, end, { entryPoints, codeStarts, dataRanges, labels: params.labels });
34
+ ({ refusedSeeds, ...walked } = walk(body, start, end, { entryPoints, codeStarts, dataRanges, labels: params.labels }));
34
35
  } catch (error) {
35
36
  context.log?.(`The decoder failed: ${describeError(error)}`);
36
37
  throw new WireFailure("operation-failed", `The decoder failed: ${describeError(error)}. Nothing was imported.`);
@@ -44,7 +45,7 @@ export async function analyze(
44
45
  context.log?.(`Decompiler result rejected: ${describeError(error)}`);
45
46
  throw new WireFailure("operation-failed", `The decompiler returned an incomplete or inconsistent result. Nothing was imported. The check found: ${describeError(error)}.`);
46
47
  }
47
- return { result };
48
+ return { result, seeds: { refused: [...report.refused, ...refusedSeeds].sort((a, b) => a.address - b.address), dataRangesLeftOut: report.dataRangesLeftOut } };
48
49
  }
49
50
 
50
51
  /** The requested routines as C text, within the character bounds; the labels name routines and data. */