fix(elf): establish direct initializer slot mappings (#13452)

This commit is contained in:
morluto authored and GitHub committed 2026-11-22 15:57:43 +00:00
1 parent edbb844e6b
commit bb81b0a88d
6 files changed
+90 -58

No files matched your search

+4 -3
View File
@@ -62,9 +62,10 @@ Each `entries[]` item reports:
- `slot_va`, `slot_file_offset`, `slot_bytes` and `slot_section`: where the
pointer or offset is stored. For a universal Mach-O, file offsets are
relative to the whole file, not the slice. For `init` and `fini` the slot is
the `DT_INIT` / `DT_FINI` value field in the dynamic section. When that field
is outside every load segment, `slot_va` and `slot_section` are null and a
limitation says so.
the `DT_INIT` / `DT_FINI` value field in the dynamic section. The virtual
slot uses the address declared by `PT_DYNAMIC` when the entire field maps to
those file bytes. Otherwise `slot_va` and `slot_section` are null, a limitation
explains the missing mapping, and the original file field stays available.
- `value_va`, `value_file_offset` and `section`: the resolved target address,
its file offset and its containing section. These are null when the value
was not established. In a linked ELF, file offsets come only from `PT_LOAD`:
+2 -1
View File
@@ -188,10 +188,11 @@ export type ImageSection = {
}
);
/** Declared PT_DYNAMIC file extent, before consumer-specific admission. */
/** Declared PT_DYNAMIC location, before consumer-specific admission. */
export interface ElfDynamicSegment {
readonly offset: bigint;
readonly size: bigint;
readonly virtual_address: bigint;
}
/** Native container facts, without language metadata search policy. */
+4 -1
View File
@@ -123,7 +123,10 @@ export interface ElfPointerRelocationInput {
readonly bits: 32 | 64;
readonly little: boolean;
readonly machine: number;
readonly dynamicSegments: readonly ElfDynamicSegment[];
readonly dynamicSegments: readonly Pick<
ElfDynamicSegment,
"offset" | "size"
>[];
readonly mappings: readonly FileMapping[];
readonly zeroFills: readonly ZeroFillMapping[];
}
@@ -221,6 +221,7 @@ export function* readElfSectionDirectory(
header_offset,
offset: program.offset,
size: program.fileSize,
virtual_address: program.virtualAddress,
});
else if (type === ELF_PT_NOTE)
programDeclarations.push({ type: ELF_PT_NOTE, ...span });
+15 -27
View File
@@ -35,7 +35,7 @@ import {
BinaryReader,
BinaryResourceFailure,
createFileMappingIndex,
mappedFileOffset,
type ElfDynamicSegment,
type FileMappingIndex,
} from "../../domain/binaryContainer.js";
import {
@@ -97,6 +97,7 @@ const EM_ARM = 40;
interface DynTag {
readonly value: bigint;
readonly valueOffset: number;
readonly valueAddress: bigint;
}
interface ArraySlot extends ElfInitializerSlot {
@@ -160,7 +161,7 @@ const isSentinel = (value: bigint, bits: 32 | 64): boolean =>
/** Read the consumed DT_* tags. The first duplicate wins. A missing DT_NULL leaves coverage unknown. */
const readDynamicTags = (
scan: ElfScan,
segment: { readonly offset: bigint; readonly size: bigint } | undefined,
segment: ElfDynamicSegment | undefined,
extra: number,
): Map<bigint, DynTag> => {
const tags = new Map<bigint, DynTag>();
@@ -202,9 +203,11 @@ const readDynamicTags = (
);
continue;
}
const valueOffset = at + wordOf(scan.bits);
tags.set(parsed.value.tag, {
value: parsed.value.value,
valueOffset: at + wordOf(scan.bits),
valueOffset,
valueAddress: segment.virtual_address + BigInt(valueOffset - start),
});
}
if (!terminated)
@@ -240,22 +243,6 @@ const fileOffsetFor = (
const AMBIGUOUS_MAPPING =
"An address has ambiguous file mappings (overlapping load segments with different file offsets, or file and zero-fill memory), so its file offset is not reported.";
const vaForFile = (
mappings: Parameters<typeof mappedFileOffset>[0],
fileOffset: number,
): bigint | null => {
for (const mapping of mappings) {
if (
fileOffset < mapping.offset ||
fileOffset >= mapping.offset + mapping.size
)
continue;
return mapping.address + BigInt(fileOffset - mapping.offset);
}
return null;
};
/** Section-name labels, independent of load-address translation. */
interface ElfSectionIndex {
/** Name of the smallest SHF_ALLOC section containing `address`; earlier headers win ties. */
readonly nameAt: (address: bigint) => string | null;
@@ -481,19 +468,22 @@ const directSource = (
scan: ElfScan,
tags: ReadonlyMap<bigint, DynTag>,
index: ElfSectionIndex,
mappings: Parameters<typeof mappedFileOffset>[0],
locate: (address: bigint) => number | null,
tag: bigint,
kind: NativeInitializerKind,
detail: string,
): Source | null => {
const entry = tags.get(tag);
if (entry === undefined) return null;
const va = vaForFile(mappings, entry.valueOffset);
// DT_INIT / DT_FINI store the target, not a slot pointer, so an unmapped field has no slot address.
const va =
locate(entry.valueAddress) === entry.valueOffset
? entry.valueAddress
: null;
// The actual file field still supplies the value even when its declared virtual slot is unproven.
if (va === null)
note(
scan,
`${detail} value field is not inside a load segment.`,
`${detail} value field is not fully file-backed at its declared PT_DYNAMIC address.`,
"unknown",
);
return {
@@ -543,7 +533,6 @@ const collectSources = (
tags: ReadonlyMap<bigint, DynTag>,
sections: readonly NativeSection[],
index: ElfSectionIndex,
mappings: Parameters<typeof mappedFileOffset>[0],
locate: (address: bigint) => number | null,
namesKnown: boolean,
): Source[] => {
@@ -554,7 +543,7 @@ const collectSources = (
scan,
tags,
index,
mappings,
locate,
DT_INIT,
"init",
"DT_INIT",
@@ -563,7 +552,7 @@ const collectSources = (
scan,
tags,
index,
mappings,
locate,
DT_FINI,
"fini",
"DT_FINI",
@@ -1030,7 +1019,6 @@ export const readElfInitializers = async (
tags,
directory.sections,
index,
image.mappings,
locate,
namesKnown,
);
@@ -44,7 +44,6 @@ vi.mock("../../domain/binaryContainer.js", async (importOriginal) => {
const sectionReads = vi.hoisted(() => ({
count: 0,
budget: Infinity,
directories: 0,
}));
vi.mock(
"../../domain/native/nativeSectionDirectory.js",
@@ -58,7 +57,6 @@ vi.mock(
readElfDirectoryFromBuffer: (
...args: Parameters<typeof actual.readElfDirectoryFromBuffer>
) => {
sectionReads.directories += 1;
const directory = actual.readElfDirectoryFromBuffer(...args);
return {
...directory,
@@ -147,13 +145,6 @@ it.each([
},
);
it("uses one ELF directory for initializer mappings and section facts", async () => {
sectionReads.directories = 0;
const report = await read(elf64PieInitializers());
expect(report.entries.length).toBeGreaterThan(0);
expect(sectionReads.directories).toBe(1);
});
it("preserves a real mapping to file offset zero instead of treating zero as missing", async () => {
const bytes = elfUnmappedInitializerTargets({ type: 3 });
bytes.writeBigUInt64LE(0n, 64 + 16);
@@ -408,25 +399,72 @@ describe("ELF slot semantics", () => {
);
});
it("reports no slot address for DT_INIT and DT_FINI fields outside every load segment", async () => {
it.each([
{ extent: 0x300n, address: 0x300n, field: "outside every load" },
{ extent: 0x30cn, address: 0x300n, field: "only partly file-backed" },
{
extent: 0xc00n,
address: 0x400n,
field: "mapped to different file bytes",
},
])(
"preserves raw dynamic values with no slot address when the field is $field",
async ({ extent, address }) => {
const bytes = elf64PieInitializers();
bytes.writeBigUInt64LE(extent, 64 + 32);
bytes.writeBigUInt64LE(extent, 64 + 40);
bytes.writeBigUInt64LE(address, 120 + 16);
bytes.writeBigUInt64LE(address, 120 + 24);
const report = await read(bytes);
const direct = report.entries.filter(
(entry) => entry.kind === "init" || entry.kind === "fini",
);
expect(
direct.map(({ kind, slot_va, slot_section, value_va }) => [
kind,
slot_va,
slot_section,
value_va,
]),
).toEqual([
["init", null, null, "0x100"],
["fini", null, null, "0x120"],
]);
expect(direct[0]).toMatchObject({
slot_file_offset: 0x308,
slot_bytes: 8,
value_file_offset: 0x100,
});
expect(report.coverage.status).toBe("unknown");
expect(report.limitations).toEqual(
expect.arrayContaining([
"DT_INIT value field is not fully file-backed at its declared PT_DYNAMIC address.",
"DT_FINI value field is not fully file-backed at its declared PT_DYNAMIC address.",
]),
);
},
);
it("uses PT_DYNAMIC's virtual address when the file bytes have a second load address", async () => {
const bytes = elf64PieInitializers();
// Shrink the only PT_LOAD so PT_DYNAMIC (file offset 0x300) is no longer mapped.
bytes.writeBigUInt64LE(0x300n, 64 + 32);
bytes.writeBigUInt64LE(0x300n, 64 + 40);
const dynamicHeader = 120;
const aliasHeader = 176;
const declaredAddress = 0x2300n;
bytes.copy(bytes, aliasHeader, dynamicHeader, dynamicHeader + 56);
bytes.writeUInt16LE(3, 56);
bytes.writeUInt32LE(1, aliasHeader);
for (const header of [dynamicHeader, aliasHeader]) {
bytes.writeBigUInt64LE(declaredAddress, header + 16);
bytes.writeBigUInt64LE(declaredAddress, header + 24);
}
const report = await read(bytes);
const direct = report.entries.filter(
(entry) => entry.kind === "init" || entry.kind === "fini",
);
expect(direct).toHaveLength(2);
for (const entry of direct)
expect(entry).toMatchObject({ slot_va: null, slot_section: null });
expect(direct.map((entry) => entry.value_va)).toEqual(["0x100", "0x120"]);
expect(report.limitations).toEqual(
expect.arrayContaining([
"DT_INIT value field is not inside a load segment.",
"DT_FINI value field is not inside a load segment.",
]),
);
expect(report.entries.find(({ kind }) => kind === "init")).toMatchObject({
slot_va: "0x2308",
slot_file_offset: 0x308,
slot_bytes: 8,
value_va: "0x100",
value_file_offset: 0x100,
});
});
const sectionlessElf = (directOnly: boolean): Buffer => {