@henols/c64-re-tools 2.5.1-rc.2 → 2.6.0-rc.10

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 (87) hide show
  1. package/package.json +2 -2
  2. package/skills/c64-assembler/SKILL.md +26 -12
  3. package/skills/c64-assembler/scripts/assembler.ts +25 -13
  4. package/skills/c64-development/SKILL.md +2 -2
  5. package/skills/c64-docs/SKILL.md +4 -4
  6. package/skills/c64-docs/scripts/docs.ts +7 -7
  7. package/skills/c64-docs/scripts/lib/reference.ts +3 -3
  8. package/skills/c64-docs/scripts/lib/source-map.ts +9 -4
  9. package/skills/c64-knowledge/SKILL.md +29 -20
  10. package/skills/c64-knowledge/scripts/knowledge.ts +33 -39
  11. package/skills/c64-knowledge/scripts/lib/listing.ts +18 -3
  12. package/skills/c64-packer/SKILL.md +1 -1
  13. package/skills/c64-provenance/SKILL.md +11 -10
  14. package/skills/c64-provenance/scripts/lib/library.ts +16 -16
  15. package/skills/c64-provenance/scripts/provenance.ts +33 -23
  16. package/skills/c64-reverse-engineering/SKILL.md +16 -10
  17. package/skills/c64-source/SKILL.md +60 -42
  18. package/skills/c64-source/scripts/lib/export.ts +76 -32
  19. package/skills/c64-source/scripts/lib/loader.ts +26 -7
  20. package/skills/c64-source/scripts/lib/source.ts +21 -24
  21. package/skills/c64-source/scripts/lib/stage.ts +6 -5
  22. package/skills/c64-source/scripts/source.ts +213 -106
  23. package/skills/c64-static-analysis/SKILL.md +7 -5
  24. package/skills/c64-static-analysis/scripts/lib/coverage.ts +2 -25
  25. package/skills/c64-static-analysis/scripts/lib/instructions.ts +22 -20
  26. package/skills/c64-static-analysis/scripts/static-analysis.ts +36 -43
  27. package/skills/c64-testing/SKILL.md +5 -2
  28. package/skills/c64-testing/references/recording-format.md +18 -3
  29. package/skills/c64-testing/references/scenario-format.md +7 -6
  30. package/skills/c64-testing/scripts/lib/diff-files.ts +4 -18
  31. package/skills/c64-testing/scripts/lib/play.ts +39 -41
  32. package/skills/c64-testing/scripts/lib/recording.ts +46 -37
  33. package/skills/c64-testing/scripts/lib/replay.ts +1 -1
  34. package/skills/c64-testing/scripts/lib/runs.ts +2 -2
  35. package/skills/c64-testing/scripts/lib/scenario.ts +17 -10
  36. package/skills/c64-unpacker/SKILL.md +4 -1
  37. package/skills/c64-unpacker/scripts/lib/loads.ts +34 -13
  38. package/skills/c64-unpacker/scripts/unpacker.ts +5 -3
  39. package/skills/emulator/SKILL.md +7 -12
  40. package/src/build-name.ts +50 -0
  41. package/src/c64-keys.ts +98 -0
  42. package/src/c64.ts +20 -0
  43. package/src/cli/main.ts +3 -29
  44. package/src/host/main.ts +1 -1
  45. package/src/host/tools/index.ts +1 -6
  46. package/src/host/vice/session.ts +88 -9
  47. package/src/host-client/steps.ts +17 -17
  48. package/src/host-client/tools.ts +2 -7
  49. package/src/host-client/vice-session.ts +7 -1
  50. package/src/knowledge/program.ts +44 -1
  51. package/src/knowledge/read.ts +28 -8
  52. package/src/knowledge/schema.ts +33 -9
  53. package/src/knowledge/start-screen.ts +4 -0
  54. package/src/knowledge/text.ts +4 -2
  55. package/src/knowledge/write.ts +59 -25
  56. package/src/mcp/inputs.ts +12 -0
  57. package/src/mcp/server.ts +1 -1
  58. package/src/mcp/tools/input.ts +38 -5
  59. package/src/mcp/tools/machine.ts +3 -42
  60. package/src/mcp/tools/media.ts +1 -1
  61. package/src/native/acme.ts +1 -1
  62. package/src/native/c64run.ts +1 -1
  63. package/src/native/discover.ts +3 -3
  64. package/src/native/dxa.ts +12 -1
  65. package/src/native/ghidra/analyze.ts +74 -63
  66. package/src/native/ghidra/c64rt-wasm.ts +4 -0
  67. package/src/native/ghidra/language/c64rt_6510.sla +0 -0
  68. package/src/native/ghidra/pcode.ts +222 -0
  69. package/src/native/ghidra/walk.ts +205 -0
  70. package/src/native/ghidra/wasm.ts +98 -0
  71. package/src/native/processes.ts +4 -4
  72. package/src/native/types.ts +2 -2
  73. package/src/platform.ts +30 -1
  74. package/src/project.ts +17 -4
  75. package/src/protocol/tools.ts +1 -45
  76. package/src/protocol/vice.ts +47 -0
  77. package/src/script.ts +1 -1
  78. package/src/vsf.ts +98 -0
  79. package/tools/c64run.c +9 -12
  80. package/tools/install-container.sh +1 -2
  81. package/src/cli/status.ts +0 -127
  82. package/src/host/tools/status.ts +0 -47
  83. package/src/native/ghidra/index.ts +0 -170
  84. package/src/native/ghidra/scripts/C64Export.java +0 -274
  85. package/src/native/ghidra/scripts/C64Prepare.java +0 -66
  86. package/src/native/status.ts +0 -135
  87. 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
  */
