cosca 0.7.0

Unified cross-platform subprocess management: spawning, stdio, process trees, stable identity, and elevation.
Documentation
//! Async (tokio) raw `CreateProcessW` spawn backend.
//!
//! The async mirror of [`crate::child::spawn::windows_raw`]: it loads an `executable()`
//! independently of argv[0] (the case std/tokio cannot express on Windows), wires arbitrary
//! descriptors (fd >= 3, via the MSVCRT `lpReserved2` table), and applies containment (Job Object /
//! TreeWalk) — the full sync feature set. It reuses the sync backend's `CreateProcessW` FFI verbatim
//! (`spawn_step`/`create_process`, the fd-table encode + cap, the STARTUPINFOEXW/HANDLE_LIST build,
//! the containment decision, the lock/close discipline, the error-teardown) and differs only where
//! async demands it: the parent ends of piped slots come from the same `resolve_stdio`, and an
//! accessor registers them with the reactor when taken (std slots via the stdin/stdout/stderr
//! accessors, fd >= 3 via fd_read_end/fd_write_end), and the owned child is
//! a [`RawAsyncChild`] whose waits run on the blocking pool over a cancellable handle wait.

use std::collections::BTreeMap;
use std::os::windows::io::{AsRawHandle, OwnedHandle};
use std::process::ExitStatus;
use std::sync::Arc;

use windows::Win32::Foundation::{HANDLE, WAIT_OBJECT_0, WAIT_TIMEOUT};
use windows::Win32::System::Threading::{WaitForSingleObject, PROCESS_ACCESS_RIGHTS};

use crate::child::owned::teardown::{Disposition, Past};
use crate::child::owned::OwnedChild;
use crate::child::spawn::held_teardown::tear_down_failed_spawn;
use crate::child::spawn::windows_raw as sync_raw;
use crate::child::spawn::{
    attach_or_fault, resolve_identity, resolve_stdio, spawn_lock, Classify, Diagnosis, ParentStd, SpawnFailure,
};
use crate::command::Command;
use crate::error::{win32_io_error, ChildFate, Error};
use crate::identity::{windows_terminate_held, Termination};
use crate::os_process::windows::cancel::{new_cancel_event, signal_cancel};
use crate::os_process::windows::{WindowsProcess, CREATE_PROCESS_ACCESS};
use crate::stdio::{Fd, ResolvedStdio};
use crate::tokio::child::{Child, ProcSource};
use crate::wait::teardown_warn::Due;

use sync_raw::{exit_status, wait_handle_or_cancel, WaitOutcome};

/// A raw `CreateProcessW` child driven from tokio. The process handle lives behind an `Arc` so a
/// dropped `wait()` future — or a dropped child — never closes a handle a blocking watcher is still
/// parked on: the blocking task holds its own clone until it returns. Async waits run on the
/// blocking pool over the shared cancellable handle wait; a cancel event (signaled by the future's
/// drop guard) releases a parked wait promptly.
#[derive(Debug)]
pub(crate) struct RawAsyncChild {
    proc: Arc<OwnedHandle>,
    /// The child's pid, as `CreateProcess` returned it: the handle pins it for the child's whole life.
    pid: u32,
    /// The access `proc` was granted: it decides what a refused kill means.
    granted: PROCESS_ACCESS_RIGHTS,
    /// Memoized once the child has exited, so a second `wait`/`try_wait` is immediate and cannot
    /// re-read a status off a (post-close) recycled handle.
    exited: Option<ExitStatus>,
    #[cfg(test)]
    observer: Option<WaitObserver>,
}

impl RawAsyncChild {
    /// The child `pid` whose process handle is `proc`, which holds `granted`.
    pub(crate) fn new(proc: OwnedHandle, pid: u32, granted: PROCESS_ACCESS_RIGHTS) -> RawAsyncChild {
        RawAsyncChild {
            proc: Arc::new(proc),
            pid,
            granted,
            exited: None,
            #[cfg(test)]
            observer: None,
        }
    }

    fn handle(&self) -> HANDLE {
        HANDLE(self.proc.as_raw_handle())
    }

    pub(crate) fn pid(&self) -> u32 {
        self.pid
    }

    pub(crate) fn raw_handle(&self) -> std::os::windows::io::RawHandle {
        self.proc.as_raw_handle()
    }

