]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/unix/process/process_unix.rs
use exhaustive_patterns to be able to use `?`
[rust.git] / src / libstd / sys / unix / process / process_unix.rs
1 use crate::io::{self, Error, ErrorKind};
2 use crate::ptr;
3 use crate::sys::cvt;
4 use crate::sys::process::process_common::*;
5 use crate::sys;
6
7 use libc::{c_int, gid_t, pid_t, uid_t};
8
9 ////////////////////////////////////////////////////////////////////////////////
10 // Command
11 ////////////////////////////////////////////////////////////////////////////////
12
13 impl Command {
14     pub fn spawn(&mut self, default: Stdio, needs_stdin: bool)
15                  -> io::Result<(Process, StdioPipes)> {
16         const CLOEXEC_MSG_FOOTER: &[u8] = b"NOEX";
17
18         let envp = self.capture_env();
19
20         if self.saw_nul() {
21             return Err(io::Error::new(ErrorKind::InvalidInput,
22                                       "nul byte found in provided data"));
23         }
24
25         let (ours, theirs) = self.setup_io(default, needs_stdin)?;
26
27         if let Some(ret) = self.posix_spawn(&theirs, envp.as_ref())? {
28             return Ok((ret, ours))
29         }
30
31         let (input, output) = sys::pipe::anon_pipe()?;
32
33         // Whatever happens after the fork is almost for sure going to touch or
34         // look at the environment in one way or another (PATH in `execvp` or
35         // accessing the `environ` pointer ourselves). Make sure no other thread
36         // is accessing the environment when we do the fork itself.
37         //
38         // Note that as soon as we're done with the fork there's no need to hold
39         // a lock any more because the parent won't do anything and the child is
40         // in its own process.
41         let result = unsafe {
42             let _env_lock = sys::os::env_lock();
43             cvt(libc::fork())?
44         };
45
46         let pid = unsafe {
47             match result {
48                 0 => {
49                     drop(input);
50                     let Err(err) = self.do_exec(theirs, envp.as_ref());
51                     let errno = err.raw_os_error().unwrap_or(libc::EINVAL) as u32;
52                     let bytes = [
53                         (errno >> 24) as u8,
54                         (errno >> 16) as u8,
55                         (errno >>  8) as u8,
56                         (errno >>  0) as u8,
57                         CLOEXEC_MSG_FOOTER[0], CLOEXEC_MSG_FOOTER[1],
58                         CLOEXEC_MSG_FOOTER[2], CLOEXEC_MSG_FOOTER[3]
59                     ];
60                     // pipe I/O up to PIPE_BUF bytes should be atomic, and then
61                     // we want to be sure we *don't* run at_exit destructors as
62                     // we're being torn down regardless
63                     assert!(output.write(&bytes).is_ok());
64                     libc::_exit(1)
65                 }
66                 n => n,
67             }
68         };
69
70         let mut p = Process { pid: pid, status: None };
71         drop(output);
72         let mut bytes = [0; 8];
73
74         // loop to handle EINTR
75         loop {
76             match input.read(&mut bytes) {
77                 Ok(0) => return Ok((p, ours)),
78                 Ok(8) => {
79                     assert!(combine(CLOEXEC_MSG_FOOTER) == combine(&bytes[4.. 8]),
80                             "Validation on the CLOEXEC pipe failed: {:?}", bytes);
81                     let errno = combine(&bytes[0.. 4]);
82                     assert!(p.wait().is_ok(),
83                             "wait() should either return Ok or panic");
84                     return Err(Error::from_raw_os_error(errno))
85                 }
86                 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
87                 Err(e) => {
88                     assert!(p.wait().is_ok(),
89                             "wait() should either return Ok or panic");
90                     panic!("the CLOEXEC pipe failed: {:?}", e)
91                 },
92                 Ok(..) => { // pipe I/O up to PIPE_BUF bytes should be atomic
93                     assert!(p.wait().is_ok(),
94                             "wait() should either return Ok or panic");
95                     panic!("short read on the CLOEXEC pipe")
96                 }
97             }
98         }
99
100         fn combine(arr: &[u8]) -> i32 {
101             let a = arr[0] as u32;
102             let b = arr[1] as u32;
103             let c = arr[2] as u32;
104             let d = arr[3] as u32;
105
106             ((a << 24) | (b << 16) | (c << 8) | (d << 0)) as i32
107         }
108     }
109
110     pub fn exec(&mut self, default: Stdio) -> io::Error {
111         let envp = self.capture_env();
112
113         if self.saw_nul() {
114             return io::Error::new(ErrorKind::InvalidInput,
115                                   "nul byte found in provided data")
116         }
117
118         match self.setup_io(default, true) {
119             Ok((_, theirs)) => {
120                 unsafe {
121                     // Similar to when forking, we want to ensure that access to
122                     // the environment is synchronized, so make sure to grab the
123                     // environment lock before we try to exec.
124                     let _lock = sys::os::env_lock();
125
126                     let Err(e) = self.do_exec(theirs, envp.as_ref());
127                     e
128                 }
129             }
130             Err(e) => e,
131         }
132     }
133
134     // And at this point we've reached a special time in the life of the
135     // child. The child must now be considered hamstrung and unable to
136     // do anything other than syscalls really. Consider the following
137     // scenario:
138     //
139     //      1. Thread A of process 1 grabs the malloc() mutex
140     //      2. Thread B of process 1 forks(), creating thread C
141     //      3. Thread C of process 2 then attempts to malloc()
142     //      4. The memory of process 2 is the same as the memory of
143     //         process 1, so the mutex is locked.
144     //
145     // This situation looks a lot like deadlock, right? It turns out
146     // that this is what pthread_atfork() takes care of, which is
147     // presumably implemented across platforms. The first thing that
148     // threads to *before* forking is to do things like grab the malloc
149     // mutex, and then after the fork they unlock it.
150     //
151     // Despite this information, libnative's spawn has been witnessed to
152     // deadlock on both macOS and FreeBSD. I'm not entirely sure why, but
153     // all collected backtraces point at malloc/free traffic in the
154     // child spawned process.
155     //
156     // For this reason, the block of code below should contain 0
157     // invocations of either malloc of free (or their related friends).
158     //
159     // As an example of not having malloc/free traffic, we don't close
160     // this file descriptor by dropping the FileDesc (which contains an
161     // allocation). Instead we just close it manually. This will never
162     // have the drop glue anyway because this code never returns (the
163     // child will either exec() or invoke libc::exit)
164     unsafe fn do_exec(
165         &mut self,
166         stdio: ChildPipes,
167         maybe_envp: Option<&CStringArray>
168     ) -> Result<!, io::Error> {
169         use crate::sys::{self, cvt_r};
170
171         if let Some(fd) = stdio.stdin.fd() {
172             cvt_r(|| libc::dup2(fd, libc::STDIN_FILENO))?;
173         }
174         if let Some(fd) = stdio.stdout.fd() {
175             cvt_r(|| libc::dup2(fd, libc::STDOUT_FILENO))?;
176         }
177         if let Some(fd) = stdio.stderr.fd() {
178             cvt_r(|| libc::dup2(fd, libc::STDERR_FILENO))?;
179         }
180
181         if cfg!(not(any(target_os = "l4re"))) {
182             if let Some(u) = self.get_gid() {
183                 cvt(libc::setgid(u as gid_t))?;
184             }
185             if let Some(u) = self.get_uid() {
186                 // When dropping privileges from root, the `setgroups` call
187                 // will remove any extraneous groups. If we don't call this,
188                 // then even though our uid has dropped, we may still have
189                 // groups that enable us to do super-user things. This will
190                 // fail if we aren't root, so don't bother checking the
191                 // return value, this is just done as an optimistic
192                 // privilege dropping function.
193                 let _ = libc::setgroups(0, ptr::null());
194
195                 cvt(libc::setuid(u as uid_t))?;
196             }
197         }
198         if let Some(ref cwd) = *self.get_cwd() {
199             cvt(libc::chdir(cwd.as_ptr()))?;
200         }
201
202         // emscripten has no signal support.
203         #[cfg(not(any(target_os = "emscripten")))]
204         {
205             use crate::mem;
206             // Reset signal handling so the child process starts in a
207             // standardized state. libstd ignores SIGPIPE, and signal-handling
208             // libraries often set a mask. Child processes inherit ignored
209             // signals and the signal mask from their parent, but most
210             // UNIX programs do not reset these things on their own, so we
211             // need to clean things up now to avoid confusing the program
212             // we're about to run.
213             let mut set: libc::sigset_t = mem::uninitialized();
214             if cfg!(target_os = "android") {
215                 // Implementing sigemptyset allow us to support older Android
216                 // versions. See the comment about Android and sig* functions in
217                 // process_common.rs
218                 libc::memset(&mut set as *mut _ as *mut _,
219                              0,
220                              mem::size_of::<libc::sigset_t>());
221             } else {
222                 cvt(libc::sigemptyset(&mut set))?;
223             }
224             cvt(libc::pthread_sigmask(libc::SIG_SETMASK, &set,
225                                          ptr::null_mut()))?;
226             let ret = sys::signal(libc::SIGPIPE, libc::SIG_DFL);
227             if ret == libc::SIG_ERR {
228                 return Err(io::Error::last_os_error())
229             }
230         }
231
232         for callback in self.get_closures().iter_mut() {
233             callback()?;
234         }
235
236         // Although we're performing an exec here we may also return with an
237         // error from this function (without actually exec'ing) in which case we
238         // want to be sure to restore the global environment back to what it
239         // once was, ensuring that our temporary override, when free'd, doesn't
240         // corrupt our process's environment.
241         let mut _reset = None;
242         if let Some(envp) = maybe_envp {
243             struct Reset(*const *const libc::c_char);
244
245             impl Drop for Reset {
246                 fn drop(&mut self) {
247                     unsafe {
248                         *sys::os::environ() = self.0;
249                     }
250                 }
251             }
252
253             _reset = Some(Reset(*sys::os::environ()));
254             *sys::os::environ() = envp.as_ptr();
255         }
256
257         libc::execvp(self.get_argv()[0], self.get_argv().as_ptr());
258         Err(io::Error::last_os_error())
259     }
260
261     #[cfg(not(any(target_os = "macos", target_os = "freebsd",
262                   all(target_os = "linux", target_env = "gnu"))))]
263     fn posix_spawn(&mut self, _: &ChildPipes, _: Option<&CStringArray>)
264         -> io::Result<Option<Process>>
265     {
266         Ok(None)
267     }
268
269     // Only support platforms for which posix_spawn() can return ENOENT
270     // directly.
271     #[cfg(any(target_os = "macos", target_os = "freebsd",
272               all(target_os = "linux", target_env = "gnu")))]
273     fn posix_spawn(&mut self, stdio: &ChildPipes, envp: Option<&CStringArray>)
274         -> io::Result<Option<Process>>
275     {
276         use crate::mem;
277         use crate::sys;
278
279         if self.get_gid().is_some() ||
280             self.get_uid().is_some() ||
281             self.env_saw_path() ||
282             self.get_closures().len() != 0 {
283             return Ok(None)
284         }
285
286         // Only glibc 2.24+ posix_spawn() supports returning ENOENT directly.
287         #[cfg(all(target_os = "linux", target_env = "gnu"))]
288         {
289             if let Some(version) = sys::os::glibc_version() {
290                 if version < (2, 24) {
291                     return Ok(None)
292                 }
293             } else {
294                 return Ok(None)
295             }
296         }
297
298         // Solaris and glibc 2.29+ can set a new working directory, and maybe
299         // others will gain this non-POSIX function too. We'll check for this
300         // weak symbol as soon as it's needed, so we can return early otherwise
301         // to do a manual chdir before exec.
302         weak! {
303             fn posix_spawn_file_actions_addchdir_np(
304                 *mut libc::posix_spawn_file_actions_t,
305                 *const libc::c_char
306             ) -> libc::c_int
307         }
308         let addchdir = match self.get_cwd() {
309             Some(cwd) => match posix_spawn_file_actions_addchdir_np.get() {
310                 Some(f) => Some((f, cwd)),
311                 None => return Ok(None),
312             },
313             None => None,
314         };
315
316         let mut p = Process { pid: 0, status: None };
317
318         struct PosixSpawnFileActions(libc::posix_spawn_file_actions_t);
319
320         impl Drop for PosixSpawnFileActions {
321             fn drop(&mut self) {
322                 unsafe {
323                     libc::posix_spawn_file_actions_destroy(&mut self.0);
324                 }
325             }
326         }
327
328         struct PosixSpawnattr(libc::posix_spawnattr_t);
329
330         impl Drop for PosixSpawnattr {
331             fn drop(&mut self) {
332                 unsafe {
333                     libc::posix_spawnattr_destroy(&mut self.0);
334                 }
335             }
336         }
337
338         unsafe {
339             let mut file_actions = PosixSpawnFileActions(mem::uninitialized());
340             let mut attrs = PosixSpawnattr(mem::uninitialized());
341
342             libc::posix_spawnattr_init(&mut attrs.0);
343             libc::posix_spawn_file_actions_init(&mut file_actions.0);
344
345             if let Some(fd) = stdio.stdin.fd() {
346                 cvt(libc::posix_spawn_file_actions_adddup2(&mut file_actions.0,
347                                                            fd,
348                                                            libc::STDIN_FILENO))?;
349             }
350             if let Some(fd) = stdio.stdout.fd() {
351                 cvt(libc::posix_spawn_file_actions_adddup2(&mut file_actions.0,
352                                                            fd,
353                                                            libc::STDOUT_FILENO))?;
354             }
355             if let Some(fd) = stdio.stderr.fd() {
356                 cvt(libc::posix_spawn_file_actions_adddup2(&mut file_actions.0,
357                                                            fd,
358                                                            libc::STDERR_FILENO))?;
359             }
360             if let Some((f, cwd)) = addchdir {
361                 cvt(f(&mut file_actions.0, cwd.as_ptr()))?;
362             }
363
364             let mut set: libc::sigset_t = mem::uninitialized();
365             cvt(libc::sigemptyset(&mut set))?;
366             cvt(libc::posix_spawnattr_setsigmask(&mut attrs.0,
367                                                  &set))?;
368             cvt(libc::sigaddset(&mut set, libc::SIGPIPE))?;
369             cvt(libc::posix_spawnattr_setsigdefault(&mut attrs.0,
370                                                     &set))?;
371
372             let flags = libc::POSIX_SPAWN_SETSIGDEF |
373                 libc::POSIX_SPAWN_SETSIGMASK;
374             cvt(libc::posix_spawnattr_setflags(&mut attrs.0, flags as _))?;
375
376             // Make sure we synchronize access to the global `environ` resource
377             let _env_lock = sys::os::env_lock();
378             let envp = envp.map(|c| c.as_ptr())
379                 .unwrap_or_else(|| *sys::os::environ() as *const _);
380             let ret = libc::posix_spawnp(
381                 &mut p.pid,
382                 self.get_argv()[0],
383                 &file_actions.0,
384                 &attrs.0,
385                 self.get_argv().as_ptr() as *const _,
386                 envp as *const _,
387             );
388             if ret == 0 {
389                 Ok(Some(p))
390             } else {
391                 Err(io::Error::from_raw_os_error(ret))
392             }
393         }
394     }
395 }
396
397 ////////////////////////////////////////////////////////////////////////////////
398 // Processes
399 ////////////////////////////////////////////////////////////////////////////////
400
401 /// The unique ID of the process (this should never be negative).
402 pub struct Process {
403     pid: pid_t,
404     status: Option<ExitStatus>,
405 }
406
407 impl Process {
408     pub fn id(&self) -> u32 {
409         self.pid as u32
410     }
411
412     pub fn kill(&mut self) -> io::Result<()> {
413         // If we've already waited on this process then the pid can be recycled
414         // and used for another process, and we probably shouldn't be killing
415         // random processes, so just return an error.
416         if self.status.is_some() {
417             Err(Error::new(ErrorKind::InvalidInput,
418                            "invalid argument: can't kill an exited process"))
419         } else {
420             cvt(unsafe { libc::kill(self.pid, libc::SIGKILL) }).map(|_| ())
421         }
422     }
423
424     pub fn wait(&mut self) -> io::Result<ExitStatus> {
425         use crate::sys::cvt_r;
426         if let Some(status) = self.status {
427             return Ok(status)
428         }
429         let mut status = 0 as c_int;
430         cvt_r(|| unsafe { libc::waitpid(self.pid, &mut status, 0) })?;
431         self.status = Some(ExitStatus::new(status));
432         Ok(ExitStatus::new(status))
433     }
434
435     pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
436         if let Some(status) = self.status {
437             return Ok(Some(status))
438         }
439         let mut status = 0 as c_int;
440         let pid = cvt(unsafe {
441             libc::waitpid(self.pid, &mut status, libc::WNOHANG)
442         })?;
443         if pid == 0 {
444             Ok(None)
445         } else {
446             self.status = Some(ExitStatus::new(status));
447             Ok(Some(ExitStatus::new(status)))
448         }
449     }
450 }