@henols/c64-re-tools 2.7.1 → 2.8.0-rc.2

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 (70) hide show
  1. package/package.json +1 -1
  2. package/skills/c64-assembler/SKILL.md +23 -38
  3. package/skills/c64-assembler/scripts/assembler.ts +137 -17
  4. package/skills/c64-basic/SKILL.md +11 -31
  5. package/skills/c64-basic/scripts/basic.ts +4 -1
  6. package/skills/c64-development/SKILL.md +2 -2
  7. package/skills/c64-disk/SKILL.md +11 -32
  8. package/skills/c64-docs/SKILL.md +27 -45
  9. package/skills/c64-docs/references/page-types.md +20 -18
  10. package/skills/c64-docs/references/style.md +10 -4
  11. package/skills/c64-docs/scripts/docs.ts +13 -2
  12. package/skills/c64-docs/scripts/lib/reference.ts +47 -5
  13. package/skills/c64-knowledge/SKILL.md +138 -267
  14. package/skills/c64-knowledge/references/batches.md +48 -0
  15. package/skills/c64-knowledge/references/coverage.md +29 -0
  16. package/skills/c64-knowledge/references/source-knowledge.md +72 -0
  17. package/skills/c64-knowledge/references/start-screen.md +44 -0
  18. package/skills/c64-knowledge/scripts/knowledge.ts +266 -61
  19. package/skills/c64-knowledge/scripts/lib/check.ts +133 -0
  20. package/skills/c64-knowledge/scripts/lib/listing.ts +71 -8
  21. package/skills/c64-memory-map/SKILL.md +11 -32
  22. package/skills/c64-packer/SKILL.md +11 -31
  23. package/skills/c64-provenance/SKILL.md +43 -64
  24. package/skills/c64-provenance/scripts/lib/leftovers.ts +8 -3
  25. package/skills/c64-provenance/scripts/provenance.ts +65 -56
  26. package/skills/c64-reverse-engineering/SKILL.md +20 -47
  27. package/skills/c64-reverse-engineering/references/comment-check.md +42 -0
  28. package/skills/c64-reverse-engineering/references/versions.md +47 -0
  29. package/skills/c64-source/SKILL.md +48 -237
  30. package/skills/c64-source/references/export.md +50 -0
  31. package/skills/c64-source/references/loader.md +78 -0
  32. package/skills/c64-source/references/source-format.md +46 -0
  33. package/skills/c64-source/scripts/lib/export.ts +28 -13
  34. package/skills/c64-source/scripts/lib/loader.ts +4 -82
  35. package/skills/c64-source/scripts/lib/source.ts +3 -5
  36. package/skills/c64-source/scripts/source.ts +48 -51
  37. package/skills/c64-static-analysis/SKILL.md +52 -52
  38. package/skills/c64-static-analysis/scripts/lib/coverage.ts +55 -2
  39. package/skills/c64-static-analysis/scripts/lib/idioms.ts +43 -17
  40. package/skills/c64-static-analysis/scripts/static-analysis.ts +79 -15
  41. package/skills/c64-testing/SKILL.md +72 -58
  42. package/skills/c64-testing/references/recording-format.md +5 -80
  43. package/skills/c64-testing/references/scenario-format.md +4 -12
  44. package/skills/c64-testing/scripts/lib/play.ts +16 -8
  45. package/skills/c64-testing/scripts/lib/recording.ts +74 -9
  46. package/skills/c64-testing/scripts/lib/replay.ts +4 -0
  47. package/skills/c64-testing/scripts/lib/runs.ts +112 -1
  48. package/skills/c64-testing/scripts/lib/scenario.ts +12 -6
  49. package/skills/c64-testing/scripts/lib/start-screen.ts +27 -0
  50. package/skills/c64-testing/scripts/testing.ts +34 -13
  51. package/skills/c64-unpacker/SKILL.md +10 -30
  52. package/skills/emulator/SKILL.md +7 -36
  53. package/src/build-name.ts +12 -1
  54. package/src/c64.ts +16 -0
  55. package/src/knowledge/history.ts +8 -0
  56. package/src/knowledge/program.ts +84 -4
  57. package/src/knowledge/read.ts +46 -2
  58. package/src/knowledge/recording-files.ts +32 -0
  59. package/src/knowledge/schema.ts +3 -1
  60. package/src/knowledge/separate.ts +165 -11
  61. package/src/knowledge/start-screen.ts +99 -17
  62. package/src/knowledge/text.ts +2 -1
  63. package/src/knowledge/write.ts +15 -8
  64. package/src/loader.ts +167 -0
  65. package/src/native/decompiler/analyze.ts +7 -6
  66. package/src/native/decompiler/walk.ts +32 -2
  67. package/src/native/dxa.ts +4 -4
  68. package/src/native/types.ts +34 -4
  69. package/src/script.ts +102 -25
  70. package/skills/c64-export/SKILL.md +0 -63
@@ -45,12 +45,11 @@ To get the command list, run the script with no arguments.
45
45
  - A vector or an interrupt target that you found in the emulator.
46
46
  - An address in `functions` of an earlier decompiler result.
47
47
  - The decompiler needs at least one entry point. DXA finds the SYS address of a BASIC start without help.
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
+ - Each routine, each `code` region and each entry of a `jumps` table that the user or the LLM recorded is also an entry point. Each name in the project knowledge is a label in the listing and in the decompiled code.
49
49
  - The two start vectors of a `CBM80` header at `$8000` are entry points without help.
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
+ - A region of the user or the LLM that is not code stays data in the analysis. A `data` or `variable` symbol keeps its region as data.
51
51
  - If an analyzer decodes data as code, classify the region as data in the project knowledge. Then run `analyze` again.
