use std::io;
use std::path::Path;
use std::process::{Command, ExitStatus};
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
pub static INTERRUPTED: AtomicBool = AtomicBool::new(false);
const WATCH_EVERY: Duration = Duration::from_millis(250);
pub const EXIT_STOPPED: i32 = 137;
pub const EXIT_INTERRUPTED: i32 = 130;
pub const SHELL_CHARS: &[char] = imp::SHELL_CHARS;
pub fn install_signal_handler() {
imp::before_handler();
let _ = ctrlc::set_handler(|| {
INTERRUPTED.store(true, Ordering::SeqCst);
imp::forward_interrupt();
});
}
pub fn watchdog(parent: i32, pgid: i32) -> i32 {
imp::watchdog(parent, pgid)
}
pub fn send_ctrl_c(pid: u32) -> bool {
imp::send_ctrl_c(pid)
}
pub fn build(argv: &[String], cwd: &Path) -> io::Result<Command> {
if argv.is_empty() {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "no command given"));
}
if crate::shell::is_shell_string(argv) {
return Ok(shell_command(&argv[0]));
}
imp::build(argv, cwd)
}
pub fn shell_command(line: &str) -> Command {
imp::shell_command(line)
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Ended {
pub code: i32,
pub stopped: bool,
}
pub fn run(
cmd: Command,
low_cpu: bool,
on_spawn: impl FnOnce(u32),
watch: &mut dyn FnMut(u32) -> bool,
) -> io::Result<Ended> {
imp::run(cmd, low_cpu, on_spawn, watch)
}
pub fn on_path(name: &str) -> bool {
imp::find_on_path(name).is_some()
}
pub fn quote_for_display(w: &str) -> String {
const SAFE: &str = "_@%+=:,./-\\";
if !w.is_empty() && w.chars().all(|c| c.is_ascii_alphanumeric() || SAFE.contains(c)) {
return w.to_string();
}
imp::quote(w)
}
pub fn code_of(status: ExitStatus) -> i32 {
imp::signal_of(&status).map_or_else(|| status.code().unwrap_or(1), |sig| 128 + sig)
}
#[cfg(unix)]
mod imp {
use super::*;
use std::os::unix::process::{CommandExt, ExitStatusExt};
use std::sync::atomic::AtomicI32;
use std::time::Instant;
static CHILD_PGID: AtomicI32 = AtomicI32::new(0);
const STOP_GRACE: Duration = Duration::from_secs(3);
const NICE: libc::c_int = 10;
pub const SHELL_CHARS: &[char] = &[
'&', '|', ';', '<', '>', '(', ')', '$', '`', '*', '?', '\n', '~', '{', '[',
];
pub fn before_handler() {}
pub fn forward_interrupt() {
let pg = CHILD_PGID.load(Ordering::SeqCst);
if pg > 0 {
unsafe {
libc::killpg(pg, libc::SIGINT);
}
}
}
pub fn send_ctrl_c(pid: u32) -> bool {
unsafe { libc::kill(pid as i32, libc::SIGINT) == 0 }
}
pub fn signal_of(status: &ExitStatus) -> Option<i32> {
status.signal()
}
pub fn find_on_path(name: &str) -> Option<std::path::PathBuf> {
use std::os::unix::fs::PermissionsExt;
let path = std::env::var_os("PATH")?;
std::env::split_paths(&path).map(|d| d.join(name)).find(|p| {
p.metadata()
.is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0)
})
}
pub fn quote(w: &str) -> String {
format!("'{}'", w.replace('\'', "'\\''"))
}
pub fn shell_command(line: &str) -> Command {
let mut c = Command::new("/bin/sh");
c.arg("-c").arg(line);
c
}
pub fn build(argv: &[String], cwd: &Path) -> io::Result<Command> {
let p = Path::new(&argv[0]);
let program = if p.is_relative() && argv[0].contains('/') {
cwd.join(p)
} else {
p.to_path_buf()
};
let mut c = Command::new(program);
c.args(&argv[1..]);
Ok(c)
}
fn owns_terminal() -> bool {
unsafe { libc::isatty(0) == 1 && libc::tcgetpgrp(0) == libc::getpgrp() }
}
fn give_terminal_to(pgrp: libc::pid_t) {
unsafe {
libc::signal(libc::SIGTTOU, libc::SIG_IGN);
libc::tcsetpgrp(0, pgrp);
libc::signal(libc::SIGTTOU, libc::SIG_DFL);
}
}
fn killpg(pid: i32, sig: libc::c_int) {
unsafe {
libc::killpg(pid, sig);
}
}
pub fn run(
mut cmd: Command,
low_cpu: bool,
on_spawn: impl FnOnce(u32),
watch: &mut dyn FnMut(u32) -> bool,
) -> io::Result<Ended> {
let tty = owns_terminal();
let parent = unsafe { libc::getpid() };
cmd.process_group(0);
unsafe {
cmd.pre_exec(move || {
die_with_parent(parent);
if low_cpu {
libc::nice(NICE);
}
if tty {
give_terminal_to(libc::getpid());
}
Ok(())
});
}
let child = cmd.spawn()?;
let pid = child.id() as i32;
CHILD_PGID.store(pid, Ordering::SeqCst);
let mut guard = Watchdog::start(parent, pid);
on_spawn(child.id());
let (status, stopped) = wait_child(pid, tty, watch);
CHILD_PGID.store(0, Ordering::SeqCst);
guard.stop();
if tty {
give_terminal_to(unsafe { libc::getpgrp() });
}
if stopped {
killpg(pid, libc::SIGKILL);
} else if INTERRUPTED.load(Ordering::SeqCst) {
killpg(pid, libc::SIGTERM);
}
let code = if stopped { EXIT_STOPPED } else { code_of(status?) };
Ok(Ended { code, stopped })
}
fn wait_child(pid: i32, tty: bool, watch: &mut dyn FnMut(u32) -> bool) -> (io::Result<ExitStatus>, bool) {
let mut stopped_at: Option<Instant> = None;
loop {
let mut st: libc::c_int = 0;
let r = unsafe { libc::waitpid(pid, &mut st, libc::WNOHANG | libc::WUNTRACED) };
if r < 0 {
return (Err(io::Error::last_os_error()), stopped_at.is_some());
}
if r == pid && libc::WIFSTOPPED(st) {
if tty {
suspend_with_child(pid);
}
continue;
}
if r == pid {
return (Ok(ExitStatus::from_raw(st)), stopped_at.is_some());
}
match stopped_at {
None if watch(pid as u32) => {
killpg(pid, libc::SIGTERM);
stopped_at = Some(Instant::now());
}
Some(t) if t.elapsed() > STOP_GRACE => killpg(pid, libc::SIGKILL),
_ => {}
}
std::thread::sleep(WATCH_EVERY);
}
}
fn suspend_with_child(pid: i32) {
unsafe {
give_terminal_to(libc::getpgrp());
libc::kill(libc::getpid(), libc::SIGSTOP);
}
give_terminal_to(pid);
killpg(pid, libc::SIGCONT);
}
#[cfg(target_os = "linux")]
fn die_with_parent(parent: libc::pid_t) {
unsafe {
libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGTERM);
if libc::getppid() != parent {
libc::_exit(1);
}
}
}
#[cfg(not(target_os = "linux"))]
fn die_with_parent(_: libc::pid_t) {}
struct Watchdog(Option<std::process::Child>);
impl Watchdog {
fn start(parent: libc::pid_t, pgid: i32) -> Watchdog {
if !cfg!(target_os = "macos") {
return Watchdog(None);
}
let child = std::env::current_exe().ok().and_then(|exe| {
let mut c = Command::new(exe);
c.args(["__watchdog", &parent.to_string(), &pgid.to_string()])
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.process_group(0);
c.spawn().ok()
});
Watchdog(child)
}
fn stop(&mut self) {
if let Some(mut c) = self.0.take() {
let _ = c.kill();
let _ = c.wait();
}
}
}
pub fn watchdog(parent: i32, pgid: i32) -> i32 {
const CHECK_EVERY: Duration = Duration::from_millis(500);
loop {
let parent_alive = unsafe { libc::kill(parent, 0) == 0 };
let group_alive = unsafe { libc::killpg(pgid, 0) == 0 };
if !group_alive {
return 0;
}
if !parent_alive {
killpg(pgid, libc::SIGTERM);
std::thread::sleep(STOP_GRACE);
killpg(pgid, libc::SIGKILL);
return 0;
}
std::thread::sleep(CHECK_EVERY);
}
}
}
#[cfg(windows)]
mod imp {
use super::*;
use std::os::windows::io::AsRawHandle;
use std::os::windows::process::CommandExt;
use std::path::PathBuf;
use windows_sys::Win32::Foundation::{CloseHandle, HANDLE, INVALID_HANDLE_VALUE};
use windows_sys::Win32::System::JobObjects::{
AssignProcessToJobObject, CreateJobObjectW, JobObjectExtendedLimitInformation,
SetInformationJobObject, TerminateJobObject, JOBOBJECT_EXTENDED_LIMIT_INFORMATION,
JOB_OBJECT_LIMIT_BREAKAWAY_OK, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
};
pub const SHELL_CHARS: &[char] = &[
'&', '|', ';', '<', '>', '(', ')', '$', '`', '*', '?', '\n', '%', '^', '!', '~',
];
pub fn watchdog(_: i32, _: i32) -> i32 {
2
}
const STATUS_CONTROL_C_EXIT: i32 = 0xC000_013Au32 as i32;
const CTRL_C_SETTLE: Duration = Duration::from_millis(500);
pub fn before_handler() {
unsafe {
windows_sys::Win32::System::Console::SetConsoleCtrlHandler(None, 0);
}
}
pub fn forward_interrupt() {}
pub fn signal_of(_: &ExitStatus) -> Option<i32> {
None
}
pub fn quote(w: &str) -> String {
format!("\"{}\"", w.replace('"', "\\\""))
}
pub fn send_ctrl_c(pid: u32) -> bool {
use windows_sys::Win32::System::Console::{
AttachConsole, FreeConsole, GenerateConsoleCtrlEvent, SetConsoleCtrlHandler, CTRL_C_EVENT,
};
unsafe {
FreeConsole();
if AttachConsole(pid) == 0 {
return false;
}
SetConsoleCtrlHandler(None, 1);
let ok = GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0) != 0;
std::thread::sleep(CTRL_C_SETTLE);
FreeConsole();
ok
}
}
fn comspec() -> String {
std::env::var("ComSpec").unwrap_or_else(|_| "cmd.exe".to_string())
}
pub fn shell_command(line: &str) -> Command {
let mut c = Command::new(comspec());
c.raw_arg(format!("/d /s /c \"{line}\""));
c
}
pub fn build(argv: &[String], cwd: &Path) -> io::Result<Command> {
let path = resolve(&argv[0], cwd).ok_or_else(|| {
io::Error::new(io::ErrorKind::NotFound, format!("command not found: {}", argv[0]))
})?;
let ext = path
.extension()
.map(|e| e.to_string_lossy().to_ascii_lowercase())
.unwrap_or_default();
let mut c = match ext.as_str() {
"cmd" | "bat" => {
let mut line = caret(&path.to_string_lossy());
for a in &argv[1..] {
line.push(' ');
line.push_str(&escape_argument(a));
}
let mut c = Command::new(comspec());
c.raw_arg(format!("/d /s /c \"{line}\""));
return Ok(c);
}
"ps1" => {
let mut c = Command::new("powershell.exe");
c.args(["-NoProfile", "-ExecutionPolicy", "Bypass", "-File"])
.arg(&path);
c
}
_ => Command::new(&path),
};
c.args(&argv[1..]);
Ok(c)
}
fn pathext() -> Vec<String> {
std::env::var("PATHEXT")
.unwrap_or_else(|_| ".COM;.EXE;.BAT;.CMD".to_string())
.split(';')
.filter(|e| !e.is_empty())
.map(|e| e.to_ascii_lowercase())
.collect()
}
fn try_file(base: &Path, exts: &[String]) -> Option<PathBuf> {
let has_ext = base.extension().is_some_and(|e| {
exts.contains(&format!(".{}", e.to_string_lossy().to_ascii_lowercase())) || e == "ps1"
});
if has_ext && base.is_file() {
return Some(base.to_path_buf());
}
exts.iter().find_map(|e| {
let mut s = base.as_os_str().to_owned();
s.push(e);
let p = PathBuf::from(s);
p.is_file().then_some(p)
})
}
pub fn resolve(name: &str, cwd: &Path) -> Option<PathBuf> {
let exts = pathext();
let p = Path::new(name);
if p.is_absolute() {
return try_file(p, &exts);
}
if name.contains(['/', '\\']) {
return try_file(&cwd.join(name.replace('/', "\\")), &exts);
}
find_on_path(name)
}
pub fn find_on_path(name: &str) -> Option<PathBuf> {
let exts = pathext();
let path = std::env::var_os("PATH")?;
std::env::split_paths(&path)
.filter(|d| !d.as_os_str().is_empty())
.find_map(|d| try_file(&d.join(name), &exts))
}
const META: &[char] = &[
'(', ')', ']', '[', '%', '!', '^', '"', '`', '<', '>', '&', '|', ';', ',', ' ', '*', '?',
];
fn caret(s: &str) -> String {
let mut out = String::with_capacity(s.len() * 2);
for c in s.chars() {
if META.contains(&c) {
out.push('^');
}
out.push(c);
}
out
}
pub fn escape_argument(arg: &str) -> String {
let mut quoted = String::from("\"");
let mut backslashes = 0;
for c in arg.chars() {
match c {
'\\' => backslashes += 1,
'"' => {
quoted.extend(std::iter::repeat_n('\\', backslashes * 2 + 1));
quoted.push('"');
backslashes = 0;
}
_ => {
quoted.extend(std::iter::repeat_n('\\', backslashes));
quoted.push(c);
backslashes = 0;
}
}
}
quoted.extend(std::iter::repeat_n('\\', backslashes * 2));
quoted.push('"');
caret(&caret("ed))
}
struct Job(HANDLE);
impl Job {
fn new() -> Option<Job> {
let h = unsafe { CreateJobObjectW(std::ptr::null(), std::ptr::null()) };
if h.is_null() {
return None;
}
let job = Job(h);
job.set_flags(JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE | JOB_OBJECT_LIMIT_BREAKAWAY_OK);
Some(job)
}
fn set_flags(&self, flags: u32) -> bool {
unsafe {
let mut info: JOBOBJECT_EXTENDED_LIMIT_INFORMATION = std::mem::zeroed();
info.BasicLimitInformation.LimitFlags = flags;
SetInformationJobObject(
self.0,
JobObjectExtendedLimitInformation,
&info as *const _ as *const core::ffi::c_void,
std::mem::size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() as u32,
) != 0
}
}
fn assign(&self, process: HANDLE) -> bool {
unsafe { AssignProcessToJobObject(self.0, process) != 0 }
}
fn release(&self) {
self.set_flags(JOB_OBJECT_LIMIT_BREAKAWAY_OK);
}
fn terminate(&self, code: u32) {
unsafe {
TerminateJobObject(self.0, code);
}
}
}
impl Drop for Job {
fn drop(&mut self) {
unsafe {
CloseHandle(self.0);
}
}
}
fn resume_threads(pid: u32) {
use windows_sys::Win32::System::Diagnostics::ToolHelp::{
CreateToolhelp32Snapshot, Thread32First, Thread32Next, TH32CS_SNAPTHREAD, THREADENTRY32,
};
use windows_sys::Win32::System::Threading::{OpenThread, ResumeThread, THREAD_SUSPEND_RESUME};
unsafe {
let snap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
if snap.is_null() || snap == INVALID_HANDLE_VALUE {
return;
}
let mut te: THREADENTRY32 = std::mem::zeroed();
te.dwSize = std::mem::size_of::<THREADENTRY32>() as u32;
let mut ok = Thread32First(snap, &mut te) != 0;
while ok {
if te.th32OwnerProcessID == pid {
let t = OpenThread(THREAD_SUSPEND_RESUME, 0, te.th32ThreadID);
if !t.is_null() {
ResumeThread(t);
CloseHandle(t);
}
}
ok = Thread32Next(snap, &mut te) != 0;
}
CloseHandle(snap);
}
}
pub fn run(
mut cmd: Command,
low_cpu: bool,
on_spawn: impl FnOnce(u32),
watch: &mut dyn FnMut(u32) -> bool,
) -> io::Result<Ended> {
use windows_sys::Win32::System::Threading::{BELOW_NORMAL_PRIORITY_CLASS, CREATE_SUSPENDED};
let job = Job::new();
let priority = if low_cpu { BELOW_NORMAL_PRIORITY_CLASS } else { 0 };
cmd.creation_flags(CREATE_SUSPENDED | priority);
let mut child = cmd.spawn()?;
if let Some(j) = &job {
j.assign(child.as_raw_handle() as HANDLE);
}
resume_threads(child.id());
on_spawn(child.id());
let mut stopped = false;
let status = loop {
if let Some(st) = child.try_wait()? {
break st;
}
if !stopped && watch(child.id()) {
stopped = true;
match &job {
Some(j) => j.terminate(EXIT_STOPPED as u32),
None => {
let _ = child.kill();
}
}
}
std::thread::sleep(WATCH_EVERY);
};
let interrupted = INTERRUPTED.load(Ordering::SeqCst);
if let Some(j) = job.as_ref().filter(|_| !interrupted && !stopped) {
j.release();
}
let code = match code_of(status) {
_ if stopped => EXIT_STOPPED,
STATUS_CONTROL_C_EXIT if interrupted => EXIT_INTERRUPTED,
c => c,
};
Ok(Ended { code, stopped })
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn escapes_metacharacters() {
assert_eq!(escape_argument("a b"), "^^^\"a^^^ b^^^\"");
assert_eq!(escape_argument("x&y"), "^^^\"x^^^&y^^^\"");
assert_eq!(escape_argument("say \"hi\""), "^^^\"say^^^ \\^^^\"hi\\^^^\"^^^\"");
assert_eq!(escape_argument("dir\\"), "^^^\"dir\\\\^^^\"");
}
#[test]
fn resolves_cmd_from_path() {
let found = resolve("cmd", Path::new(".")).expect("cmd.exe on PATH");
assert!(found.to_string_lossy().to_ascii_lowercase().ends_with("cmd.exe"));
}
}
}