@henols/c64-re-tools 2.6.0-rc.13 → 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.
Files changed (32) hide show
  1. package/package.json +1 -1
  2. package/skills/c64-docs/scripts/lib/reference.ts +1 -1
  3. package/skills/c64-knowledge/SKILL.md +3 -3
  4. package/skills/c64-knowledge/scripts/knowledge.ts +2 -2
  5. package/skills/c64-source/SKILL.md +1 -1
  6. package/skills/c64-source/scripts/lib/export.ts +1 -1
  7. package/skills/c64-source/scripts/lib/source.ts +4 -4
  8. package/skills/c64-source/scripts/source.ts +13 -13
  9. package/skills/c64-static-analysis/SKILL.md +20 -20
  10. package/skills/c64-static-analysis/scripts/lib/findings.ts +11 -11
  11. package/skills/c64-static-analysis/scripts/lib/instructions.ts +4 -4
  12. package/skills/c64-static-analysis/scripts/static-analysis.ts +23 -23
  13. package/src/c64.ts +1 -1
  14. package/src/host/tools/index.ts +1 -1
  15. package/src/host-client/tools.ts +1 -1
  16. package/src/knowledge/import.ts +5 -5
  17. package/src/knowledge/program.ts +1 -1
  18. package/src/knowledge/read.ts +3 -3
  19. package/src/knowledge/schema.ts +3 -3
  20. package/src/native/{ghidra → decompiler}/analyze.ts +17 -17
  21. package/src/native/{ghidra → decompiler}/language/c64rt_6510.slaspec +1 -1
  22. package/src/native/{ghidra → decompiler}/walk.ts +6 -6
  23. package/src/native/types.ts +25 -25
  24. package/src/opcodes.ts +1 -1
  25. package/src/script.ts +1 -1
  26. /package/src/native/{ghidra → decompiler}/c64rt-wasm.ts +0 -0
  27. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.cspec +0 -0
  28. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.ldefs +0 -0
  29. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.pspec +0 -0
  30. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.sla +0 -0
  31. /package/src/native/{ghidra → decompiler}/pcode.ts +0 -0
  32. /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.13",
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: Ghidra gives an indexed read (lda table,x) as "reference". */
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, 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`.
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`, `ghidra`, `heuristic`, `semantic` (user and llm), `analyzer` (dxa, ghidra and heuristic), or a comma list. The default is all origins. |
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 Ghidra. 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.
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.
@@ -299,7 +299,7 @@ function listingSource(db: DatabaseSync | undefined, space: string): ListingSour
299
299
  /** Every value of --origin, for the message of a wrong one. */
300
300
  const ORIGIN_VALUES = `one of ${ORIGINS.join(", ")}, semantic or analyzer, or a comma list of them. semantic is ${SEMANTIC_ORIGINS.join(" and ")}. analyzer is ${ANALYZERS.slice(0, -1).join(", ")} and ${ANALYZERS.at(-1)}`;
301
301
 
