@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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@henols/c64-re-tools",
3
- "version": "2.6.0-rc.2",
3
+ "version": "2.6.0-rc.3",
4
4
  "description": "Agent-friendly Commodore 64 engineering toolkit for reverse engineering, debugging, development and testing.",
5
5
  "license": "MIT",
6
6
  "author": "Henrik Olsson",
@@ -87,7 +87,7 @@ Each flag applies only to the commands in the table. On another command, the scr
87
87
  | `--set-pc <address>` | `build` | The start address when the source does not set one, for example `'$0801'`. |
88
88
  | `--release <label>` | `build` | Build a release of the project knowledge. Each switch gets the value of that release. With `--compare`, the reference is the file of the release. |
89
89
  | `--compare` | `build` | Compare the program byte by byte with the program in the project knowledge, or with the file of `--release`, segment by segment. Off by default. |
90
- | `--space <space>` | `build` | The space of the program in the project knowledge: `c64`, `drive8`, or `bank0` to `bank255`. The default is `c64`. Give it only with `--compare` or `--release`. |
90
+ | `--space <space>` | `build` | The space of the program in the project knowledge: `c64`, `drive8`, `loading`, or `bank0` to `bank255`. The default is `c64`. Give it only with `--compare` or `--release`. |
91
91
  | `--plain` | `build` | Write only the bytes of the program, without the 2-byte load address. Off by default. |
92
92
  | `--all-symbols` | `build` | List also the constants that the source does not use. Off by default. |
93
93
  | `--max-listed <n>` | `build` | List at most `n` symbols. The default is 50. `symbols.count` always gives the count of all symbols. |