52
- - The facts of an analyzer are not entry points or data for the next analysis. Thus a new analysis can correct them.
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`.
52
+ - With coverage, the RAM under ROM that the runs did not read or execute stays data. If the program has code there, give its address with `--entry`.
54
53
  - 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
54
  - `--decompile` takes the address of a routine. Get it from `functions` of an earlier decompiler result, or from the routines in the project knowledge.
56
55
 
@@ -64,12 +63,11 @@ To get the command list, run the script with no arguments.
64
63
  - A range is `<start>-<end>`, for example `'$c000-$cfff'`. In a JSON file, a range is `start` and `end`.
65
64
  - Bytes in a JSON file are hex in a field `data`, for example `"data": "a900"`.
66
65
  - Write each file that you make for your work in `.c64-re-tools/local/` of the project. Git ignores that folder. Examples are results, batches, step files, runs, snapshots and memory dumps.
67
- - The script refuses an `--out` path in `.c64-re-tools/knowledge/` and the index of the knowledge. Change the project knowledge only with the commands that change it.
66
+ - The script refuses an `--out` path in `.c64-re-tools/knowledge/`. Change the project knowledge only with the commands that change it.
68
67
  - The script refuses a folder where the command writes a file. It refuses a file where the command writes a folder.
69
68
  - When a test or another file is the evidence for a finding in the project knowledge, move it out of `.c64-re-tools/local/` first. The project knowledge refuses that evidence in that folder.
70
- - A coverage map can stay in `.c64-re-tools/local/`. The project knowledge keeps its ranges and its SHA-256.
71
- - Do not move a coverage map after you put it into the project knowledge. The knowledge refers to the map by its path at that time.
72
- - Put a run that is evidence in `runs/<name>/`, with its run file, its results and its snapshot files. Change the paths in the run file to the new paths. Then git keeps them, and another person can do the run again.
69
+ - A coverage map can stay in `.c64-re-tools/local/`. Do not move a coverage map after you put it into the project knowledge.
70
+ - To keep a run as evidence, use the command that keeps a run. It copies the run, its results and its snapshot files into `runs/<name>/`, and it changes the paths in the copy. Then git keeps them, and another person can do the run again.
73
71
  - A shell redirect (`>`) is relative to the working directory, not to the project folder. From the folder above the project, write `<folder>/.c64-re-tools/local/result.json`.
74
72
 
75
73
  ---
@@ -104,72 +102,93 @@ The script records only structure: code and data regions, analyzer names, and th
104
102
 
105
103
  - `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`.
106
104
  - `revision`: the revision of the findings, or `null` when the knowledge did not change.
107
- - `coverage`: the ranges that the analyzer examined.
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.
105
+ - `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 start in a data region of the user, the LLM or an idiom. The analyzer decoded these data bytes as code.
109
106
  - `conflicts`: each place where the analyzer and the project knowledge disagree. `problem` tells the disagreement.
107
+ - `seeds`: what the analyzer got and what it did not use.
108
+ - `entryPoints`, `codeStarts` (decompiler only) and `dataRanges` count the seeds that the analyzer got.
109
+ - `overLimit` counts the seeds over the limit of the analyzer. The analyzer did not get them.
110
+ - `refused` lists each seed that the analyzer did not decode, with `address` and `reason`. `byReason` counts the seeds for each reason. See "Refused seeds and coverage gaps".
111
+ - `dataRangesLeftOut` lists each data range that the analyzer did not keep as data, because the seed at `code` is in it.
110
112
  - `coverageSeeds`: only with coverage. `entryPoints` and `used` give how many entry points the coverage gave, and how many the analysis used. `romOnlyRanges` and `romOnlyUsed` give the same counts for the data ranges under ROM.
111
113
  - `coverageConflicts`: only with coverage. Each analyzer data region where the coverage shows executed code.
112
- - `idioms`: the 6502 idioms that the script found by pattern. The counts are `rtsTables`, `jumpTables`, `bitSkips` and `cartridgeHeaders`. `revision`, `changes` and `conflicts` are for the idioms, as above. `candidates` holds what the script did not record.
114
+ - `writtenNotExecuted`: only with coverage. Each code region of the analyzer on bytes that the runs wrote and never executed, with `start` and `end`. `from` gives the call and jump instructions outside the region that reach it.
115
+ - `idioms`: the 6502 idioms that the script found by pattern. The counts are `rtsTables`, `jumpTables`, `bitSkips` and `cartridgeHeaders`. `revision`, `changes` and `conflicts` are for the idioms, as above. `leftOut` lists each idiom that the script found but did not record, with `kind` and `reason`: `overlaps-idiom` or `leaves-program`. `candidates` holds what the script did not record. See "The candidates".
116
+ - `coverage`: the ranges that the analyzer examined.
113
117
 
114
118
  DXA also gives:
115
119
 
116
- - `regions`: the code and data regions, each with `start`, `end` and `classification`.
120
+ - `regions`: the code and data regions as a list, each with `start`, `end` and `classification`.
117
121
  - `labels`: the names that DXA found, as a list.
118
122
  - `listing`: the listing file, with `--out-listing`.
119
123
 
120
124
  The decompiler also gives:
121
125
 
126
+ - `coverageGaps`: only with coverage. Each executed instruction start that is not an instruction of the decompiler, with `address` and `reason`. See "Refused seeds and coverage gaps".
122
127
  - `functions`: the routines that the decompiler found, as a list, each with `entry` and `name`.
123
128
  - `decompilations`: the C-like code of each `--decompile` routine, with `entry` and `text`. `truncated` tells that the text is cut.
124
129
  - `notDecompiled`: the routines that the decompiler did not decompile, each with a `reason`.
125
130
  - `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.
126
- - `coverageGaps`: only with coverage. The executed instruction starts that are not in the instructions of the decompiler.
127
131
 
128
132
  The `hint` gives each of these cases:
129
133
 
130
134
  - `conflicts` is not empty. Find the correct answer in the emulator. Then correct the project knowledge.
131
135
  - `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.
136
+ - `seeds.refused` has a seed with a reason that is not `outside-program`, or an `--entry` outside the program. See "Refused seeds and coverage gaps".
137
+ - `writtenNotExecuted` is not empty. A wrong entry point leads an analyzer from code into data. Examine the routine that holds the instructions in `from`. Correct the routine or its region in the project knowledge. Then run `analyze` again.
132
138
  - `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
139
  - 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
140
  - `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.
135
- - A list is cut. Give a larger `--max-listed`. The project knowledge has all `labels` and `functions` as analyzer names.
141
+ - A list is cut. Give a larger `--max-listed`. The project knowledge has all `labels`, `functions` and DXA `regions`.
136
142
 
137
143
  There is no `nextAction`.
138
144
 
