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

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 (107) hide show
  1. package/package.json +2 -2
  2. package/skills/c64-assembler/SKILL.md +28 -14
  3. package/skills/c64-assembler/scripts/assembler.ts +28 -15
  4. package/skills/c64-development/SKILL.md +4 -4
  5. package/skills/c64-docs/SKILL.md +9 -7
  6. package/skills/c64-docs/scripts/docs.ts +24 -11
  7. package/skills/c64-docs/scripts/lib/reference.ts +119 -33
  8. package/skills/c64-docs/scripts/lib/source-map.ts +23 -4
  9. package/skills/c64-knowledge/SKILL.md +67 -42
  10. package/skills/c64-knowledge/scripts/knowledge.ts +90 -67
  11. package/skills/c64-knowledge/scripts/lib/listing.ts +18 -3
  12. package/skills/c64-packer/SKILL.md +1 -1
  13. package/skills/c64-provenance/SKILL.md +11 -10
  14. package/skills/c64-provenance/scripts/lib/library.ts +16 -16
  15. package/skills/c64-provenance/scripts/provenance.ts +33 -23
  16. package/skills/c64-reverse-engineering/SKILL.md +17 -11
  17. package/skills/c64-source/SKILL.md +71 -47
  18. package/skills/c64-source/scripts/lib/export.ts +89 -34
  19. package/skills/c64-source/scripts/lib/loader.ts +79 -36
  20. package/skills/c64-source/scripts/lib/source.ts +38 -32
  21. package/skills/c64-source/scripts/lib/stage.ts +11 -5
  22. package/skills/c64-source/scripts/lib/start-screen.asm +4 -2
  23. package/skills/c64-source/scripts/source.ts +278 -145
  24. package/skills/c64-static-analysis/SKILL.md +29 -25
  25. package/skills/c64-static-analysis/scripts/lib/coverage.ts +2 -25
  26. package/skills/c64-static-analysis/scripts/lib/findings.ts +11 -11
  27. package/skills/c64-static-analysis/scripts/lib/instructions.ts +26 -24
  28. package/skills/c64-static-analysis/scripts/lib/macros.ts +3 -1
  29. package/skills/c64-static-analysis/scripts/static-analysis.ts +69 -67
  30. package/skills/c64-testing/SKILL.md +15 -5
  31. package/skills/c64-testing/references/recording-format.md +26 -5
  32. package/skills/c64-testing/references/scenario-format.md +11 -8
  33. package/skills/c64-testing/scripts/lib/diff-files.ts +4 -18
  34. package/skills/c64-testing/scripts/lib/play.ts +39 -41
  35. package/skills/c64-testing/scripts/lib/recording.ts +220 -46
  36. package/skills/c64-testing/scripts/lib/replay.ts +32 -6
  37. package/skills/c64-testing/scripts/lib/runs.ts +8 -3
  38. package/skills/c64-testing/scripts/lib/scenario.ts +18 -11
  39. package/skills/c64-testing/scripts/testing.ts +23 -2
  40. package/skills/c64-unpacker/SKILL.md +10 -5
  41. package/skills/c64-unpacker/scripts/lib/loads.ts +34 -13
  42. package/skills/c64-unpacker/scripts/lib/machine.ts +7 -3
  43. package/skills/c64-unpacker/scripts/lib/stages.ts +18 -3
  44. package/skills/c64-unpacker/scripts/unpacker.ts +43 -9
  45. package/skills/emulator/SKILL.md +7 -12
  46. package/src/build-name.ts +55 -0
  47. package/src/c64-keys.ts +98 -0
  48. package/src/c64.ts +22 -2
  49. package/src/cli/main.ts +3 -29
  50. package/src/host/main.ts +3 -3
  51. package/src/host/server.ts +3 -1
  52. package/src/host/tools/index.ts +2 -7
  53. package/src/host/vice/process.ts +34 -17
  54. package/src/host/vice/session.ts +138 -31
  55. package/src/host-client/steps.ts +21 -18
  56. package/src/host-client/tools.ts +2 -7
  57. package/src/host-client/vice-session.ts +7 -1
  58. package/src/knowledge/evidence.ts +66 -0
  59. package/src/knowledge/history.ts +5 -5
  60. package/src/knowledge/import.ts +12 -5
  61. package/src/knowledge/program.ts +123 -32
  62. package/src/knowledge/read.ts +36 -13
  63. package/src/knowledge/schema.ts +43 -17
  64. package/src/knowledge/start-screen.ts +70 -0
  65. package/src/knowledge/text.ts +33 -5
  66. package/src/knowledge/write.ts +75 -36
  67. package/src/mcp/inputs.ts +12 -0
  68. package/src/mcp/server.ts +1 -1
  69. package/src/mcp/tools/debug.ts +23 -21
  70. package/src/mcp/tools/input.ts +38 -5
  71. package/src/mcp/tools/machine.ts +3 -42
  72. package/src/mcp/tools/media.ts +1 -1
  73. package/src/mcp/tools/memory.ts +12 -9
  74. package/src/native/acme.ts +1 -1
  75. package/src/native/c64run.ts +7 -4
  76. package/src/native/decompiler/analyze.ts +98 -0
  77. package/src/native/decompiler/c64rt-wasm.ts +4 -0
  78. package/src/native/decompiler/language/c64rt_6510.sla +0 -0
  79. package/src/native/{ghidra → decompiler}/language/c64rt_6510.slaspec +1 -1
  80. package/src/native/decompiler/pcode.ts +222 -0
  81. package/src/native/decompiler/walk.ts +205 -0
  82. package/src/native/decompiler/wasm.ts +98 -0
  83. package/src/native/discover.ts +3 -3
  84. package/src/native/dxa.ts +12 -1
  85. package/src/native/processes.ts +4 -4
  86. package/src/native/types.ts +27 -27
  87. package/src/opcodes.ts +1 -1
  88. package/src/platform.ts +30 -1
  89. package/src/project.ts +17 -4
  90. package/src/protocol/tools.ts +1 -45
  91. package/src/protocol/vice.ts +47 -0
  92. package/src/reference-pages.ts +64 -0
  93. package/src/script.ts +4 -4
  94. package/src/vsf.ts +98 -0
  95. package/tools/c64run.c +158 -15
  96. package/tools/install-container.sh +1 -2
  97. package/src/cli/status.ts +0 -127
  98. package/src/host/tools/status.ts +0 -47
  99. package/src/native/ghidra/analyze.ts +0 -87
  100. package/src/native/ghidra/index.ts +0 -170
  101. package/src/native/ghidra/scripts/C64Export.java +0 -274
  102. package/src/native/ghidra/scripts/C64Prepare.java +0 -66
  103. package/src/native/status.ts +0 -135
  104. package/tools/install-ghidra.sh +0 -40
  105. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.cspec +0 -0
  106. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.ldefs +0 -0
  107. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.pspec +0 -0
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: c64-static-analysis
3
- description: Finds the structure of a C64 program with DXA or Ghidra, without running it. It records the code and data regions, the analyzer names and the references in the project knowledge. Use it to get a fast first pass of code and data, and a disassembly listing. Use it to get the routines, the references, an instruction list and decompiled code. Use it when the project knowledge has coverage, to find code that only a vector, a table or an interrupt reaches. Use it to find 6502 idioms, pointer candidates, raster pitfalls and macro candidates. It does not run the program. It does not give names to routines.
3
+ description: Finds the structure of a C64 program with DXA or the decompiler, without running it. It records the code and data regions, the analyzer names and the references in the project knowledge. Use it to get a fast first pass of code and data, and a disassembly listing. Use it to get the routines, the references, an instruction list and decompiled code. Use it when the project knowledge has coverage, to find code that only a vector, a table or an interrupt reaches. Use it to find 6502 idioms, pointer candidates, raster pitfalls and macro candidates. It does not run the program. It does not give names to routines.
4
4
  ---
