]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/unix/process2.rs
Stabilize `std::convert` and related code
[rust.git] / src / libstd / sys / unix / process2.rs
1 // Copyright 2014-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 use prelude::v1::*;
12 use os::unix::prelude::*;
13
14 use collections::HashMap;
15 use env;
16 use ffi::{OsString, OsStr, CString};
17 use fmt;
18 use io::{self, Error, ErrorKind};
19 use libc::{self, pid_t, c_void, c_int, gid_t, uid_t};
20 use mem;
21 use ptr;
22 use sys::pipe2::AnonPipe;
23 use sys::{self, retry, c, cvt};
24
25 ////////////////////////////////////////////////////////////////////////////////
26 // Command
27 ////////////////////////////////////////////////////////////////////////////////
28
29 #[derive(Clone)]
30 pub struct Command {
31     pub program: CString,
32     pub args: Vec<CString>,
33     pub env: Option<HashMap<OsString, OsString>>,
34     pub cwd: Option<CString>,
35     pub uid: Option<uid_t>,
36     pub gid: Option<gid_t>,
37     pub detach: bool, // not currently exposed in std::process
38 }
39
40 impl Command {
41     pub fn new(program: &OsStr) -> Command {
42         Command {
43             program: program.to_cstring().unwrap(),
44             args: Vec::new(),
45             env: None,
46             cwd: None,
47             uid: None,
48             gid: None,
49             detach: false,
50         }
51     }
52
53     pub fn arg(&mut self, arg: &OsStr) {
54         self.args.push(arg.to_cstring().unwrap())
55     }
56     pub fn args<'a, I: Iterator<Item = &'a OsStr>>(&mut self, args: I) {
57         self.args.extend(args.map(|s| s.to_cstring().unwrap()))
58     }
59     fn init_env_map(&mut self) {
60         if self.env.is_none() {
61             self.env = Some(env::vars_os().collect());
62         }
63     }
64     pub fn env(&mut self, key: &OsStr, val: &OsStr) {
65         self.init_env_map();
66         self.env.as_mut().unwrap().insert(key.to_os_string(), val.to_os_string());
67     }
68     pub fn env_remove(&mut self, key: &OsStr) {
69         self.init_env_map();
70         self.env.as_mut().unwrap().remove(&key.to_os_string());
71     }
72     pub fn env_clear(&mut self) {
73         self.env = Some(HashMap::new())
74     }
75     pub fn cwd(&mut self, dir: &OsStr) {
76         self.cwd = Some(dir.to_cstring().unwrap())
77     }
78 }
79
80 ////////////////////////////////////////////////////////////////////////////////
81 // Processes
82 ////////////////////////////////////////////////////////////////////////////////
83
84 /// Unix exit statuses
85 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
86 pub enum ExitStatus {
87     /// Normal termination with an exit code.
88     Code(i32),
89
90     /// Termination by signal, with the signal number.
91     ///
92     /// Never generated on Windows.
93     Signal(i32),
94 }
95
96 impl ExitStatus {
97     pub fn success(&self) -> bool {
98         *self == ExitStatus::Code(0)
99     }
100     pub fn code(&self) -> Option<i32> {
101         match *self {
102             ExitStatus::Code(c) => Some(c),
103             _ => None
104         }
105     }
106 }
107
108 impl fmt::Display for ExitStatus {
109     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
110         match *self {
111             ExitStatus::Code(code) =>  write!(f, "exit code: {}", code),
112             ExitStatus::Signal(code) =>  write!(f, "signal: {}", code),
113         }
114     }
115 }
116
117 /// The unique id of the process (this should never be negative).
118 pub struct Process {
119     pid: pid_t
120 }
121
122 const CLOEXEC_MSG_FOOTER: &'static [u8] = b"NOEX";
123
124 impl Process {
125     pub unsafe fn kill(&self) -> io::Result<()> {
126         try!(cvt(libc::funcs::posix88::signal::kill(self.pid, libc::SIGKILL)));
127         Ok(())
128     }
129
130     pub fn spawn(cfg: &Command,
131                  in_fd: Option<AnonPipe>, out_fd: Option<AnonPipe>, err_fd: Option<AnonPipe>)
132                  -> io::Result<Process>
133     {
134         use libc::funcs::posix88::unistd::{fork, dup2, close, chdir, execvp};
135
136         mod rustrt {
137             extern {
138                 pub fn rust_unset_sigprocmask();
139             }
140         }
141
142         unsafe fn set_cloexec(fd: c_int) {
143             let ret = c::ioctl(fd, c::FIOCLEX);
144             assert_eq!(ret, 0);
145         }
146
147         #[cfg(all(target_os = "android", target_arch = "aarch64"))]
148         unsafe fn getdtablesize() -> c_int {
149             libc::sysconf(libc::consts::os::sysconf::_SC_OPEN_MAX) as c_int
150         }
151
152         #[cfg(not(all(target_os = "android", target_arch = "aarch64")))]
153         unsafe fn getdtablesize() -> c_int {
154             libc::funcs::bsd44::getdtablesize()
155         }
156
157         let dirp = cfg.cwd.as_ref().map(|c| c.as_ptr()).unwrap_or(ptr::null());
158
159         with_envp(cfg.env.as_ref(), |envp: *const c_void| {
160             with_argv(&cfg.program, &cfg.args, |argv: *const *const libc::c_char| unsafe {
161                 let (input, mut output) = try!(sys::pipe2::anon_pipe());
162
163                 // We may use this in the child, so perform allocations before the
164                 // fork
165                 let devnull = b"/dev/null\0";
166
167                 set_cloexec(output.raw());
168
169                 let pid = fork();
170                 if pid < 0 {
171                     return Err(Error::last_os_error())
172                 } else if pid > 0 {
173                     #[inline]
174                     fn combine(arr: &[u8]) -> i32 {
175                         let a = arr[0] as u32;
176                         let b = arr[1] as u32;
177                         let c = arr[2] as u32;
178                         let d = arr[3] as u32;
179
180                         ((a << 24) | (b << 16) | (c << 8) | (d << 0)) as i32
181                     }
182
183                     let p = Process{ pid: pid };
184                     drop(output);
185                     let mut bytes = [0; 8];
186
187                     // loop to handle EINTER
188                     loop {
189                         match input.read(&mut bytes) {
190                             Ok(8) => {
191                                 assert!(combine(CLOEXEC_MSG_FOOTER) == combine(&bytes[4.. 8]),
192                                         "Validation on the CLOEXEC pipe failed: {:?}", bytes);
193                                 let errno = combine(&bytes[0.. 4]);
194                                 assert!(p.wait().is_ok(),
195                                         "wait() should either return Ok or panic");
196                                 return Err(Error::from_os_error(errno))
197                             }
198                             Ok(0) => return Ok(p),
199                             Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
200                             Err(e) => {
201                                 assert!(p.wait().is_ok(),
202                                         "wait() should either return Ok or panic");
203                                 panic!("the CLOEXEC pipe failed: {:?}", e)
204                             },
205                             Ok(..) => { // pipe I/O up to PIPE_BUF bytes should be atomic
206                                 assert!(p.wait().is_ok(),
207                                         "wait() should either return Ok or panic");
208                                 panic!("short read on the CLOEXEC pipe")
209                             }
210                         }
211                     }
212                 }
213
214                 // And at this point we've reached a special time in the life of the
215                 // child. The child must now be considered hamstrung and unable to
216                 // do anything other than syscalls really. Consider the following
217                 // scenario:
218                 //
219                 //      1. Thread A of process 1 grabs the malloc() mutex
220                 //      2. Thread B of process 1 forks(), creating thread C
221                 //      3. Thread C of process 2 then attempts to malloc()
222                 //      4. The memory of process 2 is the same as the memory of
223                 //         process 1, so the mutex is locked.
224                 //
225                 // This situation looks a lot like deadlock, right? It turns out
226                 // that this is what pthread_atfork() takes care of, which is
227                 // presumably implemented across platforms. The first thing that
228                 // threads to *before* forking is to do things like grab the malloc
229                 // mutex, and then after the fork they unlock it.
230                 //
231                 // Despite this information, libnative's spawn has been witnessed to
232                 // deadlock on both OSX and FreeBSD. I'm not entirely sure why, but
233                 // all collected backtraces point at malloc/free traffic in the
234                 // child spawned process.
235                 //
236                 // For this reason, the block of code below should contain 0
237                 // invocations of either malloc of free (or their related friends).
238                 //
239                 // As an example of not having malloc/free traffic, we don't close
240                 // this file descriptor by dropping the FileDesc (which contains an
241                 // allocation). Instead we just close it manually. This will never
242                 // have the drop glue anyway because this code never returns (the
243                 // child will either exec() or invoke libc::exit)
244                 let _ = libc::close(input.raw());
245
246                 fn fail(output: &mut AnonPipe) -> ! {
247                     let errno = sys::os::errno() as u32;
248                     let bytes = [
249                         (errno >> 24) as u8,
250                         (errno >> 16) as u8,
251                         (errno >>  8) as u8,
252                         (errno >>  0) as u8,
253                         CLOEXEC_MSG_FOOTER[0], CLOEXEC_MSG_FOOTER[1],
254                         CLOEXEC_MSG_FOOTER[2], CLOEXEC_MSG_FOOTER[3]
255                     ];
256                     // pipe I/O up to PIPE_BUF bytes should be atomic
257                     assert!(output.write(&bytes).is_ok());
258                     unsafe { libc::_exit(1) }
259                 }
260
261                 rustrt::rust_unset_sigprocmask();
262
263                 // If a stdio file descriptor is set to be ignored, we don't
264                 // actually close it, but rather open up /dev/null into that
265                 // file descriptor. Otherwise, the first file descriptor opened
266                 // up in the child would be numbered as one of the stdio file
267                 // descriptors, which is likely to wreak havoc.
268                 let setup = |src: Option<AnonPipe>, dst: c_int| {
269                     let src = match src {
270                         None => {
271                             let flags = if dst == libc::STDIN_FILENO {
272                                 libc::O_RDONLY
273                             } else {
274                                 libc::O_RDWR
275                             };
276                             libc::open(devnull.as_ptr() as *const _, flags, 0)
277                         }
278                         Some(obj) => {
279                             let fd = obj.raw();
280                             // Leak the memory and the file descriptor. We're in the
281                             // child now an all our resources are going to be
282                             // cleaned up very soon
283                             mem::forget(obj);
284                             fd
285                         }
286                     };
287                     src != -1 && retry(|| dup2(src, dst)) != -1
288                 };
289
290                 if !setup(in_fd, libc::STDIN_FILENO) { fail(&mut output) }
291                 if !setup(out_fd, libc::STDOUT_FILENO) { fail(&mut output) }
292                 if !setup(err_fd, libc::STDERR_FILENO) { fail(&mut output) }
293
294                 // close all other fds
295                 for fd in (3..getdtablesize()).rev() {
296                     if fd != output.raw() {
297                         let _ = close(fd as c_int);
298                     }
299                 }
300
301                 match cfg.gid {
302                     Some(u) => {
303                         if libc::setgid(u as libc::gid_t) != 0 {
304                             fail(&mut output);
305                         }
306                     }
307                     None => {}
308                 }
309                 match cfg.uid {
310                     Some(u) => {
311                         // When dropping privileges from root, the `setgroups` call
312                         // will remove any extraneous groups. If we don't call this,
313                         // then even though our uid has dropped, we may still have
314                         // groups that enable us to do super-user things. This will
315                         // fail if we aren't root, so don't bother checking the
316                         // return value, this is just done as an optimistic
317                         // privilege dropping function.
318                         extern {
319                             fn setgroups(ngroups: libc::c_int,
320                                          ptr: *const libc::c_void) -> libc::c_int;
321                         }
322                         let _ = setgroups(0, ptr::null());
323
324                         if libc::setuid(u as libc::uid_t) != 0 {
325                             fail(&mut output);
326                         }
327                     }
328                     None => {}
329                 }
330                 if cfg.detach {
331                     // Don't check the error of setsid because it fails if we're the
332                     // process leader already. We just forked so it shouldn't return
333                     // error, but ignore it anyway.
334                     let _ = libc::setsid();
335                 }
336                 if !dirp.is_null() && chdir(dirp) == -1 {
337                     fail(&mut output);
338                 }
339                 if !envp.is_null() {
340                     *sys::os::environ() = envp as *const _;
341                 }
342                 let _ = execvp(*argv, argv as *mut _);
343                 fail(&mut output);
344             })
345         })
346     }
347
348     pub fn wait(&self) -> io::Result<ExitStatus> {
349         let mut status = 0 as c_int;
350         try!(cvt(retry(|| unsafe { c::waitpid(self.pid, &mut status, 0) })));
351         Ok(translate_status(status))
352     }
353
354     pub fn try_wait(&self) -> Option<ExitStatus> {
355         let mut status = 0 as c_int;
356         match retry(|| unsafe {
357             c::waitpid(self.pid, &mut status, c::WNOHANG)
358         }) {
359             n if n == self.pid => Some(translate_status(status)),
360             0 => None,
361             n => panic!("unknown waitpid error `{:?}`: {:?}", n,
362                        super::last_error()),
363         }
364     }
365 }
366
367 fn with_argv<T,F>(prog: &CString, args: &[CString], cb: F) -> T
368     where F : FnOnce(*const *const libc::c_char) -> T
369 {
370     let mut ptrs: Vec<*const libc::c_char> = Vec::with_capacity(args.len()+1);
371
372     // Convert the CStrings into an array of pointers. Note: the
373     // lifetime of the various CStrings involved is guaranteed to be
374     // larger than the lifetime of our invocation of cb, but this is
375     // technically unsafe as the callback could leak these pointers
376     // out of our scope.
377     ptrs.push(prog.as_ptr());
378     ptrs.extend(args.iter().map(|tmp| tmp.as_ptr()));
379
380     // Add a terminating null pointer (required by libc).
381     ptrs.push(ptr::null());
382
383     cb(ptrs.as_ptr())
384 }
385
386 fn with_envp<T, F>(env: Option<&HashMap<OsString, OsString>>, cb: F) -> T
387     where F : FnOnce(*const c_void) -> T
388 {
389     // On posixy systems we can pass a char** for envp, which is a
390     // null-terminated array of "k=v\0" strings. Since we must create
391     // these strings locally, yet expose a raw pointer to them, we
392     // create a temporary vector to own the CStrings that outlives the
393     // call to cb.
394     match env {
395         Some(env) => {
396             let mut tmps = Vec::with_capacity(env.len());
397
398             for pair in env {
399                 let mut kv = Vec::new();
400                 kv.push_all(pair.0.as_bytes());
401                 kv.push('=' as u8);
402                 kv.push_all(pair.1.as_bytes());
403                 kv.push(0); // terminating null
404                 tmps.push(kv);
405             }
406
407             // As with `with_argv`, this is unsafe, since cb could leak the pointers.
408             let mut ptrs: Vec<*const libc::c_char> =
409                 tmps.iter()
410                     .map(|tmp| tmp.as_ptr() as *const libc::c_char)
411                     .collect();
412             ptrs.push(ptr::null());
413
414             cb(ptrs.as_ptr() as *const c_void)
415         }
416         _ => cb(ptr::null())
417     }
418 }
419
420 fn translate_status(status: c_int) -> ExitStatus {
421     #![allow(non_snake_case)]
422     #[cfg(any(target_os = "linux", target_os = "android"))]
423     mod imp {
424         pub fn WIFEXITED(status: i32) -> bool { (status & 0xff) == 0 }
425         pub fn WEXITSTATUS(status: i32) -> i32 { (status >> 8) & 0xff }
426         pub fn WTERMSIG(status: i32) -> i32 { status & 0x7f }
427     }
428
429     #[cfg(any(target_os = "macos",
430               target_os = "ios",
431               target_os = "freebsd",
432               target_os = "dragonfly",
433               target_os = "bitrig",
434               target_os = "openbsd"))]
435     mod imp {
436         pub fn WIFEXITED(status: i32) -> bool { (status & 0x7f) == 0 }
437         pub fn WEXITSTATUS(status: i32) -> i32 { status >> 8 }
438         pub fn WTERMSIG(status: i32) -> i32 { status & 0o177 }
439     }
440
441     if imp::WIFEXITED(status) {
442         ExitStatus::Code(imp::WEXITSTATUS(status))
443     } else {
444         ExitStatus::Signal(imp::WTERMSIG(status))
445     }
446 }