@@ -350,7 +350,7 @@ export class ProcessSupervisor {
350
350
  } catch {
351
351
  // The leader has ended already.
352
352
  }
353
- await Promise.race([exited, sleep(this.#graceMs)]);
353
+ await Promise.race([exited, sleep(this.#graceMs, undefined, { ref: false })]);
354
354
  if (!hasExited(child)) throw new Refusal("operation-failed", `process ${pid} did not end${failure === undefined ? "" : `: ${failure}`}`);
355
355
  return;
356
356
  }
@@ -362,7 +362,7 @@ export class ProcessSupervisor {
362
362
  }
363
363
  }
364
364
  // A group of zombies counts as gone before Node reaps the leader and reports its exit;
365
- // stopped means that Node has seen that exit.
366
- await Promise.race([exited, sleep(KILL_WAIT_MS)]);
365
+ // stopped means that Node has seen that exit. The limit does not keep this process running.
366
+ await Promise.race([exited, sleep(KILL_WAIT_MS, undefined, { ref: false })]);
367
367
  }
368
368
  }
@@ -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/platform.ts CHANGED
@@ -3,7 +3,7 @@
3
3
  // Names follow "Mapping the Commodore 64". Only platform facts live here:
4
4
  // an address without one belongs to the application.
5
5
 
6
- import { COVERAGE, d018Offsets, formatC64Address, vicBankBase } from "./c64.ts";
6
+ import { type AddressRange, COVERAGE, d018Offsets, formatC64Address, romOnlyRanges, vicBankBase } from "./c64.ts";
7
7
  import { Refusal } from "./errors.ts";
8
8
 
9
9
  export interface Entry {
@@ -433,6 +433,35 @@ export function romUseOfProgram(coverage: Uint8Array | undefined, state: Record<
433
433
  return { basic: true, kernal: true, from: "none" };
434
434
  }
435
435
 
436
+ /** The ROMs as the CPU sees them. */
437
+ const BASIC_ROM: AddressRange = { start: 0xa000, end: 0xbfff };
438
+ const KERNAL_ROM: AddressRange = { start: 0xe000, end: 0xffff };
439
+
440
+ /**
441
+ * The ranges of an image where the CPU sees ROM and not the RAM of the
442
+ * image, so a JSR there runs the ROM: with coverage, the image bytes that the
443
+ * runs used only as ROM; without coverage, the ROMs that $01 of the entry
444
+ * state switches in. A range with known code (`known`) in it is left out:
445
+ * that code stays code.
446
+ */
447
+ export function romRanges(coverage: Uint8Array | undefined, state: Record<string, unknown> | undefined, image: (address: number) => number | undefined, known: readonly number[]): AddressRange[] {
448
+ let ranges: AddressRange[] = [];
449
+ if (coverage !== undefined) ranges = romOnlyRanges(coverage, image);
450
+ else {
451
+ const port = (state?.cpuPort as Record<string, unknown> | undefined)?.$01;
452
+ const use = typeof port === "number" ? romUseOfPort(port) : { basic: false, kernal: false };
453
+ for (const rom of [...(use.basic ? [BASIC_ROM] : []), ...(use.kernal ? [KERNAL_ROM] : [])]) {
454
+ for (let address = rom.start; address <= rom.end; address++) {
455
+ if (image(address) === undefined) continue;
456
+ const last = ranges.at(-1);
457
+ if (last !== undefined && last.end === address - 1) last.end = address;
458
+ else ranges.push({ start: address, end: address });
459
+ }
460
+ }
461
+ }
462
+ return ranges.filter((range) => !known.some((address) => address >= range.start && address <= range.end));
463
+ }
464
+
436
465
  export type Decoded = Record<string, unknown>;
437
466
 
438
467
  const bits = (value: number) => [0, 1, 2, 3, 4, 5, 6, 7].filter((bit) => (value & (1 << bit)) !== 0);
package/src/project.ts CHANGED
@@ -7,7 +7,7 @@
7
7
  import { Refusal } from "./errors.ts";
8
8
  import { accessSync, constants, existsSync, lstatSync, mkdirSync, readdirSync, realpathSync, statSync, writeFileSync } from "node:fs";
9
9
  import { homedir } from "node:os";
10
- import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
10
+ import { basename, dirname, isAbsolute, join, posix, relative, resolve, sep } from "node:path";
11
11
 
12
12
  /** The folder that marks a project and holds its knowledge. */
13
13
  export const PROJECT_DIRECTORY = ".c64-re-tools";
@@ -15,6 +15,18 @@ export const PROJECT_DIRECTORY = ".c64-re-tools";
15
15
  /** The folder for machine-local scratch: saved results, batches and step files. */
16
16
  export const LOCAL_DIRECTORY = "local";
17
17
 
18
+ /** The folder in LOCAL_DIRECTORY for the reports of a generated source: its source map and the code that no run executed. */
19
+ export const GENERATED_DIRECTORY = "generated";
20
+
21
+ /**
22
+ * The folder of the reports of the source that was generated into `out`, relative
23
+ * to the project folder: .c64-re-tools/local/generated/<out>. The source folder
24
+ * then holds only source files.
25
+ */
26
+ export function generatedDirectory(out: string): string {
27
+ return posix.join(PROJECT_DIRECTORY, LOCAL_DIRECTORY, GENERATED_DIRECTORY, posix.normalize(out.split("\\").join("/")).replace(/\/+$/, ""));
28
+ }
29
+
18
30
  /** The .gitignore of LOCAL_DIRECTORY: git ignores everything in it, the .gitignore too. */
19
31
  const LOCAL_GITIGNORE = "# Machine-local scratch of c64-re-tools (saved results, batches, step files). Never committed.\n*\n";
20
32
 
@@ -145,7 +157,7 @@ export function namedProject(folder: string, cwd: string = process.cwd()): strin
145
157
  }
146
158
 
147
159
  /**
148
- * 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
149
161
  * projects, for example one project for each version of a game. Its pages can
150
162
  * link into each project, and a page of a project into the other projects.
151
163
  */
@@ -163,7 +175,7 @@ function inRepository(folder: string): boolean {
163
175
  /**
164
176
  * The group at `folder`: its folders that are projects and are not a git
165
177
  * repository of their own. Undefined when `folder` is the home folder, is in a
166
- * project, is in no git repository, or holds no project.
178
+ * project, is in no git repository, or holds fewer than two projects.
167
179
  */
168
180
  export function groupAt(folder: string): ProjectGroup | undefined {
169
181
  const root = resolve(folder);
@@ -181,7 +193,8 @@ export function groupAt(folder: string): ProjectGroup | undefined {
181
193
  const path = join(root, entry.name);
182
194
  if (isProject(path) && !existsSync(join(path, ".git"))) projects.set(entry.name, path);
183
195
  }
184
- 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 };
185
198
  }
186
199
 
187
200
  /** The group of the project `root`: the folder above it, when that is a group that holds the project. */