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
@@ -0,0 +1,93 @@
import { describe, expect, it } from "vitest";
import type { BinaryTarget } from "../../../src/domain/binaryTargetTypes.js";
import { createAnalysisProfile } from "../../../src/domain/analysisProfile.js";
import { createEvidence, parseEvidence } from "../../../src/domain/evidence.js";
import { createEvidenceBundle } from "../../../src/domain/evidenceBundle.js";
import {
createAnalysisSnapshotEntry,
parseAnalysisSnapshot,
serializeAnalysisSnapshot,
snapshotBinding,
snapshotTarget,
snapshotMatchesProfile,
} from "../../../src/domain/analysisSnapshot.js";
import { sessionOutputSchemas } from "../../../src/contracts/toolOutputSchemaGroups.js";
const target: BinaryTarget = {
path: "/source-owned.elf",
sha256: "a".repeat(64),
kind: "executable",
format: "elf",
architecture: "powerpc",
availableArchitectures: ["powerpc"],
powerpc: { elfClass: 32, byteOrder: "big", type: 2, flags: 0 },
};
const provider = { id: "ghidra", name: "Ghidra", version: "12.1.4" };
const profile = createAnalysisProfile(provider, {
powerpc_elf: { elf_class: 32, byte_order: "big", type: 2, flags: 0 },
});
describe("PowerPC identity through lifecycle, Evidence and snapshot consumers", () => {
it("round-trips query bindings without relaxing integrity", () => {
const result = [{ address: "0x100101b0", value: "rea_ppc_entry" }];
const parameters = {};
const evidence = createEvidence(target, provider, {
operation: "list_procedures",
parameters,
result,
analysisProfile: profile,
});
const binding = snapshotBinding(profile);
const entry = createAnalysisSnapshotEntry({
target: snapshotTarget(target),
binding,
operation: "list_procedures",
parameters,
execution: {
result,
rawResult: null,
provider,
analysisProfile: profile,
limitations: [],
locations: [],
subject: target,
},
});
const snapshot = {
target: snapshotTarget(target),
binding,
entries: [entry],
workflow_entries: [],
evidence_bundle: createEvidenceBundle([evidence]),
};
const restored = parseAnalysisSnapshot(
JSON.parse(serializeAnalysisSnapshot(snapshot)),
);
expect(restored.target.architecture).toBe("powerpc");
expect(restored.evidence_bundle.records[0]?.subject?.architecture).toBe(
"powerpc",
);
expect(restored.entries[0]?.execution.subject?.architecture).toBe(
"powerpc",
);
expect(
sessionOutputSchemas.open_binary.parse({ result: target }).result
.architecture,
).toBe("powerpc");
expect(() =>
parseEvidence({
...evidence,
subject: { ...evidence.subject, architecture: "x86" },
}),
).toThrow("semantic identifier");
const changed = createAnalysisProfile(provider, {
powerpc_elf: {
elf_class: 32,
byte_order: "big",
type: 2,
flags: 0x00010000,
},
});
expect(snapshotMatchesProfile(binding, changed)).toBe(false);
});
});
+14
View File
@@ -0,0 +1,14 @@
/* Freestanding, source-owned static-analysis fixture. Never executed by REA. */
volatile unsigned int rea_ppc_global = 7;
const char rea_ppc_marker[] = "rea-ppc-source-owned-fixture";
__attribute__((noinline)) unsigned int rea_ppc_leaf(unsigned int value)
{
return value * 3u + rea_ppc_global;
}
__attribute__((noinline)) unsigned int rea_ppc_entry(unsigned int selector)
{
unsigned int adjusted = selector > 10u ? selector : selector + 1u;
return rea_ppc_leaf(adjusted) + (unsigned char)rea_ppc_marker[0];
}
+29
View File
@@ -0,0 +1,29 @@
import type { PowerPcElfMetadata } from "../../../src/domain/binaryTargetTypes.js";
export interface PowerPcReadelfFacts {
powerpc: PowerPcElfMetadata;
symbols: Record<
| "rea_ppc_entry"
| "rea_ppc_leaf"
| "rea_ppc_probe"
| "rea_ppc_global"
| "rea_ppc_marker",
string
>;
}
export function parsePowerPcReadelf(text: string): PowerPcReadelfFacts;
export function inspectPowerPcReadelf(
path: string,
): Promise<
PowerPcReadelfFacts & { command: string; version: string; raw: string }
>;
export function assertPowerPcLoadedImage(
observations: unknown,
sha256: string,
): void;
export function assertPowerPcProbe(
move: unknown,
branch: unknown,
address: string,
): void;
export function assertPowerPcGlobal(bytes: string): void;
+132
View File
@@ -0,0 +1,132 @@
import assert from "node:assert/strict";
import { execFile } from "node:child_process";
import { promisify } from "node:util";
const execute = promisify(execFile);
// The lane binds this language; Ghidra's ELF loader alone selects e500.
const LANGUAGE = "PowerPC:BE:32:default";
const wordHex = (value) => {
const bytes = Buffer.alloc(4);
bytes.writeUInt32BE(value);
return bytes.toString("hex");
};
/** Parse only the documented GNU readelf fields needed by our tiny fixture. */
export function parsePowerPcReadelf(text) {
const field = (expression, label) => {
const matches = [...text.matchAll(expression)];
assert.equal(matches.length, 1, `Missing or ambiguous readelf ${label}`);
return matches[0][1].trim();
};
assert.equal(field(/^\s*Class:\s*(.+)$/gmu, "class"), "ELF32");
assert.equal(
field(/^\s*Data:.*?,\s*(little|big) endian\s*$/gmu, "byte order"),
"big",
);
assert.match(field(/^\s*Type:\s*(.+)$/gmu, "type"), /^EXEC\b/u);
assert.equal(field(/^\s*Machine:\s*(.+)$/gmu, "machine"), "PowerPC");
const flags = Number(field(/^\s*Flags:\s*(0x[\da-f]+)\s*$/gmu, "flags"));
assert.equal(flags, 0, "Fixture ELF flags differ from build intent");
const symbols = {};
for (const name of [
"rea_ppc_entry",
"rea_ppc_leaf",
"rea_ppc_probe",
"rea_ppc_global",
"rea_ppc_marker",
]) {
const value = field(
new RegExp(
`^\\s*\\d+:\\s+([\\da-f]+)\\s+\\d+\\s+(?:FUNC|OBJECT)\\s+GLOBAL\\s+\\S+\\s+\\d+\\s+${name}\\s*$`,
"gmu",
),
`symbol ${name}`,
);
symbols[name] = `0x${BigInt(`0x${value}`).toString(16)}`;
}
return {
powerpc: { elfClass: 32, byteOrder: "big", type: 2, flags },
symbols,
};
}
/** Independent reader is a bounded test prerequisite, never an REA provider. */
export async function inspectPowerPcReadelf(path) {
const command = process.env.REA_PPC_READELF ?? "readelf";
const options = {
env: { ...process.env, LC_ALL: "C" },
timeout: 10000,
maxBuffer: 1024 * 1024,
};
const version = await execute(command, ["--version"], options);
assert.match(
version.stdout,
/^GNU readelf\b/u,
"This lane requires GNU readelf",
);
const result = await execute(command, ["-h", "-s", "-W", path], options);
assert.equal(
result.stderr.trim(),
"",
`readelf diagnostics: ${result.stderr}`,
);
return {
...parsePowerPcReadelf(result.stdout),
command,
version: version.stdout.split("\n")[0],
raw: result.stdout,
};
}
/** Check effective Ghidra observations, not the requested analysis profile. */
export function assertPowerPcLoadedImage(observations, sha256) {
assert.equal(observations.language_id, LANGUAGE);
assert.equal(observations.compiler_spec_id, "default");
assert.ok(
observations.source_files.some(
(file) =>
file.original_sha256 === sha256 && file.modified_sha256 === sha256,
),
"Ghidra loaded source identity changed",
);
}
/** Verify the exact constant/conditional destination in ppc-probe.S. */
export function assertPowerPcProbe(move, branch, address) {
const start = BigInt(address);
for (const [instruction, offset, word] of [
[move, 0n, 0x38641234],
[branch, 8n, 0x41820008],
]) {
assert.equal(instruction.status, "decoded");
assert.equal(BigInt(instruction.address), start + offset);
assert.equal(instruction.architecture, LANGUAGE);
assert.equal(instruction.length, 4);
assert.equal(instruction.bytes, wordHex(word));
}
assert.match(move.mnemonic, /^ADDI$/iu);
assert.ok(
move.operands.some((operand) =>
operand.components.some(
(part) =>
part.kind === "immediate" &&
part.value !== null &&
BigInt(part.value) === 0x1234n,
),
),
"ADDI immediate was not recovered",
);
assert.match(branch.mnemonic, /^BEQ$/iu);
assert.equal(branch.flow.kind, "jump");
assert.equal(branch.flow.conditional, true);
assert.equal(branch.flow.computed, false);
assert.deepEqual(
branch.flow.direct_destinations.map((value) => BigInt(value)),
[start + 16n],
);
}
/** Four bytes must encode the known source-owned global in big-endian order. */
export function assertPowerPcGlobal(bytes) {
assert.equal(bytes, wordHex(7));
}
+187
View File
@@ -0,0 +1,187 @@
import { describe, expect, it } from "vitest";
import {
assertPowerPcGlobal,
assertPowerPcLoadedImage,
assertPowerPcProbe,
parsePowerPcReadelf,
} from "./ppc-checks.mjs";
// GNU readelf 2.47 output for the source-owned Clang 23 / LLD fixture.
// This tests the reader boundary, not Ghidra; the real lane rebuilds it.
const readelf = `ELF Header:
Magic: 7f 45 4c 46 01 02 01 00 00 00 00 00 00 00 00 00
Class: ELF32
Data: 2's complement, big endian
Version: 1 (current)
OS/ABI: UNIX - System V
ABI Version: 0
Type: EXEC (Executable file)
Machine: PowerPC
Version: 0x1
Entry point address: 0x100101b0
Start of program headers: 52 (bytes into file)
Start of section headers: 2188 (bytes into file)
Flags: 0x0
Size of this header: 52 (bytes)
Size of program headers: 32 (bytes)
Number of program headers: 6
Size of section headers: 40 (bytes)
Number of section headers: 18
Section header string table index: 16
Symbol table '.symtab' contains 7 entries:
Num: Value Size Type Bind Vis Ndx Name
0: 00000000 0 NOTYPE LOCAL DEFAULT UND
1: 00000000 0 FILE LOCAL DEFAULT ABS ppc.c
2: 10010180 48 FUNC GLOBAL DEFAULT 4 rea_ppc_leaf
3: 1002023c 4 OBJECT GLOBAL DEFAULT 5 rea_ppc_global
4: 100101b0 116 FUNC GLOBAL DEFAULT 4 rea_ppc_entry
5: 100000f4 29 OBJECT GLOBAL DEFAULT 1 rea_ppc_marker
6: 10010224 24 FUNC GLOBAL DEFAULT 4 rea_ppc_probe
`;
const sha256 = "a".repeat(64);
const image = {
language_id: "PowerPC:BE:32:default",
compiler_spec_id: "default",
source_files: [{ original_sha256: sha256, modified_sha256: sha256 }],
};
const move = {
address: "0x10010224",
status: "decoded",
architecture: "PowerPC:BE:32:default",
length: 4,
bytes: "38641234",
mnemonic: "addi",
operands: [
{ index: 2, components: [{ kind: "immediate", value: "0x1234" }] },
],
};
const branch = {
address: "0x1001022c",
status: "decoded",
architecture: "PowerPC:BE:32:default",
length: 4,
bytes: "41820008",
mnemonic: "beq",
flow: {
kind: "jump",
conditional: true,
computed: false,
direct_destinations: ["0x10010234"],
},
};
describe("PowerPC real-verifier independent expectations", () => {
it("reads GNU header and defined symbols without a Ghidra-derived oracle", () => {
const parsed = parsePowerPcReadelf(readelf);
expect(parsed.powerpc).toEqual({
elfClass: 32,
byteOrder: "big",
type: 2,
flags: 0,
});
expect(parsed.symbols.rea_ppc_probe).toBe("0x10010224");
});
it.each([
["wrong class", "ELF32", "ELF64"],
["wrong byte order", "big endian", "little endian"],
[
"wrong machine",
"Machine: PowerPC",
"Machine: PowerPC64",
],
["wrong object type", "EXEC (Executable file)", "DYN (Shared object file)"],
[
"wrong flags",
"Flags: 0x0",
"Flags: 0x80000000",
],
["missing symbol", "rea_ppc_probe", "unrelated_probe"],
])(
"rejects %s instead of returning a guessed fixture interpretation",
(_name, from, to) => {
expect(() => parsePowerPcReadelf(readelf.replace(from, to))).toThrow();
},
);
it("rejects ambiguous producer fields", () => {
expect(() => parsePowerPcReadelf(`${readelf}\nClass: ELF32\n`)).toThrow(
/ambiguous/u,
);
});
it("checks the effective loaded image, including Ghidra's e500 default", () => {
assertPowerPcLoadedImage(image, sha256);
expect(() =>
assertPowerPcLoadedImage(
{ ...image, language_id: "PowerPC:BE:32:e500" },
sha256,
),
).toThrow();
expect(() =>
assertPowerPcLoadedImage(
{ ...image, compiler_spec_id: "macosx" },
sha256,
),
).toThrow();
expect(() =>
assertPowerPcLoadedImage(
{
...image,
source_files: [
{ original_sha256: sha256, modified_sha256: "b".repeat(64) },
],
},
sha256,
),
).toThrow();
});
it("checks exact probe bytes, immediate and conditional destination", () => {
assertPowerPcProbe(move, branch, "0x10010224");
});
it("rejects plausible nonempty but incorrect instruction observations", () => {
expect(() =>
assertPowerPcProbe({ ...move, bytes: "38641235" }, branch, "0x10010224"),
).toThrow();
expect(() =>
assertPowerPcProbe({ ...move, length: 2 }, branch, "0x10010224"),
).toThrow();
expect(() =>
assertPowerPcProbe(
{
...move,
operands: [
{ index: 2, components: [{ kind: "immediate", value: "0x1235" }] },
],
},
branch,
"0x10010224",
),
).toThrow();
expect(() =>
assertPowerPcProbe(
move,
{
...branch,
flow: { ...branch.flow, direct_destinations: ["0x10010230"] },
},
"0x10010224",
),
).toThrow();
expect(() =>
assertPowerPcProbe(
move,
{ ...branch, flow: { ...branch.flow, conditional: false } },
"0x10010224",
),
).toThrow();
});
it("checks the big-endian global word", () => {
assertPowerPcGlobal("00000007");
expect(() => assertPowerPcGlobal("07000000")).toThrow();
});
});
+62
View File
@@ -0,0 +1,62 @@
import { execFile } from "node:child_process";
import { createHash } from "node:crypto";
import { readFile } from "node:fs/promises";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
const execute = promisify(execFile);
/** Build a source-owned freestanding ELF; never execute its target code. */
export async function buildPowerPcFixture(directory) {
const compiler = process.env.REA_PPC_CLANG ?? "clang";
const target = "powerpc-unknown-linux-gnu";
const source = fileURLToPath(new URL("../c/ppc.c", import.meta.url));
const probe = fileURLToPath(new URL("./ppc-probe.S", import.meta.url));
const path = join(directory, `${target}.elf`);
const args = [
`--target=${target}`,
// A 750-family core with the classic FPU, unlike the e500 SPE variant.
"-mcpu=750",
"-fno-pic",
"-fuse-ld=lld",
"-nostdlib",
"-static",
"-O0",
"-g",
"-Wl,-e,rea_ppc_entry",
"-Wl,--build-id=none",
source,
probe,
"-o",
path,
];
const version = await execute(compiler, ["--version"], { timeout: 10000 });
await execute(compiler, args, { timeout: 60000 });
const bytes = await readFile(path);
if (
bytes.length < 52 ||
bytes.toString("hex", 0, 4) !== "7f454c46" ||
bytes[4] !== 1 ||
bytes[5] !== 2 ||
bytes.readUInt16BE(16) !== 2 ||
bytes.readUInt16BE(18) !== 20 ||
bytes.readUInt32BE(36) !== 0
)
throw new Error(
"Compiler did not produce the declared ELF32 big-endian PowerPC fixture",
);
return {
path,
flags: bytes.readUInt32BE(36),
sha256: createHash("sha256").update(bytes).digest("hex"),
source_sha256: createHash("sha256")
.update(await readFile(source))
.digest("hex"),
probe_sha256: createHash("sha256")
.update(await readFile(probe))
.digest("hex"),
compiler: version.stdout.trim(),
arguments: args,
};
}
+17
View File
@@ -0,0 +1,17 @@
/* Source-owned 32-bit PowerPC instructions with fixed, reviewable encodings.
* No target execution. The conditional branch at +8 targets +16.
*/
.text
.p2align 2
.globl rea_ppc_probe
.type rea_ppc_probe, @function
rea_ppc_probe:
addi 3, 4, 0x1234
cmpwi 0, 4, 0
beq 0, .Lzero
blr
.Lzero:
li 3, 7
blr
.size rea_ppc_probe, .-rea_ppc_probe
.section .note.GNU-stack,"",@progbits