1 #![unstable(feature = "process_internals", issue = "none")]
6 use crate::borrow::Borrow;
7 use crate::collections::BTreeMap;
9 use crate::env::split_paths;
10 use crate::ffi::{OsStr, OsString};
13 use crate::io::{self, Error, ErrorKind};
15 use crate::os::windows::ffi::OsStrExt;
16 use crate::path::Path;
20 use crate::sys::fs::{File, OpenOptions};
21 use crate::sys::handle::Handle;
22 use crate::sys::pipe::{self, AnonPipe};
23 use crate::sys::stdio;
24 use crate::sys_common::mutex::StaticMutex;
25 use crate::sys_common::process::{CommandEnv, CommandEnvs};
26 use crate::sys_common::AsInner;
28 use libc::{c_void, EXIT_FAILURE, EXIT_SUCCESS};
30 ////////////////////////////////////////////////////////////////////////////////
32 ////////////////////////////////////////////////////////////////////////////////
34 #[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
36 pub struct EnvKey(OsString);
38 impl From<OsString> for EnvKey {
39 fn from(mut k: OsString) -> Self {
40 k.make_ascii_uppercase();
45 impl From<EnvKey> for OsString {
46 fn from(k: EnvKey) -> Self {
51 impl Borrow<OsStr> for EnvKey {
52 fn borrow(&self) -> &OsStr {
57 impl AsRef<OsStr> for EnvKey {
58 fn as_ref(&self) -> &OsStr {
63 fn ensure_no_nuls<T: AsRef<OsStr>>(str: T) -> io::Result<T> {
64 if str.as_ref().encode_wide().any(|b| b == 0) {
65 Err(io::Error::new_const(ErrorKind::InvalidInput, &"nul byte found in provided data"))
75 cwd: Option<OsString>,
77 detach: bool, // not currently exposed in std::process
79 stdout: Option<Stdio>,
80 stderr: Option<Stdio>,
81 force_quotes_enabled: bool,
91 pub struct StdioPipes {
92 pub stdin: Option<AnonPipe>,
93 pub stdout: Option<AnonPipe>,
94 pub stderr: Option<AnonPipe>,
98 pub fn new(program: &OsStr) -> Command {
100 program: program.to_os_string(),
102 env: Default::default(),
109 force_quotes_enabled: false,
113 pub fn arg(&mut self, arg: &OsStr) {
114 self.args.push(arg.to_os_string())
116 pub fn env_mut(&mut self) -> &mut CommandEnv {
119 pub fn cwd(&mut self, dir: &OsStr) {
120 self.cwd = Some(dir.to_os_string())
122 pub fn stdin(&mut self, stdin: Stdio) {
123 self.stdin = Some(stdin);
125 pub fn stdout(&mut self, stdout: Stdio) {
126 self.stdout = Some(stdout);
128 pub fn stderr(&mut self, stderr: Stdio) {
129 self.stderr = Some(stderr);
131 pub fn creation_flags(&mut self, flags: u32) {
135 pub fn force_quotes(&mut self, enabled: bool) {
136 self.force_quotes_enabled = enabled;
139 pub fn get_program(&self) -> &OsStr {
143 pub fn get_args(&self) -> CommandArgs<'_> {
144 let iter = self.args.iter();
148 pub fn get_envs(&self) -> CommandEnvs<'_> {
152 pub fn get_current_dir(&self) -> Option<&Path> {
153 self.cwd.as_ref().map(|cwd| Path::new(cwd))
160 ) -> io::Result<(Process, StdioPipes)> {
161 let maybe_env = self.env.capture_if_changed();
162 // To have the spawning semantics of unix/windows stay the same, we need
163 // to read the *child's* PATH if one is provided. See #15149 for more
165 let program = maybe_env.as_ref().and_then(|env| {
166 if let Some(v) = env.get(OsStr::new("PATH")) {
167 // Split the value and test each path to see if the
169 for path in split_paths(&v) {
171 .join(self.program.to_str().unwrap())
172 .with_extension(env::consts::EXE_EXTENSION);
173 if fs::metadata(&path).is_ok() {
174 return Some(path.into_os_string());
181 let mut si = zeroed_startupinfo();
182 si.cb = mem::size_of::<c::STARTUPINFO>() as c::DWORD;
183 si.dwFlags = c::STARTF_USESTDHANDLES;
185 let program = program.as_ref().unwrap_or(&self.program);
186 let mut cmd_str = make_command_line(program, &self.args, self.force_quotes_enabled)?;
187 cmd_str.push(0); // add null terminator
189 // stolen from the libuv code.
190 let mut flags = self.flags | c::CREATE_UNICODE_ENVIRONMENT;
192 flags |= c::DETACHED_PROCESS | c::CREATE_NEW_PROCESS_GROUP;
195 let (envp, _data) = make_envp(maybe_env)?;
196 let (dirp, _data) = make_dirp(self.cwd.as_ref())?;
197 let mut pi = zeroed_process_information();
199 // Prepare all stdio handles to be inherited by the child. This
200 // currently involves duplicating any existing ones with the ability to
201 // be inherited by child processes. Note, however, that once an
202 // inheritable handle is created, *any* spawned child will inherit that
203 // handle. We only want our own child to inherit this handle, so we wrap
204 // the remaining portion of this spawn in a mutex.
206 // For more information, msdn also has an article about this race:
207 // http://support.microsoft.com/kb/315939
208 static CREATE_PROCESS_LOCK: StaticMutex = StaticMutex::new();
210 let _guard = unsafe { CREATE_PROCESS_LOCK.lock() };
212 let mut pipes = StdioPipes { stdin: None, stdout: None, stderr: None };
213 let null = Stdio::Null;
214 let default_stdin = if needs_stdin { &default } else { &null };
215 let stdin = self.stdin.as_ref().unwrap_or(default_stdin);
216 let stdout = self.stdout.as_ref().unwrap_or(&default);
217 let stderr = self.stderr.as_ref().unwrap_or(&default);
218 let stdin = stdin.to_handle(c::STD_INPUT_HANDLE, &mut pipes.stdin)?;
219 let stdout = stdout.to_handle(c::STD_OUTPUT_HANDLE, &mut pipes.stdout)?;
220 let stderr = stderr.to_handle(c::STD_ERROR_HANDLE, &mut pipes.stderr)?;
221 si.hStdInput = stdin.raw();
222 si.hStdOutput = stdout.raw();
223 si.hStdError = stderr.raw();
226 cvt(c::CreateProcessW(
228 cmd_str.as_mut_ptr(),
240 // We close the thread handle because we don't care about keeping
241 // the thread id valid, and we aren't keeping the thread handle
242 // around to be able to close it later.
243 drop(Handle::new(pi.hThread));
245 Ok((Process { handle: Handle::new(pi.hProcess) }, pipes))
249 impl fmt::Debug for Command {
250 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
251 write!(f, "{:?}", self.program)?;
252 for arg in &self.args {
253 write!(f, " {:?}", arg)?;
260 fn to_handle(&self, stdio_id: c::DWORD, pipe: &mut Option<AnonPipe>) -> io::Result<Handle> {
262 // If no stdio handle is available, then inherit means that it
263 // should still be unavailable so propagate the
264 // INVALID_HANDLE_VALUE.
265 Stdio::Inherit => match stdio::get_handle(stdio_id) {
267 let io = Handle::new(io);
268 let ret = io.duplicate(0, true, c::DUPLICATE_SAME_ACCESS);
272 Err(..) => Ok(Handle::new(c::INVALID_HANDLE_VALUE)),
276 let ours_readable = stdio_id != c::STD_INPUT_HANDLE;
277 let pipes = pipe::anon_pipe(ours_readable, true)?;
278 *pipe = Some(pipes.ours);
279 Ok(pipes.theirs.into_handle())
282 Stdio::Handle(ref handle) => handle.duplicate(0, true, c::DUPLICATE_SAME_ACCESS),
284 // Open up a reference to NUL with appropriate read/write
285 // permissions as well as the ability to be inherited to child
286 // processes (as this is about to be inherited).
288 let size = mem::size_of::<c::SECURITY_ATTRIBUTES>();
289 let mut sa = c::SECURITY_ATTRIBUTES {
290 nLength: size as c::DWORD,
291 lpSecurityDescriptor: ptr::null_mut(),
294 let mut opts = OpenOptions::new();
295 opts.read(stdio_id == c::STD_INPUT_HANDLE);
296 opts.write(stdio_id != c::STD_INPUT_HANDLE);
297 opts.security_attributes(&mut sa);
298 File::open(Path::new("NUL"), &opts).map(|file| file.into_handle())
304 impl From<AnonPipe> for Stdio {
305 fn from(pipe: AnonPipe) -> Stdio {
306 Stdio::Handle(pipe.into_handle())
310 impl From<File> for Stdio {
311 fn from(file: File) -> Stdio {
312 Stdio::Handle(file.into_handle())
316 ////////////////////////////////////////////////////////////////////////////////
318 ////////////////////////////////////////////////////////////////////////////////
320 /// A value representing a child process.
322 /// The lifetime of this value is linked to the lifetime of the actual
323 /// process - the Process destructor calls self.finish() which waits
324 /// for the process to terminate.
330 pub fn kill(&mut self) -> io::Result<()> {
331 cvt(unsafe { c::TerminateProcess(self.handle.raw(), 1) })?;
335 pub fn id(&self) -> u32 {
336 unsafe { c::GetProcessId(self.handle.raw()) as u32 }
339 pub fn wait(&mut self) -> io::Result<ExitStatus> {
341 let res = c::WaitForSingleObject(self.handle.raw(), c::INFINITE);
342 if res != c::WAIT_OBJECT_0 {
343 return Err(Error::last_os_error());
346 cvt(c::GetExitCodeProcess(self.handle.raw(), &mut status))?;
347 Ok(ExitStatus(status))
351 pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
353 match c::WaitForSingleObject(self.handle.raw(), 0) {
354 c::WAIT_OBJECT_0 => {}
358 _ => return Err(io::Error::last_os_error()),
361 cvt(c::GetExitCodeProcess(self.handle.raw(), &mut status))?;
362 Ok(Some(ExitStatus(status)))
366 pub fn handle(&self) -> &Handle {
370 pub fn into_handle(self) -> Handle {
375 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
376 pub struct ExitStatus(c::DWORD);
379 pub fn success(&self) -> bool {
382 pub fn code(&self) -> Option<i32> {
387 /// Converts a raw `c::DWORD` to a type-safe `ExitStatus` by wrapping it without copying.
388 impl From<c::DWORD> for ExitStatus {
389 fn from(u: c::DWORD) -> ExitStatus {
394 impl fmt::Display for ExitStatus {
395 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
396 // Windows exit codes with the high bit set typically mean some form of
397 // unhandled exception or warning. In this scenario printing the exit
398 // code in decimal doesn't always make sense because it's a very large
399 // and somewhat gibberish number. The hex code is a bit more
400 // recognizable and easier to search for, so print that.
401 if self.0 & 0x80000000 != 0 {
402 write!(f, "exit code: {:#x}", self.0)
404 write!(f, "exit code: {}", self.0)
409 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
410 pub struct ExitCode(c::DWORD);
413 pub const SUCCESS: ExitCode = ExitCode(EXIT_SUCCESS as _);
414 pub const FAILURE: ExitCode = ExitCode(EXIT_FAILURE as _);
417 pub fn as_i32(&self) -> i32 {
422 fn zeroed_startupinfo() -> c::STARTUPINFO {
425 lpReserved: ptr::null_mut(),
426 lpDesktop: ptr::null_mut(),
427 lpTitle: ptr::null_mut(),
438 lpReserved2: ptr::null_mut(),
439 hStdInput: c::INVALID_HANDLE_VALUE,
440 hStdOutput: c::INVALID_HANDLE_VALUE,
441 hStdError: c::INVALID_HANDLE_VALUE,
445 fn zeroed_process_information() -> c::PROCESS_INFORMATION {
446 c::PROCESS_INFORMATION {
447 hProcess: ptr::null_mut(),
448 hThread: ptr::null_mut(),
454 // Produces a wide string *without terminating null*; returns an error if
455 // `prog` or any of the `args` contain a nul.
456 fn make_command_line(prog: &OsStr, args: &[OsString], force_quotes: bool) -> io::Result<Vec<u16>> {
457 // Encode the command and arguments in a command line string such
458 // that the spawned process may recover them using CommandLineToArgvW.
459 let mut cmd: Vec<u16> = Vec::new();
460 // Always quote the program name so CreateProcess doesn't interpret args as
461 // part of the name if the binary wasn't found first time.
462 append_arg(&mut cmd, prog, true)?;
464 cmd.push(' ' as u16);
465 append_arg(&mut cmd, arg, force_quotes)?;
469 fn append_arg(cmd: &mut Vec<u16>, arg: &OsStr, force_quotes: bool) -> io::Result<()> {
470 // If an argument has 0 characters then we need to quote it to ensure
471 // that it actually gets passed through on the command line or otherwise
472 // it will be dropped entirely when parsed on the other end.
473 ensure_no_nuls(arg)?;
474 let arg_bytes = &arg.as_inner().inner.as_inner();
475 let quote = force_quotes
476 || arg_bytes.iter().any(|c| *c == b' ' || *c == b'\t')
477 || arg_bytes.is_empty();
479 cmd.push('"' as u16);
482 let mut backslashes: usize = 0;
483 for x in arg.encode_wide() {
484 if x == '\\' as u16 {
488 // Add n+1 backslashes to total 2n+1 before internal '"'.
489 cmd.extend((0..=backslashes).map(|_| '\\' as u16));
497 // Add n backslashes to total 2n before ending '"'.
498 cmd.extend((0..backslashes).map(|_| '\\' as u16));
499 cmd.push('"' as u16);
505 fn make_envp(maybe_env: Option<BTreeMap<EnvKey, OsString>>) -> io::Result<(*mut c_void, Vec<u16>)> {
506 // On Windows we pass an "environment block" which is not a char**, but
507 // rather a concatenation of null-terminated k=v\0 sequences, with a final
509 if let Some(env) = maybe_env {
510 let mut blk = Vec::new();
513 blk.extend(ensure_no_nuls(k.0)?.encode_wide());
514 blk.push('=' as u16);
515 blk.extend(ensure_no_nuls(v)?.encode_wide());
519 Ok((blk.as_mut_ptr() as *mut c_void, blk))
521 Ok((ptr::null_mut(), Vec::new()))
525 fn make_dirp(d: Option<&OsString>) -> io::Result<(*const u16, Vec<u16>)> {
528 let mut dir_str: Vec<u16> = ensure_no_nuls(dir)?.encode_wide().collect();
530 Ok((dir_str.as_ptr(), dir_str))
532 None => Ok((ptr::null(), Vec::new())),
536 pub struct CommandArgs<'a> {
537 iter: crate::slice::Iter<'a, OsString>,
540 impl<'a> Iterator for CommandArgs<'a> {
541 type Item = &'a OsStr;
542 fn next(&mut self) -> Option<&'a OsStr> {
543 self.iter.next().map(|s| s.as_ref())
545 fn size_hint(&self) -> (usize, Option<usize>) {
546 self.iter.size_hint()
550 impl<'a> ExactSizeIterator for CommandArgs<'a> {
551 fn len(&self) -> usize {
554 fn is_empty(&self) -> bool {
559 impl<'a> fmt::Debug for CommandArgs<'a> {
560 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
561 f.debug_list().entries(self.iter.clone()).finish()