mirror of
https://github.com/morluto/rea.git
synced 2026-12-01 08:38:57 +00:00
* fix(plist): rethrow internal invariant violations from plist consumers KeyedArchiveReader reported any non-limit decode failure as a format failure, InterfaceBuilderAnalysis listed it as an invalid archive, ReleaseExposureReader fell back to scanning raw bytes, and the native plist parser reported it as provider output. An InternalInvariantError is a REA defect, not evidence about the input, so each consumer now rethrows it. The native parser's binary path now shares its one cause projection instead of a duplicate. * fix(native): rethrow internal invariant violations from the native output projection nativeOutputFailure wrapped any producer failure as AnalysisOutputError, so a REA defect thrown while reading a plist or dispatching a command was reported as native output parsing. It now rethrows InternalInvariantError, which reaches the provider's adapter-failure path with the invariant as its cause. * fix(artifacts): rethrow internal invariant violations from the shared artifact failure mapper translateArtifactFailure turned every unrecognised cause into an ArtifactOperationError with reason io, so the keyed-archive and Interface Builder rethrows still reached users as artifact read failures. The shared mapper now rethrows InternalInvariantError, and the deferred client reports it as a ProviderAdapterError. Provider-level tests drive both operations through that client. * refactor(dotnet): report managed reader defects through invariantViolation (#11030) * refactor(dotnet): report managed reader defects through invariantViolation The managed readers threw plain TypeError and RangeError for states their callers rule out: an allowance or method page outside the input schema, a missing snapshot after identity admission, and a missing CLI header after the caller already returned for it. These are REA defects, not malformed targets, so they throw invariantViolation. The two CLI re-checks are gone: the callers pass the CLI header they already narrowed. The dotnet parser-plain-throw baseline drops from 6 to 0. * refactor(providers): refuse unusable tool paths and record marker mismatches without throwing to their own catch (#11031) * refactor(firmware): refuse unusable tool paths without throwing to its own catch resolveFirmwareCommand threw a plain TypeError for a configured engine or limiter path that is not a regular file, only to catch it in the next line and wrap it as an unavailable capability. A helper now returns why a path cannot run, and each caller builds the one refusal directly. Refusal reasons are unchanged; the directory tests now pin them exactly. The firmware parser-plain-throw baseline drops from 2 to 0. * refactor(pwndbg): refuse unusable debugger paths without throwing to its own catch inspectPwndbgCore threw plain Errors for a relative or wrong-kind configured path only to catch them and wrap them as an unavailable capability. A helper now returns why a path cannot be used, with any host error as its cause, and the loop builds the one refusal. Cancellation between host checks still propagates. Refusal reasons are unchanged. The PwndbgCoreContext parser-plain-throw baseline entry is removed. * refactor(pwntools): record a mismatched failure marker without throwing to its own catch readPwntoolsFailureEvidence threw a plain Error when the private bridge marker disagreed with the exit status, only to catch it and record its message as the marker failure. The mismatch is now recorded directly. The recorded evidence is unchanged; a unit test pins both the matching and the mismatched marker. The PwntoolsResourceLimits parser-plain-throw baseline entry is removed. * fix(android): report an unobserved Java probe as a REA defect, not a Java refusal (#11032) * fix(android): report an unobserved Java probe as a REA defect, not a Java refusal When runOwnedCommand resolved without observing the completed run, the probe threw a plain Error that its catch then classified as a Java runtime refusal, telling the caller to review their launcher. The state is a broken internal assumption, so the probe throws invariantViolation and projects it as a jadx adapter failure. The JadxJavaProbe parser-plain-throw baseline entry is removed. * refactor(native): report native provider defects through invariantViolation (#11033) * refactor(native): report native provider defects through invariantViolation Native providers threw plain Error and TypeError for states their own earlier steps rule out: a client with no target, a measured slice with no selection, a read longer than requested, a decoder command without its runtime, an LLDB root released before its children, and an IPS integer fact from another reader. These are REA defects, so they throw invariantViolation. NativeUiInterruptionControl no longer needs a throw: recording the deadline interruption returns the interruption its error is built from. Six native parser-plain-throw baseline entries drop. * refactor(native): report malformed lipo, swift-demangle and UI helper output through ParseFailure (#11034) * refactor(native): report malformed lipo and swift-demangle output through ParseFailure The lipo and swift-demangle output parsers threw plain TypeError for output that breaks their framing, and the lipo result classifier caught every TypeError as malformed output, so a host TypeError from a REA defect was reported as lipo output. Both parsers now throw malformedInput with their own format, and the lipo classifier accepts ParseFailureError instead of TypeError. Messages and the consumers' output and format failure categories are unchanged. Four native parser-plain-throw baseline entries drop. * refactor(native): report the UI helper's non-JSON output through ParseFailure The native UI helper runtime threw a plain Error when the helper's stdout was not JSON. It now throws malformedInput with its own format and the JSON failure as cause. The observation boundary still reports it as a native-macos adapter failure with the same reason. The NativeUiHelperRuntime parser-plain-throw baseline entry is removed. * refactor(verify): keep process-lifecycle owners out of the parser plain-throw guard (#11035) * refactor(verify): keep process-lifecycle owners out of the parser plain-throw guard JadxWorkspaceRoot and PwntoolsDecoder sit in parser folders but own a private helper process; their remaining plain throws report the helper's startup, handshake and cleanup outcomes, not parse faults. The guard now names them as process-lifecycle owners and leaves them out, so their five baseline entries drop without inventing parse errors for process failures. * refactor(parsers): report the remaining artifact, il2cpp, model and domain defects through invariantViolation (#11036) * refactor(parsers): report the remaining artifact, il2cpp, model and domain defects through invariantViolation Nine plain Error, TypeError and RangeError throws in parser folders reported broken internal assumptions or caller contracts (an uninitialized ZIP or DMG reader, a missing scan result, a non-byte stream chunk, an invalid traversal or marshal limit, a header count or linking fact the reader itself should have produced, a misordered Safetensors budget, an append after fingerprinting). None is an input fault, and no catch site depends on their class. They now throw invariantViolation with the same messages, and their parser-plain-throw baseline entries drop. * refactor(evidence): refuse an earlier Evidence format through ParseFailure (#11037) * refactor(evidence): refuse an earlier Evidence format through ParseFailure UnsupportedEvidenceFormatError restated the ParseFailure algebra as its own TypeError subclass. The format owner now throws unsupportedInput for the evidence-bundle format at the evidence_format field and exports the predicate its consumers use. The bundle reader's unsupported-format kind and message are unchanged. The snapshot reader surfaced only TypeError messages, so it now also surfaces the format refusal and keeps its recreate guidance; a boundary test pins that. * refactor(native): report Mach-O reader and inspection defects through invariantViolation (#11042) The Mach-O inspection plan reads the lipo, nm and dyld_info captures it just ran, the dispatch metadata reader is called only for Mach-O executables, and the command-name reader takes limits its callers derive. A missing capture, a non-Mach-O target or a malformed limit is a REA defect, not an input fault, so these six sites throw invariantViolation with their existing messages instead of TypeError. No catch site depends on their class. Their parser-plain-throw baseline entries drop. * fix(artifacts): join the Interface Builder cleanup failure to a catalog defect When catalog work failed while the concurrent Interface Builder reader failed to close, analyzeAppleAssetCatalogs built the primary through translateArtifactFailure before joining cleanup. That mapper now rethrows an InternalInvariantError, so a defect skipped the join and the reader's retained resources were lost. The defect now becomes the artifact graph provider's adapter failure at that site and joins the cleanup failure as before.
784 lines
28 KiB
TypeScript
784 lines
28 KiB
TypeScript
import { LC, LC_REQ_DYLD } from "../domain/apple/machoLoadCommandCodes.js";
|
|
import {
|
|
MachoLoadCommandCursor,
|
|
decodeMachoFixedWordFields,
|
|
machoFixedWordFieldNames,
|
|
readMachoLoadCommandTableHeader,
|
|
} from "../domain/apple/machoLoadCommands.js";
|
|
import {
|
|
MACHO_VERSION_MIN_PLATFORMS,
|
|
type MachoVersionMinPlatform,
|
|
} from "../domain/apple/machoPlatform.js";
|
|
import { readMachoSegmentHeader } from "../domain/apple/machoSegmentHeader.js";
|
|
import { readMachoSectionHeader } from "../domain/apple/machoSectionHeader.js";
|
|
import { createHash } from "node:crypto";
|
|
import {
|
|
malformedInput,
|
|
ParseFailureError,
|
|
truncatedInput,
|
|
} from "../domain/parseFailure.js";
|
|
import { invariantViolation } from "../domain/internalInvariant.js";
|
|
|
|
/** loader.h defines these with LC_REQ_DYLD; the reader also accepts each code without that bit. */
|
|
const withoutRequiredByDyld = (code: number): number => code & ~LC_REQ_DYLD;
|
|
const DYLIB_COMMANDS = new Set([
|
|
LC.LOAD_DYLIB,
|
|
LC.ID_DYLIB,
|
|
withoutRequiredByDyld(LC.LOAD_WEAK_DYLIB),
|
|
LC.LOAD_WEAK_DYLIB,
|
|
withoutRequiredByDyld(LC.REEXPORT_DYLIB),
|
|
LC.REEXPORT_DYLIB,
|
|
LC.LAZY_LOAD_DYLIB,
|
|
withoutRequiredByDyld(LC.LOAD_UPWARD_DYLIB),
|
|
LC.LOAD_UPWARD_DYLIB,
|
|
]);
|
|
const LC_STR_COMMANDS = new Set([
|
|
...DYLIB_COMMANDS,
|
|
LC.LOADFVMLIB,
|
|
LC.IDFVMLIB,
|
|
LC.FVMFILE,
|
|
LC.PREBOUND_DYLIB,
|
|
LC.LOAD_DYLINKER,
|
|
LC.ID_DYLINKER,
|
|
LC.SUB_FRAMEWORK,
|
|
LC.SUB_UMBRELLA,
|
|
LC.SUB_CLIENT,
|
|
LC.SUB_LIBRARY,
|
|
LC.RPATH,
|
|
LC.DYLD_ENVIRONMENT,
|
|
LC.TARGET_TRIPLE,
|
|
]);
|
|
|
|
/** Read exact ranges from an already admitted and identity-verified slice. */
|
|
export type MachoRangeReader = (
|
|
offset: number,
|
|
size: number,
|
|
) => Promise<Uint8Array>;
|
|
|
|
/**
|
|
* Producer-derived output capacity exceeded while retaining binary strings,
|
|
* with the unit its maximum counts.
|
|
*/
|
|
export class MachoCommandNamesLimitError extends ParseFailureError<"limit"> {
|
|
constructor(
|
|
readonly maximum: number,
|
|
readonly unit: "bytes" | "records" | "projected_bytes",
|
|
) {
|
|
super({
|
|
kind: "limit",
|
|
format: "macho",
|
|
detail: `Mach-O load-command ${unit === "projected_bytes" ? "projected bytes" : unit} exceed the retained output budget`,
|
|
limit: { name: `macho_load_command_${unit}`, maximum },
|
|
});
|
|
this.name = "MachoCommandNamesLimitError";
|
|
}
|
|
}
|
|
|
|
// Reserve fixed projection keys, scalar metadata, arrays and bounded limitation
|
|
// messages even when the input has no load commands.
|
|
const PROJECTED_ENVELOPE_BYTES = 8192;
|
|
// A section becomes both a segment-view object and a set of indexed command
|
|
// fields. Reserve for their keys, numbers, identities and JSON framing before
|
|
// retaining the section. Strings are charged separately for escaping and hex.
|
|
const PROJECTED_COMMAND_BYTES = 2048;
|
|
const PROJECTED_SECTION_BYTES = 2048;
|
|
const PROJECTED_CHILD_BYTES = 256;
|
|
const PROJECTED_STRING_EXPANSION = 24;
|
|
const DEFAULT_PROJECTED_BYTES = 64 * 1024 * 1024;
|
|
|
|
export interface MachoCommandNames {
|
|
readonly sliceSize: number;
|
|
readonly header: {
|
|
readonly wide: boolean;
|
|
readonly littleEndian: boolean;
|
|
readonly cpuType: number;
|
|
readonly cpuSubtype: number;
|
|
readonly fileType: number;
|
|
readonly flags: number;
|
|
};
|
|
readonly commands: readonly {
|
|
readonly index: number;
|
|
readonly command: number;
|
|
readonly offset: number;
|
|
readonly size: number;
|
|
/** Every byte after the command header belongs to a decoded field. */
|
|
readonly fullyDecoded?: boolean;
|
|
/** Whole-command digest when it fits the retained output allowance. */
|
|
readonly rawSha256: string | null;
|
|
readonly fixedFields?: Readonly<Record<string, number>>;
|
|
readonly segmentName?: Uint8Array;
|
|
readonly segment?: {
|
|
readonly address: bigint;
|
|
readonly memorySize: bigint;
|
|
readonly fileOffset: bigint;
|
|
readonly fileSize: bigint;
|
|
readonly maxProtection: number;
|
|
readonly protection: number;
|
|
readonly flags: number;
|
|
};
|
|
readonly sections?: readonly {
|
|
readonly name: Uint8Array;
|
|
readonly segmentName: Uint8Array;
|
|
readonly address: bigint;
|
|
readonly size: bigint;
|
|
readonly fileOffset: number;
|
|
readonly alignmentExponent: number;
|
|
readonly relocationOffset: number;
|
|
readonly relocationCount: number;
|
|
readonly reserved1: number;
|
|
readonly reserved2: number;
|
|
readonly reserved3?: number;
|
|
readonly flags: number;
|
|
}[];
|
|
readonly commandString?: Uint8Array;
|
|
readonly commandStringOffset?: number;
|
|
readonly dylib?: {
|
|
readonly nameOffset: number;
|
|
readonly currentVersion: number;
|
|
readonly compatibilityVersion: number;
|
|
readonly encoding:
|
|
| { readonly kind: "timestamp"; readonly timestamp: number }
|
|
| { readonly kind: "use"; readonly flags: number };
|
|
};
|
|
readonly legacyBuild?: {
|
|
readonly platform: MachoVersionMinPlatform;
|
|
readonly version: number;
|
|
readonly sdk: number;
|
|
};
|
|
readonly linkerOptions?: readonly Uint8Array[];
|
|
readonly note?: {
|
|
readonly owner: Uint8Array;
|
|
readonly offset: bigint;
|
|
readonly size: bigint;
|
|
};
|
|
readonly fileset?: {
|
|
readonly address: bigint;
|
|
readonly fileOffset: bigint;
|
|
readonly entryId: Uint8Array;
|
|
readonly reserved: number;
|
|
};
|
|
readonly prebound?: {
|
|
readonly moduleCount: number;
|
|
readonly linkedModulesOffset: number;
|
|
readonly linkedModules: Uint8Array;
|
|
};
|
|
readonly fvmlib?: {
|
|
readonly minorVersion: number;
|
|
readonly headerAddress: number;
|
|
};
|
|
readonly fvmfile?: { readonly headerAddress: number };
|
|
readonly uuid?: Uint8Array;
|
|
readonly entrypoint?: {
|
|
readonly offset: bigint;
|
|
readonly stackSize: bigint;
|
|
};
|
|
readonly build?: {
|
|
readonly platform: number;
|
|
readonly minimumOs: number;
|
|
readonly sdk: number;
|
|
readonly tools: readonly {
|
|
readonly tool: number;
|
|
readonly version: number;
|
|
}[];
|
|
};
|
|
}[];
|
|
}
|
|
|
|
/**
|
|
* Walk only fixed records and declared strings from a selected thin image.
|
|
* The caller owns identity, cancellation, closing, and the per-string byte cap.
|
|
*/
|
|
export const readMachoCommandNames = async (
|
|
read: MachoRangeReader,
|
|
imageSize: number,
|
|
maximumStringBytes: number,
|
|
maximumRecords: number,
|
|
maximumProjectedBytes = DEFAULT_PROJECTED_BYTES,
|
|
): Promise<MachoCommandNames> => {
|
|
if (
|
|
!Number.isSafeInteger(maximumStringBytes) ||
|
|
maximumStringBytes < 0 ||
|
|
!Number.isSafeInteger(maximumRecords) ||
|
|
maximumRecords < 0 ||
|
|
!Number.isSafeInteger(maximumProjectedBytes) ||
|
|
maximumProjectedBytes < 0
|
|
)
|
|
throw invariantViolation(
|
|
"Mach-O read limits must be nonnegative safe integers",
|
|
);
|
|
const exact = async (offset: number, size: number): Promise<Uint8Array> => {
|
|
if (
|
|
!Number.isSafeInteger(offset) ||
|
|
!Number.isSafeInteger(size) ||
|
|
offset < 0 ||
|
|
size < 0 ||
|
|
offset > imageSize - size
|
|
)
|
|
throw malformedInput("macho", "Mach-O range exceeds selected slice");
|
|
const value = await read(offset, size);
|
|
if (value.byteLength !== size)
|
|
throw truncatedInput("macho", "Mach-O range is truncated");
|
|
return value;
|
|
};
|
|
const header = await exact(0, Math.min(32, imageSize));
|
|
const parsed = readMachoLoadCommandTableHeader(header, imageSize);
|
|
if (!parsed.ok) throw malformedInput("macho", parsed.error);
|
|
if (parsed.value === null)
|
|
throw malformedInput("macho", "Selected slice is not Mach-O");
|
|
const table = parsed.value;
|
|
const cursor = new MachoLoadCommandCursor(table);
|
|
if (table.commandCount > maximumRecords)
|
|
throw new MachoCommandNamesLimitError(maximumRecords, "records");
|
|
let projectedBytes = 0;
|
|
const chargeProjection = (count: number, perItem: number): void => {
|
|
if (count > Math.floor((maximumProjectedBytes - projectedBytes) / perItem))
|
|
throw new MachoCommandNamesLimitError(
|
|
maximumProjectedBytes,
|
|
"projected_bytes",
|
|
);
|
|
projectedBytes += count * perItem;
|
|
};
|
|
chargeProjection(1, PROJECTED_ENVELOPE_BYTES);
|
|
chargeProjection(table.commandCount, PROJECTED_COMMAND_BYTES);
|
|
let records = table.commandCount;
|
|
let retainedStringBytes = 0;
|
|
const stringAllowance = (): number =>
|
|
Math.min(
|
|
maximumStringBytes - retainedStringBytes,
|
|
Math.floor(
|
|
(maximumProjectedBytes - projectedBytes) / PROJECTED_STRING_EXPANSION,
|
|
),
|
|
);
|
|
const admitStringBytes = (count: number): void => {
|
|
if (count > maximumStringBytes - retainedStringBytes)
|
|
throw new MachoCommandNamesLimitError(maximumStringBytes, "bytes");
|
|
if (count > stringAllowance())
|
|
throw new MachoCommandNamesLimitError(
|
|
maximumProjectedBytes,
|
|
"projected_bytes",
|
|
);
|
|
};
|
|
const retain = (bytes: Uint8Array): Uint8Array => {
|
|
admitStringBytes(bytes.byteLength);
|
|
chargeProjection(bytes.byteLength, PROJECTED_STRING_EXPANSION);
|
|
retainedStringBytes += bytes.byteLength;
|
|
// Range readers may return Buffer views into a much larger read window.
|
|
// Charge the retained length before allocating an independently owned copy.
|
|
return Uint8Array.from(bytes);
|
|
};
|
|
const readString = async (
|
|
offset: number,
|
|
extent: number,
|
|
label: string,
|
|
): Promise<Uint8Array> => {
|
|
const length = Math.min(extent, stringAllowance() + 1);
|
|
const bytes = await exact(offset, length);
|
|
const end = bytes.indexOf(0);
|
|
if (end < 0) {
|
|
if (length < extent) admitStringBytes(length);
|
|
throw malformedInput("macho", `${label} is unterminated`);
|
|
}
|
|
return retain(bytes.subarray(0, end));
|
|
};
|
|
const commands: MachoCommandNames["commands"][number][] = [];
|
|
while (cursor.nextOffset !== null) {
|
|
const row = cursor.read(
|
|
await exact(table.headerSize + cursor.nextOffset, 8),
|
|
);
|
|
if (!row.ok) throw malformedInput("macho", row.error);
|
|
const frame = row.value;
|
|
const at = table.headerSize + frame.offset;
|
|
const fixedNames = machoFixedWordFieldNames(frame.command);
|
|
let fixedFields: Readonly<Record<string, number>> | undefined;
|
|
if (fixedNames !== undefined) {
|
|
const byteLength = fixedNames.length * 4;
|
|
const decoded =
|
|
frame.size < 8 + byteLength
|
|
? null
|
|
: decodeMachoFixedWordFields(
|
|
frame.command,
|
|
await exact(at + 8, byteLength),
|
|
table.littleEndian,
|
|
);
|
|
if (decoded === null)
|
|
throw malformedInput(
|
|
"macho",
|
|
"Mach-O fixed command fields are truncated",
|
|
);
|
|
fixedFields = decoded;
|
|
}
|
|
const segmentWide =
|
|
frame.command === LC.SEGMENT_64
|
|
? true
|
|
: frame.command === LC.SEGMENT
|
|
? false
|
|
: null;
|
|
let segmentName: Uint8Array | undefined;
|
|
let segmentFacts: MachoCommandNames["commands"][number]["segment"];
|
|
let sections:
|
|
| NonNullable<MachoCommandNames["commands"][number]["sections"]>[number][]
|
|
| undefined;
|
|
if (segmentWide !== null) {
|
|
const segmentHeaderSize = segmentWide ? 72 : 56;
|
|
if (frame.size < segmentHeaderSize)
|
|
throw malformedInput("macho", "Mach-O segment is truncated");
|
|
const segmentBytes = await exact(at, segmentHeaderSize);
|
|
const segment = readMachoSegmentHeader(
|
|
segmentBytes,
|
|
segmentWide,
|
|
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)
|
|
)
|
|
throw malformedInput("macho", "Mach-O section table is truncated");
|
|
if (segment.value.sectionCount > maximumRecords - records)
|
|
throw new MachoCommandNamesLimitError(maximumRecords, "records");
|
|
chargeProjection(segment.value.sectionCount, PROJECTED_SECTION_BYTES);
|
|
records += segment.value.sectionCount;
|
|
segmentName = retain(segment.value.nameBytes);
|
|
const segmentView = new DataView(
|
|
segmentBytes.buffer,
|
|
segmentBytes.byteOffset,
|
|
segmentBytes.byteLength,
|
|
);
|
|
segmentFacts = {
|
|
address: segment.value.address,
|
|
memorySize: segment.value.memorySize,
|
|
fileOffset: segment.value.fileOffset,
|
|
fileSize: segment.value.fileSize,
|
|
maxProtection: segment.value.maxProtection,
|
|
protection: segment.value.protection,
|
|
flags: segmentView.getUint32(segmentWide ? 68 : 52, table.littleEndian),
|
|
};
|
|
sections = [];
|
|
for (let i = 0; i < segment.value.sectionCount; i++) {
|
|
const sectionBytes = await exact(
|
|
at + segmentHeaderSize + i * width,
|
|
width,
|
|
);
|
|
const section = readMachoSectionHeader(
|
|
sectionBytes,
|
|
segmentWide,
|
|
table.littleEndian,
|
|
);
|
|
if (!section.ok) throw malformedInput("macho", section.error.message);
|
|
const sectionView = new DataView(
|
|
sectionBytes.buffer,
|
|
sectionBytes.byteOffset,
|
|
sectionBytes.byteLength,
|
|
);
|
|
sections.push({
|
|
name: retain(section.value.nameBytes),
|
|
segmentName: retain(section.value.segmentNameBytes),
|
|
address: section.value.address,
|
|
size: section.value.size,
|
|
fileOffset: section.value.offset,
|
|
alignmentExponent: sectionView.getUint32(
|
|
segmentWide ? 52 : 44,
|
|
table.littleEndian,
|
|
),
|
|
relocationOffset: sectionView.getUint32(
|
|
segmentWide ? 56 : 48,
|
|
table.littleEndian,
|
|
),
|
|
relocationCount: sectionView.getUint32(
|
|
segmentWide ? 60 : 52,
|
|
table.littleEndian,
|
|
),
|
|
reserved1: sectionView.getUint32(
|
|
segmentWide ? 68 : 60,
|
|
table.littleEndian,
|
|
),
|
|
reserved2: sectionView.getUint32(
|
|
segmentWide ? 72 : 64,
|
|
table.littleEndian,
|
|
),
|
|
...(segmentWide
|
|
? { reserved3: sectionView.getUint32(76, table.littleEndian) }
|
|
: {}),
|
|
flags: section.value.flags,
|
|
});
|
|
}
|
|
}
|
|
// Dylib and rpath commands own an lc_str at offset 8. Retain bytes up to
|
|
// the first NUL without allocating the command's full declared extent.
|
|
let commandString: Uint8Array | undefined;
|
|
let commandStringOffset: number | undefined;
|
|
let dylib: MachoCommandNames["commands"][number]["dylib"];
|
|
if (LC_STR_COMMANDS.has(frame.command)) {
|
|
if (frame.size < 12)
|
|
throw malformedInput(
|
|
"macho",
|
|
"Mach-O command string offset is truncated",
|
|
);
|
|
const data = await exact(at + 8, 4);
|
|
const offset = new DataView(
|
|
data.buffer,
|
|
data.byteOffset,
|
|
data.byteLength,
|
|
).getUint32(0, table.littleEndian);
|
|
const minimum = DYLIB_COMMANDS.has(frame.command)
|
|
? 24
|
|
: frame.command === LC.LOADFVMLIB ||
|
|
frame.command === LC.IDFVMLIB ||
|
|
frame.command === LC.PREBOUND_DYLIB
|
|
? 20
|
|
: frame.command === LC.FVMFILE
|
|
? 16
|
|
: 12;
|
|
if (offset < minimum || offset >= frame.size)
|
|
throw malformedInput(
|
|
"macho",
|
|
"Mach-O command string offset is invalid",
|
|
);
|
|
commandString = await readString(
|
|
at + offset,
|
|
frame.size - offset,
|
|
"Mach-O command string",
|
|
);
|
|
commandStringOffset = offset;
|
|
if (DYLIB_COMMANDS.has(frame.command)) {
|
|
const fixed = await exact(at + 12, 12);
|
|
const view = new DataView(
|
|
fixed.buffer,
|
|
fixed.byteOffset,
|
|
fixed.byteLength,
|
|
);
|
|
const marker = view.getUint32(0, table.littleEndian);
|
|
const useEncoding =
|
|
(frame.command === LC.LOAD_DYLIB ||
|
|
frame.command === LC.LOAD_WEAK_DYLIB) &&
|
|
offset === 28 &&
|
|
marker === 0x1a741800;
|
|
if (useEncoding && frame.size < 28)
|
|
throw malformedInput(
|
|
"macho",
|
|
"Mach-O dylib use command is truncated",
|
|
);
|
|
const flags = useEncoding ? await exact(at + 24, 4) : undefined;
|
|
dylib = {
|
|
nameOffset: offset,
|
|
currentVersion: view.getUint32(4, table.littleEndian),
|
|
compatibilityVersion: view.getUint32(8, table.littleEndian),
|
|
encoding:
|
|
flags === undefined
|
|
? { kind: "timestamp", timestamp: marker }
|
|
: {
|
|
kind: "use",
|
|
flags: new DataView(
|
|
flags.buffer,
|
|
flags.byteOffset,
|
|
flags.byteLength,
|
|
).getUint32(0, table.littleEndian),
|
|
},
|
|
};
|
|
}
|
|
}
|
|
let prebound: MachoCommandNames["commands"][number]["prebound"];
|
|
if (frame.command === LC.PREBOUND_DYLIB) {
|
|
if (frame.size < 20)
|
|
throw malformedInput(
|
|
"macho",
|
|
"Mach-O prebound dylib command is truncated",
|
|
);
|
|
const data = await exact(at + 12, 8);
|
|
const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
|
|
const moduleCount = view.getUint32(0, table.littleEndian);
|
|
const linkedModulesOffset = view.getUint32(4, table.littleEndian);
|
|
const length = Math.ceil(moduleCount / 8);
|
|
if (linkedModulesOffset < 20 || linkedModulesOffset > frame.size - length)
|
|
throw malformedInput(
|
|
"macho",
|
|
"Mach-O prebound module bitmap exceeds its command",
|
|
);
|
|
admitStringBytes(length);
|
|
prebound = {
|
|
moduleCount,
|
|
linkedModulesOffset,
|
|
linkedModules: retain(await exact(at + linkedModulesOffset, length)),
|
|
};
|
|
}
|
|
let fvmlib: MachoCommandNames["commands"][number]["fvmlib"];
|
|
if (frame.command === LC.LOADFVMLIB || frame.command === LC.IDFVMLIB) {
|
|
if (frame.size < 20)
|
|
throw malformedInput("macho", "Mach-O fvmlib command is truncated");
|
|
const data = await exact(at + 12, 8);
|
|
const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
|
|
fvmlib = {
|
|
minorVersion: view.getUint32(0, table.littleEndian),
|
|
headerAddress: view.getUint32(4, table.littleEndian),
|
|
};
|
|
}
|
|
let fvmfile: MachoCommandNames["commands"][number]["fvmfile"];
|
|
if (frame.command === LC.FVMFILE) {
|
|
if (frame.size < 16)
|
|
throw malformedInput("macho", "Mach-O fvmfile command is truncated");
|
|
const data = await exact(at + 12, 4);
|
|
fvmfile = {
|
|
headerAddress: new DataView(
|
|
data.buffer,
|
|
data.byteOffset,
|
|
data.byteLength,
|
|
).getUint32(0, table.littleEndian),
|
|
};
|
|
}
|
|
let linkerOptions: Uint8Array[] | undefined;
|
|
if (frame.command === LC.LINKER_OPTION) {
|
|
if (frame.size < 12)
|
|
throw malformedInput(
|
|
"macho",
|
|
"Mach-O linker option count is truncated",
|
|
);
|
|
const countBytes = await exact(at + 8, 4);
|
|
const count = new DataView(
|
|
countBytes.buffer,
|
|
countBytes.byteOffset,
|
|
countBytes.byteLength,
|
|
).getUint32(0, table.littleEndian);
|
|
if (count > maximumRecords - records)
|
|
throw new MachoCommandNamesLimitError(maximumRecords, "records");
|
|
if (count > frame.size - 12)
|
|
throw malformedInput(
|
|
"macho",
|
|
"Mach-O linker option table is truncated",
|
|
);
|
|
chargeProjection(count, PROJECTED_CHILD_BYTES);
|
|
records += count;
|
|
linkerOptions = [];
|
|
let offset = 12;
|
|
let current = new Uint8Array(0);
|
|
let currentLength = 0;
|
|
while (linkerOptions.length < count && offset < frame.size) {
|
|
const length = Math.min(frame.size - offset, 4096);
|
|
const bytes = await exact(at + offset, length);
|
|
offset += length;
|
|
for (const byte of bytes) {
|
|
if (byte === 0) {
|
|
linkerOptions.push(retain(current.subarray(0, currentLength)));
|
|
current = new Uint8Array(0);
|
|
currentLength = 0;
|
|
if (linkerOptions.length === count) break;
|
|
} else {
|
|
const remaining = stringAllowance();
|
|
if (currentLength >= remaining) admitStringBytes(currentLength + 1);
|
|
if (currentLength === current.byteLength) {
|
|
const capacity = Math.min(
|
|
remaining,
|
|
Math.max(32, current.byteLength * 2),
|
|
);
|
|
const expanded = new Uint8Array(capacity);
|
|
expanded.set(current);
|
|
current = expanded;
|
|
}
|
|
current[currentLength++] = byte;
|
|
}
|
|
}
|
|
}
|
|
if (linkerOptions.length !== count)
|
|
throw malformedInput("macho", "Mach-O linker option is unterminated");
|
|
}
|
|
let legacyBuild: MachoCommandNames["commands"][number]["legacyBuild"];
|
|
const legacyPlatform = MACHO_VERSION_MIN_PLATFORMS.get(frame.command);
|
|
if (legacyPlatform !== undefined) {
|
|
if (frame.size < 16)
|
|
throw malformedInput(
|
|
"macho",
|
|
"Mach-O minimum version command is truncated",
|
|
);
|
|
const bytes = await exact(at + 8, 8);
|
|
const view = new DataView(
|
|
bytes.buffer,
|
|
bytes.byteOffset,
|
|
bytes.byteLength,
|
|
);
|
|
legacyBuild = {
|
|
platform: legacyPlatform,
|
|
version: view.getUint32(0, table.littleEndian),
|
|
sdk: view.getUint32(4, table.littleEndian),
|
|
};
|
|
}
|
|
let note: MachoCommandNames["commands"][number]["note"];
|
|
if (frame.command === LC.NOTE) {
|
|
if (frame.size < 40)
|
|
throw malformedInput("macho", "Mach-O note command is truncated");
|
|
const data = await exact(at + 8, 32);
|
|
const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
|
|
note = {
|
|
owner: retain(data.subarray(0, 16)),
|
|
offset: view.getBigUint64(16, table.littleEndian),
|
|
size: view.getBigUint64(24, table.littleEndian),
|
|
};
|
|
}
|
|
let fileset: MachoCommandNames["commands"][number]["fileset"];
|
|
let filesetStringStartsAfterHeader = false;
|
|
let filesetStringEnd: number | undefined;
|
|
if (frame.command === LC.FILESET_ENTRY) {
|
|
if (frame.size < 32)
|
|
throw malformedInput("macho", "Mach-O fileset command is truncated");
|
|
const data = await exact(at + 8, 24);
|
|
const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
|
|
const offset = view.getUint32(16, table.littleEndian);
|
|
if (offset < 32 || offset >= frame.size)
|
|
throw malformedInput(
|
|
"macho",
|
|
"Mach-O fileset entry string offset is invalid",
|
|
);
|
|
filesetStringStartsAfterHeader = offset === 32;
|
|
const entryId = await readString(
|
|
at + offset,
|
|
frame.size - offset,
|
|
"Mach-O fileset entry string",
|
|
);
|
|
fileset = {
|
|
address: view.getBigUint64(0, table.littleEndian),
|
|
fileOffset: view.getBigUint64(8, table.littleEndian),
|
|
entryId,
|
|
reserved: view.getUint32(20, table.littleEndian),
|
|
};
|
|
filesetStringEnd = offset + entryId.byteLength + 1;
|
|
}
|
|
let uuid: Uint8Array | undefined;
|
|
if (frame.command === LC.UUID) {
|
|
if (frame.size < 24)
|
|
throw malformedInput("macho", "Mach-O UUID command is truncated");
|
|
uuid = Uint8Array.from(await exact(at + 8, 16));
|
|
}
|
|
let entrypoint: MachoCommandNames["commands"][number]["entrypoint"];
|
|
if (frame.command === LC.MAIN) {
|
|
if (frame.size < 24)
|
|
throw malformedInput("macho", "Mach-O entrypoint command is truncated");
|
|
const bytes = await exact(at + 8, 16);
|
|
const view = new DataView(
|
|
bytes.buffer,
|
|
bytes.byteOffset,
|
|
bytes.byteLength,
|
|
);
|
|
entrypoint = {
|
|
offset: view.getBigUint64(0, table.littleEndian),
|
|
stackSize: view.getBigUint64(8, table.littleEndian),
|
|
};
|
|
}
|
|
let build: MachoCommandNames["commands"][number]["build"];
|
|
if (frame.command === LC.BUILD_VERSION) {
|
|
if (frame.size < 24)
|
|
throw malformedInput(
|
|
"macho",
|
|
"Mach-O build version command is truncated",
|
|
);
|
|
const header = await exact(at + 8, 16);
|
|
const view = new DataView(
|
|
header.buffer,
|
|
header.byteOffset,
|
|
header.byteLength,
|
|
);
|
|
const toolCount = view.getUint32(12, table.littleEndian);
|
|
if (toolCount > Math.floor((frame.size - 24) / 8))
|
|
throw malformedInput("macho", "Mach-O build tool table is truncated");
|
|
if (toolCount > maximumRecords - records)
|
|
throw new MachoCommandNamesLimitError(maximumRecords, "records");
|
|
chargeProjection(toolCount, PROJECTED_CHILD_BYTES);
|
|
records += toolCount;
|
|
const tools: { tool: number; version: number }[] = [];
|
|
for (let i = 0; i < toolCount; i++) {
|
|
const tool = await exact(at + 24 + i * 8, 8);
|
|
const toolView = new DataView(
|
|
tool.buffer,
|
|
tool.byteOffset,
|
|
tool.byteLength,
|
|
);
|
|
tools.push({
|
|
tool: toolView.getUint32(0, table.littleEndian),
|
|
version: toolView.getUint32(4, table.littleEndian),
|
|
});
|
|
}
|
|
build = {
|
|
platform: view.getUint32(0, table.littleEndian),
|
|
minimumOs: view.getUint32(4, table.littleEndian),
|
|
sdk: view.getUint32(8, table.littleEndian),
|
|
tools,
|
|
};
|
|
}
|
|
const fullyDecoded =
|
|
(linkerOptions !== undefined &&
|
|
frame.size ===
|
|
12 +
|
|
linkerOptions.reduce(
|
|
(total, option) => total + option.byteLength + 1,
|
|
0,
|
|
)) ||
|
|
(note !== undefined && frame.size === 40) ||
|
|
(fileset !== undefined &&
|
|
filesetStringStartsAfterHeader &&
|
|
filesetStringEnd === frame.size) ||
|
|
(fixedNames !== undefined && frame.size === 8 + fixedNames.length * 4) ||
|
|
(uuid !== undefined && frame.size === 24) ||
|
|
(entrypoint !== undefined && frame.size === 24) ||
|
|
(legacyBuild !== undefined && frame.size === 16) ||
|
|
(segmentWide !== null &&
|
|
sections !== undefined &&
|
|
frame.size ===
|
|
(segmentWide ? 72 : 56) +
|
|
sections.length * (segmentWide ? 80 : 68)) ||
|
|
(build !== undefined && frame.size === 24 + build.tools.length * 8);
|
|
let rawSha256: string | null = null;
|
|
if (!fullyDecoded && frame.size <= maximumStringBytes) {
|
|
const digest = createHash("sha256");
|
|
for (let position = 0; position < frame.size;) {
|
|
const length = Math.min(64 * 1024, frame.size - position);
|
|
digest.update(await exact(at + position, length));
|
|
position += length;
|
|
}
|
|
rawSha256 = digest.digest("hex");
|
|
}
|
|
commands.push({
|
|
index: frame.index,
|
|
command: frame.command,
|
|
offset: frame.offset,
|
|
size: frame.size,
|
|
fullyDecoded,
|
|
rawSha256,
|
|
...(fixedFields === undefined ? {} : { fixedFields }),
|
|
...(segmentName === undefined ||
|
|
sections === undefined ||
|
|
segmentFacts === undefined
|
|
? {}
|
|
: { segmentName, segment: segmentFacts, sections }),
|
|
...(commandString === undefined ? {} : { commandString }),
|
|
...(commandStringOffset === undefined ? {} : { commandStringOffset }),
|
|
...(dylib === undefined ? {} : { dylib }),
|
|
...(legacyBuild === undefined ? {} : { legacyBuild }),
|
|
...(linkerOptions === undefined ? {} : { linkerOptions }),
|
|
...(note === undefined ? {} : { note }),
|
|
...(fileset === undefined ? {} : { fileset }),
|
|
...(prebound === undefined ? {} : { prebound }),
|
|
...(fvmlib === undefined ? {} : { fvmlib }),
|
|
...(fvmfile === undefined ? {} : { fvmfile }),
|
|
...(uuid === undefined ? {} : { uuid }),
|
|
...(entrypoint === undefined ? {} : { entrypoint }),
|
|
...(build === undefined ? {} : { build }),
|
|
});
|
|
}
|
|
const end = cursor.finish();
|
|
if (!end.ok) throw malformedInput("macho", end.error);
|
|
return {
|
|
sliceSize: imageSize,
|
|
header: {
|
|
wide: table.wide,
|
|
littleEndian: table.littleEndian,
|
|
cpuType: table.identity.cpuType,
|
|
cpuSubtype: table.identity.cpuSubtype,
|
|
fileType: table.fileType,
|
|
flags: new DataView(
|
|
header.buffer,
|
|
header.byteOffset,
|
|
header.byteLength,
|
|
).getUint32(24, table.littleEndian),
|
|
},
|
|
commands,
|
|
};
|
|
};
|