    /// Block until the child exits, returning its status. Runs the blocking handle wait on the
    /// blocking pool; a `CancelGuard` in this future signals a cancel event on drop so an aborted
    /// or timed-out wait releases the parked watcher at once.
    pub(crate) async fn wait(&mut self) -> Result<ExitStatus, Error> {
        loop {
            if let Some(status) = self.exited {
                return Ok(status);
            }
            // Arc-owned handles: the blocking task holds clones for its whole lifetime, so dropping
            // this future (or the child) never closes a handle the task is parked on.
            let cancel = Arc::new(new_cancel_event()?);
            let proc = Arc::clone(&self.proc);
            let cancel_for_task = Arc::clone(&cancel);
            #[cfg(test)]
            let observer = self.observer.take();
            let task = ::tokio::task::spawn_blocking(move || {
                #[cfg(test)]
                let (started, outcome_tx) = match observer {
                    Some(obs) => (Some(obs.started), Some(obs.outcome)),
                    None => (None, None),
                };
                // The task is on the blocking pool and about to park on the handle wait.
                #[cfg(test)]
                if let Some(tx) = started {
                    _ = tx.send(());
                }
                let result = wait_handle_or_cancel(
                    HANDLE(proc.as_raw_handle()),
                    Some(HANDLE(cancel_for_task.as_raw_handle())),
                );
                #[cfg(test)]
                if let (Some(tx), Ok(outcome)) = (outcome_tx, result.as_ref()) {
                    _ = tx.send(*outcome);
                }
                result
            });
            // Signals the cancel event if THIS future is dropped before the blocking wait returns,
            // releasing the parked watcher promptly. Harmless after completion (manual-reset event,
            // nothing waits on it any more). The Arcs above keep both handles live until the task
            // returns, so the signal races nothing.
            let _guard = CancelGuard(cancel);
            let outcome = match task.await {
                Ok(o) => o,
                // A JoinError (task panic / runtime shutdown) is not an exit — surface it.
                Err(_e) => return Err(Error::Io(std::io::Error::other("raw async wait task failed"))),
            };
            match outcome {
                Ok(WaitOutcome::Exited) => {
                    let status = exit_status(self.handle()).map_err(Error::Io)?;
                    self.exited = Some(status);
                    return Ok(status);
                }
                // Only `CancelGuard::drop` signals the cancel event, and it runs solely when THIS
                // future is dropped — in which case this continuation never executes. A defensive
                // re-wait (fresh event) preserves the "resolved ⇒ exited" postcondition if that
                // ever broke; never a false exit.
                Ok(WaitOutcome::Cancelled) => {
                    debug_assert!(false, "raw async wait resolved Cancelled while its future was live");
                    continue;
                }
                Err(e) => return Err(Error::Io(e)),
            }
        }
    }

    /// Exit status if the child has already exited (non-blocking), memoizing it.
    pub(crate) fn try_wait(&mut self) -> Result<Option<ExitStatus>, Error> {
        if let Some(status) = self.exited {
            return Ok(Some(status));
        }
        // SAFETY: our live, owned process handle; a zero timeout polls without blocking.
        let r = unsafe { WaitForSingleObject(self.handle(), 0) };
        if r == WAIT_OBJECT_0 {
            let status = exit_status(self.handle()).map_err(Error::Io)?;
            self.exited = Some(status);
            Ok(Some(status))
        } else if r == WAIT_TIMEOUT {
            Ok(None)
        } else {
            Err(Error::Io(std::io::Error::last_os_error()))
        }
    }

    /// Signal a hard kill (does not reap). Signal-only, so it never blocks.
    pub(crate) fn start_kill(&self) -> Result<(), Error> {
        // Signal-only, never block. A handle without `PROCESS_TERMINATE` (a runas child we cannot
        // terminate) surfaces as `Io`.
        match windows_terminate_held(self.handle(), self.granted) {
            Termination::Terminated | Termination::Exited => Ok(()),
            Termination::Failed(e) => Err(Error::Io(win32_io_error(e))),
        }
    }

    /// `true` once this backend has collected the child's exit status, so no wait remains.
    pub(crate) fn is_reaped(&self) -> bool {
        self.exited.is_some()
    }

    /// Install the per-instance test wait observer on THIS child (see `WaitObserver`).
    #[cfg(test)]
    pub(crate) fn set_observer(
        &mut self,
        started: ::tokio::sync::oneshot::Sender<()>,
        outcome: ::tokio::sync::oneshot::Sender<WaitOutcome>,
    ) {
        self.observer = Some(WaitObserver { started, outcome });
    }
}

