diff --git a/packages/cli-rs/Cargo.lock b/packages/cli-rs/Cargo.lock index c38772df160..9b3f5a44d0b 100644 --- a/packages/cli-rs/Cargo.lock +++ b/packages/cli-rs/Cargo.lock @@ -938,6 +938,7 @@ dependencies = [ "libc", "ring", "serde_json", + "windows-sys 0.61.2", ] [[package]] diff --git a/packages/cli-rs/Cargo.toml b/packages/cli-rs/Cargo.toml index 047073d38cb..4105528abbf 100644 --- a/packages/cli-rs/Cargo.toml +++ b/packages/cli-rs/Cargo.toml @@ -65,6 +65,8 @@ tokio-tungstenite = { version = "0.30", features = ["rustls-tls-native-roots"] } tokio-util = "0.7" unicode-width = "0.2" url = "2" +# Win32 calls, for opencode-util's `win` module only (DW1); each use adds its features there. +windows-sys = "0.61" # Tree-sitter grammars for opencode-ui's `grammars` and `grammars-all` features (crates/ui/src/grammars), pinned to # the WASM releases packages/tui/src/parsers-config.ts loads where crates.io has them. The five opentui bundles take diff --git a/packages/cli-rs/crates/service/Cargo.toml b/packages/cli-rs/crates/service/Cargo.toml index 39059544e5e..2019c735ccf 100644 --- a/packages/cli-rs/crates/service/Cargo.toml +++ b/packages/cli-rs/crates/service/Cargo.toml @@ -24,6 +24,9 @@ url.workspace = true [target.'cfg(unix)'.dependencies] rustix.workspace = true +[target.'cfg(windows)'.dependencies] +opencode-util.workspace = true + [dev-dependencies] bytes.workspace = true opencode-util.workspace = true diff --git a/packages/cli-rs/crates/service/src/stop.rs b/packages/cli-rs/crates/service/src/stop.rs index e1c44f1ec3d..45f7caebfa1 100644 --- a/packages/cli-rs/crates/service/src/stop.rs +++ b/packages/cli-rs/crates/service/src/stop.rs @@ -135,19 +135,24 @@ pub(crate) fn signal(pid: u32, signal: Signal) { }; let _ = kill_process(pid, raw); } - #[cfg(not(unix))] - let _ = (pid, signal); + // libuv's `uv_kill` terminates the process for either signal. + #[cfg(windows)] + { + let _ = signal; + let _ = opencode_util::win::terminate(pid); + } } -/// Whether `pid` exists (`process.kill(pid, 0)`; any error counts as gone). +/// Whether `pid` exists (`process.kill(pid, 0)`; any error counts as gone, but on Windows a process this user may +/// not open counts as alive). pub(crate) fn running(pid: u32) -> bool { #[cfg(unix)] return i32::try_from(pid) .ok() .and_then(rustix::process::Pid::from_raw) .is_some_and(|pid| rustix::process::test_kill_process(pid).is_ok()); - #[cfg(not(unix))] - return pid == 0; + #[cfg(windows)] + return opencode_util::win::process_alive(pid); } async fn stopped(pid: u32, poll: Poll) -> bool { @@ -161,3 +166,22 @@ async fn stopped(pid: u32, poll: Poll) -> bool { } false } + +#[cfg(all(test, windows))] +mod tests { + use super::*; + + #[test] + fn kill_ends_a_running_process() { + // `ping` waits a second between echoes; `timeout` needs a console on stdin. + let mut child = std::process::Command::new("ping") + .args(["-n", "60", "127.0.0.1"]) + .stdout(std::process::Stdio::null()) + .spawn() + .unwrap(); + assert!(running(child.id())); + signal(child.id(), Signal::Kill); + child.wait().unwrap(); + assert!(!running(child.id())); + } +} diff --git a/packages/cli-rs/crates/util/Cargo.toml b/packages/cli-rs/crates/util/Cargo.toml index cc6c8e2e246..c622a6180d7 100644 --- a/packages/cli-rs/crates/util/Cargo.toml +++ b/packages/cli-rs/crates/util/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "opencode-util" -description = "Small shared modules on libc alone: errors with context, civil time and local offsets, shared libraries, digests." +description = "Small shared modules on libc alone: errors with context, civil time and local offsets, shared libraries, digests, Win32 process calls." version.workspace = true edition.workspace = true license.workspace = true @@ -17,5 +17,8 @@ ring = ["dep:ring"] libc.workspace = true ring = { workspace = true, optional = true } +[target.'cfg(windows)'.dependencies] +windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_System_Threading", "Win32_System_Console"] } + [dev-dependencies] serde_json.workspace = true diff --git a/packages/cli-rs/crates/util/src/lib.rs b/packages/cli-rs/crates/util/src/lib.rs index 7e5a90989e3..52d88966197 100644 --- a/packages/cli-rs/crates/util/src/lib.rs +++ b/packages/cli-rs/crates/util/src/lib.rs @@ -1,4 +1,4 @@ -//! Small modules that several crates share, on `libc` alone, and `ring` behind its feature. +//! Small modules that several crates share, on `libc` alone, `ring` behind its feature, and `windows-sys` on Windows. use std::sync::{Mutex, MutexGuard, PoisonError}; @@ -8,6 +8,8 @@ pub mod error; pub mod hash; pub mod temp; pub mod time; +#[cfg(windows)] +pub mod win; /// Locks `mutex`, and takes the guard of a poisoned one: a panic on another thread leaves the data usable. pub fn lock(mutex: &Mutex) -> MutexGuard<'_, T> { diff --git a/packages/cli-rs/crates/util/src/win.rs b/packages/cli-rs/crates/util/src/win.rs new file mode 100644 index 00000000000..881ce9c6d25 --- /dev/null +++ b/packages/cli-rs/crates/util/src/win.rs @@ -0,0 +1,85 @@ +//! Win32 calls that std does not cover: whether a process is alive, ending one, and pointing stdin at the console. +//! Windows only. + +#![allow(unsafe_code)] + +use std::io; +use std::os::windows::io::{AsRawHandle, FromRawHandle, IntoRawHandle, OwnedHandle}; +use windows_sys::Win32::Foundation::{ERROR_ACCESS_DENIED, STILL_ACTIVE}; +use windows_sys::Win32::System::Console::{STD_INPUT_HANDLE, SetStdHandle}; +use windows_sys::Win32::System::Threading::{ + GetExitCodeProcess, OpenProcess, PROCESS_ACCESS_RIGHTS, PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_TERMINATE, + TerminateProcess, +}; + +/// Whether process `pid` exists and has not exited. A process this user may not open exists, so it counts as alive. +pub fn process_alive(pid: u32) -> bool { + let process = match open(pid, PROCESS_QUERY_LIMITED_INFORMATION) { + Ok(process) => process, + Err(error) => return error.raw_os_error() == Some(ERROR_ACCESS_DENIED as i32), + }; + let mut code = 0; + // SAFETY: `process` is an open handle with query access, and `code` outlives the call. + let ok = unsafe { GetExitCodeProcess(process.as_raw_handle(), &mut code) }; + // An exited process keeps its handle until the last one closes; its exit code tells it apart. + ok == 0 || code == STILL_ACTIVE as u32 +} + +/// Ends process `pid` with exit code 1 (`TerminateProcess`, what libuv does for every signal but 0). +pub fn terminate(pid: u32) -> io::Result<()> { + let process = open(pid, PROCESS_TERMINATE)?; + // SAFETY: `process` is an open handle with terminate access. + if unsafe { TerminateProcess(process.as_raw_handle(), 1) } == 0 { + return Err(io::Error::last_os_error()); + } + Ok(()) +} + +/// Makes the console (`CONIN$`) this process's standard input, for a process whose stdin was a pipe. The handle stays +/// open for the life of the process; std and OpenTUI look the standard handle up on each read. +pub fn set_stdin_console() -> io::Result<()> { + let console = std::fs::OpenOptions::new().read(true).write(true).open("CONIN$")?.into_raw_handle(); + // SAFETY: `console` is an open handle that is never closed. + if unsafe { SetStdHandle(STD_INPUT_HANDLE, console) } == 0 { + let error = io::Error::last_os_error(); + // SAFETY: `SetStdHandle` failed, so nothing else holds `console`. + drop(unsafe { OwnedHandle::from_raw_handle(console) }); + return Err(error); + } + Ok(()) +} + +fn open(pid: u32, access: PROCESS_ACCESS_RIGHTS) -> io::Result { + // SAFETY: plain call; a null result is an error. + let handle = unsafe { OpenProcess(access, 0, pid) }; + if handle.is_null() { + return Err(io::Error::last_os_error()); + } + // SAFETY: `handle` is open and owned by nothing else. + Ok(unsafe { OwnedHandle::from_raw_handle(handle) }) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::process::{Command, Stdio}; + + #[test] + fn terminate_ends_a_live_process() { + // `ping` waits a second between echoes; `timeout` needs a console on stdin. + let mut child = Command::new("ping").args(["-n", "60", "127.0.0.1"]).stdout(Stdio::null()).spawn().unwrap(); + assert!(process_alive(child.id())); + terminate(child.id()).unwrap(); + let status = child.wait().unwrap(); + assert_eq!(status.code(), Some(1)); + assert!(!process_alive(child.id())); + } + + #[test] + fn a_missing_process_is_gone() { + // Process IDs are multiples of 4, so this one never exists; 0 is the idle process, which cannot be opened. + assert!(!process_alive(u32::MAX - 2)); + assert!(!process_alive(0)); + assert!(terminate(u32::MAX - 2).is_err()); + } +}