@henols/c64-re-tools 2.6.0-rc.2 → 2.6.0-rc.3

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.
@@ -33,6 +33,8 @@ export interface MemoryObservation {
33
33
  view?: "cpu" | "ram";
34
34
  /** The largest allowed difference per byte; 0 when not given. */
35
35
  tolerance?: number;
36
+ /** Hex bits that the comparison uses: one byte for each byte, or one byte per byte of the range; all bits when not given. */
37
+ mask?: string;
36
38
  /** Bytes in the range that the comparison leaves out, each with the reason. */
37
39
  exclude?: Array<{ address: Location; reason: string }>;
38
40
  }
@@ -207,7 +209,7 @@ function checkObserve(step: Record<string, unknown>, at: string, fail: (message:
207
209
  checkLocation(item, `${at}: memory`, fail);
208
210
  continue;
209
211
  }
210
- const itemFields = ["address", "size", "view", "tolerance", "exclude"];
212
+ const itemFields = ["address", "size", "view", "tolerance", "mask", "exclude"];
211
213
  if (!isObject(item)) return fail(`${at}: memory must be a list of names, $ addresses or objects with address`);
212
214
  for (const key of Object.keys(item)) if (!itemFields.includes(key)) fail(`${at}: a memory object has the field ${key}. ${renamedField(key, itemFields) ?? `It has ${itemFields.join(", ")}, and nothing else`}`);
213
215
  if (item.view !== undefined && item.view !== "cpu" && item.view !== "ram") fail(`${at}: memory.view must be cpu or ram`);
@@ -223,6 +225,12 @@ function checkObserve(step: Record<string, unknown>, at: string, fail: (message:
223
225
  checkLocation(item.address, `${at}: memory.address`, fail);
224
226
  if (item.size !== undefined && !isInteger(item.size, 1, 0x10000)) fail(`${at}: memory.size must be a number from 1 to 65536`);
225
227
  if (item.tolerance !== undefined && !isInteger(item.tolerance, 0, 0xff)) fail(`${at}: memory.tolerance must be a number from 0 to 255`);
228
+ if (item.mask !== undefined) {
229
+ const size = isInteger(item.size, 1, 0x10000) ? item.size : 1;
230
+ if (typeof item.mask !== "string" || !/^(?:[0-9a-fA-F]{2})+$/.test(item.mask) || (item.mask.length !== 2 && item.mask.length !== size * 2)) {
231
+ fail(`${at}: memory.mask must be hex bits, one byte for each byte (for example 0f) or one byte per byte of size`);
232
+ }
233
+ }
226
234
  }
227
235
  }
228
236
  if (step.registers !== undefined) {
@@ -354,7 +362,7 @@ export function resolve(location: Location, symbols: Map<string, number>, side:
354
362
  }
355
363
 
356
364
  interface Observation {
357
- memory: Array<{ label: string; address: number; bytes: number[]; tolerance: number; excluded: Array<{ offset: number; address: Location; reason: string }> }>;
365
+ memory: Array<{ label: string; address: number; bytes: number[]; tolerance: number; mask?: number[]; excluded: Array<{ offset: number; address: Location; reason: string }> }>;
358
366
  registers: Partial<Record<ObservedRegister, unknown>>;
359
367
  screen?: { match: boolean; mismatchingPixels: number; comparedPixels: number; mismatchRatio: number; bounds?: unknown };
360
368
  vicii?: unknown;
@@ -444,7 +452,7 @@ async function runStep(client: ViceSessionClient, scenario: Scenario, side: Side
444
452
  if (offset < 0 || offset >= size) throw new Refusal("invalid-input", `the exclude ${exclude.address} lies outside the observed ${spec.address} (${size} bytes)`);
445
453
  return { offset, address: exclude.address, reason: exclude.reason };
446
454
  });
447
- observation.memory.push({ label: size > 1 ? `${spec.address} (${size} bytes)` : spec.address, address, bytes: [...Buffer.from(read.data, "hex")], tolerance: spec.tolerance ?? 0, excluded });
455
+ observation.memory.push({ label: size > 1 ? `${spec.address} (${size} bytes)` : spec.address, address, bytes: [...Buffer.from(read.data, "hex")], tolerance: spec.tolerance ?? 0, ...(spec.mask === undefined ? {} : { mask: [...Buffer.from(spec.mask, "hex")] }), excluded });
448
456
  }
449
457
  if (step.registers !== undefined) {
450
458
  const registers = await client.registersGet("c64");
@@ -495,11 +503,12 @@ async function runStep(client: ViceSessionClient, scenario: Scenario, side: Side
495
503
 
496
504
  type MemoryItem = Observation["memory"][number];
497
505
 
498
- /** The bytes of a memory item that differ by more than its tolerance, without the excluded bytes. */
506
+ /** The bytes of a memory item whose bits of the mask differ by more than its tolerance, without the excluded bytes. */
499
507
  function differingBytes(item: MemoryItem, other: MemoryItem): DifferingByte[] {
500
508
  const hex = (byte: number) => byte.toString(16).padStart(2, "0");
501
509
  const skipped = new Set(item.excluded.map((excluded) => excluded.offset));
502
- return item.bytes.flatMap((byte, offset) => (!skipped.has(offset) && Math.abs(byte - other.bytes[offset]!) > item.tolerance ? [{ address: formatC64Address(item.address + offset), original: hex(byte), rebuild: hex(other.bytes[offset]!) }] : []));
510
+ const bits = (offset: number) => (item.mask === undefined ? 0xff : item.mask.length === 1 ? item.mask[0]! : item.mask[offset]!);
511
+ return item.bytes.flatMap((byte, offset) => (!skipped.has(offset) && Math.abs((byte & bits(offset)) - (other.bytes[offset]! & bits(offset))) > item.tolerance ? [{ address: formatC64Address(item.address + offset), original: hex(byte), rebuild: hex(other.bytes[offset]!) }] : []));
503
512
  }
504
513
 
505
514
  /** The most differing bytes of one memory item that a result lists when no --max-listed is given. */
@@ -202,7 +202,7 @@ The folder `--out` gets these files:
202
202
  - `image.bin`: all 64 KiB of RAM at the entry. This RAM includes the RAM under the ROMs and the I/O area. A segment can be in the RAM under the I/O area at `$d000`-`$dfff`.
203
203
  - `image.json`: the entry, the segments, the vectors and the stages. `writtenBy` of a segment tells the last stage that wrote into it.
204
204
  - One PRG for each segment.
205
- - `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.
205
+ - `entry_state.json`: the registers, `$00` and `$01`, pages 0 to 3, the VIC, SID and CIA registers, the colour RAM, and the vectors. `io.colour` holds the 1000 colours at $d800. `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.
206
206
 
207
207
  A segment is a block that a stage wrote, also a small block. These blocks are not segments:
208
208
 
@@ -260,7 +260,7 @@ Traps:
260
260
  5. Make sure that the result is the program. 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.
261
261
  - Exclude each range of a cracktro that the program does not read. A rebuild has no cracktro. Also exclude a picture, an intro or a credit screen of a crack.
262
262
  - Do not exclude the start screen of the program, also when the program does not read it. An example is the loading picture of the publisher. Record it as the start screen in the project knowledge. The loader of the rebuild shows it.
263
- - When the start screen is only in an earlier stage of the loading, capture that stage too, while it shows the screen. Do not exclude the memory of the screen in that capture. Put it into the project knowledge in a space of its own, for example `bank1`.
263
+ - When the start screen is only in an earlier stage of the loading, capture that stage too, while it shows the screen. Do not exclude the memory of the screen in that capture. Put it into the project knowledge in the space `loading`. The capture holds the VIC-II registers and the colour RAM, so the start screen needs nothing more.
264
264
  - Do not exclude other unused bytes, for example leftovers of the development or an old copy of a routine. A rebuild keeps them.
265
265
  - Keep a crack change that the program reads, for example a credit text in the game. Record it as a `crack` switch in the project knowledge.
266
266
  6. Put `<out>/image.json` into the project knowledge. The knowledge keeps the segments, the entry, the entry state and the stages. After that, you do not need the files in `<out>`.
@@ -15,8 +15,10 @@ type Registers = Awaited<ReturnType<ViceSessionClient["registersGet"]>>;
15
15
 
16
16
  const MAX_READ = 4096;
17
17
 
18
- /** The I/O areas of the entry state, read without side effects. */
19
- export const IO_AREAS = { vic: [0xd000, 0x2f], sid: [0xd400, 0x1d], cia1: [0xdc00, 0x10], cia2: [0xdd00, 0x10] } as const;
18
+ /** The I/O areas of the entry state, read without side effects. The colour RAM is the colours of the screen: a start screen of a captured stage uses them. */
19
+ export const IO_AREAS = { vic: [0xd000, 0x2f], sid: [0xd400, 0x1d], cia1: [0xdc00, 0x10], cia2: [0xdd00, 0x10], colour: [0xd800, 1000] } as const;
20
+ /** The I/O areas of chips: what differsFrom compares. The colour RAM is the content of the screen, not the state of the machine. */
21
+ const CHIP_AREAS = ["vic", "sid", "cia1", "cia2"] as const;
20
22
 
21
23
  /** What no register read of a CIA gives. */
22
24
  export interface CiaHidden {
@@ -49,6 +51,8 @@ export async function machineState(client: ViceSessionClient): Promise<MachineSt
49
51
  const pages = await readRam(client, 0x0000, 0x400);
50
52
  const io = {} as Record<keyof typeof IO_AREAS, Buffer>;
51
53
  for (const [name, [address, size]] of Object.entries(IO_AREAS)) io[name as keyof typeof IO_AREAS] = Buffer.from((await client.ioRead(address, size)).data, "hex");
54
+ // The colour RAM has 4 bits: a read gives other bits above them.
55
+ io.colour = Buffer.from(io.colour.map((value) => value & 0x0f));
52
56
  const [cia1, cia2] = (await client.cia("both")).chips.map(({ latchA, latchB, interruptMask }) => ({ latchA, latchB, interruptMask }));
53
57
  const romVectors = Buffer.from((await client.memoryRead({ address: 0xfffa, size: 6, space: "c64", view: "cpu" })).data, "hex");
54
58
  return { port, pages, io, cia: { cia1: cia1!, cia2: cia2! }, romVectors };
@@ -79,7 +83,7 @@ export function differsFrom(state: MachineState, clean: MachineState): Array<{ a
79
83
  const compare = (base: number, entry: Buffer, reset: Buffer) => entry.forEach((value, offset) => value !== reset[offset] && differs.push({ address: formatC64Address(base + offset), entry: value, reset: reset[offset]! }));
80
84
  compare(0x0000, state.port, clean.port);
81
85
  compare(0x0002, state.pages.subarray(2), clean.pages.subarray(2));
82
- for (const [name, [address]] of Object.entries(IO_AREAS)) compare(address, state.io[name as keyof typeof IO_AREAS], clean.io[name as keyof typeof IO_AREAS]);
86
+ for (const name of CHIP_AREAS) compare(IO_AREAS[name][0], state.io[name], clean.io[name]);
83
87
  return differs;
84
88
  }
85
89
 
package/src/c64.ts CHANGED
@@ -33,7 +33,7 @@ export interface AddressRange {
33
33
  }
34
34
 
35
35
  /** The knowledge spaces: the C64, the 1541 drive in unit 8, and cartridge banks 0 to 255. */
36
- export const SPACE_PATTERN = /^(c64|drive8|bank(0|[1-9][0-9]?|1[0-9]{2}|2[0-4][0-9]|25[0-5]))$/;
36
+ export const SPACE_PATTERN = /^(c64|drive8|loading|bank(0|[1-9][0-9]?|1[0-9]{2}|2[0-4][0-9]|25[0-5]))$/;
37
37
 
38
38
  /** VIC-II state with its addresses as $xxxx; the other values stay numbers. */
39
39
  export function formatVicii<T extends { screenAddress: number; graphicsAddress: number }>(state: T): Omit<T, "screenAddress" | "graphicsAddress"> & { screenAddress: string; graphicsAddress: string } {
@@ -478,6 +478,26 @@ export function coverageEntries(map: Uint8Array, image: (address: number) => num
478
478
  return entries;
479
479
  }
480
480
 
481
+ const ROM_ACCESS = COVERAGE.romRead | COVERAGE.romExecute;
482
+ const RAM_USE = COVERAGE.ramRead | COVERAGE.ramExecute;
483
+
484
+ /**
485
+ * The image bytes under ROM that the runs never used: the CPU read or ran the
486
+ * ROM there, and never read or ran the RAM. A JSR $FFE4 or an IRQ
487
+ * vector at $FFFE then leads into ROM, not into the leftover RAM bytes of a
488
+ * flat image, so the ranges are data for an analysis run.
489
+ */
490
+ export function romOnlyRanges(map: Uint8Array, image: (address: number) => number | undefined): AddressRange[] {
491
+ const ranges: AddressRange[] = [];
492
+ for (let address = 0; address < 0x10000; address++) {
493
+ if ((map[address]! & ROM_ACCESS) === 0 || (map[address]! & RAM_USE) !== 0 || image(address) === undefined) continue;
494
+ const last = ranges.at(-1);
495
+ if (last !== undefined && last.end === address - 1) last.end = address;
496
+ else ranges.push({ start: address, end: address });
497
+ }
498
+ return ranges;
499
+ }
500
+
481
501
  /** Every executed instruction start in RAM inside the image: VICE marks the opcode byte of an instruction as executed, not its operand. */
482
502
  export function executedStarts(map: Uint8Array, image: (address: number) => number | undefined): number[] {
483
503
  const starts: number[] = [];
@@ -134,6 +134,7 @@ export interface ReleaseRow {
134
134
  * Without `stage`, the bytes are in the program at the entry. With `stage`,
135
135
  * they are in the memory of that space (a captured stage of the loading, for
136
136
  * example), and `call` is a routine of the stage that the start screen calls.
137
+ * `colourRam` takes the colours from the colour RAM of the capture of the stage.
137
138
  */
138
139
  export interface StartScreenRow {
139
140
  space: Space;
@@ -147,6 +148,7 @@ export interface StartScreenRow {
147
148
  background: number;
148
149
  stage?: Space;
149
150
  call?: number;
151
+ colourRam?: true;
150
152
  comment?: string;
151
153
  origin: Extract<Origin, "user" | "llm">;
152
154
  revision: string;
@@ -202,7 +204,7 @@ export const SWITCH_COLUMNS = "space, name, kind, default_value, releases, comme
202
204
  export const RELEASE_COLUMNS = "space, label, file, sha256, base, comment, origin, valid_from_revision";
203
205
  export const MACRO_COLUMNS = "space, name, params, body, comment, origin, valid_from_revision";
204
206
  export const MACRO_USE_COLUMNS = "space, start_address, end_address, macro, args, origin, valid_from_revision";
205
- export const START_SCREEN_COLUMNS = "space, mode, screen, bitmap, charset, colours, colour, border, background, stage, call_address, comment, origin, valid_from_revision";
207
+ export const START_SCREEN_COLUMNS = "space, mode, screen, bitmap, charset, colours, colour, border, background, stage, call_address, colour_ram, comment, origin, valid_from_revision";
206
208
 
207
209
  export function toSymbol(row: Raw): SymbolRow {
208
210
  return { space: row.space as Space, address: row.address as number, name: row.name as string, kind: row.kind as SymbolKind, origin: row.origin as Origin, revision: row.valid_from_revision as string };
@@ -325,6 +327,7 @@ export function toStartScreen(row: Raw): StartScreenRow {
325
327
  for (const key of ["bitmap", "charset", "colours", "colour"] as const) if (row[key] !== null && row[key] !== undefined) value[key] = row[key] as number;
326
328
  if (row.stage !== null && row.stage !== undefined) value.stage = row.stage as Space;
327
329
  if (row.call_address !== null && row.call_address !== undefined) value.call = row.call_address as number;
330
+ if (row.colour_ram === 1) value.colourRam = true;
328
331
  if (row.comment !== null && row.comment !== undefined) value.comment = row.comment as string;
329
332
  return value;
330
333
  }
@@ -742,7 +745,7 @@ export function listSpaces(db: DatabaseSync | undefined): Space[] {
742
745
  `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_start_screens UNION SELECT space FROM current_memory UNION SELECT space FROM current_entries UNION SELECT space FROM current_coverage`,
743
746
  )
744
747
  .all() as Array<{ space: Space }>;
745
- const order = (space: Space) => (space === "c64" ? -2 : space === "drive8" ? -1 : Number(space.slice(4)));
748
+ const order = (space: Space) => (space === "c64" ? -3 : space === "drive8" ? -2 : space === "loading" ? -1 : Number(space.slice(4)));
746
749
  return rows.map((row) => row.space).sort((a, b) => order(a) - order(b));
747
750
  }
748
751
 
@@ -114,7 +114,7 @@ export function isGeneratedFile(file: string): boolean {
114
114
  */
115
115
  export type Space = string;
116
116
  export const DEFAULT_SPACE: Space = "c64";
117
- const SPACE_CHECK = "space IN ('c64', 'drive8') OR space GLOB 'bank[0-9]' OR space GLOB 'bank[1-9][0-9]' OR space GLOB 'bank[12][0-9][0-9]'";
117
+ const SPACE_CHECK = "space IN ('c64', 'drive8', 'loading') OR space GLOB 'bank[0-9]' OR space GLOB 'bank[1-9][0-9]' OR space GLOB 'bank[12][0-9][0-9]'";
118
118
 
119
119
  const list = (values: readonly string[]) => values.map((value) => `'${value}'`).join(", ");
120
120
 
@@ -321,15 +321,17 @@ function createSchema(db: DatabaseSync): void {
321
321
  background INTEGER NOT NULL CHECK (background BETWEEN 0 AND 15),
322
322
  stage TEXT CHECK (stage IS NULL OR (stage <> 'c64' AND (${SPACE_CHECK.replaceAll("space", "stage")}))),
323
323
  call_address INTEGER CHECK (call_address BETWEEN 0 AND 65535),
324
+ colour_ram INTEGER CHECK (colour_ram = 1),
324
325
  comment TEXT CHECK (comment IS NULL OR length(comment) > 0),
325
326
  origin TEXT NOT NULL CHECK (origin IN ('user', 'llm')),
326
327
  valid_from_revision TEXT NOT NULL REFERENCES revisions (id),
327
328
  valid_to_revision TEXT REFERENCES revisions (id),
328
329
  CHECK (call_address IS NULL OR stage IS NOT NULL),
330
+ CHECK (colour_ram IS NULL OR (stage IS NOT NULL AND colours IS NULL AND colour IS NULL AND mode <> 'hires')),
329
331
  CHECK ((mode = 'text') = (charset IS NOT NULL)),
330
332
  CHECK ((mode = 'text') = (bitmap IS NULL)),
331
333
  CHECK (colours IS NULL OR colour IS NULL),
332
- CHECK ((mode = 'hires') = (colours IS NULL AND colour IS NULL))
334
+ CHECK ((mode = 'hires') = (colours IS NULL AND colour IS NULL AND colour_ram IS NULL))
333
335
  );
334
336
  CREATE INDEX start_screens_space ON start_screens (space);
335
337
  CREATE TABLE macro_uses (
@@ -397,7 +399,7 @@ function createSchema(db: DatabaseSync): void {
397
399
  }
398
400
 
399
401
  /** The version of the index this build makes. An index with another version is emptied and made again. */
400
- export const INDEX_VERSION = 11;
402
+ export const INDEX_VERSION = 13;
401
403
 
402
404
  function indexVersion(db: DatabaseSync): number | undefined {
403
405
  const hasMeta = db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'meta'").get();
@@ -0,0 +1,68 @@
1
+ // The start screen of a captured stage, from the entry state of its capture:
2
+ // the VIC-II registers and the VIC bank give the mode and the addresses, and
3
+ // the colour RAM of the capture gives the colours. Thus the start screen of a
4
+ // stage needs no address from the user.
5
+
6
+ import { Refusal } from "../errors.ts";
7
+ import type { StartScreenMode } from "./schema.ts";
8
+
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
+ export const START_SCREEN_WAIT = "loader_start_screen_wait";
11
+ export const START_SCREEN_CONTINUE = "loader_start_screen_continue";
12
+
13
+ /** The fields of a start screen that the capture of a stage gives. */
14
+ export interface StageScreen {
15
+ mode: StartScreenMode;
16
+ screen: number;
17
+ bitmap?: number;
18
+ charset?: number;
19
+ border: number;
20
+ background: number;
21
+ /** The colours are the colour RAM of the capture: not for hires. */
22
+ colourRam?: true;
23
+ }
24
+
25
+ /** The bytes of an I/O area of an entry state: io.<name>.bytes as hex, when the capture has them. */
26
+ function ioBytes(state: Record<string, unknown> | undefined, name: string): Buffer | undefined {
27
+ const io = state?.io as Record<string, { bytes?: unknown }> | undefined;
28
+ const bytes = io?.[name]?.bytes;
29
+ return typeof bytes === "string" && /^([0-9a-f]{2})+$/i.test(bytes) ? Buffer.from(bytes, "hex") : undefined;
30
+ }
31
+
32
+ /** The colour RAM of the capture of a stage: 1000 colours from $d800, or undefined when the capture has none. */
33
+ export function capturedColourRam(state: Record<string, unknown> | undefined): Uint8Array | undefined {
34
+ const bytes = ioBytes(state, "colour");
35
+ return bytes === undefined || bytes.length !== 1000 ? undefined : Uint8Array.from(bytes, (value) => value & 0x0f);
36
+ }
37
+
38
+ /**
39
+ * The start screen that the capture of a stage shows: its mode, its screen,
40
+ * its bitmap or charset, its colours and the colour RAM. Refuses by name when
41
+ * the capture does not show a start screen that the loader can show.
42
+ */
43
+ export function startScreenOfStage(state: Record<string, unknown> | undefined, stage: string): StageScreen {
44
+ const again = `Capture the stage again while it shows the screen, and put the capture into the project knowledge with image --space ${stage}.`;
45
+ const vic = ioBytes(state, "vic");
46
+ const cia2 = ioBytes(state, "cia2");
47
+ 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}`);
48
+ const [d011, d016, d018] = [vic[0x11]!, vic[0x16]!, vic[0x18]!];
49
+ 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}`);
50
+ 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.`);
51
+ const bitmap = (d011 & 0x20) !== 0;
52
+ const multicolour = (d016 & 0x10) !== 0;
53
+ if (!bitmap && multicolour) throw new Refusal("invalid-input", `The capture in ${stage} shows a multicolour text screen, which a start screen does not have.`);
54
+ const bank = (3 - (cia2[0]! & 0x03)) << 14;
55
+ const mode: StartScreenMode = bitmap ? (multicolour ? "multicolour" : "hires") : "text";
56
+ const screen = bank + ((d018 >> 4) & 0x0f) * 0x400;
57
+ const colourRam = mode === "hires" ? undefined : capturedColourRam(state);
58
+ 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}`);
59
+ return {
60
+ mode,
61
+ screen,
62
+ ...(bitmap ? { bitmap: bank + ((d018 >> 3) & 1) * 0x2000 } : { charset: bank + ((d018 >> 1) & 7) * 0x800 }),
63
+ border: vic[0x20]! & 0x0f,
64
+ background: vic[0x21]! & 0x0f,
65
+ ...(colourRam === undefined ? {} : { colourRam: true as const }),
66
+ };
67
+ }
68
+
@@ -202,6 +202,7 @@ export const TABLES: readonly TableSpec[] = [
202
202
  field("background", "background", "integer"),
203
203
  field("stage", "stage", "text", true),
204
204
  field("call", "call_address", "address", true),
205
+ field("colourRam", "colour_ram", "integer", true),
205
206
  field("comment", "comment", "text", true),
206
207
  origin,
207
208
  ],
@@ -99,8 +99,8 @@ export interface WriteContext {
99
99
  expectedRevision?: string;
100
100
  /** Kept with the revision when the write changes something. */
101
101
  evidence?: Evidence[];
102
- /** The image that an operand, patch or macro use write is checked against. */
103
- image?: OperandImage;
102
+ /** The image of a space that an operand, patch or macro use write in that space is checked against. */
103
+ image?: (space: Space) => OperandImage;
104
104
  }
105
105
 
106
106
  /** The bytes of the image and the platform names (C64 space only) that operand expressions, patches and macro uses are checked against. */
@@ -287,8 +287,8 @@ export class Change {
287
287
 
288
288
  insertStartScreen(row: Omit<StartScreenRow, "revision">): void {
289
289
  this.#db
290
- .prepare("INSERT INTO start_screens (id, space, mode, screen, bitmap, charset, colours, colour, border, background, stage, call_address, comment, origin, valid_from_revision) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
291
- .run(this.#rowId(), row.space, row.mode, row.screen, row.bitmap ?? null, row.charset ?? null, row.colours ?? null, row.colour ?? null, row.border, row.background, row.stage ?? null, row.call ?? null, row.comment ?? null, row.origin, this.id());
290
+ .prepare("INSERT INTO start_screens (id, space, mode, screen, bitmap, charset, colours, colour, border, background, stage, call_address, colour_ram, comment, origin, valid_from_revision) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
291
+ .run(this.#rowId(), row.space, row.mode, row.screen, row.bitmap ?? null, row.charset ?? null, row.colours ?? null, row.colour ?? null, row.border, row.background, row.stage ?? null, row.call ?? null, row.colourRam === true ? 1 : null, row.comment ?? null, row.origin, this.id());
292
292
  }
293
293
 
294
294
  insertMacro(row: Omit<MacroRow, "revision">): void {
@@ -713,13 +713,13 @@ function checkOperandValue(db: DatabaseSync, space: Space, image: OperandImage,
713
713
  return identifiers(text).map((name) => resolve(name)!);
714
714
  }
715
715
 
716
- function operandStep(db: DatabaseSync, change: Change, context: ChangeContext & { image?: OperandImage }, request: OperandRequest): Step<OperandRow, OperandRow> {
716
+ function operandStep(db: DatabaseSync, change: Change, context: ChangeContext & { image?: (space: Space) => OperandImage }, request: OperandRequest): Step<OperandRow, OperandRow> {
717
717
  const space = spaceOf(request);
718
718
  if (context.image === undefined) throw new Refusal("invalid-input", "An operand expression is checked against the image, and no image was given.");
719
719
  const wanted: Omit<OperandRow, "space" | "address" | "origin" | "revision"> = { select: request.select, offset: request.offset ?? 0 };
720
720
  if (request.symbol !== undefined) wanted.symbol = request.symbol;
721
721
  if (request.expression !== undefined) wanted.expression = request.expression.trim();
722
- const targets = new Set(checkOperandValue(db, space, context.image, request, operandText(wanted)));
722
+ const targets = new Set(checkOperandValue(db, space, context.image(space), request, operandText(wanted)));
723
723
  const existing = operandAt(db, request.address, space);
724
724
  const origin = context.origin as OperandRow["origin"];
725
725
  if (existing !== undefined && existing.select === wanted.select && existing.symbol === wanted.symbol && existing.offset === wanted.offset && existing.expression === wanted.expression && !confirms(existing.origin, origin)) {
@@ -874,11 +874,12 @@ export function leastPatchBytes(code: string): number | undefined {
874
874
  return bytes;
875
875
  }
876
876
 
877
- function patchStep(db: DatabaseSync, change: Change, context: ChangeContext & { image?: OperandImage }, request: PatchRequest): Step<PatchRow, PatchRow> {
877
+ function patchStep(db: DatabaseSync, change: Change, context: ChangeContext & { image?: (space: Space) => OperandImage }, request: PatchRequest): Step<PatchRow, PatchRow> {
878
878
  const space = spaceOf(request);
879
879
  const range = `${formatC64Address(request.start)}-${formatC64Address(request.end)}`;
880
880
  if (context.image === undefined) throw new Refusal("invalid-input", "A patch is checked against the image, and no image was given.");
881
- checkInImage(context.image, request.start, request.end, "a patch");
881
+ const image = context.image(space);
882
+ checkInImage(image, request.start, request.end, "a patch");
882
883
  const least = leastPatchBytes(request.code);
883
884
  const length = request.end - request.start + 1;
884
885
  if (least !== undefined && least > length) {
@@ -979,7 +980,7 @@ function defaultOf(request: SwitchRequest, existing: SwitchRow | undefined): 0 |
979
980
  throw new Refusal("invalid-input", `A ${request.kind} switch needs a default: give --default 0 or --default 1.`);
980
981
  }
981
982
 
982
- function switchStep(db: DatabaseSync, change: Change, context: ChangeContext & { image?: OperandImage }, request: SwitchRequest): Step<SwitchRow, SwitchRow> {
983
+ function switchStep(db: DatabaseSync, change: Change, context: ChangeContext & { image?: (space: Space) => OperandImage }, request: SwitchRequest): Step<SwitchRow, SwitchRow> {
983
984
  const space = spaceOf(request);
984
985
  const base = baseLabel(db, space);
985
986
  if (base === undefined) throw new Refusal("not-found", "The knowledge has no base release. Record the release whose bytes are the program first (release <label> --file <file> --base).");
@@ -992,7 +993,7 @@ function switchStep(db: DatabaseSync, change: Change, context: ChangeContext & {
992
993
  if (existing !== undefined && existing.kind === request.kind && existing.default === value && listText(existing.releases) === listText(releases) && existing.comment === comment && !confirms(existing.origin, origin)) return { current: existing };
993
994
  const symbol = symbolNamed(db, request.name, space);
994
995
  if (symbol !== undefined) throw new Refusal("conflict", `The switch name ${request.name} is the name of the symbol at ${formatC64Address(symbol.address)}. Give the switch another name.`);
995
- if (space === DEFAULT_SPACE && context.image?.platform.has(request.name)) throw new Refusal("conflict", `The switch name ${request.name} is a C64 platform name. Give the switch another name.`);
996
+ if (space === DEFAULT_SPACE && context.image?.(space).platform.has(request.name)) throw new Refusal("conflict", `The switch name ${request.name} is a C64 platform name. Give the switch another name.`);
996
997
  // The patches hold the code of the value that the base release does not have: that value cannot change under them.
997
998
  if (existing !== undefined && baseValue(existing, base) !== baseValue({ releases }, base)) {
998
999
  const patches = listPatches(db, undefined, request.name, undefined, space);
@@ -1066,7 +1067,7 @@ function unreleaseStep(db: DatabaseSync, change: Change, _origin: Origin, reques
1066
1067
  return { current: null };
1067
1068
  }
1068
1069
 
1069
- type StartScreenRequest = InSpace & { mode: StartScreenMode; screen: number; bitmap?: number; charset?: number; colours?: number; colour?: number; border: number; background: number; stage?: Space; call?: number; comment?: string };
1070
+ type StartScreenRequest = InSpace & { mode: StartScreenMode; screen: number; bitmap?: number; charset?: number; colours?: number; colour?: number; border: number; background: number; stage?: Space; call?: number; colourRam?: boolean; comment?: string };
1070
1071
 
1071
1072
  /**
1072
1073
  * The rules of the VIC-II for a start screen: the screen at a 1K step, the
@@ -1099,7 +1100,11 @@ function checkStartScreen(request: StartScreenRequest): void {
1099
1100
  throw new Refusal("invalid-input", `A ${request.mode} start screen has a bitmap and no charset. Give --bitmap.`);
1100
1101
  }
1101
1102
  if (request.colours !== undefined && request.colour !== undefined) throw new Refusal("invalid-input", "Give the colour RAM as --colours or as --colour, not both.");
1102
- const colourRam = request.colours !== undefined || request.colour !== undefined;
1103
+ if (request.colourRam === true) {
1104
+ if (request.stage === undefined) throw new Refusal("invalid-input", "The colour RAM of a capture is only for a start screen of a stage: give --stage.");
1105
+ if (request.colours !== undefined || request.colour !== undefined) throw new Refusal("invalid-input", "The colours come from the colour RAM of the capture: do not give --colours or --colour too.");
1106
+ }
1107
+ const colourRam = request.colours !== undefined || request.colour !== undefined || request.colourRam === true;
1103
1108
  if (request.mode === "hires" && colourRam) throw new Refusal("invalid-input", "A hires bitmap does not use the colour RAM. Remove --colours and --colour.");
1104
1109
  if (request.mode !== "hires" && !colourRam) throw new Refusal("invalid-input", `A ${request.mode} start screen uses the colour RAM. Give --colours with the address of its 1000 bytes, or --colour with one colour.`);
1105
1110
  const step = (value: number, size: number, what: string) => {
@@ -1162,6 +1167,7 @@ function startScreenStep(db: DatabaseSync, change: Change, origin: Origin, reque
1162
1167
  background: request.background,
1163
1168
  ...(request.stage === undefined ? {} : { stage: request.stage }),
1164
1169
  ...(request.call === undefined ? {} : { call: request.call }),
1170
+ ...(request.colourRam === true ? { colourRam: true as const } : {}),
1165
1171
  ...(comment === undefined ? {} : { comment }),
1166
1172
  origin: origin as StartScreenRow["origin"],
1167
1173
  };
@@ -1259,11 +1265,11 @@ function renameInUses(db: DatabaseSync, change: Change, space: Space, from: stri
1259
1265
  }
1260
1266
  }
1261
1267
 
1262
- function useStep(db: DatabaseSync, change: Change, context: ChangeContext & { image?: OperandImage }, request: MacroUseRequest): Step<MacroUseRow, MacroUseRow> {
1268
+ function useStep(db: DatabaseSync, change: Change, context: ChangeContext & { image?: (space: Space) => OperandImage }, request: MacroUseRequest): Step<MacroUseRow, MacroUseRow> {
1263
1269
  const space = spaceOf(request);
1264
- const image = context.image;
1265
1270
  const range = `${formatC64Address(request.start)}-${formatC64Address(request.end)}`;
1266
- if (image === undefined) throw new Refusal("invalid-input", "A macro use is checked against the image, and no image was given.");
1271
+ if (context.image === undefined) throw new Refusal("invalid-input", "A macro use is checked against the image, and no image was given.");
1272
+ const image = context.image(space);
1267
1273
  const macro = macroNamed(db, request.macro, space);
1268
1274
  if (macro === undefined) throw new Refusal("not-found", `There is no macro ${request.macro}. Write it first (macro).`);
1269
1275
  const args = (request.args ?? []).map((arg) => arg.trim());
@@ -1635,7 +1641,7 @@ const KEYS = {
1635
1641
  columns: START_SCREEN_COLUMNS,
1636
1642
  map: toStartScreen,
1637
1643
  key: (row: StartScreenRow) =>
1638
- `${row.space}|${row.mode}|${row.screen}|${row.bitmap ?? ""}|${row.charset ?? ""}|${row.colours ?? ""}|${row.colour ?? ""}|${row.border}|${row.background}|${row.stage ?? ""}|${row.call ?? ""}|${row.comment ?? ""}|${row.origin}`,
1644
+ `${row.space}|${row.mode}|${row.screen}|${row.bitmap ?? ""}|${row.charset ?? ""}|${row.colours ?? ""}|${row.colour ?? ""}|${row.border}|${row.background}|${row.stage ?? ""}|${row.call ?? ""}|${row.colourRam === true ? 1 : ""}|${row.comment ?? ""}|${row.origin}`,
1639
1645
  },
1640
1646
  macros: { columns: MACRO_COLUMNS, map: toMacro, key: (row: MacroRow) => `${row.space}|${row.name}|${listText(row.params)}|${row.body}|${row.comment ?? ""}|${row.origin}` },
1641
1647
  macro_uses: { columns: MACRO_USE_COLUMNS, map: toMacroUse, key: (row: MacroUseRow) => `${row.space}|${row.start}|${row.end}|${row.macro}|${listText(row.args)}|${row.origin}` },
package/src/platform.ts CHANGED
@@ -3,7 +3,7 @@
3
3
  // Names follow "Mapping the Commodore 64". Only platform facts live here:
4
4
  // an address without one belongs to the application.
5
5
 
6
- import { COVERAGE, d018Offsets, formatC64Address, vicBankBase } from "./c64.ts";
6
+ import { type AddressRange, COVERAGE, d018Offsets, formatC64Address, romOnlyRanges, vicBankBase } from "./c64.ts";
7
7
  import { Refusal } from "./errors.ts";
8
8
 
9
9
  export interface Entry {
@@ -433,6 +433,35 @@ export function romUseOfProgram(coverage: Uint8Array | undefined, state: Record<
433
433
  return { basic: true, kernal: true, from: "none" };
434
434
  }
435
435
 
436
+ /** The ROMs as the CPU sees them. */
437
+ const BASIC_ROM: AddressRange = { start: 0xa000, end: 0xbfff };
438
+ const KERNAL_ROM: AddressRange = { start: 0xe000, end: 0xffff };
439
+
440
+ /**
441
+ * The ranges of an image where the CPU sees ROM and not the RAM of the
442
+ * image, so a JSR there runs the ROM: with coverage, the image bytes that the
443
+ * runs used only as ROM; without coverage, the ROMs that $01 of the entry
444
+ * state switches in. A range with known code (`known`) in it is left out:
445
+ * that code stays code.
446
+ */
447
+ export function romRanges(coverage: Uint8Array | undefined, state: Record<string, unknown> | undefined, image: (address: number) => number | undefined, known: readonly number[]): AddressRange[] {
448
+ let ranges: AddressRange[] = [];
449
+ if (coverage !== undefined) ranges = romOnlyRanges(coverage, image);
450
+ else {
451
+ const port = (state?.cpuPort as Record<string, unknown> | undefined)?.$01;
452
+ const use = typeof port === "number" ? romUseOfPort(port) : { basic: false, kernal: false };
453
+ for (const rom of [...(use.basic ? [BASIC_ROM] : []), ...(use.kernal ? [KERNAL_ROM] : [])]) {
454
+ for (let address = rom.start; address <= rom.end; address++) {
455
+ if (image(address) === undefined) continue;
456
+ const last = ranges.at(-1);
457
+ if (last !== undefined && last.end === address - 1) last.end = address;
458
+ else ranges.push({ start: address, end: address });
459
+ }
460
+ }
461
+ }
462
+ return ranges.filter((range) => !known.some((address) => address >= range.start && address <= range.end));
463
+ }
464
+
436
465
  export type Decoded = Record<string, unknown>;
437
466
 
438
467
  const bits = (value: number) => [0, 1, 2, 3, 4, 5, 6, 7].filter((bit) => (value & (1 << bit)) !== 0);
package/src/script.ts CHANGED
@@ -88,7 +88,7 @@ export type OptionKind =
88
88
  | "number" // a value: $ and hex digits, decimal, or % and binary digits
89
89
  | "address" // $ and 1 to 4 hex digits, or a name
90
90
  | "range" // <start>-<end>, each an address
91
- | "space" // c64, drive8, or bank0 to bank255
91
+ | "space" // c64, drive8, loading, or bank0 to bank255
92
92
  | "choice"; // one of `choices`
93
93
 
94
94
  export interface OptionSpec {
@@ -121,7 +121,7 @@ export interface OptionSpec {
121
121
  /** The options that have one meaning in every script. A command can change the help, the value and whether it is required, never the kind. */
122
122
  export const OPTIONS = {
123
123
  out: { kind: "path", value: "<path>", help: "write the output here, relative to the project folder" },
124
- space: { kind: "space", value: "<space>", help: "the knowledge space: c64 (the default), drive8 for 1541 drive code, or bank0 to bank255 for a cartridge bank", default: "c64" },
124
+ space: { kind: "space", value: "<space>", help: "the knowledge space: c64 (the default), drive8 for 1541 drive code, loading for a captured stage of the loading, or bank0 to bank255 for a cartridge bank", default: "c64" },
125
125
  range: { kind: "range", value: "<start>-<end>", help: "only the addresses from start to end, for example '$c000-$cfff'" },
126
126
  entry: { kind: "address", value: "<address>", help: "an entry point of the program" },
127
127
  steps: { kind: "path", value: "<file>", help: "a JSON file of action steps that run after the start" },
@@ -608,7 +608,7 @@ export function parseCall(script: ScriptSpec, command: CommandSpec, argv: readon
608
608
  if (text === "") throw new UsageError(`--${name} needs a value`);
609
609
  if (spec.kind === "address" && !isAddressText(text)) throw new UsageError(`--${name} must be ${ADDRESS_FORM}, not ${JSON.stringify(text)}`);
610
610
  if (spec.kind === "range" && rangeParts(text) === undefined) throw new UsageError(`--${name} must be <start>-<end>, each ${ADDRESS_FORM}, for example '$c000-$cfff', not ${JSON.stringify(text)}`);
611
- if (spec.kind === "space" && !SPACE_PATTERN.test(text)) throw new UsageError(`--${name} must be c64, drive8, or bank0 to bank255, not ${JSON.stringify(text)}`);
611
+ if (spec.kind === "space" && !SPACE_PATTERN.test(text)) throw new UsageError(`--${name} must be c64, drive8, loading, or bank0 to bank255, not ${JSON.stringify(text)}`);
612
612
  if (spec.kind === "choice" && !(spec.choices ?? []).includes(text)) throw new UsageError(`--${name} must be one of ${(spec.choices ?? []).join(", ")}, not ${JSON.stringify(text)}`);
613
613
  if (spec.kind === "path") {
614
614
  if (spec.output === undefined) checkPath(text, `--${name}`, true);