@henols/c64-re-tools 2.6.0-rc.8 → 2.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/package.json +2 -2
  2. package/skills/c64-assembler/SKILL.md +3 -3
  3. package/skills/c64-assembler/scripts/assembler.ts +4 -3
  4. package/skills/c64-development/SKILL.md +3 -3
  5. package/skills/c64-docs/SKILL.md +6 -4
  6. package/skills/c64-docs/scripts/docs.ts +23 -10
  7. package/skills/c64-docs/scripts/lib/reference.ts +117 -31
  8. package/skills/c64-docs/scripts/lib/source-map.ts +14 -0
  9. package/skills/c64-knowledge/SKILL.md +10 -9
  10. package/skills/c64-knowledge/scripts/knowledge.ts +16 -9
  11. package/skills/c64-reverse-engineering/SKILL.md +9 -3
  12. package/skills/c64-source/SKILL.md +13 -10
  13. package/skills/c64-source/scripts/lib/export.ts +13 -2
  14. package/skills/c64-source/scripts/lib/loader.ts +51 -28
  15. package/skills/c64-source/scripts/lib/source.ts +24 -7
  16. package/skills/c64-source/scripts/source.ts +65 -47
  17. package/skills/c64-static-analysis/SKILL.md +26 -22
  18. package/skills/c64-static-analysis/scripts/lib/findings.ts +11 -11
  19. package/skills/c64-static-analysis/scripts/lib/instructions.ts +4 -4
  20. package/skills/c64-static-analysis/scripts/lib/macros.ts +3 -1
  21. package/skills/c64-static-analysis/scripts/static-analysis.ts +51 -35
  22. package/skills/c64-testing/SKILL.md +11 -4
  23. package/skills/c64-testing/references/recording-format.md +19 -7
  24. package/skills/c64-testing/references/scenario-format.md +6 -5
  25. package/skills/c64-testing/scripts/lib/diff-files.ts +4 -18
  26. package/skills/c64-testing/scripts/lib/play.ts +39 -37
  27. package/skills/c64-testing/scripts/lib/recording.ts +213 -65
  28. package/skills/c64-testing/scripts/lib/replay.ts +31 -5
  29. package/skills/c64-testing/scripts/lib/runs.ts +8 -3
  30. package/skills/c64-testing/scripts/lib/scenario.ts +4 -6
  31. package/skills/c64-testing/scripts/testing.ts +23 -2
  32. package/skills/c64-unpacker/SKILL.md +6 -3
  33. package/skills/c64-unpacker/scripts/lib/loads.ts +2 -2
  34. package/skills/c64-unpacker/scripts/lib/stages.ts +18 -3
  35. package/skills/c64-unpacker/scripts/unpacker.ts +38 -6
  36. package/skills/emulator/SKILL.md +2 -5
  37. package/src/build-name.ts +9 -4
  38. package/src/c64-keys.ts +98 -0
  39. package/src/c64.ts +1 -1
  40. package/src/host/main.ts +2 -2
  41. package/src/host/server.ts +3 -1
  42. package/src/host/tools/index.ts +1 -1
  43. package/src/host/vice/process.ts +34 -17
  44. package/src/host/vice/session.ts +132 -30
  45. package/src/host-client/steps.ts +21 -18
  46. package/src/host-client/tools.ts +1 -1
  47. package/src/host-client/vice-session.ts +7 -1
  48. package/src/knowledge/evidence.ts +66 -0
  49. package/src/knowledge/history.ts +5 -5
  50. package/src/knowledge/import.ts +12 -5
  51. package/src/knowledge/program.ts +81 -33
  52. package/src/knowledge/read.ts +12 -3
  53. package/src/knowledge/schema.ts +7 -7
  54. package/src/knowledge/start-screen.ts +2 -0
  55. package/src/knowledge/text.ts +28 -3
  56. package/src/knowledge/write.ts +6 -6
  57. package/src/mcp/inputs.ts +12 -0
  58. package/src/mcp/server.ts +1 -0
  59. package/src/mcp/tools/debug.ts +23 -21
  60. package/src/mcp/tools/input.ts +38 -5
  61. package/src/mcp/tools/memory.ts +12 -9
  62. package/src/native/c64run.ts +7 -4
  63. package/src/native/{ghidra → decompiler}/analyze.ts +17 -17
  64. package/src/native/{ghidra → decompiler}/language/c64rt_6510.slaspec +1 -1
  65. package/src/native/{ghidra → decompiler}/walk.ts +6 -6
  66. package/src/native/discover.ts +3 -3
  67. package/src/native/processes.ts +3 -3
  68. package/src/native/types.ts +25 -25
  69. package/src/opcodes.ts +1 -1
  70. package/src/protocol/vice.ts +47 -0
  71. package/src/reference-pages.ts +64 -0
  72. package/src/script.ts +1 -1
  73. package/src/vsf.ts +98 -0
  74. package/tools/c64run.c +158 -15
  75. package/skills/c64-testing/scripts/lib/keys.ts +0 -36
  76. /package/src/native/{ghidra → decompiler}/c64rt-wasm.ts +0 -0
  77. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.cspec +0 -0
  78. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.ldefs +0 -0
  79. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.pspec +0 -0
  80. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.sla +0 -0
  81. /package/src/native/{ghidra → decompiler}/pcode.ts +0 -0
  82. /package/src/native/{ghidra → decompiler}/wasm.ts +0 -0
@@ -17,7 +17,7 @@ import { operandText } from "#src/knowledge/expression.ts";
17
17
  import { historyAt, historyNamed, historyOfMacro, historyOfSwitch, revision, revisionNote, revisions, type HistoryEntry } from "#src/knowledge/history.ts";
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
- import { addCoverage, memoryRows, operandImages as programImages, programCoverage, programImage, requireProgram, setImage, type ImageRequest } from "#src/knowledge/program.ts";
20
+ import { addCoverage, coverageRangeCounts, memoryRows, operandImages as programImages, programCoverage, programImage, requireProgram, setImage, type ImageRequest } from "#src/knowledge/program.ts";
21
21
  import { startScreenOfStage } from "#src/knowledge/start-screen.ts";
