@henols/c64-re-tools 2.6.0-rc.6 → 2.6.0-rc.8

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 (45) hide show
  1. package/package.json +1 -1
  2. package/skills/c64-knowledge/SKILL.md +1 -1
  3. package/skills/c64-knowledge/scripts/knowledge.ts +2 -0
  4. package/skills/c64-knowledge/scripts/lib/listing.ts +18 -3
  5. package/skills/c64-reverse-engineering/SKILL.md +1 -1
  6. package/skills/c64-source/SKILL.md +5 -5
  7. package/skills/c64-source/scripts/source.ts +22 -20
  8. package/skills/c64-static-analysis/SKILL.md +3 -3
  9. package/skills/c64-static-analysis/scripts/lib/instructions.ts +22 -20
  10. package/skills/c64-static-analysis/scripts/static-analysis.ts +1 -8
  11. package/skills/c64-testing/SKILL.md +1 -0
  12. package/skills/c64-testing/references/recording-format.md +8 -0
  13. package/skills/c64-testing/scripts/lib/keys.ts +36 -0
  14. package/skills/c64-testing/scripts/lib/play.ts +2 -6
  15. package/skills/c64-testing/scripts/lib/recording.ts +13 -4
  16. package/skills/emulator/SKILL.md +6 -8
  17. package/src/cli/main.ts +3 -29
  18. package/src/host/main.ts +1 -1
  19. package/src/host/tools/index.ts +1 -6
  20. package/src/host/vice/session.ts +1 -1
  21. package/src/host-client/tools.ts +2 -7
  22. package/src/knowledge/read.ts +16 -1
  23. package/src/mcp/server.ts +0 -1
  24. package/src/mcp/tools/machine.ts +3 -42
  25. package/src/mcp/tools/media.ts +1 -1
  26. package/src/native/dxa.ts +12 -1
  27. package/src/native/ghidra/analyze.ts +74 -63
  28. package/src/native/ghidra/c64rt-wasm.ts +4 -0
  29. package/src/native/ghidra/language/c64rt_6510.sla +0 -0
  30. package/src/native/ghidra/pcode.ts +222 -0
  31. package/src/native/ghidra/walk.ts +205 -0
  32. package/src/native/ghidra/wasm.ts +98 -0
  33. package/src/native/processes.ts +1 -1
  34. package/src/native/types.ts +2 -2
  35. package/src/project.ts +4 -3
  36. package/src/protocol/tools.ts +1 -45
  37. package/src/script.ts +1 -1
  38. package/tools/install-container.sh +1 -2
  39. package/src/cli/status.ts +0 -127
  40. package/src/host/tools/status.ts +0 -47
  41. package/src/native/ghidra/index.ts +0 -170
  42. package/src/native/ghidra/scripts/C64Export.java +0 -274
  43. package/src/native/ghidra/scripts/C64Prepare.java +0 -66
  44. package/src/native/status.ts +0 -135
  45. package/tools/install-ghidra.sh +0 -40
