1 | //! Unix-specific extensions to primitives in the [`std::process`] module. |
2 | //! |
3 | //! [`std::process`]: crate::process |
4 | |
5 | #![stable (feature = "rust1" , since = "1.0.0" )] |
6 | |
7 | use crate::ffi::OsStr; |
8 | use crate::io; |
9 | use crate::os::unix::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, OwnedFd, RawFd}; |
10 | use crate::process; |
11 | use crate::sealed::Sealed; |
12 | use crate::sys; |
13 | use crate::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner}; |
14 | |
15 | use cfg_if::cfg_if; |
16 | |
17 | cfg_if! { |
18 | if #[cfg(any(target_os = "vxworks" , target_os = "espidf" , target_os = "horizon" , target_os = "vita" ))] { |
19 | type UserId = u16; |
20 | type GroupId = u16; |
21 | } else if #[cfg(target_os = "nto" )] { |
22 | // Both IDs are signed, see `sys/target_nto.h` of the QNX Neutrino SDP. |
23 | // Only positive values should be used, see e.g. |
24 | // https://www.qnx.com/developers/docs/7.1/#com.qnx.doc.neutrino.lib_ref/topic/s/setuid.html |
25 | type UserId = i32; |
26 | type GroupId = i32; |
27 | } else { |
28 | type UserId = u32; |
29 | type GroupId = u32; |
30 | } |
31 | } |
32 | |
33 | /// Unix-specific extensions to the [`process::Command`] builder. |
34 | /// |
35 | /// This trait is sealed: it cannot be implemented outside the standard library. |
36 | /// This is so that future additional methods are not breaking changes. |
37 | #[stable (feature = "rust1" , since = "1.0.0" )] |
38 | pub trait CommandExt: Sealed { |
39 | /// Sets the child process's user ID. This translates to a |
40 | /// `setuid` call in the child process. Failure in the `setuid` |
41 | /// call will cause the spawn to fail. |
42 | /// |
43 | /// # Notes |
44 | /// |
45 | /// This will also trigger a call to `setgroups(0, NULL)` in the child |
46 | /// process if no groups have been specified. |
47 | /// This removes supplementary groups that might have given the child |
48 | /// unwanted permissions. |
49 | #[stable (feature = "rust1" , since = "1.0.0" )] |
50 | fn uid(&mut self, id: UserId) -> &mut process::Command; |
51 | |
52 | /// Similar to `uid`, but sets the group ID of the child process. This has |
53 | /// the same semantics as the `uid` field. |
54 | #[stable (feature = "rust1" , since = "1.0.0" )] |
55 | fn gid(&mut self, id: GroupId) -> &mut process::Command; |
56 | |
57 | /// Sets the supplementary group IDs for the calling process. Translates to |
58 | /// a `setgroups` call in the child process. |
59 | #[unstable (feature = "setgroups" , issue = "90747" )] |
60 | fn groups(&mut self, groups: &[GroupId]) -> &mut process::Command; |
61 | |
62 | /// Schedules a closure to be run just before the `exec` function is |
63 | /// invoked. |
64 | /// |
65 | /// The closure is allowed to return an I/O error whose OS error code will |
66 | /// be communicated back to the parent and returned as an error from when |
67 | /// the spawn was requested. |
68 | /// |
69 | /// Multiple closures can be registered and they will be called in order of |
70 | /// their registration. If a closure returns `Err` then no further closures |
71 | /// will be called and the spawn operation will immediately return with a |
72 | /// failure. |
73 | /// |
74 | /// # Notes and Safety |
75 | /// |
76 | /// This closure will be run in the context of the child process after a |
77 | /// `fork`. This primarily means that any modifications made to memory on |
78 | /// behalf of this closure will **not** be visible to the parent process. |
79 | /// This is often a very constrained environment where normal operations |
80 | /// like `malloc`, accessing environment variables through [`std::env`] |
81 | /// or acquiring a mutex are not guaranteed to work (due to |
82 | /// other threads perhaps still running when the `fork` was run). |
83 | /// |
84 | /// For further details refer to the [POSIX fork() specification] |
85 | /// and the equivalent documentation for any targeted |
86 | /// platform, especially the requirements around *async-signal-safety*. |
87 | /// |
88 | /// This also means that all resources such as file descriptors and |
89 | /// memory-mapped regions got duplicated. It is your responsibility to make |
90 | /// sure that the closure does not violate library invariants by making |
91 | /// invalid use of these duplicates. |
92 | /// |
93 | /// Panicking in the closure is safe only if all the format arguments for the |
94 | /// panic message can be safely formatted; this is because although |
95 | /// `Command` calls [`std::panic::always_abort`](crate::panic::always_abort) |
96 | /// before calling the pre_exec hook, panic will still try to format the |
97 | /// panic message. |
98 | /// |
99 | /// When this closure is run, aspects such as the stdio file descriptors and |
100 | /// working directory have successfully been changed, so output to these |
101 | /// locations might not appear where intended. |
102 | /// |
103 | /// [POSIX fork() specification]: |
104 | /// https://pubs.opengroup.org/onlinepubs/9699919799/functions/fork.html |
105 | /// [`std::env`]: mod@crate::env |
106 | #[stable (feature = "process_pre_exec" , since = "1.34.0" )] |
107 | unsafe fn pre_exec<F>(&mut self, f: F) -> &mut process::Command |
108 | where |
109 | F: FnMut() -> io::Result<()> + Send + Sync + 'static; |
110 | |
111 | /// Schedules a closure to be run just before the `exec` function is |
112 | /// invoked. |
113 | /// |
114 | /// This method is stable and usable, but it should be unsafe. To fix |
115 | /// that, it got deprecated in favor of the unsafe [`pre_exec`]. |
116 | /// |
117 | /// [`pre_exec`]: CommandExt::pre_exec |
118 | #[stable (feature = "process_exec" , since = "1.15.0" )] |
119 | #[deprecated (since = "1.37.0" , note = "should be unsafe, use `pre_exec` instead" )] |
120 | fn before_exec<F>(&mut self, f: F) -> &mut process::Command |
121 | where |
122 | F: FnMut() -> io::Result<()> + Send + Sync + 'static, |
123 | { |
124 | unsafe { self.pre_exec(f) } |
125 | } |
126 | |
127 | /// Performs all the required setup by this `Command`, followed by calling |
128 | /// the `execvp` syscall. |
129 | /// |
130 | /// On success this function will not return, and otherwise it will return |
131 | /// an error indicating why the exec (or another part of the setup of the |
132 | /// `Command`) failed. |
133 | /// |
134 | /// `exec` not returning has the same implications as calling |
135 | /// [`process::exit`] – no destructors on the current stack or any other |
136 | /// thread’s stack will be run. Therefore, it is recommended to only call |
137 | /// `exec` at a point where it is fine to not run any destructors. Note, |
138 | /// that the `execvp` syscall independently guarantees that all memory is |
139 | /// freed and all file descriptors with the `CLOEXEC` option (set by default |
140 | /// on all file descriptors opened by the standard library) are closed. |
141 | /// |
142 | /// This function, unlike `spawn`, will **not** `fork` the process to create |
143 | /// a new child. Like spawn, however, the default behavior for the stdio |
144 | /// descriptors will be to inherited from the current process. |
145 | /// |
146 | /// # Notes |
147 | /// |
148 | /// The process may be in a "broken state" if this function returns in |
149 | /// error. For example the working directory, environment variables, signal |
150 | /// handling settings, various user/group information, or aspects of stdio |
151 | /// file descriptors may have changed. If a "transactional spawn" is |
152 | /// required to gracefully handle errors it is recommended to use the |
153 | /// cross-platform `spawn` instead. |
154 | #[stable (feature = "process_exec2" , since = "1.9.0" )] |
155 | fn exec(&mut self) -> io::Error; |
156 | |
157 | /// Set executable argument |
158 | /// |
159 | /// Set the first process argument, `argv[0]`, to something other than the |
160 | /// default executable path. |
161 | #[stable (feature = "process_set_argv0" , since = "1.45.0" )] |
162 | fn arg0<S>(&mut self, arg: S) -> &mut process::Command |
163 | where |
164 | S: AsRef<OsStr>; |
165 | |
166 | /// Sets the process group ID (PGID) of the child process. Equivalent to a |
167 | /// `setpgid` call in the child process, but may be more efficient. |
168 | /// |
169 | /// Process groups determine which processes receive signals. |
170 | /// |
171 | /// # Examples |
172 | /// |
173 | /// Pressing Ctrl-C in a terminal will send SIGINT to all processes in |
174 | /// the current foreground process group. By spawning the `sleep` |
175 | /// subprocess in a new process group, it will not receive SIGINT from the |
176 | /// terminal. |
177 | /// |
178 | /// The parent process could install a signal handler and manage the |
179 | /// subprocess on its own terms. |
180 | /// |
181 | /// A process group ID of 0 will use the process ID as the PGID. |
182 | /// |
183 | /// ```no_run |
184 | /// use std::process::Command; |
185 | /// use std::os::unix::process::CommandExt; |
186 | /// |
187 | /// Command::new("sleep" ) |
188 | /// .arg("10" ) |
189 | /// .process_group(0) |
190 | /// .spawn()? |
191 | /// .wait()?; |
192 | /// # |
193 | /// # Ok::<_, Box<dyn std::error::Error>>(()) |
194 | /// ``` |
195 | #[stable (feature = "process_set_process_group" , since = "1.64.0" )] |
196 | fn process_group(&mut self, pgroup: i32) -> &mut process::Command; |
197 | } |
198 | |
199 | #[stable (feature = "rust1" , since = "1.0.0" )] |
200 | impl CommandExt for process::Command { |
201 | fn uid(&mut self, id: UserId) -> &mut process::Command { |
202 | self.as_inner_mut().uid(id); |
203 | self |
204 | } |
205 | |
206 | fn gid(&mut self, id: GroupId) -> &mut process::Command { |
207 | self.as_inner_mut().gid(id); |
208 | self |
209 | } |
210 | |
211 | fn groups(&mut self, groups: &[GroupId]) -> &mut process::Command { |
212 | self.as_inner_mut().groups(groups); |
213 | self |
214 | } |
215 | |
216 | unsafe fn pre_exec<F>(&mut self, f: F) -> &mut process::Command |
217 | where |
218 | F: FnMut() -> io::Result<()> + Send + Sync + 'static, |
219 | { |
220 | self.as_inner_mut().pre_exec(Box::new(f)); |
221 | self |
222 | } |
223 | |
224 | fn exec(&mut self) -> io::Error { |
225 | // NOTE: This may *not* be safe to call after `libc::fork`, because it |
226 | // may allocate. That may be worth fixing at some point in the future. |
227 | self.as_inner_mut().exec(sys::process::Stdio::Inherit) |
228 | } |
229 | |
230 | fn arg0<S>(&mut self, arg: S) -> &mut process::Command |
231 | where |
232 | S: AsRef<OsStr>, |
233 | { |
234 | self.as_inner_mut().set_arg_0(arg.as_ref()); |
235 | self |
236 | } |
237 | |
238 | fn process_group(&mut self, pgroup: i32) -> &mut process::Command { |
239 | self.as_inner_mut().pgroup(pgroup); |
240 | self |
241 | } |
242 | } |
243 | |
244 | /// Unix-specific extensions to [`process::ExitStatus`] and |
245 | /// [`ExitStatusError`](process::ExitStatusError). |
246 | /// |
247 | /// On Unix, `ExitStatus` **does not necessarily represent an exit status**, as |
248 | /// passed to the `_exit` system call or returned by |
249 | /// [`ExitStatus::code()`](crate::process::ExitStatus::code). It represents **any wait status** |
250 | /// as returned by one of the `wait` family of system |
251 | /// calls. |
252 | /// |
253 | /// A Unix wait status (a Rust `ExitStatus`) can represent a Unix exit status, but can also |
254 | /// represent other kinds of process event. |
255 | /// |
256 | /// This trait is sealed: it cannot be implemented outside the standard library. |
257 | /// This is so that future additional methods are not breaking changes. |
258 | #[stable (feature = "rust1" , since = "1.0.0" )] |
259 | pub trait ExitStatusExt: Sealed { |
260 | /// Creates a new `ExitStatus` or `ExitStatusError` from the raw underlying integer status |
261 | /// value from `wait` |
262 | /// |
263 | /// The value should be a **wait status, not an exit status**. |
264 | /// |
265 | /// # Panics |
266 | /// |
267 | /// Panics on an attempt to make an `ExitStatusError` from a wait status of `0`. |
268 | /// |
269 | /// Making an `ExitStatus` always succeeds and never panics. |
270 | #[stable (feature = "exit_status_from" , since = "1.12.0" )] |
271 | fn from_raw(raw: i32) -> Self; |
272 | |
273 | /// If the process was terminated by a signal, returns that signal. |
274 | /// |
275 | /// In other words, if `WIFSIGNALED`, this returns `WTERMSIG`. |
276 | #[stable (feature = "rust1" , since = "1.0.0" )] |
277 | fn signal(&self) -> Option<i32>; |
278 | |
279 | /// If the process was terminated by a signal, says whether it dumped core. |
280 | #[stable (feature = "unix_process_wait_more" , since = "1.58.0" )] |
281 | fn core_dumped(&self) -> bool; |
282 | |
283 | /// If the process was stopped by a signal, returns that signal. |
284 | /// |
285 | /// In other words, if `WIFSTOPPED`, this returns `WSTOPSIG`. This is only possible if the status came from |
286 | /// a `wait` system call which was passed `WUNTRACED`, and was then converted into an `ExitStatus`. |
287 | #[stable (feature = "unix_process_wait_more" , since = "1.58.0" )] |
288 | fn stopped_signal(&self) -> Option<i32>; |
289 | |
290 | /// Whether the process was continued from a stopped status. |
291 | /// |
292 | /// Ie, `WIFCONTINUED`. This is only possible if the status came from a `wait` system call |
293 | /// which was passed `WCONTINUED`, and was then converted into an `ExitStatus`. |
294 | #[stable (feature = "unix_process_wait_more" , since = "1.58.0" )] |
295 | fn continued(&self) -> bool; |
296 | |
297 | /// Returns the underlying raw `wait` status. |
298 | /// |
299 | /// The returned integer is a **wait status, not an exit status**. |
300 | #[stable (feature = "unix_process_wait_more" , since = "1.58.0" )] |
301 | fn into_raw(self) -> i32; |
302 | } |
303 | |
304 | #[stable (feature = "rust1" , since = "1.0.0" )] |
305 | impl ExitStatusExt for process::ExitStatus { |
306 | fn from_raw(raw: i32) -> Self { |
307 | process::ExitStatus::from_inner(From::from(raw)) |
308 | } |
309 | |
310 | fn signal(&self) -> Option<i32> { |
311 | self.as_inner().signal() |
312 | } |
313 | |
314 | fn core_dumped(&self) -> bool { |
315 | self.as_inner().core_dumped() |
316 | } |
317 | |
318 | fn stopped_signal(&self) -> Option<i32> { |
319 | self.as_inner().stopped_signal() |
320 | } |
321 | |
322 | fn continued(&self) -> bool { |
323 | self.as_inner().continued() |
324 | } |
325 | |
326 | fn into_raw(self) -> i32 { |
327 | self.as_inner().into_raw().into() |
328 | } |
329 | } |
330 | |
331 | #[unstable (feature = "exit_status_error" , issue = "84908" )] |
332 | impl ExitStatusExt for process::ExitStatusError { |
333 | fn from_raw(raw: i32) -> Self { |
334 | process::ExitStatus::from_raw(raw) |
335 | .exit_ok() |
336 | .expect_err("<ExitStatusError as ExitStatusExt>::from_raw(0) but zero is not an error" ) |
337 | } |
338 | |
339 | fn signal(&self) -> Option<i32> { |
340 | self.into_status().signal() |
341 | } |
342 | |
343 | fn core_dumped(&self) -> bool { |
344 | self.into_status().core_dumped() |
345 | } |
346 | |
347 | fn stopped_signal(&self) -> Option<i32> { |
348 | self.into_status().stopped_signal() |
349 | } |
350 | |
351 | fn continued(&self) -> bool { |
352 | self.into_status().continued() |
353 | } |
354 | |
355 | fn into_raw(self) -> i32 { |
356 | self.into_status().into_raw() |
357 | } |
358 | } |
359 | |
360 | #[stable (feature = "process_extensions" , since = "1.2.0" )] |
361 | impl FromRawFd for process::Stdio { |
362 | #[inline ] |
363 | unsafe fn from_raw_fd(fd: RawFd) -> process::Stdio { |
364 | let fd: FileDesc = sys::fd::FileDesc::from_raw_fd(fd); |
365 | let io: Stdio = sys::process::Stdio::Fd(fd); |
366 | process::Stdio::from_inner(io) |
367 | } |
368 | } |
369 | |
370 | #[stable (feature = "io_safety" , since = "1.63.0" )] |
371 | impl From<OwnedFd> for process::Stdio { |
372 | /// Takes ownership of a file descriptor and returns a [`Stdio`](process::Stdio) |
373 | /// that can attach a stream to it. |
374 | #[inline ] |
375 | fn from(fd: OwnedFd) -> process::Stdio { |
376 | let fd: FileDesc = sys::fd::FileDesc::from_inner(fd); |
377 | let io: Stdio = sys::process::Stdio::Fd(fd); |
378 | process::Stdio::from_inner(io) |
379 | } |
380 | } |
381 | |
382 | #[stable (feature = "process_extensions" , since = "1.2.0" )] |
383 | impl AsRawFd for process::ChildStdin { |
384 | #[inline ] |
385 | fn as_raw_fd(&self) -> RawFd { |
386 | self.as_inner().as_raw_fd() |
387 | } |
388 | } |
389 | |
390 | #[stable (feature = "process_extensions" , since = "1.2.0" )] |
391 | impl AsRawFd for process::ChildStdout { |
392 | #[inline ] |
393 | fn as_raw_fd(&self) -> RawFd { |
394 | self.as_inner().as_raw_fd() |
395 | } |
396 | } |
397 | |
398 | #[stable (feature = "process_extensions" , since = "1.2.0" )] |
399 | impl AsRawFd for process::ChildStderr { |
400 | #[inline ] |
401 | fn as_raw_fd(&self) -> RawFd { |
402 | self.as_inner().as_raw_fd() |
403 | } |
404 | } |
405 | |
406 | #[stable (feature = "into_raw_os" , since = "1.4.0" )] |
407 | impl IntoRawFd for process::ChildStdin { |
408 | #[inline ] |
409 | fn into_raw_fd(self) -> RawFd { |
410 | self.into_inner().into_inner().into_raw_fd() |
411 | } |
412 | } |
413 | |
414 | #[stable (feature = "into_raw_os" , since = "1.4.0" )] |
415 | impl IntoRawFd for process::ChildStdout { |
416 | #[inline ] |
417 | fn into_raw_fd(self) -> RawFd { |
418 | self.into_inner().into_inner().into_raw_fd() |
419 | } |
420 | } |
421 | |
422 | #[stable (feature = "into_raw_os" , since = "1.4.0" )] |
423 | impl IntoRawFd for process::ChildStderr { |
424 | #[inline ] |
425 | fn into_raw_fd(self) -> RawFd { |
426 | self.into_inner().into_inner().into_raw_fd() |
427 | } |
428 | } |
429 | |
430 | #[stable (feature = "io_safety" , since = "1.63.0" )] |
431 | impl AsFd for crate::process::ChildStdin { |
432 | #[inline ] |
433 | fn as_fd(&self) -> BorrowedFd<'_> { |
434 | self.as_inner().as_fd() |
435 | } |
436 | } |
437 | |
438 | #[stable (feature = "io_safety" , since = "1.63.0" )] |
439 | impl From<crate::process::ChildStdin> for OwnedFd { |
440 | /// Takes ownership of a [`ChildStdin`](crate::process::ChildStdin)'s file descriptor. |
441 | #[inline ] |
442 | fn from(child_stdin: crate::process::ChildStdin) -> OwnedFd { |
443 | child_stdin.into_inner().into_inner().into_inner() |
444 | } |
445 | } |
446 | |
447 | /// Create a `ChildStdin` from the provided `OwnedFd`. |
448 | /// |
449 | /// The provided file descriptor must point to a pipe |
450 | /// with the `CLOEXEC` flag set. |
451 | #[stable (feature = "child_stream_from_fd" , since = "1.74.0" )] |
452 | impl From<OwnedFd> for process::ChildStdin { |
453 | #[inline ] |
454 | fn from(fd: OwnedFd) -> process::ChildStdin { |
455 | let fd: FileDesc = sys::fd::FileDesc::from_inner(fd); |
456 | let pipe: AnonPipe = sys::pipe::AnonPipe::from_inner(fd); |
457 | process::ChildStdin::from_inner(pipe) |
458 | } |
459 | } |
460 | |
461 | #[stable (feature = "io_safety" , since = "1.63.0" )] |
462 | impl AsFd for crate::process::ChildStdout { |
463 | #[inline ] |
464 | fn as_fd(&self) -> BorrowedFd<'_> { |
465 | self.as_inner().as_fd() |
466 | } |
467 | } |
468 | |
469 | #[stable (feature = "io_safety" , since = "1.63.0" )] |
470 | impl From<crate::process::ChildStdout> for OwnedFd { |
471 | /// Takes ownership of a [`ChildStdout`](crate::process::ChildStdout)'s file descriptor. |
472 | #[inline ] |
473 | fn from(child_stdout: crate::process::ChildStdout) -> OwnedFd { |
474 | child_stdout.into_inner().into_inner().into_inner() |
475 | } |
476 | } |
477 | |
478 | /// Create a `ChildStdout` from the provided `OwnedFd`. |
479 | /// |
480 | /// The provided file descriptor must point to a pipe |
481 | /// with the `CLOEXEC` flag set. |
482 | #[stable (feature = "child_stream_from_fd" , since = "1.74.0" )] |
483 | impl From<OwnedFd> for process::ChildStdout { |
484 | #[inline ] |
485 | fn from(fd: OwnedFd) -> process::ChildStdout { |
486 | let fd: FileDesc = sys::fd::FileDesc::from_inner(fd); |
487 | let pipe: AnonPipe = sys::pipe::AnonPipe::from_inner(fd); |
488 | process::ChildStdout::from_inner(pipe) |
489 | } |
490 | } |
491 | |
492 | #[stable (feature = "io_safety" , since = "1.63.0" )] |
493 | impl AsFd for crate::process::ChildStderr { |
494 | #[inline ] |
495 | fn as_fd(&self) -> BorrowedFd<'_> { |
496 | self.as_inner().as_fd() |
497 | } |
498 | } |
499 | |
500 | #[stable (feature = "io_safety" , since = "1.63.0" )] |
501 | impl From<crate::process::ChildStderr> for OwnedFd { |
502 | /// Takes ownership of a [`ChildStderr`](crate::process::ChildStderr)'s file descriptor. |
503 | #[inline ] |
504 | fn from(child_stderr: crate::process::ChildStderr) -> OwnedFd { |
505 | child_stderr.into_inner().into_inner().into_inner() |
506 | } |
507 | } |
508 | |
509 | /// Create a `ChildStderr` from the provided `OwnedFd`. |
510 | /// |
511 | /// The provided file descriptor must point to a pipe |
512 | /// with the `CLOEXEC` flag set. |
513 | #[stable (feature = "child_stream_from_fd" , since = "1.74.0" )] |
514 | impl From<OwnedFd> for process::ChildStderr { |
515 | #[inline ] |
516 | fn from(fd: OwnedFd) -> process::ChildStderr { |
517 | let fd: FileDesc = sys::fd::FileDesc::from_inner(fd); |
518 | let pipe: AnonPipe = sys::pipe::AnonPipe::from_inner(fd); |
519 | process::ChildStderr::from_inner(pipe) |
520 | } |
521 | } |
522 | |
523 | /// Returns the OS-assigned process identifier associated with this process's parent. |
524 | #[must_use ] |
525 | #[stable (feature = "unix_ppid" , since = "1.27.0" )] |
526 | pub fn parent_id() -> u32 { |
527 | crate::sys::os::getppid() |
528 | } |
529 | |