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

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 (107) hide show
  1. package/package.json +2 -2
  2. package/skills/c64-assembler/SKILL.md +28 -14
  3. package/skills/c64-assembler/scripts/assembler.ts +28 -15
  4. package/skills/c64-development/SKILL.md +4 -4
  5. package/skills/c64-docs/SKILL.md +9 -7
  6. package/skills/c64-docs/scripts/docs.ts +24 -11
  7. package/skills/c64-docs/scripts/lib/reference.ts +119 -33
  8. package/skills/c64-docs/scripts/lib/source-map.ts +23 -4
  9. package/skills/c64-knowledge/SKILL.md +67 -42
  10. package/skills/c64-knowledge/scripts/knowledge.ts +90 -67
  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 +17 -11
  17. package/skills/c64-source/SKILL.md +71 -47
  18. package/skills/c64-source/scripts/lib/export.ts +89 -34
  19. package/skills/c64-source/scripts/lib/loader.ts +79 -36
  20. package/skills/c64-source/scripts/lib/source.ts +38 -32
  21. package/skills/c64-source/scripts/lib/stage.ts +11 -5
  22. package/skills/c64-source/scripts/lib/start-screen.asm +4 -2
  23. package/skills/c64-source/scripts/source.ts +278 -145
  24. package/skills/c64-static-analysis/SKILL.md +29 -25
  25. package/skills/c64-static-analysis/scripts/lib/coverage.ts +2 -25
  26. package/skills/c64-static-analysis/scripts/lib/findings.ts +11 -11
  27. package/skills/c64-static-analysis/scripts/lib/instructions.ts +26 -24
  28. package/skills/c64-static-analysis/scripts/lib/macros.ts +3 -1
  29. package/skills/c64-static-analysis/scripts/static-analysis.ts +69 -67
  30. package/skills/c64-testing/SKILL.md +15 -5
  31. package/skills/c64-testing/references/recording-format.md +26 -5
  32. package/skills/c64-testing/references/scenario-format.md +11 -8
  33. package/skills/c64-testing/scripts/lib/diff-files.ts +4 -18
  34. package/skills/c64-testing/scripts/lib/play.ts +39 -41
  35. package/skills/c64-testing/scripts/lib/recording.ts +220 -46
  36. package/skills/c64-testing/scripts/lib/replay.ts +32 -6
  37. package/skills/c64-testing/scripts/lib/runs.ts +8 -3
  38. package/skills/c64-testing/scripts/lib/scenario.ts +18 -11
  39. package/skills/c64-testing/scripts/testing.ts +23 -2
  40. package/skills/c64-unpacker/SKILL.md +10 -5
  41. package/skills/c64-unpacker/scripts/lib/loads.ts +34 -13
  42. package/skills/c64-unpacker/scripts/lib/machine.ts +7 -3
  43. package/skills/c64-unpacker/scripts/lib/stages.ts +18 -3
  44. package/skills/c64-unpacker/scripts/unpacker.ts +43 -9
  45. package/skills/emulator/SKILL.md +7 -12
  46. package/src/build-name.ts +55 -0
  47. package/src/c64-keys.ts +98 -0
  48. package/src/c64.ts +22 -2
  49. package/src/cli/main.ts +3 -29
  50. package/src/host/main.ts +3 -3
  51. package/src/host/server.ts +3 -1
  52. package/src/host/tools/index.ts +2 -7
  53. package/src/host/vice/process.ts +34 -17
  54. package/src/host/vice/session.ts +138 -31
  55. package/src/host-client/steps.ts +21 -18
  56. package/src/host-client/tools.ts +2 -7
  57. package/src/host-client/vice-session.ts +7 -1
  58. package/src/knowledge/evidence.ts +66 -0
  59. package/src/knowledge/history.ts +5 -5
  60. package/src/knowledge/import.ts +12 -5
  61. package/src/knowledge/program.ts +123 -32
  62. package/src/knowledge/read.ts +36 -13
  63. package/src/knowledge/schema.ts +43 -17
  64. package/src/knowledge/start-screen.ts +70 -0
  65. package/src/knowledge/text.ts +33 -5
  66. package/src/knowledge/write.ts +75 -36
  67. package/src/mcp/inputs.ts +12 -0
  68. package/src/mcp/server.ts +1 -1
  69. package/src/mcp/tools/debug.ts +23 -21
  70. package/src/mcp/tools/input.ts +38 -5
  71. package/src/mcp/tools/machine.ts +3 -42
  72. package/src/mcp/tools/media.ts +1 -1
  73. package/src/mcp/tools/memory.ts +12 -9
  74. package/src/native/acme.ts +1 -1
  75. package/src/native/c64run.ts +7 -4
  76. package/src/native/decompiler/analyze.ts +98 -0
  77. package/src/native/decompiler/c64rt-wasm.ts +4 -0
  78. package/src/native/decompiler/language/c64rt_6510.sla +0 -0
  79. package/src/native/{ghidra → decompiler}/language/c64rt_6510.slaspec +1 -1
  80. package/src/native/decompiler/pcode.ts +222 -0
  81. package/src/native/decompiler/walk.ts +205 -0
  82. package/src/native/decompiler/wasm.ts +98 -0
  83. package/src/native/discover.ts +3 -3
  84. package/src/native/dxa.ts +12 -1
  85. package/src/native/processes.ts +4 -4
  86. package/src/native/types.ts +27 -27
  87. package/src/opcodes.ts +1 -1
  88. package/src/platform.ts +30 -1
  89. package/src/project.ts +17 -4
  90. package/src/protocol/tools.ts +1 -45
  91. package/src/protocol/vice.ts +47 -0
  92. package/src/reference-pages.ts +64 -0
  93. package/src/script.ts +4 -4
  94. package/src/vsf.ts +98 -0
  95. package/tools/c64run.c +158 -15
  96. package/tools/install-container.sh +1 -2
  97. package/src/cli/status.ts +0 -127
  98. package/src/host/tools/status.ts +0 -47
  99. package/src/native/ghidra/analyze.ts +0 -87
  100. package/src/native/ghidra/index.ts +0 -170
  101. package/src/native/ghidra/scripts/C64Export.java +0 -274
  102. package/src/native/ghidra/scripts/C64Prepare.java +0 -66
  103. package/src/native/status.ts +0 -135
  104. package/tools/install-ghidra.sh +0 -40
  105. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.cspec +0 -0
  106. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.ldefs +0 -0
  107. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.pspec +0 -0
