a10 0.4.2

This library is meant as a low-level library safely exposing different OS's abilities to perform non-blocking I/O.
Documentation
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
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
//! Process handling.
//!
//! [`wait`] and [`wait_on`] can be used to wait on started processes.
//! [`Signals`] can be used for process signal handling.

use std::mem::{self, ManuallyDrop, MaybeUninit};
use std::os::unix::process::ExitStatusExt;
use std::pin::Pin;
use std::process::{Child, ExitStatus};
use std::task::{self, Poll};
use std::{fmt, io, ptr};

use crate::op::{FdOp, OpState, fd_operation, operation};
use crate::{AsyncFd, SubmissionQueue, man_link, new_flag, sys, syscall};

#[cfg(any(target_os = "android", target_os = "linux"))]
pub use crate::sys::process::ToDirect;

/// Wait on the child `process`.
///
/// See [`wait`].
pub fn wait_on(sq: SubmissionQueue, process: &Child) -> WaitId {
    wait(sq, WaitOn::Process(process.id()))
}

/// Obtain status information on termination, stop, and/or continue events in
/// one of the caller's child processes.
///
/// Also see [`wait_on`] to wait on a [`Child`] process.
#[doc = man_link!(waitid(2))]
#[doc(alias = "waitid")]
pub fn wait(sq: SubmissionQueue, wait: WaitOn) -> WaitId {
    // SAFETY: fully zeroed `libc::siginfo_t` is a valid value.
    let info = unsafe { mem::zeroed() };
    WaitId::new(sq, info, (wait, WaitOption(0)))
}

/// Defines on what process (or processes) to wait.
#[doc(alias = "idtype")]
#[doc(alias = "idtype_t")]
#[derive(Copy, Clone, Debug)]
pub enum WaitOn {
    /// Wait for the child process.
    #[doc(alias = "P_PID")]
    Process(u32),
    /// Wait for any child process in the process group with ID.
    #[doc(alias = "P_PGID")]
    #[cfg(any(target_os = "android", target_os = "linux"))]
    Group(u32),
    /// Wait for all childeren.
    #[doc(alias = "P_ALL")]
    #[cfg(any(target_os = "android", target_os = "linux"))]
    All,
}

new_flag!(
    /// Wait option.
    ///
    /// See [`WaitId::flags`].
    pub struct WaitOption(u32) {
        /// Return if a child has stopped (but not traced via `ptrace(2)`).
        UNTRACED = libc::WUNTRACED,
        /// Wait for children that have been stopped by delivery of a signal.
        STOPPED = libc::WSTOPPED,
        /// Wait for children that have terminated.
        EXITED = libc::WEXITED,
        /// Return if a stopped child has been resumed by delivery of `SIGCONT`.
        CONTINUED = libc::WCONTINUED,
        /// Leave the child in a waitable state; a later wait call can be used
        /// to again retrieve the child status information.
        NO_WAIT = libc::WNOWAIT,
    }
);

/// Information about an awaited process.
///
/// See [`wait`] and [`wait_on`].
#[repr(transparent)]
pub struct WaitInfo(pub(crate) libc::siginfo_t);

impl WaitInfo {
    /// Process id of the child.
    pub fn pid(&self) -> i32 {
        unsafe { self.0.si_pid() }
    }

    /// Real user ID of the child.
    pub fn real_user_id(&self) -> u32 {
        unsafe { self.0.si_uid() }
    }

    /// Process signal.
    pub fn signal(&self) -> Signal {
        Signal(self.0.si_signo)
    }

    /// Either the exit status of the child or the signal that caused the child
    /// to terminate, stop, or continue.
    ///
    /// The [`code`] field can be used to determine how to interpret this field.
    ///
    /// [`code`]: WaitInfo::code
    pub fn status(&self) -> ExitStatus {
        unsafe { ExitStatus::from_raw(self.0.si_status()) }
    }

    /// Status of the child process.
    pub fn code(&self) -> ChildStatus {
        ChildStatus(self.0.si_code)
    }
}

unsafe impl Send for WaitInfo {}
unsafe impl Sync for WaitInfo {}

impl fmt::Debug for WaitInfo {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("WaitInfo")
            .field("pid", &self.pid())
            .field("real_user_id", &self.real_user_id())
            .field("signal", &self.signal())
            .field("status", &self.status())
            .field("code", &self.code())
            .finish()
    }
}

