@henols/c64-re-tools 2.6.0-rc.7 → 2.6.0-rc.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/package.json +2 -2
  2. package/skills/c64-docs/SKILL.md +1 -1
  3. package/skills/c64-docs/scripts/docs.ts +6 -6
  4. package/skills/c64-knowledge/SKILL.md +3 -3
  5. package/skills/c64-knowledge/scripts/knowledge.ts +2 -0
  6. package/skills/c64-knowledge/scripts/lib/listing.ts +18 -3
  7. package/skills/c64-reverse-engineering/SKILL.md +1 -1
  8. package/skills/c64-source/SKILL.md +7 -7
  9. package/skills/c64-source/scripts/lib/source.ts +10 -0
  10. package/skills/c64-source/scripts/source.ts +32 -27
  11. package/skills/c64-static-analysis/SKILL.md +5 -3
  12. package/skills/c64-static-analysis/scripts/lib/instructions.ts +22 -20
  13. package/skills/c64-static-analysis/scripts/static-analysis.ts +16 -16
  14. package/skills/c64-testing/SKILL.md +2 -1
  15. package/skills/c64-testing/references/recording-format.md +17 -3
  16. package/skills/c64-testing/references/scenario-format.md +2 -3
  17. package/skills/c64-testing/scripts/lib/diff-files.ts +4 -18
  18. package/skills/c64-testing/scripts/lib/play.ts +39 -41
  19. package/skills/c64-testing/scripts/lib/recording.ts +21 -29
  20. package/skills/c64-testing/scripts/lib/runs.ts +2 -2
  21. package/skills/c64-testing/scripts/lib/scenario.ts +3 -5
  22. package/skills/c64-unpacker/SKILL.md +2 -1
  23. package/skills/c64-unpacker/scripts/lib/loads.ts +2 -2
  24. package/skills/emulator/SKILL.md +2 -5
  25. package/src/c64-keys.ts +98 -0
  26. package/src/cli/main.ts +1 -1
  27. package/src/host/vice/session.ts +82 -8
  28. package/src/host-client/steps.ts +17 -17
  29. package/src/host-client/tools.ts +1 -1
  30. package/src/host-client/vice-session.ts +7 -1
  31. package/src/knowledge/read.ts +25 -1
  32. package/src/mcp/inputs.ts +12 -0
  33. package/src/mcp/server.ts +1 -0
  34. package/src/mcp/tools/input.ts +38 -5
  35. package/src/native/c64run.ts +1 -1
  36. package/src/native/discover.ts +3 -3
  37. package/src/native/ghidra/analyze.ts +74 -63
  38. package/src/native/ghidra/c64rt-wasm.ts +4 -0
  39. package/src/native/ghidra/language/c64rt_6510.sla +0 -0
  40. package/src/native/ghidra/pcode.ts +222 -0
  41. package/src/native/ghidra/walk.ts +205 -0
  42. package/src/native/ghidra/wasm.ts +98 -0
  43. package/src/native/processes.ts +4 -4
  44. package/src/native/types.ts +2 -2
  45. package/src/project.ts +4 -3
  46. package/src/protocol/vice.ts +47 -0
  47. package/src/script.ts +1 -1
  48. package/src/vsf.ts +98 -0
  49. package/tools/c64run.c +9 -12
  50. package/tools/install-container.sh +1 -2
  51. package/src/native/ghidra/index.ts +0 -170
  52. package/src/native/ghidra/scripts/C64Export.java +0 -274
  53. package/src/native/ghidra/scripts/C64Prepare.java +0 -66
  54. package/tools/install-ghidra.sh +0 -40
@@ -1,5 +1,6 @@
1
1
  // The VICE-session operations of the Host Runtime wire: their vocabulary, shapes and validators.
2
2
 
3
+ import { MAX_PRESS_FRAMES, MAX_PRESS_TAPS, MAX_TAP_KEYS, type KeyTap } from "../c64-keys.ts";
3
4
  import { invalid, isInteger, isObject, isOneOf, onlyFields, ProtocolError, VIDEO_STANDARDS, type VideoStandard } from "./messages.ts";
4
5
 
5
6
  export const SPACES = ["c64", "drive8"] as const;
@@ -475,6 +476,20 @@ export interface ExecutionResult {
475
476
  space?: "c64" | "drive8";
476
477
  }
