fix(elf): retain mapped leading GNU symbol version slots (#12685)

* fix(elf): retain mapped leading GNU symbol version slots

* fix(elf): report short version tables during admission
This commit is contained in:
morluto authored and GitHub committed 2026-11-20 02:19:55 +00:00
1 parent ed96765d11
commit ea26a4a46c
4 files changed
+211 -20

No files matched your search

+4
View File
@@ -59,6 +59,10 @@ out of the derived set. `version_definitions` summarizes the image's own
each import keeps its version index, hidden bit, and a resolved
`library@version` when a matching verneed record exists. Index 0 and 1 stay
`unversioned`. A missing matching record is `unknown` and is an issue.
For `DT_VERSYM`, the reader keeps the contiguous prefix of complete slots
that share one unambiguous file translation. It stops at the first slot that
cannot be admitted, even if later slots map independently. Later import
versions remain unexamined and coverage is `partial`.
A missing `PT_DYNAMIC` is an observed empty load-time dependency inventory. It
is not proof another overlay or container carried dynamic linking metadata.
+28 -4
View File
@@ -120,8 +120,12 @@ export interface ElfDependencyFixtureOptions {
readonly sectionEntrySizes?: Readonly<Record<string, number>>;
/** Leaves DT_SYMENT out of the dynamic table. */
readonly omitSymentTag?: boolean;
/** Leaves DT_SYMTAB out of the dynamic table. */
readonly omitSymtabTag?: boolean;
/** Splits the identity PT_LOAD in two halfway through the .hash table. */
readonly splitLoadAtHash?: boolean;
/** Adds a one-byte zero-fill load alias at this offset into .gnu.version. */
readonly versymZeroFillOffset?: number;
}
const defaultNeeded = (): string[] => [
@@ -325,6 +329,7 @@ const writeProgramHeader = (
size: number,
align: number,
vaddr = offset,
memorySize = size,
): void => {
write32(bytes, at, type, little);
if (bits === 64) {
@@ -333,7 +338,7 @@ const writeProgramHeader = (
writeWord(bytes, at + 16, vaddr, bits, little);
writeWord(bytes, at + 24, vaddr, bits, little);
writeWord(bytes, at + 32, size, bits, little);
writeWord(bytes, at + 40, size, bits, little);
writeWord(bytes, at + 40, memorySize, bits, little);
writeWord(bytes, at + 48, align, bits, little);
return;
}
@@ -341,7 +346,7 @@ const writeProgramHeader = (
writeWord(bytes, at + 8, vaddr, bits, little);
writeWord(bytes, at + 12, vaddr, bits, little);
writeWord(bytes, at + 16, size, bits, little);
writeWord(bytes, at + 20, size, bits, little);
writeWord(bytes, at + 20, memorySize, bits, little);
write32(bytes, at + 24, flags, little);
writeWord(bytes, at + 28, align, bits, little);
};
@@ -408,7 +413,9 @@ interface FixtureConfig {
readonly sectionSizes: Readonly<Record<string, number>>;
readonly sectionEntrySizes: Readonly<Record<string, number>>;
readonly omitSymentTag: boolean;
readonly omitSymtabTag: boolean;
readonly splitLoadAtHash: boolean;
readonly versymZeroFillOffset: number | undefined;
}
interface DependencyTables {
@@ -505,7 +512,9 @@ const fixtureConfig = (options: ElfDependencyFixtureOptions): FixtureConfig => {
sectionSizes: options.sectionSizes ?? {},
sectionEntrySizes: options.sectionEntrySizes ?? {},
omitSymentTag: options.omitSymentTag === true,
omitSymtabTag: options.omitSymtabTag === true,
splitLoadAtHash: options.splitLoadAtHash === true,
versymZeroFillOffset: options.versymZeroFillOffset,
};
};
@@ -643,7 +652,7 @@ const buildDynamicTags = (
addTag(4, offsets.hashOff);
if (tables.gnuHashBytes.length !== 0) addTag(0x6ffffef5, offsets.gnuHashOff);
addTag(5, offsets.dynstrOff);
addTag(6, offsets.dynsymOff);
if (!config.omitSymtabTag) addTag(6, offsets.dynsymOff);
addTag(10, tables.dynstrBytes.length);
if (!config.omitSymentTag) addTag(11, bits === 64 ? 24 : 16);
addTag(0x6ffffff0, offsets.versymOff);
@@ -680,7 +689,8 @@ const layoutDependencyImage = (
const programCount =
(config.interpreter === null ? 0 : 1) +
(config.splitLoadAtHash ? 2 : 1) +
(config.omitDynamic ? 0 : 1);
(config.omitDynamic ? 0 : 1) +
(config.versymZeroFillOffset === undefined ? 0 : 1);
const phoff = headerSize;
let cursor = phoff + programCount * phent;
const place = (size: number): number => {
@@ -830,6 +840,20 @@ const writeDependencyPrograms = (
} else add(1, 5, 0, layout.fileSize, 0x1000);
if (!config.omitDynamic)
add(2, 6, layout.dynamicOff, layout.dynamicBytes.length, 8);
if (config.versymZeroFillOffset !== undefined)
writeProgramHeader(
bytes,
layout.phoff + programIndex * layout.phent,
config.bits,
config.little,
1,
4,
0,
0,
1,
layout.versymOff + config.versymZeroFillOffset,
1,
);
};
const writeDependencySections = (
+73 -16
View File
@@ -523,6 +523,45 @@ const tableFromVirtual = (
};
};
const GNU_VERSYM_SLOT_BYTES = 2;
/** Keep complete leading slots in one proven file translation. */
const tableFromMappedVersym = (
mappings: ElfLoadMappings,
address: bigint | undefined,
count: number,
): LocatedTable | null => {
if (address === undefined) return null;
const complete = tableFromVirtual(
mappings,
address,
count * GNU_VERSYM_SLOT_BYTES,
);
if (complete !== null || count <= 1) return complete;
const mapping = createFileMappingIndex(
mappings.fileBacked,
mappings.zeroFills,
);
let low = 0;
let high = count - 1;
let offset: number | null = null;
// A mapped prefix proves every shorter span at the same start.
while (low < high) {
const slots = Math.ceil((low + high) / 2);
try {
offset = mapping.offset(address, slots * GNU_VERSYM_SLOT_BYTES);
low = slots;
} catch (cause) {
if (!(cause instanceof BinaryMappingFailure)) throw cause;
high = slots - 1;
}
}
if (offset === null) return null;
const size = low * GNU_VERSYM_SLOT_BYTES;
return { offset, size, location: { offset, bytes: size } };
};
/**
* Reads hash-table words from file bytes `[base, end)`. File mapping stays
* here; `elfHashSymbolCount.ts` owns the DT_HASH and DT_GNU_HASH layouts.
@@ -1058,7 +1097,7 @@ export const readElfDependenciesSteps = function* (
tableFromSection(versymSection, bytes.length, "GNU versym", issues) ??
(symbolCount === null
? null
: tableFromVirtual(mappings, addresses.get(DT_VERSYM), symbolCount * 2));
: tableFromMappedVersym(mappings, addresses.get(DT_VERSYM), symbolCount));
if (
dynsymTable === null &&
symbolCount !== null &&
@@ -1081,12 +1120,29 @@ export const readElfDependenciesSteps = function* (
message:
"GNU versym table could not be located from section headers or DT_VERSYM",
});
const versymSlots =
versymTable === null
? null
: {
offset: versymTable.offset,
count: Math.floor(versymTable.size / GNU_VERSYM_SLOT_BYTES),
};
if (
versymSlots !== null &&
symbolCount !== null &&
versymSlots.count < symbolCount
)
issues.push({
code: "table_unavailable",
location: hex(versymSlots.offset),
message: `GNU versym table holds ${String(versymSlots.count)} of ${String(symbolCount)} dynamic symbol slots; later slots were not read`,
});
const imports = parseImports(
reader,
bytes,
bits,
dynsymTable,
versymTable,
versymSlots,
dynstr,
symbolCount,
symbolEntrySize,
@@ -1578,7 +1634,7 @@ const parseImports = (
bytes: Buffer,
bits: 32 | 64,
dynsym: LocatedTable | null,
versym: LocatedTable | null,
versym: { readonly offset: number; readonly count: number } | null,
dynstr: DynamicStrings,
declaredCount: number | null,
entrySize: number,
@@ -1623,17 +1679,13 @@ const parseImports = (
}
let versymBytes: Buffer | null = null;
if (versym !== null) {
// A short table still holds whole slots for its leading symbols; keep those
// and leave only the symbols past its end without a version.
const slotCount = Math.min(symbolCount, Math.floor(versym.size / 2));
if (slotCount < symbolCount)
issues.push({
code: "table_unavailable",
location: hex(versym.offset),
message: `GNU versym table holds ${String(slotCount)} of ${String(symbolCount)} dynamic symbol slots; later imports have no version`,
});
const slotCount = Math.min(symbolCount, versym.count);
try {
versymBytes = reader.range(versym.offset, slotCount * 2, "GNU versym");
versymBytes = reader.range(
versym.offset,
slotCount * GNU_VERSYM_SLOT_BYTES,
"GNU versym",
);
} catch (cause) {
if (!(cause instanceof BinaryFormatFailure)) throw cause;
issues.push({
@@ -1673,9 +1725,12 @@ const parseImports = (
`dynsym[${String(index)}]`,
);
let version: ElfDependencyImport["version"] = null;
if (versymBytes !== null && (index + 1) * 2 <= versymBytes.length) {
if (
versymBytes !== null &&
(index + 1) * GNU_VERSYM_SLOT_BYTES <= versymBytes.length
) {
const raw = new BinaryReader(versymBytes, reader.little, "elf").u16(
index * 2,
index * GNU_VERSYM_SLOT_BYTES,
);
const versionIndex = raw & 0x7fff;
const hidden = (raw & 0x8000) !== 0;
@@ -1700,7 +1755,9 @@ const parseImports = (
if (resolved === undefined)
issues.push({
code: "version_unresolved",
location: hex((versym?.offset ?? 0) + index * 2),
location: hex(
(versym?.offset ?? 0) + index * GNU_VERSYM_SLOT_BYTES,
),
message: `Import ${name ?? `#${String(index)}`} references version index ${String(versionIndex)} with no matching verneed record`,
});
}
+106
View File
@@ -275,3 +275,109 @@ for (const tableAvailable of [true, false]) {
},
);
}
cliTest(
"retains backed leading GNU version slots without section headers",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-elf-dependencies-versym-");
for (const { label, alias, versions, coverage } of [
{
label: "complete",
alias: undefined,
versions: [
"GLIBC_2.34",
"GLIBC_2.2.5",
"GLIBCXX_3.4.29",
null,
"GLIBC_2.2.5",
],
coverage: "complete",
},
{
label: "later-byte-ambiguous",
alias: 7,
versions: ["GLIBC_2.34", "GLIBC_2.2.5", null, null, null],
coverage: "partial",
},
{
label: "first-slot-ambiguous",
alias: 1,
versions: [null, null, null, null, null],
coverage: "partial",
},
]) {
const path = join(root, label);
await writeFile(
path,
elfDependencyFixture({
stripped: true,
...(alias === undefined ? {} : { versymZeroFillOffset: alias }),
}),
);
const result = await cli.run({
arguments: ["inspect-elf-dependencies", path, "--json"],
});
expect(result.exitCode, JSON.stringify(result.json)).toBe(0);
const report = dependenciesContract.outputSchema.parse(
result.json,
).normalized_result;
if (!("imports" in report))
throw new Error("Expected an inline ELF dependency inventory");
expect(report.coverage.status, label).toBe(coverage);
expect(
report.imports.map(({ name }) => name),
label,
).toEqual(["printf", "memcpy", "_ZSt4cout", "abort", "_exit"]);
expect(
report.imports.map(({ version }) => version?.name ?? null),
label,
).toEqual(versions);
if (alias !== undefined) {
const blocked = report.imports.slice(alias === 7 ? 2 : 0);
expect(
blocked.map(({ version }) => version),
label,
).toEqual(blocked.map(() => null));
}
if (alias === 7)
expect(report.issues, label).toContainEqual(
expect.objectContaining({ code: "table_unavailable" }),
);
}
},
);
cliTest(
"reports short GNU version tables when the symbol table is unavailable",
async ({ cli }) => {
const root = await createTestTempDirectory(
"rea-elf-dependencies-short-versym-",
);
const path = join(root, "program");
await writeFile(
path,
elfDependencyFixture({
stripped: true,
omitSymtabTag: true,
versymZeroFillOffset: 7,
}),
);
const result = await cli.run({
arguments: ["inspect-elf-dependencies", path, "--json"],
});
expect(result.exitCode, JSON.stringify(result.json)).toBe(0);
const report = dependenciesContract.outputSchema.parse(
result.json,
).normalized_result;
if (!("imports" in report))
throw new Error("Expected an inline ELF dependency inventory");
expect(report.coverage).toMatchObject({
status: "partial",
examined_imports: 0,
});
expect(report.imports).toEqual([]);
expect(report.issues).toContainEqual(
expect.objectContaining({ code: "table_unavailable" }),
);
},
);