@@ -45,7 +45,7 @@ await runScript({
45
45
  "set-pc": { kind: "address", value: "<address>", help: "the start address when the source sets none, for example '$0801'" },
46
46
  release: { kind: "text", value: "<label>", help: `build a release of the knowledge: defines ${RELEASE_DEFINE}<label>=1, so each switch has the value of that release. With --compare, the reference is the file of the release` },
47
47
  compare: { kind: "flag", help: "check the program byte by byte against the program in the knowledge (or the file of --release), each segment" },
48
- space: { kind: "space", value: "<space>", help: "with --compare or --release: the knowledge space of the program: c64 (the default), drive8, or bank0 to bank255" },
48
+ space: { kind: "space", value: "<space>", help: "with --compare or --release: the knowledge space of the program: c64 (the default), drive8, loading, or bank0 to bank255" },
49
49
  plain: { kind: "flag", help: "write the bytes only, without the 2-byte load address of a PRG" },
50
50
  "all-symbols": { kind: "flag", help: "list also the constants that the source does not use" },
51
51
  "max-listed": { ...OPTIONS["max-listed"], help: "list at most n symbols (default 50). The count is always given" },
@@ -53,7 +53,7 @@ The knowledge is text in `.c64-re-tools/knowledge/` of the project. Commit that
53
53
  | Write the code of a switch for a range | `patch '$100e-$1010' PROTECTION --code-file no-check.asm` |
54
54
  | List the releases, switches and patches | `switches` |
55
55
  | Record the start screen of the program | `start-screen --mode multicolour --screen '$5c00' --bitmap '$6000' --colours '$8328' --border 0 --background 0` |
56
- | Record the start screen of a captured stage, and its tune | `start-screen --mode multicolour --screen '$cc00' --bitmap '$e000' --colours '$8328' --border 3 --background 1 --stage bank1 --call '$9000'` |
56
+ | Record the start screen of a captured stage, and its tune | `start-screen --stage loading --call '$9000'` |
57
57
  | Remove the start screen | `unstart-screen` |
58
58
  | Write a macro | `macro inc16 --params dst --body-file inc16.asm` |
59
59
  | Write instructions as one use of a macro | `use '$1005-$100a' inc16 --args ptr` |
@@ -72,7 +72,7 @@ The knowledge is text in `.c64-re-tools/knowledge/` of the project. Commit that
72
72
  - An analyzer name is a second name from DXA, Ghidra or an idiom search, for example `FUN_17e2`. Each analyzer keeps its own name at an address. Get them from `at`, `search` or `symbols --analyzer`.
73
73
  - The generated source uses only the symbols. To use an analyzer name in the source, give the address that name with `rename`.
74
74
  - A symbol name is a label for ACME: a letter or an underscore, then letters, digits or underscores. The knowledge refuses the name of a 6502 instruction, for example `lda`, in upper or lower case.
75
- - A space is `c64` (the default), `drive8` for code in the 1541 drive, or `bank0` to `bank255` for cartridge banks and for a captured stage of the loading. Drive code, banks and stages use the same addresses as the C64. Thus each space has its own knowledge. A name is unique in one space.
75
+ - A space is `c64` (the default), `drive8` for code in the 1541 drive, `loading` or `bank0` to `bank255`. `loading` is the captured stage of the loading that shows the start screen. `bank0` to `bank255` are cartridge banks. Drive code, the stage and banks use the same addresses as the C64. Thus each space has its own knowledge. A name is unique in one space.
76
76
  - A revision id has the form `20261015T214501.123-k3f9qz`. It starts with the date and the time. Give the full id, or a start of the id that only one revision has. Get the ids from `revisions`, or from the `revision` field of a result. The revision `0` is the knowledge before the first revision.
77
77
  - A file of a capture is the `image.json` that the capture of a packed program wrote. Keep the other files of the capture next to it.
78
78
 
@@ -102,7 +102,7 @@ Each flag applies only to the commands in the table. On another command, the scr
102
102
 
103
103
  | Flag | Command | Effect |
104
104
  |---|---|---|
105
- | `--space <space>` | All commands | The space of the command: `c64`, `drive8`, or `bank0` to `bank255`. The default is `c64`. Without `--space`, `revert` reverts all spaces. |
105
+ | `--space <space>` | All commands | The space of the command: `c64`, `drive8`, `loading`, or `bank0` to `bank255`. The default is `c64`. Without `--space`, `revert` reverts all spaces. |
106
106
  | `--by <user\|llm>` | All commands in "Change the knowledge" | Who decided the change. The default is `llm`. Give `user` only when the user decided the change. |
107
107
  | `--reason <text>` | All commands in "Change the knowledge" | Why you make the change. The revision keeps it, and `history` shows it. |
108
108
  | `--evidence <kind:ref>` | All commands in "Change the knowledge" | One thing that the change rests on: `coverage:<map>`, `test:<file>`, `file:<file>` or `note:<text>`. You can give it more than one time. |
@@ -142,15 +142,15 @@ Each flag applies only to the commands in the table. On another command, the scr
142
142
  | `--body <text>` | `macro` | The body of the macro. |
143
143
  | `--body-file <file>` | `macro` | A project file with the body of the macro. |
144
144
  | `--args <x, y>` | `use` | One expression for each param of the macro, as a comma list. |
145
- | `--mode <mode>` | `start-screen` | Necessary. The mode of the VIC-II: `text`, `hires` or `multicolour`. |
146
- | `--screen <address>` | `start-screen` | Necessary. The address of the screen memory: 1000 bytes. |
145
+ | `--mode <mode>` | `start-screen` | The mode of the VIC-II: `text`, `hires` or `multicolour`. Necessary without `--stage`. |
146
+ | `--screen <address>` | `start-screen` | The address of the screen memory: 1000 bytes. Necessary without `--stage`. |
147
147
  | `--bitmap <address>` | `start-screen` | The address of the bitmap: 8000 bytes. `hires` and `multicolour` need it. |
148
148
  | `--charset <address>` | `start-screen` | The address of the charset: 2048 bytes. `text` needs it. |
149
149
  | `--colours <address>` | `start-screen` | The address of the 1000 bytes that the loader copies to the colour RAM. |
150
150
  | `--colour <0-15>` | `start-screen` | One colour for all of the colour RAM, in place of `--colours`. |
151
- | `--border <0-15>` | `start-screen` | Necessary. The border colour. |
152
- | `--background <0-15>` | `start-screen` | Necessary. The background colour. |
153
- | `--stage <space>` | `start-screen` | The space of a captured stage that holds the bytes of the screen, for example `bank1`. Without it, the bytes are in the program at the entry. |
151
+ | `--border <0-15>` | `start-screen` | The border colour. Necessary without `--stage`. |
152
+ | `--background <0-15>` | `start-screen` | The background colour. Necessary without `--stage`. |
153
+ | `--stage <space>` | `start-screen` | The space of the captured stage that shows the screen: `loading`. The script takes the mode, the addresses and the colours from the capture. Without it, the bytes are in the program at the entry. |
154
154
  | `--call <address>` | `start-screen` | A routine of the stage that the start screen calls before it waits, for example the start of the loading tune. It must return with RTS. It needs `--stage`. |
155
155
 
156
156
  ---
@@ -407,15 +407,30 @@ A start screen is a loading screen, a title screen or a presentation screen of t
407
407
  1. Record patches under a switch that take out the change.
408
408
  2. Use the screen as it is.
409
409
  3. Do not record a start screen.
410
- - The bytes of the screen must be in the program of the knowledge at the entry, or in a captured stage. Thus capture the program while the bytes of the screen are in memory.
411
- - When the bytes are only in a stage of the loading, do these steps:
412
- 1. Capture the stage while it shows the screen. Do not exclude the memory of the screen.
413
- 2. Put the capture into the knowledge in a space of its own, for example `image stage/image.json --space bank1`.
414
- 3. If the stage plays a tune or does other work during the screen, find the routine that starts it. Run the stage with coverage while that routine runs. Put the map into the knowledge with `coverage <map> --space bank1`.
415
- 4. Record the start screen with `--stage bank1`, and with `--call` for the routine.
416
- - With `--stage`, the addresses are in the program of that space. Each part and the call must be in it.
410
+ - The bytes of the screen must be in the program of the knowledge at the entry, or in a captured stage.
411
+
412
+ #### A start screen of a captured stage
413
+
414
+ Use this when a stage of the loading shows the screen, and the program at the entry does not have it. Do these steps:
415
+
416
+ 1. Capture the stage while it shows the screen. Do not exclude the memory of the screen.
417
+ 2. Put the capture into the knowledge in the space `loading`: `image stage/image.json --space loading`. Do not use another space for it.
418
+ 3. If the stage plays a tune or does other work during the screen, find the routine that starts it. Run the stage with coverage while that routine runs. Put the map into the knowledge with `coverage <map> --space loading`.
419
+ 4. Record the start screen with `start-screen --stage loading`, and with `--call` for the routine.
420
+
421
+ - The script takes the mode, the screen, the bitmap or the charset, the colours and the colour RAM from the capture. Do not find the addresses or the colours yourself.
422
+ - The generated source puts the screen in memory. It does not matter where the stage keeps its bytes, if the memory has enough room.
423
+ - A flag that you give replaces the value of the capture. Give a flag only to correct a value.
424
+ - A capture of an older version has no colour RAM. Then capture the stage again.
425
+
426
+ #### A start screen in the program
427
+
428
+ - Capture the program while the bytes of the screen are in memory.
417
429
  - Get the mode, the addresses and the colours from the VIC-II while the original program shows the screen.
418
- - The colour RAM is not in the capture. Find the 1000 colour bytes in the program: compare them with the colour RAM at $d800 while the original shows the screen. Give their address with `--colours`. If the program does not have them, give one colour with `--colour`.
430
+ - Find the 1000 colour bytes in the program: compare them with the colour RAM at $d800 while the original shows the screen. Give their address with `--colours`. If the program does not have them, give one colour with `--colour`.
431
+
432
+ #### The rules of the VIC-II
433
+
419
434
  - `text` needs `--charset`. `hires` and `multicolour` need `--bitmap`. `text` and `multicolour` need `--colours` or `--colour`. `hires` uses neither.
420
435
  - The screen is at a step of $0400, the bitmap at a step of $2000 and the charset at a step of $0800. They must be in one VIC bank of 16 KB.
421
436
  - In VIC bank 0 and 2, the VIC-II reads the character ROM at $1000-$1fff of the bank. A screen or a bitmap cannot be there. A charset at $1000 or $1800 of the bank is the character ROM.
@@ -18,6 +18,7 @@ import { historyAt, historyNamed, historyOfMacro, historyOfSwitch, revision, rev
18
18
  import { joinBatches, type Batch, type JoinChoice, type JoinClash } from "#src/knowledge/join.ts";
19
19
  import { knowledgeNames } from "#src/knowledge/names.ts";
20
20
  import { addCoverage, programCoverage, programImage, requireProgram, setImage, type ImageRequest } from "#src/knowledge/program.ts";
21
+ import { startScreenOfStage } from "#src/knowledge/start-screen.ts";
21
22
  import {
22
23
  analyzerNamesAt,
23
24
  at,
@@ -177,6 +178,7 @@ const startScreen = (row: StartScreenRow) => ({
177
178
  background: row.background,
178
179
  ...(row.stage === undefined ? {} : { stage: row.stage }),
179
180
  ...(row.call === undefined ? {} : { call: formatC64Address(row.call) }),
181
+ ...(row.colourRam === true ? { colourRam: true } : {}),
180
182
  ...(row.comment === undefined ? {} : { comment: row.comment }),
181
183
  origin: row.origin,
182
184
  revision: row.revision,
@@ -360,14 +362,22 @@ function imageRequest(path: string, space: string): ImageRequest {
360
362
  }
361
363
 
362
364
  /**
363
- * The program in the knowledge that operand, patch and macro use writes
364
- * are checked against, with the platform names. A byte outside
365
- * the segments of the program is not in it.
365
+ * The program of each space in the knowledge that operand, patch and macro
366
+ * use writes in that space are checked against, with the platform names. A
367
+ * byte outside the segments of the program is not in it. Each program is
368
+ * read once, when a write in its space needs it.
366
369
  */
367
- function operandImage(db: DatabaseSync, space: string): OperandImage {
368
- const image = requireProgram(db, space);
369
- const inside = (at: number) => image.segments.some((segment) => at >= segment.start && at <= segment.end);
370
- return { byteAt: (at) => (inside(at) ? image.byteAt(at) : undefined), platform: new Map(platformNames().map((entry) => [entry.name, entry.address])) };
370
+ function operandImages(db: DatabaseSync): (space: string) => OperandImage {
371
+ const images = new Map<string, OperandImage>();
372
+ return (space) => {
373
+ const known = images.get(space);
374
+ if (known !== undefined) return known;
375
+ const image = requireProgram(db, space);
376
+ const inside = (at: number) => image.segments.some((segment) => at >= segment.start && at <= segment.end);
377
+ const made: OperandImage = { byteAt: (at) => (inside(at) ? image.byteAt(at) : undefined), platform: new Map(platformNames().map((entry) => [entry.name, entry.address])) };
378
+ images.set(space, made);
379
+ return made;
380
+ };
371
381
  }
372
382
 
373
383
  /** An offset: a whole number in decimal or $ hex, with an optional minus sign. */
@@ -810,7 +820,7 @@ const WRITE_COMMANDS: CommandSpec[] = [
810
820
  request.symbol = call.string(select)!;
811
821
  if (offset !== undefined) request.offset = offsetOf(offset, "--offset");
812
822
  }
813
- return (db) => shown(setOperand(db, { ...context, image: operandImage(db, call.space) }, request), "operand", operand);
823
+ return (db) => shown(setOperand(db, { ...context, image: operandImages(db) }, request), "operand", operand);
814
824
  },
815
825
  ),
816
826
  writeCommand({ name: "unoperand", summary: "Removes the operand expression at an address.", subjects: [ADDRESS] }, (call) => {
@@ -837,7 +847,7 @@ const WRITE_COMMANDS: CommandSpec[] = [
837
847
  if ((code === undefined) === !call.flag("nop")) throw new UsageError("patch needs exactly one of --code, --code-file or --nop.");
838
848
  const commentText = call.string("comment");
839
849
  const request = { space: call.space, ...call.parseRange(call.subject(0), "<range>"), switch: call.subject(1), code: code ?? "", ...(commentText === undefined ? {} : { comment: commentText }) };
840
- return (db) => shown(setPatch(db, { ...context, image: operandImage(db, call.space) }, request), "patch", patch);
850
+ return (db) => shown(setPatch(db, { ...context, image: operandImages(db) }, request), "patch", patch);
841
851
  },
842
852
  ),
843
853
  writeCommand(
@@ -881,7 +891,7 @@ const WRITE_COMMANDS: CommandSpec[] = [
881
891
  ...(commentText === undefined ? {} : { comment: commentText }),
882
892
  };
883
893
  return (db) => {
884
- const result = setSwitch(db, { ...context, image: operandImage(db, call.space) }, request);
894
+ const result = setSwitch(db, { ...context, image: operandImages(db) }, request);
885
895
  const base = listReleases(db, undefined, call.space).find((row) => row.base)?.label;
886
896
  return shown(result, "switch", (row: SwitchRow) => switchRow(row, base));
887
897
  };
@@ -939,42 +949,62 @@ const WRITE_COMMANDS: CommandSpec[] = [
939
949
  name: "start-screen",
940
950
  summary: "Records the start screen of the program: a loading, title or presentation screen of the program itself, in memory at the entry or in a captured stage of the loading. The loader of the generated source shows it and waits for a key or a fire button before the entry.",
941
951
  options: {
942
- mode: { kind: "choice", value: "<mode>", choices: START_SCREEN_MODES, help: `one of ${START_SCREEN_MODES.join(", ")}`, required: true },
943
- screen: { kind: "address", value: "<address>", help: "the screen: the 1000 characters of a text screen, or the 1000 colour bytes of a bitmap", required: true },
952
+ mode: { kind: "choice", value: "<mode>", choices: START_SCREEN_MODES, help: `one of ${START_SCREEN_MODES.join(", ")}. Necessary without --stage` },
953
+ screen: { kind: "address", value: "<address>", help: "the screen: the 1000 characters of a text screen, or the 1000 colour bytes of a bitmap. Necessary without --stage" },
944
954
  bitmap: { kind: "address", value: "<address>", help: "the 8000 bytes of the bitmap. hires and multicolour need it" },
945
955
  charset: { kind: "address", value: "<address>", help: "the 2048 bytes of the charset, or '$1000' or '$1800' for the character ROM in VIC bank 0. text needs it" },
946
956
  colours: { kind: "address", value: "<address>", help: "the 1000 bytes that the loader copies to the colour RAM" },
947
957
  colour: { kind: "count", value: "<0-15>", min: 0, max: 15, help: "one colour for all of the colour RAM, in place of --colours" },
948
- border: { kind: "count", value: "<0-15>", min: 0, max: 15, help: "the border colour", required: true },
949
- background: { kind: "count", value: "<0-15>", min: 0, max: 15, help: "the background colour", required: true },
950
- stage: { kind: "text", value: "<space>", help: "the space of a captured stage that holds the bytes of the screen, for example bank1. Without it, the bytes are in the program at the entry" },
958
+ border: { kind: "count", value: "<0-15>", min: 0, max: 15, help: "the border colour. Necessary without --stage" },
959
+ background: { kind: "count", value: "<0-15>", min: 0, max: 15, help: "the background colour. Necessary without --stage" },
960
+ stage: { kind: "text", value: "<space>", help: "the space of the captured stage that shows the screen: loading. The script takes the mode, the addresses and the colours from the capture of the stage. Without it, the bytes are in the program at the entry" },
951
961
  call: { kind: "address", value: "<address>", help: "a routine of the stage that the start screen calls before it waits, for example the routine that starts the loading tune. It must return with RTS. Needs --stage" },
952
962
  comment: { kind: "text", value: "<text>", help: "what the screen is" },
953
963
  },
954
- notes: "Record only a screen of the program itself, never a screen of a crack. If a release changed the screen, for example with the text of a crack, stop and ask the user how to deal with it. text and multicolour need --colours or --colour; hires uses neither. With --stage, the addresses are in the program of that space. A write replaces the start screen of the knowledge.",
964
+ notes: "Record only a screen of the program itself, never a screen of a crack. If a release changed the screen, for example with the text of a crack, stop and ask the user how to deal with it. text and multicolour need --colours or --colour; hires uses neither. With --stage, the script takes the screen from the capture of the stage: give only --stage, and --call for a tune. A flag that you give too replaces the value of the capture. A write replaces the start screen of the knowledge.",
955
965
  },
956
966
  (call) => {
957
967
  const context = contextOf(call);
958
968
  const commentText = call.string("comment");
959
- const optional = (key: "bitmap" | "charset" | "colours") => ((value) => (value === undefined ? {} : { [key]: value }))(call.address(key));
960
- const colour = call.count("colour");
969
+ // The values that the call gives. With --stage, the capture of the stage gives the others.
970
+ const given: { mode?: StartScreenMode; screen?: number; bitmap?: number; charset?: number; colours?: number; colour?: number; border?: number; background?: number } = {};
971
+ const mode = call.string("mode") as StartScreenMode | undefined;
972
+ if (mode !== undefined) given.mode = mode;
973
+ for (const key of ["screen", "bitmap", "charset", "colours"] as const) {
974
+ const value = call.address(key);
975
+ if (value !== undefined) given[key] = value;
976
+ }
977
+ for (const key of ["colour", "border", "background"] as const) {
978
+ const value = call.count(key);
979
+ if (value !== undefined) given[key] = value;
980
+ }
961
981
  const stage = call.string("stage");
962
982
  const routine = call.address("call");
963
- const request = {
983
+ const extra = {
964
984
  space: call.space,
965
- mode: call.string("mode") as StartScreenMode,
966
- screen: call.address("screen")!,
967
- ...optional("bitmap"),
968
- ...optional("charset"),
969
- ...optional("colours"),
970
- ...(colour === undefined ? {} : { colour }),
971
- border: call.count("border")!,
972
- background: call.count("background")!,
973
985
  ...(stage === undefined ? {} : { stage }),
974
986
  ...(routine === undefined ? {} : { call: routine }),
975
987
  ...(commentText === undefined ? {} : { comment: commentText }),
976
988
  };
977
- return (db) => shown(setStartScreen(db, context, request), "startScreen", startScreen);
989
+ const complete = (values: typeof given & { colourRam?: true }, remedy: string) => {
990
+ const missing = (["mode", "screen", "border", "background"] as const).filter((key) => values[key] === undefined);
991
+ if (missing.length > 0) throw new UsageError(`Give ${missing.map((key) => `--${key}`).join(", ")}, ${remedy}`);
992
+ return { ...values, mode: values.mode!, screen: values.screen!, border: values.border!, background: values.background!, ...extra };
993
+ };
994
+ if (stage === undefined) {
995
+ const request = complete(given, "or give --stage with the space of a captured stage that shows the screen.");
996
+ return (db) => shown(setStartScreen(db, context, request), "startScreen", startScreen);
997
+ }
998
+ return (db) => {
999
+ // The capture of the stage gives the screen. A flag of the call replaces a value of the capture, and --colours or --colour replaces the colour RAM.
1000
+ const image = programImage(db, stage);
1001
+ if (image === undefined) throw new Refusal("not-found", `The knowledge has no program in ${stage}. Capture the stage while it shows the start screen, and put the capture into the project knowledge with image --space ${stage}. Then record the start screen again.`);
1002
+ const captured = mode === undefined ? startScreenOfStage(image.state, stage) : undefined;
1003
+ const { colourRam, ...fromCapture } = captured ?? { colourRam: undefined };
1004
+ const ownColours = given.colours !== undefined || given.colour !== undefined;
1005
+ const request = complete({ ...fromCapture, ...(colourRam === true && !ownColours ? { colourRam } : {}), ...given }, "or give --stage alone to take the screen from the capture.");
1006
+ return shown(setStartScreen(db, context, request), "startScreen", startScreen);
1007
+ };
978
1008
  },
979
1009
  ),
980
1010
  writeCommand({ name: "unstart-screen", summary: "Removes the start screen. The loader of the generated source then starts the program at once." }, (call) => {
@@ -1020,7 +1050,7 @@ const WRITE_COMMANDS: CommandSpec[] = [
1020
1050
  const context = contextOf(call);
1021
1051
  const request = { space: call.space, ...call.parseRange(call.subject(0), "<range>"), macro: call.subject(1), args: commaList(call.string("args") ?? "") };
1022
1052
  return (db) => {
1023
- const result = setMacroUse(db, { ...context, image: operandImage(db, call.space) }, request);
1053
+ const result = setMacroUse(db, { ...context, image: operandImages(db) }, request);
1024
1054
  return { revision: result.revision, use: macroUse(result.current), ...(result.previous === undefined ? {} : { previous: macroUse(result.previous) }) };
1025
1055
  };
1026
1056
  },
@@ -1065,7 +1095,7 @@ const WRITE_COMMANDS: CommandSpec[] = [
1065
1095
  name: "revert",
1066
1096
  summary: "Makes the knowledge the same as at one revision: all spaces, or with --space only that space. The revert is a new revision: the history stays complete.",
1067
1097
  subjects: [REVISION],
1068
- options: { space: { kind: "space", value: "<space>", help: "revert only this space: c64, drive8, or bank0 to bank255. The other spaces do not change. Without --space, every space reverts" } },
1098
+ options: { space: { kind: "space", value: "<space>", help: "revert only this space: c64, drive8, loading, or bank0 to bank255. The other spaces do not change. Without --space, every space reverts" } },
1069
1099
  },
1070
1100
  (call) => {
1071
1101
  const context = contextOf(call);
@@ -1104,9 +1134,8 @@ const WRITE_COMMANDS: CommandSpec[] = [
1104
1134
  }
1105
1135
  if (!Array.isArray(parsed)) throw new Refusal("invalid-input", `The batch ${path} is not a JSON list of writes. Give a list such as [{"op": "rename", "address": "$2100", "name": "update_player"}].`);
1106
1136
  const operations = parsed.map((item, index) => batchOperation(call, item, `write ${index + 1}`));
1107
- const checked = operations.some((operation) => operation.op === "operand" || operation.op === "patch" || operation.op === "use");
1108
1137
  return (db) => {
1109
- const applied = applyBatch(db, checked ? { ...context, image: operandImage(db, call.space) } : context, operations);
1138
+ const applied = applyBatch(db, { ...context, image: operandImages(db) }, operations);
1110
1139
  // replaced: each write that replaced a row of another origin, with that row as previous gives it for one write.
1111
1140
  const replaced = applied.steps.flatMap((step, index) => (step.previous === undefined ? [] : [{ write: index + 1, op: operations[index]!.op, previous: shownPrevious(step.previous) }]));
1112
1141
  return { revision: applied.revision, writes: applied.steps.length, replaced };
@@ -1243,7 +1272,7 @@ function batchFields(fields: Record<string, unknown>, at: string, address: (text
1243
1272
 
1244
1273
  await runScript({
1245
1274
  name: "knowledge",
1246
- summary: "Reads and writes the knowledge of the project: names, regions, comments, references, the program and its coverage, and the source knowledge. A read needs no knowledge folder. Every command takes --space: c64 (the default), drive8 for 1541 drive code, or bank0 to bank255 for cartridge banks. revert without --space reverts all spaces.",
1275
+ summary: "Reads and writes the knowledge of the project: names, regions, comments, references, the program and its coverage, and the source knowledge. A read needs no knowledge folder. Every command takes --space: c64 (the default), drive8 for 1541 drive code, loading for a captured stage of the loading, or bank0 to bank255 for cartridge banks. revert without --space reverts all spaces.",
1247
1276
  names: knowledgeNames,
1248
1277
  commands: [...READ_COMMANDS, ...WRITE_COMMANDS, JOIN],
1249
1278
  });
@@ -37,7 +37,7 @@ These rules apply to each rebuild:
37
37
 
38
38
  - Do not keep a cracktro. A capture of a packed program starts at the last stage, so the code of a cracktro is not in the program. When the capture has data of a cracktro that the program does not read, capture again and exclude that range.
39
39
  - Keep the start screen of the program, for example the loading picture of the publisher. Keep its bytes in the capture, and record the start screen in the project knowledge. The loader of the rebuild then shows it and waits for a key or a fire button. Do not keep a screen of a crack, for example a picture, an intro or a credit screen of a crack group.
40
- - When the start screen is only in a stage of the loading, capture that stage while it shows the screen. Put the capture into the project knowledge in a space of its own. Then record the start screen of that stage. Keep its tune: record the routine that starts the tune as the call of the start screen.
40
+ - When the start screen is only in a stage of the loading, capture that stage while it shows the screen. Put the capture into the project knowledge in the space `loading`. Then record the start screen of that stage. Keep its tune: record the routine that starts the tune as the call of the start screen.
41
41
  - A release can change the start screen, for example with the text of a crack. Then stop and ask the user how to deal with it. Do not decide alone.
42
42
  - Keep all other bytes: unused bytes, dead code, old copies, texts and leftovers of the development. Record each one as a region with a comment. Do not remove them. The source keeps them, and the build of each release has them. The default build and the loader do not have them.
43
43
  - Do not write a file of the rebuild by hand, for example a boot file, a packed picture or a script that changes bytes. Record each change in the project knowledge, and generate the source.
@@ -74,7 +74,7 @@ Each flag applies only to the commands in the table. On another command, the scr
74
74
  |---|---|---|
75
75
  | `--out <dir>` | `generate` | The folder for the source files. It is necessary. The script writes over the files of an earlier run. It removes a generated `.asm` file that this run does not write. A run without `--loader` keeps `loader.asm`, `loader.prg`, `start_screen.asm` and `start_screen_stage.asm` of an earlier run. `staleLoader` tells when they are of another knowledge revision. |
76
76
  | `--entry <address>` | `generate` | An address where code starts. Give the flag again for more addresses. There is no default. |
77
- | `--space <space>` | `generate` | The knowledge space: `c64`, `drive8`, or `bank0` to `bank255`. The default is `c64`. `--loader` and the platform names apply only to `c64`. The coverage is the coverage of the space. |
77
+ | `--space <space>` | `generate` | The knowledge space: `c64`, `drive8`, `loading`, or `bank0` to `bank255`. The default is `c64`. `--loader` and the platform names apply only to `c64`. The coverage is the coverage of the space. |
78
78
  | `--loader` | `generate` | Also write `loader.asm` and `loader.prg`, and `start_screen.asm` when the knowledge has a start screen. A start screen of a captured stage also gives `start_screen_stage.asm`. The script writes `loader.prg` only after the check of the new loader ran. Else the `loader.prg` of an earlier run stays. It needs a capture in the knowledge. The default is no loader. |
79
79
  | `--analyzer-names` | `generate` | Name an address without a name of the user or the LLM, and without a platform name, with its analyzer name, for example `FUN_17e2`. Without the flag, the source makes its own name, for example `l_17e2`. |
80
80
  | `--to <folder>` | `export` | The folder of the new project. It is necessary. The script also writes `<folder>.zip` beside the folder. |
@@ -264,8 +264,10 @@ The start screen:
264
264
 
265
265
  - 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".
266
266
  - With a start screen, the copier uses three pages, not two.
267
- - `loader.prg` always shows the start screen. To start the program at once, set `START_SCREEN = 0` in `config.asm`, and assemble `loader.asm`. Do not define `START_SCREEN` on the command line of the build: `config.asm` sets it. The build of a release does not read `config.asm`, so it shows the start screen.
267
+ - The start screen is part of the clean build only. `loader.prg` always shows it. A release build has no start screen, and `LEFTOVERS = 1` also turns it off.
268
+ - To start the program at once, set `START_SCREEN = 0` in `config.asm`, and assemble `loader.asm`. Do not define `START_SCREEN` on the command line of the build: `config.asm` sets it.
268
269
  - A test that runs `loader.prg` stops at the start screen, because the emulator cannot press a key of the keyboard matrix. Run until `loader_start_screen_wait`. Then set the PC to `loader_start_screen_continue`.
270
+ - `loader.json` is the symbol file of `loader.prg`. It holds the labels of `loader.asm`, `main.asm` and `start_screen_stage.asm`. Give it to a test of `loader.prg` as its symbols.
269
271
 
270
272
  `loader` holds these fields:
271
273
 
@@ -286,14 +288,14 @@ Do these actions when `verified` is `false`:
286
288
  | `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, write the loader by hand. If the check of the unpack fails, give the reason to the user. |
287
289
  | `reason` that the source does not assemble | Correct the source first. The loader includes the source. |
288
290
  | `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. |
289
- | `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. |
291
+ | `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. |
290
292
  | `reason` that the check of `loader.prg` 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. |
291
293
  | `differences` | The loader ran. The list gives the bytes and the registers that are not equal. |
292
294
  | `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. |
293
295
 
294
296
  #### The start screen of a captured stage
295
297
 
296
- 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 a captured stage: a space such as `bank1`. `--stage` of the start screen names that space. `--call` names a routine of the stage, for example the routine that starts the loading tune.
298
+ 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.
297
299
 
298
300
  The loader then always has the packed form, and the start screen is a program of its own in front of it:
299
301
 
@@ -307,11 +309,13 @@ The loader then always has the packed form, and the start screen is a program of
307
309
 
308
310
  The program is packed while the screen shows. Thus the picture and the tune have more free memory.
309
311
 
310
- - `loader.prg` has only the bytes of the stage that the start screen uses. These are the screen, the bitmap, the charset and the colours. 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.
312
+ - The script puts everything in memory. It does not matter where the stage keeps its bytes, if the memory has enough room.
313
+ - `loader.prg` 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.
314
+ - With colours from the colour RAM of the capture, the show code holds the 1000 colours. It copies them to the colour RAM.
311
315
  - 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.
312
316
  - `start_screen_stage.asm` holds the show code and the bytes of the stage. Do not edit it. To make `loader.prg` again, run `generate --loader`.
313
317
  - 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.
314
- - The check runs `loader.prg` to `loader_start_screen_wait` of the show stage. There, it compares the VIC-II with the start screen, and the screen bytes in memory with the stage. Then it sets the PC to `loader_start_screen_continue`, and it checks the loader as usual.
318
+ - The check runs `loader.prg` to `loader_start_screen_wait` of the show stage. There, it compares the VIC-II with the start screen, the screen bytes in memory with the stage, and the colour RAM with the capture. Then it sets the PC to `loader_start_screen_continue`, and it checks the loader as usual.
315
319
 
316
320
  #### The packed loader
317
321
 
@@ -384,6 +388,16 @@ A block of code stops after RTS, RTI, JMP, BRK or a JAM, and before a gap. A blo
384
388
  - No run of the coverage executed it.
385
389
  - No path gets to it from the entry, the hardware vectors or the code that stays. A path is a call, a jump, a branch, a reference of the knowledge or an operand expression. An entry of a table, and two immediate operands that give its address, are paths too.
386
390
 
391
+ Two immediate operands give an address only in these cases:
392
+
393
+ - The code stores the low byte and the high byte to two adjacent addresses outside $d000-$dfff.
394
+ - The code calls a routine with the low byte and the high byte in two registers.
395
+ - The code pushes the high byte and then the low byte onto the stack.
396
+
397
+ An operand expression of the knowledge at an immediate operand replaces these cases for that operand. Thus an operand expression with a constant stops a wrong address.
398
+
399
+ A call or a jump to ROM is not a path. The coverage shows where the CPU sees ROM. Without coverage, $01 of the entry state shows it. Known code of the knowledge is never ROM.
400
+
387
401
  Code that a run executed always stays. `unreachableExecuted` lists the executed code that the entry and the vectors do not get to. An example is a copy check whose call the export removed. Give its `drop` value to `export` to make it free.
388
402
 
389
403
  Data becomes free only when all of these are true:
@@ -391,7 +405,7 @@ Data becomes free only when all of these are true:
391
405
  - Its region type is `bytes`, `words`, a table of addresses, `petscii`, `workspace` or `unused`.
392
406
  - No run read, wrote or executed a byte of it.
393
407
  - No code that stays reads it or names it. No table that stays has an entry in it.
394
- - It is not at the first address of the program, and not at $fffa-$ffff.
408
+ - It is not in the BASIC line that starts the program, and not at $fffa-$ffff.
395
409
 
396
410
  The coverage does not show the reads of the VIC-II. Thus `charset`, `sprite`, `bitmap` and `screen` data stay, unless `--drop` names them. The bytes of the start screen always stay. Bytes without a region also stay.
397
411
 
@@ -28,8 +28,19 @@ const CODE_TYPES: readonly RegionType[] = ["code", "jumps", "dual-use"];
28
28
  /** The hardware vectors $fffa-$ffff: they stay when the image holds them. */
29
29
  const VECTORS: AddressRange = { start: 0xfffa, end: 0xffff };
30
30
 
31
- /** Two immediate operands at most this many immediates apart can be the low and high byte of one address. */
32
- const PAIR_WINDOW = 4;
31
+ /** The I/O area: two immediates stored there are chip values, such as a timer latch, not an address. */
32
+ const IO_AREA: AddressRange = { start: 0xd000, end: 0xdfff };
33
+
34
+ /** The registers that each instruction changes, other than by a load of an immediate or a transfer. */
35
+ const WRITES_A = new Set(["lda", "adc", "sbc", "and", "ora", "eor", "pla", "lax", "anc", "asr", "arr", "ane", "lxa", "las", "slo", "rla", "sre", "rra", "isc"]);
36
+ const WRITES_X = new Set(["ldx", "inx", "dex", "tsx", "lax", "sbx", "lxa", "las"]);
37
+ const WRITES_Y = new Set(["ldy", "iny", "dey"]);
38
+ /** The registers that a JSR gets an address in, low byte first, as the KERNAL and BASIC routines get a pointer. */
39
+ const CALL_PAIRS = [
40
+ ["x", "y"],
41
+ ["a", "y"],
42
+ ["a", "x"],
43
+ ] as const;
33
44
 
34
45
  export interface DropInput {
35
46
  segments: readonly AddressRange[];
@@ -41,8 +52,12 @@ export interface DropInput {
41
52
  coverage?: Uint8Array;
42
53
  regions: ReadonlyArray<{ start: number; end: number; type: RegionType }>;
43
54
  references: ReadonlyArray<{ from: number; to: number; kind: string }>;
44
- /** The addresses that the operand expression of an instruction names, by the address of the instruction. */
55
+ /** The addresses that the operand expression of an instruction names, by the address of each instruction with an operand expression; none for a constant. */
45
56
  operandTargets: ReadonlyMap<number, readonly number[]>;
57
+ /** The ranges where the CPU sees ROM and not the RAM of the image: code does not go there, and no address points there. */
58
+ rom?: readonly AddressRange[];
59
+ /** The BASIC line that starts the program: RUN reads it, which no coverage from the entry shows. */
60
+ basic?: AddressRange;
46
61
  /** The patch ranges whose bytes the export changed. */
47
62
  changed: readonly AddressRange[];
48
63
  keep: readonly AddressRange[];
@@ -115,42 +130,72 @@ function flowsOf(input: DropInput, inImage: (address: number) => boolean, indexe
115
130
  const reads: DataReference[] = [];
116
131
  const { memory } = input;
117
132
  const word = (at: number) => memory[at]! | (memory[(at + 1) & 0xffff]! << 8);
118
- const immediates: Array<{ at: number; value: number }> = [];
119
- let previousEnd = -2;
120
- const pairs = () => {
121
- // A low byte and a high byte near each other in one block: the address of a vector, a table or an RTS target.
122
- immediates.forEach((low, index) => {
123
- for (let other = Math.max(0, index - PAIR_WINDOW); other <= Math.min(immediates.length - 1, index + PAIR_WINDOW); other++) {
124
- if (other === index) continue;
125
- const target = low.value | (immediates[other]!.value << 8);
126
- if (!inImage(target)) continue;
127
- flows.push({ from: low.at, to: target }, { from: low.at, to: (target + 1) & 0xffff });
128
- reads.push({ from: low.at, start: target, end: target });
129
- }
130
- });
131
- immediates.length = 0;
133
+ const rom = (address: number) => inside(address, input.rom ?? []);
134
+ // The address of a vector, a table or an RTS target in two immediates of one block: the low byte and the high byte
135
+ // go into a pointer (two stores to N and N+1), into the registers of a JSR, or onto the stack (PHA high, PHA low).
136
+ type Immediate = { at: number; value: number } | undefined;
137
+ const registers: { a: Immediate; x: Immediate; y: Immediate } = { a: undefined, x: undefined, y: undefined };
138
+ const stores = new Map<number, NonNullable<Immediate>>();
139
+ const pushes: Immediate[] = [];
140
+ const pair = (low: Immediate, high: Immediate) => {
141
+ if (low === undefined || high === undefined) return;
142
+ const target = low.value | (high.value << 8);
143
+ if (!inImage(target) || rom(target)) return;
144
+ flows.push({ from: low.at, to: target }, { from: low.at, to: (target + 1) & 0xffff });
145
+ reads.push({ from: low.at, start: target, end: target });
146
+ };
147
+ const endBlock = () => {
148
+ registers.a = registers.x = registers.y = undefined;
149
+ stores.clear();
150
+ pushes.length = 0;
132
151
  };
152
+ let previousEnd = -2;
133
153
  for (const at of [...input.instructions.keys()].sort((a, b) => a - b)) {
134
154
  const opcode = memory[at]!;
135
- const { mode } = OPCODES[opcode]!;
136
- if (at > previousEnd + 1) pairs();
155
+ const { mnemonic, mode } = OPCODES[opcode]!;
156
+ if (at > previousEnd + 1) endBlock();
137
157
  previousEnd = at + input.instructions.get(at)! - 1;
138
158
  const operand = input.instructions.get(at) === 3 ? word(at + 1) : memory[at + 1]!;
159
+ // The registers: a load of an immediate that no operand expression explains, a transfer, a store, a push, a call.
160
+ const loaded = mode === "imm" && !input.operandTargets.has(at) ? { at, value: operand } : undefined;
161
+ if (WRITES_A.has(mnemonic) || (mode === "imp" && ["asl", "lsr", "rol", "ror"].includes(mnemonic))) registers.a = mnemonic === "lda" ? loaded : undefined;
162
+ if (WRITES_X.has(mnemonic)) registers.x = mnemonic === "ldx" ? loaded : undefined;
163
+ if (WRITES_Y.has(mnemonic)) registers.y = mnemonic === "ldy" ? loaded : undefined;
164
+ if (mnemonic === "tax") registers.x = registers.a;
165
+ if (mnemonic === "tay") registers.y = registers.a;
166
+ if (mnemonic === "txa") registers.a = registers.x;
167
+ if (mnemonic === "tya") registers.a = registers.y;
168
+ const stored = { sta: registers.a, stx: registers.x, sty: registers.y }[mnemonic];
169
+ if ((mode === "zp" || mode === "abs") && ["sta", "stx", "sty"].includes(mnemonic) && !inside(operand, [IO_AREA])) {
170
+ stores.delete(operand);
171
+ if (stored !== undefined) {
172
+ stores.set(operand, stored);
173
+ pair(stored, stores.get((operand + 1) & 0xffff));
174
+ pair(stores.get((operand - 1) & 0xffff), stored);
175
+ }
176
+ }
177
+ if (mnemonic === "pha") {
178
+ pushes.push(registers.a);
179
+ if (pushes.length >= 2) pair(pushes.at(-1), pushes.at(-2));
180
+ }
181
+ if (mnemonic === "pla") pushes.pop();
182
+ if (mnemonic === "jsr") {
183
+ for (const [low, high] of CALL_PAIRS) pair(registers[low], registers[high]);
184
+ registers.a = registers.x = registers.y = undefined;
185
+ }
139
186
  switch (mode) {
140
187
  case "rel":
141
188
  flows.push({ from: at, to: (at + 2 + (operand < 0x80 ? operand : operand - 0x100)) & 0xffff });
142
189
  break;
143
- case "imm":
144
- immediates.push({ at, value: operand });
145
- break;
146
190
  case "ind":
147
191
  reads.push({ from: at, start: operand, end: (operand + 1) & 0xffff });
148
192
  if (inImage(operand) && inImage((operand + 1) & 0xffff)) flows.push({ from: at, to: word(operand) });
149
193
  break;
150
194
  case "abs":
151
195
  case "zp":
152
- if (opcode === 0x20 || opcode === 0x4c) flows.push({ from: at, to: operand });
153
- else reads.push({ from: at, start: operand, end: operand });
196
+ if (opcode === 0x20 || opcode === 0x4c) {
197
+ if (!rom(operand)) flows.push({ from: at, to: operand });
198
+ } else reads.push({ from: at, start: operand, end: operand });
154
199
  break;
155
200
  case "abx":
156
201
  case "aby":
@@ -165,9 +210,8 @@ function flowsOf(input: DropInput, inImage: (address: number) => boolean, indexe
165
210
  default:
166
211
  break;
167
212
  }
168
- if (NO_FALL_THROUGH.has(opcode)) pairs();
213
+ if (NO_FALL_THROUGH.has(opcode)) endBlock();
169
214
  }
170
- pairs();
171
215
  for (const reference of input.references) {
172
216
  if (inside(reference.from, input.changed)) continue;
173
217
  if (reference.kind === "call" || reference.kind === "jump" || reference.kind === "pointer") flows.push({ from: reference.from, to: reference.to });
@@ -275,11 +319,10 @@ export function planDrops(input: DropInput): DropPlan {
275
319
 
276
320
  // Data: a region of a droppable type that no run touched and that nothing that stays names.
277
321
  const gone = [...input.drop, ...droppedCode];
278
- const imageStart = Math.min(...input.segments.map((segment) => segment.start));
279
322
  const units = automatic
280
323
  ? regions.filter((region) => {
281
324
  if (!DROPPABLE_DATA.includes(region.type) || gone.some((range) => overlaps(range, region))) return false;
282
- if ([...input.keep, ...input.changed, VECTORS].some((range) => overlaps(range, region)) || (region.start <= imageStart && imageStart <= region.end)) return false;
325
+ if ([...input.keep, ...input.changed, VECTORS, ...(input.basic === undefined ? [] : [input.basic])].some((range) => overlaps(range, region))) return false;
283
326
  for (let address = region.start; address <= region.end; address++) if (touched(address)) return false;
284
327
  return true;
285
328
  })