@@ -0,0 +1,222 @@
1
+ // A p-code interpreter for integer operations over byte-addressed spaces,
2
+ // machine-neutral: it knows no CPU, only the p-code that SLEIGH gives. A value
3
+ // that depends on an unknown byte is unknown (undefined). The analysis uses it
4
+ // to find the target of an indirect jump from the stores before it; the
5
+ // language tests use it to execute one instruction.
6
+
7
+ import type { PcodeOp, Varnode } from "./wasm.ts";
8
+
9
+ /** Where an instruction leaves the flow; next is unknown for a computed target that the state does not give. */
10
+ export type Exit = { kind: "fall" } | { kind: "branch" | "call" | "return" | "indirect"; next: number | undefined } | { kind: "stop" };
11
+
12
+ /** Values are kept below 2^48, so sizes up to 6 bytes are exact. */
13
+ const MAX_SIZE = 6;
14
+
15
+ const mask = (size: number) => 2 ** (8 * Math.min(size, MAX_SIZE)) - 1;
16
+ /** The value modulo 2^(8 * size), also for a negative value. */
17
+ const wrap = (value: number, size: number) => ((value % (mask(size) + 1)) + mask(size) + 1) % (mask(size) + 1);
18
+ const signed = (value: number, size: number) => (value >= 2 ** (8 * size - 1) ? value - 2 ** (8 * size) : value);
19
+
20
+ export class PcodeState {
21
+ /** Space name to byte offset to byte value. */
22
+ private readonly spaces = new Map<string, Map<number, number>>();
23
+ private readonly memory: (address: number) => number | undefined;
24
+
25
+ /** memory gives the RAM bytes that no store of this state wrote, or undefined for an unknown byte. */
26
+ constructor(memory: (address: number) => number | undefined = () => undefined) {
27
+ this.memory = memory;
28
+ }
29
+
30
+ private bytes(space: string): Map<number, number> {
31
+ let bytes = this.spaces.get(space);
32
+ if (bytes === undefined) this.spaces.set(space, (bytes = new Map()));
33
+ return bytes;
34
+ }
35
+
36
+ get(varnode: Varnode): number | undefined {
37
+ if (varnode.space === "const") return varnode.offset & mask(varnode.size);
38
+ const bytes = this.spaces.get(varnode.space);
39
+ let value = 0;
40
+ for (let index = 0; index < varnode.size; index++) {
41
+ const at = varnode.space === "ram" ? (varnode.offset + index) & 0xffff : varnode.offset + index;
42
+ const byte = bytes?.get(at) ?? (varnode.space === "ram" ? this.memory(at) : undefined);
43
+ if (byte === undefined) return undefined;
44
+ value += byte * 2 ** (8 * index);
45
+ }
46
+ return value;
47
+ }
48
+
49
+ set(varnode: Varnode, value: number | undefined): void {
50
+ const bytes = this.bytes(varnode.space);
51
+ for (let index = 0; index < varnode.size; index++) {
52
+ const at = varnode.space === "ram" ? (varnode.offset + index) & 0xffff : varnode.offset + index;
53
+ if (value === undefined) bytes.delete(at);
54
+ else bytes.set(at, Math.floor(value / 2 ** (8 * index)) & 0xff);
55
+ }
56
+ }
57
+
58
+ /** Forgets every RAM byte: a store through an unknown pointer can change any of them. */
59
+ forgetRam(): void {
60
+ this.spaces.delete("ram");
61
+ }
62
+
63
+ /** Forgets every value: after a call, the routine can have changed anything. */
64
+ forget(): void {
65
+ this.spaces.clear();
66
+ }
67
+
68
+ /** Runs the p-code of one instruction and tells where the flow goes. */
69
+ run(pcode: readonly PcodeOp[]): Exit {
70
+ for (let index = 0; index < pcode.length; ) {
71
+ const operation = pcode[index]!;
72
+ const inputs = operation.in.map((varnode) => this.get(varnode));
73
+ const [a, b] = inputs;
74
+ const size = operation.out?.size ?? operation.in[0]?.size ?? 1;
75
+ const known = a !== undefined && b !== undefined;
76
+ let out: number | undefined;
77
+ switch (operation.op) {
78
+ case "COPY":
79
+ case "INT_ZEXT":
80
+ out = a;
81
+ break;
82
+ case "INT_SEXT":
83
+ out = a === undefined ? undefined : signed(a, operation.in[0]!.size);
84
+ break;
85
+ case "INT_ADD":
86
+ out = known ? a + b : undefined;
87
+ break;
88
+ case "INT_SUB":
89
+ out = known ? a - b : undefined;
90
+ break;
91
+ case "INT_MULT":
92
+ out = known ? a * b : undefined;
93
+ break;
94
+ case "INT_DIV":
95
+ out = known && b !== 0 ? Math.floor(a / b) : undefined;
96
+ break;
97
+ case "INT_REM":
98
+ out = known && b !== 0 ? a % b : undefined;
99
+ break;
100
+ case "INT_AND":
101
+ out = known ? bitwise(a, b, (x, y) => x & y) : undefined;
102
+ break;
103
+ case "INT_OR":
104
+ out = known ? bitwise(a, b, (x, y) => x | y) : undefined;
105
+ break;
106
+ case "INT_XOR":
107
+ out = known ? bitwise(a, b, (x, y) => x ^ y) : undefined;
108
+ break;
109
+ case "INT_NEGATE":
110
+ out = a === undefined ? undefined : mask(size) - a;
111
+ break;
112
+ case "INT_2COMP":
113
+ out = a === undefined ? undefined : -a;
114
+ break;
115
+ case "INT_LEFT":
116
+ out = known ? (b >= 8 * size ? 0 : a * 2 ** b) : undefined;
117
+ break;
118
+ case "INT_RIGHT":
119
+ out = known ? Math.floor(a / 2 ** b) : undefined;
120
+ break;
121
+ case "INT_SRIGHT":
122
+ out = known ? Math.floor(signed(a, operation.in[0]!.size) / 2 ** b) : undefined;
123
+ break;
124
+ case "INT_EQUAL":
125
+ out = known ? Number(a === b) : undefined;
126
+ break;
127
+ case "INT_NOTEQUAL":
128
+ out = known ? Number(a !== b) : undefined;
129
+ break;
130
+ case "INT_LESS":
131
+ out = known ? Number(a < b) : undefined;
132
+ break;
133
+ case "INT_LESSEQUAL":
134
+ out = known ? Number(a <= b) : undefined;
135
+ break;
136
+ case "INT_SLESS":
137
+ out = known ? Number(signed(a, operation.in[0]!.size) < signed(b, operation.in[1]!.size)) : undefined;
138
+ break;
139
+ case "INT_SLESSEQUAL":
140
+ out = known ? Number(signed(a, operation.in[0]!.size) <= signed(b, operation.in[1]!.size)) : undefined;
141
+ break;
142
+ case "INT_CARRY":
143
+ out = known ? Number(a + b > mask(operation.in[0]!.size)) : undefined;
144
+ break;
145
+ case "INT_SCARRY":
146
+ case "INT_SBORROW": {
147
+ if (!known) break;
148
+ const width = operation.in[0]!.size;
149
+ const result = operation.op === "INT_SCARRY" ? signed(a, width) + signed(b, width) : signed(a, width) - signed(b, width);
150
+ out = Number(result < -(2 ** (8 * width - 1)) || result >= 2 ** (8 * width - 1));
151
+ break;
152
+ }
153
+ case "BOOL_NEGATE":
154
+ out = a === undefined ? undefined : Number(a === 0);
155
+ break;
156
+ case "BOOL_AND":
157
+ out = known ? Number(a !== 0 && b !== 0) : undefined;
158
+ break;
159
+ case "BOOL_OR":
160
+ out = known ? Number(a !== 0 || b !== 0) : undefined;
161
+ break;
162
+ case "BOOL_XOR":
163
+ out = known ? Number((a !== 0) !== (b !== 0)) : undefined;
164
+ break;
165
+ case "PIECE":
166
+ out = known ? a * 2 ** (8 * operation.in[1]!.size) + b : undefined;
167
+ break;
168
+ case "SUBPIECE":
169
+ out = known ? Math.floor(a / 2 ** (8 * b)) : undefined;
170
+ break;
171
+ case "POPCOUNT":
172
+ out = a === undefined ? undefined : [...a.toString(2)].filter((bit) => bit === "1").length;
173
+ break;
174
+ case "LOAD":
175
+ out = b === undefined ? undefined : this.get({ space: "ram", offset: b & 0xffff, size: operation.out!.size });
176
+ break;
177
+ case "STORE":
178
+ if (b === undefined) this.forgetRam();
179
+ else this.set({ space: "ram", offset: b & 0xffff, size: operation.in[2]!.size }, inputs[2]);
180
+ break;
181
+ case "BRANCH":
182
+ case "CBRANCH": {
183
+ const target = operation.in[0]!;
184
+ const taken = operation.op === "BRANCH" ? 1 : b;
185
+ if (taken === undefined) return target.space === "const" ? { kind: "stop" } : { kind: "branch", next: undefined };
186
+ if (taken !== 0) {
187
+ // A const target is a p-code relative branch inside this instruction.
188
+ if (target.space === "const") {
189
+ index += signed(target.offset & mask(target.size), target.size);
190
+ continue;
191
+ }
192
+ return { kind: "branch", next: target.offset };
193
+ }
194
+ break;
195
+ }
196
+ case "BRANCHIND":
197
+ return { kind: "indirect", next: a === undefined ? undefined : a & 0xffff };
198
+ case "CALL":
199
+ return { kind: "call", next: operation.in[0]!.offset };
200
+ case "CALLIND":
201
+ return { kind: "call", next: a === undefined ? undefined : a & 0xffff };
202
+ case "RETURN":
203
+ return { kind: "return", next: a === undefined ? undefined : a & 0xffff };
204
+ case "CALLOTHER":
205
+ // An opaque operation: its result is unknown, and a jam ends the flow at its branch to itself.
206
+ break;
207
+ default:
208
+ break;
209
+ }
210
+ if (operation.out !== null) this.set(operation.out, out === undefined ? undefined : wrap(out, operation.out.size));
211
+ index++;
212
+ }
213
+ return { kind: "fall" };
214
+ }
215
+ }
216
+
217
+ /** A bitwise operation on values that can be wider than the 32 bits of JavaScript's operators. */
218
+ function bitwise(a: number, b: number, operation: (x: number, y: number) => number): number {
219
+ const low = operation(a % 2 ** 24, b % 2 ** 24) >>> 0;
220
+ const high = operation(Math.floor(a / 2 ** 24), Math.floor(b / 2 ** 24)) >>> 0;
221
+ return high * 2 ** 24 + (low & 0xffffff);
222
+ }
@@ -0,0 +1,205 @@
1
+ // The analysis from seeds: a recursive descent over the instructions that the
2
+ // SLEIGH decoder gives, with flows and references read from their p-code.
3
+ // Entry points and call targets are functions; data ranges are never decoded.
4
+ // A byte that an operand reads or writes, and that is no code, is data.
5
+ // The target of an indirect jump comes from the stores of the straight-line
6
+ // code before it, or else from the pointer in the image.
7
+
8
+ import { SYMBOL_NAME } from "../../c64.ts";
9
+ import type { GhidraInstruction, GhidraResult } from "../types.ts";
10
+ import { PcodeState } from "./pcode.ts";
11
+ import { decode, type Decoded, type Varnode } from "./wasm.ts";
12
+
13
+ export interface WalkSeeds {
14
+ entryPoints: number[];
15
+ codeStarts: number[];
16
+ dataRanges: Array<{ start: number; end: number }>;
17
+ labels: Array<{ address: number; name: string }>;
18
+ }
19
+
20
+ interface Instruction {
21
+ decoded: Decoded;
22
+ flows: number[];
23
+ fallthrough: boolean;
24
+ references: Array<{ to: number; type: "call" | "jump" | "read" | "write" }>;
25
+ /** The addresses that an operand reads or writes without an index. */
26
+ accessed: number[];
27
+ }
28
+
29
+ /** The longest straight-line run before an indirect jump that gives its target. */
30
+ const MAX_CHAIN = 32;
31
+
32
+ const isRam = (varnode: Varnode) => varnode.space === "ram";
33
+
34
+ /** The value of the operand bytes after the first byte, little-endian; undefined without operand bytes. */
35
+ function operandValue(bytes: readonly number[]): number | undefined {
36
+ if (bytes.length === 2) return bytes[1]!;
37
+ if (bytes.length === 3) return bytes[1]! | (bytes[2]! << 8);
38
+ return undefined;
39
+ }
40
+
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"> {
43
+ const isData = new Uint8Array(0x10000);
44
+ for (const range of seeds.dataRanges) isData.fill(1, range.start, range.end + 1);
45
+ const imageByte = (address: number) => (address >= start && address <= end ? image[address - start] : undefined);
46
+
47
+ const instructions = new Map<number, Instruction>();
48
+ /** The start of the instruction that holds each byte, or -1. */
49
+ const owner = new Int32Array(0x10000).fill(-1);
50
+ const functions = new Set(seeds.entryPoints);
51
+ const work = [...seeds.entryPoints, ...seeds.codeStarts];
52
+
53
+ while (work.length > 0) {
54
+ const address = work.pop()!;
55
+ if (address < start || address > end || instructions.has(address) || owner[address] !== -1 || isData[address]) continue;
56
+ let decoded: Decoded;
57
+ try {
58
+ decoded = decode(address);
59
+ } catch {
60
+ continue;
61
+ }
62
+ const last = address + decoded.length - 1;
63
+ let free = last <= end;
64
+ for (let at = address; free && at <= last; at++) free = owner[at] === -1 && !isData[at];
65
+ if (!free) continue;
66
+
67
+ const instruction: Instruction = { decoded, flows: [], fallthrough: true, references: [], accessed: [] };
68
+ const reference = (to: number, type: Instruction["references"][number]["type"]) => instruction.references.push({ to, type });
69
+ const access = (to: number, type: "read" | "write") => {
70
+ reference(to, type);
71
+ instruction.accessed.push(to);
72
+ };
73
+ const operand = operandValue(decoded.bytes);
74
+ // Unique and register varnodes that hold an operand address plus an index.
75
+ const indexed = new Map<string, number>();
76
+ const key = (varnode: Varnode) => `${varnode.space}:${varnode.offset}`;
77
+ const jams = decoded.pcode.some((operation) => operation.op === "CALLOTHER");
78
+ for (const operation of decoded.pcode) {
79
+ const [first, second] = operation.in;
80
+ switch (operation.op) {
81
+ case "BRANCH":
82
+ case "CBRANCH":
83
+ if (isRam(first!)) {
84
+ // A jam branches to itself: the flow ends there.
85
+ if (first!.offset === address && operation.op === "BRANCH" && jams) instruction.fallthrough = false;
86
+ else {
87
+ instruction.flows.push(first!.offset);
88
+ reference(first!.offset, "jump");
89
+ if (operation.op === "BRANCH") instruction.fallthrough = false;
90
+ }
91
+ }
92
+ break;
93
+ case "CALL":
94
+ if (isRam(first!)) {
95
+ instruction.flows.push(first!.offset);
96
+ reference(first!.offset, "call");
97
+ functions.add(first!.offset);
98
+ }
99
+ break;
100
+ case "RETURN":
101
+ instruction.fallthrough = false;
102
+ break;
103
+ case "BRANCHIND": {
104
+ instruction.fallthrough = false;
105
+ const target = indirectTarget(address, decoded, instructions, owner, imageByte);
106
+ if (target !== undefined) {
107
+ instruction.flows.push(target);
108
+ reference(target, "jump");
109
+ }
110
+ break;
111
+ }
112
+ case "LOAD":
113
+ case "STORE": {
114
+ const type = operation.op === "LOAD" ? "read" : "write";
115
+ if (second!.space === "const") access(second!.offset & 0xffff, type);
116
+ else if (indexed.has(key(second!))) reference(indexed.get(key(second!))!, type);
117
+ break;
118
+ }
119
+ case "INT_ADD": {
120
+ // An address operand plus an index register: the reference goes to the operand address.
121
+ const constant = operation.in.find((varnode) => varnode.space === "const");
122
+ if (operation.out !== null && constant !== undefined && constant.offset === operand) indexed.set(key(operation.out), operand);
123
+ break;
124
+ }
125
+ case "COPY":
126
+ case "INT_ZEXT":
127
+ case "INT_AND":
128
+ if (operation.out !== null && first !== undefined && indexed.has(key(first))) indexed.set(key(operation.out), indexed.get(key(first))!);
129
+ break;
130
+ }
131
+ if (!["BRANCH", "CBRANCH", "CALL", "LOAD", "STORE"].includes(operation.op)) {
132
+ for (const input of operation.in) if (isRam(input)) access(input.offset, "read");
133
+ if (operation.out !== null && isRam(operation.out)) access(operation.out.offset, "write");
134
+ }
135
+ }
136
+ owner.fill(address, address, last + 1);
137
+ instructions.set(address, instruction);
138
+ for (const flow of instruction.flows) work.push(flow);
139
+ // Last in, first out: the next instruction is decoded first, so the code before an indirect jump is known.
140
+ if (instruction.fallthrough) work.push(last + 1);
141
+ }
142
+
143
+ for (const instruction of instructions.values()) {
144
+ for (const address of instruction.accessed) if (address >= start && address <= end && owner[address] === -1) isData[address] = 1;
145
+ }
146
+
147
+ const labels = new Map(seeds.labels.map((label) => [label.address, label.name]));
148
+ const sorted = [...instructions.keys()].sort((a, b) => a - b);
149
+ const seen = new Set<string>();
150
+ const references: GhidraResult["references"] = [];
151
+ for (const from of sorted) {
152
+ for (const { to, type } of instructions.get(from)!.references) {
153
+ const id = `${from}:${to}:${type}`;
154
+ if (seen.has(id)) continue;
155
+ seen.add(id);
156
+ references.push({ from, to, type });
157
+ }
158
+ }
159
+ return {
160
+ coverage: [{ start, end }],
161
+ functions: [...functions]
162
+ .filter((entry) => instructions.has(entry))
163
+ .sort((a, b) => a - b)
164
+ .map((entry) => {
165
+ const name = labels.get(entry);
166
+ return name !== undefined && SYMBOL_NAME.test(name) ? { entry, name, nameSource: "seed" as const } : { entry, name: `FUN_${hex4(entry)}`, nameSource: "generated" as const };
167
+ }),
168
+ regions: regions(start, end, (address) => (owner[address] !== -1 ? "code" : isData[address] ? "data" : undefined)),
169
+ references,
170
+ instructions: sorted.map((address): GhidraInstruction => {
171
+ const { decoded, flows } = instructions.get(address)!;
172
+ return { address, bytes: decoded.bytes.map((byte) => byte.toString(16).padStart(2, "0")).join(""), mnemonic: decoded.mnemonic.toLowerCase(), operands: decoded.operands, flows };
173
+ }),
174
+ };
175
+ }
176
+
177
+ /** The target of the indirect jump at address, or undefined; a zero pointer is no target. */
178
+ function indirectTarget(address: number, decoded: Decoded, instructions: Map<number, Instruction>, owner: Int32Array, imageByte: (address: number) => number | undefined): number | undefined {
179
+ const chain: Decoded[] = [];
180
+ for (let at = address; chain.length < MAX_CHAIN && at > 0; ) {
181
+ const previous = owner[at - 1]!;
182
+ const instruction = previous === -1 ? undefined : instructions.get(previous);
183
+ if (instruction === undefined || !instruction.fallthrough) break;
184
+ chain.unshift(instruction.decoded);
185
+ at = previous;
186
+ }
187
+ const state = new PcodeState(imageByte);
188
+ for (const instruction of chain) if (state.run(instruction.pcode).kind === "call") state.forget();
189
+ const exit = state.run(decoded.pcode);
190
+ return exit.kind === "indirect" && exit.next !== undefined && exit.next !== 0 ? exit.next : undefined;
191
+ }
192
+
193
+ function regions(start: number, end: number, kind: (address: number) => "code" | "data" | undefined): GhidraResult["regions"] {
194
+ const result: GhidraResult["regions"] = [];
195
+ for (let address = start; address <= end; address++) {
196
+ const classification = kind(address);
197
+ if (classification === undefined) continue;
198
+ const previous = result.at(-1);
199
+ if (previous !== undefined && previous.classification === classification && previous.end === address - 1) previous.end = address;
200
+ else result.push({ start: address, end: address, classification });
201
+ }
202
+ return result;
203
+ }
204
+
205
+ const hex4 = (value: number) => value.toString(16).padStart(4, "0");
@@ -0,0 +1,98 @@
1
+ // The Ghidra SLEIGH decoder and decompiler for the c64-re-tools 6510
2
+ // language, as a WebAssembly module (built from native/sleigh/). It has no imports and holds one program image at a time.
3
+ // A panic in the module traps: the instance is then dropped and the next
4
+ // load makes a new one.
5
+
6
+ import { Refusal } from "../../errors.ts";
7
+ import { C64RT_WASM } from "./c64rt-wasm.ts";
8
+
9
+ /** The decoder and decompiler, as a result names its tool. */
10
+ export const SLEIGH_VERSION = "ghidra-decompiler 2.1.0";
11
+
12
+ export interface Varnode {
13
+ /** "ram", "const", "register" or "unique". */
14
+ space: string;
15
+ offset: number;
16
+ size: number;
17
+ }
18
+
19
+ export interface PcodeOp {
20
+ /** Ghidra's name of the operation, for example "INT_ADD" or "CBRANCH". */
21
+ op: string;
22
+ out: Varnode | null;
23
+ in: Varnode[];
24
+ /** The name of a CALLOTHER operation, for example "jam". */
25
+ userop?: string | null;
26
+ }
27
+
28
+ export interface Decoded {
29
+ length: number;
30
+ bytes: number[];
31
+ mnemonic: string;
32
+ operands: string;
33
+ pcode: PcodeOp[];
34
+ }
35
+
36
+ interface Exports {
37
+ memory: WebAssembly.Memory;
38
+ alloc(length: number): number;
39
+ out_ptr(): number;
40
+ load(image: number, length: number, base: number): number;
41
+ decode(address: number): number;
42
+ name(address: number, text: number, length: number, kind: number): number;
43
+ decompile(address: number): number;
44
+ }
45
+
46
+ const utf8 = new TextDecoder();
47
+
48
+ let module: WebAssembly.Module | undefined;
49
+ let instance: Exports | undefined;
50
+
51
+ function exports(): Exports {
52
+ module ??= new WebAssembly.Module(Buffer.from(C64RT_WASM, "base64"));
53
+ instance ??= new WebAssembly.Instance(module, {}).exports as unknown as Exports;
54
+ return instance;
55
+ }
56
+
57
+ /** Runs one call; a trap drops the instance, and the reply's error becomes a Refusal. */
58
+ function call<T>(run: (wasm: Exports) => number): T {
59
+ const wasm = exports();
60
+ let length: number;
61
+ try {
62
+ length = run(wasm);
63
+ } catch (error) {
64
+ instance = undefined;
65
+ throw new Refusal("operation-failed", `the decompiler stopped: ${error instanceof Error ? error.message : String(error)}`);
66
+ }
67
+ const reply = JSON.parse(utf8.decode(new Uint8Array(wasm.memory.buffer, wasm.out_ptr(), length))) as T & { error?: string };
68
+ if (reply.error !== undefined) throw new Refusal("operation-failed", reply.error);
69
+ return reply;
70
+ }
71
+
72
+ /** Copies bytes into a buffer of the module, which the called function takes. */
73
+ function put(wasm: Exports, bytes: Uint8Array): number {
74
+ const pointer = wasm.alloc(bytes.length);
75
+ new Uint8Array(wasm.memory.buffer, pointer, bytes.length).set(bytes);
76
+ return pointer;
77
+ }
78
+
79
+ /** The program image that decode, name and decompile work on: the bytes at base. */
80
+ export function loadImage(bytes: Uint8Array, base: number): void {
81
+ call((wasm) => wasm.load(put(wasm, bytes), bytes.length, base));
82
+ }
83
+
84
+ /** The instruction at an address of the loaded image. */
85
+ export function decode(address: number): Decoded {
86
+ return call((wasm) => wasm.decode(address));
87
+ }
88
+
89
+ /** Gives the decompiler the name of a routine or of a data address. */
90
+ export function setName(address: number, name: string, kind: "function" | "data"): void {
91
+ const text = new TextEncoder().encode(name);
92
+ call((wasm) => wasm.name(address, put(wasm, text), text.length, kind === "function" ? 0 : 1));
93
+ }
94
+
95
+ /** The C text of the routine at an address. */
96
+ export function decompile(address: number): string {
97
+ return call<{ text: string }>((wasm) => wasm.decompile(address)).text;
98
+ }
@@ -91,7 +91,7 @@ export function windowsQuote(arg: string): string {
91
91
  }