477
478
 
479
+ /**
480
+ * The end of a press: `taps` taps were done. A breakpoint, watchpoint or JAM
481
+ * can stop the taps early; then `stopReason` tells which, and the machine
482
+ * stays stopped. All keys are up again in both cases.
483
+ */
484
+ export interface PressResult {
485
+ taps: number;
486
+ state: RunState;
487
+ stopReason?: PointStopReason;
488
+ pc?: number;
489
+ pointId?: number;
490
+ space?: "c64" | "drive8";
491
+ }
492
+
478
493
  /** c64_run_until targets. */
479
494
  export type RunTarget =
480
495
  | { kind: "address"; address: number; space: Space; condition?: Condition }
@@ -528,6 +543,8 @@ export interface ViceOperations {
528
543
  /** `data`: PETSCII bytes as lowercase hex. */
529
544
  keyboard: { params: { data: string }; result: { queuedBytes: number } };
530
545
  joystick: { params: JoystickState; result: JoystickState };
546
+ /** Each tap holds its keys for `frames` frames, then waits `frames` frames with all keys up. */
547
+ press: { params: { taps: KeyTap[]; frames: number }; result: PressResult };
531
548
  breakpoint: { params: BreakpointParams; result: Breakpoint | PointRemoved | { breakpoints: Breakpoint[] } };
532
549
  watchpoint: { params: WatchpointParams; result: Watchpoint | PointRemoved | { watchpoints: Watchpoint[] } };
533
550
  cpuHistory: { params: { limit: number; space: Space }; result: { entries: HistoryEntry[] } };
@@ -589,6 +606,7 @@ export const VICE_OPERATIONS = [
589
606
  "reset",
590
607
  "keyboard",
591
608
  "joystick",
609
+ "press",
592
610
  "breakpoint",
593
611
  "watchpoint",
594
612
  "screenCapture",
@@ -915,6 +933,24 @@ export function validateViceParams<O extends ViceOperation>(op: O, params: unkno
915
933
  if (/^(?:..)*?00/.test(params.data)) invalid("PETSCII byte 0 cannot be typed");
916
934
  return { data: params.data } as ViceOperations[O]["params"];
917
935
  }
936
+ case "press": {
937
+ onlyFields(params, ["taps", "frames"]);
938
+ if (!Array.isArray(params.taps) || params.taps.length === 0 || params.taps.length > MAX_PRESS_TAPS) invalid(`taps must be a list of 1 to ${MAX_PRESS_TAPS} taps`);
939
+ const taps = (params.taps as unknown[]).map((tap): KeyTap => {
940
+ if (!isObject(tap)) invalid("each tap must be an object with keys and restore");
941
+ onlyFields(tap, ["keys", "restore"], "a tap");
942
+ const { keys, restore } = tap;
943
+ if (!Array.isArray(keys) || !keys.every((key, index) => isInteger(key, 0, 63) && (index === 0 || key > (keys[index - 1] as number)))) {
944
+ invalid("keys of a tap must be matrix places from 0 to 63, each once, in rising order");
945
+ }
946
+ if (typeof restore !== "boolean") invalid("restore of a tap must be true or false");
947
+ const count = keys.length + (restore ? 1 : 0);
948
+ if (count === 0 || count > MAX_TAP_KEYS) invalid(`a tap holds 1 to ${MAX_TAP_KEYS} keys, RESTORE included`);
949
+ return { keys: keys as number[], restore };
950
+ });
951
+ if (!isInteger(params.frames, 1, MAX_PRESS_FRAMES)) invalid(`frames must be a whole number from 1 to ${MAX_PRESS_FRAMES}`);
952
+ return { taps, frames: params.frames } as ViceOperations[O]["params"];
953
+ }
918
954
  case "joystick": {
919
955
  onlyFields(params, ["port", "direction", "fire"]);
920
956
  if (params.port !== 1 && params.port !== 2) invalid("port must be 1 or 2");
@@ -1206,6 +1242,17 @@ export function validateViceResult<O extends ViceOperation>(op: O, value: unknow
1206
1242
  if (!isInteger(value.queuedBytes, 1, MAX_KEYBOARD_BYTES)) throw new ProtocolError("keyboard result is malformed");
1207
1243
  break;
1208
1244
  }
1245
+ case "press": {
1246
+ const ok =
1247
+ isInteger(value.taps, 0, MAX_PRESS_TAPS) &&
1248
+ isOneOf(RUN_STATES, value.state) &&
1249
+ (value.stopReason === undefined || isOneOf(POINT_STOP_REASONS, value.stopReason)) &&
1250
+ (value.pc === undefined || isInteger(value.pc, 0, 0xffff)) &&
1251
+ (value.pointId === undefined || isInteger(value.pointId, 1, Number.MAX_SAFE_INTEGER)) &&
1252
+ (value.space === undefined || isOneOf(SPACES, value.space));
1253
+ if (!ok) throw new ProtocolError("press result is malformed");
1254
+ break;
1255
+ }
1209
1256
  case "breakpoint": {
1210
1257
  const ok = Array.isArray(value.breakpoints) ? value.breakpoints.every(isBreakpoint) : isRemoved(value) || isBreakpoint(value);
1211
1258
  if (!ok) throw new ProtocolError("breakpoint result is malformed");
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" },
package/src/vsf.ts ADDED
@@ -0,0 +1,98 @@
1
+ // The modules of a VICE snapshot file (.vsf), and the two changes that press
2
+ // keys in it: the keyboard matrix and a RESTORE. VICE saves a module as its
3
+ // name (16 bytes), its version (major, minor), its size with this header
4
+ // (4 bytes) and its data; every number is little-endian.
5
+
6
+ import { hasSignature, VSF_SIGNATURE } from "./media.ts";
7
+
8
+ /** The size of the header of a module: the name (16 bytes), the version (2 bytes) and the size (4 bytes). */
9
+ const MODULE_HEADER = 22;
10
+ const VSF_VERSION = "VICE Version\x1a";
11
+
12
+ export interface SnapshotModule {
13
+ major: number;
14
+ minor: number;
15
+ /** The data of the module: a view into the file, so a change to it changes the file. */
16
+ data: Buffer;
17
+ }
18
+
19
+ /** The module `name` of a snapshot file. Undefined when the file is no snapshot or has no such module. */
20
+ export function snapshotModule(file: Buffer, name: string): SnapshotModule | undefined {
21
+ if (!hasSignature("vsf", file)) return undefined;
22
+ // The magic, the version (2 bytes) and the machine name (16 bytes); a newer VICE adds its own version (8 bytes).
23
+ let at = VSF_SIGNATURE.length + 2 + 16;
24
+ if (file.subarray(at, at + VSF_VERSION.length).toString("latin1") === VSF_VERSION) at += VSF_VERSION.length + 8;
25
+ while (at + MODULE_HEADER <= file.length) {
26
+ const size = file.readUInt32LE(at + 18);
27
+ if (size < MODULE_HEADER || at + size > file.length) return undefined;
28
+ if (file.subarray(at, at + 16).toString("latin1").replace(/\0+$/, "") === name) {
29
+ return { major: file[at + 16]!, minor: file[at + 17]!, data: file.subarray(at + MODULE_HEADER, at + size) };
30
+ }
31
+ at += size;
32
+ }
33
+ return undefined;
34
+ }
35
+
36
+ /** VICE's keyboard module: keyarr (16 rows) and rev_keyarr (8 columns), each a DWORD. */
37
+ const KEYBOARD = { name: "KEYBOARD", major: 1, minor: 1, size: (16 + 8) * 4 };
38
+
39
+ /**
40
+ * The CPU module of x64sc. VICE r46088 renamed MAINCPU 1.4 to MAINC64CPU 1.5;
41
+ * the data is the same: the clock (8 bytes), A, X, Y, SP, PC (2), P, five
42
+ * DWORDs, five clocks (irq_clk, nmi_clk, ...), then nirq, nnmi and
43
+ * global_pending_int, then two clocks.
44
+ */
45
+ const CPU = [
46
+ { name: "MAINC64CPU", major: 1, minor: 5 },
47
+ { name: "MAINCPU", major: 1, minor: 4 },
48
+ ];
49
+ const CPU_SIZE = 103;
50
+ const NMI_CLK = 43;
51
+ const NNMI = 79;
52
+ const PENDING = 83;
53
+ /** IK_NMI of global_pending_int. */
54
+ const PENDING_NMI = 1;
55
+
56
+ /** A module of a version that the patch knows, or why there is none. */
57
+ function known(file: Buffer, versions: Array<{ name: string; major: number; minor: number }>, size: number): Buffer | string {
58
+ for (const version of versions) {
59
+ const module = snapshotModule(file, version.name);
60
+ if (module === undefined) continue;
61
+ if (module.major !== version.major || module.minor !== version.minor || module.data.length < size) {
62
+ return `the snapshot has ${version.name} ${module.major}.${module.minor} with ${module.data.length} bytes, and c64-re-tools knows ${version.major}.${version.minor} with ${size}`;
63
+ }
64
+ return module.data;
65
+ }
66
+ return `the snapshot has no module ${versions.map((version) => version.name).join(" or ")}`;
67
+ }
68
+
69
+ /**
70
+ * Sets the keyboard matrix of a snapshot file: bit n of rows[r] is the key at
71
+ * row r, column n. Gives why it cannot, for a snapshot of another layout.
72
+ */
73
+ export function setSnapshotMatrix(file: Buffer, rows: readonly number[]): string | undefined {
74
+ const data = known(file, [KEYBOARD], KEYBOARD.size);
75
+ if (typeof data === "string") return data;
76
+ for (let row = 0; row < 16; row++) data.writeUInt32LE(rows[row] ?? 0, row * 4);
77
+ for (let column = 0; column < 8; column++) {
78
+ let lines = 0;
79
+ for (let row = 0; row < 8; row++) if (((rows[row] ?? 0) >> column) & 1) lines |= 1 << row;
80
+ data.writeUInt32LE(lines, 64 + column * 4);
81
+ }
82
+ return undefined;
83
+ }
84
+
85
+ /**
86
+ * Presses RESTORE in a snapshot file, as VICE does: an NMI from now on, unless
87
+ * another source holds the NMI line or an NMI is pending already, which gives
88
+ * no new edge. Gives why it cannot, for a snapshot of another layout.
89
+ */
90
+ export function pressSnapshotRestore(file: Buffer): string | undefined {
91
+ const data = known(file, CPU, CPU_SIZE);
92
+ if (typeof data === "string") return data;
93
+ const pending = data.readUInt32LE(PENDING);
94
+ if (data.readUInt32LE(NNMI) !== 0 || (pending & PENDING_NMI) !== 0) return undefined;
95
+ data.writeUInt32LE(pending | PENDING_NMI, PENDING);
96
+ data.writeBigUInt64LE(data.readBigUInt64LE(0), NMI_CLK);
97
+ return undefined;
98
+ }
package/tools/c64run.c CHANGED
@@ -27,11 +27,9 @@
27
27
  #include "systems/c1541.h"
28
28
  #include "systems/c64.h"
29
29
 
30
- #define C64RUN_PROTOCOL 3
31
- // Keys that chips has no code for: each SHIFT alone, and the up arrow.
32
- #define C64RUN_KEY_LSHIFT 0x11
33
- #define C64RUN_KEY_RSHIFT 0x12
34
- #define C64RUN_KEY_UPARROW 0x5E
30
+ #define C64RUN_PROTOCOL 4
31
+ // The key code of matrix place 0 (row 0, column 0); place n has code 0x80 + n.
32
+ #define C64RUN_KEY_PLACE 0x80
35
33
  #ifndef CHIPS_COMMIT
36
34
  #define CHIPS_COMMIT "unknown"
37
35
  #endif
@@ -335,10 +333,9 @@ static const char* init(const char* romdir) {
335
333
  .chars = { .ptr = rom[2], .size = 0x1000 },
336
334
  },
337
335
  });
338
- // The matrix positions (column, line) of the keys that chips has no code for.
339
- kbd_register_key(&sys.kbd, C64RUN_KEY_LSHIFT, 7, 1, 0);
340
- kbd_register_key(&sys.kbd, C64RUN_KEY_RSHIFT, 4, 6, 0);
341
- kbd_register_key(&sys.kbd, C64RUN_KEY_UPARROW, 6, 6, 0);
336
+ // One code for each place of the matrix: place row * 8 + column, where the row is the
337
+ // line of CIA 1 port A and the column the bit of port B (chips: column, line).
338
+ for (int place = 0; place < 64; place++) kbd_register_key(&sys.kbd, C64RUN_KEY_PLACE + place, place & 7, place >> 3, 0);
342
339
  const uint16_t vector = rom[0][0x1FFC] | (rom[0][0x1FFD] << 8);
343
340
  for (int i = 0; i < 3; i++) free(rom[i]);
344
341
  pins = sys.pins;
@@ -536,11 +533,11 @@ int main(int argc, char** argv) {
536
533
  c64_joystick(&sys, (uint8_t)j1, (uint8_t)j2);
537
534
  printf("ok\n");
538
535
  } else if (!strcmp(cmd, "key")) {
539
- // key <code hex> down|up: a key of the keyboard matrix; the code is ASCII as
540
- // chips maps it (A-Z, 0-9, space 20, return 0d, ...); shifted keys press SHIFT.
541
- // 11 and 12 are the left and right SHIFT alone, 5e the up arrow, ff RESTORE (NMI).
536
+ // key <code hex> down|up: 80 + place is the key at matrix place row * 8 + column
537
+ // (80-bf), ff is RESTORE (NMI). chips holds at most 4 keys at once.
542
538
  unsigned code;
543
539
  if (sscanf(a1, "%x", &code) != 1 || (strcmp(a2, "down") && strcmp(a2, "up"))) { printf("err key: give a code and down or up\n"); continue; }
540
+ if ((code < C64RUN_KEY_PLACE || code >= C64RUN_KEY_PLACE + 64) && code != C64_KEY_RESTORE) { printf("err key: give 80-bf (a matrix place) or ff (RESTORE)\n"); continue; }
544
541
  if (!strcmp(a2, "down")) c64_key_down(&sys, (int)code);
545
542
  else {
546
543
  // chips releases a key in kbd_update, after its sticky time: one call
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env bash
2
2
  # The native tools of the skill scripts in a Debian or Ubuntu dev container,
3
- # as root: ACME, dxa, Exomizer, c64run with its C64 ROMs, and Ghidra. The dev container
3
+ # as root: ACME, dxa, Exomizer, and c64run with its C64 ROMs. The dev container
4
4
  # Feature runs the copy of this script that comes with the toolkit version it
5
5
  # installs, so the tools and the skills are always of the same version.
6
6
  # A tool is installed again only when its install files changed: a stamp in
@@ -57,6 +57,5 @@ packages acme unzip curl ca-certificates build-essential
57
57
  tool dxa install-dxa.sh
58
58
  tool exomizer install-exomizer.sh
59
59
  tool c64run install-chips.sh c64run.c
60
- tool ghidra install-ghidra.sh
61
60
 
62
61
  [[ -z "${APT_UPDATED}" ]] || rm -rf /var/lib/apt/lists/*
@@ -1,170 +0,0 @@
1
- // Headless Ghidra, run by the c64-static-analysis script. Ghidra runs with a settings
2
- // directory of its own per request: the c64-re-tools NMOS 6510 language goes
3
- // in there as an extension, so the user's Ghidra installation and settings
4
- // never change. Ghidra compiles the language from its source on first load.
5
- // Projects are disposable and live in the request workspace.
6
-
7
- import { cpSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
8
- import { userInfo } from "node:os";
9
- import { dirname, isAbsolute, join, resolve } from "node:path";
10
- import { fileURLToPath } from "node:url";
11
-
12
- import { Refusal } from "../../errors.ts";
13
- import { WireFailure } from "../../protocol/messages.ts";
14
- import { findOnPath, INSTALL_STEPS, isExecutableFile } from "../discover.ts";
15
- import type { ProcessSupervisor } from "../processes.ts";
16
- import type { Workspace } from "../staging.ts";
17
- import { outputTail, runToolOrFail, type ToolRun } from "../run.ts";
18
-
19
- export const GHIDRA_LANGUAGE = "C64RT_6510:LE:16:nmos";
20
- // Next to this module. New URL literals, so an installed skill gets the directories too.
21
- export const LANGUAGE_DIRECTORY = fileURLToPath(new URL("./language/", import.meta.url));
22
- export const SCRIPT_DIRECTORY = fileURLToPath(new URL("./scripts/", import.meta.url));
23
-
24
- export interface GhidraInstallation {
25
- /** The installation directory. */
26
- root: string;
27
- analyzeHeadless: string;
28
- /** For example ghidra_12.1.3_PUBLIC: the name of Ghidra's settings directory. */
29
- settingsName: string;
30
- version: string;
31
- /** The lowest Java version this Ghidra runs on (application.java.min), when it names one. */
32
- javaMin?: string;
33
- }
34
-
35
- /** Ghidra's launcher is a shell script, and a batch file on Windows. */
36
- const LAUNCHER_SUFFIX = process.platform === "win32" ? ".bat" : "";
37
-
38
- function installationAt(root: string, source: string): GhidraInstallation {
39
- const analyzeHeadless = join(root, "support", `analyzeHeadless${LAUNCHER_SUFFIX}`);
40
- let properties: string;
41
- try {
42
- if (!isExecutableFile(analyzeHeadless)) throw new Refusal("operation-failed", "no analyzeHeadless");
43
- properties = readFileSync(join(root, "Ghidra", "application.properties"), "utf8");
44
- } catch {
45
- throw new WireFailure("installation-incomplete", `${source} does not point to a Ghidra installation. ${INSTALL_STEPS}`);
46
- }
47
- const value = (key: string) => new RegExp(`^${key.replace(/\./g, "\\.")}=(.*)$`, "m").exec(properties)?.[1]?.trim();
48
- const version = value("application.version");
49
- const release = value("application.release.name");
50
- if (version === undefined || release === undefined) throw new WireFailure("installation-incomplete", `The Ghidra installation at ${source} has no version. ${INSTALL_STEPS}`);
51
- const javaMin = value("application.java.min");
52
- return { root, analyzeHeadless, settingsName: `ghidra_${version}_${release}`, version, ...(javaMin === undefined || javaMin === "" ? {} : { javaMin }) };
53
- }
54
-
55
- /** The version of a Ghidra installation as a result and the tool status name it, for example "Ghidra 12.1.3". */
56
- export function ghidraVersion(ghidra: GhidraInstallation): string {
57
- return `Ghidra ${ghidra.version}`;
58
- }
59
-
60
- /** Finds Ghidra: C64RT_GHIDRA names the installation directory, else analyzeHeadless on PATH. */
61
- export function findGhidra(env: NodeJS.ProcessEnv = process.env): GhidraInstallation {
62
- const configured = env.C64RT_GHIDRA;
63
- if (configured !== undefined && configured !== "") {
64
- if (!isAbsolute(configured)) throw new WireFailure("installation-incomplete", `C64RT_GHIDRA on this machine is not an absolute path. ${INSTALL_STEPS}`);
65
- return installationAt(configured, "C64RT_GHIDRA");
66
- }
67
- const found = findOnPath(["analyzeHeadless"], env, [LAUNCHER_SUFFIX]);
68
- if (found !== undefined) return installationAt(resolve(dirname(realpathSync(found)), ".."), "analyzeHeadless on PATH");
69
- throw new WireFailure("installation-incomplete", `Ghidra is not installed on this machine. ${INSTALL_STEPS}`);
70
- }
71
-
72
- /**
73
- * The user name in the name of Ghidra's settings directory: Java's user.name
74
- * without spaces and without a domain before the last backslash or slash. Java gives "?"
75
- * for a user without an entry in the password database, where Node throws.
76
- */
77
- export function ghidraUserName(lookup: () => string = () => userInfo().username): string {
78
- let name: string;
79
- try {
80
- name = lookup();
81
- } catch {
82
- name = "?";
83
- }
84
- name = name.split(" ").join("");
85
- return name.slice(Math.max(name.lastIndexOf("\\"), name.lastIndexOf("/")) + 1);
86
- }
87
-
88
- /**
89
- * Makes a Ghidra settings directory inside the workspace with the NMOS 6510
90
- * language installed as an extension. Returns the environment that makes
91
- * Ghidra use it.
92
- */
93
- export function prepareSettings(workspace: Workspace, ghidra: GhidraInstallation, env: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv {
94
- const config = workspace.directory("ghidra-config");
95
- const cache = workspace.directory("ghidra-cache");
96
- // With XDG_CONFIG_HOME set, Ghidra keeps its settings in [<user>-]ghidra/<settings name> below it: with
97
- // the user name only when that directory lies outside the user's home. The temporary directory is
98
- // outside it on Linux and macOS but inside it on Windows (in AppData), so both names get it.
99
- for (const application of [`${ghidraUserName()}-ghidra`, "ghidra"]) {
100
- const extension = join(config, application, ghidra.settingsName, "Extensions", "C64RT");
101
- mkdirSync(join(extension, "data"), { recursive: true });
102
- cpSync(LANGUAGE_DIRECTORY, join(extension, "data", "languages"), { recursive: true });
103
- writeFileSync(join(extension, "extension.properties"), `name=C64RT\ndescription=c64-re-tools NMOS 6510 language\nauthor=c64-re-tools\ncreatedOn=\nversion=${ghidra.version}\n`);
104
- writeFileSync(join(extension, "Module.manifest"), "");
105
- }
106
- return { ...env, XDG_CONFIG_HOME: config, XDG_CACHE_HOME: cache };
107
- }
108
-
109
- export interface HeadlessOptions {
110
- ghidra: GhidraInstallation;
111
- workspace: Workspace;
112
- /** Workspace-relative path of the file to import. */
113
- file: string;
114
- baseAddress: number;
115
- /** Scripts from these directories, before and after analysis, with their arguments. */
116
- scriptDirectories: string[];
117
- preScripts?: Array<{ name: string; args: string[] }>;
118
- postScripts?: Array<{ name: string; args: string[] }>;
119
- analyze: boolean;
120
- timeoutMs: number;
121
- supervisor: ProcessSupervisor;
122
- signal: AbortSignal;
123
- env?: NodeJS.ProcessEnv;
124
- }
125
-
126
- /** What Ghidra's launcher (launch.sh, launch.bat) prints when it finds no Java that it can use. */
127
- export const NO_USABLE_JDK = /The 'java' command could not be found in your PATH or with JAVA_HOME|Unable to prompt user for JDK path, no TTY detected|Failed to find a supported JDK/;
128
-
129
- /** A Ghidra without a usable JDK is an incomplete installation that names the Java version it needs. */
130
- export function noJdk(ghidra: GhidraInstallation): WireFailure {
131
- const java = ghidra.javaMin === undefined ? "a JDK" : `JDK ${ghidra.javaMin} or later`;
132
- return new WireFailure(
133
- "installation-incomplete",
134
- `${ghidraVersion(ghidra)} found no Java that it can use. It needs ${java}. ${INSTALL_STEPS}`,
135
- );
136
- }
137
-
138
- /** Imports one file into a disposable project and runs the scripts. Fails on timeout, abort or a Ghidra error exit. */
139
- export async function runHeadless(options: HeadlessOptions): Promise<ToolRun> {
140
- const env = prepareSettings(options.workspace, options.ghidra, options.env);
141
- const project = options.workspace.directory("ghidra-project");
142
- const argv = [
143
- options.ghidra.analyzeHeadless,
144
- project,
145
- "request",
146
- "-import",
147
- options.workspace.path(options.file),
148
- "-processor",
149
- GHIDRA_LANGUAGE,
150
- "-loader",
151
- "BinaryLoader",
152
- "-loader-baseAddr",
153
- `0x${options.baseAddress.toString(16)}`,
154
- "-scriptPath",
155
- options.scriptDirectories.join(";"),
156
- "-deleteProject",
157
- ];
158
- if (!options.analyze) argv.push("-noanalysis");
159
- else argv.push("-analysisTimeoutPerFile", String(Math.ceil(options.timeoutMs / 1000)));
160
- for (const script of options.preScripts ?? []) argv.push("-preScript", script.name, ...script.args);
161
- for (const script of options.postScripts ?? []) argv.push("-postScript", script.name, ...script.args);
162
- const run = await runToolOrFail("Ghidra", "The Ghidra analysis", { argv, cwd: options.workspace.root, timeoutMs: options.timeoutMs }, { supervisor: options.supervisor, signal: options.signal, env });
163
- if (run.code !== 0 && NO_USABLE_JDK.test(run.stdout + run.stderr)) throw noJdk(options.ghidra);
164
- if (run.code !== 0 || /^ERROR REPORT SCRIPT ERROR|Exception in thread "main"/m.test(run.stdout + run.stderr)) {
165
- // Ghidra's own error lines tell the user what to fix.
166
- const tail = outputTail("Ghidra", run, options.workspace.root, /ERROR|Exception|Error:/);
167
- throw new WireFailure("operation-failed", `Ghidra stopped with an error${tail === "" ? ` (exit ${run.code}).` : `.${tail}`}`);
168
- }
169
- return run;
170
- }