Skip to content

armgit / rea

Public Imported from GitHub
0

Reverse engineer anything with agents, from app behavior down to native binaries.

test(cli): keep IPC trace input under the Linux spawn limit (#5673)

morlutoc38f96fa693d
diff --git a/tests/acceptance/applications/electronIpcListenerCallsiteCli.test.ts b/tests/acceptance/applications/electronIpcListenerCallsiteCli.test.ts
index 54f6883e5..472603cf7 100644
--- a/tests/acceptance/applications/electronIpcListenerCallsiteCli.test.ts
+++ b/tests/acceptance/applications/electronIpcListenerCallsiteCli.test.ts
@@ -9,6 +9,10 @@ import { applicationFeatureTraceResultSchema } from "../../../src/domain/javascr
import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
+import {
+ assertSpawnArgumentsWithinLimit,
+ LINUX_4K_SINGLE_ARGUMENT_BYTES,
+} from "../../support/process/spawnArgumentLimit.js";
cliTest.for(["CLI", "stdio MCP"] as const)(
"counts exposed IPC listener callsites once and retains bridge paths through %s",
@@ -104,12 +108,24 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
};
let traceEvidence: unknown;
if (surface === "CLI") {
- // The application Evidence document exceeds the runner argument limit
- // when it is placed on argv. The command reads the same JSON from a file.
+ // Linux counts one argv string plus its trailing NUL against
+ // MAX_ARG_STRLEN (32 pages) and returns E2BIG before the CLI starts.
+ // This Evidence document is past that ceiling, so the command reads the
+ // same JSON from a file instead of argv.
+ const serialized = JSON.stringify(traceArguments);
+ expect(Buffer.byteLength(serialized)).toBeGreaterThan(
+ LINUX_4K_SINGLE_ARGUMENT_BYTES,
+ );
const traceInput = join(root, "trace-input.json");
- await writeFile(traceInput, JSON.stringify(traceArguments));
+ await writeFile(traceInput, serialized);
+ const traceCommand = [
+ "trace-application-feature",
+ traceInput,
+ "--json",
+ ] as const;
+ assertSpawnArgumentsWithinLimit(traceCommand);
const response = await cli.run({
- arguments: ["trace-application-feature", traceInput, "--json"],
+ arguments: traceCommand,
});
expect(response.exitCode, response.stderr).toBe(0);
traceEvidence = response.json;
diff --git a/tests/boundary/process/spawnArgumentLimit.test.ts b/tests/boundary/process/spawnArgumentLimit.test.ts
new file mode 100644
index 000000000..78e64518a
--- /dev/null
+++ b/tests/boundary/process/spawnArgumentLimit.test.ts
@@ -0,0 +1,181 @@
+import { execFileSync } from "node:child_process";
+import { writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { expect, it } from "vitest";
+
+import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
+import { processTest } from "../../support/process/processFixture.js";
+import {
+ acceptedSpawnPayloadBytes,
+ assertSpawnArgumentsWithinLimit,
+ LINUX_4K_SINGLE_ARGUMENT_BYTES,
+} from "../../support/process/spawnArgumentLimit.js";
+
+const minimalSpawnEnvironment = (): NodeJS.ProcessEnv => ({
+ PATH: process.env.PATH ?? "",
+ ...(process.platform === "win32"
+ ? {
+ SystemRoot: process.env.SystemRoot,
+ TEMP: tmpdir(),
+ TMP: tmpdir(),
+ }
+ : {}),
+});
+
+const linuxGetconf = (name: "PAGE_SIZE" | "ARG_MAX"): number => {
+ const raw = execFileSync("getconf", [name], { encoding: "utf8" }).trim();
+ const value = Number(raw);
+ if (!Number.isSafeInteger(value) || value < 1)
+ throw new Error(`unexpected ${name} ${raw}`);
+ return value;
+};
+
+/** Linux `execve` stores one native pointer per argv and environment string. */
+const linuxPointerBytes = (): number =>
+ process.arch === "arm" ||
+ process.arch === "ia32" ||
+ process.arch === "mips" ||
+ process.arch === "mipsel"
+ ? 4
+ : 8;
+
+const execStringBytes = (value: string): number => Buffer.byteLength(value) + 1;
+
+const captureSpawnFailure = async (
+ run: () => Promise<unknown>,
+): Promise<unknown> => {
+ try {
+ await run();
+ } catch (error) {
+ return error;
+ }
+ return undefined;
+};
+
+processTest(
+ "spawns a file path when the payload exceeds the single-argument budget",
+ async ({ processes }) => {
+ const root = await createTestTempDirectory("rea-spawn-argument-");
+ const payload = "x".repeat(LINUX_4K_SINGLE_ARGUMENT_BYTES + 1);
+ const file = join(root, "payload.txt");
+ await writeFile(file, payload);
+ expect(() => assertSpawnArgumentsWithinLimit([file])).not.toThrow();
+ expect(() => assertSpawnArgumentsWithinLimit([payload])).toThrow(/E2BIG/u);
+ const result = await processes.run(
+ process.execPath,
+ ["-e", "process.exit(0)", file],
+ { env: minimalSpawnEnvironment(), timeoutMs: 15_000 },
+ );
+ expect(result.exitCode).toBe(0);
+ },
+);
+
+it("fits the accepted payload to both the single-string and aggregate budgets", () => {
+ const fixedStringBytes = 500;
+ const pointerCount = 5;
+ const pointerBytes = 8;
+ expect(
+ acceptedSpawnPayloadBytes({
+ pageSize: 4096,
+ argMax: 2 * 1024 * 1024,
+ pointerBytes,
+ pointerCount,
+ fixedStringBytes,
+ }),
+ ).toBe(LINUX_4K_SINGLE_ARGUMENT_BYTES);
+ const tight = acceptedSpawnPayloadBytes({
+ pageSize: 4096,
+ argMax: 32 * 4096,
+ pointerBytes,
+ pointerCount,
+ fixedStringBytes,
+ });
+ expect(tight).toBe(
+ 32 * 4096 - pointerCount * pointerBytes - fixedStringBytes - 1,
+ );
+ expect(tight).toBeLessThan(LINUX_4K_SINGLE_ARGUMENT_BYTES);
+ expect(
+ acceptedSpawnPayloadBytes({
+ pageSize: 4096,
+ argMax: 32 * 4096,
+ pointerBytes,
+ pointerCount,
+ fixedStringBytes: 32 * 4096,
+ }),
+ ).toBeUndefined();
+});
+
+it("counts UTF-8 bytes when applying the single-argument budget", () => {
+ const argument = "é".repeat(
+ Math.ceil((LINUX_4K_SINGLE_ARGUMENT_BYTES + 1) / 2),
+ );
+ expect(argument.length).toBeLessThanOrEqual(LINUX_4K_SINGLE_ARGUMENT_BYTES);
+ expect(Buffer.byteLength(argument)).toBeGreaterThan(
+ LINUX_4K_SINGLE_ARGUMENT_BYTES,
+ );
+ expect(() => assertSpawnArgumentsWithinLimit([argument])).toThrow(/E2BIG/u);
+ expect(() =>
+ assertSpawnArgumentsWithinLimit([
+ "x".repeat(LINUX_4K_SINGLE_ARGUMENT_BYTES),
+ ]),
+ ).not.toThrow();
+});
+
+processTest.skipIf(process.platform !== "linux")(
+ "matches the kernel single-argument ceiling through the test process registry",
+ async ({ processes }) => {
+ const script = "process.exit(0)";
+ const environment = minimalSpawnEnvironment();
+ const environmentEntries = Object.entries(environment).flatMap(
+ ([key, value]) =>
+ typeof value === "string" ? [[key, value] as const] : [],
+ );
+ const pageSize = linuxGetconf("PAGE_SIZE");
+ const singleStringBytes = 32 * pageSize - 1;
+ expect(LINUX_4K_SINGLE_ARGUMENT_BYTES).toBeLessThanOrEqual(
+ singleStringBytes,
+ );
+ if (pageSize === 4096)
+ expect(LINUX_4K_SINGLE_ARGUMENT_BYTES).toBe(singleStringBytes);
+ // The filename is copied before argv, so the executable path is counted twice.
+ const fixedStringBytes =
+ execStringBytes(process.execPath) +
+ execStringBytes(process.execPath) +
+ execStringBytes("-e") +
+ execStringBytes(script) +
+ environmentEntries.reduce(
+ (sum, [key, value]) => sum + execStringBytes(`${key}=${value}`),
+ 0,
+ );
+ const accepted = acceptedSpawnPayloadBytes({
+ pageSize,
+ argMax: linuxGetconf("ARG_MAX"),
+ pointerBytes: linuxPointerBytes(),
+ pointerCount: Math.max(4, 1) + environmentEntries.length,
+ fixedStringBytes,
+ });
+
+ const run = (payloadBytes: number) =>
+ processes.run(
+ process.execPath,
+ ["-e", script, "x".repeat(payloadBytes)],
+ { env: environment, timeoutMs: 15_000 },
+ );
+ if (accepted !== undefined) {
+ const result = await run(accepted);
+ expect(result.exitCode).toBe(0);
+ }
+ expect(
+ await captureSpawnFailure(() => run(singleStringBytes + 1)),
+ ).toMatchObject({
+ code: "E2BIG",
+ });
+ if (accepted !== undefined && accepted < singleStringBytes) {
+ expect(await captureSpawnFailure(() => run(accepted + 1))).toMatchObject({
+ code: "E2BIG",
+ });
+ }
+ },
+);
diff --git a/tests/composition/reverseEngineeringAdmission.test.ts b/tests/composition/reverseEngineeringAdmission.test.ts
index 8440827b3..cb4d03f9d 100644
--- a/tests/composition/reverseEngineeringAdmission.test.ts
+++ b/tests/composition/reverseEngineeringAdmission.test.ts
@@ -263,7 +263,9 @@ it.each([
] as const)(
"classifies a $code command failure with captured output $captured while the caller is aborted",
async ({ captured, code, tag }) => {
- const directory = await mkdtemp(join(tmpdir(), "rea-reverse-command-abort-"));
+ const directory = await mkdtemp(
+ join(tmpdir(), "rea-reverse-command-abort-"),
+ );
const path = join(directory, "fixture.bin");
await writeFile(path, "fixture");
const reason = Object.freeze({ requested: `stop-${code}` });
@@ -287,9 +289,7 @@ it.each([
);
expect(result).toMatchObject({ ok: false, error: { _tag: tag } });
if (result.ok) return;
- expect(result.error.cause).toBe(
- code === "ABORT_ERR" ? reason : failure,
- );
+ expect(result.error.cause).toBe(code === "ABORT_ERR" ? reason : failure);
if (captured && code === "ABORT_ERR") {
expect(result.error.capturedOutput).toMatchObject({
stdout: "partial stdout",
diff --git a/tests/support/cli/cliFixture.ts b/tests/support/cli/cliFixture.ts
index 3ee43177a..9d093c7da 100644
--- a/tests/support/cli/cliFixture.ts
+++ b/tests/support/cli/cliFixture.ts
@@ -182,9 +182,8 @@ const createFileMcpSession = (
compileCache: string,
): { session: SharedMcpSession; close(): Promise<void> } =>
createSharedMcpSession(async (registerCleanup, isClosed) => {
- const { connectLocalToolsMcp } = await import(
- "../../fixtures/localToolsMcp.js"
- );
+ const { connectLocalToolsMcp } =
+ await import("../../fixtures/localToolsMcp.js");
if (isClosed()) throw sharedMcpSessionClosed();
const mcp = await connectLocalToolsMcp(
{ NODE_COMPILE_CACHE: compileCache },
diff --git a/tests/support/process/spawnArgumentLimit.ts b/tests/support/process/spawnArgumentLimit.ts
new file mode 100644
index 000000000..962d934cf
--- /dev/null
+++ b/tests/support/process/spawnArgumentLimit.ts
@@ -0,0 +1,66 @@
+import { Buffer } from "node:buffer";
+
+/**
+ * Largest single argv or environment string Linux will pass to `execve` on a
+ * 4 KiB page host. The kernel's `MAX_ARG_STRLEN` is 32 pages and includes the
+ * trailing NUL, so the caller-visible budget is one byte smaller. GitHub
+ * Actions runners use 4 KiB pages. One argument past this budget fails with
+ * `E2BIG` before the process starts. The combined argv, environment, filename,
+ * and pointer table must also fit in `ARG_MAX`, which shrinks with the stack.
+ */
+export const LINUX_4K_SINGLE_ARGUMENT_BYTES = 32 * 4096 - 1;
+
+/**
+ * Largest payload that fits this execve image.
+ *
+ * `fixedStringBytes` counts the filename, every argv string except the
+ * payload, and every `KEY=value` environment string, each including its NUL.
+ * `pointerCount` is `max(argc, 1) + envc`: Linux reserves that many native
+ * pointers inside `ARG_MAX` before it copies strings. The payload's own NUL
+ * is reserved here. The result is undefined when the fixed image already
+ * fills `ARG_MAX`.
+ */
+export const acceptedSpawnPayloadBytes = (input: {
+ readonly pageSize: number;
+ readonly argMax: number;
+ readonly pointerBytes: number;
+ readonly pointerCount: number;
+ readonly fixedStringBytes: number;
+}): number | undefined => {
+ for (const [name, value] of [
+ ["pageSize", input.pageSize],
+ ["argMax", input.argMax],
+ ["pointerBytes", input.pointerBytes],
+ ["pointerCount", input.pointerCount],
+ ["fixedStringBytes", input.fixedStringBytes],
+ ] as const) {
+ if (!Number.isSafeInteger(value) || value < 0)
+ throw new Error(`${name} must be a non-negative safe integer`);
+ }
+ if (input.pageSize < 1 || input.pointerBytes < 1 || input.pointerCount < 1)
+ throw new Error(
+ "page size, pointer size, and pointer count must be positive",
+ );
+ const singleStringBytes = 32 * input.pageSize - 1;
+ const aggregatePayload =
+ input.argMax -
+ input.pointerCount * input.pointerBytes -
+ input.fixedStringBytes -
+ 1;
+ if (aggregatePayload < 1) return undefined;
+ return Math.min(singleStringBytes, aggregatePayload);
+};
+
+/** Require every argv string to fit in the Linux single-argument budget. */
+export const assertSpawnArgumentsWithinLimit = (
+ arguments_: readonly string[],
+): void => {
+ for (const argument of arguments_) {
+ const bytes = Buffer.byteLength(argument);
+ if (bytes > LINUX_4K_SINGLE_ARGUMENT_BYTES) {
+ throw new Error(
+ `spawn argument is ${bytes} bytes; one Linux argument above ${LINUX_4K_SINGLE_ARGUMENT_BYTES} bytes fails with E2BIG before the process starts. Pass the payload through a file.`,
+ );
+ }
+ }
+};