/// Signals the cancel event when the `wait()` future is dropped (aborted / timed-out), releasing
/// the parked blocking watcher. Harmless once the wait has already returned.
struct CancelGuard(Arc<OwnedHandle>);

impl Drop for CancelGuard {
    fn drop(&mut self) {
        // `signal_cancel` asserts loudly on failure; Drop cannot propagate.
        signal_cancel(&self.0);
    }
}

/// Per-instance test observable seam: the blocking wait closure signals when it has parked
/// (`started`) and reports its `WaitOutcome` — on THIS child's channels only, so a parallel test's
/// wait never fires into another test's receivers (a process-global seam would). Injected via
/// `RawAsyncChild::set_observer`; consumed on the next `wait()`.
#[cfg(test)]
#[derive(Debug)]
struct WaitObserver {
    started: ::tokio::sync::oneshot::Sender<()>,
    outcome: ::tokio::sync::oneshot::Sender<WaitOutcome>,
}

/// Spawn `cmd` via the async raw backend: an `executable()` loaded independently of argv[0], with
/// arbitrary descriptors (fd >= 3) and containment — the full sync feature set. Reuses the sync
/// backend's FFI (fd-table + HANDLE_LIST + containment decision + lock/close + error-teardown).
///
/// Everything up to `CreateProcessW` fails before the program could start; everything after may
/// come after it started.
pub(crate) fn spawn_raw(
    cmd: &Command,
    fds: BTreeMap<Fd, ResolvedStdio>,
    kill_on_drop: bool,
) -> Result<Child, SpawnFailure> {
    // Batch reject on the program token, resolve the executable, NUL-check, build the command line
    // — all shared verbatim with the sync raw backend.
    sync_raw::reject_batch_program(cmd).not_started()?;
    let spawn_env = sync_raw::spawn_env(cmd).not_started()?;
    // THE SAME function the sync raw backend uses, not a mirror of it — the `raw_executable()`
    // contract must not depend on which API you spawned through, and a copy here could drift.
    let sync_raw::Target { image, cwd } = sync_raw::target(cmd, &spawn_env).not_started()?;
    if let Some(p) = &image {
        sync_raw::resolve::debug_assert_no_nul_wide("program image", p.as_os_str());
    }
    let mut cmdline = sync_raw::raw_program_and_line(cmd).not_started()?; // each token NUL-checked
    cmdline.push(0);
    // Ordered after `raw_program_and_line` for the same reason as the sync backend — see its
    // comment: that call names which no-program mistake the caller made, this one is the backstop
    // that keeps a NULL `lpApplicationName` unrepresentable.
    let app_name: Vec<u16> = sync_raw::app_name_wide(image.as_deref()).not_started()?;

    // Containment: mirror the sync raw backend's pre-spawn decision. Uncontained keeps the defaults
    // (flags 0, `mode: None`/`is_root: false`); a Strongest root spawns CREATE_SUSPENDED and is
    // job-assigned + resumed in `attach_or_fault`.
    let req = cmd.contain_request();
    // Composed and validated, like the stdio below, BEFORE `clear_std_handle_inheritance`, which is
    // a process-global `SetHandleInformation` on THIS process's std handles that nothing undoes: a
    // refused spawn must not have mutated the parent.
    let plan = crate::command::flags::windows_spawn(
        &req,
        *cmd.flags_request(),
        spawn_env.is_root,
        crate::command::flags::SpawnBackend::Raw,
    )
    .not_started()?;
    debug_assert_eq!(plan.marker_env, spawn_env.marker_env, "the marker decision drifted");

    let cwd_w = Some(sync_raw::to_wide_nul(cwd.as_os_str()));

    // Cap the MSVCRT fd-table to the WORD-sized `cbReserved2` field BEFORE allocating any pipes.
    sync_raw::ensure_fd_table_fits(&fds).not_started()?;

    // Resolve 0/1/2 (always) plus any configured fd >= 3 to child handles, and every piped slot to
    // its parent end (the shared `resolve_stdio` rejects inherit on fd >= 3).
    let parent_std = ParentStd::read();
    let (child_ends, pipes) = resolve_stdio(&fds, parent_std).not_started()?;

    // Classify + encode the dense MSVCRT fd-table the child CRT reads back from `lpReserved2` — the
    // SAME layout + HANDLE_LIST source as the sync backend.
    let table = sync_raw::build_fd_table(&child_ends).not_started()?;

    // `table` (`bytes`) and the attribute list stay alive until after CreateProcessW.
    let startup = sync_raw::startup_info(&child_ends, &table, parent_std).not_started()?;
    // The listed handles: `table.handles` (the non-null ends among 0/1/2 + fd >= 3, each a distinct
    // fresh dup, its 0/1/2 entries being the hStd* handles) or, when that is empty, the filler. No
    // duplicate reaches the list.
    let all_handles: Vec<HANDLE> = startup.handles(&table).to_vec();
    // The complete word, composed above by the ONE function all three backends share — the two
    // structural bits this backend cannot spawn without included. Nothing ORs into it here.
    let flags = plan.creation_flags;

    // Nothing above is refused after this point.
    if req.mode.is_some() {
        crate::containment::windows::clear_std_handle_inheritance();
    }

    // UNDER THE LOCK: mark the listed child ends inheritable, spawn, then CLOSE the child ends and
    // the attribute list BEFORE the guard releases on EVERY path (mirrors the sync raw backend).
    let spawned = {
        let _guard = spawn_lock();
        // Rebound after the guard: locals drop in reverse order, so on success, an error or a panic
        // the inheritable ends close before the lock is released.
        let (_child_ends, mut startup) = (child_ends, startup);
        sync_raw::spawn_step(
            &all_handles,
            &app_name,
            &mut cmdline,
            &mut startup.si,
            &spawn_env.block,
            &cwd_w,
            flags,
            *cmd.flags_request(),
        )
    };
    let (proc, pid) = spawned.not_started()?;

    // Identity read + attach BEFORE building `Child`, with the REAL mode + is_root (Job Object for a
    // Strongest root, else TreeWalk/Delegated), and the SAME kill+reap error-teardown as the
    // sync-raw/std path (dropping the OwnedHandle alone neither kills nor reaps on Windows). Spawn +
    // attach + identity are synchronous — no await before the identity read, so the runtime cannot
    // park and reap in between.
    let prepared = crate::containment::Prepared {
        mode: req.mode,
        is_root: spawn_env.is_root,
        // From the COMPOSED word, which carries the caller's flags as well as the containment
        // decision: a derivation reading only the containment half would report an in-process
        // route for a child this spawn deliberately put in another console.
        graceful: crate::containment::windows::mechanism_from_flags(flags),
        frozen: cmd.flags_request().suspended,
    };
    let raw_handle = proc.as_raw_handle();
    let (resolved, cause, mut why) = resolve_identity(
        &crate::identity::HostKernel,
        pid,
        &crate::wait::exit_only::Target::Handle(std::os::windows::io::AsHandle::as_handle(&proc)),
    );
    let id = match resolved {
        crate::identity::Resolved::Found(id) => Ok(id),
        // Kept with no identity; see `Child::id`.
        crate::identity::Resolved::Unknown => Err(crate::child::spawn::kept_without_identity(pid, cause, &mut why)),
        other => {
            let fate = raw_spawn_teardown(proc, pid, None);
            return Err(SpawnFailure::started(
                crate::child::spawn::spawn_identity_error(other, cause),
                fate,
                None,
            ));
        }
    };
    let id_read = id.as_ref().ok().copied();
    let attachment = match attach_or_fault(id, raw_handle, prepared) {
        Ok(v) => v,
        Err(e) => {
            let fate = raw_spawn_teardown(proc, pid, id_read);
            return Err(SpawnFailure::started(e, fate, None));
        }
    };

    Ok(Child::from_parts(
        ProcSource::Raw(RawAsyncChild::new(proc, pid, CREATE_PROCESS_ACCESS)),
        id_read,
        kill_on_drop,
        attachment,
        pipes,
    ))
}

/// Kills and reaps a just-spawned child whose attach or identity read failed, so a failed spawn
/// never leaks a running process, and answers its fate. The wait for the killed child blocks this
/// thread, and warns once it passes [`slow_teardown_after`](crate::tokio::child::slow_teardown_after).
/// A child whose kill was refused is left running, warned of.
fn raw_spawn_teardown(proc: OwnedHandle, pid: u32, id: Option<crate::identity::ProcessId>) -> ChildFate {
    let owned = OwnedChild::new(Box::new(WindowsProcess::for_child(proc, pid)));
    let (fate, _) = tear_down_failed_spawn(
        owned,
        id,
        Past::Clean,
        Disposition::Leave,
        Due::in_(crate::tokio::child::slow_teardown_after()),
        &mut Diagnosis::default(),
    );
    fate
}

#[cfg(test)]
#[path = "windows_raw_tests.rs"]
mod windows_raw_tests;