92
92
 
93
93
  /**
94
- * On Windows a .bat or .cmd file (Ghidra's analyzeHeadless.bat, for example)
94
+ * On Windows a .bat or .cmd file
95
95
  * starts only through cmd.exe: Node refuses it without a shell (EINVAL). /s
96
96
  * keeps the quoted command line as it is. Undefined for any other program.
97
97
  */
@@ -63,7 +63,7 @@ export interface GhidraInstruction {
63
63
  /** Lowercase hex, 1 to 3 bytes. */
64
64
  bytes: string;
65
65
  mnemonic: string;
66
- /** Ghidra's text of the operands, empty for an implied operand. */
66
+ /** The decoder's text of the operands, empty for an implied operand. */
67
67
  operands: string;
68
68
  /** Where the flow goes besides the next instruction: a branch, jump or call target. */
69
69
  flows: number[];
@@ -81,7 +81,7 @@ export interface GhidraResult {
81
81
  instructions: GhidraInstruction[];
82
82
  /** Which categories are complete inside the coverage; private to the importer. */
83
83
  completeness: { functions: boolean; regions: boolean; references: boolean };
84
- /** The version of the Ghidra that made the result, for example "Ghidra 12.1.3". */
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
 
package/src/project.ts CHANGED
@@ -157,7 +157,7 @@ export function namedProject(folder: string, cwd: string = process.cwd()): strin
157
157
  }
158
158
 
159
159
  /**
160
- * A group folder: a folder of a git repository, in no project, that holds
160
+ * A group folder: a folder of a git repository, in no project, that holds two or more
161
161
  * projects, for example one project for each version of a game. Its pages can
162
162
  * link into each project, and a page of a project into the other projects.
163
163
  */
@@ -175,7 +175,7 @@ function inRepository(folder: string): boolean {
175
175
  /**
176
176
  * The group at `folder`: its folders that are projects and are not a git
177
177
  * repository of their own. Undefined when `folder` is the home folder, is in a
178
- * project, is in no git repository, or holds no project.
178
+ * project, is in no git repository, or holds fewer than two projects.
179
179
  */
180
180
  export function groupAt(folder: string): ProjectGroup | undefined {
181
181
  const root = resolve(folder);
@@ -193,7 +193,8 @@ export function groupAt(folder: string): ProjectGroup | undefined {
193
193
  const path = join(root, entry.name);
194
194
  if (isProject(path) && !existsSync(join(path, ".git"))) projects.set(entry.name, path);
195
195
  }
196
- return projects.size === 0 ? undefined : { root, projects };
196
+ // One project alone is no group: a group holds the versions of one program.
197
+ return projects.size < 2 ? undefined : { root, projects };
197
198
  }
198
199
 
199
200
  /** The group of the project `root`: the folder above it, when that is a group that holds the project. */
@@ -79,38 +79,12 @@ export type PetcatResult =
79
79
  handoffs: BasicHandoff[];
80
80
  };
81
81
 
82
- /** One native tool on the host, as host.status found and ran it. */
83
- export interface ToolStatus {
84
- name: string;
85
- found: boolean;
86
- /** Where it is, when found. */
87
- path?: string;
88
- /** Its version text, when it ran. */
89
- version?: string;
90
- runs: boolean;
91
- /** What is wrong and what to do, when it is missing or does not run. */
92
- problem?: string;
93
- /** Known flaws of this version, each with the version that fixes it. The tool still runs. */
94
- flaws?: string[];
95
- }
96
-
97
- /** The Host Runtime itself: its package version and the system it runs on. */
98
- export interface HostInfo {
99
- version: string;
100
- /** Node's name of the operating system: linux, darwin or win32. */
101
- platform: string;
102
- /** The release of the operating system. */
103
- release: string;
104
- arch: string;
105
- }
106
-
107
82
  export interface ToolOperations {
108
- "host.status": { params: Record<string, never>; result: { host: HostInfo; tools: ToolStatus[] } };
109
83
  "c1541.inspect": { params: C1541Params; result: C1541Result };
110
84
  "petcat.decode": { params: PetcatParams; result: PetcatResult };
111
85
  }
112
86
  export type ToolOperation = keyof ToolOperations;
113
- export const TOOL_OPERATIONS = ["host.status", "c1541.inspect", "petcat.decode"] as const satisfies readonly ToolOperation[];
87
+ export const TOOL_OPERATIONS = ["c1541.inspect", "petcat.decode"] as const satisfies readonly ToolOperation[];
114
88
 
115
89
  const RELATIVE_PATH = /^(?!\/)(?!.*(?:^|\/)\.\.?(?:\/|$))[^\0\\]+$/;
116
90
 
@@ -166,10 +140,6 @@ export function validateToolParams<O extends ToolOperation>(op: O, params: unkno
166
140
  oneFile(attachments, "the program");
167
141
  return {} as ToolOperations[O]["params"];
168
142
  }
169
- case "host.status":
170
- onlyFields(params, []);
171
- if (attachments.length !== 0) invalid("host.status takes no attachment");
172
- return {} as ToolOperations[O]["params"];
173
143
  }