new_flag!(
    /// See [`WaitInfo::code`].
    pub struct ChildStatus(i32) {
        /// Exited (called `exit(3)`).
        EXITED = libc::CLD_EXITED,
        /// Killed by a signal.
        KILLED = libc::CLD_KILLED,
        /// Killed by a signal, dumped core.
        DUMPED = libc::CLD_DUMPED,
        /// Stopped by signal.
        STOPPED = libc::CLD_STOPPED,
        /// Traced child has trapped.
        TRAPPED = libc::CLD_TRAPPED,
        /// Continue by continue signal.
        CONTINUED = libc::CLD_CONTINUED,
    }
);

operation!(
    /// [`Future`] behind [`wait_on`] and [`wait`].
    pub struct WaitId(sys::process::WaitIdOp) -> io::Result<WaitInfo>;
);

impl WaitId {
    /// Set the `flags`.
    pub fn flags(mut self, options: WaitOption) -> Self {
        if let Some((_, o)) = self.state.args_mut() {
            *o = options;
        }
        self
    }

    /// Return what this future is waiting on.
    pub fn waiting_on(&self) -> WaitOn {
        self.state.args().0
    }
}

/// Notification of process signals.
///
/// # Multithreaded process
///
/// For `Signals` to function correctly in multithreaded processes it must be
/// created on the main thread **before** spawning any threads. This is due to
/// an implementation detail where the spawned threads must inherit various
/// signal related thread properties from the parent thread.
///
/// Any threads spawned before creating a `Signals` instance will experience the
/// default process signals behaviour, i.e. sending it a signal will interrupt
/// or stop it.
///
/// Furthermore only a single instance of `Signals` should be active for a given
/// signal set. In other words, no two `Signals` instances should be created
/// for the signal. Easiest is to limit yourself to a single instance.
///
/// # Implementation Notes
///
/// ## io_uring
///
/// This will block all signals in the signal set given when creating `Signals`,
/// using [`pthread_sigmask(3)`]. This means that the thread in which `Signals`
/// was created (and it's children) is not interrupted, or in any way notified
/// of a signal until [`Signals::receive`] is called (and the returned
/// [`Future`] polled to completion). Under the hood [`Signals`] is just a
/// wrapper around [`signalfd(2)`].
///
/// [`pthread_sigmask(3)`]: https://man7.org/linux/man-pages/man3/pthread_sigmask.3.html
/// [`Future`]: std::future::Future
/// [`signalfd(2)`]: http://man7.org/linux/man-pages/man2/signalfd.2.html
///
/// ## kqueue
///
/// This will block all signals in the signal set given when creating `Signals`,
/// by setting the handler action to `SIG_IGN` using [`sigaction(2)`], meaning
/// that all signals will be ignored. Same as on io_uring based systems; the
/// program is not interrupted, or in any way notified of signal until the
/// assiocated `Ring` is polled.
///
/// [`sigaction(2)`]: https://www.freebsd.org/cgi/man.cgi?query=sigaction&sektion=2
///
/// # Examples
///
/// ```
/// use std::io;
/// use std::mem::MaybeUninit;
///
/// use a10::Ring;
/// use a10::process::{Signals, Signal};
///
/// # fn main() {
/// async fn main() -> io::Result<()> {
///     let ring = Ring::new()?;
///     let sq = ring.sq().clone();
///
///     // Create a new `Signals` instance.
///     let signals = Signals::from_signals(sq, [Signal::INTERRUPT, Signal::QUIT, Signal::TERMINATION])?;
///
///     let signal_info = signals.receive().await?;
///     println!("Got process signal: {:?}", signal_info.signal());
///     Ok(())
/// }
/// # }
/// ```
pub struct Signals {
    /// `signalfd(2)` or `kqueue(2)` file descriptor.
    pub(crate) fd: AsyncFd,
    /// All signals this is listening for, used in resetting the signal handlers.
    pub(crate) signals: SignalSet,
}

impl Signals {
    /// Create a new signal notifier from a signal set.
    pub fn from_set(sq: SubmissionQueue, signals: SignalSet) -> io::Result<Signals> {
        log::trace!(signals:?; "setting up signal handling");
        Signals::new(sq, signals) // See sys::process.
    }

    /// Create a new signal notifier from a collection of signals.
    pub fn from_signals<I>(sq: SubmissionQueue, signals: I) -> io::Result<Signals>
    where
        I: IntoIterator<Item = Signal>,
    {
        let mut set = SignalSet::empty()?;
        for signal in signals {
            set.add(signal)?;
        }
        Signals::from_set(sq, set)
    }

