oscall 0.1.1

Low-level cross-platform interface to operating system services: files, memory mapping, networking and more, with no libc on Linux
Documentation
//! Waiting for any change of state of a child, and reaching into another
//! process: its memory, its handles.

use super::ptrace::Stop;
use crate::io::{IoSlice, IoSliceMut};
use crate::{AsHandle, BorrowedHandle, OwnedHandle, Result, sys};

/// Whom [`wait`] waits for.
#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
pub enum WaitFor<'a> {
    /// Any child of the caller, and any thread it traces (`P_ALL`).
    Any,
    /// The child, or the traced thread, with this identifier (`P_PID`).
    Process(u32),
    /// Any child in this process group; 0 for the group of the caller
    /// (`P_PGID`).
    Group(u32),
    /// The child a pidfd names (`P_PIDFD`, Linux 5.4).
    PidFd(BorrowedHandle<'a>),
}

crate::macros::flags! {
    /// What [`wait`] reports, and how: the options of `waitid`.
    pub struct WaitFlags: u32 {
        /// Children that have ended (`WEXITED`). Reporting one collects
        /// it, unless [`NO_WAIT`](Self::NO_WAIT).
        const EXITED = 1;
        /// Children a signal has stopped, and traced threads that
        /// stopped for their tracer (`WSTOPPED`).
        const STOPPED = 1 << 1;
        /// Children that were stopped and go on (`SIGCONT`):
        /// `WCONTINUED`.
        const CONTINUED = 1 << 2;
        /// Returns at once, with `None`, when there is nothing to report
        /// yet (`WNOHANG`).
        const NO_HANG = 1 << 3;
        /// Leaves what is reported to be reported again: a child that
        /// has ended is not collected (`WNOWAIT`).
        const NO_WAIT = 1 << 4;
        /// Children of every kind, those that have no exit signal (a
        /// thread, a `clone` with another signal) included: `__WALL`. A
        /// tracer wants it, to see the threads of its tracee.
        const ALL_CHILDREN = 1 << 5;
        /// Only the children of the calling thread, not those the other
        /// threads of the process created or trace (`__WNOTHREAD`).
        const NO_THREAD = 1 << 6;
    }
}

/// What happened to a child: part of what [`wait`] returns.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum WaitEvent {
    /// It exited, with this code (`CLD_EXITED`).
    Exited(i32),
    /// A signal ended it (`CLD_KILLED`, `CLD_DUMPED`).
    Killed {
        /// The number of the signal.
        signal: i32,
        /// Whether it left a core dump.
        core_dumped: bool,
    },
    /// This signal stopped it (`CLD_STOPPED`).
    Stopped(i32),
    /// It goes on after a stop (`CLD_CONTINUED`).
    Continued,
    /// A thread the caller traces stopped for it (`CLD_TRAPPED`).
    Trapped(Stop),
}

impl WaitEvent {
    /// The end of the child as [`Child::wait`](crate::process::Child::wait)
    /// would have reported it; `None` for an event that is not its end.
    #[cfg(feature = "alloc")]
    pub fn exit_status(&self) -> Option<crate::process::ExitStatus> {
        match *self {
            Self::Exited(code) => Some(crate::process::ExitStatus::exited(code)),
            Self::Killed {
                signal,
                core_dumped,
            } => Some(crate::process::ExitStatus::signaled(signal, core_dumped)),
            _ => None,
        }
    }
}

/// A change of state of a child: what [`wait`] returns.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct Waited {
    /// The child: a process, or, for a traced thread, that thread.
    pub pid: u32,
    /// The real user of the child.
    pub uid: u32,
    /// What happened to it.
    pub event: WaitEvent,
}

/// Waits for a change of state of a child of the caller, of the kinds
/// `flags` names: `waitid`. This is the wait of a shell, of a tracer and
/// of a process that adopts orphans
/// ([`set_child_subreaper`](super::set_child_subreaper)): it reports
/// children that stop and go on as well as those that end, and it can
/// wait for any child at all. [`Child::wait`](crate::process::Child::wait)
/// and [`pidfd_wait`](super::pidfd_wait) are for the end of one child.
///
/// `flags` must name a kind of event: [`WaitFlags::EXITED`],
/// [`STOPPED`](WaitFlags::STOPPED) or
/// [`CONTINUED`](WaitFlags::CONTINUED). Returns `None` with
/// [`WaitFlags::NO_HANG`] when no child has anything to report.
///
/// **A child whose end is reported here is collected**, and a
/// [`Child`](crate::process::Child) for it then finds it gone, as with
/// [`pidfd_wait`](super::pidfd_wait): wait for the end of a child one way
/// or the other. Leaving [`WaitFlags::EXITED`] out, or adding
/// [`WaitFlags::NO_WAIT`], collects nothing.
///
/// A child that ends *while it is only waited for to stop* ends the wait
/// with `ECHILD`, as measured: what was waited for can no longer happen.
///
/// # Errors
///
/// `ECHILD` when the caller has no child that fits, or none left that
/// could report what is asked;
/// [`InvalidInput`](crate::ErrorKind::InvalidInput) for no kind of event;
/// [`Interrupted`](crate::ErrorKind::Interrupted) when a signal handler
/// runs during the wait.
pub fn wait(who: WaitFor<'_>, flags: WaitFlags) -> Result<Option<Waited>> {
    sys::process::ptrace::wait(who, flags)
}

/// A range of the memory of another process: where
/// [`read_memory_vectored`] reads and [`write_memory_vectored`] writes
/// (a `struct iovec` of addresses that are not the caller's).
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct RemoteSlice {
    /// The address of the first byte, in the other process.
    pub address: usize,
    /// The number of bytes.
    pub len: usize,
}

