]> git.proxmox.com Git - rustc.git/blob - library/std/src/os/unix/process.rs
New upstream version 1.55.0+dfsg1
[rustc.git] / library / std / src / os / unix / process.rs
1 //! Unix-specific extensions to primitives in the `std::process` module.
2
3 #![stable(feature = "rust1", since = "1.0.0")]
4
5 use crate::ffi::OsStr;
6 use crate::io;
7 use crate::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd};
8 use crate::process;
9 use crate::sealed::Sealed;
10 use crate::sys;
11 use crate::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner};
12
13 /// Unix-specific extensions to the [`process::Command`] builder.
14 ///
15 /// This trait is sealed: it cannot be implemented outside the standard library.
16 /// This is so that future additional methods are not breaking changes.
17 #[stable(feature = "rust1", since = "1.0.0")]
18 pub trait CommandExt: Sealed {
19 /// Sets the child process's user ID. This translates to a
20 /// `setuid` call in the child process. Failure in the `setuid`
21 /// call will cause the spawn to fail.
22 #[stable(feature = "rust1", since = "1.0.0")]
23 fn uid(
24 &mut self,
25 #[cfg(not(target_os = "vxworks"))] id: u32,
26 #[cfg(target_os = "vxworks")] id: u16,
27 ) -> &mut process::Command;
28
29 /// Similar to `uid`, but sets the group ID of the child process. This has
30 /// the same semantics as the `uid` field.
31 #[stable(feature = "rust1", since = "1.0.0")]
32 fn gid(
33 &mut self,
34 #[cfg(not(target_os = "vxworks"))] id: u32,
35 #[cfg(target_os = "vxworks")] id: u16,
36 ) -> &mut process::Command;
37
38 /// Sets the supplementary group IDs for the calling process. Translates to
39 /// a `setgroups` call in the child process.
40 #[unstable(feature = "setgroups", issue = "38527", reason = "")]
41 fn groups(
42 &mut self,
43 #[cfg(not(target_os = "vxworks"))] groups: &[u32],
44 #[cfg(target_os = "vxworks")] groups: &[u16],
45 ) -> &mut process::Command;
46
47 /// Schedules a closure to be run just before the `exec` function is
48 /// invoked.
49 ///
50 /// The closure is allowed to return an I/O error whose OS error code will
51 /// be communicated back to the parent and returned as an error from when
52 /// the spawn was requested.
53 ///
54 /// Multiple closures can be registered and they will be called in order of
55 /// their registration. If a closure returns `Err` then no further closures
56 /// will be called and the spawn operation will immediately return with a
57 /// failure.
58 ///
59 /// # Notes and Safety
60 ///
61 /// This closure will be run in the context of the child process after a
62 /// `fork`. This primarily means that any modifications made to memory on
63 /// behalf of this closure will **not** be visible to the parent process.
64 /// This is often a very constrained environment where normal operations
65 /// like `malloc`, accessing environment variables through [`std::env`]
66 /// or acquiring a mutex are not guaranteed to work (due to
67 /// other threads perhaps still running when the `fork` was run).
68 ///
69 /// For further details refer to the [POSIX fork() specification]
70 /// and the equivalent documentation for any targeted
71 /// platform, especially the requirements around *async-signal-safety*.
72 ///
73 /// This also means that all resources such as file descriptors and
74 /// memory-mapped regions got duplicated. It is your responsibility to make
75 /// sure that the closure does not violate library invariants by making
76 /// invalid use of these duplicates.
77 ///
78 /// Panicking in the closure is safe only if all the format arguments for the
79 /// panic message can be safely formatted; this is because although
80 /// `Command` calls [`std::panic::always_abort`](crate::panic::always_abort)
81 /// before calling the pre_exec hook, panic will still try to format the
82 /// panic message.
83 ///
84 /// When this closure is run, aspects such as the stdio file descriptors and
85 /// working directory have successfully been changed, so output to these
86 /// locations may not appear where intended.
87 ///
88 /// [POSIX fork() specification]:
89 /// https://pubs.opengroup.org/onlinepubs/9699919799/functions/fork.html
90 /// [`std::env`]: mod@crate::env
91 #[stable(feature = "process_pre_exec", since = "1.34.0")]
92 unsafe fn pre_exec<F>(&mut self, f: F) -> &mut process::Command
93 where
94 F: FnMut() -> io::Result<()> + Send + Sync + 'static;
95
96 /// Schedules a closure to be run just before the `exec` function is
97 /// invoked.
98 ///
99 /// This method is stable and usable, but it should be unsafe. To fix
100 /// that, it got deprecated in favor of the unsafe [`pre_exec`].
101 ///
102 /// [`pre_exec`]: CommandExt::pre_exec
103 #[stable(feature = "process_exec", since = "1.15.0")]
104 #[rustc_deprecated(since = "1.37.0", reason = "should be unsafe, use `pre_exec` instead")]
105 fn before_exec<F>(&mut self, f: F) -> &mut process::Command
106 where
107 F: FnMut() -> io::Result<()> + Send + Sync + 'static,
108 {
109 unsafe { self.pre_exec(f) }
110 }
111
112 /// Performs all the required setup by this `Command`, followed by calling
113 /// the `execvp` syscall.
114 ///
115 /// On success this function will not return, and otherwise it will return
116 /// an error indicating why the exec (or another part of the setup of the
117 /// `Command`) failed.
118 ///
119 /// `exec` not returning has the same implications as calling
120 /// [`process::exit`] – no destructors on the current stack or any other
121 /// thread’s stack will be run. Therefore, it is recommended to only call
122 /// `exec` at a point where it is fine to not run any destructors. Note,
123 /// that the `execvp` syscall independently guarantees that all memory is
124 /// freed and all file descriptors with the `CLOEXEC` option (set by default
125 /// on all file descriptors opened by the standard library) are closed.
126 ///
127 /// This function, unlike `spawn`, will **not** `fork` the process to create
128 /// a new child. Like spawn, however, the default behavior for the stdio
129 /// descriptors will be to inherited from the current process.
130 ///
131 /// # Notes
132 ///
133 /// The process may be in a "broken state" if this function returns in
134 /// error. For example the working directory, environment variables, signal
135 /// handling settings, various user/group information, or aspects of stdio
136 /// file descriptors may have changed. If a "transactional spawn" is
137 /// required to gracefully handle errors it is recommended to use the
138 /// cross-platform `spawn` instead.
139 #[stable(feature = "process_exec2", since = "1.9.0")]
140 fn exec(&mut self) -> io::Error;
141
142 /// Set executable argument
143 ///
144 /// Set the first process argument, `argv[0]`, to something other than the
145 /// default executable path.
146 #[stable(feature = "process_set_argv0", since = "1.45.0")]
147 fn arg0<S>(&mut self, arg: S) -> &mut process::Command
148 where
149 S: AsRef<OsStr>;
150 }
151
152 #[stable(feature = "rust1", since = "1.0.0")]
153 impl CommandExt for process::Command {
154 fn uid(
155 &mut self,
156 #[cfg(not(target_os = "vxworks"))] id: u32,
157 #[cfg(target_os = "vxworks")] id: u16,
158 ) -> &mut process::Command {
159 self.as_inner_mut().uid(id);
160 self
161 }
162
163 fn gid(
164 &mut self,
165 #[cfg(not(target_os = "vxworks"))] id: u32,
166 #[cfg(target_os = "vxworks")] id: u16,
167 ) -> &mut process::Command {
168 self.as_inner_mut().gid(id);
169 self
170 }
171
172 fn groups(
173 &mut self,
174 #[cfg(not(target_os = "vxworks"))] groups: &[u32],
175 #[cfg(target_os = "vxworks")] groups: &[u16],
176 ) -> &mut process::Command {
177 self.as_inner_mut().groups(groups);
178 self
179 }
180
181 unsafe fn pre_exec<F>(&mut self, f: F) -> &mut process::Command
182 where
183 F: FnMut() -> io::Result<()> + Send + Sync + 'static,
184 {
185 self.as_inner_mut().pre_exec(Box::new(f));
186 self
187 }
188
189 fn exec(&mut self) -> io::Error {
190 // NOTE: This may *not* be safe to call after `libc::fork`, because it
191 // may allocate. That may be worth fixing at some point in the future.
192 self.as_inner_mut().exec(sys::process::Stdio::Inherit)
193 }
194
195 fn arg0<S>(&mut self, arg: S) -> &mut process::Command
196 where
197 S: AsRef<OsStr>,
198 {
199 self.as_inner_mut().set_arg_0(arg.as_ref());
200 self
201 }
202 }
203
204 /// Unix-specific extensions to [`process::ExitStatus`] and
205 /// [`ExitStatusError`](process::ExitStatusError).
206 ///
207 /// On Unix, `ExitStatus` **does not necessarily represent an exit status**, as
208 /// passed to the `exit` system call or returned by
209 /// [`ExitStatus::code()`](crate::process::ExitStatus::code). It represents **any wait status**
210 /// as returned by one of the `wait` family of system
211 /// calls.
212 ///
213 /// A Unix wait status (a Rust `ExitStatus`) can represent a Unix exit status, but can also
214 /// represent other kinds of process event.
215 ///
216 /// This trait is sealed: it cannot be implemented outside the standard library.
217 /// This is so that future additional methods are not breaking changes.
218 #[stable(feature = "rust1", since = "1.0.0")]
219 pub trait ExitStatusExt: Sealed {
220 /// Creates a new `ExitStatus` or `ExitStatusError` from the raw underlying integer status
221 /// value from `wait`
222 ///
223 /// The value should be a **wait status, not an exit status**.
224 ///
225 /// # Panics
226 ///
227 /// Panics on an attempt to make an `ExitStatusError` from a wait status of `0`.
228 ///
229 /// Making an `ExitStatus` always succeeds and never panics.
230 #[stable(feature = "exit_status_from", since = "1.12.0")]
231 fn from_raw(raw: i32) -> Self;
232
233 /// If the process was terminated by a signal, returns that signal.
234 ///
235 /// In other words, if `WIFSIGNALED`, this returns `WTERMSIG`.
236 #[stable(feature = "rust1", since = "1.0.0")]
237 fn signal(&self) -> Option<i32>;
238
239 /// If the process was terminated by a signal, says whether it dumped core.
240 #[unstable(feature = "unix_process_wait_more", issue = "80695")]
241 fn core_dumped(&self) -> bool;
242
243 /// If the process was stopped by a signal, returns that signal.
244 ///
245 /// In other words, if `WIFSTOPPED`, this returns `WSTOPSIG`. This is only possible if the status came from
246 /// a `wait` system call which was passed `WUNTRACED`, and was then converted into an `ExitStatus`.
247 #[unstable(feature = "unix_process_wait_more", issue = "80695")]
248 fn stopped_signal(&self) -> Option<i32>;
249
250 /// Whether the process was continued from a stopped status.
251 ///
252 /// Ie, `WIFCONTINUED`. This is only possible if the status came from a `wait` system call
253 /// which was passed `WCONTINUED`, and was then converted into an `ExitStatus`.
254 #[unstable(feature = "unix_process_wait_more", issue = "80695")]
255 fn continued(&self) -> bool;
256
257 /// Returns the underlying raw `wait` status.
258 ///
259 /// The returned integer is a **wait status, not an exit status**.
260 #[unstable(feature = "unix_process_wait_more", issue = "80695")]
261 fn into_raw(self) -> i32;
262 }
263
264 #[stable(feature = "rust1", since = "1.0.0")]
265 impl ExitStatusExt for process::ExitStatus {
266 fn from_raw(raw: i32) -> Self {
267 process::ExitStatus::from_inner(From::from(raw))
268 }
269
270 fn signal(&self) -> Option<i32> {
271 self.as_inner().signal()
272 }
273
274 fn core_dumped(&self) -> bool {
275 self.as_inner().core_dumped()
276 }
277
278 fn stopped_signal(&self) -> Option<i32> {
279 self.as_inner().stopped_signal()
280 }
281
282 fn continued(&self) -> bool {
283 self.as_inner().continued()
284 }
285
286 fn into_raw(self) -> i32 {
287 self.as_inner().into_raw().into()
288 }
289 }
290
291 #[unstable(feature = "exit_status_error", issue = "84908")]
292 impl ExitStatusExt for process::ExitStatusError {
293 fn from_raw(raw: i32) -> Self {
294 process::ExitStatus::from_raw(raw)
295 .exit_ok()
296 .expect_err("<ExitStatusError as ExitStatusExt>::from_raw(0) but zero is not an error")
297 }
298
299 fn signal(&self) -> Option<i32> {
300 self.into_status().signal()
301 }
302
303 fn core_dumped(&self) -> bool {
304 self.into_status().core_dumped()
305 }
306
307 fn stopped_signal(&self) -> Option<i32> {
308 self.into_status().stopped_signal()
309 }
310
311 fn continued(&self) -> bool {
312 self.into_status().continued()
313 }
314
315 fn into_raw(self) -> i32 {
316 self.into_status().into_raw()
317 }
318 }
319
320 #[stable(feature = "process_extensions", since = "1.2.0")]
321 impl FromRawFd for process::Stdio {
322 #[inline]
323 unsafe fn from_raw_fd(fd: RawFd) -> process::Stdio {
324 let fd = sys::fd::FileDesc::new(fd);
325 let io = sys::process::Stdio::Fd(fd);
326 process::Stdio::from_inner(io)
327 }
328 }
329
330 #[stable(feature = "process_extensions", since = "1.2.0")]
331 impl AsRawFd for process::ChildStdin {
332 #[inline]
333 fn as_raw_fd(&self) -> RawFd {
334 self.as_inner().fd().raw()
335 }
336 }
337
338 #[stable(feature = "process_extensions", since = "1.2.0")]
339 impl AsRawFd for process::ChildStdout {
340 #[inline]
341 fn as_raw_fd(&self) -> RawFd {
342 self.as_inner().fd().raw()
343 }
344 }
345
346 #[stable(feature = "process_extensions", since = "1.2.0")]
347 impl AsRawFd for process::ChildStderr {
348 #[inline]
349 fn as_raw_fd(&self) -> RawFd {
350 self.as_inner().fd().raw()
351 }
352 }
353
354 #[stable(feature = "into_raw_os", since = "1.4.0")]
355 impl IntoRawFd for process::ChildStdin {
356 #[inline]
357 fn into_raw_fd(self) -> RawFd {
358 self.into_inner().into_fd().into_raw()
359 }
360 }
361
362 #[stable(feature = "into_raw_os", since = "1.4.0")]
363 impl IntoRawFd for process::ChildStdout {
364 #[inline]
365 fn into_raw_fd(self) -> RawFd {
366 self.into_inner().into_fd().into_raw()
367 }
368 }
369
370 #[stable(feature = "into_raw_os", since = "1.4.0")]
371 impl IntoRawFd for process::ChildStderr {
372 #[inline]
373 fn into_raw_fd(self) -> RawFd {
374 self.into_inner().into_fd().into_raw()
375 }
376 }
377
378 /// Returns the OS-assigned process identifier associated with this process's parent.
379 #[stable(feature = "unix_ppid", since = "1.27.0")]
380 pub fn parent_id() -> u32 {
381 crate::sys::os::getppid()
382 }