@henols/c64-re-tools 2.1.7 → 2.2.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -42,6 +42,18 @@ One repository can hold several programs, with one project folder for each progr
42
42
  - Do not write a script that makes a deliverable again, for example a capture, copy or replay script. Commit the deliverable.
43
43
  - Write the knowledge only with the c64-knowledge script. Do not write or edit the files in `.c64-re-tools/knowledge/` yourself.
44
44
 
45
+ ## What a rebuild keeps
46
+
47
+ These rules apply to each rebuild:
48
+
49
+ - Do not keep a cracktro. The capture of the c64-unpacker skill starts at the last stage, so the code of a cracktro is not in the program. Cut the data of a cracktro that the program does not read with `capture --exclude`.
50
+ - 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.
51
+ - Keep a copy protection in the source, off by default. Record a `protection` switch and its patches.
52
+ - Keep a trainer and a cheat in the source, off by default. Record a `trainer` or `cheat` switch and its patches.
53
+ - When two or more releases have different corrections, record each release and one `fix` switch for each correction. The switch names the releases that have the correction. The default build has all corrections.
54
+ - Record all switches with the c64-knowledge skill. Do not write a switch in a source file.
55
+ - When a crack removed a copy protection and no release has its bytes, write this in a comment and in the answer.
56
+
45
57
  ## Workflow
46
58
 
47
59
  Select the path for the scope:
@@ -63,7 +75,7 @@ Select the path for the scope:
63
75
  | What the program does at run time: values, input, timing, screen | c64-emulator |
64
76
  | The routines, code, data and references of the program | c64-static-analysis |
65
77
  | The platform meaning of an address or a register | c64-memory-map |
66
- | Differences between releases of the program | c64-provenance `compare` |
78
+ | Differences between releases of the program | c64-provenance `compare`, then c64-knowledge `release`, `switch` and `patch` |
67
79
  | Leftovers of the development, a crack or a recrack: texts, old copies, unused bytes, dead code | c64-provenance `leftovers` |
68
80
  | A routine that another program of the workspace has, for example a music driver | c64-provenance, with the library |
69
81
  | Source code from the knowledge | c64-source |
@@ -76,29 +88,31 @@ Select the path for the scope:
76
88
 
77
89
  ### The stages of a full rebuild
78
90
 
79
- Do the stages in this sequence. Go to the next stage only when its exit check is true, or when the user accepts an exception. Remember each exception for the answer of stage 11.
91
+ Do the stages in this sequence. Go to the next stage only when its exit check is true, or when the user accepts an exception. Remember each exception for the answer of stage 12.
80
92
 
81
93
  | Stage | Work | Exit check |
82
94
  |---|---|---|
83
95
  | 1. Acceptance | Ask the user for the criteria of the rebuild. Offer these: identical source, a verified loader, passed c64-testing scenarios, passed replays of the recordings, and a list of the code that no run executed. Also offer documentation of the flows, tables, formats and graphics. | The user gave the criteria. |
84
96
  | 2. Get | c64-disk: list the disk. Extract the start file into `original/`. | The start file is in the project. |
85
97
  | 3. Start | c64-basic: find the SYS address of the BASIC start. | You have the entry address. |
86
- | 4. Unpack | c64-unpacker: examine the program with `unpacker.ts inspect`, `trace` and `stages`. Capture a packed program with `unpacker.ts capture` into `.c64-re-tools/local/`. Then c64-knowledge: put the capture, or the PRG of a program without a packer, into the knowledge with `knowledge.ts image`. | `program` of c64-knowledge shows the segments and the entry. |
98
+ | 4. Unpack | c64-unpacker: examine the program with `unpacker.ts inspect`, `trace` and `stages`. Capture a packed program with `unpacker.ts capture` into `.c64-re-tools/local/`. When a segment is the data of a cracktro and the program does not read it, capture again with `--exclude` for that range. Then c64-knowledge: put the capture, or the PRG of a program without a packer, into the knowledge with `knowledge.ts image`. | `program` of c64-knowledge shows the segments and the entry. |
87
99
  | 5. Run | First record: ask the user to play each part that the scope names, with `testing.ts record --play` of c64-testing. Tell the user which parts. Record a part yourself only when the sessions of the user do not have it. Put the recordings in `tests/recordings/`. Then use c64-emulator and `testing.ts run` of c64-testing for the parts that a recording cannot have. Write a coverage map for each part into `.c64-re-tools/local/`. Then c64-knowledge: add the maps and the `coverage.bin` of each recording with `knowledge.ts coverage`. | `program` of c64-knowledge lists a coverage map for each part that the scope names. |
88
100
  | 6. Analyze | c64-static-analysis: `static-analysis.ts analyze`. It reads the program and the coverage from the knowledge. | No coverage conflict is open. |
89
101
  | 7. Name | c64-provenance: if the workspace has a library, find its routines with `provenance.ts match` and apply the batch. Then c64-knowledge and c64-memory-map: name each routine in the scope and give it a comment. Record the modules. When the scope has hundreds of routines, ask the user which routines to name. The source gives the other routines an `l_xxxx` label. | Each routine that the user selected has a name and a comment. |