5
5
 
6
6
  # Static analysis
@@ -29,7 +29,8 @@ To get the command list, run the script with no arguments.
29
29
  | Get C-like code of a routine | `analyze --entry '$080d' --decompile '$0818'` |
30
30
  | Get each instruction as JSON | `analyze --entry '$080d' --out-instructions .c64-re-tools/local/instructions.json` |
31
31
  | Analyze drive code or a cartridge bank | `analyze --space drive8` |
32
- | Get the macro candidates as a batch of changes | `analyze --out-macro-batch .c64-re-tools/local/macros.json` |
32
+ | Write the macro candidates to the project knowledge | `analyze --apply-macros` |
33
+ | Write only the correct macro candidates | `analyze --apply-macros --skip '$1e64' --skip '$2010'` |
33
34
  | Get more items in each list | `analyze --max-listed 500` |
34
35
 
35
36
  ---
@@ -42,16 +43,16 @@ To get the command list, run the script with no arguments.
42
43
  - An entry point is an address where code starts. Give it with `--entry`. Get it from these sources:
43
44
  - The SYS address of a BASIC start. Get it from a listing of the BASIC program.
44
45
  - A vector or an interrupt target that you found in the emulator.
45
- - An address in `functions` of an earlier Ghidra result.
46
- - Ghidra needs at least one entry point. DXA finds the SYS address of a BASIC start without help.
46
+ - An address in `functions` of an earlier decompiler result.
47
+ - The decompiler needs at least one entry point. DXA finds the SYS address of a BASIC start without help.
47
48
  - Each routine, each `code` region and each entry of a `jumps` table in the project knowledge is also an entry point. Each name in the project knowledge is a label in the listing and in the decompiled code.
