Skip to main content

nix/
spawn.rs

1//! Safe wrappers around posix_spawn* functions found in the libc "spawn.h" header.
2
3use std::{ffi::CStr, mem, os::fd::RawFd};
4
5#[cfg(any(feature = "fs", feature = "term"))]
6use crate::fcntl::OFlag;
7#[cfg(feature = "signal")]
8use crate::sys::signal::SigSet;
9#[cfg(feature = "fs")]
10use crate::sys::stat::Mode;
11use crate::{errno::Errno, unistd::Pid, NixPath, Result};
12
13/// The posix_spawn* functions return 0 on success and an error number on
14/// failure, rather than -1 with `errno` set.
15fn spawn_result(res: libc::c_int) -> Result<()> {
16    if res == 0 {
17        Ok(())
18    } else {
19        Err(Errno::from_raw(res))
20    }
21}
22
23/// A spawn attributes object. See [posix_spawnattr_t](https://pubs.opengroup.org/onlinepubs/9699919799/functions/posix_spawnattr_init.html).
24#[repr(transparent)]
25#[derive(Debug)]
26pub struct PosixSpawnAttr {
27    attr: libc::posix_spawnattr_t,
28}
29
30impl PosixSpawnAttr {
31    /// Initialize the spawn attributes object. See
32    /// [posix_spawnattr_init](https://pubs.opengroup.org/onlinepubs/9699919799/functions/posix_spawnattr_init.html).
33    #[doc(alias("posix_spawnattr_init"))]
34    pub fn init() -> Result<PosixSpawnAttr> {
35        let mut attr = mem::MaybeUninit::uninit();
36        let res = unsafe { libc::posix_spawnattr_init(attr.as_mut_ptr()) };
37
38        spawn_result(res)?;
39
40        let attr = unsafe { attr.assume_init() };
41        Ok(PosixSpawnAttr { attr })
42    }
43
44    /// Reinitialize the spawn attributes object.
45    /// This is a wrapper around
46    /// [posix_spawnattr_destroy](https://pubs.opengroup.org/onlinepubs/9699919799/functions/posix_spawnattr_destroy.html)
47    /// followed by
48    /// [posix_spawnattr_init](https://pubs.opengroup.org/onlinepubs/9699919799/functions/posix_spawnattr_init.html).
49    #[doc(alias("posix_spawnattr_destroy"))]
50    pub fn reinit(mut self) -> Result<PosixSpawnAttr> {
51        let res = unsafe {
52            libc::posix_spawnattr_destroy(
53                &mut self.attr as *mut libc::posix_spawnattr_t,
54            )
55        };
56        spawn_result(res)?;
57
58        let res = unsafe {
59            libc::posix_spawnattr_init(
60                &mut self.attr as *mut libc::posix_spawnattr_t,
61            )
62        };
63        spawn_result(res)?;
64
65        Ok(self)
66    }
67
68    /// Set spawn flags. See
69    /// [posix_spawnattr_setflags](https://pubs.opengroup.org/onlinepubs/9699919799/functions/posix_spawnattr_setflags.html).
70    #[doc(alias("posix_spawnattr_setflags"))]
71    pub fn set_flags(&mut self, flags: PosixSpawnFlags) -> Result<()> {
72        let res = unsafe {
73            libc::posix_spawnattr_setflags(
74                &mut self.attr as *mut libc::posix_spawnattr_t,
75                flags.bits() as libc::c_short,
76            )
77        };
78        spawn_result(res)?;
79
80        Ok(())
81    }
82
83    /// Get spawn flags. See
84    /// [posix_spawnattr_getflags](https://pubs.opengroup.org/onlinepubs/9699919799/functions/posix_spawnattr_getflags.html).
85    #[doc(alias("posix_spawnattr_getflags"))]
86    pub fn flags(&self) -> Result<PosixSpawnFlags> {
87        let mut flags: libc::c_short = 0;
88        let res = unsafe {
89            libc::posix_spawnattr_getflags(
90                &self.attr as *const libc::posix_spawnattr_t,
91                &mut flags,
92            )
93        };
94        spawn_result(res)?;
95
96        Ok(PosixSpawnFlags::from_bits_truncate(flags.into()))
97    }
98
99    /// Set spawn pgroup. See
100    /// [posix_spawnattr_setpgroup](https://pubs.opengroup.org/onlinepubs/9699919799/functions/posix_spawnattr_setpgroup.html).
101    #[doc(alias("posix_spawnattr_setpgroup"))]
102    pub fn set_pgroup(&mut self, pgroup: Pid) -> Result<()> {
103        let res = unsafe {
104            libc::posix_spawnattr_setpgroup(
105                &mut self.attr as *mut libc::posix_spawnattr_t,
106                pgroup.as_raw(),
107            )
108        };
109        spawn_result(res)?;
110
111        Ok(())
112    }
113
114    /// Get spawn pgroup. See
115    /// [posix_spawnattr_getpgroup](https://pubs.opengroup.org/onlinepubs/9699919799/functions/posix_spawnattr_getpgroup.html).
116    #[doc(alias("posix_spawnattr_getpgroup"))]
117    pub fn pgroup(&self) -> Result<Pid> {
118        let mut pid: libc::pid_t = 0;
119
120        let res = unsafe {
121            libc::posix_spawnattr_getpgroup(
122                &self.attr as *const libc::posix_spawnattr_t,
123                &mut pid,
124            )
125        };
126        spawn_result(res)?;
127
128        Ok(Pid::from_raw(pid))
129    }
130
131    feature! {
132    #![feature = "signal"]
133    /// Set spawn sigdefault. See
134    /// [posix_spawnattr_setsigdefault](https://pubs.opengroup.org/onlinepubs/9699919799/functions/posix_spawnattr_setsigdefault.html).
135    #[doc(alias("posix_spawnattr_setsigdefault"))]
136    pub fn set_sigdefault(&mut self, sigdefault: &SigSet) -> Result<()> {
137        let res = unsafe {
138            libc::posix_spawnattr_setsigdefault(
139                &mut self.attr as *mut libc::posix_spawnattr_t,
140                sigdefault.as_ref(),
141            )
142        };
143        spawn_result(res)?;
144
145        Ok(())
146    }
147
148    /// Get spawn sigdefault. See
149    /// [posix_spawnattr_getsigdefault](https://pubs.opengroup.org/onlinepubs/9699919799/functions/posix_spawnattr_getsigdefault.html).
150    #[doc(alias("posix_spawnattr_getsigdefault"))]
151    pub fn sigdefault(&self) -> Result<SigSet> {
152        let mut sigset = mem::MaybeUninit::uninit();
153
154        let res = unsafe {
155            libc::posix_spawnattr_getsigdefault(
156                &self.attr as *const libc::posix_spawnattr_t,
157                sigset.as_mut_ptr(),
158            )
159        };
160        spawn_result(res)?;
161
162        let sigdefault =
163            unsafe { SigSet::from_sigset_t_unchecked(sigset.assume_init()) };
164        Ok(sigdefault)
165    }
166
167    /// Set spawn sigmask. See
168    /// [posix_spawnattr_setsigmask](https://pubs.opengroup.org/onlinepubs/9699919799/functions/posix_spawnattr_setsigmask.html).
169    #[doc(alias("posix_spawnattr_setsigmask"))]
170    pub fn set_sigmask(&mut self, sigdefault: &SigSet) -> Result<()> {
171        let res = unsafe {
172            libc::posix_spawnattr_setsigmask(
173                &mut self.attr as *mut libc::posix_spawnattr_t,
174                sigdefault.as_ref(),
175            )
176        };
177        spawn_result(res)?;
178
179        Ok(())
180    }
181
182    /// Get spawn sigmask. See
183    /// [posix_spawnattr_getsigmask](https://pubs.opengroup.org/onlinepubs/9699919799/functions/posix_spawnattr_getsigmask.html).
184    #[doc(alias("posix_spawnattr_getsigmask"))]
185    pub fn sigmask(&self) -> Result<SigSet> {
186        let mut sigset = mem::MaybeUninit::uninit();
187
188        let res = unsafe {
189            libc::posix_spawnattr_getsigmask(
190                &self.attr as *const libc::posix_spawnattr_t,
191                sigset.as_mut_ptr(),
192            )
193        };
194        spawn_result(res)?;
195
196        let sigdefault =
197            unsafe { SigSet::from_sigset_t_unchecked(sigset.assume_init()) };
198        Ok(sigdefault)
199    }
200    }
201}
202
203impl Drop for PosixSpawnAttr {
204    fn drop(&mut self) {
205        unsafe {
206            libc::posix_spawnattr_destroy(
207                &mut self.attr as *mut libc::posix_spawnattr_t,
208            );
209        }
210    }
211}
212
213libc_bitflags!(
214    /// Process attributes to be changed in the new process image when invoking [`posix_spawn`]
215    /// or [`posix_spawnp`]. See
216    /// [posix_spawn](https://pubs.opengroup.org/onlinepubs/9699919799/functions/posix_spawn.html).
217    pub struct PosixSpawnFlags: libc::c_int {
218        /// Reset effective user ID of the child process to parent's real user ID.
219        POSIX_SPAWN_RESETIDS;
220        /// Put the child in a process group specified by the spawn-pgroup attribute. See
221        /// [posix_spawnattr_setpgroup](https://pubs.opengroup.org/onlinepubs/9699919799/functions/posix_spawnattr_setpgroup.html).
222        POSIX_SPAWN_SETPGROUP;
223        /// Force set signals to default signal handling in child process. See
224        /// [posix_spawnattr_setsigdefault](https://pubs.opengroup.org/onlinepubs/9699919799/functions/posix_spawnattr_setsigdefault.html).
225        #[cfg(feature = "signal")]
226        POSIX_SPAWN_SETSIGDEF;
227        /// Set signal mask of child process. See
228        /// [posix_spawnattr_setsigmask](https://pubs.opengroup.org/onlinepubs/9699919799/functions/posix_spawnattr_setsigmask.html).
229        #[cfg(feature = "signal")]
230        POSIX_SPAWN_SETSIGMASK;
231        // TODO: Add support for the following two flags whenever support for
232        // https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/sched.h.html
233        // is added to nix.
234        // POSIX_SPAWN_SETSCHEDPARAM;
235        // POSIX_SPAWN_SETSCHEDULER;
236    }
237);
238
239/// A spawn file actions object. See [posix_spawn_file_actions_t](https://pubs.opengroup.org/onlinepubs/9699919799/functions/posix_spawn_file_actions_addclose.html).
240#[repr(transparent)]
241#[derive(Debug)]
242pub struct PosixSpawnFileActions {
243    fa: libc::posix_spawn_file_actions_t,
244}
245
246impl PosixSpawnFileActions {
247    /// Initialize the spawn file actions object. See
248    /// [posix_spawn_file_actions_init](https://pubs.opengroup.org/onlinepubs/9699919799/functions/posix_spawn_file_actions_init.html).
249    #[doc(alias("posix_spawn_file_actions_init"))]
250    pub fn init() -> Result<PosixSpawnFileActions> {
251        let mut actions = mem::MaybeUninit::uninit();
252        let res = unsafe {
253            libc::posix_spawn_file_actions_init(actions.as_mut_ptr())
254        };
255        spawn_result(res)?;
256        Ok(unsafe {
257            PosixSpawnFileActions {
258                fa: actions.assume_init(),
259            }
260        })
261    }
262
263    /// Reinitialize the spawn file actions object.
264    /// This is a wrapper around
265    /// [posix_spawn_file_actions_destroy](https://pubs.opengroup.org/onlinepubs/9699919799/functions/posix_spawn_file_actions_destroy.html).
266    /// followed by
267    /// [posix_spawn_file_actions_init](https://pubs.opengroup.org/onlinepubs/9699919799/functions/posix_spawn_file_actions_init.html).
268    #[doc(alias("posix_spawn_file_actions_destroy"))]
269    pub fn reinit(mut self) -> Result<PosixSpawnFileActions> {
270        let res = unsafe {
271            libc::posix_spawn_file_actions_destroy(
272                &mut self.fa as *mut libc::posix_spawn_file_actions_t,
273            )
274        };
275        spawn_result(res)?;
276
277        let res = unsafe {
278            libc::posix_spawn_file_actions_init(
279                &mut self.fa as *mut libc::posix_spawn_file_actions_t,
280            )
281        };
282        spawn_result(res)?;
283
284        Ok(self)
285    }
286
287    /// Add a [dup2](https://pubs.opengroup.org/onlinepubs/9699919799/functions/dup2.html) action. See
288    /// [posix_spawn_file_actions_adddup2](https://pubs.opengroup.org/onlinepubs/9699919799/functions/posix_spawn_file_actions_adddup2.html).
289    #[doc(alias("posix_spawn_file_actions_adddup2"))]
290    pub fn add_dup2(&mut self, fd: RawFd, newfd: RawFd) -> Result<()> {
291        let res = unsafe {
292            libc::posix_spawn_file_actions_adddup2(
293                &mut self.fa as *mut libc::posix_spawn_file_actions_t,
294                fd,
295                newfd,
296            )
297        };
298        spawn_result(res)?;
299
300        Ok(())
301    }
302
303    feature! {
304    #![all(feature = "fs", feature = "term")]
305    /// Add an open action. See
306    /// [posix_spawn_file_actions_addopen](https://pubs.opengroup.org/onlinepubs/9699919799/functions/posix_spawn_file_actions_addopen.html).
307    #[doc(alias("posix_spawn_file_actions_addopen"))]
308    pub fn add_open<P: ?Sized + NixPath>(
309        &mut self,
310        fd: RawFd,
311        path: &P,
312        oflag: OFlag,
313        mode: Mode,
314    ) -> Result<()> {
315        let res = path.with_nix_path(|cstr| unsafe {
316            libc::posix_spawn_file_actions_addopen(
317                &mut self.fa as *mut libc::posix_spawn_file_actions_t,
318                fd,
319                cstr.as_ptr(),
320                oflag.bits(),
321                mode.bits(),
322            )
323        })?;
324        spawn_result(res)?;
325
326        Ok(())
327    }
328    }
329
330    /// Add a close action. See
331    /// [posix_spawn_file_actions_addclose](https://pubs.opengroup.org/onlinepubs/9699919799/functions/posix_spawn_file_actions_addclose.html).
332    #[doc(alias("posix_spawn_file_actions_addclose"))]
333    pub fn add_close(&mut self, fd: RawFd) -> Result<()> {
334        let res = unsafe {
335            libc::posix_spawn_file_actions_addclose(
336                &mut self.fa as *mut libc::posix_spawn_file_actions_t,
337                fd,
338            )
339        };
340        spawn_result(res)?;
341
342        Ok(())
343    }
344}
345
346impl Drop for PosixSpawnFileActions {
347    fn drop(&mut self) {
348        unsafe {
349            libc::posix_spawn_file_actions_destroy(
350                &mut self.fa as *mut libc::posix_spawn_file_actions_t,
351            );
352        }
353    }
354}
355
356// The POSIX standard requires those `args` and `envp` to be of type `*const *mut [c_char]`,
357// but implementations won't modify them, making the `mut` type redundant. Considering this,
358// Nix does not expose this mutability, but we have to change the interface when calling the
359// underlying libc interfaces , this helper function does the conversion job.
360//
361// SAFETY:
362// It is safe to add the mutability in types as implementations won't mutable them.
363unsafe fn to_exec_array<S: AsRef<CStr>>(args: &[S]) -> Vec<*mut libc::c_char> {
364    let mut v: Vec<*mut libc::c_char> = args
365        .iter()
366        .map(|s| s.as_ref().as_ptr().cast_mut())
367        .collect();
368    v.push(std::ptr::null_mut());
369    v
370}
371
372/// Create a new child process from the specified process image. See
373/// [posix_spawn](https://pubs.opengroup.org/onlinepubs/9699919799/functions/posix_spawn.html).
374pub fn posix_spawn<P, SA, SE>(
375    path: &P,
376    file_actions: &PosixSpawnFileActions,
377    attr: &PosixSpawnAttr,
378    args: &[SA],
379    envp: &[SE],
380) -> Result<Pid>
381where
382    P: NixPath + ?Sized,
383    SA: AsRef<CStr>,
384    SE: AsRef<CStr>,
385{
386    let mut pid = 0;
387
388    let ret = unsafe {
389        let args_p = to_exec_array(args);
390        let env_p = to_exec_array(envp);
391
392        path.with_nix_path(|c_str| {
393            libc::posix_spawn(
394                &mut pid as *mut libc::pid_t,
395                c_str.as_ptr(),
396                &file_actions.fa as *const libc::posix_spawn_file_actions_t,
397                &attr.attr as *const libc::posix_spawnattr_t,
398                args_p.as_ptr(),
399                env_p.as_ptr(),
400            )
401        })?
402    };
403
404    if ret != 0 {
405        return Err(Errno::from_raw(ret));
406    }
407
408    Ok(Pid::from_raw(pid))
409}
410
411/// Create a new child process from the specified process image. See
412/// [posix_spawnp](https://pubs.opengroup.org/onlinepubs/9699919799/functions/posix_spawnp.html).
413pub fn posix_spawnp<SA: AsRef<CStr>, SE: AsRef<CStr>>(
414    path: &CStr,
415    file_actions: &PosixSpawnFileActions,
416    attr: &PosixSpawnAttr,
417    args: &[SA],
418    envp: &[SE],
419) -> Result<Pid> {
420    let mut pid = 0;
421
422    let ret = unsafe {
423        let args_p = to_exec_array(args);
424        let env_p = to_exec_array(envp);
425
426        libc::posix_spawnp(
427            &mut pid as *mut libc::pid_t,
428            path.as_ptr(),
429            &file_actions.fa as *const libc::posix_spawn_file_actions_t,
430            &attr.attr as *const libc::posix_spawnattr_t,
431            args_p.as_ptr(),
432            env_p.as_ptr(),
433        )
434    };
435
436    if ret != 0 {
437        return Err(Errno::from_raw(ret));
438    }
439
440    Ok(Pid::from_raw(pid))
441}