]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/windows/process.rs
Rollup merge of #65144 - clarfon:moo, r=sfackler
[rust.git] / src / libstd / sys / windows / process.rs
1 #![unstable(feature = "process_internals", issue = "0")]
2
3 use crate::collections::BTreeMap;
4 use crate::env::split_paths;
5 use crate::env;
6 use crate::ffi::{OsString, OsStr};
7 use crate::fmt;
8 use crate::fs;
9 use crate::io::{self, Error, ErrorKind};
10 use crate::mem;
11 use crate::os::windows::ffi::OsStrExt;
12 use crate::path::Path;
13 use crate::ptr;
14 use crate::sys::mutex::Mutex;
15 use crate::sys::c;
16 use crate::sys::fs::{OpenOptions, File};
17 use crate::sys::handle::Handle;
18 use crate::sys::pipe::{self, AnonPipe};
19 use crate::sys::stdio;
20 use crate::sys::cvt;
21 use crate::sys_common::{AsInner, FromInner, IntoInner};
22 use crate::sys_common::process::CommandEnv;
23 use crate::borrow::Borrow;
24
25 use libc::{c_void, EXIT_SUCCESS, EXIT_FAILURE};
26
27 ////////////////////////////////////////////////////////////////////////////////
28 // Command
29 ////////////////////////////////////////////////////////////////////////////////
30
31 #[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
32 #[doc(hidden)]
33 pub struct EnvKey(OsString);
34
35 impl From<OsString> for EnvKey {
36     fn from(k: OsString) -> Self {
37         let mut buf = k.into_inner().into_inner();
38         buf.make_ascii_uppercase();
39         EnvKey(FromInner::from_inner(FromInner::from_inner(buf)))
40     }
41 }
42
43 impl From<EnvKey> for OsString {
44     fn from(k: EnvKey) -> Self { k.0 }
45 }
46
47 impl Borrow<OsStr> for EnvKey {
48     fn borrow(&self) -> &OsStr { &self.0 }
49 }
50
51 impl AsRef<OsStr> for EnvKey {
52     fn as_ref(&self) -> &OsStr { &self.0 }
53 }
54
55
56 fn ensure_no_nuls<T: AsRef<OsStr>>(str: T) -> io::Result<T> {
57     if str.as_ref().encode_wide().any(|b| b == 0) {
58         Err(io::Error::new(ErrorKind::InvalidInput, "nul byte found in provided data"))
59     } else {
60         Ok(str)
61     }
62 }
63
64 pub struct Command {
65     program: OsString,
66     args: Vec<OsString>,
67     env: CommandEnv,
68     cwd: Option<OsString>,
69     flags: u32,
70     detach: bool, // not currently exposed in std::process
71     stdin: Option<Stdio>,
72     stdout: Option<Stdio>,
73     stderr: Option<Stdio>,
74 }
75
76 pub enum Stdio {
77     Inherit,
78     Null,
79     MakePipe,
80     Handle(Handle),
81 }
82
83 pub struct StdioPipes {
84     pub stdin: Option<AnonPipe>,
85     pub stdout: Option<AnonPipe>,
86     pub stderr: Option<AnonPipe>,
87 }
88
89 struct DropGuard<'a> {
90     lock: &'a Mutex,
91 }
92
93 impl Command {
94     pub fn new(program: &OsStr) -> Command {
95         Command {
96             program: program.to_os_string(),
97             args: Vec::new(),
98             env: Default::default(),
99             cwd: None,
100             flags: 0,
101             detach: false,
102             stdin: None,
103             stdout: None,
104             stderr: None,
105         }
106     }
107
108     pub fn arg(&mut self, arg: &OsStr) {
109         self.args.push(arg.to_os_string())
110     }
111     pub fn env_mut(&mut self) -> &mut CommandEnv {
112         &mut self.env
113     }
114     pub fn cwd(&mut self, dir: &OsStr) {
115         self.cwd = Some(dir.to_os_string())
116     }
117     pub fn stdin(&mut self, stdin: Stdio) {
118         self.stdin = Some(stdin);
119     }
120     pub fn stdout(&mut self, stdout: Stdio) {
121         self.stdout = Some(stdout);
122     }
123     pub fn stderr(&mut self, stderr: Stdio) {
124         self.stderr = Some(stderr);
125     }
126     pub fn creation_flags(&mut self, flags: u32) {
127         self.flags = flags;
128     }
129
130     pub fn spawn(&mut self, default: Stdio, needs_stdin: bool)
131                  -> io::Result<(Process, StdioPipes)> {
132         let maybe_env = self.env.capture_if_changed();
133         // To have the spawning semantics of unix/windows stay the same, we need
134         // to read the *child's* PATH if one is provided. See #15149 for more
135         // details.
136         let program = maybe_env.as_ref().and_then(|env| {
137             if let Some(v) = env.get(OsStr::new("PATH")) {
138                 // Split the value and test each path to see if the
139                 // program exists.
140                 for path in split_paths(&v) {
141                     let path = path.join(self.program.to_str().unwrap())
142                                    .with_extension(env::consts::EXE_EXTENSION);
143                     if fs::metadata(&path).is_ok() {
144                         return Some(path.into_os_string())
145                     }
146                 }
147             }
148             None
149         });
150
151         let mut si = zeroed_startupinfo();
152         si.cb = mem::size_of::<c::STARTUPINFO>() as c::DWORD;
153         si.dwFlags = c::STARTF_USESTDHANDLES;
154
155         let program = program.as_ref().unwrap_or(&self.program);
156         let mut cmd_str = make_command_line(program, &self.args)?;
157         cmd_str.push(0); // add null terminator
158
159         // stolen from the libuv code.
160         let mut flags = self.flags | c::CREATE_UNICODE_ENVIRONMENT;
161         if self.detach {
162             flags |= c::DETACHED_PROCESS | c::CREATE_NEW_PROCESS_GROUP;
163         }
164
165         let (envp, _data) = make_envp(maybe_env)?;
166         let (dirp, _data) = make_dirp(self.cwd.as_ref())?;
167         let mut pi = zeroed_process_information();
168
169         // Prepare all stdio handles to be inherited by the child. This
170         // currently involves duplicating any existing ones with the ability to
171         // be inherited by child processes. Note, however, that once an
172         // inheritable handle is created, *any* spawned child will inherit that
173         // handle. We only want our own child to inherit this handle, so we wrap
174         // the remaining portion of this spawn in a mutex.
175         //
176         // For more information, msdn also has an article about this race:
177         // http://support.microsoft.com/kb/315939
178         static CREATE_PROCESS_LOCK: Mutex = Mutex::new();
179         let _guard = DropGuard::new(&CREATE_PROCESS_LOCK);
180
181         let mut pipes = StdioPipes {
182             stdin: None,
183             stdout: None,
184             stderr: None,
185         };
186         let null = Stdio::Null;
187         let default_stdin = if needs_stdin {&default} else {&null};
188         let stdin = self.stdin.as_ref().unwrap_or(default_stdin);
189         let stdout = self.stdout.as_ref().unwrap_or(&default);
190         let stderr = self.stderr.as_ref().unwrap_or(&default);
191         let stdin = stdin.to_handle(c::STD_INPUT_HANDLE, &mut pipes.stdin)?;
192         let stdout = stdout.to_handle(c::STD_OUTPUT_HANDLE,
193                                       &mut pipes.stdout)?;
194         let stderr = stderr.to_handle(c::STD_ERROR_HANDLE,
195                                       &mut pipes.stderr)?;
196         si.hStdInput = stdin.raw();
197         si.hStdOutput = stdout.raw();
198         si.hStdError = stderr.raw();
199
200         unsafe {
201             cvt(c::CreateProcessW(ptr::null(),
202                                   cmd_str.as_mut_ptr(),
203                                   ptr::null_mut(),
204                                   ptr::null_mut(),
205                                   c::TRUE, flags, envp, dirp,
206                                   &mut si, &mut pi))
207         }?;
208
209         // We close the thread handle because we don't care about keeping
210         // the thread id valid, and we aren't keeping the thread handle
211         // around to be able to close it later.
212         drop(Handle::new(pi.hThread));
213
214         Ok((Process { handle: Handle::new(pi.hProcess) }, pipes))
215     }
216
217 }
218
219 impl fmt::Debug for Command {
220     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
221         write!(f, "{:?}", self.program)?;
222         for arg in &self.args {
223             write!(f, " {:?}", arg)?;
224         }
225         Ok(())
226     }
227 }
228
229 impl<'a> DropGuard<'a> {
230     fn new(lock: &'a Mutex) -> DropGuard<'a> {
231         unsafe {
232             lock.lock();
233             DropGuard { lock }
234         }
235     }
236 }
237
238 impl<'a> Drop for DropGuard<'a> {
239     fn drop(&mut self) {
240         unsafe {
241             self.lock.unlock();
242         }
243     }
244 }
245
246 impl Stdio {
247     fn to_handle(&self, stdio_id: c::DWORD, pipe: &mut Option<AnonPipe>)
248                  -> io::Result<Handle> {
249         match *self {
250             // If no stdio handle is available, then inherit means that it
251             // should still be unavailable so propagate the
252             // INVALID_HANDLE_VALUE.
253             Stdio::Inherit => {
254                 match stdio::get_handle(stdio_id) {
255                     Ok(io) => {
256                         let io = Handle::new(io);
257                         let ret = io.duplicate(0, true,
258                                                c::DUPLICATE_SAME_ACCESS);
259                         io.into_raw();
260                         ret
261                     }
262                     Err(..) => Ok(Handle::new(c::INVALID_HANDLE_VALUE)),
263                 }
264             }
265
266             Stdio::MakePipe => {
267                 let ours_readable = stdio_id != c::STD_INPUT_HANDLE;
268                 let pipes = pipe::anon_pipe(ours_readable, true)?;
269                 *pipe = Some(pipes.ours);
270                 Ok(pipes.theirs.into_handle())
271             }
272
273             Stdio::Handle(ref handle) => {
274                 handle.duplicate(0, true, c::DUPLICATE_SAME_ACCESS)
275             }
276
277             // Open up a reference to NUL with appropriate read/write
278             // permissions as well as the ability to be inherited to child
279             // processes (as this is about to be inherited).
280             Stdio::Null => {
281                 let size = mem::size_of::<c::SECURITY_ATTRIBUTES>();
282                 let mut sa = c::SECURITY_ATTRIBUTES {
283                     nLength: size as c::DWORD,
284                     lpSecurityDescriptor: ptr::null_mut(),
285                     bInheritHandle: 1,
286                 };
287                 let mut opts = OpenOptions::new();
288                 opts.read(stdio_id == c::STD_INPUT_HANDLE);
289                 opts.write(stdio_id != c::STD_INPUT_HANDLE);
290                 opts.security_attributes(&mut sa);
291                 File::open(Path::new("NUL"), &opts).map(|file| {
292                     file.into_handle()
293                 })
294             }
295         }
296     }
297 }
298
299 impl From<AnonPipe> for Stdio {
300     fn from(pipe: AnonPipe) -> Stdio {
301         Stdio::Handle(pipe.into_handle())
302     }
303 }
304
305 impl From<File> for Stdio {
306     fn from(file: File) -> Stdio {
307         Stdio::Handle(file.into_handle())
308     }
309 }
310
311 ////////////////////////////////////////////////////////////////////////////////
312 // Processes
313 ////////////////////////////////////////////////////////////////////////////////
314
315 /// A value representing a child process.
316 ///
317 /// The lifetime of this value is linked to the lifetime of the actual
318 /// process - the Process destructor calls self.finish() which waits
319 /// for the process to terminate.
320 pub struct Process {
321     handle: Handle,
322 }
323
324 impl Process {
325     pub fn kill(&mut self) -> io::Result<()> {
326         cvt(unsafe {
327             c::TerminateProcess(self.handle.raw(), 1)
328         })?;
329         Ok(())
330     }
331
332     pub fn id(&self) -> u32 {
333         unsafe {
334             c::GetProcessId(self.handle.raw()) as u32
335         }
336     }
337
338     pub fn wait(&mut self) -> io::Result<ExitStatus> {
339         unsafe {
340             let res = c::WaitForSingleObject(self.handle.raw(), c::INFINITE);
341             if res != c::WAIT_OBJECT_0 {
342                 return Err(Error::last_os_error())
343             }
344             let mut status = 0;
345             cvt(c::GetExitCodeProcess(self.handle.raw(), &mut status))?;
346             Ok(ExitStatus(status))
347         }
348     }
349
350     pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
351         unsafe {
352             match c::WaitForSingleObject(self.handle.raw(), 0) {
353                 c::WAIT_OBJECT_0 => {}
354                 c::WAIT_TIMEOUT => {
355                     return Ok(None);
356                 }
357                 _ => return Err(io::Error::last_os_error()),
358             }
359             let mut status = 0;
360             cvt(c::GetExitCodeProcess(self.handle.raw(), &mut status))?;
361             Ok(Some(ExitStatus(status)))
362         }
363     }
364
365     pub fn handle(&self) -> &Handle { &self.handle }
366
367     pub fn into_handle(self) -> Handle { self.handle }
368 }
369
370 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
371 pub struct ExitStatus(c::DWORD);
372
373 impl ExitStatus {
374     pub fn success(&self) -> bool {
375         self.0 == 0
376     }
377     pub fn code(&self) -> Option<i32> {
378         Some(self.0 as i32)
379     }
380 }
381
382 impl From<c::DWORD> for ExitStatus {
383     fn from(u: c::DWORD) -> ExitStatus {
384         ExitStatus(u)
385     }
386 }
387
388 impl fmt::Display for ExitStatus {
389     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
390         // Windows exit codes with the high bit set typically mean some form of
391         // unhandled exception or warning. In this scenario printing the exit
392         // code in decimal doesn't always make sense because it's a very large
393         // and somewhat gibberish number. The hex code is a bit more
394         // recognizable and easier to search for, so print that.
395         if self.0 & 0x80000000 != 0 {
396             write!(f, "exit code: {:#x}", self.0)
397         } else {
398             write!(f, "exit code: {}", self.0)
399         }
400     }
401 }
402
403 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
404 pub struct ExitCode(c::DWORD);
405
406 impl ExitCode {
407     pub const SUCCESS: ExitCode = ExitCode(EXIT_SUCCESS as _);
408     pub const FAILURE: ExitCode = ExitCode(EXIT_FAILURE as _);
409
410     #[inline]
411     pub fn as_i32(&self) -> i32 {
412         self.0 as i32
413     }
414 }
415
416 fn zeroed_startupinfo() -> c::STARTUPINFO {
417     c::STARTUPINFO {
418         cb: 0,
419         lpReserved: ptr::null_mut(),
420         lpDesktop: ptr::null_mut(),
421         lpTitle: ptr::null_mut(),
422         dwX: 0,
423         dwY: 0,
424         dwXSize: 0,
425         dwYSize: 0,
426         dwXCountChars: 0,
427         dwYCountCharts: 0,
428         dwFillAttribute: 0,
429         dwFlags: 0,
430         wShowWindow: 0,
431         cbReserved2: 0,
432         lpReserved2: ptr::null_mut(),
433         hStdInput: c::INVALID_HANDLE_VALUE,
434         hStdOutput: c::INVALID_HANDLE_VALUE,
435         hStdError: c::INVALID_HANDLE_VALUE,
436     }
437 }
438
439 fn zeroed_process_information() -> c::PROCESS_INFORMATION {
440     c::PROCESS_INFORMATION {
441         hProcess: ptr::null_mut(),
442         hThread: ptr::null_mut(),
443         dwProcessId: 0,
444         dwThreadId: 0
445     }
446 }
447
448 // Produces a wide string *without terminating null*; returns an error if
449 // `prog` or any of the `args` contain a nul.
450 fn make_command_line(prog: &OsStr, args: &[OsString]) -> io::Result<Vec<u16>> {
451     // Encode the command and arguments in a command line string such
452     // that the spawned process may recover them using CommandLineToArgvW.
453     let mut cmd: Vec<u16> = Vec::new();
454     // Always quote the program name so CreateProcess doesn't interpret args as
455     // part of the name if the binary wasn't found first time.
456     append_arg(&mut cmd, prog, true)?;
457     for arg in args {
458         cmd.push(' ' as u16);
459         append_arg(&mut cmd, arg, false)?;
460     }
461     return Ok(cmd);
462
463     fn append_arg(cmd: &mut Vec<u16>, arg: &OsStr, force_quotes: bool) -> io::Result<()> {
464         // If an argument has 0 characters then we need to quote it to ensure
465         // that it actually gets passed through on the command line or otherwise
466         // it will be dropped entirely when parsed on the other end.
467         ensure_no_nuls(arg)?;
468         let arg_bytes = &arg.as_inner().inner.as_inner();
469         let quote = force_quotes || arg_bytes.iter().any(|c| *c == b' ' || *c == b'\t')
470             || arg_bytes.is_empty();
471         if quote {
472             cmd.push('"' as u16);
473         }
474
475         let mut backslashes: usize = 0;
476         for x in arg.encode_wide() {
477             if x == '\\' as u16 {
478                 backslashes += 1;
479             } else {
480                 if x == '"' as u16 {
481                     // Add n+1 backslashes to total 2n+1 before internal '"'.
482                     cmd.extend((0..=backslashes).map(|_| '\\' as u16));
483                 }
484                 backslashes = 0;
485             }
486             cmd.push(x);
487         }
488
489         if quote {
490             // Add n backslashes to total 2n before ending '"'.
491             cmd.extend((0..backslashes).map(|_| '\\' as u16));
492             cmd.push('"' as u16);
493         }
494         Ok(())
495     }
496 }
497
498 fn make_envp(maybe_env: Option<BTreeMap<EnvKey, OsString>>)
499              -> io::Result<(*mut c_void, Vec<u16>)> {
500     // On Windows we pass an "environment block" which is not a char**, but
501     // rather a concatenation of null-terminated k=v\0 sequences, with a final
502     // \0 to terminate.
503     if let Some(env) = maybe_env {
504         let mut blk = Vec::new();
505
506         for (k, v) in env {
507             blk.extend(ensure_no_nuls(k.0)?.encode_wide());
508             blk.push('=' as u16);
509             blk.extend(ensure_no_nuls(v)?.encode_wide());
510             blk.push(0);
511         }
512         blk.push(0);
513         Ok((blk.as_mut_ptr() as *mut c_void, blk))
514     } else {
515         Ok((ptr::null_mut(), Vec::new()))
516     }
517 }
518
519 fn make_dirp(d: Option<&OsString>) -> io::Result<(*const u16, Vec<u16>)> {
520
521     match d {
522         Some(dir) => {
523             let mut dir_str: Vec<u16> = ensure_no_nuls(dir)?.encode_wide().collect();
524             dir_str.push(0);
525             Ok((dir_str.as_ptr(), dir_str))
526         },
527         None => Ok((ptr::null(), Vec::new()))
528     }
529 }
530
531 #[cfg(test)]
532 mod tests {
533     use crate::ffi::{OsStr, OsString};
534     use super::make_command_line;
535
536     #[test]
537     fn test_make_command_line() {
538         fn test_wrapper(prog: &str, args: &[&str]) -> String {
539             let command_line = &make_command_line(OsStr::new(prog),
540                                                   &args.iter()
541                                                        .map(|a| OsString::from(a))
542                                                        .collect::<Vec<OsString>>())
543                                     .unwrap();
544             String::from_utf16(command_line).unwrap()
545         }
546
547         assert_eq!(
548             test_wrapper("prog", &["aaa", "bbb", "ccc"]),
549             "\"prog\" aaa bbb ccc"
550         );
551
552         assert_eq!(
553             test_wrapper("C:\\Program Files\\blah\\blah.exe", &["aaa"]),
554             "\"C:\\Program Files\\blah\\blah.exe\" aaa"
555         );
556         assert_eq!(
557             test_wrapper("C:\\Program Files\\test", &["aa\"bb"]),
558             "\"C:\\Program Files\\test\" aa\\\"bb"
559         );
560         assert_eq!(
561             test_wrapper("echo", &["a b c"]),
562             "\"echo\" \"a b c\""
563         );
564         assert_eq!(
565             test_wrapper("echo", &["\" \\\" \\", "\\"]),
566             "\"echo\" \"\\\" \\\\\\\" \\\\\" \\"
567         );
568         assert_eq!(
569             test_wrapper("\u{03c0}\u{042f}\u{97f3}\u{00e6}\u{221e}", &[]),
570             "\"\u{03c0}\u{042f}\u{97f3}\u{00e6}\u{221e}\""
571         );
572     }
573 }