Skip to main content

terminator/platform/
windows.rs

1//! Windows backend.
2//!
3//! A process can be attached to at most one console. To deliver a console
4//! control event or console input to a *foreign* console we must be attached
5//! to it, and attaching means detaching from our own first (which destroys it
6//! if we were the last process using it). Three routes avoid that problem
7//! whenever possible, see [`Route`].
8
9use std::ffi::OsString;
10use std::os::windows::process::CommandExt;
11use std::path::PathBuf;
12use std::process::{Command, Stdio};
13use std::sync::atomic::{AtomicBool, Ordering};
14use std::sync::Mutex;
15use std::time::{Duration, Instant};
16
17use windows_sys::Win32::Foundation::{
18    CloseHandle, GetLastError, ERROR_ACCESS_DENIED, ERROR_INVALID_HANDLE, ERROR_INVALID_PARAMETER,
19    FALSE, GENERIC_READ, GENERIC_WRITE, HANDLE, HMODULE, HWND, INVALID_HANDLE_VALUE, LPARAM, TRUE,
20    WAIT_TIMEOUT,
21};
22use windows_sys::Win32::Storage::FileSystem::{
23    CreateFileW, FILE_SHARE_READ, FILE_SHARE_WRITE, OPEN_EXISTING,
24};
25use windows_sys::Win32::System::Console::{
26    AttachConsole, FreeConsole, GenerateConsoleCtrlEvent, GetConsoleProcessList,
27    SetConsoleCtrlHandler, WriteConsoleInputW, CTRL_BREAK_EVENT, CTRL_C_EVENT, INPUT_RECORD,
28    INPUT_RECORD_0, KEY_EVENT, KEY_EVENT_RECORD, KEY_EVENT_RECORD_0,
29};
30use windows_sys::Win32::System::LibraryLoader::{
31    GetModuleHandleExW, GetModuleHandleW, GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
32    GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
33};
34use windows_sys::Win32::System::Threading::{
35    ExitProcess, OpenProcess, TerminateProcess, WaitForSingleObject, DETACHED_PROCESS,
36    PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_SYNCHRONIZE, PROCESS_TERMINATE,
37};
38use windows_sys::Win32::UI::WindowsAndMessaging::{
39    EnumChildWindows, EnumWindows, GetClassNameW, GetWindow, GetWindowThreadProcessId,
40    IsWindowVisible, PostMessageW, SendMessageW, GW_OWNER, WM_CLOSE,
41};
42
43use crate::{Error, Method, Result};
44
45/// Opaque top-level window handle (an `HWND` value).
46pub type WindowHandle = usize;
47
48/// Which executable acts as the detached helper when one is required.
49#[derive(Debug, Clone)]
50pub enum Helper {
51    /// Re-launch the current executable (default). Requires that the code
52    /// runs from an `.exe`, not from a DLL loaded into a foreign host.
53    SelfExe,
54    /// Launch another executable that links this crate (for example the
55    /// `terminator` CLI). It must handle the helper marker before `main`,
56    /// which every binary linking this crate does automatically.
57    Path(PathBuf),
58}
59
60static HELPER: Mutex<Helper> = Mutex::new(Helper::SelfExe);
61
62/// Choose which executable is used when a detached helper is required.
63pub fn set_helper(helper: Helper) {
64    *HELPER.lock().unwrap_or_else(|e| e.into_inner()) = helper;
65}
66
67// ---------------------------------------------------------------------------
68// Helper protocol
69// ---------------------------------------------------------------------------
70
71/// First argument of a helper invocation. Deliberately unlikely to collide
72/// with a real command line.
73const MARKER: &str = "--terminator-internal-helper-v1";
74const PROTOCOL: &str = "1";
75/// How long the parent waits for the helper before assuming that the helper
76/// executable does not understand the protocol and killing it.
77const HELPER_TIMEOUT: Duration = Duration::from_secs(10);
78
79// Helper exit codes. Distinct from STATUS_CONTROL_C_EXIT (0xC000013A) so a
80// helper killed by the event it generated is never mistaken for success.
81const H_OK: i32 = 0;
82const H_BAD_ARGS: i32 = 100;
83const H_NO_CONSOLE: i32 = 104;
84const H_ACCESS_DENIED: i32 = 105;
85const H_NO_PROCESS: i32 = 106;
86const H_ATTACH_FAILED: i32 = 107;
87const H_ACTION_FAILED: i32 = 109;
88
89/// What a helper (or an attached caller) has to do on the target console.
90enum Task {
91    Ctrl(u32),
92    Message(String),
93}
94
95impl Task {
96    fn describe(&self) -> &'static str {
97        match self {
98            Task::Ctrl(_) => "sending a console control event",
99            Task::Message(_) => "writing to console input",
100        }
101    }
102}
103
104// Run before `main` by the C runtime (`.CRT$XCB` sorts before the `.CRT$XCU`
105// section used by `ctor`/`inventory`, so we run first). Keeps the "forgot to
106// call the helper entry point" failure mode impossible: any binary that can
107// spawn a helper contains this initializer, because `spawn_helper` references
108// the static below and so keeps it linked.
109#[used]
110#[link_section = ".CRT$XCB"]
111static HELPER_CTOR: unsafe extern "C" fn() = helper_ctor;
112
113unsafe extern "C" fn helper_ctor() {
114    run_helper_if_requested();
115}
116
117/// If this process was started as a helper, perform the requested task and
118/// exit. Otherwise return immediately.
119///
120/// Called automatically before `main`; calling it again is harmless.
121pub fn run_helper_if_requested() {
122    let args: Vec<OsString> = std::env::args_os().collect();
123    if args.len() < 2 || args[1] != MARKER {
124        return;
125    }
126    let code = helper_main(&args[2..]);
127    // SAFETY: plain FFI call, never returns.
128    unsafe { ExitProcess(code as u32) }
129}
130
131fn helper_main(args: &[OsString]) -> i32 {
132    // <protocol> <ctrl|msg> <pid> <payload>
133    if args.len() != 4 || args[0] != PROTOCOL {
134        return H_BAD_ARGS;
135    }
136    let (Some(kind), Some(pid), Some(payload)) =
137        (args[1].to_str(), args[2].to_str(), args[3].to_str())
138    else {
139        return H_BAD_ARGS;
140    };
141    let Ok(pid) = pid.parse::<u32>() else {
142        return H_BAD_ARGS;
143    };
144    let task = match kind {
145        "ctrl" => match payload.parse::<u32>() {
146            Ok(ev) if ev == CTRL_C_EVENT || ev == CTRL_BREAK_EVENT => Task::Ctrl(ev),
147            _ => return H_BAD_ARGS,
148        },
149        "msg" => match hex_decode(payload) {
150            Some(m) => Task::Message(m),
151            None => return H_BAD_ARGS,
152        },
153        _ => return H_BAD_ARGS,
154    };
155
156    if let Err(e) = attach(pid) {
157        return match e {
158            Error::ProcessNotFound(_) => H_NO_PROCESS,
159            Error::NoConsole(_) => H_NO_CONSOLE,
160            Error::Os(ref io) if io.raw_os_error() == Some(ERROR_ACCESS_DENIED as i32) => {
161                H_ACCESS_DENIED
162            }
163            _ => H_ATTACH_FAILED,
164        };
165    }
166    match run_here(&task) {
167        Ok(()) => H_OK,
168        Err(_) => H_ACTION_FAILED,
169    }
170}
171
172fn hex_encode(s: &str) -> String {
173    s.bytes().map(|b| format!("{b:02x}")).collect()
174}
175
176fn hex_decode(s: &str) -> Option<String> {
177    if s.len() % 2 != 0 {
178        return None;
179    }
180    let bytes: Option<Vec<u8>> = (0..s.len())
181        .step_by(2)
182        .map(|i| u8::from_str_radix(s.get(i..i + 2)?, 16).ok())
183        .collect();
184    String::from_utf8(bytes?).ok()
185}
186
187// ---------------------------------------------------------------------------
188// Routing
189// ---------------------------------------------------------------------------
190
191#[derive(Debug, Clone, Copy, PartialEq, Eq)]
192enum Route {
193    /// Target shares our console: act on it directly.
194    Direct,
195    /// We have no console: attach to the target's, act, detach.
196    InProcess,
197    /// We have our own console: a detached helper does the attaching.
198    Helper,
199}
200
201/// Serializes console attach/detach (process-wide state).
202static CONSOLE_LOCK: Mutex<()> = Mutex::new(());
203
204fn console_pids() -> Vec<u32> {
205    let mut cap = 16usize;
206    loop {
207        let mut buf = vec![0u32; cap];
208        // SAFETY: `buf` holds `cap` writable u32 values.
209        let n = unsafe { GetConsoleProcessList(buf.as_mut_ptr(), cap as u32) } as usize;
210        if n == 0 {
211            return Vec::new(); // not attached to a console
212        }
213        if n <= cap {
214            buf.truncate(n);
215            return buf;
216        }
217        cap = n + 4;
218    }
219}
220
221fn route_for(pid: u32) -> Route {
222    let pids = console_pids();
223    if pids.is_empty() {
224        Route::InProcess
225    } else if pids.contains(&pid) {
226        Route::Direct
227    } else {
228        Route::Helper
229    }
230}
231
232fn trace(route: Route, pid: u32) {
233    if std::env::var_os("TERMINATOR_DEBUG").is_some() {
234        eprintln!("terminator: pid={pid} route={route:?}");
235    }
236}
237
238fn dispatch(pid: u32, task: Task) -> Result<()> {
239    if !is_running(pid) {
240        return Err(Error::ProcessNotFound(pid));
241    }
242    let route = route_for(pid);
243    trace(route, pid);
244    match route {
245        Route::Direct => {
246            let _guard = CONSOLE_LOCK.lock().unwrap_or_else(|e| e.into_inner());
247            run_here(&task)
248        }
249        Route::InProcess => {
250            let _guard = CONSOLE_LOCK.lock().unwrap_or_else(|e| e.into_inner());
251            attach(pid)?;
252            let result = run_here(&task);
253            // SAFETY: plain FFI call; we attached above.
254            unsafe { FreeConsole() };
255            result
256        }
257        Route::Helper => spawn_helper(pid, &task),
258    }
259}
260
261/// Perform `task` on the console we are currently attached to.
262fn run_here(task: &Task) -> Result<()> {
263    match task {
264        Task::Ctrl(event) => generate_here(*event),
265        Task::Message(msg) => write_input_here(msg),
266    }
267}
268
269fn attach(pid: u32) -> Result<()> {
270    // SAFETY: plain FFI calls.
271    unsafe {
272        if AttachConsole(pid) != 0 {
273            return Ok(());
274        }
275        match GetLastError() {
276            ERROR_INVALID_PARAMETER => Err(Error::ProcessNotFound(pid)),
277            ERROR_INVALID_HANDLE => Err(Error::NoConsole(pid)),
278            // Either we are already attached to a console or the target is
279            // not accessible (for example it is elevated and we are not).
280            code => Err(Error::Os(std::io::Error::from_raw_os_error(code as i32))),
281        }
282    }
283}
284
285// ---------------------------------------------------------------------------
286// Console control events and console input
287// ---------------------------------------------------------------------------
288
289static EVENT_SEEN: AtomicBool = AtomicBool::new(false);
290
291/// Swallows Ctrl+C / Ctrl+Break so that an event generated for the whole
292/// console does not terminate the process that generated it.
293///
294/// A handler is used instead of `SetConsoleCtrlHandler(NULL, TRUE)` because
295/// the latter is inherited by child processes started meanwhile.
296unsafe extern "system" fn swallow(ctrl_type: u32) -> i32 {
297    if ctrl_type == CTRL_C_EVENT || ctrl_type == CTRL_BREAK_EVENT {
298        EVENT_SEEN.store(true, Ordering::SeqCst);
299        TRUE
300    } else {
301        FALSE
302    }
303}
304
305fn generate_here(event: u32) -> Result<()> {
306    EVENT_SEEN.store(false, Ordering::SeqCst);
307    // SAFETY: plain FFI calls; `swallow` has the required signature.
308    unsafe {
309        if SetConsoleCtrlHandler(Some(swallow), TRUE) == 0 {
310            return Err(Error::Os(std::io::Error::last_os_error()));
311        }
312        let ok = GenerateConsoleCtrlEvent(event, 0);
313        let err = std::io::Error::last_os_error();
314        if ok != 0 {
315            // The event arrives on a new thread. Wait for it so removing the
316            // handler cannot race with delivery. (If this process ignores
317            // Ctrl+C the handler never fires; the short timeout covers that.)
318            let deadline = Instant::now() + Duration::from_millis(500);
319            while !EVENT_SEEN.load(Ordering::SeqCst) && Instant::now() < deadline {
320                std::thread::sleep(Duration::from_millis(1));
321            }
322        }
323        SetConsoleCtrlHandler(Some(swallow), FALSE);
324        if ok == 0 {
325            return Err(Error::Os(err));
326        }
327    }
328    Ok(())
329}
330
331const VK_RETURN: u16 = 0x0D;
332const SCAN_RETURN: u16 = 0x1C;
333
334fn key_record(down: bool, vk: u16, scan: u16, ch: u16) -> INPUT_RECORD {
335    INPUT_RECORD {
336        EventType: KEY_EVENT as u16,
337        Event: INPUT_RECORD_0 {
338            KeyEvent: KEY_EVENT_RECORD {
339                bKeyDown: if down { TRUE } else { 0 },
340                wRepeatCount: 1,
341                wVirtualKeyCode: vk,
342                wVirtualScanCode: scan,
343                uChar: KEY_EVENT_RECORD_0 { UnicodeChar: ch },
344                dwControlKeyState: 0,
345            },
346        },
347    }
348}
349
350/// Turns text into console key events.
351///
352/// Ordinary characters are key-down only with no virtual key code. Line breaks (`\r`, `\n` and
353/// `\r\n`) become one real Enter press (down and up, with the Return virtual key and scan code).
354fn key_records(msg: &str) -> Vec<INPUT_RECORD> {
355    let mut out = Vec::with_capacity(msg.len());
356    let mut prev_cr = false;
357    for ch in msg.encode_utf16() {
358        match ch {
359            0x0D | 0x0A => {
360                // The `\n` of a `\r\n` pair is already covered by the Enter sent for `\r`.
361                if !(ch == 0x0A && prev_cr) {
362                    out.push(key_record(true, VK_RETURN, SCAN_RETURN, 0x0D));
363                    out.push(key_record(false, VK_RETURN, SCAN_RETURN, 0x0D));
364                }
365                prev_cr = ch == 0x0D;
366            }
367            _ => {
368                out.push(key_record(true, 0, 0, ch));
369                prev_cr = false;
370            }
371        }
372    }
373    out
374}
375
376fn write_input_here(msg: &str) -> Result<()> {
377    if msg.is_empty() {
378        return Err(Error::Os(std::io::Error::new(
379            std::io::ErrorKind::InvalidInput,
380            "empty message",
381        )));
382    }
383    let records = key_records(msg);
384    let name: Vec<u16> = "CONIN$\0".encode_utf16().collect();
385    // SAFETY: `name` is NUL-terminated; `records` outlives the call.
386    unsafe {
387        // CONIN$ is the input buffer of the console we are attached to, even
388        // when the standard handles were redirected.
389        let handle: HANDLE = CreateFileW(
390            name.as_ptr(),
391            GENERIC_READ | GENERIC_WRITE,
392            FILE_SHARE_READ | FILE_SHARE_WRITE,
393            std::ptr::null(),
394            OPEN_EXISTING,
395            0,
396            std::ptr::null_mut(),
397        );
398        if handle == INVALID_HANDLE_VALUE {
399            return Err(Error::Os(std::io::Error::last_os_error()));
400        }
401        let mut written = 0u32;
402        let ok = WriteConsoleInputW(handle, records.as_ptr(), records.len() as u32, &mut written);
403        let err = std::io::Error::last_os_error();
404        CloseHandle(handle);
405        if ok == 0 {
406            return Err(Error::Os(err));
407        }
408    }
409    Ok(())
410}
411
412// ---------------------------------------------------------------------------
413// Helper process
414// ---------------------------------------------------------------------------
415
416/// Whether the code of this crate is part of the process' main executable
417/// (as opposed to a DLL loaded into some other host).
418fn code_lives_in_exe() -> bool {
419    let mut module: HMODULE = std::ptr::null_mut();
420    // SAFETY: the address belongs to this function, which is always mapped.
421    unsafe {
422        let ok = GetModuleHandleExW(
423            GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
424            code_lives_in_exe as *const () as *const u16,
425            &mut module,
426        );
427        ok != 0 && module == GetModuleHandleW(std::ptr::null())
428    }
429}
430
431fn helper_program() -> Result<PathBuf> {
432    let helper = HELPER.lock().unwrap_or_else(|e| e.into_inner()).clone();
433    match helper {
434        Helper::Path(path) => Ok(path),
435        Helper::SelfExe => {
436            if !code_lives_in_exe() {
437                return Err(Error::HelperUnavailable(
438                    "terminator is loaded as a DLL into a foreign host, which cannot be \
439                     re-launched; call terminator::set_helper(Helper::Path(..)) with an \
440                     executable that links terminator (for example terminator.exe)"
441                        .into(),
442                ));
443            }
444            std::env::current_exe().map_err(Error::Os)
445        }
446    }
447}
448
449fn spawn_helper(pid: u32, task: &Task) -> Result<()> {
450    // Keep the pre-main initializer linked into every binary that can spawn
451    // a helper (otherwise the linker may drop the otherwise unreferenced static).
452    std::hint::black_box(&HELPER_CTOR);
453
454    let program = helper_program()?;
455    let (kind, payload) = match task {
456        Task::Ctrl(event) => ("ctrl", event.to_string()),
457        Task::Message(msg) => ("msg", hex_encode(msg)),
458    };
459    let mut child = Command::new(&program)
460        .arg(MARKER)
461        .arg(PROTOCOL)
462        .arg(kind)
463        .arg(pid.to_string())
464        .arg(payload)
465        .stdin(Stdio::null())
466        .stdout(Stdio::null())
467        .stderr(Stdio::null())
468        // No console of its own, so it is free to attach to the target's.
469        .creation_flags(DETACHED_PROCESS)
470        .spawn()
471        .map_err(Error::Os)?;
472
473    let deadline = Instant::now() + HELPER_TIMEOUT;
474    let status = loop {
475        match child.try_wait().map_err(Error::Os)? {
476            Some(status) => break status,
477            None if Instant::now() >= deadline => {
478                let _ = child.kill();
479                let _ = child.wait();
480                return Err(Error::HelperUnavailable(format!(
481                    "{} did not finish within {:?}; it probably does not link terminator \
482                     (the helper executable must handle the helper marker before main)",
483                    program.display(),
484                    HELPER_TIMEOUT
485                )));
486            }
487            None => std::thread::sleep(Duration::from_millis(2)),
488        }
489    };
490
491    match status.code().unwrap_or(-1) {
492        H_OK => Ok(()),
493        H_NO_PROCESS => Err(Error::ProcessNotFound(pid)),
494        H_NO_CONSOLE => Err(Error::NoConsole(pid)),
495        H_ACCESS_DENIED => Err(Error::Os(std::io::Error::from_raw_os_error(
496            ERROR_ACCESS_DENIED as i32,
497        ))),
498        code => Err(Error::HelperFailed {
499            code,
500            what: task.describe(),
501        }),
502    }
503}
504
505// ---------------------------------------------------------------------------
506// Windows (GUI)
507// ---------------------------------------------------------------------------
508
509struct EnumState {
510    pid: u32,
511    found: Option<usize>,
512}
513
514unsafe extern "system" fn enum_proc(hwnd: HWND, lparam: LPARAM) -> i32 {
515    let state = &mut *(lparam as *mut EnumState);
516    let mut window_pid = 0u32;
517    GetWindowThreadProcessId(hwnd, &mut window_pid);
518    if window_pid == state.pid && is_main_window(hwnd) {
519        state.found = Some(hwnd as usize);
520        return FALSE; // stop enumerating
521    }
522    TRUE
523}
524
525fn is_main_window(hwnd: HWND) -> bool {
526    // SAFETY: plain FFI calls.
527    unsafe { GetWindow(hwnd, GW_OWNER).is_null() && IsWindowVisible(hwnd) != 0 }
528}
529
530/// Class of the top-level windows that host packaged (UWP) apps. They are owned by
531/// `ApplicationFrameHost.exe`, not by the app, which keeps its content in a child window of
532/// the frame.
533const UWP_FRAME_CLASS: &str = "ApplicationFrameWindow";
534
535fn has_class(hwnd: HWND, expected: &str) -> bool {
536    let mut buf = [0u16; 64];
537    // SAFETY: `buf` is writable for its whole length.
538    let len = unsafe { GetClassNameW(hwnd, buf.as_mut_ptr(), buf.len() as i32) };
539    len > 0 && String::from_utf16_lossy(&buf[..len as usize]) == expected
540}
541
542struct FrameState {
543    pid: u32,
544    owns_child: bool,
545    frame: Option<usize>,
546}
547
548unsafe extern "system" fn child_proc(hwnd: HWND, lparam: LPARAM) -> i32 {
549    let state = &mut *(lparam as *mut FrameState);
550    let mut window_pid = 0u32;
551    GetWindowThreadProcessId(hwnd, &mut window_pid);
552    if window_pid == state.pid {
553        state.owns_child = true;
554        return FALSE; // stop enumerating children
555    }
556    TRUE
557}
558
559unsafe extern "system" fn frame_proc(hwnd: HWND, lparam: LPARAM) -> i32 {
560    let state = &mut *(lparam as *mut FrameState);
561    if has_class(hwnd, UWP_FRAME_CLASS) {
562        state.owns_child = false;
563        EnumChildWindows(hwnd, Some(child_proc), lparam);
564        if state.owns_child {
565            state.frame = Some(hwnd as usize);
566            return FALSE; // stop enumerating
567        }
568    }
569    TRUE
570}
571
572/// Returns the main window of process `pid`.
573///
574/// For a classic application that is its visible, unowned top-level window. A packaged (UWP)
575/// app has no such window: the frame that hosts it belongs to `ApplicationFrameHost.exe`, so
576/// the frame containing a window of `pid` is returned instead. Closing that frame closes the
577/// app, exactly like its close button.
578pub fn main_window(pid: u32) -> Result<WindowHandle> {
579    let mut state = EnumState { pid, found: None };
580    // SAFETY: `state` outlives the synchronous EnumWindows call.
581    unsafe { EnumWindows(Some(enum_proc), &mut state as *mut EnumState as LPARAM) };
582    if let Some(window) = state.found {
583        return Ok(window);
584    }
585
586    let mut frames = FrameState {
587        pid,
588        owns_child: false,
589        frame: None,
590    };
591    // SAFETY: `frames` outlives the synchronous enumeration.
592    unsafe { EnumWindows(Some(frame_proc), &mut frames as *mut FrameState as LPARAM) };
593    frames.frame.ok_or(Error::NoWindow(pid))
594}
595
596/// Sends `WM_CLOSE` to `window`, as if its close button was pressed.
597///
598/// With `wait` the call blocks until the window procedure handled the message (for example
599/// until the user answers a "save changes?" dialog).
600pub fn close_window(window: WindowHandle, wait: bool) -> Result<()> {
601    let hwnd = window as HWND;
602    let msg = WM_CLOSE;
603    // SAFETY: plain FFI calls; an invalid handle just makes them fail.
604    let ok = unsafe {
605        if wait {
606            SendMessageW(hwnd, msg, 0, 0) == 0
607        } else {
608            PostMessageW(hwnd, msg, 0, 0) != 0
609        }
610    };
611    if ok {
612        Ok(())
613    } else {
614        Err(Error::Os(std::io::Error::last_os_error()))
615    }
616}
617
618// ---------------------------------------------------------------------------
619// Public platform API
620// ---------------------------------------------------------------------------
621
622pub(crate) fn stop(pid: u32, method: Method) -> Result<()> {
623    match method {
624        Method::CtrlC => dispatch(pid, Task::Ctrl(CTRL_C_EVENT)),
625        Method::CtrlBreak => dispatch(pid, Task::Ctrl(CTRL_BREAK_EVENT)),
626        Method::CloseWindow => {
627            if !is_running(pid) {
628                return Err(Error::ProcessNotFound(pid));
629            }
630            close_window(main_window(pid)?, false)
631        }
632    }
633}
634
635pub(crate) fn send_message(pid: u32, msg: &str) -> Result<()> {
636    dispatch(pid, Task::Message(msg.to_owned()))
637}
638
639pub(crate) fn kill(pid: u32) -> Result<()> {
640    // An exited process whose handle is still open elsewhere can be opened
641    // but not terminated (ERROR_ACCESS_DENIED), which would be misleading.
642    if !is_running(pid) {
643        return Err(Error::ProcessNotFound(pid));
644    }
645    // SAFETY: plain FFI calls; the handle is closed on every path.
646    unsafe {
647        let handle = OpenProcess(PROCESS_TERMINATE, FALSE, pid);
648        if handle.is_null() {
649            return Err(match GetLastError() {
650                ERROR_INVALID_PARAMETER => Error::ProcessNotFound(pid),
651                code => Error::Os(std::io::Error::from_raw_os_error(code as i32)),
652            });
653        }
654        let ok = TerminateProcess(handle, 1);
655        let err = std::io::Error::last_os_error();
656        CloseHandle(handle);
657        if ok == 0 {
658            return Err(Error::Os(err));
659        }
660    }
661    Ok(())
662}
663
664pub(crate) fn is_running(pid: u32) -> bool {
665    // SAFETY: plain FFI calls; the handle is closed on every path.
666    unsafe {
667        let handle = OpenProcess(
668            PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_SYNCHRONIZE,
669            FALSE,
670            pid,
671        );
672        if handle.is_null() {
673            // Access denied means the process exists but is not ours.
674            return GetLastError() == ERROR_ACCESS_DENIED;
675        }
676        let running = WaitForSingleObject(handle, 0) == WAIT_TIMEOUT;
677        CloseHandle(handle);
678        running
679    }
680}