@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
@@ -0,0 +1,78 @@
1
+ # The loader
2
+
3
+ This file gives the loader program of `generate --out <dir> --loader`, the fields of `loader` in its result, and the action for each result. For the command, see the section "Generate the source" of `SKILL.md`.
4
+
5
+ ## The loader program
6
+
7
+ `--loader` writes `loader.asm` in `--out`. It also writes the loader program and its symbols in `build/`. Git ignores `build/`.
8
+
9
+ - `loader.program` is the loader program. `loader.symbols` is its symbols file. The symbols file holds the labels of `loader.asm`, `main.asm` and `start_screen_stage.asm`. Give the two files to a test of the loader program.
10
+ - The loader program has the switch values of `config.asm`. With the defaults, it is the clean program: no copy protection, all corrections and no leftovers. The entry state is the state of the base release.
11
+ - The name of the loader program changes with the switch values. Then the script removes the loader program of the earlier run and its symbols.
12
+ - The loader program sets the entry state of the capture and jumps to the entry. It sets the memory, $00/$01, the registers, the VIC-II, the colour RAM, the raster line and the CIA timers.
13
+ - The loader changes the free stack byte below the stack pointer (`stackByte`). It does not set the SID, the time of day of the CIAs, the CIA interrupt flags or the interrupt registers of the VIC-II. A program that reads SID voice 3 for random numbers can thus give a different result. When you compare the reference and the rebuild, observe after the program sets its own random numbers.
14
+ - For the loader program of a release, build `loader.asm` with the build option `--release <label>`. This is possible only when `loader.packed` is not in the result. That loader program also does not have the leftovers.
15
+
16
+ ## The start screen
17
+
18
+ - When the knowledge has a start screen and `START_SCREEN` is 1, the loader program shows the start screen. It waits until the user releases all keys and fire buttons. Then it waits for a key, or for a fire button on joystick port 1 or 2, and for its release. A move of a joystick is not a key.
19
+ - The start screen needs the VIC-II values of the entry state. Its screen, bitmap, charset and colours must be in a segment of the program, or in a captured stage. See "The start screen of a captured stage".
20
+ - The start screen is part of the clean build only. A release build has no start screen. `LEFTOVERS = 1` also turns it off.
21
+ - To start the program at once, build the source with the switch value `START_SCREEN=0`. The build then also gives its loader program. See "The loader of other switch values".
22
+ - A test, a run and a replay of the loader program pass the start screen.
23
+
24
+ ## The loader of other switch values
25
+
26
+ To get the loader program of other switch values, build `main.asm` of the source with these switch values, for example `TRAINER=1`. `config.asm` does not change. The build result then has the loader program in `loader.out` and its symbols file in `loader.symbolsFile.out`. No check of this loader program runs, so `loader.verified` is `false`. Test the loader program before you trust it.
27
+
28
+ The build refuses the loader program in these cases:
29
+
30
+ - A segment of the program starts below $0400.
31
+ - The switch values change a byte that `loader.asm` holds between its free ranges.
32
+ - The start screen is of a captured stage.
33
+
34
+ In these cases, set the switch values in `config.asm`. Then run `generate --out <dir> --loader`.
35
+
36
+ ## The fields of the loader
37
+
38
+ `loader` holds these fields:
39
+
40
+ - `program` and `symbols`: the loader program and its symbols file.
41
+ - The `copies` in their order, `copier` and `stackByte`.
42
+ - `verified: true`: the check ran the loader program to its jump to the entry. There, the memory, $00/$01, the registers, the VIC-II and the colour RAM are equal to the entry state. The raster line and the CIA values are also equal. An interrupt can run right at the entry, as in the program of the base release.
43
+ - `limits`: each CIA value that the loader cannot set as it was at the entry. An old capture has no CIA values or no colour RAM. Then capture the program again at its entry point.
44
+ When no free RAM outside the segments has room for the 1000 colours, the loader does not set the colour RAM, and `limits` tells this. Then the program starts with other colours where it does not write them.
45
+ - `startScreen`: with a start screen, `shown: true` when the VIC-II had the values of the start screen, and `waits: true` when the start screen waited without a key.
46
+ - `packed`: `packedBytes` and `unpackedBytes` of the packed form. A program that is too large for one loader file gets the packed form. With a start screen of a captured stage, this is the packed program in the loader program.
47
+ - `stage`: the show stage of a start screen of a captured stage. It has the `space` of the stage and the address of the show `code`. It also has the `bytes` of the stage in the loader program, the `stash` copies, `packedBytes` and `unpackedBytes`. `startScreen.stage` names the space.
48
+ - When the check of the loader program cannot run, the script does not write a loader program. The loader program of an earlier run stays as it was. `loader.asm` is new. `reason` tells why the check did not run.
49
+ - `kept`: when the result has no new loader program, the paths of the loader programs of an earlier run. They are not of this source.
50
+
51
+ ## When the loader is not verified
52
+
53
+ Do these actions when `verified` is `false`:
54
+
55
+ | Field | Action |
56
+ |---|---|
57
+ | `reason` about the copy order, the free pages or the count of copies | The reason gives the ranges. Capture the program again with fewer segments. If this is not possible, stop the task and give the reason to the user. |
58
+ | `reason` about the packed form | If a tool is missing, stop the task and give the message to the user. If the free ranges are too small, stop the task and give the reason to the user. If the check of the unpack fails, give the reason to the user. |
59
+ | `reason` that the source does not assemble | Correct the source first. The loader includes the source. |
60
+ | `reason` about the start screen | Correct the start screen in the project knowledge, or capture the program again with the start screen in memory. If the start screen is not necessary, remove it from the project knowledge. |
61
+ | `reason` about the show stage | If the reason names the coverage of the stage, run the stage with coverage. Put the map into the project knowledge in the space of the stage. If the memory is too small, capture the stage again with less memory. If a tool is missing, stop the task and give the message to the user. If `start_screen_stage.asm` does not assemble, stop the task and give the reason to the user. The reason names the file in `.c64-re-tools/local/` with the source that failed. |
62
+ | `reason` that the check of the loader program did not run | Stop the task and give the reason to the user. When the user tells you that the emulator is available, run the same command again. |
63
+ | `differences` | The loader ran. The list gives the bytes and the registers that are not equal. |
64
+ | `stop` | The loader did not get to its copier or its jump. `stop` gives the address and `port`, the value of $01. `history` gives the last 16 instructions. `cause` gives the first byte of the copier or of a copy that is not correct. |
65
+
66
+ ## The start screen of a captured stage
67
+
68
+ Often the loading stage of a program shows a picture that is not in memory at the entry. Then the knowledge has the picture in the captured stage of the space `loading`. `--stage` of the start screen names that space. `--call` names a routine of the stage, for example the routine that starts the loading tune.
69
+
70
+ The loader program then shows the start screen before it unpacks the program. The program stays packed while the screen shows. Thus the picture and the tune have more free memory.
71
+
72
+ - The script puts everything in memory. It does not matter where the stage keeps its bytes, if the memory has enough room.
73
+ - The loader program has only the bytes of the stage that the start screen uses. These are the screen, the bitmap and the charset. With a call, they are also each byte of the stage that is not free from the call, as in "The free ranges". A call thus needs the coverage of the stage.
74
+ - With colours from the colour RAM of the capture, the loader program sets the colour RAM to these colours.
75
+ - The patches of the stage are in at the defaults of their switches. Thus a patch under a switch can remove the text of a crack from the picture.
76
+ - `start_screen_stage.asm` holds the show code and the bytes of the stage. Do not edit it. To make the loader program again, run `generate --out <dir> --loader`.
77
+ - The show stage needs Exomizer. The show code needs free memory in $0400-$9fff or $c000-$cfff. When the memory is too small, the reason gives the largest free ranges.
78
+ - The check also compares the VIC-II, the screen bytes and the colour RAM with the start screen.
@@ -0,0 +1,46 @@
1
+ # Source format
2
+
3
+ This file gives the files, the names and the lines of the source that `generate` writes. For the command, see the section "Generate the source" of `SKILL.md`.
4
+
5
+ ## The source files
6
+
7
+ - `main.asm` sets the address of each segment. It includes the files in address order.
8
+ - Each module in the knowledge is one file. A module starts at its address. It stops at the next module or at the end of its segment. The file of a module can be in a folder, for example `music/driver.asm`. Without modules, each segment is one file, `segments/segment_xxxx.asm`.
9
+ - `constants.asm` holds the names of addresses outside the program, for example `EXTCOL = $d020`. It also holds the register names in the program, for example `RASTER = $d012`. The names are in groups by memory area, in address order. Drive code and banks have one group only.
10
+ - The side comment of a constant is the knowledge comment of the address. Without a comment, it is the platform meaning. When the knowledge name is not the platform name, the platform name comes first. For an I/O mirror without a meaning, the comment gives the register that the mirror repeats.
11
+ - After the side comment, `Used:` counts how the source uses the name. The kinds are `read`, `written`, `modified`, `called`, `jumped to`, `jumped through`, `branched to`, `pointer`, `address`, `table` and `macro argument`. `address` is an immediate operand expression. `table` is an entry in a table of addresses. A macro line counts one `macro argument` for each name in its args. The other bytes that the macro reads or writes, for example the high byte of a 16-bit value, count for no name.
12
+ - `config.asm` holds the value of each switch, for example `PROTECTION = 0`. The switches are in groups by kind. The side comment gives the releases that have the switch on, the ranges of its patches and the comment of the switch.
13
+ - You can change a value in `config.asm` to 0 or 1. The next run keeps the values of the file. It adds a new switch with its default. It removes a switch that the knowledge does not have.
14
+ - `start_screen.asm` is the code that shows the start screen and waits. It is the same for each program.
15
+ - `switches.asm` holds each release of the knowledge. `main.asm` and `loader.asm` include it first. The script writes it only when the knowledge has switches or releases, or when the source has leftovers. For each release, a block `!ifdef RELEASE_<label>` gives each switch the value of that release.
16
+ - `leftovers/leftover_xxxx.asm` holds a range of leftovers. See "The leftovers".
17
+ - `macros.asm` holds the macros of the knowledge. `main.asm` and `loader.asm` include it.
18
+
19
+ ## Names in the source
20
+
21
+ - A label or a constant gets the name of the address in the knowledge.
22
+ - Without a knowledge name, it gets the platform name, for example `EXTCOL` or `CHROUT`. A platform name wins over an analyzer name (`dxa`, `decompiler` or `heuristic`), for example `EXTCOL` over `ld020`. A `user` or `llm` name wins over a platform name.
23
+ - An address in the program without a name gets `l_xxxx`.
24
+ - A read or a write in the I/O area `$d000-$dfff` uses the register, also when the program has RAM there. For example, `lda $dd0e` is `lda CI2CRA` and `sta $d012` is `sta RASTER`. `constants.asm` has these names. An address without a platform name stays a number, for example `sta $d800,x`. The data label of the RAM stays at its data. A `user` or `llm` name of the address wins over the register.
25
+ - A platform name in an operand expression of the knowledge stays in the source. When the program has the address, `constants.asm` has the name, and the RAM there keeps its label.
26
+ - The source does not use the names of a ROM that the program does not use. `romNamesLeftOut` gives these ROMs.
27
+ - When the program uses no ROM, the zero page and pages 2 and 3 get no system names. An operand expression or a macro use with such a name gets that reason.
28
+
29
+ ## Lines in the source
30
+
31
+ - `sta $d011 ; $d011: yScroll 3, rows 25, displayEnabled` is a store of an immediate to a register with a known meaning. The side comment gives the decoded value. A side comment in the knowledge replaces it.
32
+ - Code regions, and the decoded instructions outside of data regions, become instructions.
33
+ - Data regions become data by their type: `!byte`, `!word`, `!pet`, `!scr`, `!fill`, tables of labels, and sprite bytes in binary.
34
+ - `lda+2 $0012` is an absolute operand below $0100. `+1` is a zero-page operand with a label.
35
+ - `sta NMINV+1` is an address inside a platform entry of more than one byte, for example the high byte of a vector.
36
+ - `lda room_colours+5` is an address inside a data region with a named start. The address has no name of its own.
37
+ - `name = * + 1` is a label inside an instruction, for example for code that changes its own operand.
38
+ - `lda #<irq_handler` and `lda bar_colours-1,x` are operand expressions of the knowledge. An expression in a non-immediate mode that starts with a bracket gets `0+` before it. ACME reads `(...)` as indirect.
39
+ - `; = <irq_handler` at the end of an instruction with a number: the source cannot use this operand expression. `operandsAsNumbers` gives the reason.
40
+ - `!byte` with an instruction as its comment: ACME writes this instruction with a different opcode. The bytes keep the source identical.
41
+ - `not decoded` marks bytes in a code region that the script did not decode.
42
+ - `; not executed $xxxx-$yyyy` starts code that no run of the coverage executed. The range is an item of `notExecuted`.
43
+ - `+inc16 ptr` is a use of a macro of the knowledge. The comments inside a use go to its side comment.
44
+ - `!zone patch_PROTECTION_100e` starts a patch. The condition is the switch state that the program does not have. It is `!if TRAINER` when the base release has the switch off. It is `!if PROTECTION = 0` when the base release has it on.
45
+ - A patch block has the code of the patch and NOP to the end of the range. `else` has the code of the base release. The labels inside the range come before the zone as `name = * + n`.
46
+ - Alternatives are patches of two or more switches at one range. They follow as `} else { !if FIX_B {`. A line before them stops the build with `!error` when two of them are in.
@@ -7,13 +7,16 @@
7
7
  // decoded instructions. Pass A starts at the entry and the hardware vectors:
