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