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
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::Mutex;
use std::thread;

use linux_api::errno::Errno;
use linux_api::posix_types::Pid;
use rustix::event::{self, epoll};
use rustix::fd::AsFd;
use rustix::fd::OwnedFd;
use rustix::io::FdFlags;
use rustix::process::PidfdFlags;

/// Utility for monitoring a set of child pid's, calling registered callbacks
/// when one exits or is killed. Starts a background thread, which is shut down
/// when the object is dropped.
#[derive(Debug)]
pub struct ChildPidWatcher {
    inner: Arc<Mutex<Inner>>,
    epoll: Arc<OwnedFd>,
}

pub type WatchHandle = u64;

#[derive(Debug)]
enum Command {
    RunCallbacks(Pid),
    UnregisterPid(Pid),
    Finish,
}

struct PidData {
    // Registered callbacks.
    callbacks: HashMap<WatchHandle, Box<dyn Send + FnOnce(Pid)>>,
    // After the pid has exited, this fd is closed and set to None.
    pidfd: Option<OwnedFd>,
    // Whether this pid has been unregistered. The whole struct is removed after
    // both the pid is unregistered, and `callbacks` is empty.
    unregistered: bool,
}

#[derive(Debug)]
struct Inner {
    // Next unique handle ID.
    next_handle: WatchHandle,
    // Pending commands for watcher thread.
    commands: Vec<Command>,
    // Data for each monitored pid.
    pids: HashMap<Pid, PidData>,
    // event_fd used to notify watcher thread via epoll. Calling thread writes a
    // single byte, which the watcher thread reads to reset.
    command_notifier: OwnedFd,
    thread_handle: Option<thread::JoinHandle<()>>,
}

impl Inner {
    fn send_command(&mut self, cmd: Command) {
        self.commands.push(cmd);
        rustix::io::write(&self.command_notifier, &1u64.to_ne_bytes()).unwrap();
    }

    fn unwatch_pid(&mut self, epoll: impl AsFd, pid: Pid) {
        let Some(piddata) = self.pids.get_mut(&pid) else {
            // Already unregistered the pid
            return;
        };
        let Some(fd) = piddata.pidfd.take() else {
            // Already unwatched the pid
            return;
        };
        epoll::delete(epoll, fd).unwrap();
    }

    fn pid_has_exited(&self, pid: Pid) -> bool {
        self.pids.get(&pid).unwrap().pidfd.is_none()
    }

    fn remove_pid(&mut self, epoll: impl AsFd, pid: Pid) {
        debug_assert!(self.should_remove_pid(pid));
        self.unwatch_pid(epoll, pid);
        self.pids.remove(&pid);
    }

    fn run_callbacks_for_pid(&mut self, pid: Pid) {
        for (_handle, cb) in self.pids.get_mut(&pid).unwrap().callbacks.drain() {
            cb(pid)
        }
    }

    fn should_remove_pid(&mut self, pid: Pid) -> bool {
        let pid_data = self.pids.get(&pid).unwrap();
        pid_data.callbacks.is_empty() && pid_data.unregistered
    }

    fn maybe_remove_pid(&mut self, epoll: impl AsFd, pid: Pid) {
        if self.should_remove_pid(pid) {
            self.remove_pid(epoll, pid)
        }
    }
}

impl ChildPidWatcher {
    /// Create a ChildPidWatcher. Spawns a background thread, which is joined
    /// when the object is dropped.
    pub fn new() -> Self {
        let epoll = Arc::new(epoll::create(epoll::CreateFlags::CLOEXEC).unwrap());
        let command_notifier = event::eventfd(
            0,
            event::EventfdFlags::NONBLOCK | event::EventfdFlags::CLOEXEC,
        )
        .unwrap();
        epoll::add(
            &epoll,
            &command_notifier,
            epoll::EventData::new_u64(0),
            epoll::EventFlags::IN,
        )
        .unwrap();
        let watcher = ChildPidWatcher {
            inner: Arc::new(Mutex::new(Inner {
                next_handle: 1,
                pids: HashMap::new(),
                commands: Vec::new(),
                command_notifier,
                thread_handle: None,
            })),
            epoll,
        };
        let thread_handle = {
            let inner = Arc::clone(&watcher.inner);
            let epoll = watcher.epoll.clone();
            thread::Builder::new()
                .name("child-pid-watcher".into())
                .spawn(move || ChildPidWatcher::thread_loop(&inner, &epoll))
                .unwrap()
        };
        watcher.inner.lock().unwrap().thread_handle = Some(thread_handle);
        watcher
    }

