pub(crate) fn read_singleton_lock(user_data_dir: &std::path::Path) -> Option<u32> {
#[cfg(unix)]
{
let target = std::fs::read_link(user_data_dir.join("SingletonLock")).ok()?;
target.to_str()?.rsplit('-').next()?.parse().ok()
}
#[cfg(not(unix))]
{
let _ = user_data_dir;
None
}
}
pub(crate) fn pid_is_alive(pid: u32) -> bool {
#[cfg(target_os = "linux")]
{
std::path::Path::new(&format!("/proc/{pid}")).exists()
}
#[cfg(not(target_os = "linux"))]
{
no_proc_pid_is_alive(pid)
}
}
pub(crate) fn read_devtools_active_port(user_data_dir: &std::path::Path) -> Option<u16> {
let contents = std::fs::read_to_string(user_data_dir.join("DevToolsActivePort")).ok()?;
contents.lines().next()?.trim().parse().ok()
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
pub(crate) fn read_process_argv(pid: u32) -> Option<Vec<String>> {
#[cfg(target_os = "linux")]
{
let raw = std::fs::read(format!("/proc/{pid}/cmdline")).ok()?;
let argv = parse_proc_cmdline(&raw);
(!argv.is_empty()).then_some(argv)
}
#[cfg(target_os = "macos")]
{
let output = std::process::Command::new("ps")
.args(["-ww", "-p", &pid.to_string(), "-o", "args="])
.output()
.ok()?;
if !output.status.success() {
return None;
}
Some(
String::from_utf8_lossy(&output.stdout)
.split_whitespace()
.map(str::to_owned)
.collect(),
)
}
}
#[cfg(any(target_os = "linux", test))]
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
fn parse_proc_cmdline(raw: &[u8]) -> Vec<String> {
let pieces: Vec<String> = raw
.split(|&b| b == 0)
.filter(|piece| !piece.is_empty())
.map(|piece| String::from_utf8_lossy(piece).into_owned())
.collect();
match pieces.as_slice() {
[title] if title.contains(char::is_whitespace) => {
title.split_whitespace().map(str::to_owned).collect()
}
_ => pieces,
}
}
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
pub(crate) fn read_process_argv(_: u32) -> Option<Vec<String>> {
None
}
#[cfg(all(unix, not(target_os = "linux")))]
fn no_proc_pid_is_alive(pid: u32) -> bool {
let Ok(pid) = libc::pid_t::try_from(pid) else {
return false;
};
unsafe { libc::kill(pid, 0) == 0 }
}
#[cfg(not(unix))]
fn no_proc_pid_is_alive(_: u32) -> bool {
false
}
#[cfg(all(test, unix))]
mod tests {
use super::*;
use std::os::unix::fs::symlink;
fn temp_profile_dir(name: &str) -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!(
"eoka-profile-test-{}-{}-{}",
std::process::id(),
name,
fastrand::u64(..)
));
std::fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn read_singleton_lock_parses_trailing_pid() {
let dir = temp_profile_dir("lock");
symlink("some-host-54321", dir.join("SingletonLock")).unwrap();
assert_eq!(read_singleton_lock(&dir), Some(54321));
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn read_singleton_lock_missing_is_none() {
let dir = temp_profile_dir("no-lock");
assert!(read_singleton_lock(&dir).is_none());
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn proc_cmdline_splits_rewritten_process_title() {
let argv =
parse_proc_cmdline(b"/opt/chrome --headless=new --no-sandbox --user-data-dir=/p\0");
assert_eq!(
argv,
[
"/opt/chrome",
"--headless=new",
"--no-sandbox",
"--user-data-dir=/p"
]
);
let argv =
parse_proc_cmdline(b"/opt/chrome\0--user-agent=Mozilla/5.0 (X11)\0--headless=new\0");
assert_eq!(
argv,
[
"/opt/chrome",
"--user-agent=Mozilla/5.0 (X11)",
"--headless=new"
]
);
}
#[test]
fn pid_is_alive_true_for_self() {
assert!(pid_is_alive(std::process::id()));
}
#[test]
fn read_devtools_active_port_parses_first_line() {
let dir = temp_profile_dir("port");
std::fs::write(
dir.join("DevToolsActivePort"),
"37469\n/devtools/browser/00000000-0000-0000-0000-000000000000\n",
)
.unwrap();
assert_eq!(read_devtools_active_port(&dir), Some(37469));
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn read_devtools_active_port_missing_is_none() {
let dir = temp_profile_dir("no-port");
assert!(read_devtools_active_port(&dir).is_none());
std::fs::remove_dir_all(&dir).unwrap();
}
#[cfg(target_os = "linux")]
#[test]
fn read_process_argv_reads_own_cmdline() {
let argv = read_process_argv(std::process::id()).expect("own /proc entry must exist");
assert!(!argv.is_empty());
}
#[cfg(target_os = "linux")]
#[test]
fn empty_cmdline_is_unverified_not_an_empty_argv() {
let mut child = std::process::Command::new("true").spawn().unwrap();
let stat = format!("/proc/{}/stat", child.id());
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
crate::cdp::poll::poll_blocking(
Some(deadline),
std::time::Duration::from_millis(5),
|| {
std::fs::read_to_string(&stat)
.unwrap()
.rsplit_once(')')
.is_some_and(|(_, rest)| rest.trim_start().starts_with('Z'))
.then_some(())
},
)
.expect("the exited child must become a zombie");
assert_eq!(read_process_argv(child.id()), None);
child.wait().unwrap();
}
}