    /// Create a new signal notifier for all supported signals.
    pub fn for_all_signals(sq: SubmissionQueue) -> io::Result<Signals> {
        let mut set = SignalSet::all()?;
        // Remove signal which we can't handle.
        for signal in [Signal::STOP, Signal::KILL] {
            syscall!(sigdelset(&raw mut set.0, signal.0))?;
        }
        Signals::from_set(sq, set)
    }

    /// Receive a signal.
    pub fn receive<'fd>(&'fd self) -> ReceiveSignal<'fd> {
        ReceiveSignal::new(&self.fd, MaybeUninit::uninit(), ())
    }

    /// Receive multiple signals.
    ///
    /// This is an combined, owned version of `Signals` and [`ReceiveSignal`]
    /// (the future behind `Signals::receive`). This is useful if you don't want
    /// to deal with the `'fd` lifetime.
    pub fn receive_signals(self) -> ReceiveSignals {
        ReceiveSignals {
            signals: self,
            state: <sys::process::ReceiveSignalOp as FdOp>::State::new(MaybeUninit::uninit(), ()),
        }
    }

    /// Returns the set of signals this is listening for.
    pub fn set(&self) -> &SignalSet {
        &self.signals
    }
}

impl fmt::Debug for Signals {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Signals")
            .field("fd", &self.fd)
            .field("signals", &self.signals)
            .finish()
    }
}

fd_operation!(
    /// [`Future`] behind [`Signals::receive`].
    pub struct ReceiveSignal(sys::process::ReceiveSignalOp) -> io::Result<SignalInfo>;
);

/// [`AsyncIterator`] behind [`Signals::receive_signals`].
///
/// [`AsyncIterator`]: std::async_iter::AsyncIterator
#[must_use = "`AsyncIterator`s do nothing unless polled"]
#[derive(Debug)]
pub struct ReceiveSignals {
    signals: Signals,
    state: <sys::process::ReceiveSignalOp as FdOp>::State,
}

impl ReceiveSignals {
    /// This is the same as the [`AsyncIterator::poll_next`] function, but
    /// then available on stable Rust.
    ///
    /// [`AsyncIterator::poll_next`]: std::async_iter::AsyncIterator::poll_next
    pub fn poll_next(
        self: Pin<&mut Self>,
        ctx: &mut task::Context<'_>,
    ) -> Poll<Option<io::Result<SignalInfo>>> {
        // SAFETY: not moving data out of self/this.
        let this = unsafe { Pin::get_unchecked_mut(self) };
        let result = sys::process::ReceiveSignalOp::poll(&mut this.state, ctx, &this.signals.fd);
        match result {
            Poll::Ready(Ok(info)) => {
                this.state.reset(MaybeUninit::uninit(), ());
                Poll::Ready(Some(Ok(info)))
            }
            Poll::Ready(Err(err)) => Poll::Ready(Some(Err(err))),
            Poll::Pending => Poll::Pending,
        }
    }

    /// Returns the underlying [`Signals`].
    pub fn into_inner(self) -> Signals {
        let mut this = ManuallyDrop::new(self);
        let ReceiveSignals { signals, state } = &mut *this;
        // SAFETY: not using state any more.
        unsafe {
            OpState::drop(state, signals.fd.sq());
            ptr::drop_in_place(state);
        }
        // SAFETY: we're not dropping self (due to the ManuallyDrop, so signals
        // is safe to return.
        unsafe { ptr::read(signals) }
    }

    /// Returns the set of signals this is listening for.
    pub fn set(&self) -> &SignalSet {
        self.signals.set()
    }
}

#[cfg(feature = "nightly")]
impl std::async_iter::AsyncIterator for ReceiveSignals {
    type Item = io::Result<SignalInfo>;

    fn poll_next(self: Pin<&mut Self>, ctx: &mut task::Context<'_>) -> Poll<Option<Self::Item>> {
        self.poll_next(ctx)
    }
}

impl Drop for ReceiveSignals {
    fn drop(&mut self) {
        // SAFETY: we're in the `Drop` implementation.
        unsafe { OpState::drop(&mut self.state, self.signals.fd.sq()) }
    }
}

/// Process signal information.
///
/// See [`Signals::receive`].
#[repr(transparent)]
pub struct SignalInfo(pub(crate) crate::sys::process::SignalInfo);

