fix(native): reject ambiguous otool load-command framing

Validate Mach command counts, byte totals, scalar uniqueness, section counts, and build-tool counts before claiming exhaustive evidence. Preserve raw output in typed parsing failures and distinguish dylib commands from the dynamic loader. Correct inconsistent handcrafted fixtures and label their provenance.

Validation: 38 native tests, combined checks, and temporary-directory hygiene. Multiline dylib-name ambiguity was reproduced with the host Apple otool; regression workflows use captured output and injected command runners.
This commit is contained in:
morluto
2026-10-12 05:24:29 +08:00
parent a8d4984404
commit 108b5f9425
10 changed files with 414 additions and 79 deletions
+32 -2
View File
@@ -108,7 +108,37 @@ export const inspectNativeMacho = async (
else if (optional.error._tag === "AnalysisCapabilityUnavailableError")
limitations.push(VTOOL_UNAVAILABLE_LIMITATION);
else return err(optional.error);
const normalized = normalizeMacho(captures, context.invocation, limitations);
const otool = captures.find(({ tool }) => tool === "otool");
if (otool === undefined) throw new TypeError("Missing otool capture");
let load: ReturnType<typeof parseOtoolLoadCommands>;
try {
load = parseOtoolLoadCommands(sliceOutput(otool));
} catch (cause: unknown) {
return err(
new AnalysisOutputError(
"inspect_macho",
"Malformed otool load-command output",
{
cause,
capturedOutput: {
stdout: otool.stdout,
stderr: otool.stderr,
truncated: false,
stdout_bytes: otool.stdoutBytes,
stderr_bytes: otool.stderrBytes,
exit_code: otool.exitCode,
signal: otool.signal,
},
},
),
);
}
const normalized = normalizeMacho(
captures,
context.invocation,
limitations,
load,
);
const segmentOffset = segmentContainerOffset(
normalized,
selectedArchitecture,
@@ -135,10 +165,10 @@ const normalizeMacho = (
captures: readonly NativeCommandCapture[],
toInvocation: (capture: NativeCommandCapture) => NativeCommandInvocation,
additionalLimitations: readonly string[],
load: ReturnType<typeof parseOtoolLoadCommands>,
) => {
const byTool = captureLookup(captures);
const architectures = parseLipoArchitectures(byTool("lipo").stdout);
const load = parseOtoolLoadCommands(sliceOutput(byTool("otool")));
const imports = parseDyldSymbols(
sliceOutput(byTool("dyld_info", 0)),
"imports",
+162 -15
View File
@@ -43,6 +43,15 @@ interface ParsedLoadCommands {
readonly flags: Set<string>;
}
const DYLIB_COMMANDS = new Set([
"LC_ID_DYLIB",
"LC_LOAD_DYLIB",
"LC_LOAD_WEAK_DYLIB",
"LC_REEXPORT_DYLIB",
"LC_LAZY_LOAD_DYLIB",
"LC_LOAD_UPWARD_DYLIB",
]);
/**
* otool emits LF, but a capture replayed from another host or toolchain can
* carry CRLF. The section/command boundaries below match a bare `\n`, so a
@@ -57,11 +66,14 @@ const normalizeLineEndings = (output: string): string =>
export const parseOtoolLoadCommands = (raw: string) => {
const output = normalizeLineEndings(raw);
const header = parseHeader(output);
const state = createLoadCommandState(header?.flags);
if (header === undefined)
throw new TypeError("otool output is missing the Mach header");
const state = createLoadCommandState(header.flags);
for (const block of output.split(/(?=^Load command \d+$)/mu))
parseLoadCommand(block, state);
validateLoadCommandFraming(header, state.commands);
return {
fileType: header?.fileType ?? null,
fileType: header.fileType,
flags: [...state.flags].sort(),
uuid: state.uuid,
commands: state.commands,
@@ -74,7 +86,14 @@ export const parseOtoolLoadCommands = (raw: string) => {
const parseHeader = (
output: string,
): { fileType: string | null; flags: string[] } | undefined => {
):
| {
fileType: string | null;
flags: string[];
commandCount: number;
commandBytes: number;
}
| undefined => {
const lines = output.split(/\r?\n/u).map((line) => line.trim());
const columnsLine = lines.findIndex((line) => /(?:^|\s)magic\s/u.test(line));
if (columnsLine < 0) return undefined;
@@ -82,6 +101,10 @@ const parseHeader = (
const dataLine = lines.slice(columnsLine + 1).find((line) => line.length > 0);
const values = dataLine?.split(/\s+/u);
if (columns === undefined || values === undefined) return undefined;
const commandCount = headerValue(columns, values, "ncmds");
const commandBytes = headerValue(columns, values, "sizeofcmds");
if (commandCount === null || commandBytes === null)
throw new TypeError("otool Mach header is missing valid command framing");
const fileTypeIndex = columns.indexOf("filetype");
const flagsIndex = columns.indexOf("flags");
const complete = values.length >= columns.length;
@@ -92,6 +115,8 @@ const parseHeader = (
const flagsEnd =
flagsIndex >= 0 ? values.length - (columns.length - flagsIndex - 1) : 0;
return {
commandCount,
commandBytes,
fileType:
complete && fileTypeValueIndex >= 0 && fileTypeValueIndex < values.length
? (values[fileTypeValueIndex] ?? null)
@@ -105,6 +130,48 @@ const parseHeader = (
};
};
const headerValue = (
columns: readonly string[],
values: readonly string[],
name: string,
): number | null => {
const index = columns.indexOf(name);
if (index < 0) return null;
const flagsIndex = columns.indexOf("flags");
const valueIndex =
flagsIndex >= 0 && index > flagsIndex
? values.length - (columns.length - index)
: index;
const value = values[valueIndex];
return value === undefined ? null : numeric(value);
};
const validateLoadCommandFraming = (
header: { readonly commandCount: number; readonly commandBytes: number },
commands: readonly {
readonly index: number;
readonly fields: Readonly<Record<string, string | number | null>>;
}[],
): void => {
if (commands.length !== header.commandCount)
throw new TypeError(
"otool load-command count does not match the Mach header",
);
let totalBytes = 0;
for (const [expectedIndex, command] of commands.entries()) {
const size = numberField(command.fields, "cmdsize");
if (command.index !== expectedIndex || size === null || size < 8)
throw new TypeError("otool load-command sequence or size is invalid");
totalBytes += size;
if (!Number.isSafeInteger(totalBytes))
throw new TypeError("otool load-command byte count is unsafe");
}
if (totalBytes !== header.commandBytes)
throw new TypeError(
"otool load-command sizes do not match the Mach header",
);
};
const createLoadCommandState = (
headerFlags: readonly string[] | undefined,
): ParsedLoadCommands => ({
@@ -120,11 +187,17 @@ const createLoadCommandState = (
const parseLoadCommand = (block: string, state: ParsedLoadCommands): void => {
const indexText = /^Load command (\d+)/u.exec(block)?.[1];
if (indexText === undefined) return;
const index = Number(indexText);
if (!Number.isSafeInteger(index))
throw new TypeError("otool load-command index is unsafe");
const header = block.split(/\n\s*Section\n/u)[0] ?? block;
const fields = parseFields(header);
const kind = stringField(fields, "cmd") ?? "unknown";
const kind = stringField(fields, "cmd");
if (kind === null) throw new TypeError("otool load command is missing cmd");
for (const key of scalarFields(kind)) requireUniqueField(header, key);
if (DYLIB_COMMANDS.has(kind)) validateDylibCommandLines(header);
state.commands.push({
index: Number.parseInt(indexText, 10),
index,
kind,
fields,
});
@@ -135,6 +208,59 @@ const parseLoadCommand = (block: string, state: ParsedLoadCommands): void => {
collectSegment(kind, block, fields, state);
};
const validateDylibCommandLines = (block: string): void => {
const allowed = new Set([
"cmd",
"cmdsize",
"name",
"time stamp",
"current version",
"compatibility version",
]);
for (const rawLine of block.split("\n").slice(1)) {
const line = rawLine.trim();
if (line.length === 0) continue;
const key = /^(time stamp|\S+(?:\s+version)?)\s+/u.exec(line)?.[1];
if (key === undefined || !allowed.has(key))
throw new TypeError(
"otool dylib command contains ambiguous multiline text",
);
}
};
const scalarFields = (kind: string): readonly string[] => {
const common = ["cmd", "cmdsize"];
if (DYLIB_COMMANDS.has(kind))
return [
...common,
"name",
"time stamp",
"current version",
"compatibility version",
];
if (kind === "LC_LOAD_DYLINKER" || kind === "LC_ID_DYLINKER")
return [...common, "name"];
if (kind === "LC_UUID") return [...common, "uuid"];
if (kind === "LC_MAIN") return [...common, "entryoff"];
if (kind === "LC_BUILD_VERSION")
return [...common, "platform", "minos", "sdk", "ntools"];
if (kind.startsWith("LC_VERSION_MIN_")) return [...common, "version", "sdk"];
if (kind === "LC_SEGMENT" || kind === "LC_SEGMENT_64")
return [
...common,
"segname",
"vmaddr",
"vmsize",
"fileoff",
"filesize",
"maxprot",
"initprot",
"nsects",
"flags",
];
return common;
};
const collectUuid = (
kind: string,
fields: Readonly<Record<string, string | number | null>>,
@@ -161,11 +287,14 @@ const collectBuild = (
state: ParsedLoadCommands,
): void => {
if (kind === "LC_BUILD_VERSION") {
const tools = parseBuildTools(block);
if (numberField(fields, "ntools") !== tools.length)
throw new TypeError("otool build-tool count does not match ntools");
state.builds.push({
platform: stringField(fields, "platform"),
minimum_os: stringField(fields, "minos"),
sdk: stringField(fields, "sdk"),
tools: parseBuildTools(block),
tools,
});
return;
}
@@ -183,13 +312,7 @@ const collectDependency = (
fields: Readonly<Record<string, string | number | null>>,
state: ParsedLoadCommands,
): void => {
if (
!kind.startsWith("LC_LOAD_") &&
kind !== "LC_ID_DYLIB" &&
kind !== "LC_REEXPORT_DYLIB" &&
kind !== "LC_LAZY_LOAD_DYLIB"
)
return;
if (!DYLIB_COMMANDS.has(kind)) return;
state.dependencies.push({
path: stripOffsetSuffix(stringField(fields, "name")),
kind,
@@ -204,8 +327,13 @@ const collectSegment = (
fields: Readonly<Record<string, string | number | null>>,
state: ParsedLoadCommands,
): void => {
if (kind === "LC_SEGMENT" || kind === "LC_SEGMENT_64")
state.segments.push(parseSegment(block, fields));
if (kind !== "LC_SEGMENT" && kind !== "LC_SEGMENT_64") return;
const segment = parseSegment(block, fields);
if (numberField(fields, "nsects") !== segment.sections.length)
throw new TypeError(
"otool segment section count does not match its sections",
);
state.segments.push(segment);
};
const parseFields = (block: string): Record<string, string | number | null> => {
@@ -227,6 +355,15 @@ const parseFields = (block: string): Record<string, string | number | null> => {
return fields;
};
const requireUniqueField = (block: string, key: string): void => {
const escaped = key.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
const pattern = new RegExp(`^\\s*${escaped}\\s+`, "mu");
let count = 0;
for (const line of block.split("\n")) if (pattern.test(line)) count += 1;
if (count !== 1)
throw new TypeError(`otool field ${key} is missing or repeated`);
};
const parseSegment = (
block: string,
fields: Readonly<Record<string, string | number | null>>,
@@ -247,6 +384,16 @@ const parseSections = (block: string): ParsedSection[] =>
.slice(1)
.map((sectionBlock) => {
const fields = parseFields(`Section${sectionBlock}`);
for (const key of [
"sectname",
"segname",
"addr",
"size",
"offset",
"align",
"flags",
])
requireUniqueField(sectionBlock, key);
return {
segment: stringField(fields, "segname") ?? "unknown",
name: stringField(fields, "sectname") ?? "unknown",