@henols/c64-re-tools 2.6.0-rc.6 → 2.6.0-rc.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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 +6 -8
- package/src/cli/main.ts +3 -29
- package/src/host/main.ts +1 -1
- package/src/host/tools/index.ts +1 -6
- package/src/host/vice/session.ts +1 -1
- package/src/host-client/tools.ts +2 -7
- package/src/knowledge/read.ts +16 -1
- package/src/mcp/server.ts +0 -1
- package/src/mcp/tools/machine.ts +3 -42
- package/src/mcp/tools/media.ts +1 -1
- package/src/native/dxa.ts +12 -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/protocol/tools.ts +1 -45
- package/src/script.ts +1 -1
- package/tools/install-container.sh +1 -2
- package/src/cli/status.ts +0 -127
- package/src/host/tools/status.ts +0 -47
- 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/src/native/status.ts +0 -135
- package/tools/install-ghidra.sh +0 -40
|
@@ -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
|
|
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/*
|
package/src/cli/status.ts
DELETED
|
@@ -1,127 +0,0 @@
|
|
|
1
|
-
// The status report of the CLI: the installed skills and MCP declarations,
|
|
2
|
-
// the tools on this machine and the Host Runtime with its tools.
|
|
3
|
-
|
|
4
|
-
import { readFileSync } from "node:fs";
|
|
5
|
-
import { isAbsolute, join } from "node:path";
|
|
6
|
-
|
|
7
|
-
import { installedItems, scopeRoot, type InstallItem, type Scope } from "./cleanup.ts";
|
|
8
|
-
import { hostTools, type ToolCallOptions } from "../host-client/tools.ts";
|
|
9
|
-
import { viceVersionOf } from "../native/discover.ts";
|
|
10
|
-
import { PACKAGE } from "../package.ts";
|
|
11
|
-
import { STOP_AND_ASK } from "../protocol/messages.ts";
|
|
12
|
-
import type { HostInfo, ToolStatus } from "../protocol/tools.ts";
|
|
13
|
-
|
|
14
|
-
/** One line per tool under `heading`: its version, or why it does not run; then each known flaw of it. */
|
|
15
|
-
export function toolLines(heading: string, tools: readonly ToolStatus[]): string[] {
|
|
16
|
-
return [
|
|
17
|
-
heading,
|
|
18
|
-
...tools.flatMap((tool) => [
|
|
19
|
-
tool.runs
|
|
20
|
-
? ` ${tool.name}: ${tool.version} (${tool.path})`
|
|
21
|
-
: tool.found
|
|
22
|
-
? ` ${tool.name}: found at ${tool.path} but it does not run. ${tool.problem}`
|
|
23
|
-
: ` ${tool.name}: missing. ${tool.problem}`,
|
|
24
|
-
...(tool.flaws ?? []).map((flaw) => ` Known flaw: ${flaw}`),
|
|
25
|
-
]),
|
|
26
|
-
];
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
/**
|
|
30
|
-
* Whether the Host Runtime answers, and the tools it has. VICE and its tools
|
|
31
|
-
* live on the host; it finds and runs each one. One request shows both that
|
|
32
|
-
* the host answers and what it has. `ready` is true when the host answers and
|
|
33
|
-
* every tool on it runs.
|
|
34
|
-
*/
|
|
35
|
-
export async function hostStatusLines(options: ToolCallOptions = {}): Promise<{ lines: string[]; ready: boolean }> {
|
|
36
|
-
let host: HostInfo;
|
|
37
|
-
let tools: ToolStatus[];
|
|
38
|
-
try {
|
|
39
|
-
({ host, tools } = await hostTools(options));
|
|
40
|
-
} catch (error) {
|
|
41
|
-
// status is read by a person: the instruction for an agent stays out.
|
|
42
|
-
return { lines: [`Host Runtime: not reachable. ${(error as Error).message.replace(` ${STOP_AND_ASK}`, "")}`], ready: false };
|
|
43
|
-
}
|
|
44
|
-
const mixed = mixedViceBuilds(tools);
|
|
45
|
-
return {
|
|
46
|
-
lines: [
|
|
47
|
-
`Host Runtime: reachable, c64-re-tools ${host.version} on ${host.platform} ${host.release} (${host.arch})`,
|
|
48
|
-
...(host.version === PACKAGE.version ? [] : [` Warning: the Host Runtime is c64-re-tools ${host.version} and this is ${PACKAGE.version}. Start the host again so that both are the same version.`]),
|
|
49
|
-
...toolLines("Tools on the host:", tools),
|
|
50
|
-
...(mixed === undefined ? [] : [` Warning: ${mixed}`]),
|
|
51
|
-
],
|
|
52
|
-
ready: tools.every((tool) => tool.runs),
|
|
53
|
-
};
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
/** A warning when x64sc, c1541 and petcat that run come from different VICE versions or builds. */
|
|
57
|
-
export function mixedViceBuilds(tools: readonly ToolStatus[]): string | undefined {
|
|
58
|
-
const running = tools.filter((tool) => tool.runs && tool.version !== undefined);
|
|
59
|
-
const builds = running.map((tool) => {
|
|
60
|
-
const version = viceVersionOf(tool.version!);
|
|
61
|
-
return version === undefined ? tool.version! : `VICE ${version.major}.${version.minor}${version.revision === undefined ? "" : ` SVN r${version.revision}`}`;
|
|
62
|
-
});
|
|
63
|
-
if (new Set(builds).size <= 1) return undefined;
|
|
64
|
-
return `the VICE tools come from different VICE builds: ${running.map((tool) => `${tool.version} (${tool.path})`).join(", ")}. Put x64sc, c1541 and petcat of one VICE first on PATH, or set C64RT_VICE, C64RT_C1541 and C64RT_PETCAT.`;
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
/**
|
|
68
|
-
* The skills and MCP declarations that install wrote for this project and
|
|
69
|
-
* globally: the c64-re-tools version of each harness's skills,
|
|
70
|
-
* from their package.json, and the command that starts the MCP server. A
|
|
71
|
-
* warning names skills of another version than this one.
|
|
72
|
-
*/
|
|
73
|
-
export function installedLines(cwd = process.cwd()): string[] {
|
|
74
|
-
const lines: string[] = [];
|
|
75
|
-
for (const scope of ["project", "global"] as const satisfies readonly Scope[]) {
|
|
76
|
-
const items = installedItems(scope, undefined, cwd);
|
|
77
|
-
if (items.length === 0) continue;
|
|
78
|
-
const root = scopeRoot(scope, cwd);
|
|
79
|
-
lines.push(`Installed ${scope === "project" ? `in this project (${root})` : "globally"}:`);
|
|
80
|
-
for (const harness of [...new Set(items.map((item) => item.harness))]) {
|
|
81
|
-
const skills = items.filter((item) => item.harness === harness && item.kind === "skill");
|
|
82
|
-
const versions = [...new Set(skills.map((item) => skillVersion(item, root)).filter((version) => version !== undefined))];
|
|
83
|
-
if (skills.length > 0) {
|
|
84
|
-
lines.push(` ${harness}: ${skills.length} skills, c64-re-tools ${versions.length === 0 ? "of an unknown version" : versions.join(" and ")}`);
|
|
85
|
-
const other = versions.filter((version) => version !== PACKAGE.version);
|
|
86
|
-
if (other.length > 0) lines.push(` Warning: the ${harness} skills are c64-re-tools ${other.join(" and ")} and this is ${PACKAGE.version}. Run npx -y ${PACKAGE.name}@${PACKAGE.tag} update${scope === "global" ? " --global" : ""} to install this version.`);
|
|
87
|
-
}
|
|
88
|
-
for (const item of items.filter((candidate) => candidate.harness === harness && candidate.kind === "mcp")) {
|
|
89
|
-
lines.push(` ${harness} MCP server: ${mcpCommand(item, root) ?? `declared in ${item.files.join(", ")}`}`);
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
}
|
|
93
|
-
if (lines.length === 0) return ["Installed: nothing in this project or globally."];
|
|
94
|
-
return lines;
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
function itemPath(file: string, root: string): string {
|
|
98
|
-
return isAbsolute(file) ? file : join(root, file);
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
/** The version in the package.json of an installed skill; a skill without scripts has none. */
|
|
102
|
-
function skillVersion(item: InstallItem, root: string): string | undefined {
|
|
103
|
-
const file = item.files.find((candidate) => candidate.endsWith("/package.json") || candidate.endsWith("\\package.json"));
|
|
104
|
-
if (file === undefined) return undefined;
|
|
105
|
-
try {
|
|
106
|
-
const { version } = JSON.parse(readFileSync(itemPath(file, root), "utf8")) as { version?: unknown };
|
|
107
|
-
return typeof version === "string" ? version : undefined;
|
|
108
|
-
} catch {
|
|
109
|
-
return undefined;
|
|
110
|
-
}
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
/** The command of the MCP server in a JSON configuration file, or undefined for another format. */
|
|
114
|
-
function mcpCommand(item: InstallItem, root: string): string | undefined {
|
|
115
|
-
const key = item.detail?.mergeKey;
|
|
116
|
-
const [file] = item.files;
|
|
117
|
-
if (key === undefined || file === undefined) return undefined;
|
|
118
|
-
try {
|
|
119
|
-
const servers = (JSON.parse(readFileSync(itemPath(file, root), "utf8")) as Record<string, unknown>)[key] as Record<string, { command?: unknown; args?: unknown }> | undefined;
|
|
120
|
-
const server = servers?.[item.name];
|
|
121
|
-
if (typeof server?.command !== "string") return undefined;
|
|
122
|
-
const args = Array.isArray(server.args) ? server.args.filter((arg): arg is string => typeof arg === "string") : [];
|
|
123
|
-
return [server.command, ...args].join(" ");
|
|
124
|
-
} catch {
|
|
125
|
-
return undefined;
|
|
126
|
-
}
|
|
127
|
-
}
|
package/src/host/tools/status.ts
DELETED
|
@@ -1,47 +0,0 @@
|
|
|
1
|
-
// host.status: VICE and the tools that come with it, each found the way its
|
|
2
|
-
// operations find it and run once with a version option. A tool from a
|
|
3
|
-
// VICE older than MIN_VICE is reported as not working, as its operations refuse it.
|
|
4
|
-
// VICE itself is reported with the version that the host read from the
|
|
5
|
-
// running emulator at start: the Homebrew x64sc of VICE 3.10 on macOS stops
|
|
6
|
-
// on -version ("argv[0] is NULL") although the emulator runs.
|
|
7
|
-
|
|
8
|
-
import { arch, platform, release } from "node:os";
|
|
9
|
-
|
|
10
|
-
import { PACKAGE } from "../../package.ts";
|
|
11
|
-
import type { HostInfo, ToolStatus } from "../../protocol/tools.ts";
|
|
12
|
-
import { C1541, findTool, isOlderThanMinimum, MIN_VICE, PETCAT, VICE, viceFlaws, viceVersionOf, type ToolSpec, type ViceVersion } from "../../native/discover.ts";
|
|
13
|
-
import type { ToolContext } from "../../native/run.ts";
|
|
14
|
-
import { probeTools } from "../../native/status.ts";
|
|
15
|
-
import { findVice } from "../vice/process.ts";
|
|
16
|
-
|
|
17
|
-
function requireMinimum(status: ToolStatus, tool: ToolSpec): ToolStatus {
|
|
18
|
-
if (!status.runs) return status;
|
|
19
|
-
const version = viceVersionOf(status.version ?? "");
|
|
20
|
-
if (version !== undefined && !isOlderThanMinimum(version)) return status;
|
|
21
|
-
const found = version === undefined ? "It does not tell its VICE version" : `It comes from VICE ${version.major}.${version.minor}`;
|
|
22
|
-
return { ...status, runs: false, problem: `${found}, and c64-re-tools needs VICE ${MIN_VICE.major}.${MIN_VICE.minor} or later. ${tool.remedy}` };
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
/** The version text of a VICE version, as x64sc -version prints it. */
|
|
26
|
-
const versionText = (version: ViceVersion) => `x64sc (VICE ${version.major}.${version.minor}${version.revision === undefined ? "" : ` SVN r${version.revision}`})`;
|
|
27
|
-
|
|
28
|
-
/** `started`: the version that the host read from the emulator at start; without it, VICE is probed with -version too. */
|
|
29
|
-
export async function hostStatus(context: ToolContext, started?: ViceVersion): Promise<{ result: { host: HostInfo; tools: ToolStatus[] } }> {
|
|
30
|
-
const specs = [VICE, C1541, PETCAT];
|
|
31
|
-
const probed = await probeTools(
|
|
32
|
-
[
|
|
33
|
-
...(started === undefined ? [{ name: VICE.name, find: findVice, args: ["-version"], pattern: /^x64sc \(VICE \d/ }] : []),
|
|
34
|
-
{ name: C1541.name, find: (env) => findTool(C1541, env), args: ["-version"], pattern: /^c1541 \(VICE \d/ },
|
|
35
|
-
{ name: PETCAT.name, find: (env) => findTool(PETCAT, env), args: ["-version"], pattern: /^petcat \(VICE \d/ },
|
|
36
|
-
],
|
|
37
|
-
context,
|
|
38
|
-
);
|
|
39
|
-
const tools = started === undefined ? probed : [{ name: VICE.name, found: true, path: findVice(context.env ?? process.env), version: versionText(started), runs: true }, ...probed];
|
|
40
|
-
const checked = tools.map((status, index) => requireMinimum(status, specs[index]!));
|
|
41
|
-
// VICE runs with its known flaws; status names them.
|
|
42
|
-
const vice = checked[0]!;
|
|
43
|
-
const version = vice.runs ? viceVersionOf(vice.version ?? "") : undefined;
|
|
44
|
-
const flaws = version === undefined ? [] : viceFlaws(version).map((flaw) => flaw.text);
|
|
45
|
-
if (flaws.length > 0) checked[0] = { ...vice, flaws };
|
|
46
|
-
return { result: { host: { version: PACKAGE.version, platform: platform(), release: release(), arch: arch() }, tools: checked } };
|
|
47
|
-
}
|
|
@@ -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
|
-
}
|