145
+ #### Refused seeds and coverage gaps
146
+
147
+ Each item of `seeds.refused` and `coverageGaps` has a `reason`. `at` gives the instruction that holds the address, or that its instruction runs into.
148
+
149
+ | `reason` | Action |
150
+ |---|---|
151
+ | `inside-instruction` | Another instruction holds the address. Examine both in the listing. If the address is a wrong routine or region in the project knowledge, correct it. If both instructions run, classify the bytes as `dual-use`. |
152
+ | `into-instruction` | The instruction at the address runs into the instruction at `at`. Do as for `inside-instruction`. |
153
+ | `in-data`, `into-data` | A data range of the analysis holds the address or its instruction. `range` gives the data range of a gap. If the code runs, correct the data region in the project knowledge. |
154
+ | `outside-program` | The address is not in the program. If the program copies the routine to this address when it runs, the routine is correct. If not, correct the entry point or the routine. |
155
+ | `past-end` | The instruction at the address runs past the end of the program. Correct the entry point or the routine. |
156
+ | `not-decodable` | No instruction decodes at the address. Correct the entry point or the routine. |
157
+ | `not-reached` | Only in `coverageGaps`: no flow and no seed reached the start. Give it with `--entry`, or record a routine there. |
158
+
159
+ A start in a `dual-use` region is a known overlap, for example a BIT skip. It is not a gap.
160
+
139
161
  #### The candidates
140
162
 
141
163
  The script does not record the candidates. Examine each candidate and decide.
142
164
 
143
165
  - `dop`: DOP padding.
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.
166
+ - `selfModified`: opcodes that the program wrote and then executed in one coverage map. A candidate can also be code that ran first and that the program then wrote over. To prevent this, save one coverage map 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.
145
167
  - `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.
146
168
  - `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.
147
169
  - `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.
148
170
 
149
- #### Which facts the analysis replaces
171
+ #### What the analysis replaces
150
172
 
151
- - The analysis never replaces a name or a region of the user or the LLM. Each disagreement shows in `conflicts`.
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.
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`.
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.
173
+ - The analysis never replaces a name or a region of the user or the LLM. Each disagreement shows in `conflicts`. A conflict with `executed` or `knowledge` shows data where a run executed code, or where the user or the LLM named code.
174
+ - Put all coverage maps into the project knowledge first. Then run DXA, then the decompiler.
155
175
  - An idiom table can be too long or too short. Correct its region in the project knowledge. Your region replaces it.
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.
176
+ - A new analysis replaces the earlier findings of the same analyzer in its `coverage`.
157
177
  - A fact that the user or the LLM removed does not come back. To remove a wrong fact, remove it in the project knowledge.
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.
178
+ - An analyzer name is a second name of the address, not a symbol. The generated source does not use it. To use a name in the source, give the address a name in the project knowledge.
159
179
  - A decompiler function that only branches and jumps reach is a `label`, not a `routine`.
160
180
 
161
181
  #### Traps
162
182
 
163
183
  - A conflict with the problem "another address has this name": the project knowledge has the generated name at a different address. The knowledge stays unchanged.
164
184
  - A false reference through a vector: the code jumps through a vector, for example `JMP ($0408)`, and the program writes the vector at run time. The analyzer follows the bytes that the program has there. Do these steps:
165
- 1. Find the real targets in the emulator, or in a coverage file.
185
+ 1. Find the real targets in the emulator, or in a coverage map.
166
186
  2. If the vector bytes are also code at another time, classify them as `dual-use` in the project knowledge.
167
187
  3. Remove the false reference in the project knowledge. It does not come back.
168
188
  4. Record a `jump` reference from the JMP to each real target in the project knowledge. Record each target as a routine.
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.
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.
189
+ - `coverageSeeds.used` is smaller than `coverageSeeds.entryPoints`, or `seeds.overLimit` is not empty. The analysis did not use all seeds. Give the important entry points with `--entry`, or record them as routines in the project knowledge. These come first.
171
190
  - `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.
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`.
191
+ - `notDecompiled` has a routine. The `reason` tells why the decompiler did not decompile it. Read the lines of that routine in the listing of the project knowledge.
173
192
 
174
193
  #### Failures
175
194
 
@@ -196,24 +215,15 @@ The script does not record the candidates. Examine each candidate and decide.
196
215
 
197
216
  Each command prints one JSON envelope on one line on stdout. Notes go to stderr.
198
217
 
199
- On success, the exit code is 0:
200
-
201
- ```json
202
- {"ok": true, "command": "<command>", "body": {}, "hint": "...", "nextAction": "..."}
203
- ```
204
-
205
- On failure, the exit code is 2:
206
-
207
- ```json
208
- {"ok": false, "command": "<command>", "code": "<code>", "error": "...", "hint": "...", "nextAction": "..."}
209
- ```
210
-
218
+ - On success, the exit code is 0: `{"ok": true, "command": "<command>", "body": {}, "hint": "...", "nextAction": "..."}`
219
+ - On failure, the exit code is 2: `{"ok": false, "command": "<command>", "code": "<code>", "error": "...", "hint": "...", "nextAction": "..."}`
211
220
  - `body` holds the result. The section of each command gives the fields of its body.
212
221
  - A check gives its verdict in `body.result`: `PASS`, `FAIL` or `INCONCLUSIVE`. The exit code is 0 for each verdict. Thus read `body.result`, not the exit code.
213
- - `error` is one sentence. It tells what is wrong.
214
- - `hint` tells what to do or what to examine. Read it before your next step. Some envelopes have no `hint`.
215
- - `nextAction` is a full command line. It runs from any directory. Run it when it agrees with your task. Some envelopes have no `nextAction`.
216
- - `code` does not change between versions. Do the action for the code:
222
+ - `error` is one sentence. It tells what is wrong. `hint` tells what to do or what to examine. Read it before your next step.
223
+ - `nextAction` is a full command line. It runs from any directory. Run it when it agrees with your task.
224
+ - A list has `count`, `listed` and `rest`. `listed` holds at most `--max-listed` items. `rest` tells how to get the other items. A file that the command wrote has `out`, `bytes` and `sha256`.
225
+ - To get only some fields of `body`, give `--fields <path>,<path>`, for example `--fields count,listed.start`. A path through a list gives that field of each item. Do not write code to filter an envelope.
226
+ - To get the command list, run the script with no arguments. To get the subjects and the flags of one command, run `<command> --help`.
217
227
 
218
228
  | `code` | Action |
219
229
  |---|---|
@@ -221,13 +231,3 @@ On failure, the exit code is 2:
221
231
  | `invalid-input`, `not-found` | Correct the call as `hint` tells. Then run the command again. |