90
- | 8. Generate | c64-source: `source.ts generate --out src`. For an unpacked program, add `--loader`. | `check.identical` is true. For an unpacked program, `loader.verified` is true. |
91
- | 9. Build and test | c64-assembler: `assembler.ts build` with `--compare` into `build/`. c64-testing: `testing.ts test` with the scenarios in `tests/`. Replay each recording on the rebuild with `testing.ts replay`: give the checkpoint routine, the state and the random state (`--pin`) with the names of stage 7. | The criteria of stage 1 are true. |
92
- | 10. Document | When the criteria ask for documentation: c64-docs into `README.md` and `docs/`, with `docs.ts generate` and `docs.ts link`. | `docs.ts link --check` of c64-docs gives `result: "PASS"`. |
93
- | 11. Hand over | Find each file that you made outside `.c64-re-tools/local/` and that is not a deliverable. Move it into `.c64-re-tools/local/`. Then give the answer (below). | Each file that you made outside `.c64-re-tools/local/` is a deliverable. |
102
+ | 8. Releases and switches | c64-knowledge: record the base release with `knowledge.ts release <label> --file original/<file> --base`. For a capture, copy its folder to `original/<label>/` first, because git ignores `.c64-re-tools/local/`. Record each other release. c64-provenance: compare the releases with `provenance.ts compare`, and find leftovers with `provenance.ts leftovers`. c64-knowledge: record a switch for each copy protection, trainer, cheat, crack change and correction, and a patch for each of its ranges. Record each leftover as a region with a comment. | `knowledge.ts switches` lists each switch. Each difference between the releases is in a patch, or the answer gives it as an exception. |
103
+ | 9. Generate | c64-source: `source.ts generate --out src`. For an unpacked program, add `--loader`. | `check.identical` is true. `default.result` is `fits`. Each item of `releases` is `identical`, or `layout differs` as an exception. For an unpacked program, `loader.verified` is true. |
104
+ | 10. Build and test | c64-assembler: `assembler.ts build` with `--release <base label> --compare` into `build/`, and the default build without options. c64-testing: `testing.ts test` with the scenarios in `tests/`. Replay each recording on the rebuild with `testing.ts replay`: give the checkpoint routine, the state and the random state (`--pin`) with the names of stage 7. | The criteria of stage 1 are true. |
105
+ | 11. Document | When the criteria ask for documentation: c64-docs into `README.md` and `docs/`, with `docs.ts generate` and `docs.ts link`. | `docs.ts link --check` of c64-docs gives `result: "PASS"`. |
106
+ | 12. Hand over | Find each file that you made outside `.c64-re-tools/local/` and that is not a deliverable. Move it into `.c64-re-tools/local/`. Then give the answer (below). | Each file that you made outside `.c64-re-tools/local/` is a deliverable. |
94
107
 
95
- In stage 5, make the recordings before you change the program. A recording needs no names, and its coverage gives the analysis of stage 6 more code. If you cannot get to a part of the program, ask the user how to get to it. Do stages 7 and 8 again until the source is clear. Each run of c64-source writes the source again.
108
+ In stage 5, make the recordings before you change the program. A recording needs no names, and its coverage gives the analysis of stage 6 more code. If you cannot get to a part of the program, ask the user how to get to it. Do stages 7 to 9 again until the source is clear. Each run of c64-source writes the source again.
96
109
 
97
110
  After stage 7, save each routine that other programs can have to the library with `provenance.ts routine` of c64-provenance. Examples are a music driver, a decruncher and a loader. Ask the user before you make a library.
98
111
 
99
112
  ### Deliverables of a full rebuild
100
113
 
101
- - `.c64-re-tools/knowledge/` with the program, its entry state, the coverage, the names, the regions, the comments and the modules
114
+ - `.c64-re-tools/knowledge/` with the program, its entry state, the coverage, the names, the regions, the comments, the modules, the releases, the switches and the patches
115
+ - the file of each release in `original/`
102
116
  - the generated source
103
117
  - the built program and the loader
104
118
  - the c64-testing scenarios
@@ -107,7 +121,7 @@ After stage 7, save each routine that other programs can have to the library wit
107
121
  - the runs in `runs/` that the knowledge gives as evidence
108
122
  - the scripts in `tools/` for the formats of this program, when you wrote them.
109
123
 
110
- All other files that you made are not deliverables. Keep them in `.c64-re-tools/local/`. Do not delete a file that the user made.
124
+ All other files that you made are not deliverables. Keep them in `.c64-re-tools/local/`. Do not remove a file that the user made.
111
125
 
112
126
  ### The answer
113
127
 
@@ -115,7 +129,8 @@ Give the user a short answer at the end. Do not write a report file. Write a rep
115
129
 
116
130
  1. Each criterion of stage 1 and its result, and each exception that the user accepted.
117
131
  2. The count of the code ranges that no run executed. The ranges are in the `not_executed.json` file of c64-source.
118
- 3. Open questions: what the evidence does not explain.
132
+ 3. The switches: the name, the kind and the default of each, and the releases that have it on. Also a copy protection that a crack removed and that no release has.
133
+ 4. Open questions: what the evidence does not explain.
119
134
 
120
135
  Keep observed facts apart from your conclusions.
121
136
 
@@ -156,12 +171,12 @@ Record durable conclusions with the c64-knowledge skill. Do not store:
156
171
 
157
172
  ## Result
158
173
 
159
- A clear answer for the scope, with the durable conclusions in the project knowledge. For a full rebuild, the deliverables and the answer of stage 11, with the criteria of the user met or each exception in the answer.
174
+ A clear answer for the scope, with the durable conclusions in the project knowledge. For a full rebuild, the deliverables and the answer of stage 12, with the criteria of the user met or each exception in the answer.
160
175
 
161
176
  ## Failure and conflicts
162
177
 
163
178
  - A skill reports `installation-incomplete`, or `machine-unavailable` with a message that the host runtime does not run: stop the whole task. Give the message to the user and wait for the user. Do not continue with other skills. Do not make a replacement for the tool or the host runtime, for example your own disk parser, disassembler or emulator script.
164
- - A tool gives a wrong result, and the exit check of a stage cannot be true. Tell the user the defect and the evidence, and wait for the user. Do not make a workaround, for example a change to a generated file. When the user accepts an exception, give the defect and the exception in the answer of stage 11.
179
+ - A tool gives a wrong result, and the exit check of a stage cannot be true. Tell the user the defect and the evidence, and wait for the user. Do not make a workaround, for example a change to a generated file. When the user accepts an exception, give the defect and the exception in the answer of stage 12.
165
180
  - If the evidence does not support a conclusion, keep the unknown and get more evidence. Do not make up a meaning.
