//! Signal support for Unix-like systems.
//!
//! Signals in Unix are much more functional and versatile than ANSI C signals – there is simply much, much more of them. In addition to that, there is a special group of signals called "real-time signals" (more on those below).
//!
//! # Main signals
//! The [`SignalType`] enumeration provides all standard signals as defined in POSIX.1-2001. More signal types may be added later, which is why exhaustively matching on it is not possible. It can be cheaply converted to a 32-bit integer, though. See its documentation for more on conversions.
//!
//! The `set_handler` function is used to create an association between a `SignalType` and a signal handling strategy.
//!
//! # Real-time signals
//! In addition to usual signals, there's a special group of signals called "real-time signals". Those signals do not have fixed identifiers and are not generated by the system or kernel. Instead, they can only be sent between processes.
//!
//! # Signal-safe C functions
//! Very few C functions can be called from a signal handler. Allocating memory, using the thread API and manipulating interval timers, for example, is prohibited in a signal handler. Calling a function which is not signal safe results in undefined behavior, i.e. memory unsafety. Rather than excluding certain specific functions, the POSIX specification only speicifies functions which *are* signal-safe. The following C functions are guaranteed to be safe to call from a signal handler:
//! - `_Exit`
//! - `_exit`
//! - `abort`
//! - `accept`
//! - `access`
//! - `aio_error`
//! - `aio_return`
//! - `aio_suspend`
//! - `alarm`
//! - `bind`
//! - `cfgetispeed`
//! - `cfgetospeed`
//! - `cfsetispeed`
//! - `cfsetospeed`
//! - `chdir`
//! - `chmod`
//! - `chown`
//! - `clock_gettime`
//! - `close`
//! - `connect`
//! - `creat`
//! - `dup`
//! - `dup2`
//! - `execle`
//! - `execve`
//! - `fchmod`
//! - `fchown`
//! - `fcntl`
//! - `fdatasync`
//! - `fork`
//! - `fpathconf`
//! - `fstat`
//! - `fsync`
//! - `ftruncate`
//! - `getegid`
//! - `geteuid`
//! - `getgid`
//! - `getgroups`
//! - `getpeername`
//! - `getpgrp`
//! - `getpid`
//! - `getppid`
//! - `getsockname`
//! - `getsockopt`
//! - `getuid`
//! - `kill`
//! - `link`
//! - `listen`
//! - `lseek`
//! - `lstat`
//! - `mkdir`
//! - `mkfifo`
//! - `open`
//! - `pathconf`
//! - `pause`
//! - `pipe`
//! - `poll`
//! - `posix_trace_event`
//! - `pselect`
//! - `raise`
//! - `read`
//! - `readlink`
//! - `recv`
//! - `recvfrom`
//! - `recvmsg`
//! - `rename`
//! - `rmdir`
//! - `select`
//! - `sem_post`
//! - `send`
//! - `sendmsg`
//! - `sendto`
//! - `setgid`
//! - `setpgid`
//! - `setsid`
//! - `setsockopt`
//! - `setuid`
//! - `shutdown`
//! - `sigaction`
//! - `sigaddset`
//! - `sigdelset`
//! - `sigemptyset`
//! - `sigfillset`
//! - `sigismember`
//! - `signal`
//! - `sigpause`
//! - `sigpending`
//! - `sigprocmask`
//! - `sigqueue`
//! - `sigset`
//! - `sigsuspend`
//! - `sleep`
//! - `sockatmark`
//! - `socket`
//! - `socketpair`
//! - `stat`
//! - `symlink`
//! - `sysconf`
//! - `tcdrain`
//! - `tcflow`
//! - `tcflush`
//! - `tcgetattr`
//! - `tcgetpgrp`
//! - `tcsendbreak`
//! - `tcsetattr`
//! - `tcsetpgrp`
//! - `time`
//! - `timer_getoverrun`
//! - `timer_gettime`
//! - `timer_settime`
//! - `times`
//! - `umask`
//! - `uname`
//! - `unlink`
//! - `utime`
//! - `wait`
//! - `waitpid`
//! - `write`
//!
//! Many Rust crates, including the standard library, use signal-unsafe functions not on this list in safe code. For example, `Vec`, `Box` and `Rc`/`Arc` perform memory allocations, and `Mutex`/`RwLock` perform `pthread` calls. For this reason, creating a signal hook is an unsafe operation.
//!
//! [`SignalType`]: enum.SignalType.html " "

use super::imports::*;
use cfg_if::cfg_if;
use std::{
    convert::{TryFrom, TryInto},
    error::Error,
    fmt::{self, Display, Formatter},
    io,
    mem::zeroed,
    panic, process,
};
use to_method::To;

cfg_if! {
    if #[cfg(any(
        target_os = "linux",
        target_os = "android",
    ))] {
        // don't care about LinuxThreads lmao
        const SIGRTMIN: i32 = 34;
        const SIGRTMAX: i32 = 64;
    } else if #[cfg(target_os = "freebsd")] {
        const SIGRTMIN: i32 = 65;
        const SIGRTMAX: i32 = 126;
    } else if #[cfg(target_os = "netbsd")] {
        const SIGRTMIN: i32 = 33;
        const SIGRTMAX: i32 = 63;
    } else if #[cfg(target_os = "redox")] {
        const SIGRTMIN: i32 = 27;
        const SIGRTMAX: i32 = 31;
    } else {
        const SIGRTMIN: i32 = 1; // min is smaller than max so that the sloppy calculation works
        const SIGRTMAX: i32 = 0;
    }
}

/// Whether real-time signals are supported at all.
///
/// The platforms for which `interprocess` has explicit support for real-time signals are:
/// - Linux
///     - includes Android
/// - FreeBSD
/// - NetBSD
/// - Redox
pub const REALTIME_SIGNALS_SUPPORTED: bool = NUM_REALTIME_SIGNALS != 0;
/// How many real-time signals are supported. Remember that real-time signals start from 0, so this number is higher than the highest possible real-time signal by 1.
///
/// Platform-specific values for this constant are:
/// - **Linux** and **NetBSD**: 31
/// - **FreeBSD**: 62
/// - **Redox**: 5 (does not conform with POSIX)
pub const NUM_REALTIME_SIGNALS: u32 = (SIGRTMAX - SIGRTMIN + 1) as u32;
/// Returns `true` if the specified signal is a valid real-time signal value, `false` otherwise.
#[allow(clippy::absurd_extreme_comparisons)] // For systems where there are no realtime signals
pub const fn is_valid_rtsignal(rtsignal: u32) -> bool {
    rtsignal < NUM_REALTIME_SIGNALS
}

/// The first field is the current method of handling a specific signal, the second one is the flags which were set for it.
#[cfg(all(unix, feature = "signals"))]
type HandlerAndFlags = (SignalHandler, i32);

#[cfg(all(unix, feature = "signals"))]
static HANDLERS: Lazy<RwLock<IntMap<HandlerAndFlags>>> = Lazy::new(|| RwLock::new(IntMap::new()));