impl SignalInfo {
    /// Signal send.
    pub fn signal(&self) -> Signal {
        crate::sys::process::signal(&self.0)
    }

    /// Process id of the sender.
    #[cfg(any(target_os = "android", target_os = "linux"))]
    pub fn pid(&self) -> u32 {
        crate::sys::process::pid(&self.0)
    }

    /// Real user ID of the sender.
    #[cfg(any(target_os = "android", target_os = "linux"))]
    pub fn real_user_id(&self) -> u32 {
        crate::sys::process::real_user_id(&self.0)
    }
}

impl fmt::Debug for SignalInfo {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut f = f.debug_struct("SignalInfo");
        f.field("signal", &self.signal());
        #[cfg(any(target_os = "android", target_os = "linux"))]
        f.field("pid", &self.pid());
        #[cfg(any(target_os = "android", target_os = "linux"))]
        f.field("real_user_id", &self.real_user_id());
        f.finish()
    }
}

/// Set of signals.
#[repr(transparent)]
pub struct SignalSet(pub(crate) libc::sigset_t);

impl SignalSet {
    /// Create an empty set.
    #[doc(alias = "sigemptyset")]
    pub fn empty() -> io::Result<SignalSet> {
        let mut set: MaybeUninit<libc::sigset_t> = MaybeUninit::uninit();
        syscall!(sigemptyset(set.as_mut_ptr()))?;
        // SAFETY: initialised the set in the call to `sigemptyset`.
        Ok(SignalSet(unsafe { set.assume_init() }))
    }

    /// Create a set with all signals.
    #[doc(alias = "sigfillset")]
    pub fn all() -> io::Result<SignalSet> {
        let mut set: MaybeUninit<libc::sigset_t> = MaybeUninit::uninit();
        syscall!(sigfillset(set.as_mut_ptr()))?;
        // SAFETY: initialised the set in the call to `sigfillset`.
        Ok(SignalSet(unsafe { set.assume_init() }))
    }

    /// Returns true if `signal` is contained in the set.
    #[doc(alias = "sigismember")]
    pub fn contains(&self, signal: Signal) -> bool {
        // SAFETY: we ensure the pointer to the signal set is valid.
        unsafe { libc::sigismember(&raw const self.0, signal.0) == 1 }
    }

    /// Add `signal` to the set.
    #[doc(alias = "sigaddset")]
    pub fn add(&mut self, signal: Signal) -> io::Result<()> {
        syscall!(sigaddset(&raw mut self.0, signal.0)).map(|_| ())
    }
}

impl fmt::Debug for SignalSet {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let signals = Signal::ALL_VALUES
            .iter()
            .filter(|signal| self.contains(**signal));
        f.debug_set().entries(signals).finish()
    }
}

