diff --git a/scripts/verify/baselines/raw-buffer-read.json b/scripts/verify/baselines/raw-buffer-read.json index 50357264bc..772e9b88de 100644 --- a/scripts/verify/baselines/raw-buffer-read.json +++ b/scripts/verify/baselines/raw-buffer-read.json @@ -5,14 +5,12 @@ "src/domain/apple/appleMachoFixups.ts": 22, "src/domain/apple/appleMachoSelection.ts": 2, "src/domain/apple/jvmClassFile.ts": 2, - "src/domain/apple/machoCommandNames.ts": 35, + "src/domain/apple/machoCommandNames.ts": 33, "src/domain/apple/machoContainer.ts": 13, "src/domain/apple/machoDylibCommand.ts": 4, "src/domain/apple/machoEncryptionReader.ts": 1, "src/domain/apple/machoLoadCommandReader.ts": 12, "src/domain/apple/machoLoadCommands.ts": 8, - "src/domain/apple/machoSectionHeader.ts": 8, - "src/domain/apple/machoSegmentHeader.ts": 5, "src/domain/apple/plistScalars.ts": 6, "src/domain/apple/propertyListDecodeBudget.ts": 2, "src/domain/binaryTarget.ts": 10, diff --git a/src/artifacts/bun/BunModuleGraphLayout.ts b/src/artifacts/bun/BunModuleGraphLayout.ts index 751e579fde..3aa1c10145 100644 --- a/src/artifacts/bun/BunModuleGraphLayout.ts +++ b/src/artifacts/bun/BunModuleGraphLayout.ts @@ -31,10 +31,12 @@ import { } from "../../domain/apple/machoLoadCommands.js"; import { machoSectionBacking, + machoSectionHeaderSize, readMachoSectionHeader, } from "../../domain/apple/machoSectionHeader.js"; import { admitMachoSegmentCommand, + machoSegmentSectionTableFits, readMachoSegmentHeader, } from "../../domain/apple/machoSegmentHeader.js"; import type { FileHandle } from "node:fs/promises"; @@ -62,8 +64,6 @@ export const BUN_RECORD_BYTES_1_3_3 = 36; export const BUN_RECORD_BYTES_1_3_9 = 52; const MAX_PE_SECTIONS = 96; -const SECTION_64_BYTES = 80; -const SECTION_32_BYTES = 68; export const BUN_LAYOUT_REVISIONS = ["bun-1.3.3", "bun-1.3.9"] as const; export type BunLayoutRevision = (typeof BUN_LAYOUT_REVISIONS)[number]; @@ -644,8 +644,8 @@ const segmentClaims = ( if (!parsedSegment.ok) return []; const segment = parsedSegment.value; const { headerSize, sectionCount } = segment; - const sectionBytes = wide ? SECTION_64_BYTES : SECTION_32_BYTES; - if (headerSize + sectionCount * sectionBytes > command.length) return []; + const sectionBytes = machoSectionHeaderSize(wide); + if (!machoSegmentSectionTableFits(segment, command.length, wide)) return []; const admission = admitMachoSegmentCommand( segment, command.length, diff --git a/src/domain/apple/appleMachoSelection.ts b/src/domain/apple/appleMachoSelection.ts index 97033ef455..353175df41 100644 --- a/src/domain/apple/appleMachoSelection.ts +++ b/src/domain/apple/appleMachoSelection.ts @@ -9,9 +9,13 @@ import { machoDependencyCommand, readMachoDylibCommandFacts, } from "./machoDylibCommand.js"; -import { readMachoSectionHeader } from "./machoSectionHeader.js"; +import { + machoSectionHeaderSize, + readMachoSectionHeader, +} from "./machoSectionHeader.js"; import { admitMachoSegmentMapping, + machoSegmentSectionTableFits, readMachoSegmentHeader, } from "./machoSegmentHeader.js"; import { @@ -269,12 +273,13 @@ const collectSegment = ( fileSize > 0n ) state.baseAddress ??= address; - if (headerSize + count * 80 > size) + if (!machoSegmentSectionTableFits(parsed.value, size, true)) throw truncatedInput("macho", "Truncated section table"); + const sectionWidth = machoSectionHeaderSize(true); for (let section = 0; section < count; section++) { - const position = cursor + headerSize + section * 80; + const position = cursor + headerSize + section * sectionWidth; const parsedSection = readMachoSectionHeader( - bytes.subarray(position, position + 80), + bytes.subarray(position, position + sectionWidth), true, true, ); diff --git a/src/domain/apple/machoCommandNames.ts b/src/domain/apple/machoCommandNames.ts index c246cf0994..ab3fa28a4a 100644 --- a/src/domain/apple/machoCommandNames.ts +++ b/src/domain/apple/machoCommandNames.ts @@ -9,8 +9,15 @@ import { MACHO_VERSION_MIN_PLATFORMS, type MachoVersionMinPlatform, } from "./machoPlatform.js"; -import { readMachoSegmentHeader } from "./machoSegmentHeader.js"; -import { readMachoSectionHeader } from "./machoSectionHeader.js"; +import { + machoSegmentHeaderSize, + machoSegmentSectionTableFits, + readMachoSegmentHeader, +} from "./machoSegmentHeader.js"; +import { + machoSectionHeaderSize, + readMachoSectionHeader, +} from "./machoSectionHeader.js"; import { createHash } from "node:crypto"; import { decodeLimit, @@ -304,7 +311,7 @@ export const readMachoCommandNames = async ( | NonNullable[number][] | undefined; if (segmentWide !== null) { - const segmentHeaderSize = segmentWide ? 72 : 56; + const segmentHeaderSize = machoSegmentHeaderSize(segmentWide); if (frame.size < segmentHeaderSize) throw malformedInput("macho", "Mach-O segment is truncated"); const segmentBytes = await exact(at, segmentHeaderSize); @@ -314,11 +321,8 @@ export const readMachoCommandNames = async ( table.littleEndian, ); if (!segment.ok) throw malformedInput("macho", segment.error.message); - const width = segmentWide ? 80 : 68; - if ( - segment.value.sectionCount > - Math.floor((frame.size - segmentHeaderSize) / width) - ) + const width = machoSectionHeaderSize(segmentWide); + if (!machoSegmentSectionTableFits(segment.value, frame.size, segmentWide)) throw malformedInput("macho", "Mach-O section table is truncated"); if (segment.value.sectionCount > maximumRecords - records) throw loadCommandLimit(maximumRecords, "records"); @@ -366,14 +370,8 @@ export const readMachoCommandNames = async ( segmentWide ? 52 : 44, table.littleEndian, ), - relocationOffset: sectionView.getUint32( - segmentWide ? 56 : 48, - table.littleEndian, - ), - relocationCount: sectionView.getUint32( - segmentWide ? 60 : 52, - table.littleEndian, - ), + relocationOffset: section.value.relocationOffset, + relocationCount: section.value.relocationCount, reserved1: sectionView.getUint32( segmentWide ? 68 : 60, table.littleEndian, diff --git a/src/domain/apple/machoEncryptionReader.ts b/src/domain/apple/machoEncryptionReader.ts index 3b0e31c550..17d7816f07 100644 --- a/src/domain/apple/machoEncryptionReader.ts +++ b/src/domain/apple/machoEncryptionReader.ts @@ -6,8 +6,16 @@ import type { MachoSliceEncryption, } from "./machoEncryption.js"; import { validateFatSliceIdentity } from "./machoContainer.js"; -import { readMachoSectionHeader } from "./machoSectionHeader.js"; -import { readMachoSegmentHeader } from "./machoSegmentHeader.js"; +import { + isMachoZeroFillSection, + machoSectionHeaderSize, + readMachoSectionHeader, +} from "./machoSectionHeader.js"; +import { + machoSegmentHeaderSize, + machoSegmentSectionTableFits, + readMachoSegmentHeader, +} from "./machoSegmentHeader.js"; import { frameLoadCommands, readMachoContainer, @@ -20,8 +28,6 @@ import { // loader.h: encryption_info_command is five 32-bit words; the 64-bit form adds `pad`. const ENCRYPTION_COMMAND_SIZE = { 32: 20, 64: 24 } as const; -// loader.h section types whose bytes occupy no file range. -const ZEROFILL_SECTION_TYPES = new Set([0x1, 0xc, 0x12]); // A second encryption command already makes a slice malformed; later ones // are counted, not retained. const RETAINED_ENCRYPTION_COMMANDS = 2; @@ -462,7 +468,10 @@ const mappingRecords = ({ command, body }: MachoLoadCommand): number => { 2 + Math.max( 0, - Math.floor((body.byteLength - (wide ? 72 : 56)) / (wide ? 80 : 68)), + Math.floor( + (body.byteLength - machoSegmentHeaderSize(wide)) / + machoSectionHeaderSize(wide), + ), ) ); }; @@ -482,11 +491,8 @@ const decodeSegment = ({ const fileSize = Number(segment.fileSize); if (!Number.isSafeInteger(fileOffset + fileSize)) return `load command ${index} segment file range exceeds the safe range`; - const sectionSize = wide ? 80 : 68; - if ( - segment.sectionCount > - (body.byteLength - segment.headerSize) / sectionSize - ) + const sectionSize = machoSectionHeaderSize(wide); + if (!machoSegmentSectionTableFits(segment, body.byteLength, wide)) return `load command ${index} section records exceed cmdsize`; const sections: SegmentFacts["sections"][number][] = []; for (let section = 0; section < segment.sectionCount; section += 1) { @@ -502,7 +508,7 @@ const decodeSegment = ({ name: fixedName(header.value.nameBytes), offset: header.value.offset, size: Number(header.value.size), - zerofill: ZEROFILL_SECTION_TYPES.has(header.value.flags & 0xff), + zerofill: isMachoZeroFillSection(header.value.flags), }); } return { diff --git a/src/domain/apple/machoImage.ts b/src/domain/apple/machoImage.ts index 5bc4cfd099..f0236c4a9a 100644 --- a/src/domain/apple/machoImage.ts +++ b/src/domain/apple/machoImage.ts @@ -3,6 +3,7 @@ import type { FileMapping, ZeroFillMapping } from "../virtualFileMapping.js"; import { decodeMachoFixedName } from "./appleMachoNames.js"; import { machoSectionBacking, + machoSectionHeaderSize, readMachoSectionHeader, type MachoSectionHeader, } from "./machoSectionHeader.js"; @@ -61,7 +62,7 @@ export const readMachoImage = ( "malformed", "Mach-O segment command does not match the header width", ); - const sectionWidth = wide ? 80 : 68; + const sectionWidth = machoSectionHeaderSize(wide); const parsedSegment = readMachoSegmentHeader( bytes.subarray(offset, offset + size), wide, diff --git a/src/domain/apple/machoSectionHeader.ts b/src/domain/apple/machoSectionHeader.ts index b4a4555b30..933ab6bf6a 100644 --- a/src/domain/apple/machoSectionHeader.ts +++ b/src/domain/apple/machoSectionHeader.ts @@ -1,3 +1,4 @@ +import { BinaryReader } from "../binaryContainer.js"; import { err, ok, type Result } from "../result.js"; export interface MachoSectionHeader { @@ -12,6 +13,10 @@ export interface MachoSectionHeader { readonly flags: number; } +/** Fixed byte widths of Apple's section and section_64 records. */ +export const machoSectionHeaderSize = (wide: boolean): 68 | 80 => + wide ? 80 : 68; + /** Fixed section/section_64 facts; callers own mapping and display policies. */ export const readMachoSectionHeader = ( bytes: Uint8Array, @@ -21,25 +26,28 @@ export const readMachoSectionHeader = ( MachoSectionHeader, { readonly kind: "malformed"; readonly message: string } > => { - if (bytes.byteLength < (wide ? 80 : 68)) + if (bytes.byteLength < machoSectionHeaderSize(wide)) return err({ kind: "malformed", message: "Mach-O section header is truncated", }); - const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + const reader = new BinaryReader( + Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength), + littleEndian, + "macho", + ); + const bits = wide ? 64 : 32; return ok({ - nameBytes: Buffer.from(bytes.subarray(0, 16)), - segmentNameBytes: Buffer.from(bytes.subarray(16, 32)), - address: wide - ? view.getBigUint64(32, littleEndian) - : BigInt(view.getUint32(32, littleEndian)), - size: wide - ? view.getBigUint64(40, littleEndian) - : BigInt(view.getUint32(36, littleEndian)), - offset: view.getUint32(wide ? 48 : 40, littleEndian), - relocationOffset: view.getUint32(wide ? 56 : 48, littleEndian), - relocationCount: view.getUint32(wide ? 60 : 52, littleEndian), - flags: view.getUint32(wide ? 64 : 56, littleEndian), + nameBytes: Buffer.from(reader.range(0, 16, "Mach-O section name")), + segmentNameBytes: Buffer.from( + reader.range(16, 16, "Mach-O section segment name"), + ), + address: reader.word(32, bits), + size: reader.word(wide ? 40 : 36, bits), + offset: reader.u32(wide ? 48 : 40), + relocationOffset: reader.u32(wide ? 56 : 48), + relocationCount: reader.u32(wide ? 60 : 52), + flags: reader.u32(wide ? 64 : 56), }); }; diff --git a/src/domain/apple/machoSegmentHeader.ts b/src/domain/apple/machoSegmentHeader.ts index b978279ba0..9c6f522a31 100644 --- a/src/domain/apple/machoSegmentHeader.ts +++ b/src/domain/apple/machoSegmentHeader.ts @@ -1,32 +1,39 @@ +import { BinaryReader } from "../binaryContainer.js"; +import { machoSectionHeaderSize } from "./machoSectionHeader.js"; import { err, ok } from "../result.js"; +/** Fixed byte widths of Apple's segment_command and segment_command_64 records. */ +export const machoSegmentHeaderSize = (wide: boolean): 56 | 72 => + wide ? 72 : 56; + /** Decode a fixed LC_SEGMENT/LC_SEGMENT_64 record; callers own command and mapping admission. */ export const readMachoSegmentHeader = ( bytes: Uint8Array, wide: boolean, littleEndian: boolean, ) => { - const headerSize = wide ? 72 : 56; + const headerSize = machoSegmentHeaderSize(wide); if (bytes.byteLength < headerSize) return err({ kind: "malformed" as const, message: "Mach-O segment header is truncated", }); - const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); - const word = (offset: number): bigint => - wide - ? view.getBigUint64(offset, littleEndian) - : BigInt(view.getUint32(offset, littleEndian)); + const reader = new BinaryReader( + Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength), + littleEndian, + "macho", + ); + const bits = wide ? 64 : 32; return ok({ headerSize, - nameBytes: Buffer.from(bytes.subarray(8, 24)), - address: word(24), - memorySize: word(wide ? 32 : 28), - fileOffset: word(wide ? 40 : 32), - fileSize: word(wide ? 48 : 36), - maxProtection: view.getUint32(wide ? 56 : 40, littleEndian), - protection: view.getUint32(wide ? 60 : 44, littleEndian), - sectionCount: view.getUint32(wide ? 64 : 48, littleEndian), + nameBytes: Buffer.from(reader.range(8, 16, "Mach-O segment name")), + address: reader.word(24, bits), + memorySize: reader.word(wide ? 32 : 28, bits), + fileOffset: reader.word(wide ? 40 : 32, bits), + fileSize: reader.word(wide ? 48 : 36, bits), + maxProtection: reader.u32(wide ? 56 : 40), + protection: reader.u32(wide ? 60 : 44), + sectionCount: reader.u32(wide ? 64 : 48), }); }; @@ -50,6 +57,17 @@ export const admitMachoSegmentMapping = ( : ok({ unmapped }); }; +/** Check that the segment's fixed sections fit inside its declared cmdsize. */ +export const machoSegmentSectionTableFits = ( + segment: { readonly headerSize: number; readonly sectionCount: number }, + commandBytes: number, + wide: boolean, +): boolean => + segment.sectionCount <= + Math.floor( + (commandBytes - segment.headerSize) / machoSectionHeaderSize(wide), + ); + /** Admit one segment command against its cmdsize and the image that holds it. */ export const admitMachoSegmentCommand = ( segment: Parameters[0] & { @@ -63,11 +81,7 @@ export const admitMachoSegmentCommand = ( ) => { const mapping = admitMachoSegmentMapping(segment, bits); if (!mapping.ok) return mapping; - const sectionBytes = bits === 64 ? 80 : 68; - if ( - segment.sectionCount > - Math.floor((commandBytes - segment.headerSize) / sectionBytes) - ) + if (!machoSegmentSectionTableFits(segment, commandBytes, bits === 64)) return err({ kind: "malformed" as const, message: "Mach-O section table exceeds its segment command", diff --git a/src/native/AppleMachoSelection.test.ts b/src/native/AppleMachoSelection.test.ts index 38a3ea2ba0..83bc2112dc 100644 --- a/src/native/AppleMachoSelection.test.ts +++ b/src/native/AppleMachoSelection.test.ts @@ -15,6 +15,7 @@ import { fatSliceRange, machoImage, machoImageWithUnknownCommand, + segmentCommand, } from "../artifacts/apple/MachoImage.fixture.js"; import { readMachoImage } from "../domain/apple/machoLoadCommandReader.js"; import { readMachoImage as readMachoMetadataImage } from "../domain/apple/machoImage.js"; @@ -71,6 +72,47 @@ it.each([ }, ); +it("keeps the selected slice's file offset bound for an empty segment", () => { + const segment = Buffer.from( + segmentCommand({ name: "__EMPTY", vmaddr: 0n, vmsize: 0n }), + ); + const imageWithSegment = () => + Buffer.from(machoImage({ cpu: CPU.arm64, commands: [segment] })); + const fileBytes = imageWithSegment().length; + segment.writeBigUInt64LE(BigInt(fileBytes), 40); + expect(layoutFor(imageWithSegment(), "arm64").segments).toEqual([ + { address: 0n, size: 0n, offset: fileBytes, executable: false }, + ]); + segment.writeBigUInt64LE(BigInt(fileBytes + 1), 40); + const outside = imageWithSegment(); + expect(() => readMachoMetadataImage(outside)).not.toThrow(); + expect(() => layoutFor(outside, "arm64")).toThrow( + malformedInput("macho", "Segment file range exceeds target bytes"), + ); +}); + +it("preserves the selected layout's truncation diagnosis when a segment lacks its declared section", () => { + const segment = Buffer.from( + segmentCommand({ name: "__EMPTY", vmaddr: 0n, vmsize: 0n }), + ); + segment.writeUInt32LE(1, 64); + const image = Buffer.from( + machoImage({ cpu: CPU.arm64, commands: [segment] }), + ); + expect(() => layoutFor(image, "arm64")).toThrow( + expect.objectContaining({ + kind: "truncated", + message: "Truncated section table", + }), + ); + expect(() => readMachoMetadataImage(image)).toThrow( + expect.objectContaining({ + kind: "malformed", + message: "Mach-O section table exceeds its segment command", + }), + ); +}); + const registerThinCpuFamilyControls = (): void => { it.each([ { cpu: CPU.x86_64, architecture: "arm64" },