]> git.lizzy.rs Git - rust.git/blob - src/libstd/process.rs
Auto merge of #31056 - kamalmarhubi:std-process-nul-chars, r=alexcrichton
[rust.git] / src / libstd / process.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Working with processes.
12
13 #![stable(feature = "process", since = "1.0.0")]
14 #![allow(non_upper_case_globals)]
15
16 use prelude::v1::*;
17 use io::prelude::*;
18
19 use ffi::OsStr;
20 use fmt;
21 use io::{self, Error, ErrorKind};
22 use path;
23 use str;
24 use sys::pipe::{self, AnonPipe};
25 use sys::process as imp;
26 use sys_common::{AsInner, AsInnerMut, FromInner, IntoInner};
27 use thread::{self, JoinHandle};
28
29 /// Representation of a running or exited child process.
30 ///
31 /// This structure is used to represent and manage child processes. A child
32 /// process is created via the `Command` struct, which configures the spawning
33 /// process and can itself be constructed using a builder-style interface.
34 ///
35 /// # Examples
36 ///
37 /// ```should_panic
38 /// use std::process::Command;
39 ///
40 /// let mut child = Command::new("/bin/cat")
41 ///                         .arg("file.txt")
42 ///                         .spawn()
43 ///                         .unwrap_or_else(|e| { panic!("failed to execute child: {}", e) });
44 ///
45 /// let ecode = child.wait()
46 ///                  .unwrap_or_else(|e| { panic!("failed to wait on child: {}", e) });
47 ///
48 /// assert!(ecode.success());
49 /// ```
50 ///
51 /// # Note
52 ///
53 /// Take note that there is no implementation of
54 /// [`Drop`](../../core/ops/trait.Drop.html) for child processes, so if you
55 /// do not ensure the `Child` has exited then it will continue to run, even
56 /// after the `Child` handle to the child process has gone out of scope.
57 ///
58 /// Calling `wait` (or other functions that wrap around it) will make the
59 /// parent process wait until the child has actually exited before continuing.
60 #[stable(feature = "process", since = "1.0.0")]
61 pub struct Child {
62     handle: imp::Process,
63
64     /// None until wait() or wait_with_output() is called.
65     status: Option<imp::ExitStatus>,
66
67     /// The handle for writing to the child's stdin, if it has been captured
68     #[stable(feature = "process", since = "1.0.0")]
69     pub stdin: Option<ChildStdin>,
70
71     /// The handle for reading from the child's stdout, if it has been captured
72     #[stable(feature = "process", since = "1.0.0")]
73     pub stdout: Option<ChildStdout>,
74
75     /// The handle for reading from the child's stderr, if it has been captured
76     #[stable(feature = "process", since = "1.0.0")]
77     pub stderr: Option<ChildStderr>,
78 }
79
80 impl AsInner<imp::Process> for Child {
81     fn as_inner(&self) -> &imp::Process { &self.handle }
82 }
83
84 impl IntoInner<imp::Process> for Child {
85     fn into_inner(self) -> imp::Process { self.handle }
86 }
87
88 /// A handle to a child process's stdin
89 #[stable(feature = "process", since = "1.0.0")]
90 pub struct ChildStdin {
91     inner: AnonPipe
92 }
93
94 #[stable(feature = "process", since = "1.0.0")]
95 impl Write for ChildStdin {
96     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
97         self.inner.write(buf)
98     }
99
100     fn flush(&mut self) -> io::Result<()> {
101         Ok(())
102     }
103 }
104
105 impl AsInner<AnonPipe> for ChildStdin {
106     fn as_inner(&self) -> &AnonPipe { &self.inner }
107 }
108
109 impl IntoInner<AnonPipe> for ChildStdin {
110     fn into_inner(self) -> AnonPipe { self.inner }
111 }
112
113 /// A handle to a child process's stdout
114 #[stable(feature = "process", since = "1.0.0")]
115 pub struct ChildStdout {
116     inner: AnonPipe
117 }
118
119 #[stable(feature = "process", since = "1.0.0")]
120 impl Read for ChildStdout {
121     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
122         self.inner.read(buf)
123     }
124 }
125
126 impl AsInner<AnonPipe> for ChildStdout {
127     fn as_inner(&self) -> &AnonPipe { &self.inner }
128 }
129
130 impl IntoInner<AnonPipe> for ChildStdout {
131     fn into_inner(self) -> AnonPipe { self.inner }
132 }
133
134 /// A handle to a child process's stderr
135 #[stable(feature = "process", since = "1.0.0")]
136 pub struct ChildStderr {
137     inner: AnonPipe
138 }
139
140 #[stable(feature = "process", since = "1.0.0")]
141 impl Read for ChildStderr {
142     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
143         self.inner.read(buf)
144     }
145 }
146
147 impl AsInner<AnonPipe> for ChildStderr {
148     fn as_inner(&self) -> &AnonPipe { &self.inner }
149 }
150
151 impl IntoInner<AnonPipe> for ChildStderr {
152     fn into_inner(self) -> AnonPipe { self.inner }
153 }
154
155 /// The `Command` type acts as a process builder, providing fine-grained control
156 /// over how a new process should be spawned. A default configuration can be
157 /// generated using `Command::new(program)`, where `program` gives a path to the
158 /// program to be executed. Additional builder methods allow the configuration
159 /// to be changed (for example, by adding arguments) prior to spawning:
160 ///
161 /// ```
162 /// use std::process::Command;
163 ///
164 /// let output = Command::new("sh")
165 ///                      .arg("-c")
166 ///                      .arg("echo hello")
167 ///                      .output()
168 ///                      .unwrap_or_else(|e| { panic!("failed to execute process: {}", e) });
169 /// let hello = output.stdout;
170 /// ```
171 #[stable(feature = "process", since = "1.0.0")]
172 pub struct Command {
173     inner: imp::Command,
174
175     // Details explained in the builder methods
176     stdin: Option<Stdio>,
177     stdout: Option<Stdio>,
178     stderr: Option<Stdio>,
179 }
180
181 impl Command {
182     /// Constructs a new `Command` for launching the program at
183     /// path `program`, with the following default configuration:
184     ///
185     /// * No arguments to the program
186     /// * Inherit the current process's environment
187     /// * Inherit the current process's working directory
188     /// * Inherit stdin/stdout/stderr for `spawn` or `status`, but create pipes for `output`
189     ///
190     /// Builder methods are provided to change these defaults and
191     /// otherwise configure the process.
192     #[stable(feature = "process", since = "1.0.0")]
193     pub fn new<S: AsRef<OsStr>>(program: S) -> Command {
194         Command {
195             inner: imp::Command::new(program.as_ref()),
196             stdin: None,
197             stdout: None,
198             stderr: None,
199         }
200     }
201
202     /// Add an argument to pass to the program.
203     #[stable(feature = "process", since = "1.0.0")]
204     pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Command {
205         self.inner.arg(arg.as_ref());
206         self
207     }
208
209     /// Add multiple arguments to pass to the program.
210     #[stable(feature = "process", since = "1.0.0")]
211     pub fn args<S: AsRef<OsStr>>(&mut self, args: &[S]) -> &mut Command {
212         self.inner.args(args.iter().map(AsRef::as_ref));
213         self
214     }
215
216     /// Inserts or updates an environment variable mapping.
217     ///
218     /// Note that environment variable names are case-insensitive (but case-preserving) on Windows,
219     /// and case-sensitive on all other platforms.
220     #[stable(feature = "process", since = "1.0.0")]
221     pub fn env<K, V>(&mut self, key: K, val: V) -> &mut Command
222         where K: AsRef<OsStr>, V: AsRef<OsStr>
223     {
224         self.inner.env(key.as_ref(), val.as_ref());
225         self
226     }
227
228     /// Removes an environment variable mapping.
229     #[stable(feature = "process", since = "1.0.0")]
230     pub fn env_remove<K: AsRef<OsStr>>(&mut self, key: K) -> &mut Command {
231         self.inner.env_remove(key.as_ref());
232         self
233     }
234
235     /// Clears the entire environment map for the child process.
236     #[stable(feature = "process", since = "1.0.0")]
237     pub fn env_clear(&mut self) -> &mut Command {
238         self.inner.env_clear();
239         self
240     }
241
242     /// Sets the working directory for the child process.
243     #[stable(feature = "process", since = "1.0.0")]
244     pub fn current_dir<P: AsRef<path::Path>>(&mut self, dir: P) -> &mut Command {
245         self.inner.cwd(dir.as_ref().as_ref());
246         self
247     }
248
249     /// Configuration for the child process's stdin handle (file descriptor 0).
250     #[stable(feature = "process", since = "1.0.0")]
251     pub fn stdin(&mut self, cfg: Stdio) -> &mut Command {
252         self.stdin = Some(cfg);
253         self
254     }
255
256     /// Configuration for the child process's stdout handle (file descriptor 1).
257     #[stable(feature = "process", since = "1.0.0")]
258     pub fn stdout(&mut self, cfg: Stdio) -> &mut Command {
259         self.stdout = Some(cfg);
260         self
261     }
262
263     /// Configuration for the child process's stderr handle (file descriptor 2).
264     #[stable(feature = "process", since = "1.0.0")]
265     pub fn stderr(&mut self, cfg: Stdio) -> &mut Command {
266         self.stderr = Some(cfg);
267         self
268     }
269
270     fn spawn_inner(&self, default_io: StdioImp) -> io::Result<Child> {
271         let default_io = Stdio(default_io);
272
273         // See comment on `setup_io` for what `_drop_later` is.
274         let (their_stdin, our_stdin, _drop_later) = try!(
275             setup_io(self.stdin.as_ref().unwrap_or(&default_io), true)
276         );
277         let (their_stdout, our_stdout, _drop_later) = try!(
278             setup_io(self.stdout.as_ref().unwrap_or(&default_io), false)
279         );
280         let (their_stderr, our_stderr, _drop_later) = try!(
281             setup_io(self.stderr.as_ref().unwrap_or(&default_io), false)
282         );
283
284         match imp::Process::spawn(&self.inner, their_stdin, their_stdout,
285                                   their_stderr) {
286             Err(e) => Err(e),
287             Ok(handle) => Ok(Child {
288                 handle: handle,
289                 status: None,
290                 stdin: our_stdin.map(|fd| ChildStdin { inner: fd }),
291                 stdout: our_stdout.map(|fd| ChildStdout { inner: fd }),
292                 stderr: our_stderr.map(|fd| ChildStderr { inner: fd }),
293             })
294         }
295     }
296
297     /// Executes the command as a child process, returning a handle to it.
298     ///
299     /// By default, stdin, stdout and stderr are inherited from the parent.
300     #[stable(feature = "process", since = "1.0.0")]
301     pub fn spawn(&mut self) -> io::Result<Child> {
302         self.spawn_inner(StdioImp::Inherit)
303     }
304
305     /// Executes the command as a child process, waiting for it to finish and
306     /// collecting all of its output.
307     ///
308     /// By default, stdin, stdout and stderr are captured (and used to
309     /// provide the resulting output).
310     ///
311     /// # Examples
312     ///
313     /// ```
314     /// use std::process::Command;
315     /// let output = Command::new("cat").arg("foo.txt").output().unwrap_or_else(|e| {
316     ///     panic!("failed to execute process: {}", e)
317     /// });
318     ///
319     /// println!("status: {}", output.status);
320     /// println!("stdout: {}", String::from_utf8_lossy(&output.stdout));
321     /// println!("stderr: {}", String::from_utf8_lossy(&output.stderr));
322     /// ```
323     #[stable(feature = "process", since = "1.0.0")]
324     pub fn output(&mut self) -> io::Result<Output> {
325         self.spawn_inner(StdioImp::MakePipe).and_then(|p| p.wait_with_output())
326     }
327
328     /// Executes a command as a child process, waiting for it to finish and
329     /// collecting its exit status.
330     ///
331     /// By default, stdin, stdout and stderr are inherited from the parent.
332     ///
333     /// # Examples
334     ///
335     /// ```
336     /// use std::process::Command;
337     ///
338     /// let status = Command::new("ls").status().unwrap_or_else(|e| {
339     ///     panic!("failed to execute process: {}", e)
340     /// });
341     ///
342     /// println!("process exited with: {}", status);
343     /// ```
344     #[stable(feature = "process", since = "1.0.0")]
345     pub fn status(&mut self) -> io::Result<ExitStatus> {
346         self.spawn().and_then(|mut p| p.wait())
347     }
348 }
349
350 #[stable(feature = "rust1", since = "1.0.0")]
351 impl fmt::Debug for Command {
352     /// Format the program and arguments of a Command for display. Any
353     /// non-utf8 data is lossily converted using the utf8 replacement
354     /// character.
355     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
356         self.inner.fmt(f)
357     }
358 }
359
360 impl AsInner<imp::Command> for Command {
361     fn as_inner(&self) -> &imp::Command { &self.inner }
362 }
363
364 impl AsInnerMut<imp::Command> for Command {
365     fn as_inner_mut(&mut self) -> &mut imp::Command { &mut self.inner }
366 }
367
368 // Takes a `Stdio` configuration (this module) and whether the to-be-owned
369 // handle will be readable.
370 //
371 // Returns a triple of (stdio to spawn with, stdio to store, stdio to drop). The
372 // stdio to spawn with is passed down to the `sys` module and indicates how the
373 // stdio stream should be set up. The "stdio to store" is an object which
374 // should be returned in the `Child` that makes its way out. The "stdio to drop"
375 // represents the raw value of "stdio to spawn with", but is the owned variant
376 // for it. This needs to be dropped after the child spawns
377 fn setup_io(io: &Stdio, readable: bool)
378             -> io::Result<(imp::Stdio, Option<AnonPipe>, Option<AnonPipe>)>
379 {
380     Ok(match io.0 {
381         StdioImp::MakePipe => {
382             let (reader, writer) = try!(pipe::anon_pipe());
383             if readable {
384                 (imp::Stdio::Raw(reader.raw()), Some(writer), Some(reader))
385             } else {
386                 (imp::Stdio::Raw(writer.raw()), Some(reader), Some(writer))
387             }
388         }
389         StdioImp::Raw(ref owned) => (imp::Stdio::Raw(owned.raw()), None, None),
390         StdioImp::Inherit => (imp::Stdio::Inherit, None, None),
391         StdioImp::None => (imp::Stdio::None, None, None),
392     })
393 }
394
395 /// The output of a finished process.
396 #[derive(PartialEq, Eq, Clone)]
397 #[stable(feature = "process", since = "1.0.0")]
398 pub struct Output {
399     /// The status (exit code) of the process.
400     #[stable(feature = "process", since = "1.0.0")]
401     pub status: ExitStatus,
402     /// The data that the process wrote to stdout.
403     #[stable(feature = "process", since = "1.0.0")]
404     pub stdout: Vec<u8>,
405     /// The data that the process wrote to stderr.
406     #[stable(feature = "process", since = "1.0.0")]
407     pub stderr: Vec<u8>,
408 }
409
410 // If either stderr or stdout are valid utf8 strings it prints the valid
411 // strings, otherwise it prints the byte sequence instead
412 #[stable(feature = "process_output_debug", since = "1.7.0")]
413 impl fmt::Debug for Output {
414     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
415
416         let stdout_utf8 = str::from_utf8(&self.stdout);
417         let stdout_debug: &fmt::Debug = match stdout_utf8 {
418             Ok(ref str) => str,
419             Err(_) => &self.stdout
420         };
421
422         let stderr_utf8 = str::from_utf8(&self.stderr);
423         let stderr_debug: &fmt::Debug = match stderr_utf8 {
424             Ok(ref str) => str,
425             Err(_) => &self.stderr
426         };
427
428         fmt.debug_struct("Output")
429             .field("status", &self.status)
430             .field("stdout", stdout_debug)
431             .field("stderr", stderr_debug)
432             .finish()
433     }
434 }
435
436 /// Describes what to do with a standard I/O stream for a child process.
437 #[stable(feature = "process", since = "1.0.0")]
438 pub struct Stdio(StdioImp);
439
440 // The internal enum for stdio setup; see below for descriptions.
441 enum StdioImp {
442     MakePipe,
443     Raw(imp::RawStdio),
444     Inherit,
445     None,
446 }
447
448 impl Stdio {
449     /// A new pipe should be arranged to connect the parent and child processes.
450     #[stable(feature = "process", since = "1.0.0")]
451     pub fn piped() -> Stdio { Stdio(StdioImp::MakePipe) }
452
453     /// The child inherits from the corresponding parent descriptor.
454     #[stable(feature = "process", since = "1.0.0")]
455     pub fn inherit() -> Stdio { Stdio(StdioImp::Inherit) }
456
457     /// This stream will be ignored. This is the equivalent of attaching the
458     /// stream to `/dev/null`
459     #[stable(feature = "process", since = "1.0.0")]
460     pub fn null() -> Stdio { Stdio(StdioImp::None) }
461 }
462
463 impl FromInner<imp::RawStdio> for Stdio {
464     fn from_inner(inner: imp::RawStdio) -> Stdio {
465         Stdio(StdioImp::Raw(inner))
466     }
467 }
468
469 /// Describes the result of a process after it has terminated.
470 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
471 #[stable(feature = "process", since = "1.0.0")]
472 pub struct ExitStatus(imp::ExitStatus);
473
474 impl ExitStatus {
475     /// Was termination successful? Signal termination not considered a success,
476     /// and success is defined as a zero exit status.
477     #[stable(feature = "process", since = "1.0.0")]
478     pub fn success(&self) -> bool {
479         self.0.success()
480     }
481
482     /// Returns the exit code of the process, if any.
483     ///
484     /// On Unix, this will return `None` if the process was terminated
485     /// by a signal; `std::os::unix` provides an extension trait for
486     /// extracting the signal and other details from the `ExitStatus`.
487     #[stable(feature = "process", since = "1.0.0")]
488     pub fn code(&self) -> Option<i32> {
489         self.0.code()
490     }
491 }
492
493 impl AsInner<imp::ExitStatus> for ExitStatus {
494     fn as_inner(&self) -> &imp::ExitStatus { &self.0 }
495 }
496
497 #[stable(feature = "process", since = "1.0.0")]
498 impl fmt::Display for ExitStatus {
499     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
500         self.0.fmt(f)
501     }
502 }
503
504 impl Child {
505     /// Forces the child to exit. This is equivalent to sending a
506     /// SIGKILL on unix platforms.
507     #[stable(feature = "process", since = "1.0.0")]
508     pub fn kill(&mut self) -> io::Result<()> {
509         #[cfg(unix)] fn collect_status(p: &mut Child) {
510             // On Linux (and possibly other unices), a process that has exited will
511             // continue to accept signals because it is "defunct". The delivery of
512             // signals will only fail once the child has been reaped. For this
513             // reason, if the process hasn't exited yet, then we attempt to collect
514             // their status with WNOHANG.
515             if p.status.is_none() {
516                 match p.handle.try_wait() {
517                     Some(status) => { p.status = Some(status); }
518                     None => {}
519                 }
520             }
521         }
522         #[cfg(windows)] fn collect_status(_p: &mut Child) {}
523
524         collect_status(self);
525
526         // if the process has finished, and therefore had waitpid called,
527         // and we kill it, then on unix we might ending up killing a
528         // newer process that happens to have the same (re-used) id
529         if self.status.is_some() {
530             return Err(Error::new(
531                 ErrorKind::InvalidInput,
532                 "invalid argument: can't kill an exited process",
533             ))
534         }
535
536         unsafe { self.handle.kill() }
537     }
538
539     /// Returns the OS-assigned process identifier associated with this child.
540     #[stable(feature = "process_id", since = "1.3.0")]
541     pub fn id(&self) -> u32 {
542         self.handle.id()
543     }
544
545     /// Waits for the child to exit completely, returning the status that it
546     /// exited with. This function will continue to have the same return value
547     /// after it has been called at least once.
548     ///
549     /// The stdin handle to the child process, if any, will be closed
550     /// before waiting. This helps avoid deadlock: it ensures that the
551     /// child does not block waiting for input from the parent, while
552     /// the parent waits for the child to exit.
553     #[stable(feature = "process", since = "1.0.0")]
554     pub fn wait(&mut self) -> io::Result<ExitStatus> {
555         drop(self.stdin.take());
556         match self.status {
557             Some(code) => Ok(ExitStatus(code)),
558             None => {
559                 let status = try!(self.handle.wait());
560                 self.status = Some(status);
561                 Ok(ExitStatus(status))
562             }
563         }
564     }
565
566     /// Simultaneously waits for the child to exit and collect all remaining
567     /// output on the stdout/stderr handles, returning an `Output`
568     /// instance.
569     ///
570     /// The stdin handle to the child process, if any, will be closed
571     /// before waiting. This helps avoid deadlock: it ensures that the
572     /// child does not block waiting for input from the parent, while
573     /// the parent waits for the child to exit.
574     #[stable(feature = "process", since = "1.0.0")]
575     pub fn wait_with_output(mut self) -> io::Result<Output> {
576         drop(self.stdin.take());
577         fn read<R>(mut input: R) -> JoinHandle<io::Result<Vec<u8>>>
578             where R: Read + Send + 'static
579         {
580             thread::spawn(move || {
581                 let mut ret = Vec::new();
582                 input.read_to_end(&mut ret).map(|_| ret)
583             })
584         }
585         let stdout = self.stdout.take().map(read);
586         let stderr = self.stderr.take().map(read);
587         let status = try!(self.wait());
588         let stdout = stdout.and_then(|t| t.join().unwrap().ok());
589         let stderr = stderr.and_then(|t| t.join().unwrap().ok());
590
591         Ok(Output {
592             status: status,
593             stdout: stdout.unwrap_or(Vec::new()),
594             stderr: stderr.unwrap_or(Vec::new()),
595         })
596     }
597 }
598
599 /// Terminates the current process with the specified exit code.
600 ///
601 /// This function will never return and will immediately terminate the current
602 /// process. The exit code is passed through to the underlying OS and will be
603 /// available for consumption by another process.
604 ///
605 /// Note that because this function never returns, and that it terminates the
606 /// process, no destructors on the current stack or any other thread's stack
607 /// will be run. If a clean shutdown is needed it is recommended to only call
608 /// this function at a known point where there are no more destructors left
609 /// to run.
610 #[stable(feature = "rust1", since = "1.0.0")]
611 pub fn exit(code: i32) -> ! {
612     ::sys_common::cleanup();
613     ::sys::os::exit(code)
614 }
615
616 #[cfg(test)]
617 mod tests {
618     use prelude::v1::*;
619     use io::prelude::*;
620
621     use io::ErrorKind;
622     use str;
623     use super::{Command, Output, Stdio};
624
625     // FIXME(#10380) these tests should not all be ignored on android.
626
627     #[test]
628     #[cfg_attr(target_os = "android", ignore)]
629     fn smoke() {
630         let p = Command::new("true").spawn();
631         assert!(p.is_ok());
632         let mut p = p.unwrap();
633         assert!(p.wait().unwrap().success());
634     }
635
636     #[test]
637     #[cfg_attr(target_os = "android", ignore)]
638     fn smoke_failure() {
639         match Command::new("if-this-is-a-binary-then-the-world-has-ended").spawn() {
640             Ok(..) => panic!(),
641             Err(..) => {}
642         }
643     }
644
645     #[test]
646     #[cfg_attr(target_os = "android", ignore)]
647     fn exit_reported_right() {
648         let p = Command::new("false").spawn();
649         assert!(p.is_ok());
650         let mut p = p.unwrap();
651         assert!(p.wait().unwrap().code() == Some(1));
652         drop(p.wait());
653     }
654
655     #[test]
656     #[cfg(unix)]
657     #[cfg_attr(target_os = "android", ignore)]
658     fn signal_reported_right() {
659         use os::unix::process::ExitStatusExt;
660
661         let mut p = Command::new("/bin/sh")
662                             .arg("-c").arg("read a")
663                             .stdin(Stdio::piped())
664                             .spawn().unwrap();
665         p.kill().unwrap();
666         match p.wait().unwrap().signal() {
667             Some(9) => {},
668             result => panic!("not terminated by signal 9 (instead, {:?})",
669                              result),
670         }
671     }
672
673     pub fn run_output(mut cmd: Command) -> String {
674         let p = cmd.spawn();
675         assert!(p.is_ok());
676         let mut p = p.unwrap();
677         assert!(p.stdout.is_some());
678         let mut ret = String::new();
679         p.stdout.as_mut().unwrap().read_to_string(&mut ret).unwrap();
680         assert!(p.wait().unwrap().success());
681         return ret;
682     }
683
684     #[test]
685     #[cfg_attr(target_os = "android", ignore)]
686     fn stdout_works() {
687         let mut cmd = Command::new("echo");
688         cmd.arg("foobar").stdout(Stdio::piped());
689         assert_eq!(run_output(cmd), "foobar\n");
690     }
691
692     #[test]
693     #[cfg_attr(any(windows, target_os = "android"), ignore)]
694     fn set_current_dir_works() {
695         let mut cmd = Command::new("/bin/sh");
696         cmd.arg("-c").arg("pwd")
697            .current_dir("/")
698            .stdout(Stdio::piped());
699         assert_eq!(run_output(cmd), "/\n");
700     }
701
702     #[test]
703     #[cfg_attr(any(windows, target_os = "android"), ignore)]
704     fn stdin_works() {
705         let mut p = Command::new("/bin/sh")
706                             .arg("-c").arg("read line; echo $line")
707                             .stdin(Stdio::piped())
708                             .stdout(Stdio::piped())
709                             .spawn().unwrap();
710         p.stdin.as_mut().unwrap().write("foobar".as_bytes()).unwrap();
711         drop(p.stdin.take());
712         let mut out = String::new();
713         p.stdout.as_mut().unwrap().read_to_string(&mut out).unwrap();
714         assert!(p.wait().unwrap().success());
715         assert_eq!(out, "foobar\n");
716     }
717
718
719     #[test]
720     #[cfg_attr(target_os = "android", ignore)]
721     #[cfg(unix)]
722     fn uid_works() {
723         use os::unix::prelude::*;
724         use libc;
725         let mut p = Command::new("/bin/sh")
726                             .arg("-c").arg("true")
727                             .uid(unsafe { libc::getuid() })
728                             .gid(unsafe { libc::getgid() })
729                             .spawn().unwrap();
730         assert!(p.wait().unwrap().success());
731     }
732
733     #[test]
734     #[cfg_attr(target_os = "android", ignore)]
735     #[cfg(unix)]
736     fn uid_to_root_fails() {
737         use os::unix::prelude::*;
738         use libc;
739
740         // if we're already root, this isn't a valid test. Most of the bots run
741         // as non-root though (android is an exception).
742         if unsafe { libc::getuid() == 0 } { return }
743         assert!(Command::new("/bin/ls").uid(0).gid(0).spawn().is_err());
744     }
745
746     #[test]
747     #[cfg_attr(target_os = "android", ignore)]
748     fn test_process_status() {
749         let mut status = Command::new("false").status().unwrap();
750         assert!(status.code() == Some(1));
751
752         status = Command::new("true").status().unwrap();
753         assert!(status.success());
754     }
755
756     #[test]
757     fn test_process_output_fail_to_start() {
758         match Command::new("/no-binary-by-this-name-should-exist").output() {
759             Err(e) => assert_eq!(e.kind(), ErrorKind::NotFound),
760             Ok(..) => panic!()
761         }
762     }
763
764     #[test]
765     #[cfg_attr(target_os = "android", ignore)]
766     fn test_process_output_output() {
767         let Output {status, stdout, stderr}
768              = Command::new("echo").arg("hello").output().unwrap();
769         let output_str = str::from_utf8(&stdout).unwrap();
770
771         assert!(status.success());
772         assert_eq!(output_str.trim().to_string(), "hello");
773         assert_eq!(stderr, Vec::new());
774     }
775
776     #[test]
777     #[cfg_attr(target_os = "android", ignore)]
778     fn test_process_output_error() {
779         let Output {status, stdout, stderr}
780              = Command::new("mkdir").arg(".").output().unwrap();
781
782         assert!(status.code() == Some(1));
783         assert_eq!(stdout, Vec::new());
784         assert!(!stderr.is_empty());
785     }
786
787     #[test]
788     #[cfg_attr(target_os = "android", ignore)]
789     fn test_finish_once() {
790         let mut prog = Command::new("false").spawn().unwrap();
791         assert!(prog.wait().unwrap().code() == Some(1));
792     }
793
794     #[test]
795     #[cfg_attr(target_os = "android", ignore)]
796     fn test_finish_twice() {
797         let mut prog = Command::new("false").spawn().unwrap();
798         assert!(prog.wait().unwrap().code() == Some(1));
799         assert!(prog.wait().unwrap().code() == Some(1));
800     }
801
802     #[test]
803     #[cfg_attr(target_os = "android", ignore)]
804     fn test_wait_with_output_once() {
805         let prog = Command::new("echo").arg("hello").stdout(Stdio::piped())
806             .spawn().unwrap();
807         let Output {status, stdout, stderr} = prog.wait_with_output().unwrap();
808         let output_str = str::from_utf8(&stdout).unwrap();
809
810         assert!(status.success());
811         assert_eq!(output_str.trim().to_string(), "hello");
812         assert_eq!(stderr, Vec::new());
813     }
814
815     #[cfg(all(unix, not(target_os="android")))]
816     pub fn env_cmd() -> Command {
817         Command::new("env")
818     }
819     #[cfg(target_os="android")]
820     pub fn env_cmd() -> Command {
821         let mut cmd = Command::new("/system/bin/sh");
822         cmd.arg("-c").arg("set");
823         cmd
824     }
825
826     #[cfg(windows)]
827     pub fn env_cmd() -> Command {
828         let mut cmd = Command::new("cmd");
829         cmd.arg("/c").arg("set");
830         cmd
831     }
832
833     #[test]
834     fn test_inherit_env() {
835         use env;
836
837         let result = env_cmd().output().unwrap();
838         let output = String::from_utf8(result.stdout).unwrap();
839
840         for (ref k, ref v) in env::vars() {
841             // don't check android RANDOM variables
842             if cfg!(target_os = "android") && *k == "RANDOM" {
843                 continue
844             }
845
846             // Windows has hidden environment variables whose names start with
847             // equals signs (`=`). Those do not show up in the output of the
848             // `set` command.
849             assert!((cfg!(windows) && k.starts_with("=")) ||
850                     k.starts_with("DYLD") ||
851                     output.contains(&format!("{}={}", *k, *v)) ||
852                     output.contains(&format!("{}='{}'", *k, *v)),
853                     "output doesn't contain `{}={}`\n{}",
854                     k, v, output);
855         }
856     }
857
858     #[test]
859     fn test_override_env() {
860         use env;
861
862         // In some build environments (such as chrooted Nix builds), `env` can
863         // only be found in the explicitly-provided PATH env variable, not in
864         // default places such as /bin or /usr/bin. So we need to pass through
865         // PATH to our sub-process.
866         let mut cmd = env_cmd();
867         cmd.env_clear().env("RUN_TEST_NEW_ENV", "123");
868         if let Some(p) = env::var_os("PATH") {
869             cmd.env("PATH", &p);
870         }
871         let result = cmd.output().unwrap();
872         let output = String::from_utf8_lossy(&result.stdout).to_string();
873
874         assert!(output.contains("RUN_TEST_NEW_ENV=123"),
875                 "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}", output);
876     }
877
878     #[test]
879     fn test_add_to_env() {
880         let result = env_cmd().env("RUN_TEST_NEW_ENV", "123").output().unwrap();
881         let output = String::from_utf8_lossy(&result.stdout).to_string();
882
883         assert!(output.contains("RUN_TEST_NEW_ENV=123"),
884                 "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}", output);
885     }
886
887     // Regression tests for #30858.
888     #[test]
889     fn test_interior_nul_in_progname_is_error() {
890         match Command::new("has-some-\0\0s-inside").spawn() {
891             Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
892             Ok(_) => panic!(),
893         }
894     }
895
896     #[test]
897     fn test_interior_nul_in_arg_is_error() {
898         match Command::new("echo").arg("has-some-\0\0s-inside").spawn() {
899             Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
900             Ok(_) => panic!(),
901         }
902     }
903
904     #[test]
905     fn test_interior_nul_in_args_is_error() {
906         match Command::new("echo").args(&["has-some-\0\0s-inside"]).spawn() {
907             Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
908             Ok(_) => panic!(),
909         }
910     }
911
912     #[test]
913     fn test_interior_nul_in_current_dir_is_error() {
914         match Command::new("echo").current_dir("has-some-\0\0s-inside").spawn() {
915             Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
916             Ok(_) => panic!(),
917         }
918     }
919
920     // Regression tests for #30862.
921     #[test]
922     fn test_interior_nul_in_env_key_is_error() {
923         match env_cmd().env("has-some-\0\0s-inside", "value").spawn() {
924             Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
925             Ok(_) => panic!(),
926         }
927     }
928
929     #[test]
930     fn test_interior_nul_in_env_value_is_error() {
931         match env_cmd().env("key", "has-some-\0\0s-inside").spawn() {
932             Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
933             Ok(_) => panic!(),
934         }
935     }
936 }