48
49
  - The two start vectors of a `CBM80` header at `$8000` are entry points without help.
49
50
  - Each region that is not code in the project knowledge stays data. Each `data` or `variable` symbol also keeps its region as data. If the region holds an entry point or executed code, only the byte of the symbol stays data.
50
51
  - If an analyzer decodes data as code, classify the region as data in the project knowledge. Then run `analyze` again.
51
52
  - The facts of an analyzer are not entry points or data for the next analysis. Thus a new analysis can correct them.
52
53
  - With coverage, the analysis keeps as data the RAM under ROM that the runs did not read or execute. A call into the KERNAL thus does not decode the RAM under it. If the program has code there, give its address with `--entry`.
53
- - Ghidra does not follow BRK. If the program removes the KERNAL and uses the BRK vector, give the target of the vector with `--entry`.
54
- - `--decompile` takes the address of a routine. Get it from `functions` of an earlier Ghidra result, or from the routines in the project knowledge.
54
+ - The decompiler does not follow BRK. If the program removes the KERNAL and uses the BRK vector, give the target of the vector with `--entry`.
55
+ - `--decompile` takes the address of a routine. Get it from `functions` of an earlier decompiler result, or from the routines in the project knowledge.
55
56
 
56
57
  ### Paths and the project folder
57
58
 
@@ -79,14 +80,15 @@ Each flag applies only to the commands in the table. On another command, the scr
79
80
 
80
81
  | Flag | Command | Effect |
81
82
  |---|---|---|
82
- | `--analyzer <dxa\|ghidra>` | `analyze` | The analyzer. `dxa` gives a fast first pass. `ghidra` gives a deeper pass. The default is `ghidra`. |
83
+ | `--analyzer <dxa\|decompiler>` | `analyze` | The analyzer. `dxa` gives a fast first pass. `decompiler` gives a deeper pass. The default is `decompiler`. |
83
84
  | `--entry <address>` | `analyze` | An entry point of the program. Give it again for more entry points. There is no default. |
84
- | `--decompile <address>` | `analyze` | Ghidra only. Decompile the routine at this address. Give it again for more routines, at most 32. There is no default. |
85
+ | `--decompile <address>` | `analyze` | Only with `--analyzer decompiler`. Decompile the routine at this address. Give it again for more routines, at most 32. There is no default. |
85
86
  | `--space <space>` | `analyze` | The knowledge space of the program: `drive8` for 1541 drive code, or `bank0` to `bank255` for a cartridge bank. The analysis reads the entry points from that space and writes the findings into it. The default is `c64`. |
86
87
  | `--max-listed <n>` | `analyze` | List at most `n` items in each list. `0` lists no items. The counts stay complete. The default is 50. |
87
88
  | `--out-listing <file>` | `analyze` | DXA only. Write the disassembly listing to this project file. There is no default. |
88
- | `--out-instructions <file>` | `analyze` | Ghidra only. Write each instruction to this project file as JSON. There is no default. |
89
- | `--out-macro-batch <file>` | `analyze` | Write the macro candidates to this project file as a batch of changes to the project knowledge. There is no default. |
89
+ | `--out-instructions <file>` | `analyze` | Only with `--analyzer decompiler`. Write each instruction to this project file as JSON. There is no default. |
90
+ | `--apply-macros` | `analyze` | Write the macro candidates and their macros to the project knowledge as one revision of the LLM. Off by default. |
91
+ | `--skip <address>` | `analyze` | With `--apply-macros`: the start of a macro candidate that is not correct. The run does not write it. Give one `--skip` for each such candidate. |
90
92
 
91
93
  ---
92
94
 
@@ -94,13 +96,13 @@ Each flag applies only to the commands in the table. On another command, the scr
94
96
 
95
97
  ### `analyze`
96
98
 
97
- Runs DXA or Ghidra over the program in the project knowledge. The script records the findings in the project knowledge as one revision. Then it records the 6502 idioms as a second revision.
99
+ Runs DXA or the decompiler over the program in the project knowledge. The script records the findings in the project knowledge as one revision. Then it records the 6502 idioms as a second revision. When the findings do not change the knowledge, the script records no revision for them.
98
100
 
99
- The script records only structure: code and data regions, analyzer names, and the references from Ghidra. It does not record the listing or the decompiled code. Do not record the listing, the decompiled code or the function list as comments in the project knowledge.
101
+ The script records only structure: code and data regions, analyzer names, and the references from the decompiler. It does not record the listing or the decompiled code. Do not record the listing, the decompiled code or the function list as comments in the project knowledge.
100
102
 
101
103
  `body` holds these fields for both analyzers:
102
104
 
