chore: merge main into feat/dyld-shared-cache

This commit is contained in:
morluto
2026-10-08 17:02:53 +08:00
85 changed files with 5854 additions and 1121 deletions
+142
View File
@@ -0,0 +1,142 @@
import assert from "node:assert/strict";
import { fileURLToPath } from "node:url";
import { join } from "node:path";
import { runOwnedCommand } from "../../../dist/process/OwnedCommand.js";
import {
spawnOwnedProviderProcess,
ProviderProcessSupervisor,
} from "../../../dist/process/ProviderProcess.js";
import { cleanupOwnedProcessGroup } from "../../../dist/process/ProcessOwnership.js";
/** Execute fixture tooling under an owned deadline; fixture generation deliberately runs its own test program. */
export async function fixtureCommand(
command,
arguments_,
{ root, environment, runId },
) {
const result = await runOwnedCommand(
{
command,
arguments: arguments_,
cwd: root,
runId,
hostEnvironment: environment,
expectedCommand: null,
},
{ timeoutMs: 45_000, diagnosticBytes: 1024 * 1024 },
);
return result.stdout.text;
}
/** Build and record a source-owned two-thread crash without changing kernel core settings. */
export async function createRecordedCore(options) {
const executable = join(options.root, "fixture-program");
const core = join(options.root, "recording.core");
await fixtureCommand(
"gcc",
[
"-g",
"-O0",
"-pthread",
"-fno-pie",
"-no-pie",
fileURLToPath(
new URL("../../fixtures/recorded-crash.c", import.meta.url),
),
"-o",
executable,
],
options,
);
// Fixed relative arguments avoid putting selected filesystem paths in GDB command syntax.
await fixtureCommand(
options.environment.REA_PWNDBG_GDB,
[
"-nx",
"-nh",
"--batch",
"--quiet",
"-iex",
"set auto-load off",
"-iex",
"set debuginfod enabled off",
"-ex",
"set startup-with-shell off",
"-ex",
"set disable-randomization off",
"-ex",
"file ./fixture-program",
"-ex",
"run",
"-ex",
"generate-core-file ./recording.core",
],
options,
);
return core;
}
/** Retain authority over an unrelated live process used only as a historical-PID collision oracle. */
export async function startCoreSentinel(options) {
const launch = await spawnOwnedProviderProcess({
command: process.execPath,
arguments: [
"-e",
"process.stdout.write('ready\\n'); setInterval(() => {}, 1000)",
],
cwd: options.root,
hostEnvironment: options.environment,
runId: options.runId,
});
const supervisor = new ProviderProcessSupervisor({
...launch,
ownsProcessLifetime: true,
cleanup: () => cleanupOwnedProcessGroup(launch.ownership),
});
try {
await new Promise((resolve, reject) => {
const timer = setTimeout(
() => finish(new Error("Sentinel readiness timed out")),
10_000,
);
const onData = () => {
if (supervisor.snapshot().stdout.text.includes("ready\n")) finish();
};
const onExit = () =>
finish(new Error("Sentinel exited before readiness"));
function finish(error) {
clearTimeout(timer);
launch.process.stdout.off("data", onData);
launch.process.off("exit", onExit);
if (error) reject(error);
else resolve();
}
launch.process.stdout.on("data", onData);
launch.process.once("exit", onExit);
onData();
});
} catch (cause) {
try {
await supervisor.stop();
} finally {
supervisor.dispose();
}
throw cause;
}
return {
pid: launch.process.pid,
assertAlive() {
assert.equal(launch.process.exitCode, null);
assert.equal(launch.process.signalCode, null);
process.kill(launch.process.pid, 0);
},
async close() {
try {
const stopped = await supervisor.stop();
assert.notEqual(stopped.status, "incomplete", JSON.stringify(stopped));
} finally {
supervisor.dispose();
}
},
};
}
+133
View File
@@ -0,0 +1,133 @@
import assert from "node:assert/strict";
import { execFile } from "node:child_process";
import { createHash } from "node:crypto";
import { readFile } from "node:fs/promises";
import { promisify } from "node:util";
import { Client } from "@modelcontextprotocol/client";
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
import { parseEvidence } from "../../../dist/domain/evidence.js";
import { recordedCrashSchema } from "../../../dist/domain/native/recordedCrash.js";
import { mcpTextValue } from "../../lib/mcp-verifier-results.mjs";
const execute = promisify(execFile);
/** Exercise the public installed CLI and SDK transport with the same selected environment. */
export async function connectRecordedCrash({ entrypoint, environment }) {
const client = new Client({ name: "recorded-crash-verifier", version: "1" });
const transport = new StdioClientTransport({
command: process.execPath,
args: [entrypoint, "mcp"],
env: environment,
stderr: "pipe",
});
try {
await client.connect(transport);
} catch (cause) {
await transport.close();
throw cause;
}
return {
client,
async inspect(mode, path, { debuggerContext = false, category } = {}) {
const original = await readFile(path);
let evidence;
if (mode === "mcp") {
const response = await client.callTool(
{
name: "inspect_recorded_crash",
arguments: { path, include_debugger_context: debuggerContext },
},
{ timeout: 90_000 },
);
const value = JSON.parse(mcpTextValue(response));
if (category !== undefined) {
assert.equal(response.isError, true);
assert.equal(value.error.category, category, JSON.stringify(value));
assert.deepEqual(await readFile(path), original);
return value.error;
}
assert.notEqual(response.isError, true, JSON.stringify(value));
evidence = parseEvidence(value.evidence);
assert.deepEqual(value.result, evidence.normalized_result);
} else {
assert.equal(mode, "cli");
let response;
try {
response = await execute(
process.execPath,
[
entrypoint,
"inspect-recorded-crash",
path,
...(debuggerContext ? ["--debugger-context"] : []),
"--json",
],
{ env: environment, timeout: 90_000, maxBuffer: 32 * 1024 * 1024 },
);
} catch (cause) {
if (category === undefined || typeof cause.code !== "number")
throw cause;
const error = JSON.parse(cause.stdout);
assert.equal(error.category, category, JSON.stringify(error));
assert.deepEqual(await readFile(path), original);
return error;
}
assert.equal(category, undefined, "Expected an explicit failure");
evidence = parseEvidence(JSON.parse(response.stdout));
}
const report = recordedCrashSchema.parse(evidence.normalized_result);
assert.equal(
evidence.confidence,
debuggerContext ? "derived" : "observed",
);
assert.deepEqual(evidence.raw_result, report);
assert.equal(evidence.subject.local_path, path);
assert.equal(report.artifact.path, path);
assert.equal(
report.artifact.sha256,
createHash("sha256").update(original).digest("hex"),
);
assert.equal(report.artifact.bytes, original.length);
assert.equal(
evidence.provider.version,
"pwntools@4.15.0;pyelftools@0.33;unicorn@2.1.2",
);
assert.equal(report.target_execution, "not-performed");
assert.equal(report.live_process_identity, "unknown");
assert.equal(report.diagnostics.truncated, false);
assert.equal(
report.debugger.status,
debuggerContext ? "available" : "not-requested",
);
for (const note of report.notes) {
for (const [encoded, range] of [
[note.owner_bytes_base64, note.owner_location],
[note.descriptor_bytes_base64, note.descriptor_location],
]) {
const start = Number(BigInt(range.offset));
assert.deepEqual(
Buffer.from(encoded, "base64"),
original.subarray(start, start + Number(BigInt(range.bytes))),
);
}
}
for (const thread of report.threads) {
assert.equal(thread.registers.length, 27);
for (const register of thread.registers)
assert.equal(
BigInt(register.value),
original.readBigUInt64LE(Number(BigInt(register.location.offset))),
);
}
assert.deepEqual(await readFile(path), original);
return report;
},
async close() {
try {
await client.close();
} finally {
await transport.close();
}
},
};
}
@@ -0,0 +1,11 @@
import { connectRecordedCrash } from "./public.mjs";
const session = await connectRecordedCrash({
entrypoint: process.argv[2],
environment: process.env,
});
try {
await session.inspect("mcp", process.argv[3], { debuggerContext: true });
} finally {
await session.close();
}
+173
View File
@@ -0,0 +1,173 @@
import assert from "node:assert/strict";
import { readdir, readFile, realpath } from "node:fs/promises";
import { fileURLToPath } from "node:url";
import { isAbsolute, join, resolve } from "node:path";
import { runOwnedCommand } from "../../../dist/process/OwnedCommand.js";
/** Check attempted syscalls, including failed attempts, on a recorded PID that collides with an owned live sentinel. */
export async function verifyCoreInspectionTrace({
root,
environment,
entrypoint,
core,
sentinel,
runId,
}) {
const gdb = await realpath(environment.REA_PWNDBG_GDB);
const python = await realpath(environment.REA_PWNTOOLS_PYTHON);
const plugin = resolve(environment.REA_PWNDBG_GDBINIT, "..");
const helperPaths = (name) =>
new Set([
join(environment.REA_PWNDBG_VENV_PATH, "bin", name),
...(environment.PATH ?? "")
.split(":")
.filter(isAbsolute)
.map((directory) => join(directory, name)),
]);
const psPaths = helperPaths("ps");
const iconvPaths = helperPaths("iconv");
const gitPaths = helperPaths("git");
const observations = [];
for (const mode of ["cli", "mcp"]) {
sentinel.assertAlive();
const prefix = join(root, `inspection-${mode}.trace`);
const invocation =
mode === "cli"
? [
entrypoint,
"inspect-recorded-crash",
core,
"--debugger-context",
"--json",
]
: [
fileURLToPath(new URL("./trace-client.mjs", import.meta.url)),
entrypoint,
core,
];
await runOwnedCommand(
{
command: environment.REA_VERIFY_STRACE_COMMAND,
arguments: [
"-ff",
"-qq",
"-s",
"8192",
"-e",
"trace=%process,%network,%file,ptrace,process_vm_readv,process_vm_writev",
"-o",
prefix,
process.execPath,
...invocation,
],
cwd: root,
hostEnvironment: environment,
expectedCommand: null,
runId,
},
{ timeoutMs: 90_000, diagnosticBytes: 1024 * 1024 },
);
const executions = [];
const ownershipReads = [];
let gdbObserved = false;
for (const file of await readdir(root)) {
if (!file.startsWith(`inspection-${mode}.trace.`)) continue;
const text = await readFile(join(root, file), "utf8");
const ownershipTrace = text
.split("\n")
.some(
(line) =>
/^execve\("\/(?:usr\/)?bin\/ps",/u.test(line) &&
line.includes(
'["ps", "-axo", "pid=,ppid=,pgid=,stat=,command="]',
) &&
line.endsWith(" = 0"),
);
const pidReads = text
.split("\n")
.filter((line) => line.includes(`/proc/${sentinel.pid}/`));
if (ownershipTrace) {
for (const line of pidReads) {
assert.ok(
new RegExp(
`/proc/${sentinel.pid}/(?:stat|status|cmdline|wchan|environ)"`,
"u",
).test(line),
`Unexpected ownership observation of the sentinel: ${line}`,
);
ownershipReads.push(line);
}
} else
assert.deepEqual(
pidReads,
[],
`Historical PID caused a provider lookup in ${file}: ${pidReads.join("\n")}`,
);
assert.ok(
!/\bptrace\(/u.test(text),
`Inspection attempted ptrace: ${file}`,
);
assert.ok(
!/\bprocess_vm_(?:readv|writev)\(/u.test(text),
`Inspection attempted process memory access: ${file}`,
);
assert.ok(
!/\b(?:socket|connect|sendto|sendmsg)\([^\n]*(?:AF_INET|AF_INET6)/u.test(
text,
),
`Inspection attempted an Internet socket: ${file}`,
);
for (const line of text.split("\n")) {
if (!/execve(?:at)?\(/u.test(line)) continue;
const match = /^execve\("([^"]+)"/u.exec(line);
assert.notEqual(match, null, `Unresolved executable identity: ${line}`);
assert.ok(
/ = (?:0|-1 [A-Z]+)/u.test(line),
`Incomplete execution observation: ${line}`,
);
const executable = await realpath(match[1]).catch(() => match[1]);
const ownership =
psPaths.has(match[1]) &&
line.includes('["ps", "-axo", "pid=,ppid=,pgid=,stat=,command="]');
const iconv =
iconvPaths.has(match[1]) && line.includes('["iconv", "-l"]');
const version =
gitPaths.has(match[1]) &&
line.includes(
"[" +
[
"git",
"--git-dir",
join(plugin, ".git"),
"rev-parse",
"--short",
"HEAD",
]
.map((argument) => JSON.stringify(argument))
.join(", ") +
"]",
);
assert.ok(
[process.execPath, python, gdb].includes(executable) ||
ownership ||
iconv ||
version,
`Unexpected attempted host execution: ${line}`,
);
if (executable === gdb) gdbObserved = true;
executions.push(executable);
}
}
assert.ok(gdbObserved, "Trace must include the actual core-only GDB stage");
assert.ok(executions.includes(python));
sentinel.assertAlive();
observations.push({
mode,
executions,
historical_pid: sentinel.pid,
sentinel: "still-alive",
ownership_process_table_reads: ownershipReads,
});
}
return observations;
}