/// Installs the specified handler for the specified standard signal, using the default values for the flags.
///
/// See [`HandlerOptions`] builder if you'd like to customize the flags.
///
/// # Example
/// ```no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # #[cfg(all(unix, feature = "signals"))] {
/// use interprocess::os::unix::signal::{self, SignalType, SignalHandler};
///
/// let handler = unsafe {
///     // Since signal handlers are restricted to a specific set of C functions, creating a
///     // handler from an arbitrary function is unsafe because it might call a function
///     // outside the list, and there's no real way to know that at compile time with the
///     // current version of Rust. Since we're only using the write() system call here, this
///     // is safe.
///     SignalHandler::from_fn(|| {
///         println!("You pressed Ctrl-C!");
///     })
/// };
///
/// // Install our handler for the KeyboardInterrupt signal type.
/// signal::set_handler(SignalType::KeyboardInterrupt, handler)?;
/// # }
/// # Ok(()) }
/// ```
///
/// [`HandlerOptions`]: struct.HandlerOptions.html " "
pub fn set_handler(signal_type: SignalType, handler: SignalHandler) -> Result<(), SetHandlerError> {
    HandlerOptions::for_signal(signal_type)
        .set_new_handler(handler)
        .set()
}
/// Installs the specified handler for the specified unsafe signal, using the default values for the flags.
///
/// See [`HandlerOptions`] builder if you'd like to customize the flags.
///
/// # Safety
/// See the [`set_unsafe`] safety notes.
///
/// # Example
/// ```no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # #[cfg(all(unix, feature = "signals"))] {
/// use interprocess::os::unix::signal::{self, SignalType, SignalHandler};
///
/// let handler = unsafe {
///     // Since signal handlers are restricted to a specific set of C functions, creating a
///     // handler from an arbitrary function is unsafe because it might call a function
///     // outside the list, and there's no real way to know that at compile time with the
///     // current version of Rust. Since we're only using the write() system call here, this
///     // is safe.
///     SignalHandler::from_fn(|| {
///         println!("Oh no, the motherboard broke!");
///         std::process::abort();
///     })
/// };
///
/// unsafe {
///     // Install our handler for the MemoryBusError signal type.
///     signal::set_unsafe_handler(SignalType::MemoryBusError, handler)?;
/// }
/// # }
/// # Ok(()) }
/// ```
///
/// [`HandlerOptions`]: struct.HandlerOptions.html " "
/// [`set_unsafe`]: struct.HandlerOptions.html#method.set_unsafe " "
pub unsafe fn set_unsafe_handler(
    signal_type: SignalType,
    handler: SignalHandler,
) -> Result<(), SetHandlerError> {
    unsafe {
        HandlerOptions::for_signal(signal_type)
            .set_new_handler(handler)
            .set_unsafe()
    }
}
/// Installs the specified handler for the specified real-time signal, using the default values for the flags.
///
/// See [`HandlerOptions`] builder if you'd like to customize the flags.
///
/// # Example
/// ```no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # #[cfg(all(unix, feature = "signals"))] {
/// use interprocess::os::unix::signal::{self, SignalHandler};
///
/// let handler = unsafe {
///     // Since signal handlers are restricted to a specific set of C functions, creating a
///     // handler from an arbitrary function is unsafe because it might call a function
///     // outside the list, and there's no real way to know that at compile time with the
///     // current version of Rust. Since we're only using the write() system call here, this
///     // is safe.
///     SignalHandler::from_fn(|| {
///         println!("You sent a real-time signal!");
///     })
/// };
///
/// // Install our handler for the real-time signal 0.
/// signal::set_rthandler(0, handler)?;
/// # }
/// # Ok(()) }
/// ```
///
/// [`HandlerOptions`]: struct.HandlerOptions.html " "
pub fn set_rthandler(rtsignal: u32, handler: SignalHandler) -> Result<(), SetHandlerError> {
    HandlerOptions::for_rtsignal(rtsignal)
        .set_new_handler(handler)
        .set()
}

unsafe fn install_hook(signum: i32, hook: usize, flags: i32) -> io::Result<()> {
    let success = {
        let [mut old_handler, mut new_handler] = unsafe {
            // SAFETY: sigaction only consists of integers and therefore can
            // contain an all-0 bit pattern
            [zeroed::<sigaction>(); 2]
        };
        new_handler.sa_sigaction = hook;
        new_handler.sa_flags = flags;
        unsafe {
            // SAFETY: all the pointers that are being passed come from references and only involve
            // a single cast, which means that it's just a reference-to-pointer cast and not a
            // pointer-to-pointer cast (the latter can cast any pointer to any other pointer, but
            // you need two casts in order to convert a reference to a pointer to an arbitrary type)
            libc::sigaction(signum, &new_handler as *const _, &mut old_handler as *mut _) != -1
        }
    };
    if success {
        Ok(())
    } else {
        Err(io::Error::last_os_error())
    }
}