174
144
  return invalid(`unknown tool operation: ${String(op)}`);
175
145
  }
@@ -186,20 +156,6 @@ export function validateToolResult<O extends ToolOperation>(op: O, value: unknow
186
156
  if (!isPetcatResult(value) || attachments.length !== 0) throw new ProtocolError("petcat.decode result is malformed");
187
157
  return value as unknown as ToolOperations[O]["result"];
188
158
  }
189
- case "host.status": {
190
- const tools = value.tools;
191
- const isStatus = (tool: unknown) =>
192
- isObject(tool) &&
193
- typeof tool.name === "string" &&
194
- typeof tool.found === "boolean" &&
195
- typeof tool.runs === "boolean" &&
196
- [tool.path, tool.version, tool.problem].every((field) => field === undefined || typeof field === "string") &&
197
- (tool.flaws === undefined || (Array.isArray(tool.flaws) && tool.flaws.every((flaw: unknown) => typeof flaw === "string")));
198
- const host = value.host;
199
- const isHost = isObject(host) && [host.version, host.platform, host.release, host.arch].every((field) => typeof field === "string");
200
- if (!isHost || !Array.isArray(tools) || !tools.every(isStatus) || attachments.length !== 0) throw new ProtocolError("host.status result is malformed");
201
- return value as unknown as ToolOperations[O]["result"];
202
- }
203
159
  }
204
160
  throw new ProtocolError(`unknown tool operation: ${String(op)}`);
205
161
  }
package/src/script.ts CHANGED
@@ -121,7 +121,7 @@ export interface OptionSpec {
121
121
  /** The options that have one meaning in every script. A command can change the help, the value and whether it is required, never the kind. */
122
122
  export const OPTIONS = {
123
123
  out: { kind: "path", value: "<path>", help: "write the output here, relative to the project folder" },
124
- space: { kind: "space", value: "<space>", help: "the knowledge space: c64 (the default), drive8 for 1541 drive code, loading for a captured stage of the loading, or bank0 to bank255 for a cartridge bank", default: "c64" },
124
+ space: { kind: "space", value: "<space>", help: "the knowledge space: c64 (the default), drive8 for 1541 drive code, loading for a captured stage of the loading, or bank0 to bank255 for a cartridge bank or another memory image of the program", default: "c64" },
125
125
  range: { kind: "range", value: "<start>-<end>", help: "only the addresses from start to end, for example '$c000-$cfff'" },
126
126
  entry: { kind: "address", value: "<address>", help: "an entry point of the program" },
127
127
  steps: { kind: "path", value: "<file>", help: "a JSON file of action steps that run after the start" },