22
22
  import {
23
23
  analyzerNamesAt,
@@ -203,11 +203,11 @@ function suppression(row: SuppressionRow) {
203
203
  return { ...spaceOf(row), suppresses: row.entity, ...place, origin: row.origin, revision: row.revision };
204
204
  }
205
205
 
206
- /** A row of the program in a revision: memory bytes, the entry, or a coverage range. */
206
+ /** A row of the program in a revision: memory bytes, the entry, or the ranges of one kind of a coverage map. */
207
207
  function programRow(entry: Extract<HistoryEntry, { entity: "memory" | "entry" | "coverage" }>) {
208
208
  if (entry.entity === "memory") return { ...spaceOf(entry.row), start: formatC64Address(entry.row.address), end: formatC64Address(entry.row.address + entry.row.bytes - 1), bytes: entry.row.bytes, origin: entry.row.origin, revision: entry.row.revision };
209
209
  if (entry.entity === "entry") return { ...spaceOf(entry.row), address: formatC64Address(entry.row.address), state: entry.row.state, stages: entry.row.stages, origin: entry.row.origin, revision: entry.row.revision };
210
- return { ...spaceOf(entry.row), kind: entry.row.kind, start: formatC64Address(entry.row.start), end: formatC64Address(entry.row.end), origin: entry.row.origin, revision: entry.row.revision };
210
+ return { ...spaceOf(entry.row), map: entry.row.map, kind: entry.row.kind, ranges: entry.row.ranges, origin: entry.row.origin, revision: entry.row.revision };
211
211
  }
212
212
 
213
213
  function historyEntry(entry: HistoryEntry) {
@@ -299,7 +299,7 @@ function listingSource(db: DatabaseSync | undefined, space: string): ListingSour
299
299
  /** Every value of --origin, for the message of a wrong one. */
300
300
  const ORIGIN_VALUES = `one of ${ORIGINS.join(", ")}, semantic or analyzer, or a comma list of them. semantic is ${SEMANTIC_ORIGINS.join(" and ")}. analyzer is ${ANALYZERS.slice(0, -1).join(", ")} and ${ANALYZERS.at(-1)}`;
301
301
 
302
- /** --origin for reads: one origin, semantic (user and llm), analyzer (dxa, ghidra and heuristic), or a comma list. */
302
+ /** --origin for reads: one origin, semantic (user and llm), analyzer (dxa, decompiler and heuristic), or a comma list. */
303
303
  function originFilter(value: string): Origin[] {
304
304
  const origins = new Set<Origin>();
305
305
  for (const part of value.split(",")) {
@@ -558,7 +558,7 @@ const READ_COMMANDS: CommandSpec[] = [
558
558
  },
559
559
  ),
560
560
  readCommand(
561
- { name: "symbols", summary: "The symbols, or with --analyzer the second names that DXA, Ghidra and the idioms gave.", options: { ...FILTER, kind: SYMBOL_KIND, analyzer: { kind: "flag", help: "the analyzer names in place of the symbols" }, ...LIST } },
561
+ { name: "symbols", summary: "The symbols, or with --analyzer the second names that DXA, the decompiler and the idioms gave.", options: { ...FILTER, kind: SYMBOL_KIND, analyzer: { kind: "flag", help: "the analyzer names in place of the symbols" }, ...LIST } },
562
562
  (db, call) => {
563
563
  const kind = call.string("kind") as (typeof SYMBOL_KINDS)[number] | undefined;
564
564
  if (call.flag("analyzer")) return { analyzerNames: list(call, listAnalyzerNames(db, rangeOf(call), kind, originsOf(call), call.space), symbol, RANGE_REST) };
@@ -598,7 +598,6 @@ const READ_COMMANDS: CommandSpec[] = [
598
598
  readCommand({ name: "spaces", summary: "The address spaces that hold knowledge.", options: LIST }, (db, call) => ({ spaces: list(call, listSpaces(db), (space) => space, MORE) })),
599
599
  readCommand({ name: "program", summary: "The program in the knowledge: its segments and entry, and the coverage maps that coverage imported, with the ranges." }, (db, call) => {
600
600
  const image = programImage(db, call.space);
601
- const ranges = db === undefined ? [] : (db.prepare("SELECT kind, count(*) AS count FROM current_coverage WHERE space = ? GROUP BY kind ORDER BY kind").all(call.space) as Array<{ kind: string; count: number }>);
602
601
  return {
603
602
  ...(call.space === DEFAULT_SPACE ? {} : { space: call.space }),
604
603
  image:
@@ -612,7 +611,7 @@ const READ_COMMANDS: CommandSpec[] = [
612
611
  stages: image.stages?.length ?? 0,
613
612
  },
614
613
  ...((row) => (row === undefined ? {} : { startScreen: startScreen(row) }))(currentStartScreen(db, call.space)),
615
- coverage: { maps: [...new Set(coverageRuns(db).filter((run) => run.space === call.space).map((run) => run.name))], ranges: Object.fromEntries(ranges.map((row) => [row.kind, row.count])) },
614
+ coverage: { maps: [...new Set(coverageRuns(db).filter((run) => run.space === call.space).map((run) => run.name))], ranges: coverageRangeCounts(db, call.space) },
616
615
  };
617
616
  }),
618
617
  readCommand(
@@ -1061,7 +1060,7 @@ const WRITE_COMMANDS: CommandSpec[] = [
1061
1060
  writeCommand(
1062
1061
  {
1063
1062
  name: "coverage",
1064
- summary: "Joins coverage maps of the emulator or of a run into the coverage of the knowledge. Each map is named by its path: --evidence coverage:<path> cites it.",
1063
+ summary: "Puts coverage maps of the emulator or of a run into the coverage of the knowledge. Each map is named by its path: a new map of a path replaces the earlier map of that path, and --evidence coverage:<path> cites it.",
1065
1064
  subjects: [{ name: "<map>", help: "a 64 KiB coverage map", list: true }],
1066
1065
  },
1067
1066
  (call) => {
@@ -1069,7 +1068,15 @@ const WRITE_COMMANDS: CommandSpec[] = [
1069
1068
  const maps = call.subjects.map((path) => ({ bytes: readProjectFile(path).bytes, name: knowledgePath(path, "<map>") }));
1070
1069
  return (db) => {
1071
1070
  const { revision, current } = addCoverage(db, context, { space: call.space, maps });
1072
- return { revision, ...spaceOf(current), imported: current.imported, known: current.known, ranges: current.ranges };
1071
+ const body = { revision, ...spaceOf(current), imported: current.imported, replaced: current.replaced, known: current.known, added: current.added, removed: current.removed };
1072
+ // Only a range that the coverage gained or lost changes the source and the reference.
1073
+ const hint =
1074
+ revision === null
1075
+ ? "The knowledge has each map already. Nothing changed."
1076
+ : current.added === 0 && current.removed === 0
1077
+ ? "The coverage did not change. The knowledge keeps the maps as evidence. The source and the reference do not change."
1078
+ : `The coverage gained ${current.added} and lost ${current.removed} ranges of accesses. They can change the leftovers and the code that no run executed. Generate the source again, then the reference.`;
1079
+ return reply(body, { hint });
1073
1080
  };
1074
1081
  },
1075
1082
  ),
@@ -85,7 +85,7 @@ Do the stages in this sequence. Go to the next stage only when its exit check is
85
85
 
86
86
  | Stage | Work | Exit check |
87
87
  |---|---|---|
88
- | 1. Acceptance | Ask the user for the criteria of the rebuild. Offer these criteria: identical source, a verified loader, passed test scenarios and passed replays of the recordings. Also offer a list of the code that no run executed, and documentation of the flows, tables, formats and graphics. | The user gave the criteria. |
88
+ | 1. Acceptance | Ask the user for the criteria of the rebuild. Offer these criteria: a base release that is identical to the original, and a passed replay of each recording on the default build. Also offer test scenarios 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. |
89
89
  | 2. Get | List the disk image. Extract the start file into `original/`. | The start file is in the project. |
90
90
  | 3. Start | Find the SYS address of the BASIC start. | You have the entry address. |
91
91
  | 4. Unpack | Examine the program for a packer. Trace it and find its stages. Capture a packed program into `.c64-re-tools/local/`. When a segment is the data of a cracktro and the program does not read it, capture again and exclude that range. Put the capture, or the PRG of a program without a packer, into the project knowledge. | The program in the project knowledge has the segments and the entry. |
@@ -94,12 +94,18 @@ Do the stages in this sequence. Go to the next stage only when its exit check is
94
94
  | 7. Name | If the workspace has a routine library, match the program against it. Write the names of the matches to the project knowledge. Then name each routine in the scope and give it a comment. Find the platform addresses in the memory map of the C64. Record the modules. Put the modules of one part of the program in one folder, for example `music/`, `irq/` or `graphics/`. 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. |
95
95
  | 8. Releases and switches | Record the original file, or the capture of it, as the base release in the project knowledge. The project knowledge keeps the bytes of each release. Record each other release. Compare the releases. Find the leftovers. Record a switch for each copy protection, trainer, cheat, crack change and correction. Record a patch for each range of a switch. Record each leftover as a region with a comment. | The project knowledge lists each switch. Each difference between the releases is in a patch, or the answer gives it as an exception. |
96
96
  | 9. Generate | Generate the source from the project knowledge into `src`. For an unpacked program, also generate the loader. | The result of the generation is PASS. A release whose code is at other addresses is a version with a project of its own, or an exception in the answer. See "Versions of one program". |
97
- | 10. Build and test | Build the base release into `build/`, and compare it with the original. Build the default build. Run the test scenarios in `tests/`. Replay each recording on the rebuild. For each replay, give the checkpoint routine, the state and the random state with the names of stage 7. | The criteria of stage 1 are true. |
97
+ | 10. Build and test | Build the base release into `build/`, and compare it with the original. Build the default build. For a generated source with a loader, the default build is `build/clean_loader.prg`. Else it is `build/clean.prg`. Replay each recording on the default build. For each replay, give the checkpoint routine, the state and the random state with the names of stage 7. Then do only the tests that the next paragraph gives. | The criteria of stage 1 are true. |
98
98
  | 11. Document | When the criteria ask for documentation, generate it into `README.md` and `docs/`. For versions in a group folder, also write the shared pages of the group folder. Then link the pages. | The link check of the documentation gives PASS. |
99
99
  | 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. |
100
100
 
101
101
  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 generation writes the source again.
102
102
 
103
+ In stage 10, a base release that is identical to the original proves the source. Do not test the base release more. The default build is different from the base release only in its patches, its leftovers and its loader. The replays on the default build test these differences:
104
+
105
+ - Replay only the default build: `build/clean_loader.prg` for a source with a loader, else `build/clean.prg`. Do not replay a release build or a build with a switch that is not at its default.
106
+ - Write a test scenario only for a test that a replay cannot do. Examples are a program that loads more files from a disk, and a criterion of the user.
107
+ - Do the other tests of stage 1 only when the user selected them.
108
+
103
109
  After stage 7, save each routine that other programs can have to the routine library of the workspace. Examples are a music driver, a decruncher and a loader. Ask the user before you make a library.
104
110
 
105
111
  ### Deliverables of a full rebuild
@@ -108,7 +114,7 @@ After stage 7, save each routine that other programs can have to the routine lib
108
114
  - the files of the program in `original/`, as the user gave them
109
115
  - the generated source
110
116
  - the built program and the loader
111
- - the test scenarios
117
+ - the test scenarios, if you wrote them
112
118
  - the recordings in `tests/recordings/`
113
119
  - the documentation in `README.md` and `docs/`, when the criteria ask for it
114
120
  - the runs in `runs/` that the knowledge gives as evidence
@@ -119,7 +119,8 @@ To make the source better, change the project knowledge. Then generate again.
119
119
  - `patchesNotWritten`: each patch that the source does not have, with its range, `switch` and `reason`.
120
120
  - `switches`, `default`, `releases`: the checks of the switches. See "Switches and releases".
121
121
  - `loader`: the check of the loader. See "The loader".
122
- - `staleLoader`: a run without `--loader` kept `loader.asm` and the loader program of another knowledge revision. `files` gives the files. `revision` gives the revision of `loader.asm`. Without `revision`, `loader.asm` does not give one. `noEntryState: true` tells that the knowledge has no entry state for a new loader. A change in a space that the loader does not hold does not make the loader stale. The loader holds space `c64` and the space of the stage of the start screen.
122
+ - `staleLoader`: a run without `--loader` kept `loader.asm` and the loader program of another knowledge revision, or of another version of the toolkit. `files` gives the files. `revision` gives the revision of `loader.asm`, and `version` its toolkit version. Without `revision`, `loader.asm` does not give one. `noEntryState: true` tells that the knowledge has no entry state for a new loader. A change in a space that the loader does not hold does not make the loader stale. The loader holds space `c64` and the space of the stage of the start screen.
123
+ - `staleReference`: each reference folder of the project that has pages of this source from an earlier knowledge revision. Each item has the `folder` and the `revision` of its pages.
123
124
 
124
125
  `result` is `FAIL` for each of these:
125
126
 
@@ -148,6 +149,7 @@ Do these actions for the findings:
148
149
  | `conflict` | The knowledge has conflicts from a git merge. Merge the open changes of the project knowledge. Then run the command again. |
149
150
  | A list with `rest` | Give a larger `--max-listed`. For `notExecuted`, read the file in `rest`. |
150
151
  | `staleLoader` | The loader can copy bytes that are not the bytes of the source. Run `nextAction`, which generates with `--loader`. With `noEntryState: true`, remove the files when the build does not use them. |
152
+ | `staleReference` | The reference pages do not agree with the new source. When you do not change the knowledge again, generate the reference pages again from this source into each `folder`. |
151
153
 
152
154
  #### The source files
153
155
 
@@ -155,7 +157,7 @@ Do these actions for the findings:
155
157
  - Each module in the knowledge is one file. A module starts at its address. It stops at the next module or at the end of its segment. The file of a module can be in a folder, for example `music/driver.asm`. Without modules, each segment is one file, `segments/segment_xxxx.asm`.
156
158
  - `constants.asm` holds the names of addresses outside the program, for example `EXTCOL = $d020`. It also holds the register names in the program, for example `RASTER = $d012`. The names are in groups by memory area, in address order. Drive code and banks have one group only.
157
159
  - The side comment of a constant is the knowledge comment of the address. Without a comment, it is the platform meaning. When the knowledge name is not the platform name, the platform name comes first. For an I/O mirror without a meaning, the comment gives the register that the mirror repeats.
158
- - After the side comment, `Used:` counts how the source uses the name. The kinds are `read`, `written`, `modified`, `called`, `jumped to`, `jumped through`, `branched to`, `pointer`, `address`, `table` and `macro argument`. `address` is an immediate operand expression. `table` is an entry in a table of addresses.
160
+ - After the side comment, `Used:` counts how the source uses the name. The kinds are `read`, `written`, `modified`, `called`, `jumped to`, `jumped through`, `branched to`, `pointer`, `address`, `table` and `macro argument`. `address` is an immediate operand expression. `table` is an entry in a table of addresses. A macro line counts one `macro argument` for each name in its args. The other bytes that the macro reads or writes, for example the high byte of a 16-bit value, count for no name.
159
161
  - `config.asm` holds the value of each switch, for example `PROTECTION = 0`. The switches are in groups by kind. The side comment gives the releases that have the switch on, the ranges of its patches and the comment of the switch.
160
162
  - You can change a value in `config.asm` to 0 or 1. The next run keeps the values of the file. It adds a new switch with its default. It removes a switch that the knowledge does not have.
161
163
  - When the knowledge has a start screen, `config.asm` also has `START_SCREEN = 1`. Set it to 0 to start the program at once. Then assemble `loader.asm` again.
@@ -167,7 +169,7 @@ Do these actions for the findings:
167
169
  #### Names in the source
168
170
 
169
171
  - A label or a constant gets the name of the address in the knowledge.
170
- - Without a knowledge name, it gets the platform name, for example `EXTCOL` or `CHROUT`. A platform name wins over an analyzer name (`dxa`, `ghidra` or `heuristic`), for example `EXTCOL` over `ld020`. A `user` or `llm` name wins over a platform name.
172
+ - Without a knowledge name, it gets the platform name, for example `EXTCOL` or `CHROUT`. A platform name wins over an analyzer name (`dxa`, `decompiler` or `heuristic`), for example `EXTCOL` over `ld020`. A `user` or `llm` name wins over a platform name.
171
173
  - An address in the program without a name gets `l_xxxx`.
172
174
  - A read or a write in the I/O area `$d000-$dfff` uses the register, also when the program has RAM there. For example, `lda $dd0e` is `lda CI2CRA` and `sta $d012` is `sta RASTER`. `constants.asm` has these names. An address without a platform name stays a number, for example `sta $d800,x`. The data label of the RAM stays at its data. A `user` or `llm` name of the address wins over the register.
173
175
  - A platform name in an operand expression of the knowledge stays in the source. When the program has the address, `constants.asm` has the name, and the RAM there keeps its label.
@@ -195,13 +197,13 @@ Do these actions for the findings:
195
197
 
196
198
  #### The leftovers
197
199
 
198
- A leftover is a range of the program that nothing uses: unused code, old copies and old data. The script finds the leftovers from the coverage, as the export finds its free ranges (see "The free ranges"). The start screen, the patches, the macro uses and the addresses that the code of a patch names are never leftovers.
200
+ A leftover is a range of the program that nothing uses: unused code, old copies and old data. The script finds the leftovers from the coverage, as the export finds its free ranges (see "The free ranges"). The start screen, the patches and the addresses that the code of a patch names are never leftovers. A macro use in code that nothing uses is in the leftover with that code. A leftover never cuts a macro use in two.
199
201
 
200
202
  - Each range of leftovers is a file `leftovers/leftover_xxxx.asm`. When a range cuts a module, the module continues after the range in `<module>_xxxx.asm`, in the folder of the module. The module in the knowledge does not change.
201
203
  - `main.asm` builds a leftover file only when `LEFTOVERS` is 1. When it is 0, the build skips the bytes. Thus the addresses after the range do not change.
202
204
  - `config.asm` has `LEFTOVERS = 0`. Thus the default build is the clean program, without the leftovers.
203
205
  - Each release has `LEFTOVERS = 1`. Thus the build of a release gives the bytes of the release.
204
- - The loader program never has the leftovers. The loader does not copy them, and the memory there keeps the bytes that were in it before.
206
+ - The loader program never has the leftovers. The plain form does not copy them, and the memory there keeps the bytes that were in it before. The packed form unpacks the build of `main.asm` in one piece, so the leftovers in it are $00. A leftover after the last byte of that build is not in it: the memory there keeps the bytes that were in it before.
205
207
  - Without coverage, no range is a leftover. Put the coverage of the runs into the project knowledge. Then generate again.
206
208
  - When `leftovers.changed` has ranges, the default build and the loader program now leave out other bytes. A test that observes the `added` bytes on the loader program gets other values there. Fill the `added` ranges in the test of the leftovers. In a test that compares them, exclude them with the reason that they are leftovers.
207
209
  - A leftover can be wrong when the coverage does not show a use. For example, the VIC-II reads a range, or the program reads a range before it writes it. Then a test of the loader program fails. Record the region in the project knowledge, or put the coverage of more runs into it. Do not change the source.
@@ -274,7 +276,7 @@ The start screen:
274
276
  - With a start screen, the copier uses three pages, not two.
275
277
  - The start screen is part of the clean build only. The loader program always shows it. A release build has no start screen, and `LEFTOVERS = 1` also turns it off.
276
278
  - 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.
277
- - A test that runs the loader program 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`.
279
+ - A test that runs the loader program stops at the start screen, because the start screen waits for a key. Run until `loader_start_screen_wait`. Then set the PC to `loader_start_screen_continue`.
278
280
 
279
281
  `loader` holds these fields:
280
282
 
@@ -320,7 +322,7 @@ The program is packed while the screen shows. Thus the picture and the tune have
320
322
  - The loader program has only the bytes of the stage that the start screen uses. These are the screen, the bitmap and the charset. With a call, they are also each byte of the stage that is not free from the call, as in "The free ranges". A call thus needs the coverage of the stage.
321
323
  - With colours from the colour RAM of the capture, the show code holds the 1000 colours. It copies them to the colour RAM.
322
324
  - 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.
323
- - `start_screen_stage.asm` holds the show code and the bytes of the stage. Do not edit it. To make the loader program again, run `generate --loader`.
325
+ - `start_screen_stage.asm` holds the show code and the bytes of the stage. Do not edit it. To make the loader program again, run `generate --out <dir> --loader`.
324
326
  - 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.
325
327
  - The check runs the loader program 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.
326
328
 
@@ -335,10 +337,10 @@ A loader file that loads into $d000 or higher writes the I/O area. When the prog
335
337
  To make the packed loader for other switch values, do these steps:
336
338
 
337
339
  1. Assemble `main.asm` without an output path. The build name of the program tells the switch values, for example `build/custom_trainer.prg`. The leftovers are $00 in this build.
338
- 2. Assemble `loader.asm` without an output path, for example to `build/custom_trainer_loader.prg`. This is the copier.
340
+ 2. Assemble `loader.asm` without an output path, for example to `build/custom_trainer_copier.prg`. This is the copier. The build name has `copier` in place of `loader`, so the build does not write over the loader program.
339
341
  3. Pack the two files into `build/custom_trainer_packed.prg`. The start address is the copier address in the comment at the start of `loader.asm`. The memory configuration at the exit is `$34`.
340
342
 
341
- These steps do not work when a segment starts below $0400. They also do not work when a patch is between the free ranges of `loader.asm`. In these cases, use `generate --loader` for the base release.
343
+ These steps do not work when a segment starts below $0400. They also do not work when a patch is between the free ranges of `loader.asm`. In these cases, use `generate --out <dir> --loader` for the base release.
342
344
 
343
345
  ---
344
346
 
@@ -413,6 +415,7 @@ Data becomes free only when all of these are true:
413
415
  - No run read, wrote or executed a byte of it.
414
416
  - No code that stays reads it or names it. No table that stays has an entry in it.
415
417
  - It is not in the BASIC line that starts the program, and not at $fffa-$ffff.
418
+ - No `charset`, `sprite`, `bitmap` or `screen` region has a byte of it. For example, `unused` bytes in a bitmap stay.
416
419
 
417
420
  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.
418
421
 
@@ -447,7 +450,7 @@ tests/ the tests of the project, changed for the new program
447
450
  5. Record names, comments, regions and modules in the project knowledge.
448
451
  6. Run `generate` again. Do steps 4 to 6 again until the source is clear.
449
452
  7. Assemble `main.asm` to a program. This is the default build. For a release, give the build option `--release <label>`.
450
- 8. For an unpacked program, run `generate` with `--loader` at the end. Compare the loader program with the original program in a test.
453
+ 8. For an unpacked program, run `generate --out <dir> --loader` at the end. Compare the loader program with the original program in a test.
451
454
  9. To start a new program from the rebuild, run `export`.
452
455
 
453
456
  ---
@@ -23,12 +23,22 @@ import { OPCODES } from "#src/opcodes.ts";
23
23
  */
24
24
  export const DROPPABLE_DATA: readonly RegionType[] = ["bytes", "words", ...POINTER_TABLE_TYPES, "petscii", "workspace", "unused"];
25
25
 
26
+ /** The data that the VIC-II reads: a region of another type that overlaps it stays too, for example unused bytes in a bitmap. */
27
+ const VIC_DATA: readonly RegionType[] = ["charset", "sprite", "bitmap", "screen"];
28
+
26
29
  /** Regions of code: their bytes are the blocks of the decoded instructions. */
27
30
  const CODE_TYPES: readonly RegionType[] = ["code", "jumps", "dual-use"];
28
31
 
29
32
  /** The hardware vectors $fffa-$ffff: they stay when the image holds them. */
30
33
  const VECTORS: AddressRange = { start: 0xfffa, end: 0xffff };
31
34
 
35
+ /**
36
+ * The coverage flags that can be a use of the RAM byte: a read or a run of the
37
+ * ROM uses the ROM, not the RAM under it, so a JSR into the KERNAL keeps no byte
38
+ * of the image. The I/O flags stay, as VICE gives each access at $d000-$dfff as I/O.
39
+ */
40
+ const RAM_ACCESS = 0xff & ~(COVERAGE.romRead | COVERAGE.romExecute);
41
+
32
42
  /** The I/O area: two immediates stored there are chip values, such as a timer latch, not an address. */
33
43
  const IO_AREA: AddressRange = { start: 0xd000, end: 0xdfff };
34
44
 
@@ -241,10 +251,10 @@ const isTable = (type: RegionType) => type === "jumps" || (POINTER_TABLE_TYPES a
241
251
  */
242
252
  export function planDrops(input: DropInput): DropPlan {
243
253
  const inImage = (address: number) => inside(address, input.segments);
244
- const touched = (address: number) => input.coverage !== undefined && input.coverage[address] !== 0;
254
+ const touched = (address: number) => input.coverage !== undefined && (input.coverage[address]! & RAM_ACCESS) !== 0;
245
255
  const executed = (address: number) => input.coverage !== undefined && (input.coverage[address]! & COVERAGE.ramExecute) !== 0;
246
256
  const regions = input.regions.flatMap((region) => input.segments.filter((segment) => overlaps(region, segment)).map((segment) => ({ start: Math.max(region.start, segment.start), end: Math.min(region.end, segment.end), type: region.type })));
247
- // The source writes a data region as data, also where Ghidra decoded instructions in it: those are no code.
257
+ // The source writes a data region as data, also where the decompiler decoded instructions in it: those are no code.
248
258
  const instructions = new Map([...input.instructions].filter(([start, length]) => !regions.some((region) => !CODE_TYPES.includes(region.type) && start <= region.end && region.start <= start + length - 1)));
249
259
  const blocks = blocksOf(instructions, input.memory);
250
260
  // An indexed operand reads in the region that holds it, and in the next region when it is the last byte (table-1,x).
@@ -323,6 +333,7 @@ export function planDrops(input: DropInput): DropPlan {
323
333
  const units = automatic
324
334
  ? regions.filter((region) => {
325
335
  if (!DROPPABLE_DATA.includes(region.type) || gone.some((range) => overlaps(range, region))) return false;
336
+ if (regions.some((other) => VIC_DATA.includes(other.type) && overlaps(other, region))) return false;
326
337
  if ([...input.keep, ...input.changed, VECTORS, ...(input.basic === undefined ? [] : [input.basic])].some((range) => overlaps(range, region))) return false;
327
338
  for (let address = region.start; address <= region.end; address++) if (touched(address)) return false;
328
339
  return true;
@@ -16,11 +16,14 @@
16
16
  import { readFileSync } from "node:fs";
17
17
  import { fileURLToPath } from "node:url";
18
18
 
19
+ import { COPIER_LINE } from "#src/build-name.ts";
19
20
  import { type AddressRange, formatC64Address, formatC64Byte, prgRange } from "#src/c64.ts";
20
21
  import { compareBuild, mergedPrograms } from "#src/compare.ts";
21
22
  import { Refusal } from "#src/errors.ts";
22
23
  import { parseEntryState } from "#src/host-client/entry-state.ts";
23
24
  import { isRomFont, startScreenRanges, type StartScreenRow } from "#src/knowledge/read.ts";
25
+ import { LOADER_JUMP } from "#src/knowledge/start-screen.ts";
26
+ import { romUseOfPort } from "#src/platform.ts";
24
27
  import { WireFailure } from "#src/host-client/tools.ts";
25
28
  import { pack } from "#src/native/exomizer.ts";
26
29
  import type { ToolContext } from "#src/native/run.ts";
@@ -137,9 +140,7 @@ export function loaderLimits(plan: { cia?: CiaPlan }): string[] {
137
140
  return plan.cia.limits;
138
141
  }
139
142
 
140
- /** The label of the loader's jump to the entry, in ACME's symbol list. */
141
- export const LOADER_JUMP = "c64_source_loader_jump";
142
- export { START_SCREEN_CONTINUE, START_SCREEN_WAIT } from "#src/knowledge/start-screen.ts";
143
+ export { LOADER_JUMP, START_SCREEN_CONTINUE, START_SCREEN_WAIT } from "#src/knowledge/start-screen.ts";
143
144
  /** The file of the start screen in the generated source. */
144
145
  export const START_SCREEN_FILE = "start_screen.asm";
145
146
  /** The code of the start screen: the same for each program. loader.asm sets its values. */
@@ -216,11 +217,12 @@ const COPY_ENTRY = 7;
216
217
  const TABLE_COPIES = Math.floor((256 - 2) / COPY_ENTRY);
217
218
  /** A loader that loads into $d000 or higher would write the I/O area. */
218
219
  const LOAD_LIMIT = 0xcfff;
219
- const COPIER_PAGES = [...Array.from({ length: 15 }, (_, index) => 0xc000 + index * 0x100), ...Array.from({ length: 0x9b }, (_, index) => 0x9e00 - index * 0x100)];
220
- /** The areas where the copier can run: RAM that no ROM and no I/O hides when $01 is $34 or $35, above the screen at $0400. */
221
- const COPIER_AREAS: readonly AddressRange[] = [
222
- { start: 0x0400, end: 0x9fff },
223
- { start: 0xc000, end: 0xcfff },
220
+ /** The pages where the plain copier can start, the first one that is free: then the RAM that a ROM can hide, as copierAreas allows. */
221
+ const COPIER_PAGES = [
222
+ ...Array.from({ length: 15 }, (_, index) => 0xc000 + index * 0x100),
223
+ ...Array.from({ length: 0x9b }, (_, index) => 0x9e00 - index * 0x100),
224
+ ...Array.from({ length: 0x20 }, (_, index) => 0xa000 + index * 0x100),
225
+ ...Array.from({ length: 0x20 }, (_, index) => 0xe000 + index * 0x100),
224
226
  ];
225
227
 
226
228
  const overlaps = (a: AddressRange, b: AddressRange) => a.start <= b.end && b.start <= a.end;
@@ -564,13 +566,14 @@ export function planLoader(input: LoaderInput): LoaderPlan {
564
566
  throw new WireFailure("invalid-input", `No copy order exists: each of these copies writes over the packed bytes of another one: ${clashing.join(", ")}. Write the loader by hand.`);
565
567
  }
566
568
  const loaded = { start: LOAD, end };
569
+ const areas = copierAreas(state.port);
567
570
  const copier = COPIER_PAGES.find((page) => {
568
571
  const pages = { start: page, end: page + copierBytes - 1 };
569
- return COPIER_AREAS.some((area) => pages.start >= area.start && pages.end <= area.end) && !overlaps(pages, loaded) && plain.every((copy) => !overlaps(pages, copy.target));
572
+ return areas.some((area) => pages.start >= area.start && pages.end <= area.end) && !overlaps(pages, loaded) && plain.every((copy) => !overlaps(pages, copy.target));
570
573
  });
571
574
  if (copier === undefined) {
572
575
  const count = copierPages === 2 ? "two" : "three";
573
- throw new WireFailure("invalid-input", `No ${count} free pages exist for the copier in $0400-$9fff or $c000-$cfff outside the loader (${show(loaded)}) and the targets: ${plain.map((copy) => show(copy.target)).join(", ")}.`);
576
+ throw new WireFailure("invalid-input", `No ${count} free pages exist for the copier in ${areas.map(show).join(" or ")} outside the loader (${show(loaded)}) and the targets: ${plain.map((copy) => show(copy.target)).join(", ")}.`);
574
577
  }
575
578
  const copies: Copy[] = order.map((index) => {
576
579
  const copy = plain[index]!;
@@ -640,11 +643,21 @@ export function planLoader(input: LoaderInput): LoaderPlan {
640
643
  };
641
644
  }
642
645
 
643
- /** Where the packed form puts its copier with the bytes of pages 0-3: the copier sets $01 to $35 and to the entry's value, so it is not under a ROM or the I/O area. */
644
- const PACKED_AREAS: readonly AddressRange[] = [
645
- { start: 0x0400, end: 0x9fff },
646
- { start: 0xc000, end: 0xcfff },
647
- ];
646
+ /** The hardware vectors at $fffa-$ffff: the copier and the pieces of pages 0-3 stay below them. */
647
+ const BELOW_VECTORS = 0xfff9;
648
+ /** Where the packed form puts the bytes of pages 0-3: the copier reads them with all RAM visible ($01 = $34). */
649
+ const PIECE_AREA: AddressRange = { start: 0x0400, end: BELOW_VECTORS };
650
+
651
+ /**
652
+ * Where a loader puts its copier: the copier sets $01 to $35 and then to the
653
+ * entry's value, so it is in RAM that both show. A port bit that is an input
654
+ * reads 1.
655
+ */
656
+ export function copierAreas(port: readonly [number, number]): AddressRange[] {
657
+ const rom = romUseOfPort((port[1] | ~port[0]) & 0x07);
658
+ if (rom.basic) return [{ start: 0x0400, end: 0x9fff }, { start: 0xc000, end: 0xcfff }];
659
+ return [{ start: 0x0400, end: 0xcfff }, ...(rom.kernal ? [] : [{ start: 0xe000, end: BELOW_VECTORS }])];
660
+ }
648
661
  /** The free ranges that a refusal of the packed form names. */
649
662
  const SHOWN_FREE = 8;
650
663
 
@@ -658,8 +671,10 @@ const SHOWN_FREE = 8;
658
671
  * writes them after the unpack. Between its ranges, loader.asm holds the
659
672
  * bytes of the image, so its build does not change a segment.
660
673
  */
661
- function planPacked(input: LoaderInput, blocks: Block[], cia: ReturnType<typeof ciaSection>, codeSize: number, screen: StartScreenPlan | undefined, tooLarge: string): LoaderPlan {
674
+ function planPacked(input: LoaderInput, blocks: Block[], cia: ReturnType<typeof ciaSection>, copierCode: number, screen: StartScreenPlan | undefined, tooLarge: string): LoaderPlan {
662
675
  const { state } = input;
676
+ // The packed copier starts with SEI, as the stub of the plain form does: an interrupt in the copies would go through the vectors in RAM.
677
+ const codeSize = copierCode + 1;
663
678
  // The parts below $0400 without $00/$01, which the loader sets last.
664
679
  const low = blocks.flatMap((block) => {
665
680
  const range = { start: Math.max(block.range.start, 0x0002), end: Math.min(block.range.end, 0x03ff) };
@@ -668,16 +683,21 @@ function planPacked(input: LoaderInput, blocks: Block[], cia: ReturnType<typeof
668
683
  return [{ what: cut ? `${block.what}, part ${show(range)}` : block.what, range, bytes: block.bytes }];
669
684
  });
670
685
  const lowBytes = low.reduce((sum, block) => sum + block.range.end - block.range.start + 1, 0);
671
- const free = PACKED_AREAS.flatMap((area) => subtract(area, input.segments));
672
- const placed = placePacked(free, low, codeSize);
686
+ const areas = copierAreas(state.port);
687
+ const free = subtract(PIECE_AREA, input.segments);
688
+ const copierFree = areas.flatMap((area) => subtract(area, input.segments));
689
+ const placed = placePacked(copierFree, free, low, codeSize);
673
690
  if ("refusal" in placed) {
674
- const largest = [...free].sort((a, b) => b.end - b.start - (a.end - a.start)).slice(0, SHOWN_FREE);
675
- const ranges = largest.length === 0 ? "none" : largest.map((range) => `${show(range)} (${range.end - range.start + 1} bytes)`).join(", ");
691
+ const largest = (ranges: AddressRange[]) => {
692
+ const shown = [...ranges].sort((a, b) => b.end - b.start - (a.end - a.start)).slice(0, SHOWN_FREE);
693
+ return shown.length === 0 ? "none" : shown.map((range) => `${show(range)} (${range.end - range.start + 1} bytes)`).join(", ");
694
+ };
695
+ const ranges = placed.refusal === "copies" ? `The largest free ranges for pages 0-3: ${largest(free)}.` : `The largest free ranges for the copier: ${largest(copierFree)}. The largest free ranges for pages 0-3: ${largest(free)}.`;
676
696
  const why =
677
697
  placed.refusal === "copies"
678
698
  ? `A packed loader needs more than ${MAX_PACKED_COPIES} copies for the ${lowBytes} bytes of pages 0-3 in the free ranges.`
679
- : `A packed loader needs one free range of ${codeSize + COPY_ENTRY * Math.max(low.length, 1) + 2} bytes or more for its copier, and ${lowBytes} more free bytes for pages 0-3, in $0400-$9fff or $c000-$cfff outside the segments.${screen === undefined ? "" : ` The start screen takes ${START_SCREEN_SIZES[screen.colourMode]} bytes of the copier: without it (unstart-screen), the copier is smaller.`}`;
680
- throw new WireFailure("invalid-input", `${tooLarge} ${why} The largest free ranges there: ${ranges}. Write the loader by hand.`);
699
+ : `A packed loader needs one free range of ${codeSize + COPY_ENTRY * Math.max(low.length, 1) + 2} bytes or more for its copier in ${areas.map(show).join(" or ")}, and ${lowBytes} more free bytes for pages 0-3 in ${show(PIECE_AREA)}, outside the segments. The copier runs with $01 = $35 and then with the $01 of the entry, so it is in RAM that both show.${screen === undefined ? "" : ` The start screen takes ${START_SCREEN_SIZES[screen.colourMode]} bytes of the copier: without it (unstart-screen), the copier is smaller.`}`;
700
+ throw new WireFailure("invalid-input", `${tooLarge} ${why} ${ranges} Write the loader by hand.`);
681
701
  }
682
702
  const { copier, pieces } = placed;
683
703
  const copierEnd = copier + codeSize + COPY_ENTRY * pieces.length + 2 - 1;
@@ -691,6 +711,7 @@ function planPacked(input: LoaderInput, blocks: Block[], cia: ReturnType<typeof
691
711
  "; The image is too large for one loader file, so this is the packed form. Exomizer packs the",
692
712
  `; build of main.asm and the build of this file into the loader program, with --entry '${formatC64Address(copier)}' and --exit-memory '$34'.`,
693
713
  "; The unpacker of Exomizer uses the zero page and $0334-$03ff, so the copier writes pages $0002-$03ff after the unpack.",
714
+ COPIER_LINE,
694
715
  "",
695
716
  "!cpu 6510",
696
717
  ...settingsLines(input),
@@ -702,6 +723,7 @@ function planPacked(input: LoaderInput, blocks: Block[], cia: ReturnType<typeof
702
723
  `; The copier runs at ${formatC64Address(copier)}. The flags pass through ${formatC64Address(stackByte)}, the free stack byte below the stack pointer.`,
703
724
  `* = ${formatC64Address(copier)}`,
704
725
  COPIER_SOURCE,
726
+ " sei",
705
727
  // The entry by its address: main.asm, which has its label, is not in this build.
706
728
  ...copierLines(state, cia, stackByte, `${formatC64Address(input.entry)}${input.entryName === undefined ? "" : ` ; ${input.entryName} in main.asm`}`, screen !== undefined),
707
729
  ];
@@ -786,19 +808,19 @@ export function placePieces(ranges: AddressRange[], low: ReadonlyArray<{ what: s
786
808
 
787
809
  /**
788
810
  * Where the packed form puts its copier and the pieces of pages 0-3: the copier
789
- * in one free range, a free page of the plain copier first, else the start of a
811
+ * in one range of copierFree, a free page of the plain copier first, else the start of a
790
812
  * free range. The placement with the fewest pieces wins, then the one with the
791
813
  * shortest build of loader.asm.
792
814
  */
793
- function placePacked(free: AddressRange[], low: Parameters<typeof placePieces>[1], codeSize: number): { copier: number; pieces: Piece[] } | { refusal: "room" | "copies" } {
794
- const candidates = [...COPIER_PAGES, ...free.map((range) => range.start)];
815
+ function placePacked(copierFree: AddressRange[], free: AddressRange[], low: Parameters<typeof placePieces>[1], codeSize: number): { copier: number; pieces: Piece[] } | { refusal: "room" | "copies" } {
816
+ const candidates = [...COPIER_PAGES, ...copierFree.map((range) => range.start)];
795
817
  // The table has one entry per piece: a split can make the copier larger, so the room for the table grows until it holds every piece.
796
818
  for (let copies = Math.max(low.length, 1); copies <= MAX_PACKED_COPIES; ) {
797
819
  const size = codeSize + COPY_ENTRY * copies + 2;
798
820
  let best: { copier: number; pieces: Piece[]; span: number } | undefined;
799
821
  for (const copier of candidates) {
800
822
  const range = { start: copier, end: copier + size - 1 };
801
- if (!free.some((area) => range.start >= area.start && range.end <= area.end)) continue;
823
+ if (!copierFree.some((area) => range.start >= area.start && range.end <= area.end)) continue;
802
824
  // A piece goes to the start of its range: a range below the copier adds its whole length to the build.
803
825
  const distance = (other: AddressRange) => (other.end < range.start ? range.start - other.start : other.start - range.end);
804
826
  const pieces = placePieces(free.flatMap((area) => subtract(area, [range])), low, distance);
@@ -934,10 +956,11 @@ function copierLines(state: EntryState, cia: ReturnType<typeof ciaSection>, stac
934
956
  // The CIA part runs after the raster wait: the wait ends its whole lines earlier, so the entry comes in its line.
935
957
  ...vicLines(state, Math.floor((cia?.ops.reduce((sum, op) => sum + op.cycles, 0) ?? 0) / LINE_CYCLES)),
936
958
  ...(cia === undefined ? [] : cia.ops.map((op) => ` ${op.text}`)),
937
- ` lda #${formatC64Byte(port0)}`,
938
- " sta $00",
959
+ // $01 before $00: with the port bits still outputs, $01 shows no ROM that the port of the entry does not show.
939
960
  ` lda #${formatC64Byte(port1)}`,
940
961
  " sta $01",
962
+ ` lda #${formatC64Byte(port0)}`,
963
+ " sta $00",
941
964
  ` ldx #${formatC64Byte((state.sp - 1) & 0xff)}`,
942
965
  " txs",
943
966
  ` lda #${formatC64Byte(state.flags)}`,
@@ -1,4 +1,4 @@
1
- // ACME source from an image, current knowledge and Ghidra's instruction
1
+ // ACME source from an image, current knowledge and the decompiler's instruction
2
2
  // boundaries. The same input gives the same text. Names come from
3
3
  // knowledge; a target that knowledge does not name gets l_xxxx. A read or
4
4
  // write in the I/O area names the register, also where the image holds RAM. Data is
@@ -30,7 +30,7 @@ export interface SourceInput {
30
30
  /** The image byte at an address inside a segment. */
31
31
  byteAt: (address: number) => number;
32
32
  entry?: number;
33
- /** Where Ghidra decoded an instruction, with its length. */
33
+ /** Where the decompiler decoded an instruction, with its length. */
34
34
  instructions: ReadonlyMap<number, number>;
35
35
  /** Without an origin, a symbol counts as a user or LLM name. */
36
36
  symbols: ReadonlyArray<{ address: number; name: string; origin?: Origin }>;
@@ -204,7 +204,7 @@ interface DataItem {
204
204
  kind: "data";
205
205
  start: number;
206
206
  end: number;
207
- /** The region type, or unclassified. In a code region, bytes that Ghidra did not decode. */
207
+ /** The region type, or unclassified. In a code region, bytes that the decompiler did not decode. */
208
208
  type: RegionType | "unclassified" | "undecoded";
209
209
  region?: Region;
210
210
  }
@@ -280,7 +280,7 @@ function operandValue(address: number, opcode: number, byteAt: (address: number)
280
280
 
281
281
  /**
282
282
  * Each entry point inside a data region of the knowledge, with that region.
283
- * A data region wins over an entry: Ghidra does not decode there,
283
+ * A data region wins over an entry: the decompiler does not decode there,
284
284
  * and the source has data there. A code region in the knowledge changes that.
285
285
  */
286
286
  export function entriesInData<R extends { start: number; end: number; type: RegionType }>(entries: readonly number[], regions: readonly R[]): Array<{ entry: number; region: R }> {
@@ -528,7 +528,11 @@ export function layout(input: SourceInput): Layout {
528
528
  expressions.push({ address: operand.address, text: expression, kind: mode === "imm" ? "address" : useKind(item!.opcode) });
529
529
  }
530
530
  // The names of expressions and macro args come first: a platform name there names the register for the plain operands too.
531
- for (const { text: expression, kind } of expressions) for (const name of identifiers(expression)) useName(name, kind);
531
+ // An expression inside a written use names nothing: the macro line names only its args.
532
+ const useExpression = ({ text, kind }: { text: string; kind: UseKind }) => {
533
+ for (const name of identifiers(text)) useName(name, kind);
534
+ };
535
+ for (const expression of expressions) if (!inUse.has(expression.address)) useExpression(expression);
532
536
  for (const candidate of candidates) for (const arg of candidate.use.args) for (const name of identifiers(arg)) useName(name, "macro argument");
533
537
  // An instruction with an expression names what the expression names, not its plain target.
534
538
  const written = new Set(expressions.map((expression) => expression.address));
@@ -557,7 +561,9 @@ export function layout(input: SourceInput): Layout {
557
561
  macrosAsInstructions.push({ start: candidate.use.start, end: candidate.use.end, macro: candidate.use.macro, reason: `The source has a label at ${formatC64Address(inside)}, inside the use.` });
558
562
  for (const item of candidate.items) {
559
563
  inUse.delete(item.address);
560
- if (takesAddress(OPCODES[item.opcode]!.mode) && !written.has(item.address)) useOperand(item);
564
+ const expression = expressions.find((each) => each.address === item.address);
565
+ if (expression !== undefined) useExpression(expression);
566
+ else if (takesAddress(OPCODES[item.opcode]!.mode)) useOperand(item);
561
567
  }
562
568
  }
563
569
  }
@@ -1096,6 +1102,17 @@ function macrosText(layout: Layout): { text: string; lines: Map<string, { first:
1096
1102
  return { text: `${out.join("\n")}\n`, lines };
1097
1103
  }
1098
1104
 
1105
+ /** The bytes of patch code from `start` so far: after a byte at $ffff, ACME sets * to $0000. */
1106
+ const patchLength = (start: string) => `((* - ${start}) & $ffff)`;
1107
+ const LENGTH = patchLength(".patch_start");
1108
+
1109
+ /** The source of one patch of a captured stage on its own: the names of the stage, the code, and NOP to the end of its range. */
1110
+ export function stagePatchText(names: ReadonlyArray<{ name: string; address: number }>, patch: { start: number; end: number; code: string }): string {
1111
+ const start = formatC64Address(patch.start);
1112
+ const lines = ["!cpu 6510", ...names.map((symbol) => `${symbol.name} = ${formatC64Address(symbol.address)}`), `* = ${start}`, ...patch.code.split(/\r?\n/)];
1113
+ return `${[...lines, `!fill ${patch.end - patch.start + 1} - ${patchLength(start)}, $ea`].join("\n")}\n`;
1114
+ }
1115
+
1099
1116
  /** The condition that puts in the code of a switch: the switch has the value that the program does not have. */
1100
1117
  const patchCondition = (alternative: PatchAlternative) => (alternative.base === 0 ? alternative.switch : `${alternative.switch} = 0`);
1101
1118
 
@@ -1122,7 +1139,7 @@ function patchOpening(patch: PatchBlock): string[] {
1122
1139
  `${INDENT}; ${alternative.switch} ${state}: ${bytes} byte${bytes === 1 ? "" : "s"} at ${range}, NOP after the code`,
1123
1140
  ...comment,
1124
1141
  ...(alternative.code === "" ? [] : alternative.code.split(/\r?\n/)),
1125
- `${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 }`,
1142
+ `${INDENT}!if ${LENGTH} > ${bytes} { !error "The patch ${alternative.switch} at ${formatC64Address(patch.start)} has ", ${LENGTH}, " bytes; the range has ${bytes}." } else { !fill ${bytes} - ${LENGTH}, $ea }`,
1126
1143
  );
1127
1144
  });
1128
1145
  out.push("} else {");