1 #[cfg(all(test, not(target_os = "emscripten")))]
4 use crate::os
::unix
::prelude
::*;
6 use crate::collections
::BTreeMap
;
7 use crate::ffi
::{CStr, CString, OsStr, OsString}
;
10 use crate::path
::Path
;
12 use crate::sys
::fd
::FileDesc
;
13 use crate::sys
::fs
::File
;
14 use crate::sys
::pipe
::{self, AnonPipe}
;
15 use crate::sys_common
::process
::{CommandEnv, CommandEnvs}
;
17 #[cfg(not(target_os = "fuchsia"))]
18 use crate::sys
::fs
::OpenOptions
;
20 use libc
::{c_char, c_int, gid_t, uid_t, EXIT_FAILURE, EXIT_SUCCESS}
;
23 if #[cfg(target_os = "fuchsia")] {
24 // fuchsia doesn't have /dev/null
25 } else if #[cfg(target_os = "redox")] {
26 const DEV_NULL
: &str = "null:\0";
28 const DEV_NULL
: &str = "/dev/null\0";
32 // Android with api less than 21 define sig* functions inline, so it is not
33 // available for dynamic link. Implementing sigemptyset and sigaddset allow us
34 // to support older Android version (independent of libc version).
35 // The following implementations are based on https://git.io/vSkNf
37 if #[cfg(target_os = "android")] {
38 pub unsafe fn sigemptyset(set
: *mut libc
::sigset_t
) -> libc
::c_int
{
39 set
.write_bytes(0u8, 1);
43 pub unsafe fn sigaddset(set
: *mut libc
::sigset_t
, signum
: libc
::c_int
) -> libc
::c_int
{
44 use crate::{slice, mem}
;
46 let raw
= slice
::from_raw_parts_mut(set
as *mut u8, mem
::size_of
::<libc
::sigset_t
>());
47 let bit
= (signum
- 1) as usize;
48 raw
[bit
/ 8] |= 1 << (bit
% 8);
52 pub use libc
::{sigemptyset, sigaddset}
;
56 ////////////////////////////////////////////////////////////////////////////////
58 ////////////////////////////////////////////////////////////////////////////////
61 // Currently we try hard to ensure that the call to `.exec()` doesn't
62 // actually allocate any memory. While many platforms try to ensure that
63 // memory allocation works after a fork in a multithreaded process, it's
64 // been observed to be buggy and somewhat unreliable, so we do our best to
65 // just not do it at all!
67 // Along those lines, the `argv` and `envp` raw pointers here are exactly
68 // what's gonna get passed to `execvp`. The `argv` array starts with the
69 // `program` and ends with a NULL, and the `envp` pointer, if present, is
70 // also null-terminated.
72 // Right now we don't support removing arguments, so there's no much fancy
73 // support there, but we support adding and removing environment variables,
74 // so a side table is used to track where in the `envp` array each key is
75 // located. Whenever we add a key we update it in place if it's already
76 // present, and whenever we remove a key we update the locations of all
87 closures
: Vec
<Box
<dyn FnMut() -> io
::Result
<()> + Send
+ Sync
>>,
89 stdout
: Option
<Stdio
>,
90 stderr
: Option
<Stdio
>,
93 // Create a new type for argv, so that we can make it `Send` and `Sync`
94 struct Argv(Vec
<*const c_char
>);
96 // It is safe to make `Argv` `Send` and `Sync`, because it contains
97 // pointers to memory owned by `Command.args`
98 unsafe impl Send
for Argv {}
99 unsafe impl Sync
for Argv {}
101 // passed back to std::process with the pipes connected to the child, if any
103 pub struct StdioPipes
{
104 pub stdin
: Option
<AnonPipe
>,
105 pub stdout
: Option
<AnonPipe
>,
106 pub stderr
: Option
<AnonPipe
>,
109 // passed to do_exec() with configuration of what the child stdio should look
111 pub struct ChildPipes
{
112 pub stdin
: ChildStdio
,
113 pub stdout
: ChildStdio
,
114 pub stderr
: ChildStdio
,
117 pub enum ChildStdio
{
122 // On Fuchsia, null stdio is the default, so we simply don't specify
123 // any actions at the time of spawning.
124 #[cfg(target_os = "fuchsia")]
136 pub fn new(program
: &OsStr
) -> Command
{
137 let mut saw_nul
= false;
138 let program
= os2c(program
, &mut saw_nul
);
140 argv
: Argv(vec
![program
.as_ptr(), ptr
::null()]),
141 args
: vec
![program
.clone()],
143 env
: Default
::default(),
148 closures
: Vec
::new(),
155 pub fn set_arg_0(&mut self, arg
: &OsStr
) {
157 let arg
= os2c(arg
, &mut self.saw_nul
);
158 debug_assert
!(self.argv
.0.len() > 1);
159 self.argv
.0[0] = arg
.as_ptr();
163 pub fn arg(&mut self, arg
: &OsStr
) {
164 // Overwrite the trailing NULL pointer in `argv` and then add a new null
166 let arg
= os2c(arg
, &mut self.saw_nul
);
167 self.argv
.0[self.args
.len()] = arg
.as_ptr();
168 self.argv
.0.push(ptr
::null());
170 // Also make sure we keep track of the owned value to schedule a
171 // destructor for this memory.
175 pub fn cwd(&mut self, dir
: &OsStr
) {
176 self.cwd
= Some(os2c(dir
, &mut self.saw_nul
));
178 pub fn uid(&mut self, id
: uid_t
) {
181 pub fn gid(&mut self, id
: gid_t
) {
185 pub fn saw_nul(&self) -> bool
{
189 pub fn get_program(&self) -> &OsStr
{
190 OsStr
::from_bytes(self.program
.as_bytes())
193 pub fn get_args(&self) -> CommandArgs
<'_
> {
194 let mut iter
= self.args
.iter();
199 pub fn get_envs(&self) -> CommandEnvs
<'_
> {
203 pub fn get_current_dir(&self) -> Option
<&Path
> {
204 self.cwd
.as_ref().map(|cs
| Path
::new(OsStr
::from_bytes(cs
.as_bytes())))
207 pub fn get_argv(&self) -> &Vec
<*const c_char
> {
211 pub fn get_program_cstr(&self) -> &CStr
{
216 pub fn get_cwd(&self) -> &Option
<CString
> {
220 pub fn get_uid(&self) -> Option
<uid_t
> {
224 pub fn get_gid(&self) -> Option
<gid_t
> {
228 pub fn get_closures(&mut self) -> &mut Vec
<Box
<dyn FnMut() -> io
::Result
<()> + Send
+ Sync
>> {
232 pub unsafe fn pre_exec(&mut self, f
: Box
<dyn FnMut() -> io
::Result
<()> + Send
+ Sync
>) {
233 self.closures
.push(f
);
236 pub fn stdin(&mut self, stdin
: Stdio
) {
237 self.stdin
= Some(stdin
);
240 pub fn stdout(&mut self, stdout
: Stdio
) {
241 self.stdout
= Some(stdout
);
244 pub fn stderr(&mut self, stderr
: Stdio
) {
245 self.stderr
= Some(stderr
);
248 pub fn env_mut(&mut self) -> &mut CommandEnv
{
252 pub fn capture_env(&mut self) -> Option
<CStringArray
> {
253 let maybe_env
= self.env
.capture_if_changed();
254 maybe_env
.map(|env
| construct_envp(env
, &mut self.saw_nul
))
257 pub fn env_saw_path(&self) -> bool
{
258 self.env
.have_changed_path()
265 ) -> io
::Result
<(StdioPipes
, ChildPipes
)> {
266 let null
= Stdio
::Null
;
267 let default_stdin
= if needs_stdin { &default }
else { &null }
;
268 let stdin
= self.stdin
.as_ref().unwrap_or(default_stdin
);
269 let stdout
= self.stdout
.as_ref().unwrap_or(&default);
270 let stderr
= self.stderr
.as_ref().unwrap_or(&default);
271 let (their_stdin
, our_stdin
) = stdin
.to_child_stdio(true)?
;
272 let (their_stdout
, our_stdout
) = stdout
.to_child_stdio(false)?
;
273 let (their_stderr
, our_stderr
) = stderr
.to_child_stdio(false)?
;
274 let ours
= StdioPipes { stdin: our_stdin, stdout: our_stdout, stderr: our_stderr }
;
275 let theirs
= ChildPipes { stdin: their_stdin, stdout: their_stdout, stderr: their_stderr }
;
280 fn os2c(s
: &OsStr
, saw_nul
: &mut bool
) -> CString
{
281 CString
::new(s
.as_bytes()).unwrap_or_else(|_e
| {
283 CString
::new("<string-with-nul>").unwrap()
287 // Helper type to manage ownership of the strings within a C-style array.
288 pub struct CStringArray
{
290 ptrs
: Vec
<*const c_char
>,
294 pub fn with_capacity(capacity
: usize) -> Self {
295 let mut result
= CStringArray
{
296 items
: Vec
::with_capacity(capacity
),
297 ptrs
: Vec
::with_capacity(capacity
+ 1),
299 result
.ptrs
.push(ptr
::null());
302 pub fn push(&mut self, item
: CString
) {
303 let l
= self.ptrs
.len();
304 self.ptrs
[l
- 1] = item
.as_ptr();
305 self.ptrs
.push(ptr
::null());
306 self.items
.push(item
);
308 pub fn as_ptr(&self) -> *const *const c_char
{
313 fn construct_envp(env
: BTreeMap
<OsString
, OsString
>, saw_nul
: &mut bool
) -> CStringArray
{
314 let mut result
= CStringArray
::with_capacity(env
.len());
315 for (mut k
, v
) in env
{
316 // Reserve additional space for '=' and null terminator
317 k
.reserve_exact(v
.len() + 2);
321 // Add the new entry into the array
322 if let Ok(item
) = CString
::new(k
.into_vec()) {
333 pub fn to_child_stdio(&self, readable
: bool
) -> io
::Result
<(ChildStdio
, Option
<AnonPipe
>)> {
335 Stdio
::Inherit
=> Ok((ChildStdio
::Inherit
, None
)),
337 // Make sure that the source descriptors are not an stdio
338 // descriptor, otherwise the order which we set the child's
339 // descriptors may blow away a descriptor which we are hoping to
340 // save. For example, suppose we want the child's stderr to be the
341 // parent's stdout, and the child's stdout to be the parent's
342 // stderr. No matter which we dup first, the second will get
343 // overwritten prematurely.
344 Stdio
::Fd(ref fd
) => {
345 if fd
.raw() >= 0 && fd
.raw() <= libc
::STDERR_FILENO
{
346 Ok((ChildStdio
::Owned(fd
.duplicate()?
), None
))
348 Ok((ChildStdio
::Explicit(fd
.raw()), None
))
353 let (reader
, writer
) = pipe
::anon_pipe()?
;
354 let (ours
, theirs
) = if readable { (writer, reader) }
else { (reader, writer) }
;
355 Ok((ChildStdio
::Owned(theirs
.into_fd()), Some(ours
)))
358 #[cfg(not(target_os = "fuchsia"))]
360 let mut opts
= OpenOptions
::new();
362 opts
.write(!readable
);
363 let path
= unsafe { CStr::from_ptr(DEV_NULL.as_ptr() as *const _) }
;
364 let fd
= File
::open_c(&path
, &opts
)?
;
365 Ok((ChildStdio
::Owned(fd
.into_fd()), None
))
368 #[cfg(target_os = "fuchsia")]
369 Stdio
::Null
=> Ok((ChildStdio
::Null
, None
)),
374 impl From
<AnonPipe
> for Stdio
{
375 fn from(pipe
: AnonPipe
) -> Stdio
{
376 Stdio
::Fd(pipe
.into_fd())
380 impl From
<File
> for Stdio
{
381 fn from(file
: File
) -> Stdio
{
382 Stdio
::Fd(file
.into_fd())
387 pub fn fd(&self) -> Option
<c_int
> {
389 ChildStdio
::Inherit
=> None
,
390 ChildStdio
::Explicit(fd
) => Some(fd
),
391 ChildStdio
::Owned(ref fd
) => Some(fd
.raw()),
393 #[cfg(target_os = "fuchsia")]
394 ChildStdio
::Null
=> None
,
399 impl fmt
::Debug
for Command
{
400 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
401 if self.program
!= self.args
[0] {
402 write
!(f
, "[{:?}] ", self.program
)?
;
404 write
!(f
, "{:?}", self.args
[0])?
;
406 for arg
in &self.args
[1..] {
407 write
!(f
, " {:?}", arg
)?
;
413 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
414 pub struct ExitCode(u8);
417 pub const SUCCESS
: ExitCode
= ExitCode(EXIT_SUCCESS
as _
);
418 pub const FAILURE
: ExitCode
= ExitCode(EXIT_FAILURE
as _
);
421 pub fn as_i32(&self) -> i32 {
426 pub struct CommandArgs
<'a
> {
427 iter
: crate::slice
::Iter
<'a
, CString
>,
430 impl<'a
> Iterator
for CommandArgs
<'a
> {
431 type Item
= &'a OsStr
;
432 fn next(&mut self) -> Option
<&'a OsStr
> {
433 self.iter
.next().map(|cs
| OsStr
::from_bytes(cs
.as_bytes()))
435 fn size_hint(&self) -> (usize, Option
<usize>) {
436 self.iter
.size_hint()
440 impl<'a
> ExactSizeIterator
for CommandArgs
<'a
> {
441 fn len(&self) -> usize {
444 fn is_empty(&self) -> bool
{
449 impl<'a
> fmt
::Debug
for CommandArgs
<'a
> {
450 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
451 f
.debug_list().entries(self.iter
.clone()).finish()