Skip to content

Commit b3dfcc5

Browse files
committed
Add Linux-specific pidfd process extensions
Background: Over the last year, pidfd support was added to the Linux kernel. This allows interacting with other processes. In particular, this allows waiting on a child process with a timeout in a race-free way, bypassing all of the awful signal-handler tricks that are usually required. Pidfds can be obtained for a child process (as well as any other process) via the `pidfd_open` syscall. Unfortunately, this requires several conditions to hold in order to be race-free (i.e. the pid is not reused). Per `man pidfd_open`: ``` · the disposition of SIGCHLD has not been explicitly set to SIG_IGN (see sigaction(2)); · the SA_NOCLDWAIT flag was not specified while establishing a han‐ dler for SIGCHLD or while setting the disposition of that signal to SIG_DFL (see sigaction(2)); and · the zombie process was not reaped elsewhere in the program (e.g., either by an asynchronously executed signal handler or by wait(2) or similar in another thread). If any of these conditions does not hold, then the child process (along with a PID file descriptor that refers to it) should instead be created using clone(2) with the CLONE_PIDFD flag. ``` Sadly, these conditions are impossible to guarantee once any libraries are used. For example, C code runnng in a different thread could call `wait()`, which is impossible to detect from Rust code trying to open a pidfd. While pid reuse issues should (hopefully) be rare in practice, we can do better. By passing the `CLONE_PIDFD` flag to `clone()` or `clone3()`, we can obtain a pidfd for the child process in a guaranteed race-free manner. This PR: This PR adds Linux-specific process extension methods to allow obtaining pidfds for processes spawned via the standard `Command` API. Other than being made available to user code, the standard library does not make use of these pidfds in any way. In particular, the implementation of `Child::wait` is completely unchanged. Two Linux-specific helper methods are added: `CommandExt::create_pidfd` and `ChildExt::pidfd`. These methods are intended to serve as a building block for libraries to build higher-level abstractions - in particular, waiting on a process with a timeout. I've included a basic test, which verifies that pidfds are created iff the `create_pidfd` method is used. This test is somewhat special - it should always succeed on systems with the `clone3` system call available, and always fail on systems without `clone3` available. I'm not sure how to best ensure this programatically. This PR relies on the newer `clone3` system call to pass the `CLONE_FD`, rather than the older `clone` system call. `clone3` was added to Linux in the same release as pidfds, so this shouldn't unnecessarily limit the kernel versions that this code supports. Unresolved questions: * What should the name of the feature gate be for these newly added methods? * Should the `pidfd` method distinguish between an error occurring and `create_pidfd` not being called?
1 parent 5ddef54 commit b3dfcc5

File tree

6 files changed

+192
-19
lines changed

6 files changed

+192
-19
lines changed

library/std/src/os/linux/mod.rs

+1
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,5 @@
33
#![stable(feature = "raw_ext", since = "1.1.0")]
44

55
pub mod fs;
6+
pub mod process;
67
pub mod raw;

library/std/src/os/linux/process.rs

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
//! Linux-specific extensions to primitives in the `std::process` module.
2+
3+
#![unstable(feature = "linux_pidfd", issue = "none")]
4+
5+
use crate::process;
6+
use crate::sys_common::AsInnerMut;
7+
use crate::io::Result;
8+
9+
/// Os-specific extensions to [`process::Child`]
10+
///
11+
/// [`process::Child`]: crate::process::Child
12+
pub trait ChildExt {
13+
/// Obtains the pidfd created for this child process, if available.
14+
///
15+
/// A pidfd will only ever be available if `create_pidfd(true)` was called
16+
/// when the corresponding `Command` was created.
17+
///
18+
/// Even if `create_pidfd(true)` is called, a pidfd may not be available
19+
/// due to an older version of Linux being in use, or if
20+
/// some other error occured.
21+
///
22+
/// See `man pidfd_open` for more details about pidfds.
23+
fn pidfd(&self) -> Result<i32>;
24+
}
25+
26+
/// Os-specific extensions to [`process::Command`]
27+
///
28+
/// [`process::Command`]: crate::process::Command
29+
pub trait CommandExt {
30+
/// Sets whether or this `Command` will attempt to create a pidfd
31+
/// for the child. If this method is never called, a pidfd will
32+
/// not be crated.
33+
///
34+
/// The pidfd can be retrieved from the child via [`ChildExt::pidfd`]
35+
///
36+
/// A pidfd will only be created if it is possible to do so
37+
/// in a guaranteed race-free manner (e.g. if the `clone3` system call is
38+
/// supported). Otherwise, [`ChildExit::pidfd`] will return an error.
39+
fn create_pidfd(&mut self, val: bool) -> &mut process::Command;
40+
}
41+
42+
impl CommandExt for process::Command {
43+
fn create_pidfd(&mut self, val: bool) -> &mut process::Command {
44+
self.as_inner_mut().create_pidfd(val);
45+
self
46+
}
47+
}