/// Options for installing a signal handler.
///
/// # Example
/// ```no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # #[cfg(all(unix, feature = "signals"))] {
/// use interprocess::os::unix::signal::{self, SignalType, SignalHandler};
///
/// let handler = unsafe {
///     // Since signal handlers are restricted to a specific set of C functions, creating a
///     // handler from an arbitrary function is unsafe because it might call a function
///     // outside the list, and there's no real way to know that at compile time with the
///     // current version of Rust. Since we're only using the write() system call here, this
///     // is safe.
///     SignalHandler::from_fn(|| {
///         println!("You pressed Ctrl-C!");
///     })
/// };
///
/// // Let's use the builder to customize the signal handler:
/// signal::HandlerOptions::for_signal(SignalType::KeyboardInterrupt)
///     .set_new_handler(handler)
///     .auto_reset_handler(true) // Let's remove the signal handler after it fires once.
///     .system_call_restart(false) // Avoid restarting system calls and let them fail with the
///                                 // Interrupted error type. There normally isn't a reason to
///                                 // do this, but for the sake of the example, let's assume
///                                 // that there is.
///     .set()?; // Finalize the builder by installing the handler.
/// # }
/// # Ok(()) }
/// ```
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
#[must_use = "the signal handler is attached by calling `.set()`, which consumes the builder"]
pub struct HandlerOptions {
    signal: i32,
    /// The handler to be set up. If `None`, the handler is not changed by the call.
    pub handler: Option<SignalHandler>,
    /// For the [`ChildProcessEvent`] signal, this option *disables* receiving the signal if it was generated because the child process was suspended (using any signal which suspends a process, such as [`Suspend`] or [`ForceSuspend`]) or [resumed][`Continue`].
    ///
    /// If enabled on a signal which is not [`ChildProcessEvent`], a panic is produced in debug builds when [`set`] is called; in release builds, the flag is simply ignored.
    ///
    /// [`ChildProcessEvent`]: enum.SignalType.html#variant.ChildProcessEvent " "
    /// [`Suspend`]: enum.SignalType.html#variant.Suspend " "
    /// [`ForceSuspend`]: enum.SignalType.html#variant.ForceSuspend " "
    /// [`Continue`]: enum.SignalType.html#variant.Continue " "
    /// [`set`]: #method.set " "
    pub ignore_child_stop_events: bool,
    /// Allow the signal handler to interrupt a previous invocation of itself. If disabled, the signal handler will disable its own signal when called and restore previous state when it finishes executing. If not, an infinite amount of signals can be received on top of each other, which is likely a stack overflow risk.
    ///
    /// If enabled but the handler is [set to use the default handling method][`Default`] from the OS, a panic is produced in debug builds when [`set`] is called; in release builds, the flag is simply ignored.
    ///
    /// [`Default`]: enum.SignalHandler.html#variant.Default " "
    /// [`set`]: #method.set " "
    pub recursive_handler: bool,
    /// Automatically restart certain system calls instead of failing with the [`Interrupted`] error type. Some other system calls are not restarted with this function and may fail with [`Interrupted`] anyway. Consult your manual pages for more details.
    ///
    /// [`Interrupted`]: https://doc.rust-lang.org/std/io/enum.ErrorKind.html#variant.Interrupted " "
    pub system_call_restart: bool,
    /// Automatically reset the handler to the default handling method whenever it is executed.
    ///
    /// If enabled but the handler is [set to use the default handling method][`Default`] from the OS, a panic is produced in debug builds when [`set`] is called; in release builds, the flag is simply ignored.
    ///
    /// [`Default`]: enum.SignalHandler.html#variant.Default " "
    /// [`set`]: #method.set " "
    pub auto_reset_handler: bool,
}
impl HandlerOptions {
    /// Creates a builder for a handler for the specified signal.
    pub fn for_signal(signal: SignalType) -> Self {
        Self {
            signal: signal.into(),
            handler: None,
            ignore_child_stop_events: false,
            recursive_handler: false,
            system_call_restart: true,
            auto_reset_handler: false,
        }
    }
    /// Creates a builder for a handler for the specified real-time signal.
    ///
    /// # Panics
    /// Guaranteed to panic if the specified real-time signal is outside the range of real-time signals supported by the OS. See [`NUM_REALTIME_SIGNALS`].
    ///
    /// [`NUM_REALTIME_SIGNALS`]: constant.NUM_REALTIME_SIGNALS.html " "
    pub fn for_rtsignal(rtsignal: u32) -> Self {
        assert!(
            is_valid_rtsignal(rtsignal),
            "invalid real-time signal value – check the NUM_REALTIME_SIGNALS constant to see how \
            many are supported"
        );
        Self {
            signal: rtsignal as i32,
            handler: None,
            ignore_child_stop_events: false,
            recursive_handler: false,
            system_call_restart: true,
            auto_reset_handler: false,
        }
    }
    /// Sets the handler for the signal to the specified value. If `None`, the old value is used.
    pub fn set_new_handler(mut self, handler: impl Into<Option<SignalHandler>>) -> Self {
        self.handler = handler.into();
        self
    }
    /// Sets the [`ignore_child_stop_events`] flag to the specified value.
    ///
    /// [`ignore_child_stop_events`]: #structfield.ignore_child_stop_events " "
    pub fn ignore_child_stop_events(mut self, ignore: impl Into<bool>) -> Self {
        self.ignore_child_stop_events = ignore.into();
        self
    }
    /// Sets the [`recursive_handler`] flag to the specified value.
    ///
    /// [`recursive_handler`]: #structfield.recursive_handler " "
    pub fn recursive_handler(mut self, recursive: impl Into<bool>) -> Self {
        self.recursive_handler = recursive.into();
        self
    }
    /// Sets the [`system_call_restart`] flag to the specified value.
    ///
    /// [`system_call_restart`]: #structfield.system_call_restart " "
    pub fn system_call_restart(mut self, restart: impl Into<bool>) -> Self {
        self.system_call_restart = restart.into();
        self
    }
    /// Sets the [`auto_reset_handler`] flag to the specified value.
    ///
    /// [`auto_reset_handler`]: #structfield.auto_reset_handler " "
    pub fn auto_reset_handler(mut self, reset: impl Into<bool>) -> Self {
        self.auto_reset_handler = reset.into();
        self
    }
    /// Installs the signal handler.
    pub fn set(self) -> Result<(), SetHandlerError> {
        if let Ok(val) = SignalType::try_from(self.signal) {
            if val.is_unsafe() {
                return Err(SetHandlerError::UnsafeSignal);
            }
        }
        unsafe { self.set_unsafe() }
    }

    /// Installs the signal handler, even if the signal being handled is unsafe.
    ///
    /// # Safety
    /// The handler and all code that may or may not execute afterwards must be prepared for the aftermath of what might've caused the signal.
    ///
    /// [`SegmentationFault`] or [`BusError`] are most likely caused by undefined behavior invoked from Rust (the former is caused by dereferencing invalid memory, the latter is caused by dereferencing an incorrectly aligned pointer on ISAs like ARM which do not tolerate misaligned pointers), which means that the program is unsound and the only meaningful thing to do is to capture as much information as possible in a safe way – preferably using OS services to create a dump, rather than trying to read the program's global state, which might be irreversibly corrupted – and write the crash dump to some on-disk location.
    ///
    /// [`SegmentationFault`]: enum.SignalType.html#variant.SegmentationFault " "
    /// [`BusError`]: enum.SignalType.html#variant.BusError " "
    pub unsafe fn set_unsafe(self) -> Result<(), SetHandlerError> {
        if let Ok(val) = SignalType::try_from(self.signal) {
            if val.is_unblockable() {
                return Err(SetHandlerError::UnblockableSignal(val));
            }
        } else if !is_valid_rtsignal(self.signal as u32) {
            return Err(SetHandlerError::RealTimeSignalOutOfBounds {
                attempted: self.signal as u32,
                max: NUM_REALTIME_SIGNALS,
            });
        }
        let handlers = HANDLERS.read();
        let new_flags = self.flags_as_i32();
        let mut need_to_upgrade_handle = false;
        let need_to_install_hook =
            if let Some((existing_handler, existing_flags)) = handlers.get(self.signal as u64) {
                // This signal's handler was set before – check if we need to install new flags or if
                // one is default and another isn't, which would mean that either that no hook was
                // installed and we have to install one or there was one installed but we need to
                // install the default hook explicitly.
                let new_handler = self.handler.unwrap_or_default();
                if new_handler != *existing_handler || new_flags != *existing_flags {
                    need_to_upgrade_handle = true;
                    true
                } else {
                    let one_handler_is_default_and_another_isnt = (new_handler.is_default()
                        && !existing_handler.is_default())
                        || (!new_handler.is_default() && existing_handler.is_default());
                    *existing_flags != new_flags || one_handler_is_default_and_another_isnt
                }
            } else {
                need_to_upgrade_handle = true;
                !self.handler.unwrap_or_default().is_default()
            };
        drop(handlers);
        if need_to_upgrade_handle {
            let mut handlers = HANDLERS.write();
            let signal_u64 = self.signal as u64;
            handlers.remove(signal_u64);
            handlers.insert(signal_u64, (self.handler.unwrap_or_default(), new_flags));
        }
        if need_to_install_hook {
            let hook_val = match self.handler.unwrap_or_default() {
                SignalHandler::Default => SIG_DFL,
                _ => signal_receiver as usize,
            };
            unsafe {
                // SAFETY: we're using a correct value for the hook
                install_hook(self.signal, hook_val, new_flags)?
            }
        }
        Ok(())
    }

