feat(native): resolve RISC-V ELF initializer pointers (#12109)

This commit is contained in:
ShuaixinHuang authored and GitHub committed 2026-11-18 19:45:05 -05:00
1 parent 8d226251a7
commit af20de3509
14 files changed
+600 -147

No files matched your search

+5 -2
View File
@@ -100,8 +100,11 @@ For PIE executables and shared objects the array slots are usually zero on
disk. A slot is reported `unresolved`, never as its stored zero, when the
dynamic relocation tables use an encoding this inspection does not decode
(for example legacy Android APS1 relocations or an unsupported machine). Relative
relocations are decoded for x86-64, i386, AArch64 and 32-bit ARM. A slot is
also `unresolved` when a dynamic relocation writes only part of it, starts
relocations are decoded for x86-64, i386, AArch64, 32-bit ARM and RISC-V
(RV32/RV64). RISC-V word-sized absolute relocations also resolve defined
symbols in section tables; imported symbols remain unresolved imports. TLS
and indirect-function resolver results are not treated as function addresses.
A slot is also `unresolved` when a dynamic relocation writes only part of it, starts
inside it, or writes it more than once with different values.
Android APS2 packed REL/RELA tables are decoded through the same relocation
@@ -23,7 +23,9 @@ and tallies per-row reasons, so the limitations list stays bounded.
declaration order with a shared slot budget, and resolves each slot. Dynamic
relocation writes come from the owner,
`readElfRelocationWritesSteps` in `ElfPointerRelocations.ts`; the RELATIVE
type per machine comes from the same owner's `elfRelativeRelocationType`.
type per machine and ELF class comes from the same owner's
`elfRelativeRelocationType`. That owner also distinguishes RISC-V TLS from
other architectures' GLOB_DAT and records full COPY/TLS descriptor extents.
Section names and fallback file offsets come from an `addressRangeIndex`
built once over the section headers and searched by address.
- `ElfInitializerSymbols.ts` loads symbol tables under one total symbol
@@ -29,6 +29,9 @@ slot's location, resolved target and how that target was obtained. The
- Resolve `SHN_XINDEX` through a uniquely linked, complete `SHT_SYMTAB_SHNDX`
table. Keep actual section indices separate from raw absolute/common/reserved
markers. Unreadable extensions preserve unknowns and independent ordinary symbols.
- Select ELF relocation rules by machine and word size, including RV32/RV64
RELATIVE, RELR and word-sized absolute records. RISC-V TLS and resolver
relocations retain unknown values and their known write extents.
- Relocation coverage is per slot. A slot that a dynamic or section relocation
only partly overwrites or writes more than once is `unresolved`, and so is an
absolute relocation against an `STT_GNU_IFUNC` resolver. On 32-bit ARM the
@@ -102,6 +105,6 @@ and MCP boundary tests exercise the public workflows and Evidence output.
Executing the image or proving that a listed address runs; runtime ordering
(file order is reported); disassembling initializer bodies; PE/COFF TLS
callbacks; Android packed relocations and machines other than x86-64, i386,
AArch64 and 32-bit ARM for relocation decoding; Mach-O fixup decoding for
AArch64, 32-bit ARM and RV32/RV64 for relocation decoding; Mach-O fixup decoding for
images other than little-endian 64-bit arm64 and x86-64, and legacy
`LC_DYSYMTAB` external relocations.
@@ -12,3 +12,5 @@
- [x] Document the tool in the native initializers guide and CLI reference.
- [x] Resolve extended ELF symbol sections through a shared owner, preserving
special markers and partial facts, with CLI/MCP and real assembler controls.
- [x] Resolve RV32/RV64 pointer relocations through the shared owner, with
public CLI/MCP controls and independent Clang/LLD producer checks.
+113 -16
View File
@@ -7,6 +7,7 @@ import {
elfRelocationWidth,
readElfRelocationWritesSteps,
readElfPointerValuesSteps,
readElfPointerRelocationsSteps,
type ElfPointerWrite,
} from "./elfPointerRelocations.js";
@@ -219,21 +220,21 @@ it("returns the decoded record type, symbol index and addend with each write", (
});
it("owns the word-sized absolute relocation type per machine", () => {
expect(elfAbsoluteRelocationType(62)).toBe(1);
expect(elfAbsoluteRelocationType(3)).toBe(1);
expect(elfAbsoluteRelocationType(183)).toBe(257);
expect(elfAbsoluteRelocationType(40)).toBe(2);
expect(elfAbsoluteRelocationType(8)).toBeUndefined();
expect(elfAbsoluteRelocationType(62, 64)).toBe(1);
expect(elfAbsoluteRelocationType(3, 32)).toBe(1);
expect(elfAbsoluteRelocationType(183, 64)).toBe(257);
expect(elfAbsoluteRelocationType(40, 32)).toBe(2);
expect(elfAbsoluteRelocationType(8, 64)).toBeUndefined();
});
it("owns the COPY relocation type per machine and gives it no fixed width", () => {
expect(elfCopyRelocationType(62)).toBe(5);
expect(elfCopyRelocationType(3)).toBe(5);
expect(elfCopyRelocationType(183)).toBe(1024);
expect(elfCopyRelocationType(40)).toBe(20);
expect(elfCopyRelocationType(8)).toBeUndefined();
expect(elfRelocationWidth(62, 5)).toBeUndefined();
expect(elfRelocationWidth(183, 1024)).toBeUndefined();
expect(elfCopyRelocationType(62, 64)).toBe(5);
expect(elfCopyRelocationType(3, 32)).toBe(5);
expect(elfCopyRelocationType(183, 64)).toBe(1024);
expect(elfCopyRelocationType(40, 32)).toBe(20);
expect(elfCopyRelocationType(8, 64)).toBeUndefined();
expect(elfRelocationWidth(62, 5, 64)).toBeUndefined();
expect(elfRelocationWidth(183, 1024, 64)).toBeUndefined();
});
/**
@@ -368,6 +369,7 @@ it.each([
["AArch64 GLOB_DAT", 183, 1025, 0x4020n],
["x86-64 absolute", 62, 1, 0x4020n],
["x86-64 GLOB_DAT", 62, 6, 0x4000n],
["RISC-V RV64 absolute", 243, 2, 0x4020n],
] as const)(
"derives %s from image definitions only when requested",
(_name, machine, kind, expected) => {
@@ -542,6 +544,8 @@ it.each([
["AArch64", 183, 64, 1024],
["i386", 3, 32, 5],
["ARM", 40, 32, 20],
["RISC-V RV32", 243, 32, 4],
["RISC-V RV64", 243, 64, 4],
] as const)(
"sizes a %s COPY write from the image's own dynamic symbol",
(_name, machine, bits, kind) => {
@@ -633,10 +637,10 @@ it("reports a TLS descriptor as a two-word write", () => {
const { writes, result } = walk(symbolicImage(36n, 0n));
expect(writes).toMatchObject([{ address: 0x300n, width: 16, value: null }]);
expect(result.pointer_coverage_known).toBe(true);
expect(elfRelocationWidth(62, 36)).toBe(16);
expect(elfRelocationWidth(183, 1031)).toBe(16);
expect(elfRelocationWidth(40, 13)).toBe(8);
expect(elfRelocationWidth(3, 41)).toBe(8);
expect(elfRelocationWidth(62, 36, 64)).toBe(16);
expect(elfRelocationWidth(183, 1031, 64)).toBe(16);
expect(elfRelocationWidth(40, 13, 32)).toBe(8);
expect(elfRelocationWidth(3, 41, 32)).toBe(8);
});
/** Three fully decoded relative values; empty REL declarations add no state. */
@@ -707,3 +711,96 @@ it("refuses pointer workspace growth before inserting the next virtual destinati
inserted.mockRestore();
}
});
/** ELF32 RELA with an ordinary defined symbol and a SysV hash bound. */
const riscvSymbolicImage32 = (kind: number, symbol = 1): Buffer => {
const bytes = symbolicImage32(kind, 0x28);
bytes.writeInt32LE(7, 0); // RELA instead of REL.
bytes.writeInt32LE(8, 8);
bytes.writeUInt32LE(12, 12);
bytes.writeInt32LE(9, 16);
bytes.writeUInt32LE(12, 20);
bytes.writeUInt32LE((symbol << 8) | kind, 0x104);
bytes.writeInt32LE(-16, 0x108);
bytes.writeUInt32LE(0x4000, 0x214);
bytes[0x21c] = 0x11;
bytes.writeUInt16LE(1, 0x21e);
bytes.writeInt32LE(4, 40);
bytes.writeUInt32LE(0x280, 44);
[1, 2, 1, 0, 0].forEach((value, index) =>
bytes.writeUInt32LE(value, 0x280 + index * 4),
);
return bytes;
};
it.each([32, 64] as const)(
"keeps RV%s symbol, TLS, resolver and COPY semantics separate",
(bits) => {
const make = (kind: number, symbol = 1) =>
bits === 32
? riscvSymbolicImage32(kind, symbol)
: symbolicImage(BigInt(kind), 0x28n, {
definition: { value: 0x4000n },
addend: -16n,
symbolIndex: symbol,
});
const absolute = bits === 32 ? 1 : 2;
expect(elfAbsoluteRelocationType(243, bits)).toBe(absolute);
expect(elfCopyRelocationType(243, bits)).toBe(4);
expect(elfRelocationWidth(243, 12, bits)).toBe(bits / 4);
expect(
walk(make(absolute), undefined, 243, bits).writes[0]?.value,
).toBeNull();
expect(
walk(make(absolute), undefined, 243, bits, true).writes[0]?.value,
).toBe(0x3ff0n);
// Type 6 must never inherit x86 GLOB_DAT semantics, even for a defined symbol.
for (const [kind, width] of [
[6, 4],
[12, bits / 4],
[58, bits / 8],
]) {
const { writes, result } = walk(make(kind!), undefined, 243, bits, true);
expect(writes[0]).toMatchObject({ value: null, width });
expect(result.pointer_coverage_known).toBe(true);
}
const relative = walk(make(3, 0), undefined, 243, bits);
expect(relative.writes[0]?.value).toBe(BigInt.asUintN(bits, -16n));
const input = {
bits,
little: true,
machine: 243,
dynamicSegments: [{ offset: 0n, size: 0x100n }],
mappings: [{ address: 0n, offset: 0, size: 0x400 }],
zeroFills: [],
};
const sparse = readElfPointerRelocationsSteps(make(3, 0), input);
let sparseNext = sparse.next();
while (!sparseNext.done) sparseNext = sparse.next();
expect(sparseNext.value.pointerAt(0x300n)).toMatchObject({
value: BigInt.asUintN(bits, -16n),
relocation: { encoding: "rela", kind: 3, record_file_offset: 0x100 },
});
const values = readElfPointerValuesSteps(
make(absolute),
input,
1024 * 1024,
{
symbolResolution: "image-definitions",
},
);
let valuesNext = values.next();
while (!valuesNext.done) valuesNext = values.next();
expect(valuesNext.value.unsignedAt(0x300n, bits === 64 ? 8 : 4)).toBe(
0x3ff0n,
);
const unknown = walk(make(0x7f), "record", 243, bits, true);
expect(unknown.result.pointer_coverage_known).toBe(false);
expect(unknown.writes).toEqual([]);
},
);
it("does not apply a machine's pointer rules to a different ELF class", () => {
expect(elfAbsoluteRelocationType(183, 32)).toBeUndefined();
expect(elfAbsoluteRelocationType(40, 64)).toBeUndefined();
});
+148 -118
View File
@@ -181,7 +181,6 @@ const SYMBOL_TABLE_TAGS = new Set([DT_SYMTAB, DT_SYMENT, DT_HASH, DT_GNU_HASH]);
const malformed = (message: string): never => {
throw new ElfPointerRelocationFailure("malformed-container", message);
};
/** Bound packed input and equivalent expanded REL/RELA work before iteration. */
const ANDROID_PACKED_TABLE_BYTES = 16 * 1024 * 1024;
type PackedRelocation = {
@@ -288,133 +287,164 @@ function* androidPackedRelocations(
return malformed("Nonzero bytes follow the Android APS2 records");
}
}
const RELOCATION_KINDS = new Map([
[
183,
{
absolute: 257,
bits: 64,
relative: 1027,
copy: 1024,
widths: new Map([
[257, 8],
[258, 4],
[259, 2],
[260, 8],
[261, 4],
[262, 2],
[1025, 8],
[1026, 8],
[1028, 8],
[1029, 8],
[1030, 8],
[1031, 16],
[1032, 8],
]),
},
],
[
62,
{
absolute: 1,
bits: 64,
relative: 8,
copy: 5,
widths: new Map([
[1, 8],
[2, 4],
[6, 8],
[7, 8],
[10, 4],
[11, 4],
[16, 8],
[17, 8],
[18, 8],
[24, 8],
[36, 16],
[37, 8],
]),
},
],
[
40,
{
absolute: 2,
bits: 32,
relative: 23,
copy: 20,
widths: new Map([
[2, 4],
[3, 4],
[13, 8],
[17, 4],
[18, 4],
[19, 4],
[21, 4],
[22, 4],
[160, 4],
]),
},
],
[
3,
{
absolute: 1,
bits: 32,
relative: 8,
copy: 5,
widths: new Map([
[1, 4],
[2, 4],
[3, 4],
[4, 4],
[6, 4],
[7, 4],
[9, 4],
[10, 4],
[11, 4],
[14, 4],
[15, 4],
[16, 4],
[17, 4],
[18, 4],
[19, 4],
[20, 2],
[21, 2],
[22, 1],
[23, 1],
[35, 4],
[36, 4],
[37, 4],
[38, 4],
[41, 8],
[42, 4],
[43, 4],
]),
},
],
]);
const RELOCATION_KINDS = [
{
machine: 183,
globalData: 1025,
absolute: 257,
bits: 64,
relative: 1027,
copy: 1024,
widths: new Map([
[257, 8],
[258, 4],
[259, 2],
[260, 8],
[261, 4],
[262, 2],
[1025, 8],
[1026, 8],
[1028, 8],
[1029, 8],
[1030, 8],
[1031, 16],
[1032, 8],
]),
},
{
machine: 62,
globalData: 6,
absolute: 1,
bits: 64,
relative: 8,
copy: 5,
widths: new Map([
[1, 8],
[2, 4],
[6, 8],
[7, 8],
[10, 4],
[11, 4],
[16, 8],
[17, 8],
[18, 8],
[24, 8],
[36, 16],
[37, 8],
]),
},
{
machine: 40,
globalData: 21,
absolute: 2,
bits: 32,
relative: 23,
copy: 20,
widths: new Map([
[2, 4],
[3, 4],
[13, 8],
[17, 4],
[18, 4],
[19, 4],
[21, 4],
[22, 4],
[160, 4],
]),
},
{
machine: 3,
globalData: 6,
absolute: 1,
bits: 32,
relative: 8,
copy: 5,
widths: new Map([
[1, 4],
[2, 4],
[3, 4],
[4, 4],
[6, 4],
[7, 4],
[9, 4],
[10, 4],
[11, 4],
[14, 4],
[15, 4],
[16, 4],
[17, 4],
[18, 4],
[19, 4],
[20, 2],
[21, 2],
[22, 1],
[23, 1],
[35, 4],
[36, 4],
[37, 4],
[38, 4],
[41, 8],
[42, 4],
[43, 4],
]),
},
...([32, 64] as const).map((bits) => ({
machine: 243, // EM_RISCV: its pointer relocation kinds depend on ELF class.
bits,
absolute: bits === 64 ? 2 : 1,
relative: 3,
copy: 4,
// RISC-V has no GLOB_DAT. In particular, type 6 is TLS_DTPMOD32.
globalData: null,
widths: new Map([
[1, 4], // R_RISCV_32
[2, 8], // R_RISCV_64
[5, bits / 8], // JUMP_SLOT
[6, 4],
[7, 8], // TLS_DTPMOD32/64
[8, 4],
[9, 8], // TLS_DTPREL32/64
[10, 4],
[11, 8], // TLS_TPREL32/64
[12, bits / 4], // TLSDESC: two pointer words
[18, 8],
[19, 8], // CALL/CALL_PLT: two instructions
[57, 4], // 32_PCREL
[58, bits / 8], // IRELATIVE: resolver result is unknown
]),
})),
];
const relocationKinds = (machine: number, bits: 32 | 64) =>
RELOCATION_KINDS.find(
(kinds) => kinds.machine === machine && kinds.bits === bits,
);
/** R_*_RELATIVE type for a supported ELF machine, or undefined when unsupported. */
export const elfRelativeRelocationType = (
machine: number,
): number | undefined => RELOCATION_KINDS.get(machine)?.relative;
bits: 32 | 64,
): number | undefined => relocationKinds(machine, bits)?.relative;
/** Word-sized absolute (S + A) relocation type for a supported ELF machine. */
export const elfAbsoluteRelocationType = (
machine: number,
): number | undefined => RELOCATION_KINDS.get(machine)?.absolute;
bits: 32 | 64,
): number | undefined => relocationKinds(machine, bits)?.absolute;
/** COPY relocation type, whose write is as wide as its symbol's `st_size`. */
export const elfCopyRelocationType = (machine: number): number | undefined =>
RELOCATION_KINDS.get(machine)?.copy;
export const elfCopyRelocationType = (
machine: number,
bits: 32 | 64,
): number | undefined => relocationKinds(machine, bits)?.copy;
/** Bytes written by a relocation; type zero is a no-op and unknown types remain undefined. */
export const elfRelocationWidth = (
machine: number,
type: number,
bits: 32 | 64,
): number | undefined =>
type === 0 ? 0 : RELOCATION_KINDS.get(machine)?.widths.get(type);
type === 0 ? 0 : relocationKinds(machine, bits)?.widths.get(type);
type DynamicTags = {
readonly values: ReadonlyMap<bigint, bigint>;
@@ -514,14 +544,15 @@ export function* readElfRelocationWritesSteps(
input: ElfPointerRelocationInput,
options: RelocationOptions = {},
): Generator<ElfPointerWrite | undefined, ElfRelocationStreamResult> {
const kinds = RELOCATION_KINDS.get(input.machine);
if (kinds === undefined || kinds.bits !== input.bits)
const kinds = relocationKinds(input.machine, input.bits);
if (kinds === undefined)
throw new ElfPointerRelocationFailure(
"unsupported-container",
"ELF relative pointers require a matching AArch64, x86-64, ARM or i386 image",
"ELF relative pointers require a matching AArch64, x86-64, ARM, i386 or RISC-V image",
);
const relative = kinds.relative;
const absolute = kinds.absolute;
const globalData = kinds.globalData;
const wholeExtents = options.wholeExtents === true;
const copy = wholeExtents ? kinds.copy : undefined;
const unknownWidths = kinds.widths;
@@ -723,7 +754,7 @@ export function* readElfRelocationWritesSteps(
source: ElfPointerRelocationSource,
): Generator<ElfPointerWrite | undefined> {
const { type: kind, offset: destination, symbolIndex } = parsed;
if (elfRelocationWidth(input.machine, kind) === 0) return;
if (elfRelocationWidth(input.machine, kind, input.bits) === 0) return;
const explicitAddend = parsed.addend;
if (source.encoding === "rela" && explicitAddend === undefined)
return malformed("RELA relocation has no decoded addend");
@@ -747,10 +778,9 @@ export function* readElfRelocationWritesSteps(
return;
}
if (kind !== relative || symbolIndex !== 0) {
const globalData = input.machine === 183 ? 1025 : 6;
if (
options.symbolResolution === "image-definitions" &&
input.bits === 64 &&
(input.bits === 64 || input.machine === 243) &&
(kind === absolute || kind === globalData)
) {
const value = yield* symbolLinkValue(symbolIndex);
@@ -60,6 +60,8 @@ export interface SlotRelocation {
const STT_FUNC = 2;
const STT_SECTION = 3;
const STT_FILE = 4;
/** `st_value` is an offset in thread-local storage. */
const STT_TLS = 6;
/** `st_value` is a resolver; the loader writes whatever the resolver returns. */
const STT_GNU_IFUNC = 10;
@@ -292,7 +294,12 @@ export const loadElfSymbolIndex = (
(symbol.section.kind !== "section" && symbol.section.kind !== "absolute")
)
return;
if (symbol.type === STT_SECTION || symbol.type === STT_FILE) return;
if (
symbol.type === STT_SECTION ||
symbol.type === STT_FILE ||
symbol.type === STT_TLS
)
return;
const func = symbol.type === STT_FUNC;
rank(ranked, symbol.value, symbol.name, func);
if (symbol.section.kind === "section")
@@ -375,8 +382,8 @@ export const relocationFromEntry = (
symbols: readonly ElfInitializerSymbol[] | undefined,
inplace: bigint | null,
): SlotRelocation => {
const relative = elfRelativeRelocationType(facts.machine);
const absolute = elfAbsoluteRelocationType(facts.machine);
const relative = elfRelativeRelocationType(facts.machine, facts.bits);
const absolute = elfAbsoluteRelocationType(facts.machine, facts.bits);
if (entry.type === relative && entry.symbolIndex === 0) {
const addend = addendOf(entry, inplace);
if (addend === null) return unresolved();
@@ -400,6 +407,7 @@ export const relocationFromEntry = (
if (
(symbol.section.kind !== "section" && symbol.section.kind !== "absolute") ||
entry.type !== absolute ||
symbol.type === STT_TLS ||
symbol.type === STT_GNU_IFUNC
)
return unresolved();
@@ -572,8 +580,8 @@ export const sectionRelocations = async (
};
// One budget across every header, so many headers over one range cannot multiply the work.
let budget = SECTION_RELOCATION_RECORD_SCAN;
const relative = elfRelativeRelocationType(input.machine);
const copy = elfCopyRelocationType(input.machine);
const relative = elfRelativeRelocationType(input.machine, input.bits);
const copy = elfCopyRelocationType(input.machine, input.bits);
// Slot visits grow with each COPY span, so the spans together are limited to
// the file size, as in the dynamic walk.
let copyAllowance = input.bytes.length;
@@ -665,7 +673,7 @@ export const sectionRelocations = async (
copied ??
(parsed.value.type === relative
? word
: elfRelocationWidth(input.machine, parsed.value.type));
: elfRelocationWidth(input.machine, parsed.value.type, input.bits));
// An unknown type is assumed to write a whole word, so it still marks what it may touch.
const span = extent ?? word;
if (span === 0) continue;
+1 -1
View File
@@ -736,7 +736,7 @@ const fromDynamicWrite = (
importName: null,
definedName: null,
};
const relative = elfRelativeRelocationType(scan.machine);
const relative = elfRelativeRelocationType(scan.machine, scan.bits);
if (write.value !== null && write.source.kind === relative)
return {
method: "relative_addend",
@@ -1,5 +1,6 @@
import { describe, expect, it, onTestFinished, vi } from "vitest";
import { deflateSync } from "node:zlib";
import { riscvInitializers } from "./RiscvInitializers.fixture.js";
import { readNativeInitializers } from "./NativeInitializersProvider.js";
/** Pass-through spies on the shared mapping module, so tests can count lookups made from other modules. */
@@ -560,7 +561,7 @@ describe("ELF section content admission", () => {
describe("ELF incomplete inputs", () => {
it("reports an unsupported relocation machine as incomplete, not as raw zeros", async () => {
const bytes = elf64PieInitializers();
bytes.writeUInt16LE(243, 18);
bytes.writeUInt16LE(21, 18); // EM_PPC64 remains unsupported by the pointer decoder.
const report = await read(bytes);
expect(report.status).toBe("incomplete");
expect(report.coverage.total_entries).toBeNull();
@@ -1822,6 +1823,29 @@ it("reports an object-file import name over the name budget as partial coverage"
});
describe("Initializer target semantics", () => {
it.each([32, 64] as const)(
"does not interpret a defined RV%s TLS offset as an initializer address or name",
async (bits) => {
const report = await read(
riscvInitializers(bits, { definedSymbolIsTls: true }),
);
const slots = report.entries.filter(
(entry) => entry.kind === "init_array",
);
expect(slots).toHaveLength(3);
expect(slots[0]).toMatchObject({
resolution: "relative_addend",
value_va: "0x100",
symbol: null,
});
expect(slots[1]).toMatchObject({
resolution: "unresolved",
value_va: null,
symbol: null,
});
},
);
it("keeps an absolute relocation against an IFUNC symbol unresolved", async () => {
const bytes = elfRelocatableCtors();
// `ctor` becomes a global STT_GNU_IFUNC, whose value is its resolver.
@@ -0,0 +1,135 @@
/** Inert RV32/RV64 ELF with RELA constructors and a RELR finalizer. */
export const riscvInitializers = (
bits: 32 | 64,
{
definedSymbolIsTls = false,
}: { readonly definedSymbolIsTls?: boolean } = {},
): Buffer => {
const bytes = Buffer.alloc(0xc00);
const word = bits / 8;
const wide = bits === 64;
const put = (at: number, value: number): void => {
if (wide) bytes.writeBigUInt64LE(BigInt(value), at);
else bytes.writeUInt32LE(value, at);
};
bytes.set([0x7f, 0x45, 0x4c, 0x46, wide ? 2 : 1, 1, 1]);
bytes.writeUInt16LE(3, 16);
bytes.writeUInt16LE(243, 18);
bytes.writeUInt32LE(1, 20);
put(wide ? 32 : 28, wide ? 64 : 52);
put(wide ? 40 : 32, 0x800);
for (const [at, value] of [
[wide ? 52 : 40, wide ? 64 : 52],
[wide ? 54 : 42, wide ? 56 : 32],
[wide ? 56 : 44, 2],
[wide ? 58 : 46, wide ? 64 : 40],
[wide ? 60 : 48, 9],
[wide ? 62 : 50, 8],
] as const)
bytes.writeUInt16LE(value, at);
const tags = [
[25, 0x200],
[27, 3 * word], // INIT_ARRAY/SZ
[26, 0x200 + 3 * word],
[28, word], // FINI_ARRAY/SZ
[7, 0x400],
[8, 9 * word],
[9, 3 * word], // RELA/SZ/ENT
[36, 0x500],
[35, word],
[37, word], // RELR/SZ/ENT
[6, 0x600],
[11, wide ? 24 : 16],
[5, 0x680],
[10, 26],
[0, 0],
];
for (let index = 0; index < 2; index += 1) {
const at = (wide ? 64 : 52) + index * (wide ? 56 : 32);
bytes.writeUInt32LE(index === 0 ? 1 : 2, at);
if (wide) bytes.writeUInt32LE(index === 0 ? 7 : 6, at + 4);
put(at + (wide ? 8 : 4), index === 0 ? 0 : 0x300);
put(at + (wide ? 16 : 8), index === 0 ? 0 : 0x300);
put(at + (wide ? 24 : 12), index === 0 ? 0 : 0x300);
put(
at + (wide ? 32 : 16),
index === 0 ? bytes.length : tags.length * word * 2,
);
put(
at + (wide ? 40 : 20),
index === 0 ? bytes.length : tags.length * word * 2,
);
if (!wide) bytes.writeUInt32LE(index === 0 ? 7 : 6, at + 24);
put(at + (wide ? 48 : 28), word);
}
bytes.writeUInt32LE(0x8067, 0x100); // jalr zero, 0(ra); never executed.
put(0x200 + 3 * word, 0x100);
tags.forEach(([tag, value], index) => {
put(0x300 + index * word * 2, tag!);
put(0x300 + index * word * 2 + word, value!);
});
const relocations = [
[0x200, 0, 3, 0x100], // RELATIVE
[0x200 + word, 1, wide ? 2 : 1, 0], // Defined absolute
[0x200 + 2 * word, 2, wide ? 2 : 1, 0], // Imported absolute
] as const;
relocations.forEach(([offset, symbol, kind, addend], index) => {
const at = 0x400 + index * 3 * word;
put(at, offset);
if (wide)
bytes.writeBigUInt64LE((BigInt(symbol) << 32n) | BigInt(kind), at + word);
else bytes.writeUInt32LE((symbol << 8) | kind, at + word);
put(at + 2 * word, addend);
});
put(0x500, 0x200 + 3 * word);
const symbolSize = wide ? 24 : 16;
for (let index = 1; index <= 2; index += 1) {
const at = 0x600 + index * symbolSize;
bytes.writeUInt32LE(index === 1 ? 1 : 12, at);
bytes[at + (wide ? 4 : 12)] =
index === 1 && definedSymbolIsTls ? 0x16 : 0x12;
bytes.writeUInt16LE(index === 1 ? 1 : 0, at + (wide ? 6 : 14));
put(at + (wide ? 8 : 4), index === 1 ? 0x100 : 0);
}
const strings = Buffer.from("\0local_ctor\0external_ctor\0");
strings.copy(bytes, 0x680);
const names = [
"",
".text",
".init_array",
".fini_array",
".dynamic",
".rela.dyn",
".dynsym",
".dynstr",
".shstrtab",
];
const shstr = Buffer.from(`${names.join("\0")}\0`);
shstr.copy(bytes, 0x700);
const sections = [
[1, 6, 0x100, 4, 0, 0],
[14, 3, 0x200, 3 * word, 0, word],
[15, 3, 0x200 + 3 * word, word, 0, word],
[6, 3, 0x300, tags.length * 2 * word, 7, 2 * word],
[4, 2, 0x400, 9 * word, 6, 3 * word],
[11, 2, 0x600, 3 * symbolSize, 7, symbolSize],
[3, 2, 0x680, strings.length, 0, 0],
[3, 0, 0x700, shstr.length, 0, 0],
];
let nameOffset = 1;
sections.forEach(([type, flags, offset, size, link, entry], index) => {
const at = 0x800 + (index + 1) * (wide ? 64 : 40);
bytes.writeUInt32LE(nameOffset, at);
bytes.writeUInt32LE(type!, at + 4);
put(at + 8, flags!);
put(at + (wide ? 16 : 12), flags === 0 ? 0 : offset!);
put(at + (wide ? 24 : 16), offset!);
put(at + (wide ? 32 : 20), size!);
bytes.writeUInt32LE(link!, at + (wide ? 40 : 24));
bytes.writeUInt32LE(index === 5 ? 1 : 0, at + (wide ? 44 : 28));
put(at + (wide ? 48 : 32), word);
put(at + (wide ? 56 : 36), entry!);
nameOffset += names[index + 1]!.length + 1;
});
return bytes;
};
@@ -0,0 +1,91 @@
import { createHash } from "node:crypto";
import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect } from "vitest";
import { BINARY_DIAGNOSTICS_TOOL_CONTRACTS } from "../../src/contracts/native/binaryDiagnosticsToolContracts.js";
import { riscvInitializers } from "../../src/native/initializers/RiscvInitializers.fixture.js";
import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js";
import { cliTest } from "../support/cli/cliFixture.js";
const contract = BINARY_DIAGNOSTICS_TOOL_CONTRACTS.find(
(candidate) => candidate.name === "inspect_native_initializers",
);
if (contract === undefined)
throw new Error("Missing native initializer contract");
cliTest(
"recovers RV32/RV64 constructors through CLI and stdio MCP without running the image",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-riscv-initializers-");
const call = await cli.sharedMcpCall!();
for (const bits of [32, 64] as const) {
const path = join(root, `rv${bits}.so`);
const bytes = riscvInitializers(bits);
await writeFile(path, bytes);
const result = await cli.run({
arguments: ["inspect-native-initializers", path, "--json"],
});
expect(result.exitCode, result.stderr).toBe(0);
const response = await call("inspect_native_initializers", { path });
expect(response.isError, JSON.stringify(response.content)).not.toBe(true);
for (const value of [result.json, response.structuredContent]) {
const evidence = contract.outputSchema.parse(value);
const report = evidence.normalized_result;
expect(report).toMatchObject({
status: "parsed",
architecture: "riscv",
bits,
coverage: {
status: "complete",
examined_entries: 4,
returned_entries: 4,
},
artifact: {
path,
bytes: bytes.length,
sha256: createHash("sha256").update(bytes).digest("hex"),
},
});
expect(
report.entries.map((entry) => [
entry.kind,
entry.value_va,
entry.resolution,
entry.symbol?.name,
]),
).toEqual([
["init_array", "0x100", "relative_addend", "local_ctor"],
["init_array", "0x100", "symbol_addend", "local_ctor"],
["init_array", null, "unresolved_import", "external_ctor"],
["fini_array", "0x100", "relr", "local_ctor"],
]);
expect(evidence.subject).toMatchObject({
local_path: path,
identity: { sha256: report.artifact.sha256 },
});
}
expect((await readFile(path)).equals(bytes)).toBe(true);
// Unknown or differently sized writes must not expose the stored zero.
for (const kind of [0x7f, bits === 64 ? 1 : 2]) {
const unknown = Buffer.from(bytes);
if (bits === 64) unknown.writeBigUInt64LE(BigInt(kind), 0x408);
else unknown.writeUInt32LE(kind, 0x404);
const unknownPath = join(root, `rv${bits}-unknown-${kind}.so`);
await writeFile(unknownPath, unknown);
const refused = await call("inspect_native_initializers", {
path: unknownPath,
});
expect(refused.isError).not.toBe(true);
const report = contract.outputSchema.parse(
refused.structuredContent,
).normalized_result;
expect(report.status).toBe("incomplete");
expect(report.entries[0]).toMatchObject({
value_va: null,
resolution: "unresolved",
});
expect((await readFile(unknownPath)).equals(unknown)).toBe(true);
}
}
},
);
@@ -1123,7 +1123,7 @@ it.each(["outside", "misaligned", "duplicate"] as const)(
it.each([
[{ dynamic: false }, "unsupported-container"],
[{ machine: 243 }, "unsupported-container"],
[{ machine: 21 }, "unsupported-container"], // EM_PPC64 has no pointer profile.
[{ androidPacked: "aps1" }, "unsupported-pointer-encoding"],
] as const)(
"refuses ELF relocations it cannot apply (%o)",
+50
View File
@@ -0,0 +1,50 @@
# RISC-V initializer producer control
`witness.c` is cross-compiled for inspection only. Do not load or execute the
resulting objects or shared libraries. Portable CLI/MCP tests use the synthetic
`RiscvInitializers.fixture.ts`; this independent producer checks the ABI facts
behind those tests without requiring a compiler in CI.
From the repository root, select Clang and LLD and create an owned output directory:
```sh
CLANG=clang-19
LD_LLD=ld.lld-19
out=$(mktemp -d)
npm run build:cached
for bits in 32 64; do
if [ "$bits" = 32 ]; then abi=ilp32d; else abi=lp64d; fi
"$CLANG" --target=riscv${bits}-linux-gnu -march=rv${bits}gc -mabi="$abi" \
-nostdlib -ffreestanding -fPIC -c tests/fixtures/riscv-initializers/witness.c \
-o "$out/rv${bits}.o"
"$LD_LLD" -shared --hash-style=both "$out/rv${bits}.o" -o "$out/rv${bits}-rela.so"
"$LD_LLD" -shared --hash-style=both -z pack-relative-relocs \
"$out/rv${bits}.o" -o "$out/rv${bits}-relr.so"
for file in "$out/rv${bits}.o" "$out/rv${bits}-rela.so" "$out/rv${bits}-relr.so"; do
readelf -rW -sW "$file"
node scripts/rea.mjs inspect-native-initializers "$file" --json
done
done
```
Executed with Debian Clang/LLD 19.1.7 and GNU readelf 2.44 on Linux x86-64.
All six files reported four entries: two constructors and a finalizer matched
the producer's `local_ctor`/`defined_ctor` symbol coordinates; `external_ctor`
remained an unresolved import. Input SHA-256 values were unchanged after inspection.
The shared objects used `R_RISCV_RELATIVE` and `R_RISCV_32`/`R_RISCV_64`, or
RELR plus the absolute records. The ET_REL objects used section-relative
absolute records. Before the change, both shared-object encodings on both
word sizes returned four unknown addresses and incomplete coverage.
Expected resolutions in file order:
| Input | Constructors | Finalizer |
| ------------------ | ------------------------------------------------- | --------------- |
| ET_REL | symbol addend, symbol addend, unresolved import | symbol addend |
| RELA shared object | relative addend, symbol addend, unresolved import | relative addend |
| RELR shared object | RELR, symbol addend, unresolved import | RELR |
This control does not establish behavior on a RISC-V host or in a dynamic
loader, nor does it verify that a listed address executes. TLS and indirect
resolver non-resolution, COPY extents and unknown kinds have separate source
tests; these six producer files do not exercise those relocation types.
+8
View File
@@ -0,0 +1,8 @@
/* Cross-compiled for inspection only; never load or execute these images. */
static void local_ctor(void) {}
void defined_ctor(void) {}
extern void external_ctor(void);
__attribute__((section(".init_array"), used))
void (*constructors[])(void) = {local_ctor, defined_ctor, external_ctor};
__attribute__((section(".fini_array"), used))
void (*finalizers[])(void) = {local_ctor};