8
8
  // it tells what the program can reach. Pass B also starts at each block that
9
9
  // a run executed, at --keep and at the patches that the export changed: it
10
- // tells what stays. Without coverage nothing becomes free by itself.
10
+ // tells what stays. Without coverage nothing becomes free by itself. While the
11
+ // program has a flow whose targets the knowledge does not give (an indirect
12
+ // jump through a vector that a run wrote, or a jump whose address a run
13
+ // wrote), code that nothing reaches is unknown: it stays.
11
14
 
12
15
  import { type AddressRange, COVERAGE, formatC64Address, pointerTableEntries, POINTER_TABLE_TYPES, type PointerTableType } from "#src/c64.ts";
13
16
  import { symbolsPath } from "#src/build-name.ts";
14
17
  import { Refusal } from "#src/errors.ts";
15
- import { NO_FALL_THROUGH, type Root, separate } from "#src/knowledge/separate.ts";
16
- import type { RegionType } from "#src/knowledge/schema.ts";
18
+ import { NO_FALL_THROUGH, type Root, separate, type UnresolvedFlow, unresolvedFlows } from "#src/knowledge/separate.ts";
19
+ import { isSemantic, type RegionType } from "#src/knowledge/schema.ts";
17
20
  import { OPCODES } from "#src/opcodes.ts";