    fn flags_as_i32(self) -> i32 {
        if self.handler.unwrap_or_default().is_default() {
            debug_assert!(
                !self.recursive_handler,
                "cannot use the recursive_handler flag with the default handling method",
            );
        }
        if self.signal != SIGCHLD {
            debug_assert!(
                !self.ignore_child_stop_events,
                "\
cannot use the ignore_child_stop_events flag when the signal to be handled isn't \
ChildProcessEvent",
            );
        }
        let mut flags = 0;
        if self.auto_reset_handler {
            flags |= SA_RESETHAND;
        }
        if self.ignore_child_stop_events {
            flags |= SA_NOCLDSTOP;
        }
        if self.recursive_handler {
            flags |= SA_NODEFER;
        }
        if self.system_call_restart {
            flags |= SA_RESTART;
        }
        flags
    }
}

/// The error produced when setting a signal handler fails.
#[derive(Debug)]
#[cfg_attr(all(unix, feature = "signals"), derive(Error))]
pub enum SetHandlerError {
    /// An unsafe signal was attempted to be handled using `set` instead of `set_unsafe`.
    #[cfg_attr(
        all(unix, feature = "signals"),
        error("an unsafe signal was attempted to be handled using `set` instead of `set_unsafe`")
    )]
    UnsafeSignal,
    /// The signal which was attempted to be handled is not allowed to be handled by the POSIX specification. This can either be [`ForceSuspend`] or [`Kill`].
    ///
    /// [`Kill`]: enum.SignalType.html#variant.Kill " "
    /// [`ForceSuspend`]: enum.SignalType.html#variant.ForceSuspend " "
    #[cfg_attr(
        all(unix, feature = "signals"),
        error("the signal {:?} cannot be handled", .0),
    )]
    UnblockableSignal(SignalType),
    /// The specified real-time signal is not available on this OS.
    #[cfg_attr(
        all(unix, feature = "signals"),
        error(
            "the real-time signal number {} is not available ({} is the highest possible)",
            .attempted,
            .max,
        ),
    )]
    RealTimeSignalOutOfBounds {
        /// The realtime signal which was attempted to be used.
        attempted: u32,
        /// The highest available realtime signal number.
        max: u32,
    },
    /// An unexpected OS error ocurred during signal handler setup.
    #[cfg_attr(
        all(unix, feature = "signals"),
        error("{}", .0),
    )]
    UnexpectedSystemCallFailure(#[cfg_attr(all(unix, feature = "signals"), from)] io::Error),
}

/// The actual hook which is passed to `sigaction` which dispatches signals according to the global handler map (the `HANDLERS` static).
extern "C" fn signal_receiver(signum: i32) {
    let catched = panic::catch_unwind(|| {
        let handler_and_flags = {
            let handlers = HANDLERS.read();
            let val = handlers
                .get(signum as u64)
                .expect("unregistered signal passed by the OS to the shared receiver");
            *val
        };
        match handler_and_flags.0 {
            SignalHandler::Ignore => {}
            SignalHandler::Hook(hook) => hook.inner()(),
            SignalHandler::Default => unreachable!(
                "signal receiver was unregistered but has been called by the OS anyway"
            ),
        }
        if handler_and_flags.1 & SA_RESETHAND != 0 {
            // If the signal is set to be reset to default handling, set the record accordingly.
            let mut handlers = HANDLERS.write();
            handlers.remove(signum as u64);
            let handler_and_flags = (SignalHandler::Default, handler_and_flags.1);
            handlers.insert(signum as u64, handler_and_flags);
        }
    });
    // The panic hook already ran, so we only have to abort the process
    catched.unwrap_or_else(|_| process::abort());
}

/// A signal handling method.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum SignalHandler {
    /// Use the default behavior specified by POSIX.
    Default,
    /// Ignore the signal whenever it is received.
    Ignore,
    /// Call a function whenever the signal is received.
    Hook(SignalHook),
}
impl SignalHandler {
    /// Returns `true` for the [`Default`] variant, `false` otherwise.
    ///
    /// [`Default`]: #variant.Default.html " "
    pub const fn is_default(self) -> bool {
        matches!(self, Self::Default)
    }
    /// Returns `true` for the [`Ignore`] variant, `false` otherwise.
    ///
    /// [`Ignore`]: #variant.Ignore.html " "
    pub const fn is_ignore(self) -> bool {
        matches!(self, Self::Ignore)
    }
    /// Returns `true` for the [`Hook`] variant, `false` otherwise.
    ///
    /// [`Hook`]: #variant.Hook.html " "
    pub const fn is_hook(self) -> bool {
        matches!(self, Self::Hook(..))
    }
    /// Creates a handler which calls the specified function.
    ///
    /// # Safety
    /// The function must not call any C functions which are not considered signal-safe. See the [module-level section on signal-safe C functions] for more.
    ///
    /// [module-level section on signal-safe C functions]: index.html#signal-safe-c-functions " "
    pub unsafe fn from_fn(function: fn()) -> Self {
        Self::Hook(unsafe { SignalHook::from_fn(function) })
    }
}
impl Default for SignalHandler {
    /// Returns [`SignalHandler::Default`].
    ///
    /// [`SignalHandler::Default`]: #variant.Default " "
    fn default() -> Self {
        Self::Default
    }
}
impl From<SignalHook> for SignalHandler {
    fn from(op: SignalHook) -> Self {
        Self::Hook(op)
    }
}
/// A function which can be used as a signal handler.
#[repr(transparent)]
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct SignalHook(fn());
impl SignalHook {
    /// Creates a hook which calls the specified function.
    ///
    /// # Safety
    /// The function must not call any C functions which are not considered signal-safe. See the [module-level section on signal-safe C functions] for more.
    ///
    /// [module-level section on signal-safe C functions]: index.html#signal-safe-c-functions " "
    pub unsafe fn from_fn(function: fn()) -> Self {
        Self(function)
    }
    /// Returns the wrapped function.
    pub fn inner(self) -> fn() {
        self.0
    }
}
impl From<SignalHook> for fn() {
    fn from(op: SignalHook) -> Self {
        op.0
    }
}

