rust/library/std/src/sys/unix/process/process_unix.rs

536 lines
19 KiB
Rust
Raw Normal View History

use crate::convert::TryInto;
use crate::fmt;
2019-02-10 19:23:21 +00:00
use crate::io::{self, Error, ErrorKind};
use crate::ptr;
2019-12-22 22:42:04 +00:00
use crate::sys;
2019-02-10 19:23:21 +00:00
use crate::sys::cvt;
use crate::sys::process::process_common::*;
#[cfg(target_os = "vxworks")]
use libc::RTP_ID as pid_t;
#[cfg(not(target_os = "vxworks"))]
2019-02-10 19:23:21 +00:00
use libc::{c_int, gid_t, pid_t, uid_t};
////////////////////////////////////////////////////////////////////////////////
// Command
////////////////////////////////////////////////////////////////////////////////
impl Command {
2019-12-22 22:42:04 +00:00
pub fn spawn(
&mut self,
default: Stdio,
needs_stdin: bool,
) -> io::Result<(Process, StdioPipes)> {
const CLOEXEC_MSG_FOOTER: [u8; 4] = *b"NOEX";
2017-12-17 15:21:47 +00:00
let envp = self.capture_env();
if self.saw_nul() {
2019-12-22 22:42:04 +00:00
return Err(io::Error::new(ErrorKind::InvalidInput, "nul byte found in provided data"));
}
let (ours, theirs) = self.setup_io(default, needs_stdin)?;
2018-01-26 02:13:45 +00:00
if let Some(ret) = self.posix_spawn(&theirs, envp.as_ref())? {
2019-12-22 22:42:04 +00:00
return Ok((ret, ours));
2018-01-26 02:13:45 +00:00
}
let (input, output) = sys::pipe::anon_pipe()?;
// Whatever happens after the fork is almost for sure going to touch or
// look at the environment in one way or another (PATH in `execvp` or
// accessing the `environ` pointer ourselves). Make sure no other thread
// is accessing the environment when we do the fork itself.
//
// Note that as soon as we're done with the fork there's no need to hold
// a lock any more because the parent won't do anything and the child is
// in its own process.
let result = unsafe {
2021-02-06 21:38:16 +00:00
let _env_lock = sys::os::env_rwlock(true);
cvt(libc::fork())?
};
let pid = unsafe {
match result {
0 => {
drop(input);
let Err(err) = self.do_exec(theirs, envp.as_ref());
let errno = err.raw_os_error().unwrap_or(libc::EINVAL) as u32;
let errno = errno.to_be_bytes();
let bytes = [
errno[0],
errno[1],
errno[2],
errno[3],
2019-12-22 22:42:04 +00:00
CLOEXEC_MSG_FOOTER[0],
CLOEXEC_MSG_FOOTER[1],
CLOEXEC_MSG_FOOTER[2],
CLOEXEC_MSG_FOOTER[3],
];
// pipe I/O up to PIPE_BUF bytes should be atomic, and then
// we want to be sure we *don't* run at_exit destructors as
// we're being torn down regardless
rtassert!(output.write(&bytes).is_ok());
libc::_exit(1)
}
n => n,
}
};
let mut p = Process { pid, status: None };
drop(output);
let mut bytes = [0; 8];
// loop to handle EINTR
loop {
match input.read(&mut bytes) {
Ok(0) => return Ok((p, ours)),
Ok(8) => {
let (errno, footer) = bytes.split_at(4);
assert_eq!(
CLOEXEC_MSG_FOOTER, footer,
2019-12-22 22:42:04 +00:00
"Validation on the CLOEXEC pipe failed: {:?}",
bytes
);
let errno = i32::from_be_bytes(errno.try_into().unwrap());
2019-12-22 22:42:04 +00:00
assert!(p.wait().is_ok(), "wait() should either return Ok or panic");
return Err(Error::from_raw_os_error(errno));
}
Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
Err(e) => {
2019-12-22 22:42:04 +00:00
assert!(p.wait().is_ok(), "wait() should either return Ok or panic");
panic!("the CLOEXEC pipe failed: {:?}", e)
2019-12-22 22:42:04 +00:00
}
Ok(..) => {
// pipe I/O up to PIPE_BUF bytes should be atomic
assert!(p.wait().is_ok(), "wait() should either return Ok or panic");
panic!("short read on the CLOEXEC pipe")
}
}
}
}
pub fn exec(&mut self, default: Stdio) -> io::Error {
2017-12-17 15:21:47 +00:00
let envp = self.capture_env();
if self.saw_nul() {
2019-12-22 22:42:04 +00:00
return io::Error::new(ErrorKind::InvalidInput, "nul byte found in provided data");
}
match self.setup_io(default, true) {
Ok((_, theirs)) => {
unsafe {
// Similar to when forking, we want to ensure that access to
// the environment is synchronized, so make sure to grab the
// environment lock before we try to exec.
2021-02-06 21:38:16 +00:00
let _lock = sys::os::env_rwlock(true);
let Err(e) = self.do_exec(theirs, envp.as_ref());
e
}
}
Err(e) => e,
}
}
// And at this point we've reached a special time in the life of the
// child. The child must now be considered hamstrung and unable to
// do anything other than syscalls really. Consider the following
// scenario:
//
// 1. Thread A of process 1 grabs the malloc() mutex
// 2. Thread B of process 1 forks(), creating thread C
// 3. Thread C of process 2 then attempts to malloc()
// 4. The memory of process 2 is the same as the memory of
// process 1, so the mutex is locked.
//
// This situation looks a lot like deadlock, right? It turns out
// that this is what pthread_atfork() takes care of, which is
// presumably implemented across platforms. The first thing that
// threads to *before* forking is to do things like grab the malloc
// mutex, and then after the fork they unlock it.
//
// Despite this information, libnative's spawn has been witnessed to
// deadlock on both macOS and FreeBSD. I'm not entirely sure why, but
// all collected backtraces point at malloc/free traffic in the
// child spawned process.
//
// For this reason, the block of code below should contain 0
// invocations of either malloc of free (or their related friends).
//
// As an example of not having malloc/free traffic, we don't close
// this file descriptor by dropping the FileDesc (which contains an
// allocation). Instead we just close it manually. This will never
// have the drop glue anyway because this code never returns (the
// child will either exec() or invoke libc::exit)
2017-12-17 15:21:47 +00:00
unsafe fn do_exec(
&mut self,
stdio: ChildPipes,
2019-12-22 22:42:04 +00:00
maybe_envp: Option<&CStringArray>,
) -> Result<!, io::Error> {
2019-02-10 19:23:21 +00:00
use crate::sys::{self, cvt_r};
if let Some(fd) = stdio.stdin.fd() {
cvt_r(|| libc::dup2(fd, libc::STDIN_FILENO))?;
}
if let Some(fd) = stdio.stdout.fd() {
cvt_r(|| libc::dup2(fd, libc::STDOUT_FILENO))?;
}
if let Some(fd) = stdio.stderr.fd() {
cvt_r(|| libc::dup2(fd, libc::STDERR_FILENO))?;
}
2019-08-19 20:02:50 +00:00
#[cfg(not(target_os = "l4re"))]
2019-08-19 20:01:02 +00:00
{
if let Some(_g) = self.get_groups() {
//FIXME: Redox kernel does not support setgroups yet
#[cfg(not(target_os = "redox"))]
cvt(libc::setgroups(_g.len().try_into().unwrap(), _g.as_ptr()))?;
}
if let Some(u) = self.get_gid() {
cvt(libc::setgid(u as gid_t))?;
}
if let Some(u) = self.get_uid() {
2019-08-19 19:58:35 +00:00
// When dropping privileges from root, the `setgroups` call
// will remove any extraneous groups. We only drop groups
// if the current uid is 0 and we weren't given an explicit
// set of groups. If we don't call this, then even though our
// uid has dropped, we may still have groups that enable us to
// do super-user things.
2019-04-07 14:39:54 +00:00
//FIXME: Redox kernel does not support setgroups yet
2019-08-19 19:58:35 +00:00
#[cfg(not(target_os = "redox"))]
if libc::getuid() == 0 && self.get_groups().is_none() {
cvt(libc::setgroups(0, ptr::null()))?;
}
cvt(libc::setuid(u as uid_t))?;
}
}
if let Some(ref cwd) = *self.get_cwd() {
cvt(libc::chdir(cwd.as_ptr()))?;
}
2017-10-05 03:01:41 +00:00
// emscripten has no signal support.
2019-08-19 20:02:50 +00:00
#[cfg(not(target_os = "emscripten"))]
{
use crate::mem::MaybeUninit;
// Reset signal handling so the child process starts in a
// standardized state. libstd ignores SIGPIPE, and signal-handling
// libraries often set a mask. Child processes inherit ignored
// signals and the signal mask from their parent, but most
// UNIX programs do not reset these things on their own, so we
// need to clean things up now to avoid confusing the program
// we're about to run.
let mut set = MaybeUninit::<libc::sigset_t>::uninit();
cvt(sigemptyset(set.as_mut_ptr()))?;
2019-12-22 22:42:04 +00:00
cvt(libc::pthread_sigmask(libc::SIG_SETMASK, set.as_ptr(), ptr::null_mut()))?;
let ret = sys::signal(libc::SIGPIPE, libc::SIG_DFL);
if ret == libc::SIG_ERR {
2019-12-22 22:42:04 +00:00
return Err(io::Error::last_os_error());
}
}
for callback in self.get_closures().iter_mut() {
callback()?;
}
// Although we're performing an exec here we may also return with an
// error from this function (without actually exec'ing) in which case we
// want to be sure to restore the global environment back to what it
// once was, ensuring that our temporary override, when free'd, doesn't
// corrupt our process's environment.
let mut _reset = None;
if let Some(envp) = maybe_envp {
struct Reset(*const *const libc::c_char);
impl Drop for Reset {
fn drop(&mut self) {
unsafe {
*sys::os::environ() = self.0;
}
}
}
_reset = Some(Reset(*sys::os::environ()));
*sys::os::environ() = envp.as_ptr();
}
2020-09-21 18:32:06 +00:00
libc::execvp(self.get_program_cstr().as_ptr(), self.get_argv().as_ptr());
Err(io::Error::last_os_error())
}
2018-01-26 02:13:45 +00:00
2019-12-22 22:42:04 +00:00
#[cfg(not(any(
target_os = "macos",
target_os = "freebsd",
all(target_os = "linux", target_env = "gnu"),
all(target_os = "linux", target_env = "musl"),
2019-12-22 22:42:04 +00:00
)))]
fn posix_spawn(
&mut self,
_: &ChildPipes,
_: Option<&CStringArray>,
) -> io::Result<Option<Process>> {
2018-01-26 02:13:45 +00:00
Ok(None)
}
// Only support platforms for which posix_spawn() can return ENOENT
// directly.
2019-12-22 22:42:04 +00:00
#[cfg(any(
target_os = "macos",
target_os = "freebsd",
all(target_os = "linux", target_env = "gnu"),
all(target_os = "linux", target_env = "musl"),
2019-12-22 22:42:04 +00:00
))]
fn posix_spawn(
&mut self,
stdio: &ChildPipes,
envp: Option<&CStringArray>,
) -> io::Result<Option<Process>> {
use crate::mem::MaybeUninit;
use crate::sys::{self, cvt_nz};
2018-01-26 02:13:45 +00:00
2019-12-22 22:42:04 +00:00
if self.get_gid().is_some()
|| self.get_uid().is_some()
Use posix_spawn() on unix if program is a path Previously `Command::spawn` would fall back to the non-posix_spawn based implementation if the `PATH` environment variable was possibly changed. On systems with a modern (g)libc `posix_spawn()` can be significantly faster. If program is a path itself the `PATH` environment variable is not used for the lookup and it should be safe to use the `posix_spawnp()` method. [1] We found this, because we have a cli application that effectively runs a lot of subprocesses. It would sometimes noticeably hang while printing output. Profiling showed that the process was spending the majority of time in the kernel's `copy_page_range` function while spawning subprocesses. During this time the process is completely blocked from running, explaining why users were reporting the cli app hanging. Through this we discovered that `std::process::Command` has a fast and slow path for process execution. The fast path is backed by `posix_spawnp()` and the slow path by fork/exec syscalls being called explicitly. Using fork for process creation is supposed to be fast, but it slows down as your process uses more memory. It's not because the kernel copies the actual memory from the parent, but it does need to copy the references to it (see `copy_page_range` above!). We ended up using the slow path, because the command spawn implementation in falls back to the slow path if it suspects the PATH environment variable was changed. Here is a smallish program demonstrating the slowdown before this code change: ``` use std::process::Command; use std::time::Instant; fn main() { let mut args = std::env::args().skip(1); if let Some(size) = args.next() { // Allocate some memory let _xs: Vec<_> = std::iter::repeat(0) .take(size.parse().expect("valid number")) .collect(); let mut command = Command::new("/bin/sh"); command .arg("-c") .arg("echo hello"); if args.next().is_some() { println!("Overriding PATH"); command.env("PATH", std::env::var("PATH").expect("PATH env var")); } let now = Instant::now(); let child = command .spawn() .expect("failed to execute process"); println!("Spawn took: {:?}", now.elapsed()); let output = child.wait_with_output().expect("failed to wait on process"); println!("Output: {:?}", output); } else { eprintln!("Usage: prog [size]"); std::process::exit(1); } () } ``` Running it and passing different amounts of elements to use to allocate memory shows that the time taken for `spawn()` can differ quite significantly. In latter case the `posix_spawnp()` implementation is 30x faster: ``` $ cargo run --release 10000000 ... Spawn took: 324.275µs hello $ cargo run --release 10000000 changepath ... Overriding PATH Spawn took: 2.346809ms hello $ cargo run --release 100000000 ... Spawn took: 387.842µs hello $ cargo run --release 100000000 changepath ... Overriding PATH Spawn took: 13.434677ms hello ``` [1]: https://github.com/bminor/glibc/blob/5f72f9800b250410cad3abfeeb09469ef12b2438/posix/execvpe.c#L81
2020-10-02 14:44:32 +00:00
|| (self.env_saw_path() && !self.program_is_path())
2019-12-22 22:42:04 +00:00
|| !self.get_closures().is_empty()
|| self.get_groups().is_some()
2019-12-22 22:42:04 +00:00
{
return Ok(None);
2018-01-26 02:13:45 +00:00
}
// Only glibc 2.24+ posix_spawn() supports returning ENOENT directly.
#[cfg(all(target_os = "linux", target_env = "gnu"))]
{
if let Some(version) = sys::os::glibc_version() {
if version < (2, 24) {
2019-12-22 22:42:04 +00:00
return Ok(None);
}
} else {
2019-12-22 22:42:04 +00:00
return Ok(None);
}
}
// Solaris, glibc 2.29+, and musl 1.24+ can set a new working directory,
// and maybe others will gain this non-POSIX function too. We'll check
// for this weak symbol as soon as it's needed, so we can return early
// otherwise to do a manual chdir before exec.
weak! {
fn posix_spawn_file_actions_addchdir_np(
*mut libc::posix_spawn_file_actions_t,
*const libc::c_char
) -> libc::c_int
}
let addchdir = match self.get_cwd() {
Some(cwd) => {
if cfg!(target_os = "macos") {
// There is a bug in macOS where a relative executable
// path like "../myprogram" will cause `posix_spawn` to
// successfully launch the program, but erroneously return
// ENOENT when used with posix_spawn_file_actions_addchdir_np
// which was introduced in macOS 10.15.
return Ok(None);
}
match posix_spawn_file_actions_addchdir_np.get() {
Some(f) => Some((f, cwd)),
None => return Ok(None),
}
}
None => None,
};
2018-01-26 02:13:45 +00:00
let mut p = Process { pid: 0, status: None };
struct PosixSpawnFileActions<'a>(&'a mut MaybeUninit<libc::posix_spawn_file_actions_t>);
2018-01-26 02:13:45 +00:00
impl Drop for PosixSpawnFileActions<'_> {
2018-01-26 02:13:45 +00:00
fn drop(&mut self) {
unsafe {
libc::posix_spawn_file_actions_destroy(self.0.as_mut_ptr());
2018-01-26 02:13:45 +00:00
}
}
}
struct PosixSpawnattr<'a>(&'a mut MaybeUninit<libc::posix_spawnattr_t>);
2018-01-26 02:13:45 +00:00
impl Drop for PosixSpawnattr<'_> {
2018-01-26 02:13:45 +00:00
fn drop(&mut self) {
unsafe {
libc::posix_spawnattr_destroy(self.0.as_mut_ptr());
2018-01-26 02:13:45 +00:00
}
}
}
unsafe {
let mut attrs = MaybeUninit::uninit();
cvt_nz(libc::posix_spawnattr_init(attrs.as_mut_ptr()))?;
let attrs = PosixSpawnattr(&mut attrs);
2018-01-26 02:13:45 +00:00
let mut file_actions = MaybeUninit::uninit();
cvt_nz(libc::posix_spawn_file_actions_init(file_actions.as_mut_ptr()))?;
let file_actions = PosixSpawnFileActions(&mut file_actions);
2018-01-26 02:13:45 +00:00
if let Some(fd) = stdio.stdin.fd() {
cvt_nz(libc::posix_spawn_file_actions_adddup2(
2019-12-22 22:42:04 +00:00
file_actions.0.as_mut_ptr(),
fd,
libc::STDIN_FILENO,
))?;
2018-01-26 02:13:45 +00:00
}
if let Some(fd) = stdio.stdout.fd() {
cvt_nz(libc::posix_spawn_file_actions_adddup2(
2019-12-22 22:42:04 +00:00
file_actions.0.as_mut_ptr(),
fd,
libc::STDOUT_FILENO,
))?;
2018-01-26 02:13:45 +00:00
}
if let Some(fd) = stdio.stderr.fd() {
cvt_nz(libc::posix_spawn_file_actions_adddup2(
2019-12-22 22:42:04 +00:00
file_actions.0.as_mut_ptr(),
fd,
libc::STDERR_FILENO,
))?;
2018-01-26 02:13:45 +00:00
}
if let Some((f, cwd)) = addchdir {
cvt_nz(f(file_actions.0.as_mut_ptr(), cwd.as_ptr()))?;
}
2018-01-26 02:13:45 +00:00
let mut set = MaybeUninit::<libc::sigset_t>::uninit();
cvt(sigemptyset(set.as_mut_ptr()))?;
cvt_nz(libc::posix_spawnattr_setsigmask(attrs.0.as_mut_ptr(), set.as_ptr()))?;
cvt(sigaddset(set.as_mut_ptr(), libc::SIGPIPE))?;
cvt_nz(libc::posix_spawnattr_setsigdefault(attrs.0.as_mut_ptr(), set.as_ptr()))?;
2018-01-26 02:13:45 +00:00
2019-12-22 22:42:04 +00:00
let flags = libc::POSIX_SPAWN_SETSIGDEF | libc::POSIX_SPAWN_SETSIGMASK;
cvt_nz(libc::posix_spawnattr_setflags(attrs.0.as_mut_ptr(), flags as _))?;
2018-01-26 02:13:45 +00:00
// Make sure we synchronize access to the global `environ` resource
2021-02-06 21:38:16 +00:00
let _env_lock = sys::os::env_rwlock(true);
2019-12-22 22:42:04 +00:00
let envp = envp.map(|c| c.as_ptr()).unwrap_or_else(|| *sys::os::environ() as *const _);
cvt_nz(libc::posix_spawnp(
2018-01-26 02:13:45 +00:00
&mut p.pid,
2020-09-21 18:32:06 +00:00
self.get_program_cstr().as_ptr(),
file_actions.0.as_ptr(),
attrs.0.as_ptr(),
2018-01-26 02:13:45 +00:00
self.get_argv().as_ptr() as *const _,
envp as *const _,
))?;
Ok(Some(p))
2018-01-26 02:13:45 +00:00
}
}
}
////////////////////////////////////////////////////////////////////////////////
// Processes
////////////////////////////////////////////////////////////////////////////////
2019-02-09 22:16:58 +00:00
/// The unique ID of the process (this should never be negative).
pub struct Process {
pid: pid_t,
status: Option<ExitStatus>,
}
impl Process {
pub fn id(&self) -> u32 {
self.pid as u32
}
pub fn kill(&mut self) -> io::Result<()> {
// If we've already waited on this process then the pid can be recycled
// and used for another process, and we probably shouldn't be killing
// random processes, so just return an error.
if self.status.is_some() {
2019-12-22 22:42:04 +00:00
Err(Error::new(
ErrorKind::InvalidInput,
"invalid argument: can't kill an exited process",
))
} else {
cvt(unsafe { libc::kill(self.pid, libc::SIGKILL) }).map(drop)
}
}
pub fn wait(&mut self) -> io::Result<ExitStatus> {
2019-02-10 19:23:21 +00:00
use crate::sys::cvt_r;
if let Some(status) = self.status {
2019-12-22 22:42:04 +00:00
return Ok(status);
}
let mut status = 0 as c_int;
cvt_r(|| unsafe { libc::waitpid(self.pid, &mut status, 0) })?;
self.status = Some(ExitStatus::new(status));
Ok(ExitStatus::new(status))
}
pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
if let Some(status) = self.status {
2019-12-22 22:42:04 +00:00
return Ok(Some(status));
}
let mut status = 0 as c_int;
2019-12-22 22:42:04 +00:00
let pid = cvt(unsafe { libc::waitpid(self.pid, &mut status, libc::WNOHANG) })?;
if pid == 0 {
Ok(None)
} else {
self.status = Some(ExitStatus::new(status));
Ok(Some(ExitStatus::new(status)))
}
}
}
/// Unix exit statuses
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
pub struct ExitStatus(c_int);
impl ExitStatus {
pub fn new(status: c_int) -> ExitStatus {
ExitStatus(status)
}
fn exited(&self) -> bool {
libc::WIFEXITED(self.0)
}
pub fn success(&self) -> bool {
self.code() == Some(0)
}
pub fn code(&self) -> Option<i32> {
if self.exited() { Some(libc::WEXITSTATUS(self.0)) } else { None }
}
pub fn signal(&self) -> Option<i32> {
if libc::WIFSIGNALED(self.0) { Some(libc::WTERMSIG(self.0)) } else { None }
}
pub fn core_dumped(&self) -> bool {
libc::WIFSIGNALED(self.0) && libc::WCOREDUMP(self.0)
}
pub fn stopped_signal(&self) -> Option<i32> {
if libc::WIFSTOPPED(self.0) { Some(libc::WSTOPSIG(self.0)) } else { None }
}
pub fn continued(&self) -> bool {
libc::WIFCONTINUED(self.0)
}
pub fn into_raw(&self) -> c_int {
self.0
}
}
/// Converts a raw `c_int` to a type-safe `ExitStatus` by wrapping it without copying.
impl From<c_int> for ExitStatus {
fn from(a: c_int) -> ExitStatus {
ExitStatus(a)
}
}
impl fmt::Display for ExitStatus {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(code) = self.code() {
write!(f, "exit code: {}", code)
} else {
let signal = self.signal().unwrap();
write!(f, "signal: {}", signal)
}
}
}