18
21
 
19
22
  /**
@@ -62,7 +65,8 @@ export interface DropInput {
62
65
  instructions: ReadonlyMap<number, number>;
63
66
  coverage?: Uint8Array;
64
67
  regions: ReadonlyArray<{ start: number; end: number; type: RegionType }>;
65
- references: ReadonlyArray<{ from: number; to: number; kind: string }>;
68
+ /** A reference of the user or the LLM resolves the flow of its instruction. */
69
+ references: ReadonlyArray<{ from: number; to: number; kind: string; origin?: string }>;
66
70
  /** The addresses that the operand expression of an instruction names, by the address of each instruction with an operand expression; none for a constant. */
67
71
  operandTargets: ReadonlyMap<number, readonly number[]>;
68
72
  /** The ranges where the CPU sees ROM and not the RAM of the image: code does not go there, and no address points there. */
@@ -87,6 +91,10 @@ export interface DropPlan {
87
91
  unreachableExecuted: Array<AddressRange & { routine?: string }>;
88
92
  /** False when the image has no entry and no hardware vectors: then nothing is unreachable. */
89
93
  rooted: boolean;
94
+ /** Code that nothing reaches and that no run executed, which stays because of the flows in `unresolved`. */
95
+ unknown: AddressRange[];
96
+ /** The flows whose targets the knowledge does not give. */
97
+ unresolved: UnresolvedFlow[];
90
98
  }
91
99
 
92
100
  const inside = (address: number, ranges: readonly AddressRange[]) => ranges.some((range) => address >= range.start && address <= range.end);
@@ -318,8 +326,13 @@ export function planDrops(input: DropInput): DropPlan {
318
326
  }
319
327
  const passB = separate({ segments: [...input.segments], memory: input.memory, ...(input.entry === undefined ? {} : { entry: input.entry }), codeRegions: asRegions(candidates), references, roots: extra });
320
328
  const automatic = input.coverage !== undefined && rooted;
321
- const stays = candidates.filter((_, index) => !automatic || passB.codeRegions[index]!.reachable !== false);
322
- const droppedCode = candidates.filter((_, index) => automatic && passB.codeRegions[index]!.reachable === false);
329
+ const unreachableCode = candidates.filter((_, index) => automatic && passB.codeRegions[index]!.reachable === false);
330
+ // A flow that nobody resolved can go to any of that code: it stays, as unknown.
331
+ const resolvedSites = new Set(input.references.filter((reference) => isSemantic(reference.origin)).map((reference) => reference.from));
332
+ const unresolved = unreachableCode.length === 0 ? [] : unresolvedFlows({ starts: [...instructions.keys()].sort((a, b) => a - b), memory: input.memory, inImage, coverage: input.coverage, resolvedSites });
333
+ const droppedCode = unresolved.length === 0 ? unreachableCode : [];
334
+ const unknown = unresolved.length === 0 ? [] : merged(unreachableCode);
335
+ const stays = candidates.filter((block) => !droppedCode.includes(block));
323
336
  const inStaying = (address: number) => stays.some((block) => address >= block.start && address <= block.end);
324
337
  for (const range of input.drop) {
325
338
  const into = flows.find((flow) => inStaying(flow.from) && inside(flow.to, [range]));
@@ -378,7 +391,7 @@ export function planDrops(input: DropInput): DropPlan {
378
391
  const routine = routines.filter((item) => item.address <= range.start).at(-1)?.name;
379
392
  return { ...range, ...(routine === undefined ? {} : { routine }) };
380
393
  });
381
- return { free, unreachableExecuted, rooted };
394
+ return { free, unreachableExecuted, rooted, unknown, unresolved };
382
395
  }
383
396
 
384
397
  /** The label of a free range. */
@@ -10,6 +10,8 @@
10
10
  // copier, and the copier writes only pages $0002-$03ff. With a start
11
11
  // screen in the knowledge, the copier shows it after the copies and waits for
12
12
  // a key or a fire button: the code is start-screen.asm, the same for each program.
13
+ // After the start screen, which writes the colour RAM, the copier sets the
14
+ // colour RAM of the entry from a free range where the copies or the unpack put it.
13
15
  // The loader loads the segments without the leftovers: the ranges of the