302
- /** --origin for reads: one origin, semantic (user and llm), analyzer (dxa, ghidra and heuristic), or a comma list. */
302
+ /** --origin for reads: one origin, semantic (user and llm), analyzer (dxa, decompiler and heuristic), or a comma list. */
303
303
  function originFilter(value: string): Origin[] {
304
304
  const origins = new Set<Origin>();
305
305
  for (const part of value.split(",")) {
@@ -558,7 +558,7 @@ const READ_COMMANDS: CommandSpec[] = [
558
558
  },
559
559
  ),
560
560
  readCommand(
561
- { name: "symbols", summary: "The symbols, or with --analyzer the second names that DXA, Ghidra and the idioms gave.", options: { ...FILTER, kind: SYMBOL_KIND, analyzer: { kind: "flag", help: "the analyzer names in place of the symbols" }, ...LIST } },
561
+ { name: "symbols", summary: "The symbols, or with --analyzer the second names that DXA, the decompiler and the idioms gave.", options: { ...FILTER, kind: SYMBOL_KIND, analyzer: { kind: "flag", help: "the analyzer names in place of the symbols" }, ...LIST } },
562
562
  (db, call) => {
563
563
  const kind = call.string("kind") as (typeof SYMBOL_KINDS)[number] | undefined;
564
564
  if (call.flag("analyzer")) return { analyzerNames: list(call, listAnalyzerNames(db, rangeOf(call), kind, originsOf(call), call.space), symbol, RANGE_REST) };
@@ -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`, `ghidra` or `heuristic`), for example `EXTCOL` over `ld020`. A `user` or `llm` name wins over a platform name.
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.
@@ -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 Ghidra decoded instructions in it: those are no code.
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 Ghidra's instruction
1
+ // ACME source from an image, current knowledge and the decompiler's instruction
2
2
  // boundaries. The same input gives the same text. Names come from
3
3
  // knowledge; a target that knowledge does not name gets l_xxxx. A read or
4
4
  // write in the I/O area names the register, also where the image holds RAM. Data is
@@ -30,7 +30,7 @@ export interface SourceInput {
30
30
  /** The image byte at an address inside a segment. */
31
31
  byteAt: (address: number) => number;
32
32
  entry?: number;
33
- /** Where Ghidra decoded an instruction, with its length. */
33
+ /** Where the decompiler decoded an instruction, with its length. */
34
34
  instructions: ReadonlyMap<number, number>;
35
35
  /** Without an origin, a symbol counts as a user or LLM name. */
36
36
  symbols: ReadonlyArray<{ address: number; name: string; origin?: Origin }>;
@@ -204,7 +204,7 @@ interface DataItem {
204
204
  kind: "data";
205
205
  start: number;
206
206
  end: number;
207
- /** The region type, or unclassified. In a code region, bytes that Ghidra did not decode. */
207
+ /** The region type, or unclassified. In a code region, bytes that the decompiler did not decode. */
208
208
  type: RegionType | "unclassified" | "undecoded";
209
209
  region?: Region;
210
210
  }
@@ -280,7 +280,7 @@ function operandValue(address: number, opcode: number, byteAt: (address: number)
280
280
 
281
281
  /**
282
282
  * Each entry point inside a data region of the knowledge, with that region.
283
- * A data region wins over an entry: Ghidra does not decode there,
283
+ * A data region wins over an entry: the decompiler does not decode there,
284
284
  * and the source has data there. A code region in the knowledge changes that.
285
285
  */
286
286
  export function entriesInData<R extends { start: number; end: number; type: RegionType }>(entries: readonly number[], regions: readonly R[]): Array<{ entry: number; region: R }> {
@@ -1,5 +1,5 @@
1
1
  // The c64-source script: generates ACME source from the program and the
2
- // knowledge and Ghidra's instructions, which it runs itself, and checks
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/ghidra/analyze.ts";
33
+ import { analyze } from "#src/native/decompiler/analyze.ts";
34
34
  import { localToolContext } from "#src/native/local.ts";
35
- import { GHIDRA_LIMITS, type AssembledSymbol, type Diagnostic } from "#src/native/types.ts";
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, Ghidra, DXA. An analyzer
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
- * Ghidra's instruction starts and lengths inside the image, seeded from the
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 Ghidra does not run.
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, GHIDRA_LIMITS.entryPoints),
189
- codeStarts: flows.codeStarts.filter((address) => !seeds.has(address)).slice(0, GHIDRA_LIMITS.codeStarts),
190
- dataRanges: dataRanges.slice(0, GHIDRA_LIMITS.dataRanges),
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 Ghidra decoded, and whether the program has known code. */
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 Ghidra. */
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 Ghidra does not run again. */
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 Ghidra and the ROM use. */
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 Ghidra, without running it. It records the code and data regions, the analyzer names and the references in the project knowledge. Use it to get a fast first pass of code and data, and a disassembly listing. Use it to get the routines, the references, an instruction list and decompiled code. Use it when the project knowledge has coverage, to find code that only a vector, a table or an interrupt reaches. Use it to find 6502 idioms, pointer candidates, raster pitfalls and macro candidates. It does not run the program. It does not give names to routines.
3
+ description: Finds the structure of a C64 program with DXA or the decompiler, without running it. It records the code and data regions, the analyzer names and the references in the project knowledge. Use it to get a fast first pass of code and data, and a disassembly listing. Use it to get the routines, the references, an instruction list and decompiled code. Use it when the project knowledge has coverage, to find code that only a vector, a table or an interrupt reaches. Use it to find 6502 idioms, pointer candidates, raster pitfalls and macro candidates. It does not run the program. It does not give names to routines.
4
4
  ---
5
5
 
6
6
  # Static analysis
@@ -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 Ghidra result.
47
- - Ghidra needs at least one entry point. DXA finds the SYS address of a BASIC start without help.
46
+ - An address in `functions` of an earlier decompiler result.
47
+ - The decompiler needs at least one entry point. DXA finds the SYS address of a BASIC start without help.
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
- - Ghidra 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 Ghidra result, or from the routines in the project knowledge.
54
+ - The decompiler does not follow BRK. If the program removes the KERNAL and uses the BRK vector, give the target of the vector with `--entry`.
55
+ - `--decompile` takes the address of a routine. Get it from `functions` of an earlier decompiler result, or from the routines in the project knowledge.
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\|ghidra>` | `analyze` | The analyzer. `dxa` gives a fast first pass. `ghidra` gives a deeper pass. The default is `ghidra`. |
83
+ | `--analyzer <dxa\|decompiler>` | `analyze` | The analyzer. `dxa` gives a fast first pass. `decompiler` gives a deeper pass. The default is `decompiler`. |
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` | Ghidra only. Decompile the routine at this address. Give it again for more routines, at most 32. There is no default. |
85
+ | `--decompile <address>` | `analyze` | Only with `--analyzer decompiler`. Decompile the routine at this address. Give it again for more routines, at most 32. There is no default. |
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` | Ghidra only. Write each instruction to this project file as JSON. There is no default. |
89
+ | `--out-instructions <file>` | `analyze` | Only with `--analyzer decompiler`. Write each instruction to this project file as JSON. There is no default. |
90
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 Ghidra over the program in the project knowledge. The script records the findings in the project knowledge as one revision. Then it records the 6502 idioms as a second revision. When the findings do not change the knowledge, the script records no revision for them.
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 Ghidra. It does not record the listing or the decompiled code. Do not record the listing, the decompiled code or the function list as comments in the project knowledge.
101
+ The script records only structure: code and data regions, analyzer names, and the references from the decompiler. It does not record the listing or the decompiled code. Do not record the listing, the decompiled code or the function list as comments in the project knowledge.
102
102
 
103
103
  `body` holds these fields for both analyzers:
104
104
 
105
- - `analyzer`: `dxa` or `ghidra`. `analyzerVersion` gives the version of the analyzer when the analyzer tells it. `space` is in `body` only for a space that is not `c64`.
105
+ - `analyzer`: `dxa` or `decompiler`. `analyzerVersion` gives the version of the analyzer when the analyzer tells it. `space` is in `body` only for a space that is not `c64`.
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,13 +117,13 @@ 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
- Ghidra also gives:
120
+ The decompiler also gives:
121
121
 
122
- - `functions`: the routines that Ghidra found, as a list, each with `entry` and `name`.
122
+ - `functions`: the routines that the decompiler found, as a list, each with `entry` and `name`.
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 Ghidra did not decompile, each with a `reason`.
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 Ghidra.
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
 
@@ -148,14 +148,14 @@ The script does not record the candidates. Examine each candidate and decide.
148
148
  #### Which facts the analysis replaces
149
149
 
150
150
  - The analysis never replaces a name or a region of the user or the LLM. Each disagreement shows in `conflicts`.
151
- - DXA and Ghidra do not replace the facts of each other, with one exception. With coverage, a code finding replaces DXA or Ghidra data where a run executed an instruction start. Thus put all coverage maps into the project knowledge first. Then run DXA, then Ghidra.
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.
152
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`.
153
- - An idiom region (origin `heuristic`) replaces the part of a DXA or Ghidra region where it lies. DXA and Ghidra never replace an idiom region. If they find code there, the result shows a conflict.
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.
154
154
  - An idiom table can be too long or too short. Correct its region in the project knowledge. Your region replaces it.
155
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.
156
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.
157
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.
158
- - A Ghidra function that only branches and jumps reach is a `label`, not a `routine`.
158
+ - A decompiler function that only branches and jumps reach is a `label`, not a `routine`.
159
159
 
160
160
  #### Traps
161
161
 
@@ -172,7 +172,7 @@ The script does not record the candidates. Examine each candidate and decide.
172
172
 
173
173
  #### Failures
174
174
 
175
- - `invalid-input` about an entry point: Ghidra has no entry point in the program. Give one with `--entry`.
175
+ - `invalid-input` about an entry point: the decompiler has no entry point in the program. Give one with `--entry`.
176
176
  - `stale-revision`: the project knowledge changed during the analysis. The script recorded nothing. Run `analyze` again.
177
177
  - `operation-failed` about an incomplete result or listing: the analyzer did not give a complete result. The script recorded nothing. Tell the user.
178
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.
@@ -185,7 +185,7 @@ The script does not record the candidates. Examine each candidate and decide.
185
185
  2. Put each coverage map of the program into the project knowledge.
186
186
  3. Run `analyze --analyzer dxa` for a first pass. Read the listing for a quick view of the code.
187
187
  4. Find the important routines. Give them names in the project knowledge.
188
- 5. Run `analyze` with Ghidra. Give the entry points with `--entry`. Give `--decompile` for the routines that you must understand.
188
+ 5. Run `analyze` with the decompiler. Give the entry points with `--entry`. Give `--decompile` for the routines that you must understand.
189
189
  6. Do the action for each `hint`. Examine the candidates.
190
190
  7. Give each important routine a name in the project knowledge. Then run `analyze` again. The analyzers use the new names.
191
191
 
@@ -1,4 +1,4 @@
1
- // Knowledge seeds for an analyzer, and the mapping of a Ghidra result to the
1
+ // Knowledge seeds for an analyzer, and the mapping of a decompiler result to the
2
2
  // common normalized findings.
3
3
 
4
4
  import type { DatabaseSync } from "node:sqlite";
@@ -6,9 +6,9 @@ import type { DatabaseSync } from "node:sqlite";
6
6
  import type { NormalizedFindings } from "#src/knowledge/import.ts";
7
7
  import { listRegions, listSymbols } from "#src/knowledge/read.ts";
8
8
  import { CODE_REGION_TYPES, DEFAULT_SPACE, isSemantic, type Space } from "#src/knowledge/schema.ts";
9
- import type { DxaResult, GhidraParams, GhidraResult } from "#src/native/types.ts";
9
+ import type { DxaResult, DecompilerParams, DecompilerResult } from "#src/native/types.ts";
10
10
 
11
- export type Seeds = Pick<GhidraParams, "entryPoints" | "dataRanges" | "labels">;
11
+ export type Seeds = Pick<DecompilerParams, "entryPoints" | "dataRanges" | "labels">;
12
12
 
13
13
  const semantic = (row: { origin: string }) => isSemantic(row.origin);
14
14
 
@@ -49,12 +49,12 @@ export function seedsFromKnowledge(db: DatabaseSync | undefined, extraEntryPoint
49
49
 
50
50
  /**
51
51
  * The 6510 opcodes with a low nibble of 1 or 3 use (zp,x) or (zp),y, also the
52
- * undocumented ones. Ghidra gives such an instruction a reference to the target
52
+ * undocumented ones. The decompiler gives such an instruction a reference to the target
53
53
  * that it computes from the pointer value at the entry state: a guess, because
54
54
  * the program sets the pointer at run time. Only the reference to the pointer
55
55
  * itself (zp or zp+1) is a fact.
56
56
  */
57
- function guessedIndirectTarget(instructions: GhidraResult["instructions"]): (reference: { from: number; to: number }) => boolean {
57
+ function guessedIndirectTarget(instructions: DecompilerResult["instructions"]): (reference: { from: number; to: number }) => boolean {
58
58
  const pointers = new Map<number, number>();
59
59
  for (const instruction of instructions) {
60
60
  const opcode = Number.parseInt(instruction.bytes.slice(0, 2), 16);
@@ -67,28 +67,28 @@ function guessedIndirectTarget(instructions: GhidraResult["instructions"]): (ref
67
67
  }
68
68
 
69
69
  /**
70
- * Ghidra's result as normalized findings. A reference from a (zp,x) or (zp),y
70
+ * The decompiler's result as normalized findings. A reference from a (zp,x) or (zp),y
71
71
  * instruction to a computed target is not a finding (see guessedIndirectTarget).
72
72
  * A function named by an echoed seed
73
73
  * stays in the snapshot: its address holds the seed's semantic symbol, which
74
74
  * the importer never replaces, so the name keeps its owner,
75
75
  * and a code/data disagreement with that symbol is still reported.
76
76
  */
77
- export function ghidraFindings(result: GhidraResult): NormalizedFindings {
78
- // Ghidra can give one generated name to two functions, for example
77
+ export function decompilerFindings(result: DecompilerResult): NormalizedFindings {
78
+ // The decompiler can give one generated name to two functions, for example
79
79
  // thunk_FUN_e434 to two thunks of one routine. A name
80
80
  // must have one address, so a repeated name that is not a seed gets its address.
81
81
  const uses = new Map<string, number>();
82
82
  for (const fn of result.functions) uses.set(fn.name, (uses.get(fn.name) ?? 0) + 1);
83
- const nameOf = (fn: GhidraResult["functions"][number]) =>
83
+ const nameOf = (fn: DecompilerResult["functions"][number]) =>
84
84
  fn.nameSource !== "seed" && uses.get(fn.name)! > 1 ? `${fn.name}_${fn.entry.toString(16).padStart(4, "0")}` : fn.name;
85
85
  // A function that branches and jumps reach, and no call, is a place in a routine: a label.
86
86
  const called = new Set(result.references.filter((reference) => reference.type === "call").map((reference) => reference.to));
87
87
  const jumped = new Set(result.references.filter((reference) => reference.type === "jump").map((reference) => reference.to));
88
88
  const guessed = guessedIndirectTarget(result.instructions);
89
- const kindOf = (fn: GhidraResult["functions"][number]) => (jumped.has(fn.entry) && !called.has(fn.entry) ? ("label" as const) : ("routine" as const));
89
+ const kindOf = (fn: DecompilerResult["functions"][number]) => (jumped.has(fn.entry) && !called.has(fn.entry) ? ("label" as const) : ("routine" as const));
90
90
  return {
91
- analyzer: "ghidra",
91
+ analyzer: "decompiler",
92
92
  coverage: result.coverage,
93
93
  authoritative: { symbols: result.completeness.functions, regions: result.completeness.regions, references: result.completeness.references },
94
94
  symbols: result.functions.map((fn) => ({ address: fn.entry, name: nameOf(fn), kind: kindOf(fn) })),
@@ -1,10 +1,10 @@
1
- // The structured instruction list: Ghidra's decoded instructions with
1
+ // The structured instruction list: the decompiler's decoded instructions with
2
2
  // the addressing mode, the operand in 6502 syntax, the flow target and,
3
3
  // with a coverage file, whether the instruction ran.
4
4
 
5
5
  import { COVERAGE, formatC64Address } from "#src/c64.ts";
6
6
  import { OPCODES, type Mode as OpcodeMode } from "#src/opcodes.ts";
7
- import type { GhidraInstruction } from "#src/native/types.ts";
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
- /** Ghidra's instructions as the list that --out-instructions writes. */
92
- export function instructionList(instructions: GhidraInstruction[], coverage?: Uint8Array): ListedInstruction[] {
91
+ /** The decompiler's instructions as the list that --out-instructions writes. */
92
+ export function instructionList(instructions: DecompilerInstruction[], coverage?: Uint8Array): ListedInstruction[] {
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 Ghidra (deeper), which it runs itself, seeded
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,9 +9,9 @@ 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 analyzeWithGhidra } from "#src/native/ghidra/analyze.ts";
12
+ import { analyze as analyzeWithDecompiler } from "#src/native/decompiler/analyze.ts";
13
13
  import { localToolContext } from "#src/native/local.ts";
14
- import { GHIDRA_LIMITS } from "#src/native/types.ts";
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";
@@ -21,7 +21,7 @@ import { DEFAULT_SPACE, SEMANTIC_ORIGINS, type Analyzer } from "#src/knowledge/s
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, ghidraFindings, seedsFromKnowledge } from "./lib/findings.ts";
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";
@@ -178,15 +178,15 @@ async function analyze(call: Call): Promise<unknown> {
178
178
  const decompile = call.addresses("decompile");
179
179
  if (decompile.length > 32) throw new UsageError("--decompile takes at most 32 routines");
180
180
  const max = call.count("max-listed")!;
181
- const analyzer = call.string("analyzer") as "dxa" | "ghidra";
181
+ const analyzer = call.string("analyzer") as "dxa" | "decompiler";
182
182
  const listingPath = call.string("out-listing");
183
183
  const instructionsPath = call.string("out-instructions");
184
184
  const applyMacros = call.flag("apply-macros");
185
185
  const skip = new Set(call.addresses("skip"));
186
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");
187
- if (analyzer === "dxa" && decompile.length > 0) throw new UsageError("--decompile works only with --analyzer ghidra");
188
- if (analyzer === "ghidra" && 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 ghidra");
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");
190
190
  const space = call.space;
191
191
  const reader = openForRead();
192
192
  const program = requireProgram(reader, space);
@@ -206,21 +206,21 @@ async function analyze(call: Call): Promise<unknown> {
206
206
  const revision = currentRevision(reader);
207
207
  const seeds = seedsFromKnowledge(reader, entries, space, executed.executed);
208
208
  // Knowledge routines and --entry first, then code regions and JMP tables, then idioms, then coverage, up to the seed bound:
209
- // at most GHIDRA_LIMITS.entryPoints (1024) entry points for both analyzers, and for Ghidra at most
210
- // GHIDRA_LIMITS.codeStarts (8192) coverage flow starts that are code in a routine. coverageSeeds gives what was used.
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.
211
211
  const fromCoverage = coverage === undefined ? [] : coverageEntries(coverage, inProgram);
212
212
  const known = [...seeds.entryPoints, ...codeEntries(reader, byteAt, space)];
213
- // Ghidra takes the coverage as code starts without a function; DXA has one list.
213
+ // The decompiler takes the coverage as code starts without a function; DXA has one list.
214
214
  const kinds = analyzer === "dxa" || coverage === undefined ? { routines: fromCoverage, codeStarts: [] } : coverageSeedKinds(coverage, inProgram);
215
215
  const ordered = [...new Set([...known, ...idioms.entryPoints, ...kinds.routines])];
216
- seeds.entryPoints = ordered.slice(0, GHIDRA_LIMITS.entryPoints).sort((a, b) => a - b);
217
- const codeStarts = kinds.codeStarts.filter((entry) => !seeds.entryPoints.includes(entry)).slice(0, GHIDRA_LIMITS.codeStarts);
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);
218
218
  // Idiom tables and the RAM under ROM that the runs never used are data for this run too; semantic data ranges come first.
219
219
  // A range with an entry point of the knowledge or --entry in it is left out: that code stays code.
220
220
  const fromRom = coverage === undefined ? [] : romOnlyRanges(coverage, byteAt).filter((range) => !known.some((entry) => entry >= range.start && entry <= range.end));
221
221
  const dataRanges = [...seeds.dataRanges];
222
222
  for (const range of [...idioms.dataRanges, ...fromRom]) if (!dataRanges.some((seed) => range.start <= seed.end && range.end >= seed.start)) dataRanges.push(range);
223
- seeds.dataRanges = dataRanges.slice(0, GHIDRA_LIMITS.dataRanges);
223
+ seeds.dataRanges = dataRanges.slice(0, DECOMPILER_LIMITS.dataRanges);
224
224
  const romUsed = fromRom.filter((range) => seeds.dataRanges.includes(range)).length;
225
225
  const coverageUsed = fromCoverage.filter((entry) => seeds.entryPoints.includes(entry) || codeStarts.includes(entry)).length;
226
226
  // Platform names are C64 names: drive code and banks get none.
@@ -316,10 +316,10 @@ async function analyze(call: Call): Promise<unknown> {
316
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 });
317
317
  }
318
318
 
319
- const { result } = await analyzeWithGhidra({ imageKind, ...seeds, codeStarts, decompile }, bytes, localToolContext());
320
- // Executed instruction starts that Ghidra did not decode: the instruction list and the source miss them.
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.
321
321
  const decoded = new Set(result.instructions.map((instruction) => instruction.address));
322
- const imported = record({ ...ghidraFindings(result), space, ...executed }, revision, "Ghidra analysis of the program", runProvenance(bytes, result.toolVersion));
322
+ const imported = record({ ...decompilerFindings(result), space, ...executed }, revision, "Decompiler analysis of the program", runProvenance(bytes, result.toolVersion));
323
323
  const found = idiomsResult();
324
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.
325
325
  // Read after the idioms, which write those regions.
@@ -333,7 +333,7 @@ async function analyze(call: Call): Promise<unknown> {
333
333
  instructions = { count: list.length, ...writeReported(instructionsPath, `${JSON.stringify(list, null, 1)}\n`, { what: "--out-instructions" }) };
334
334
  }
335
335
  const body = {
336
- analyzer: "ghidra",
336
+ analyzer: "decompiler",
337
337
  ...(result.toolVersion === undefined ? {} : { analyzerVersion: result.toolVersion }),
338
338
  ...(space === DEFAULT_SPACE ? {} : { space }),
339
339
  ...(instructions === undefined ? {} : { instructions }),
@@ -353,24 +353,24 @@ async function analyze(call: Call): Promise<unknown> {
353
353
 
354
354
  await runScript({
355
355
  name: "static-analysis",
356
- summary: "Analyzes the program in the knowledge with DXA or Ghidra, seeded from the knowledge and its coverage, and imports the structural findings into the knowledge.",
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.",
357
357
  names: knowledgeNames,
358
358
  commands: [
359
359
  {
360
360
  name: "analyze",
361
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.",
362
362
  options: {
363
- analyzer: { kind: "choice", value: "<dxa|ghidra>", choices: ["dxa", "ghidra"], default: "ghidra", help: "dxa (a fast first pass) or ghidra (deeper, the default)" },
363
+ analyzer: { kind: "choice", value: "<dxa|decompiler>", choices: ["dxa", "decompiler"], default: "decompiler", help: "dxa (a fast first pass) or decompiler (deeper, the default)" },
364
364
  entry: { ...OPTIONS.entry, multiple: true, help: "an entry point of the program" },
365
- decompile: { kind: "address", value: "<address>", multiple: true, help: "ghidra: a routine to decompile, at most 32" },
365
+ decompile: { kind: "address", value: "<address>", multiple: true, help: "decompiler: a routine to decompile, at most 32" },
366
366
  space: OPTIONS.space,
367
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" },
368
368
  "out-listing": { kind: "path", output: "file", value: "<file>", help: "dxa: write the disassembly listing to this project file" },
369
- "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" },
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" },
370
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" },
371
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" },
372
372
  },
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. Ghidra needs at least one entry point. DXA finds the SYS of a BASIC start by itself.",
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.",
374
374
  run: analyze,
375
375
  },
376
376
  ],
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 Ghidra. A start is a code start, a
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
@@ -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 Ghidra themselves. One entry per operation, never a
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";
@@ -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 Ghidra themselves through src/native (Ghidra in process).
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";
@@ -268,10 +268,10 @@ function importNames(db: DatabaseSync, change: Change, findings: NormalizedFindi
268
268
  }
269
269
  }
270
270
 
271
- /** Analyzers whose regions a heuristic finding replaces where it lies: user/LLM > heuristic > DXA/Ghidra. */
272
- const YIELDS_TO_HEURISTIC = new Set<Origin>(["dxa", "ghidra"]);
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"]);
273
273
  /** Analyzers whose data gives way to a code finding over an executed instruction start. */
274
- const YIELDS_TO_EXECUTED_CODE = new Set<Origin>(["dxa", "ghidra"]);
274
+ const YIELDS_TO_EXECUTED_CODE = new Set<Origin>(["dxa", "decompiler"]);
275
275
 
276
276
  /** The first address in the range that is an executed instruction start, or undefined. */
277
277
  function firstExecuted(findings: NormalizedFindings, start: number, end: number): number | undefined {
@@ -286,7 +286,7 @@ function holdsExecuted(findings: NormalizedFindings, start: number, end: number)
286
286
  }
287
287
 
288
288
  /**
289
- * The data findings of DXA or Ghidra that code evidence contradicts: an
289
+ * The data findings of DXA or the decompiler that code evidence contradicts: an
290
290
  * executed instruction start, or a code name (label or routine) of the user or
291
291
  * the LLM, in the range. Evidence wins over an analyzer guess: such a finding
292
292
  * is not imported, and the analyzer's own code there stays.
@@ -321,7 +321,7 @@ function importRegions(db: DatabaseSync, change: Change, given: NormalizedFindin
321
321
  result.conflicts.push(...contradicted);
322
322
  const findings = { ...given, regions: given.regions.filter((region) => !contradicted.some((item) => item.start === region.start && item.end === region.end)) };
323
323
  if (analyzer === "heuristic") {
324
- // An idiom is specific evidence about its bytes: the DXA or Ghidra region there gives way, its parts outside stay.
324
+ // An idiom is specific evidence about its bytes: the DXA or decompiler region there gives way, its parts outside stay.
325
325
  for (const region of findings.regions) {
326
326
  for (const row of regionsOverlapping(db, region.start, region.end, space).filter((candidate) => YIELDS_TO_HEURISTIC.has(candidate.origin))) {
327
327
  change.close("regions", "space = ? AND start_address = ? AND end_address = ? AND origin = ?", space, row.start, row.end, row.origin);
@@ -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, Ghidra and
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" } {
@@ -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, Ghidra, DXA. */
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", "ghidra", "dxa"];
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, Ghidra, DXA. */
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[])
@@ -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", "ghidra", "heuristic"] as const;
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", "ghidra", "heuristic"] as const satisfies readonly Origin[];
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', 'ghidra', 'heuristic')),
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 Ghidra analysis: the Ghidra SLEIGH decoder and decompiler with the NMOS
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 { checkGhidraResult, checkRequestBounds, GHIDRA_LIMITS, imageRange, seedsInside, type GhidraParams, type GhidraResult } from "../types.ts";
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: GhidraParams,
16
+ params: DecompilerParams,
17
17
  image: Buffer,
18
18
  context: ToolContext,
19
- ): Promise<{ result: GhidraResult }> {
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 Ghidra decoder failed: ${describeError(error)}`);
36
- throw new WireFailure("operation-failed", `The Ghidra decoder failed: ${describeError(error)}. Nothing was imported.`);
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: GhidraResult;
40
+ let result: DecompilerResult;
41
41
  try {
42
- result = checkGhidraResult({ ...walked, decompilations, notDecompiled, completeness: { functions: true, regions: true, references: true }, toolVersion: SLEIGH_VERSION });
42
+ result = checkDecompilerResult({ ...walked, decompilations, notDecompiled, completeness: { functions: true, regions: true, references: true }, toolVersion: SLEIGH_VERSION });
43
43
  } catch (error) {
44
- context.log?.(`Ghidra result rejected: ${describeError(error)}`);
45
- throw new WireFailure("operation-failed", `Ghidra returned an incomplete or inconsistent result. Nothing was imported. The check found: ${describeError(error)}.`);
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: GhidraParams, functions: GhidraResult["functions"], body: Uint8Array, start: number, context: ToolContext): Pick<GhidraResult, "decompilations" | "notDecompiled"> {
52
- const decompilations: GhidraResult["decompilations"] = [];
53
- const notDecompiled: NonNullable<GhidraResult["notDecompiled"]> = [];
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 Ghidra decompiler refused the name ${label.name}: ${describeError(error)}`);
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 = GHIDRA_LIMITS.decompiledTotalChars;
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 Ghidra decompiler failed at ${entry}: ${describeError(error)}`);
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(GHIDRA_LIMITS.decompiledChars, remaining);
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 Ghidra
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 { GhidraInstruction, GhidraResult } from "../types.ts";
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<GhidraResult, "decompilations" | "completeness" | "toolVersion"> {
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: GhidraResult["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): GhidraInstruction => {
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): GhidraResult["regions"] {
194
- const result: GhidraResult["regions"] = [];
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;
@@ -1,5 +1,5 @@
1
1
  // Types of the native tools that skill scripts run directly (ACME, DXA,
2
- // Ghidra), and the checks of their complete results. The skill script runs
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 GHIDRA_LIMITS = { entryPoints: 1024, codeStarts: 8192, dataRanges: 1024, labels: 4096, decompile: 32, decompiledChars: 16_000, decompiledTotalChars: 128_000 } as 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 Ghidra analysis. Its image is given next to these fields: a PRG, or 64 KiB from $0000. */
49
- export interface GhidraParams {
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 Ghidra disassembles without making a function: a branch target is no routine. */
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 GhidraInstruction {
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 GhidraResult {
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 Ghidra decoded it. */
81
- instructions: GhidraInstruction[];
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 Ghidra request with more seeds or decompilations than the request bounds allow, by name. */
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, GHIDRA_LIMITS.entryPoints],
92
- ["code starts", params.codeStarts?.length ?? 0, GHIDRA_LIMITS.codeStarts],
93
- ["data ranges", params.dataRanges.length, GHIDRA_LIMITS.dataRanges],
94
- ["labels", params.labels.length, GHIDRA_LIMITS.labels],
95
- ["routines to decompile", params.decompile?.length ?? 0, GHIDRA_LIMITS.decompile],
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 Ghidra, without decompilation. */
103
- export type DxaParams = Omit<GhidraParams, "decompile" | "codeStarts">;
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 Ghidra result: every field typed and in range, every
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 checkGhidraResult(value: unknown): GhidraResult {
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 > GHIDRA_LIMITS.decompile) fail("bad decompilations");
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 > GHIDRA_LIMITS.decompiledChars) fail("a decompilation is too long");
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 > GHIDRA_LIMITS.decompiledTotalChars) fail("the decompilations are too long together");
189
+ if (total > DECOMPILER_LIMITS.decompiledTotalChars) fail("the decompilations are too long together");
190
190
  if (notDecompiled !== undefined) {
191
- if (!isList(notDecompiled) || notDecompiled.length > GHIDRA_LIMITS.decompile) fail("bad list of routines that were not decompiled");
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 GhidraResult;
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<GhidraParams, "entryPoints" | "dataRanges" | "codeStarts">, start: number, end: number): { entryPoints: number[]; codeStarts: number[]; dataRanges: GhidraParams["dataRanges"] } {
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. Ghidra gives the instruction
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, ghidra, heuristic, semantic (user and llm) or analyzer (dxa, ghidra and heuristic), or a comma list" },
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