103
- - `analyzer`: `dxa` or `ghidra`. `space` is in `body` only for a space that is not `c64`.
105
+ - `analyzer`: `dxa` or `decompiler`. `analyzerVersion` gives the version of the analyzer when the analyzer tells it. `space` is in `body` only for a space that is not `c64`.
104
106
  - `revision`: the revision of the findings, or `null` when the knowledge did not change.
105
107
  - `coverage`: the ranges that the analyzer examined.
106
108
  - `changes`: for analyzer names (`names`), `regions` and `references`, the counts `added`, `changed`, `retired`, `unchanged` and `suppressed`. `suppressed` counts the findings that the script did not record, because the user or the LLM removed a fact at that place. `references.inData` counts the references that the script did not record, because they start in a data region of the user, the LLM or a heuristic. The analyzer decoded these data bytes as code. `symbols.retired` counts the old symbols of the analyzer that became analyzer names.
@@ -115,19 +117,21 @@ DXA also gives:
115
117
  - `labels`: the names that DXA found, as a list.
116
118
  - `listing`: the listing file, with `--out-listing`.
117
119
 
118
- Ghidra also gives:
120
+ The decompiler also gives:
119
121
 
120
- - `functions`: the routines that Ghidra found, as a list, each with `entry` and `name`.
122
+ - `functions`: the routines that the decompiler found, as a list, each with `entry` and `name`.
121
123
  - `decompilations`: the C-like code of each `--decompile` routine, with `entry` and `text`. `truncated` tells that the text is cut.
122
- - `notDecompiled`: the routines that Ghidra did not decompile, each with a `reason`.
124
+ - `notDecompiled`: the routines that the decompiler did not decompile, each with a `reason`.
123
125
  - `instructions`: the file and the `count`, with `--out-instructions`. Each instruction has `address`, `bytes`, `mnemonic`, `mode` and `operand` in 6502 syntax. A branch, a jump or a call also has `target`. With coverage, `executed` tells if the instruction ran.
124
- - `coverageGaps`: only with coverage. The executed instruction starts that are not in the instructions of Ghidra.
126
+ - `coverageGaps`: only with coverage. The executed instruction starts that are not in the instructions of the decompiler.
125
127
 
126
128
  The `hint` gives each of these cases:
127
129
 
128
130
  - `conflicts` is not empty. Find the correct answer in the emulator. Then correct the project knowledge.
129
131
  - `coverageConflicts` is not empty. Classify each range as code in the project knowledge, or as `dual-use` when its bytes are also data. For many ranges, write all classifications in one batch of changes.
130
- - The batch of `--out-macro-batch` has changes. Apply the changes in the batch file to the project knowledge. Then generate the source again.
132
+ - `idioms.candidates.macros` has candidates, and the run had no `--apply-macros`. Examine the candidates. To write the correct candidates to the project knowledge, run the analysis again with `--apply-macros`. Give `--skip` with the start of each candidate that is not correct. Then generate the source again.
133
+ - The last analysis of the same program bytes used another analyzer version. Thus a change in `revision` can come from the new analyzer, and not from the program or the project knowledge.
134
+ - `changes.references.retired` is more than 0. A data range that only a retired reference used can be a leftover now. Generate the source again, and examine the leftovers that changed.
131
135
  - A list is cut. Give a larger `--max-listed`. The project knowledge has all `labels` and `functions` as analyzer names.
132
136
 
133
137
  There is no `nextAction`.
@@ -140,19 +144,19 @@ The script does not record the candidates. Examine each candidate and decide.
140
144
  - `selfModified`: opcodes that the program wrote and then executed. The write and the execution must be in one coverage file. A coverage file does not record the order. Thus a candidate can also be code that ran first, and that the program then wrote over. To prevent this, save one coverage file for each part of the program, for example the intro, the game, or a loader that copies code. Clear the memory map between the parts.
141
145
  - `pointers`: code that makes an address from immediates. A `vector` or a `zero-page pointer` candidate stores a low byte (`low`) and a high byte (`high`) to a vector or to a zero-page pair. A `sprite pointer` candidate stores an immediate (`at`) to a sprite pointer of the screen at `$0400` in VIC bank 0. For each correct candidate, record a low and a high operand expression to its `target` in the project knowledge. Then a rebuild can move the target.
142
146
  - `pitfalls`: code that a C64 runs in a different way than it reads. For `raster-bit-8`, the instruction at `at` reads `$D011`, and the instruction at `store` writes the value back. The write can move the raster interrupt to line 256 or later. On PAL, past line 311, the interrupt never comes. Where the code must not keep bit 7, add a comment and test the program.