library/std/src/process.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -161,7 +161,7 @@ use crate::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner};
161161
/// [`wait`]: Child::wait
162162
#[stable(feature = "process", since = "1.0.0")]
163163
pub struct Child {
164-
handle: imp::Process,
164+
pub(crate) handle: imp::Process,
165165

166166
/// The handle for writing to the child's standard input (stdin), if it has
167167
/// been captured. To avoid partially moving

library/std/src/sys/unix/process/process_common.rs

+5
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,7 @@ pub struct Command {
8888
stdin: Option<Stdio>,
8989
stdout: Option<Stdio>,
9090
stderr: Option<Stdio>,
91+
pub(crate) make_pidfd: bool,
9192
}
9293

9394
// Create a new type for argv, so that we can make it `Send` and `Sync`
@@ -149,6 +150,7 @@ impl Command {
149150
stdin: None,
150151
stdout: None,
151152
stderr: None,
153+
make_pidfd: false,
152154
}
153155
}
154156

@@ -181,6 +183,9 @@ impl Command {
181183
pub fn gid(&mut self, id: gid_t) {
182184
self.gid = Some(id);
183185
}
186+
pub fn create_pidfd(&mut self, val: bool) {
187+
self.make_pidfd = val;
188+
}
184189

185190
pub fn saw_nul(&self) -> bool {
186191
self.saw_nul

library/std/src/sys/unix/process/process_unix.rs

+111-18
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ use crate::ptr;
55
use crate::sys;
66
use crate::sys::cvt;
77
use crate::sys::process::process_common::*;
8+
use crate::sync::atomic::{AtomicBool, Ordering};
89

910
use libc::{c_int, gid_t, pid_t, uid_t};
1011

@@ -34,18 +35,7 @@ impl Command {
3435

3536
let (input, output) = sys::pipe::anon_pipe()?;
3637

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-
};
38+
let (result, pidfd) = self.do_fork()?;
4939

5040
let pid = unsafe {
5141
match result {
@@ -70,11 +60,11 @@ impl Command {
7060
rtassert!(output.write(&bytes).is_ok());
7161
libc::_exit(1)
7262
}
73-
n => n,
63+
n => n as pid_t,
7464
}
7565
};
7666

77-
let mut p = Process { pid, status: None };
67+
let mut p = Process { pid, status: None, pidfd };
7868
drop(output);
7969
let mut bytes = [0; 8];
8070

@@ -107,6 +97,95 @@ impl Command {
10797
}
10898
}
10999

100+
// Attempts to fork the process. If successful, returns
101+
// Ok((0, -1)) in the child, and Ok((child_pid, child_pidfd)) in the parent.
102+
fn do_fork(&mut self) -> Result<(libc::c_long, libc::pid_t), io::Error> {
103+
// Whatever happens after the fork is almost for sure going to touch or
104+
// look at thbe environment in one way or another (PATH in `execvp` or
105+
// accessing the `environ` pointer ourselves). Make sure no other thread
106+
// is accessing the environment when we do the fork itself.
107+
//
108+
// Note that as soon as we're done with the fork there's no need to hold
109+
// a lock any more because the parent won't do anything and the child is
110+
// in its own process.
111+
let _env_lock = unsafe { sys::os::env_lock() };
112+
113+
// If we fail to create a pidfd for any reason, this will
114+
// stay as -1, which indicates an error
115+
let mut pidfd: libc::pid_t = -1;
116+
117+
// On Linux, attempt to use the `clone3` syscall, which
118+
// supports more argument (in prarticular, the ability to create a pidfd).
119+
// If this fails, we will fall through this block to a call to `fork()`
120+
cfg_if::cfg_if! {
121+
if #[cfg(target_os = "linux")] {
122+
static HAS_CLONE3: AtomicBool = AtomicBool::new(true);
123+
124+
const CLONE_PIDFD: u64 = 0x00001000;
125+
126+
#[repr(C)]
127+
struct clone_args {
128+
flags: u64,
129+
pidfd: u64,
130+
child_tid: u64,
131+
parent_tid: u64,
132+
exit_signal: u64,
133+
stack: u64,
134+
stack_size: u64,
135+
tls: u64,
136+
set_tid: u64,
137+
set_tid_size: u64,
138+
cgroup: u64,
139+
}
140+
141+
syscall! {
142+
fn clone3(cl_args: *mut clone_args, len: libc::size_t) -> libc::c_long
143+
}
144+
145+
if HAS_CLONE3.load(Ordering::Relaxed) {
146+
let mut flags = 0;
147+
if self.make_pidfd {
148+
flags |= CLONE_PIDFD;
149+
}
150+
151+
let mut args = clone_args {
152+
flags,
153+
pidfd: &mut pidfd as *mut libc::pid_t as u64,
154+
child_tid: 0,
155+
parent_tid: 0,
156+
exit_signal: libc::SIGCHLD as u64,
157+
stack: 0,
158+
stack_size: 0,
159+
tls: 0,
160+
set_tid: 0,
161+
set_tid_size: 0,
162+
cgroup: 0
163+
};
164+
165+
let args_ptr = &mut args as *mut clone_args;
166+
let args_size = crate::mem::size_of::<clone_args>();
167+
168+
let res = cvt(unsafe { clone3(args_ptr, args_size) });
169+
match res {
170+
Ok(n) => return Ok((n, pidfd)),
171+
Err(e) => match e.raw_os_error() {
172+
// Multiple threads can race to execute this store,
173+
// but that's fine - that just means that multiple threads
174+
// will have tried and failed to execute the same syscall,
175+
// with no other side effects.
176+
Some(libc::ENOSYS) => HAS_CLONE3.store(false, Ordering::Relaxed),
177+
_ => return Err(e)
178+
}
179+
}
180+
}
181+
}
182+
}
183+
// If we get here, we are either not on Linux,
184+
// or we are on Linux and the 'clone3' syscall does not exist
185+
cvt(unsafe { libc::fork() }.into()).map(|res| (res, pidfd))
186+
}
187+
188+
110189
pub fn exec(&mut self, default: Stdio) -> io::Error {
111190
let envp = self.capture_env();
112191

@@ -252,8 +331,6 @@ impl Command {
252331
#[cfg(not(any(
253332
target_os = "macos",
254333
target_os = "freebsd",
255-
all(target_os = "linux", target_env = "gnu"),
256-
all(target_os = "linux", target_env = "musl"),
257334
)))]
258335
fn posix_spawn(
259336
&mut self,
@@ -268,8 +345,6 @@ impl Command {
268345
#[cfg(any(
269346
target_os = "macos",
270347
target_os = "freebsd",
271-
all(target_os = "linux", target_env = "gnu"),
272-
all(target_os = "linux", target_env = "musl"),
273348
))]
274349
fn posix_spawn(
275350
&mut self,
@@ -404,6 +479,12 @@ impl Command {
404479
pub struct Process {
405480
pid: pid_t,
406481
status: Option<ExitStatus>,
482+
// On Linux, stores the pidfd created for this child.
483+
// This is -1 if the user did not request pidfd creation,
484+
// or if the pidfd could not be created for some reason
485+
// (e.g. the `clone3` syscall was not available).
486+
#[cfg(target_os = "linux")]
487+
pidfd: libc::c_int,
407488
}
408489

409490
impl Process {
@@ -494,3 +575,15 @@ impl fmt::Display for ExitStatus {
494575
}
495576
}
496577
}
578+
579+
#[cfg(target_os = "linux")]
580+
#[unstable(feature = "linux_pidfd", issue = "none")]
581+
impl crate::os::linux::process::ChildExt for crate::process::Child {
582+
fn pidfd(&self) -> crate::io::Result<i32> {
583+
if self.handle.pidfd > 0 {
584+
Ok(self.handle.pidfd)
585+
} else {
586+
Err(crate::io::Error::from(crate::io::ErrorKind::Other))
587+
}
588+
}
589+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
// run-pass
2+
// linux-only - pidfds are a linux-specific concept
3+
4+
#![feature(linux_pidfd)]
5+
use std::os::linux::process::{CommandExt, ChildExt};
6+
use std::process::Command;
7+
8+
fn main() {
9+
// We don't assert the precise value, since the standard libarary
10+
// may be opened other file descriptors before our code ran.
11+
let _ = Command::new("echo")
12+
.create_pidfd(true)
13+
.spawn()
14+
.unwrap()
15+
.pidfd().expect("failed to obtain pidfd");
16+
17+
let _ = Command::new("echo")
18+
.create_pidfd(false)
19+
.spawn()
20+
.unwrap()
21+
.pidfd().expect_err("pidfd should not have been created when create_pid(false) is set");
22+
23+
let _ = Command::new("echo")
24+
.spawn()
25+
.unwrap()
26+
.pidfd().expect_err("pidfd should not have been created");
27+
}

0 commit comments

Comments
 (0)