mod common;
use oscall::process;
#[test]
fn ids() {
#[cfg(not(target_family = "wasm"))]
{
assert_eq!(process::id(), std::process::id());
assert_ne!(process::parent_id(), 0);
assert_ne!(process::parent_id(), process::id());
}
#[cfg(unix)]
assert_eq!(process::parent_id(), std::os::unix::process::parent_id());
#[cfg(target_family = "wasm")]
{
assert_eq!(process::id(), 0);
assert_eq!(process::parent_id(), 0);
}
}
#[test]
fn arguments() {
use oscall::ErrorKind;
let expected: Vec<Vec<u8>> = std::env::args_os()
.map(|arg| arg.as_encoded_bytes().to_vec())
.collect();
assert!(!expected.is_empty());
let mut buf = vec![0u8; 1 << 16];
let args: Vec<Vec<u8>> = process::args(&mut buf)
.unwrap()
.map(<[u8]>::to_vec)
.collect();
assert_eq!(args, expected);
#[cfg(feature = "alloc")]
assert_eq!(process::args_vec().unwrap(), expected);
let size: usize = expected.iter().map(|arg| arg.len() + 1).sum();
for small in [0, 1, size - 1] {
let error = process::args(&mut buf[..small]).unwrap_err();
assert_eq!(error.kind(), ErrorKind::BufferTooSmall, "{small}");
}
let size = if cfg!(target_os = "wasi") {
size + 4 * expected.len() + 3
} else {
size
};
let exact: Vec<&[u8]> = process::args(&mut buf[..size]).unwrap().collect();
assert_eq!(exact, expected);
}
#[test]
fn environment() {
use oscall::ErrorKind;
let stable = |(name, _): &(Vec<u8>, Vec<u8>)| !name.starts_with(b"=");
let mut expected: Vec<(Vec<u8>, Vec<u8>)> = std::env::vars_os()
.map(|(name, value)| {
(
name.as_encoded_bytes().to_vec(),
value.as_encoded_bytes().to_vec(),
)
})
.filter(stable)
.collect();
expected.sort();
let mut buf = vec![0u8; 1 << 20];
let mut vars: Vec<(Vec<u8>, Vec<u8>)> = process::vars(&mut buf)
.unwrap()
.map(|(name, value)| (name.to_vec(), value.to_vec()))
.filter(stable)
.collect();
vars.sort();
assert_eq!(vars, expected);
#[cfg(feature = "alloc")]
{
let mut vars = process::vars_vec().unwrap();
vars.retain(stable);
vars.sort();
assert_eq!(vars, expected);
}
if !expected.is_empty() {
let error = process::vars(&mut buf[..1]).unwrap_err();
assert_eq!(error.kind(), ErrorKind::BufferTooSmall);
}
if let Some(value) = std::env::var_os("OSCALL_TEST_ENV") {
assert!(
vars.iter().any(
|(name, found)| name == b"OSCALL_TEST_ENV" && found == value.as_encoded_bytes()
)
);
}
}
#[test]
#[cfg(all(feature = "alloc", target_family = "wasm"))]
fn spawn_unsupported() {
use oscall::process::{Command, Stdio};
let error = Command::new("/bin/sh")
.args(&["-c", "exit 0"])
.stdin(Stdio::Null)
.spawn()
.unwrap_err();
assert_eq!(error.kind(), oscall::ErrorKind::Unsupported);
}
#[test]
#[cfg(target_family = "wasm")]
fn processes_unsupported() {
use oscall::ErrorKind;
let mut buf = [0u8; 64];
let error = process::find_program("sh", "/bin", &mut buf).unwrap_err();
assert_eq!(error.kind(), ErrorKind::Unsupported);
#[cfg(feature = "alloc")]
assert_eq!(
process::find_program_vec("sh", "/bin").unwrap_err().kind(),
ErrorKind::Unsupported
);
assert_eq!(
process::exists(1).unwrap_err().kind(),
ErrorKind::Unsupported
);
assert_eq!(process::kill(1).unwrap_err().kind(), ErrorKind::Unsupported);
assert_eq!(
process::resource_usage().unwrap_err().kind(),
ErrorKind::Unsupported
);
assert_eq!(
process::exists(0).unwrap_err().kind(),
ErrorKind::InvalidInput
);
}
#[test]
#[cfg(not(target_family = "wasm"))]
fn find_program_errors() {
use oscall::ErrorKind;
let mut buf = [0u8; 256];
let dir = common::tmp_dir("process_find_program_errors");
let dir = dir.to_str().unwrap();
for (name, path) in [("a\0", dir), ("a", "x\0y")] {
let error = process::find_program(name, path, &mut buf).unwrap_err();
assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
}
for (name, path) in [
("", dir),
("missing", dir),
("missing", ""),
("missing", ";:"),
] {
let error = process::find_program(name, path, &mut buf).unwrap_err();
assert_eq!(error.kind(), ErrorKind::NotFound, "{error:?}");
}
let error = process::find_program("missing", dir, &mut buf[..4]).unwrap_err();
assert_eq!(error.kind(), ErrorKind::BufferTooSmall, "{error:?}");
}
#[test]
#[cfg(any(target_os = "linux", target_os = "fullrust", target_os = "macos"))]
fn find_program() {
use oscall::ErrorKind;
use std::os::unix::fs::PermissionsExt;
let dir = common::tmp_dir("process_find_program");
let file = |name: &str, mode: u32| {
let path = dir.join(name);
std::fs::write(&path, "#!/bin/sh\nexit 0\n").unwrap();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode)).unwrap();
};
for sub in ["a", "b", "a/folder", "b/folder"] {
std::fs::create_dir(dir.join(sub)).unwrap();
}
file("a/both", 0o755);
file("b/both", 0o755);
file("a/second", 0o644);
file("b/second", 0o700);
file("b/data", 0o644);
std::os::unix::fs::symlink("both", dir.join("b/link")).unwrap();
std::os::unix::fs::symlink("nowhere", dir.join("a/link")).unwrap();
let dir = dir.to_str().unwrap();
let path = format!("{dir}/missing::{dir}/a:{dir}/b/:");
let find = |name: &str| {
let mut buf = [0u8; 512];
let found = process::find_program(name, path.as_str(), &mut buf)
.map(|len| String::from_utf8(buf[..len].to_vec()).unwrap());
#[cfg(feature = "alloc")]
assert_eq!(
process::find_program_vec(name, path.as_str())
.map(|found| String::from_utf8(found).unwrap()),
found
);
found
};
assert_eq!(find("both").unwrap(), format!("{dir}/a/both"));
assert_eq!(find("second").unwrap(), format!("{dir}/b/second"));
assert_eq!(find("link").unwrap(), format!("{dir}/b/link"));
for name in ["data", "folder", "missing", ".", ".."] {
assert_eq!(
find(name).unwrap_err().kind(),
ErrorKind::NotFound,
"{name}"
);
}
let both = format!("{dir}/b/both");
assert_eq!(find(&both).unwrap(), both);
assert_eq!(find("a/both").unwrap_err().kind(), ErrorKind::NotFound);
let data = format!("{dir}/b/data");
assert_eq!(find(&data).unwrap_err().kind(), ErrorKind::NotFound);
let mut buf = [0u8; 512];
let path = format!("{dir}/a");
let len = dir.len() + "/a/both".len();
assert_eq!(
process::find_program("both", path.as_str(), &mut buf[..len]),
Ok(len)
);
assert_eq!(
process::find_program("both", path.as_str(), &mut buf[..len - 1])
.unwrap_err()
.kind(),
ErrorKind::BufferTooSmall
);
}
#[test]
#[cfg(windows)]
fn find_program() {
use oscall::ErrorKind;
let root = std::env::var("SystemRoot").unwrap();
let dir = common::tmp_dir("process_find_program");
std::fs::write(dir.join("data"), "x").unwrap();
std::fs::write(dir.join("tool.exe"), "x").unwrap();
std::fs::write(dir.join("script.cmd"), "x").unwrap();
std::fs::create_dir(dir.join("folder.exe")).unwrap();
let dir = dir.to_str().unwrap();
let path = format!("{dir}\\missing;;\"{dir}\";{root}\\System32\\;{root}");
let find = |name: &str| {
let mut buf = [0u8; 512];
let found = process::find_program(name, path.as_str(), &mut buf)
.map(|len| String::from_utf8(buf[..len].to_vec()).unwrap());
#[cfg(feature = "alloc")]
assert_eq!(
process::find_program_vec(name, path.as_str())
.map(|found| String::from_utf8(found).unwrap()),
found
);
found
};
assert_eq!(find("cmd").unwrap(), format!("{root}\\System32\\cmd.exe"));
assert_eq!(
find("cmd.exe").unwrap(),
format!("{root}\\System32\\cmd.exe")
);
assert_eq!(find("tool").unwrap(), format!("{dir}\\tool.exe"));
assert_eq!(find("script.cmd").unwrap(), format!("{dir}\\script.cmd"));
for name in [
"data",
"script",
"folder",
"folder.exe",
"cmd.com",
"missing",
] {
assert_eq!(
find(name).unwrap_err().kind(),
ErrorKind::NotFound,
"{name}"
);
}
let cmd = format!("{root}\\System32\\cmd.exe");
assert_eq!(find(&cmd).unwrap(), cmd);
let bare = format!("{root}\\System32\\cmd");
assert_eq!(find(&bare).unwrap_err().kind(), ErrorKind::NotFound);
assert_eq!(
find("System32\\cmd.exe").unwrap_err().kind(),
ErrorKind::NotFound
);
assert_eq!(find("C:cmd.exe").unwrap_err().kind(), ErrorKind::NotFound);
}
#[test]
#[cfg(not(target_family = "wasm"))]
fn pid_errors() {
use oscall::ErrorKind;
assert_eq!(process::exists(process::id()), Ok(true));
for pid in [0, u32::MAX, 1 << 31] {
let error = process::exists(pid).unwrap_err();
assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
let error = process::kill(pid).unwrap_err();
assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
}
}
#[test]
#[cfg(not(target_family = "wasm"))]
fn resource_usage() {
use oscall::time::Clock;
use std::time::Duration;
const BLOCK: usize = 48 << 20;
let total = |usage: process::ResourceUsage| usage.user_time() + usage.system_time();
let before = process::resource_usage().unwrap();
if !cfg!(any(target_os = "linux", target_os = "fullrust")) {
assert!(before.max_resident_memory() > 0);
}
let mut block = vec![0u8; BLOCK];
for at in (0..BLOCK).step_by(512) {
block[at] = at as u8;
}
let start = Clock::ProcessCpu.now().unwrap();
let mut sum = 0u64;
while Clock::ProcessCpu.now().unwrap() - start < Duration::from_millis(100) {
for byte in block.iter().step_by(4096) {
sum = sum.wrapping_mul(31).wrapping_add(u64::from(*byte));
}
}
std::hint::black_box(sum);
let after = process::resource_usage().unwrap();
let clock = Clock::ProcessCpu.now().unwrap();
drop(block);
let peak = after.max_resident_memory();
assert!(peak >= BLOCK as u64 / 2, "{peak}");
assert!(peak >= before.max_resident_memory(), "{before:?} {after:?}");
assert!(peak < 1 << 44, "{peak}");
let spent = total(after).saturating_sub(total(before));
assert!(spent >= Duration::from_millis(50), "{before:?} {after:?}");
assert!(
total(after) <= clock + Duration::from_millis(100),
"{after:?} {clock:?}"
);
}
#[test]
#[cfg(any(target_os = "linux", target_os = "fullrust", target_os = "macos"))]
fn limits() {
use oscall::ErrorKind;
use oscall::process::unix::{self, Limit, Resource};
for resource in [
Resource::OpenFiles,
Resource::Stack,
Resource::CoreSize,
Resource::FileSize,
Resource::CpuTime,
Resource::AddressSpace,
Resource::Data,
Resource::LockedMemory,
Resource::Processes,
] {
let limit = unix::limit(resource).unwrap();
if let (Some(soft), Some(hard)) = (limit.soft, limit.hard) {
assert!(soft <= hard, "{resource:?}: {limit:?}");
}
let adjusted = cfg!(target_os = "macos") && resource == Resource::Processes;
if !adjusted && (resource != Resource::OpenFiles || limit.soft.is_some()) {
unix::set_limit(resource, limit).unwrap();
assert_eq!(unix::limit(resource), Ok(limit), "{resource:?}");
}
}
let files = unix::limit(Resource::OpenFiles).unwrap();
assert!(files.soft.is_none_or(|soft| soft > 3), "{files:?}");
let core = unix::limit(Resource::CoreSize).unwrap();
let none = Limit {
soft: Some(0),
hard: core.hard,
};
unix::set_limit(Resource::CoreSize, none).unwrap();
let seen = unix::limit(Resource::CoreSize);
let child = std::process::Command::new("/bin/sh")
.args(["-c", "ulimit -c"])
.output();
let above = core.hard.map(|hard| {
unix::set_limit(
Resource::CoreSize,
Limit {
soft: Some(hard + 1),
hard: Some(hard),
},
)
});
let huge = unix::set_limit(
Resource::CoreSize,
Limit {
soft: Some(u64::MAX),
hard: core.hard,
},
);
unix::set_limit(Resource::CoreSize, core).unwrap();
assert_eq!(unix::limit(Resource::CoreSize), Ok(core));
assert_eq!(seen, Ok(none));
assert_eq!(String::from_utf8_lossy(&child.unwrap().stdout).trim(), "0");
if let Some(above) = above {
let error = above.unwrap_err();
assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
}
let error = huge.unwrap_err();
assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
}
#[test]
#[cfg(not(target_family = "wasm"))]
fn helper_child_process() {
let Some(mode) = std::env::var_os("OSCALL_TEST_HELPER") else {
return;
};
let mode = mode.into_string().unwrap();
if let Some(code) = mode.strip_prefix("exit:") {
process::exit(code.parse().unwrap());
} else if mode == "abort" {
process::abort();
} else if let Some(file) = mode.strip_prefix("ids:") {
let ids = format!("{} {}", process::id(), process::parent_id());
std::fs::write(file, ids).unwrap();
process::exit(0);
} else if let Some(file) = mode.strip_prefix("args:") {
let mut out = Vec::new();
for arg in std::env::args_os().skip_while(|arg| arg != "--").skip(1) {
out.extend_from_slice(arg.as_encoded_bytes());
out.push(0);
}
std::fs::write(file, out).unwrap();
process::exit(0);
} else if let Some(file) = mode.strip_prefix("oscall-args:") {
let mut buf = vec![0u8; 1 << 16];
let mut out = Vec::new();
for arg in process::args(&mut buf)
.unwrap()
.skip_while(|arg| *arg != b"--")
.skip(1)
{
out.extend_from_slice(arg);
out.push(0);
}
out.push(0xff);
let mut buf = vec![0u8; 1 << 20];
for (name, value) in process::vars(&mut buf).unwrap() {
if name.starts_with(b"OSCALL_T_") {
out.extend_from_slice(name);
out.push(0);
out.extend_from_slice(value);
out.push(0);
}
}
std::fs::write(file, out).unwrap();
process::exit(0);
}
#[cfg(all(
feature = "alloc",
any(target_os = "linux", target_os = "fullrust", windows)
))]
if let Some(kind) = mode.strip_prefix("orphan:") {
children::orphan_helper(kind == "tied");
}
#[cfg(all(feature = "alloc", windows))]
if mode == "bare-job" {
children::bare_job_helper();
}
#[cfg(all(feature = "alloc", not(windows)))]
if mode == "fork" {
children::fork_helper();
}
panic!("unknown helper mode {mode}");
}
#[cfg(all(feature = "alloc", not(target_family = "wasm")))]
mod children {
use std::fs::File;
use std::path::{Path, PathBuf};
use std::sync::mpsc;
use std::time::{Duration, Instant};
use oscall::process::{Child, Command, ExitStatus, Stdio};
use oscall::{AsHandle, Error, ErrorKind, OwnedHandle, io};
use super::common::{handle_of, tmp_dir};
fn bytes(path: &Path) -> &[u8] {
path.as_os_str().as_encoded_bytes()
}
#[cfg(not(windows))]
fn shell() -> String {
"/bin/sh".to_owned()
}
#[cfg(windows)]
fn shell() -> String {
system32("cmd.exe")
}
#[cfg(windows)]
fn system32(name: &str) -> String {
format!("{}\\System32\\{name}", std::env::var("SystemRoot").unwrap())
}
const RUN: &str = if cfg!(windows) { "/C" } else { "-c" };
fn filter() -> (String, Vec<&'static str>) {
#[cfg(windows)]
return (system32("findstr.exe"), vec!["x"]);
#[cfg(not(windows))]
return (
shell(),
vec![
"-c",
r#"while read -r line; do case "$line" in *x*) echo "$line";; esac; done"#,
],
);
}
fn write_all(handle: impl AsHandle, mut buf: &[u8]) {
while !buf.is_empty() {
let n = io::write(handle.as_handle(), buf).unwrap();
assert!(n > 0);
buf = &buf[n..];
}
}
fn read_bytes(handle: impl AsHandle) -> Vec<u8> {
let mut out = Vec::new();
let mut buf = [0u8; 4096];
loop {
match io::read(handle.as_handle(), &mut buf) {
Ok(0) => break,
Ok(n) => out.extend_from_slice(&buf[..n]),
Err(error) if error.kind() == ErrorKind::BrokenPipe => break,
Err(error) => panic!("read failed: {error}"),
}
}
out
}
fn read_text(handle: impl AsHandle) -> String {
String::from_utf8_lossy(&read_bytes(handle)).replace('\r', "")
}
fn wait(child: &mut Child) -> ExitStatus {
let start = Instant::now();
loop {
if let Some(status) = child.try_wait().unwrap() {
assert_eq!(child.wait().unwrap(), status);
assert_eq!(child.try_wait().unwrap(), Some(status));
return status;
}
if start.elapsed() > Duration::from_secs(60) {
child.kill().unwrap();
panic!("the child did not exit");
}
std::thread::sleep(Duration::from_millis(2));
}
}
struct Output {
status: ExitStatus,
stdout: String,
stderr: String,
}
#[derive(Default)]
struct Options<'a> {
env: Option<&'a [String]>,
dir: Option<&'a Path>,
arg0: Option<&'a str>,
}
fn run_with(script: &str, options: &Options<'_>) -> Output {
let (out_read, out_write) = io::pipe().unwrap();
let (err_read, err_write) = io::pipe().unwrap();
let shell = shell();
let args = [RUN, script];
let mut command = Command::new(&shell)
.args(&args)
.stdin(Stdio::Null)
.stdout(Stdio::Handle(out_write.as_handle()))
.stderr(Stdio::Handle(err_write.as_handle()));
if let Some(env) = options.env {
command = command.env(env);
}
if let Some(dir) = options.dir {
command = command.current_dir(bytes(dir));
}
if let Some(arg0) = options.arg0 {
command = command.arg0(arg0);
}
let mut child = command.spawn().unwrap();
assert_ne!(child.id(), 0);
assert_ne!(child.id(), oscall::process::id());
drop((out_write, err_write));
let stdout = read_text(&out_read);
let stderr = read_text(&err_read);
Output {
status: wait(&mut child),
stdout,
stderr,
}
}
fn run(script: &str) -> Output {
run_with(script, &Options::default())
}
#[test]
fn exit_codes() {
for code in [0, 1, 7, 42, 255] {
let output = run(&format!("exit {code}"));
assert_eq!(output.status.code(), Some(code));
assert_eq!(output.status.success(), code == 0);
assert_eq!(output.stdout, "");
assert_eq!(output.stderr, "");
assert!(format!("{:?} {}", output.status, output.status).contains(&code.to_string()));
#[cfg(not(windows))]
{
use oscall::process::unix::ExitStatusExt;
assert_eq!(output.status.signal(), None);
assert!(!output.status.core_dumped());
}
}
}
#[test]
fn output_and_error() {
let script = if cfg!(windows) {
"echo out& echo err>&2"
} else {
"echo out; echo err >&2"
};
let output = run(script);
assert!(output.status.success());
assert_eq!(output.stdout, "out\n");
assert_eq!(output.stderr, "err\n");
}
#[test]
fn shared_output() {
let script = if cfg!(windows) {
"echo out& echo err>&2"
} else {
"echo out; echo err >&2"
};
let (read, write) = io::pipe().unwrap();
let shell = shell();
let mut child = Command::new(&shell)
.args(&[RUN, script])
.stdin(Stdio::Null)
.stdout(Stdio::Handle(write.as_handle()))
.stderr(Stdio::Handle(write.as_handle()))
.spawn()
.unwrap();
drop(write);
assert_eq!(read_text(&read), "out\nerr\n");
assert!(wait(&mut child).success());
}
#[test]
#[cfg(not(windows))]
fn arguments() {
let script = r#"for arg in "$@"; do printf '[%s]\n' "$arg"; done"#;
let args: Vec<Vec<u8>> = [
&b"-c"[..],
script.as_bytes(),
b"name",
b"plain",
b"two words",
b"",
b" spaces ",
b"tab\there",
br#"quote"inside"#,
br#""quoted""#,
br"back\slash",
br"trailing\",
br#"both\"of them\\"#,
b"'single'",
b"$HOME `id` $(id) ; & | > < * ? ~ # !",
b"%PATH% ^ %%",
"h\u{e9}llo \u{4e16}\u{754c} \u{1f600}".as_bytes(),
b"not utf-8: \xff\xfe\x80",
b"-n",
b"--",
]
.iter()
.map(|arg| arg.to_vec())
.collect();
let mut expected = Vec::new();
for arg in &args[3..] {
expected.push(b'[');
expected.extend_from_slice(arg);
expected.extend_from_slice(b"]\n");
}
let (read, write) = io::pipe().unwrap();
let mut child = Command::new("/bin/sh")
.args(&args)
.stdin(Stdio::Null)
.stdout(Stdio::Handle(write.as_handle()))
.spawn()
.unwrap();
drop(write);
let out = read_bytes(&read);
assert!(wait(&mut child).success());
assert_eq!(out, expected);
}
#[test]
#[cfg(not(windows))]
fn arg0() {
let output = run(r#"printf %s "$0""#);
assert_eq!(output.stdout, "/bin/sh");
let options = Options {
arg0: Some("another name"),
..Options::default()
};
let output = run_with(r#"printf %s "$0""#, &options);
assert_eq!(output.stdout, "another name");
}
#[test]
fn nul_is_refused() {
let shell = shell();
let invalid = |command: Command<'_>| {
assert_eq!(command.spawn().unwrap_err().kind(), ErrorKind::InvalidInput);
};
invalid(Command::new(&shell).args(&[RUN, "exit\0 0"]));
invalid(Command::new(&shell).args(&[RUN, "exit 0"]).env(&["A=\0"]));
invalid(
Command::new(&shell)
.args(&[RUN, "exit 0"])
.current_dir("a\0"),
);
invalid(Command::new(&shell).args(&[RUN, "exit 0"]).arg0("a\0"));
invalid(Command::new("a\0b"));
}
fn helper_env(mode: &str) -> Vec<Vec<u8>> {
let mut env: Vec<Vec<u8>> = std::env::vars_os()
.filter(|(name, _)| name != "OSCALL_TEST_HELPER")
.map(|(name, value)| [name.as_encoded_bytes(), b"=", value.as_encoded_bytes()].concat())
.collect();
env.push(format!("OSCALL_TEST_HELPER={mode}").into_bytes());
env
}
fn helper(mode: &str, args: &[Vec<u8>]) -> Option<ExitStatus> {
let exe = std::env::current_exe().ok()?;
let env = helper_env(mode);
let mut all: Vec<Vec<u8>> = ["--exact", "--nocapture", "helper_child_process", "--"]
.iter()
.map(|arg| arg.as_bytes().to_vec())
.collect();
all.extend_from_slice(args);
let spawned = Command::new(bytes(&exe))
.args(&all)
.env(&env)
.stdin(Stdio::Null)
.stdout(Stdio::Null)
.stderr(Stdio::Null)
.spawn();
match spawned {
Ok(mut child) => Some(wait(&mut child)),
Err(error) if is_exec_format(error) => {
eprintln!("skipped: the system cannot execute {}", exe.display());
None
}
Err(error) => panic!("cannot run {}: {error}", exe.display()),
}
}
fn is_exec_format(error: Error) -> bool {
const ENOEXEC: i32 = 8;
cfg!(not(any(windows, target_os = "macos"))) && error.raw_os_error() == ENOEXEC
}
#[test]
fn arguments_through_std() {
let dir = tmp_dir("process_arguments_through_std");
let file = std::path::absolute(dir.join("args")).unwrap();
let args: Vec<Vec<u8>> = [
"plain",
"two words",
"",
" spaces ",
"tab\there",
r#"quote"inside"#,
r#""quoted""#,
r"back\slash",
r"trailing\",
r"trailing space\ ",
r"two trailing\\",
r#"both\"of them\\"#,
r#"\\"\\\"#,
"'single'",
"$HOME ; & | > < * ? ~ # ! ^ %PATH% %%",
"h\u{e9}llo \u{4e16}\u{754c} \u{1f600}",
"-n",
"--",
]
.iter()
.map(|arg| arg.as_bytes().to_vec())
.collect();
let mode = format!("args:{}", file.display());
let Some(status) = helper(&mode, &args) else {
return;
};
assert!(status.success(), "{status}");
let mut expected = Vec::new();
for arg in &args {
expected.extend_from_slice(arg);
expected.push(0);
}
assert_eq!(std::fs::read(&file).unwrap(), expected);
}
#[test]
fn arguments_and_environment_of_a_child() {
let dir = tmp_dir("process_arguments_and_environment_of_a_child");
let file = std::path::absolute(dir.join("args")).unwrap();
let args: Vec<Vec<u8>> = [
"plain",
"two words",
"",
"tab\there",
r#"quote"inside"#,
r#""quoted""#,
r"trailing\",
r"trailing space\ ",
r#"both\"of them\\"#,
r#"\\"\\\"#,
"%PATH% ^ & |",
"h\u{e9}llo \u{4e16}\u{754c} \u{1f600}",
"",
]
.iter()
.map(|arg| arg.as_bytes().to_vec())
.collect();
let vars = [
("OSCALL_T_PLAIN", "value"),
("OSCALL_T_EMPTY", ""),
("OSCALL_T_EQUALS", "a=b=c"),
("OSCALL_T_UNICODE", "h\u{e9}llo \u{1f600}"),
("OSCALL_T_SPACES", " a b "),
];
let exe = match std::env::current_exe() {
Ok(exe) => exe,
Err(_) => return,
};
let mut env = helper_env(&format!("oscall-args:{}", file.display()));
env.retain(|var| !var.starts_with(b"OSCALL_T_"));
for (name, value) in vars {
env.push(format!("{name}={value}").into_bytes());
}
let mut all: Vec<Vec<u8>> = ["--exact", "--nocapture", "helper_child_process", "--"]
.iter()
.map(|arg| arg.as_bytes().to_vec())
.collect();
all.extend_from_slice(&args);
let spawned = Command::new(bytes(&exe))
.args(&all)
.env(&env)
.stdin(Stdio::Null)
.stdout(Stdio::Null)
.stderr(Stdio::Null)
.spawn();
let status = match spawned {
Ok(mut child) => wait(&mut child),
Err(error) if is_exec_format(error) => {
eprintln!("skipped: the system cannot execute {}", exe.display());
return;
}
Err(error) => panic!("cannot run {}: {error}", exe.display()),
};
assert!(status.success(), "{status}");
let mut expected = Vec::new();
for arg in &args {
expected.extend_from_slice(arg);
expected.push(0);
}
expected.push(0xff);
let written = std::fs::read(&file).unwrap();
let (got_args, got_vars) = written.split_at(expected.len().min(written.len()));
assert_eq!(got_args, expected);
let mut got: Vec<&[u8]> = got_vars.split(|&b| b == 0).collect();
assert_eq!(got.pop(), Some(&b""[..]));
let mut got: Vec<(&[u8], &[u8])> = got.chunks(2).map(|pair| (pair[0], pair[1])).collect();
got.sort();
let mut want: Vec<(&[u8], &[u8])> = vars
.iter()
.map(|(name, value)| (name.as_bytes(), value.as_bytes()))
.collect();
want.sort();
assert_eq!(got, want);
}
#[test]
#[cfg(windows)]
fn raw_command_line() {
use oscall::process::windows::CommandExt;
let (read, write) = io::pipe().unwrap();
let shell = shell();
let mut child = Command::new(&shell)
.args(&["ignored"])
.raw_command_line(r#"cmd /C echo "a b" c& exit 3"#)
.stdin(Stdio::Null)
.stdout(Stdio::Handle(write.as_handle()))
.spawn()
.unwrap();
drop(write);
assert_eq!(read_text(&read), "\"a b\" c\n");
assert_eq!(wait(&mut child).code(), Some(3));
}
#[test]
#[cfg(windows)]
fn batch_files() {
use oscall::process::windows::CommandExt;
let dir = tmp_dir("process_batch_files");
let dir = std::path::absolute(&dir).unwrap();
let marker = dir.join("marker");
let inject = format!("\"&echo x>{}", marker.display());
for name in [
"x.bat",
"x.cmd",
"X.BAT",
"x.Cmd",
"x.bat.",
"x.bat ",
"x.cmd. . ",
"x.bat\\.",
"x.bat/.",
"sub\\..\\x.bat",
".\\x.cmd\\",
] {
let file = dir.join(if name.to_ascii_lowercase().contains("cmd") {
"x.cmd"
} else {
"x.bat"
});
std::fs::write(&file, "@exit /b 7\r\n").unwrap();
let program = dir.join(name);
let error = Command::new(bytes(&program))
.args(&[inject.as_str()])
.stdin(Stdio::Null)
.spawn()
.unwrap_err();
assert_eq!(error.kind(), ErrorKind::InvalidInput, "{name}: {error:?}");
let error = Command::new(bytes(&program)).spawn().unwrap_err();
assert_eq!(error.kind(), ErrorKind::InvalidInput, "{name}: {error:?}");
let error = Command::new(name).spawn().unwrap_err();
assert_eq!(error.kind(), ErrorKind::InvalidInput, "{name}: {error:?}");
}
assert!(!marker.exists());
for name in ["x.bat.exe", "bat", "x.batx", ".bat\\x"] {
let error = Command::new(name).spawn().unwrap_err();
assert_eq!(error.kind(), ErrorKind::NotFound, "{name}: {error:?}");
}
let line = format!("cmd /C \"{}\"", dir.join("x.bat").display());
let shell = shell();
let mut child = Command::new(&shell)
.raw_command_line(&line)
.stdin(Stdio::Null)
.spawn()
.unwrap();
assert_eq!(wait(&mut child).code(), Some(7));
}
#[test]
fn invalid_environment() {
let shell = shell();
for vars in [
&[""][..],
&["A=1", "", "B=2"],
&["A=1", "B"],
&["="],
&["=B"],
&["A=1", "B=2\0"],
] {
let error = Command::new(&shell)
.args(&[RUN, "exit 0"])
.env(vars)
.stdin(Stdio::Null)
.spawn()
.unwrap_err();
assert_eq!(error.kind(), ErrorKind::InvalidInput, "{vars:?}: {error:?}");
}
let script = if cfg!(windows) {
"echo [%OSCALL_A%][%OSCALL_B%]"
} else {
r#"echo "[${OSCALL_A-unset}][$OSCALL_B]""#
};
let mut vars = vec![
"OSCALL_A=".to_owned(),
"OSCALL_B=b".to_owned(),
"=Q:=x".to_owned(),
];
if cfg!(windows) {
vars.push(format!(
"SystemRoot={}",
std::env::var("SystemRoot").unwrap()
));
}
let options = Options {
env: Some(&vars),
..Options::default()
};
let output = run_with(script, &options);
assert!(output.status.success(), "{}", output.stderr);
let expected = if cfg!(windows) {
"[%OSCALL_A%][b]\n"
} else {
"[][b]\n"
};
assert_eq!(output.stdout, expected);
}
#[test]
fn exit_and_abort() {
let Some(status) = helper("exit:0", &[]) else {
return;
};
assert!(status.success());
let status = helper("exit:37", &[]).unwrap();
assert_eq!(status.code(), Some(37));
assert!(!status.success());
let status = helper("abort", &[]).unwrap();
assert!(!status.success());
#[cfg(windows)]
assert_eq!(status.code(), Some(0xc000_0409_u32 as i32));
#[cfg(not(windows))]
{
use oscall::process::unix::ExitStatusExt;
const SIGABRT: i32 = 6;
assert_eq!(status.code(), None);
assert_eq!(status.signal(), Some(SIGABRT));
}
}
#[test]
fn child_ids() {
let dir = tmp_dir("process_child_ids");
let file = std::path::absolute(dir.join("ids")).unwrap();
let mode = format!("ids:{}", file.display());
if helper(&mode, &[]).is_none() {
return;
}
let ids = std::fs::read_to_string(&file).unwrap();
let (id, parent) = ids.split_once(' ').unwrap();
assert_ne!(id.parse::<u32>().unwrap(), oscall::process::id());
assert_eq!(parent.parse::<u32>().unwrap(), oscall::process::id());
}
#[test]
fn explicit_environment() {
let script = if cfg!(windows) {
"echo %OSCALL_A%-%OSCALL_B%-%OSCALL_C%"
} else {
r#"echo "$OSCALL_A-$OSCALL_B-${OSCALL_C-unset}-${HOME-unset}""#
};
let vars = vec![
"OSCALL_A=two words".to_owned(),
"OSCALL_B=h\u{e9}=\u{4e16}".to_owned(),
];
let options = Options {
env: Some(&vars),
..Options::default()
};
let output = run_with(script, &options);
assert!(output.status.success());
if cfg!(windows) {
let out = &output.stdout;
assert!(out.starts_with("two words-h"), "{out:?}");
assert!(out.ends_with("-%OSCALL_C%\n"), "{out:?}");
} else {
assert_eq!(output.stdout, "two words-h\u{e9}=\u{4e16}-unset-unset\n");
}
let script = if cfg!(windows) {
"echo %OSCALL_A%-%SystemRoot%"
} else {
r#"echo "${OSCALL_A-unset}-${HOME-unset}""#
};
let options = Options {
env: Some(&[]),
..Options::default()
};
let output = run_with(script, &options);
assert!(output.status.success());
let expected = if cfg!(windows) {
"%OSCALL_A%-%SystemRoot%\n"
} else {
"unset-unset\n"
};
assert_eq!(output.stdout, expected);
}
#[test]
fn inherited_environment() {
let name = if cfg!(windows) { "SystemRoot" } else { "PATH" };
let value = std::env::var(name).unwrap();
let script = if cfg!(windows) {
"echo %SystemRoot%"
} else {
r#"echo "$PATH""#
};
let output = run(script);
assert!(output.status.success());
assert_eq!(output.stdout, format!("{value}\n"));
}
#[test]
fn working_directory() {
let dir = tmp_dir("process_working_directory");
let script = if cfg!(windows) {
"echo x> marker"
} else {
"echo x > marker"
};
let options = Options {
dir: Some(&dir),
..Options::default()
};
let output = run_with(script, &options);
assert!(output.status.success(), "{}", output.stderr);
assert!(dir.join("marker").is_file());
assert!(!PathBuf::from("marker").exists());
let shell = shell();
let missing = dir.join("missing");
let result = Command::new(&shell)
.args(&[RUN, "exit 0"])
.current_dir(bytes(&missing))
.spawn();
let kind = result.unwrap_err().kind();
if cfg!(windows) {
assert_eq!(kind, ErrorKind::NotADirectory);
} else {
assert_eq!(kind, ErrorKind::NotFound);
}
}
#[test]
#[cfg(not(windows))]
fn relative_program() {
let dir = tmp_dir("process_relative_program");
let sub = dir.join("sub");
std::fs::create_dir(&sub).unwrap();
let script = dir.join("script");
assert!(script.is_relative());
std::fs::write(&script, "#!/bin/sh\necho \"$0\" > marker\nexit 5\n").unwrap();
let executable = oscall::fs::Permissions::from_mode(0o755);
oscall::fs::set_permissions(bytes(&script), executable).unwrap();
let command = Command::new(bytes(&script))
.stdin(Stdio::Null)
.current_dir(bytes(&sub));
let mut child = loop {
match command.spawn() {
Ok(child) => break child,
Err(error) if error.kind() == ErrorKind::ExecutableFileBusy => {
std::thread::sleep(Duration::from_millis(2));
}
Err(error) => panic!("{error:?}"),
}
};
assert_eq!(wait(&mut child).code(), Some(5));
let seen = std::fs::read_to_string(sub.join("marker")).unwrap();
let absolute = std::path::absolute(&script).unwrap();
assert_eq!(seen.trim_end(), absolute.to_str().unwrap());
assert!(!dir.join("marker").exists());
let (read, write) = io::pipe().unwrap();
std::fs::write(&script, "#!/bin/sh\necho \"$0\"\n").unwrap();
let command = Command::new(bytes(&script))
.stdin(Stdio::Null)
.stdout(Stdio::Handle(write.as_handle()));
let mut child = loop {
match command.spawn() {
Ok(child) => break child,
Err(error) if error.kind() == ErrorKind::ExecutableFileBusy => {
std::thread::sleep(Duration::from_millis(2));
}
Err(error) => panic!("{error:?}"),
}
};
drop(write);
assert_eq!(read_text(&read).trim_end(), script.to_str().unwrap());
assert!(wait(&mut child).success());
}
#[test]
#[cfg(windows)]
fn relative_program() {
let dir = tmp_dir("process_relative_program");
let exe = std::env::current_exe().unwrap();
let here = std::env::current_dir().unwrap();
let Ok(relative) = exe.strip_prefix(&here) else {
eprintln!("skipped: {} is not under {}", exe.display(), here.display());
return;
};
let env = helper_env("exit:5");
let mut child = Command::new(bytes(relative))
.args(&["--exact", "--nocapture", "helper_child_process"])
.env(&env)
.stdin(Stdio::Null)
.stdout(Stdio::Null)
.stderr(Stdio::Null)
.current_dir(bytes(&dir))
.spawn()
.unwrap();
assert_eq!(wait(&mut child).code(), Some(5));
}
#[test]
fn found_program() {
let Some(path) = std::env::var_os("PATH") else {
eprintln!("skipped: no PATH");
return;
};
let name = if cfg!(windows) { "cmd" } else { "sh" };
let program = oscall::process::find_program_vec(name, path.as_encoded_bytes()).unwrap();
assert!(std::path::Path::new(std::str::from_utf8(&program).unwrap()).is_file());
let mut child = Command::new(&program)
.args(&[RUN, "exit 3"])
.stdin(Stdio::Null)
.spawn()
.unwrap();
assert_eq!(wait(&mut child).code(), Some(3));
}
#[test]
#[cfg(windows)]
fn sorted_environment() {
let vars = vec![
format!("SystemRoot={}", std::env::var("SystemRoot").unwrap()),
"OSCALL_ZZ=1".to_owned(),
"oscall_mm=2".to_owned(),
"OSCALL_AA=3".to_owned(),
"oscall_b=4".to_owned(),
"OSCALL_B=5".to_owned(),
"=X:=X:\\".to_owned(),
];
let options = Options {
env: Some(&vars),
..Options::default()
};
let output = run_with("set", &options);
assert!(output.status.success(), "{}", output.stderr);
let ours: Vec<&str> = output
.stdout
.lines()
.filter(|line| line.to_ascii_lowercase().starts_with("oscall_"))
.collect();
assert_eq!(
ours,
[
"OSCALL_AA=3",
"oscall_b=4",
"OSCALL_B=5",
"oscall_mm=2",
"OSCALL_ZZ=1"
],
"{}",
output.stdout
);
}
#[test]
fn child_resource_usage() {
let script = if cfg!(windows) {
"for /L %i in (1,1,30000) do @rem"
} else {
"i=0; while [ $i -lt 100000 ]; do i=$((i+1)); done"
};
let shell = shell();
let mut child = Command::new(&shell)
.args(&[RUN, script])
.stdin(Stdio::Null)
.stdout(Stdio::Null)
.spawn()
.unwrap();
assert_eq!(child.resource_usage(), None);
let started = Instant::now();
assert!(wait(&mut child).success());
let elapsed = started.elapsed();
let usage = child
.resource_usage()
.expect("no usage for a child waited for");
assert_eq!(child.resource_usage(), Some(usage));
let peak = usage.max_resident_memory();
assert!(peak < 1 << 40, "{usage:?}");
if !cfg!(any(target_os = "linux", target_os = "fullrust")) {
assert!(peak > 0, "{usage:?}");
}
let total = usage.user_time() + usage.system_time();
assert!(
total <= 2 * elapsed + Duration::from_secs(1),
"{usage:?} {elapsed:?}"
);
if !cfg!(windows) {
assert!(total > Duration::ZERO, "{usage:?}");
}
let (mut child, _input) = blocked_child();
child.kill().unwrap();
child.wait().unwrap();
assert!(child.resource_usage().is_some());
}
#[test]
fn exists_and_kill() {
let (mut child, _input) = blocked_child();
let pid = child.id();
assert_eq!(oscall::process::exists(pid), Ok(true));
oscall::process::kill(pid).unwrap();
let status = child.wait().unwrap();
#[cfg(windows)]
assert_eq!(status.code(), Some(1));
#[cfg(not(windows))]
{
use oscall::process::unix::{ExitStatusExt, SIGKILL};
assert_eq!(status.signal(), Some(SIGKILL));
}
assert_eq!(oscall::process::exists(pid), Ok(false));
let error = oscall::process::kill(pid).unwrap_err();
let expected = if cfg!(windows) {
ErrorKind::InvalidInput
} else {
ErrorKind::NoSuchProcess
};
assert_eq!(error.kind(), expected, "{error:?}");
}
#[test]
#[cfg(windows)]
fn new_process_group() {
use oscall::process::windows::CommandExt;
let (read, write) = io::pipe().unwrap();
let shell = shell();
let mut child = Command::new(&shell)
.args(&[RUN, "echo out& exit 3"])
.new_process_group()
.stdin(Stdio::Null)
.stdout(Stdio::Handle(write.as_handle()))
.spawn()
.unwrap();
drop(write);
assert_eq!(read_text(&read), "out\n");
assert_eq!(wait(&mut child).code(), Some(3));
}
#[cfg(not(windows))]
fn blocked_child_with(
configure: impl for<'a> FnOnce(Command<'a>) -> Command<'a>,
) -> (Child, OwnedHandle) {
let (read, write) = io::pipe().unwrap();
let (program, args) = filter();
let command = Command::new(&program)
.args(&args)
.stdin(Stdio::Handle(read.as_handle()))
.stdout(Stdio::Null)
.stderr(Stdio::Null);
(configure(command).spawn().unwrap(), write)
}
#[test]
#[cfg(not(windows))]
fn signal_by_pid() {
use oscall::process::unix::{self, ExitStatusExt};
let (mut child, _input) = blocked_child();
let pid = child.id();
unix::send_signal(pid, 0).unwrap();
assert_eq!(child.try_wait().unwrap(), None);
let error = unix::send_signal(pid, 1000).unwrap_err();
assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
unix::send_signal(pid, unix::SIGUSR1).unwrap();
assert_eq!(child.wait().unwrap().signal(), Some(unix::SIGUSR1));
let error = unix::send_signal(pid, 0).unwrap_err();
assert_eq!(error.kind(), ErrorKind::NoSuchProcess, "{error:?}");
for pid in [0, u32::MAX, 1 << 31] {
let error = unix::send_signal(pid, 0).unwrap_err();
assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
let error = unix::send_signal_to_group(pid, 0).unwrap_err();
assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
let error = unix::process_group(pid).unwrap_err();
assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
let error = unix::session(pid).unwrap_err();
assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
}
let error = unix::send_signal_to_group(1, 0).unwrap_err();
assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
}
#[test]
#[cfg(not(windows))]
fn process_groups() {
use oscall::process::unix::{self, CommandExt, ExitStatusExt};
let own = oscall::process::id();
let group = unix::process_group(own).unwrap();
let session = unix::session(own).unwrap();
assert_ne!(group, 0);
assert_ne!(session, 0);
let (mut child, _input) = blocked_child();
assert_eq!(unix::process_group(child.id()), Ok(group));
assert_eq!(unix::session(child.id()), Ok(session));
child.kill().unwrap();
child.wait().unwrap();
let (mut leader, _leader_input) = blocked_child_with(|command| command.process_group(0));
assert_eq!(unix::process_group(leader.id()), Ok(leader.id()));
assert_eq!(unix::session(leader.id()), Ok(session));
let id = leader.id();
let (mut member, _member_input) = blocked_child_with(|command| command.process_group(id));
assert_eq!(unix::process_group(member.id()), Ok(leader.id()));
unix::send_signal_to_group(leader.id(), 0).unwrap();
unix::send_signal_to_group(leader.id(), unix::SIGTERM).unwrap();
assert_eq!(leader.wait().unwrap().signal(), Some(unix::SIGTERM));
assert_eq!(member.wait().unwrap().signal(), Some(unix::SIGTERM));
let error = unix::send_signal_to_group(id, 0).unwrap_err();
assert_eq!(error.kind(), ErrorKind::NoSuchProcess, "{error:?}");
let (read, _write) = io::pipe().unwrap();
let (program, args) = filter();
let error = Command::new(&program)
.args(&args)
.stdin(Stdio::Handle(read.as_handle()))
.process_group(id)
.spawn()
.unwrap_err();
assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
let (mut child, _input) =
blocked_child_with(|command| command.new_session().process_group(group));
assert_eq!(unix::session(child.id()), Ok(child.id()));
assert_eq!(unix::process_group(child.id()), Ok(child.id()));
child.kill().unwrap();
child.wait().unwrap();
}
#[cfg(not(windows))]
fn run_configured<'a>(
script: &'a str,
configure: impl FnOnce(Command<'a>) -> Command<'a>,
) -> Result<Output, Error> {
const SHELL: &str = "/bin/sh";
let (out_read, out_write) = io::pipe().unwrap();
let (err_read, err_write) = io::pipe().unwrap();
let args = [RUN, script];
let command = configure(Command::new(SHELL));
let mut child = command
.args(&args)
.stdin(Stdio::Null)
.stdout(Stdio::Handle(out_write.as_handle()))
.stderr(Stdio::Handle(err_write.as_handle()))
.spawn()?;
drop((out_write, err_write));
let stdout = read_text(&out_read);
let stderr = read_text(&err_read);
Ok(Output {
status: wait(&mut child),
stdout,
stderr,
})
}
#[test]
#[cfg(not(windows))]
fn child_limits() {
use oscall::process::unix::{self, CommandExt, Limit, Resource};
let files = unix::limit(Resource::OpenFiles).unwrap();
let limits = [
(
Resource::OpenFiles,
Limit {
soft: Some(57),
hard: files.hard,
},
),
(
Resource::CoreSize,
Limit {
soft: Some(0),
hard: Some(0),
},
),
];
let output = run_configured("ulimit -n; ulimit -c; ulimit -H -c", |command| {
command.limits(&limits)
})
.unwrap();
assert_eq!(output.stdout, "57\n0\n0\n", "{}", output.stderr);
assert!(output.status.success());
let output = run_configured("ulimit -n", |command| command.limits(&[])).unwrap();
let inherited = files.soft.map_or("unlimited".to_owned(), |n| n.to_string());
assert_eq!(output.stdout.trim(), inherited);
assert_eq!(unix::limit(Resource::OpenFiles), Ok(files));
for limit in [
Limit {
soft: Some(u64::MAX),
hard: None,
},
Limit {
soft: Some(2),
hard: Some(1),
},
] {
let limits = [(Resource::CoreSize, limit)];
let error = run_configured("exit 0", |command| command.limits(&limits))
.err()
.unwrap();
assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
}
if let Some(hard) = files.hard
&& !is_root()
{
let limits = [(
Resource::OpenFiles,
Limit {
soft: files.soft,
hard: Some(hard + 1),
},
)];
let error = run_configured("exit 0", |command| command.limits(&limits))
.err()
.unwrap();
assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
}
}
#[cfg(not(windows))]
fn own_ids() -> (u32, u32) {
let output = run("id -u; id -g");
let mut ids = output.stdout.lines().map(|id| id.parse().unwrap());
(ids.next().unwrap(), ids.next().unwrap())
}
#[cfg(not(windows))]
fn is_root() -> bool {
own_ids().0 == 0
}
#[cfg(not(any(windows, target_os = "macos")))]
fn own_groups() -> String {
run("id -G").stdout
}
#[cfg(target_os = "macos")]
fn own_groups() -> String {
unsafe extern "C" {
fn getgroups(count: i32, list: *mut u32) -> i32;
fn getegid() -> u32;
}
let mut list = [0u32; 64];
let count = unsafe { getgroups(list.len() as i32, list.as_mut_ptr()) };
assert!(count >= 0);
let own = unsafe { getegid() };
let others = list[..count as usize].iter().filter(|group| **group != own);
let mut out = own.to_string();
for group in others {
out.push_str(&format!(" {group}"));
}
out + "\n"
}
#[test]
#[cfg(not(windows))]
fn child_umask() {
use oscall::process::unix::{self, CommandExt};
for mask in [0o027, 0o777, 0] {
let output = run_configured("umask", |command| command.umask(mask)).unwrap();
assert_eq!(output.stdout, format!("{mask:04o}\n"), "{}", output.stderr);
assert!(output.status.success());
}
let dir = tmp_dir("process_child_umask");
let dir = std::path::absolute(&dir).unwrap();
let output = run_configured(
"umask; pwd; echo text > file; echo error >&2; exit 7",
|c| c.umask(0o026).current_dir(bytes(&dir)).arg0("custom"),
)
.unwrap();
let mut lines = output.stdout.lines();
assert_eq!(lines.next(), Some("0026"));
let here = PathBuf::from(lines.next().unwrap());
assert_eq!(
here.canonicalize().unwrap(),
dir.canonicalize().unwrap(),
"{here:?}"
);
assert_eq!(output.stderr, "error\n");
assert_eq!(output.status.code(), Some(7));
let metadata = oscall::fs::metadata(bytes(&dir.join("file"))).unwrap();
assert_eq!(metadata.permissions().mode() & 0o777, 0o640);
let error = run_configured("exit 0", |command| command.umask(0o1000))
.err()
.unwrap();
assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
let (mut child, _input) = blocked_child_with(|c| c.umask(0o022).process_group(0));
assert_eq!(unix::process_group(child.id()), Ok(child.id()));
let gone = child.id();
child.kill().unwrap();
child.wait().unwrap();
let (mut child, _input) = blocked_child_with(|c| c.umask(0o022).new_session());
assert_eq!(unix::session(child.id()), Ok(child.id()));
assert_eq!(unix::process_group(child.id()), Ok(child.id()));
child.kill().unwrap();
child.wait().unwrap();
let error = run_configured("exit 0", |c| c.umask(0o022).process_group(gone))
.err()
.unwrap();
assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
let missing = dir.join("missing");
let error = Command::new(bytes(&missing)).umask(0o022).spawn();
let error = error.unwrap_err();
assert_eq!(error.kind(), ErrorKind::NotFound, "{error:?}");
let error = run_configured("exit 0", |c| c.umask(0o022).current_dir(bytes(&missing)))
.err()
.unwrap();
assert_eq!(error.kind(), ErrorKind::NotFound, "{error:?}");
let (read, write) = io::pipe().unwrap();
io::set_inheritable(&write, true).unwrap();
let (mut child, input) = blocked_child_with(|command| command.umask(0o022));
drop(write);
let (sender, receiver) = mpsc::channel();
let reader = std::thread::spawn(move || {
let mut buf = [0u8; 1];
let _ = sender.send(io::read(&read, &mut buf));
});
let result = receiver.recv_timeout(Duration::from_secs(20));
child.kill().unwrap();
child.wait().unwrap();
drop(input);
reader.join().unwrap();
match result {
Ok(Ok(0)) => {}
other => panic!("the child inherited the pipe: {other:?}"),
}
}
#[cfg(any(target_os = "linux", target_os = "fullrust"))]
fn dumpable() -> usize {
use oscall::raw::linux::{nr, syscall1};
const PR_GET_DUMPABLE: usize = 3;
unsafe { syscall1(nr::PRCTL, PR_GET_DUMPABLE) }
}
#[test]
#[cfg(not(windows))]
fn child_identity() {
use oscall::process::unix::CommandExt;
let (uid, gid) = own_ids();
let output = run_configured("id -u; id -g", |c| c.uid(uid).gid(gid)).unwrap();
assert_eq!(
output.stdout,
format!("{uid}\n{gid}\n"),
"{}",
output.stderr
);
if uid == 0 {
let groups = [4242];
#[cfg(not(target_os = "macos"))]
let dumpable = dumpable();
let output = run_configured("id -u; id -g; id -G", |command| {
command.uid(4243).gid(4242).groups(&groups)
})
.unwrap();
assert_eq!(output.stdout, "4243\n4242\n4242\n", "{}", output.stderr);
#[cfg(not(target_os = "macos"))]
assert_eq!(self::dumpable(), dumpable);
let before = own_groups();
let output = run_configured("id -u; id -G", |c| c.uid(4243)).unwrap();
assert_eq!(output.stdout, format!("4243\n{before}"));
use oscall::process::unix::{Limit, Resource};
let lower = Limit {
soft: Some(0),
hard: Some(0),
};
let raise = Limit {
soft: Some(0),
hard: None,
};
let both = [(Resource::CoreSize, lower), (Resource::CoreSize, raise)];
let may_raise = run_configured("exit 0", |command| command.limits(&both)).is_ok();
let limits = if may_raise { &both[..] } else { &both[1..] };
let output = run_configured("id -u; ulimit -H -c", |command| {
command.uid(4243).limits(limits)
})
.unwrap();
assert_eq!(output.stdout, "4243\nunlimited\n", "{}", output.stderr);
let output = run_configured("id -g; id -G", |command| {
command.uid(4243).gid(4242).groups(&[7, 8])
})
.unwrap();
assert_eq!(output.stdout, "4242\n4242 7 8\n", "{}", output.stderr);
let output = run_configured("id -g; id -G", |c| c.uid(4243).groups(&[7, 8])).unwrap();
assert_eq!(
output.stdout,
format!("{gid}\n{gid} 7 8\n"),
"{}",
output.stderr
);
let output = run_configured("id -G", |c| c.uid(4243).gid(4242).groups(&[])).unwrap();
assert_eq!(output.stdout, "4242\n", "{}", output.stderr);
let most = if cfg!(target_os = "macos") { 15 } else { 65536 };
let many: Vec<u32> = (5000..=5000 + most).collect();
let output = run_configured("exit 0", |c| c.groups(&many[..most as usize]));
assert!(output.unwrap().status.success());
let error = run_configured("exit 0", |c| c.groups(&many)).err().unwrap();
assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
} else {
for configure in [
(|c| c.uid(0)) as for<'a> fn(Command<'a>) -> Command<'a>,
|c| c.gid(0),
|c| c.groups(&[]),
|c| c.groups(&[0]),
] {
let error = run_configured("exit 0", configure).err().unwrap();
assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
}
}
}
#[cfg(any(target_os = "linux", target_os = "fullrust", windows))]
pub(super) fn orphan_helper(tied: bool) -> ! {
let (program, args) = filter();
let command = Command::new(&program).args(&args).stderr(Stdio::Null);
#[cfg(not(windows))]
let command = {
use oscall::process::linux::CommandExt;
if tied {
command.parent_death_signal(oscall::process::unix::SIGKILL)
} else {
command
}
};
#[cfg(windows)]
let job = {
use oscall::process::windows::{Job, JobLimits};
let job = Job::new().unwrap();
let mut limits = JobLimits::new();
limits.kill_on_close = tied;
job.set_limits(&limits).unwrap();
job
};
#[cfg(windows)]
let command = {
use oscall::process::windows::CommandExt;
command.job(&job)
};
let child = command.spawn().unwrap();
std::mem::forget(child);
oscall::process::exit(0)
}
#[cfg(any(target_os = "linux", target_os = "fullrust", windows))]
fn orphan_survives(mode: &str) -> Option<bool> {
let exe = std::env::current_exe().unwrap();
let env = helper_env(mode);
let args = ["--exact", "--nocapture", "helper_child_process"];
let (in_read, in_write) = io::pipe().unwrap();
let (out_read, out_write) = io::pipe().unwrap();
let spawned = Command::new(bytes(&exe))
.args(&args)
.env(&env)
.stdin(Stdio::Handle(in_read.as_handle()))
.stdout(Stdio::Handle(out_write.as_handle()))
.stderr(Stdio::Null)
.spawn();
let mut helper = match spawned {
Ok(child) => child,
Err(error) if is_exec_format(error) => {
eprintln!("skipped: the system cannot execute {}", exe.display());
return None;
}
Err(error) => panic!("cannot run {}: {error}", exe.display()),
};
drop((in_read, out_write));
assert_eq!(wait(&mut helper).code(), Some(0));
let (sender, ended) = mpsc::channel();
let reader = std::thread::spawn(move || {
read_bytes(&out_read);
let _ = sender.send(());
});
let survives = ended.recv_timeout(Duration::from_millis(300)).is_err()
&& (mode.ends_with("plain") || ended.recv_timeout(Duration::from_secs(60)).is_err());
drop(in_write);
reader.join().unwrap();
Some(survives)
}
#[test]
#[cfg(any(target_os = "linux", target_os = "fullrust"))]
fn parent_death_signal() {
use oscall::process::linux::CommandExt;
use oscall::process::unix::{self, ExitStatusExt};
let (mut child, input) =
blocked_child_with(|command| command.parent_death_signal(unix::SIGTERM));
std::thread::sleep(Duration::from_millis(20));
assert_eq!(child.try_wait().unwrap(), None);
drop(input);
assert!(wait(&mut child).code().is_some());
let (mut child, _input) = std::thread::spawn(|| {
blocked_child_with(|command| command.parent_death_signal(unix::SIGTERM))
})
.join()
.unwrap();
assert_eq!(wait(&mut child).signal(), Some(unix::SIGTERM));
if is_root() {
use oscall::process::unix::CommandExt as _;
let (mut child, _input) = std::thread::spawn(|| {
blocked_child_with(|command| {
command
.uid(4243)
.gid(4242)
.parent_death_signal(unix::SIGTERM)
})
})
.join()
.unwrap();
assert_eq!(wait(&mut child).signal(), Some(unix::SIGTERM));
}
for signal in [0, -1, 65, 1000] {
let error = run_configured("exit 0", |c| c.parent_death_signal(signal))
.err()
.unwrap();
assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
}
if let Some(survives) = orphan_survives("orphan:plain") {
assert!(survives);
}
if let Some(survives) = orphan_survives("orphan:tied") {
assert!(!survives);
}
}
#[test]
#[cfg(not(windows))]
fn fork() {
if let Some(status) = helper("fork", &[]) {
assert_eq!(status.code(), Some(0));
}
}
#[cfg(not(windows))]
pub(super) fn fork_helper() -> ! {
use oscall::process::unix::{self, ExitStatusExt, Fork};
let own = oscall::process::id();
let (read, write) = io::pipe().unwrap();
match unsafe { unix::fork() }.unwrap() {
Fork::Child => {
let id = oscall::process::id().to_ne_bytes();
let parent = oscall::process::parent_id().to_ne_bytes();
let written = io::write(&write, &id).is_ok_and(|n| n == 4)
&& io::write(&write, &parent).is_ok_and(|n| n == 4);
oscall::process::exit(if written { 42 } else { 1 })
}
Fork::Parent(mut child) => {
drop(write);
let said = read_bytes(&read);
assert_eq!(wait(&mut child).code(), Some(42));
assert_ne!(child.id(), own);
assert_eq!(said[..4], child.id().to_ne_bytes());
assert_eq!(said[4..], own.to_ne_bytes());
}
}
let (read, write) = io::pipe().unwrap();
match unsafe { unix::fork() }.unwrap() {
Fork::Child => {
let mut byte = [0];
let _ = io::read(&read, &mut byte);
oscall::process::exit(3)
}
Fork::Parent(mut child) => {
assert_eq!(child.try_wait().unwrap(), None);
assert_eq!(unix::process_group(child.id()), unix::process_group(own));
child.kill().unwrap();
assert_eq!(wait(&mut child).signal(), Some(unix::SIGKILL));
drop(write);
}
}
oscall::process::exit(0)
}
#[test]
#[cfg(windows)]
fn job_limits() {
use oscall::process::windows::{Job, JobLimits};
let job = Job::new().unwrap();
assert_eq!(job.limits().unwrap(), JobLimits::new());
assert_eq!(JobLimits::new(), JobLimits::default());
let accounting = job.accounting().unwrap();
assert_eq!(accounting.total_processes, 0);
assert_eq!(accounting.active_processes, 0);
assert_eq!(accounting.terminated_processes, 0);
assert_eq!(accounting.user_time, Duration::ZERO);
assert_eq!(accounting.system_time, Duration::ZERO);
let mut limits = JobLimits::new();
limits.process_memory = Some(256 << 20);
limits.job_memory = Some(512 << 20);
limits.active_processes = Some(5);
limits.process_time = Some(Duration::from_millis(1500));
limits.job_time = Some(Duration::from_secs(90));
limits.kill_on_close = true;
job.set_limits(&limits).unwrap();
assert_eq!(job.limits().unwrap(), limits);
let mut one = JobLimits::new();
one.active_processes = Some(1);
job.set_limits(&one).unwrap();
assert_eq!(job.limits().unwrap(), one);
job.set_limits(&JobLimits::new()).unwrap();
assert_eq!(job.limits().unwrap(), JobLimits::new());
job.terminate(1).unwrap();
let handle: OwnedHandle = job.into();
drop(handle);
}
#[test]
#[cfg(windows)]
fn job_spawn() {
use oscall::process::windows::{CommandExt, Job, JobLimits};
let in_job = |job: &Job| {
let (read, write) = io::pipe().unwrap();
let (program, args) = filter();
let child = Command::new(&program)
.args(&args)
.stdin(Stdio::Handle(read.as_handle()))
.stdout(Stdio::Null)
.stderr(Stdio::Null)
.job(job)
.spawn();
child.map(|child| (child, write))
};
let job = Job::new().unwrap();
let mut limits = JobLimits::new();
limits.active_processes = Some(2);
job.set_limits(&limits).unwrap();
let (mut first, _first_input) = in_job(&job).unwrap();
let (mut second, second_input) = in_job(&job).unwrap();
let accounting = job.accounting().unwrap();
assert_eq!(accounting.total_processes, 2);
assert_eq!(accounting.active_processes, 2);
let full = in_job(&job).map(|_| ()).unwrap_err();
assert_eq!(job.accounting().unwrap().active_processes, 2);
drop(second_input);
assert!(wait(&mut second).code().is_some());
wait_for_active(&job, 1);
let (mut third, _third_input) = in_job(&job).unwrap();
assert_eq!(job.accounting().unwrap().total_processes, 3);
assert_eq!(first.try_wait().unwrap(), None);
job.terminate(77).unwrap();
assert_eq!(wait(&mut first).code(), Some(77));
assert_eq!(wait(&mut third).code(), Some(77));
wait_for_active(&job, 0);
let shell = shell();
let mut child = Command::new(&shell)
.args(&[RUN, "exit 5"])
.stdin(Stdio::Null)
.stdout(Stdio::Null)
.stderr(Stdio::Null)
.job(&job)
.spawn()
.unwrap();
assert_eq!(wait(&mut child).code(), Some(5));
assert_eq!(job.accounting().unwrap().total_processes, 4);
assert_eq!(full.raw_os_error(), 1816, "{full:?}");
}
#[test]
#[cfg(windows)]
fn job_spawn_without_handles() {
let status = helper("bare-job", &[]).unwrap();
assert_eq!(status.code(), Some(0));
}
#[cfg(windows)]
pub(super) fn bare_job_helper() -> ! {
use oscall::process::exit;
use oscall::process::windows::{CommandExt, Job};
#[link(name = "kernel32")]
unsafe extern "system" {
fn SetStdHandle(which: u32, handle: *mut core::ffi::c_void) -> i32;
}
for which in [-10i32, -11, -12] {
if unsafe { SetStdHandle(which as u32, std::ptr::null_mut()) } == 0 {
exit(10);
}
}
let Ok(job) = Job::new() else { exit(11) };
let shell = shell();
let spawned = Command::new(&shell)
.args(&[RUN, "exit 5"])
.job(&job)
.spawn();
let Ok(mut child) = spawned else { exit(12) };
if child.wait().ok().and_then(|status| status.code()) != Some(5) {
exit(13);
}
match job.accounting() {
Ok(accounting) if accounting.total_processes == 1 => exit(0),
_ => exit(14),
}
}
#[cfg(windows)]
fn wait_for_active(job: &oscall::process::windows::Job, count: u32) {
let start = Instant::now();
loop {
let accounting = job.accounting().unwrap();
if accounting.active_processes == count {
return;
}
assert!(
start.elapsed() < Duration::from_secs(60),
"{accounting:?}, not {count}"
);
std::thread::sleep(Duration::from_millis(2));
}
}
#[test]
#[cfg(windows)]
fn job_assign_and_close() {
use oscall::process::windows::{Job, JobLimits};
let job = Job::new().unwrap();
let (mut child, _input) = blocked_child();
job.assign(&child).unwrap();
let accounting = job.accounting().unwrap();
assert_eq!(accounting.total_processes, 1);
assert_eq!(accounting.active_processes, 1);
drop(job);
std::thread::sleep(Duration::from_millis(20));
assert_eq!(child.try_wait().unwrap(), None);
let job = Job::new().unwrap();
let mut limits = JobLimits::new();
limits.kill_on_close = true;
job.set_limits(&limits).unwrap();
job.assign(&child).unwrap();
assert_eq!(child.try_wait().unwrap(), None);
drop(job);
let closed = wait(&mut child);
let job = Job::new().unwrap();
let exited = job.assign(&child).unwrap_err();
assert_eq!(exited.kind(), ErrorKind::PermissionDenied, "{exited:?}");
assert_eq!(closed.code(), Some(0), "{closed:?}");
}
#[test]
#[cfg(windows)]
fn job_kill_on_parent_exit() {
assert_eq!(orphan_survives("orphan:plain"), Some(true));
assert_eq!(orphan_survives("orphan:tied"), Some(false));
}
#[test]
#[cfg(windows)]
fn job_time_limit() {
use oscall::process::windows::{CommandExt, Job, JobLimits};
let job = Job::new().unwrap();
let mut limits = JobLimits::new();
limits.process_time = Some(Duration::from_millis(100));
job.set_limits(&limits).unwrap();
let shell = shell();
let mut child = Command::new(&shell)
.args(&[RUN, "for /L %i in (0,0,1) do @rem"])
.stdin(Stdio::Null)
.stdout(Stdio::Null)
.stderr(Stdio::Null)
.job(&job)
.spawn()
.unwrap();
let status = wait(&mut child);
assert_eq!(status.code(), Some(0xc000_0044_u32 as i32), "{status:?}");
let accounting = job.accounting().unwrap();
assert_eq!(accounting.terminated_processes, 1, "{accounting:?}");
assert!(
accounting.user_time >= Duration::from_millis(100),
"{accounting:?}"
);
}
#[test]
fn pipes() {
let (in_read, in_write) = io::pipe().unwrap();
let (out_read, out_write) = io::pipe().unwrap();
let (program, args) = filter();
let mut child = Command::new(&program)
.args(&args)
.stdin(Stdio::Handle(in_read.as_handle()))
.stdout(Stdio::Handle(out_write.as_handle()))
.spawn()
.unwrap();
drop((in_read, out_write));
assert_eq!(child.try_wait().unwrap(), None);
write_all(&in_write, b"x one\nno\nx two\n");
drop(in_write);
assert_eq!(read_text(&out_read), "x one\nx two\n");
assert!(wait(&mut child).success());
}
#[test]
fn files() {
let dir = tmp_dir("process_files");
std::fs::write(dir.join("in"), "x one\nno\nx two\n").unwrap();
let input = File::open(dir.join("in")).unwrap();
let output = File::create(dir.join("out")).unwrap();
let (program, args) = filter();
let mut child = Command::new(&program)
.args(&args)
.stdin(Stdio::Handle(handle_of(&input)))
.stdout(Stdio::Handle(handle_of(&output)))
.stderr(Stdio::Null)
.spawn()
.unwrap();
assert!(wait(&mut child).success());
let text = std::fs::read_to_string(dir.join("out")).unwrap();
assert_eq!(text.replace('\r', ""), "x one\nx two\n");
assert!(!io::is_inheritable(handle_of(&output)).unwrap());
}
#[test]
fn null() {
let (program, args) = filter();
let mut child = Command::new(&program)
.args(&args)
.stdin(Stdio::Null)
.stdout(Stdio::Null)
.stderr(Stdio::Null)
.spawn()
.unwrap();
assert!(wait(&mut child).code().is_some());
let script = if cfg!(windows) {
"echo out& echo err>&2& exit 3"
} else {
"echo out; echo err >&2; exit 3"
};
let shell = shell();
let mut child = Command::new(&shell)
.args(&[RUN, script])
.stdin(Stdio::Null)
.stdout(Stdio::Null)
.stderr(Stdio::Null)
.spawn()
.unwrap();
assert_eq!(wait(&mut child).code(), Some(3));
}
#[test]
fn invalid_handle() {
#[cfg(windows)]
let values = [0x7ffc_0000usize as oscall::RawHandle];
#[cfg(not(windows))]
let values: [oscall::RawHandle; 2] = [-1, 1_000_000];
let shell = shell();
for raw in values {
let handle = unsafe { oscall::BorrowedHandle::borrow_raw(raw) };
for target in 0..3 {
let mut command = Command::new(&shell).args(&[RUN, "exit 0"]);
command = match target {
0 => command.stdin(Stdio::Handle(handle)),
1 => command.stdout(Stdio::Handle(handle)),
_ => command.stderr(Stdio::Handle(handle)),
};
let error = command.spawn().unwrap_err();
assert_eq!(error.kind(), ErrorKind::BadHandle, "{error:?}");
}
}
}
fn blocked_child() -> (Child, OwnedHandle) {
let (read, write) = io::pipe().unwrap();
let (program, args) = filter();
let child = Command::new(&program)
.args(&args)
.stdin(Stdio::Handle(read.as_handle()))
.stdout(Stdio::Null)
.stderr(Stdio::Null)
.spawn()
.unwrap();
(child, write)
}
#[test]
fn try_wait() {
let (mut child, input) = blocked_child();
for _ in 0..3 {
assert_eq!(child.try_wait().unwrap(), None);
}
std::thread::sleep(Duration::from_millis(20));
assert_eq!(child.try_wait().unwrap(), None);
drop(input);
let status = wait(&mut child);
assert!(status.code().is_some());
assert_eq!(child.try_wait().unwrap(), Some(status));
assert_eq!(child.wait().unwrap(), status);
}
#[test]
fn kill() {
let (mut child, _input) = blocked_child();
assert_eq!(child.try_wait().unwrap(), None);
child.kill().unwrap();
let status = child.wait().unwrap();
assert!(!status.success());
#[cfg(windows)]
assert_eq!(status.code(), Some(1));
#[cfg(not(windows))]
{
use oscall::process::unix::{ExitStatusExt, SIGKILL};
assert_eq!(status.code(), None);
assert_eq!(status.signal(), Some(SIGKILL));
assert!(!status.core_dumped());
}
child.kill().unwrap();
assert_eq!(child.try_wait().unwrap(), Some(status));
assert_eq!(child.wait().unwrap(), status);
}
#[test]
fn kill_after_exit() {
let (mut child, input) = blocked_child();
drop(input);
std::thread::sleep(Duration::from_millis(200));
child.kill().unwrap();
let _ = child.wait().unwrap();
child.kill().unwrap();
}
#[test]
#[cfg(not(windows))]
fn signals() {
use oscall::process::unix::{self, ChildExt, ExitStatusExt};
let (mut child, _input) = blocked_child();
child.send_signal(0).unwrap();
assert_eq!(child.try_wait().unwrap(), None);
child.send_signal(unix::SIGTERM).unwrap();
let status = child.wait().unwrap();
assert_eq!(status.signal(), Some(unix::SIGTERM));
assert_eq!(status.code(), None);
assert!(!status.success());
assert!(format!("{status}").contains("signal"));
assert_eq!(
child.send_signal(unix::SIGTERM).unwrap_err().kind(),
ErrorKind::NoSuchProcess
);
let (mut child, input) = blocked_child();
child.send_signal(unix::SIGSTOP).unwrap();
assert_eq!(child.try_wait().unwrap(), None);
child.send_signal(unix::SIGCONT).unwrap();
assert_eq!(child.try_wait().unwrap(), None);
child.send_signal(unix::SIGKILL).unwrap();
assert_eq!(child.wait().unwrap().signal(), Some(unix::SIGKILL));
drop(input);
assert_eq!(unix::SIGQUIT, 3);
for signal in [unix::SIGHUP, unix::SIGINT, unix::SIGUSR1, unix::SIGUSR2] {
let (mut child, _input) = blocked_child();
child.send_signal(signal).unwrap();
assert_eq!(child.wait().unwrap().signal(), Some(signal));
}
}
#[test]
#[cfg(not(windows))]
fn signal_dispositions() {
use oscall::process::unix::ExitStatusExt;
const SIGPIPE: i32 = 13;
let (read, write) = io::pipe().unwrap();
drop(read);
let mut child = Command::new("/bin/sh")
.args(&["-c", "echo one; echo two; exit 0"])
.stdin(Stdio::Null)
.stdout(Stdio::Handle(write.as_handle()))
.stderr(Stdio::Null)
.spawn()
.unwrap();
let status = wait(&mut child);
assert_eq!(status.signal(), Some(SIGPIPE), "{status}");
}
#[test]
fn missing_program() {
let dir = tmp_dir("process_missing_program");
for path in [dir.join("missing"), dir.join("missing").join("program")] {
let error = Command::new(bytes(&path)).spawn().unwrap_err();
assert_eq!(error.kind(), ErrorKind::NotFound, "{error:?}");
}
let name = if cfg!(windows) { "cmd.exe" } else { "sh" };
let error = Command::new(name).spawn().unwrap_err();
assert_eq!(error.kind(), ErrorKind::NotFound, "{error:?}");
let error = Command::new("").spawn().unwrap_err();
assert!(
matches!(error.kind(), ErrorKind::NotFound | ErrorKind::InvalidInput),
"{error:?}"
);
}
#[test]
fn not_executable() {
let dir = tmp_dir("process_not_executable");
let error = Command::new(bytes(&dir)).spawn().unwrap_err();
assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
let file = dir.join("script");
std::fs::write(&file, "#!/bin/sh\nexit 5\n").unwrap();
let command = Command::new(bytes(&file)).stdin(Stdio::Null);
let error = command.spawn().unwrap_err();
if cfg!(windows) {
const ERROR_BAD_EXE_FORMAT: i32 = 193;
assert_eq!(error.raw_os_error(), ERROR_BAD_EXE_FORMAT);
return;
}
assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
let executable = oscall::fs::Permissions::from_mode(0o755);
oscall::fs::set_permissions(bytes(&file), executable).unwrap();
assert!(format!("{command:?}").contains("script"));
let spawn = |command: &Command<'_>| loop {
match command.spawn() {
Ok(child) => break child,
Err(error) if error.kind() == ErrorKind::ExecutableFileBusy => {
std::thread::sleep(Duration::from_millis(2));
}
Err(error) => panic!("{error:?}"),
}
};
for _ in 0..2 {
let mut child = spawn(&command);
assert_eq!(wait(&mut child).code(), Some(5));
}
let mut child = spawn(&command.clone());
assert_eq!(wait(&mut child).code(), Some(5));
}
#[test]
fn nothing_else_is_inherited() {
let (read, write) = io::pipe().unwrap();
io::set_inheritable(&write, true).unwrap();
let (mut child, input) = blocked_child();
drop(write);
let (sender, receiver) = mpsc::channel();
let reader = std::thread::spawn(move || {
let mut buf = [0u8; 1];
let _ = sender.send(io::read(&read, &mut buf));
});
let result = receiver.recv_timeout(Duration::from_secs(20));
child.kill().unwrap();
child.wait().unwrap();
drop(input);
reader.join().unwrap();
match result {
Ok(Ok(0)) => {}
Ok(Err(error)) if error.kind() == ErrorKind::BrokenPipe => {}
other => panic!("the child inherited the pipe: {other:?}"),
}
}
#[test]
#[cfg(any(target_os = "linux", target_os = "fullrust", windows))]
fn child_handle() {
let (mut child, input) = blocked_child();
assert!(!io::is_inheritable(child.as_handle()).unwrap());
let copy = io::duplicate(&child).unwrap();
drop(input);
wait(&mut child);
drop(copy);
}
#[test]
fn concurrent_spawns() {
let threads: Vec<_> = (0..8)
.map(|thread| {
std::thread::spawn(move || {
for round in 0..8 {
let token = thread * 10 + round;
let script = if cfg!(windows) {
format!("echo {token}& exit {token}")
} else {
format!("echo {token}; exit {token}")
};
let output = run(&script);
assert_eq!(output.stdout, format!("{token}\n"));
assert_eq!(output.stderr, "");
assert_eq!(output.status.code(), Some(token));
}
})
})
.collect();
for thread in threads {
thread.join().unwrap();
}
}
}