/// Sends the specified signal to the specified process. If the specified signal is `None`, no signal is sent and only a privilege check is performed instead.
///
/// # Example
/// ```no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # #[cfg(all(unix, feature = "signals"))] {
/// use interprocess::os::unix::signal::{self, SignalType};
/// use std::process;
///
/// // Send a Termination signal to the calling process.
/// signal::send(SignalType::Termination, process::id())?;
/// # }
/// # Ok(()) }
/// ```
pub fn send(signal: impl Into<Option<SignalType>>, pid: impl Into<u32>) -> io::Result<()> {
    let pid = pid
        .to::<u32>()
        .try_to::<i32>()
        .unwrap_or_else(|_| panic!("process identifier out of range"));
    debug_assert_ne!(
        pid, 0,
        "to send the signal to the process group of the calling process, use send_to_group instead"
    );
    let success = unsafe { libc::kill(signal.into().map_or(0, Into::into), pid) != -1 };
    if success {
        Ok(())
    } else {
        Err(io::Error::last_os_error())
    }
}
/// Sends the specified real-time signal to the specified process. If the specified signal is `None`, no signal is sent and only a privilege check is performed instead.
///
/// # Example
/// ```no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # #[cfg(all(unix, feature = "signals"))] {
/// use interprocess::os::unix::signal::{self, SignalType};
/// use std::process;
///
/// // Send a real-timne signal 0 to the calling process.
/// signal::send_rt(0, process::id())?;
/// # }
/// # Ok(()) }
/// ```
pub fn send_rt(signal: impl Into<Option<u32>>, pid: impl Into<u32>) -> io::Result<()> {
    let pid = pid
        .to::<u32>()
        .try_to::<i32>()
        .unwrap_or_else(|_| panic!("process identifier out of range"));
    debug_assert_ne!(
        pid, 0,
        "to send the signal to the process group of the calling process, use send_to_group instead"
    );
    let signal = signal.into().map_or(0, |val| {
        assert!(is_valid_rtsignal(val), "invalid real-time signal");
        val
    }) as i32;
    let success = unsafe { libc::kill(signal, pid) != -1 };
    if success {
        Ok(())
    } else {
        Err(io::Error::last_os_error())
    }
}
/// Sends the specified signal to the specified process group. If the specified signal is `None`, no signal is sent and only a privilege check is performed instead.
///
/// # Example
/// ```no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # #[cfg(all(unix, feature = "signals"))] {
/// use interprocess::os::unix::signal::{self, SignalType};
/// use std::process;
///
/// // Send a Termination signal to the process group of the calling process.
/// signal::send_to_group(SignalType::Termination, 0_u32)?;
/// # }
/// # Ok(()) }
/// ```
pub fn send_to_group(signal: impl Into<Option<SignalType>>, pid: impl Into<u32>) -> io::Result<()> {
    #[allow(clippy::neg_multiply)] // "it's more readable to just negate"? how about no
    let pid = pid
        .to::<u32>()
        .try_to::<i32>()
        .unwrap_or_else(|_| panic!("process group identifier out of range"))
        * -1;
    let success = unsafe { libc::kill(signal.into().map_or(0, Into::into), pid) != -1 };
    if success {
        Ok(())
    } else {
        Err(io::Error::last_os_error())
    }
}
/// Sends the specified real-time signal to the specified process. If the specified signal is `None`, no signal is sent and only a privilege check is performed instead.
///
/// # Example
/// ```no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # #[cfg(all(unix, feature = "signals"))] {
/// use interprocess::os::unix::signal::{self, SignalType};
/// use std::process;
///
/// // Send a real-timne signal 0 to the process group of the calling process.
/// signal::send_rt(0_u32, 0_u32)?;
/// # }
/// # Ok(()) }
/// ```
pub fn send_rt_to_group(signal: impl Into<Option<u32>>, pid: impl Into<u32>) -> io::Result<()> {
    #[allow(clippy::neg_multiply)]
    let pid = pid
        .to::<u32>()
        .try_to::<i32>()
        .unwrap_or_else(|_| panic!("process identifier out of range"))
        * -1;
    debug_assert_ne!(
        pid, 0,
        "to send the signal to the process group of the calling process, use send_to_group instead"
    );
    let signal = signal.into().map_or(0, |val| {
        assert!(is_valid_rtsignal(val), "invalid real-time signal");
        val
    }) as i32;
    let success = unsafe { libc::kill(signal, pid) != -1 };
    if success {
        Ok(())
    } else {
        Err(io::Error::last_os_error())
    }
}