222
232
  | `operation-failed` | Give `error` and `hint` to the user. |
223
233
  | Another code | Do as `hint` tells. |
224
-
225
- These fields have the same meaning in each body:
226
-
227
- | Field | Meaning |
228
- |---|---|
229
- | `out`, `bytes`, `sha256` | A file that the command wrote: its path, its size and its SHA-256. |
230
- | `count`, `listed`, `rest` | A list. `count` is the number of items. `listed` holds the first items, at most `--max-listed`. `rest` tells how to get the other items. |
231
-
232
- To get the command list, run the script with no arguments. The envelope has `command: "help"`, and `body.commands` gives the name, the summary and the synopsis of each command.
233
- To get the subjects and the flags of one command, run `<command> --help`. Then `body.subjects` and `body.options` give them.
@@ -5,10 +5,11 @@
5
5
  import type { DatabaseSync } from "node:sqlite";
6
6
 
7
7
  import { COVERAGE, coverageEntries, coverageSeedKinds, executedStarts, romOnlyRanges } from "#src/c64.ts";
8
+ import type { RefusedSeed, RefusedSeedReason } from "#src/native/types.ts";
8
9
 
9
10
  export { coverageEntries, coverageSeedKinds, executedStarts, romOnlyRanges };
10
- import { listRegions, type RegionRow } from "#src/knowledge/read.ts";
11
- import { CODE_REGION_TYPES, DEFAULT_SPACE, isAnalyzer, isSemantic, type Space } from "#src/knowledge/schema.ts";
11
+ import { listReferences, listRegions, type RegionRow } from "#src/knowledge/read.ts";
12
+ import { CODE_REGION_TYPES, DEFAULT_SPACE, isAnalyzer, isSemantic, type Analyzer, type Space } from "#src/knowledge/schema.ts";
12
13
 
13
14
  /** The byte at an address of the analyzed image, or undefined outside it. */
14
15
  export type ImageByte = (address: number) => number | undefined;
@@ -46,3 +47,55 @@ export function coverageConflicts(db: DatabaseSync | undefined, map: Uint8Array)
46
47
  }
47
48
  return conflicts;
48
49
  }