166
181
  - Before you replace current knowledge from the user or the LLM, read its history and the evidence for it.
167
182
  - A conflict from the static analysis: find the correct answer at run time with the c64-emulator skill.
@@ -66,11 +66,11 @@ When the knowledge has coverage, code that no run executed gets the line `; not
66
66
 
67
67
  1. Put the program into the knowledge with `image` of the c64-knowledge skill. For a packed program, capture it first with the c64-unpacker skill. For a program without a packer, use the PRG.
68
68
  2. Run the script.
69
- 3. Read `result` and `check`. `check.identical: true` tells that the source assembles to the program byte by byte.
69
+ 3. Read `result` and `check`. `check.identical: true` tells that the build of the base release assembles to the program byte by byte. Without switches, this build is the default build.
70
70
  4. Read the source. A label `l_xxxx` is an address that has no name in the knowledge.
71
71
  5. Record names, comments, regions and modules with the c64-knowledge skill. Use `apply` for many changes.
72
72
  6. Run the script again. Do steps 4 to 6 again until the source is clear.
73
- 7. Build the program with the c64-assembler skill: `assembler.ts build src main.asm --out <file.prg>`.
73
+ 7. Build the program with the c64-assembler skill: `assembler.ts build src main.asm --out <file.prg>`. This is the default build. For a release, add `--release <label>`.
74
74
  8. For an unpacked program, run the script with `--loader` at the end. Test `loader.prg` against the original with the c64-testing skill.
75
75
 
76
76
  ## The source
@@ -78,7 +78,7 @@ When the knowledge has coverage, code that no run executed gets the line `; not
78
78
  - `main.asm` sets the address of each segment and includes the files in address order.
79
79
  - Each module in the knowledge is one file. A module starts at its address and stops at the next module or at the end of its segment. Without modules, each segment is one file, `segment_xxxx.asm`.
