]> git.lizzy.rs Git - rust.git/blob - library/std/src/sys/windows/process.rs
Rollup merge of #84328 - Folyd:stablize_map_into_keys_values, r=m-ou-se
[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::env;
9 use crate::env::split_paths;
10 use crate::ffi::{OsStr, OsString};
11 use crate::fmt;
12 use crate::fs;
13 use crate::io::{self, Error, ErrorKind};
14 use crate::mem;
15 use crate::os::windows::ffi::OsStrExt;
16 use crate::path::Path;
17 use crate::ptr;
18 use crate::sys::c;
19 use crate::sys::cvt;
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;
27
28 use libc::{c_void, EXIT_FAILURE, EXIT_SUCCESS};
29
30 ////////////////////////////////////////////////////////////////////////////////
31 // Command
32 ////////////////////////////////////////////////////////////////////////////////
33
34 #[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
35 #[doc(hidden)]
36 pub struct EnvKey(OsString);
37
38 impl From<OsString> for EnvKey {
39     fn from(mut k: OsString) -> Self {
40         k.make_ascii_uppercase();
41         EnvKey(k)
42     }
43 }
44
45 impl From<EnvKey> for OsString {
46     fn from(k: EnvKey) -> Self {
47         k.0
48     }
49 }
50
51 impl Borrow<OsStr> for EnvKey {
52     fn borrow(&self) -> &OsStr {
53         &self.0
54     }
55 }
56
57 impl AsRef<OsStr> for EnvKey {
58     fn as_ref(&self) -> &OsStr {
59         &self.0
60     }
61 }
62
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"))
66     } else {
67         Ok(str)
68     }
69 }
70
71 pub struct Command {
72     program: OsString,
73     args: Vec<OsString>,
74     env: CommandEnv,
75     cwd: Option<OsString>,
76     flags: u32,
77     detach: bool, // not currently exposed in std::process
78     stdin: Option<Stdio>,
79     stdout: Option<Stdio>,
80     stderr: Option<Stdio>,
81     force_quotes_enabled: bool,
82 }
83
84 pub enum Stdio {
85     Inherit,
86     Null,
87     MakePipe,
88     Handle(Handle),
89 }
90
91 pub struct StdioPipes {
92     pub stdin: Option<AnonPipe>,
93     pub stdout: Option<AnonPipe>,
94     pub stderr: Option<AnonPipe>,
95 }
96
97 impl Command {
98     pub fn new(program: &OsStr) -> Command {
99         Command {
100             program: program.to_os_string(),
101             args: Vec::new(),
102             env: Default::default(),
103             cwd: None,
104             flags: 0,
105             detach: false,
106             stdin: None,
107             stdout: None,
108             stderr: None,
109             force_quotes_enabled: false,
110         }
111     }
112
113     pub fn arg(&mut self, arg: &OsStr) {
114         self.args.push(arg.to_os_string())
115     }
116     pub fn env_mut(&mut self) -> &mut CommandEnv {
117         &mut self.env
118     }
119     pub fn cwd(&mut self, dir: &OsStr) {
120         self.cwd = Some(dir.to_os_string())
121     }
122     pub fn stdin(&mut self, stdin: Stdio) {
123         self.stdin = Some(stdin);
124     }
125     pub fn stdout(&mut self, stdout: Stdio) {
126         self.stdout = Some(stdout);
127     }
128     pub fn stderr(&mut self, stderr: Stdio) {
129         self.stderr = Some(stderr);
130     }
131     pub fn creation_flags(&mut self, flags: u32) {
132         self.flags = flags;
133     }
134
135     pub fn force_quotes(&mut self, enabled: bool) {
136         self.force_quotes_enabled = enabled;
137     }
138
139     pub fn get_program(&self) -> &OsStr {
140         &self.program
141     }
142
143     pub fn get_args(&self) -> CommandArgs<'_> {
144         let iter = self.args.iter();
145         CommandArgs { iter }
146     }
147
148     pub fn get_envs(&self) -> CommandEnvs<'_> {
149         self.env.iter()
150     }
151
152     pub fn get_current_dir(&self) -> Option<&Path> {
153         self.cwd.as_ref().map(|cwd| Path::new(cwd))
154     }
155
156     pub fn spawn(
157         &mut self,
158         default: Stdio,
159         needs_stdin: bool,
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
164         // details.
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
168                 // program exists.
169                 for path in split_paths(&v) {
170                     let path = path
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());
175                     }
176                 }
177             }
178             None
179         });
180
181         let mut si = zeroed_startupinfo();
182         si.cb = mem::size_of::<c::STARTUPINFO>() as c::DWORD;
183         si.dwFlags = c::STARTF_USESTDHANDLES;
184
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
188
189         // stolen from the libuv code.
190         let mut flags = self.flags | c::CREATE_UNICODE_ENVIRONMENT;
191         if self.detach {
192             flags |= c::DETACHED_PROCESS | c::CREATE_NEW_PROCESS_GROUP;
193         }
194
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();
198
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.
205         //
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();
209
210         let _guard = unsafe { CREATE_PROCESS_LOCK.lock() };
211
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();
224
225         unsafe {
226             cvt(c::CreateProcessW(
227                 ptr::null(),
228                 cmd_str.as_mut_ptr(),
229                 ptr::null_mut(),
230                 ptr::null_mut(),
231                 c::TRUE,
232                 flags,
233                 envp,
234                 dirp,
235                 &mut si,
236                 &mut pi,
237             ))
238         }?;
239
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));
244
245         Ok((Process { handle: Handle::new(pi.hProcess) }, pipes))
246     }
247 }
248
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)?;
254         }
255         Ok(())
256     }
257 }
258
259 impl Stdio {
260     fn to_handle(&self, stdio_id: c::DWORD, pipe: &mut Option<AnonPipe>) -> io::Result<Handle> {
261         match *self {
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) {
266                 Ok(io) => {
267                     let io = Handle::new(io);
268                     let ret = io.duplicate(0, true, c::DUPLICATE_SAME_ACCESS);
269                     io.into_raw();
270                     ret
271                 }
272                 Err(..) => Ok(Handle::new(c::INVALID_HANDLE_VALUE)),
273             },
274
275             Stdio::MakePipe => {
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())
280             }
281
282             Stdio::Handle(ref handle) => handle.duplicate(0, true, c::DUPLICATE_SAME_ACCESS),
283
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).
287             Stdio::Null => {
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(),
292                     bInheritHandle: 1,
293                 };
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())
299             }
300         }
301     }
302 }
303
304 impl From<AnonPipe> for Stdio {
305     fn from(pipe: AnonPipe) -> Stdio {
306         Stdio::Handle(pipe.into_handle())
307     }
308 }
309
310 impl From<File> for Stdio {
311     fn from(file: File) -> Stdio {
312         Stdio::Handle(file.into_handle())
313     }
314 }
315
316 ////////////////////////////////////////////////////////////////////////////////
317 // Processes
318 ////////////////////////////////////////////////////////////////////////////////
319
320 /// A value representing a child process.
321 ///
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.
325 pub struct Process {
326     handle: Handle,
327 }
328
329 impl Process {
330     pub fn kill(&mut self) -> io::Result<()> {
331         cvt(unsafe { c::TerminateProcess(self.handle.raw(), 1) })?;
332         Ok(())
333     }
334
335     pub fn id(&self) -> u32 {
336         unsafe { c::GetProcessId(self.handle.raw()) as u32 }
337     }
338
339     pub fn wait(&mut self) -> io::Result<ExitStatus> {
340         unsafe {
341             let res = c::WaitForSingleObject(self.handle.raw(), c::INFINITE);
342             if res != c::WAIT_OBJECT_0 {
343                 return Err(Error::last_os_error());
344             }
345             let mut status = 0;
346             cvt(c::GetExitCodeProcess(self.handle.raw(), &mut status))?;
347             Ok(ExitStatus(status))
348         }
349     }
350
351     pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
352         unsafe {
353             match c::WaitForSingleObject(self.handle.raw(), 0) {
354                 c::WAIT_OBJECT_0 => {}
355                 c::WAIT_TIMEOUT => {
356                     return Ok(None);
357                 }
358                 _ => return Err(io::Error::last_os_error()),
359             }
360             let mut status = 0;
361             cvt(c::GetExitCodeProcess(self.handle.raw(), &mut status))?;
362             Ok(Some(ExitStatus(status)))
363         }
364     }
365
366     pub fn handle(&self) -> &Handle {
367         &self.handle
368     }
369
370     pub fn into_handle(self) -> Handle {
371         self.handle
372     }
373 }
374
375 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
376 pub struct ExitStatus(c::DWORD);
377
378 impl ExitStatus {
379     pub fn success(&self) -> bool {
380         self.0 == 0
381     }
382     pub fn code(&self) -> Option<i32> {
383         Some(self.0 as i32)
384     }
385 }
386
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 {
390         ExitStatus(u)
391     }
392 }
393
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)
403         } else {
404             write!(f, "exit code: {}", self.0)
405         }
406     }
407 }
408
409 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
410 pub struct ExitCode(c::DWORD);
411
412 impl ExitCode {
413     pub const SUCCESS: ExitCode = ExitCode(EXIT_SUCCESS as _);
414     pub const FAILURE: ExitCode = ExitCode(EXIT_FAILURE as _);
415
416     #[inline]
417     pub fn as_i32(&self) -> i32 {
418         self.0 as i32
419     }
420 }
421
422 fn zeroed_startupinfo() -> c::STARTUPINFO {
423     c::STARTUPINFO {
424         cb: 0,
425         lpReserved: ptr::null_mut(),
426         lpDesktop: ptr::null_mut(),
427         lpTitle: ptr::null_mut(),
428         dwX: 0,
429         dwY: 0,
430         dwXSize: 0,
431         dwYSize: 0,
432         dwXCountChars: 0,
433         dwYCountCharts: 0,
434         dwFillAttribute: 0,
435         dwFlags: 0,
436         wShowWindow: 0,
437         cbReserved2: 0,
438         lpReserved2: ptr::null_mut(),
439         hStdInput: c::INVALID_HANDLE_VALUE,
440         hStdOutput: c::INVALID_HANDLE_VALUE,
441         hStdError: c::INVALID_HANDLE_VALUE,
442     }
443 }
444
445 fn zeroed_process_information() -> c::PROCESS_INFORMATION {
446     c::PROCESS_INFORMATION {
447         hProcess: ptr::null_mut(),
448         hThread: ptr::null_mut(),
449         dwProcessId: 0,
450         dwThreadId: 0,
451     }
452 }
453
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)?;
463     for arg in args {
464         cmd.push(' ' as u16);
465         append_arg(&mut cmd, arg, force_quotes)?;
466     }
467     return Ok(cmd);
468
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();
478         if quote {
479             cmd.push('"' as u16);
480         }
481
482         let mut backslashes: usize = 0;
483         for x in arg.encode_wide() {
484             if x == '\\' as u16 {
485                 backslashes += 1;
486             } else {
487                 if x == '"' as u16 {
488                     // Add n+1 backslashes to total 2n+1 before internal '"'.
489                     cmd.extend((0..=backslashes).map(|_| '\\' as u16));
490                 }
491                 backslashes = 0;
492             }
493             cmd.push(x);
494         }
495
496         if quote {
497             // Add n backslashes to total 2n before ending '"'.
498             cmd.extend((0..backslashes).map(|_| '\\' as u16));
499             cmd.push('"' as u16);
500         }
501         Ok(())
502     }
503 }
504
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
508     // \0 to terminate.
509     if let Some(env) = maybe_env {
510         let mut blk = Vec::new();
511
512         for (k, v) in env {
513             blk.extend(ensure_no_nuls(k.0)?.encode_wide());
514             blk.push('=' as u16);
515             blk.extend(ensure_no_nuls(v)?.encode_wide());
516             blk.push(0);
517         }
518         blk.push(0);
519         Ok((blk.as_mut_ptr() as *mut c_void, blk))
520     } else {
521         Ok((ptr::null_mut(), Vec::new()))
522     }
523 }
524
525 fn make_dirp(d: Option<&OsString>) -> io::Result<(*const u16, Vec<u16>)> {
526     match d {
527         Some(dir) => {
528             let mut dir_str: Vec<u16> = ensure_no_nuls(dir)?.encode_wide().collect();
529             dir_str.push(0);
530             Ok((dir_str.as_ptr(), dir_str))
531         }
532         None => Ok((ptr::null(), Vec::new())),
533     }
534 }
535
536 pub struct CommandArgs<'a> {
537     iter: crate::slice::Iter<'a, OsString>,
538 }
539
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())
544     }
545     fn size_hint(&self) -> (usize, Option<usize>) {
546         self.iter.size_hint()
547     }
548 }
549
550 impl<'a> ExactSizeIterator for CommandArgs<'a> {
551     fn len(&self) -> usize {
552         self.iter.len()
553     }
554     fn is_empty(&self) -> bool {
555         self.iter.is_empty()
556     }
557 }
558
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()
562     }
563 }