    fn thread_loop(inner: &Mutex<Inner>, epoll: impl AsFd) {
        let mut commands = Vec::new();
        let mut done = false;
        while !done {
            let mut events = epoll::EventVec::with_capacity(10);
            match epoll::wait(epoll.as_fd(), &mut events, -1) {
                Ok(()) => (),
                Err(rustix::io::Errno::INTR) => {
                    // Just try again.
                    continue;
                }
                Err(e) => panic!("epoll_wait: {:?}", e),
            };

            // We hold the lock the whole time we're processing events. While it'd
            // be nice to avoid holding it while executing callbacks (and therefore
            // not require that callbacks don't call ChildPidWatcher APIs), that'd
            // make it difficult to guarantee a callback *won't* be run if the
            // caller unregisters it.
            let mut inner = inner.lock().unwrap();

            for event in events.into_iter() {
                if event.data.u64() == 0 {
                    // We get an event for pid=0 when there's a write to the
                    // command_notifier; Ignore that here and handle below.
                    continue;
                }
                let pid = Pid::from_raw(i32::try_from(event.data.u64()).unwrap()).unwrap();
                inner.unwatch_pid(epoll.as_fd(), pid);
                inner.run_callbacks_for_pid(pid);
                inner.maybe_remove_pid(epoll.as_fd(), pid);
            }
            // Reading an eventfd always returns an 8 byte integer. Do so to ensure it's
            // no longer marked 'readable'.
            let mut buf = [0; 8];
            let res = rustix::io::read(&inner.command_notifier, &mut buf);
            debug_assert!(match res {
                Ok(8) => true,
                Ok(i) => panic!("Unexpected read size {}", i),
                Err(rustix::io::Errno::AGAIN) => true,
                Err(e) => panic!("Unexpected error {:?}", e),
            });
            // Run commands
            std::mem::swap(&mut commands, &mut inner.commands);
            for cmd in commands.drain(..) {
                match cmd {
                    Command::RunCallbacks(pid) => {
                        debug_assert!(inner.pid_has_exited(pid));
                        inner.run_callbacks_for_pid(pid);
                        inner.maybe_remove_pid(epoll.as_fd(), pid);
                    }
                    Command::UnregisterPid(pid) => {
                        if let Some(pid_data) = inner.pids.get_mut(&pid) {
                            pid_data.unregistered = true;
                            inner.maybe_remove_pid(epoll.as_fd(), pid);
                        }
                    }
                    Command::Finish => {
                        done = true;
                        // There could be more commands queued and/or more epoll
                        // events ready, but it doesn't matter. We don't
                        // guarantee to callers whether callbacks have run or
                        // not after having sent `Finish`; only that no more
                        // callbacks will run after the thread is joined.
                        break;
                    }
                }
            }
        }
    }

    /// Fork a child and register it. Uses `fork` internally; it `vfork` is desired,
    /// use `register_pid` instead.
    ///
    /// Panics if `child_fn` returns.
    /// TODO: change the type to `FnOnce() -> !` once that's stabilized in Rust.
    /// <https://github.com/rust-lang/rust/issues/35121>
    ///
    /// # Safety
    ///
    /// As for fork in Rust in general. *Probably*, *mostly*, safe, since the
    /// child process gets its own copy of the address space and OS resources etc.
    /// Still, there may be some dragons here. Best to call exec before too long
    /// in the child.
    pub unsafe fn fork_watchable(&self, child_fn: impl FnOnce()) -> Result<Pid, Errno> {
        let raw_pid = Errno::result_from_libc_errno(-1, unsafe { libc::syscall(libc::SYS_fork) })?;
        if raw_pid == 0 {
            child_fn();
            panic!("child_fn shouldn't have returned");
        }
        let pid = Pid::from_raw(raw_pid.try_into().unwrap()).unwrap();
        self.register_pid(pid);

        Ok(pid)
    }