80
80
  - `constants.asm` holds the names of addresses outside the program, for example `EXTCOL = $d020`. The file puts the names in groups by memory area, for example zero page, VIC-II registers or CIA 1 registers. Each group is in address order. Drive code and banks have one group only. The side comment of a name tells what the address is. This text is the knowledge comment of the address. Without a comment, the text 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 text gives the register that the mirror repeats. Then `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.
81
- - The top of `constants.asm` sets each switch to 0, for example `!ifndef CRACK { CRACK = 0 }`. A build that defines the switch as 1 uses the patches of that switch.
81
+ - `switches.asm` holds every switch and every release of the knowledge. `main.asm` and `loader.asm` include it first. The script writes it only when the knowledge has switches or releases. For each release, a block `!ifdef RELEASE_<label>` gives each switch the value of that release. Then each switch gets its default, for example `!ifndef PROTECTION { 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.
82
82
  - A label or a constant gets the name of the address in the knowledge. Without a knowledge name, it gets the platform name of the c64-memory-map skill, for example `EXTCOL` or `CHROUT`. A platform name wins over a name from an analyzer (`dxa`, `ghidra` or `heuristic`), for example `EXTCOL` over `ld020`. A `user` or `llm` name wins over a platform name. An address in the program without a name gets `l_xxxx`.
83
83
  - The source uses the names of a ROM only when the program uses that ROM. When the knowledge has coverage, a ROM is in use when a run executed code of it. A read of ROM bytes as data does not count. Without coverage, `$01` of the entry state tells which ROMs are in. When the program uses neither ROM, the zero page and pages 2 and 3 get no system names. `romNamesLeftOut` gives the ROMs that the source did not name, and the evidence. An operand expression or a macro use with such a name gets that reason.
84
84
  - `sta $d011 ; $d011: yScroll 3, rows 25, displayEnabled` is a store of an immediate to a register that the c64-memory-map skill decodes. The side comment gives the decoded value. A side comment in the knowledge replaces it.
@@ -94,18 +94,25 @@ When the knowledge has coverage, code that no run executed gets the line `; not
94
94
  - `not decoded` marks bytes in a code region that Ghidra did not decode.
95
95
  - `; not executed $xxxx-$yyyy` starts code that no run of the coverage executed. The range is the same as in `not_executed.json`.
96
96
  - `+inc16 ptr` is a use of a macro of the knowledge. `macros.asm` holds the macros. `main.asm` and `loader.asm` include it. The comments inside a use go to its side comment.
97
- - `!zone patch_CRACK_100e` starts a patch of the knowledge. `!if CRACK` has the code of the patch and NOP to the end of the range. `else` has the original code. The labels inside the range come before the zone as `name = * + n`. Thus both builds have them.
97
+ - `!zone patch_PROTECTION_100e` starts a patch of the knowledge. The condition is the 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. The block has the code of the patch and NOP to the end of the range. `else` has the original code. The labels inside the range come before the zone as `name = * + n`. Thus all builds have them.
98
+ - 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.
98
99
 
99
100
  Do not edit the generated files. The next run writes over them.
100
101
 
101
102
  ## Switches and macros
102
103
 
103
- A switch changes the program only when the build defines it. Thus the source without a define stays identical to the program.
104
+ The program of the knowledge is the base release. The default build is the clean program: no copy protection, no trainer, no cheat and no crack change, and all corrections. Thus the default build can differ from the program. The script does these checks:
104
105
 
105
- 1. The script checks the default build with `check`.
106
- 2. Then it builds each switch on its own, with the switch as 1. It does not build two switches together.
107
- 3. The build of a switch must have the same length as the default build. It can change bytes only in the ranges of its patches.
108
- 4. Build the program with a switch on with the c64-assembler skill: `--define CRACK=1`.
106
+ 1. `check`: the build of the base release, with each switch at its base value, must give the program byte by byte.
107
+ 2. `switches`: the script builds each switch alone at the other value. It does not build two switches together. The build must have the same length as the build of the base release. It can change bytes only in the ranges of the patches of the switch.
108
+ 3. `default`: the default build must have the same length. It can change bytes only in the patches of the switches in `default.in`. These are the switches whose default is not their base value.
109
+ 4. `releases`: the script builds each release with `RELEASE_<label>=1` and compares it with the file of the release.
110
+
111
+ Build the program with the c64-assembler skill:
112
+
113
+ - The default build: no option.
114
+ - A release: `--release ORIGINAL`.
115
+ - One switch: `--define TRAINER=1`.
109
116
 
110
117
  The script writes a patch only when its range is complete items of one file. A patch cannot cut an instruction. Its switch name cannot be a name of the source.
111
118
 
@@ -128,6 +135,8 @@ The flags go through the free stack byte below the stack pointer (`stackByte`).
128
135
 
129
136
  The script simulates the copies first. Then it runs `loader.prg` in the emulator to its jump to the entry. It compares the memory, $00/$01, the registers, the screen registers of the VIC-II, the VIC bank and the raster line with the entry state there. It also compares the CIA timers, latches and interrupt masks. `loader.verified: true` tells that all of them are equal. An interrupt can run right at the entry, as in the original program.
130
137
 
138
+ The entry state is the state of the base release. Thus the script builds and checks `loader.prg` with the switch values of the base release. For a loader of the default build, build `loader.asm` with the c64-assembler skill and no option.
139
+
131
140
  ## Knowledge
132
141
 
133
142
  Read:
@@ -157,11 +166,19 @@ Do not store:
157
166
  - `macroUses`: the count of macro uses that the source has.
158
167
  - `macrosAsInstructions`: the macro uses that the source has as instructions, each with its `start`, `end`, `macro` and `reason`.
159
168
  - `patchesNotWritten`: the patches that the source does not have, each with its range, `switch` and `reason`.
160
- - `check`: `identical`, and the result for each segment. A different segment gives its first different address.
161
- - `switches`: the build of each switch. Each item has the `define` for the c64-assembler skill, the patches and the `result` of the build with the switch on. `fits` tells that the build is good, and `changedBytes` counts the changed bytes. `overflow` tells that the code of a patch is longer than its range. `changes outside` gives the first byte outside the ranges that changed. `does not assemble` gives the diagnostics of ACME. `insideNames` lists the labels inside a patch. Code that writes to one of these labels changes the patch when the switch is on.
169
+ - `check`: `identical`, and the result for each segment of the build of the base release. A different segment gives its first different address.
170
+ - `switches`: the build of each switch that has patches. Each item has `kind`, `default`, `base`, the `define` for the c64-assembler skill and the patches. `result` is the result of the build with the switch at the value that is not `base`. `fits` tells that the build is good, and `changedBytes` counts the changed bytes. `overflow` tells that the code of a patch is longer than its range. `changes outside` gives the first byte outside the ranges that changed. `does not assemble` gives the diagnostics of ACME. `insideNames` lists the labels inside a patch. Code that writes to one of these labels changes the patch when the switch is on.
171
+ - `default`: the default build. `in` lists the switches whose patches are in. `result` and `changedBytes` are as in `switches`.
172
+ - `releases`: the build of each release. Each item has `label`, `base`, `file`, the `define` and the `result`. `identical` tells that the build gives the bytes of the file. `different` gives the segments that differ. `layout differs` tells that the release has other segments than the program: patches cannot move code, so this result does not fail the run. `file changed` tells that the file is not the file that the knowledge recorded. `does not assemble` gives the diagnostics of ACME.
162
173
  - `loader`: the program, the copies in their order, the copier page, `stackByte`, `verified` and `differences`. `limits` lists the CIA values that the loader cannot set. An entry state from an old capture has no CIA values. Then `limits` tells you to capture the program again. When the script cannot make the loader, `loader` has `verified: false` and a `reason`. The loader includes the source. Thus a source that does not assemble to the program also stops the loader.
163
174
 
164
- `result` is `PASS` when the source is identical and the emulator check of the loader passes. `result` is `FAIL` for a failed check and for an entry in no segment. A patch that the source does not have, or a switch that does not fit, also gives `FAIL`. `asBytes`, `notExecuted`, `operandsAsNumbers`, `macrosAsInstructions` and `patchesNotWritten` are lists of at most `--max-listed` items.
175
+ `result` is `PASS` when the source is identical and the emulator check of the loader passes. `result` is `FAIL` for a failed check and for an entry in no segment. These also give `FAIL`:
176
+
177
+ - a patch that the source does not have
178
+ - a switch or a default build that does not fit
179
+ - a release that the build does not give. A release with `layout differs` does not give `FAIL`, but the base release must be `identical`.
180
+
181
+ `asBytes`, `notExecuted`, `operandsAsNumbers`, `macrosAsInstructions` and `patchesNotWritten` are lists of at most `--max-listed` items.
165
182
 
166
183
  ## Failure and conflicts
167
184
 
@@ -171,7 +188,10 @@ Do not store:
171
188
  - `invalid-input` that names a symbol or a module: change that symbol or module in the knowledge.
172
189
  - `switches` with `overflow`: make the code of the patch shorter, or make the range of the patch larger, with `patch` of the c64-knowledge skill.
173
190
  - `switches` with `does not assemble`: read the diagnostics and correct the code of the patch.
174
- - `patchesNotWritten`: read each `reason`. Move the start or the end of the patch to an instruction, or give the switch another name.
191
+ - `patchesNotWritten`: read each `reason`. Move the start or the end of the patch to an instruction, or give the switch another name. For a switch that is not in the knowledge, write it with `switch` of the c64-knowledge skill.
192
+ - `default` with `overflow` and the message `turn on one of them`: two alternatives are in the default build. Give one of the switches the default of the base release.
193
+ - `releases` with `different`: the release has bytes that no patch gives. Compare the releases with the c64-provenance skill. Then record a switch and a patch for each difference.
194
+ - `releases` with `file changed`: put back the file, or record the release again with `release` of the c64-knowledge skill.
175
195
  - `macrosAsInstructions`: read each `reason`. Correct the macro or the args, or remove the use with `unuse`. The source stays identical, so this is not a failure.
176
196
  - `entryOutside`: the run fails, but the script still writes and checks the source. With `--loader`, `loader.verified` is `false` with the same `reason`. Capture the program again with c64-unpacker `loads` or `capture`. Make sure that a segment holds the entry. Then put it into the knowledge again with `image`.
177
197
  - `dataOnly`: this is not a failure. If the space has code, give `--entry` or classify the code with the c64-knowledge skill. Then generate again.
@@ -368,6 +368,8 @@ export interface LoaderInput {
368
368
  /** The label of the entry in the source: the loader jumps to it, so the jump follows the code when it moves. */
369
369
  entryName?: string;
370
370
  header: string[];
371
+ /** The source has switches.asm: the loader includes it before the constants. */
372
+ switches?: boolean;
371
373
  /** The source has macros.asm: the loader includes it after the constants. */
372
374
  macros?: boolean;
373
375
  }
@@ -432,7 +434,7 @@ export function planLoader(input: LoaderInput): LoaderPlan {
432
434
  const copyBlocks = order.map((index) => blockOf[index]!);
433
435
 
434
436
  const stackByte = 0x0100 + state.sp;
435
- const lines: string[] = [...input.header.map((line) => `; ${line}`), "", "!cpu 6510", '!source "constants.asm"', ...(input.macros ? ['!source "macros.asm"'] : []), "", `* = ${formatC64Address(LOAD)}`];
437
+ const lines: string[] = [...input.header.map((line) => `; ${line}`), "", "!cpu 6510", ...(input.switches === true ? ['!source "switches.asm"'] : []), '!source "constants.asm"', ...(input.macros ? ['!source "macros.asm"'] : []), "", `* = ${formatC64Address(LOAD)}`];
436
438
  lines.push(` !byte $0b,$08,$0a,$00,$9e,${[...String(STUB)].map((digit) => formatC64Byte(digit.charCodeAt(0))).join(",")},$00,$00,$00 ; 10 SYS ${STUB}`);
437
439
  lines.push(
438
440
  "!zone loader_stub {",
@@ -5,13 +5,14 @@
5
5
  // generator forces operand sizes, and writes an opcode form that ACME
6
6
  // encodes differently as bytes (see the probe in source.ts). An operand
7
7
  // expression of the knowledge is written in place of its number. A
8
- // patch is written as !if SWITCH { code } else { original }, and a
9
- // macro use as one +name args line.
8
+ // patch is written as !if SWITCH { code } else { original }, with the
9
+ // condition of the state that the program does not have, and a macro use as
10
+ // one +name args line. switches.asm holds every switch and release.
10
11
 
11
12
  import { type AddressRange, COVERAGE, formatC64Address, formatC64Byte, POINTER_TABLE_TYPES, pointerTableEntries, type PointerTableType } from "#src/c64.ts";
12
13
  import { WireFailure } from "#src/host-client/tools.ts";
13
14
  import { identifiers, operandText, replaceIdentifiers, type OperandExpression } from "#src/knowledge/expression.ts";
14
- import { type CommentPlacement, isAnalyzer, isGeneratedFile, type Origin, type RegionType } from "#src/knowledge/schema.ts";
15
+ import { type CommentPlacement, isAnalyzer, isGeneratedFile, RELEASE_DEFINE, type Origin, type RegionType, type SwitchKind } from "#src/knowledge/schema.ts";
15
16
  import type { Area } from "#src/platform.ts";
16
17
  import { hasZeroPageForm, instructionWith, labelProblem, MODE_LENGTH, OPCODES, takesAddress, USE_KINDS, useKind, type UseKind } from "#src/opcodes.ts";
17
18
 
@@ -42,8 +43,12 @@ export interface SourceInput {
42
43
  decode?: (register: number, value: number) => Record<string, unknown>;
43
44
  /** Operand expressions of the knowledge, by instruction address. */
44
45
  operands?: ReadonlyArray<OperandExpression & { address: number }>;
45
- /** Patches of the knowledge: code that replaces a range when the build defines the switch. */
46
+ /** Patches of the knowledge: code for a range in the state of the switch that the program does not have. */
46
47
  patches?: ReadonlyArray<{ start: number; end: number; switch: string; code: string; comment?: string }>;
48
+ /** The switches of the knowledge, each with its value in the program. switches.asm holds them all. */
49
+ switches?: ReadonlyArray<SourceSwitch>;
50
+ /** The releases of the knowledge: switches.asm gives each one its switch values. */
51
+ releases?: ReadonlyArray<SourceRelease>;
47
52
  /** Macros of the knowledge, written to macros.asm. */
48
53
  macros?: ReadonlyArray<{ name: string; params: readonly string[]; body: string; comment?: string }>;
49
54
  /** Macro uses of the knowledge: the instructions of a range, written as one use of a macro. */
@@ -66,13 +71,41 @@ export interface MacroAsInstructions {
66
71
  reason: string;
67
72
  }
68
73
 
69
- /** A patch that the source writes, with the addresses inside it that have a name. */
70
- export interface PatchBlock {
71
- start: number;
72
- end: number;
74
+ /** A switch: its kind, its default, its value in the program (`base`) and the releases that have it on. */
75
+ export interface SourceSwitch {
76
+ name: string;
77
+ kind: SwitchKind;
78
+ default: 0 | 1;
79
+ base: 0 | 1;
80
+ releases: readonly string[];
81
+ comment?: string;
82
+ }
83
+
84
+ /** A release: the build with RELEASE_<label> gives each switch the value of this release. */
85
+ export interface SourceRelease {
86
+ label: string;
87
+ file: string;
88
+ base: boolean;
89
+ comment?: string;
90
+ }
91
+
92
+ /** The code of one switch in a patch: it is in when the switch does not have its base value. */
93
+ export interface PatchAlternative {
73
94
  switch: string;
74
95
  code: string;
75
96
  comment?: string;
97
+ base: 0 | 1;
98
+ }
99
+
100
+ /**
101
+ * A patch that the source writes, with the addresses inside it that have a
102
+ * name. Two or more alternatives are patches of different switches at the
103
+ * same range: at most one of them is in.
104
+ */
105
+ export interface PatchBlock {
106
+ start: number;
107
+ end: number;
108
+ alternatives: PatchAlternative[];
76
109
  /** Named addresses after the start of the range: the source defines them before the patch, so both builds have them. */
77
110
  inner: number[];
78
111
  }
@@ -201,6 +234,9 @@ export interface Layout {
201
234
  /** The patches that the source writes, by start. */
202
235
  patches: Map<number, PatchBlock>;
203
236
  patchesNotWritten: PatchNotWritten[];
237
+ /** Every switch of the knowledge, by name, and the releases, the base release first. */
238
+ switches: SourceSwitch[];
239
+ releases: SourceRelease[];
204
240
  /** The macros, by name. */
205
241
  macros: NonNullable<SourceInput["macros"]>;
206
242
  /** The macro uses that the source can write, by start. */
@@ -481,12 +517,24 @@ export function layout(input: SourceInput): Layout {
481
517
  names.set(address, name);
482
518
  generatedLabels++;
483
519
  }
484
- // A patch is written when its range is whole items of one file and its switch is no name of the source.
520
+ // A patch is written when its range is whole items of one file and its switch is a switch of the knowledge and no name of the source.
485
521
  const blocks = new Map<number, PatchBlock>();
486
522
  const patchesNotWritten: PatchNotWritten[] = [];
487
523
  const sourceNames = new Set([...names.values(), ...taken]);
488
- for (const patch of patches) {
524
+ const switches = new Map((input.switches ?? []).map((row) => [row.name, row]));
525
+ for (const patch of [...patches].sort((a, b) => a.start - b.start || (a.switch < b.switch ? -1 : 1))) {
489
526
  const refuse = (reason: string) => patchesNotWritten.push({ start: patch.start, end: patch.end, switch: patch.switch, reason });
527
+ const owner = switches.get(patch.switch);
528
+ if (owner === undefined) {
529
+ refuse(`The switch ${patch.switch} is not a switch of the knowledge.`);
530
+ continue;
531
+ }
532
+ const known = blocks.get(patch.start);
533
+ if (known !== undefined) {
534
+ if (known.end !== patch.end) refuse(`The range overlaps the patch of ${known.alternatives[0]!.switch} at ${formatC64Address(known.start)}-${formatC64Address(known.end)}: alternatives have the same range.`);
535
+ else known.alternatives.push({ switch: patch.switch, code: patch.code, ...(patch.comment === undefined ? {} : { comment: patch.comment }), base: owner.base });
536
+ continue;
537
+ }
490
538
  const piece = pieces.find((row) => patch.start >= row.start && patch.start <= row.end);
491
539
  if (piece === undefined) {
492
540
  refuse("The range is not in the image.");
@@ -508,7 +556,7 @@ export function layout(input: SourceInput): Layout {
508
556
  continue;
509
557
  }
510
558
  const inner = [...names.keys()].filter((address) => address > patch.start && address <= patch.end).sort((a, b) => a - b);
511
- blocks.set(patch.start, { start: patch.start, end: patch.end, switch: patch.switch, code: patch.code, ...(patch.comment === undefined ? {} : { comment: patch.comment }), inner });
559
+ blocks.set(patch.start, { start: patch.start, end: patch.end, alternatives: [{ switch: patch.switch, code: patch.code, ...(patch.comment === undefined ? {} : { comment: patch.comment }), base: owner.base }], inner });
512
560
  }
513
561
  // The high byte of a vector is NMINV+1. A zero-page entry keeps zero-page instructions: its constant has two digits.
514
562
  // An address inside a table keeps its own label when the source needs one there anyway, for example as the entry.
@@ -549,6 +597,8 @@ export function layout(input: SourceInput): Layout {
549
597
  operandsAsNumbers: operandsAsNumbers.sort((a, b) => a.address - b.address),
550
598
  patches: blocks,
551
599
  patchesNotWritten,
600
+ switches: [...(input.switches ?? [])].sort((a, b) => (a.name < b.name ? -1 : 1)),
601
+ releases: [...(input.releases ?? [])].sort((a, b) => Number(b.base) - Number(a.base) || (a.label < b.label ? -1 : 1)),
552
602
  macros: [...(input.macros ?? [])].sort((a, b) => (a.name < b.name ? -1 : 1)),
553
603
  macroUses: usesWritten,
554
604
  macrosAsInstructions: macrosAsInstructions.sort((a, b) => a.start - b.start),
@@ -772,23 +822,67 @@ function usageText(kinds: ReadonlyMap<UseKind, number> | undefined): string | un
772
822
  return parts.length === 0 ? undefined : `Used: ${parts.join(", ")}.`;
773
823
  }
774
824
 
775
- /** The switches of the patches, each 0 unless the build defines it, with the ranges of its patches. */
825
+ /** The patches of each switch that has one, by switch name. */
776
826
  export function switchesOf(layout: Pick<Layout, "patches">): Map<string, PatchBlock[]> {
777
827
  const switches = new Map<string, PatchBlock[]>();
778
- for (const patch of [...layout.patches.values()].sort((a, b) => a.start - b.start)) switches.set(patch.switch, [...(switches.get(patch.switch) ?? []), patch]);
828
+ for (const patch of [...layout.patches.values()].sort((a, b) => a.start - b.start)) {
829
+ for (const alternative of patch.alternatives) switches.set(alternative.switch, [...(switches.get(alternative.switch) ?? []), patch]);
830
+ }
779
831
  return new Map([...switches].sort(([a], [b]) => (a < b ? -1 : 1)));
780
832
  }
781
833
 
782
- function switchLines(layout: Layout): string[] {
783
- const switches = switchesOf(layout);
784
- if (switches.size === 0) return [];
785
- const width = Math.max(...[...switches.keys()].map((name) => name.length));
786
- const lines = ["; Switches: each is 0 unless the build defines it. Assemble with -DNAME=1", "; (c64-assembler --define NAME=1) to put in the patches of NAME."];
787
- for (const [name, patches] of switches) {
788
- const ranges = patches.map((patch) => `${formatC64Address(patch.start)}-${formatC64Address(patch.end)}`).join(", ");
789
- lines.push(`!ifndef ${name} { ${name} = 0 }${" ".repeat(width - name.length)} ; ${patches.length} patch${patches.length === 1 ? "" : "es"}: ${ranges}`);
834
+ /** The groups of switches.asm, in order, with the default of each group. */
835
+ const SWITCH_GROUPS: ReadonlyArray<{ kind: SwitchKind; title: string }> = [
836
+ { kind: "protection", title: "Copy protection: off by default" },
837
+ { kind: "trainer", title: "Trainers: off by default" },
838
+ { kind: "cheat", title: "Cheats: off by default" },
839
+ { kind: "crack", title: "Changes of a crack: off by default" },
840
+ { kind: "fix", title: "Fixes of the releases: on by default" },
841
+ { kind: "change", title: "Other changes" },
842
+ ];
843
+
844
+ /** True when the source has switches.asm: the knowledge has switches or releases. */
845
+ export const hasSwitchFile = (layout: Pick<Layout, "switches" | "releases">) => layout.switches.length > 0 || layout.releases.length > 0;
846
+
847
+ /**
848
+ * switches.asm: every switch of the knowledge in one place. A release block
849
+ * gives each switch the value of that release when the build defines
850
+ * RELEASE_<label>; then each switch gets its default unless the build defines
851
+ * it. A comment tells the releases that have the switch on, and its patches.
852
+ */
853
+ function switchesText(layout: Layout): string {
854
+ const patches = switchesOf(layout);
855
+ const out = [
856
+ "; The switches of the patches. Each switch is 0 or 1.",
857
+ "; The default build is the clean program: copy protection, trainers, cheats",
858
+ "; and changes of a crack are off, and the fixes of the releases are on.",
859
+ `; Build a release with -D${RELEASE_DEFINE}<label>=1 (c64-assembler --release <label>).`,
860
+ "; Set one switch with -DNAME=0 or -DNAME=1 (c64-assembler --define NAME=1).",
861
+ ];
862
+ if (layout.releases.length > 0) out.push("", "; Releases");
863
+ for (const release of layout.releases) {
864
+ out.push(`; ${release.label}${release.base ? " (the program of the knowledge)" : ""}: ${release.file}${release.comment === undefined ? "" : `. ${release.comment.replace(/\s*\r?\n\s*/g, " ")}`}`);
865
+ out.push(`!ifdef ${RELEASE_DEFINE}${release.label} {`);
866
+ for (const row of layout.switches) out.push(`${INDENT}!ifndef ${row.name} { ${row.name} = ${row.releases.includes(release.label) ? 1 : 0} }`);
867
+ out.push("}");
790
868
  }
791
- return [...lines, ""];
869
+ const line = (row: SourceSwitch) => `!ifndef ${row.name} { ${row.name} = ${row.default} }`;
870
+ const width = Math.max(0, ...layout.switches.map((row) => line(row).length));
871
+ for (const group of SWITCH_GROUPS) {
872
+ const rows = layout.switches.filter((row) => row.kind === group.kind);
873
+ if (rows.length === 0) continue;
874
+ out.push("", `; ${group.title}`);
875
+ for (const row of rows) {
876
+ const ranges = (patches.get(row.name) ?? []).map((patch) => `${formatC64Address(patch.start)}-${formatC64Address(patch.end)}`);
877
+ const parts = [
878
+ row.releases.length === 0 ? "on in no release" : `on in ${row.releases.join(", ")}`,
879
+ ranges.length === 0 ? "no patch" : ranges.join(", "),
880
+ ...(row.comment === undefined ? [] : [row.comment.replace(/\s*\r?\n\s*/g, " ")]),
881
+ ];
882
+ out.push(`${line(row).padEnd(width)} ; ${parts.join(". ")}`);
883
+ }
884
+ }
885
+ return `${out.join("\n")}\n`;
792
886
  }
793
887
 
794
888
  /** constants.asm: the names outside the image by platform area, each with what it is and how the source uses it. */
@@ -801,7 +895,7 @@ function constantsText(layout: Layout): { text: string; labels: SourceLabel[] }
801
895
  });
802
896
  const nameColumn = Math.min(MAX_NAME_COLUMN, Math.max(0, ...rows.map((row) => row.name.length)));
803
897
  const valueColumn = Math.max(0, ...rows.map((row) => row.value.length));
804
- const out = [...switchLines(layout)];
898
+ const out: string[] = [];
805
899
  out.push(
806
900
  describe === undefined ? "; Names of addresses outside the image." : "; Names of addresses outside the image, by memory area.",
807
901
  '; "Used" counts the instructions and table entries of this source that use the name.',
@@ -881,23 +975,42 @@ function macrosText(layout: Layout): { text: string; lines: Map<string, { first:
881
975
  return { text: `${out.join("\n")}\n`, lines };
882
976
  }
883
977
 
884
- /** The lines that open a patch: its zone, the switch, the code, and the guard that stops a patch longer than its range. */
978
+ /** The condition that puts in the code of a switch: the switch has the value that the program does not have. */
979
+ const patchCondition = (alternative: PatchAlternative) => (alternative.base === 0 ? alternative.switch : `${alternative.switch} = 0`);
980
+
981
+ /**
982
+ * The lines that open a patch: its zone, a guard that stops two alternatives
983
+ * together, then for each switch its condition, its code and the guard that
984
+ * stops code longer than the range. The original code follows in the last
985
+ * else; the patch closes with closingBraces.
986
+ */
885
987
  function patchOpening(patch: PatchBlock): string[] {
886
988
  const bytes = patch.end - patch.start + 1;
887
989
  const range = `${formatC64Address(patch.start)}-${formatC64Address(patch.end)}`;
888
- const comment = patch.comment === undefined ? [] : patch.comment.split(/\r?\n/).map((line) => `${INDENT}; ${line}`.trimEnd());
889
- return [
890
- `!zone patch_${patch.switch}_${patch.start.toString(16).padStart(4, "0")} {`,
891
- ".patch_start",
892
- `!if ${patch.switch} {`,
893
- `${INDENT}; ${patch.switch} on: ${bytes} byte${bytes === 1 ? "" : "s"} at ${range}, NOP after the code`,
894
- ...comment,
895
- ...(patch.code === "" ? [] : patch.code.split(/\r?\n/)),
896
- `${INDENT}!if * - .patch_start > ${bytes} { !error "The patch ${patch.switch} at ${formatC64Address(patch.start)} has ", * - .patch_start, " bytes; the range has ${bytes}." } else { !fill ${bytes} - (* - .patch_start), $ea }`,
897
- "} else {",
898
- ];
990
+ const out = [`!zone patch_${patch.alternatives[0]!.switch}_${patch.start.toString(16).padStart(4, "0")} {`, ".patch_start"];
991
+ patch.alternatives.forEach((first, index) => {
992
+ for (const second of patch.alternatives.slice(index + 1)) {
993
+ out.push(`!if ${patchCondition(first)} { !if ${patchCondition(second)} { !error "${first.switch} and ${second.switch} change ${range}: turn on one of them." } }`);
994
+ }
995
+ });
996
+ patch.alternatives.forEach((alternative, index) => {
997
+ const state = alternative.base === 0 ? "on" : "off";
998
+ const comment = alternative.comment === undefined ? [] : alternative.comment.split(/\r?\n/).map((line) => `${INDENT}; ${line}`.trimEnd());
999
+ out.push(
1000
+ `${index === 0 ? "" : "} else { "}!if ${patchCondition(alternative)} {`,
1001
+ `${INDENT}; ${alternative.switch} ${state}: ${bytes} byte${bytes === 1 ? "" : "s"} at ${range}, NOP after the code`,
1002
+ ...comment,
1003
+ ...(alternative.code === "" ? [] : alternative.code.split(/\r?\n/)),
1004
+ `${INDENT}!if * - .patch_start > ${bytes} { !error "The patch ${alternative.switch} at ${formatC64Address(patch.start)} has ", * - .patch_start, " bytes; the range has ${bytes}." } else { !fill ${bytes} - (* - .patch_start), $ea }`,
1005
+ );
1006
+ });
1007
+ out.push("} else {");
1008
+ return out;
899
1009
  }
900
1010
 
1011
+ /** The braces that close a patch: one for each alternative, then the zone. */
1012
+ const closingBraces = (patch: PatchBlock) => ["}".repeat(patch.alternatives.length), "}"];
1013
+
901
1014
  const withSide = (text: string, side: string | undefined) => (side === undefined ? text : `${text.padEnd(SIDE_COLUMN - 1)} ; ${side}`);
902
1015
 
903
1016
  /**
@@ -996,7 +1109,7 @@ export function render(layout: Layout, asBytes: ReadonlySet<string>, header: str
996
1109
  const close = () => {
997
1110
  const itemEnd = item.kind === "instruction" ? item.address + item.length - 1 : item.end;
998
1111
  if (patch === undefined || itemEnd !== patch.end) return;
999
- out.push("}", "}");
1112
+ out.push(...closingBraces(patch));
1000
1113
  patch = undefined;
1001
1114
  };
1002
1115
  if (item.kind === "instruction" && item.address <= useEnd) {
@@ -1084,6 +1197,7 @@ export function render(layout: Layout, asBytes: ReadonlySet<string>, header: str
1084
1197
  result.files.push({ name: piece.file, text: `${out.join("\n")}\n` });
1085
1198
  }
1086
1199
 
1200
+ if (hasSwitchFile(layout)) result.files.push({ name: "switches.asm", text: switchesText(layout) });
1087
1201
  const constants = constantsText(layout);
1088
1202
  result.files.push({ name: "constants.asm", text: constants.text });
1089
1203
  result.labels.push(...constants.labels);
@@ -1092,7 +1206,7 @@ export function render(layout: Layout, asBytes: ReadonlySet<string>, header: str
1092
1206
  result.files.push({ name: "macros.asm", text: macros.text });
1093
1207
  result.macroLines = macros.lines;
1094
1208
  }
1095
- const main = [...header.map((line) => `; ${line}`), "", "!cpu 6510", '!source "constants.asm"', ...(layout.macros.length > 0 ? ['!source "macros.asm"'] : [])];
1209
+ const main = [...header.map((line) => `; ${line}`), "", "!cpu 6510", ...(hasSwitchFile(layout) ? ['!source "switches.asm"'] : []), '!source "constants.asm"', ...(layout.macros.length > 0 ? ['!source "macros.asm"'] : [])];
1096
1210
  for (const piece of layout.pieces) {
1097
1211
  if (piece.segmentStart) main.push("", `* = ${formatC64Address(piece.start)}`);
1098
1212
  main.push(`!source "${piece.file}"`);