new_flag!(
    /// Process signal.
    #[doc = man_link!(signal(7))]
    pub struct Signal(i32) {
        /// Hangup signal.
        ///
        /// This signal is sent to a process when its controlling terminal is
        /// closed. In modern systems, this signal usually means that the
        /// controlling pseudo or virtual terminal has been closed.
        HUP = libc::SIGHUP,
        /// Interrupt signal.
        ///
        /// This signal is received by the process when its controlling terminal
        /// wishes to interrupt the process. This signal will for example be
        /// send when Ctrl+C is pressed in most terminals.
        INTERRUPT = libc::SIGINT,
        /// Quit signal.
        ///
        /// This signal is received when the process is requested to quit and
        /// perform a core dump.
        QUIT = libc::SIGQUIT,
        /// Illegal instruction.
        ///
        /// This signal is sent to a process when it attempts to execute an
        /// illegal, malformed, unknown, or privileged instruction.
        ILLEGAL = libc::SIGILL,
        /// Trace/breakpoint trap.
        ///
        /// This signal is sent to a process when an exception (or trap) occurs:
        /// a condition that a debugger has requested to be informed of.
        TRAP = libc::SIGTRAP,
        /// Abort signal.
        ///
        /// This signal is sent to a process to tell it to abort, i.e. to
        /// terminate. This signal can also indicate that the CPU has executed
        /// an explicit "trap" instruction (without a defined function), or an
        /// unimplemented instruction (when emulation is unavailable).
        ABORT = libc::SIGABRT,
        /// IOT trap.
        IOT = libc::SIGIOT,
        /// Kill signal.
        KILL = libc::SIGKILL,
        /// Bus error (bad memory access) signal.
        ///
        /// This signal is sent to a process when it causes a bus error. The
        /// conditions that lead to the signal being sent are, for example,
        /// incorrect memory access alignment or non-existent physical address.
        BUS = libc::SIGBUS,
        /// Erroneous arithmetic operation signal.
        ///
        /// This signal is sent to a process when an exceptional (but not
        /// necessarily erroneous) condition has been detected in the floating
        /// point or integer arithmetic hardware. This may include division by
        /// zero, floating point underflow or overflow, integer overflow, an
        /// invalid operation or an inexact computation. Behaviour may differ
        /// depending on hardware.
        FP_ERROR = libc::SIGFPE,
        /// User-defined signal 1.
        USER1 = libc::SIGUSR1,
        /// User-defined signal 2.
        USER2 = libc::SIGUSR2,
        /// Invalid memory reference.
        ///
        /// This signal is sent to a process when it makes an invalid virtual
        /// memory reference, or segmentation fault.
        SEG_VAULT = libc::SIGSEGV,
        /// Broken pipe signal.
        ///
        /// This signal is sent to a process when it attempts to write to a pipe
        /// without a process connected to the other end.
        PIPE = libc::SIGPIPE,
        /// Alarm signal.
        ///
        /// This signal is sent to a process when a time limit is reached. This
        /// alarm is based on real or clock time.
        ///
        /// Also see [`Signal::VIRTUAL_ALARM`] and  [`Signal::PROFILE_ALARM`].
        ALARM = libc::SIGALRM,
        /// Termination request signal.
        ///
        /// This signal received when the process is requested to terminate. This
        /// allows the process to perform nice termination, releasing resources and
        /// saving state if appropriate. This signal will be send when using the
        /// `kill` command for example.
        TERMINATION = libc::SIGTERM,
        /// Child signal.
        ///
        /// This signal is sent to a process when a child process terminates, is
        /// stopped, or resumes after being stopped.
        CHILD = libc::SIGCHLD,
        /// Continue signal.
        ///
        /// This signal sent to a process to continue (restart) after being
        /// previously paused by the [`Signal::STOP`] or [`Signal::TERM_STOP`]
        /// signals.
        CONTINUE = libc::SIGCONT,
        /// Stop process.
        STOP = libc::SIGSTOP,
        /// Stop typed at terminal.
        TERM_STOP = libc::SIGTSTP,
        /// Terminal input for background process signal.
        ///
        /// This signal is sent to a process when it attempts to read from the
        /// tty while in the background.
        TTY_IN = libc::SIGTTIN,
        /// Terminal output for background process signal.
        ///
        /// This signal is sent to a process when it attempts to write to the
        /// tty while in the background.
        TTY_OUT = libc::SIGTTOU,
        /// Urgent condition on socket signal.
        ///
        /// This signal is sent to a process when a socket has urgent or
        /// out-of-band data available to read.
        URGENT = libc::SIGURG,
        /// CPU time limit exceeded signal.
        ///
        /// This signal is sent to a process when it has used up the CPU for a
        /// duration that exceeds a certain predetermined user-settable value.
        EXCEEDED_CPU = libc::SIGXCPU,
        /// File size limit exceeded signal.
        ///
        /// This signal is sent to a process when it grows a file that exceeds
        /// the maximum allowed size.
        EXCEEDED_FILE_SIZE = libc::SIGXFSZ,
        /// Virtual timer alarm signal.
        ///
        /// This signal is sent to a process when a time limit is reached. This
        /// alarm is based on CPU time.
        ///
        /// Also see [`Signal::ALARM`] and [`Signal::PROFILE_ALARM`].
        VIRTUAL_ALARM = libc::SIGVTALRM,
        /// Profiling timer expired.
        ///
        /// This signal is sent to a process when a time limit is reached. This
        /// alarm is based on CPU time used by the process and the system
        /// itself.
        ///
        /// Also see [`Signal::ALARM`] and [`Signal::VIRTUAL_ALARM`].
        PROFILE_ALARM = libc::SIGPROF,
        /// Window resize signal.
        ///
        /// This signal is sent to a process when its controlling terminal
        /// changes its size.
        WINDOW_RESIZE = libc::SIGWINCH,
        /// I/O now possible.
        IO = libc::SIGIO,
        /// Pollable event.
        ///
        /// NOTE: same value as [`Signal::IO`].
        #[cfg(any(target_os = "android", target_os = "linux"))]
        POLL = libc::SIGPOLL,
        /// Power failure.
        #[cfg(any(target_os = "android", target_os = "linux"))]
        PWR = libc::SIGPWR,
        /// Bad system call signal.
        ///
        /// This signal is sent to a process when it passes a bad argument to a
        /// system call. This can also be received by applications violating the
        /// Linux Seccomp security rules configured to restrict them.
        SYS = libc::SIGSYS,
    }
);