14
16
  // source that nothing uses are not in the loader program.
15
17
 
@@ -17,17 +19,14 @@ import { readFileSync } from "node:fs";
17
19
  import { fileURLToPath } from "node:url";
18
20
 
19
21
  import { COPIER_LINE } from "#src/build-name.ts";
20
- import { type AddressRange, formatC64Address, formatC64Byte, prgRange } from "#src/c64.ts";
21
- import { compareBuild, mergedPrograms } from "#src/compare.ts";
22
+ import { type AddressRange, formatC64Address, formatC64Byte } from "#src/c64.ts";
22
23
  import { Refusal } from "#src/errors.ts";
23
24
  import { parseEntryState } from "#src/host-client/entry-state.ts";
24
25
  import { isRomFont, startScreenRanges, type StartScreenRow } from "#src/knowledge/read.ts";
25
- import { LOADER_JUMP } from "#src/knowledge/start-screen.ts";
26
+ import { capturedColourRam, LOADER_JUMP } from "#src/knowledge/start-screen.ts";
27
+ import { COPIER_SOURCE } from "#src/loader.ts";
26
28
  import { romUseOfPort } from "#src/platform.ts";
27
29
  import { WireFailure } from "#src/host-client/tools.ts";
28
- import { pack } from "#src/native/exomizer.ts";
29
- import type { ToolContext } from "#src/native/run.ts";
30
- import type { AssembledSymbol } from "#src/native/types.ts";
31
30
 
