Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion src/io/PipeWriter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ pub trait PosixPipeWriter {
self.try_write_with_write_fn(buf, sys::write)
}
FileType::Pipe => self.try_write_with_write_fn(buf, write_to_blocking_pipe),
FileType::Socket => self.try_write_with_write_fn(buf, sys::send_non_block),
FileType::Socket => self.try_write_with_write_fn(buf, write_to_socket),
}
}

Expand Down Expand Up @@ -232,6 +232,20 @@ fn write_to_blocking_pipe(fd: Fd, buf: &[u8]) -> sys::Result<usize> {
}
}

/// A pipe's errors for the socket that stands in for one: syscall `write` as in
/// Node, and macOS's mid-send ENOTCONN as EPIPE. Node passes ENOTCONN through;
/// Bun's callers (FileSink, the shell) only know EPIPE, so it is folded here.
/// https://github.com/apple-oss-distributions/xnu/blob/xnu-12377.121.6/bsd/kern/uipc_usrreq.c#L605-L619
Comment thread
robobun marked this conversation as resolved.
Resolved
fn write_to_socket(fd: Fd, buf: &[u8]) -> sys::Result<usize> {
sys::send_non_block(fd, buf).map_err(|err| {
let errno = match err.get_errno() {
sys::E::ENOTCONN => sys::E::EPIPE,
errno => errno,
};
sys::Error::from_code(errno, sys::Tag::write)
})
}

// ──────────────────────────────────────────────────────────────────────────
// PosixBufferedWriter
// ──────────────────────────────────────────────────────────────────────────
Expand Down
129 changes: 129 additions & 0 deletions test/js/node/child_process/child-process-stdin-send-errno.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
// On POSIX, Bun backs a "pipe" child stdio with socketpair(2) and writes to it
// with send(2). When the child closes its end while a send is copying data in,
// the macOS kernel fails the send with ENOTCONN where a pipe reports EPIPE. Bun
// reports the socket the way a pipe would: EPIPE from "write". The race is
// timing dependent, so an LD_PRELOAD shim makes send() on the child's stdin
// socket fail with a chosen errno instead.
import { afterAll, beforeAll, describe, expect, test } from "bun:test";
import { bunEnv, bunExe, isLinux, tempDir } from "harness";
import { constants } from "node:os";
import { join } from "node:path";

const cc = Bun.which("cc") || Bun.which("gcc") || Bun.which("clang");

// STDIN_FAIL_SEND_ERRNO=<n>: every send() on a non-stdio AF_UNIX socket fails
// with errno n. The child's stdin is the only such socket the fixture writes.
const SHIM_C = /* c */ `
#define _GNU_SOURCE
#include <dlfcn.h>
#include <errno.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

static ssize_t (*real_send)(int, const void *, size_t, int);
static int fail_errno = -1;

static int is_unix_sock(int fd) {
struct stat st;
if (fstat(fd, &st) != 0 || !S_ISSOCK(st.st_mode)) return 0;
int domain = 0;
socklen_t len = sizeof(domain);
return getsockopt(fd, SOL_SOCKET, SO_DOMAIN, &domain, &len) == 0 && domain == AF_UNIX;
}

ssize_t send(int fd, const void *buf, size_t len, int flags) {
if (!real_send) {
real_send = (ssize_t (*)(int, const void *, size_t, int))dlsym(RTLD_NEXT, "send");
const char *value = getenv("STDIN_FAIL_SEND_ERRNO");
fail_errno = value ? atoi(value) : 0;
}
if (fail_errno > 0 && fd > 2 && is_unix_sock(fd)) {
errno = fail_errno;
return -1;
}
return real_send(fd, buf, len, flags);
}
`;

// The child only has to exist long enough to own the other end of the stdin
// socketpair. It runs without the shim so the fault stays in the parent.
const FIXTURE = /* js */ `
import { spawn } from "node:child_process";
const env = { ...process.env };
delete env.LD_PRELOAD;
delete env.STDIN_FAIL_SEND_ERRNO;
const child = spawn(process.execPath, ["-e", "setTimeout(() => {}, 30_000)"], {
stdio: ["pipe", "ignore", "ignore"],
env,
});
// "error" precedes "close", so a close without an error reports as such.
const error = await new Promise(resolve => {
child.stdin.on("error", err => resolve({ code: err.code, syscall: err.syscall, errno: err.errno }));
child.stdin.on("close", () => resolve("stdin closed without an error"));
child.on("error", err => resolve("spawn failed: " + err.code));
child.stdin.end(Buffer.alloc(64 * 1024, 0x61));
});
child.kill();
console.log(JSON.stringify(error));
`;