    /// Register interest in `pid`.
    ///
    /// Will succeed even if `pid` is already dead, in which case callbacks
    /// registered for this `pid` will immediately be scheduled to run.
    ///
    /// `pid` must refer to some process, but that process may be a zombie (dead
    /// but not yet reaped). Panics if `pid` doesn't exist at all.  The caller
    /// should ensure the process has not been reaped before calling this
    /// function both to avoid such panics, and to avoid accidentally watching
    /// an unrelated process with a recycled `pid`.
    pub fn register_pid(&self, pid: Pid) {
        let mut inner = self.inner.lock().unwrap();
        // We defensively make the pidfd non-blocking, since we intend to always
        // use epoll to validate that it's ready before operating on it.
        let pidfd = rustix::process::pidfd_open(pid.into(), PidfdFlags::NONBLOCK)
            .unwrap_or_else(|e| panic!("pidfd_open failed for {pid:?}: {e:?}"));
        // `pidfd_open(2)`: the close-on-exec flag is set on the file descriptor.
        debug_assert!(
            rustix::io::fcntl_getfd(&pidfd)
                .unwrap()
                .contains(FdFlags::CLOEXEC),
            "pidfd_open unexpected didn't set CLOEXEC"
        );
        epoll::add(
            &self.epoll,
            &pidfd,
            epoll::EventData::new_u64(pid.as_raw_nonzero().get().try_into().unwrap()),
            epoll::EventFlags::IN,
        )
        .unwrap();

        let prev = inner.pids.insert(
            pid,
            PidData {
                callbacks: HashMap::new(),
                pidfd: Some(pidfd),
                unregistered: false,
            },
        );
        assert!(prev.is_none());
    }

    // TODO: Re-enable when Rust supports vfork: https://github.com/rust-lang/rust/issues/58314
    // pub unsafe fn vfork_watchable(&self, child_fn: impl FnOnce()) -> Result<Pid, nix::Error> {
    //     unsafe { self.fork_watchable_internal(libc::SYS_vfork, child_fn) }
    // }

    /// Unregister the pid. After unregistration, no more callbacks may be
    /// registered for the given pid. Already-registered callbacks will still be
    /// called if and when the pid exits unless individually unregistered.
    ///
    /// Safe to call multiple times.
    pub fn unregister_pid(&self, pid: Pid) {
        // Let the worker handle the actual unregistration. This avoids a race
        // where we unregister a pid at the same time as the worker thread
        // receives an epoll event for it.
        let mut inner = self.inner.lock().unwrap();
        inner.send_command(Command::UnregisterPid(pid));
    }

    /// Call `callback` from another thread after the child `pid`
    /// has exited, including if it has already exited. Does *not* reap the
    /// child itself.
    ///
    /// The returned handle is guaranteed to be non-zero.
    ///
    /// Panics if `pid` isn't registered.
    pub fn register_callback(
        &self,
        pid: Pid,
        callback: impl Send + FnOnce(Pid) + 'static,
    ) -> WatchHandle {
        let mut inner = self.inner.lock().unwrap();
        let handle = inner.next_handle;
        inner.next_handle += 1;
        let pid_data = inner.pids.get_mut(&pid).unwrap();
        assert!(!pid_data.unregistered);
        pid_data.callbacks.insert(handle, Box::new(callback));
        if pid_data.pidfd.is_none() {
            // pid is already dead. Run the callback we just registered.
            inner.send_command(Command::RunCallbacks(pid));
        }
        handle
    }

    /// Unregisters a callback. After returning, the corresponding callback is
    /// guaranteed either to have already run, or to never run. i.e. it's safe to
    /// free data that the callback might otherwise access.
    ///
    /// No-op if `pid` isn't registered.
    pub fn unregister_callback(&self, pid: Pid, handle: WatchHandle) {
        let mut inner = self.inner.lock().unwrap();
        if let Some(pid_data) = inner.pids.get_mut(&pid) {
            pid_data.callbacks.remove(&handle);
            inner.maybe_remove_pid(&self.epoll, pid);
        }
    }
}

impl Default for ChildPidWatcher {
    fn default() -> Self {
        Self::new()
    }
}

