feat(ghidra): admit 32-bit big-endian PowerPC ELF (#1747)

* feat(ghidra): admit 32-bit big-endian PowerPC ELF

Recognize EM_PPC as a provider-neutral `powerpc` family that keeps its ELF
class, byte order, type and flags, and admit ELF32 big-endian ET_EXEC through
a bounded Ghidra lane. ELF64, little-endian, relocatable/shared objects and
EF_PPC_EMB are refused with a specific reason; Hopper and IDA do not gain
PowerPC support, and Windows Ghidra P0 is unchanged.

Ghidra's ELF loader selects PowerPC:BE:32:e500:default for a plain EM_PPC
header, which misreads 750-family code. The lane binds
PowerPC:BE:32:default/default in the profile (language_selection
"admitted-lane-v1"), imports with it and checks the reported language. A
language set through REA_GHIDRA_LANGUAGE_ID still replaces the lane default.

Add a source-owned fixture, fixed-encoding probe, GNU readelf cross-check and
the optional `verify:ghidra:ppc` real-provider lane, plus docs/ghidra-ppc.md.

Refs #1741

* style(ghidra): format shared PowerPC profile integration

* fix(ghidra): preserve caller-selected PowerPC languages

---------

Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
This commit is contained in:
Ariel Fikru Avicenna
2026-10-14 06:35:55 +08:00
committed by GitHub
co-authored by morluto
parent 7e9fb6f1bb
commit c86b09a109
22 changed files with 1258 additions and 4 deletions
+58
View File
@@ -0,0 +1,58 @@
import { describe, expect, it } from "vitest";
import { parseExecutableHeader } from "./binaryTarget.js";
const header = (little: boolean, bits: 32 | 64 = 32, machine = 20): Buffer => {
const bytes = Buffer.alloc(bits === 32 ? 52 : 64);
bytes.set([0x7f, 0x45, 0x4c, 0x46, bits === 32 ? 1 : 2, little ? 1 : 2, 1]);
if (little) {
bytes.writeUInt16LE(2, 16);
bytes.writeUInt16LE(machine, 18);
bytes.writeUInt32LE(1, 20);
bytes.writeUInt16LE(bytes.length, bits === 32 ? 40 : 52);
} else {
bytes.writeUInt16BE(2, 16);
bytes.writeUInt16BE(machine, 18);
bytes.writeUInt32BE(1, 20);
bytes.writeUInt16BE(bytes.length, bits === 32 ? 40 : 52);
}
return bytes;
};
describe("PowerPC ELF header boundaries", () => {
it.each([false, true])(
"retains source endian and flags (little=%s)",
(little) => {
const parsed = parseExecutableHeader(header(little), "x64");
if (!parsed.ok) throw new Error(parsed.error);
expect(parsed.value).toEqual({
format: "elf",
architecture: "powerpc",
availableArchitectures: ["powerpc"],
powerpc: {
elfClass: 32,
byteOrder: little ? "little" : "big",
type: 2,
flags: 0,
},
});
},
);
it("reads ELF64 flags at their own offset without claiming support", () => {
const bytes = header(false, 64);
bytes.writeUInt32BE(0x80000000, 48);
const parsed = parseExecutableHeader(bytes, "x64");
if (!parsed.ok) throw new Error(parsed.error);
expect(parsed.value).toMatchObject({
architecture: "powerpc",
powerpc: { elfClass: 64, byteOrder: "big", flags: 0x80000000 },
});
});
it("does not recognize EM_PPC64 as the 32-bit family", () => {
expect(parseExecutableHeader(header(false, 64, 21), "x64")).toEqual({
ok: false,
error: "unsupported ELF architecture",
});
});
});
+21 -1
View File
@@ -5,6 +5,7 @@ import type {
MipsElfMetadata,
PeCodeViewRecord,
RiscvElfMetadata,
PowerPcElfMetadata,
UniversalMachOSlice,
} from "./binaryTargetTypes.js";
import { err, ok, type Result } from "./result.js";
@@ -30,6 +31,12 @@ export type ExecutableMetadata =
readonly availableArchitectures: readonly "riscv"[];
readonly riscv: RiscvElfMetadata;
}
| {
readonly format: "elf";
readonly architecture: "powerpc";
readonly availableArchitectures: readonly "powerpc"[];
readonly powerpc: PowerPcElfMetadata;
}
| {
readonly format: "mach-o" | "elf" | "dos-mz" | "dos-com";
readonly architecture: HeaderArchitecture;
@@ -201,7 +208,11 @@ const parseElf = (
const machine = little ? bytes.readUInt16LE(18) : bytes.readUInt16BE(18);
const architecture = elfArchitecture(machine);
if (architecture === undefined) return err("unsupported ELF architecture");
if (architecture === "mips" || architecture === "riscv") {
if (
architecture === "mips" ||
architecture === "riscv" ||
architecture === "powerpc"
) {
const flagsOffset = elfClass === 32 ? 36 : 48;
const metadata: ElfFamilyMetadata = {
elfClass,
@@ -211,6 +222,13 @@ const parseElf = (
? bytes.readUInt32LE(flagsOffset)
: bytes.readUInt32BE(flagsOffset),
};
if (architecture === "powerpc")
return ok({
format: "elf",
architecture,
availableArchitectures: [architecture],
powerpc: metadata,
});
return architecture === "mips"
? ok({
format: "elf",
@@ -532,6 +550,8 @@ const elfArchitecture = (
return "x86_64";
case 8: // EM_MIPS: ISA, ABI and byte order remain separate ELF facts.
return "mips";
case 20: // EM_PPC; byte order and processor variant remain ELF declarations.
return "powerpc";
case 40:
return "arm";
case 183:
+14
View File
@@ -9,6 +9,7 @@ export const BINARY_ARCHITECTURES = [
"mips",
"6502",
"riscv",
"powerpc",
] as const;
export type BinaryArchitecture = (typeof BINARY_ARCHITECTURES)[number];
@@ -36,6 +37,7 @@ export interface PeCodeViewRecord {
export const ELF_METADATA_ARCHITECTURES = [
"mips",
"riscv",
"powerpc",
] as const satisfies readonly BinaryArchitecture[];
export type ElfMetadataArchitecture =
(typeof ELF_METADATA_ARCHITECTURES)[number];
@@ -90,6 +92,9 @@ export interface MipsAbiFlags {
*/
export type RiscvElfMetadata = ElfFamilyMetadata;
/** Raw PowerPC declarations; family identity does not select a processor variant. */
export type PowerPcElfMetadata = ElfFamilyMetadata;
/** Byte range of the selected slice inside its universal Mach-O container. */
export interface UniversalMachOSlice {
readonly offset: number;
@@ -140,6 +145,15 @@ export type BinaryTarget =
readonly executableRole?: never;
readonly managed?: never;
})
| (BinaryTargetIdentity & {
readonly kind: "executable";
readonly format: "elf";
readonly architecture: "powerpc";
readonly availableArchitectures: readonly "powerpc"[];
readonly powerpc: PowerPcElfMetadata;
readonly executableRole?: never;
readonly managed?: never;
})
| (ExecutableTarget & {
readonly format: "mach-o" | "elf" | "dos-mz" | "dos-com";
readonly universalSlice?: never;
+9 -1
View File
@@ -21,6 +21,10 @@ import {
ghidraRiscvLanguageOverride,
ghidraRiscvProfileParameters,
} from "./GhidraRiscvProfile.js";
import {
ghidraPowerPcLanguage,
ghidraPowerPcProfileParameters,
} from "./GhidraPowerPcProfile.js";
import { ghidraRawBinaryLanguage } from "./GhidraRawBinaryLanguage.js";
import {
@@ -44,7 +48,9 @@ import {
export const ghidraPinnedLanguage = (
target: BinaryTarget,
): GhidraLanguageOverride | undefined =>
ghidraMipsLanguageOverride(target) ?? ghidraRiscvLanguageOverride(target);
ghidraMipsLanguageOverride(target) ??
ghidraRiscvLanguageOverride(target) ??
ghidraPowerPcLanguage(target);
/** Resolve version-bound, deterministic semantics before Ghidra imports a target. */
export const resolveGhidraAnalysisProfile = async (
@@ -155,6 +161,7 @@ export const resolveGhidraAnalysisProfile = async (
const pinnedLanguage = ghidraPinnedLanguage(target);
if (
pinnedLanguage !== undefined &&
target.architecture !== "powerpc" &&
languageOverride !== undefined &&
(languageOverride.languageId !== pinnedLanguage.languageId ||
(languageOverride.compilerSpecId !== undefined &&
@@ -277,6 +284,7 @@ export const resolveGhidraAnalysisProfile = async (
...analyzerParameters,
...ghidraMipsProfileParameters(target, languageOverride),
...ghidraRiscvProfileParameters(target),
...ghidraPowerPcProfileParameters(target),
...(pspExtension?.ok === true
? {
mips_support_lane: "psp-elf32-exec-eabi32-allegrex-v2",
+166
View File
@@ -0,0 +1,166 @@
import { mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js";
import { parseConfig } from "../config/parseConfig.js";
import type {
BinaryTarget,
PowerPcElfMetadata,
} from "../domain/binaryTargetTypes.js";
import { silentLogger } from "../logger.js";
import { HopperProvider } from "../hopper/HopperProvider.js";
import { hopperLoaderArgsForTarget } from "../hopper/HopperAnalysisProfile.js";
import { IdaProvider } from "../ida/IdaProvider.js";
import {
ghidraPinnedLanguage,
ghidraProfileLanguageOverride,
} from "./GhidraAnalysisProfile.js";
import { GhidraProvider } from "./GhidraProvider.js";
import type { GhidraInstallationHost } from "./GhidraInstallation.js";
// Abbreviated from Ghidra 12.1.4 Processors/PowerPC/data/languages/ppc.ldefs.
const PPC_LDEFS = `<?xml version="1.0" encoding="UTF-8"?>
<language_definitions>
<language processor="PowerPC" endian="big" size="32" variant="default"
id="PowerPC:BE:32:default">
<compiler name="default" spec="ppc_32.cspec" id="default"/>
</language>
<language processor="PowerPC" endian="big" size="32" variant="e500"
id="PowerPC:BE:32:e500">
<compiler name="default" spec="ppc_32_e500_be.cspec" id="default"/>
</language>
</language_definitions>
`;
// Fake installation inspection tests admission/profile contracts, not Ghidra.
const host: GhidraInstallationHost = {
platform: "linux",
architecture: "x64",
readText: () => "application.version=12.1.4\n",
executable: () => true,
probeJava: () => ({
version: "21.0.11",
major: 21,
home: "/jdk-21",
bits: 64,
runtime: "jdk",
}),
};
const configFor = (environment: NodeJS.ProcessEnv) => {
const parsed = parseConfig({ GHIDRA_INSTALL_DIR: "/ghidra", ...environment });
if (!parsed.ok) throw parsed.error;
return parsed.value;
};
const config = configFor({});
const target = (change: Partial<PowerPcElfMetadata> = {}): BinaryTarget => ({
path: "/fixture.elf",
sha256: "a".repeat(64),
kind: "executable",
format: "elf",
architecture: "powerpc",
availableArchitectures: ["powerpc"],
powerpc: { elfClass: 32, byteOrder: "big", type: 2, flags: 0, ...change },
});
describe("bounded Ghidra PowerPC admission", () => {
it("binds the generic language instead of the loader's e500 choice", async () => {
const ghidra = new GhidraProvider(config, silentLogger, {}, host);
expect(ghidra.inspectTargetSupport(target()).status).toBe("supported");
const resolved = await ghidra.resolveAnalysisProfile(target());
if (!resolved.ok) throw resolved.error;
const parameters = resolved.value.profile?.parameters ?? {};
expect(parameters).toMatchObject({
architecture: "powerpc",
language_id: "PowerPC:BE:32:default",
compiler_spec_id: "default",
language_selection: "provider-pinned-v1",
powerpc_elf: { elf_class: 32, byte_order: "big", type: 2, flags: 0 },
powerpc_support_lane: "elf32-be-exec-generic-v1",
});
expect(ghidraPinnedLanguage(target())).toEqual({
languageId: "PowerPC:BE:32:default",
compilerSpecId: "default",
});
expect(ghidraProfileLanguageOverride(parameters)).toEqual(
ghidraPinnedLanguage(target()),
);
});
it("lets a configured language replace the lane default", async () => {
const installDir = await createTestTempDirectory("rea-ghidra-ppc-");
const languages = join(
installDir,
"Ghidra/Processors/PowerPC/data/languages",
);
await mkdir(languages, { recursive: true });
await writeFile(join(languages, "ppc.ldefs"), PPC_LDEFS);
const ghidra = new GhidraProvider(
configFor({
GHIDRA_INSTALL_DIR: installDir,
REA_GHIDRA_LANGUAGE_ID: "PowerPC:BE:32:e500",
}),
silentLogger,
{},
host,
);
const resolved = await ghidra.resolveAnalysisProfile(target());
if (!resolved.ok) throw resolved.error;
const parameters = resolved.value.profile?.parameters ?? {};
expect(parameters).toMatchObject({
language_id: "PowerPC:BE:32:e500",
language_selection: "configured-v1",
});
expect(ghidraProfileLanguageOverride(parameters)).toEqual({
languageId: "PowerPC:BE:32:e500",
});
});
it("commits header flags so a changed interpretation changes the profile", async () => {
const ghidra = new GhidraProvider(config, silentLogger, {}, host);
const left = await ghidra.resolveAnalysisProfile(target());
const right = await ghidra.resolveAnalysisProfile(
target({ flags: 0x00010000 }),
);
if (!left.ok) throw left.error;
if (!right.ok) throw right.error;
expect(left.value.profile?.digest).not.toBe(right.value.profile?.digest);
});
it("does not widen Windows P0", () => {
const windows = new GhidraProvider(
config,
silentLogger,
{},
{ ...host, platform: "win32" },
);
expect(windows.inspectTargetSupport(target()).status).toBe("unsupported");
});
it.each([
[{ elfClass: 64 }, "ELF32"],
[{ byteOrder: "little" }, "big-endian"],
[{ type: 1 }, "ET_EXEC"],
[{ type: 3 }, "ET_EXEC"],
[{ flags: 0x80000000 }, "EF_PPC_EMB"],
] satisfies [Partial<PowerPcElfMetadata>, string][])(
"refuses an unverified PowerPC interpretation %j",
async (change, reason) => {
const ghidra = new GhidraProvider(config, silentLogger, {}, host);
const value = target(change);
expect(ghidra.inspectTargetSupport(value)).toMatchObject({
status: "unsupported",
reason: expect.stringContaining(reason),
});
const resolved = await ghidra.resolveAnalysisProfile(value);
expect(resolved.ok).toBe(false);
},
);
it("keeps PowerPC out of unverified Hopper and IDA adapter lanes", () => {
const hopper = new HopperProvider(config, silentLogger, {}, "linux");
expect(hopper.inspectTargetSupport(target()).status).toBe("unsupported");
expect(hopperLoaderArgsForTarget(target()).ok).toBe(false);
const ida = new IdaProvider(config, {});
expect(ida.inspectTargetSupport(target()).status).toBe("unsupported");
});
});
+67
View File
@@ -0,0 +1,67 @@
import type { GhidraLanguageOverride } from "../config/ghidraLanguageOverride.js";
import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
import type { JsonValue } from "../domain/jsonValue.js";
/**
* Generic 32-bit big-endian PowerPC. Ghidra's ELF loader selects the e500
* (Book-E/SPE) variant for a plain EM_PPC header, so the lane binds this
* language instead of accepting the loader's choice.
*/
export const GHIDRA_POWERPC_LANGUAGE: GhidraLanguageOverride = {
languageId: "PowerPC:BE:32:default",
compilerSpecId: "default",
};
/** Keep family recognition separate from the deliberately bounded Ghidra lane. */
export const ghidraPowerPcUnsupportedReason = (
target: BinaryTarget,
): string | null => {
if (target.kind !== "executable" || target.architecture !== "powerpc")
return null;
const metadata = target.powerpc;
if (target.format !== "elf" || metadata === undefined)
return "PowerPC analysis requires ELF header metadata; a family name alone does not select a processor variant.";
if (metadata.elfClass !== 32)
return "This Ghidra PowerPC lane supports ELF32 only; PPC64 remains unsupported.";
if (metadata.byteOrder !== "big")
return "This Ghidra PowerPC lane supports big-endian ELF32 only; little-endian PowerPC needs separate verification.";
if (metadata.type !== 2)
return "This Ghidra PowerPC lane supports ET_EXEC only; relocatable objects and shared images need separate load verification.";
// EF_PPC_EMB (0x80000000) marks embedded variants; other bits only declare
// relocation conventions that do not change instruction decoding.
if ((metadata.flags & 0x80000000) !== 0)
return "EF_PPC_EMB declares an embedded PowerPC variant that needs a separately supported processor profile.";
return null;
};
/**
* The language the lane imports with, unless REA_GHIDRA_LANGUAGE_ID already
* selected one through the committed profile.
*/
export const ghidraPowerPcLanguage = (
target: BinaryTarget,
): GhidraLanguageOverride | undefined =>
target.kind === "executable" && target.architecture === "powerpc"
? GHIDRA_POWERPC_LANGUAGE
: undefined;
/** Commit source ELF interpretation without confusing target ISA with host CPU. */
export const ghidraPowerPcProfileParameters = (
target: BinaryTarget,
): Readonly<Record<string, JsonValue>> => {
if (
target.kind !== "executable" ||
target.architecture !== "powerpc" ||
target.powerpc === undefined
)
return {};
return {
powerpc_elf: {
elf_class: target.powerpc.elfClass,
byte_order: target.powerpc.byteOrder,
type: target.powerpc.type,
flags: target.powerpc.flags,
},
powerpc_support_lane: "elf32-be-exec-generic-v1",
};
};
+1
View File
@@ -68,6 +68,7 @@ const SUPPORTED_ARCHITECTURES = new Set([
"mips",
"6502",
"riscv",
"powerpc",
]);
/** Ghidra candidate backed by an isolated ephemeral headless import. */
+3
View File
@@ -1,5 +1,6 @@
import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
import { ghidraMipsUnsupportedReason } from "./GhidraMipsProfile.js";
import { ghidraPowerPcUnsupportedReason } from "./GhidraPowerPcProfile.js";
import { ghidraRiscvUnsupportedReason } from "./GhidraRiscvProfile.js";
/** Allegrex's ELF machine declaration, not a filename or inferred instruction. */
@@ -14,6 +15,8 @@ export const isGhidraPspTarget = (target: BinaryTarget): boolean =>
export const ghidraProcessorUnsupportedReason = (
target: BinaryTarget,
): string | null => {
if (target.kind === "executable" && target.architecture === "powerpc")
return ghidraPowerPcUnsupportedReason(target);
if (target.kind === "executable" && target.architecture === "riscv")
return ghidraRiscvUnsupportedReason(target);
if (
+1
View File
@@ -110,6 +110,7 @@ const HOPPER_DECLINED_ARCHITECTURE_LABELS: Record<
> = {
mips: "MIPS",
riscv: "RISC-V",
powerpc: "PowerPC",
};
/** Derive Hopper's complete non-interactive CLI loader selection. */
+5 -1
View File
@@ -126,7 +126,11 @@ export class HopperProvider implements AnalysisProviderCandidate {
status: "unsupported",
code: "architecture_unsupported",
reason: `REA's Hopper adapter does not admit ${
target.architecture === "mips" ? "MIPS" : "RISC-V"
target.architecture === "mips"
? "MIPS"
: target.architecture === "riscv"
? "RISC-V"
: "PowerPC"
} targets.`,
diagnostics,
};
+5 -1
View File
@@ -113,7 +113,11 @@ export class IdaProvider implements AnalysisProviderCandidate {
status: "unsupported",
code: "architecture_unsupported",
reason: `REA's IDA adapter has no verified ${
target.architecture === "mips" ? "MIPS" : "RISC-V"
target.architecture === "mips"
? "MIPS"
: target.architecture === "riscv"
? "RISC-V"
: "PowerPC"
} lane. Select a supported Ghidra profile instead.`,
diagnostics,
};