Repository navigation
Expand file tree
/
Copy pathprocess.rs
More file actions
672 lines (630 loc) · 23.8 KB
/
Copy pathprocess.rs
File metadata and controls
672 lines (630 loc) · 23.8 KB
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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
//! Linux process and signal primitives. Scheduling, deadlines, buffering, and
//! cleanup decisions remain in Lean. The caller exclusively owns child waits
//! and retains an exited leader until every process-group signal has been sent.
use std::ffi::{CStr, CString};
use std::fs::File;
use std::io::{self, Read};
use std::mem::MaybeUninit;
use std::os::fd::{AsRawFd, FromRawFd, IntoRawFd, OwnedFd, RawFd};
use std::ptr;
use std::sync::atomic::{AtomicBool, Ordering};
fn invalid(operation: &str) -> io::Error {
io::Error::new(io::ErrorKind::InvalidInput, operation)
}
fn context(operation: &str, error: io::Error) -> io::Error {
io::Error::new(error.kind(), format!("{operation}: {error}"))
}
fn posix_result(operation: &str, error: libc::c_int) -> io::Result<()> {
if error == 0 {
Ok(())
} else {
Err(context(operation, io::Error::from_raw_os_error(error)))
}
}
fn checked_pid(pid: u32) -> io::Result<libc::pid_t> {
if pid == 0 || pid > i32::MAX as u32 {
Err(invalid("invalid process id"))
} else {
Ok(pid as libc::pid_t)
}
}
fn c_string(value: &str) -> io::Result<CString> {
CString::new(value).map_err(|_| invalid("process argument contains NUL"))
}
fn owned_fd(fd: RawFd, operation: &str) -> io::Result<OwnedFd> {
if fd < 0 {
Err(context(operation, io::Error::last_os_error()))
} else {
// SAFETY: each caller passes a newly created descriptor, transferring its
// unique ownership here. No descriptor is wrapped more than once.
Ok(unsafe { OwnedFd::from_raw_fd(fd) })
}
}
fn above_stdio(fd: OwnedFd) -> io::Result<OwnedFd> {
if fd.as_raw_fd() >= 3 {
return Ok(fd);
}
// SAFETY: fd remains open throughout fcntl; the command takes one integer.
let copy = unsafe { libc::fcntl(fd.as_raw_fd(), libc::F_DUPFD_CLOEXEC, 3) };
owned_fd(copy, "duplicate process pipe")
}
fn pipe_pair() -> io::Result<(OwnedFd, OwnedFd)> {
let mut ends = [-1; 2];
// SAFETY: ends contains two writable descriptor slots as required by pipe2.
if unsafe { libc::pipe2(ends.as_mut_ptr(), libc::O_CLOEXEC) } < 0 {
return Err(context("create process pipe", io::Error::last_os_error()));
}
// Both descriptors must be owned before either normalization can fail.
let read = owned_fd(ends[0], "process read pipe")?;
let write = owned_fd(ends[1], "process write pipe")?;
Ok((above_stdio(read)?, above_stdio(write)?))
}
fn nonblocking(fd: &OwnedFd) -> io::Result<()> {
// SAFETY: fd is open, and both fcntl commands use their documented arguments.
let flags = unsafe { libc::fcntl(fd.as_raw_fd(), libc::F_GETFL) };
if flags < 0 {
return Err(context(
"read process pipe flags",
io::Error::last_os_error(),
));
}
// SAFETY: same open descriptor; F_SETFL takes an integer flag set.
if unsafe { libc::fcntl(fd.as_raw_fd(), libc::F_SETFL, flags | libc::O_NONBLOCK) } < 0 {
return Err(context(
"set process pipe flags",
io::Error::last_os_error(),
));
}
Ok(())
}
struct Actions(libc::posix_spawn_file_actions_t);
impl Actions {
fn new() -> io::Result<Self> {
let mut value = MaybeUninit::uninit();
// SAFETY: libc initializes this object on a successful return.
posix_result("initialize spawn actions", unsafe {
libc::posix_spawn_file_actions_init(value.as_mut_ptr())
})?;
// SAFETY: initialization above succeeded.
Ok(Self(unsafe { value.assume_init() }))
}
}
impl Drop for Actions {
fn drop(&mut self) {
// SAFETY: this object was initialized and is destroyed exactly once.
unsafe { libc::posix_spawn_file_actions_destroy(&mut self.0) };
}
}
struct Attributes(libc::posix_spawnattr_t);
impl Attributes {
fn new() -> io::Result<Self> {
let mut value = MaybeUninit::uninit();
// SAFETY: libc initializes this object on a successful return.
posix_result("initialize spawn attributes", unsafe {
libc::posix_spawnattr_init(value.as_mut_ptr())
})?;
// SAFETY: initialization above succeeded.
Ok(Self(unsafe { value.assume_init() }))
}
}
impl Drop for Attributes {
fn drop(&mut self) {
// SAFETY: this object was initialized and is destroyed exactly once.
unsafe { libc::posix_spawnattr_destroy(&mut self.0) };
}
}
fn add_chdir(actions: &mut Actions, directory: &CStr) -> io::Result<()> {
type AddChdir = unsafe extern "C" fn(
*mut libc::posix_spawn_file_actions_t,
*const libc::c_char,
) -> libc::c_int;
// Lean's link-time libc stub predates this GNU extension; resolve it from
// the actual supported Linux libc, without a second C implementation.
// SAFETY: this is a static NUL-terminated symbol name and RTLD_DEFAULT.
let symbol = unsafe {
libc::dlsym(
libc::RTLD_DEFAULT,
c"posix_spawn_file_actions_addchdir_np".as_ptr(),
)
};
if symbol.is_null() {
return Err(context(
"spawn chdir unavailable",
io::Error::from_raw_os_error(libc::ENOSYS),
));
}
// SAFETY: the named glibc symbol has precisely AddChdir's documented ABI.
let function: AddChdir = unsafe { std::mem::transmute(symbol) };
// SAFETY: actions is initialized; directory is a live NUL-terminated string.
posix_result("add spawn chdir", unsafe {
function(&mut actions.0, directory.as_ptr())
})
}
fn add_closefrom(actions: &mut Actions, first: RawFd) -> io::Result<()> {
type AddCloseFrom =
unsafe extern "C" fn(*mut libc::posix_spawn_file_actions_t, libc::c_int) -> libc::c_int;
// SAFETY: static NUL-terminated symbol name and RTLD_DEFAULT.
let symbol = unsafe {
libc::dlsym(
libc::RTLD_DEFAULT,
c"posix_spawn_file_actions_addclosefrom_np".as_ptr(),
)
};
if symbol.is_null() {
return Err(context(
"spawn closefrom unavailable",
io::Error::from_raw_os_error(libc::ENOSYS),
));
}
// SAFETY: the named glibc symbol has precisely AddCloseFrom's documented ABI.
let function: AddCloseFrom = unsafe { std::mem::transmute(symbol) };
// SAFETY: actions is initialized and first is a checked descriptor boundary.
posix_result("add spawn closefrom", unsafe {
function(&mut actions.0, first)
})
}
/// Launch one process in a new session with exactly the supplied environment.
/// Success transfers the three parent pipe descriptors to Lean, in the order
/// `[pid, stdin_writer, stdout_reader, stderr_reader]`. Exec failure is an error;
/// a program's eventual exit code 255 remains an ordinary program result.
pub fn spawn(
command: &str,
args: &[String],
cwd: Option<&str>,
environment: &[(String, Option<String>)],
inherited: &[u32],
) -> io::Result<[u32; 4]> {
if args.len() > 4096 || environment.len() > 4096 {
return Err(invalid("spawn argument count exceeds 4096"));
}
if inherited.len() > 16 {
return Err(invalid(
"at most 16 explicit inherited descriptors are supported",
));
}
let command = c_string(command)?;
let args: Vec<CString> = args
.iter()
.map(|arg| c_string(arg))
.collect::<io::Result<_>>()?;
let cwd = cwd.map(c_string).transpose()?;
let mut env = Vec::with_capacity(environment.len());
for (key, value) in environment {
if let Some(value) = value {
if key.is_empty() || key.contains('=') {
return Err(invalid("invalid process environment key"));
}
env.push(c_string(&format!("{key}={value}"))?);
}
}
let mut argv: Vec<*mut libc::c_char> = std::iter::once(&command)
.chain(args.iter())
.map(|value| value.as_ptr().cast_mut())
.collect();
argv.push(ptr::null_mut());
let mut envp: Vec<*mut libc::c_char> =
env.iter().map(|value| value.as_ptr().cast_mut()).collect();
envp.push(ptr::null_mut());
let (input_read, input_write) = pipe_pair()?;
let (output_read, output_write) = pipe_pair()?;
let (error_read, error_write) = pipe_pair()?;
let first_closed = 3 + inherited.len() as RawFd;
// Copy sources outside the child target range before any dup2 can replace them.
let inherited: Vec<OwnedFd> = inherited
.iter()
.map(|&fd| {
let fd = i32::try_from(fd).map_err(|_| invalid("invalid inherited descriptor"))?;
if fd < 3 {
return Err(invalid("stdio cannot be an inherited setup descriptor"));
}
// SAFETY: fcntl validates the borrowed FD; the result is newly owned.
owned_fd(
unsafe { libc::fcntl(fd, libc::F_DUPFD_CLOEXEC, first_closed) },
"duplicate inherited descriptor",
)
})
.collect::<io::Result<_>>()?;
nonblocking(&input_write)?;
nonblocking(&output_read)?;
nonblocking(&error_read)?;
let mut actions = Actions::new()?;
let mut attributes = Attributes::new()?;
if let Some(directory) = &cwd {
add_chdir(&mut actions, directory)?;
}
for (source, target) in [
(input_read.as_raw_fd(), libc::STDIN_FILENO),
(output_write.as_raw_fd(), libc::STDOUT_FILENO),
(error_write.as_raw_fd(), libc::STDERR_FILENO),
] {
// SAFETY: actions is initialized; source remains open until spawn returns.
posix_result("add spawn dup2", unsafe {
libc::posix_spawn_file_actions_adddup2(&mut actions.0, source, target)
})?;
}
// All owned pipe descriptors are >=3, so these cannot close a dup2 target.
for fd in [
&input_read,
&input_write,
&output_read,
&output_write,
&error_read,
&error_write,
] {
// SAFETY: actions is initialized and fd is a valid open descriptor.
posix_result("add spawn close", unsafe {
libc::posix_spawn_file_actions_addclose(&mut actions.0, fd.as_raw_fd())
})?;
}
for (index, source) in inherited.iter().enumerate() {
// Only these deliberately selected descriptors survive as 3, 4, ... .
// SAFETY: actions is initialized; sources remain owned through spawn.
posix_result("add explicit inherited descriptor", unsafe {
libc::posix_spawn_file_actions_adddup2(
&mut actions.0,
source.as_raw_fd(),
3 + index as RawFd,
)
})?;
}
add_closefrom(&mut actions, first_closed)?;
// SAFETY: sigset_t is a libc POD type, initialized by sigemptyset before use.
let mut mask: libc::sigset_t = unsafe { std::mem::zeroed() };
// SAFETY: same argument as mask.
let mut defaults: libc::sigset_t = unsafe { std::mem::zeroed() };
// SAFETY: these point to valid writable sigset_t objects; all signals are valid.
unsafe {
libc::sigemptyset(&mut mask);
libc::sigemptyset(&mut defaults);
libc::sigaddset(&mut defaults, libc::SIGINT);
libc::sigaddset(&mut defaults, libc::SIGTERM);
libc::sigaddset(&mut defaults, libc::SIGPIPE);
}
// SAFETY: initialized attributes and signal sets, valid Linux spawn flags.
unsafe {
posix_result(
"set spawn signal mask",
libc::posix_spawnattr_setsigmask(&mut attributes.0, &mask),
)?;
posix_result(
"set spawn signal defaults",
libc::posix_spawnattr_setsigdefault(&mut attributes.0, &defaults),
)?;
posix_result(
"set spawn session",
libc::posix_spawnattr_setflags(
&mut attributes.0,
(libc::POSIX_SPAWN_SETSID as libc::c_int
| libc::POSIX_SPAWN_SETSIGMASK
| libc::POSIX_SPAWN_SETSIGDEF) as libc::c_short,
),
)?;
}
let mut child: libc::pid_t = 0;
// SAFETY: all strings, pointer arrays (including their null terminators),
// actions, attributes, and descriptor sources remain alive through spawn.
// libc does not modify the bytes of argv/envp despite their C pointer type.
posix_result("posix_spawn", unsafe {
libc::posix_spawnp(
&mut child,
command.as_ptr(),
&actions.0,
&attributes.0,
argv.as_ptr(),
envp.as_ptr(),
)
})?;
// No fallible work follows process creation. Child-side ends and spawn
// resources drop locally; only the parent-side descriptors transfer to Lean.
Ok([
child as u32,
input_write.into_raw_fd() as u32,
output_read.into_raw_fd() as u32,
error_read.into_raw_fd() as u32,
])
}
/// An owned CLOEXEC pipe with a nonblocking reader and a blocking writer.
pub fn status_pipe() -> io::Result<[u32; 2]> {
let (read, write) = pipe_pair()?;
nonblocking(&read)?;
Ok([read.into_raw_fd() as u32, write.into_raw_fd() as u32])
}
/// Observe without reaping, retaining the leader identity against PID reuse.
pub fn peek_exit(pid: u32) -> io::Result<Option<u32>> {
let pid = checked_pid(pid)?;
// SAFETY: siginfo_t is libc POD; waitid writes its documented fields.
let mut info: libc::siginfo_t = unsafe { std::mem::zeroed() };
loop {
// SAFETY: info is writable; pid and wait flags are valid.
let result = unsafe {
libc::waitid(
libc::P_PID,
pid as libc::id_t,
&mut info,
libc::WEXITED | libc::WNOHANG | libc::WNOWAIT,
)
};
if result == 0 {
break;
}
let error = io::Error::last_os_error();
if error.kind() != io::ErrorKind::Interrupted {
return Err(context("waitid", error));
}
}
// SAFETY: successful waitid with WEXITED initialized the child-status union.
if unsafe { info.si_pid() } == 0 {
return Ok(None);
}
// SAFETY: same successful child-status observation.
let status = unsafe { info.si_status() } as u32;
Ok(Some(if info.si_code == libc::CLD_EXITED {
status
} else {
128 + status
}))
}
/// Reap only after the caller has finished every process-group signal.
pub fn try_wait(pid: u32) -> io::Result<Option<u32>> {
let pid = checked_pid(pid)?;
let mut status = 0;
let result = loop {
// SAFETY: status is writable and pid identifies the caller's child.
let result = unsafe { libc::waitpid(pid, &mut status, libc::WNOHANG) };
if result >= 0 {
break result;
}
let error = io::Error::last_os_error();
if error.kind() != io::ErrorKind::Interrupted {
return Err(context("waitpid", error));
}
};
if result == 0 {
Ok(None)
} else if libc::WIFEXITED(status) {
Ok(Some(libc::WEXITSTATUS(status) as u32))
} else if libc::WIFSIGNALED(status) {
Ok(Some((128 + libc::WTERMSIG(status)) as u32))
} else {
Ok(None)
}
}
struct Directory(*mut libc::DIR);
impl Drop for Directory {
fn drop(&mut self) {
// SAFETY: this non-null DIR was opened successfully and is uniquely owned.
unsafe { libc::closedir(self.0) };
}
}
fn decimal_pid(bytes: &[u8]) -> Option<(u32, usize)> {
let mut value = 0u32;
let mut count = 0;
for &byte in bytes {
if !byte.is_ascii_digit() {
break;
}
value = value.checked_mul(10)?.checked_add((byte - b'0') as u32)?;
if value > i32::MAX as u32 {
return None;
}
count += 1;
}
(count != 0).then_some((value, count))
}
fn group_from_stat(bytes: &[u8]) -> Option<(u8, u32)> {
let closing = bytes.iter().rposition(|&byte| byte == b')')?;
let rest = bytes.get(closing + 1..)?;
if rest.first() != Some(&b' ') || rest.get(2) != Some(&b' ') {
return None;
}
let state = *rest.get(1)?;
if state == 0 {
return None;
}
// A task observed during final teardown can expose state X with PGID and
// SID -1. It is already dead and cannot keep the group alive. Do not parse
// its disappearing identifiers as live-process metadata.
if matches!(state, b'Z' | b'X' | b'x') {
return Some((state, 0));
}
let (_, parent_end) = decimal_pid(rest.get(3..)?)?;
let rest = rest.get(3 + parent_end..)?;
if rest.first() != Some(&b' ') {
return None;
}
let (group, group_end) = decimal_pid(rest.get(1..)?)?;
if rest.get(group_end + 1) != Some(&b' ') {
return None;
}
Some((state, group))
}
fn vanished(error: &io::Error) -> bool {
matches!(error.raw_os_error(), Some(libc::ENOENT | libc::ESRCH))
}
/// Bounded, conservative procfs observation of live members other than the
/// held leader. It is not atomic against forking and cannot contain detached
/// descendants. Incomplete or unreadable observations fail rather than report
/// an empty group. The caller must own a complete Linux proc namespace.
pub fn group_has_others(pid: u32) -> io::Result<bool> {
checked_pid(pid)?;
// SAFETY: static NUL-terminated path; opendir returns a uniquely owned DIR.
let raw = unsafe { libc::opendir(c"/proc".as_ptr()) };
if raw.is_null() {
return Err(context("open /proc", io::Error::last_os_error()));
}
let directory = Directory(raw);
for visited in 0..100_001 {
// SAFETY: errno is this thread's libc slot; DIR stays alive throughout
// readdir, and no second thread accesses this Directory.
let entry = unsafe {
*libc::__errno_location() = 0;
libc::readdir(directory.0)
};
if entry.is_null() {
let error = io::Error::last_os_error();
return if error.raw_os_error() == Some(0) {
Ok(false)
} else {
Err(context("inspect process group", error))
};
}
if visited == 100_000 {
return Err(context(
"process group entry limit",
io::Error::from_raw_os_error(libc::EOVERFLOW),
));
}
// SAFETY: readdir supplied a live dirent with NUL-terminated d_name;
// its bytes are consumed before the next call to readdir.
let name = unsafe { CStr::from_ptr((*entry).d_name.as_ptr()) }.to_bytes();
let Some((candidate, length)) = decimal_pid(name) else {
continue;
};
if length != name.len() || candidate == 0 || candidate == pid {
continue;
}
// Formatted decimal numbers cannot contain NUL.
let path = c_string(&format!("{candidate}/stat"))?;
// SAFETY: directory is live; relative path is a valid CString; flags
// need no mode argument and the returned descriptor is uniquely owned.
let fd = unsafe {
libc::openat(
libc::dirfd(directory.0),
path.as_ptr(),
libc::O_RDONLY | libc::O_CLOEXEC | libc::O_NOFOLLOW,
)
};
if fd < 0 {
let error = io::Error::last_os_error();
if vanished(&error) {
continue;
}
return Err(context("inspect process group", error));
}
let mut file = File::from(owned_fd(fd, "open process stat")?);
let mut data = [0; 4095];
let size = loop {
match file.read(&mut data) {
Ok(size) => break Some(size),
Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
Err(error) if vanished(&error) => break None,
Err(error) => return Err(context("read process stat", error)),
}
};
let Some(size) = size else { continue };
if size == 0 || size == data.len() {
return Err(context(
"process stat size",
io::Error::from_raw_os_error(libc::EOVERFLOW),
));
}
let (state, group) = group_from_stat(&data[..size]).ok_or_else(|| {
context(
"parse process stat",
io::Error::from_raw_os_error(libc::EPROTO),
)
})?;
if group == pid && !matches!(state, b'Z' | b'X' | b'x') {
return Ok(true);
}
}
Err(context(
"process group entry limit",
io::Error::from_raw_os_error(libc::EOVERFLOW),
))
}
pub fn signal_group(pid: u32, signal: u32) -> io::Result<()> {
let pid = checked_pid(pid)?;
if signal > i32::MAX as u32 {
return Err(invalid("invalid signal number"));
}
// SAFETY: negating a checked positive pid is defined and targets its group.
if unsafe { libc::kill(-pid, signal as libc::c_int) } < 0 {
let error = io::Error::last_os_error();
if error.raw_os_error() != Some(libc::ESRCH) {
return Err(context("kill process group", error));
}
}
Ok(())
}
pub fn group_exists(pid: u32) -> io::Result<bool> {
let pid = checked_pid(pid)?;
// SAFETY: signal zero probes the checked process group without sending one.
if unsafe { libc::kill(-pid, 0) } == 0 {
return Ok(true);
}
let error = io::Error::last_os_error();
match error.raw_os_error() {
Some(libc::EPERM) => Ok(true),
Some(libc::ESRCH) => Ok(false),
_ => Err(context("probe process group", error)),
}
}
static CANCELLED: AtomicBool = AtomicBool::new(false);
extern "C" fn cancel_signal(_: libc::c_int) {
// AtomicBool's store is lock-free on the supported Linux target; this
// handler allocates nothing and calls no non-signal-safe runtime function.
CANCELLED.store(true, Ordering::Relaxed);
}
fn set_handler(signal: libc::c_int, handler: libc::sighandler_t) -> io::Result<()> {
// SAFETY: sigaction is libc POD; zero flags clear inherited SA_NOCLDWAIT.
let mut action: libc::sigaction = unsafe { std::mem::zeroed() };
action.sa_sigaction = handler;
// SAFETY: valid writable action, valid signal, and no previous-action output.
unsafe {
libc::sigemptyset(&mut action.sa_mask);
if libc::sigaction(signal, &action, ptr::null_mut()) < 0 {
return Err(context(
"install signal handler",
io::Error::last_os_error(),
));
}
}
Ok(())
}
/// The runtime exclusively owns waits for spawned children. Reset inherited
/// SIGCHLD auto-reaping so an exited leader continues to pin its process id.
pub fn install_signals() -> io::Result<()> {
set_handler(libc::SIGCHLD, libc::SIG_DFL)?;
set_handler(
libc::SIGINT,
cancel_signal as *const () as libc::sighandler_t,
)?;
set_handler(
libc::SIGTERM,
cancel_signal as *const () as libc::sighandler_t,
)?;
set_handler(libc::SIGPIPE, libc::SIG_IGN)
}
pub fn cancelled() -> bool {
CANCELLED.load(Ordering::Relaxed)
}
pub fn pid() -> u32 {
// SAFETY: getpid has no pointer arguments or preconditions and cannot fail.
unsafe { libc::getpid() as u32 }
}
#[cfg(test)]
mod tests {
use super::group_from_stat;
#[test]
fn dead_task_teardown_does_not_require_a_live_group_id() {
// Captured during concurrent bubblewrap exits on the supported host.
let observed =
b"2341507 (bwrap) X 0 -1 -1 0 -1 4227340 119 0 0 0 0 0 0 0 20 0 0 0 705109031 0 0\n";
assert_eq!(group_from_stat(observed), Some((b'X', 0)));
assert_eq!(
group_from_stat(b"123 (done) Z 1 456 456 0\n"),
Some((b'Z', 0))
);
}
#[test]
fn live_group_ids_remain_required_and_names_are_not_field_delimiters() {
assert_eq!(
group_from_stat(b"123 (a ) name) S 1 456 456 0\n"),
Some((b'S', 456))
);
assert_eq!(group_from_stat(b"123 (live) R 1 -1 456 0\n"), None);
assert_eq!(group_from_stat(b"123 (live) R 1 456"), None);
assert_eq!(group_from_stat(b"123 (live) R 1 bad 456 0\n"), None);
}
}