feat(native): admit bounded MIPS ELF analysis through Ghidra (#1362)

* feat(native): admit bounded MIPS ELF analysis through Ghidra

Retain MIPS ELF identity and interpretation through Evidence and snapshots.
Keep provider admission bounded to ELF32 ET_EXEC o32 MIPS32r2, without
implicitly widening Hopper, IDA or Windows P0 coverage. Add source-owned
fixtures and an optional real-provider verifier; real Ghidra verification
remains pending in this contribution environment.

Refs #718

* fix(ghidra): bound MIPS floating-point mode admission

Reject explicit EF_MIPS_FP64 and EF_MIPS_NAN2008 declarations until their
semantics have a real-provider verification lane. Add PSP PRX/Allegrex,
o64/EABI and floating-point-mode refusal regressions. Document that the
header gate is not a full .MIPS.abiflags check and advance the profile lane
identity to invalidate older interpretation bindings.

Validation: 24 standalone checks against the transpiled production profile
module passed; the two new flag cases failed before this change. Clang 17
and LLD compiled the source-owned fixture for both endian targets. The
complete Vitest/typecheck suite and real Ghidra verification remain pending.

Refs morluto/rea#718; PSP support remains follow-up morluto/rea#1330.

* fix(native): validate MIPS ABI records before Ghidra admission

Read bounded ELF32 PT_MIPS_ABIFLAGS and SHT_MIPS_ABIFLAGS records through
the already-open target handle. Preserve declared ABI fields, reject
conflicting/duplicate/truncated records, and keep missing records unknown.
Wire inspection into target resolution before provider selection. Require
compatible declarations for the deliberately narrow Ghidra lane and bind
all ABI fields into profile identity (v3) for snapshot invalidation.

Clang 17 produced eight source-owned fixtures spanning both byte orders
and FPXX/FP32/FP64/soft-float modes with identical ELF header flags. The
new reader and policy distinguish them. 24 focused regression test bodies
passed after TypeScript transpilation using node:test in place of Vitest;
strict isolated TypeScript checking of the reader and target/result types
passed. These are limited checks, not full Vitest/project typechecking or
real-Ghidra verification, which remain pending.

Advances morluto/rea#718. PSP/Allegrex remains morluto/rea#1330 follow-up.

* fix(native): repair MIPS integration boundaries and test resolver behavior

Keep ELF targets out of Hopper Mach-O preparation and scope existing PE fixture types correctly. Move ABI tests into the filesystem boundary lane, use shared cleanup, add resolver regressions, apply the pinned formatter, and register the real MIPS verifier through the existing package-command pattern. Validated with repository-pinned Node/npm, check:ci, actual focused Vitest, discovery and docs:check. Real Ghidra conformance remains pending.

* fix(test): honor caller-selected JDK in real MIPS verification

* test(native): strengthen MIPS Ghidra conformance

Cross-check the source-owned fixture with bounded GNU readelf inspection, compare production ELF/ABI interpretation and independent symbol addresses, and verify effective Ghidra language/compiler identity through existing public operations. Add a source-owned fixed-encoding probe for immediate and conditional branch checks plus global/string byte assertions.

Add 16 assertion/producer-boundary regression cases without widening production admission, changing provider contracts, or introducing proprietary dependencies. Local focused suite: 99 passed, one existing root-permission test skipped. Typecheck, lint/module boundaries, formatting and 700-file discovery pass; full hosted checks and real Ghidra verification remain pending for this checkpoint.

* fix(ghidra): preserve native-tool architecture checks after MIPS integration

The conflict-free upstream merge failed TypeScript compilation because includes on the union of MIPS-only and other architecture arrays requires never. Use equality-based membership without casts or changing accepted native hosts. Extend the existing native-decompiler rejection table with a MIPS executable at a Linux x64 tool path; retain upstream FAT and unknown-header behavior. Hosted verification follows this commit; no success is claimed yet.

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
This commit is contained in:
Jay-Alexander Elliot
2026-10-10 23:04:27 +08:00
committed by GitHub
co-authored by github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
parent 96fd98cce0
commit bddddccdee
32 changed files with 2028 additions and 35 deletions
@@ -0,0 +1,309 @@
import assert from "node:assert/strict";
import { createHash } from "node:crypto";
import { open, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { it } from "vitest";
import { parseBinaryTarget } from "../../../src/application/BinaryTargetResolver.js";
import { AnalysisCancelledError } from "../../../src/domain/analysisErrorCore.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import type { MipsElfMetadata } from "../../../src/domain/binaryTargetTypes.js";
import { readMipsElfAbiFlags } from "../../../src/application/MipsElfAbiFlags.js";
import {
ghidraMipsProfileParameters,
ghidraMipsUnsupportedReason,
} from "../../../src/ghidra/GhidraMipsProfile.js";
const metadata = (little = true): MipsElfMetadata => ({
elfClass: 32,
byteOrder: little ? "little" : "big",
type: 2,
flags: 0x70001001,
});
const abiOffset = 8192; // Deliberately outside BinaryTargetResolver's 4 KiB probe.
const fixture = (little = true): Buffer => {
const bytes = Buffer.alloc(abiOffset + 48);
bytes.set([0x7f, 0x45, 0x4c, 0x46, 1, little ? 1 : 2, 1]);
const u16 = (value: number, offset: number) =>
little
? bytes.writeUInt16LE(value, offset)
: bytes.writeUInt16BE(value, offset);
const u32 = (value: number, offset: number) =>
little
? bytes.writeUInt32LE(value, offset)
: bytes.writeUInt32BE(value, offset);
u16(2, 16);
u16(8, 18);
u32(1, 20);
u32(52, 28);
u32(128, 32);
u32(0x70001001, 36);
u16(52, 40);
u16(32, 42);
u16(1, 44);
u16(40, 46);
u16(2, 48);
u32(0x70000003, 52);
u32(abiOffset, 56);
u32(24, 68);
u32(24, 72);
u32(0x7000002a, 172);
u32(abiOffset, 184);
u32(24, 188);
bytes.set([0, 0, 32, 2, 1, 1, 0, 5], abiOffset);
return bytes;
};
const inspect = async (
bytes: Buffer,
little = true,
checkCancelled: () => void = () => {},
) => {
const directory = await createTestTempDirectory("rea-mips-abi-test-");
const path = join(directory, "fixture.elf");
await writeFile(path, bytes);
const handle = await open(path, "r");
try {
return await readMipsElfAbiFlags(handle, metadata(little), checkCancelled);
} finally {
await handle.close();
}
};
const target = (mips: MipsElfMetadata) => ({
path: "/fixture.elf",
sha256: "a".repeat(64),
kind: "executable" as const,
format: "elf" as const,
architecture: "mips" as const,
availableArchitectures: ["mips"] as const,
mips,
});
for (const little of [true, false]) {
it(`reads a remote ABI record through both ELF tables (${little ? "LE" : "BE"})`, async () => {
const bytes = fixture(little);
const result = await inspect(bytes, little);
assert.ok(result.ok);
assert.deepEqual(result.value, {
version: 0,
isaLevel: 32,
isaRevision: 2,
gprSize: 1,
cpr1Size: 1,
cpr2Size: 0,
fpAbi: 5,
isaExtension: 0,
ases: 0,
flags1: 0,
flags2: 0,
});
const resolved = target({ ...metadata(little), abiFlags: result.value });
assert.equal(ghidraMipsUnsupportedReason(resolved), null);
const before = ghidraMipsProfileParameters(resolved);
bytes[abiOffset + 5] = 2;
bytes[abiOffset + 7] = 6;
const fp64 = await inspect(bytes, little);
assert.ok(fp64.ok);
const changed = target({ ...metadata(little), abiFlags: fp64.value });
assert.match(ghidraMipsUnsupportedReason(changed) ?? "", /register modes/u);
assert.notDeepEqual(ghidraMipsProfileParameters(changed), before);
});
}
it("supports stripped section tables using PT_MIPS_ABIFLAGS", async () => {
const bytes = fixture();
bytes.writeUInt32LE(0, 32);
bytes.writeUInt16LE(0, 48);
const result = await inspect(bytes);
assert.ok(result.ok);
assert.equal(result.value?.fpAbi, 5);
});
it("supports a section-only ABI record without assuming its name", async () => {
const bytes = fixture();
bytes.writeUInt32LE(0, 28);
bytes.writeUInt16LE(0, 44);
const result = await inspect(bytes);
assert.ok(result.ok);
assert.equal(result.value?.fpAbi, 5);
});
it("keeps absent ABI declarations unknown and refuses provider admission", async () => {
const bytes = fixture();
bytes.writeUInt32LE(0, 52);
bytes.writeUInt32LE(0, 172);
const result = await inspect(bytes);
assert.ok(result.ok);
assert.equal(result.value, null);
assert.match(
ghidraMipsUnsupportedReason(target({ ...metadata(), abiFlags: null })) ??
"",
/inspected ABI/u,
);
assert.match(
ghidraMipsUnsupportedReason(target(metadata())) ?? "",
/inspected ABI/u,
);
});
it("rejects contradictory program and section ABI declarations", async () => {
const bytes = fixture();
bytes.copy(bytes, abiOffset + 24, abiOffset, abiOffset + 24);
bytes[abiOffset + 24 + 7] = 6;
bytes.writeUInt32LE(abiOffset + 24, 184);
const result = await inspect(bytes);
assert.ok(!result.ok);
assert.match(result.error, /conflicting/u);
});
it("rejects duplicate ABI declarations in one table", async () => {
const bytes = fixture();
bytes.copy(bytes, 84, 52, 84);
bytes.writeUInt16LE(2, 44);
const result = await inspect(bytes);
assert.ok(!result.ok);
assert.match(result.error, /duplicate/u);
});
const malformed: [string, (bytes: Buffer) => void, RegExp][] = [
["record outside file", (b) => b.writeUInt32LE(0xfffffff0, 56), /outside/u],
["table outside file", (b) => b.writeUInt32LE(0xfffffff0, 28), /outside/u],
["short record", (b) => b.writeUInt32LE(23, 68), /record size/u],
["oversized record", (b) => b.writeUInt32LE(0xffffffff, 68), /record size/u],
["invalid table stride", (b) => b.writeUInt16LE(31, 42), /entry size/u],
["extended program count", (b) => b.writeUInt16LE(0xffff, 44), /numbering/u],
["extended section count", (b) => b.writeUInt16LE(0, 48), /extended/u],
["changed identity", (b) => b.writeUInt32LE(0x60001001, 36), /identity/u],
["invalid ELF version", (b) => b.writeUInt32LE(0, 20), /version/u],
];
for (const [name, change, reason] of malformed) {
it(`rejects ${name} instead of using a guessed ABI`, async () => {
const bytes = fixture();
change(bytes);
const result = await inspect(bytes);
assert.ok(!result.ok);
assert.match(result.error, reason);
});
}
const unsupported: [string, (bytes: Buffer) => void, RegExp][] = [
["new record version", (b) => b.writeUInt16LE(1, abiOffset), /version 0/u],
[
"conflicting ISA",
(b) => {
b[abiOffset + 3] = 6;
},
/MIPS32r2/u,
],
[
"soft-float",
(b) => {
b[abiOffset + 5] = 0;
b[abiOffset + 7] = 3;
},
/register modes/u,
],
[
"unspecified FP ABI",
(b) => {
b[abiOffset + 7] = 0;
},
/unspecified/u,
],
["ISA extension", (b) => b.writeUInt32LE(1, abiOffset + 8), /extension/u],
["ASE", (b) => b.writeUInt32LE(0x800, abiOffset + 12), /ASE/u],
[
"reserved flags",
(b) => b.writeUInt32LE(2, abiOffset + 16),
/general flags/u,
],
];
for (const [name, change, reason] of unsupported) {
it(`retains ${name} while rejecting its unverified provider interpretation`, async () => {
const bytes = fixture();
change(bytes);
const result = await inspect(bytes);
assert.ok(result.ok);
assert.ok(result.value !== null);
assert.match(
ghidraMipsUnsupportedReason(
target({ ...metadata(), abiFlags: result.value }),
) ?? "",
reason,
);
});
}
it("preserves the caller's cancellation error during table inspection", async () => {
const cancelled = new Error("caller cancellation sentinel");
let checks = 0;
await assert.rejects(
inspect(fixture(), true, () => {
checks += 1;
if (checks === 12) throw cancelled;
}),
(error) => error === cancelled,
);
});
for (const little of [true, false]) {
it(`resolves full-file MIPS ABI identity before provider selection (${little ? "LE" : "BE"})`, async () => {
const directory = await createTestTempDirectory("rea-mips-resolution-");
const path = join(directory, "fixture.elf");
const bytes = fixture(little);
await writeFile(path, bytes);
const result = await parseBinaryTarget(path);
if (!result.ok) throw result.error;
assert.equal(result.value.architecture, "mips");
assert.equal(result.value.format, "elf");
assert.equal(
result.value.sha256,
createHash("sha256").update(bytes).digest("hex"),
);
if (
result.value.kind !== "executable" ||
result.value.architecture !== "mips"
)
throw new Error("Expected a resolved MIPS executable");
assert.equal(result.value.mips.byteOrder, little ? "little" : "big");
assert.equal(result.value.mips.abiFlags?.fpAbi, 5);
assert.equal(ghidraMipsUnsupportedReason(result.value), null);
assert.deepEqual(await readFile(path), bytes);
});
}
it("keeps missing ABI data unknown through the public target resolver", async () => {
const directory = await createTestTempDirectory("rea-mips-resolution-");
const path = join(directory, "fixture.elf");
const bytes = fixture();
bytes.writeUInt32LE(0, 52);
bytes.writeUInt32LE(0, 172);
await writeFile(path, bytes);
const result = await parseBinaryTarget(path);
if (!result.ok) throw result.error;
if (
result.value.kind !== "executable" ||
result.value.architecture !== "mips"
)
throw new Error("Expected a resolved MIPS executable");
assert.equal(result.value.mips.abiFlags, null);
assert.match(
ghidraMipsUnsupportedReason(result.value) ?? "",
/inspected ABI/u,
);
});
it("projects a malformed out-of-probe ABI record as a target error", async () => {
const directory = await createTestTempDirectory("rea-mips-resolution-");
const path = join(directory, "fixture.elf");
const bytes = fixture();
bytes.writeUInt32LE(0xfffffff0, 56);
await writeFile(path, bytes);
const result = await parseBinaryTarget(path);
if (result.ok) throw new Error("Malformed ABI extent was accepted");
assert.equal(result.error._tag, "BinaryTargetError");
assert.match(result.error.message, /ABI record lies outside the file/u);
assert.deepEqual(await readFile(path), bytes);
});
it("preserves cancellation instead of turning it into malformed target data", async () => {
const directory = await createTestTempDirectory("rea-mips-resolution-");
const path = join(directory, "fixture.elf");
await writeFile(path, fixture());
const controller = new AbortController();
controller.abort();
const result = await parseBinaryTarget(path, { signal: controller.signal });
if (result.ok) throw new Error("Cancelled target resolution succeeded");
assert.ok(result.error instanceof AnalysisCancelledError);
});
@@ -0,0 +1,91 @@
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: "mips",
availableArchitectures: ["mips"],
mips: { elfClass: 32, byteOrder: "little", type: 2, flags: 0x70001001 },
};
const provider = { id: "ghidra", name: "Ghidra", version: "12.1.4" };
const profile = createAnalysisProfile(provider, {
mips_elf: { elf_class: 32, byte_order: "little", type: 2, flags: 0x70001001 },
});
describe("MIPS identity through lifecycle, Evidence and snapshot consumers", () => {
it("round-trips query bindings without relaxing integrity", () => {
const result = [{ address: "0x20150", value: "rea_mips_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("mips");
expect(restored.evidence_bundle.records[0]?.subject?.architecture).toBe(
"mips",
);
expect(restored.entries[0]?.execution.subject?.architecture).toBe("mips");
expect(
sessionOutputSchemas.open_binary.parse({ result: target }).result
.architecture,
).toBe("mips");
expect(() =>
parseEvidence({
...evidence,
subject: { ...evidence.subject, architecture: "x86" },
}),
).toThrow("semantic identifier");
const changed = createAnalysisProfile(provider, {
mips_elf: {
elf_class: 32,
byte_order: "big",
type: 2,
flags: 0x70001001,
},
});
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_mips_global = 7;
const char rea_mips_marker[] = "rea-mips-source-owned-fixture";
__attribute__((noinline)) unsigned int rea_mips_leaf(unsigned int value)
{
return value * 3u + rea_mips_global;
}
__attribute__((noinline)) unsigned int rea_mips_entry(unsigned int selector)
{
unsigned int adjusted = selector > 10u ? selector : selector + 1u;
return rea_mips_leaf(adjusted) + (unsigned char)rea_mips_marker[0];
}
@@ -0,0 +1,35 @@
import type { MipsElfMetadata } from "../../../src/domain/binaryTargetTypes.js";
export interface MipsReadelfFacts {
mips: MipsElfMetadata;
symbols: Record<
| "rea_mips_entry"
| "rea_mips_leaf"
| "rea_mips_probe"
| "rea_mips_global"
| "rea_mips_marker",
string
>;
}
export function parseMipsReadelf(
text: string,
byteOrder: string,
): MipsReadelfFacts;
export function inspectMipsReadelf(
path: string,
byteOrder: string,
): Promise<
MipsReadelfFacts & { command: string; version: string; raw: string }
>;
export function assertMipsLoadedImage(
observations: unknown,
byteOrder: string,
sha256: string,
): void;
export function assertMipsProbe(
move: unknown,
branch: unknown,
byteOrder: string,
address: string,
): void;
export function assertMipsGlobal(bytes: string, byteOrder: string): void;
+180
View File
@@ -0,0 +1,180 @@
import assert from "node:assert/strict";
import { execFile } from "node:child_process";
import { promisify } from "node:util";
const execute = promisify(execFile);
const language = (byteOrder) => {
assert.ok(byteOrder === "little" || byteOrder === "big");
return `MIPS:${byteOrder === "little" ? "LE" : "BE"}:32:default`;
};
const wordHex = (value, byteOrder) => {
language(byteOrder);
const bytes = Buffer.alloc(4);
if (byteOrder === "little") bytes.writeUInt32LE(value);
else bytes.writeUInt32BE(value);
return bytes.toString("hex");
};
/** Parse only the documented GNU readelf fields needed by our tiny fixture. */
export function parseMipsReadelf(text, byteOrder) {
language(byteOrder);
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"),
byteOrder,
);
assert.match(field(/^\s*Type:\s*(.+)$/gmu, "type"), /^EXEC\b/u);
assert.match(field(/^\s*Machine:\s*(.+)$/gmu, "machine"), /^MIPS\b/u);
const flags = Number(field(/^\s*Flags:\s*(0x[\da-f]+),.*$/gmu, "flags"));
assert.equal(flags, 0x70001001, "Fixture ELF flags differ from build intent");
assert.equal(field(/^ISA:\s*(.+)$/gmu, "ISA"), "MIPS32r2");
const registerSize = (name) => {
const bits = Number(
field(new RegExp(`^${name} size:\\s*(\\d+)\\s*$`, "gmu"), name),
);
assert.ok(bits === 0 || bits === 32, `Unexpected ${name} width`);
return bits === 32 ? 1 : 0;
};
const fp = field(/^FP ABI:\s*(.+)$/gmu, "FP ABI");
const fpAbi = new Map([
["Hard float (double precision)", 1],
["Hard float (32-bit CPU, Any FPU)", 5],
]).get(fp);
assert.ok(fpAbi !== undefined, `Unrecognized fixture FP ABI: ${fp}`);
assert.equal(field(/^ISA Extension:\s*(.+)$/gmu, "ISA extension"), "None");
assert.equal(field(/^ASEs:\s*\n[ \t]*(.+)$/gmu, "ASEs"), "None");
const abiFlags = {
version: Number(
field(/^MIPS ABI Flags Version:\s*(\d+)\s*$/gmu, "ABI version"),
),
isaLevel: 32,
isaRevision: 2,
gprSize: registerSize("GPR"),
cpr1Size: registerSize("CPR1"),
cpr2Size: registerSize("CPR2"),
fpAbi,
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,
),
};
const symbols = {};
for (const name of [
"rea_mips_entry",
"rea_mips_leaf",
"rea_mips_probe",
"rea_mips_global",
"rea_mips_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 {
mips: { elfClass: 32, byteOrder, type: 2, flags, abiFlags },
symbols,
};
}
/** Independent reader is a bounded test prerequisite, never an REA provider. */
export async function inspectMipsReadelf(path, byteOrder) {
const command = process.env.REA_MIPS_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", "-A", "-s", "-W", path],
options,
);
assert.equal(
result.stderr.trim(),
"",
`readelf diagnostics: ${result.stderr}`,
);
return {
...parseMipsReadelf(result.stdout, byteOrder),
command,
version: version.stdout.split("\n")[0],
raw: result.stdout,
};
}
/** Check effective Ghidra observations, not the requested analysis profile. */
export function assertMipsLoadedImage(observations, byteOrder, sha256) {
assert.equal(observations.language_id, language(byteOrder));
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 mips-probe.S. */
export function assertMipsProbe(move, branch, byteOrder, address) {
const start = BigInt(address);
for (const [instruction, offset, word] of [
[move, 0n, 0x24821234],
[branch, 4n, 0x10800003],
]) {
assert.equal(instruction.status, "decoded");
assert.equal(BigInt(instruction.address), start + offset);
assert.equal(instruction.architecture, language(byteOrder));
assert.equal(instruction.length, 4);
assert.equal(instruction.bytes, wordHex(word, byteOrder));
}
assert.match(move.mnemonic, /^ADDIU$/iu);
assert.ok(
move.operands.some(
(operand) =>
operand.index === 2 &&
operand.components.some(
(part) =>
part.kind === "immediate" &&
part.value !== null &&
BigInt(part.value) === 0x1234n,
),
),
"ADDIU immediate was not recovered",
);
assert.match(branch.mnemonic, /^BEQZ?$/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 + 20n],
);
}
/** Four bytes must encode the known source-owned global in the declared order. */
export function assertMipsGlobal(bytes, byteOrder) {
assert.equal(bytes, wordHex(7, byteOrder));
}
@@ -0,0 +1,229 @@
import { describe, expect, it } from "vitest";
import {
assertMipsGlobal,
assertMipsLoadedImage,
assertMipsProbe,
parseMipsReadelf,
} from "./mips-checks.mjs";
// GNU readelf 2.40 output for the source-owned Clang 17 / LLD fixture.
// This tests the reader boundary, not Ghidra; the real lane rebuilds both orders.
const readelf = `ELF Header:
Magic: 7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00
Class: ELF32
Data: 2's complement, little endian
Version: 1 (current)
OS/ABI: UNIX - System V
ABI Version: 0
Type: EXEC (Executable file)
Machine: MIPS R3000
Version: 0x1
Entry point address: 0x201b0
Start of program headers: 52 (bytes into file)
Start of section headers: 2996 (bytes into file)
Flags: 0x70001001, noreorder, o32, mips32r2
Size of this header: 52 (bytes)
Size of program headers: 32 (bytes)
Number of program headers: 7
Size of section headers: 40 (bytes)
Number of section headers: 24
Section header string table index: 22
Symbol table '.symtab' contains 9 entries:
Num: Value Size Type Bind Vis Ndx Name
0: 00000000 0 NOTYPE LOCAL DEFAULT UND
1: 00000000 0 FILE LOCAL DEFAULT ABS mips.c
2: 00020254 0 NOTYPE LOCAL DEFAULT 4 .Lzero
3: 00038250 0 NOTYPE LOCAL HIDDEN 6 _gp
4: 00020170 64 FUNC GLOBAL DEFAULT 4 rea_mips_leaf
5: 00030268 4 OBJECT GLOBAL DEFAULT 7 rea_mips_global
6: 000201b0 136 FUNC GLOBAL DEFAULT 4 rea_mips_entry
7: 00010148 30 OBJECT GLOBAL DEFAULT 3 rea_mips_marker
8: 00020240 32 FUNC GLOBAL DEFAULT 4 rea_mips_probe
MIPS ABI Flags Version: 0
ISA: MIPS32r2
GPR size: 32
CPR1 size: 32
CPR2 size: 0
FP ABI: Hard float (32-bit CPU, Any FPU)
ISA Extension: None
ASEs:
None
FLAGS 1: 00000000
FLAGS 2: 00000000
`;
const sha256 = "a".repeat(64);
const image = {
language_id: "MIPS:LE:32:default",
compiler_spec_id: "default",
source_files: [{ original_sha256: sha256, modified_sha256: sha256 }],
};
const move = {
address: "0x20240",
status: "decoded",
architecture: "MIPS:LE:32:default",
length: 4,
bytes: "34128224",
mnemonic: "addiu",
operands: [
{ index: 2, components: [{ kind: "immediate", value: "0x1234" }] },
],
};
const branch = {
address: "0x20244",
status: "decoded",
architecture: "MIPS:LE:32:default",
length: 4,
bytes: "03008010",
mnemonic: "beqz",
flow: {
kind: "jump",
conditional: true,
computed: false,
direct_destinations: ["0x20254"],
},
};
describe("MIPS real-verifier independent expectations", () => {
it("reads GNU header, ABI and defined symbols without a Ghidra-derived oracle", () => {
const parsed = parseMipsReadelf(readelf, "little");
expect(parsed.mips).toMatchObject({
elfClass: 32,
byteOrder: "little",
flags: 0x70001001,
abiFlags: {
isaLevel: 32,
isaRevision: 2,
gprSize: 1,
cpr1Size: 1,
fpAbi: 5,
},
});
expect(parsed.symbols.rea_mips_probe).toBe("0x20240");
expect(
parseMipsReadelf(readelf.replace("little endian", "big endian"), "big")
.mips.byteOrder,
).toBe("big");
});
it.each([
["wrong class", "ELF32", "ELF64"],
["wrong byte order", "little endian", "big endian"],
["wrong machine", "MIPS R3000", "AArch64"],
["wrong object type", "EXEC (Executable file)", "DYN (Shared object file)"],
["wrong flags", "0x70001001", "0x60001001"],
["wrong ISA", "ISA: MIPS32r2", "ISA: MIPS32r6"],
["unknown FP ABI", "Hard float (32-bit CPU, Any FPU)", "unknown"],
["unknown register width", "GPR size: 32", "GPR size: 64"],
["missing symbol", "rea_mips_probe", "unrelated_probe"],
["missing ABI", "MIPS ABI Flags Version: 0", "ABI omitted"],
])(
"rejects %s instead of returning a guessed fixture interpretation",
(_name, from, to) => {
expect(() =>
parseMipsReadelf(readelf.replace(from, to), "little"),
).toThrow();
},
);
it("rejects ambiguous producer fields", () => {
expect(() =>
parseMipsReadelf(`${readelf}\nClass: ELF32\n`, "little"),
).toThrow(/ambiguous/u);
});
it("checks the effective loaded image, not requested profile metadata", () => {
assertMipsLoadedImage(image, "little", sha256);
expect(() =>
assertMipsLoadedImage(
{ ...image, language_id: "MIPS:BE:32:default" },
"little",
sha256,
),
).toThrow();
expect(() =>
assertMipsLoadedImage(
{ ...image, compiler_spec_id: "other" },
"little",
sha256,
),
).toThrow();
expect(() =>
assertMipsLoadedImage(
{
...image,
source_files: [
{ original_sha256: sha256, modified_sha256: "b".repeat(64) },
],
},
"little",
sha256,
),
).toThrow();
});
it("checks exact probe bytes, immediate and conditional destination in both orders", () => {
assertMipsProbe(move, branch, "little", "0x20240");
assertMipsProbe(
{ ...move, architecture: "MIPS:BE:32:default", bytes: "24821234" },
{ ...branch, architecture: "MIPS:BE:32:default", bytes: "10800003" },
"big",
"0x20240",
);
});
it("rejects plausible nonempty but incorrect instruction observations", () => {
expect(() =>
assertMipsProbe(
{ ...move, bytes: "35128224" },
branch,
"little",
"0x20240",
),
).toThrow();
expect(() =>
assertMipsProbe({ ...move, length: 2 }, branch, "little", "0x20240"),
).toThrow();
expect(() =>
assertMipsProbe(
{
...move,
operands: [
{ index: 2, components: [{ kind: "immediate", value: "0x1235" }] },
],
},
branch,
"little",
"0x20240",
),
).toThrow();
expect(() =>
assertMipsProbe(
move,
{
...branch,
flow: { ...branch.flow, direct_destinations: ["0x20250"] },
},
"little",
"0x20240",
),
).toThrow();
expect(() =>
assertMipsProbe(
move,
{ ...branch, flow: { ...branch.flow, conditional: false } },
"little",
"0x20240",
),
).toThrow();
});
it("checks all four global bytes in the declared order", () => {
assertMipsGlobal("07000000", "little");
assertMipsGlobal("00000007", "big");
expect(() => assertMipsGlobal("00000007", "little")).toThrow();
expect(() => assertMipsGlobal("0700", "little")).toThrow();
});
});
+74
View File
@@ -0,0 +1,74 @@
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 buildMipsFixture(directory, byteOrder) {
if (byteOrder !== "little" && byteOrder !== "big")
throw new Error("MIPS fixture byte order must be little or big");
const compiler = process.env.REA_MIPS_CLANG ?? "clang";
const target = byteOrder === "little" ? "mipsel-linux-gnu" : "mips-linux-gnu";
const source = fileURLToPath(new URL("../c/mips.c", import.meta.url));
const probe = fileURLToPath(new URL("./mips-probe.S", import.meta.url));
const path = join(directory, `${target}.elf`);
const args = [
`--target=${target}`,
"-march=mips32r2",
"-mabi=32",
"-mno-abicalls",
"-fno-pic",
"-fuse-ld=lld",
"-nostdlib",
"-static",
"-O0",
"-g",
"-Wl,-e,rea_mips_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);
const read16 =
byteOrder === "little"
? bytes.readUInt16LE.bind(bytes)
: bytes.readUInt16BE.bind(bytes);
const read32 =
byteOrder === "little"
? bytes.readUInt32LE.bind(bytes)
: bytes.readUInt32BE.bind(bytes);
if (
bytes.length < 52 ||
bytes.toString("hex", 0, 4) !== "7f454c46" ||
bytes[4] !== 1 ||
bytes[5] !== (byteOrder === "little" ? 1 : 2) ||
read16(16) !== 2 ||
read16(18) !== 8 ||
read32(36) !== 0x70001001
)
throw new Error(
"Compiler did not produce the declared ELF32/o32/MIPS32r2 fixture",
);
return {
path,
byte_order: byteOrder,
flags: read32(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,
};
}
+24
View File
@@ -0,0 +1,24 @@
/* Source-owned standard MIPS32 instructions with fixed, reviewable encodings.
* No target execution. The branch at +4 targets +20; its delay slot is a NOP.
*/
.set push
.set noreorder
.text
.p2align 2
.globl rea_mips_probe
.type rea_mips_probe, @function
.ent rea_mips_probe
rea_mips_probe:
addiu $2, $4, 0x1234
beq $4, $0, .Lzero
nop
jr $31
nop
.Lzero:
addiu $2, $0, 7
jr $31
nop
.end rea_mips_probe
.size rea_mips_probe, .-rea_mips_probe
.set pop
.section .note.GNU-stack,"",@progbits