feat(ghidra): admit bounded PSP ELF through installed Allegrex (#1599)
* feat(ghidra): admit bounded PSP ELF through installed Allegrex Build on merged generic MIPS without weakening its policy. Bind caller-installed processor files into the analysis profile, check them again before launch, force and verify PSP language selection, retain limitations, and extend the public CLI/MCP verifier with source-owned PSP and target-switching checks. Local actual focused Vitest: 102 passed, one existing permission skip. Hosted static and real-provider results are pending. * fix(ghidra): validate PSPSDK ABI records in PSP admission * test(ghidra): bind PSP ABI verification to snapshot profiles * test(ghidra): declare independent PSP ABI reader contract * test(ghidra): retain the PSP fixture discriminated type * test(ghidra): contextually type PSP metadata as the MIPS target variant * test(ghidra): keep carved firmware checks scoped to generic MIPS fixtures * style(ghidra): format PSP language-override guard * style(test): format PSP language override regressions * fix(ghidra): bound PSP extension enumeration before allocation --------- Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
This commit is contained in:
co-authored by
github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
morluto
parent
0153b4d95b
commit
e4407dbed5
@@ -0,0 +1,506 @@
|
||||
import { mkdir, rename, symlink, truncate, writeFile } from "node:fs/promises";
|
||||
import { dirname, join } from "node:path";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { parseConfig } from "../../../src/config/parseConfig.js";
|
||||
import { silentLogger } from "../../../src/logger.js";
|
||||
import type {
|
||||
BinaryTarget,
|
||||
MipsAbiFlags,
|
||||
} from "../../../src/domain/binaryTargetTypes.js";
|
||||
import { parseBinaryTarget } from "../../../src/application/BinaryTargetResolver.js";
|
||||
import { GhidraProvider } from "../../../src/ghidra/GhidraProvider.js";
|
||||
import { ghidraProcessorUnsupportedReason } from "../../../src/ghidra/GhidraPspProfile.js";
|
||||
import { inspectGhidraPspExtension } from "../../../src/ghidra/GhidraPspExtension.js";
|
||||
import {
|
||||
GhidraHeadlessLauncher,
|
||||
ghidraHeadlessArguments,
|
||||
} from "../../../src/ghidra/GhidraLauncher.js";
|
||||
import type { GhidraInstallationHost } from "../../../src/ghidra/GhidraInstallation.js";
|
||||
|
||||
// Synthetic installation files exercise the filesystem/profile boundary, not
|
||||
// Allegrex execution. Only the optional real CLI/MCP lane proves tool behavior.
|
||||
// Independently inspected with PSPDEV v20261001 / GNU readelf 2.44.
|
||||
const pspAbiFlags: MipsAbiFlags = {
|
||||
version: 0,
|
||||
isaLevel: 2,
|
||||
isaRevision: 0,
|
||||
gprSize: 1,
|
||||
cpr1Size: 1,
|
||||
cpr2Size: 0,
|
||||
fpAbi: 2,
|
||||
isaExtension: 0,
|
||||
ases: 0,
|
||||
flags1: 1,
|
||||
flags2: 0,
|
||||
};
|
||||
const target = {
|
||||
kind: "executable",
|
||||
format: "elf",
|
||||
architecture: "mips",
|
||||
availableArchitectures: ["mips"],
|
||||
path: "/caller/psp.elf",
|
||||
sha256: "a".repeat(64),
|
||||
mips: {
|
||||
elfClass: 32,
|
||||
byteOrder: "little",
|
||||
type: 2,
|
||||
flags: 0x10a23001,
|
||||
abiFlags: pspAbiFlags,
|
||||
},
|
||||
} satisfies BinaryTarget;
|
||||
const host: GhidraInstallationHost = {
|
||||
platform: "linux",
|
||||
architecture: "x64",
|
||||
readText: () => "application.version=12.1.3\n",
|
||||
executable: () => true,
|
||||
probeJava: () => ({
|
||||
version: "21.0.12",
|
||||
major: 21,
|
||||
home: "/jdk-21",
|
||||
bits: 64,
|
||||
runtime: "jdk",
|
||||
}),
|
||||
};
|
||||
async function installation() {
|
||||
const directory = await createTestTempDirectory("rea-psp-profile-");
|
||||
const root = join(directory, "Ghidra", "Extensions", "ghidra-allegrex");
|
||||
const contents = {
|
||||
"Module.manifest": "",
|
||||
"extension.properties": "name=ghidra-allegrex\nversion=12.1.3\n",
|
||||
"data/languages/allegrex.ldefs": "synthetic language definition",
|
||||
"data/languages/allegrex.sla": "synthetic compiled processor",
|
||||
"data/languages/allegrex.pspec": "synthetic processor specification",
|
||||
"data/languages/allegrex.cspec": "synthetic compiler specification",
|
||||
"lib/extension.jar": "synthetic loader artifact",
|
||||
};
|
||||
for (const [path, text] of Object.entries(contents)) {
|
||||
await mkdir(dirname(join(root, path)), { recursive: true });
|
||||
await writeFile(join(root, path), text);
|
||||
}
|
||||
await mkdir(join(directory, "support"));
|
||||
const parsed = parseConfig({ GHIDRA_INSTALL_DIR: directory });
|
||||
if (!parsed.ok) throw parsed.error;
|
||||
return {
|
||||
directory,
|
||||
root,
|
||||
config: parsed.value,
|
||||
provider: new GhidraProvider(parsed.value, silentLogger, {}, host),
|
||||
};
|
||||
}
|
||||
|
||||
describe.skipIf(process.platform === "win32")(
|
||||
"PSP installed-extension and profile boundary",
|
||||
() => {
|
||||
it("binds source interpretation and installed content, not mtimes or discovery order", async () => {
|
||||
const { provider, root } = await installation();
|
||||
expect(provider.inspectTargetSupport(target).status).toBe("supported");
|
||||
const first = await provider.resolveAnalysisProfile(target);
|
||||
if (!first.ok) throw first.error;
|
||||
const again = await provider.resolveAnalysisProfile(target);
|
||||
if (!again.ok) throw again.error;
|
||||
expect(again.value.profile?.digest).toBe(first.value.profile?.digest);
|
||||
expect(first.value.profile?.parameters).toMatchObject({
|
||||
architecture: "mips",
|
||||
language_id: "Allegrex:LE:32:default",
|
||||
compiler_spec_id: "default",
|
||||
loader: "PspElfLoader",
|
||||
mips_support_lane: "psp-elf32-exec-eabi32-allegrex-v2",
|
||||
mips_elf: {
|
||||
elf_class: 32,
|
||||
byte_order: "little",
|
||||
type: 2,
|
||||
flags: 0x10a23001,
|
||||
abi_flags: {
|
||||
version: 0,
|
||||
isa_level: 2,
|
||||
isa_revision: 0,
|
||||
gpr_size: 1,
|
||||
cpr1_size: 1,
|
||||
cpr2_size: 0,
|
||||
fp_abi: 2,
|
||||
isa_extension: 0,
|
||||
ases: 0,
|
||||
flags1: 1,
|
||||
flags2: 0,
|
||||
},
|
||||
},
|
||||
psp_extension: {
|
||||
id: "ghidra-allegrex",
|
||||
root,
|
||||
ghidra_version: "12.1.3",
|
||||
sha256: expect.stringMatching(/^[a-f0-9]{64}$/u),
|
||||
},
|
||||
});
|
||||
await writeFile(
|
||||
join(root, "data/languages/allegrex.sla"),
|
||||
"changed processor semantics",
|
||||
);
|
||||
const changed = await provider.resolveAnalysisProfile(target);
|
||||
if (!changed.ok) throw changed.error;
|
||||
expect(changed.value.profile?.digest).not.toBe(
|
||||
first.value.profile?.digest,
|
||||
);
|
||||
});
|
||||
|
||||
it("fails before starting a provider after resolved extension bytes change", async () => {
|
||||
const { directory, root } = await installation();
|
||||
const extension = await inspectGhidraPspExtension(root, "12.1.3");
|
||||
await writeFile(join(root, "lib/extension.jar"), "changed loader");
|
||||
const spawn = vi.fn();
|
||||
const launcher = new GhidraHeadlessLauncher({
|
||||
environment: {},
|
||||
analyzeHeadlessPath: join(directory, "support/analyzeHeadless"),
|
||||
javaHome: "/jdk-21",
|
||||
bridgeScriptPath: "/packaged/ReaGhidraBridge.java",
|
||||
pspExtension: extension,
|
||||
spawnProcess: spawn,
|
||||
});
|
||||
const launched = await launcher.launch({
|
||||
runtimeRoot: join(directory, "runtime"),
|
||||
transport: "unix-socket",
|
||||
endpointPath: join(directory, "socket"),
|
||||
token: "test-only-token",
|
||||
runId: "00000000-0000-4000-8000-000000000001",
|
||||
targetPath: target.path,
|
||||
targetSha256: target.sha256,
|
||||
providerVersion: "12.1.3",
|
||||
profileDigest: "b".repeat(64),
|
||||
});
|
||||
expect(launched.ok).toBe(false);
|
||||
if (launched.ok)
|
||||
throw new Error("Changed extension reached provider startup");
|
||||
expect(launched.error.cause).toBeInstanceOf(Error);
|
||||
expect(String(launched.error.cause)).toContain(
|
||||
"changed since profile resolution",
|
||||
);
|
||||
expect(spawn).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("requires a fresh extension when a saved profile's installation has disappeared", async () => {
|
||||
const { provider, root } = await installation();
|
||||
const before = await provider.resolveAnalysisProfile(target);
|
||||
if (!before.ok) throw before.error;
|
||||
await rename(root, `${root}-removed`);
|
||||
const missing = await provider.resolveAnalysisProfile(target);
|
||||
expect(missing.ok).toBe(false);
|
||||
if (missing.ok) throw new Error("Missing installation was accepted");
|
||||
expect(missing.error.message).toContain("PSP_EXTENSION_UNAVAILABLE");
|
||||
});
|
||||
|
||||
it.each([
|
||||
["name=other\nversion=12.1.3\n", "does not match"],
|
||||
["name=ghidra-allegrex\nversion=12.1.4\n", "does not match"],
|
||||
[
|
||||
"name=ghidra-allegrex\nversion=12.1.3\nversion=12.1.3\n",
|
||||
"exactly one version",
|
||||
],
|
||||
])(
|
||||
"rejects incompatible or ambiguous extension metadata %s",
|
||||
async (properties, reason) => {
|
||||
const { root } = await installation();
|
||||
await writeFile(join(root, "extension.properties"), properties);
|
||||
await expect(inspectGhidraPspExtension(root, "12.1.3")).rejects.toThrow(
|
||||
reason,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it("does not treat an uninstall marker or missing compiled language as installed", async () => {
|
||||
const { root } = await installation();
|
||||
await rename(
|
||||
join(root, "Module.manifest"),
|
||||
join(root, "Module.manifest.uninstalled"),
|
||||
);
|
||||
await expect(inspectGhidraPspExtension(root, "12.1.3")).rejects.toThrow(
|
||||
"Module.manifest",
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects symlinked code instead of hashing an untracked external producer", async () => {
|
||||
const { root, directory } = await installation();
|
||||
const path = join(root, "lib/extension.jar");
|
||||
await rename(path, join(directory, "external.jar"));
|
||||
await symlink(join(directory, "external.jar"), path);
|
||||
await expect(inspectGhidraPspExtension(root, "12.1.3")).rejects.toThrow(
|
||||
"regular files",
|
||||
);
|
||||
});
|
||||
|
||||
it("bounds sparse extension input before reading or allocating its declared extent", async () => {
|
||||
const { root } = await installation();
|
||||
await truncate(join(root, "lib/extension.jar"), 64 * 1024 * 1024 + 1);
|
||||
await expect(inspectGhidraPspExtension(root, "12.1.3")).rejects.toThrow(
|
||||
"inspection limit",
|
||||
);
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
describe.skipIf(process.platform === "win32")(
|
||||
"PSP extension inventory bounds",
|
||||
() => {
|
||||
it.each([1, 2])(
|
||||
"bounds the total inventory across %i directories",
|
||||
async (directories) => {
|
||||
const { root } = await installation();
|
||||
for (let directory = 0; directory < directories; directory++) {
|
||||
const path = join(root, `inventory-${directory}`);
|
||||
await mkdir(path);
|
||||
await Promise.all(
|
||||
Array.from({ length: 1024 / directories }, (_, index) =>
|
||||
writeFile(join(path, `entry-${index}`), ""),
|
||||
),
|
||||
);
|
||||
}
|
||||
await expect(inspectGhidraPspExtension(root, "12.1.3")).rejects.toThrow(
|
||||
"inventory exceeds the inspection limit",
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
describe.skipIf(process.platform === "win32")(
|
||||
"PSP admission failures and explicit loader",
|
||||
() => {
|
||||
it("preserves already-aborted cancellation rather than reporting missing prerequisites", async () => {
|
||||
const { provider } = await installation();
|
||||
const result = await provider.resolveAnalysisProfile(target, {
|
||||
signal: AbortSignal.abort(),
|
||||
});
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) throw new Error("Cancellation was ignored");
|
||||
expect(result.error._tag).toBe("AnalysisCancelledError");
|
||||
});
|
||||
|
||||
it("does not broaden the separately verified host platforms", async () => {
|
||||
const { config } = await installation();
|
||||
for (const platform of ["darwin", "win32"] as const) {
|
||||
const provider = new GhidraProvider(
|
||||
config,
|
||||
silentLogger,
|
||||
{},
|
||||
{ ...host, platform },
|
||||
);
|
||||
expect(provider.inspectTargetSupport(target).status).toBe(
|
||||
"unsupported",
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
[{ byteOrder: "big" }, "little-endian"],
|
||||
[{ elfClass: 64 }, "ELF32"],
|
||||
[{ type: 0xffa0 }, "ET_EXEC"],
|
||||
[{ flags: 0x12a23001 }, "0x10a23001"],
|
||||
[{ flags: 0x10a23021 }, "0x10a23001"],
|
||||
])(
|
||||
"refuses unverified PSP declarations %j before extension reads",
|
||||
async (change, reason) => {
|
||||
const { provider } = await installation();
|
||||
const altered = {
|
||||
...target,
|
||||
mips: { ...target.mips, ...change },
|
||||
} as BinaryTarget;
|
||||
expect(ghidraProcessorUnsupportedReason(altered)).toContain(reason);
|
||||
expect(provider.inspectTargetSupport(altered).status).toBe(
|
||||
"unsupported",
|
||||
);
|
||||
const result = await provider.resolveAnalysisProfile(altered);
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) throw new Error("Invalid target was admitted");
|
||||
expect(result.error._tag).toBe("AnalysisUnsupportedTargetError");
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
describe.skipIf(process.platform === "win32")(
|
||||
"PSP inspected ABI declaration boundary",
|
||||
() => {
|
||||
it("retains independently inspected PSP ABI bytes through the real target reader", async () => {
|
||||
const { directory, provider } = await installation();
|
||||
const abiOffset = 8192;
|
||||
const bytes = Buffer.alloc(abiOffset + 24);
|
||||
bytes.set([0x7f, 0x45, 0x4c, 0x46, 1, 1, 1]);
|
||||
bytes.writeUInt16LE(2, 16);
|
||||
bytes.writeUInt16LE(8, 18);
|
||||
bytes.writeUInt32LE(1, 20);
|
||||
bytes.writeUInt32LE(52, 28);
|
||||
bytes.writeUInt32LE(0x10a23001, 36);
|
||||
bytes.writeUInt16LE(52, 40);
|
||||
bytes.writeUInt16LE(32, 42);
|
||||
bytes.writeUInt16LE(1, 44);
|
||||
bytes.writeUInt32LE(0x70000003, 52);
|
||||
bytes.writeUInt32LE(abiOffset, 56);
|
||||
bytes.writeUInt32LE(24, 68);
|
||||
bytes.writeUInt32LE(24, 72);
|
||||
// GNU readelf -x .MIPS.abiflags, not bytes generated by REA.
|
||||
bytes.set(
|
||||
Buffer.from("000002000101000200000000000000000100000000000000", "hex"),
|
||||
abiOffset,
|
||||
);
|
||||
const path = join(directory, "psp-with-abi.elf");
|
||||
await writeFile(path, bytes);
|
||||
const parsed = await parseBinaryTarget(path);
|
||||
if (!parsed.ok) throw parsed.error;
|
||||
if (
|
||||
parsed.value.kind !== "executable" ||
|
||||
parsed.value.architecture !== "mips"
|
||||
)
|
||||
throw new Error("PSP ELF was not recognized as MIPS");
|
||||
expect(parsed.value.mips.abiFlags).toEqual(pspAbiFlags);
|
||||
expect(provider.inspectTargetSupport(parsed.value).status).toBe(
|
||||
"supported",
|
||||
);
|
||||
const profile = await provider.resolveAnalysisProfile(parsed.value);
|
||||
if (!profile.ok) throw profile.error;
|
||||
expect(profile.value.profile?.parameters.mips_elf).toMatchObject({
|
||||
flags: 0x10a23001,
|
||||
abi_flags: { isa_level: 2, fp_abi: 2, flags1: 1 },
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
["version", 1],
|
||||
["isaLevel", 32],
|
||||
["isaRevision", 1],
|
||||
["gprSize", 2],
|
||||
["cpr1Size", 2],
|
||||
["cpr2Size", 1],
|
||||
["fpAbi", 1],
|
||||
["fpAbi", 3],
|
||||
["fpAbi", 5],
|
||||
["isaExtension", 1],
|
||||
["ases", 1],
|
||||
["flags1", 0],
|
||||
["flags1", 3],
|
||||
["flags2", 1],
|
||||
] satisfies [keyof MipsAbiFlags, number][])(
|
||||
"rejects unverified PSP ABI field %s=%i before extension discovery",
|
||||
async (field, value) => {
|
||||
const { provider, root } = await installation();
|
||||
await rename(root, `${root}-unavailable`);
|
||||
const altered: Extract<BinaryTarget, { architecture: "mips" }> = {
|
||||
...target,
|
||||
mips: {
|
||||
elfClass: 32,
|
||||
byteOrder: "little",
|
||||
type: 2,
|
||||
flags: 0x10a23001,
|
||||
abiFlags: { ...pspAbiFlags, [field]: value },
|
||||
},
|
||||
};
|
||||
expect(provider.inspectTargetSupport(altered).status).toBe(
|
||||
"unsupported",
|
||||
);
|
||||
const result = await provider.resolveAnalysisProfile(altered);
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) throw new Error("Invalid ABI was admitted");
|
||||
expect(result.error._tag).toBe("AnalysisUnsupportedTargetError");
|
||||
expect(result.error.message).toContain(
|
||||
"separate MIPS ABI flags record",
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it.each([undefined, null])(
|
||||
"does not guess an uninspected or absent PSP ABI record: %s",
|
||||
async (abiFlags) => {
|
||||
const { provider, root } = await installation();
|
||||
await rename(root, `${root}-unavailable`);
|
||||
const altered: Extract<BinaryTarget, { architecture: "mips" }> = {
|
||||
...target,
|
||||
mips: {
|
||||
elfClass: 32,
|
||||
byteOrder: "little",
|
||||
type: 2,
|
||||
flags: 0x10a23001,
|
||||
...(abiFlags === undefined ? {} : { abiFlags }),
|
||||
},
|
||||
};
|
||||
const result = await provider.resolveAnalysisProfile(altered);
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) throw new Error("Missing ABI was inferred");
|
||||
expect(result.error._tag).toBe("AnalysisUnsupportedTargetError");
|
||||
expect(result.error.message).toContain(
|
||||
"inspected separate MIPS ABI flags record",
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
describe.skipIf(process.platform === "win32")(
|
||||
"PSP explicit loader boundary",
|
||||
() => {
|
||||
it("rejects mixing the PSP loader with a configured generic processor", async () => {
|
||||
const { directory } = await installation();
|
||||
const config = parseConfig({
|
||||
GHIDRA_INSTALL_DIR: directory,
|
||||
REA_GHIDRA_LANGUAGE_ID: "x86:LE:64:default",
|
||||
});
|
||||
if (!config.ok) throw config.error;
|
||||
const provider = new GhidraProvider(config.value, silentLogger, {}, host);
|
||||
const result = await provider.resolveAnalysisProfile(target);
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok)
|
||||
throw new Error("Conflicting language override was accepted");
|
||||
expect(result.error._tag).toBe("AnalysisUnsupportedTargetError");
|
||||
expect(result.error.message).toContain(
|
||||
"does not accept REA_GHIDRA_LANGUAGE_ID overrides",
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps PSP and generic language-override launch paths mutually exclusive", () => {
|
||||
const paths = {
|
||||
projectRoot: "/project",
|
||||
targetPath: "/target.elf",
|
||||
bridgeScriptPath: "/bridge/Rea.java",
|
||||
descriptorPath: "/session",
|
||||
ghidraLogPath: "/log",
|
||||
scriptLogPath: "/scriptlog",
|
||||
};
|
||||
const languageOverride = { languageId: "x86:LE:64:default" };
|
||||
expect(() =>
|
||||
ghidraHeadlessArguments({ ...paths, psp: true, languageOverride }),
|
||||
).toThrow("PSP ELF import cannot be combined");
|
||||
expect(ghidraHeadlessArguments({ ...paths, languageOverride })).toEqual(
|
||||
expect.arrayContaining(["-processor", "x86:LE:64:default"]),
|
||||
);
|
||||
expect(ghidraHeadlessArguments({ ...paths, psp: true })).toEqual(
|
||||
expect.arrayContaining([
|
||||
"-loader",
|
||||
"PspElfLoader",
|
||||
"-processor",
|
||||
"Allegrex:LE:32:default",
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it("forces the PSP loader/language only for the selected profile", () => {
|
||||
const paths = {
|
||||
projectRoot: "/project",
|
||||
targetPath: "/target.elf",
|
||||
bridgeScriptPath: "/bridge/Rea.java",
|
||||
descriptorPath: "/session",
|
||||
ghidraLogPath: "/log",
|
||||
scriptLogPath: "/scriptlog",
|
||||
};
|
||||
expect(ghidraHeadlessArguments({ ...paths, psp: true })).toEqual(
|
||||
expect.arrayContaining([
|
||||
"-loader",
|
||||
"PspElfLoader",
|
||||
"-processor",
|
||||
"Allegrex:LE:32:default",
|
||||
"-cspec",
|
||||
"default",
|
||||
]),
|
||||
);
|
||||
expect(ghidraHeadlessArguments(paths)).not.toContain(
|
||||
"Allegrex:LE:32:default",
|
||||
);
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,51 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { it } from "vitest";
|
||||
import { parsePspReadelfAbi } from "./psp-fixture.mjs";
|
||||
|
||||
// GNU readelf 2.44 output from the maintained PSPDEV v20261001 fixture.
|
||||
const observed = `MIPS ABI Flags Version: 0
|
||||
ISA: MIPS2
|
||||
GPR size: 32
|
||||
CPR1 size: 32
|
||||
CPR2 size: 0
|
||||
FP ABI: Hard float (single precision)
|
||||
ISA Extension: None
|
||||
ASEs:
|
||||
None
|
||||
FLAGS 1: 00000001
|
||||
FLAGS 2: 00000000
|
||||
`;
|
||||
|
||||
it("reads the independent PSP producer's single-float declaration", () => {
|
||||
assert.deepEqual(parsePspReadelfAbi(observed), {
|
||||
version: 0,
|
||||
isaLevel: 2,
|
||||
isaRevision: 0,
|
||||
gprSize: 1,
|
||||
cpr1Size: 1,
|
||||
cpr2Size: 0,
|
||||
fpAbi: 2,
|
||||
isaExtension: 0,
|
||||
ases: 0,
|
||||
flags1: 1,
|
||||
flags2: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
["ISA: MIPS2", "ISA: MIPS32r2"],
|
||||
["GPR size: 32", "GPR size: 64"],
|
||||
["Hard float (single precision)", "Hard float (double precision)"],
|
||||
["FLAGS 1: 00000001", "FLAGS 1: 00000003"],
|
||||
["FLAGS 2: 00000000", "FLAGS 2: 00000001"],
|
||||
["MIPS ABI Flags Version: 0", "MIPS ABI Flags Version: 1"],
|
||||
["CPR1 size: 32", "CPR1 size: 0"],
|
||||
["ISA Extension: None", "ISA Extension: R5900"],
|
||||
["GPR size: 32", "GPR size: 32\nGPR size: 32"],
|
||||
["FLAGS 1: 00000001", ""],
|
||||
])(
|
||||
"rejects unsupported or ambiguous independent ABI output: %s",
|
||||
(before, after) => {
|
||||
assert.throws(() => parsePspReadelfAbi(observed.replace(before, after)));
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,3 @@
|
||||
import type { MipsAbiFlags } from "../../../src/domain/binaryTargetTypes.js";
|
||||
|
||||
export declare function parsePspReadelfAbi(text: string): MipsAbiFlags;
|
||||
@@ -0,0 +1,212 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { execFile } from "node:child_process";
|
||||
import { createHash } from "node:crypto";
|
||||
import { copyFile, readFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
const execute = promisify(execFile);
|
||||
const sha256 = (bytes) => createHash("sha256").update(bytes).digest("hex");
|
||||
|
||||
/** Build the maintained, non-PRX PSPSDK fixture, without executing the target. */
|
||||
export async function buildPspFixture(directory, globalValue = 7) {
|
||||
assert.ok(globalValue === 7 || globalValue === 11);
|
||||
const options = {
|
||||
cwd: directory,
|
||||
env: { ...process.env, LC_ALL: "C", LANG: "C" },
|
||||
timeout: 10000,
|
||||
maxBuffer: 1024 * 1024,
|
||||
};
|
||||
const versions = {};
|
||||
for (const command of ["make", "psp-gcc", "psp-readelf", "psp-objdump"])
|
||||
versions[command] = (
|
||||
await execute(command, ["--version"], options)
|
||||
).stdout.trim();
|
||||
const sourceDigests = {};
|
||||
for (const name of ["main.c", "probe.S", "Makefile"]) {
|
||||
const source = new URL(`../psp/${name}`, import.meta.url);
|
||||
sourceDigests[name] = sha256(await readFile(source));
|
||||
await copyFile(source, join(directory, name));
|
||||
}
|
||||
const build = await execute(
|
||||
"make",
|
||||
[`REA_PSP_GLOBAL=${globalValue}`, "rea_psp_fixture.elf"],
|
||||
{ ...options, timeout: 60000 },
|
||||
);
|
||||
const path = join(directory, "rea_psp_fixture.elf");
|
||||
const bytes = await readFile(path);
|
||||
assert.ok(bytes.length >= 52);
|
||||
assert.equal(bytes.toString("hex", 0, 6), "7f454c460101");
|
||||
assert.equal(bytes.readUInt16LE(16), 2);
|
||||
assert.equal(bytes.readUInt16LE(18), 8);
|
||||
assert.equal(bytes.readUInt32LE(36), 0x10a23001);
|
||||
const readelf = await execute(
|
||||
"psp-readelf",
|
||||
["-h", "-A", "-sW", path],
|
||||
options,
|
||||
);
|
||||
assert.equal(readelf.stderr.trim(), "");
|
||||
assert.match(readelf.stdout, /Class:\s+ELF32/u);
|
||||
assert.match(readelf.stdout, /Data:\s+2's complement, little endian/u);
|
||||
assert.match(readelf.stdout, /Type:\s+EXEC\b/u);
|
||||
assert.match(readelf.stdout, /Flags:\s+0x10a23001\b/u);
|
||||
const abiFlags = parsePspReadelfAbi(readelf.stdout);
|
||||
const abiDump = await execute(
|
||||
"psp-readelf",
|
||||
["-x", ".MIPS.abiflags", path],
|
||||
options,
|
||||
);
|
||||
assert.equal(abiDump.stderr.trim(), "");
|
||||
const abiWords = abiDump.stdout
|
||||
.split("\n")
|
||||
.filter((line) => /^\s*0x[0-9a-f]+\s/u.test(line))
|
||||
.flatMap((line) => line.match(/\b[0-9a-f]{8}\b/gu) ?? []);
|
||||
assert.equal(
|
||||
abiWords.join(""),
|
||||
"000002000101000200000000000000000100000000000000",
|
||||
"PSPSDK ABI bytes differ from independently inspected build intent",
|
||||
);
|
||||
const symbols = {};
|
||||
for (const [name, type] of [
|
||||
["rea_psp_entry", "FUNC"],
|
||||
["rea_psp_leaf", "FUNC"],
|
||||
["rea_psp_probe", "FUNC"],
|
||||
["rea_psp_global", "OBJECT"],
|
||||
["rea_psp_marker", "OBJECT"],
|
||||
]) {
|
||||
const rows = readelf.stdout
|
||||
.split("\n")
|
||||
.map((line) => line.trim().split(/\s+/u))
|
||||
.filter((row) => row.length === 8 && row[7] === name);
|
||||
assert.equal(rows.length, 1, `Expected one defined PSP symbol: ${name}`);
|
||||
const row = rows[0];
|
||||
assert.match(row[1], /^[0-9a-fA-F]{8}$/u);
|
||||
assert.equal(row[3], type);
|
||||
assert.equal(row[4], "GLOBAL");
|
||||
assert.match(row[6], /^\d+$/u);
|
||||
symbols[name] = `0x${Number.parseInt(row[1], 16).toString(16)}`;
|
||||
}
|
||||
const objdump = await execute(
|
||||
"psp-objdump",
|
||||
["-d", "--disassemble=rea_psp_probe", path],
|
||||
options,
|
||||
);
|
||||
assert.equal(objdump.stderr.trim(), "");
|
||||
assert.match(objdump.stdout, /\bbitrev\b/u);
|
||||
return {
|
||||
path,
|
||||
sha256: sha256(bytes),
|
||||
source_sha256: sourceDigests,
|
||||
symbols,
|
||||
flags: "0x10a23001",
|
||||
mips: {
|
||||
elfClass: 32,
|
||||
byteOrder: "little",
|
||||
type: 2,
|
||||
flags: 0x10a23001,
|
||||
abiFlags,
|
||||
},
|
||||
abi_record_hex_dump: abiDump.stdout,
|
||||
global_value: globalValue,
|
||||
versions,
|
||||
readelf: readelf.stdout,
|
||||
objdump: objdump.stdout,
|
||||
build_stderr: build.stderr,
|
||||
};
|
||||
}
|
||||
|
||||
/** Independent GNU fields for the pinned PSPSDK fixture, not REA's parser. */
|
||||
export function parsePspReadelfAbi(text) {
|
||||
const field = (expression, label) => {
|
||||
const matches = [...text.matchAll(expression)];
|
||||
assert.equal(
|
||||
matches.length,
|
||||
1,
|
||||
`Missing or ambiguous PSP readelf ${label}`,
|
||||
);
|
||||
return matches[0][1].trim();
|
||||
};
|
||||
const width = (name) => {
|
||||
const bits = Number(
|
||||
field(new RegExp(`^${name} size:\\s*(\\d+)\\s*$`, "gmu"), name),
|
||||
);
|
||||
assert.ok(bits === 0 || bits === 32, `Unverified PSP ${name} width`);
|
||||
return bits === 32 ? 1 : 0;
|
||||
};
|
||||
const isaLevel = Number(field(/^ISA:\s*MIPS(\d+)\s*$/gmu, "ISA"));
|
||||
assert.equal(
|
||||
field(/^FP ABI:\s*(.+)$/gmu, "FP ABI"),
|
||||
"Hard float (single precision)",
|
||||
);
|
||||
assert.equal(field(/^ISA Extension:\s*(.+)$/gmu, "ISA extension"), "None");
|
||||
assert.equal(field(/^ASEs:\s*\n[ \t]*(.+)$/gmu, "ASEs"), "None");
|
||||
const abi = {
|
||||
version: Number(
|
||||
field(/^MIPS ABI Flags Version:\s*(\d+)\s*$/gmu, "ABI version"),
|
||||
),
|
||||
isaLevel,
|
||||
isaRevision: 0,
|
||||
gprSize: width("GPR"),
|
||||
cpr1Size: width("CPR1"),
|
||||
cpr2Size: width("CPR2"),
|
||||
fpAbi: 2,
|
||||
isaExtension: 0,
|
||||
ases: 0,
|
||||
flags1: Number.parseInt(
|
||||
field(/^FLAGS 1:\s*([\da-f]+)\s*$/gmu, "flags1"),
|
||||
16,
|
||||
),
|
||||
flags2: Number.parseInt(
|
||||
field(/^FLAGS 2:\s*([\da-f]+)\s*$/gmu, "flags2"),
|
||||
16,
|
||||
),
|
||||
};
|
||||
assert.deepEqual(
|
||||
abi,
|
||||
{
|
||||
version: 0,
|
||||
isaLevel: 2,
|
||||
isaRevision: 0,
|
||||
gprSize: 1,
|
||||
cpr1Size: 1,
|
||||
cpr2Size: 0,
|
||||
fpAbi: 2,
|
||||
isaExtension: 0,
|
||||
ases: 0,
|
||||
flags1: 1,
|
||||
flags2: 0,
|
||||
},
|
||||
"PSPSDK ABI declaration differs from independently inspected build intent",
|
||||
);
|
||||
return abi;
|
||||
}
|
||||
|
||||
/** Observations from Ghidra, not an echo of the requested profile. */
|
||||
export function assertPspLoadedImage(image, targetSha256) {
|
||||
assert.equal(image.executable_format, "PSP Executable (ELF)");
|
||||
assert.equal(image.language_id, "Allegrex:LE:32:default");
|
||||
assert.equal(image.compiler_spec_id, "default");
|
||||
assert.equal(image.source_files.length, 1);
|
||||
assert.equal(image.source_files[0].original_sha256, targetSha256);
|
||||
assert.equal(image.source_files[0].modified_sha256, targetSha256);
|
||||
}
|
||||
|
||||
/** Fixed source encodings and independently chosen immediate, not pseudocode. */
|
||||
export function assertPspProbe(move, bitrev) {
|
||||
assert.equal(move.status, "decoded");
|
||||
assert.equal(move.length, 4);
|
||||
assert.equal(move.bytes, "34120224");
|
||||
assert.ok(
|
||||
move.operands.some((operand) =>
|
||||
operand.components.some(
|
||||
(part) =>
|
||||
part.kind === "immediate" &&
|
||||
part.value !== null &&
|
||||
BigInt(part.value) === 0x1234n,
|
||||
),
|
||||
),
|
||||
);
|
||||
assert.equal(bitrev.status, "decoded");
|
||||
assert.equal(bitrev.length, 4);
|
||||
assert.match(bitrev.mnemonic, /^bitrev$/iu);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
TARGET = rea_psp_fixture
|
||||
OBJS = main.o probe.o
|
||||
BUILD_PRX = 0
|
||||
REA_PSP_GLOBAL ?= 7
|
||||
CFLAGS = -O0 -g -G0 -fno-inline -fno-builtin -DREA_PSP_GLOBAL=$(REA_PSP_GLOBAL)
|
||||
ASFLAGS = -g
|
||||
PSPSDK := $(shell psp-config --pspsdk-path)
|
||||
include $(PSPSDK)/lib/build.mak
|
||||
@@ -0,0 +1,20 @@
|
||||
#include <pspkernel.h>
|
||||
|
||||
PSP_MODULE_INFO("rea_psp_fixture", 0, 1, 0);
|
||||
#ifndef REA_PSP_GLOBAL
|
||||
#define REA_PSP_GLOBAL 7
|
||||
#endif
|
||||
volatile unsigned int rea_psp_global = REA_PSP_GLOBAL;
|
||||
const char rea_psp_marker[] = "rea-psp-source-owned-fixture";
|
||||
unsigned int rea_psp_probe(void);
|
||||
|
||||
__attribute__((noinline)) unsigned int rea_psp_leaf(unsigned int value) {
|
||||
return value * 3u + rea_psp_global;
|
||||
}
|
||||
__attribute__((noinline)) unsigned int rea_psp_entry(unsigned int selector) {
|
||||
unsigned int adjusted = selector > 10u ? selector : selector + 1u;
|
||||
return rea_psp_leaf(adjusted) + rea_psp_probe();
|
||||
}
|
||||
int main(void) {
|
||||
return (int)rea_psp_entry(11u);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
/* Source-owned Allegrex decoding probe. This fixture is never executed. */
|
||||
.set noreorder
|
||||
.text
|
||||
.align 2
|
||||
.globl rea_psp_probe
|
||||
.type rea_psp_probe, @function
|
||||
.ent rea_psp_probe
|
||||
rea_psp_probe:
|
||||
addiu $v0, $zero, 0x1234
|
||||
bitrev $v0, $v0
|
||||
jr $ra
|
||||
nop
|
||||
.end rea_psp_probe
|
||||
.size rea_psp_probe, .-rea_psp_probe
|
||||
Reference in New Issue
Block a user