fix(analysis): preserve producer identity and partial evidence

Reconcile Mach-O UUID observations without hiding malformed or conflicting sources. Require source-map identity digests to be supported by consistent observations. Keep truncated Android manifests as partial raw evidence, validate WABT section framing, and reject missing JEB inventories or error-marked success replies.

Consolidate native UUID parsing and simplify capacity and malformed-input fixtures. Focused source and public workflow checks pass, including native arm64e inspection and real WABT framing probes; a successful real JEB GUI project opening remains unverified.
This commit is contained in:
morluto
2026-10-12 12:37:00 +08:00
parent 1c64fe3eff
commit 6fb3a345fe
18 changed files with 680 additions and 50 deletions
+115
View File
@@ -4,6 +4,11 @@ import { AnalysisCancelledError } from "../domain/analysisErrorCore.js";
import { err, ok } from "../domain/result.js";
import type { NativeCommandCapture } from "./CommandRunner.js";
import { inspectNativeMacho } from "./NativeMachoInspection.js";
import {
NativeFixtureRunner,
nativeMachoTarget,
withOtoolMachHeader,
} from "../../tests/fixtures/nativeCommands.js";
const capture = (tool: string, stdout: string): NativeCommandCapture => ({
tool,
@@ -71,3 +76,113 @@ describe("Mach-O tool architecture selection", () => {
]);
});
});
describe("Mach-O UUID reconciliation", () => {
const validUuid = "01234567-89AB-CDEF-0123-456789ABCDEF";
const runInspection = async (
dwarfdump: string,
otoolUuids: readonly string[] = [validUuid],
targetPath = "/fixture/app",
) => {
const runner = new NativeFixtureRunner({
dwarfdump,
otool: withOtoolMachHeader(
otoolUuids
.map(
(uuid, index) =>
`Load command ${index}\n cmd LC_UUID\n cmdsize 24\n uuid ${uuid}`,
)
.join("\n"),
),
});
const result = await inspectNativeMacho({
target: nativeMachoTarget(targetPath),
run: (tool, args) => runner.run(tool, args),
invocation: (capture) => ({
tool: capture.tool,
command: [capture.executable, ...capture.arguments],
tool_version: capture.toolVersion,
version_reason: capture.versionReason,
executable_sha256: capture.executableSha256,
exit: { code: capture.exitCode, signal: capture.signal },
stdout_bytes: capture.stdoutBytes,
stderr_bytes: capture.stderrBytes,
}),
});
return result;
};
it("keeps a valid otool UUID when dwarfdump is malformed and reports the limitation", async () => {
const result = await runInspection("UUID: A (arm64) /fixture/app\n");
if (!result.ok) throw result.error;
expect(result.value.result).toMatchObject({ uuid: validUuid });
expect(result.value.limitations).toContain(
'dwarfdump --uuid returned malformed UUID "A"; using the unambiguous otool LC_UUID.',
);
});
it("does not choose between conflicting valid UUIDs", async () => {
const result = await runInspection(
`UUID: FEDCBA98-7654-3210-FEDC-BA9876543210 (arm64) /fixture/app\n`,
);
if (!result.ok) throw result.error;
expect(result.value.result).toMatchObject({ uuid: null });
expect(result.value.limitations).toContain(
`dwarfdump --uuid (FEDCBA98-7654-3210-FEDC-BA9876543210) conflicts with otool LC_UUID (${validUuid}); the image UUID is unknown.`,
);
});
it("accepts matching UUIDs with different case and preserves dwarfdump spelling", async () => {
const lower = validUuid.toLowerCase();
const result = await runInspection(`UUID: ${lower} (arm64) /fixture/app\n`);
if (!result.ok) throw result.error;
expect(result.value.result).toMatchObject({ uuid: lower });
});
it("uses a valid dwarfdump UUID when otool has no UUID observation", async () => {
const result = await runInspection(
`UUID: ${validUuid} (arm64) /fixture/app\n`,
[],
);
if (!result.ok) throw result.error;
expect(result.value.result).toMatchObject({ uuid: validUuid });
});
it("frames a path containing a newline and UUID-like text as one dwarfdump row", async () => {
const path =
"/fixture/\nUUID: FEDCBA98-7654-3210-FEDC-BA9876543210 (arm64) fake";
const result = await runInspection(
`UUID: ${validUuid} (arm64) ${path}\n`,
[validUuid],
path,
);
if (!result.ok) throw result.error;
expect(result.value.result).toMatchObject({ uuid: validUuid });
});
it("keeps a conflict between duplicate valid LC_UUID commands unknown despite dwarfdump", async () => {
const result = await runInspection(
`UUID: ${validUuid} (arm64) /fixture/app\n`,
[validUuid, "FEDCBA98-7654-3210-FEDC-BA9876543210"],
"/fixture/app",
);
if (!result.ok) throw result.error;
expect(result.value.result).toMatchObject({ uuid: null });
expect(result.value.limitations).toContain(
`otool returned conflicting LC_UUID values ${JSON.stringify(validUuid)} and ${JSON.stringify("FEDCBA98-7654-3210-FEDC-BA9876543210")}`,
);
});
it("keeps conflicting duplicate dwarfdump rows unknown despite otool", async () => {
const conflictingUuid = "FEDCBA98-7654-3210-FEDC-BA9876543210";
const result = await runInspection(
`UUID: ${validUuid} (arm64) /fixture/app\nUUID: ${conflictingUuid} (arm64) /fixture/app\n`,
);
if (!result.ok) throw result.error;
expect(result.value.result).toMatchObject({ uuid: null });
expect(result.value.limitations).toContain(
"dwarfdump --uuid returned conflicting UUIDs for selected architecture arm64",
);
});
});
+12 -5
View File
@@ -13,6 +13,7 @@ import { parseDyldSymbols } from "./parsers/dyldInfo.js";
import { parseLipoArchitectures } from "./parsers/lipo.js";
import { withoutEchoedPathHeader } from "./parsers/echoedPath.js";
import { parseOtoolLoadCommands } from "./parsers/otool.js";
import { reconcileMachoUuid } from "./parsers/machoUuid.js";
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
interface NativeMachoObservation {
@@ -50,7 +51,6 @@ const REQUIRED_SLICE_COMMANDS = [
const OPTIONAL_VTOOL_COMMAND = ["vtool", ["-show-build"]] as const;
const VTOOL_UNAVAILABLE_LIMITATION =
"vtool is unavailable; build metadata is normalized from otool only.";
/** Inspect one Mach-O with the required native commands and normalized output. */
export const inspectNativeMacho = async (
context: NativeMachoInspectionContext,
@@ -148,6 +148,7 @@ export const inspectNativeMacho = async (
limitations,
load,
architectures,
context.target.path,
{
name: selectedArchitectureName,
container_file_offset: containerOffset ?? null,
@@ -178,6 +179,7 @@ const normalizeMacho = (
additionalLimitations: readonly string[],
load: ReturnType<typeof parseOtoolLoadCommands>,
architectures: ReturnType<typeof parseLipoArchitectures>,
artifactPath: string,
selectedArchitecture: {
readonly name: string | null;
readonly container_file_offset: number | null;
@@ -200,9 +202,13 @@ const normalizeMacho = (
new Set(nmExports.map(({ name }) => name)),
);
const exports = uniqueSymbols([...dyldExports, ...nmExports]);
const uuid =
/UUID:\s*([A-Fa-f0-9-]+)/u.exec(byTool("dwarfdump").stdout)?.[1] ??
load.uuid;
const dwarfdump = byTool("dwarfdump");
const uuid = reconcileMachoUuid(
load.commands,
dwarfdump.stdout,
artifactPath,
selectedArchitecture.name,
);
const provenance = captures.map(toInvocation);
// A thread-state command carries the entrypoint in architecture-specific
// register state, so an absent decoded offset means unknown, not absent.
@@ -222,6 +228,7 @@ const normalizeMacho = (
]
: []),
...additionalLimitations,
...uuid.limitations,
...(threadEntrypoint ? [threadEntrypointLimitation] : []),
...(imageBase === null &&
/^\s*offset\s+symbol\s*$/mu.test(sliceOutput(byTool("dyld_info", 1)))
@@ -237,7 +244,7 @@ const normalizeMacho = (
word_size: parseWordSize(byTool("file").stdout),
file_type: load.fileType,
flags: load.flags,
uuid: uuid ?? null,
uuid: uuid.value,
entrypoints: covered(
load.entrypoints,
!threadEntrypoint,
+212
View File
@@ -0,0 +1,212 @@
import type { parseOtoolLoadCommands } from "./otool.js";
const MACHO_UUID = /^[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}$/iu;
type UuidObservation =
| { readonly kind: "absent" }
| { readonly kind: "valid"; readonly value: string }
| { readonly kind: "invalid" | "conflict"; readonly reason: string };
/** Reconcile the selected slice's UUID observations from otool and dwarfdump. */
export const reconcileMachoUuid = (
commands: ReturnType<typeof parseOtoolLoadCommands>["commands"],
dwarfdumpOutput: string,
artifactPath: string,
selectedArchitecture: string | null,
): {
readonly value: string | null;
readonly limitations: readonly string[];
} =>
reconcileObservations(
loadCommandUuid(commands),
parseDwarfdumpUuid(dwarfdumpOutput, artifactPath, selectedArchitecture),
);
const parseDwarfdumpUuid = (
output: string,
artifactPath: string,
selectedArchitecture: string | null,
): UuidObservation => {
const parsed = parseDwarfdumpRows(output, artifactPath);
return parsed.kind === "invalid"
? parsed
: selectDwarfdumpRow(parsed.rows, selectedArchitecture);
};
interface DwarfdumpUuidRow {
readonly value: string;
readonly architecture: string;
}
type DwarfdumpRows =
| { readonly kind: "rows"; readonly rows: readonly DwarfdumpUuidRow[] }
| { readonly kind: "invalid"; readonly reason: string };
const parseDwarfdumpRows = (
output: string,
artifactPath: string,
): DwarfdumpRows => {
if (output.trim().length === 0) return { kind: "rows", rows: [] };
// Frame the documented row header, then consume the exact operand path.
// Paths may contain newlines and text that resembles another UUID row.
const header = /UUID:[ \t]*([^\s]+)[ \t]+\(([^)\r\n]+)\) /uy;
const rows: DwarfdumpUuidRow[] = [];
let offset = 0;
while (offset < output.length) {
if (output.startsWith("\r\n", offset)) {
offset += 2;
continue;
}
if (output[offset] === "\n") {
offset += 1;
continue;
}
header.lastIndex = offset;
const match = header.exec(output);
if (match === null)
return {
kind: "invalid",
reason: "dwarfdump --uuid output contains an unrecognized row",
};
const value = match[1] ?? "";
const architecture = match[2] ?? "";
offset = header.lastIndex;
if (!output.startsWith(artifactPath, offset))
return {
kind: "invalid",
reason: `dwarfdump --uuid row does not match the selected artifact path (UUID ${JSON.stringify(value)})`,
};
offset += artifactPath.length;
if (offset < output.length && output.startsWith("\r\n", offset))
offset += 2;
else if (output[offset] === "\n") offset += 1;
else if (offset !== output.length)
return {
kind: "invalid",
reason: `dwarfdump --uuid returned malformed UUID row ${JSON.stringify(value)}`,
};
rows.push({ value, architecture });
}
return { kind: "rows", rows };
};
const selectDwarfdumpRow = (
rows: readonly DwarfdumpUuidRow[],
selectedArchitecture: string | null,
): UuidObservation => {
if (rows.length === 0) return { kind: "absent" };
const selectedRows =
selectedArchitecture === null
? rows
: rows.filter(
({ architecture }) => architecture === selectedArchitecture,
);
const validRows = selectedRows.filter(({ value }) => MACHO_UUID.test(value));
const distinctValid = new Set(
validRows.map(({ value }) => value.toLowerCase()),
);
if (distinctValid.size > 1)
return {
kind: "conflict",
reason: `dwarfdump --uuid returned conflicting UUIDs for selected architecture ${selectedArchitecture ?? "unknown"}`,
};
if (selectedRows.length !== 1)
return {
kind: "invalid",
reason:
selectedRows.length > 1
? `dwarfdump --uuid returned multiple rows for selected architecture ${selectedArchitecture}`
: `dwarfdump --uuid returned no row for selected architecture ${selectedArchitecture}`,
};
const [row] = selectedRows;
if (row === undefined) return { kind: "absent" };
if (!MACHO_UUID.test(row.value))
return {
kind: "invalid",
reason: `dwarfdump --uuid returned malformed UUID ${JSON.stringify(row.value)}`,
};
return { kind: "valid", value: row.value };
};
const loadCommandUuid = (
commands: ReturnType<typeof parseOtoolLoadCommands>["commands"],
): UuidObservation => {
const loadCommands = commands.filter(({ kind }) => kind === "LC_UUID");
if (loadCommands.length === 0) return { kind: "absent" };
if (loadCommands.length > 1) {
const observed = loadCommands
.map(({ fields }) => fields.uuid)
.filter(
(value): value is string =>
typeof value === "string" && MACHO_UUID.test(value),
);
const distinct = new Set(observed.map((value) => value.toLowerCase()));
return {
kind: distinct.size > 1 ? "conflict" : "invalid",
reason:
distinct.size > 1
? `otool returned conflicting LC_UUID values ${observed.map((value) => JSON.stringify(value)).join(" and ")}`
: `otool returned ${String(loadCommands.length)} LC_UUID commands`,
};
}
const value = loadCommands[0]?.fields.uuid;
return typeof value === "string" && MACHO_UUID.test(value)
? { kind: "valid", value }
: {
kind: "invalid",
reason: `otool LC_UUID contains malformed UUID ${JSON.stringify(value ?? null)}`,
};
};
const reconcileObservations = (
loadUuid: UuidObservation,
dwarfdump: UuidObservation,
): {
readonly value: string | null;
readonly limitations: readonly string[];
} => {
if (dwarfdump.kind === "valid" && loadUuid.kind === "valid") {
if (dwarfdump.value.toLowerCase() === loadUuid.value.toLowerCase())
return { value: dwarfdump.value, limitations: [] };
return {
value: null,
limitations: [
`dwarfdump --uuid (${dwarfdump.value}) conflicts with otool LC_UUID (${loadUuid.value}); the image UUID is unknown.`,
],
};
}
if (dwarfdump.kind === "valid" && loadUuid.kind === "conflict")
return { value: null, limitations: [loadUuid.reason] };
if (loadUuid.kind === "valid" && dwarfdump.kind === "conflict")
return { value: null, limitations: [dwarfdump.reason] };
if (dwarfdump.kind === "valid")
return {
value: dwarfdump.value,
limitations:
loadUuid.kind === "invalid"
? [`${loadUuid.reason}; using the unambiguous dwarfdump UUID.`]
: [],
};
if (loadUuid.kind === "valid")
return {
value: loadUuid.value,
limitations:
dwarfdump.kind === "invalid"
? [`${dwarfdump.reason}; using the unambiguous otool LC_UUID.`]
: [],
};
return {
value: null,
limitations: [
...(dwarfdump.kind === "invalid" || dwarfdump.kind === "conflict"
? [dwarfdump.reason]
: []),
...(loadUuid.kind === "invalid" || loadUuid.kind === "conflict"
? [loadUuid.reason]
: []),
],
};
};