impl Drop for ChildPidWatcher {
    fn drop(&mut self) {
        let handle = {
            let mut inner = self.inner.lock().unwrap();
            inner.send_command(Command::Finish);
            inner.thread_handle.take().unwrap()
        };
        handle.join().unwrap();
    }
}

impl std::fmt::Debug for PidData {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PidData")
            .field("fd", &self.pidfd)
            .field("unregistered", &self.unregistered)
            .finish_non_exhaustive()
    }
}

#[cfg(test)]
mod tests {
    use std::sync::{Arc, Condvar};

    use nix::sys::eventfd::EventFd;
    use rustix::fd::AsRawFd;
    use rustix::process::{waitpid, WaitOptions};

    use super::*;

    fn is_zombie(pid: Pid) -> bool {
        let stat_name = format!("/proc/{}/stat", pid.as_raw_nonzero().get());
        let contents = std::fs::read_to_string(stat_name).unwrap();
        contents.contains(") Z")
    }

    #[test]
    // can't call foreign function: pipe
    #[cfg_attr(miri, ignore)]
    fn register_before_exit() {
        let notifier = EventFd::new().unwrap();

        let watcher = ChildPidWatcher::new();
        let child = unsafe {
            watcher.fork_watchable(|| {
                let mut buf = [0; 8];
                // Wait for parent to register its callback.
                nix::unistd::read(notifier.as_raw_fd(), &mut buf).unwrap();
                libc::_exit(42);
            })
        }
        .unwrap();

        let callback_ran = Arc::new((Mutex::new(false), Condvar::new()));
        {
            let callback_ran = callback_ran.clone();
            watcher.register_callback(
                child,
                Box::new(move |pid| {
                    assert_eq!(pid, child);
                    *callback_ran.0.lock().unwrap() = true;
                    callback_ran.1.notify_all();
                }),
            );
        }

        // Should be safe to unregister the pid now.
        // We don't be able to register any more callbacks, but existing one
        // should still work.
        watcher.unregister_pid(child);

        // Child should still be alive.
        let status = waitpid(Some(child.into()), WaitOptions::NOHANG).unwrap();
        assert!(status.is_none(), "Unexpected status: {status:?}");

        // Callback shouldn't have run yet.
        assert!(!*callback_ran.0.lock().unwrap());

        // Let the child exit.
        nix::unistd::write(&notifier, &1u64.to_ne_bytes()).unwrap();

        // Wait for our callback to run.
        let mut callback_ran_lock = callback_ran.0.lock().unwrap();
        while !*callback_ran_lock {
            callback_ran_lock = callback_ran.1.wait(callback_ran_lock).unwrap();
        }

        // Child should be ready to be reaped.
        // TODO: use WNOHANG here if we go back to a pidfd-based implementation.
        // With the current fd-based implementation we may be notified before kernel
        // marks the child reapable.
        let status = waitpid(Some(child.into()), WaitOptions::empty())
            .unwrap()
            .unwrap();
        assert_eq!(status.exit_status(), Some(42));
    }

    #[test]
    // can't call foreign functions
    #[cfg_attr(miri, ignore)]
    fn register_after_exit() {
        let child = match unsafe { libc::fork() } {
            0 => {
                unsafe { libc::_exit(42) };
            }
            child => Pid::from_raw(child).unwrap(),
        };

        // Wait until child is dead, but don't reap it yet.
        while !is_zombie(child) {
            unsafe {
                libc::sched_yield();
            }
        }

        let watcher = ChildPidWatcher::new();
        watcher.register_pid(child);

        // Used to wait until after the ChildPidWatcher has ran our callback
        let callback_ran = Arc::new((Mutex::new(false), Condvar::new()));
        {
            let callback_ran = callback_ran.clone();
            watcher.register_callback(
                child,
                Box::new(move |pid| {
                    assert_eq!(pid, child);
                    *callback_ran.0.lock().unwrap() = true;
                    callback_ran.1.notify_all();
                }),
            );
        }

        // Should be safe to unregister the pid now.
        // We don't be able to register any more callbacks, but existing one
        // should still work.
        watcher.unregister_pid(child);

        // Wait for our callback to run.
        let mut callback_ran_lock = callback_ran.0.lock().unwrap();
        while !*callback_ran_lock {
            callback_ran_lock = callback_ran.1.wait(callback_ran_lock).unwrap();
        }

        // Child should be ready to be reaped.
        // TODO: use WNOHANG here if we go back to a pidfd-based implementation.
        // With the current fd-based implementation we may be notified before kernel
        // marks the child reapable.
        assert_eq!(
            waitpid(Some(child.into()), WaitOptions::empty())
                .unwrap()
                .unwrap()
                .exit_status(),
            Some(42)
        );
    }