32
31
  export interface EntryState {
33
32
  pc: number;
@@ -44,6 +43,8 @@ export interface EntryState {
44
43
  vic?: { registers: Uint8Array; bank: number };
45
44
  /** CIA 1 and CIA 2 at the entry. */
46
45
  cia?: [EntryCia, EntryCia];
46
+ /** The colour RAM at the entry: 1000 colours from $d800. */
47
+ colourRam?: Uint8Array;
47
48
  }
48
49
 
49
50
  /** A CIA at the entry: $xx00-$xx0f as a read without side effects gives them, and what no read gives. */
@@ -81,7 +82,8 @@ const FLAG_BITS = { n: 0x80, v: 0x40, d: 0x08, i: 0x04, z: 0x02, c: 0x01 } as co
81
82
 
82
83
  /**
83
84
  * The entry state that the loader recreates: the shared entry state of the
84
- * program capture, with the flags as PLP reads them, the VIC-II and the CIAs.
85
+ * program capture, with the flags as PLP reads them, the VIC-II, the CIAs and
86
+ * the colour RAM.
85
87
  */
86
88
  export function loaderState(value: unknown, where: string): EntryState {
87
89
  const state = parseEntryState(value, where);
@@ -90,7 +92,8 @@ export function loaderState(value: unknown, where: string): EntryState {
90
92
  };
91
93
  let flags = 0x20;
92
94
  for (const [name, bit] of Object.entries(FLAG_BITS)) if (state.flags[name as keyof typeof FLAG_BITS]) flags |= bit;
93
- return { pc: state.pc, a: state.a, x: state.x, y: state.y, sp: state.sp, flags, port: state.port, pages: state.pages, ...readVic(state.raw.io as Record<string, any> | undefined, fail), ...readCia(state.raw, fail) };
95
+ const colourRam = capturedColourRam(state.raw);
96
+ return { pc: state.pc, a: state.a, x: state.x, y: state.y, sp: state.sp, flags, port: state.port, pages: state.pages, ...readVic(state.raw.io as Record<string, any> | undefined, fail), ...readCia(state.raw, fail), ...(colourRam === undefined ? {} : { colourRam }) };
94
97
  }
95
98
 
96
99
  export interface Copy {
@@ -127,17 +130,19 @@ export interface LoaderPlan {
127
130
  packed?: { start: number };
128
131
  /** The VIC-II values that the start screen sets, when the knowledge has one. */
129
132
  startScreen?: StartScreenPlan;
133
+ /** The range where the copier reads the colours of the entry state, when the loader sets the colour RAM. */
134
+ colours?: AddressRange;
135
+ /** Why the loader does not set the colour RAM, when it does not. */
136
+ colourLimit?: string;
130
137
  }
131
138
 
132
139
  /**
133
140
  * What the loader cannot set as it was at the entry. An entry state
134
141
  * without CIA values (from a capture of an older version) gives no timers at all.
135
142
  */
136
- export function loaderLimits(plan: { cia?: CiaPlan }): string[] {
137
- if (plan.cia === undefined) {
138
- return ["The entry state has no CIA values, so the loader does not set the CIA timers. Capture the program again at its entry point to get them."];
139
- }
140
- return plan.cia.limits;
143
+ export function loaderLimits(plan: { cia?: CiaPlan; colourLimit?: string }): string[] {
144
+ const cia = plan.cia === undefined ? ["The entry state has no CIA values, so the loader does not set the CIA timers. Capture the program again at its entry point to get them."] : plan.cia.limits;
145
+ return [...cia, ...(plan.colourLimit === undefined ? [] : [plan.colourLimit])];
141
146
  }
142
147
 
143
148
  export { LOADER_JUMP, START_SCREEN_CONTINUE, START_SCREEN_WAIT } from "#src/knowledge/start-screen.ts";
@@ -208,6 +213,10 @@ const COPIER_CODE_SIZE = 167;
208
213
  /** The VIC-II code of the copier, without its two tables of one byte per register. */
209
214
  const VIC_CODE_SIZE = 44;
210
215
  const VIC_SIZE = VIC_CODE_SIZE + 2 * VIC_DISPLAY_REGISTERS.length;
216
+ /** The colours of the colour RAM at $d800-$dbe7. */
217
+ const COLOURS = 1000;
218
+ /** The colour code of the copier: its copy of the colours into the colour RAM. */
219
+ const COLOUR_CODE_SIZE = 35;
211
220
  /** The copier and the stub's move of it: two pages, or three with a start screen. */
212
221
  const COPIER_LIMIT = 0x200;
213
222
  /** The bytes that the stub adds for each more page of the copier: lda and sta. */
@@ -494,8 +503,6 @@ function settingsLines(input: LoaderInput): string[] {
494
503
  /** The label of a block: its first byte and the byte after it in the loader file, and its first address where it runs. */
495
504
  const blockLabel = (start: number, part: "from" | "end" | "to") => `loader_${part}_${start.toString(16).padStart(4, "0")}`;
496
505
  const plus = (label: string, offset: number) => (offset === 0 ? label : `${label}+${offset}`);
497
- /** The label of the copier in the loader file, which the stub moves to its two pages. */
498
- export const COPIER_SOURCE = "loader_copier_src";
499
506
 
500
507
  /** A block of the loader: a segment with its files, or bytes of pages 0-3. */
501
508
  interface Block {
@@ -521,6 +528,23 @@ function byteLines(range: AddressRange, bytes: (address: number) => number): str
521
528
  * An image too large for one loader file gets the packed form (see planPacked). Refuses by name when no plan exists.
522
529
  */
523
530
  export function planLoader(input: LoaderInput): LoaderPlan {
531
+ const { colourRam } = input.state;
532
+ if (colourRam === undefined) return { ...planForm(input, undefined)!, colourLimit: "The entry state has no colour RAM, so the loader does not set it. Capture the program again at its entry point to get it." };
533
+ // The colours take 1000 bytes of free RAM and make the loader larger: a plan that has no room for them is made without them.
534
+ try {
535
+ const plan = planForm(input, colourRam);
536
+ if (plan !== undefined) return plan;
537
+ } catch (error) {
538
+ if (!(error instanceof WireFailure)) throw error;
539
+ }
540
+ return {
541
+ ...planForm(input, undefined)!,
542
+ colourLimit: `The loader has no room for the ${COLOURS} colours of the colour RAM in ${COLOUR_AREAS.map(show).join(" or ")} outside the segments, the loader and its copier, so it does not set the colour RAM. The program starts with the colours that the loader leaves there.`,
543
+ };
544
+ }
545
+
546
+ /** The plain or the packed plan, with the colours of the colour RAM when they are given. Undefined when the colours have no room. */
547
+ function planForm(input: LoaderInput, colours: Uint8Array | undefined): LoaderPlan | undefined {
524
548
  const { state } = input;
525
549
  const screen = checkStartScreen(input);
526
550
  const copierBytes = screen === undefined ? COPIER_LIMIT : COPIER_LIMIT + 0x100;
@@ -550,20 +574,24 @@ export function planLoader(input: LoaderInput): LoaderPlan {
550
574
  }
551
575
  const cia = ciaSection(state);
552
576
  const ciaSize = cia === undefined ? 0 : cia.ops.reduce((sum, op) => sum + op.bytes, 0);
553
- const codeSize = COPIER_CODE_SIZE + (state.vic === undefined ? 0 : VIC_SIZE) + ciaSize + (screen === undefined ? 0 : START_SCREEN_SIZES[screen.colourMode]);
577
+ const codeSize = COPIER_CODE_SIZE + (state.vic === undefined ? 0 : VIC_SIZE) + ciaSize + (screen === undefined ? 0 : START_SCREEN_SIZES[screen.colourMode]) + (colours === undefined ? 0 : COLOUR_CODE_SIZE);
578
+ // The colours come after the blocks in the loader file. Their copy runs first, to a free range outside the loader file.
579
+ const colourSource = at;
580
+ if (colours !== undefined) at += COLOURS;
581
+ const copyCount = plain.length + (colours === undefined ? 0 : 1);
554
582
  const copierImage = at;
555
- const end = copierImage + codeSize + COPY_ENTRY * plain.length + 2 - 1;
556
- if (input.packed === true) return planPacked(input, blocks, cia, codeSize, screen, "The start screen of a captured stage shows while the program is still packed.");
583
+ const end = copierImage + codeSize + COPY_ENTRY * copyCount + 2 - 1;
584
+ if (input.packed === true) return planPacked(input, blocks, cia, codeSize, screen, "The start screen of a captured stage shows while the program is still packed.", colours);
557
585
  // The end can be past $ffff, which is no address.
558
- if (end > LOAD_LIMIT) return planPacked(input, blocks, cia, codeSize, screen, `The plain loader would end ${end > 0xffff ? "past $ffff" : `at ${formatC64Address(end)}`}, after ${formatC64Address(LOAD_LIMIT)}: loading it would write the I/O area.`);
586
+ if (end > LOAD_LIMIT) return planPacked(input, blocks, cia, codeSize, screen, `The plain loader would end ${end > 0xffff ? "past $ffff" : `at ${formatC64Address(end)}`}, after ${formatC64Address(LOAD_LIMIT)}: loading it would write the I/O area.`, colours);
559
587
  // The CIA part and the start screen take room from the copy table in the copier's pages.
560
588
  const maxCopies = Math.max(0, Math.min(TABLE_COPIES, Math.floor((copierBytes - codeSize - 2) / COPY_ENTRY)));
561
- if (plain.length > maxCopies) return planPacked(input, blocks, cia, codeSize, screen, `The plain loader needs ${plain.length} copies, and its copier can do at most ${maxCopies}.`);
589
+ if (copyCount > maxCopies) return planPacked(input, blocks, cia, codeSize, screen, `The plain loader needs ${copyCount} copies, and its copier can do at most ${maxCopies}.`, colours);
562
590
 
563
591
  const order = copyOrder(plain);
564
592
  if (order === undefined) {
565
593
  const clashing = plain.filter((copy) => plain.some((other) => other !== copy && overlaps(copy.target, other.source))).map((copy) => `${copy.what} (packed at ${show(copy.source)})`);
566
- throw new WireFailure("invalid-input", `No copy order exists: each of these copies writes over the packed bytes of another one: ${clashing.join(", ")}. Write the loader by hand.`);
594
+ throw new WireFailure("invalid-input", `No copy order exists: each of these copies writes over the packed bytes of another one: ${clashing.join(", ")}. Give this reason to the user.`);
567
595
  }
568
596
  const loaded = { start: LOAD, end };
569
597
  const areas = copierAreas(state.port);
@@ -572,9 +600,22 @@ export function planLoader(input: LoaderInput): LoaderPlan {
572
600
  return areas.some((area) => pages.start >= area.start && pages.end <= area.end) && !overlaps(pages, loaded) && plain.every((copy) => !overlaps(pages, copy.target));
573
601
  });
574
602
  if (copier === undefined) {
603
+ if (colours !== undefined) return undefined;
575
604
  const count = copierPages === 2 ? "two" : "three";
576
605
  throw new WireFailure("invalid-input", `No ${count} free pages exist for the copier in ${areas.map(show).join(" or ")} outside the loader (${show(loaded)}) and the targets: ${plain.map((copy) => show(copy.target)).join(", ")}.`);
577
606
  }
607
+ let colourRange: AddressRange | undefined;
608
+ if (colours !== undefined) {
609
+ // Outside the loader file, the copy of the colours writes over no source: it runs first, before a copy writes over its own source.
610
+ colourRange = freeColourRange([...input.segments, loaded, { start: copier, end: copier + copierBytes - 1 }]);
611
+ if (colourRange === undefined) return undefined;
612
+ const block = { what: "entry state colour RAM", range: colourRange, pseudo: colourRange.start, bytes: (address: number) => colours[address - colourRange!.start]! };
613
+ blocks.push(block);
614
+ packedAt.push(colourSource);
615
+ order.unshift(plain.length);
616
+ plain.push({ what: block.what, target: colourRange, source: { start: colourSource, end: colourSource + COLOURS - 1 } });
617
+ blockOf.push(colourRange.start);
618
+ }
578
619
  const copies: Copy[] = order.map((index) => {
579
620
  const copy = plain[index]!;
580
621
  return { ...copy, backward: copy.target.start > copy.source.start && overlaps(copy.target, copy.source) };
@@ -617,7 +658,7 @@ export function planLoader(input: LoaderInput): LoaderPlan {
617
658
  lines.push("}", blockLabel(block.range.start, "end"));
618
659
  }
619
660
  lines.push("", `; The copier runs at ${formatC64Address(copier)}. The flags pass through ${formatC64Address(stackByte)}, the free stack byte below the stack pointer.`, COPIER_SOURCE, `!pseudopc ${formatC64Address(copier)} {`);
620
- lines.push(...copierLines(state, cia, stackByte, input.entryName ?? formatC64Address(input.entry), screen !== undefined));
661
+ lines.push(...copierLines(state, cia, stackByte, input.entryName ?? formatC64Address(input.entry), screen !== undefined, colourRange?.start));
621
662
  copies.forEach((copy, index) => {
622
663
  // A block that starts at $0000 skips $00/$01, which the loader sets last.
623
664
  const start = copyBlocks[index]!;
@@ -640,6 +681,7 @@ export function planLoader(input: LoaderInput): LoaderPlan {
640
681
  text: `${lines.join("\n")}\n`,
641
682
  ...(cia === undefined ? {} : { cia: cia.plan }),
642
683
  ...(screen === undefined ? {} : { startScreen: screen }),
684
+ ...(colourRange === undefined ? {} : { colours: colourRange }),
643
685
  };
644
686
  }
645
687
 
@@ -647,6 +689,23 @@ export function planLoader(input: LoaderInput): LoaderPlan {
647
689
  const BELOW_VECTORS = 0xfff9;
648
690
  /** Where the packed form puts the bytes of pages 0-3: the copier reads them with all RAM visible ($01 = $34). */
649
691
  const PIECE_AREA: AddressRange = { start: 0x0400, end: BELOW_VECTORS };
692
+ /** Where the colours of the colour RAM wait for the copier, which reads them with $01 = $35: RAM outside the I/O area, below the vectors. */
693
+ const COLOUR_AREAS: readonly AddressRange[] = [
694
+ { start: 0x0400, end: 0xcfff },
695
+ { start: 0xe000, end: BELOW_VECTORS },
696
+ ];
697
+
698
+ /**
699
+ * The first free range of the 1000 colours outside the taken ranges, or
700
+ * undefined when none holds them. The screen at $0400 comes last: the colours
701
+ * there show while the loader runs.
702
+ */
703
+ function freeColourRange(taken: AddressRange[]): AddressRange | undefined {
704
+ const free = COLOUR_AREAS.flatMap((area) => subtract(area, taken))
705
+ .sort((a, b) => Number(a.start < 0x0800) - Number(b.start < 0x0800))
706
+ .find((range) => range.end - range.start + 1 >= COLOURS);
707
+ return free === undefined ? undefined : { start: free.start, end: free.start + COLOURS - 1 };
708
+ }
650
709
 
651
710
  /**
652
711
  * Where a loader puts its copier: the copier sets $01 to $35 and then to the
@@ -669,9 +728,11 @@ const SHOWN_FREE = 8;
669
728
  * and the bytes of pages $0002-$03ff, in pieces in the free ranges: the
670
729
  * unpacker of Exomizer uses the zero page and $0334-$03ff, so the copier
671
730
  * writes them after the unpack. Between its ranges, loader.asm holds the
672
- * bytes of the image, so its build does not change a segment.
731
+ * bytes of the image, so its build does not change a segment. The colours of
732
+ * the colour RAM are in one more free range, where the unpack puts them.
733
+ * Undefined when the colours have no room.
673
734
  */
674
- function planPacked(input: LoaderInput, blocks: Block[], cia: ReturnType<typeof ciaSection>, copierCode: number, screen: StartScreenPlan | undefined, tooLarge: string): LoaderPlan {
735
+ function planPacked(input: LoaderInput, blocks: Block[], cia: ReturnType<typeof ciaSection>, copierCode: number, screen: StartScreenPlan | undefined, tooLarge: string, colours: Uint8Array | undefined): LoaderPlan | undefined {
675
736
  const { state } = input;
676
737
  // The packed copier starts with SEI, as the stub of the plain form does: an interrupt in the copies would go through the vectors in RAM.
677
738
  const codeSize = copierCode + 1;
@@ -697,14 +758,17 @@ function planPacked(input: LoaderInput, blocks: Block[], cia: ReturnType<typeof
697
758
  placed.refusal === "copies"
698
759
  ? `A packed loader needs more than ${MAX_PACKED_COPIES} copies for the ${lowBytes} bytes of pages 0-3 in the free ranges.`
699
760
  : `A packed loader needs one free range of ${codeSize + COPY_ENTRY * Math.max(low.length, 1) + 2} bytes or more for its copier in ${areas.map(show).join(" or ")}, and ${lowBytes} more free bytes for pages 0-3 in ${show(PIECE_AREA)}, outside the segments. The copier runs with $01 = $35 and then with the $01 of the entry, so it is in RAM that both show.${screen === undefined ? "" : ` The start screen takes ${START_SCREEN_SIZES[screen.colourMode]} bytes of the copier: without it (unstart-screen), the copier is smaller.`}`;
700
- throw new WireFailure("invalid-input", `${tooLarge} ${why} ${ranges} Write the loader by hand.`);
761
+ throw new WireFailure("invalid-input", `${tooLarge} ${why} ${ranges} Give this reason to the user.`);
701
762
  }
702
763
  const { copier, pieces } = placed;
703
764
  const copierEnd = copier + codeSize + COPY_ENTRY * pieces.length + 2 - 1;
704
765
  // The sources are at $0400 or higher and the targets below: any order works.
705
766
  const copies: Copy[] = pieces.map((piece) => ({ what: piece.what, target: piece.target, source: { start: piece.at, end: piece.at + piece.target.end - piece.target.start }, backward: false }));
706
- const start = Math.min(copier, ...pieces.map((piece) => piece.at));
707
- const end = Math.max(copierEnd, ...copies.map((copy) => copy.source.end));
767
+ const colourRange = colours === undefined ? undefined : freeColourRange([...input.segments, { start: copier, end: copierEnd }, ...copies.map((copy) => copy.source)]);
768
+ if (colours !== undefined && colourRange === undefined) return undefined;
769
+ const colourBytes = (address: number) => colours![address - colourRange!.start]!;
770
+ const start = Math.min(copier, ...pieces.map((piece) => piece.at), ...(colourRange === undefined ? [] : [colourRange.start]));
771
+ const end = Math.max(copierEnd, ...copies.map((copy) => copy.source.end), ...(colourRange === undefined ? [] : [colourRange.end]));
708
772
  const stackByte = 0x0100 + state.sp;
709
773
  const lines: string[] = [
710
774
  ...input.header.map((line) => `; ${line}`),
@@ -725,7 +789,7 @@ function planPacked(input: LoaderInput, blocks: Block[], cia: ReturnType<typeof
725
789
  COPIER_SOURCE,
726
790
  " sei",
727
791
  // The entry by its address: main.asm, which has its label, is not in this build.
728
- ...copierLines(state, cia, stackByte, `${formatC64Address(input.entry)}${input.entryName === undefined ? "" : ` ; ${input.entryName} in main.asm`}`, screen !== undefined),
792
+ ...copierLines(state, cia, stackByte, `${formatC64Address(input.entry)}${input.entryName === undefined ? "" : ` ; ${input.entryName} in main.asm`}`, screen !== undefined, colourRange?.start),
729
793
  ];
730
794
  for (const copy of copies) {
731
795
  const [from, to] = [blockLabel(copy.target.start, "from"), blockLabel(copy.target.start, "end")];
@@ -738,6 +802,7 @@ function planPacked(input: LoaderInput, blocks: Block[], cia: ReturnType<typeof
738
802
  const text = [`; ${piece.what}`, `* = ${formatC64Address(piece.at)}`, blockLabel(piece.target.start, "from"), ...byteLines(piece.target, piece.bytes), blockLabel(piece.target.start, "end")];
739
803
  parts.push({ range, text });
740
804
  }
805
+ if (colourRange !== undefined) parts.push({ range: colourRange, text: ["; The colour RAM of the entry state: the copier puts it into $d800-$dbe7", `* = ${formatC64Address(colourRange.start)}`, ...byteLines(colourRange, colourBytes)] });
741
806
  const used = parts.map((part) => part.range);
742
807
  for (const segment of input.segments) {
743
808
  const within = { start: Math.max(segment.start, start), end: Math.min(segment.end, end) };
@@ -750,7 +815,7 @@ function planPacked(input: LoaderInput, blocks: Block[], cia: ReturnType<typeof
750
815
  for (const part of parts) lines.push("", ...part.text);
751
816
  return {
752
817
  loaded: input.segments.map(({ start, end }) => ({ start, end })),
753
- blocks: pieces.map((piece) => ({ what: piece.what, range: piece.target, packedAt: piece.at, bytes: piece.bytes })),
818
+ blocks: [...pieces.map((piece) => ({ what: piece.what, range: piece.target, packedAt: piece.at, bytes: piece.bytes })), ...(colourRange === undefined ? [] : [{ what: "entry state colour RAM", range: colourRange, packedAt: colourRange.start, bytes: colourBytes }])],
754
819
  copies,
755
820
  copier,
756
821
  stackByte,
@@ -758,6 +823,7 @@ function planPacked(input: LoaderInput, blocks: Block[], cia: ReturnType<typeof
758
823
  text: `${lines.join("\n")}\n`,
759
824
  ...(cia === undefined ? {} : { cia: cia.plan }),
760
825
  ...(screen === undefined ? {} : { startScreen: screen }),
826
+ ...(colourRange === undefined ? {} : { colours: colourRange }),
761
827
  packed: { start },
762
828
  };
763
829
  }
@@ -835,67 +901,15 @@ function placePacked(copierFree: AddressRange[], free: AddressRange[], low: Para
835
901
  return { refusal: "copies" };
836
902
  }
837
903
 
838
- /** What Exomizer makes of a packed loader. */
839
- export interface PackedLoader {
840
- /** The loader program: it loads at $0801 and starts with RUN. */
841
- program: Buffer;
842
- packedBytes: number;
843
- unpackedBytes: number;
844
- /** The CPU cycles of the unpack, when Exomizer gives them. */
845
- cycles?: number;
846
- }
847
-
848
- /**
849
- * Packs the loaded ranges of the build of main.asm from $0400 and the build of
850
- * loader.asm (the copier wins where they overlap) with the entry at the copier
851
- * and $01 = $34, and checks the unpack in the emulator of Exomizer: every byte
852
- * of the two builds, and the jump to the copier. Refuses by name when it does
853
- * not hold.
854
- */
855
- export async function packLoader(main: Uint8Array, copier: Uint8Array, plan: LoaderPlan, context: ToolContext): Promise<PackedLoader> {
856
- return packParts(packedParts(main, copier, plan), plan.copier, 0x34, "main.asm and loader.asm", "the copier", context);
857
- }
858
-
859
- /** What Exomizer packs in the packed form: the loaded ranges of the build of main.asm from $0400, and the build of loader.asm. */
860
- function packedParts(main: Uint8Array, copier: Uint8Array, plan: Pick<LoaderPlan, "loaded">): Array<{ start: number; body: Uint8Array }> {
861
- // The unpacker uses pages 0-3; the copier writes them. The leftovers between the loaded ranges are not packed.
862
- const program = prgRange(main);
863
- const ranges = plan.loaded.flatMap((range) => {
864
- const start = Math.max(range.start, 0x0400, program.start);
865
- const end = Math.min(range.end, program.start + program.body.length - 1);
866
- return start <= end ? [{ start, body: program.body.subarray(start - program.start, end - program.start + 1) }] : [];
867
- });
868
- return [...ranges, prgRange(copier)];
869
- }
870
-
871
- /**
872
- * Packs parts (a later one wins where they overlap) into one program that
873
- * unpacks itself, starts at `entry` with $01 = `exitMemory`, and checks the
874
- * unpack in the emulator of Exomizer: every byte of the parts, and the jump
875
- * to the entry. Refuses by name when it does not hold.
876
- */
877
- export async function packParts(parts: ReadonlyArray<{ start: number; body: Uint8Array }>, entry: number, exitMemory: number, what: string, entryName: string, context: ToolContext): Promise<PackedLoader> {
878
- const prg = (part: { start: number; body: Uint8Array }) => Buffer.concat([Buffer.from([part.start & 0xff, part.start >> 8]), part.body]);
879
- const packed = await pack({ programs: parts.map(prg), entry, exitMemory }, context);
880
- if (packed.entry !== entry) throw new WireFailure("operation-failed", `The unpack in the emulator of Exomizer jumps to ${formatC64Address(packed.entry)}, not to ${entryName} at ${formatC64Address(entry)}.`);
881
- const reference = mergedPrograms(parts);
882
- const wrong = compareBuild(packed.unpacked, reference).segments.find((segment) => segment.result !== "identical");
883
- if (wrong !== undefined) {
884
- const first = wrong.firstDifference === undefined ? "" : `: the first is ${wrong.firstDifference.address}, ${wrong.firstDifference.built} and not ${wrong.firstDifference.reference}`;
885
- throw new WireFailure("operation-failed", `The unpack in the emulator of Exomizer does not give ${wrong.start}-${wrong.end} of ${what} (${wrong.result}${first}).`);
886
- }
887
- const unpackedBytes = reference.segments.reduce((sum, segment) => sum + segment.end - segment.start + 1, 0);
888
- return { program: packed.program, packedBytes: packed.program.length, unpackedBytes, ...(packed.cycles === undefined ? {} : { cycles: packed.cycles }) };
889
- }
890
-
891
904
  /**
892
905
  * The copier: its copies by the table, the VIC-II and CIA parts, then $00/$01,
893
906
  * the stack pointer, the flags and A/X/Y, and the jump to the entry. It ends
894
907
  * with the label of the table; the caller writes the table and closes the zone.
895
908
  * A start screen comes after the copies, which put its bytes in place, and
896
- * before the VIC-II part, which sets the display of the entry again.
909
+ * before the VIC-II part, which sets the display of the entry again. The
910
+ * colours come after the start screen, which writes the colour RAM.
897
911
  */
898
- function copierLines(state: EntryState, cia: ReturnType<typeof ciaSection>, stackByte: number, jumpTarget: string, startScreen: boolean): string[] {
912
+ function copierLines(state: EntryState, cia: ReturnType<typeof ciaSection>, stackByte: number, jumpTarget: string, startScreen: boolean, colours: number | undefined): string[] {
899
913
  const [port0, port1] = state.port;
900
914
  return [
901
915
  "!zone loader_copier {",
@@ -953,6 +967,7 @@ function copierLines(state: EntryState, cia: ReturnType<typeof ciaSection>, stac
953
967
  " jmp .next",
954
968
  ".done",
955
969
  ...(startScreen ? START_SCREEN_LINES : []),
970
+ ...(colours === undefined ? [] : colourLines(colours)),
956
971
  // The CIA part runs after the raster wait: the wait ends its whole lines earlier, so the entry comes in its line.
957
972
  ...vicLines(state, Math.floor((cia?.ops.reduce((sum, op) => sum + op.cycles, 0) ?? 0) / LINE_CYCLES)),
958
973
  ...(cia === undefined ? [] : cia.ops.map((op) => ` ${op.text}`)),
@@ -984,6 +999,23 @@ function copierLines(state: EntryState, cia: ReturnType<typeof ciaSection>, stac
984
999
  ];
985
1000
  }
986
1001
 
1002
+ /**
1003
+ * The copier's colour part: with the I/O area visible, it copies the 1000
1004
+ * colours of the entry state from `at` into the colour RAM, in four parts of 250.
1005
+ */
1006
+ function colourLines(at: number): string[] {
1007
+ const parts = [0, 250, 500, 750];
1008
+ return [
1009
+ " lda #$35",
1010
+ " sta $01",
1011
+ " ldx #0",
1012
+ ...parts.flatMap((offset, index) => [`${index === 0 ? ".colour " : " "}lda ${formatC64Address(at + offset)},x`, ` sta ${formatC64Address(0xd800 + offset)},x`]),
1013
+ " inx",
1014
+ ` cpx #${formatC64Byte(250)}`,
1015
+ " bne .colour",
1016
+ ];
1017
+ }
1018
+
987
1019
  /**
988
1020
  * The copier's VIC-II part: with the I/O area visible it sets the
989
1021
  * display registers and the VIC bank of the entry state, then waits for the
@@ -1014,23 +1046,3 @@ function vicLines(state: EntryState, earlier: number): string[] {
1014
1046
  " bne .raster",
1015
1047
  ];
1016
1048
  }
1017
-
1018
- /**
1019
- * The symbols of the loader program: the labels of the build of loader.asm, which
1020
- * includes main.asm, and of start_screen_stage.asm when the loader has a show
1021
- * stage. A test takes one symbols file. Refuses a name with two values.
1022
- */
1023
- export function loaderSymbols(...builds: ReadonlyArray<readonly AssembledSymbol[]>): AssembledSymbol[] {
1024
- const valueOf = (symbol: AssembledSymbol) => (symbol.kind === "address" ? symbol.address : symbol.value);
1025
- const byName = new Map<string, AssembledSymbol>();
1026
- for (const symbol of builds.flat()) {
1027
- const known = byName.get(symbol.name);
1028
- if (known !== undefined && valueOf(known) !== valueOf(symbol)) {
1029
- throw new WireFailure("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.`);
1030
- }
1031
- // An address in one build can be outside the load range of the other build, where it is a constant.
1032
- const kept = known === undefined || (known.kind === "constant" && symbol.kind === "address") ? symbol : known;
1033
- byName.set(symbol.name, { ...kept, used: symbol.used || (known?.used ?? false) });
1034
- }
1035
- return [...byName.values()].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
1036
- }