143
- - `macros`: runs of instructions that one macro line can replace, for example `+inc16 ptr`. Each candidate has `macro`, `start`, `end`, `args` and `text`. The macros are `inc16`, `dec16`, `add16_8`, `add16`, `sub16`, `set16`, `mov16` and `wait_line`. An arg is a name of the user or the LLM, or a platform name of a ROM that the program uses. `known` counts the uses that the project knowledge has. `leftOut` counts the candidates with a label inside, or with a patch or a use over them. With `--out-macro-batch`, `batch` gives the file and the count of changes (`writes`). The batch holds the macros that the project knowledge does not have, and the uses. `otherMacros` names each macro that the project knowledge has with another body. The batch does not have the uses of that macro.
147
+ - `macros`: runs of instructions that one macro line can replace, for example `+inc16 ptr`. Each candidate has `macro`, `start`, `end`, `args` and `text`. The macros are `inc16`, `dec16`, `add16_8`, `add16`, `sub16`, `set16`, `mov16` and `wait_line`. An arg is a name of the user or the LLM, or a platform name of a ROM that the program uses. A value of `set16` below $0100 is a number. `known` counts the uses that the project knowledge has. `leftOut` counts the candidates with a label inside, or with a patch over them, or with another use of the project knowledge over them. With `--apply-macros`, `revision` gives the revision of the writes, and `writes` counts them. The writes hold the macros that the project knowledge does not have, with their bodies, and the uses. Do not write these macros yourself. `otherMacros` names each macro that the project knowledge has with another body. The writes do not have the uses of that macro. `skipped` counts the candidates that `--skip` left out. `notCandidates` lists each `--skip` address that starts no candidate.
144
148
 
145
149
  #### Which facts the analysis replaces
146
150
 
147
151
  - The analysis never replaces a name or a region of the user or the LLM. Each disagreement shows in `conflicts`.
148
- - DXA and Ghidra do not replace the facts of each other, with one exception. With coverage, a code finding replaces DXA or Ghidra data where a run executed an instruction start. Thus put all coverage maps into the project knowledge first. Then run DXA, then Ghidra.
152
+ - DXA and the decompiler do not replace the facts of each other, with one exception. With coverage, a code finding replaces DXA or decompiler data where a run executed an instruction start. Thus put all coverage maps into the project knowledge first. Then run DXA, then the decompiler.
149
153
  - An analyzer can find data where a run executed an instruction start, or at a `label` or `routine` symbol of the user or the LLM. Then the script does not record that data region, and the earlier region stays. The conflict has `executed` or `knowledge`.
150
- - An idiom region (origin `heuristic`) replaces the part of a DXA or Ghidra region where it lies. DXA and Ghidra never replace an idiom region. If they find code there, the result shows a conflict.
154
+ - An idiom region (origin `heuristic`) replaces the part of a DXA or decompiler region where it lies. DXA and the decompiler never replace an idiom region. If they find code there, the result shows a conflict.
151
155
  - An idiom table can be too long or too short. Correct its region in the project knowledge. Your region replaces it.
152
156
  - A new analysis replaces the earlier facts of the same analyzer in its `coverage`, also its analyzer names. The history keeps the earlier facts.
153
157
  - A fact that the user or the LLM removed does not come back. To remove a wrong fact, remove it in the project knowledge.
154
158
  - An analyzer name is a second name of the address, not a symbol. Each analyzer keeps its own name at an address. The generated source does not use an analyzer name by default. To use a name in the source, give the address a name in the project knowledge.
155
- - A Ghidra function that only branches and jumps reach is a `label`, not a `routine`.
159
+ - A decompiler function that only branches and jumps reach is a `label`, not a `routine`.
156
160
 
157
161
  #### Traps
158
162
 
@@ -165,11 +169,11 @@ The script does not record the candidates. Examine each candidate and decide.
165
169
  - `coverageGaps` has starts. Normally its count is 0. Each start is not in `--out-instructions` and not in the generated source. Examine the code at the start. Overlapped instructions and self-modified code can cause a gap. A start in a `dual-use` region is a known overlap, for example a BIT skip, and is not in the list.
166
170
  - `coverageSeeds.used` is smaller than `coverageSeeds.entryPoints`. The analysis did not use all entry points of the coverage. Give the important entry points with `--entry`, or record them as routines in the project knowledge. These come first.
167
171
  - `romOnlyUsed` is smaller than `romOnlyRanges`. The analysis did not keep all RAM under ROM as data. Classify the RAM under ROM that is not code as data in the project knowledge.
168
- - `notDecompiled` has a reason that the decompiler did not start. Give the remedy in the reason to the user.
172
+ - `notDecompiled` has a routine. The `reason` tells why the decompiler did not decompile it. Read the instructions of that routine in the file of `--out-instructions`.
169
173
 
170
174
  #### Failures
171
175
 