@@ -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
- }
@@ -1,274 +0,0 @@
1
- // Runs after Ghidra's analysis. Arguments: <request.json> <out.json>.
2
- //
3
- // Writes the structural result for the loaded image: functions with the
4
- // source of their names, code and defined-data regions, memory references
5
- // from instructions, every instruction with its bytes, mnemonic, operand
6
- // text and flow targets, and the requested decompilations within their bounds.
7
- //@category c64-re-tools
8
-
9
- import java.io.FileReader;
10
- import java.io.FileWriter;
11
- import java.util.LinkedHashSet;
12
- import java.util.Set;
13
-
14
- import com.google.gson.Gson;
15
- import com.google.gson.JsonArray;
16
- import com.google.gson.JsonElement;
17
- import com.google.gson.JsonObject;
18
-
19
- import ghidra.app.decompiler.DecompInterface;
20
- import ghidra.app.decompiler.DecompileResults;
21
- import ghidra.app.script.GhidraScript;
22
- import ghidra.program.model.address.Address;
23
- import ghidra.program.model.address.AddressSet;
24
- import ghidra.program.model.listing.CodeUnit;
25
- import ghidra.program.model.listing.Data;
26
- import ghidra.program.model.listing.Function;
27
- import ghidra.program.model.listing.Instruction;
28
- import ghidra.program.model.symbol.RefType;
29
- import ghidra.program.model.symbol.Reference;
30
- import ghidra.program.model.symbol.SourceType;
31
-
32
- public class C64Export extends GhidraScript {
33
- private static final java.util.regex.Pattern NAME = java.util.regex.Pattern.compile("^\\.?[A-Za-z_][A-Za-z0-9_]{0,63}$");
34
- /** The longest reason that the result check accepts. */
35
- private static final int MAX_REASON = 1000;
36
- /** The longest time for one decompilation, in seconds. */
37
- private static final int MAX_DECOMPILE_SECONDS = 60;
38
-
39
- @Override
40
- public void run() throws Exception {
41
- String[] args = getScriptArgs();
42
- JsonObject request;
43
- try (FileReader reader = new FileReader(args[0])) {
44
- request = new Gson().fromJson(reader, JsonObject.class);
45
- }
46
- long start = request.get("start").getAsLong();
47
- long end = request.get("end").getAsLong();
48
- AddressSet coverage = new AddressSet(toAddr(start), toAddr(end));
49
-
50
- JsonObject out = new JsonObject();
51
- JsonArray coverageOut = new JsonArray();
52
- coverageOut.add(range(start, end));
53
- out.add("coverage", coverageOut);
54
- out.add("functions", functions(coverage));
55
- out.add("regions", regions(coverage));
56
- out.add("references", references(coverage));
57
- out.add("instructions", instructions(coverage));
58
- JsonArray notDecompiled = new JsonArray();
59
- out.add("decompilations", decompile(request, notDecompiled));
60
- out.add("notDecompiled", notDecompiled);
61
- JsonObject completeness = new JsonObject();
62
- completeness.addProperty("functions", true);
63
- completeness.addProperty("regions", true);
64
- completeness.addProperty("references", true);
65
- out.add("completeness", completeness);
66
- try (FileWriter writer = new FileWriter(args[1])) {
67
- new Gson().toJson(out, writer);
68
- }
69
- }
70
-
71
- private static JsonObject range(long start, long end) {
72
- JsonObject range = new JsonObject();
73
- range.addProperty("start", start);
74
- range.addProperty("end", end);
75
- return range;
76
- }
77
-
78
- private JsonArray functions(AddressSet coverage) {
79
- JsonArray functions = new JsonArray();
80
- for (Function function : currentProgram.getFunctionManager().getFunctions(coverage, true)) {
81
- String name = function.getName();
82
- SourceType source = function.getSymbol().getSource();
83
- // Only the seeds carry user-defined names in this disposable project.
84
- String nameSource = source == SourceType.USER_DEFINED ? "seed" : source == SourceType.DEFAULT ? "generated" : "native";
85
- if (!NAME.matcher(name).matches()) {
86
- // A name that this script makes is generated, whatever name it replaces.
87
- name = String.format("FUN_%04x", function.getEntryPoint().getOffset());
88
- nameSource = "generated";
89
- }
90
- JsonObject item = new JsonObject();
91
- item.addProperty("entry", function.getEntryPoint().getOffset());
92
- item.addProperty("name", name);
93
- item.addProperty("nameSource", nameSource);
94
- functions.add(item);
95
- }
96
- return functions;
97
- }
98
-
99
- /** Instructions are code and defined data is data; undefined bytes are not classified. */
100
- private JsonArray regions(AddressSet coverage) {
101
- JsonArray regions = new JsonArray();
102
- String kind = null;
103
- long first = 0;
104
- long last = -2;
105
- for (CodeUnit unit : currentProgram.getListing().getCodeUnits(coverage, true)) {
106
- String unitKind = unit instanceof Instruction ? "code" : (unit instanceof Data && ((Data) unit).isDefined()) ? "data" : null;
107
- long unitStart = unit.getMinAddress().getOffset();
108
- long unitEnd = Math.min(unit.getMaxAddress().getOffset(), coverage.getMaxAddress().getOffset());
109
- if (unitKind != null && unitKind.equals(kind) && unitStart == last + 1) {
110
- last = unitEnd;
111
- continue;
112
- }
113
- if (kind != null) {
114
- JsonObject region = range(first, last);
115
- region.addProperty("classification", kind);
116
- regions.add(region);
117
- }
118
- kind = unitKind;
119
- first = unitStart;
120
- last = unitEnd;
121
- }
122
- if (kind != null) {
123
- JsonObject region = range(first, last);
124
- region.addProperty("classification", kind);
125
- regions.add(region);
126
- }
127
- return regions;
128
- }
129
-
130
- private JsonArray references(AddressSet coverage) {
131
- Set<String> seen = new LinkedHashSet<>();
132
- JsonArray references = new JsonArray();
133
- for (Instruction instruction : currentProgram.getListing().getInstructions(coverage, true)) {
134
- for (Reference reference : instruction.getReferencesFrom()) {
135
- RefType type = reference.getReferenceType();
136
- Address to = reference.getToAddress();
137
- if (!reference.isMemoryReference() || !to.isMemoryAddress() || type == RefType.FALL_THROUGH) {
138
- continue;
139
- }
140
- long from = instruction.getMinAddress().getOffset();
141
- if (type.isCall()) {
142
- add(references, seen, from, to.getOffset(), "call");
143
- } else if (type.isJump() || type.isFlow()) {
144
- add(references, seen, from, to.getOffset(), "jump");
145
- } else {
146
- if (type.isRead()) {
147
- add(references, seen, from, to.getOffset(), "read");
148
- }
149
- if (type.isWrite()) {
150
- add(references, seen, from, to.getOffset(), "write");
151
- }
152
- if (!type.isRead() && !type.isWrite()) {
153
- add(references, seen, from, to.getOffset(), "reference");
154
- }
155
- }
156
- }
157
- }
158
- return references;
159
- }
160
-
161
- /** Every instruction in the coverage, in address order, as Ghidra decoded it with the 6510 language. */
162
- private JsonArray instructions(AddressSet coverage) throws Exception {
163
- JsonArray instructions = new JsonArray();
164
- for (Instruction instruction : currentProgram.getListing().getInstructions(coverage, true)) {
165
- JsonObject item = new JsonObject();
166
- item.addProperty("address", instruction.getMinAddress().getOffset());
167
- StringBuilder bytes = new StringBuilder();
168
- for (byte value : instruction.getBytes()) {
169
- bytes.append(String.format("%02x", value & 0xff));
170
- }
171
- item.addProperty("bytes", bytes.toString());
172
- item.addProperty("mnemonic", instruction.getMnemonicString().toLowerCase());
173
- StringBuilder operands = new StringBuilder();
174
- for (int index = 0; index < instruction.getNumOperands(); index++) {
175
- if (index > 0) {
176
- operands.append(",");
177
- }
178
- operands.append(instruction.getDefaultOperandRepresentation(index));
179
- }
180
- item.addProperty("operands", operands.toString());
181
- JsonArray flows = new JsonArray();
182
- for (Address flow : instruction.getFlows()) {
183
- flows.add(flow.getOffset());
184
- }
185
- item.add("flows", flows);
186
- instructions.add(item);
187
- }
188
- return instructions;
189
- }
190
-
191
- private static void add(JsonArray references, Set<String> seen, long from, long to, String type) {
192
- if (!seen.add(from + ":" + to + ":" + type)) {
193
- return;
194
- }
195
- JsonObject reference = new JsonObject();
196
- reference.addProperty("from", from);
197
- reference.addProperty("to", to);
198
- reference.addProperty("type", type);
199
- references.add(reference);
200
- }
201
-
202
- /** A requested routine without decompiled code, and the decompiler's reason. */
203
- private static void notDecompiled(JsonArray list, long entry, String reason) {
204
- JsonObject item = new JsonObject();
205
- item.addProperty("entry", entry);
206
- String text = reason == null || reason.isBlank() ? "the decompiler gave no reason" : reason.strip();
207
- item.addProperty("reason", text.length() > MAX_REASON ? text.substring(0, MAX_REASON) : text);
208
- list.add(item);
209
- }
210
-
211
- private JsonArray decompile(JsonObject request, JsonArray failures) {
212
- JsonArray decompilations = new JsonArray();
213
- JsonArray entries = request.getAsJsonArray("decompile");
214
- if (entries.size() == 0) {
215
- return decompilations;
216
- }
217
- int perFunction = request.get("maxChars").getAsInt();
218
- int remaining = request.get("maxTotalChars").getAsInt();
219
- // The time that is left for the decompilations, as a clock time in milliseconds.
220
- long deadline = request.get("decompileDeadline").getAsLong();
221
- int routinesLeft = entries.size();
222
- DecompInterface decompiler = new DecompInterface();
223
- try {
224
- // Ghidra ships no native decompiler for some platforms (macOS): it then does not start.
225
- if (!decompiler.openProgram(currentProgram)) {
226
- String reason = "the Ghidra decompiler did not start: " + decompiler.getLastMessage();
227
- for (JsonElement element : entries) {
228
- notDecompiled(failures, element.getAsLong(), reason);
229
- }
230
- return decompilations;
231
- }
232
- for (JsonElement element : entries) {
233
- // Each routine gets an equal part of the time that is left, so every routine gets a turn.
234
- long secondsLeft = (deadline - System.currentTimeMillis()) / 1000;
235
- int seconds = (int) Math.min(MAX_DECOMPILE_SECONDS, secondsLeft / routinesLeft);
236
- routinesLeft--;
237
- Function function = getFunctionAt(toAddr(element.getAsLong()));
238
- if (function == null) {
239
- notDecompiled(failures, element.getAsLong(), "no function starts at this address");
240
- continue;
241
- }
242
- if (remaining <= 0) {
243
- notDecompiled(failures, element.getAsLong(), "the decompiled text of the other routines used the whole limit");
244
- continue;
245
- }
246
- if (seconds < 1) {
247
- notDecompiled(failures, element.getAsLong(), "the time for the Ghidra run ended before this routine");
248
- continue;
249
- }
250
- DecompileResults results = decompiler.decompileFunction(function, seconds, monitor);
251
- if (!results.decompileCompleted() || results.getDecompiledFunction() == null) {
252
- notDecompiled(failures, element.getAsLong(), results.getErrorMessage());
253
- continue;
254
- }
255
- String text = results.getDecompiledFunction().getC();
256
- int limit = Math.min(perFunction, remaining);
257
- boolean truncated = text.length() > limit;
258
- if (truncated) {
259
- text = text.substring(0, limit);
260
- }
261
- remaining -= text.length();
262
- JsonObject item = new JsonObject();
263
- item.addProperty("entry", function.getEntryPoint().getOffset());
264
- item.addProperty("text", text);
265
- item.addProperty("truncated", truncated);
266
- decompilations.add(item);
267
- }
268
- }
269
- finally {
270
- decompiler.dispose();
271
- }
272
- return decompilations;
273
- }
274
- }
@@ -1,66 +0,0 @@
1
- // Runs before Ghidra's analysis. Arguments: <seeds.json>.
2
- //
3
- // Fills the rest of the 64 KiB address space with uninitialized memory, so
4
- // references to I/O and other RAM resolve, then applies the knowledge seeds:
5
- // labels (user-defined names), data ranges (defined bytes that analysis does
6
- // not disassemble), entry points (disassembled functions) and code starts
7
- // (disassembled code without a function: a branch target is no routine).
8
- //@category c64-re-tools
9
-
10
- import java.io.FileReader;
11
-
12
- import com.google.gson.Gson;
13
- import com.google.gson.JsonElement;
14
- import com.google.gson.JsonObject;
15
-
16
- import ghidra.app.script.GhidraScript;
17
- import ghidra.program.model.address.Address;
18
- import ghidra.program.model.data.ArrayDataType;
19
- import ghidra.program.model.data.ByteDataType;
20
- import ghidra.program.model.mem.Memory;
21
- import ghidra.program.model.symbol.SourceType;
22
-
23
- public class C64Prepare extends GhidraScript {
24
- @Override
25
- public void run() throws Exception {
26
- JsonObject seeds;
27
- try (FileReader reader = new FileReader(getScriptArgs()[0])) {
28
- seeds = new Gson().fromJson(reader, JsonObject.class);
29
- }
30
- long start = seeds.get("start").getAsLong();
31
- long end = seeds.get("end").getAsLong();
32
- Memory memory = currentProgram.getMemory();
33
- if (start > 0) {
34
- memory.createUninitializedBlock("RAM_LOW", toAddr(0), start, false);
35
- }
36
- if (end < 0xffff) {
37
- memory.createUninitializedBlock("RAM_HIGH", toAddr(end + 1), 0xffff - end, false);
38
- }
39
-
40
- for (JsonElement element : seeds.getAsJsonArray("labels")) {
41
- JsonObject label = element.getAsJsonObject();
42
- createLabel(toAddr(label.get("address").getAsLong()), label.get("name").getAsString(), true, SourceType.USER_DEFINED);
43
- }
44
- for (JsonElement element : seeds.getAsJsonArray("dataRanges")) {
45
- JsonObject range = element.getAsJsonObject();
46
- Address first = toAddr(range.get("start").getAsLong());
47
- Address last = toAddr(range.get("end").getAsLong());
48
- int length = (int) (last.getOffset() - first.getOffset() + 1);
49
- currentProgram.getListing().clearCodeUnits(first, last, false);
50
- currentProgram.getListing().createData(first, new ArrayDataType(ByteDataType.dataType, length, 1));
51
- }
52
- for (JsonElement element : seeds.getAsJsonArray("entryPoints")) {
53
- Address entry = toAddr(element.getAsLong());
54
- addEntryPoint(entry);
55
- disassemble(entry);
56
- if (getFunctionAt(entry) == null) {
57
- createFunction(entry, null);
58
- }
59
- }
60
- if (seeds.has("codeStarts")) {
61
- for (JsonElement element : seeds.getAsJsonArray("codeStarts")) {
62
- disassemble(toAddr(element.getAsLong()));
63
- }
64
- }
65
- }
66
- }
@@ -1,135 +0,0 @@
1
- // Tool status: finds each native tool the way its operations do and runs it
2
- // once with a version option, so a user can see in advance which tools work.
3
- // The Host Runtime reports VICE and its tools (host.status); the CLI reports
4
- // the tools that skill scripts run themselves (ACME, DXA, Exomizer, Ghidra).
5
-
6
- import { tmpdir } from "node:os";
7
- import { stripVTControlCharacters } from "node:util";
8
-
9
- import { isRefusal } from "../errors.ts";
10
- import { type ToolStatus } from "../protocol/tools.ts";
11
- import { ACME, C64RUN, DXA, EXOMIZER, findTool, INSTALL_STEPS } from "./discover.ts";
12
- import { findGhidra, ghidraVersion, NO_USABLE_JDK, noJdk } from "./ghidra/index.ts";
13
- import { runTool, type ToolContext } from "./run.ts";
14
- import { Workspace } from "./staging.ts";
15
-
16
- const PROBE_TIMEOUT_MS = 20_000;
17
-
18
- export interface Probe {
19
- name: string;
20
- /** The executable; throws WireFailure(installation-incomplete) when missing. */
21
- find: (env: NodeJS.ProcessEnv) => string;
22
- args: string[];
23
- /** The version line; no such line means the tool did not run correctly. */
24
- pattern: RegExp;
25
- }
26
-
27
- /** dxa's version line, also as "D:\\tools\\dxa.exe v0.1.5 -- symbolic 65xx disassembler" on Windows. */
28
- export const DXA_VERSION = /^(?:.*[\\/])?dxa(?:\.exe)? v\d/i;
29
-
30
- /** The first output line that matches, without terminal color codes (c1541 colors an OpenCBM notice). */
31
- export function versionLine(output: string, pattern: RegExp): string | undefined {
32
- return stripVTControlCharacters(output)
33
- .split(/\r?\n/)
34
- .map((line) => line.trim())
35
- .find((line) => pattern.test(line));
36
- }
37
-
38
- async function run(
39
- name: string,
40
- path: string,
41
- args: string[],
42
- version: (output: string) => string | undefined,
43
- context: ToolContext,
44
- /** A known cause in the output, said in place of the exit status. */
45
- cause?: (output: string) => string | undefined,
46
- ): Promise<ToolStatus> {
47
- const result = await runTool({ argv: [path, ...args], cwd: tmpdir(), supervisor: context.supervisor, signal: context.signal, timeoutMs: PROBE_TIMEOUT_MS, env: context.env });
48
- const output = `${result.stdout}\n${result.stderr}`;
49
- const found = version(output);
50
- if (found !== undefined) return { name, found: true, path, version: found, runs: true };
51
- const known = cause?.(output);
52
- if (known !== undefined) return { name, found: true, path, runs: false, problem: known };
53
- const problem = result.timedOut ? "It did not answer in time." : result.spawnError !== undefined ? `It did not start (${result.spawnError}).` : `It did not run correctly (exit ${result.code ?? result.signal}).`;
54
- return { name, found: true, path, runs: false, problem };
55
- }
56
-
57
- function missing(name: string, error: unknown): ToolStatus {
58
- if (!isRefusal(error)) throw error;
59
- return { name, found: false, runs: false, problem: error.message };
60
- }
61
-
62
- /** Finds and runs each probed tool once. */
63
- export function probeTools(probes: Probe[], context: ToolContext): Promise<ToolStatus[]> {
64
- const env = context.env ?? process.env;
65
- return Promise.all(
66
- probes.map(async (probe) => {
67
- let path: string;
68
- try {
69
- path = probe.find(env);
70
- } catch (error) {
71
- return missing(probe.name, error);
72
- }
73
- return run(probe.name, path, probe.args, (output) => versionLine(output, probe.pattern), context);
74
- }),
75
- );
76
- }
77
-
78
- /** Ghidra: without arguments analyzeHeadless starts Java and prints its usage, which proves that it runs. */
79
- export async function probeGhidra(context: ToolContext): Promise<ToolStatus> {
80
- const env = context.env ?? process.env;
81
- try {
82
- const ghidra = findGhidra(env);
83
- // Its own settings directory keeps the user's Ghidra settings and logs untouched.
84
- const workspace = Workspace.create(context.supervisor, "c64-re-tools-ghidra-status-");
85
- const settings = workspace.root;
86
- try {
87
- const status = await run(
88
- "Ghidra",
89
- ghidra.analyzeHeadless,
90
- [],
91
- (output) => (/Headless Analyzer Usage/.test(output) ? ghidraVersion(ghidra) : undefined),
92
- { ...context, env: { ...env, XDG_CONFIG_HOME: settings, XDG_CACHE_HOME: settings } },
93
- (output) => (NO_USABLE_JDK.test(output) ? noJdk(ghidra).message : undefined),
94
- );
95
- return { ...status, path: ghidra.root };
96
- } finally {
97
- workspace.remove();
98
- }
99
- } catch (error) {
100
- return missing("Ghidra", error);
101
- }
102
- }
103
-
104
- /** c64run: --version prints its version and whether its ROM folder has the three C64 ROMs. */
105
- export async function probeC64run(context: ToolContext): Promise<ToolStatus> {
106
- const env = context.env ?? process.env;
107
- try {
108
- const path = findTool(C64RUN, env);
109
- return await run(
110
- "c64run",
111
- path,
112
- ["--version"],
113
- (output) => (/^roms=ok /m.test(output) ? versionLine(output, /^c64run protocol=/) : undefined),
114
- context,
115
- (output) => {
116
- const missing = /^roms=missing (.*)$/m.exec(output)?.[1];
117
- return missing === undefined ? undefined : `It has no C64 ROMs: ${missing}. ${INSTALL_STEPS}`;
118
- },
119
- );
120
- } catch (error) {
121
- return missing("c64run", error);
122
- }
123
- }
124
-
125
- /** The tools that skill scripts run themselves, on this machine. */
126
- export async function localToolStatus(context: ToolContext): Promise<ToolStatus[]> {
127
- const probes: Probe[] = [
128
- { name: "ACME", find: (env) => findTool(ACME, env), args: ["--version"], pattern: /^This is ACME, release / },
129
- // dxa -V prints its version and exits with status 1. It names itself by argv[0], without the
130
- // directory only where that uses "/": on Windows the line starts with the full path.
131
- { name: "dxa", find: (env) => findTool(DXA, env), args: ["-V"], pattern: DXA_VERSION },
132
- { name: "Exomizer", find: (env) => findTool(EXOMIZER, env), args: ["-v"], pattern: /^Exomizer v\d/ },
133
- ];
134
- return [...(await probeTools(probes, context)), await probeGhidra(context), await probeC64run(context)];
135
- }