@henols/c64-re-tools 2.6.0-rc.12 → 2.6.0-rc.14
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 +1 -1
- package/skills/c64-docs/scripts/lib/reference.ts +1 -1
- package/skills/c64-knowledge/SKILL.md +4 -4
- package/skills/c64-knowledge/scripts/knowledge.ts +2 -2
- package/skills/c64-source/SKILL.md +2 -2
- package/skills/c64-source/scripts/lib/export.ts +1 -1
- package/skills/c64-source/scripts/lib/source.ts +4 -4
- package/skills/c64-source/scripts/source.ts +13 -13
- package/skills/c64-static-analysis/SKILL.md +21 -20
- package/skills/c64-static-analysis/scripts/lib/findings.ts +11 -11
- package/skills/c64-static-analysis/scripts/lib/instructions.ts +4 -4
- package/skills/c64-static-analysis/scripts/static-analysis.ts +34 -27
- package/skills/c64-testing/SKILL.md +1 -1
- package/skills/c64-testing/scripts/testing.ts +3 -3
- package/src/c64.ts +1 -1
- package/src/host/tools/index.ts +1 -1
- package/src/host-client/tools.ts +1 -1
- package/src/knowledge/import.ts +12 -5
- package/src/knowledge/program.ts +1 -1
- package/src/knowledge/read.ts +3 -3
- package/src/knowledge/schema.ts +3 -3
- package/src/native/{ghidra → decompiler}/analyze.ts +17 -17
- package/src/native/{ghidra → decompiler}/language/c64rt_6510.slaspec +1 -1
- package/src/native/{ghidra → decompiler}/walk.ts +6 -6
- package/src/native/types.ts +25 -25
- package/src/opcodes.ts +1 -1
- package/src/script.ts +1 -1
- /package/src/native/{ghidra → decompiler}/c64rt-wasm.ts +0 -0
- /package/src/native/{ghidra → decompiler}/language/c64rt_6510.cspec +0 -0
- /package/src/native/{ghidra → decompiler}/language/c64rt_6510.ldefs +0 -0
- /package/src/native/{ghidra → decompiler}/language/c64rt_6510.pspec +0 -0
- /package/src/native/{ghidra → decompiler}/language/c64rt_6510.sla +0 -0
- /package/src/native/{ghidra → decompiler}/pcode.ts +0 -0
- /package/src/native/{ghidra → decompiler}/wasm.ts +0 -0
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.14",
|
|
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",
|
|
@@ -46,7 +46,7 @@ const MAX_LISTED = 40;
|
|
|
46
46
|
const MAX_EDGES = 60;
|
|
47
47
|
/** A name outside the image covers the addresses that references use up to the next name, at most this many. */
|
|
48
48
|
const MAX_SPAN = 256;
|
|
49
|
-
/** The kinds of a reference that reads a table:
|
|
49
|
+
/** The kinds of a reference that reads a table: the decompiler gives an indexed read (lda table,x) as "reference". */
|
|
50
50
|
const TABLE_READS: readonly string[] = ["read", "reference", "pointer"];
|
|
51
51
|
|
|
52
52
|
const hex = (address: number) => formatC64Address(address).toUpperCase();
|
|
@@ -70,7 +70,7 @@ The knowledge is text in `.c64-re-tools/knowledge/` of the project. Commit that
|
|
|
70
70
|
## Addresses, names and spaces
|
|
71
71
|
|
|
72
72
|
- A symbol is the name of an address from the user or the LLM. Get it from `at`, `search` or `symbols`.
|
|
73
|
-
- An analyzer name is a second name from DXA,
|
|
73
|
+
- An analyzer name is a second name from DXA, the decompiler 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
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.
|
|
@@ -113,7 +113,7 @@ Each flag applies only to the commands in the table. On another command, the scr
|
|
|
113
113
|
| `--evidence <kind:ref>` | `join` | With `--apply`: the same as for the commands in "Change the knowledge". |
|
|
114
114
|
| `--expect-revision <revision>` | `join` | With `--apply`: the same as for the commands in "Change the knowledge". |
|
|
115
115
|
| `--range <start>-<end>` | `symbols`, `regions`, `comments`, `references`, `suppressions`, `modules`, `operands`, `patches`, `uses`, `export` | Only the rows in this range. The default is all addresses. |
|
|
116
|
-
| `--origin <origin>` | `search`, `symbols`, `regions`, `comments`, `references`, `modules`, `operands`, `patches`, `macros`, `uses`, `export` | Only the rows of these origins: `user`, `llm`, `dxa`, `
|
|
116
|
+
| `--origin <origin>` | `search`, `symbols`, `regions`, `comments`, `references`, `modules`, `operands`, `patches`, `macros`, `uses`, `export` | Only the rows of these origins: `user`, `llm`, `dxa`, `decompiler`, `heuristic`, `semantic` (user and llm), `analyzer` (dxa, decompiler and heuristic), or a comma list. The default is all origins. |
|
|
117
117
|
| `--max-listed <n>` | `search`, `symbols`, `regions`, `comments`, `references`, `suppressions`, `modules`, `operands`, `patches`, `switches`, `releases`, `macros`, `uses`, `spaces`, `history`, `revisions`, `revision`, `listing`, `join` | The most items in each list of the body. The default is 50. The counts are always complete. |
|
|
118
118
|
| `--kind <kind>` | `symbols`, `rename` | The symbol kind: `label`, `routine`, `variable`, `data` or `vector`. A read gives all kinds by default. A new symbol without `--kind` is a `label`. A `rename` without `--kind` keeps the kind of the symbol. |
|
|
119
119
|
| `--kind <kind>` | `references` | Only references of this kind: `call`, `jump`, `read`, `write`, `reference` or `pointer`. |
|
|
@@ -200,7 +200,7 @@ When a git merge left conflicts in the knowledge, each read body also has `confl
|
|
|
200
200
|
### `suppressions`
|
|
201
201
|
|
|
202
202
|
- `body.suppressions` lists the places that a removal blocks. Each item has `suppresses` (`symbol`, `region` or `reference`), the place, and the `reason` of the removal.
|
|
203
|
-
- `unclassify` and `unreference` block the place for DXA and
|
|
203
|
+
- `unclassify` and `unreference` block the place for DXA and the decompiler. A later analysis does not add a region in that range or that reference again. This is also true for a fact from the LLM.
|
|
204
204
|
- `remove-symbol` does not block the address, because an analyzer name never becomes a symbol.
|
|
205
205
|
- A `rename`, `classify` or `reference` at a blocked place ends the block there. A `revert` to a revision before the removal also ends the block.
|
|
206
206
|
- `at` and `history` also show the blocks.
|
|
@@ -251,7 +251,7 @@ When a git merge left conflicts in the knowledge, each read body also has `confl
|
|
|
251
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
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
|
+
- `access` is there when the knowledge has coverage. It tells if a run executed (`x`), read (`r`) or wrote (`w`) the bytes of the line. `-` tells that no run did. An `r` on code can come from a read of the 6502 that the program does not do. Examples are the byte after an RTS and the opcode after a branch that the CPU takes. Another example is the opcode at the PC when an interrupt starts.
|
|
255
255
|
- With `--out`, the body has `lines` as a number, and `out`, `bytes` and `sha256` of the text file.
|
|
256
256
|
- If the knowledge has no program in the space, the script refuses. Put the program in with `image` first.
|
|
257
257
|
- Use `listing` in place of your own disassembler.
|
|
@@ -299,7 +299,7 @@ function listingSource(db: DatabaseSync | undefined, space: string): ListingSour
|
|
|
299
299
|
/** Every value of --origin, for the message of a wrong one. */
|
|
300
300
|
const ORIGIN_VALUES = `one of ${ORIGINS.join(", ")}, semantic or analyzer, or a comma list of them. semantic is ${SEMANTIC_ORIGINS.join(" and ")}. analyzer is ${ANALYZERS.slice(0, -1).join(", ")} and ${ANALYZERS.at(-1)}`;
|
|
301
301
|
|
|
302
|
-
/** --origin for reads: one origin, semantic (user and llm), analyzer (dxa,
|
|
302
|
+
/** --origin for reads: one origin, semantic (user and llm), analyzer (dxa, decompiler and heuristic), or a comma list. */
|
|
303
303
|
function originFilter(value: string): Origin[] {
|
|
304
304
|
const origins = new Set<Origin>();
|
|
305
305
|
for (const part of value.split(",")) {
|
|
@@ -558,7 +558,7 @@ const READ_COMMANDS: CommandSpec[] = [
|
|
|
558
558
|
},
|
|
559
559
|
),
|
|
560
560
|
readCommand(
|
|
561
|
-
{ name: "symbols", summary: "The symbols, or with --analyzer the second names that DXA,
|
|
561
|
+
{ name: "symbols", summary: "The symbols, or with --analyzer the second names that DXA, the decompiler and the idioms gave.", options: { ...FILTER, kind: SYMBOL_KIND, analyzer: { kind: "flag", help: "the analyzer names in place of the symbols" }, ...LIST } },
|
|
562
562
|
(db, call) => {
|
|
563
563
|
const kind = call.string("kind") as (typeof SYMBOL_KINDS)[number] | undefined;
|
|
564
564
|
if (call.flag("analyzer")) return { analyzerNames: list(call, listAnalyzerNames(db, rangeOf(call), kind, originsOf(call), call.space), symbol, RANGE_REST) };
|
|
@@ -167,7 +167,7 @@ Do these actions for the findings:
|
|
|
167
167
|
#### Names in the source
|
|
168
168
|
|
|
169
169
|
- A label or a constant gets the name of the address in the knowledge.
|
|
170
|
-
- Without a knowledge name, it gets the platform name, for example `EXTCOL` or `CHROUT`. A platform name wins over an analyzer name (`dxa`, `
|
|
170
|
+
- Without a knowledge name, it gets the platform name, for example `EXTCOL` or `CHROUT`. A platform name wins over an analyzer name (`dxa`, `decompiler` or `heuristic`), for example `EXTCOL` over `ld020`. A `user` or `llm` name wins over a platform name.
|
|
171
171
|
- An address in the program without a name gets `l_xxxx`.
|
|
172
172
|
- A read or a write in the I/O area `$d000-$dfff` uses the register, also when the program has RAM there. For example, `lda $dd0e` is `lda CI2CRA` and `sta $d012` is `sta RASTER`. `constants.asm` has these names. An address without a platform name stays a number, for example `sta $d800,x`. The data label of the RAM stays at its data. A `user` or `llm` name of the address wins over the register.
|
|
173
173
|
- A platform name in an operand expression of the knowledge stays in the source. When the program has the address, `constants.asm` has the name, and the RAM there keeps its label.
|
|
@@ -201,7 +201,7 @@ A leftover is a range of the program that nothing uses: unused code, old copies
|
|
|
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.
|
|
202
202
|
- `config.asm` has `LEFTOVERS = 0`. Thus the default build is the clean program, without the leftovers.
|
|
203
203
|
- Each release has `LEFTOVERS = 1`. Thus the build of a release gives the bytes of the release.
|
|
204
|
-
- The loader program never has the leftovers. The plain form does not copy them, and the memory there keeps the bytes that were in it before. The packed form unpacks the build of `main.asm` in one piece, so the leftovers are $00.
|
|
204
|
+
- The loader program never has the leftovers. The plain form does not copy them, and the memory there keeps the bytes that were in it before. The packed form unpacks the build of `main.asm` in one piece, so the leftovers in it are $00. A leftover after the last byte of that build is not in it: the memory there keeps the bytes that were in it before.
|
|
205
205
|
- Without coverage, no range is a leftover. Put the coverage of the runs into the project knowledge. Then generate again.
|
|
206
206
|
- When `leftovers.changed` has ranges, the default build and the loader program now leave out other bytes. A test that observes the `added` bytes on the loader program gets other values there. Fill the `added` ranges in the test of the leftovers. In a test that compares them, exclude them with the reason that they are leftovers.
|
|
207
207
|
- A leftover can be wrong when the coverage does not show a use. For example, the VIC-II reads a range, or the program reads a range before it writes it. Then a test of the loader program fails. Record the region in the project knowledge, or put the coverage of more runs into it. Do not change the source.
|
|
@@ -247,7 +247,7 @@ export function planDrops(input: DropInput): DropPlan {
|
|
|
247
247
|
const touched = (address: number) => input.coverage !== undefined && input.coverage[address] !== 0;
|
|
248
248
|
const executed = (address: number) => input.coverage !== undefined && (input.coverage[address]! & COVERAGE.ramExecute) !== 0;
|
|
249
249
|
const regions = input.regions.flatMap((region) => input.segments.filter((segment) => overlaps(region, segment)).map((segment) => ({ start: Math.max(region.start, segment.start), end: Math.min(region.end, segment.end), type: region.type })));
|
|
250
|
-
// The source writes a data region as data, also where
|
|
250
|
+
// The source writes a data region as data, also where the decompiler decoded instructions in it: those are no code.
|
|
251
251
|
const instructions = new Map([...input.instructions].filter(([start, length]) => !regions.some((region) => !CODE_TYPES.includes(region.type) && start <= region.end && region.start <= start + length - 1)));
|
|
252
252
|
const blocks = blocksOf(instructions, input.memory);
|
|
253
253
|
// An indexed operand reads in the region that holds it, and in the next region when it is the last byte (table-1,x).
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// ACME source from an image, current knowledge and
|
|
1
|
+
// ACME source from an image, current knowledge and the decompiler's instruction
|
|
2
2
|
// boundaries. The same input gives the same text. Names come from
|
|
3
3
|
// knowledge; a target that knowledge does not name gets l_xxxx. A read or
|
|
4
4
|
// write in the I/O area names the register, also where the image holds RAM. Data is
|
|
@@ -30,7 +30,7 @@ export interface SourceInput {
|
|
|
30
30
|
/** The image byte at an address inside a segment. */
|
|
31
31
|
byteAt: (address: number) => number;
|
|
32
32
|
entry?: number;
|
|
33
|
-
/** Where
|
|
33
|
+
/** Where the decompiler decoded an instruction, with its length. */
|
|
34
34
|
instructions: ReadonlyMap<number, number>;
|
|
35
35
|
/** Without an origin, a symbol counts as a user or LLM name. */
|
|
36
36
|
symbols: ReadonlyArray<{ address: number; name: string; origin?: Origin }>;
|
|
@@ -204,7 +204,7 @@ interface DataItem {
|
|
|
204
204
|
kind: "data";
|
|
205
205
|
start: number;
|
|
206
206
|
end: number;
|
|
207
|
-
/** The region type, or unclassified. In a code region, bytes that
|
|
207
|
+
/** The region type, or unclassified. In a code region, bytes that the decompiler did not decode. */
|
|
208
208
|
type: RegionType | "unclassified" | "undecoded";
|
|
209
209
|
region?: Region;
|
|
210
210
|
}
|
|
@@ -280,7 +280,7 @@ function operandValue(address: number, opcode: number, byteAt: (address: number)
|
|
|
280
280
|
|
|
281
281
|
/**
|
|
282
282
|
* Each entry point inside a data region of the knowledge, with that region.
|
|
283
|
-
* A data region wins over an entry:
|
|
283
|
+
* A data region wins over an entry: the decompiler does not decode there,
|
|
284
284
|
* and the source has data there. A code region in the knowledge changes that.
|
|
285
285
|
*/
|
|
286
286
|
export function entriesInData<R extends { start: number; end: number; type: RegionType }>(entries: readonly number[], regions: readonly R[]): Array<{ entry: number; region: R }> {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// The c64-source script: generates ACME source from the program and the
|
|
2
|
-
// knowledge and
|
|
2
|
+
// knowledge and the decompiler's instructions, which it runs itself, and checks
|
|
3
3
|
// with ACME that the build of the base release assembles to the program byte
|
|
4
4
|
// by byte. With --loader it also writes a loader that recreates the entry
|
|
5
5
|
// state, simulates it, and checks it in the emulator. The default build may
|
|
@@ -30,9 +30,9 @@ import { ANALYZER_NAME_ORDER, baseValue, currentRevision, currentStartScreen, so
|
|
|
30
30
|
import { CODE_REGION_TYPES, DEFAULT_SPACE, isSemantic, LEFTOVER_FOLDER, LEFTOVERS_SWITCH, RELEASE_DEFINE, START_SCREEN_SWITCH, type Space } from "#src/knowledge/schema.ts";
|
|
31
31
|
import { subtract, write } from "#src/knowledge/write.ts";
|
|
32
32
|
import { assemble, symbolsFileText } from "#src/native/acme.ts";
|
|
33
|
-
import { analyze } from "#src/native/
|
|
33
|
+
import { analyze } from "#src/native/decompiler/analyze.ts";
|
|
34
34
|
import { localToolContext } from "#src/native/local.ts";
|
|
35
|
-
import {
|
|
35
|
+
import { DECOMPILER_LIMITS, type AssembledSymbol, type Diagnostic } from "#src/native/types.ts";
|
|
36
36
|
import { decode as decodeRegister, describeAddress, platformNames, platformNamesFor, romRanges, romUseOfProgram } from "#src/platform.ts";
|
|
37
37
|
import { ensureLocal, generatedDirectory, LOCAL_DIRECTORY, newProjectFolder, PROJECT_DIRECTORY, projectRelative, projectRoot, resolveProjectPath } from "#src/project.ts";
|
|
38
38
|
import { isoCet } from "#src/time.ts";
|
|
@@ -128,7 +128,7 @@ type SourceKnowledge = ReturnType<typeof readKnowledge>;
|
|
|
128
128
|
|
|
129
129
|
/**
|
|
130
130
|
* The names of the user and the LLM, and for each address without one the
|
|
131
|
-
* first analyzer name in the order heuristic,
|
|
131
|
+
* first analyzer name in the order heuristic, decompiler, DXA. An analyzer
|
|
132
132
|
* name that another address has already is left out. The analyzer names keep
|
|
133
133
|
* their origin, so a platform name still wins over them.
|
|
134
134
|
*/
|
|
@@ -156,11 +156,11 @@ function romOf(image: ProgramImage, knowledge: Pick<SourceKnowledge, "routines"
|
|
|
156
156
|
}
|
|
157
157
|
|
|
158
158
|
/**
|
|
159
|
-
*
|
|
159
|
+
* The decompiler's instruction starts and lengths inside the image, seeded from the
|
|
160
160
|
* entry, from knowledge of any origin, and from the coverage: a run's flow
|
|
161
161
|
* starts, also after a JSR, so code that an analyzer does not reach by itself
|
|
162
162
|
* is in the source. A program without a seed has no known code: it is data
|
|
163
|
-
* only, and
|
|
163
|
+
* only, and the decompiler does not run.
|
|
164
164
|
*/
|
|
165
165
|
async function decode(image: ProgramImage, knowledge: Pick<SourceKnowledge, "routines" | "regions">, entries: number[], coverage: Uint8Array | undefined): Promise<{ instructions: Map<number, number>; dataOnly: boolean }> {
|
|
166
166
|
const inImage = (address: number) => image.segments.some((segment) => address >= segment.start && address <= segment.end);
|
|
@@ -185,9 +185,9 @@ async function decode(image: ProgramImage, knowledge: Pick<SourceKnowledge, "rou
|
|
|
185
185
|
const { result } = await analyze(
|
|
186
186
|
{
|
|
187
187
|
imageKind: analyzedBytes(image).kind,
|
|
188
|
-
entryPoints: entryPoints.slice(0,
|
|
189
|
-
codeStarts: flows.codeStarts.filter((address) => !seeds.has(address)).slice(0,
|
|
190
|
-
dataRanges: dataRanges.slice(0,
|
|
188
|
+
entryPoints: entryPoints.slice(0, DECOMPILER_LIMITS.entryPoints),
|
|
189
|
+
codeStarts: flows.codeStarts.filter((address) => !seeds.has(address)).slice(0, DECOMPILER_LIMITS.codeStarts),
|
|
190
|
+
dataRanges: dataRanges.slice(0, DECOMPILER_LIMITS.dataRanges),
|
|
191
191
|
labels: [],
|
|
192
192
|
decompile: [],
|
|
193
193
|
},
|
|
@@ -814,22 +814,22 @@ function removeOldFiles(out: string, keep: ReadonlySet<string>, loaderRun: boole
|
|
|
814
814
|
return removed;
|
|
815
815
|
}
|
|
816
816
|
|
|
817
|
-
/** The instructions that
|
|
817
|
+
/** The instructions that the decompiler decoded, and whether the program has known code. */
|
|
818
818
|
type DecodedProgram = Awaited<ReturnType<typeof decode>>;
|
|
819
819
|
|
|
820
820
|
/** How buildSource makes and checks the source of a knowledge. */
|
|
821
821
|
interface SourceOptions {
|
|
822
822
|
space: Space;
|
|
823
|
-
/** More entry points for
|
|
823
|
+
/** More entry points for the decompiler. */
|
|
824
824
|
entries: number[];
|
|
825
825
|
header: string[];
|
|
826
826
|
/** The first line of each file, or none. */
|
|
827
827
|
mark?: string;
|
|
828
828
|
/** The switch values of the build that must give the program. */
|
|
829
829
|
values: ReadonlyMap<string, number>;
|
|
830
|
-
/** The instructions of an earlier decode: then
|
|
830
|
+
/** The instructions of an earlier decode: then the decompiler does not run again. */
|
|
831
831
|
decoded?: DecodedProgram;
|
|
832
|
-
/** Mark the code that no run executed. Without the marks, the coverage only gives the seeds of
|
|
832
|
+
/** Mark the code that no run executed. Without the marks, the coverage only gives the seeds of the decompiler and the ROM use. */
|
|
833
833
|
notExecutedMarks: boolean;
|
|
834
834
|
/** With an entry state, the loader is planned too. */
|
|
835
835
|
state?: EntryState;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: c64-static-analysis
|
|
3
|
-
description: Finds the structure of a C64 program with DXA or
|
|
3
|
+
description: Finds the structure of a C64 program with DXA or the decompiler, without running it. It records the code and data regions, the analyzer names and the references in the project knowledge. Use it to get a fast first pass of code and data, and a disassembly listing. Use it to get the routines, the references, an instruction list and decompiled code. Use it when the project knowledge has coverage, to find code that only a vector, a table or an interrupt reaches. Use it to find 6502 idioms, pointer candidates, raster pitfalls and macro candidates. It does not run the program. It does not give names to routines.
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# Static analysis
|
|
@@ -43,16 +43,16 @@ To get the command list, run the script with no arguments.
|
|
|
43
43
|
- An entry point is an address where code starts. Give it with `--entry`. Get it from these sources:
|
|
44
44
|
- The SYS address of a BASIC start. Get it from a listing of the BASIC program.
|
|
45
45
|
- A vector or an interrupt target that you found in the emulator.
|
|
46
|
-
- An address in `functions` of an earlier
|
|
47
|
-
-
|
|
46
|
+
- An address in `functions` of an earlier decompiler result.
|
|
47
|
+
- The decompiler needs at least one entry point. DXA finds the SYS address of a BASIC start without help.
|
|
48
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.
|
|
49
49
|
- The two start vectors of a `CBM80` header at `$8000` are entry points without help.
|
|
50
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.
|
|
51
51
|
- If an analyzer decodes data as code, classify the region as data in the project knowledge. Then run `analyze` again.
|
|
52
52
|
- The facts of an analyzer are not entry points or data for the next analysis. Thus a new analysis can correct them.
|
|
53
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`.
|
|
54
|
-
-
|
|
55
|
-
- `--decompile` takes the address of a routine. Get it from `functions` of an earlier
|
|
54
|
+
- The decompiler does not follow BRK. If the program removes the KERNAL and uses the BRK vector, give the target of the vector with `--entry`.
|
|
55
|
+
- `--decompile` takes the address of a routine. Get it from `functions` of an earlier decompiler result, or from the routines in the project knowledge.
|
|
56
56
|
|
|
57
57
|
### Paths and the project folder
|
|
58
58
|
|
|
@@ -80,13 +80,13 @@ Each flag applies only to the commands in the table. On another command, the scr
|
|
|
80
80
|
|
|
81
81
|
| Flag | Command | Effect |
|
|
82
82
|
|---|---|---|
|
|
83
|
-
| `--analyzer <dxa\|
|
|
83
|
+
| `--analyzer <dxa\|decompiler>` | `analyze` | The analyzer. `dxa` gives a fast first pass. `decompiler` gives a deeper pass. The default is `decompiler`. |
|
|
84
84
|
| `--entry <address>` | `analyze` | An entry point of the program. Give it again for more entry points. There is no default. |
|
|
85
|
-
| `--decompile <address>` | `analyze` |
|
|
85
|
+
| `--decompile <address>` | `analyze` | Only with `--analyzer decompiler`. Decompile the routine at this address. Give it again for more routines, at most 32. There is no default. |
|
|
86
86
|
| `--space <space>` | `analyze` | The knowledge space of the program: `drive8` for 1541 drive code, or `bank0` to `bank255` for a cartridge bank. The analysis reads the entry points from that space and writes the findings into it. The default is `c64`. |
|
|
87
87
|
| `--max-listed <n>` | `analyze` | List at most `n` items in each list. `0` lists no items. The counts stay complete. The default is 50. |
|
|
88
88
|
| `--out-listing <file>` | `analyze` | DXA only. Write the disassembly listing to this project file. There is no default. |
|
|
89
|
-
| `--out-instructions <file>` | `analyze` |
|
|
89
|
+
| `--out-instructions <file>` | `analyze` | Only with `--analyzer decompiler`. Write each instruction to this project file as JSON. There is no default. |
|
|
90
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
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. |
|
|
92
92
|
|
|
@@ -96,13 +96,13 @@ Each flag applies only to the commands in the table. On another command, the scr
|
|
|
96
96
|
|
|
97
97
|
### `analyze`
|
|
98
98
|
|
|
99
|
-
Runs DXA or
|
|
99
|
+
Runs DXA or the decompiler over the program in the project knowledge. The script records the findings in the project knowledge as one revision. Then it records the 6502 idioms as a second revision. When the findings do not change the knowledge, the script records no revision for them.
|
|
100
100
|
|
|
101
|
-
The script records only structure: code and data regions, analyzer names, and the references from
|
|
101
|
+
The script records only structure: code and data regions, analyzer names, and the references from the decompiler. It does not record the listing or the decompiled code. Do not record the listing, the decompiled code or the function list as comments in the project knowledge.
|
|
102
102
|
|
|
103
103
|
`body` holds these fields for both analyzers:
|
|
104
104
|
|
|
105
|
-
- `analyzer`: `dxa` or `
|
|
105
|
+
- `analyzer`: `dxa` or `decompiler`. `analyzerVersion` gives the version of the analyzer when the analyzer tells it. `space` is in `body` only for a space that is not `c64`.
|
|
106
106
|
- `revision`: the revision of the findings, or `null` when the knowledge did not change.
|
|
107
107
|
- `coverage`: the ranges that the analyzer examined.
|
|
108
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.
|
|
@@ -117,19 +117,20 @@ DXA also gives:
|
|
|
117
117
|
- `labels`: the names that DXA found, as a list.
|
|
118
118
|
- `listing`: the listing file, with `--out-listing`.
|
|
119
119
|
|
|
120
|
-
|
|
120
|
+
The decompiler also gives:
|
|
121
121
|
|
|
122
|
-
- `functions`: the routines that
|
|
122
|
+
- `functions`: the routines that the decompiler found, as a list, each with `entry` and `name`.
|
|
123
123
|
- `decompilations`: the C-like code of each `--decompile` routine, with `entry` and `text`. `truncated` tells that the text is cut.
|
|
124
|
-
- `notDecompiled`: the routines that
|
|
124
|
+
- `notDecompiled`: the routines that the decompiler did not decompile, each with a `reason`.
|
|
125
125
|
- `instructions`: the file and the `count`, with `--out-instructions`. Each instruction has `address`, `bytes`, `mnemonic`, `mode` and `operand` in 6502 syntax. A branch, a jump or a call also has `target`. With coverage, `executed` tells if the instruction ran.
|
|
126
|
-
- `coverageGaps`: only with coverage. The executed instruction starts that are not in the instructions of
|
|
126
|
+
- `coverageGaps`: only with coverage. The executed instruction starts that are not in the instructions of the decompiler.
|
|
127
127
|
|
|
128
128
|
The `hint` gives each of these cases:
|
|
129
129
|
|
|
130
130
|
- `conflicts` is not empty. Find the correct answer in the emulator. Then correct the project knowledge.
|
|
131
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.
|
|
132
132
|
- `idioms.candidates.macros` has candidates, and the run had no `--apply-macros`. Examine the candidates. To write the correct candidates to the project knowledge, run the analysis again with `--apply-macros`. Give `--skip` with the start of each candidate that is not correct. Then generate the source again.
|
|
133
|
+
- The last analysis of the same program bytes used another analyzer version. Thus a change in `revision` can come from the new analyzer, and not from the program or the project knowledge.
|
|
133
134
|
- A list is cut. Give a larger `--max-listed`. The project knowledge has all `labels` and `functions` as analyzer names.
|
|
134
135
|
|
|
135
136
|
There is no `nextAction`.
|
|
@@ -147,14 +148,14 @@ The script does not record the candidates. Examine each candidate and decide.
|
|
|
147
148
|
#### Which facts the analysis replaces
|
|
148
149
|
|
|
149
150
|
- The analysis never replaces a name or a region of the user or the LLM. Each disagreement shows in `conflicts`.
|
|
150
|
-
- DXA and
|
|
151
|
+
- 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.
|
|
151
152
|
- 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`.
|
|
152
|
-
- An idiom region (origin `heuristic`) replaces the part of a DXA or
|
|
153
|
+
- 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.
|
|
153
154
|
- An idiom table can be too long or too short. Correct its region in the project knowledge. Your region replaces it.
|
|
154
155
|
- A new analysis replaces the earlier facts of the same analyzer in its `coverage`, also its analyzer names. The history keeps the earlier facts.
|
|
155
156
|
- A fact that the user or the LLM removed does not come back. To remove a wrong fact, remove it in the project knowledge.
|
|
156
157
|
- 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.
|
|
157
|
-
- A
|
|
158
|
+
- A decompiler function that only branches and jumps reach is a `label`, not a `routine`.
|
|
158
159
|
|
|
159
160
|
#### Traps
|
|
160
161
|
|
|
@@ -171,7 +172,7 @@ The script does not record the candidates. Examine each candidate and decide.
|
|
|
171
172
|
|
|
172
173
|
#### Failures
|
|
173
174
|
|
|
174
|
-
- `invalid-input` about an entry point:
|
|
175
|
+
- `invalid-input` about an entry point: the decompiler has no entry point in the program. Give one with `--entry`.
|
|
175
176
|
- `stale-revision`: the project knowledge changed during the analysis. The script recorded nothing. Run `analyze` again.
|
|
176
177
|
- `operation-failed` about an incomplete result or listing: the analyzer did not give a complete result. The script recorded nothing. Tell the user.
|
|
177
178
|
- The script did not write the listing: the error tells if the project knowledge has the findings. Correct `--out-listing` and run `analyze` again.
|
|
@@ -184,7 +185,7 @@ The script does not record the candidates. Examine each candidate and decide.
|
|
|
184
185
|
2. Put each coverage map of the program into the project knowledge.
|
|
185
186
|
3. Run `analyze --analyzer dxa` for a first pass. Read the listing for a quick view of the code.
|
|
186
187
|
4. Find the important routines. Give them names in the project knowledge.
|
|
187
|
-
5. Run `analyze` with
|
|
188
|
+
5. Run `analyze` with the decompiler. Give the entry points with `--entry`. Give `--decompile` for the routines that you must understand.
|
|
188
189
|
6. Do the action for each `hint`. Examine the candidates.
|
|
189
190
|
7. Give each important routine a name in the project knowledge. Then run `analyze` again. The analyzers use the new names.
|
|
190
191
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// Knowledge seeds for an analyzer, and the mapping of a
|
|
1
|
+
// Knowledge seeds for an analyzer, and the mapping of a decompiler result to the
|
|
2
2
|
// common normalized findings.
|
|
3
3
|
|
|
4
4
|
import type { DatabaseSync } from "node:sqlite";
|
|
@@ -6,9 +6,9 @@ import type { DatabaseSync } from "node:sqlite";
|
|
|
6
6
|
import type { NormalizedFindings } from "#src/knowledge/import.ts";
|
|
7
7
|
import { listRegions, listSymbols } from "#src/knowledge/read.ts";
|
|
8
8
|
import { CODE_REGION_TYPES, DEFAULT_SPACE, isSemantic, type Space } from "#src/knowledge/schema.ts";
|
|
9
|
-
import type { DxaResult,
|
|
9
|
+
import type { DxaResult, DecompilerParams, DecompilerResult } from "#src/native/types.ts";
|
|
10
10
|
|
|
11
|
-
export type Seeds = Pick<
|
|
11
|
+
export type Seeds = Pick<DecompilerParams, "entryPoints" | "dataRanges" | "labels">;
|
|
12
12
|
|
|
13
13
|
const semantic = (row: { origin: string }) => isSemantic(row.origin);
|
|
14
14
|
|
|
@@ -49,12 +49,12 @@ export function seedsFromKnowledge(db: DatabaseSync | undefined, extraEntryPoint
|
|
|
49
49
|
|
|
50
50
|
/**
|
|
51
51
|
* The 6510 opcodes with a low nibble of 1 or 3 use (zp,x) or (zp),y, also the
|
|
52
|
-
* undocumented ones.
|
|
52
|
+
* undocumented ones. The decompiler gives such an instruction a reference to the target
|
|
53
53
|
* that it computes from the pointer value at the entry state: a guess, because
|
|
54
54
|
* the program sets the pointer at run time. Only the reference to the pointer
|
|
55
55
|
* itself (zp or zp+1) is a fact.
|
|
56
56
|
*/
|
|
57
|
-
function guessedIndirectTarget(instructions:
|
|
57
|
+
function guessedIndirectTarget(instructions: DecompilerResult["instructions"]): (reference: { from: number; to: number }) => boolean {
|
|
58
58
|
const pointers = new Map<number, number>();
|
|
59
59
|
for (const instruction of instructions) {
|
|
60
60
|
const opcode = Number.parseInt(instruction.bytes.slice(0, 2), 16);
|
|
@@ -67,28 +67,28 @@ function guessedIndirectTarget(instructions: GhidraResult["instructions"]): (ref
|
|
|
67
67
|
}
|
|
68
68
|
|
|
69
69
|
/**
|
|
70
|
-
*
|
|
70
|
+
* The decompiler's result as normalized findings. A reference from a (zp,x) or (zp),y
|
|
71
71
|
* instruction to a computed target is not a finding (see guessedIndirectTarget).
|
|
72
72
|
* A function named by an echoed seed
|
|
73
73
|
* stays in the snapshot: its address holds the seed's semantic symbol, which
|
|
74
74
|
* the importer never replaces, so the name keeps its owner,
|
|
75
75
|
* and a code/data disagreement with that symbol is still reported.
|
|
76
76
|
*/
|
|
77
|
-
export function
|
|
78
|
-
//
|
|
77
|
+
export function decompilerFindings(result: DecompilerResult): NormalizedFindings {
|
|
78
|
+
// The decompiler can give one generated name to two functions, for example
|
|
79
79
|
// thunk_FUN_e434 to two thunks of one routine. A name
|
|
80
80
|
// must have one address, so a repeated name that is not a seed gets its address.
|
|
81
81
|
const uses = new Map<string, number>();
|
|
82
82
|
for (const fn of result.functions) uses.set(fn.name, (uses.get(fn.name) ?? 0) + 1);
|
|
83
|
-
const nameOf = (fn:
|
|
83
|
+
const nameOf = (fn: DecompilerResult["functions"][number]) =>
|
|
84
84
|
fn.nameSource !== "seed" && uses.get(fn.name)! > 1 ? `${fn.name}_${fn.entry.toString(16).padStart(4, "0")}` : fn.name;
|
|
85
85
|
// A function that branches and jumps reach, and no call, is a place in a routine: a label.
|
|
86
86
|
const called = new Set(result.references.filter((reference) => reference.type === "call").map((reference) => reference.to));
|
|
87
87
|
const jumped = new Set(result.references.filter((reference) => reference.type === "jump").map((reference) => reference.to));
|
|
88
88
|
const guessed = guessedIndirectTarget(result.instructions);
|
|
89
|
-
const kindOf = (fn:
|
|
89
|
+
const kindOf = (fn: DecompilerResult["functions"][number]) => (jumped.has(fn.entry) && !called.has(fn.entry) ? ("label" as const) : ("routine" as const));
|
|
90
90
|
return {
|
|
91
|
-
analyzer: "
|
|
91
|
+
analyzer: "decompiler",
|
|
92
92
|
coverage: result.coverage,
|
|
93
93
|
authoritative: { symbols: result.completeness.functions, regions: result.completeness.regions, references: result.completeness.references },
|
|
94
94
|
symbols: result.functions.map((fn) => ({ address: fn.entry, name: nameOf(fn), kind: kindOf(fn) })),
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
// The structured instruction list:
|
|
1
|
+
// The structured instruction list: the decompiler's decoded instructions with
|
|
2
2
|
// the addressing mode, the operand in 6502 syntax, the flow target and,
|
|
3
3
|
// with a coverage file, whether the instruction ran.
|
|
4
4
|
|
|
5
5
|
import { COVERAGE, formatC64Address } from "#src/c64.ts";
|
|
6
6
|
import { OPCODES, type Mode as OpcodeMode } from "#src/opcodes.ts";
|
|
7
|
-
import type {
|
|
7
|
+
import type { DecompilerInstruction } from "#src/native/types.ts";
|
|
8
8
|
|
|
9
9
|
export type Mode =
|
|
10
10
|
| "implied"
|
|
@@ -88,8 +88,8 @@ export interface ListedInstruction {
|
|
|
88
88
|
executed?: boolean;
|
|
89
89
|
}
|
|
90
90
|
|
|
91
|
-
/**
|
|
92
|
-
export function instructionList(instructions:
|
|
91
|
+
/** The decompiler's instructions as the list that --out-instructions writes. */
|
|
92
|
+
export function instructionList(instructions: DecompilerInstruction[], coverage?: Uint8Array): ListedInstruction[] {
|
|
93
93
|
return instructions.map((instruction) => {
|
|
94
94
|
const bytes = Buffer.from(instruction.bytes, "hex");
|
|
95
95
|
const mode = modeOf(bytes[0]!);
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// The c64-static-analysis script: analyzes the program in the knowledge
|
|
2
|
-
// with DXA (fast first pass) or
|
|
2
|
+
// with DXA (fast first pass) or the decompiler (deeper), which it runs itself, seeded
|
|
3
3
|
// from current knowledge and the coverage of the knowledge, and imports the
|
|
4
4
|
// structural findings into .c64-re-tools/knowledge/.
|
|
5
5
|
|
|
@@ -9,19 +9,19 @@ import { WireFailure } from "#src/host-client/tools.ts";
|
|
|
9
9
|
import { writeReported } from "#src/host-client/transfer.ts";
|
|
10
10
|
import { knowledgeNames } from "#src/knowledge/names.ts";
|
|
11
11
|
import { analyze as analyzeWithDxa } from "#src/native/dxa.ts";
|
|
12
|
-
import { analyze as
|
|
12
|
+
import { analyze as analyzeWithDecompiler } from "#src/native/decompiler/analyze.ts";
|
|
13
13
|
import { localToolContext } from "#src/native/local.ts";
|
|
14
|
-
import {
|
|
14
|
+
import { DECOMPILER_LIMITS } 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";
|
|
18
|
-
import { importFindings, runProvenance, type ImportConflict, type ImportContext, type ImportResult, type NormalizedFindings } from "#src/knowledge/import.ts";
|
|
18
|
+
import { importFindings, lastToolVersion, runProvenance, type ImportConflict, type ImportContext, type ImportResult, type NormalizedFindings } from "#src/knowledge/import.ts";
|
|
19
19
|
import { currentRevision, listMacros, listMacroUses, listPatches, listReferences, listRegions, listSymbols } from "#src/knowledge/read.ts";
|
|
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
23
|
import { codeEntries, coverageConflicts, coverageEntries, coverageSeedKinds, executedStarts, imageReader, romOnlyRanges, type ImageByte } from "./lib/coverage.ts";
|
|
24
|
-
import { dxaFindings,
|
|
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";
|
|
27
27
|
import { CATALOGUE, findMacroUses, type MacroCandidate } from "./lib/macros.ts";
|
|
@@ -36,8 +36,11 @@ const ALL_NAMES = "a larger --max-listed. The project knowledge has all of them
|
|
|
36
36
|
* analyzer data over executed code to classify, and macro candidates to write.
|
|
37
37
|
* The envelope adds the sentence for a cut list.
|
|
38
38
|
*/
|
|
39
|
-
function withHint(body: Record<string, unknown>, conflicts: number, coverageConflicts: number, macros: { candidates: number; applied: boolean; revision: string | null | undefined }) {
|
|
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 }) {
|
|
40
40
|
const hints: string[] = [];
|
|
41
|
+
if (version.revision !== null && version.now !== undefined && version.last !== undefined && version.now !== version.last) {
|
|
42
|
+
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
|
+
}
|
|
41
44
|
if (conflicts > 0) hints.push("The analysis and the project knowledge disagree at each place in conflicts. Find the correct answer in the emulator. Then correct the project knowledge.");
|
|
42
45
|
if (coverageConflicts > 0) hints.push("The coverage shows executed code in each range of coverageConflicts. Classify each range as code, or as dual-use when its bytes are also data, in the project knowledge.");
|
|
43
46
|
if (typeof macros.revision === "string") hints.push("The project knowledge has the macro candidates now. Generate the source again.");
|
|
@@ -175,15 +178,15 @@ async function analyze(call: Call): Promise<unknown> {
|
|
|
175
178
|
const decompile = call.addresses("decompile");
|
|
176
179
|
if (decompile.length > 32) throw new UsageError("--decompile takes at most 32 routines");
|
|
177
180
|
const max = call.count("max-listed")!;
|
|
178
|
-
const analyzer = call.string("analyzer") as "dxa" | "
|
|
181
|
+
const analyzer = call.string("analyzer") as "dxa" | "decompiler";
|
|
179
182
|
const listingPath = call.string("out-listing");
|
|
180
183
|
const instructionsPath = call.string("out-instructions");
|
|
181
184
|
const applyMacros = call.flag("apply-macros");
|
|
182
185
|
const skip = new Set(call.addresses("skip"));
|
|
183
186
|
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");
|
|
184
|
-
if (analyzer === "dxa" && decompile.length > 0) throw new UsageError("--decompile works only with --analyzer
|
|
185
|
-
if (analyzer === "
|
|
186
|
-
if (analyzer === "dxa" && instructionsPath !== undefined) throw new UsageError("--out-instructions works only with --analyzer
|
|
187
|
+
if (analyzer === "dxa" && decompile.length > 0) throw new UsageError("--decompile works only with --analyzer decompiler");
|
|
188
|
+
if (analyzer === "decompiler" && listingPath !== undefined) throw new UsageError("--out-listing works only with --analyzer dxa");
|
|
189
|
+
if (analyzer === "dxa" && instructionsPath !== undefined) throw new UsageError("--out-instructions works only with --analyzer decompiler");
|
|
187
190
|
const space = call.space;
|
|
188
191
|
const reader = openForRead();
|
|
189
192
|
const program = requireProgram(reader, space);
|
|
@@ -203,25 +206,27 @@ async function analyze(call: Call): Promise<unknown> {
|
|
|
203
206
|
const revision = currentRevision(reader);
|
|
204
207
|
const seeds = seedsFromKnowledge(reader, entries, space, executed.executed);
|
|
205
208
|
// Knowledge routines and --entry first, then code regions and JMP tables, then idioms, then coverage, up to the seed bound:
|
|
206
|
-
// at most
|
|
207
|
-
//
|
|
209
|
+
// at most DECOMPILER_LIMITS.entryPoints (1024) entry points for both analyzers, and for the decompiler at most
|
|
210
|
+
// DECOMPILER_LIMITS.codeStarts (8192) coverage flow starts that are code in a routine. coverageSeeds gives what was used.
|
|
208
211
|
const fromCoverage = coverage === undefined ? [] : coverageEntries(coverage, inProgram);
|
|
209
212
|
const known = [...seeds.entryPoints, ...codeEntries(reader, byteAt, space)];
|
|
210
|
-
//
|
|
213
|
+
// The decompiler takes the coverage as code starts without a function; DXA has one list.
|
|
211
214
|
const kinds = analyzer === "dxa" || coverage === undefined ? { routines: fromCoverage, codeStarts: [] } : coverageSeedKinds(coverage, inProgram);
|
|
212
215
|
const ordered = [...new Set([...known, ...idioms.entryPoints, ...kinds.routines])];
|
|
213
|
-
seeds.entryPoints = ordered.slice(0,
|
|
214
|
-
const codeStarts = kinds.codeStarts.filter((entry) => !seeds.entryPoints.includes(entry)).slice(0,
|
|
216
|
+
seeds.entryPoints = ordered.slice(0, DECOMPILER_LIMITS.entryPoints).sort((a, b) => a - b);
|
|
217
|
+
const codeStarts = kinds.codeStarts.filter((entry) => !seeds.entryPoints.includes(entry)).slice(0, DECOMPILER_LIMITS.codeStarts);
|
|
215
218
|
// Idiom tables and the RAM under ROM that the runs never used are data for this run too; semantic data ranges come first.
|
|
216
219
|
// A range with an entry point of the knowledge or --entry in it is left out: that code stays code.
|
|
217
220
|
const fromRom = coverage === undefined ? [] : romOnlyRanges(coverage, byteAt).filter((range) => !known.some((entry) => entry >= range.start && entry <= range.end));
|
|
218
221
|
const dataRanges = [...seeds.dataRanges];
|
|
219
222
|
for (const range of [...idioms.dataRanges, ...fromRom]) if (!dataRanges.some((seed) => range.start <= seed.end && range.end >= seed.start)) dataRanges.push(range);
|
|
220
|
-
seeds.dataRanges = dataRanges.slice(0,
|
|
223
|
+
seeds.dataRanges = dataRanges.slice(0, DECOMPILER_LIMITS.dataRanges);
|
|
221
224
|
const romUsed = fromRom.filter((range) => seeds.dataRanges.includes(range)).length;
|
|
222
225
|
const coverageUsed = fromCoverage.filter((entry) => seeds.entryPoints.includes(entry) || codeStarts.includes(entry)).length;
|
|
223
226
|
// Platform names are C64 names: drive code and banks get none.
|
|
224
227
|
const platform = space === DEFAULT_SPACE ? platformNames() : [];
|
|
228
|
+
/** The analyzer version of the last analysis of these bytes: a new version can change the findings by itself. */
|
|
229
|
+
const lastVersion = reader === undefined ? undefined : lastToolVersion(reader, analyzer, bytes);
|
|
225
230
|
reader?.close();
|
|
226
231
|
/** Imports the idioms as their own revision, after the analyzer's, and gives their part of the result. */
|
|
227
232
|
const idiomsResult = () => {
|
|
@@ -298,6 +303,7 @@ async function analyze(call: Call): Promise<unknown> {
|
|
|
298
303
|
const found = idiomsResult();
|
|
299
304
|
const body = {
|
|
300
305
|
analyzer: "dxa",
|
|
306
|
+
...(result.toolVersion === undefined ? {} : { analyzerVersion: result.toolVersion }),
|
|
301
307
|
...(space === DEFAULT_SPACE ? {} : { space }),
|
|
302
308
|
...found,
|
|
303
309
|
...coverageResult(),
|
|
@@ -307,13 +313,13 @@ async function analyze(call: Call): Promise<unknown> {
|
|
|
307
313
|
labels: listed(result.labels, max, (label) => ({ address: formatC64Address(label.address), name: label.name }), ALL_NAMES),
|
|
308
314
|
...(written === undefined ? {} : { listing: written }),
|
|
309
315
|
};
|
|
310
|
-
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 });
|
|
316
|
+
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 });
|
|
311
317
|
}
|
|
312
318
|
|
|
313
|
-
const { result } = await
|
|
314
|
-
// Executed instruction starts that
|
|
319
|
+
const { result } = await analyzeWithDecompiler({ imageKind, ...seeds, codeStarts, decompile }, bytes, localToolContext());
|
|
320
|
+
// Executed instruction starts that the decompiler did not decode: the instruction list and the source miss them.
|
|
315
321
|
const decoded = new Set(result.instructions.map((instruction) => instruction.address));
|
|
316
|
-
const imported = record({ ...
|
|
322
|
+
const imported = record({ ...decompilerFindings(result), space, ...executed }, revision, "Decompiler analysis of the program", runProvenance(bytes, result.toolVersion));
|
|
317
323
|
const found = idiomsResult();
|
|
318
324
|
// A start inside a dual-use region is a known overlap, for example the second instruction of a BIT skip: one list cannot hold both.
|
|
319
325
|
// Read after the idioms, which write those regions.
|
|
@@ -327,7 +333,8 @@ async function analyze(call: Call): Promise<unknown> {
|
|
|
327
333
|
instructions = { count: list.length, ...writeReported(instructionsPath, `${JSON.stringify(list, null, 1)}\n`, { what: "--out-instructions" }) };
|
|
328
334
|
}
|
|
329
335
|
const body = {
|
|
330
|
-
analyzer: "
|
|
336
|
+
analyzer: "decompiler",
|
|
337
|
+
...(result.toolVersion === undefined ? {} : { analyzerVersion: result.toolVersion }),
|
|
331
338
|
...(space === DEFAULT_SPACE ? {} : { space }),
|
|
332
339
|
...(instructions === undefined ? {} : { instructions }),
|
|
333
340
|
...found,
|
|
@@ -341,29 +348,29 @@ async function analyze(call: Call): Promise<unknown> {
|
|
|
341
348
|
? {}
|
|
342
349
|
: { notDecompiled: result.notDecompiled!.map((item) => ({ entry: formatC64Address(item.entry), reason: item.reason })) }),
|
|
343
350
|
};
|
|
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 });
|
|
351
|
+
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 });
|
|
345
352
|
}
|
|
346
353
|
|
|
347
354
|
await runScript({
|
|
348
355
|
name: "static-analysis",
|
|
349
|
-
summary: "Analyzes the program in the knowledge with DXA or
|
|
356
|
+
summary: "Analyzes the program in the knowledge with DXA or the decompiler, seeded from the knowledge and its coverage, and imports the structural findings into the knowledge.",
|
|
350
357
|
names: knowledgeNames,
|
|
351
358
|
commands: [
|
|
352
359
|
{
|
|
353
360
|
name: "analyze",
|
|
354
361
|
summary: "Runs the analyzer over the program in the knowledge and imports what it finds as one revision, then the 6502 idioms as a second one.",
|
|
355
362
|
options: {
|
|
356
|
-
analyzer: { kind: "choice", value: "<dxa|
|
|
363
|
+
analyzer: { kind: "choice", value: "<dxa|decompiler>", choices: ["dxa", "decompiler"], default: "decompiler", help: "dxa (a fast first pass) or decompiler (deeper, the default)" },
|
|
357
364
|
entry: { ...OPTIONS.entry, multiple: true, help: "an entry point of the program" },
|
|
358
|
-
decompile: { kind: "address", value: "<address>", multiple: true, help: "
|
|
365
|
+
decompile: { kind: "address", value: "<address>", multiple: true, help: "decompiler: a routine to decompile, at most 32" },
|
|
359
366
|
space: OPTIONS.space,
|
|
360
367
|
"max-listed": { ...OPTIONS["max-listed"], help: "list at most n labels, functions or candidates (default 50, 0 for none). The counts are always given, and the knowledge has all labels and functions" },
|
|
361
368
|
"out-listing": { kind: "path", output: "file", value: "<file>", help: "dxa: write the disassembly listing to this project file" },
|
|
362
|
-
"out-instructions": { kind: "path", output: "file", value: "<file>", help: "
|
|
369
|
+
"out-instructions": { kind: "path", output: "file", value: "<file>", help: "decompiler: write every instruction (address, bytes, mnemonic, mode, operand, target, executed) to this project file as JSON" },
|
|
363
370
|
"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
371
|
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
372
|
},
|
|
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.
|
|
373
|
+
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. The decompiler needs at least one entry point. DXA finds the SYS of a BASIC start by itself.",
|
|
367
374
|
run: analyze,
|
|
368
375
|
},
|
|
369
376
|
],
|
|
@@ -207,7 +207,7 @@ The script does the steps of the record file on the original program. Then it wr
|
|
|
207
207
|
|
|
208
208
|
Do this for each result:
|
|
209
209
|
|
|
210
|
-
- `PASS`: `hint` tells you to commit the folder and to add its `coverage.bin` to the project knowledge as coverage. `nextAction` replays the recording on the original. Run it to make sure that the recording replays.
|
|
210
|
+
- `PASS`: for a folder in `tests/recordings/`, `hint` tells you to commit the folder and to add its `coverage.bin` to the project knowledge as coverage. Git ignores `.c64-re-tools/local/`, thus the project knowledge must not name a file in it. For a folder there, `hint` tells you to record again with `--out tests/recordings/<name>`. `nextAction` replays the recording on the original. Run it to make sure that the recording replays.
|
|
211
211
|
- `FAIL` after a cancel on the page: `hint` tells you to ask the user what to do. Do not record a session from steps in place of the session of the user.
|
|
212
212
|
- Another `FAIL`: `reason` names the step that did not complete. Examples are a `runUntil` step that did not get to its target, and a `type` step with too many keys. Change the step, then run `record` again.
|
|
213
213
|
- `coverageFrom` is `null` and `executed` is 0: the coverage did not start, so the coverage map is empty. The recording can still replay.
|
|
@@ -107,11 +107,11 @@ async function recordCommand(call: Call): Promise<Reply> {
|
|
|
107
107
|
];
|
|
108
108
|
// A recording in the local folder is a work file: git ignores it, so it is no test.
|
|
109
109
|
const keep = projectRelative(out).startsWith(`${PROJECT_DIRECTORY}/${LOCAL_DIRECTORY}/`)
|
|
110
|
-
? `Git ignores ${out}. To keep the recording as a test, record again with --out tests/recordings/<name>.`
|
|
111
|
-
: `Commit ${out} with the scenarios.`;
|
|
110
|
+
? `Git ignores ${out}. To keep the recording as a test and to add its coverage to the project knowledge, record again with --out tests/recordings/<name>.`
|
|
111
|
+
: `Commit ${out} with the scenarios. Add ${out}/${RECORDING_FILES.coverage} to the project knowledge as coverage.`;
|
|
112
112
|
return reply(
|
|
113
113
|
{ result: "PASS", recorded: true, out, ...summary, files },
|
|
114
|
-
{ hint: `${keep}
|
|
114
|
+
{ hint: `${keep} ${summary.coverageFrom === null ? "The coverage did not start: the map is empty." : "The map has no marks for the code that ran before coverageFrom."} To make sure that the recording replays, run nextAction.`, nextAction: call.next("replay", out) },
|
|
115
115
|
);
|
|
116
116
|
} finally {
|
|
117
117
|
await core.close();
|
package/src/c64.ts
CHANGED
|
@@ -511,7 +511,7 @@ const BRANCHES = new Set([0x10, 0x30, 0x50, 0x70, 0x90, 0xb0, 0xd0, 0xf0]);
|
|
|
511
511
|
const NO_FALL = new Set([0x00, 0x40, 0x4c, 0x60, 0x6c]);
|
|
512
512
|
|
|
513
513
|
/**
|
|
514
|
-
* The coverage flow starts split for
|
|
514
|
+
* The coverage flow starts split for the decompiler. A start is a code start, a
|
|
515
515
|
* place in a routine, when it follows an executed JSR, or when an executed
|
|
516
516
|
* branch or JMP from outside its own flow reaches it (the loop of a routine
|
|
517
517
|
* that jumps back to its own start does not count). Any other start, for
|
package/src/host/tools/index.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// The typed tool dispatcher of the Host Runtime. The host runs only
|
|
2
2
|
// VICE and the tools that come with it (c1541, petcat); skill scripts run
|
|
3
|
-
// ACME, DXA and
|
|
3
|
+
// ACME, DXA and the decompiler themselves. One entry per operation, never a
|
|
4
4
|
// generic executable route.
|
|
5
5
|
|
|
6
6
|
import type { ProcessSupervisor } from "../../native/processes.ts";
|
package/src/host-client/tools.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// Short-lived typed requests to the Host Runtime for skill scripts:
|
|
2
2
|
// VICE's own tools (c1541, petcat) and the host tool status. Each request
|
|
3
3
|
// opens its own "tool" connection, sends bytes, and closes. Skill scripts run
|
|
4
|
-
// ACME, DXA and
|
|
4
|
+
// ACME, DXA and the decompiler themselves through src/native (the decompiler in process).
|
|
5
5
|
|
|
6
6
|
import { ProtocolError, WireFailure } from "../protocol/messages.ts";
|
|
7
7
|
import { DISK_IMAGE_TYPES, validateToolResult, type C1541Result, type DiskAction, type DiskImageType, type DiskSector, type PetcatResult, type ToolOperation, type ToolOperations } from "../protocol/tools.ts";
|
package/src/knowledge/import.ts
CHANGED
|
@@ -69,6 +69,13 @@ export function runProvenance(image: Uint8Array, toolVersion: string | undefined
|
|
|
69
69
|
return toolVersion === undefined ? { inputHash } : { inputHash, toolVersion };
|
|
70
70
|
}
|
|
71
71
|
|
|
72
|
+
/** The version of the analyzer in its last revision of these image bytes: undefined when it has none, or when that revision does not tell it. */
|
|
73
|
+
export function lastToolVersion(db: DatabaseSync, analyzer: Analyzer, image: Uint8Array): string | undefined {
|
|
74
|
+
const { inputHash } = runProvenance(image, undefined);
|
|
75
|
+
const row = db.prepare("SELECT tool_version FROM revisions WHERE origin = ? AND input_hash = ? ORDER BY id DESC LIMIT 1").get(analyzer, inputHash!) as { tool_version: string | null } | undefined;
|
|
76
|
+
return row?.tool_version ?? undefined;
|
|
77
|
+
}
|
|
78
|
+
|
|
72
79
|
export type ImportConflict =
|
|
73
80
|
| {
|
|
74
81
|
category: "symbol";
|
|
@@ -261,10 +268,10 @@ function importNames(db: DatabaseSync, change: Change, findings: NormalizedFindi
|
|
|
261
268
|
}
|
|
262
269
|
}
|
|
263
270
|
|
|
264
|
-
/** Analyzers whose regions a heuristic finding replaces where it lies: user/LLM > heuristic > DXA/
|
|
265
|
-
const YIELDS_TO_HEURISTIC = new Set<Origin>(["dxa", "
|
|
271
|
+
/** Analyzers whose regions a heuristic finding replaces where it lies: user/LLM > heuristic > DXA/decompiler. */
|
|
272
|
+
const YIELDS_TO_HEURISTIC = new Set<Origin>(["dxa", "decompiler"]);
|
|
266
273
|
/** Analyzers whose data gives way to a code finding over an executed instruction start. */
|
|
267
|
-
const YIELDS_TO_EXECUTED_CODE = new Set<Origin>(["dxa", "
|
|
274
|
+
const YIELDS_TO_EXECUTED_CODE = new Set<Origin>(["dxa", "decompiler"]);
|
|
268
275
|
|
|
269
276
|
/** The first address in the range that is an executed instruction start, or undefined. */
|
|
270
277
|
function firstExecuted(findings: NormalizedFindings, start: number, end: number): number | undefined {
|
|
@@ -279,7 +286,7 @@ function holdsExecuted(findings: NormalizedFindings, start: number, end: number)
|
|
|
279
286
|
}
|
|
280
287
|
|
|
281
288
|
/**
|
|
282
|
-
* The data findings of DXA or
|
|
289
|
+
* The data findings of DXA or the decompiler that code evidence contradicts: an
|
|
283
290
|
* executed instruction start, or a code name (label or routine) of the user or
|
|
284
291
|
* the LLM, in the range. Evidence wins over an analyzer guess: such a finding
|
|
285
292
|
* is not imported, and the analyzer's own code there stays.
|
|
@@ -314,7 +321,7 @@ function importRegions(db: DatabaseSync, change: Change, given: NormalizedFindin
|
|
|
314
321
|
result.conflicts.push(...contradicted);
|
|
315
322
|
const findings = { ...given, regions: given.regions.filter((region) => !contradicted.some((item) => item.start === region.start && item.end === region.end)) };
|
|
316
323
|
if (analyzer === "heuristic") {
|
|
317
|
-
// An idiom is specific evidence about its bytes: the DXA or
|
|
324
|
+
// An idiom is specific evidence about its bytes: the DXA or decompiler region there gives way, its parts outside stay.
|
|
318
325
|
for (const region of findings.regions) {
|
|
319
326
|
for (const row of regionsOverlapping(db, region.start, region.end, space).filter((candidate) => YIELDS_TO_HEURISTIC.has(candidate.origin))) {
|
|
320
327
|
change.close("regions", "space = ? AND start_address = ? AND end_address = ? AND origin = ?", space, row.start, row.end, row.origin);
|
package/src/knowledge/program.ts
CHANGED
|
@@ -250,7 +250,7 @@ export function entryMemory(image: ProgramImage): Uint8Array {
|
|
|
250
250
|
|
|
251
251
|
/**
|
|
252
252
|
* The bytes for an analyzer: a PRG for one segment without an entry state,
|
|
253
|
-
* else the 64 KiB with the entry-state pages (entryMemory). DXA,
|
|
253
|
+
* else the 64 KiB with the entry-state pages (entryMemory). DXA, the decompiler and
|
|
254
254
|
* c64-source get the same bytes.
|
|
255
255
|
*/
|
|
256
256
|
export function analyzedBytes(image: ProgramImage): { bytes: Buffer; kind: "prg" | "flat64k" } {
|
package/src/knowledge/read.ts
CHANGED
|
@@ -451,7 +451,7 @@ export function symbolNamed(db: DatabaseSync | undefined, name: string, space: S
|
|
|
451
451
|
return row === undefined ? undefined : toSymbol(row);
|
|
452
452
|
}
|
|
453
453
|
|
|
454
|
-
/** The analyzer names at an address: one for each analyzer, in the order heuristic,
|
|
454
|
+
/** The analyzer names at an address: one for each analyzer, in the order heuristic, decompiler, DXA. */
|
|
455
455
|
export function analyzerNamesAt(db: DatabaseSync | undefined, address: number, space: Space = DEFAULT_SPACE): SymbolRow[] {
|
|
456
456
|
if (db === undefined) return [];
|
|
457
457
|
return (db.prepare(`SELECT ${SYMBOL_COLUMNS} FROM current_analyzer_names WHERE space = ? AND address = ?`).all(space, address) as Raw[]).map(toSymbol).sort(byAnalyzer);
|
|
@@ -464,10 +464,10 @@ export function analyzerNamed(db: DatabaseSync | undefined, name: string, space:
|
|
|
464
464
|
}
|
|
465
465
|
|
|
466
466
|
/** The analyzers in the order that their names are used when no other name exists. */
|
|
467
|
-
export const ANALYZER_NAME_ORDER: readonly Origin[] = ["heuristic", "
|
|
467
|
+
export const ANALYZER_NAME_ORDER: readonly Origin[] = ["heuristic", "decompiler", "dxa"];
|
|
468
468
|
const byAnalyzer = (a: SymbolRow, b: SymbolRow) => a.address - b.address || ANALYZER_NAME_ORDER.indexOf(a.origin) - ANALYZER_NAME_ORDER.indexOf(b.origin);
|
|
469
469
|
|
|
470
|
-
/** Current analyzer names in a range, in address order and then heuristic,
|
|
470
|
+
/** Current analyzer names in a range, in address order and then heuristic, decompiler, DXA. */
|
|
471
471
|
export function listAnalyzerNames(db: DatabaseSync | undefined, range: AddressRange = ALL, kind?: SymbolKind, origins?: OriginFilter, space: Space = DEFAULT_SPACE): SymbolRow[] {
|
|
472
472
|
if (db === undefined) return [];
|
|
473
473
|
return (db.prepare(`SELECT ${SYMBOL_COLUMNS} FROM current_analyzer_names WHERE space = ? AND address BETWEEN ? AND ?`).all(space, range.start, range.end) as Raw[])
|
package/src/knowledge/schema.ts
CHANGED
|
@@ -8,12 +8,12 @@ import { REFERENCE_KINDS, type ReferenceKind } from "../c64.ts";
|
|
|
8
8
|
import { OPERAND_SELECTS } from "./expression.ts";
|
|
9
9
|
|
|
10
10
|
/** heuristic: 6502 idioms that the static analysis finds by pattern; an analyzer origin. */
|
|
11
|
-
export const ORIGINS = ["user", "llm", "dxa", "
|
|
11
|
+
export const ORIGINS = ["user", "llm", "dxa", "decompiler", "heuristic"] as const;
|
|
12
12
|
export type Origin = (typeof ORIGINS)[number];
|
|
13
13
|
/** The origins of semantic knowledge: what the user or the LLM decided. It wins over analyzer facts. */
|
|
14
14
|
export const SEMANTIC_ORIGINS = ["user", "llm"] as const satisfies readonly Origin[];
|
|
15
15
|
/** The analyzers: their facts and names give way to semantic knowledge. */
|
|
16
|
-
export const ANALYZERS = ["dxa", "
|
|
16
|
+
export const ANALYZERS = ["dxa", "decompiler", "heuristic"] as const satisfies readonly Origin[];
|
|
17
17
|
export type Analyzer = (typeof ANALYZERS)[number];
|
|
18
18
|
export const isSemantic = (origin: string | undefined): boolean => (SEMANTIC_ORIGINS as readonly (string | undefined)[]).includes(origin);
|
|
19
19
|
export const isAnalyzer = (origin: string | undefined): boolean => (ANALYZERS as readonly (string | undefined)[]).includes(origin);
|
|
@@ -176,7 +176,7 @@ function createSchema(db: DatabaseSync): void {
|
|
|
176
176
|
address INTEGER NOT NULL CHECK (address BETWEEN 0 AND 65535),
|
|
177
177
|
name TEXT NOT NULL CHECK (length(name) > 0),
|
|
178
178
|
kind TEXT NOT NULL CHECK (kind IN (${list(SYMBOL_KINDS)})),
|
|
179
|
-
origin TEXT NOT NULL CHECK (origin IN ('dxa', '
|
|
179
|
+
origin TEXT NOT NULL CHECK (origin IN ('dxa', 'decompiler', 'heuristic')),
|
|
180
180
|
valid_from_revision TEXT NOT NULL REFERENCES revisions (id),
|
|
181
181
|
valid_to_revision TEXT REFERENCES revisions (id)
|
|
182
182
|
);
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
// The
|
|
1
|
+
// The decompiler analysis: the Ghidra SLEIGH decoder and decompiler with the NMOS
|
|
2
2
|
// 6510 language, in this process as a WebAssembly module. Knowledge seeds go
|
|
3
3
|
// in, the structural result comes out, and the result is checked completely
|
|
4
4
|
// before the script imports it.
|
|
5
5
|
|
|
6
6
|
import { describeError, WireFailure } from "../../protocol/messages.ts";
|
|
7
|
-
import {
|
|
7
|
+
import { checkDecompilerResult, checkRequestBounds, DECOMPILER_LIMITS, imageRange, seedsInside, type DecompilerParams, type DecompilerResult } from "../types.ts";
|
|
8
8
|
import type { ToolContext } from "../run.ts";
|
|
9
9
|
import { walk } from "./walk.ts";
|
|
10
10
|
import { decompile, loadImage, setName, SLEIGH_VERSION } from "./wasm.ts";
|
|
@@ -13,10 +13,10 @@ import { decompile, loadImage, setName, SLEIGH_VERSION } from "./wasm.ts";
|
|
|
13
13
|
const MAX_REASON = 1000;
|
|
14
14
|
|
|
15
15
|
export async function analyze(
|
|
16
|
-
params:
|
|
16
|
+
params: DecompilerParams,
|
|
17
17
|
image: Buffer,
|
|
18
18
|
context: ToolContext,
|
|
19
|
-
): Promise<{ result:
|
|
19
|
+
): Promise<{ result: DecompilerResult }> {
|
|
20
20
|
checkRequestBounds(params);
|
|
21
21
|
const { start, end, body } = imageRange(params.imageKind, image);
|
|
22
22
|
|
|
@@ -32,25 +32,25 @@ export async function analyze(
|
|
|
32
32
|
loadImage(body, start);
|
|
33
33
|
walked = walk(body, start, end, { entryPoints, codeStarts, dataRanges, labels: params.labels });
|
|
34
34
|
} catch (error) {
|
|
35
|
-
context.log?.(`The
|
|
36
|
-
throw new WireFailure("operation-failed", `The
|
|
35
|
+
context.log?.(`The decoder failed: ${describeError(error)}`);
|
|
36
|
+
throw new WireFailure("operation-failed", `The decoder failed: ${describeError(error)}. Nothing was imported.`);
|
|
37
37
|
}
|
|
38
38
|
const { decompilations, notDecompiled } = decompileRoutines(params, walked.functions, body, start, context);
|
|
39
39
|
|
|
40
|
-
let result:
|
|
40
|
+
let result: DecompilerResult;
|
|
41
41
|
try {
|
|
42
|
-
result =
|
|
42
|
+
result = checkDecompilerResult({ ...walked, decompilations, notDecompiled, completeness: { functions: true, regions: true, references: true }, toolVersion: SLEIGH_VERSION });
|
|
43
43
|
} catch (error) {
|
|
44
|
-
context.log?.(`
|
|
45
|
-
throw new WireFailure("operation-failed", `
|
|
44
|
+
context.log?.(`Decompiler result rejected: ${describeError(error)}`);
|
|
45
|
+
throw new WireFailure("operation-failed", `The decompiler returned an incomplete or inconsistent result. Nothing was imported. The check found: ${describeError(error)}.`);
|
|
46
46
|
}
|
|
47
47
|
return { result };
|
|
48
48
|
}
|
|
49
49
|
|
|
50
50
|
/** The requested routines as C text, within the character bounds; the labels name routines and data. */
|
|
51
|
-
function decompileRoutines(params:
|
|
52
|
-
const decompilations:
|
|
53
|
-
const notDecompiled: NonNullable<
|
|
51
|
+
function decompileRoutines(params: DecompilerParams, functions: DecompilerResult["functions"], body: Uint8Array, start: number, context: ToolContext): Pick<DecompilerResult, "decompilations" | "notDecompiled"> {
|
|
52
|
+
const decompilations: DecompilerResult["decompilations"] = [];
|
|
53
|
+
const notDecompiled: NonNullable<DecompilerResult["notDecompiled"]> = [];
|
|
54
54
|
if (params.decompile.length === 0) return { decompilations, notDecompiled };
|
|
55
55
|
const entries = new Set(functions.map((fn) => fn.entry));
|
|
56
56
|
// A trap in the decompiler drops its image: the next routine loads it again.
|
|
@@ -63,12 +63,12 @@ function decompileRoutines(params: GhidraParams, functions: GhidraResult["functi
|
|
|
63
63
|
setName(label.address, label.name, entries.has(label.address) ? "function" : "data");
|
|
64
64
|
} catch (error) {
|
|
65
65
|
// The decompiler then prints its own name for the address.
|
|
66
|
-
context.log?.(`The
|
|
66
|
+
context.log?.(`The decompiler refused the name ${label.name}: ${describeError(error)}`);
|
|
67
67
|
}
|
|
68
68
|
}
|
|
69
69
|
prepared = true;
|
|
70
70
|
};
|
|
71
|
-
let remaining =
|
|
71
|
+
let remaining = DECOMPILER_LIMITS.decompiledTotalChars;
|
|
72
72
|
for (const entry of params.decompile) {
|
|
73
73
|
if (!entries.has(entry)) {
|
|
74
74
|
notDecompiled.push({ entry, reason: "no function starts at this address" });
|
|
@@ -84,11 +84,11 @@ function decompileRoutines(params: GhidraParams, functions: GhidraResult["functi
|
|
|
84
84
|
text = decompile(entry);
|
|
85
85
|
} catch (error) {
|
|
86
86
|
prepared = false;
|
|
87
|
-
context.log?.(`The
|
|
87
|
+
context.log?.(`The decompiler failed at ${entry}: ${describeError(error)}`);
|
|
88
88
|
notDecompiled.push({ entry, reason: describeError(error).slice(0, MAX_REASON) || "the decompiler gave no reason" });
|
|
89
89
|
continue;
|
|
90
90
|
}
|
|
91
|
-
const limit = Math.min(
|
|
91
|
+
const limit = Math.min(DECOMPILER_LIMITS.decompiledChars, remaining);
|
|
92
92
|
const truncated = text.length > limit;
|
|
93
93
|
if (truncated) text = text.slice(0, limit);
|
|
94
94
|
remaining -= text.length;
|
|
@@ -264,7 +264,7 @@ REL: target is rel [ target = inst_next + rel; ] { export *:2 target; }
|
|
|
264
264
|
|
|
265
265
|
# BRK skips its padding byte: the return address is two bytes on.
|
|
266
266
|
# The vector at $FFFE is in ROM unless the program banks the KERNAL out, and
|
|
267
|
-
# the analysis cannot know the banking. Thus BRK ends the flow, and
|
|
267
|
+
# the analysis cannot know the banking. Thus BRK ends the flow, and the decompiler
|
|
268
268
|
# does not follow the RAM bytes at $FFFE of a flat image.
|
|
269
269
|
:BRK is op=0x00 {
|
|
270
270
|
*:2 (SP - 1) = inst_next + 1;
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
// code before it, or else from the pointer in the image.
|
|
7
7
|
|
|
8
8
|
import { SYMBOL_NAME } from "../../c64.ts";
|
|
9
|
-
import type {
|
|
9
|
+
import type { DecompilerInstruction, DecompilerResult } from "../types.ts";
|
|
10
10
|
import { PcodeState } from "./pcode.ts";
|
|
11
11
|
import { decode, type Decoded, type Varnode } from "./wasm.ts";
|
|
12
12
|
|
|
@@ -39,7 +39,7 @@ function operandValue(bytes: readonly number[]): number | undefined {
|
|
|
39
39
|
}
|
|
40
40
|
|
|
41
41
|
/** Decodes [start, end] from the seeds; the image bytes are already loaded at start. */
|
|
42
|
-
export function walk(image: Uint8Array, start: number, end: number, seeds: WalkSeeds): Omit<
|
|
42
|
+
export function walk(image: Uint8Array, start: number, end: number, seeds: WalkSeeds): Omit<DecompilerResult, "decompilations" | "completeness" | "toolVersion"> {
|
|
43
43
|
const isData = new Uint8Array(0x10000);
|
|
44
44
|
for (const range of seeds.dataRanges) isData.fill(1, range.start, range.end + 1);
|
|
45
45
|
const imageByte = (address: number) => (address >= start && address <= end ? image[address - start] : undefined);
|
|
@@ -147,7 +147,7 @@ export function walk(image: Uint8Array, start: number, end: number, seeds: WalkS
|
|
|
147
147
|
const labels = new Map(seeds.labels.map((label) => [label.address, label.name]));
|
|
148
148
|
const sorted = [...instructions.keys()].sort((a, b) => a - b);
|
|
149
149
|
const seen = new Set<string>();
|
|
150
|
-
const references:
|
|
150
|
+
const references: DecompilerResult["references"] = [];
|
|
151
151
|
for (const from of sorted) {
|
|
152
152
|
for (const { to, type } of instructions.get(from)!.references) {
|
|
153
153
|
const id = `${from}:${to}:${type}`;
|
|
@@ -167,7 +167,7 @@ export function walk(image: Uint8Array, start: number, end: number, seeds: WalkS
|
|
|
167
167
|
}),
|
|
168
168
|
regions: regions(start, end, (address) => (owner[address] !== -1 ? "code" : isData[address] ? "data" : undefined)),
|
|
169
169
|
references,
|
|
170
|
-
instructions: sorted.map((address):
|
|
170
|
+
instructions: sorted.map((address): DecompilerInstruction => {
|
|
171
171
|
const { decoded, flows } = instructions.get(address)!;
|
|
172
172
|
return { address, bytes: decoded.bytes.map((byte) => byte.toString(16).padStart(2, "0")).join(""), mnemonic: decoded.mnemonic.toLowerCase(), operands: decoded.operands, flows };
|
|
173
173
|
}),
|
|
@@ -190,8 +190,8 @@ function indirectTarget(address: number, decoded: Decoded, instructions: Map<num
|
|
|
190
190
|
return exit.kind === "indirect" && exit.next !== undefined && exit.next !== 0 ? exit.next : undefined;
|
|
191
191
|
}
|
|
192
192
|
|
|
193
|
-
function regions(start: number, end: number, kind: (address: number) => "code" | "data" | undefined):
|
|
194
|
-
const result:
|
|
193
|
+
function regions(start: number, end: number, kind: (address: number) => "code" | "data" | undefined): DecompilerResult["regions"] {
|
|
194
|
+
const result: DecompilerResult["regions"] = [];
|
|
195
195
|
for (let address = start; address <= end; address++) {
|
|
196
196
|
const classification = kind(address);
|
|
197
197
|
if (classification === undefined) continue;
|
package/src/native/types.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// Types of the native tools that skill scripts run directly (ACME, DXA,
|
|
2
|
-
//
|
|
2
|
+
// the decompiler), and the checks of their complete results. The skill script runs
|
|
3
3
|
// these tools itself: nothing here crosses the Host Runtime wire. Bytes
|
|
4
4
|
// (a program, an image, a listing) go next to these values as attachments.
|
|
5
5
|
|
|
@@ -43,14 +43,14 @@ export interface AcmeResult {
|
|
|
43
43
|
export const IMAGE_KINDS = ["prg", "flat64k"] as const;
|
|
44
44
|
export type ImageKind = (typeof IMAGE_KINDS)[number];
|
|
45
45
|
|
|
46
|
-
export const
|
|
46
|
+
export const DECOMPILER_LIMITS = { entryPoints: 1024, codeStarts: 8192, dataRanges: 1024, labels: 4096, decompile: 32, decompiledChars: 16_000, decompiledTotalChars: 128_000 } as const;
|
|
47
47
|
|
|
48
|
-
/** The
|
|
49
|
-
export interface
|
|
48
|
+
/** The analysis. Its image is given next to these fields: a PRG, or 64 KiB from $0000. */
|
|
49
|
+
export interface DecompilerParams {
|
|
50
50
|
imageKind: ImageKind;
|
|
51
51
|
/** Seeds from current knowledge. */
|
|
52
52
|
entryPoints: number[];
|
|
53
|
-
/** Executed instruction starts that
|
|
53
|
+
/** Executed instruction starts that the decompiler disassembles without making a function: a branch target is no routine. */
|
|
54
54
|
codeStarts?: number[];
|
|
55
55
|
dataRanges: Array<{ start: number; end: number }>;
|
|
56
56
|
labels: Array<{ address: number; name: string }>;
|
|
@@ -58,7 +58,7 @@ export interface GhidraParams {
|
|
|
58
58
|
decompile: number[];
|
|
59
59
|
}
|
|
60
60
|
|
|
61
|
-
export interface
|
|
61
|
+
export interface DecompilerInstruction {
|
|
62
62
|
address: number;
|
|
63
63
|
/** Lowercase hex, 1 to 3 bytes. */
|
|
64
64
|
bytes: string;
|
|
@@ -69,7 +69,7 @@ export interface GhidraInstruction {
|
|
|
69
69
|
flows: number[];
|
|
70
70
|
}
|
|
71
71
|
|
|
72
|
-
export interface
|
|
72
|
+
export interface DecompilerResult {
|
|
73
73
|
coverage: Array<{ start: number; end: number }>;
|
|
74
74
|
functions: Array<{ entry: number; name: string; nameSource: "seed" | "generated" | "native" }>;
|
|
75
75
|
regions: Array<{ start: number; end: number; classification: "code" | "data" }>;
|
|
@@ -77,30 +77,30 @@ export interface GhidraResult {
|
|
|
77
77
|
decompilations: Array<{ entry: number; text: string; truncated: boolean }>;
|
|
78
78
|
/** Requested routines without decompiled code, with the decompiler's reason. */
|
|
79
79
|
notDecompiled?: Array<{ entry: number; reason: string }>;
|
|
80
|
-
/** Every instruction in the coverage, as
|
|
81
|
-
instructions:
|
|
80
|
+
/** Every instruction in the coverage, as the decompiler decoded it. */
|
|
81
|
+
instructions: DecompilerInstruction[];
|
|
82
82
|
/** Which categories are complete inside the coverage; private to the importer. */
|
|
83
83
|
completeness: { functions: boolean; regions: boolean; references: boolean };
|
|
84
84
|
/** The version of the Ghidra port that made the result, for example "ghidra-decompiler 2.1.0". */
|
|
85
85
|
toolVersion?: string;
|
|
86
86
|
}
|
|
87
87
|
|
|
88
|
-
/** Refuses a DXA or
|
|
88
|
+
/** Refuses a DXA or decompiler request with more seeds or decompilations than the request bounds allow, by name. */
|
|
89
89
|
export function checkRequestBounds(params: DxaParams & { decompile?: number[]; codeStarts?: number[] }): void {
|
|
90
90
|
const bounds = [
|
|
91
|
-
["entry points", params.entryPoints.length,
|
|
92
|
-
["code starts", params.codeStarts?.length ?? 0,
|
|
93
|
-
["data ranges", params.dataRanges.length,
|
|
94
|
-
["labels", params.labels.length,
|
|
95
|
-
["routines to decompile", params.decompile?.length ?? 0,
|
|
91
|
+
["entry points", params.entryPoints.length, DECOMPILER_LIMITS.entryPoints],
|
|
92
|
+
["code starts", params.codeStarts?.length ?? 0, DECOMPILER_LIMITS.codeStarts],
|
|
93
|
+
["data ranges", params.dataRanges.length, DECOMPILER_LIMITS.dataRanges],
|
|
94
|
+
["labels", params.labels.length, DECOMPILER_LIMITS.labels],
|
|
95
|
+
["routines to decompile", params.decompile?.length ?? 0, DECOMPILER_LIMITS.decompile],
|
|
96
96
|
] as const;
|
|
97
97
|
for (const [name, count, limit] of bounds) {
|
|
98
98
|
if (count > limit) throw new WireFailure("invalid-input", `The request has ${count} ${name}. Give at most ${limit} ${name}.`);
|
|
99
99
|
}
|
|
100
100
|
}
|
|
101
101
|
|
|
102
|
-
/** The DXA analysis: the same image and seeds as
|
|
103
|
-
export type DxaParams = Omit<
|
|
102
|
+
/** The DXA analysis: the same image and seeds as the decompiler, without decompilation. */
|
|
103
|
+
export type DxaParams = Omit<DecompilerParams, "decompile" | "codeStarts">;
|
|
104
104
|
|
|
105
105
|
export interface DxaResult {
|
|
106
106
|
coverage: Array<{ start: number; end: number }>;
|
|
@@ -129,11 +129,11 @@ function fail(message: string): never {
|
|
|
129
129
|
const isList = (value: unknown): value is unknown[] => Array.isArray(value);
|
|
130
130
|
|
|
131
131
|
/**
|
|
132
|
-
* Checks a complete
|
|
132
|
+
* Checks a complete decompiler result: every field typed and in range, every
|
|
133
133
|
* function, region and reference source inside the coverage, regions sorted
|
|
134
134
|
* and without overlap. Throws an Error naming the first problem.
|
|
135
135
|
*/
|
|
136
|
-
export function
|
|
136
|
+
export function checkDecompilerResult(value: unknown): DecompilerResult {
|
|
137
137
|
if (!isObject(value)) fail("not an object");
|
|
138
138
|
const { coverage, functions, regions, references, decompilations, notDecompiled, completeness, toolVersion, instructions } = value;
|
|
139
139
|
if (!isList(coverage) || coverage.length === 0) fail("no coverage");
|
|
@@ -179,16 +179,16 @@ export function checkGhidraResult(value: unknown): GhidraResult {
|
|
|
179
179
|
if (!isObject(reference) || !isInteger(reference.from, 0, 0xffff) || !isInteger(reference.to, 0, 0xffff) || !isOneOf(REFERENCE_KINDS, reference.type)) fail("bad reference");
|
|
180
180
|
if (!covered(reference.from)) fail("a reference source lies outside the coverage");
|
|
181
181
|
}
|
|
182
|
-
if (!isList(decompilations) || decompilations.length >
|
|
182
|
+
if (!isList(decompilations) || decompilations.length > DECOMPILER_LIMITS.decompile) fail("bad decompilations");
|
|
183
183
|
let total = 0;
|
|
184
184
|
for (const item of decompilations) {
|
|
185
185
|
if (!isObject(item) || !isInteger(item.entry, 0, 0xffff) || typeof item.text !== "string" || typeof item.truncated !== "boolean") fail("bad decompilation");
|
|
186
|
-
if (item.text.length >
|
|
186
|
+
if (item.text.length > DECOMPILER_LIMITS.decompiledChars) fail("a decompilation is too long");
|
|
187
187
|
total += item.text.length;
|
|
188
188
|
}
|
|
189
|
-
if (total >
|
|
189
|
+
if (total > DECOMPILER_LIMITS.decompiledTotalChars) fail("the decompilations are too long together");
|
|
190
190
|
if (notDecompiled !== undefined) {
|
|
191
|
-
if (!isList(notDecompiled) || notDecompiled.length >
|
|
191
|
+
if (!isList(notDecompiled) || notDecompiled.length > DECOMPILER_LIMITS.decompile) fail("bad list of routines that were not decompiled");
|
|
192
192
|
for (const item of notDecompiled) {
|
|
193
193
|
if (!isObject(item) || !isInteger(item.entry, 0, 0xffff) || typeof item.reason !== "string" || item.reason.length > 1000) fail("bad routine that was not decompiled");
|
|
194
194
|
}
|
|
@@ -196,7 +196,7 @@ export function checkGhidraResult(value: unknown): GhidraResult {
|
|
|
196
196
|
if (!isObject(completeness) || typeof completeness.functions !== "boolean" || typeof completeness.regions !== "boolean" || typeof completeness.references !== "boolean") fail("no completeness");
|
|
197
197
|
if (!isToolVersion(toolVersion)) fail("bad tool version");
|
|
198
198
|
// Every field is checked: the object is the result as it is.
|
|
199
|
-
return value as unknown as
|
|
199
|
+
return value as unknown as DecompilerResult;
|
|
200
200
|
}
|
|
201
201
|
|
|
202
202
|
/**
|
|
@@ -249,7 +249,7 @@ export function imageRange(kind: ImageKind, image: Uint8Array): { start: number;
|
|
|
249
249
|
* it, and the data ranges cut to it. A data range that holds an entry point
|
|
250
250
|
* is left out, so that the entry point is disassembled.
|
|
251
251
|
*/
|
|
252
|
-
export function seedsInside(params: Pick<
|
|
252
|
+
export function seedsInside(params: Pick<DecompilerParams, "entryPoints" | "dataRanges" | "codeStarts">, start: number, end: number): { entryPoints: number[]; codeStarts: number[]; dataRanges: DecompilerParams["dataRanges"] } {
|
|
253
253
|
const inside = (address: number) => address >= start && address <= end;
|
|
254
254
|
const entryPoints = params.entryPoints.filter(inside);
|
|
255
255
|
const codeStarts = (params.codeStarts ?? []).filter(inside);
|
package/src/opcodes.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// The ACME spelling of each 6510 opcode: the mnemonic and the addressing
|
|
2
|
-
// mode, undocumented opcodes included.
|
|
2
|
+
// mode, undocumented opcodes included. The decompiler gives the instruction
|
|
3
3
|
// boundaries; this table gives the text. Where several opcodes share one
|
|
4
4
|
// spelling, ACME writes only one of them: the generator finds those with a
|
|
5
5
|
// probe and writes the others as bytes.
|
package/src/script.ts
CHANGED
|
@@ -129,7 +129,7 @@ export const OPTIONS = {
|
|
|
129
129
|
"timeout-frames": { kind: "count", value: "<n>", help: "stop a wait after this number of video frames", min: 1, max: 1_000_000 },
|
|
130
130
|
"max-listed": { kind: "count", value: "<n>", help: "list at most n items of each list (default 50). The counts are always given", min: 0, max: 100_000, default: 50 },
|
|
131
131
|
symbols: { kind: "path", value: "<file>", help: "the symbols of a build: the symbols file of the assembler, or a JSON map of name to $ address" },
|
|
132
|
-
origin: { kind: "text", value: "<origin>", help: "user, llm, dxa,
|
|
132
|
+
origin: { kind: "text", value: "<origin>", help: "user, llm, dxa, decompiler, heuristic, semantic (user and llm) or analyzer (dxa, decompiler and heuristic), or a comma list" },
|
|
133
133
|
reason: { kind: "text", value: "<text>", help: "why: kept with the revision" },
|
|
134
134
|
evidence: { kind: "text", value: "<kind:ref>", help: "what the change rests on: coverage:<map>, test:<file>, file:<file> or note:<text>", multiple: true },
|
|
135
135
|
"expect-revision": { kind: "text", value: "<revision>", help: "refuse the write when the knowledge changed after this revision" },
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|