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