@henols/c64-re-tools 2.6.0-rc.7 → 2.6.0-rc.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +2 -2
- package/skills/c64-docs/SKILL.md +1 -1
- package/skills/c64-docs/scripts/docs.ts +6 -6
- package/skills/c64-knowledge/SKILL.md +3 -3
- package/skills/c64-knowledge/scripts/knowledge.ts +2 -0
- package/skills/c64-knowledge/scripts/lib/listing.ts +18 -3
- package/skills/c64-reverse-engineering/SKILL.md +1 -1
- package/skills/c64-source/SKILL.md +7 -7
- package/skills/c64-source/scripts/lib/source.ts +10 -0
- package/skills/c64-source/scripts/source.ts +32 -27
- package/skills/c64-static-analysis/SKILL.md +5 -3
- package/skills/c64-static-analysis/scripts/lib/instructions.ts +22 -20
- package/skills/c64-static-analysis/scripts/static-analysis.ts +16 -16
- package/skills/c64-testing/SKILL.md +2 -1
- package/skills/c64-testing/references/recording-format.md +17 -3
- package/skills/c64-testing/references/scenario-format.md +2 -3
- package/skills/c64-testing/scripts/lib/diff-files.ts +4 -18
- package/skills/c64-testing/scripts/lib/play.ts +39 -41
- package/skills/c64-testing/scripts/lib/recording.ts +21 -29
- package/skills/c64-testing/scripts/lib/runs.ts +2 -2
- package/skills/c64-testing/scripts/lib/scenario.ts +3 -5
- package/skills/c64-unpacker/SKILL.md +2 -1
- package/skills/c64-unpacker/scripts/lib/loads.ts +2 -2
- package/skills/emulator/SKILL.md +2 -5
- package/src/c64-keys.ts +98 -0
- package/src/cli/main.ts +1 -1
- package/src/host/vice/session.ts +82 -8
- package/src/host-client/steps.ts +17 -17
- package/src/host-client/tools.ts +1 -1
- package/src/host-client/vice-session.ts +7 -1
- package/src/knowledge/read.ts +25 -1
- package/src/mcp/inputs.ts +12 -0
- package/src/mcp/server.ts +1 -0
- package/src/mcp/tools/input.ts +38 -5
- package/src/native/c64run.ts +1 -1
- package/src/native/discover.ts +3 -3
- package/src/native/ghidra/analyze.ts +74 -63
- package/src/native/ghidra/c64rt-wasm.ts +4 -0
- package/src/native/ghidra/language/c64rt_6510.sla +0 -0
- package/src/native/ghidra/pcode.ts +222 -0
- package/src/native/ghidra/walk.ts +205 -0
- package/src/native/ghidra/wasm.ts +98 -0
- package/src/native/processes.ts +4 -4
- package/src/native/types.ts +2 -2
- package/src/project.ts +4 -3
- package/src/protocol/vice.ts +47 -0
- package/src/script.ts +1 -1
- package/src/vsf.ts +98 -0
- package/tools/c64run.c +9 -12
- package/tools/install-container.sh +1 -2
- package/src/native/ghidra/index.ts +0 -170
- package/src/native/ghidra/scripts/C64Export.java +0 -274
- package/src/native/ghidra/scripts/C64Prepare.java +0 -66
- package/tools/install-ghidra.sh +0 -40
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@henols/c64-re-tools",
|
|
3
|
-
"version": "2.6.0-rc.
|
|
3
|
+
"version": "2.6.0-rc.9",
|
|
4
4
|
"description": "Agent-friendly Commodore 64 engineering toolkit for reverse engineering, debugging, development and testing.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Henrik Olsson",
|
|
@@ -34,7 +34,7 @@
|
|
|
34
34
|
"scripts": {
|
|
35
35
|
"host": "node src/host/main.ts",
|
|
36
36
|
"typecheck": "tsc -p tsconfig.json",
|
|
37
|
-
"test": "node
|
|
37
|
+
"test": "node test/run.ts"
|
|
38
38
|
},
|
|
39
39
|
"devDependencies": {
|
|
40
40
|
"@types/node": "24.13.3",
|
package/skills/c64-docs/SKILL.md
CHANGED
|
@@ -41,7 +41,7 @@ The documentation is Markdown in the project. It has two parts:
|
|
|
41
41
|
|
|
42
42
|
Get the values for the commands from these places:
|
|
43
43
|
|
|
44
|
-
- `<source-dir>` and `--source`: the folder of the source that you generated from the project knowledge, for example `src`. The source must be from the current revision of the project knowledge.
|
|
44
|
+
- `<source-dir>` and `--source`: the folder of the source that you generated from the project knowledge, for example `src`. The source must be from the current revision of the project knowledge in its space. A change in another space does not make the source old.
|
|
45
45
|
- `--out`: a folder that holds only the reference, for example `docs/reference`. Keep the pages that you write outside it.
|
|
46
46
|
- `<page>`: the entry page `README.md` and the folder of the other pages, for example `docs`.
|
|
47
47
|
- The program bytes: put them into the project knowledge before `generate`. Then the reference decodes the tables and shows the graphics.
|
|
@@ -14,7 +14,7 @@ import { writeProjectFile, writeReported } from "#src/host-client/transfer.ts";
|
|
|
14
14
|
import { conflicts } from "#src/knowledge/conflicts.ts";
|
|
15
15
|
import { openForRead } from "#src/knowledge/database.ts";
|
|
16
16
|
import { programImage, type ProgramImage } from "#src/knowledge/program.ts";
|
|
17
|
-
import {
|
|
17
|
+
import { listComments, listModules, listReferences, listRegions, listSymbols, sourceRevision } from "#src/knowledge/read.ts";
|
|
18
18
|
import { groupOf, namedGroup, projectRoot, resolveProjectFile, resolveProjectPath, type ProjectGroup } from "#src/project.ts";
|
|
19
19
|
import { listed, OPTIONS, reply, runScript, UsageError, type Call, type Reply } from "#src/script.ts";
|
|
20
20
|
import { checkLinks, linkPage, type Files, type LinkContext, type Names, type Problem } from "./lib/links.ts";
|
|
@@ -64,10 +64,10 @@ function generate(call: Call): Reply {
|
|
|
64
64
|
image = programImage(db, map.space);
|
|
65
65
|
const found = conflicts(db).length;
|
|
66
66
|
if (found > 0) throw new Refusal("conflict", `The knowledge has ${found} conflict${found === 1 ? "" : "s"} from a git merge. Nothing was written. Resolve the merge conflicts of the project knowledge. Then generate the source again from the knowledge, and run generate again.`);
|
|
67
|
-
|
|
68
|
-
|
|
67
|
+
// A source of another revision has other lines: the links would point to the wrong code. A change in another space does not change the source.
|
|
68
|
+
const revision = sourceRevision(db, map.space);
|
|
69
69
|
if (map.revision !== revision) {
|
|
70
|
-
throw new WireFailure("invalid-input", `${map.mapPath} is from knowledge revision ${map.revision}, and the knowledge is at revision ${revision}. Nothing was written. Generate the source again from the knowledge. Then run generate again.`);
|
|
70
|
+
throw new WireFailure("invalid-input", `${map.mapPath} is from knowledge revision ${map.revision}, and the knowledge of the source is at revision ${revision}. Nothing was written. Generate the source again from the knowledge. Then run generate again.`);
|
|
71
71
|
}
|
|
72
72
|
knowledge = {
|
|
73
73
|
revision,
|
|
@@ -266,13 +266,13 @@ function link(call: Call): Reply {
|
|
|
266
266
|
let symbols;
|
|
267
267
|
let revision;
|
|
268
268
|
try {
|
|
269
|
-
revision =
|
|
269
|
+
revision = sourceRevision(db, map.space);
|
|
270
270
|
symbols = listSymbols(db, undefined, undefined, undefined, map.space);
|
|
271
271
|
} finally {
|
|
272
272
|
db?.close();
|
|
273
273
|
}
|
|
274
274
|
if (map.revision !== revision) {
|
|
275
|
-
problems.push({ page: inProject(map.mapPath), line: 1, kind: "stale-reference", message: `The source${of} is from knowledge revision ${map.revision}, and the knowledge is at ${revision}. Generate the source and the reference again, then run docs.ts link.` });
|
|
275
|
+
problems.push({ page: inProject(map.mapPath), line: 1, kind: "stale-reference", message: `The source${of} is from knowledge revision ${map.revision}, and the knowledge of the source is at ${revision}. Generate the source and the reference again, then run docs.ts link.` });
|
|
276
276
|
}
|
|
277
277
|
const addresses = new Map<string, number>();
|
|
278
278
|
for (const label of map.labels) addresses.set(label.name, label.address);
|
|
@@ -73,7 +73,7 @@ The knowledge is text in `.c64-re-tools/knowledge/` of the project. Commit that
|
|
|
73
73
|
- An analyzer name is a second name from DXA, Ghidra or an idiom search, for example `FUN_17e2`. Each analyzer keeps its own name at an address. Get them from `at`, `search` or `symbols --analyzer`.
|
|
74
74
|
- The generated source uses only the symbols. To use an analyzer name in the source, give the address that name with `rename`.
|
|
75
75
|
- A symbol name is a label for ACME: a letter or an underscore, then letters, digits or underscores. The knowledge refuses the name of a 6502 instruction, for example `lda`, in upper or lower case.
|
|
76
|
-
- A space is `c64` (the default), `drive8` for code in the 1541 drive, `loading` or `bank0` to `bank255`. `loading` is the captured stage of the loading that shows the start screen. `bank0` to `bank255` are cartridge banks. Drive code, the stage and banks use the same addresses as the C64. Thus each space has its own knowledge. A name is unique in one space.
|
|
76
|
+
- A space is `c64` (the default), `drive8` for code in the 1541 drive, `loading` or `bank0` to `bank255`. `loading` is the captured stage of the loading that shows the start screen. `bank0` to `bank255` are cartridge banks, or other memory images of the program, for example a file that the program loads later. Drive code, the stage and banks use the same addresses as the C64. Thus each space has its own knowledge. A name is unique in one space.
|
|
77
77
|
- A revision id has the form `20261015T214501.123-k3f9qz`. It starts with the date and the time. Give the full id, or a start of the id that only one revision has. Get the ids from `revisions`, or from the `revision` field of a result. The revision `0` is the knowledge before the first revision.
|
|
78
78
|
- A file of a capture is the `image.json` that the capture of a packed program wrote. The other files of the capture must be next to it.
|
|
79
79
|
|
|
@@ -248,8 +248,8 @@ When a git merge left conflicts in the knowledge, each read body also has `confl
|
|
|
248
248
|
|
|
249
249
|
### `listing <range>`
|
|
250
250
|
|
|
251
|
-
- `body.lines`
|
|
252
|
-
- Each line has `address`, `bytes`, `text`, `referencesIn` and `referencesOut`. It can also have `label`, `analyzerNames` and `comment`.
|
|
251
|
+
- `body.lines` has `count` and `listed`. `listed` holds one line for each instruction of a code region, and one `!byte` line for other bytes.
|
|
252
|
+
- Each line has `address`, `bytes`, `text`, `referencesIn` and `referencesOut`. It can also have `label`, `analyzerNames`, `lineComments` and `comment`. `lineComments` are the line comments before the line. `comment` is the side comment.
|
|
253
253
|
- `text` is the instruction with the names of its target. An operand expression of the knowledge replaces the operand.
|
|
254
254
|
- When the knowledge has coverage, `access` tells if a run executed (`x`), read (`r`) or wrote (`w`) the bytes of the line, or `-` for none.
|
|
255
255
|
- With `--out`, the body has `lines` as a number, and `out`, `bytes` and `sha256` of the text file.
|
|
@@ -271,8 +271,10 @@ function listingSource(db: DatabaseSync | undefined, space: string): ListingSour
|
|
|
271
271
|
const coverage = programCoverage(db, space)?.map;
|
|
272
272
|
const inside = (at: number) => image.segments.some((segment) => at >= segment.start && at <= segment.end);
|
|
273
273
|
const platform = new Map(space === DEFAULT_SPACE ? platformNames().map((entry) => [entry.address, entry.name]) : []);
|
|
274
|
+
const entries = space === DEFAULT_SPACE ? platformNames().filter((entry) => entry.end > entry.address) : [];
|
|
274
275
|
return {
|
|
275
276
|
byteAt: (at) => (inside(at) ? image.byteAt(at) : undefined),
|
|
277
|
+
entryStart: (at) => (inside(at) ? undefined : entries.find((entry) => at > entry.address && at <= entry.end)?.address),
|
|
276
278
|
// A user or LLM name, else the platform name; an analyzer name in symbols (knowledge from an older version) gives way to it.
|
|
277
279
|
nameOf: (at) => {
|
|
278
280
|
const own = symbolAt(db, at, space);
|
|
@@ -11,6 +11,8 @@ export interface ListingSource {
|
|
|
11
11
|
byteAt: (address: number) => number | undefined;
|
|
12
12
|
/** The name of an address: a symbol, else a platform name. */
|
|
13
13
|
nameOf: (address: number) => string | undefined;
|
|
14
|
+
/** The start of the platform entry of more bytes that holds an address outside the image (NMINV for its high byte), or undefined. */
|
|
15
|
+
entryStart?: (address: number) => number | undefined;
|
|
14
16
|
/** The analyzer names of an address, for reference. */
|
|
15
17
|
secondNames: (address: number) => string[];
|
|
16
18
|
/** The knowledge regions, in address order. */
|
|
@@ -52,9 +54,22 @@ function accessOf(coverage: Uint8Array | undefined, start: number, length: numbe
|
|
|
52
54
|
return text === "" ? "-" : text;
|
|
53
55
|
}
|
|
54
56
|
|
|
57
|
+
/**
|
|
58
|
+
* The name of an operand target, as c64-source writes it: its own name, else
|
|
59
|
+
* name+offset inside a named data region, or inside a platform entry of more bytes.
|
|
60
|
+
*/
|
|
61
|
+
function targetName(target: number, source: ListingSource): string | undefined {
|
|
62
|
+
const own = source.nameOf(target);
|
|
63
|
+
if (own !== undefined) return own;
|
|
64
|
+
const region = source.regions.find((row) => target > row.start && target <= row.end && !CODE.has(row.type) && row.type !== "dual-use");
|
|
65
|
+
const start = region?.start ?? source.entryStart?.(target);
|
|
66
|
+
const name = start === undefined ? undefined : source.nameOf(start);
|
|
67
|
+
return name === undefined ? undefined : `${name}+${target - start!}`;
|
|
68
|
+
}
|
|
69
|
+
|
|
55
70
|
/** The operand value of an instruction as an expression: the name of its target where one exists, else the number. Empty for no operand. */
|
|
56
|
-
function operandOf(mode: Mode, address: number, low: number, high: number,
|
|
57
|
-
const named = (target: number, digits: 2 | 4) =>
|
|
71
|
+
function operandOf(mode: Mode, address: number, low: number, high: number, source: ListingSource): string {
|
|
72
|
+
const named = (target: number, digits: 2 | 4) => targetName(target, source) ?? (digits === 2 ? formatC64Byte(target) : formatC64Address(target));
|
|
58
73
|
if (mode === "imp") return "";
|
|
59
74
|
if (mode === "imm") return formatC64Byte(low);
|
|
60
75
|
if (mode === "rel") return named((address + 2 + (low < 0x80 ? low : low - 0x100)) & 0xffff, 4);
|
|
@@ -108,7 +123,7 @@ export function listing(source: ListingSource, start: number, end: number): List
|
|
|
108
123
|
const bytes = Array.from({ length: length - 1 }, (_, offset) => source.byteAt(address + 1 + offset));
|
|
109
124
|
if (address + length - 1 <= region.end && bytes.every((value) => value !== undefined)) {
|
|
110
125
|
// The operand expression of the knowledge in the syntax of the addressing mode, as c64-source writes it.
|
|
111
|
-
const operand = source.operand(address) ?? operandOf(opcode.mode, address, bytes[0] ?? 0, bytes[1] ?? 0, source
|
|
126
|
+
const operand = source.operand(address) ?? operandOf(opcode.mode, address, bytes[0] ?? 0, bytes[1] ?? 0, source);
|
|
112
127
|
if (address >= start) lines.push(line(address, length, instructionWith(byte, operand)));
|
|
113
128
|
address += length;
|
|
114
129
|
continue;
|
|
@@ -93,7 +93,7 @@ Do the stages in this sequence. Go to the next stage only when its exit check is
|
|
|
93
93
|
| 6. Analyze | Analyze the program statically. The analysis reads the program and the coverage from the project knowledge. | No coverage conflict is open. |
|
|
94
94
|
| 7. Name | If the workspace has a routine library, match the program against it. Write the names of the matches to the project knowledge. Then name each routine in the scope and give it a comment. Find the platform addresses in the memory map of the C64. Record the modules. Put the modules of one part of the program in one folder, for example `music/`, `irq/` or `graphics/`. When the scope has hundreds of routines, ask the user which routines to name. The source gives the other routines an `l_xxxx` label. | Each routine that the user selected has a name and a comment. |
|
|
95
95
|
| 8. Releases and switches | Record the original file, or the capture of it, as the base release in the project knowledge. The project knowledge keeps the bytes of each release. Record each other release. Compare the releases. Find the leftovers. Record a switch for each copy protection, trainer, cheat, crack change and correction. Record a patch for each range of a switch. Record each leftover as a region with a comment. | The project knowledge lists each switch. Each difference between the releases is in a patch, or the answer gives it as an exception. |
|
|
96
|
-
| 9. Generate | Generate the source from the project knowledge into `src`. For an unpacked program, also generate the loader. | The result of the generation is PASS.
|
|
96
|
+
| 9. Generate | Generate the source from the project knowledge into `src`. For an unpacked program, also generate the loader. | The result of the generation is PASS. A release whose code is at other addresses is a version with a project of its own, or an exception in the answer. See "Versions of one program". |
|
|
97
97
|
| 10. Build and test | Build the base release into `build/`, and compare it with the original. Build the default build. Run the test scenarios in `tests/`. Replay each recording on the rebuild. For each replay, give the checkpoint routine, the state and the random state with the names of stage 7. | The criteria of stage 1 are true. |
|
|
98
98
|
| 11. Document | When the criteria ask for documentation, generate it into `README.md` and `docs/`. For versions in a group folder, also write the shared pages of the group folder. Then link the pages. | The link check of the documentation gives PASS. |
|
|
99
99
|
| 12. Hand over | Find each file that you made outside `.c64-re-tools/local/` and that is not a deliverable. Move it into `.c64-re-tools/local/`. Then give the answer (below). | Each file that you made outside `.c64-re-tools/local/` is a deliverable. |
|
|
@@ -119,7 +119,7 @@ To make the source better, change the project knowledge. Then generate again.
|
|
|
119
119
|
- `patchesNotWritten`: each patch that the source does not have, with its range, `switch` and `reason`.
|
|
120
120
|
- `switches`, `default`, `releases`: the checks of the switches. See "Switches and releases".
|
|
121
121
|
- `loader`: the check of the loader. See "The loader".
|
|
122
|
-
- `staleLoader`: a run without `--loader` kept `loader.asm` and the loader program of another knowledge revision. `files` gives the files. `revision` gives the revision of `loader.asm`. Without `revision`, `loader.asm` does not give one. `noEntryState: true` tells that the knowledge has no entry state for a new loader.
|
|
122
|
+
- `staleLoader`: a run without `--loader` kept `loader.asm` and the loader program of another knowledge revision. `files` gives the files. `revision` gives the revision of `loader.asm`. Without `revision`, `loader.asm` does not give one. `noEntryState: true` tells that the knowledge has no entry state for a new loader. A change in a space that the loader does not hold does not make the loader stale. The loader holds space `c64` and the space of the stage of the start screen.
|
|
123
123
|
|
|
124
124
|
`result` is `FAIL` for each of these:
|
|
125
125
|
|
|
@@ -127,7 +127,7 @@ To make the source better, change the project knowledge. Then generate again.
|
|
|
127
127
|
- The entry is in no segment of the program.
|
|
128
128
|
- A patch is in `patchesNotWritten`.
|
|
129
129
|
- A switch or the default build does not fit.
|
|
130
|
-
- A release does not give its bytes.
|
|
130
|
+
- A release does not give its bytes.
|
|
131
131
|
- The loader is not verified.
|
|
132
132
|
|
|
133
133
|
`hint` gives the action for each finding. When a change of the project knowledge corrects a finding, `nextAction` is the same `generate` command. Run it after the change. A `PASS` without findings gives a `hint` and no `nextAction`.
|
|
@@ -195,7 +195,7 @@ Do these actions for the findings:
|
|
|
195
195
|
|
|
196
196
|
#### The leftovers
|
|
197
197
|
|
|
198
|
-
A leftover is a range of the program that nothing uses: unused code, old copies and old data. The script finds the leftovers from the coverage, as the export finds its free ranges (see "The free ranges"). The start screen, the patches
|
|
198
|
+
A leftover is a range of the program that nothing uses: unused code, old copies and old data. The script finds the leftovers from the coverage, as the export finds its free ranges (see "The free ranges"). The start screen, the patches and the addresses that the code of a patch names are never leftovers. A macro use in code that nothing uses is in the leftover with that code. A leftover never cuts a macro use in two.
|
|
199
199
|
|
|
200
200
|
- Each range of leftovers is a file `leftovers/leftover_xxxx.asm`. When a range cuts a module, the module continues after the range in `<module>_xxxx.asm`, in the folder of the module. The module in the knowledge does not change.
|
|
201
201
|
- `main.asm` builds a leftover file only when `LEFTOVERS` is 1. When it is 0, the build skips the bytes. Thus the addresses after the range do not change.
|
|
@@ -227,12 +227,12 @@ Each item of `switches` has `name`, `kind`, `default`, `base`, `define` and the
|
|
|
227
227
|
|
|
228
228
|
`default` has `in`, `result` and `changedBytes`, as in `switches`. When `default` has `overflow` and the message `turn on one of them`, two alternatives are in the default build. Give one of the switches the default of the base release.
|
|
229
229
|
|
|
230
|
-
Each item of `releases` has `label`, `base`, `define` and `result
|
|
230
|
+
Each item of `releases` has `label`, `base`, `define` and `result`. The check compares the build with each segment of the release. The build compare of the assembler does the same.
|
|
231
231
|
|
|
232
|
-
- `identical`: the build gives the bytes of the release.
|
|
232
|
+
- `identical`: the build gives the bytes of each segment of the release.
|
|
233
233
|
- `different`: the release has bytes that no patch gives. Compare the release with the program. Then record a switch and a patch for each difference.
|
|
234
|
-
- `layout differs`: the release has other segments than the program. Patches cannot move code. This result does not fail the run.
|
|
235
234
|
- `does not assemble`: read the ACME diagnostics.
|
|
235
|
+
- `notInRelease`: the ranges of the program that the release does not have. The check does not compare them.
|
|
236
236
|
|
|
237
237
|
The script writes a patch only when its range is complete items of one file. A patch cannot cut an instruction. Its switch name cannot be a name of the source.
|
|
238
238
|
The script writes a macro use only when the use gives the bytes of the program. A label inside the range of a use also keeps the instructions. The macro line has no place for the label.
|
|
@@ -274,7 +274,7 @@ The start screen:
|
|
|
274
274
|
- With a start screen, the copier uses three pages, not two.
|
|
275
275
|
- The start screen is part of the clean build only. The loader program always shows it. A release build has no start screen, and `LEFTOVERS = 1` also turns it off.
|
|
276
276
|
- To start the program at once, set `START_SCREEN = 0` in `config.asm`, and assemble `loader.asm`. Do not define `START_SCREEN` on the command line of the build: `config.asm` sets it.
|
|
277
|
-
- A test that runs the loader program stops at the start screen, because the
|
|
277
|
+
- A test that runs the loader program stops at the start screen, because the start screen waits for a key. Run until `loader_start_screen_wait`. Then set the PC to `loader_start_screen_continue`.
|
|
278
278
|
|
|
279
279
|
`loader` holds these fields:
|
|
280
280
|
|
|
@@ -561,6 +561,16 @@ export function layout(input: SourceInput): Layout {
|
|
|
561
561
|
}
|
|
562
562
|
}
|
|
563
563
|
}
|
|
564
|
+
// A macro line also uses the addresses that its instructions name besides its args, for example the high byte
|
|
565
|
+
// CUTHI of +mov16 CUTLO: a name of the source counts that use too. The args count as macro argument above.
|
|
566
|
+
for (const candidate of accepted) {
|
|
567
|
+
const argAddresses = new Set(candidate.use.args.flatMap((arg) => identifiers(arg)).map((name) => byName.get(name)));
|
|
568
|
+
for (const item of candidate.items) {
|
|
569
|
+
if (!takesAddress(OPCODES[item.opcode]!.mode)) continue;
|
|
570
|
+
const value = operandValue(item.address, item.opcode, input.byteAt)!;
|
|
571
|
+
if (!argAddresses.has(value) && uses.has(value)) tally(value, useKind(item.opcode));
|
|
572
|
+
}
|
|
573
|
+
}
|
|
564
574
|
|
|
565
575
|
const names = new Map<number, string>();
|
|
566
576
|
const taken = new Set([...knowledgeNames, ...platform.values()]);
|
|
@@ -25,7 +25,7 @@ import { conflicts } from "#src/knowledge/conflicts.ts";
|
|
|
25
25
|
import { openForRead, withWrite } from "#src/knowledge/database.ts";
|
|
26
26
|
import { identifiers } from "#src/knowledge/expression.ts";
|
|
27
27
|
import { analyzedBytes, memoryRows, programCoverage, releaseImage, requireProgram, type ProgramImage } from "#src/knowledge/program.ts";
|
|
28
|
-
import { ANALYZER_NAME_ORDER, baseValue, currentRevision, currentStartScreen, startScreenRanges, type StartScreenRow, listAnalyzerNames, listComments, listMacros, listMacroUses, listModules, listOperands, listPatches, listReferences, listRegions, listReleases, listSpaces, listSwitches, listSymbols, type ReleaseRow, type SymbolRow } from "#src/knowledge/read.ts";
|
|
28
|
+
import { ANALYZER_NAME_ORDER, baseValue, currentRevision, currentStartScreen, sourceRevision, startScreenRanges, type StartScreenRow, listAnalyzerNames, listComments, listMacros, listMacroUses, listModules, listOperands, listPatches, listReferences, listRegions, listReleases, listSpaces, listSwitches, listSymbols, type ReleaseRow, type SymbolRow } from "#src/knowledge/read.ts";
|
|
29
29
|
import { CODE_REGION_TYPES, DEFAULT_SPACE, isSemantic, LEFTOVER_FOLDER, LEFTOVERS_SWITCH, RELEASE_DEFINE, START_SCREEN_SWITCH, type Space } from "#src/knowledge/schema.ts";
|
|
30
30
|
import { subtract, write } from "#src/knowledge/write.ts";
|
|
31
31
|
import { assemble, symbolsFileText } from "#src/native/acme.ts";
|
|
@@ -92,8 +92,11 @@ function readKnowledge(space: Space, analyzerNames = false) {
|
|
|
92
92
|
const second = listAnalyzerNames(db, undefined, undefined, undefined, space);
|
|
93
93
|
const releases = listReleases(db, undefined, space);
|
|
94
94
|
const base = releases.find((release) => release.base)?.label;
|
|
95
|
+
const startScreen = space === DEFAULT_SPACE ? currentStartScreen(db, space) : undefined;
|
|
95
96
|
return {
|
|
96
97
|
revision: currentRevision(db),
|
|
98
|
+
// The source and its loader hold the program of this space and the stage of its start screen: a change elsewhere does not change them.
|
|
99
|
+
sourceRevision: sourceRevision(db, space),
|
|
97
100
|
program: requireProgram(db, space),
|
|
98
101
|
// The coverage of the space: a run of the C64, or of a captured stage that coverage put into that space.
|
|
99
102
|
coverage: programCoverage(db, space)?.map,
|
|
@@ -112,7 +115,7 @@ function readKnowledge(space: Space, analyzerNames = false) {
|
|
|
112
115
|
macros: listMacros(db, undefined, space),
|
|
113
116
|
macroUses: listMacroUses(db, undefined, undefined, undefined, space),
|
|
114
117
|
// The start screen is of the C64 program: the loader shows it.
|
|
115
|
-
startScreen
|
|
118
|
+
startScreen,
|
|
116
119
|
};
|
|
117
120
|
} finally {
|
|
118
121
|
db?.close();
|
|
@@ -484,28 +487,27 @@ interface ReleaseCheck {
|
|
|
484
487
|
label: string;
|
|
485
488
|
base: boolean;
|
|
486
489
|
define: string;
|
|
487
|
-
result: "identical" | "different" | "
|
|
488
|
-
reason?: string;
|
|
490
|
+
result: "identical" | "different" | "does not assemble";
|
|
489
491
|
segments?: SegmentCheck[];
|
|
492
|
+
/** The ranges of the program that the release does not have: the check does not compare them. */
|
|
493
|
+
notInRelease?: Array<{ start: string; end: string }>;
|
|
490
494
|
diagnostics?: Diagnostic[];
|
|
491
495
|
}
|
|
492
496
|
|
|
493
497
|
/**
|
|
494
|
-
* Builds a release with RELEASE_<label> and compares it with its bytes
|
|
495
|
-
*
|
|
496
|
-
*
|
|
498
|
+
* Builds a release with RELEASE_<label> and compares it with its bytes, in
|
|
499
|
+
* each segment of the release, as the build compare of the assembler does. A
|
|
500
|
+
* part of the program that the release does not have is listed, not compared.
|
|
497
501
|
*/
|
|
498
502
|
async function checkRelease(release: ReleaseRow & { image: Pick<ProgramImage, "segments" | "byteAt"> }, files: Array<{ name: string; text: string }>, program: ProgramImage): Promise<ReleaseCheck> {
|
|
499
503
|
const shown = { label: release.label, base: release.base, define: `--define ${RELEASE_DEFINE}${release.label}=1` };
|
|
500
504
|
const { image } = release;
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
return { ...shown, result: "layout differs", reason: `The release has the segments ${segments(image.segments)}, and the program has ${segments(program.segments)}. Patches change bytes in place; they cannot move code.` };
|
|
504
|
-
}
|
|
505
|
+
const missing = program.segments.flatMap((segment) => subtract(segment, [...image.segments])).map((range) => ({ start: formatC64Address(range.start), end: formatC64Address(range.end) }));
|
|
506
|
+
const notInRelease = missing.length === 0 ? {} : { notInRelease: missing };
|
|
505
507
|
const built = await assembleFiles(files, "main.asm", { [`${RELEASE_DEFINE}${release.label}`]: 1 });
|
|
506
|
-
if (built.program === undefined) return { ...shown, result: "does not assemble", diagnostics: built.diagnostics.slice(0, MAX_DIAGNOSTICS) };
|
|
508
|
+
if (built.program === undefined) return { ...shown, result: "does not assemble", diagnostics: built.diagnostics.slice(0, MAX_DIAGNOSTICS), ...notInRelease };
|
|
507
509
|
const checked = check(built.program, built.start!, image);
|
|
508
|
-
return { ...shown, result: checked.identical ? "identical" : "different", ...(checked.identical ? {} : { segments: checked.segments.filter((segment) => segment.result !== "identical") }) };
|
|
510
|
+
return { ...shown, result: checked.identical ? "identical" : "different", ...(checked.identical ? {} : { segments: checked.segments.filter((segment) => segment.result !== "identical") }), ...notInRelease };
|
|
509
511
|
}
|
|
510
512
|
|
|
511
513
|
/** Reads RAM in parts. */
|
|
@@ -568,8 +570,8 @@ async function runLoader(path: string, program: Buffer, plan: LoaderPlan, state:
|
|
|
568
570
|
const port01 = `$${port.toString(16).padStart(2, "0")}`;
|
|
569
571
|
return { verified: false, differences: [`The loader did not get to ${what}; it stopped at ${formatC64Address(pc)}.`], stop: { pc: formatC64Address(pc), port: port01, ...(cause === undefined ? {} : { cause }), history } };
|
|
570
572
|
};
|
|
571
|
-
// The start screen waits for a key or a fire button.
|
|
572
|
-
//
|
|
573
|
+
// The start screen waits for a key or a fire button. Not each VICE can press a key of the keyboard matrix,
|
|
574
|
+
// so the check lets it wait, then sets the PC to the code after the wait.
|
|
573
575
|
let screen: LoaderRun["startScreen"];
|
|
574
576
|
const screenDifferences: string[] = [];
|
|
575
577
|
const showScreen = async (at: { wait: number; continue: number }, wanted: StartScreenPlan, frames: number, copied: boolean, parts: readonly StagePart[] = [], colourRam?: Uint8Array): Promise<LoaderRun | undefined> => {
|
|
@@ -713,7 +715,7 @@ function loaderPrograms(): string[] {
|
|
|
713
715
|
.filter((path) => existsSync(resolveProjectPath(path)));
|
|
714
716
|
}
|
|
715
717
|
|
|
716
|
-
/** The start of the line of loader.asm that gives the knowledge revision of the loader. */
|
|
718
|
+
/** The start of the line of loader.asm that gives the newest knowledge revision of the spaces that the loader holds. */
|
|
717
719
|
const LOADER_REVISION = "Loader generated by c64-source from knowledge revision ";
|
|
718
720
|
|
|
719
721
|
/**
|
|
@@ -1137,8 +1139,8 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
|
|
|
1137
1139
|
const given = existsSync(configPath) ? configValues(readFileSync(configPath, "utf8")) : new Map<string, 0 | 1>();
|
|
1138
1140
|
const configNames = new Set([...knowledge.switches.map((row) => row.name), START_SCREEN_SWITCH, LEFTOVERS_SWITCH]);
|
|
1139
1141
|
const loaderValues = new Map([...given].filter(([name]) => configNames.has(name)));
|
|
1140
|
-
const header = [`Generated by c64-source from knowledge revision ${knowledge.
|
|
1141
|
-
const loaderHeader = [`${LOADER_REVISION}${knowledge.
|
|
1142
|
+
const header = [`Generated by c64-source from knowledge revision ${knowledge.sourceRevision}${space === DEFAULT_SPACE ? "" : ` in space ${space}`}.`, "Change names, comments, regions and modules in knowledge, then generate again."];
|
|
1143
|
+
const loaderHeader = [`${LOADER_REVISION}${knowledge.sourceRevision}.`, "It copies the segments into place, sets the entry state and jumps to the entry."];
|
|
1142
1144
|
const { romUse, dataOnly, laid, rendered, files, built, loader, loaderMain, missingEntry, loaderRefused } = await buildSource(knowledge, {
|
|
1143
1145
|
space,
|
|
1144
1146
|
entries,
|
|
@@ -1158,11 +1160,11 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
|
|
|
1158
1160
|
// Read before the old files go: the leftovers of the earlier run, to tell what changed.
|
|
1159
1161
|
const earlier = earlierLeftovers(out);
|
|
1160
1162
|
const removed = removeOldFiles(out, new Set(files.map((file) => file.name)), loaderWanted);
|
|
1161
|
-
const stale = loaderWanted || space !== DEFAULT_SPACE ? undefined : staleLoader(out, knowledge.
|
|
1163
|
+
const stale = loaderWanted || space !== DEFAULT_SPACE ? undefined : staleLoader(out, knowledge.sourceRevision);
|
|
1162
1164
|
const written: Written[] = withValues(files, laid, kept).map((file) => writeReported(`${out}/${file.name}`, file.text, { what: "--out" }));
|
|
1163
1165
|
// The reports go to the local folder: the source folder holds only source files.
|
|
1164
1166
|
const reports = generatedDirectory(projectRelative(out));
|
|
1165
|
-
written.push(writeReported(`${reports}/${SOURCE_MAP_FILE}`, sourceMapText(rendered, space, knowledge.
|
|
1167
|
+
written.push(writeReported(`${reports}/${SOURCE_MAP_FILE}`, sourceMapText(rendered, space, knowledge.sourceRevision, files)));
|
|
1166
1168
|
const showRange = (range: AddressRange) => ({ start: formatC64Address(range.start), end: formatC64Address(range.end) });
|
|
1167
1169
|
const inData = entriesInData(entries, knowledge.regions);
|
|
1168
1170
|
if (rendered.notExecuted !== undefined) {
|
|
@@ -1175,7 +1177,7 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
|
|
|
1175
1177
|
});
|
|
1176
1178
|
const files: Record<string, number> = {};
|
|
1177
1179
|
for (const range of placed) if (range.file !== undefined) files[range.file] = (files[range.file] ?? 0) + 1;
|
|
1178
|
-
const all = { revision: knowledge.
|
|
1180
|
+
const all = { revision: knowledge.sourceRevision, instructions: rendered.notExecuted.instructions, files, ranges: placed };
|
|
1179
1181
|
written.push(writeReported(`${reports}/${NOT_EXECUTED_FILE}`, `${JSON.stringify(all, null, 2)}\n`));
|
|
1180
1182
|
}
|
|
1181
1183
|
// The leftovers that changed since the earlier run: the default build and the loader now leave out other bytes.
|
|
@@ -1279,7 +1281,7 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
|
|
|
1279
1281
|
const releases: ReleaseCheck[] = [];
|
|
1280
1282
|
for (const release of knowledge.releases) releases.push(await checkRelease(release, files, image));
|
|
1281
1283
|
if (releases.length > 0) output.releases = releases;
|
|
1282
|
-
const releasesFailed = releases.some((item) => item.result !== "identical"
|
|
1284
|
+
const releasesFailed = releases.some((item) => item.result !== "identical");
|
|
1283
1285
|
const sourceFailed = laid.patchesNotWritten.length > 0 || switches.some((item) => item.result !== "fits") || defaultFailed || releasesFailed;
|
|
1284
1286
|
if (loaderRefused !== undefined) return { output: { ...output, loader: notVerified({ reason: loaderRefused }) }, removed, failed: true };
|
|
1285
1287
|
if (loader === undefined || loaderMain === undefined || state === undefined) return { output, removed, failed: missingEntry !== undefined || sourceFailed };
|
|
@@ -1467,9 +1469,12 @@ function leftoversOf(knowledge: SourceKnowledge, instructions: ReadonlyMap<numbe
|
|
|
1467
1469
|
const addressOf = new Map(knowledge.symbols.map((symbol) => [symbol.name, symbol.address]));
|
|
1468
1470
|
const screenParts = knowledge.startScreen === undefined || knowledge.startScreen.stage !== undefined ? [] : startScreenRanges(knowledge.startScreen).map((part) => part.range);
|
|
1469
1471
|
const named = knowledge.patches.flatMap((patch) => patchTargets(patch.code, addressOf)).map((address) => ({ start: address, end: address }));
|
|
1470
|
-
const keep = [...screenParts, ...kept, ...
|
|
1472
|
+
const keep = [...screenParts, ...kept, ...named].map((range) => ({ start: range.start, end: range.end })).filter(inImage);
|
|
1471
1473
|
const changed = knowledge.patches.map((patch) => ({ start: patch.start, end: patch.end })).filter(inImage);
|
|
1472
|
-
|
|
1474
|
+
const free = freeRanges(knowledge, image.memory, instructions, { changed, keep, drop: [] }).free.map((range) => ({ start: range.start, end: range.end }));
|
|
1475
|
+
// A macro use in code that nothing uses goes with that code. A leftover never cuts a use in two: its edge stops at the use.
|
|
1476
|
+
const cut = (range: AddressRange) => knowledge.macroUses.filter((use) => use.start <= range.end && range.start <= use.end && (use.start < range.start || use.end > range.end));
|
|
1477
|
+
return free.flatMap((range) => subtract(range, cut(range)));
|
|
1473
1478
|
}
|
|
1474
1479
|
|
|
1475
1480
|
/** Every file in a folder with its path in it, with / between the parts, in path order. `skip` leaves out a folder by its path. */
|
|
@@ -1752,9 +1757,9 @@ function generateReply(call: Call, body: Record<string, unknown>): Reply {
|
|
|
1752
1757
|
steps.push("Read the reason of each item in patchesNotWritten, and the result of each switch and of the default build. Correct the patches and the switches in the project knowledge.");
|
|
1753
1758
|
again = true;
|
|
1754
1759
|
}
|
|
1755
|
-
const releases = body.releases as Array<{ result: string
|
|
1756
|
-
if (releases?.some((item) => item.result !== "identical"
|
|
1757
|
-
steps.push("Read the result of each release.
|
|
1760
|
+
const releases = body.releases as Array<{ result: string }> | undefined;
|
|
1761
|
+
if (releases?.some((item) => item.result !== "identical") === true) {
|
|
1762
|
+
steps.push("Read the result of each release. Record a switch and a patch in the project knowledge for each difference.");
|
|
1758
1763
|
again = true;
|
|
1759
1764
|
}
|
|
1760
1765
|
if ((body.loader as { verified?: boolean } | undefined)?.verified === false) steps.push("The loader is not verified. Read loader.reason, loader.differences and loader.stop.");
|
|
@@ -30,6 +30,7 @@ To get the command list, run the script with no arguments.
|
|
|
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
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
|
---
|
|
@@ -87,6 +88,7 @@ Each flag applies only to the commands in the table. On another command, the scr
|
|
|
87
88
|
| `--out-listing <file>` | `analyze` | DXA only. Write the disassembly listing to this project file. There is no default. |
|
|
88
89
|
| `--out-instructions <file>` | `analyze` | Ghidra only. Write each instruction to this project file as JSON. There is no default. |
|
|
89
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
|
|
|
@@ -127,7 +129,7 @@ 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
|
-
- `macros` has candidates, and the run had no `--apply-macros`. Examine the candidates. To write
|
|
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.
|
|
131
133
|
- A list is cut. Give a larger `--max-listed`. The project knowledge has all `labels` and `functions` as analyzer names.
|
|
132
134
|
|
|
133
135
|
There is no `nextAction`.
|
|
@@ -140,7 +142,7 @@ The script does not record the candidates. Examine each candidate and decide.
|
|
|
140
142
|
- `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
143
|
- `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
144
|
- `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
|
|
145
|
+
- `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 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
146
|
|
|
145
147
|
#### Which facts the analysis replaces
|
|
146
148
|
|
|
@@ -165,7 +167,7 @@ The script does not record the candidates. Examine each candidate and decide.
|
|
|
165
167
|
- `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
168
|
- `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
169
|
- `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
|
|
170
|
+
- `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
171
|
|
|
170
172
|
#### Failures
|
|
171
173
|
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
// with a coverage file, whether the instruction ran.
|
|
4
4
|
|
|
5
5
|
import { COVERAGE, formatC64Address } from "#src/c64.ts";
|
|
6
|
+
import { OPCODES, type Mode as OpcodeMode } from "#src/opcodes.ts";
|
|
6
7
|
import type { GhidraInstruction } from "#src/native/types.ts";
|
|
7
8
|
|
|
8
9
|
export type Mode =
|
|
@@ -20,26 +21,27 @@ export type Mode =
|
|
|
20
21
|
| "(indirect),y"
|
|
21
22
|
| "relative";
|
|
22
23
|
|
|
23
|
-
|
|
24
|
-
const
|
|
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
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
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. */
|
|
@@ -90,7 +92,7 @@ export interface ListedInstruction {
|
|
|
90
92
|
export function instructionList(instructions: GhidraInstruction[], coverage?: Uint8Array): ListedInstruction[] {
|
|
91
93
|
return instructions.map((instruction) => {
|
|
92
94
|
const bytes = Buffer.from(instruction.bytes, "hex");
|
|
93
|
-
const mode = modeOf(bytes[0]
|
|
95
|
+
const mode = modeOf(bytes[0]!);
|
|
94
96
|
const [target] = instruction.flows;
|
|
95
97
|
return {
|
|
96
98
|
address: formatC64Address(instruction.address),
|
|
@@ -75,11 +75,11 @@ function showMacro(candidate: MacroCandidate) {
|
|
|
75
75
|
* the ROMs that the program uses, as c64-source names them. A candidate is left out when
|
|
76
76
|
* a name or a reference target is inside it, or a patch or a use overlaps it:
|
|
77
77
|
* c64-source would write its instructions. The same use in the knowledge is
|
|
78
|
-
* known. The writes are the candidates with the macros they need
|
|
79
|
-
*
|
|
80
|
-
* candidates out of the writes.
|
|
78
|
+
* known. The writes are the candidates with the macros they need, without the
|
|
79
|
+
* candidates that start at an address of `skip`. A macro of the catalogue that
|
|
80
|
+
* the knowledge has with another body leaves its candidates out of the writes.
|
|
81
81
|
*/
|
|
82
|
-
function macroCandidates(space: string, byteAt: ImageByte, romUse: RomUse) {
|
|
82
|
+
function macroCandidates(space: string, byteAt: ImageByte, romUse: RomUse, skip: ReadonlySet<number>) {
|
|
83
83
|
const db = openForRead();
|
|
84
84
|
try {
|
|
85
85
|
// The platform names that c64-source uses: a name of a ROM that the program does not use is no arg.
|
|
@@ -104,28 +104,23 @@ function macroCandidates(space: string, byteAt: ImageByte, romUse: RomUse) {
|
|
|
104
104
|
const macros = new Map(listMacros(db, undefined, space).map((macro) => [macro.name, macro]));
|
|
105
105
|
const writes: BatchOperation[] = [];
|
|
106
106
|
const other = new Set<string>();
|
|
107
|
-
|
|
107
|
+
const chosen = candidates.filter((candidate) => !skip.has(candidate.start));
|
|
108
|
+
for (const idiom of CATALOGUE.filter((item) => chosen.some((candidate) => candidate.macro === item.name))) {
|
|
108
109
|
const existing = macros.get(idiom.name);
|
|
109
110
|
if (existing === undefined) writes.push({ op: "macro", space, name: idiom.name, params: [...idiom.params], body: idiom.body, comment: idiom.comment });
|
|
110
111
|
else if (existing.params.join(",") !== idiom.params.join(",") || existing.body !== idiom.body) other.add(idiom.name);
|
|
111
112
|
}
|
|
112
|
-
for (const candidate of
|
|
113
|
+
for (const candidate of chosen) {
|
|
113
114
|
if (other.has(candidate.macro)) continue;
|
|
114
115
|
writes.push({ op: "use", space, start: candidate.start, end: candidate.end, macro: candidate.macro, args: candidate.args });
|
|
115
116
|
}
|
|
116
|
-
|
|
117
|
+
const notCandidates = [...skip].filter((address) => !candidates.some((candidate) => candidate.start === address)).sort((a, b) => a - b);
|
|
118
|
+
return { candidates, known, leftOut, writes, skipped: candidates.length - chosen.length, notCandidates, otherMacros: [...other].map((name) => `The knowledge has another macro ${name}: its candidates are not written.`) };
|
|
117
119
|
} finally {
|
|
118
120
|
db?.close();
|
|
119
121
|
}
|
|
120
122
|
}
|
|
121
123
|
|
|
122
|
-
/** A decompiler that did not start gets the remedy: Ghidra ships no native decompiler for macOS. */
|
|
123
|
-
function withRemedy(reason: string): string {
|
|
124
|
-
return reason.startsWith("the Ghidra decompiler did not start")
|
|
125
|
-
? `${reason} On macOS, build the native decompiler once: in <Ghidra>/support/gradle run ./gradlew buildNatives.`
|
|
126
|
-
: reason;
|
|
127
|
-
}
|
|
128
|
-
|
|
129
124
|
/** One conflict: what the knowledge has, and what the analyzer found, under the analyzer's name. */
|
|
130
125
|
function showConflict(conflict: ImportConflict, analyzer: Analyzer): Record<string, unknown> {
|
|
131
126
|
if (conflict.category === "code-evidence") {
|
|
@@ -184,6 +179,8 @@ async function analyze(call: Call): Promise<unknown> {
|
|
|
184
179
|
const listingPath = call.string("out-listing");
|
|
185
180
|
const instructionsPath = call.string("out-instructions");
|
|
186
181
|
const applyMacros = call.flag("apply-macros");
|
|
182
|
+
const skip = new Set(call.addresses("skip"));
|
|
183
|
+
if (skip.size > 0 && !applyMacros) throw new UsageError("--skip works only with --apply-macros: it names a macro candidate that the run does not write");
|
|
187
184
|
if (analyzer === "dxa" && decompile.length > 0) throw new UsageError("--decompile works only with --analyzer ghidra");
|
|
188
185
|
if (analyzer === "ghidra" && listingPath !== undefined) throw new UsageError("--out-listing works only with --analyzer dxa");
|
|
189
186
|
if (analyzer === "dxa" && instructionsPath !== undefined) throw new UsageError("--out-instructions works only with --analyzer ghidra");
|
|
@@ -230,7 +227,7 @@ async function analyze(call: Call): Promise<unknown> {
|
|
|
230
227
|
const idiomsResult = () => {
|
|
231
228
|
const imported = withWrite((db) => importFindings(db, { ...idioms.findings, space }, { description: "Idioms in the program" }));
|
|
232
229
|
// The macro candidates read the code regions after both imports.
|
|
233
|
-
const macros = macroCandidates(space, byteAt, romUseOfProgram(coverage, program.state));
|
|
230
|
+
const macros = macroCandidates(space, byteAt, romUseOfProgram(coverage, program.state), skip);
|
|
234
231
|
// With --apply-macros, the candidates and their macros are a third revision of the LLM.
|
|
235
232
|
const platformNamed = new Map(platformNames().map((entry) => [entry.name, entry.address]));
|
|
236
233
|
const written = applyMacros && macros.writes.length > 0 ? withWrite((db) => applyBatch(db, { origin: "llm", description: "Macro candidates in the program", image: operandImages(db, platformNamed) }, macros.writes)) : undefined;
|
|
@@ -260,6 +257,8 @@ async function analyze(call: Call): Promise<unknown> {
|
|
|
260
257
|
...(macros.known === 0 ? {} : { known: macros.known }),
|
|
261
258
|
...(macros.leftOut === 0 ? {} : { leftOut: macros.leftOut }),
|
|
262
259
|
...(written === undefined ? {} : { revision: written.revision, writes: macros.writes.length }),
|
|
260
|
+
...(macros.skipped === 0 ? {} : { skipped: macros.skipped }),
|
|
261
|
+
...(macros.notCandidates.length === 0 ? {} : { notCandidates: macros.notCandidates.map(formatC64Address) }),
|
|
263
262
|
...(macros.otherMacros.length === 0 ? {} : { otherMacros: macros.otherMacros }),
|
|
264
263
|
},
|
|
265
264
|
},
|
|
@@ -340,7 +339,7 @@ async function analyze(call: Call): Promise<unknown> {
|
|
|
340
339
|
decompilations: result.decompilations.map((item) => ({ entry: formatC64Address(item.entry), text: item.text, ...(item.truncated ? { truncated: true } : {}) })),
|
|
341
340
|
...((result.notDecompiled ?? []).length === 0
|
|
342
341
|
? {}
|
|
343
|
-
: { notDecompiled: result.notDecompiled!.map((item) => ({ entry: formatC64Address(item.entry), reason:
|
|
342
|
+
: { notDecompiled: result.notDecompiled!.map((item) => ({ entry: formatC64Address(item.entry), reason: item.reason })) }),
|
|
344
343
|
};
|
|
345
344
|
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 });
|
|
346
345
|
}
|
|
@@ -362,6 +361,7 @@ await runScript({
|
|
|
362
361
|
"out-listing": { kind: "path", output: "file", value: "<file>", help: "dxa: write the disassembly listing to this project file" },
|
|
363
362
|
"out-instructions": { kind: "path", output: "file", value: "<file>", help: "ghidra: write every instruction (address, bytes, mnemonic, mode, operand, target, executed) to this project file as JSON" },
|
|
364
363
|
"apply-macros": { kind: "flag", help: "write the macro candidates (the macros and their uses) to the project knowledge as one revision of the LLM" },
|
|
364
|
+
skip: { kind: "address", value: "<address>", multiple: true, help: "with --apply-macros: the start of a macro candidate that is not correct. The run does not write it" },
|
|
365
365
|
},
|
|
366
366
|
notes: "The program and the coverage come from the project knowledge: put them into the project knowledge first. The executed code of the coverage gives entry points. Routine symbols in the knowledge are entry points too. Ghidra needs at least one entry point. DXA finds the SYS of a BASIC start by itself.",
|
|
367
367
|
run: analyze,
|