const _: () = assert!(
    size_of::<RemoteSlice>() == 2 * size_of::<usize>()
        && size_of::<IoSlice<'_>>() == size_of::<RemoteSlice>()
        && size_of::<IoSliceMut<'_>>() == size_of::<RemoteSlice>()
);

/// Reads the memory of the process `pid` at `address` into `buf`, and
/// returns how many bytes were read: `process_vm_readv`. The other
/// process is not stopped, not traced, and not told.
///
/// Fewer bytes than asked are read when the range runs into memory the
/// other process does not have: what comes before the first page that
/// cannot be read is returned.
///
/// This is how the supervisor of a system call filter reads what an
/// argument points to; see [`seccomp`](super::seccomp) for why what it
/// reads may change under it.
///
/// # Errors
///
/// [`PermissionDenied`](crate::ErrorKind::PermissionDenied) when the
/// caller may not trace the process (the rules of
/// [`ptrace::seize`](super::ptrace::seize));
/// [`NoSuchProcess`](crate::ErrorKind::NoSuchProcess); `EFAULT` when not
/// even the first byte can be read;
/// [`Unsupported`](crate::ErrorKind::Unsupported) on a kernel built
/// without the call (`CONFIG_CROSS_MEMORY_ATTACH`), and under an
/// emulator that lacks it.
pub fn read_memory(pid: u32, address: usize, buf: &mut [u8]) -> Result<usize> {
    let local = [IoSliceMut::new(buf)];
    let remote = [RemoteSlice {
        address,
        len: local[0].len(),
    }];
    // SAFETY: one structure each, the local one of a slice that may be
    // written.
    unsafe {
        sys::process::ptrace::process_vm(
            false,
            pid,
            local.as_ptr().cast(),
            1,
            remote.as_ptr().cast(),
            1,
        )
    }
}

/// Writes `data` to the memory of the process `pid` at `address`, and
/// returns how many bytes were written: `process_vm_writev`. As
/// [`read_memory`], for memory the other process itself may write: its
/// code and its read-only data are refused (`EFAULT`), where
/// [`ptrace::poke`](super::ptrace::poke) writes them.
pub fn write_memory(pid: u32, address: usize, data: &[u8]) -> Result<usize> {
    let local = [IoSlice::new(data)];
    let remote = [RemoteSlice {
        address,
        len: data.len(),
    }];
    // SAFETY: one structure each, the local one of a slice that may be
    // read.
    unsafe {
        sys::process::ptrace::process_vm(
            true,
            pid,
            local.as_ptr().cast(),
            1,
            remote.as_ptr().cast(),
            1,
        )
    }
}

/// Reads several ranges of the memory of the process `pid` into several
/// buffers, in one call: `process_vm_readv`. The bytes of the ranges of
/// `remote`, in order, fill the buffers of `bufs`, in order; the two
/// lists need not be cut at the same places. Returns how many bytes were
/// read, which is less than asked as for [`read_memory`], range by range.
///
/// # Errors
///
/// As [`read_memory`]; [`InvalidInput`](crate::ErrorKind::InvalidInput)
/// for more than 1024 buffers or ranges, and for lengths whose sum does
/// not fit in a signed number.
pub fn read_memory_vectored(
    pid: u32,
    bufs: &mut [IoSliceMut<'_>],
    remote: &[RemoteSlice],
) -> Result<usize> {
    // SAFETY: an `IoSliceMut` is a `struct iovec` of memory that may be
    // written, a `RemoteSlice` one of addresses for the kernel to check.
    unsafe {
        sys::process::ptrace::process_vm(
            false,
            pid,
            bufs.as_ptr().cast(),
            bufs.len(),
            remote.as_ptr().cast(),
            remote.len(),
        )
    }
}

/// Writes several buffers to several ranges of the memory of the process
/// `pid`, in one call: `process_vm_writev`. As [`read_memory_vectored`],
/// the other way.
pub fn write_memory_vectored(
    pid: u32,
    bufs: &[IoSlice<'_>],
    remote: &[RemoteSlice],
) -> Result<usize> {
    // SAFETY: an `IoSlice` is a `struct iovec` of memory that may be
    // read, a `RemoteSlice` one of addresses for the kernel to check.
    unsafe {
        sys::process::ptrace::process_vm(
            true,
            pid,
            bufs.as_ptr().cast(),
            bufs.len(),
            remote.as_ptr().cast(),
            remote.len(),
        )
    }
}

/// Opens, in the caller, the file that the handle numbered `fd` of
/// another process is open on: `pidfd_getfd` (Linux 5.6). The two then
/// share one open file, with its position and its flags, as after a
/// [`duplicate`](crate::io::duplicate) across processes.
///
/// `pidfd` names the process ([`pidfd_open`](super::pidfd_open), a
/// [`Child`](crate::process::Child)). The new handle is close-on-exec.
///
/// With [`seccomp::add_handle`](super::seccomp::add_handle), which goes
/// the other way, this lets a supervisor work on the handles of the
/// process it supervises.
///
/// # Errors
///
/// [`PermissionDenied`](crate::ErrorKind::PermissionDenied) when the
/// caller may not trace the process (the rules of
/// [`ptrace::seize`](super::ptrace::seize));
/// [`BadHandle`](crate::ErrorKind::BadHandle) for a `pidfd` that is not
/// one, and for a number the process has nothing open under;
/// [`NoSuchProcess`](crate::ErrorKind::NoSuchProcess) for a process that
/// has ended.
pub fn pidfd_getfd<H: AsHandle + ?Sized>(pidfd: &H, fd: u32) -> Result<OwnedHandle> {
    sys::process::ptrace::pidfd_getfd(pidfd.as_handle(), fd)
}