Reverse engineer anything with agents, from app behavior down to native binaries.
TypeScript agent-skillsai-agentsbinary-analysisclaude-codeclicodexcordisdecompilerdeveloper-toolsdshdsh-pluginghidrahopperllmmcpmodel-context-protocolreareverse-engineeringstatic-analysistouhou
fix(macho): share width-specific load command alignment
morluto108c0e7e495b
diff --git a/src/artifacts/apple/MachoImage.fixture.ts b/src/artifacts/apple/MachoImage.fixture.tsindex 2fa611d1f..07fe1d316 100644--- a/src/artifacts/apple/MachoImage.fixture.ts+++ b/src/artifacts/apple/MachoImage.fixture.ts@@ -130,6 +130,22 @@ export const machoImage = (options: {return bytes;};+/** Thin Mach-O with one unknown command, for width and command-size regressions. */+export const machoImageWithUnknownCommand = (+ wide: boolean,+ commandSize: number,+): Uint8Array => {+ const command = new Uint8Array(commandSize);+ const view = new DataView(command.buffer);+ view.setUint32(0, 0x7f000001, true);+ view.setUint32(4, commandSize, true);+ return machoImage({+ cpu: wide ? CPU.arm64 : CPU.i386,+ wide,+ commands: [command],+ });+};+/*** A FAT container whose slices start on 4 KiB boundaries. Headers are* big-endian unless `littleEndian` selects the swapped FAT_CIGAM magics.diff --git a/src/artifacts/apple/MachoLoadCommandReader.ts b/src/artifacts/apple/MachoLoadCommandReader.tsindex 84267e7ed..490b2d0c6 100644--- a/src/artifacts/apple/MachoLoadCommandReader.ts+++ b/src/artifacts/apple/MachoLoadCommandReader.ts@@ -5,6 +5,7 @@ import type {} from "../../domain/apple/dylibResolution.js";import { machoCpuSubtypeBase } from "../../domain/apple/machoCpuIdentity.js";import {+ machoLoadCommandAlignment,classifyFatContainerIdentity,readFatContainerHeader,validateFatSliceIdentity,@@ -322,8 +323,6 @@ const decodeCommands = (readonly fatAlignmentExponent: number | null;},): MachoSlice => {- // loader.h: load commands are 8-byte aligned in 64-bit images, 4 in 32-bit.- const alignment = header.wide ? 8 : 4;const view = viewOf(bytes);const slice: MachoSlice = {architecture: architectureName(header.cpuType, header.cpuSubtype),@@ -353,7 +352,11 @@ const decodeCommands = ();const command = view.getUint32(offset, true);const size = view.getUint32(offset + 4, true);- if (size < 8 || size % alignment !== 0 || offset + size > bytes.byteLength)+ if (+ size < 8 ||+ size % machoLoadCommandAlignment(header.wide) !== 0 ||+ offset + size > bytes.byteLength+ )throw new MachoFormatIssue("malformed",`load command ${index} at offset ${offset} has invalid cmdsize ${size}`,diff --git a/src/domain/apple/machoContainer.ts b/src/domain/apple/machoContainer.tsindex bf1459d2e..7d5ae9f61 100644--- a/src/domain/apple/machoContainer.ts+++ b/src/domain/apple/machoContainer.ts@@ -1,5 +1,9 @@import { isJvmClassFile } from "./jvmClassFile.js";+/** loader.h: load commands are 8-byte aligned in 64-bit images, 4 in 32-bit. */+export const machoLoadCommandAlignment = (wide: boolean): 4 | 8 =>+ wide ? 8 : 4;+/** Physical facts for one entry in a Mach-O FAT architecture table. */export interface FatSliceDeclaration {readonly index: number;diff --git a/src/go/GoMachoImage.alignment.test.ts b/src/go/GoMachoImage.alignment.test.tsnew file mode 100644index 000000000..07a378a86--- /dev/null+++ b/src/go/GoMachoImage.alignment.test.ts@@ -0,0 +1,30 @@+import { expect, it } from "vitest";+import { machoImageWithUnknownCommand } from "../artifacts/apple/MachoImage.fixture.js";+import { readGoBinaryImage } from "./GoBinaryImage.js";++it("rejects a 12-byte load command in a 64-bit Go Mach-O image", () => {+ expect(() =>+ readGoBinaryImage(Buffer.from(machoImageWithUnknownCommand(true, 12))),+ ).toThrow(+ expect.objectContaining({+ name: "GoBinaryFormatFailure",+ kind: "malformed",+ }),+ );+});++it.each([+ { wide: true, size: 16, bits: 64 },+ { wide: false, size: 12, bits: 32 },+])(+ "accepts $bits-bit Mach-O load commands of size $size",+ ({ wide, size, bits }) => {+ expect(+ readGoBinaryImage(Buffer.from(machoImageWithUnknownCommand(wide, size))),+ ).toMatchObject({+ format: "macho",+ bits,+ build_info: null,+ });+ },+);diff --git a/src/go/GoMachoImage.ts b/src/go/GoMachoImage.tsindex cba13bf2d..6e2caae6c 100644--- a/src/go/GoMachoImage.ts+++ b/src/go/GoMachoImage.ts@@ -8,6 +8,7 @@ import {type GoImageSection,type GoZeroFillMapping,} from "./GoBinaryContainer.js";+import { machoLoadCommandAlignment } from "../domain/apple/machoContainer.js";/** Read thin Mach-O images, retaining the slice's exact file-backed mappings. */export const readGoMachoImage = (bytes: Buffer): GoBinaryContainer => {@@ -40,7 +41,11 @@ export const readGoMachoImage = (bytes: Buffer): GoBinaryContainer => {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)+ if (+ size < 8 ||+ size % machoLoadCommandAlignment(bits === 64) !== 0 ||+ size > end - offset+ )throw new GoBinaryFormatFailure("malformed","Mach-O load command size is invalid or truncated",diff --git a/src/native/AppleMachoSelection.test.ts b/src/native/AppleMachoSelection.test.tsindex af2d0be55..81c34fa7b 100644--- a/src/native/AppleMachoSelection.test.ts+++ b/src/native/AppleMachoSelection.test.ts@@ -6,6 +6,7 @@ import {dylibCommand,fatImage,machoImage,+ machoImageWithUnknownCommand,} from "../artifacts/apple/MachoImage.fixture.js";import { parseMachoLayout, selectMachoSlice } from "./AppleMachoSelection.js";import { decodeAppleDispatchMetadata } from "./AppleDispatchMetadata.js";@@ -15,6 +16,24 @@ const ARM64E_X1 = { type: 0x0100000c, subtype: 0x8000000c } as const;const X86_64H = { type: 0x01000007, subtype: 8 } as const;describe("native Mach-O slice selection", () => {+ it("rejects misaligned load commands", () => {+ expect(() =>+ parseMachoLayout(+ Buffer.from(machoImageWithUnknownCommand(true, 12)),+ "arm64",+ ),+ ).toThrow(/Invalid load command size/u);+ });++ it("accepts an aligned load command", () => {+ expect(+ parseMachoLayout(+ Buffer.from(machoImageWithUnknownCommand(true, 16)),+ "arm64",+ ).segments,+ ).toEqual([]);+ });+it("preserves high-bit section-name bytes instead of ASCII-folding metadata names", () => {const segment = Buffer.alloc(152);segment.writeUInt32LE(0x19, 0);diff --git a/src/native/AppleMachoSelection.ts b/src/native/AppleMachoSelection.tsindex c0c68068d..bcd07cc6c 100644--- a/src/native/AppleMachoSelection.ts+++ b/src/native/AppleMachoSelection.ts@@ -5,6 +5,7 @@ import {} from "./MachoArchitectureSelection.js";import { machoCpuSubtypeBase } from "../domain/apple/machoCpuIdentity.js";import {+ machoLoadCommandAlignment,readFatSliceDeclarations,validateFatSlice,type FatSliceDeclaration,@@ -192,7 +193,11 @@ export const parseMachoLayout = (kind: bytes.readUInt32LE(cursor),size: bytes.readUInt32LE(cursor + 4),};- if (command.size < 8 || cursor + command.size > commandEnd)+ if (+ command.size < 8 ||+ command.size % machoLoadCommandAlignment(true) !== 0 ||+ cursor + command.size > commandEnd+ )throw new RangeError("Invalid load command size");if (command.kind === 0x19) collectSegment(bytes, command, state);else collectFixupCommand(bytes, command, state);diff --git a/src/rust/RustBinaryImage.machoAlignment.test.ts b/src/rust/RustBinaryImage.machoAlignment.test.tsnew file mode 100644index 000000000..35ca20844--- /dev/null+++ b/src/rust/RustBinaryImage.machoAlignment.test.ts@@ -0,0 +1,26 @@+import { expect, it } from "vitest";+import { machoImageWithUnknownCommand } from "../artifacts/apple/MachoImage.fixture.js";+import { readRustBinaryImage } from "./RustBinaryImage.js";+import { RustAuditableFormatFailure } from "./RustAuditableReader.js";++it("maps malformed 64-bit Mach-O load-command alignment to Rust input failure", () => {+ expect(() =>+ readRustBinaryImage(Buffer.from(machoImageWithUnknownCommand(true, 12))),+ ).toThrow(RustAuditableFormatFailure);+ expect(() =>+ readRustBinaryImage(Buffer.from(machoImageWithUnknownCommand(true, 12))),+ ).toThrow(expect.objectContaining({ kind: "malformed" }));+});++it.each([+ { wide: true, size: 16 },+ { wide: false, size: 12 },+])(+ "accepts $size-byte Rust Mach-O command for wide=$wide",+ ({ wide, size }) => {+ expect(+ readRustBinaryImage(Buffer.from(machoImageWithUnknownCommand(wide, size)))+ .format,+ ).toBe("macho");+ },+);diff --git a/tests/acceptance/goBinaryCli.test.ts b/tests/acceptance/goBinaryCli.test.tsindex 1a4fef24e..5cf8b1abc 100644--- a/tests/acceptance/goBinaryCli.test.ts+++ b/tests/acceptance/goBinaryCli.test.ts@@ -3,6 +3,7 @@ import { join } from "node:path";import { createHash } from "node:crypto";import { expect } from "vitest";import { toolContract } from "../../src/contracts/toolContracts.js";+import { machoImageWithUnknownCommand } from "../../src/artifacts/apple/MachoImage.fixture.js";import {createGoBinaryByteStringFixture,createGoBinaryDiagnosticFixtures,@@ -127,6 +128,62 @@ for (const bits of [32, 64] as const) {}}+cliTest(+ "rejects misaligned 64-bit Mach-O through Go CLI and stdio MCP",+ async ({ cli }) => {+ const root = await createTestTempDirectory("rea-go-macho-alignment-");+ const { client, call } = await connectLocalToolsMcp();+ const expectedFailure = {+ code: "invalid_request",+ details: {+ operation: "inspect_go_binary",+ issues: [{ path: ["path"], reason: "invalid_format" }],+ },+ };++ for (const fixture of [+ { wide: true, size: 12, bits: 64, malformed: true },+ { wide: true, size: 16, bits: 64, malformed: false },+ { wide: false, size: 12, bits: 32, malformed: false },+ ]) {+ const path = join(root, `image-${fixture.bits}-${fixture.size}.macho`);+ await writeFile(+ path,+ machoImageWithUnknownCommand(fixture.wide, fixture.size),+ );+ const result = await cli.run({+ arguments: ["inspect-go-binary", path, "--json"],+ });+ const response = await call("inspect_go_binary", { path });++ if (fixture.malformed) {+ expect(result.exitCode).toBe(1);+ expect(result.json).toMatchObject(expectedFailure);+ expect(result.json).not.toHaveProperty("normalized_result");+ expect(parseMcpToolError(response).error).toMatchObject(+ expectedFailure,+ );+ expect(response.structuredContent).toBeUndefined();+ continue;+ }++ expect(result.exitCode, result.stderr).toBe(0);+ const evidence = toolContract("inspect_go_binary").outputSchema.parse(+ result.json,+ );+ expect(evidence.normalized_result).toMatchObject({+ format: "macho",+ bits: fixture.bits,+ build_info: null,+ });+ expect(response.isError, JSON.stringify(response)).not.toBe(true);+ expect(response.structuredContent).toEqual(evidence);+ }+ await client.ping();+ },+ 30000,+);+for (const expectedErrno of ["ELOOP", "ENAMETOOLONG"] as const) {cliTest.skipIf(expectedErrno === "ELOOP" && process.platform === "win32")(`reports native ${expectedErrno} path failure as invalid selected-path input through the public Go CLI`,diff --git a/tests/acceptance/rustBinaryCli.test.ts b/tests/acceptance/rustBinaryCli.test.tsindex d6ade5c41..fbd8f69f5 100644--- a/tests/acceptance/rustBinaryCli.test.ts+++ b/tests/acceptance/rustBinaryCli.test.ts@@ -4,12 +4,71 @@ import { pathToFileURL } from "node:url";import { join } from "node:path";import { expect } from "vitest";import { toolContract } from "../../src/contracts/toolContracts.js";+import { machoImageWithUnknownCommand } from "../../src/artifacts/apple/MachoImage.fixture.js";import {createRustImage,rustDependencyPayload,} from "../fixtures/rust/image.js";import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js";import { cliTest } from "../support/cli/cliFixture.js";+import { connectLocalToolsMcp } from "../fixtures/localToolsMcp.js";+import { parseMcpToolError } from "../fixtures/mcpToolError.js";++cliTest(+ "rejects misaligned 64-bit Mach-O through Rust CLI and stdio MCP",+ async ({ cli }) => {+ const root = await createTestTempDirectory("rea-rust-macho-alignment-");+ const { client, call } = await connectLocalToolsMcp();+ const expectedFailure = {+ code: "invalid_request",+ details: {+ operation: "inspect_rust_binary",+ issues: [{ path: ["path"], reason: "invalid_format" }],+ },+ };++ for (const fixture of [+ { wide: true, size: 12, bits: 64, malformed: true },+ { wide: true, size: 16, bits: 64, malformed: false },+ { wide: false, size: 12, bits: 32, malformed: false },+ ]) {+ const path = join(root, `image-${fixture.bits}-${fixture.size}.macho`);+ await writeFile(+ path,+ machoImageWithUnknownCommand(fixture.wide, fixture.size),+ );+ const result = await cli.run({+ arguments: ["inspect-rust-binary", path, "--json"],+ });+ const response = await call("inspect_rust_binary", { path });++ if (fixture.malformed) {+ expect(result.exitCode).toBe(1);+ expect(result.json).toMatchObject(expectedFailure);+ expect(result.json).not.toHaveProperty("normalized_result");+ expect(parseMcpToolError(response).error).toMatchObject(+ expectedFailure,+ );+ expect(response.structuredContent).toBeUndefined();+ continue;+ }++ expect(result.exitCode, result.stderr).toBe(0);+ const evidence = toolContract("inspect_rust_binary").outputSchema.parse(+ result.json,+ );+ expect(evidence.normalized_result).toMatchObject({+ format: "macho",+ bits: fixture.bits,+ auditable_metadata: null,+ });+ expect(response.isError, JSON.stringify(response)).not.toBe(true);+ expect(response.structuredContent).toEqual(evidence);+ }+ await client.ping();+ },+ 30000,+);cliTest("reports cargo-auditable packages through the public CLI",