From 910b111efa4d776d195556e6ae7a6efe1585c2e2 Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Fri, 31 Dec 2021 19:30:52 -0700 Subject: [PATCH] move procinfo bits into own crate --- Cargo.lock | 12 + mux/Cargo.toml | 1 + mux/src/lib.rs | 1 - mux/src/localpane.rs | 30 +- procinfo/Cargo.toml | 22 + procinfo/src/lib.rs | 56 +++ procinfo/src/linux.rs | 130 ++++++ procinfo/src/macos.rs | 212 ++++++++++ .../procinfo.rs => procinfo/src/windows.rs | 399 +----------------- 9 files changed, 439 insertions(+), 424 deletions(-) create mode 100644 procinfo/Cargo.toml create mode 100644 procinfo/src/lib.rs create mode 100644 procinfo/src/linux.rs create mode 100644 procinfo/src/macos.rs rename mux/src/procinfo.rs => procinfo/src/windows.rs (51%) diff --git a/Cargo.lock b/Cargo.lock index 00070c142..be5c056a6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2294,6 +2294,7 @@ dependencies = [ "mlua", "ntapi", "portable-pty", + "procinfo", "promise", "rangeset", "ratelim", @@ -3088,6 +3089,17 @@ dependencies = [ "unicode-xid", ] +[[package]] +name = "procinfo" +version = "0.1.0" +dependencies = [ + "libc", + "luahelper", + "ntapi", + "serde", + "winapi 0.3.9", +] + [[package]] name = "promise" version = "0.2.0" diff --git a/mux/Cargo.toml b/mux/Cargo.toml index 9e007c92b..597ac9d7c 100644 --- a/mux/Cargo.toml +++ b/mux/Cargo.toml @@ -22,6 +22,7 @@ luahelper = { path = "../luahelper" } metrics = { version="0.17", features=["std"]} mlua = "0.7" portable-pty = { path = "../pty", features = ["serde_support"]} +procinfo = { path = "../procinfo" } promise = { path = "../promise" } rangeset = { path = "../rangeset" } ratelim= { path = "../ratelim" } diff --git a/mux/src/lib.rs b/mux/src/lib.rs index 250560ede..4c8b4d8f3 100644 --- a/mux/src/lib.rs +++ b/mux/src/lib.rs @@ -29,7 +29,6 @@ pub mod connui; pub mod domain; pub mod localpane; pub mod pane; -pub mod procinfo; pub mod renderable; pub mod ssh; pub mod tab; diff --git a/mux/src/localpane.rs b/mux/src/localpane.rs index 827251d79..336fabb05 100644 --- a/mux/src/localpane.rs +++ b/mux/src/localpane.rs @@ -1,6 +1,6 @@ use crate::domain::DomainId; use crate::pane::{CloseReason, Pane, PaneId, Pattern, SearchResult}; -use crate::procinfo::LocalProcessInfo; +use procinfo::LocalProcessInfo; use crate::renderable::*; use crate::tmux::{TmuxDomain, TmuxDomainState}; use crate::{Domain, Mux, MuxNotification}; @@ -834,35 +834,11 @@ impl LocalPane { } fn divine_process_list(&self, _force_refresh: bool) -> Option { - #[cfg(target_os = "macos")] + #[cfg(any(target_os = "macos", target_os = "linux", windows))] if let ProcessState::Running { pid: Some(pid), .. } = &*self.process.borrow() { - return LocalProcessInfo::with_root_pid_macos(*pid); + return LocalProcessInfo::with_root_pid(*pid); } - #[cfg(target_os = "linux")] - if let ProcessState::Running { pid: Some(pid), .. } = &*self.process.borrow() { - return LocalProcessInfo::with_root_pid_linux(*pid); - } - - #[cfg(windows)] - if let ProcessState::Running { pid: Some(pid), .. } = &*self.process.borrow() { - return dbg!(LocalProcessInfo::with_root_pid_windows(*pid)); - } - - /* - #[cfg(windows)] - if let ProcessState::Running { pid: Some(pid), .. } = &*self.process.borrow() { - return LocalProcessInfo::with_root_pid( - &*if _force_refresh { - crate::sysinfo::get_with_forced_refresh() - } else { - crate::sysinfo::get() - }, - *pid, - ); - } - */ - None } } diff --git a/procinfo/Cargo.toml b/procinfo/Cargo.toml new file mode 100644 index 000000000..d9a55ebed --- /dev/null +++ b/procinfo/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "procinfo" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +libc = "0.2" +serde = {version="1.0", features = ["rc", "derive"]} +luahelper = { path = "../luahelper" } + +[target."cfg(windows)".dependencies] +ntapi = "0.3" +winapi = { version = "0.3", features = [ + "handleapi", + "memoryapi", + "psapi", + "processthreadsapi", + "tlhelp32", +]} + diff --git a/procinfo/src/lib.rs b/procinfo/src/lib.rs new file mode 100644 index 000000000..1f0944f87 --- /dev/null +++ b/procinfo/src/lib.rs @@ -0,0 +1,56 @@ +use serde::{Deserialize, Serialize}; +use std::collections::{HashMap, HashSet}; +use std::path::PathBuf; +use std::time::{Duration, SystemTime}; + +mod macos; +mod windows; +mod linux; + +#[derive(Debug, Serialize, Deserialize, Copy, Clone)] +pub enum LocalProcessStatus { + Idle, + Run, + Sleep, + Stop, + Zombie, + Tracing, + Dead, + Wakekill, + Waking, + Parked, + LockBlocked, + Unknown, +} + +#[derive(Debug, Serialize, Deserialize, Clone)] +pub struct LocalProcessInfo { + pub pid: u32, + pub ppid: u32, + pub name: String, + pub executable: PathBuf, + pub argv: Vec, + pub cwd: PathBuf, + pub status: LocalProcessStatus, + pub children: HashMap, + pub start_time: SystemTime, +} +luahelper::impl_lua_conversion!(LocalProcessInfo); + +impl LocalProcessInfo { + pub fn flatten_to_exe_names(&self) -> HashSet { + let mut names = HashSet::new(); + + fn flatten(item: &LocalProcessInfo, names: &mut HashSet) { + if let Some(exe) = item.executable.file_name() { + names.insert(exe.to_string_lossy().into_owned()); + } + for proc in item.children.values() { + flatten(proc, names); + } + } + + flatten(self, &mut names); + names + } +} diff --git a/procinfo/src/linux.rs b/procinfo/src/linux.rs new file mode 100644 index 000000000..27cb87a27 --- /dev/null +++ b/procinfo/src/linux.rs @@ -0,0 +1,130 @@ +#![cfg(target_os = "linux")] +use super::*; + +impl From<&str> for LocalProcessStatus { + fn from(s: &str) -> Self { + match s { + "R" => Self::Run, + "S" => Self::Sleep, + "D" => Self::Idle, + "Z" => Self::Zombie, + "T" => Self::Stop, + "t" => Self::Tracing, + "X" | "x" => Self::Dead, + "K" => Self::Wakekill, + "W" => Self::Waking, + "P" => Self::Parked, + _ => Self::Unknown, + } + } +} + +impl LocalProcessInfo { + pub fn with_root_pid(pid: u32) -> Option { + use libc::pid_t; + + let pid = pid as pid_t; + + fn all_pids() -> Vec { + let mut pids = vec![]; + if let Ok(dir) = std::fs::read_dir("/proc") { + for entry in dir { + if let Ok(entry) = entry { + if let Ok(file_type) = entry.file_type() { + if file_type.is_dir() { + if let Some(name) = entry.file_name().to_str() { + if let Ok(pid) = name.parse::() { + pids.push(pid); + } + } + } + } + } + } + } + pids + } + + struct LinuxStat { + pid: pid_t, + name: String, + status: String, + ppid: pid_t, + // Time process started after boot, measured in ticks + starttime: u64, + } + + fn info_for_pid(pid: pid_t) -> Option { + let data = std::fs::read_to_string(format!("/proc/{}/stat", pid)).ok()?; + let (_pid_space, name) = data.split_once('(')?; + let (name, fields) = name.rsplit_once(')')?; + let fields = fields.split_whitespace().collect::>(); + + Some(LinuxStat { + pid, + name: name.to_string(), + status: fields.get(0)?.to_string(), + ppid: fields.get(1)?.parse().ok()?, + starttime: fields.get(20)?.parse().ok()?, + }) + } + + fn exe_for_pid(pid: pid_t) -> PathBuf { + std::fs::read_link(format!("/proc/{}/exe", pid)).unwrap_or_else(|_| PathBuf::new()) + } + fn cwd_for_pid(pid: pid_t) -> PathBuf { + std::fs::read_link(format!("/proc/{}/cwd", pid)).unwrap_or_else(|_| PathBuf::new()) + } + + fn parse_cmdline(pid: pid_t) -> Vec { + let data = match std::fs::read(format!("/proc/{}/cmdline", pid)) { + Ok(data) => data, + Err(_) => return vec![], + }; + + let mut args = vec![]; + + let data = data.strip_suffix(&[0]).unwrap_or(&data); + + for arg in data.split(|&c| c == 0) { + args.push(String::from_utf8_lossy(arg).to_owned().to_string()); + } + + args + } + + let procs: Vec<_> = all_pids().into_iter().filter_map(info_for_pid).collect(); + + fn build_proc(info: &LinuxStat, procs: &[LinuxStat]) -> LocalProcessInfo { + let mut children = HashMap::new(); + + for kid in procs { + if kid.ppid == info.pid { + children.insert(kid.pid as u32, build_proc(kid, procs)); + } + } + + let executable = exe_for_pid(info.pid); + let name = info.name.clone(); + let argv = parse_cmdline(info.pid); + + LocalProcessInfo { + pid: info.pid as _, + ppid: info.ppid as _, + name, + executable, + cwd: cwd_for_pid(info.pid), + argv, + start_time: info.starttime, + status: info.status.as_str().into(), + children, + } + } + + if let Some(info) = procs.iter().find(|info| info.pid == pid) { + Some(build_proc(info, &procs)) + } else { + None + } + } +} diff --git a/procinfo/src/macos.rs b/procinfo/src/macos.rs new file mode 100644 index 000000000..b92d6f69f --- /dev/null +++ b/procinfo/src/macos.rs @@ -0,0 +1,212 @@ +#![cfg(target_os = "macos")] +use super::*; + +impl From for LocalProcessStatus { + fn from(s: u32) -> Self { + match s { + 1 => Self::Idle, + 2 => Self::Run, + 3 => Self::Sleep, + 4 => Self::Stop, + 5 => Self::Zombie, + _ => Self::Unknown, + } + } +} + +impl LocalProcessInfo { + pub fn with_root_pid(pid: u32) -> Option { + /// Enumerate all current process identifiers + fn all_pids() -> Vec { + let num_pids = unsafe { libc::proc_listallpids(std::ptr::null_mut(), 0) }; + if num_pids < 1 { + return vec![]; + } + + // Give a bit of padding to avoid looping if processes are spawning + // rapidly while we're trying to collect this info + const PADDING: usize = 32; + let mut pids: Vec = Vec::with_capacity(num_pids as usize + PADDING); + loop { + let n = unsafe { + libc::proc_listallpids( + pids.as_mut_ptr() as *mut _, + (pids.capacity() * std::mem::size_of::()) as _, + ) + }; + + if n < 1 { + return vec![]; + } + + let n = n as usize; + + if n > pids.capacity() { + pids.reserve(n + PADDING); + continue; + } + + unsafe { pids.set_len(n) }; + return pids; + } + } + + /// Obtain info block for a pid. + /// Note that the process could have gone away since we first + /// observed the pid and the time we call this, so we must + /// be able to tolerate this failing. + fn info_for_pid(pid: libc::pid_t) -> Option { + let mut info: libc::proc_bsdinfo = unsafe { std::mem::zeroed() }; + let wanted_size = std::mem::size_of::() as _; + let res = unsafe { + libc::proc_pidinfo( + pid, + libc::PROC_PIDTBSDINFO, + 0, + &mut info as *mut _ as *mut _, + wanted_size, + ) + }; + + if res == wanted_size { + Some(info) + } else { + None + } + } + + fn cwd_for_pid(pid: libc::pid_t) -> PathBuf { + let mut pathinfo: libc::proc_vnodepathinfo = unsafe { std::mem::zeroed() }; + let size = std::mem::size_of_val(&pathinfo) as libc::c_int; + let ret = unsafe { + libc::proc_pidinfo( + pid, + libc::PROC_PIDVNODEPATHINFO, + 0, + &mut pathinfo as *mut _ as *mut _, + size, + ) + }; + if ret == size { + let path = + unsafe { std::ffi::CStr::from_ptr(pathinfo.pvi_cdir.vip_path.as_ptr() as _) }; + path.to_str().unwrap_or("").into() + } else { + PathBuf::new() + } + } + + fn exe_and_args_for_pid_sysctl(pid: libc::pid_t) -> Option<(PathBuf, Vec)> { + use libc::c_int; + let mut size = 64 * 1024; + let mut buf: Vec = Vec::with_capacity(size); + let mut mib = [libc::CTL_KERN, libc::KERN_PROCARGS2, pid as c_int]; + + let res = unsafe { + libc::sysctl( + mib.as_mut_ptr(), + mib.len() as _, + buf.as_mut_ptr() as *mut _, + &mut size, + std::ptr::null_mut(), + 0, + ) + }; + if res == -1 { + return None; + } + if size < (std::mem::size_of::() * 2) { + // Not big enough + return None; + } + unsafe { buf.set_len(size) }; + + // The data in our buffer is laid out like this: + // argc - c_int + // exe_path - NUL terminated string + // argv[0] - NUL terminated string + // argv[1] - NUL terminated string + // ... + // argv[n] - NUL terminated string + // envp[0] - NUL terminated string + // ... + + let mut ptr = &buf[0..size]; + + let argc: c_int = unsafe { std::ptr::read(ptr.as_ptr() as *const c_int) }; + ptr = &ptr[std::mem::size_of::()..]; + + fn consume_cstr(ptr: &mut &[u8]) -> Option { + let nul = ptr.iter().position(|&c| c == 0)?; + let s = String::from_utf8_lossy(&ptr[0..nul]).to_owned().to_string(); + *ptr = ptr.get(nul + 1..)?; + Some(s) + } + + let exe_path = consume_cstr(&mut ptr)?.into(); + + let mut args = vec![]; + for _ in 0..argc { + args.push(consume_cstr(&mut ptr)?); + } + + Some((exe_path, args)) + } + + fn exe_for_pid(pid: libc::pid_t) -> PathBuf { + let mut buffer: Vec = Vec::with_capacity(libc::PROC_PIDPATHINFO_MAXSIZE as _); + let x = unsafe { + libc::proc_pidpath( + pid, + buffer.as_mut_ptr() as *mut _, + libc::PROC_PIDPATHINFO_MAXSIZE as _, + ) + }; + if x > 0 { + unsafe { buffer.set_len(x as usize) }; + String::from_utf8_lossy(&buffer) + .to_owned() + .to_string() + .into() + } else { + PathBuf::new() + } + } + + let procs: Vec<_> = all_pids().into_iter().filter_map(info_for_pid).collect(); + + fn build_proc(info: &libc::proc_bsdinfo, procs: &[libc::proc_bsdinfo]) -> LocalProcessInfo { + let mut children = HashMap::new(); + + for kid in procs { + if kid.pbi_ppid == info.pbi_pid { + children.insert(kid.pbi_pid, build_proc(kid, procs)); + } + } + + let (executable, argv) = exe_and_args_for_pid_sysctl(info.pbi_pid as _) + .unwrap_or_else(|| (exe_for_pid(info.pbi_pid as _), vec![])); + + let name = unsafe { std::ffi::CStr::from_ptr(info.pbi_comm.as_ptr() as _) }; + let name = name.to_str().unwrap_or("").to_string(); + + LocalProcessInfo { + pid: info.pbi_pid, + ppid: info.pbi_ppid, + name, + executable, + cwd: cwd_for_pid(info.pbi_pid as _), + argv, + start_time: info.pbi_start_tvsec, + status: LocalProcessStatus::from(info.pbi_status), + children, + } + } + + if let Some(info) = procs.iter().find(|info| info.pbi_pid == pid) { + Some(build_proc(info, &procs)) + } else { + None + } + } +} diff --git a/mux/src/procinfo.rs b/procinfo/src/windows.rs similarity index 51% rename from mux/src/procinfo.rs rename to procinfo/src/windows.rs index a6ba783f8..3aee4c494 100644 --- a/mux/src/procinfo.rs +++ b/procinfo/src/windows.rs @@ -1,203 +1,8 @@ -use serde::{Deserialize, Serialize}; -use std::collections::{HashMap, HashSet}; -use std::path::PathBuf; -use std::time::{Duration, SystemTime}; - -#[derive(Debug, Serialize, Deserialize, Copy, Clone)] -pub enum LocalProcessStatus { - Idle, - Run, - Sleep, - Stop, - Zombie, - Tracing, - Dead, - Wakekill, - Waking, - Parked, - LockBlocked, - Unknown, -} - -#[cfg(target_os = "linux")] -impl From<&str> for LocalProcessStatus { - fn from(s: &str) -> Self { - match s { - "R" => Self::Run, - "S" => Self::Sleep, - "D" => Self::Idle, - "Z" => Self::Zombie, - "T" => Self::Stop, - "t" => Self::Tracing, - "X" | "x" => Self::Dead, - "K" => Self::Wakekill, - "W" => Self::Waking, - "P" => Self::Parked, - _ => Self::Unknown, - } - } -} - -#[cfg(target_os = "macos")] -impl From for LocalProcessStatus { - fn from(s: u32) -> Self { - match s { - 1 => Self::Idle, - 2 => Self::Run, - 3 => Self::Sleep, - 4 => Self::Stop, - 5 => Self::Zombie, - _ => Self::Unknown, - } - } -} - -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct LocalProcessInfo { - pub pid: u32, - pub ppid: u32, - pub name: String, - pub executable: PathBuf, - pub argv: Vec, - pub cwd: PathBuf, - pub status: LocalProcessStatus, - pub children: HashMap, - pub start_time: SystemTime, -} -luahelper::impl_lua_conversion!(LocalProcessInfo); +#![cfg(windows)] +use super::*; impl LocalProcessInfo { - pub fn flatten_to_exe_names(&self) -> HashSet { - let mut names = HashSet::new(); - - fn flatten(item: &LocalProcessInfo, names: &mut HashSet) { - if let Some(exe) = item.executable.file_name() { - names.insert(exe.to_string_lossy().into_owned()); - } - for proc in item.children.values() { - flatten(proc, names); - } - } - - flatten(self, &mut names); - names - } -} - -#[cfg(target_os = "linux")] -impl LocalProcessInfo { - pub(crate) fn with_root_pid_linux(pid: u32) -> Option { - use libc::pid_t; - - let pid = pid as pid_t; - - fn all_pids() -> Vec { - let mut pids = vec![]; - if let Ok(dir) = std::fs::read_dir("/proc") { - for entry in dir { - if let Ok(entry) = entry { - if let Ok(file_type) = entry.file_type() { - if file_type.is_dir() { - if let Some(name) = entry.file_name().to_str() { - if let Ok(pid) = name.parse::() { - pids.push(pid); - } - } - } - } - } - } - } - pids - } - - struct LinuxStat { - pid: pid_t, - name: String, - status: String, - ppid: pid_t, - // Time process started after boot, measured in ticks - starttime: u64, - } - - fn info_for_pid(pid: pid_t) -> Option { - let data = std::fs::read_to_string(format!("/proc/{}/stat", pid)).ok()?; - let (_pid_space, name) = data.split_once('(')?; - let (name, fields) = name.rsplit_once(')')?; - let fields = fields.split_whitespace().collect::>(); - - Some(LinuxStat { - pid, - name: name.to_string(), - status: fields.get(0)?.to_string(), - ppid: fields.get(1)?.parse().ok()?, - starttime: fields.get(20)?.parse().ok()?, - }) - } - - fn exe_for_pid(pid: pid_t) -> PathBuf { - std::fs::read_link(format!("/proc/{}/exe", pid)).unwrap_or_else(|_| PathBuf::new()) - } - fn cwd_for_pid(pid: pid_t) -> PathBuf { - std::fs::read_link(format!("/proc/{}/cwd", pid)).unwrap_or_else(|_| PathBuf::new()) - } - - fn parse_cmdline(pid: pid_t) -> Vec { - let data = match std::fs::read(format!("/proc/{}/cmdline", pid)) { - Ok(data) => data, - Err(_) => return vec![], - }; - - let mut args = vec![]; - - let data = data.strip_suffix(&[0]).unwrap_or(&data); - - for arg in data.split(|&c| c == 0) { - args.push(String::from_utf8_lossy(arg).to_owned().to_string()); - } - - args - } - - let procs: Vec<_> = all_pids().into_iter().filter_map(info_for_pid).collect(); - - fn build_proc(info: &LinuxStat, procs: &[LinuxStat]) -> LocalProcessInfo { - let mut children = HashMap::new(); - - for kid in procs { - if kid.ppid == info.pid { - children.insert(kid.pid as u32, build_proc(kid, procs)); - } - } - - let executable = exe_for_pid(info.pid); - let name = info.name.clone(); - let argv = parse_cmdline(info.pid); - - LocalProcessInfo { - pid: info.pid as _, - ppid: info.ppid as _, - name, - executable, - cwd: cwd_for_pid(info.pid), - argv, - start_time: info.starttime, - status: info.status.as_str().into(), - children, - } - } - - if let Some(info) = procs.iter().find(|info| info.pid == pid) { - Some(build_proc(info, &procs)) - } else { - None - } - } -} - -#[cfg(windows)] -impl LocalProcessInfo { - pub(crate) fn with_root_pid_windows(pid: u32) -> Option { + pub fn with_root_pid(pid: u32) -> Option { use ntapi::ntpebteb::PEB; use ntapi::ntpsapi::{ NtQueryInformationProcess, ProcessBasicInformation, ProcessWow64Information, @@ -578,201 +383,3 @@ impl LocalProcessInfo { } } } - -#[cfg(target_os = "macos")] -impl LocalProcessInfo { - pub(crate) fn with_root_pid_macos(pid: u32) -> Option { - /// Enumerate all current process identifiers - fn all_pids() -> Vec { - let num_pids = unsafe { libc::proc_listallpids(std::ptr::null_mut(), 0) }; - if num_pids < 1 { - return vec![]; - } - - // Give a bit of padding to avoid looping if processes are spawning - // rapidly while we're trying to collect this info - const PADDING: usize = 32; - let mut pids: Vec = Vec::with_capacity(num_pids as usize + PADDING); - loop { - let n = unsafe { - libc::proc_listallpids( - pids.as_mut_ptr() as *mut _, - (pids.capacity() * std::mem::size_of::()) as _, - ) - }; - - if n < 1 { - return vec![]; - } - - let n = n as usize; - - if n > pids.capacity() { - pids.reserve(n + PADDING); - continue; - } - - unsafe { pids.set_len(n) }; - return pids; - } - } - - /// Obtain info block for a pid. - /// Note that the process could have gone away since we first - /// observed the pid and the time we call this, so we must - /// be able to tolerate this failing. - fn info_for_pid(pid: libc::pid_t) -> Option { - let mut info: libc::proc_bsdinfo = unsafe { std::mem::zeroed() }; - let wanted_size = std::mem::size_of::() as _; - let res = unsafe { - libc::proc_pidinfo( - pid, - libc::PROC_PIDTBSDINFO, - 0, - &mut info as *mut _ as *mut _, - wanted_size, - ) - }; - - if res == wanted_size { - Some(info) - } else { - None - } - } - - fn cwd_for_pid(pid: libc::pid_t) -> PathBuf { - let mut pathinfo: libc::proc_vnodepathinfo = unsafe { std::mem::zeroed() }; - let size = std::mem::size_of_val(&pathinfo) as libc::c_int; - let ret = unsafe { - libc::proc_pidinfo( - pid, - libc::PROC_PIDVNODEPATHINFO, - 0, - &mut pathinfo as *mut _ as *mut _, - size, - ) - }; - if ret == size { - let path = - unsafe { std::ffi::CStr::from_ptr(pathinfo.pvi_cdir.vip_path.as_ptr() as _) }; - path.to_str().unwrap_or("").into() - } else { - PathBuf::new() - } - } - - fn exe_and_args_for_pid_sysctl(pid: libc::pid_t) -> Option<(PathBuf, Vec)> { - use libc::c_int; - let mut size = 64 * 1024; - let mut buf: Vec = Vec::with_capacity(size); - let mut mib = [libc::CTL_KERN, libc::KERN_PROCARGS2, pid as c_int]; - - let res = unsafe { - libc::sysctl( - mib.as_mut_ptr(), - mib.len() as _, - buf.as_mut_ptr() as *mut _, - &mut size, - std::ptr::null_mut(), - 0, - ) - }; - if res == -1 { - return None; - } - if size < (std::mem::size_of::() * 2) { - // Not big enough - return None; - } - unsafe { buf.set_len(size) }; - - // The data in our buffer is laid out like this: - // argc - c_int - // exe_path - NUL terminated string - // argv[0] - NUL terminated string - // argv[1] - NUL terminated string - // ... - // argv[n] - NUL terminated string - // envp[0] - NUL terminated string - // ... - - let mut ptr = &buf[0..size]; - - let argc: c_int = unsafe { std::ptr::read(ptr.as_ptr() as *const c_int) }; - ptr = &ptr[std::mem::size_of::()..]; - - fn consume_cstr(ptr: &mut &[u8]) -> Option { - let nul = ptr.iter().position(|&c| c == 0)?; - let s = String::from_utf8_lossy(&ptr[0..nul]).to_owned().to_string(); - *ptr = ptr.get(nul + 1..)?; - Some(s) - } - - let exe_path = consume_cstr(&mut ptr)?.into(); - - let mut args = vec![]; - for _ in 0..argc { - args.push(consume_cstr(&mut ptr)?); - } - - Some((exe_path, args)) - } - - fn exe_for_pid(pid: libc::pid_t) -> PathBuf { - let mut buffer: Vec = Vec::with_capacity(libc::PROC_PIDPATHINFO_MAXSIZE as _); - let x = unsafe { - libc::proc_pidpath( - pid, - buffer.as_mut_ptr() as *mut _, - libc::PROC_PIDPATHINFO_MAXSIZE as _, - ) - }; - if x > 0 { - unsafe { buffer.set_len(x as usize) }; - String::from_utf8_lossy(&buffer) - .to_owned() - .to_string() - .into() - } else { - PathBuf::new() - } - } - - let procs: Vec<_> = all_pids().into_iter().filter_map(info_for_pid).collect(); - - fn build_proc(info: &libc::proc_bsdinfo, procs: &[libc::proc_bsdinfo]) -> LocalProcessInfo { - let mut children = HashMap::new(); - - for kid in procs { - if kid.pbi_ppid == info.pbi_pid { - children.insert(kid.pbi_pid, build_proc(kid, procs)); - } - } - - let (executable, argv) = exe_and_args_for_pid_sysctl(info.pbi_pid as _) - .unwrap_or_else(|| (exe_for_pid(info.pbi_pid as _), vec![])); - - let name = unsafe { std::ffi::CStr::from_ptr(info.pbi_comm.as_ptr() as _) }; - let name = name.to_str().unwrap_or("").to_string(); - - LocalProcessInfo { - pid: info.pbi_pid, - ppid: info.pbi_ppid, - name, - executable, - cwd: cwd_for_pid(info.pbi_pid as _), - argv, - start_time: info.pbi_start_tvsec, - status: LocalProcessStatus::from(info.pbi_status), - children, - } - } - - if let Some(info) = procs.iter().find(|info| info.pbi_pid == pid) { - Some(build_proc(info, &procs)) - } else { - None - } - } -}