/// All standard signal types as defined in POSIX.1-2001.
///
/// The values can be safely and quickly converted to [`i32`]/[`u32`]. The reverse process involves safety checks, making sure that unknown signal values are never stored.
///
/// [`i32`]: https://doc.rust-lang.org/std/primitive.i32.html " "
/// [`u32`]: https://doc.rust-lang.org/std/primitive.u32.html " "
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
#[repr(i32)]
#[non_exhaustive]
pub enum SignalType {
    /// `SIGHUP` – lost connection to controlling terminal. Opting out of this signal is recommended if the process does not need to stop after the user who started it logs out.
    ///
    /// *Default handler: process termination.*
    #[cfg(any(doc, se_basic))]
    Hangup = SIGHUP,
    /// `SIGINT` – keyboard interrupt, usually sent by pressing `Ctrl`+`C` by the terminal. This signal is typically set to be ignored if the program runs an interactive interface: GUI/TUI, interactive shell (the Python shell, for example) or any other kind of interface which runs in a loop, as opposed to a command-line invocation of the program which reads its standard input or command-line arguments, performs a task and exits. If the interactive interface is running a lengthy operation, a good idea is to temporarily re-enable the signal and abort the lengthy operation if the signal is received, then disable it again.
    ///
    /// *Default handler: process termination.*
    #[cfg(any(doc, se_basic))]
    KeyboardInterrupt = SIGINT,
    /// `SIGQUIT` – request to perform a core dump and quit, usually sent by pressing `Ctrl`+`\`. This signal normally should not be overriden or masked out – the core dump is performed automatically by the OS.
    ///
    /// *Default handler: process termination with a core dump.*
    #[cfg(any(doc, se_basic))]
    QuitAndDump = SIGQUIT,
    /// `SIGILL` – illegal or malformed instruction exception, generated by the CPU whenever such an instruction is executed. This signal normally should not be overriden or masked out, since it likely means that the executable file or the memory of the process has been corrupted and further execution is a risk of invoking negative consequences.
    ///
    /// For reasons described above, **this signal is considered unsafe** – handling it requires using `set_unsafe_handler`.
    ///
    /// *Default handler: process termination with a core dump.*
    #[cfg(any(doc, se_basic))]
    IllegalInstruction = SIGILL,
    /// `SIGABRT` – abnormal termination requested. This signal is typically invoked by the program itself, using [`std::process::abort`] or the equivalent C function; still, like any other signal, it can be sent from outside the process.
    ///
    /// *Default handler: process termination with a core dump.*
    ///
    /// [`std::process::abort`]: https://doc.rust-lang.org/std/process/fn.abort.html " "
    #[cfg(any(doc, se_basic))]
    Abort = SIGABRT,
    /// `SIGFPE` – mathematical exception. This signal is generated whenever an undefined mathematical operation is performed – mainly integer division by zero.
    ///
    /// *Default handler: process termination with a core dump.*
    #[cfg(any(doc, se_basic))]
    MathException = SIGFPE,
    /// `SIGKILL` – forced termination. This signal can only be sent using the usual signal sending procedures and, unlike most other signals, cannot be masked out or handled at all. The main purpose for this signal is to stop a program which has masked out all other signals for malicious purposes or has stuck in such a state because of a bug.
    ///
    /// *Default handler: process termination, **cannot be overriden or disabled**.*
    #[cfg(any(doc, se_basic))]
    Kill = SIGKILL,
    /// `SIGSEGV` – invaid memory access. This signal is issued by the OS whenever the program tries to access an invalid memory location, such as the `NULL` pointer or simply an address outside the user-mode address space as established by the OS. The only case when this signal can be received by a Rust program is if memory unsafety occurs due to misuse of unsafe code. As such, it should normally not be masked out or handled, as it likely indicates a critical bug (soundness hole), executable file corruption or process memory corruption.
    ///
    /// For reasons described above, **this signal is considered unsafe** – handling it requires using `set_unsafe_handler`.
    ///
    /// *Default handler: process termination with a core dump.*
    #[cfg(any(doc, se_basic))]
    SegmentationFault = SIGSEGV,
    /// `SIGPIPE` – invalid access to an [unnamed pipe]. This signal is issued by the OS whenever a program attempts to write to an unnamed pipe which has no readers connected to it. If unexpected, this might mean abnormal termination of the process which the pipe was used to communicate with.
    ///
    /// *Default handler: process termination.*
    ///
    /// [unnamed pipe]: ../../../unnamed_pipe/index.html " "
    #[cfg(any(doc, se_basic))]
    BrokenPipe = SIGPIPE,
    /// `SIGALRM` – "alarm clock" signal. This signal is issued by the OS when the arranged amount of real (wall clock) time expires. This clock can be set using the [`alarm`] and [`setitimer`] system calls.
    ///
    /// *Default handler: process termination.*
    ///
    /// [`alarm`]: https://www.man7.org/linux/man-pages/man2/alarm.2.html " "
    /// [`setitimer`]: https://www.man7.org/linux/man-pages/man2/setitimer.2.html " "
    #[cfg(any(doc, se_basic))]
    AlarmClock = SIGALRM,
    /// `SIGTERM` – request for termination. This signal can only be sent using the usual signal sending procedures. Unlike [`KeyboardInterrupt`], this signal is not a request to break out of a lengthy operation, but rather to close the program as a whole. Signal handlers for this signal are expected to perform minimal cleanup and quick state save procedures and then exit.
    ///
    /// *Default handler: process termination.*
    ///
    /// [`KeyboardInterrupt`]: #variant.KeyboardInterrupt " "
    #[cfg(any(doc, se_basic))]
    Termination = SIGTERM,
    /// `SIGUSR1` – user-defined signal 1. This signal, like [`UserSignal2`], does not have a predefined meaning and is not produced by the OS. For this reason, it is typically used for interprocess communication between two programs familiar with each other, or in language runtimes to signal certain events, such as externally activated immediate garbage collection.
    ///
    /// *Default handler: process termination.*
    ///
    /// [`UserSignal2`]: #variant.UserSignal2 " "
    #[cfg(any(doc, se_full_posix_1990))]
    #[cfg_attr( // se_full_posix_1990/se_base_posix_2001 templat
        feature = "doc_cfg",
        doc(cfg(not(target_os = "hermit"))),
    )]
    UserSignal1 = SIGUSR1,
    /// `SIGUSR2` – user-defined signal 2. This signal is similar to [`UserSignal1`] and has the same properties, but is a distinct signal nonetheless.
    ///
    /// *Default handler: process termination.*
    ///
    /// [`UserSignal1`]: #variant.UserSignal1 " "
    #[cfg(any(doc, se_full_posix_1990))]
    #[cfg_attr( // se_full_posix_1990/se_base_posix_2001 templat
        feature = "doc_cfg",
        doc(cfg(not(target_os = "hermit"))),
    )]
    UserSignal2 = SIGUSR2,
    /// `SIGCHLD` – child process suspended, resumed or terminated. This signal is issued by the OS whenever a child process is suspended/resumed or terminated by a signal or otherwise.
    ///
    /// *Default handler: ignore.*
    #[cfg(any(doc, se_full_posix_1990))]
    #[cfg_attr( // se_full_posix_1990/se_base_posix_2001 templat
        feature = "doc_cfg",
        doc(cfg(not(target_os = "hermit"))),
    )]
    ChildProcessEvent = SIGCHLD,
    /// `SIGCONT` – resume the process after being suspended. This signal can be sent to a process by an external program when it wishes to resume that process after it being suspended in a stopped state.
    ///
    /// *Default handler: continue execution.*
    #[cfg(any(doc, se_full_posix_1990))]
    #[cfg_attr( // se_full_posix_1990/se_base_posix_2001 templat
        feature = "doc_cfg",
        doc(cfg(not(target_os = "hermit"))),
    )]
    Continue = SIGCONT,
    /// `SIGSTOP` – forcefully stop a process temporarily. This signal can only be sent to a process by an external program. Unlike [`Suspend`], this signal cannot be masked out or handled, i.e. it is guaranteed to be able to temporarily stop a process from executing without [forcefully terminating it]. The process can then be restarted using [`Continue`].
    ///
    /// *Default handler: temporarily stop process, **cannot be overriden or disabled**.*
    ///
    /// [`Suspend`]: #variant.Suspend " "
    /// [forcefully terminating it]: #variant.Kill " "
    /// [`Continue`]: #variant.Continue " "
    #[cfg(any(doc, se_full_posix_1990))]
    #[cfg_attr( // se_full_posix_1990/se_base_posix_2001 templat
        feature = "doc_cfg",
        doc(cfg(not(target_os = "hermit"))),
    )]
    ForceSuspend = SIGSTOP,
    /// `SIGTSTP` – temporarily stop a process. This signal can only be sent to a process by an external program. Unlike [`ForceSuspend`], this signal can be masked out or handled by the process which is requested to stop. The process can then be restarted using [`Continue`].
    ///
    /// *Default handler: temporarily stop process.*
    ///
    /// [`ForceSuspend`]: #variant.ForceSuspend " "
    /// [`Continue`]: #variant.Continue " "
    #[cfg(any(doc, se_full_posix_1990))]
    #[cfg_attr( // se_full_posix_1990/se_base_posix_2001 templat
        feature = "doc_cfg",
        doc(cfg(not(target_os = "hermit"))),
    )]
    Suspend = SIGTSTP,
    /// `SIGTTIN` – attempt to read from standard input while in the background. This signal is issued by the OS whenever a process which is under [job control] tries to read from standard input but is in the background, i.e. temporarily detached from the terminal.
    ///
    /// *Default handler: temporarily stop process.*
    ///
    /// [job control]: https://en.wikipedia.org/wiki/Job_control_(Unix) " "
    #[cfg(any(doc, se_full_posix_1990))]
    #[cfg_attr( // se_full_posix_1990/se_base_posix_2001 templat
        feature = "doc_cfg",
        doc(cfg(not(target_os = "hermit"))),
    )]
    TerminalInputWhileInBackground = SIGTTIN,
    /// `SIGTTOU` – attempt to write to standard output while in the background. This signal is issued by the OS whenever a process which is under [job control] tries to write to standard input but is in the background, i.e. temporarily detached from the terminal.
    ///
    /// *Default handler: temporarily stop process.*
    ///
    /// [job control]: https://en.wikipedia.org/wiki/Job_control_(Unix) " "
    #[cfg(any(doc, se_full_posix_1990))]
    #[cfg_attr( // se_full_posix_1990/se_base_posix_2001 templat
        feature = "doc_cfg",
        doc(cfg(not(target_os = "hermit"))),
    )]
    TerminalOutputWhileInBackground = SIGTTOU,
    /// `SIGPOLL` – watched file descriptor event. This signal is issued by the OS when a file descriptor which has been enabled to interact with this signal has a state update.
    ///
    /// *Default handler: process termination.*
    // TODO more on this
    #[cfg(any(se_sigpoll, se_sigpoll_is_sigio))]
    #[cfg_attr( // any(se_sigpoll, se_sigpoll_is_sigio) template
        feature = "doc_cfg",
        doc(cfg(any(
            target_os = "linux",
            target_os = "android",
            target_os = "emscripten",
            target_os = "redox",
            target_os = "haiku",
            target_os = "solaris",
            target_os = "illumos"
        )))
    )]
    PollNotification = SIGPOLL,
    /// `SIGBUS` – [bus error]. This signal is issued by the OS when a process does one of the following:
    /// - **Tries to access an invalid physical address**. Normally, this should never happen – attempts to access invalid *virtual* memory are handled as [segmentation faults], and invalid phyiscal addresses are typically not present in the address space of a program in user-mode.
    /// - **Performs an incorrectly aligned memory access**. In Rust, this can only happen if unsafe code is misused to construct an incorrectly aligned pointer to a type which requires alignment which is more strict than simple one byte alignment. This is a direct sign of memory unsafety being invoked.
    /// - **Incorrect x86 segment register**. This can only be acheieved using inline assembly or FFI (calling an external function written in assembly language or with usage of C/C++ inline assembly), and only on the x86 architecture. If an invalid value is loaded into the segment registers, the CPU generates this exception. This is either a sign of a failed advanced unsafe operation or a deliberate attempt to cryptically crash the program.
    ///
    /// For reasons described above, **this signal is considered unsafe** – handling it requires using `set_unsafe_handler`.
    ///
    /// *Default handler: process termination with a core dump.*
    ///
    /// [bus error]: https://en.wikipedia.org/wiki/Bus_error " "
    /// [segmentation faults]: #variant.SegmentationFault " "
    #[cfg(any(doc, se_base_posix_2001))]
    #[cfg_attr( // se_full_posix_1990/se_base_posix_2001 template
        feature = "doc_cfg",
        doc(cfg(not(target_os = "hermit"))),
    )]
    MemoryBusError = SIGBUS,
    /// `SIGPROF` – profiler clock signal. This signal is issued by the OS when the arranged amount of CPU time expires. The time includes not only user-mode CPU time spent in the process, but also kernel-mode CPU time which the OS associates with the process. This is different from [`UserModeProfilerClock`]'s behavior, which counts only user-mode CPU time. This clock can be set using the [`setitimer`] system call.
    ///
    /// *Default handler: process termination.*
    ///
    /// [`UserModeProfilerClock`]: #variant.UserModeProfilerClock " "
    /// [`setitimer`]: https://www.man7.org/linux/man-pages/man2/setitimer.2.html " "
    #[cfg(any(doc, se_base_posix_2001))]
    #[cfg_attr( // se_full_posix_1990/se_base_posix_2001 template
        feature = "doc_cfg",
        doc(cfg(not(target_os = "hermit"))),
    )]
    ProfilerClock = SIGPROF,
    /// `SIGVTALRM` – user-mode profiler clock signal. This signal is issued by the OS when the arranged amount of CPU time expires. Only user-mode CPU time is counted, in contrast to `ProfilerClock`, which counts kernel-mode time associated by the system with the process as well. This clock can be set using the [`setitimer`] system call.
    ///
    /// *Default handler: process termination.*
    ///
    /// [`ProfilerClock`]: #variant.ProfilerClock " "
    /// [`setitimer`]: https://www.man7.org/linux/man-pages/man2/setitimer.2.html " "
    #[cfg(any(doc, se_base_posix_2001))]
    #[cfg_attr( // se_full_posix_1990/se_base_posix_2001 template
        feature = "doc_cfg",
        doc(cfg(not(target_os = "hermit"))),
    )]
    UserModeProfilerClock = SIGVTALRM,
    /// `SIGSYS` – attempt to perform an invalid system call. This signal is issued by the OS when a system call receives invalid arguments. Normally, the C library functions used to perform system calls in Rust programs do not generate this signal – the only way to generate it is to send it to a process explicitly, use raw system call instructions or violate [`seccomp`] rules if it is enabled.
    ///
    /// *Default handler: process termination with a core dump.*
    ///
    /// [`seccomp`]: https://en.wikipedia.org/wiki/Seccomp " "
    #[cfg(any(doc, se_base_posix_2001))]
    #[cfg_attr( // se_full_posix_1990/se_base_posix_2001 template
        feature = "doc_cfg",
        doc(cfg(not(target_os = "hermit"))),
    )]
    InvalidSystemCall = SIGSYS,
    /// `SIGTRAP` – software breakpoint. This signal is issued by the OS when a breakpoint instruction is executed. On x86, the instruction to do so is `int 3`. This instruction is typically inserted by debuggers and code injection utilities.
    ///
    /// *Default handler: process termination with a core dump.*
    #[cfg(any(doc, se_base_posix_2001))]
    #[cfg_attr( // se_full_posix_1990/se_base_posix_2001 template
        feature = "doc_cfg",
        doc(cfg(not(target_os = "hermit"))),
    )]
    Breakpoint = SIGTRAP,
    /// `SIGURG` – [out-of-band data] received on a socket. This signal is issued by the OS when a socket owned by the process receives urgent out-of-band data.
    ///
    /// *Default handler: ignore.*
    ///
    /// [out-of-band data]: https://en.wikipedia.org/wiki/Out-of-band_data " "
    #[cfg(any(doc, se_base_posix_2001))]
    #[cfg_attr( // se_full_posix_1990/se_base_posix_2001 template
        feature = "doc_cfg",
        doc(cfg(not(target_os = "hermit"))),
    )]
    OutOfBandDataAvailable = SIGURG,
    /// `SIGXCPU` – assigned CPU time limit for the process was exceeded. This signal is issued by the OS if a CPU time limit for the process was set, when that limit expires. If not handled quickly, the system will issue a [`Kill`] signal to shut down the process forcefully, i.e. ignoring this signal won't lead to bypassing the limit. The [`setrlimit`] system call is used to set the soft limit for this signal and the hard limit, which invokes [`Kill`].
    ///
    /// *Default handler: process termination with a core dump.*
    ///
    /// [`setrlimit`]: https://www.man7.org/linux/man-pages/man2/setrlimit.2.html " "
    /// [`Kill`]: #variant.Kill " "
    #[cfg(any(doc, se_base_posix_2001))]
    #[cfg_attr( // se_full_posix_1990/se_base_posix_2001 template
        feature = "doc_cfg",
        doc(cfg(not(target_os = "hermit"))),
    )]
    CpuTimeLimitExceeded = SIGXCPU,
    /// `SIGXFSZ` – assigned file size limit for the process was exceeded. This signal is issued by the OS if a limit on the size of files which are written to by the process was set, when that limit is exceeded by the process. If ignored/handled, the offending system call fails with an error regardless of the handling method. The [`setrlimit`] system call is used to set the limit.
    ///
    /// *Default handler: process termination with a core dump.*
    ///
    /// [`setrlimit`]: https://www.man7.org/linux/man-pages/man2/setrlimit.2.html " "
    #[cfg(any(doc, se_base_posix_2001))]
    #[cfg_attr( // se_full_posix_1990/se_base_posix_2001 template
        feature = "doc_cfg",
        doc(cfg(not(target_os = "hermit"))),
    )]
    FileSizeLimitExceeded = SIGXFSZ,
}
impl SignalType {
    /// Returns `true` if the value is a special signal which cannot be blocked or handled ([`Kill`] or [`ForceSuspend`]), `false` otherwise.
    ///
    /// [`Kill`]: #variant.Kill " "
    /// [`ForceSuspend`]: #variant.ForceSuspend " "
    pub const fn is_unblockable(self) -> bool {
        matches!(self, Self::Kill | Self::ForceSuspend)
    }
    /// Returns `true` if the value is an unsafe signal which requires unsafe code when setting a handling method, `false` otherwise.
    pub const fn is_unsafe(self) -> bool {
        matches!(
            self,
            Self::SegmentationFault | Self::MemoryBusError | Self::IllegalInstruction
        )
    }
}
impl From<SignalType> for i32 {
    fn from(op: SignalType) -> Self {
        op as i32
    }
}
impl From<SignalType> for u32 {
    fn from(op: SignalType) -> Self {
        op as u32
    }
}
impl TryFrom<i32> for SignalType {
    type Error = UnknownSignalError;
    #[rustfmt::skip]
    fn try_from(value: i32) -> Result<Self, Self::Error> {
        match value {
            #[cfg(se_basic)] SIGHUP => Ok(Self::Hangup),
            #[cfg(se_basic)] SIGINT => Ok(Self::KeyboardInterrupt),
            #[cfg(se_basic)] SIGQUIT => Ok(Self::QuitAndDump),
            #[cfg(se_basic)] SIGILL => Ok(Self::IllegalInstruction),
            #[cfg(se_basic)] SIGABRT => Ok(Self::Abort),
            #[cfg(se_basic)] SIGFPE => Ok(Self::MathException),
            #[cfg(se_basic)] SIGKILL => Ok(Self::Kill),
            #[cfg(se_basic)] SIGSEGV => Ok(Self::SegmentationFault),
            #[cfg(se_basic)] SIGPIPE => Ok(Self::BrokenPipe),
            #[cfg(se_basic)] SIGALRM => Ok(Self::AlarmClock),
            #[cfg(se_basic)] SIGTERM => Ok(Self::Termination),
            #[cfg(se_full_posix_1990)] SIGUSR1 => Ok(Self::UserSignal1),
            #[cfg(se_full_posix_1990)] SIGUSR2 => Ok(Self::UserSignal2),
            #[cfg(se_full_posix_1990)] SIGCHLD => Ok(Self::ChildProcessEvent),
            #[cfg(se_full_posix_1990)] SIGCONT => Ok(Self::Continue),
            #[cfg(se_full_posix_1990)] SIGSTOP => Ok(Self::ForceSuspend),
            #[cfg(se_full_posix_1990)] SIGTSTP => Ok(Self::Suspend),
            #[cfg(se_full_posix_1990)] SIGTTIN => Ok(Self::TerminalInputWhileInBackground),
            #[cfg(se_full_posix_1990)] SIGTTOU => Ok(Self::TerminalOutputWhileInBackground),
            #[cfg(any(se_sigpoll, se_sigpoll_is_sigio))] SIGPOLL => Ok(Self::PollNotification),
            #[cfg(se_full_posix_2001)] SIGBUS => Ok(Self::MemoryBusError),
            #[cfg(se_full_posix_2001)] SIGPROF => Ok(Self::ProfilerClock),
            #[cfg(se_base_posix_2001)] SIGSYS => Ok(Self::InvalidSystemCall),
            #[cfg(se_base_posix_2001)] SIGTRAP => Ok(Self::Breakpoint),
            #[cfg(se_base_posix_2001)] SIGURG => Ok(Self::OutOfBandDataAvailable),
            #[cfg(se_base_posix_2001)] SIGVTALRM => Ok(Self::UserModeProfilerClock),
            #[cfg(se_base_posix_2001)] SIGXCPU => Ok(Self::CpuTimeLimitExceeded),
            #[cfg(se_base_posix_2001)] SIGXFSZ => Ok(Self::FileSizeLimitExceeded),
            _ => Err(UnknownSignalError { value }),
        }
    }
}
impl TryFrom<u32> for SignalType {
    type Error = UnknownSignalError;
    fn try_from(value: u32) -> Result<Self, Self::Error> {
        value.try_into()
    }
}

/// Error type returned when a conversion from [`i32`]/[`u32`] to [`SignalType`] fails.
///
/// [`i32`]: https://doc.rust-lang.org/std/primitive.i32.html " "
/// [`u32`]: https://doc.rust-lang.org/std/primitive.u32.html " "
/// [`SignalType`]: enum.SignalType.html " "
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct UnknownSignalError {
    /// The unknown signal value which was encountered.
    pub value: i32,
}
impl Display for UnknownSignalError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "unknown signal value {}", self.value)
    }
}
impl fmt::Binary for UnknownSignalError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "unknown signal value {:b}", self.value)
    }
}
impl fmt::LowerHex for UnknownSignalError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "unknown signal value {:x}", self.value)
    }
}
impl fmt::UpperExp for UnknownSignalError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "unknown signal value {:X}", self.value)
    }
}
impl fmt::Octal for UnknownSignalError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "unknown signal value {:o}", self.value)
    }
}
impl Error for UnknownSignalError {}
