1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
//! A Linux subreaper for one launch, not for every child of the artifactize process.
use std::{
io,
os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd},
os::unix::process::ExitStatusExt,
process::ExitStatus,
};
use tokio::io::unix::AsyncFd;
use super::{ProcessOutcome, ResolvedCommand};
pub(super) struct Reaper(AsyncFd<OwnedFd>);
impl Reaper {
pub(super) fn spawn(mut command: ResolvedCommand) -> io::Result<(tokio::process::Child, Self)> {
let (status, report) = socket_pair()?;
let status = AsyncFd::new(status)?;
// The child remaps stdio before pre_exec, even if an inherited stream was closed.
let report = if report.as_raw_fd() <= libc::STDERR_FILENO {
rustix::io::fcntl_dupfd_cloexec(&report, libc::STDERR_FILENO + 1)?
} else {
report
};
command.command.process_group(0).kill_on_drop(false);
// SAFETY: the setup and reaper use only Linux syscalls, async-signal-safe libc
// functions and stack data. The workload alone returns to std's normal exec path.
unsafe {
command
.command
.pre_exec(move || fork_workload(report.as_raw_fd()))
};
Ok((command.spawn()?, Self(status)))
}
pub(super) async fn wait(&self) -> io::Result<ProcessOutcome> {
loop {
let mut ready = self.0.readable().await?;
match ready.try_io(|_| self.outcome()) {
Ok(result) => return result,
Err(_) => continue,
}
}
}
pub(super) fn try_wait(&self) -> io::Result<Option<ProcessOutcome>> {
match self.outcome() {
Ok(outcome) => Ok(Some(outcome)),
Err(error) if error.kind() == io::ErrorKind::WouldBlock => Ok(None),
Err(error) => Err(error),
}
}
fn outcome(&self) -> io::Result<ProcessOutcome> {
let mut bytes = [0; size_of::<libc::c_int>()];
loop {
// SAFETY: recv writes into `bytes`; the fd is owned by this reaper handle.
// The one packet stays queued, so polling, waiting and cleanup see the same result.
let read = unsafe {
libc::recv(
self.0.get_ref().as_raw_fd(),
bytes.as_mut_ptr().cast(),
bytes.len(),
libc::MSG_PEEK | libc::MSG_DONTWAIT,
)
};
match read {
n if n == bytes.len() as isize => {
return Ok(ProcessOutcome::from_native(ExitStatus::from_raw(
libc::c_int::from_ne_bytes(bytes),
)));
}
0 => return Err(io::ErrorKind::BrokenPipe.into()),
..0 => {
let error = io::Error::last_os_error();
if error.kind() != io::ErrorKind::Interrupted {
return Err(error);
}
}
_ => return Err(io::ErrorKind::InvalidData.into()),
}
}
}
}
fn socket_pair() -> io::Result<(OwnedFd, OwnedFd)> {
let mut fds = [-1; 2];
// SAFETY: socketpair initializes two descriptors on success; this call owns both.
unsafe {
if libc::socketpair(
libc::AF_UNIX,
libc::SOCK_SEQPACKET | libc::SOCK_CLOEXEC | libc::SOCK_NONBLOCK,
0,
fds.as_mut_ptr(),
) != 0
{
return Err(io::Error::last_os_error());
}
Ok((OwnedFd::from_raw_fd(fds[0]), OwnedFd::from_raw_fd(fds[1])))
}
}
fn fork_workload(report: RawFd) -> io::Result<()> {
// A plain clone with an inherited stack is fork without pthread_atfork callbacks.
// The workload does not inherit the subreaper setting and can use waitpid normally.
// SAFETY: a single-threaded pre-exec child calls this with a live socket descriptor;
// these syscalls only change this process and clone private memory and descriptors.
let pid = unsafe {
if libc::prctl(
libc::PR_SET_CHILD_SUBREAPER,
1 as libc::c_ulong,
0 as libc::c_ulong,
0 as libc::c_ulong,
0 as libc::c_ulong,
) != 0
|| libc::signal(libc::SIGCHLD, libc::SIG_DFL) == libc::SIG_ERR
{
return Err(io::Error::last_os_error());
}
let null = std::ptr::null_mut::<libc::c_void>();
#[cfg(not(target_arch = "s390x"))]
let pid = libc::syscall(libc::SYS_clone, libc::SIGCHLD, null, null, null, null);
#[cfg(target_arch = "s390x")]
let pid = libc::syscall(libc::SYS_clone, null, libc::SIGCHLD, null, null, null);
pid as libc::pid_t
};
match pid {
..0 => Err(io::Error::last_os_error()),
0 => {
// SAFETY: only the workload's group changes, not its inherited session.
if unsafe { libc::setpgid(0, 0) } == 0 {
Ok(())
} else {
Err(io::Error::last_os_error())
}
}
pid => reap(pid, report),
}
}
fn reap(leader: libc::pid_t, report: RawFd) -> ! {
// Before closing the inherited fd table, prevent inherited signal handlers from
// running: they can still refer to old fd numbers. Restoring the original mask in
// the workload is unnecessary because it never executes this branch.
let mut blocked = std::mem::MaybeUninit::<libc::sigset_t>::uninit();
// SAFETY: sigfillset writes a complete set; sigprocmask copies it into the kernel.
unsafe {
libc::sigfillset(blocked.as_mut_ptr());
libc::sigprocmask(libc::SIG_SETMASK, blocked.as_ptr(), std::ptr::null_mut());
}
// Release std's exec-error pipe, the workload's stdio, and all unrelated descriptors.
// The forked workload still owns its copies and reports exec errors normally.
if super::descriptors::close_except(report).is_err() {
// SAFETY: the workload is our own unreaped child. The reaper cannot safely run
// with inherited descriptors after the exec-error pipe has been closed.
unsafe {
libc::kill(leader, libc::SIGKILL);
while libc::waitpid(leader, std::ptr::null_mut(), 0) < 0
&& *libc::__errno_location() == libc::EINTR
{}
libc::_exit(1);
}
}
// SAFETY: this process owns only the workload and its adopted descendants; waitpid
// writes one status word and send reads only that word. No allocation or unwinding.
unsafe {
let mut unreported = Some(leader);
loop {
let mut status = 0;
// Include clone children even if they don't use SIGCHLD to notify their parent.
let pid = libc::waitpid(-1, &mut status, libc::__WALL);
if pid < 0 {
match *libc::__errno_location() {
libc::EINTR => continue,
libc::ECHILD => libc::_exit(0),
_ => libc::_exit(1),
}
}
if unreported == Some(pid) && (libc::WIFEXITED(status) || libc::WIFSIGNALED(status)) {
unreported = None;
let bytes = status.to_ne_bytes();
while libc::send(
report,
bytes.as_ptr().cast(),
bytes.len(),
libc::MSG_NOSIGNAL,
) < 0
&& *libc::__errno_location() == libc::EINTR
{}
}
}
}
}