impl Signal {
    /// Whether or not the signal is considered an "exiting" signal.
    ///
    /// Currently returns true for [`Signal::INTERRUPT`],
    /// [`Signal::TERMINATION`] and [`Signal::QUIT`].
    pub const fn should_exit(self) -> bool {
        matches!(self, Signal::INTERRUPT | Signal::TERMINATION | Signal::QUIT)
    }
}

impl fmt::Display for Signal {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match *self {
            Signal::HUP => "hangup",
            Signal::INTERRUPT => "interrupt",
            Signal::QUIT => "quit",
            Signal::ILLEGAL => "illegal",
            Signal::TRAP => "trap",
            Signal::ABORT => "abort",
            #[allow(unreachable_patterns)] // Same as ABORT.
            Signal::IOT => "iot",
            Signal::KILL => "kill",
            Signal::BUS => "bus",
            Signal::FP_ERROR => "floating-point-error",
            Signal::USER1 => "user-1",
            Signal::USER2 => "user-2",
            Signal::SEG_VAULT => "segfault",
            Signal::PIPE => "pipe",
            Signal::ALARM => "alarm",
            Signal::TERMINATION => "termination",
            Signal::CHILD => "child",
            Signal::CONTINUE => "continue",
            Signal::STOP => "stop",
            Signal::TERM_STOP => "terminal stop",
            Signal::TTY_IN => "terminal-input",
            Signal::TTY_OUT => "terminal-output",
            Signal::URGENT => "urgent",
            Signal::EXCEEDED_CPU => "exceeded-cpu",
            Signal::EXCEEDED_FILE_SIZE => "excess-file-size",
            Signal::VIRTUAL_ALARM => "virtual-alarm",
            Signal::PROFILE_ALARM => "profile-alarm",
            Signal::WINDOW_RESIZE => "window-change",
            Signal::IO => "I/O",
            #[cfg(any(target_os = "android", target_os = "linux"))]
            #[allow(unreachable_patterns)] // Same as IO.
            Signal::POLL => "poll",
            #[cfg(any(target_os = "android", target_os = "linux"))]
            Signal::PWR => "power-failure",
            Signal::SYS => "bad-syscall",
            _ => return write!(f, "Signal({})", self.0),
        })
    }
}

/// Who to send a signal to, see [`send_signal`].
#[derive(Copy, Clone, Debug)]
pub enum To {
    /// To a single process.
    Process(u32),
    /// Send the signal to all processes in the same process group as the
    /// current process.
    AllSameGroup,
    /// Send the signal to all processes in a specific process group.
    AllInGroup(u32),
    /// Send the signal to all processes to which the process has permission to
    /// send signals to.
    ///
    /// # Notes
    ///
    /// Depending on the OS various processes are excluded from this, e.g.
    /// process with id 1.
    All,
}

impl To {
    /// Send a signal to this process itself.
    pub fn this_process() -> To {
        To::Process(std::process::id())
    }

    /// Send a signal to a child process.
    pub fn child(child: &std::process::Child) -> To {
        To::Process(child.id())
    }
}

/// Send a process signal.
///
/// Also see [`send_signal_check`] to do an existence and permission check.
pub fn send_signal(to: To, signal: Signal) -> io::Result<()> {
    kill(to, signal.0)
}

/// Check for existence of a process and permission of sending a signal to it.
///
/// This can be used to check for the existence of a process or process group
/// that the caller is permitted to signal.
pub fn send_signal_check(to: To) -> io::Result<()> {
    kill(to, 0)
}

fn kill(to: To, signal: libc::c_int) -> io::Result<()> {
    let pid = match to {
        To::Process(pid) => pid.cast_signed(),
        To::AllSameGroup => 0,
        To::AllInGroup(id) => -(id.cast_signed()),
        To::All => -1,
    };
    syscall!(kill(pid, signal))?;
    Ok(())
}