    #[test]
    // can't call foreign function: pipe
    #[cfg_attr(miri, ignore)]
    fn register_multiple() {
        let cb1_ran = Arc::new((Mutex::new(false), Condvar::new()));
        let cb2_ran = Arc::new((Mutex::new(false), Condvar::new()));

        let watcher = ChildPidWatcher::new();
        let child = unsafe {
            watcher.fork_watchable(|| {
                libc::_exit(42);
            })
        }
        .unwrap();

        for cb_ran in vec![cb1_ran.clone(), cb2_ran.clone()].drain(..) {
            let cb_ran = cb_ran.clone();
            watcher.register_callback(
                child,
                Box::new(move |pid| {
                    assert_eq!(pid, child);
                    *cb_ran.0.lock().unwrap() = true;
                    cb_ran.1.notify_all();
                }),
            );
        }

        // Should be safe to unregister the pid now.
        // We don't be able to register any more callbacks, but existing one
        // should still work.
        watcher.unregister_pid(child);

        for cb_ran in vec![cb1_ran, cb2_ran].drain(..) {
            let mut cb_ran_lock = cb_ran.0.lock().unwrap();
            while !*cb_ran_lock {
                cb_ran_lock = cb_ran.1.wait(cb_ran_lock).unwrap();
            }
        }

        // Child should be ready to be reaped.
        // TODO: use WNOHANG here if we go back to a pidfd-based implementation.
        // With the current fd-based implementation we may be notified before kernel
        // marks the child reapable.
        assert_eq!(
            waitpid(Some(child.into()), WaitOptions::empty())
                .unwrap()
                .unwrap()
                .exit_status(),
            Some(42)
        );
    }

    #[test]
    // can't call foreign function
    #[cfg_attr(miri, ignore)]
    fn unregister_one() {
        let cb1_ran = Arc::new((Mutex::new(false), Condvar::new()));
        let cb2_ran = Arc::new((Mutex::new(false), Condvar::new()));

        let notifier = EventFd::new().unwrap();

        let watcher = ChildPidWatcher::new();
        let child = unsafe {
            watcher.fork_watchable(|| {
                let mut buf = [0; 8];
                // Wait for parent to register its callback.
                nix::unistd::read(notifier.as_raw_fd(), &mut buf).unwrap();
                libc::_exit(42);
            })
        }
        .unwrap();

        let handles: Vec<WatchHandle> = [&cb1_ran, &cb2_ran]
            .iter()
            .cloned()
            .map(|cb_ran| {
                let cb_ran = cb_ran.clone();
                watcher.register_callback(
                    child,
                    Box::new(move |pid| {
                        assert_eq!(pid, child);
                        *cb_ran.0.lock().unwrap() = true;
                        cb_ran.1.notify_all();
                    }),
                )
            })
            .collect();

        // Should be safe to unregister the pid now.
        // We don't be able to register any more callbacks, but existing one
        // should still work.
        watcher.unregister_pid(child);

        watcher.unregister_callback(child, handles[0]);

        // Let the child exit.
        nix::unistd::write(&notifier, &1u64.to_ne_bytes()).unwrap();

        // Wait for the still-registered callback to run.
        let mut cb_ran_lock = cb2_ran.0.lock().unwrap();
        while !*cb_ran_lock {
            cb_ran_lock = cb2_ran.1.wait(cb_ran_lock).unwrap();
        }

        // The unregistered cb should *not* have run.
        assert!(!*cb1_ran.0.lock().unwrap());

        // Child should be ready to be reaped.
        // TODO: use WNOHANG here if we go back to a pidfd-based implementation.
        // With the current fd-based implementation we may be notified before kernel
        // marks the child reapable.
        assert_eq!(
            waitpid(Some(child.into()), WaitOptions::empty())
                .unwrap()
                .unwrap()
                .exit_status(),
            Some(42)
        );
    }
}