172
- - `invalid-input` about an entry point: Ghidra has no entry point in the program. Give one with `--entry`.
176
+ - `invalid-input` about an entry point: the decompiler has no entry point in the program. Give one with `--entry`.
173
177
  - `stale-revision`: the project knowledge changed during the analysis. The script recorded nothing. Run `analyze` again.
174
178
  - `operation-failed` about an incomplete result or listing: the analyzer did not give a complete result. The script recorded nothing. Tell the user.
175
179
  - The script did not write the listing: the error tells if the project knowledge has the findings. Correct `--out-listing` and run `analyze` again.
@@ -182,7 +186,7 @@ The script does not record the candidates. Examine each candidate and decide.
182
186
  2. Put each coverage map of the program into the project knowledge.
183
187
  3. Run `analyze --analyzer dxa` for a first pass. Read the listing for a quick view of the code.
184
188
  4. Find the important routines. Give them names in the project knowledge.
185
- 5. Run `analyze` with Ghidra. Give the entry points with `--entry`. Give `--decompile` for the routines that you must understand.
189
+ 5. Run `analyze` with the decompiler. Give the entry points with `--entry`. Give `--decompile` for the routines that you must understand.
186
190
  6. Do the action for each `hint`. Examine the candidates.
187
191
  7. Give each important routine a name in the project knowledge. Then run `analyze` again. The analyzers use the new names.
188
192
 
@@ -4,15 +4,12 @@
4
4
 
5
5
  import type { DatabaseSync } from "node:sqlite";
6
6
 
7
- import { COVERAGE, coverageEntries, coverageSeedKinds, executedStarts } from "#src/c64.ts";
7
+ import { COVERAGE, coverageEntries, coverageSeedKinds, executedStarts, romOnlyRanges } from "#src/c64.ts";
8
8
 
9
- export { coverageEntries, coverageSeedKinds, executedStarts };
10
- import { FULL_COVERAGE } from "#src/host-client/coverage.ts";
9
+ export { coverageEntries, coverageSeedKinds, executedStarts, romOnlyRanges };
11
10
  import { listRegions, type RegionRow } from "#src/knowledge/read.ts";
12
11
  import { CODE_REGION_TYPES, DEFAULT_SPACE, isAnalyzer, isSemantic, type Space } from "#src/knowledge/schema.ts";
13
12
 
14
- const FULL_MAP = FULL_COVERAGE;
15
-
16
13
  /** The byte at an address of the analyzed image, or undefined outside it. */
17
14
  export type ImageByte = (address: number) => number | undefined;
18
15
 
@@ -22,26 +19,6 @@ export function imageReader(bytes: Uint8Array, kind: "prg" | "flat64k"): ImageBy
22
19
  return (address) => (address >= load && address - load + 2 < bytes.length ? bytes[address - load + 2] : undefined);
23
20
  }
24
21
 
25
- const ROM_ACCESS = COVERAGE.romRead | COVERAGE.romExecute;
26
- const RAM_USE = COVERAGE.ramRead | COVERAGE.ramExecute;
27
-
28
- /**
29
- * The image bytes under ROM that the runs never used: the CPU read or ran the
30
- * ROM there, and never read or ran the RAM. A JSR $FFE4 or an IRQ
31
- * vector at $FFFE then leads into ROM, not into the leftover RAM bytes of a
32
- * flat image, so the ranges are data for the analysis run.
33
- */
34
- export function romOnlyRanges(map: Uint8Array, image: ImageByte): Array<{ start: number; end: number }> {
35
- const ranges: Array<{ start: number; end: number }> = [];
36
- for (let address = 0; address < FULL_MAP; address++) {
37
- if ((map[address]! & ROM_ACCESS) === 0 || (map[address]! & RAM_USE) !== 0 || image(address) === undefined) continue;
38
- const last = ranges.at(-1);
39
- if (last !== undefined && last.end === address - 1) last.end = address;
40
- else ranges.push({ start: address, end: address });
41
- }
42
- return ranges;
43
- }
44
-
45
22
  /** Entry points from semantic knowledge beyond routines: the start of each code region, and each entry of a JMP table with its target. */
