Files
rea/src/go/GoMachoImage.ts
T
a1b5d51a8d feat(go): inspect embedded binary build metadata (#1363)
* feat(go): inspect embedded binary build metadata

* fix(go): preserve byte metadata and validate container mappings

* fix(go): support moduleless legacy build metadata

Recognize optional module string headers in declared zero-filled memory while rejecting ambiguous and unmapped pointers. Preserve the original module-pointer field as the zero-byte source anchor.

Classify initial symlink-loop and overlong-path failures as invalid input, with CLI and MCP regressions.

* fix(go): reject undersized PE optional headers

* fix(native): stabilize ELF memory checks and clean up exec wrappers

Use existing parent/group/run-token ownership for caller-selected Python launchers, which can exec through a shell or prlimit. Add cancellation regressions for the valid wrapper and wrong-parent/token cases.

Replace the timing-dependent 30,000-section memory workload with a valid 32 MiB padded ELF under a 64 MiB address-space limit. Check the same image successfully through CLI and MCP before requiring a typed memory failure, preserving the production timeout and all error assertions.

Validation: npm run check and check:fast passed; 61 focused tests passed including Go CLI/MCP and session snapshots. Real decoder probes with pinned packages passed on Python 3.12.3 and 3.12.14. The full local ELF verifier is blocked by this container's procps/process-ownership boundary; the exact pushed head requires GitHub's real-binary-layout lane.

* test: repair Electron fixtures and stabilize catalog startup checks

Declare Electron imports in option, preload override, and path-resolution fixtures after upstream began requiring proven API provenance. Retain all option and preload assertions and adjust exact source ranges for the added import line.

Use the existing bounded acceptance timeout for the cold catalog lifecycle test instead of a separate 15-second ceiling. This retains the coverage allowance and all catalog, error, and cleanup assertions without retries.

Validation: npm run check, final check:fast, formatting and diff checks passed. Source path regression and Go boundary/MCP/service checks passed. All 20 Go CLI cases and both supported-host runtime cases passed on rerun; two macOS-only cases skipped on Linux. A prior contended local run timed out once in a Go CLI diagnostic; that case passed on rerun. Electron process-boundary verification is blocked locally by procps namespace inspection and requires fresh CI.

* test(mcp): isolate nested schema references between tool contracts

Clear Ajv's non-meta schema registry after each root, including compilation failures. Disabling root registration alone leaves nested IDs available to later tools and can let a dangling reference pass the catalog gate.

Add regressions for leakage after successful and failed compilation while retaining shared meta-schema validators. The regression failed before the fix; all 11 schema cases and full npm run check pass. Reviewed independently.

* test(ci): align Go effects and source-map verification contracts

Audit the Go inspector wording as static metadata inspection. Assert retained source declaration indexes in BOM reconstruction and the compiler-derived nested-map oracle. Keep a 45,000-map admission control below the 32 MiB output budget and the 50,000-map overflow case above it with the expanded representation.

Validation: reproduced all four failing assertions, then passed 120 focused tests and the final admission suite. npm run check and real Chrome 154 / esbuild 0.25.10 source-map verification passed, including all four nested-map scenarios and verified process lineage.

---------

Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
2026-10-12 11:34:02 +08:00

169 lines
5.7 KiB
TypeScript

import {
GoBinaryFormatFailure,
GoBinaryReader,
mappedFileOffset,
type GoBinaryContainer,
type GoFileMapping,
type GoZeroFillMapping,
} from "./GoBinaryContainer.js";
/** Read thin Mach-O images, retaining the slice's exact file-backed mappings. */
export const readGoMachoImage = (bytes: Buffer): GoBinaryContainer => {
const magic = bytes.readUInt32BE(0);
const little = magic === 0xcefaedfe || magic === 0xcffaedfe;
const bits = magic === 0xfeedfacf || magic === 0xcffaedfe ? 64 : 32;
const reader = new GoBinaryReader(bytes, little);
const headerSize = bits === 64 ? 32 : 28;
reader.range(0, headerSize, "Mach-O header");
const count = reader.u32(16);
const commandBytes = reader.u32(20);
const commandStart = reader.table(
BigInt(headerSize),
commandBytes,
1,
"Mach-O load commands",
);
if (count > Math.floor(commandBytes / 8))
throw new GoBinaryFormatFailure(
"malformed",
"Mach-O command count exceeds its load-command range",
);
const mappings: GoFileMapping[] = [];
const zeroFills: GoZeroFillMapping[] = [];
const named: GoFileMapping[] = [];
let fallback: GoFileMapping | null = null;
let offset = commandStart;
const end = commandStart + commandBytes;
for (let index = 0; index < count; index++) {
const command = reader.u32(offset);
const size = reader.u32(offset + 4);
if (size < 8 || size % 4 !== 0 || size > end - offset)
throw new GoBinaryFormatFailure(
"malformed",
"Mach-O load command size is invalid or truncated",
);
if (command === 1 || command === 0x19) {
const wide = command === 0x19;
if (wide !== (bits === 64))
throw new GoBinaryFormatFailure(
"malformed",
"Mach-O segment command does not match the header width",
);
const segmentHeader = wide ? 72 : 56;
const sectionWidth = wide ? 80 : 68;
if (size < segmentHeader)
throw new GoBinaryFormatFailure(
"malformed",
"Mach-O segment header is truncated",
);
const address = reader.word(offset + 24, bits);
const memorySize = reader.word(offset + (wide ? 32 : 28), bits);
const fileOffset = reader.word(offset + (wide ? 40 : 32), bits);
const fileSize = reader.word(offset + (wide ? 48 : 36), bits);
const maxProtection = reader.u32(offset + (wide ? 56 : 40));
const protection = reader.u32(offset + (wide ? 60 : 44));
const sectionCount = reader.u32(offset + (wide ? 64 : 48));
if (fileSize > memorySize || address + memorySize > 1n << BigInt(bits))
throw new GoBinaryFormatFailure(
"malformed",
"Mach-O segment addresses or sizes are invalid",
);
if (sectionCount > Math.floor((size - segmentHeader) / sectionWidth))
throw new GoBinaryFormatFailure(
"malformed",
"Mach-O section table exceeds its segment command",
);
const mapping = {
...(fileSize === 0n
? { offset: 0, size: 0 }
: reader.fileRange(fileOffset, fileSize, "Mach-O segment")),
address,
};
const name = fixedName(
reader.range(offset + 8, 16, "Mach-O segment name"),
);
if (mapping.size !== 0 && name !== "__PAGEZERO") mappings.push(mapping);
if (memorySize > fileSize && name !== "__PAGEZERO")
zeroFills.push({
address: address + fileSize,
size: memorySize - fileSize,
});
if (
fallback === null &&
address !== 0n &&
mapping.size !== 0 &&
protection === 3 &&
maxProtection === 3
)
fallback = mapping;
for (let sectionIndex = 0; sectionIndex < sectionCount; sectionIndex++) {
const section = offset + segmentHeader + sectionIndex * sectionWidth;
if (
fixedName(reader.range(section, 16, "Mach-O section name")) !==
"__go_buildinfo"
)
continue;
const sectionFlags = reader.u32(section + (wide ? 64 : 56));
if ([1, 0xc, 0x12].includes(sectionFlags & 0xff))
throw new GoBinaryFormatFailure(
"malformed",
"Mach-O build-info section is zero-fill data",
);
const sectionAddress = reader.word(section + 32, bits);
const sectionSize = reader.word(section + (wide ? 40 : 36), bits);
const sectionOffset = BigInt(reader.u32(section + (wide ? 48 : 40)));
const info = {
...reader.fileRange(
sectionOffset,
sectionSize,
"Mach-O build-info section",
),
address: sectionAddress,
};
if (
mappedFileOffset([mapping], sectionAddress, info.size) !== info.offset
)
throw new GoBinaryFormatFailure(
"malformed",
"Mach-O build-info section disagrees with its segment",
);
named.push(info);
}
}
offset += size;
}
if (offset !== end)
throw new GoBinaryFormatFailure(
"malformed",
"Mach-O load-command byte count does not match its commands",
);
if (named.length > 1)
throw new GoBinaryFormatFailure(
"malformed",
"Mach-O has ambiguous build-info sections",
);
const cpu = reader.u32(4);
const names = new Map([
[7, "386"],
[0x01000007, "amd64"],
[12, "arm"],
[0x0100000c, "arm64"],
[18, "ppc"],
[0x01000012, "ppc64"],
]);
return {
format: "macho",
architecture: names.get(cpu) ?? `macho-cpu-${cpu}`,
bits,
byte_order: little ? "little" : "big",
mappings,
zero_fills: zeroFills,
search: named[0] ?? fallback,
};
};
const fixedName = (bytes: Buffer): string => {
const nul = bytes.indexOf(0);
return bytes.subarray(0, nul < 0 ? bytes.length : nul).toString("latin1");
};