Skip to main content

quickjs_jit_stdlib/llrt/llrt_utils/
signals.rs

1// Vendored from LLRT d9fd873e793c (libs/llrt_utils/src/signals.rs); module paths and
2// feature names adapted by scripts/import-stdlib.py, with local patches.
3// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
4// SPDX-License-Identifier: Apache-2.0
5use rquickjs::{prelude::Opt, Ctx, Exception, Result, Value};
6
7use crate::utils::result::ResultExt;
8use std::io;
9
10#[cfg(unix)]
11macro_rules! generate_signal_from_str_fn {
12    ($($signal:path),*) => {
13        pub fn signal_from_str(signal: &str) -> Option<i32> {
14            let signal = ["libc::", signal].concat();
15            match signal.as_str() {
16                $(stringify!($signal) => Some($signal),)*
17                _ => None,
18            }
19        }
20
21        pub fn signal_str_from_i32(signal: i32) -> Option<&'static str> {
22            $(if signal == $signal {
23                return Some(&stringify!($signal)[6..]);
24            })*
25            None
26        }
27    };
28}
29
30#[cfg(unix)]
31generate_signal_from_str_fn!(
32    libc::SIGHUP,
33    libc::SIGINT,
34    libc::SIGQUIT,
35    libc::SIGILL,
36    libc::SIGABRT,
37    libc::SIGFPE,
38    libc::SIGKILL,
39    libc::SIGSEGV,
40    libc::SIGPIPE,
41    libc::SIGALRM,
42    libc::SIGTERM
43);
44
45#[cfg(not(unix))]
46static WINDOWS_SIGTERM: i32 = -1;
47
48pub fn parse_signal(signal: Option<Value<'_>>) -> Result<i32> {
49    let Some(val) = signal else {
50        #[cfg(unix)]
51        return Ok(libc::SIGTERM);
52        #[cfg(not(unix))]
53        return Ok(WINDOWS_SIGTERM);
54    };
55
56    if let Some(num) = val.as_number() {
57        let sig = num as i32;
58        #[cfg(unix)]
59        return Ok(sig);
60        // On Windows: 0 checks existence, anything else kills
61        #[cfg(not(unix))]
62        return Ok(if sig == 0 { 0 } else { WINDOWS_SIGTERM });
63    }
64
65    if let Some(str_val) = val.as_string() {
66        let s = str_val.to_string()?;
67
68        #[cfg(unix)]
69        let mapped_sig = signal_from_str(&s);
70
71        #[cfg(not(unix))]
72        let mapped_sig = match s.as_str() {
73            "SIGINT" | "SIGTERM" | "SIGKILL" | "SIGQUIT" | "SIGHUP" | "SIGUSR1" => {
74                Some(WINDOWS_SIGTERM)
75            }
76            _ => None,
77        };
78
79        return match mapped_sig {
80            Some(sig) => Ok(sig),
81            None => Err(Exception::throw_type(
82                val.ctx(),
83                &format!("Unknown signal: {}", s),
84            )),
85        };
86    }
87
88    Err(Exception::throw_type(val.ctx(), "Invalid signal type"))
89}
90
91#[cfg(unix)]
92pub fn kill_process_raw(pid: u32, signal: i32) -> io::Result<()> {
93    // libc::kill returns 0 on success, -1 on error
94    // SAFETY: kill is a safe system call as long as the signal value is valid, which is ensured by parse_signal
95    if unsafe { libc::kill(pid as i32, signal) } == 0 {
96        Ok(())
97    } else {
98        Err(io::Error::last_os_error())
99    }
100}
101
102#[cfg(windows)]
103pub fn kill_process_raw(pid: u32, signal: i32) -> io::Result<()> {
104    use windows_sys::Win32::Foundation::CloseHandle;
105    use windows_sys::Win32::System::Threading::{OpenProcess, TerminateProcess, PROCESS_TERMINATE};
106
107    // SAFETY: OpenProcess is safe to call with valid parameters, and PROCESS_TERMINATE is a valid access right
108    let handle = unsafe { OpenProcess(PROCESS_TERMINATE, 0, pid) };
109    if handle == std::ptr::null_mut() {
110        return Err(io::Error::last_os_error());
111    }
112
113    let result = if signal == 0 {
114        Ok(())
115    } else {
116        // SAFETY: TerminateProcess is safe to call with a valid process handle obtained from OpenProcess
117        if unsafe { TerminateProcess(handle, 1) } != 0 {
118            Ok(())
119        } else {
120            Err(io::Error::last_os_error())
121        }
122    };
123
124    // SAFETY: CloseHandle is safe to call with a valid handle obtained from OpenProcess
125    unsafe { CloseHandle(handle) };
126    result
127}
128
129// Other targets (WebAssembly) cannot send operating-system signals.
130#[cfg(not(any(unix, windows)))]
131pub fn kill_process_raw(_pid: u32, _signal: i32) -> io::Result<()> {
132    Err(io::Error::new(
133        io::ErrorKind::Unsupported,
134        "process signals require a native host",
135    ))
136}
137
138pub fn kill(ctx: &Ctx<'_>, pid: u32, signal: Opt<Value<'_>>) -> Result<bool> {
139    let signal = parse_signal(signal.0)?;
140
141    kill_process_raw(pid, signal)
142        .map(|_| true)
143        .or_else(|e| {
144            // Handle "Process Not Found" / "Existence Check" logic
145            // If signal is 0 (check existence) and we hit a specific error, return Ok(false).
146
147            #[cfg(unix)]
148            let is_not_found = e.raw_os_error() == Some(libc::ESRCH); // Error 3
149
150            #[cfg(not(any(unix, windows)))]
151            let is_not_found = false;
152
153            #[cfg(windows)]
154            let is_not_found = true; // On Windows, any OpenProcess failure during check implies "not found" (or not accessible)
155
156            if signal == 0 && is_not_found {
157                Ok(false)
158            } else {
159                Err(e)
160            }
161        })
162        .or_throw(ctx)
163}