use std::fs::File;
#[cfg(target_os = "linux")]
use std::io::Read;
use std::io::{Seek, SeekFrom, Write};
use std::os::fd::{AsRawFd, OwnedFd, RawFd};
#[cfg(not(target_os = "linux"))]
use std::os::unix::process::CommandExt;
#[cfg(not(target_os = "linux"))]
use std::process::{Command, Stdio};
use super::{install, FdMapping};
#[cfg(not(target_os = "linux"))]
use crate::child::spawn::in_child::register_alone;
use crate::child::spawn::in_child::InChild;
use crate::test_own_process::{own_process, test_path};
#[cfg(not(target_os = "linux"))]
use crate::test_spawn::spawn;
use crate::test_stdio::RestoreStdio;
fn file_with(content: &str) -> File {
let mut f = tempfile::tempfile().expect("tempfile");
f.write_all(content.as_bytes()).expect("write tempfile");
f.seek(SeekFrom::Start(0)).expect("seek to start");
f
}
#[cfg(not(target_os = "linux"))]
fn install_on(cmd: &mut Command, mappings: Vec<FdMapping>) -> std::io::Result<()> {
register_alone(cmd, |steps| install(steps, mappings))
}
#[cfg(not(target_os = "linux"))]
fn run_sh(script: &str, mappings: Vec<FdMapping>) -> String {
let mut cmd = Command::new("/bin/sh");
cmd.arg("-c").arg(script).stdout(Stdio::piped());
install_on(&mut cmd, mappings).expect("install");
let out = crate::test_spawn::output_captured(&mut cmd).expect("spawn /bin/sh");
assert!(out.status.success(), "child failed: {out:?}");
String::from_utf8(out.stdout).expect("utf8 stdout")
}
#[cfg(target_os = "linux")]
fn run_sh(script: &str, mappings: Vec<FdMapping>) -> String {
let (mut stdout_read, mut steps) = sh_steps(mappings);
let started = crate::child::spawn::in_child::spawn_sh(script, &mut steps).expect("spawn /bin/sh");
drop(steps);
let mut stdout = String::new();
stdout_read.read_to_string(&mut stdout).expect("read the stdout");
assert_eq!(
crate::child::spawn::in_child::exit_code(&started),
Some(0),
"child failed"
);
stdout
}
#[cfg(target_os = "linux")]
fn sh_steps(mappings: Vec<FdMapping>) -> (std::io::PipeReader, InChild) {
let (stdout_read, stdout_write) = std::io::pipe().expect("pipe");
let mut steps = InChild::default();
steps.map_stdio(super::Plan::stdio(vec![FdMapping {
parent_fd: OwnedFd::from(stdout_write),
child_fd: 1,
}]));
install(&mut steps, mappings).expect("install");
(stdout_read, steps)
}
fn read_fd(fd: RawFd) -> String {
format!("cat /dev/fd/{fd}")
}
#[skuld::test]
fn a_simple_mapping_lands_the_parent_fd_on_the_requested_child_number() {
let f = file_with("hello-fd5");
let out = run_sh(
&read_fd(5),
vec![FdMapping {
parent_fd: f.into(),
child_fd: 5,
}],
);
assert_eq!(out, "hello-fd5");
}
#[skuld::test]
fn empty_mappings_installs_nothing_and_spawns_normally() {
assert_eq!(run_sh("echo ok", vec![]).trim(), "ok");
}
#[skuld::test]
fn a_mapping_onto_its_own_current_number_clears_cloexec_so_the_fd_survives_exec() {
let f = file_with("self-mapped");
let owned: OwnedFd = f.into();
let raw = owned.as_raw_fd();
let out = run_sh(
&read_fd(raw),
vec![FdMapping {
parent_fd: owned,
child_fd: raw,
}],
);
assert_eq!(out, "self-mapped");
}
#[skuld::test]
fn colliding_mappings_deliver_each_files_own_content() {
let a = file_with("AAA");
let b = file_with("BBB");
let a_owned: OwnedFd = a.into();
let b_owned: OwnedFd = b.into();
let a_raw = a_owned.as_raw_fd();
let b_raw = b_owned.as_raw_fd();
let out = run_sh(
&format!("{}; {}", read_fd(b_raw), read_fd(a_raw)),
vec![
FdMapping {
parent_fd: a_owned,
child_fd: b_raw,
},
FdMapping {
parent_fd: b_owned,
child_fd: a_raw,
},
],
);
assert_eq!(
out, "AAABBB",
"the swap must deliver each file's OWN content, uncorrupted"
);
}
#[skuld::test]
fn a_three_way_rotation_of_colliding_mappings_resolves_correctly() {
let a = file_with("AAA");
let b = file_with("BBB");
let c = file_with("CCC");
let a_owned: OwnedFd = a.into();
let b_owned: OwnedFd = b.into();
let c_owned: OwnedFd = c.into();
let a_raw = a_owned.as_raw_fd();
let b_raw = b_owned.as_raw_fd();
let c_raw = c_owned.as_raw_fd();
let out = run_sh(
&format!("{}; {}; {}", read_fd(a_raw), read_fd(b_raw), read_fd(c_raw)),
vec![
FdMapping {
parent_fd: c_owned,
child_fd: a_raw,
},
FdMapping {
parent_fd: a_owned,
child_fd: b_raw,
},
FdMapping {
parent_fd: b_owned,
child_fd: c_raw,
},
],
);
assert_eq!(out, "CCCAAABBB");
}
#[skuld::test]
fn install_rejects_a_duplicate_child_fd_in_every_build_profile() {
let a = file_with("A");
let b = file_with("B");
let err = install(
&mut InChild::default(),
vec![
FdMapping {
parent_fd: a.into(),
child_fd: 5,
},
FdMapping {
parent_fd: b.into(),
child_fd: 5,
},
],
)
.expect_err("a duplicate child fd must be rejected by install itself, in every build profile");
assert_eq!(
err.kind(),
std::io::ErrorKind::InvalidInput,
"expected InvalidInput (mirrors Command::fd's own negative-fd rejection), got {err:?}"
);
}
#[cfg(target_os = "macos")]
#[skuld::test]
fn preserve_clears_cloexec_so_the_fd_survives_exec() {
let f = file_with("preserved");
let owned: OwnedFd = f.into();
let raw = owned.as_raw_fd();
let mut cmd = Command::new("/bin/sh");
cmd.arg("-c").arg(read_fd(raw)).stdout(Stdio::piped());
register_alone(&mut cmd, |steps| steps.preserve(owned));
let out = crate::test_spawn::output_captured(&mut cmd).expect("spawn");
assert!(out.status.success());
assert_eq!(String::from_utf8(out.stdout).unwrap(), "preserved");
}
#[cfg(target_os = "macos")]
#[skuld::test]
fn without_preserve_the_fd_is_closed_at_exec() {
let f = file_with("not-preserved");
let owned: OwnedFd = f.into();
let raw = owned.as_raw_fd();
let mut cmd = Command::new("/bin/sh");
cmd.arg("-c")
.arg(format!("{} 2>/dev/null || echo CLOSED", read_fd(raw)))
.stdout(Stdio::piped());
let out = crate::test_spawn::output_captured(&mut cmd).expect("spawn");
drop(owned); assert_eq!(String::from_utf8(out.stdout).unwrap().trim(), "CLOSED");
}
#[skuld::test]
fn an_i32_max_child_fd_fails_at_spawn_not_at_install() {
let f = file_with("x");
let mapping = vec![FdMapping {
parent_fd: f.into(),
child_fd: i32::MAX,
}];
#[cfg(not(target_os = "linux"))]
let err = {
let mut cmd = Command::new("/bin/sh");
cmd.arg("-c").arg("true").stdout(Stdio::piped());
install_on(&mut cmd, mapping).expect("i32::MAX must be accepted by install");
crate::test_spawn::spawn(&mut cmd)
.and_then(|c| c.wait_with_output())
.expect_err("dup2 onto i32::MAX must fail the spawn with an Err, not abort the child")
};
#[cfg(target_os = "linux")]
let err = failed_spawn_of_true(mapping);
assert!(err.raw_os_error().is_some(), "expected an OS error, got {err:?}");
}
#[cfg(target_os = "linux")]
fn failed_spawn_of_true(mappings: Vec<FdMapping>) -> std::io::Error {
let (_stdout, mut steps) = sh_steps(mappings);
match crate::child::spawn::in_child::spawn_sh("true", &mut steps) {
Err(err) => err,
Ok(started) => panic!("the spawn succeeded (child {})", started.pid),
}
}
#[cfg(target_os = "linux")]
fn lower_the_limit_to_256(_own_process: &crate::test_own_process::Completion) {
let mut limit = libc::rlimit {
rlim_cur: 0,
rlim_max: 0,
};
unsafe {
assert_eq!(libc::getrlimit(libc::RLIMIT_NOFILE, &mut limit), 0);
limit.rlim_cur = 256;
assert_eq!(libc::setrlimit(libc::RLIMIT_NOFILE, &limit), 0, "lower the limit");
}
}
#[skuld::test]
fn an_out_of_range_but_representable_child_fd_fails_at_spawn_not_at_install() {
#[cfg(target_os = "linux")]
{
let Some(done) = own_process(
test_path!(an_out_of_range_but_representable_child_fd_fails_at_spawn_not_at_install),
crate::test_spawn::spawn,
) else {
return;
};
lower_the_limit_to_256(&done);
let mapping = vec![FdMapping {
parent_fd: file_with("x").into(),
child_fd: 1_000_000,
}];
let err = failed_spawn_of_true(mapping);
assert!(err.raw_os_error().is_some(), "expected an OS error, got {err:?}");
}
#[cfg(not(target_os = "linux"))]
{
let f = file_with("x");
let mut cmd = Command::new("/bin/sh");
cmd.arg("-c").arg("true").stdout(Stdio::piped());
unsafe {
cmd.pre_exec(|| {
let lim = libc::rlimit {
rlim_cur: 256,
rlim_max: 256,
};
if libc::setrlimit(libc::RLIMIT_NOFILE, &lim) != 0 {
return Err(std::io::Error::last_os_error());
}
Ok(())
});
}
install_on(
&mut cmd,
vec![FdMapping {
parent_fd: f.into(),
child_fd: 1_000_000,
}],
)
.expect("1_000_000 must be accepted by install (representable, just not achievable)");
let err = crate::test_spawn::spawn(&mut cmd)
.and_then(|c| c.wait_with_output())
.expect_err("dup2 onto an unachievable fd number must fail the spawn with an Err, not abort the child");
assert!(err.raw_os_error().is_some(), "expected an OS error, got {err:?}");
}
}
#[skuld::test]
fn a_distant_high_target_does_not_inflate_every_other_temporary_past_a_tight_rlimit() {
#[cfg(target_os = "linux")]
let Some(done) = own_process(
test_path!(a_distant_high_target_does_not_inflate_every_other_temporary_past_a_tight_rlimit),
crate::test_spawn::spawn,
) else {
return;
};
let a = file_with("AAA");
let b = file_with("BBB");
let c = file_with("CCC");
let a_owned: OwnedFd = a.into();
let b_owned: OwnedFd = b.into();
let c_owned: OwnedFd = c.into();
let a_raw = a_owned.as_raw_fd();
let b_raw = b_owned.as_raw_fd();
let script = format!("{}; {}", read_fd(b_raw), read_fd(a_raw));
let mappings = vec![
FdMapping {
parent_fd: a_owned,
child_fd: b_raw,
},
FdMapping {
parent_fd: b_owned,
child_fd: a_raw,
},
FdMapping {
parent_fd: c_owned,
child_fd: 255,
},
];
#[cfg(target_os = "linux")]
let stdout = {
lower_the_limit_to_256(&done);
run_sh(&script, mappings).into_bytes()
};
#[cfg(not(target_os = "linux"))]
let stdout = {
let mut cmd = Command::new("/bin/sh");
cmd.arg("-c").arg(script).stdout(Stdio::piped());
unsafe {
cmd.pre_exec(|| {
let lim = libc::rlimit {
rlim_cur: 256,
rlim_max: 256,
};
if libc::setrlimit(libc::RLIMIT_NOFILE, &lim) != 0 {
return Err(std::io::Error::last_os_error());
}
Ok(())
});
}
install_on(&mut cmd, mappings).expect("install");
let out = crate::test_spawn::output_captured(&mut cmd).expect("spawn /bin/sh");
assert!(out.status.success(), "child failed: {out:?}");
out.stdout
};
assert_eq!(
stdout, b"AAABBB",
"the swap must still resolve correctly even with a numerically distant child_fd \
elsewhere in the mapping set"
);
}
#[cfg(not(target_os = "linux"))]
#[skuld::test]
fn a_source_starting_below_fd_3_is_moved_before_stdio_dup2_can_clobber_it() {
let Some(done) = own_process(
test_path!(a_source_starting_below_fd_3_is_moved_before_stdio_dup2_can_clobber_it),
spawn,
) else {
return;
};
let _restore = RestoreStdio::close(&done, &[2]);
let owned: OwnedFd = file_with("fd3-token").into();
assert_eq!(
owned.as_raw_fd(),
2,
"test setup invariant: the source must land exactly at fd 2 to reproduce the bug"
);
let mut cmd = Command::new("/bin/sh");
cmd.arg("-c")
.arg(format!(
"if test -f /dev/fd/3; then {} >&1; else printf %s fd3-is-not-a-regular-file; fi; echo unrelated-stderr >&2",
read_fd(3)
))
.stdout(Stdio::piped())
.stderr(Stdio::piped());
install_on(
&mut cmd,
vec![FdMapping {
parent_fd: owned,
child_fd: 3,
}],
)
.expect("install");
let out = crate::test_spawn::output_captured(&mut cmd).expect("spawn /bin/sh");
assert!(out.status.success(), "child failed: {out:?}");
assert_ne!(
out.stdout, b"fd3-is-not-a-regular-file",
"fd 3 in the child is not a regular file: the relocation is missing and fd 3 is the stderr pipe"
);
assert_eq!(
out.stdout, b"fd3-token",
"fd 3 in the child must deliver the mapping's OWN source, not whatever std's stdio \
dup2 later put at the parent-side fd 2 number"
);
assert_eq!(
String::from_utf8(out.stderr).unwrap().trim(),
"unrelated-stderr",
"the stderr pipe must carry only the child's own stderr writes, not fd 3's bytes"
);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_source_starting_below_fd_3_is_moved_before_the_stdio_plan_can_clobber_it() {
let Some(done) = own_process(
test_path!(a_source_starting_below_fd_3_is_moved_before_the_stdio_plan_can_clobber_it),
crate::test_spawn::spawn,
) else {
return;
};
let _restore = RestoreStdio::close(&done, &[2]);
let owned: OwnedFd = file_with("fd3-token").into();
assert_eq!(
owned.as_raw_fd(),
2,
"test setup invariant: the source must land exactly at fd 2 to reproduce the bug"
);
let (mut stdout_read, stdout_write) = std::io::pipe().expect("pipe");
let (mut stderr_read, stderr_write) = std::io::pipe().expect("pipe");
let mut steps = InChild::default();
steps.map_stdio(super::Plan::stdio(vec![
FdMapping {
parent_fd: OwnedFd::from(stdout_write),
child_fd: 1,
},
FdMapping {
parent_fd: OwnedFd::from(stderr_write),
child_fd: 2,
},
]));
install(
&mut steps,
vec![FdMapping {
parent_fd: owned,
child_fd: 3,
}],
)
.expect("install");
let script = format!(
"if test -f /dev/fd/3; then {} >&1; else printf %s fd3-is-not-a-regular-file; fi; echo unrelated-stderr >&2",
read_fd(3)
);
let started = crate::child::spawn::in_child::spawn_sh(&script, &mut steps).expect("spawn /bin/sh");
drop(steps);
let (mut stdout, mut stderr) = (String::new(), String::new());
stdout_read.read_to_string(&mut stdout).expect("read the stdout");
stderr_read.read_to_string(&mut stderr).expect("read the stderr");
assert_eq!(
crate::child::spawn::in_child::exit_code(&started),
Some(0),
"child failed"
);
assert_ne!(
stdout, "fd3-is-not-a-regular-file",
"fd 3 in the child is not a regular file: the relocation is missing and fd 3 is the stderr pipe"
);
assert_eq!(
stdout, "fd3-token",
"fd 3 in the child must deliver the mapping's OWN source, not whatever the stdio plan later put \
at the parent-side fd 2 number"
);
assert_eq!(
stderr.trim(),
"unrelated-stderr",
"the stderr pipe must carry only the child's own stderr writes, not fd 3's bytes"
);
}
#[skuld::test]
fn a_relocated_low_parent_fd_stays_open_in_the_parent_until_its_steps_drop() {
let Some(done) = own_process(
test_path!(a_relocated_low_parent_fd_stays_open_in_the_parent_until_its_steps_drop),
crate::test_spawn::spawn,
) else {
return;
};
let _restore = RestoreStdio::close(&done, &[2]);
let owned: OwnedFd = file_with("kept-open").into();
assert_eq!(
owned.as_raw_fd(),
2,
"test setup invariant: the source must land exactly at fd 2 to reproduce the bug"
);
let mut steps = InChild::default();
install(
&mut steps,
vec![FdMapping {
parent_fd: owned,
child_fd: 5,
}],
)
.expect("install");
let still_open = unsafe { libc::fcntl(2, libc::F_GETFD) } != -1;
assert!(
still_open,
"the original low fd (2) must remain open across install() — it must not be freed \
back to the OS before the spawn's own fd allocations have run"
);
drop(steps);
let closed_after_drop = unsafe { libc::fcntl(2, libc::F_GETFD) } == -1;
assert!(
closed_after_drop,
"the retired original fd (2) must be closed once its steps drop, not leaked open"
);
}