50
+
51
+ /**
52
+ * The code regions of an analyzer on bytes that a run wrote and that no run
53
+ * executed, each with the call and jump instructions outside it that reach it:
54
+ * a wrong entry point leads an analyzer from code into data.
55
+ */
56
+ export function writtenNotExecuted(db: DatabaseSync | undefined, analyzer: Analyzer, coverage: Uint8Array, space: Space = DEFAULT_SPACE): Array<{ start: number; end: number; from: number[] }> {
57
+ const found: Array<{ start: number; end: number; from: number[] }> = [];
58
+ for (const region of listRegions(db, undefined, "code", [analyzer], space)) {
59
+ let written = false;
60
+ let executed = false;
61
+ for (let address = region.start; address <= region.end && !executed; address++) {
62
+ executed = (coverage[address]! & COVERAGE.ramExecute) !== 0;
63
+ written ||= (coverage[address]! & COVERAGE.ramWrite) !== 0;
64
+ }
65
+ if (executed || !written) continue;
66
+ const outside = (address: number) => address < region.start || address > region.end;
67
+ const from = listReferences(db, region, undefined, undefined, space).filter((reference) => (reference.kind === "call" || reference.kind === "jump") && !outside(reference.to) && outside(reference.from));
68
+ found.push({ start: region.start, end: region.end, from: [...new Set(from.map((reference) => reference.from))].sort((a, b) => a - b) });
69
+ }
70
+ return found;
71
+ }
72
+
73
+ /** Why an executed instruction start has no decoded instruction. */
74
+ export interface GapReason {
75
+ address: number;
76
+ reason: RefusedSeedReason | "not-reached";
77
+ /** The instruction that holds the start or that its instruction runs into. */
78
+ at?: number;
79
+ /** The data range of the analysis that holds the start. */
80
+ range?: { start: number; end: number };
81
+ }
82
+
83
+ /**
84
+ * The reason of each coverage gap: the reason of the analysis when the gap
85
+ * was a seed that it refused; else inside a decoded instruction, in a data
86
+ * range of the analysis, or not reached by any flow or seed.
87
+ */
88
+ export function explainGaps(gaps: readonly number[], instructions: ReadonlyArray<{ address: number; bytes: string }>, refused: readonly RefusedSeed[], dataRanges: ReadonlyArray<{ start: number; end: number }>): GapReason[] {
89
+ const holder = new Map<number, number>();
90
+ for (const instruction of instructions) for (let offset = 1; offset < instruction.bytes.length / 2; offset++) holder.set(instruction.address + offset, instruction.address);
91
+ const refusedAt = new Map(refused.map((seed) => [seed.address, seed]));
92
+ return gaps.map((address): GapReason => {
93
+ const seed = refusedAt.get(address);
94
+ if (seed !== undefined) return { ...seed };
95
+ const at = holder.get(address);
96
+ if (at !== undefined) return { address, reason: "inside-instruction", at };
97
+ const range = dataRanges.find((item) => address >= item.start && address <= item.end);
98
+ if (range !== undefined) return { address, reason: "in-data", range: { start: range.start, end: range.end } };
99
+ return { address, reason: "not-reached" };
100
+ });
101
+ }
@@ -20,6 +20,14 @@ const DOPS = new Set([0x04, 0x14, 0x34, 0x44, 0x54, 0x64, 0x74, 0x80, 0x82, 0x89
20
20
  /** "CBM80" in PETSCII at $8004: the KERNAL then starts the cartridge through the vectors at $8000 (cold) and $8002 (warm). */
21
21
  const CBM80 = [0xc3, 0xc2, 0xcd, 0x38, 0x30];
22
22
 
23
+ /** An idiom that the pass found but could not record: its bytes leave the program, or an idiom found before holds some of them. */
24
+ export interface LeftOutIdiom {
25
+ start: number;
26
+ end: number;
27
+ kind: "cartridge-header" | "rts-table" | "jump-table" | "bit-skip";
28
+ reason: "leaves-program" | "overlaps-idiom";
29
+ }
30
+
23
31
  export interface Idioms {
24
32
  findings: NormalizedFindings;
25
33
  /** Entry points for the same analysis run: analyzer facts are never seeds. */
@@ -27,6 +35,8 @@ export interface Idioms {
27
35
  /** Table ranges for the same run: they are data. */
28
36
  dataRanges: Array<{ start: number; end: number }>;
29
37
  counts: { cartridgeHeaders: number; rtsTables: number; jumpTables: number; bitSkips: number };
38
+ /** The idioms that were found but not recorded, with the reason. */
39
+ leftOut: LeftOutIdiom[];
30
40
  /** Seen in the coverage, not written: the LLM decides. All of them: the result lists the first ones. */
31
41
  candidates: { dop: number[]; selfModified: number[] };
32
42
  }
@@ -54,16 +64,24 @@ export function findIdioms(byteAt: ImageByte, range: { start: number; end: numbe
54
64
  const references: NormalizedFindings["references"] = [];
55
65
  const entryPoints = new Set<number>();
56
66
  const counts = { cartridgeHeaders: 0, rtsTables: 0, jumpTables: 0, bitSkips: 0 };
67
+ const leftOut: LeftOutIdiom[] = [];
57
68
  const taken = (start: number, end: number) => regions.some((region) => start <= region.end && end >= region.start);
58
- const addRegion = (start: number, end: number, type: NormalizedFindings["regions"][number]["type"]) => {
59
- if (start < range.start || end > range.end || taken(start, end)) return false;
60
- regions.push({ start, end, type });
69
+ const blocked = (start: number, end: number): LeftOutIdiom["reason"] | undefined => (start < range.start || end > range.end ? "leaves-program" : taken(start, end) ? "overlaps-idiom" : undefined);
70
+ /** Records the region of an idiom when all of its parts fit; else records why the idiom is left out. */
71
+ const addRegions = (kind: LeftOutIdiom["kind"], parts: ReadonlyArray<{ start: number; end: number; type: NormalizedFindings["regions"][number]["type"] }>) => {
72
+ for (const part of parts) {
73
+ const reason = blocked(part.start, part.end) ?? (parts.some((other) => other !== part && part.start <= other.end && part.end >= other.start) ? "overlaps-idiom" : undefined);
74
+ if (reason === undefined) continue;
75
+ leftOut.push({ start: Math.min(...parts.map((item) => item.start)), end: Math.max(...parts.map((item) => item.end)), kind, reason });
76
+ return false;
77
+ }
78
+ regions.push(...parts);
61
79
  return true;
62
80
  };
63
81
 
64
82
  if (range.start <= 0x8000 && range.end >= 0x8008 && CBM80.every((byte, index) => byteAt(0x8004 + index) === byte)) {
65
83
  const vectors = [word(byteAt, 0x8000)!, word(byteAt, 0x8002)!].filter((target) => plausible(byteAt, target, range));
66
- if (addRegion(0x8000, 0x8003, "addresses") && addRegion(0x8004, 0x8008, "petscii")) {
84
+ if (addRegions("cartridge-header", [{ start: 0x8000, end: 0x8003, type: "addresses" }, { start: 0x8004, end: 0x8008, type: "petscii" }])) {
67
85
  counts.cartridgeHeaders++;
68
86
  for (const target of vectors) entryPoints.add(target);
69
87
  }
@@ -87,13 +105,17 @@ export function findIdioms(byteAt: ImageByte, range: { start: number; end: numbe
87
105
  }
88
106
  if (targets.length === 0) continue;
89
107
  const n = targets.length;
90
- const written = interleaved
91
- ? addRegion(low, low + 2 * n - 1, "rts-addresses")
108
+ const parts: Parameters<typeof addRegions>[1] = interleaved
109
+ ? [{ start: low, end: low + 2 * n - 1, type: "rts-addresses" }]
92
110
  : low + n === high
93
- ? addRegion(low, high + n - 1, "rts-addresses-split")
94
- : addRegion(low, low + n - 1, "bytes") && addRegion(high, high + n - 1, "bytes");
95
- if (!written) continue;
96
- counts.rtsTables++;
111
+ ? [{ start: low, end: high + n - 1, type: "rts-addresses-split" }]
112
+ : [{ start: low, end: low + n - 1, type: "bytes" }, { start: high, end: high + n - 1, type: "bytes" }];
113
+ // Another dispatch through the same table: the table is recorded, and this RTS goes to its targets too.
114
+ const known = parts.every((part) => regions.some((region) => region.start === part.start && region.end === part.end && region.type === part.type));
115
+ if (!known) {
116
+ if (!addRegions("rts-table", parts)) continue;
117
+ counts.rtsTables++;
118
+ }
97
119
  for (const target of targets) {
98
120
  references.push({ from: at + 8, to: target, kind: "jump" });
99
121
  entryPoints.add(target);
@@ -105,13 +127,16 @@ export function findIdioms(byteAt: ImageByte, range: { start: number; end: numbe
105
127
  for (let at = range.start; at + 3 * MIN_JUMPS - 1 <= range.end; at++) {
106
128
  let n = 0;
107
129
  while (at + 3 * n + 2 <= range.end && byteAt(at + 3 * n) === 0x4c) n++;
108
- if (n < MIN_JUMPS || !addRegion(at, at + 3 * n - 1, "jumps")) continue;
109
- counts.jumpTables++;
110
- for (let index = 0; index < n; index++) {
111
- entryPoints.add(at + 3 * index);
112
- const target = word(byteAt, at + 3 * index + 1)!;
113
- if (plausible(byteAt, target, range)) entryPoints.add(target);
130
+ if (n < MIN_JUMPS) continue;
131
+ if (addRegions("jump-table", [{ start: at, end: at + 3 * n - 1, type: "jumps" }])) {
132
+ counts.jumpTables++;
133
+ for (let index = 0; index < n; index++) {
134
+ entryPoints.add(at + 3 * index);
135
+ const target = word(byteAt, at + 3 * index + 1)!;
136
+ if (plausible(byteAt, target, range)) entryPoints.add(target);
137
+ }
114
138
  }
139
+ // The JMPs inside the run are the same table: a run that is left out is left out once.
115
140
  at += 3 * n - 1;
116
141
  }
117
142
 
@@ -123,7 +148,7 @@ export function findIdioms(byteAt: ImageByte, range: { start: number; end: numbe
123
148
  if (coverage !== undefined) for (let address = range.start; address <= range.end; address++) if ((coverage[address]! & COVERAGE.ramExecute) !== 0) entered.add(address);
124
149
  for (let at = range.start; at + 2 <= range.end; at++) {
125
150
  if (byteAt(at) !== 0x2c || !entered.has(at + 1) || !plausible(byteAt, at + 1, range)) continue;
126
- if (!addRegion(at + 1, at + 2, "dual-use")) continue;
151
+ if (!addRegions("bit-skip", [{ start: at + 1, end: at + 2, type: "dual-use" }])) continue;
127
152
  counts.bitSkips++;
128
153
  entryPoints.add(at);
129
154
  entryPoints.add(at + 1);
@@ -157,6 +182,7 @@ export function findIdioms(byteAt: ImageByte, range: { start: number; end: numbe
157
182
  entryPoints: [...entryPoints].sort((a, b) => a - b),
158
183
  dataRanges,
159
184
  counts,
185
+ leftOut,
160
186
  candidates,
161
187
  };
162
188
  }
@@ -11,7 +11,7 @@ import { knowledgeNames } from "#src/knowledge/names.ts";
11
11
  import { analyze as analyzeWithDxa } from "#src/native/dxa.ts";
12
12
  import { analyze as analyzeWithDecompiler } from "#src/native/decompiler/analyze.ts";
13
13
  import { localToolContext } from "#src/native/local.ts";
14
- import { DECOMPILER_LIMITS } from "#src/native/types.ts";
14
+ import { DECOMPILER_LIMITS, type RefusedSeed, type SeedReport } from "#src/native/types.ts";
15
15
  import { openForRead, withWrite } from "#src/knowledge/database.ts";
16
16
  import { analyzedBytes, operandImages, programCoverage, requireProgram } from "#src/knowledge/program.ts";
17
17
  import { applyBatch, type BatchOperation } from "#src/knowledge/write.ts";
@@ -20,7 +20,7 @@ import { currentRevision, listMacros, listMacroUses, listPatches, listReferences
20
20
  import { DEFAULT_SPACE, SEMANTIC_ORIGINS, type Analyzer } from "#src/knowledge/schema.ts";
21
21
  import { platformNames, platformNamesFor, romUseOfProgram, type RomUse } from "#src/platform.ts";
22
22
  import { listed, OPTIONS, reply, runScript, UsageError, type Call } from "#src/script.ts";
23
- import { codeEntries, coverageConflicts, coverageEntries, coverageSeedKinds, executedStarts, imageReader, romOnlyRanges, type ImageByte } from "./lib/coverage.ts";
23
+ import { codeEntries, coverageConflicts, coverageEntries, coverageSeedKinds, executedStarts, imageReader, romOnlyRanges, writtenNotExecuted, explainGaps, type GapReason, type ImageByte } from "./lib/coverage.ts";
24
24
  import { dxaFindings, decompilerFindings, seedsFromKnowledge } from "./lib/findings.ts";
25
25
  import { findIdioms } from "./lib/idioms.ts";
26
26
  import { instructionList } from "./lib/instructions.ts";
@@ -30,14 +30,18 @@ import { findPointers, type PointerCandidate } from "./lib/pointers.ts";
30
30
 
31
31
  /** The rest of a cut label or function list: the knowledge has all of them as analyzer names. */
32
32
  const ALL_NAMES = "a larger --max-listed. The project knowledge has all of them as analyzer names";
33
+ /** The rest of a cut region list: the knowledge has all of them. */
34
+ const ALL_REGIONS = "a larger --max-listed. The project knowledge has all of them as regions";
33
35
 
34
36
  /**
35
37
  * The result with a hint for what the agent does next: conflicts to examine,
36
38
  * analyzer data over executed code to classify, and macro candidates to write.
37
39
  * The envelope adds the sentence for a cut list.
38
40
  */
39
- function withHint(body: Record<string, unknown>, conflicts: number, coverageConflicts: number, macros: { candidates: number; applied: boolean; revision: string | null | undefined }, version: { now: string | undefined; last: string | undefined; revision: string | null }, retiredReferences: number) {
41
+ function withHint(body: Record<string, unknown>, conflicts: number, coverageConflicts: number, macros: { candidates: number; applied: boolean; revision: string | null | undefined }, version: { now: string | undefined; last: string | undefined; revision: string | null }, retiredReferences: number, guards: { refused: number; writtenNotExecuted: number }) {
40
42
  const hints: string[] = [];
43
+ if (guards.refused > 0) hints.push(`The analysis did not decode ${guards.refused} seeds in the program or of --entry: seeds.refused gives each refused seed with its reason. A seed inside an instruction or in data is often a wrong routine or region in the project knowledge. Examine it in the listing, and correct the project knowledge.`);
44
+ if (guards.writtenNotExecuted > 0) hints.push("Each range in writtenNotExecuted is code of the analyzer on bytes that the runs wrote and never executed. Its from gives the instructions that reach it. Examine the routine that holds them: a wrong entry point leads the analyzer into data. Correct the project knowledge, and run the analysis again.");
41
45
  if (version.revision !== null && version.now !== undefined && version.last !== undefined && version.now !== version.last) {
42
46
  hints.push(`The last analysis of this program used ${version.last}. Thus a change in revision ${version.revision} can come from the new analyzer version, and not from the program or the project knowledge.`);
43
47
  }
@@ -51,6 +55,44 @@ function withHint(body: Record<string, unknown>, conflicts: number, coverageConf
51
55
  return reply(body, { hint: hints.join(" ") });
52
56
  }
53
57
 
58
+ /**
59
+ * The refused seeds that can be a fault of the project knowledge: a routine
60
+ * outside the program can be code that the program copies there when it
61
+ * runs, so only an --entry outside the program counts.
62
+ */
63
+ function toCorrect(refused: readonly RefusedSeed[], entries: readonly number[]): number {
64
+ return refused.filter((seed) => seed.reason !== "outside-program" || entries.includes(seed.address)).length;
65
+ }
66
+
67
+ /** A refused seed with $ addresses. */
68
+ function showRefused(seed: RefusedSeed) {
69
+ return { address: formatC64Address(seed.address), reason: seed.reason, ...(seed.at === undefined ? {} : { at: formatC64Address(seed.at) }) };
70
+ }
71
+
72
+ /** The seeds part of a result: the counts that the analyzer got, the counts over its limits, and the seeds and data ranges that it left out. */
73
+ function seedsResult(given: Record<string, number>, overLimit: Record<string, number>, report: SeedReport, max: number) {
74
+ const over = Object.fromEntries(Object.entries(overLimit).filter(([, count]) => count > 0));
75
+ const byReason: Record<string, number> = {};
76
+ for (const seed of report.refused) byReason[seed.reason] = (byReason[seed.reason] ?? 0) + 1;
77
+ return {
78
+ ...given,
79
+ ...(Object.keys(over).length === 0 ? {} : { overLimit: over }),
80
+ ...(report.refused.length === 0 ? {} : { refused: { ...listed(report.refused, max, showRefused), byReason } }),
81
+ ...(report.dataRangesLeftOut.length === 0 ? {} : { dataRangesLeftOut: listed(report.dataRangesLeftOut, max, (range) => ({ start: formatC64Address(range.start), end: formatC64Address(range.end), code: formatC64Address(range.code) })) }),
82
+ };
83
+ }
84
+
85
+ /** The code regions of the analyzer on bytes that the runs wrote and never executed, from the knowledge after the import. */
86
+ function writtenNotExecutedOf(analyzer: Analyzer, space: string, coverage: Uint8Array | undefined) {
87
+ if (coverage === undefined) return [];
88
+ const db = openForRead();
89
+ try {
90
+ return writtenNotExecuted(db, analyzer, coverage, space);
91
+ } finally {
92
+ db?.close();
93
+ }
94
+ }
95
+
54
96
  /** A pitfall with $ addresses and what goes wrong. */
55
97
  function showPitfall(pitfall: Pitfall) {
56
98
  return {
@@ -216,13 +258,16 @@ async function analyze(call: Call): Promise<unknown> {
216
258
  const kinds = analyzer === "dxa" || coverage === undefined ? { routines: fromCoverage, codeStarts: [] } : coverageSeedKinds(coverage, inProgram);
217
259
  const ordered = [...new Set([...known, ...idioms.entryPoints, ...kinds.routines])];
218
260
  seeds.entryPoints = ordered.slice(0, DECOMPILER_LIMITS.entryPoints).sort((a, b) => a - b);
219
- const codeStarts = kinds.codeStarts.filter((entry) => !seeds.entryPoints.includes(entry)).slice(0, DECOMPILER_LIMITS.codeStarts);
261
+ const allCodeStarts = kinds.codeStarts.filter((entry) => !seeds.entryPoints.includes(entry));
262
+ const codeStarts = allCodeStarts.slice(0, DECOMPILER_LIMITS.codeStarts);
220
263
  // Idiom tables and the RAM under ROM that the runs never used are data for this run too; semantic data ranges come first.
221
264
  // A range with an entry point of the knowledge or --entry in it is left out: that code stays code.
222
265
  const fromRom = coverage === undefined ? [] : romOnlyRanges(coverage, byteAt).filter((range) => !known.some((entry) => entry >= range.start && entry <= range.end));
223
266
  const dataRanges = [...seeds.dataRanges];
224
267
  for (const range of [...idioms.dataRanges, ...fromRom]) if (!dataRanges.some((seed) => range.start <= seed.end && range.end >= seed.start)) dataRanges.push(range);
225
268
  seeds.dataRanges = dataRanges.slice(0, DECOMPILER_LIMITS.dataRanges);
269
+ // The seeds over the limits of the analyzer: it never sees them.
270
+ const overLimit = { entryPoints: Math.max(0, ordered.length - DECOMPILER_LIMITS.entryPoints), codeStarts: allCodeStarts.length - codeStarts.length, dataRanges: Math.max(0, dataRanges.length - DECOMPILER_LIMITS.dataRanges) };
226
271
  const romUsed = fromRom.filter((range) => seeds.dataRanges.includes(range)).length;
227
272
  const coverageUsed = fromCoverage.filter((entry) => seeds.entryPoints.includes(entry) || codeStarts.includes(entry)).length;
228
273
  // Platform names are C64 names: drive code and banks get none.
@@ -253,6 +298,7 @@ async function analyze(call: Call): Promise<unknown> {
253
298
  revision: imported.revision,
254
299
  changes: { regions: imported.regions, references: imported.references },
255
300
  conflicts: imported.conflicts.map((conflict) => showConflict(conflict, "heuristic")),
301
+ ...(idioms.leftOut.length === 0 ? {} : { leftOut: listed(idioms.leftOut, max, (item) => ({ start: formatC64Address(item.start), end: formatC64Address(item.end), kind: item.kind, reason: item.reason })) }),
256
302
  // Candidates are not knowledge: a larger --max-listed gives more of them.
257
303
  candidates: {
258
304
  dop: listed(idioms.candidates.dop, max, formatC64Address, "a larger --max-listed"),
@@ -289,7 +335,7 @@ async function analyze(call: Call): Promise<unknown> {
289
335
  };
290
336
  };
291
337
  if (analyzer === "dxa") {
292
- const { result, attachments } = await analyzeWithDxa({ imageKind, ...seeds }, bytes, localToolContext());
338
+ const { result, attachments, seeds: report } = await analyzeWithDxa({ imageKind, ...seeds }, bytes, localToolContext());
293
339
  const listing = attachments[0]!.toString("utf8");
294
340
  // The listing is written only after the import: a refused import leaves no new file.
295
341
  const imported = record({ ...dxaFindings(result), space, ...executed }, revision, "DXA analysis of the program", runProvenance(bytes, result.toolVersion));
@@ -303,22 +349,25 @@ async function analyze(call: Call): Promise<unknown> {
303
349
  }
304
350
  }
305
351
  const found = idiomsResult();
352
+ const runOnWritten = writtenNotExecutedOf("dxa", space, coverage);
306
353
  const body = {
307
354
  analyzer: "dxa",
308
355
  ...(result.toolVersion === undefined ? {} : { analyzerVersion: result.toolVersion }),
309
356
  ...(space === DEFAULT_SPACE ? {} : { space }),
310
- ...found,
357
+ ...imported,
358
+ seeds: seedsResult({ entryPoints: seeds.entryPoints.length, dataRanges: seeds.dataRanges.length }, { entryPoints: overLimit.entryPoints, dataRanges: overLimit.dataRanges }, report, max),
311
359
  ...coverageResult(),
360
+ ...(runOnWritten.length === 0 ? {} : { writtenNotExecuted: listed(runOnWritten, max, showWritten) }),
361
+ ...found,
312
362
  coverage: result.coverage.map((range) => ({ start: formatC64Address(range.start), end: formatC64Address(range.end) })),
313
- ...imported,
314
- regions: result.regions.map((region) => ({ start: formatC64Address(region.start), end: formatC64Address(region.end), classification: region.classification })),
363
+ regions: listed(result.regions, max, (region) => ({ start: formatC64Address(region.start), end: formatC64Address(region.end), classification: region.classification }), ALL_REGIONS),
315
364
  labels: listed(result.labels, max, (label) => ({ address: formatC64Address(label.address), name: label.name }), ALL_NAMES),
316
365
  ...(written === undefined ? {} : { listing: written }),
317
366
  };
318
- return withHint(body, imported.conflicts.length + found.idioms.conflicts.length, body.coverageConflicts?.length ?? 0, { candidates: found.idioms.candidates.macros.count, applied: applyMacros, revision: found.idioms.candidates.macros.revision }, { now: result.toolVersion, last: lastVersion, revision: imported.revision }, imported.changes.references.retired);
367
+ return withHint(body, imported.conflicts.length + found.idioms.conflicts.length, body.coverageConflicts?.length ?? 0, { candidates: found.idioms.candidates.macros.count, applied: applyMacros, revision: found.idioms.candidates.macros.revision }, { now: result.toolVersion, last: lastVersion, revision: imported.revision }, imported.changes.references.retired, { refused: toCorrect(report.refused, entries), writtenNotExecuted: runOnWritten.length });
319
368
  }
320
369
 
321
- const { result } = await analyzeWithDecompiler({ imageKind, ...seeds, codeStarts, decompile }, bytes, localToolContext());
370
+ const { result, seeds: report } = await analyzeWithDecompiler({ imageKind, ...seeds, codeStarts, decompile }, bytes, localToolContext());
322
371
  // Executed instruction starts that the decompiler did not decode: the instruction list and the source miss them.
323
372
  const decoded = new Set(result.instructions.map((instruction) => instruction.address));
324
373
  const imported = record({ ...decompilerFindings(result), space, ...executed }, revision, "Decompiler analysis of the program", runProvenance(bytes, result.toolVersion));
@@ -329,6 +378,9 @@ async function analyze(call: Call): Promise<unknown> {
329
378
  const overlaps = listRegions(overlapDb, undefined, "dual-use", undefined, space);
330
379
  overlapDb?.close();
331
380
  const gaps = coverage === undefined ? [] : executedStarts(coverage, inProgram).filter((address) => address >= loaded.start && address <= loaded.end && !decoded.has(address) && !overlaps.some((region) => address >= region.start && address <= region.end));
381
+ // The data ranges that the decompiler used: not the ranges that hold a seed, and only the part in the program.
382
+ const explained = explainGaps(gaps, result.instructions, report.refused, report.dataRanges);
383
+ const runOnWritten = writtenNotExecutedOf("decompiler", space, coverage);
332
384
  let instructions: Record<string, unknown> | undefined;
333
385
  if (instructionsPath !== undefined) {
334
386
  const list = instructionList(result.instructions, coverage);
@@ -338,19 +390,31 @@ async function analyze(call: Call): Promise<unknown> {
338
390
  analyzer: "decompiler",
339
391
  ...(result.toolVersion === undefined ? {} : { analyzerVersion: result.toolVersion }),
340
392
  ...(space === DEFAULT_SPACE ? {} : { space }),
341
- ...(instructions === undefined ? {} : { instructions }),
342
- ...found,
393
+ ...imported,
394
+ seeds: seedsResult({ entryPoints: seeds.entryPoints.length, codeStarts: codeStarts.length, dataRanges: seeds.dataRanges.length }, overLimit, report, max),
343
395
  ...coverageResult(),
344
- ...(coverage === undefined ? {} : { coverageGaps: listed(gaps, max, formatC64Address, "a larger --max-listed") }),
396
+ ...(coverage === undefined ? {} : { coverageGaps: listed(explained, max, showGap, "a larger --max-listed") }),
397
+ ...(runOnWritten.length === 0 ? {} : { writtenNotExecuted: listed(runOnWritten, max, showWritten) }),
398
+ ...found,
399
+ ...(instructions === undefined ? {} : { instructions }),
345
400
  coverage: result.coverage.map((range) => ({ start: formatC64Address(range.start), end: formatC64Address(range.end) })),
346
- ...imported,
347
401
  functions: listed(result.functions, max, (fn) => ({ entry: formatC64Address(fn.entry), name: fn.name }), ALL_NAMES),
348
402
  decompilations: result.decompilations.map((item) => ({ entry: formatC64Address(item.entry), text: item.text, ...(item.truncated ? { truncated: true } : {}) })),
349
403
  ...((result.notDecompiled ?? []).length === 0
350
404
  ? {}
351
405
  : { notDecompiled: result.notDecompiled!.map((item) => ({ entry: formatC64Address(item.entry), reason: item.reason })) }),
352
406
  };
353
- return withHint(body, imported.conflicts.length + found.idioms.conflicts.length, body.coverageConflicts?.length ?? 0, { candidates: found.idioms.candidates.macros.count, applied: applyMacros, revision: found.idioms.candidates.macros.revision }, { now: result.toolVersion, last: lastVersion, revision: imported.revision }, imported.changes.references.retired);
407
+ return withHint(body, imported.conflicts.length + found.idioms.conflicts.length, body.coverageConflicts?.length ?? 0, { candidates: found.idioms.candidates.macros.count, applied: applyMacros, revision: found.idioms.candidates.macros.revision }, { now: result.toolVersion, last: lastVersion, revision: imported.revision }, imported.changes.references.retired, { refused: toCorrect(report.refused, entries), writtenNotExecuted: runOnWritten.length });
408
+ }
409
+
410
+ /** A coverage gap with $ addresses. */
411
+ function showGap(gap: GapReason) {
412
+ return { address: formatC64Address(gap.address), reason: gap.reason, ...(gap.at === undefined ? {} : { at: formatC64Address(gap.at) }), ...(gap.range === undefined ? {} : { range: { start: formatC64Address(gap.range.start), end: formatC64Address(gap.range.end) } }) };
413
+ }
414
+
415
+ /** A range of writtenNotExecuted with $ addresses. */
416
+ function showWritten(range: { start: number; end: number; from: number[] }) {
417
+ return { start: formatC64Address(range.start), end: formatC64Address(range.end), from: range.from.map(formatC64Address) };
354
418
  }
355
419
 
356
420
  await runScript({