46
23
  export function codeEntries(db: DatabaseSync | undefined, image: ImageByte, space: Space = DEFAULT_SPACE): number[] {
47
24
  const entries: number[] = [];
@@ -1,4 +1,4 @@
1
- // Knowledge seeds for an analyzer, and the mapping of a Ghidra result to the
1
+ // Knowledge seeds for an analyzer, and the mapping of a decompiler result to the
2
2
  // common normalized findings.
3
3
 
4
4
  import type { DatabaseSync } from "node:sqlite";
@@ -6,9 +6,9 @@ import type { DatabaseSync } from "node:sqlite";
6
6
  import type { NormalizedFindings } from "#src/knowledge/import.ts";
7
7
  import { listRegions, listSymbols } from "#src/knowledge/read.ts";
8
8
  import { CODE_REGION_TYPES, DEFAULT_SPACE, isSemantic, type Space } from "#src/knowledge/schema.ts";
9
- import type { DxaResult, GhidraParams, GhidraResult } from "#src/native/types.ts";
9
+ import type { DxaResult, DecompilerParams, DecompilerResult } from "#src/native/types.ts";
10
10
 
11
- export type Seeds = Pick<GhidraParams, "entryPoints" | "dataRanges" | "labels">;
11
+ export type Seeds = Pick<DecompilerParams, "entryPoints" | "dataRanges" | "labels">;
12
12
 
13
13
  const semantic = (row: { origin: string }) => isSemantic(row.origin);
14
14
 
@@ -49,12 +49,12 @@ export function seedsFromKnowledge(db: DatabaseSync | undefined, extraEntryPoint
49
49
 
50
50
  /**
51
51
  * The 6510 opcodes with a low nibble of 1 or 3 use (zp,x) or (zp),y, also the
52
- * undocumented ones. Ghidra gives such an instruction a reference to the target
52
+ * undocumented ones. The decompiler gives such an instruction a reference to the target
53
53
  * that it computes from the pointer value at the entry state: a guess, because
54
54
  * the program sets the pointer at run time. Only the reference to the pointer
55
55
  * itself (zp or zp+1) is a fact.
56
56
  */
57
- function guessedIndirectTarget(instructions: GhidraResult["instructions"]): (reference: { from: number; to: number }) => boolean {
57
+ function guessedIndirectTarget(instructions: DecompilerResult["instructions"]): (reference: { from: number; to: number }) => boolean {
58
58
  const pointers = new Map<number, number>();
59
59
  for (const instruction of instructions) {
60
60
  const opcode = Number.parseInt(instruction.bytes.slice(0, 2), 16);
@@ -67,28 +67,28 @@ function guessedIndirectTarget(instructions: GhidraResult["instructions"]): (ref
67
67
  }
68
68
 
69
69
  /**
70
- * Ghidra's result as normalized findings. A reference from a (zp,x) or (zp),y
70
+ * The decompiler's result as normalized findings. A reference from a (zp,x) or (zp),y
71
71
  * instruction to a computed target is not a finding (see guessedIndirectTarget).
72
72
  * A function named by an echoed seed
73
73
  * stays in the snapshot: its address holds the seed's semantic symbol, which
74
74
  * the importer never replaces, so the name keeps its owner,
75
75
  * and a code/data disagreement with that symbol is still reported.
76
76
  */
77
- export function ghidraFindings(result: GhidraResult): NormalizedFindings {
78
- // Ghidra can give one generated name to two functions, for example
77
+ export function decompilerFindings(result: DecompilerResult): NormalizedFindings {
78
+ // The decompiler can give one generated name to two functions, for example
79
79
  // thunk_FUN_e434 to two thunks of one routine. A name
80
80
  // must have one address, so a repeated name that is not a seed gets its address.
81
81
  const uses = new Map<string, number>();
82
82
  for (const fn of result.functions) uses.set(fn.name, (uses.get(fn.name) ?? 0) + 1);
83
- const nameOf = (fn: GhidraResult["functions"][number]) =>
83
+ const nameOf = (fn: DecompilerResult["functions"][number]) =>
84
84
  fn.nameSource !== "seed" && uses.get(fn.name)! > 1 ? `${fn.name}_${fn.entry.toString(16).padStart(4, "0")}` : fn.name;
85
85
  // A function that branches and jumps reach, and no call, is a place in a routine: a label.
86
86
  const called = new Set(result.references.filter((reference) => reference.type === "call").map((reference) => reference.to));
87
87
  const jumped = new Set(result.references.filter((reference) => reference.type === "jump").map((reference) => reference.to));
88
88
  const guessed = guessedIndirectTarget(result.instructions);
89
- const kindOf = (fn: GhidraResult["functions"][number]) => (jumped.has(fn.entry) && !called.has(fn.entry) ? ("label" as const) : ("routine" as const));
89
+ const kindOf = (fn: DecompilerResult["functions"][number]) => (jumped.has(fn.entry) && !called.has(fn.entry) ? ("label" as const) : ("routine" as const));
90
90
  return {
91
- analyzer: "ghidra",
91
+ analyzer: "decompiler",
92
92
  coverage: result.coverage,
93
93
  authoritative: { symbols: result.completeness.functions, regions: result.completeness.regions, references: result.completeness.references },
94
94
  symbols: result.functions.map((fn) => ({ address: fn.entry, name: nameOf(fn), kind: kindOf(fn) })),
@@ -1,9 +1,10 @@
1
- // The structured instruction list: Ghidra's decoded instructions with
1
+ // The structured instruction list: the decompiler's decoded instructions with
2
2
  // the addressing mode, the operand in 6502 syntax, the flow target and,
3
3
  // with a coverage file, whether the instruction ran.
4
4
 
5
5
  import { COVERAGE, formatC64Address } from "#src/c64.ts";
6
- import type { GhidraInstruction } from "#src/native/types.ts";
6
+ import { OPCODES, type Mode as OpcodeMode } from "#src/opcodes.ts";
7
+ import type { DecompilerInstruction } from "#src/native/types.ts";
7
8
 
8
9
  export type Mode =
9
10
  | "implied"
@@ -20,26 +21,27 @@ export type Mode =
20
21
  | "(indirect),y"
21
22
  | "relative";
22
23
 
23
- const BRANCHES = new Set([0x10, 0x30, 0x50, 0x70, 0x90, 0xb0, 0xd0, 0xf0]);
24
- const JMP_INDIRECT = 0x6c;
24
+ /** ASL, ROL, LSR and ROR of the accumulator: the implied forms that work on A. */
25
+ const ACCUMULATOR = new Set([0x0a, 0x2a, 0x4a, 0x6a]);
25
26
 
26
- /**
27
- * The addressing mode from Ghidra's operand text and the instruction length.
28
- * Ghidra prints zero page and absolute alike, and JMP (indirect) as an
29
- * address, so the length and the opcode decide those.
30
- */
31
- export function modeOf(opcode: number, length: number, operands: string): Mode {
32
- const text = operands.toUpperCase();
33
- if (text === "") return "implied";
34
- if (text === "A") return "accumulator";
35
- if (text.startsWith("#")) return "immediate";
36
- if (text.startsWith("(") && text.endsWith(",X)")) return "(indirect,x)";
37
- if (text.startsWith("(") && text.endsWith("),Y")) return "(indirect),y";
38
- if (text.endsWith(",X")) return length === 2 ? "zeropage,x" : "absolute,x";
39
- if (text.endsWith(",Y")) return length === 2 ? "zeropage,y" : "absolute,y";
40
- if (BRANCHES.has(opcode)) return "relative";
41
- if (opcode === JMP_INDIRECT) return "(indirect)";
42
- return length === 2 ? "zeropage" : "absolute";
27
+ const MODES: Record<OpcodeMode, Mode> = {
28
+ imp: "implied",
29
+ imm: "immediate",
30
+ zp: "zeropage",
31
+ zpx: "zeropage,x",
32
+ zpy: "zeropage,y",
33
+ abs: "absolute",
34
+ abx: "absolute,x",
35
+ aby: "absolute,y",
36
+ ind: "(indirect)",
37
+ izx: "(indirect,x)",
38
+ izy: "(indirect),y",
39
+ rel: "relative",
40
+ };
41
+
42
+ /** The addressing mode of an opcode. */
43
+ export function modeOf(opcode: number): Mode {
44
+ return ACCUMULATOR.has(opcode) ? "accumulator" : MODES[OPCODES[opcode]!.mode];
43
45
  }
44
46
 
45
47
  /** The operand in 6502 syntax, from the instruction bytes; empty for implied. */
@@ -86,11 +88,11 @@ export interface ListedInstruction {
86
88
  executed?: boolean;
87
89
  }
88
90
 
89
- /** Ghidra's instructions as the list that --out-instructions writes. */
90
- export function instructionList(instructions: GhidraInstruction[], coverage?: Uint8Array): ListedInstruction[] {
91
+ /** The decompiler's instructions as the list that --out-instructions writes. */
92
+ export function instructionList(instructions: DecompilerInstruction[], coverage?: Uint8Array): ListedInstruction[] {
91
93
  return instructions.map((instruction) => {
92
94
  const bytes = Buffer.from(instruction.bytes, "hex");
93
- const mode = modeOf(bytes[0]!, bytes.length, instruction.operands);
95
+ const mode = modeOf(bytes[0]!);
94
96
  const [target] = instruction.flows;
95
97
  return {
96
98
  address: formatC64Address(instruction.address),
@@ -152,7 +152,9 @@ const MATCHERS: Record<string, { count: number; match: (run: Instruction[], name
152
152
  const dst = memory(storeLow, "sta");
153
153
  if (low === undefined || high === undefined || !same(dst, memory(storeHigh, "sta"), 1)) return undefined;
154
154
  const value = low | (high << 8);
155
- return [addressArg(dst!, name), name(value) ?? formatC64Address(value)];
155
+ // A value of $0100 or more can be the address of a routine or a table, for example an IRQ handler: it gets its name.
156
+ // A smaller value is a number: the name of a zero-page address with that value is not what the code means.
157
+ return [addressArg(dst!, name), (value >= 0x100 ? name(value) : undefined) ?? formatC64Address(value)];
156
158
  },
157
159
  },
158
160
  mov16: {