diff --git a/scripts/verify/baselines/raw-buffer-read.json b/scripts/verify/baselines/raw-buffer-read.json index 66c0962f7f..af5a57788f 100644 --- a/scripts/verify/baselines/raw-buffer-read.json +++ b/scripts/verify/baselines/raw-buffer-read.json @@ -4,7 +4,7 @@ "src/application/MipsGnuAttributes.ts": 2, "src/artifacts/DesktopFileInspection.ts": 4, "src/artifacts/apple/NibArchive.ts": 8, - "src/artifacts/bun/BunModuleGraphLayout.ts": 22, + "src/artifacts/bun/BunModuleGraphLayout.ts": 16, "src/artifacts/dotnet/DotnetBundle.ts": 5, "src/artifacts/nodeSea/NodeSeaBlob.ts": 4, "src/domain/apkSignature/apkSignatureSchemes.ts": 1, diff --git a/src/artifacts/bun/BunModuleGraph.test.ts b/src/artifacts/bun/BunModuleGraph.test.ts index 1ef8ee3a76..62a2620375 100644 --- a/src/artifacts/bun/BunModuleGraph.test.ts +++ b/src/artifacts/bun/BunModuleGraph.test.ts @@ -344,16 +344,20 @@ it("reads a shared long ELF section name once without materializing its string t const shnum = 16_383; const stringOffset = 64; const strings = Buffer.alloc(1024 * 1024, 0x61); + strings[0] = 0; + strings[strings.length - 1] = 0; const tableOffset = stringOffset + strings.length; const bytes = Buffer.alloc(tableOffset + shnum * 64); elfPrefix().copy(bytes, 0); bytes.writeBigUInt64LE(BigInt(tableOffset), 40); bytes.writeUInt16LE(64, 58); bytes.writeUInt16LE(shnum, 60); - bytes.writeUInt16LE(0, 62); + bytes.writeUInt16LE(1, 62); strings.copy(bytes, stringOffset); - for (let index = 0; index < shnum; index += 1) { + for (let index = 1; index < shnum; index += 1) { const header = tableOffset + index * 64; + bytes.writeUInt32LE(1, header); + bytes.writeUInt32LE(index === 1 ? 3 : 1, header + 4); bytes.writeBigUInt64LE(BigInt(stringOffset), header + 24); bytes.writeBigUInt64LE(BigInt(strings.length), header + 32); } diff --git a/src/artifacts/bun/BunModuleGraphLayout.ts b/src/artifacts/bun/BunModuleGraphLayout.ts index 3b84b4dc32..d890487fd7 100644 --- a/src/artifacts/bun/BunModuleGraphLayout.ts +++ b/src/artifacts/bun/BunModuleGraphLayout.ts @@ -1,5 +1,10 @@ import { LC } from "../../domain/apple/machoLoadCommandCodes.js"; import { Budget } from "../../domain/budget.js"; +import { declaredFileRange } from "../../domain/binaryContainer.js"; +import { readElfHeaderFacts } from "../../domain/elfFixedHeader.js"; +import { readElfRawTableDeclarations } from "../../domain/elfRawTableDeclarations.js"; +import { readElfSectionHeader } from "../../domain/elfSectionHeader.js"; +import { observeElfStringTableEntry } from "../../domain/elfStringTable.js"; import { readFatContainerHeader, readMachoHeaderPrefixFacts, @@ -672,121 +677,112 @@ const peClaims = async ( return claims; }; +const ELF_BUN_NAME = Buffer.from(".bun"); +const ELF_SHT_NULL = 0; +const ELF_SHT_STRTAB = 3; +const ELF_SHT_NOBITS = 8; +const MAX_SAFE_FILE_WORD = BigInt(Number.MAX_SAFE_INTEGER); + const elfClaims = async ( source: BunProbeSource, ): Promise => { const { handle, fileSize, signal, limits } = source; const header = await tryRead(handle, 0, 64, fileSize, signal); - if ( - header === null || - header.length < 16 || - !header.subarray(0, 4).equals(Buffer.from([0x7f, 0x45, 0x4c, 0x46])) - ) - return []; - const wide = header[4] === 2; - if (header[4] !== 1 && header[4] !== 2) return []; - if (header[5] !== 1 && header[5] !== 2) return []; - const littleEndian = header[5] === 1; - const shentsize = wide ? 64 : 40; - const shoffOffset = wide ? 40 : 32; - const shnumOffset = wide ? 60 : 48; - const shstrndxOffset = wide ? 62 : 50; - if (header.length < (wide ? 64 : 52)) return []; - const observedShentsize = readU16(header, wide ? 58 : 46, littleEndian); - if (observedShentsize !== 0 && observedShentsize !== shentsize) return []; - const shoff = wide - ? readBoundedU64(header, shoffOffset, littleEndian) - : readU32(header, shoffOffset, littleEndian); - const shnum = readU16(header, shnumOffset, littleEndian); - const shstrndx = readU16(header, shstrndxOffset, littleEndian); + if (header === null) return []; + const format = readElfHeaderFacts(header, fileSize); + if (!format.ok) return []; + const { elfClass, byteOrder } = format.value; + const declarations = readElfRawTableDeclarations(header, format.value); + if (!declarations.ok) return []; + const { offset, width, count, namesIndex } = declarations.value.sections; + const sectionWidth = elfClass === 64 ? 64 : 40; // Unsupported extended numbering does not establish a Bun graph. if ( - shoff === undefined || - shoff === 0 || - shnum === 0 || - shnum === 0xffff || - shstrndx >= shnum + (width !== 0 && width !== sectionWidth) || + offset === 0n || + offset > MAX_SAFE_FILE_WORD || + count === 0 || + count === 0xffff || + namesIndex >= count ) return []; - if (shnum * shentsize > limits.recognition_table_bytes) + const tableBytes = count * sectionWidth; + if (tableBytes > limits.recognition_table_bytes) throw artifactReaderLimitFailure( "artifact_limits.bun.recognition_table_bytes", limits.recognition_table_bytes, "bytes", - shnum * shentsize, + tableBytes, ); const table = await tryRead( handle, - shoff, - shnum * shentsize, + Number(offset), + tableBytes, fileSize, signal, ); if (table === null) return []; - const strings = elfSectionBounds(table, shstrndx, wide, littleEndian); - if (strings === null) return []; - // A section name lookup needs only `.bun` and its terminator. Read the - // referenced range, rather than treating a truncated string-table prefix as - // evidence that later names are absent. Duplicate offsets share one lookup. + const readSection = (index: number) => { + const start = index * sectionWidth; + const section = readElfSectionHeader( + table.subarray(start, start + sectionWidth), + elfClass, + byteOrder === "little", + ); + return section.ok ? section.value : null; + }; + + const strings = readSection(namesIndex); + if (strings === null || strings.type !== ELF_SHT_STRTAB) return []; + const stringRange = declaredFileRange(fileSize, strings.offset, strings.size); + if (!stringRange.file_backed) return []; + // Only ".bun" and its terminator are needed. Duplicate offsets share one + // bounded lookup, even when the referenced string is much longer. const names = new Map(); const claims: SectionWindow[] = []; - for (let index = 0; index < shnum; index += 1) { - const bounds = elfSectionBounds(table, index, wide, littleEndian); - if (bounds === null) continue; - const nameOffset = readU32(table, index * shentsize, littleEndian); + for (let index = 0; index < count; index += 1) { + const section = readSection(index); + if ( + section === null || + section.type === ELF_SHT_NULL || + section.type === ELF_SHT_NOBITS || + section.offset > MAX_SAFE_FILE_WORD || + section.size > MAX_SAFE_FILE_WORD + ) + continue; + const { nameOffset } = section; let isBun = names.get(nameOffset); if (isBun === undefined) { const name = - nameOffset >= strings.size + nameOffset >= stringRange.size ? null : await tryRead( handle, - strings.offset + nameOffset, - Math.min(ELF_BUN_NAME.length + 1, strings.size - nameOffset), + stringRange.offset + nameOffset, + Math.min(ELF_BUN_NAME.length + 1, stringRange.size - nameOffset), fileSize, signal, ); - isBun = name !== null && elfNameIsBun(name, 0); + isBun = + name !== null && + observeElfStringTableEntry(name, 0, name.length).bytes?.equals( + ELF_BUN_NAME, + ) === true; names.set(nameOffset, isBun); } if (!isBun) continue; - claims.push(windowFor("elf-section", bounds.offset, bounds.size, fileSize)); + claims.push( + windowFor( + "elf-section", + Number(section.offset), + Number(section.size), + fileSize, + ), + ); } return claims; }; -const elfSectionBounds = ( - table: Buffer, - index: number, - wide: boolean, - littleEndian: boolean, -): { readonly offset: number; readonly size: number } | null => { - const shentsize = wide ? 64 : 40; - const start = index * shentsize; - if (start + shentsize > table.length) return null; - const offset = wide - ? readBoundedU64(table, start + 24, littleEndian) - : readU32(table, start + 16, littleEndian); - const size = wide - ? readBoundedU64(table, start + 32, littleEndian) - : readU32(table, start + 20, littleEndian); - if (offset === undefined || size === undefined) return null; - return { offset, size }; -}; - -const ELF_BUN_NAME = Buffer.from(".bun"); - -/** - * Compare only `.bun` and its terminator. Many headers may share one long - * name, so scanning each name to its NUL would repeat unbounded work. - */ -const elfNameIsBun = (table: Buffer, offset: number): boolean => { - const end = offset + ELF_BUN_NAME.length; - if (end > table.length) return false; - if (end < table.length && table[end] !== 0) return false; - return table.subarray(offset, end).equals(ELF_BUN_NAME); -}; - const windowFor = ( carrier: SectionWindow["carrier"], fileOffset: number, @@ -819,33 +815,6 @@ const exactName = (bytes: Buffer, text: string): boolean => { return encoded.equals(bytes); }; -const readBoundedU64 = ( - bytes: Buffer, - offset: number, - littleEndian: boolean, -): number | undefined => { - if (offset < 0 || offset + 8 > bytes.length) return undefined; - const value = littleEndian - ? bytes.readBigUInt64LE(offset) - : bytes.readBigUInt64BE(offset); - if (value > BigInt(Number.MAX_SAFE_INTEGER)) return undefined; - return Number(value); -}; - -const readU32 = ( - bytes: Buffer, - offset: number, - littleEndian: boolean, -): number => - littleEndian ? bytes.readUInt32LE(offset) : bytes.readUInt32BE(offset); - -const readU16 = ( - bytes: Buffer, - offset: number, - littleEndian: boolean, -): number => - littleEndian ? bytes.readUInt16LE(offset) : bytes.readUInt16BE(offset); - const tryRead = async ( handle: FileHandle, position: number, diff --git a/src/artifacts/bun/BunStandalone.fixture.ts b/src/artifacts/bun/BunStandalone.fixture.ts index 3ca9f78dd9..f3e8558743 100644 --- a/src/artifacts/bun/BunStandalone.fixture.ts +++ b/src/artifacts/bun/BunStandalone.fixture.ts @@ -217,11 +217,12 @@ export const elfBunSection = (section: Buffer, nameOffset = 11): Buffer => { bytes.writeUInt16LE(1, 62); shstr.copy(bytes, shstrOffset); section.copy(bytes, sectionOffset); - writeElfSection(bytes, tableOffset + 64, 1, shstrOffset, shstr.length); + writeElfSection(bytes, tableOffset + 64, 1, 3, shstrOffset, shstr.length); writeElfSection( bytes, tableOffset + 128, nameOffset, + 1, sectionOffset, section.length, ); @@ -232,10 +233,12 @@ const writeElfSection = ( bytes: Buffer, header: number, name: number, + type: number, offset: number, size: number, ): void => { bytes.writeUInt32LE(name, header); + bytes.writeUInt32LE(type, header + 4); bytes.writeBigUInt64LE(BigInt(offset), header + 24); bytes.writeBigUInt64LE(BigInt(size), header + 32); }; diff --git a/src/artifacts/bun/BunStandaloneArtifactReader.test.ts b/src/artifacts/bun/BunStandaloneArtifactReader.test.ts index 438fcea8e0..d06a4ca332 100644 --- a/src/artifacts/bun/BunStandaloneArtifactReader.test.ts +++ b/src/artifacts/bun/BunStandaloneArtifactReader.test.ts @@ -154,6 +154,70 @@ it("keeps exhausted Bun recognition distinct from a native ELF inventory and rec }); }); +it.each([ + { declaration: "file-backed .bun", format: "bun-standalone" }, + { declaration: "SHT_NOBITS .bun", format: "elf" }, + { declaration: "inactive .bun", format: "elf" }, + { declaration: "non-string section-name table", format: "elf" }, + { declaration: "unterminated .bun name", format: "elf" }, + { declaration: "truncated section-name table", format: "elf" }, + { declaration: "truncated section-header table", format: "elf" }, +] as const)( + "inventories an ELF carrier with $declaration as $format", + async ({ declaration, format }) => { + const bytes = elfBunSection( + bunPrefixedPayload( + bunModuleGraphPayload({ + modules: [ + { name: "main.js", contents: Buffer.from("fixture member") }, + ], + }), + ), + ); + const sectionTable = Number(bytes.readBigUInt64LE(40)); + if (declaration === "SHT_NOBITS .bun") + bytes.writeUInt32LE(8, sectionTable + 128 + 4); + if (declaration === "inactive .bun") + bytes.writeUInt32LE(0, sectionTable + 128 + 4); + if (declaration === "non-string section-name table") + bytes.writeUInt32LE(1, sectionTable + 64 + 4); + const stringTableSize = sectionTable + 64 + 32; + if (declaration === "truncated section-name table") { + const stringTableOffset = bytes.readBigUInt64LE(sectionTable + 64 + 24); + bytes.writeBigUInt64LE( + BigInt(bytes.length) - stringTableOffset + 1n, + stringTableSize, + ); + } + if (declaration === "unterminated .bun name") { + bytes.writeBigUInt64LE( + bytes.readBigUInt64LE(stringTableSize) - 1n, + stringTableSize, + ); + } + const path = join( + await createTestTempDirectory("rea-bun-elf-section-"), + "app", + ); + await writeFile( + path, + declaration === "truncated section-header table" + ? bytes.subarray(0, -1) + : bytes, + ); + const scope = new ArtifactResourceScope(); + try { + const result = await inventoryArtifact(path, { resourceScope: scope }); + expect(result.manifest.root_format).toBe(format); + expect(result.occurrences.map((entry) => entry.logical_path)).toEqual( + format === "bun-standalone" ? [".", "main.js"] : ["."], + ); + } finally { + await scope.close(); + } + }, +); + async function collect(values: AsyncIterable): Promise { const result: T[] = []; for await (const value of values) result.push(value);