@henols/c64-re-tools 2.6.0-rc.7 → 2.6.0-rc.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/skills/c64-knowledge/SKILL.md +1 -1
- package/skills/c64-knowledge/scripts/knowledge.ts +2 -0
- package/skills/c64-knowledge/scripts/lib/listing.ts +18 -3
- package/skills/c64-reverse-engineering/SKILL.md +1 -1
- package/skills/c64-source/SKILL.md +5 -5
- package/skills/c64-source/scripts/source.ts +22 -20
- package/skills/c64-static-analysis/SKILL.md +3 -3
- package/skills/c64-static-analysis/scripts/lib/instructions.ts +22 -20
- package/skills/c64-static-analysis/scripts/static-analysis.ts +1 -8
- package/skills/c64-testing/SKILL.md +1 -0
- package/skills/c64-testing/references/recording-format.md +8 -0
- package/skills/c64-testing/scripts/lib/keys.ts +36 -0
- package/skills/c64-testing/scripts/lib/play.ts +2 -6
- package/skills/c64-testing/scripts/lib/recording.ts +13 -4
- package/skills/emulator/SKILL.md +1 -1
- package/src/cli/main.ts +1 -1
- package/src/host-client/tools.ts +1 -1
- package/src/knowledge/read.ts +16 -1
- package/src/native/ghidra/analyze.ts +74 -63
- package/src/native/ghidra/c64rt-wasm.ts +4 -0
- package/src/native/ghidra/language/c64rt_6510.sla +0 -0
- package/src/native/ghidra/pcode.ts +222 -0
- package/src/native/ghidra/walk.ts +205 -0
- package/src/native/ghidra/wasm.ts +98 -0
- package/src/native/processes.ts +1 -1
- package/src/native/types.ts +2 -2
- package/src/project.ts +4 -3
- package/src/script.ts +1 -1
- package/tools/install-container.sh +1 -2
- package/src/native/ghidra/index.ts +0 -170
- package/src/native/ghidra/scripts/C64Export.java +0 -274
- package/src/native/ghidra/scripts/C64Prepare.java +0 -66
- package/tools/install-ghidra.sh +0 -40
|
@@ -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
|
-
}
|
package/tools/install-ghidra.sh
DELETED
|
@@ -1,40 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env bash
|
|
2
|
-
# Installs Ghidra in /opt/ghidra_<version>_PUBLIC and points /opt/ghidra at
|
|
3
|
-
# it, so that C64RT_GHIDRA=/opt/ghidra stays the same when the version
|
|
4
|
-
# changes. Removes the Ghidra versions that it installed before. Ghidra needs
|
|
5
|
-
# Java 21. install-container.sh runs it as root.
|
|
6
|
-
|
|
7
|
-
set -Eeuo pipefail
|
|
8
|
-
|
|
9
|
-
GHIDRA_VERSION="12.1.3"
|
|
10
|
-
GHIDRA_ZIP="ghidra_${GHIDRA_VERSION}_PUBLIC_20260817.zip"
|
|
11
|
-
GHIDRA_URL="https://github.com/NationalSecurityAgency/ghidra/releases/download/Ghidra_${GHIDRA_VERSION}_build/${GHIDRA_ZIP}"
|
|
12
|
-
GHIDRA_SHA256="93a5d11a9ad510622acaaf908c556a7b9b764d338e78a7567f3689bf5081fd54"
|
|
13
|
-
DEST="/opt"
|
|
14
|
-
GHIDRA_DIR="${DEST}/ghidra_${GHIDRA_VERSION}_PUBLIC"
|
|
15
|
-
|
|
16
|
-
fail() {
|
|
17
|
-
printf 'Ghidra: %s\n' "$*" >&2
|
|
18
|
-
exit 1
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
[[ "$(id -u)" -eq 0 ]] || fail "run as root."
|
|
22
|
-
|
|
23
|
-
if [[ ! -d "${GHIDRA_DIR}" ]]; then
|
|
24
|
-
BUILD_DIR="$(mktemp -d -t ghidra-XXXXXXXX)"
|
|
25
|
-
trap 'rm -rf "${BUILD_DIR}"' EXIT
|
|
26
|
-
curl -fsSL --retry 3 -o "${BUILD_DIR}/${GHIDRA_ZIP}" "${GHIDRA_URL}"
|
|
27
|
-
echo "${GHIDRA_SHA256} ${BUILD_DIR}/${GHIDRA_ZIP}" | sha256sum -c - > /dev/null || fail "the archive has the wrong checksum."
|
|
28
|
-
unzip -q "${BUILD_DIR}/${GHIDRA_ZIP}" -d "${BUILD_DIR}/unpacked"
|
|
29
|
-
# Ghidra ships its decompiler only for x86-64; on arm64 its own Gradle wrapper builds it.
|
|
30
|
-
if [[ "$(uname -m)" == aarch64 || "$(uname -m)" == arm64 ]]; then
|
|
31
|
-
(cd "${BUILD_DIR}/unpacked/ghidra_${GHIDRA_VERSION}_PUBLIC/support/gradle" && GRADLE_USER_HOME="${BUILD_DIR}/gradle" ./gradlew --no-daemon buildNatives)
|
|
32
|
-
fi
|
|
33
|
-
mv "${BUILD_DIR}/unpacked/ghidra_${GHIDRA_VERSION}_PUBLIC" "${GHIDRA_DIR}"
|
|
34
|
-
fi
|
|
35
|
-
|
|
36
|
-
ln -sfn "${GHIDRA_DIR}" "${DEST}/ghidra"
|
|
37
|
-
for old in "${DEST}"/ghidra_*_PUBLIC; do
|
|
38
|
-
[[ "${old}" == "${GHIDRA_DIR}" || ! -d "${old}" ]] || rm -rf "${old}"
|
|
39
|
-
done
|
|
40
|
-
echo "Ghidra ${GHIDRA_VERSION} is installed in ${GHIDRA_DIR}, and ${DEST}/ghidra points at it."
|