describe.skipIf(!isLinux || !cc)("node:child_process stdin write error on a socketpair", () => {
let shimPath: string;
let dir: ReturnType<typeof tempDir>;

beforeAll(async () => {
dir = tempDir("child-stdin-send-errno", {
"shim.c": SHIM_C,
"fixture.mjs": FIXTURE,
});
shimPath = join(String(dir), "shim.so");
await using ccProc = Bun.spawn({
cmd: [cc!, "-shared", "-fPIC", "-o", shimPath, join(String(dir), "shim.c"), "-ldl"],
env: bunEnv,
stdout: "pipe",
stderr: "pipe",
});
const [ccOut, ccErr, ccExit] = await Promise.all([ccProc.stdout.text(), ccProc.stderr.text(), ccProc.exited]);
if (ccExit !== 0) {
throw new Error(`shim compile failed: ${ccErr || ccOut}`);
}
});

afterAll(() => {
dir?.[Symbol.dispose]();
});

// Node names every stream write failure "write". The errno is the one a pipe
// gives for a reader that is gone, whatever the socket said.
describe.concurrent.each(["ENOTCONN", "EPIPE"] as const)("send() failing with %s", sendErrno => {
test("surfaces as EPIPE from write", async () => {
const existing = bunEnv.LD_PRELOAD;
await using proc = Bun.spawn({
cmd: [bunExe(), "fixture.mjs"],
cwd: String(dir),
env: {
...bunEnv,
LD_PRELOAD: existing ? `${shimPath}:${existing}` : shimPath,
STDIN_FAIL_SEND_ERRNO: String(constants.errno[sendErrno]),
},
stdout: "pipe",
stderr: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
let error: unknown;
try {
error = JSON.parse(stdout.trim().split("\n").pop() ?? "");
} catch {
error = stdout;
}
expect({ error, stderr, exitCode }).toEqual({
error: { code: "EPIPE", syscall: "write", errno: -constants.errno.EPIPE },
stderr: "",
exitCode: 0,
});
});
});
});
31 changes: 31 additions & 0 deletions test/js/node/child_process/child_process.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
} from "harness";
import { ChildProcess, exec, execFile, execFileSync, execSync, fork, spawn, spawnSync } from "node:child_process";
import { getEventListeners, once, setMaxListeners } from "node:events";
import os from "node:os";
import { promisify } from "node:util";
import path from "path";
const debug = process.env.DEBUG ? console.log : () => {};
Expand Down Expand Up @@ -617,14 +618,18 @@ describe("spawn()", () => {

const [cb1Err, errEvErr] = await Promise.all([cb1.promise, errEv.promise]);

// Node names the syscall "write" even though the stdio pipe is a
// socketpair underneath.
expect({
cb1: cb1Err?.code,
errEv: errEvErr?.code,
syscall: errEvErr?.syscall,
destroyed: child.stdin!.destroyed,
writable: child.stdin!.writable,
}).toEqual({
cb1: "EPIPE",
errEv: "EPIPE",
syscall: "write",
destroyed: true,
writable: false,
});
Expand All @@ -639,6 +644,32 @@ describe("spawn()", () => {
}
},
);

it.skipIf(isWindows)("stdin write to a child that exits before draining it fails with EPIPE", async () => {
// The child exits with most of the 16 MiB (more than any socket buffer
// holds) unread. Whether the kernel fails the next send or the exit handler
// settles the pending write first, the stream reports EPIPE from "write".
const child = spawn(bunExe(), ["-e", `require("fs").readSync(0, Buffer.alloc(1)); process.exit(0);`], {
env: bunEnv,
stdio: ["pipe", "ignore", "ignore"],
});
const closed = new Promise<void>((resolve, reject) => {
child.on("error", reject);
child.on("close", () => resolve());
});
// A stream emits "error" before "close", so a close without an error rejects.
const stdinError = new Promise<any>((resolve, reject) => {
child.stdin!.on("error", resolve);
child.stdin!.on("close", () => reject(new Error("stdin closed without an error")));
});
child.stdin!.end(Buffer.alloc(16 * 1024 * 1024, 0x61));
const [err] = await Promise.all([stdinError, closed]);
expect({ code: err.code, syscall: err.syscall, errno: err.errno }).toEqual({
code: "EPIPE",
syscall: "write",
errno: -os.constants.errno.EPIPE,
});
});
});

describe("execFile()", () => {
Expand Down
Loading