1 use crate::os
::unix
::prelude
::*;
3 use crate::collections
::BTreeMap
;
4 use crate::ffi
::{CStr, CString, OsStr, OsString}
;
8 use crate::sys
::fd
::FileDesc
;
9 use crate::sys
::fs
::File
;
10 use crate::sys
::pipe
::{self, AnonPipe}
;
11 use crate::sys_common
::process
::CommandEnv
;
13 #[cfg(not(target_os = "fuchsia"))]
14 use crate::sys
::fs
::OpenOptions
;
16 use libc
::{c_char, c_int, gid_t, uid_t, EXIT_FAILURE, EXIT_SUCCESS}
;
19 if #[cfg(target_os = "fuchsia")] {
20 // fuchsia doesn't have /dev/null
21 } else if #[cfg(target_os = "redox")] {
22 const DEV_NULL
: &str = "null:\0";
24 const DEV_NULL
: &str = "/dev/null\0";
28 // Android with api less than 21 define sig* functions inline, so it is not
29 // available for dynamic link. Implementing sigemptyset and sigaddset allow us
30 // to support older Android version (independent of libc version).
31 // The following implementations are based on https://git.io/vSkNf
33 if #[cfg(target_os = "android")] {
34 pub unsafe fn sigemptyset(set
: *mut libc
::sigset_t
) -> libc
::c_int
{
35 set
.write_bytes(0u8, 1);
39 pub unsafe fn sigaddset(set
: *mut libc
::sigset_t
, signum
: libc
::c_int
) -> libc
::c_int
{
40 use crate::{slice, mem}
;
42 let raw
= slice
::from_raw_parts_mut(set
as *mut u8, mem
::size_of
::<libc
::sigset_t
>());
43 let bit
= (signum
- 1) as usize;
44 raw
[bit
/ 8] |= 1 << (bit
% 8);
48 pub use libc
::{sigemptyset, sigaddset}
;
52 ////////////////////////////////////////////////////////////////////////////////
54 ////////////////////////////////////////////////////////////////////////////////
57 // Currently we try hard to ensure that the call to `.exec()` doesn't
58 // actually allocate any memory. While many platforms try to ensure that
59 // memory allocation works after a fork in a multithreaded process, it's
60 // been observed to be buggy and somewhat unreliable, so we do our best to
61 // just not do it at all!
63 // Along those lines, the `argv` and `envp` raw pointers here are exactly
64 // what's gonna get passed to `execvp`. The `argv` array starts with the
65 // `program` and ends with a NULL, and the `envp` pointer, if present, is
66 // also null-terminated.
68 // Right now we don't support removing arguments, so there's no much fancy
69 // support there, but we support adding and removing environment variables,
70 // so a side table is used to track where in the `envp` array each key is
71 // located. Whenever we add a key we update it in place if it's already
72 // present, and whenever we remove a key we update the locations of all
83 closures
: Vec
<Box
<dyn FnMut() -> io
::Result
<()> + Send
+ Sync
>>,
85 stdout
: Option
<Stdio
>,
86 stderr
: Option
<Stdio
>,
89 // Create a new type for argv, so that we can make it `Send` and `Sync`
90 struct Argv(Vec
<*const c_char
>);
92 // It is safe to make `Argv` `Send` and `Sync`, because it contains
93 // pointers to memory owned by `Command.args`
94 unsafe impl Send
for Argv {}
95 unsafe impl Sync
for Argv {}
97 // passed back to std::process with the pipes connected to the child, if any
99 pub struct StdioPipes
{
100 pub stdin
: Option
<AnonPipe
>,
101 pub stdout
: Option
<AnonPipe
>,
102 pub stderr
: Option
<AnonPipe
>,
105 // passed to do_exec() with configuration of what the child stdio should look
107 pub struct ChildPipes
{
108 pub stdin
: ChildStdio
,
109 pub stdout
: ChildStdio
,
110 pub stderr
: ChildStdio
,
113 pub enum ChildStdio
{
118 // On Fuchsia, null stdio is the default, so we simply don't specify
119 // any actions at the time of spawning.
120 #[cfg(target_os = "fuchsia")]
132 pub fn new(program
: &OsStr
) -> Command
{
133 let mut saw_nul
= false;
134 let program
= os2c(program
, &mut saw_nul
);
136 argv
: Argv(vec
![program
.as_ptr(), ptr
::null()]),
137 args
: vec
![program
.clone()],
139 env
: Default
::default(),
144 closures
: Vec
::new(),
151 pub fn set_arg_0(&mut self, arg
: &OsStr
) {
153 let arg
= os2c(arg
, &mut self.saw_nul
);
154 debug_assert
!(self.argv
.0.len() > 1);
155 self.argv
.0[0] = arg
.as_ptr();
159 pub fn arg(&mut self, arg
: &OsStr
) {
160 // Overwrite the trailing NULL pointer in `argv` and then add a new null
162 let arg
= os2c(arg
, &mut self.saw_nul
);
163 self.argv
.0[self.args
.len()] = arg
.as_ptr();
164 self.argv
.0.push(ptr
::null());
166 // Also make sure we keep track of the owned value to schedule a
167 // destructor for this memory.
171 pub fn cwd(&mut self, dir
: &OsStr
) {
172 self.cwd
= Some(os2c(dir
, &mut self.saw_nul
));
174 pub fn uid(&mut self, id
: uid_t
) {
177 pub fn gid(&mut self, id
: gid_t
) {
181 pub fn saw_nul(&self) -> bool
{
184 pub fn get_argv(&self) -> &Vec
<*const c_char
> {
188 pub fn get_program(&self) -> &CStr
{
193 pub fn get_cwd(&self) -> &Option
<CString
> {
197 pub fn get_uid(&self) -> Option
<uid_t
> {
201 pub fn get_gid(&self) -> Option
<gid_t
> {
205 pub fn get_closures(&mut self) -> &mut Vec
<Box
<dyn FnMut() -> io
::Result
<()> + Send
+ Sync
>> {
209 pub unsafe fn pre_exec(&mut self, f
: Box
<dyn FnMut() -> io
::Result
<()> + Send
+ Sync
>) {
210 self.closures
.push(f
);
213 pub fn stdin(&mut self, stdin
: Stdio
) {
214 self.stdin
= Some(stdin
);
217 pub fn stdout(&mut self, stdout
: Stdio
) {
218 self.stdout
= Some(stdout
);
221 pub fn stderr(&mut self, stderr
: Stdio
) {
222 self.stderr
= Some(stderr
);
225 pub fn env_mut(&mut self) -> &mut CommandEnv
{
229 pub fn capture_env(&mut self) -> Option
<CStringArray
> {
230 let maybe_env
= self.env
.capture_if_changed();
231 maybe_env
.map(|env
| construct_envp(env
, &mut self.saw_nul
))
234 pub fn env_saw_path(&self) -> bool
{
235 self.env
.have_changed_path()
242 ) -> io
::Result
<(StdioPipes
, ChildPipes
)> {
243 let null
= Stdio
::Null
;
244 let default_stdin
= if needs_stdin { &default }
else { &null }
;
245 let stdin
= self.stdin
.as_ref().unwrap_or(default_stdin
);
246 let stdout
= self.stdout
.as_ref().unwrap_or(&default);
247 let stderr
= self.stderr
.as_ref().unwrap_or(&default);
248 let (their_stdin
, our_stdin
) = stdin
.to_child_stdio(true)?
;
249 let (their_stdout
, our_stdout
) = stdout
.to_child_stdio(false)?
;
250 let (their_stderr
, our_stderr
) = stderr
.to_child_stdio(false)?
;
251 let ours
= StdioPipes { stdin: our_stdin, stdout: our_stdout, stderr: our_stderr }
;
252 let theirs
= ChildPipes { stdin: their_stdin, stdout: their_stdout, stderr: their_stderr }
;
257 fn os2c(s
: &OsStr
, saw_nul
: &mut bool
) -> CString
{
258 CString
::new(s
.as_bytes()).unwrap_or_else(|_e
| {
260 CString
::new("<string-with-nul>").unwrap()
264 // Helper type to manage ownership of the strings within a C-style array.
265 pub struct CStringArray
{
267 ptrs
: Vec
<*const c_char
>,
271 pub fn with_capacity(capacity
: usize) -> Self {
272 let mut result
= CStringArray
{
273 items
: Vec
::with_capacity(capacity
),
274 ptrs
: Vec
::with_capacity(capacity
+ 1),
276 result
.ptrs
.push(ptr
::null());
279 pub fn push(&mut self, item
: CString
) {
280 let l
= self.ptrs
.len();
281 self.ptrs
[l
- 1] = item
.as_ptr();
282 self.ptrs
.push(ptr
::null());
283 self.items
.push(item
);
285 pub fn as_ptr(&self) -> *const *const c_char
{
290 fn construct_envp(env
: BTreeMap
<OsString
, OsString
>, saw_nul
: &mut bool
) -> CStringArray
{
291 let mut result
= CStringArray
::with_capacity(env
.len());
292 for (mut k
, v
) in env
{
293 // Reserve additional space for '=' and null terminator
294 k
.reserve_exact(v
.len() + 2);
298 // Add the new entry into the array
299 if let Ok(item
) = CString
::new(k
.into_vec()) {
310 pub fn to_child_stdio(&self, readable
: bool
) -> io
::Result
<(ChildStdio
, Option
<AnonPipe
>)> {
312 Stdio
::Inherit
=> Ok((ChildStdio
::Inherit
, None
)),
314 // Make sure that the source descriptors are not an stdio
315 // descriptor, otherwise the order which we set the child's
316 // descriptors may blow away a descriptor which we are hoping to
317 // save. For example, suppose we want the child's stderr to be the
318 // parent's stdout, and the child's stdout to be the parent's
319 // stderr. No matter which we dup first, the second will get
320 // overwritten prematurely.
321 Stdio
::Fd(ref fd
) => {
322 if fd
.raw() >= 0 && fd
.raw() <= libc
::STDERR_FILENO
{
323 Ok((ChildStdio
::Owned(fd
.duplicate()?
), None
))
325 Ok((ChildStdio
::Explicit(fd
.raw()), None
))
330 let (reader
, writer
) = pipe
::anon_pipe()?
;
331 let (ours
, theirs
) = if readable { (writer, reader) }
else { (reader, writer) }
;
332 Ok((ChildStdio
::Owned(theirs
.into_fd()), Some(ours
)))
335 #[cfg(not(target_os = "fuchsia"))]
337 let mut opts
= OpenOptions
::new();
339 opts
.write(!readable
);
340 let path
= unsafe { CStr::from_ptr(DEV_NULL.as_ptr() as *const _) }
;
341 let fd
= File
::open_c(&path
, &opts
)?
;
342 Ok((ChildStdio
::Owned(fd
.into_fd()), None
))
345 #[cfg(target_os = "fuchsia")]
346 Stdio
::Null
=> Ok((ChildStdio
::Null
, None
)),
351 impl From
<AnonPipe
> for Stdio
{
352 fn from(pipe
: AnonPipe
) -> Stdio
{
353 Stdio
::Fd(pipe
.into_fd())
357 impl From
<File
> for Stdio
{
358 fn from(file
: File
) -> Stdio
{
359 Stdio
::Fd(file
.into_fd())
364 pub fn fd(&self) -> Option
<c_int
> {
366 ChildStdio
::Inherit
=> None
,
367 ChildStdio
::Explicit(fd
) => Some(fd
),
368 ChildStdio
::Owned(ref fd
) => Some(fd
.raw()),
370 #[cfg(target_os = "fuchsia")]
371 ChildStdio
::Null
=> None
,
376 impl fmt
::Debug
for Command
{
377 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
378 if self.program
!= self.args
[0] {
379 write
!(f
, "[{:?}] ", self.program
)?
;
381 write
!(f
, "{:?}", self.args
[0])?
;
383 for arg
in &self.args
[1..] {
384 write
!(f
, " {:?}", arg
)?
;
390 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
391 pub struct ExitCode(u8);
394 pub const SUCCESS
: ExitCode
= ExitCode(EXIT_SUCCESS
as _
);
395 pub const FAILURE
: ExitCode
= ExitCode(EXIT_FAILURE
as _
);
398 pub fn as_i32(&self) -> i32 {
403 #[cfg(all(test, not(target_os = "emscripten")))]
407 use crate::ffi
::OsStr
;
416 Err(e
) => panic
!("received error for `{}`: {}", stringify
!($e
), e
),
421 // See #14232 for more information, but it appears that signal delivery to a
422 // newly spawned process may just be raced in the macOS, so to prevent this
423 // test from being flaky we ignore it on macOS.
425 #[cfg_attr(target_os = "macos", ignore)]
426 // When run under our current QEMU emulation test suite this test fails,
427 // although the reason isn't very clear as to why. For now this test is
429 #[cfg_attr(target_arch = "arm", ignore)]
430 #[cfg_attr(target_arch = "aarch64", ignore)]
431 #[cfg_attr(target_arch = "riscv64", ignore)]
432 fn test_process_mask() {
434 // Test to make sure that a signal mask does not get inherited.
435 let mut cmd
= Command
::new(OsStr
::new("cat"));
437 let mut set
= mem
::MaybeUninit
::<libc
::sigset_t
>::uninit();
438 let mut old_set
= mem
::MaybeUninit
::<libc
::sigset_t
>::uninit();
439 t
!(cvt(sigemptyset(set
.as_mut_ptr())));
440 t
!(cvt(sigaddset(set
.as_mut_ptr(), libc
::SIGINT
)));
441 t
!(cvt(libc
::pthread_sigmask(libc
::SIG_SETMASK
, set
.as_ptr(), old_set
.as_mut_ptr())));
443 cmd
.stdin(Stdio
::MakePipe
);
444 cmd
.stdout(Stdio
::MakePipe
);
446 let (mut cat
, mut pipes
) = t
!(cmd
.spawn(Stdio
::Null
, true));
447 let stdin_write
= pipes
.stdin
.take().unwrap();
448 let stdout_read
= pipes
.stdout
.take().unwrap();
450 t
!(cvt(libc
::pthread_sigmask(libc
::SIG_SETMASK
, old_set
.as_ptr(), ptr
::null_mut())));
452 t
!(cvt(libc
::kill(cat
.id() as libc
::pid_t
, libc
::SIGINT
)));
453 // We need to wait until SIGINT is definitely delivered. The
454 // easiest way is to write something to cat, and try to read it
455 // back: if SIGINT is unmasked, it'll get delivered when cat is
457 let _
= stdin_write
.write(b
"Hello");
460 // Either EOF or failure (EPIPE) is okay.
461 let mut buf
= [0; 5];
462 if let Ok(ret
) = stdout_read
.read(&mut buf
) {