Skip to content

Computer use CLI for AI agents

perf(macos): read the app process inventory with libproc instead of spawning ps (#573)

Railly Hugob43ac4f6e892
diff --git a/crates/macos/src/system/app/app_inventory.rs b/crates/macos/src/system/app/app_inventory.rs
index 4db7008b2..2c1e109cc 100644
--- a/crates/macos/src/system/app/app_inventory.rs
+++ b/crates/macos/src/system/app/app_inventory.rs
@@ -191,7 +191,7 @@ fn required_sources_failed(
) -> AdapterError {
let failures = [
source_failure("ns_workspace", workspace),
- source_failure("ps", process),
+ source_failure("libproc", process),
]
.into_iter()
.filter(|failure| !failure["code"].is_null())
diff --git a/crates/macos/src/system/app/app_inventory_tests.rs b/crates/macos/src/system/app/app_inventory_tests.rs
index cb24e304d..1e59b2da0 100644
--- a/crates/macos/src/system/app/app_inventory_tests.rs
+++ b/crates/macos/src/system/app/app_inventory_tests.rs
@@ -81,8 +81,9 @@ fn merge_apps_rejects_pid_reuse_between_sources() {
#[test]
fn signal_inventory_rejects_even_one_missing_complete_source() {
- let error = complete_apps_from_sources(Ok(vec![app("Finder", 10)]), Err(source_error("ps")))
- .unwrap_err();
+ let error =
+ complete_apps_from_sources(Ok(vec![app("Finder", 10)]), Err(source_error("libproc")))
+ .unwrap_err();
assert_eq!(error.code, ErrorCode::AppUnresponsive);
let details = error.details.unwrap();
diff --git a/crates/macos/src/system/process/legacy_host.rs b/crates/macos/src/system/process/legacy_host.rs
index 64bacfa7e..df7f69907 100644
--- a/crates/macos/src/system/process/legacy_host.rs
+++ b/crates/macos/src/system/process/legacy_host.rs
@@ -2,8 +2,11 @@
use std::mem::{MaybeUninit, size_of};
+use super::process_arguments::{
+ PROC_UID_ONLY, argument_buffer, arguments, list_pids, read_arguments,
+};
+
const HOST_MARKER: &[u8] = b"AGENT_DESKTOP_INTERNAL_COMMAND_HOST=1";
-const PROC_UID_ONLY: u32 = 4;
const CS_OPS_IDENTITY: u32 = 11;
const IDENTITY_BUFFER_LEN: usize = 512;
const BLOB_HEADER_LEN: usize = 8;
@@ -26,7 +29,7 @@ pub fn stop_legacy_command_hosts() {
let Some(mut buffer) = argument_buffer() else {
return;
};
- for pid in user_processes(uid) {
+ for pid in list_pids(PROC_UID_ONLY, uid).unwrap_or_default() {
if pid <= 0 || pid == own_pid || !has_marker(pid, &mut buffer) {
continue;
}
@@ -45,21 +48,9 @@ pub fn stop_legacy_command_hosts() {
/// Whether a `KERN_PROCARGS2` buffer carries the host marker in its environment,
/// skipping the executable path and arguments that precede it.
pub(crate) fn environment_has_marker(procargs: &[u8]) -> bool {
- let Some((count, rest)) = procargs.split_first_chunk::<4>() else {
- return false;
- };
- let arguments = i32::from_ne_bytes(*count);
- if arguments <= 0 {
- return false;
- }
- let Some(path_end) = rest.iter().position(|byte| *byte == 0) else {
- return false;
- };
- let rest = &rest[path_end + 1..];
- let Some(arguments_start) = rest.iter().position(|byte| *byte != 0) else {
+ let Some((arguments, mut rest)) = arguments(procargs) else {
return false;
};
- let mut rest = &rest[arguments_start..];
for _ in 0..arguments {
let Some(end) = rest.iter().position(|byte| *byte == 0) else {
return false;
@@ -98,32 +89,6 @@ fn is_agent_desktop(pid: libc::pid_t) -> bool {
read == 0 && blob_names_agent_desktop(&blob)
}
-fn user_processes(uid: libc::uid_t) -> Vec<libc::pid_t> {
- let size = unsafe { libc::proc_listpids(PROC_UID_ONLY, uid, std::ptr::null_mut(), 0) };
- let Ok(size) = usize::try_from(size) else {
- return Vec::new();
- };
- let mut pids = vec![0; size / size_of::<libc::pid_t>() + 1];
- loop {
- let Some(bytes) = pids.len().checked_mul(size_of::<libc::pid_t>()) else {
- return Vec::new();
- };
- let Ok(bytes) = i32::try_from(bytes) else {
- return Vec::new();
- };
- let written =
- unsafe { libc::proc_listpids(PROC_UID_ONLY, uid, pids.as_mut_ptr().cast(), bytes) };
- if written <= 0 {
- return Vec::new();
- }
- if written < bytes {
- pids.truncate(written as usize / size_of::<libc::pid_t>());
- return pids;
- }
- pids.resize(pids.len() * 2, 0);
- }
-}
-
fn process_start_time(pid: libc::pid_t, uid: libc::uid_t) -> Option<(u64, u64)> {
let info = process_info(pid)?;
(info.pbi_pid == pid as u32 && info.pbi_uid == uid && info.pbi_status != libc::SZOMB)
@@ -145,43 +110,8 @@ fn process_info(pid: libc::pid_t) -> Option<libc::proc_bsdinfo> {
(read == size).then(|| unsafe { info.assume_init() })
}
-fn argument_buffer() -> Option<Vec<u8>> {
- let mut mib = [libc::CTL_KERN, libc::KERN_ARGMAX];
- let mut max: libc::c_int = 0;
- let mut size = size_of::<libc::c_int>();
- let read = unsafe {
- libc::sysctl(
- mib.as_mut_ptr(),
- 2,
- (&mut max as *mut libc::c_int).cast(),
- &mut size,
- std::ptr::null_mut(),
- 0,
- )
- };
- if read != 0 {
- return None;
- }
- usize::try_from(max)
- .ok()
- .filter(|max| *max > 0)
- .map(|max| vec![0u8; max])
-}
-
fn has_marker(pid: libc::pid_t, buffer: &mut [u8]) -> bool {
- let mut mib = [libc::CTL_KERN, libc::KERN_PROCARGS2, pid];
- let mut size = buffer.len();
- let read = unsafe {
- libc::sysctl(
- mib.as_mut_ptr(),
- 3,
- buffer.as_mut_ptr().cast(),
- &mut size,
- std::ptr::null_mut(),
- 0,
- )
- };
- read == 0 && size <= buffer.len() && environment_has_marker(&buffer[..size])
+ read_arguments(pid, buffer).is_some_and(environment_has_marker)
}
#[cfg(test)]
diff --git a/crates/macos/src/system/process/legacy_host_tests.rs b/crates/macos/src/system/process/legacy_host_tests.rs
index 1ce337c33..a6c5fe7dc 100644
--- a/crates/macos/src/system/process/legacy_host_tests.rs
+++ b/crates/macos/src/system/process/legacy_host_tests.rs
@@ -4,7 +4,9 @@ const MARKER: &str = "AGENT_DESKTOP_INTERNAL_COMMAND_HOST=1";
fn procargs(arguments: &[&str], environment: &[&str]) -> Vec<u8> {
let mut buffer = (arguments.len() as i32).to_ne_bytes().to_vec();
- buffer.extend_from_slice(b"/usr/local/bin/agent-desktop\0\0\0");
+ let mut path = b"/usr/local/bin/agent-desktop\0".to_vec();
+ path.resize(path.len().next_multiple_of(8), 0);
+ buffer.extend_from_slice(&path);
for field in arguments.iter().chain(environment) {
buffer.extend_from_slice(field.as_bytes());
buffer.push(0);
@@ -34,6 +36,15 @@ fn the_marker_counts_only_as_an_exact_environment_entry() {
}
}
+#[test]
+fn an_empty_first_argument_keeps_the_environment_aligned() {
+ assert!(environment_has_marker(&procargs(&["", "x"], &[MARKER])));
+ assert!(!environment_has_marker(&procargs(
+ &["", MARKER],
+ &["HOME=/Users/a"]
+ )));
+}
+
#[test]
fn malformed_argument_blocks_fail_closed() {
assert!(!environment_has_marker(&[1, 0]));
diff --git a/crates/macos/src/system/process/mod.rs b/crates/macos/src/system/process/mod.rs
index 0fe6e7059..dca44c028 100644
--- a/crates/macos/src/system/process/mod.rs
+++ b/crates/macos/src/system/process/mod.rs
@@ -326,6 +326,7 @@ fn output_limit_error(label: &str, stdout: &DrainResult, stderr: &DrainResult) -
pub(crate) mod legacy_host;
pub(crate) mod process_apps;
+pub(crate) mod process_arguments;
pub(crate) mod process_identity;
pub(crate) mod process_state;
#[cfg(all(test, unix))]
diff --git a/crates/macos/src/system/process/process_apps.rs b/crates/macos/src/system/process/process_apps.rs
index aa0acf147..2be49ff94 100644
--- a/crates/macos/src/system/process/process_apps.rs
+++ b/crates/macos/src/system/process/process_apps.rs
@@ -1,5 +1,5 @@
use agent_desktop_core::{AdapterError, AppInfo, ErrorCode};
-use std::{process::Output, time::Instant};
+use std::time::Instant;
pub(crate) fn list_apps_until(deadline: Instant) -> Result<Vec<AppInfo>, AdapterError> {
#[cfg(test)]
@@ -21,15 +21,17 @@ fn list_apps_with_filter(
deadline: Instant,
) -> Result<Vec<AppInfo>, AdapterError> {
if Instant::now() >= deadline {
- return Err(AdapterError::timeout("ps app inventory timed out"));
+ return Err(AdapterError::timeout("process app inventory timed out"));
}
- let mut command = std::process::Command::new("/bin/ps");
- command.args(["-axo", "pid=,comm="]);
- let output = crate::system::process::run_with_deadline(&mut command, "ps", deadline)?;
- let mut apps = apps_from_output(output)?;
- apps.retain(|app| {
- name.is_none_or(|name| agent_desktop_core::app_name_matches(&app.name, name))
- });
+ let mut apps = Vec::new();
+ crate::system::process::process_arguments::visit_commands_until(deadline, |pid, command| {
+ if let Some(app) = app_from_command(pid, command)?
+ && name.is_none_or(|name| agent_desktop_core::app_name_matches(&app.name, name))
+ {
+ apps.push(app);
+ }
+ Ok(())
+ })?;
enrich_process_instances(
apps,
crate::system::process::process_identity::token_for_pid,
@@ -64,82 +66,23 @@ pub(crate) fn is_cross_uid_identity_error(error: &AdapterError) -> bool {
== Some("process_identity_permission")
}
-fn apps_from_output(output: Output) -> Result<Vec<AppInfo>, AdapterError> {
- if !output.status.success() {
- let detail = String::from_utf8_lossy(&output.stderr).trim().to_string();
- return Err(inventory_error(
- format!("ps app inventory exited with {}", output.status),
- detail,
- ));
+fn app_from_command(pid: i32, command: &[u8]) -> Result<Option<AppInfo>, AdapterError> {
+ if pid <= 0 {
+ return Ok(None);
}
- let text = String::from_utf8(output.stdout).map_err(|error| {
- inventory_error(
- "ps app inventory returned non-UTF-8 output".to_string(),
- error.to_string(),
- )
- })?;
- parse_apps(&text)
-}
-
-fn parse_apps(text: &str) -> Result<Vec<AppInfo>, AdapterError> {
- let mut seen_pids = rustc_hash::FxHashSet::default();
- let mut apps = Vec::new();
-
- for line in text.lines() {
- let line = line.trim_start();
- if line.is_empty() {
- continue;
- }
- let mut fields = line.splitn(2, char::is_whitespace);
- let pid_text = fields.next().ok_or_else(malformed_output)?;
- let command = fields
- .next()
- .map(str::trim)
- .filter(|command| !command.is_empty())
- .ok_or_else(malformed_output)?;
- let pid = pid_text.parse::<i32>().map_err(|_| malformed_output())?;
- if pid <= 0 {
- return Err(malformed_output());
- }
- let Some(name) = app_name_from_command(command) else {
- if command.contains(".app/Contents/MacOS")
- && !command.contains("/Contents/Frameworks/")
- && !command.contains("/Contents/PlugIns/")
- {
- return Err(malformed_output());
- }
- continue;
- };
- if seen_pids.insert(pid) {
- apps.push(AppInfo {
- name,
- pid: crate::system::process::process_identity::from_pid_t(pid)?,
- bundle_id: None,
- process_instance: None,
- presentation: None,
- });
- }
- }
-
- Ok(apps)
-}
-
-fn malformed_output() -> AdapterError {
- inventory_error(
- "ps app inventory returned malformed output".to_string(),
- "expected one positive pid and executable path per line".to_string(),
- )
-}
-
-fn inventory_error(message: String, detail: String) -> AdapterError {
- AdapterError::new(ErrorCode::AppUnresponsive, message)
- .with_suggestion("Retry after macOS finishes updating the process inventory")
- .with_platform_detail(detail)
- .with_details(serde_json::json!({
- "kind": "inventory_source",
- "source": "ps",
- "retryable": true,
- }))
+ let Some(name) = std::str::from_utf8(command)
+ .ok()
+ .and_then(app_name_from_command)
+ else {
+ return Ok(None);
+ };
+ Ok(Some(AppInfo {
+ name,
+ pid: crate::system::process::process_identity::from_pid_t(pid)?,
+ bundle_id: None,
+ process_instance: None,
+ presentation: None,
+ }))
}
fn app_name_from_command(command: &str) -> Option<String> {
diff --git a/crates/macos/src/system/process/process_apps_tests.rs b/crates/macos/src/system/process/process_apps_tests.rs
index 2a2728bd9..d5bfb8f10 100644
--- a/crates/macos/src/system/process/process_apps_tests.rs
+++ b/crates/macos/src/system/process/process_apps_tests.rs
@@ -1,5 +1,5 @@
use super::*;
-use std::os::unix::process::ExitStatusExt;
+use agent_desktop_core::ProcessId;
#[test]
fn app_name_from_command_extracts_app_bundle_name() {
@@ -53,60 +53,69 @@ fn app_name_from_command_rejects_empty_app_name() {
);
}
-#[test]
-fn successful_empty_ps_output_is_a_real_empty_inventory() {
- let output = Output {
- status: std::process::ExitStatus::from_raw(0),
- stdout: Vec::new(),
- stderr: Vec::new(),
- };
-
- let apps = apps_from_output(output).unwrap();
-
- assert!(apps.is_empty());
+fn apps_from(commands: &[(i32, &str)]) -> Vec<AppInfo> {
+ commands
+ .iter()
+ .filter_map(|(pid, command)| app_from_command(*pid, command.as_bytes()).unwrap())
+ .collect()
}
#[test]
-fn failed_ps_output_is_not_an_empty_inventory() {
- let output = Output {
- status: std::process::ExitStatus::from_raw(256),
- stdout: Vec::new(),
- stderr: b"resource temporarily unavailable".to_vec(),
- };
+fn expired_deadline_is_rejected_before_reading_processes() {
+ let error = list_apps_until(Instant::now()).unwrap_err();
- let error = apps_from_output(output).unwrap_err();
+ assert_eq!(error.code.as_str(), "TIMEOUT");
+}
- assert_eq!(error.code, ErrorCode::AppUnresponsive);
- assert_eq!(error.details.unwrap()["source"], "ps");
+#[test]
+fn app_command_produces_an_unidentified_app_record() {
+ let app = app_from_command(42, b"/Applications/Mail.app/Contents/MacOS/Mail")
+ .unwrap()
+ .unwrap();
+
+ assert_eq!(app.name, "Mail");
+ assert_eq!(app.pid, ProcessId::new(42));
+ assert!(app.bundle_id.is_none());
+ assert!(app.process_instance.is_none());
}
#[test]
-fn expired_ps_deadline_is_rejected_before_starting_a_process() {
- let error = list_apps_until(Instant::now()).unwrap_err();
+fn non_app_processes_produce_no_records() {
+ assert!(apps_from(&[(1, "/sbin/launchd"), (2, "/usr/libexec/logd"), (3, "-zsh")]).is_empty());
+}
- assert_eq!(error.code.as_str(), "TIMEOUT");
+#[test]
+fn rewritten_commands_that_cannot_name_an_app_are_skipped() {
+ for command in [
+ "/Applications/.app/Contents/MacOS/Foo",
+ "/Applications/Foo.app/Contents/XPCServices/Bar.app/Contents/MacOS/Bar",
+ "2BUA8C4S2C.com.example.helper",
+ ] {
+ assert!(app_from_command(42, command.as_bytes()).unwrap().is_none());
+ }
}
#[test]
-fn malformed_ps_line_is_not_silently_dropped() {
- let error = parse_apps("not-a-pid /Applications/Mail.app/Contents/MacOS/Mail").unwrap_err();
+fn non_utf8_command_is_skipped_without_failing_the_inventory() {
+ let command = b"/tmp/\xffZ.app/Contents/MacOS/Z";
- assert_eq!(error.code, ErrorCode::AppUnresponsive);
+ assert!(app_from_command(42, command).unwrap().is_none());
}
#[test]
-fn valid_non_app_processes_still_produce_successful_empty_inventory() {
- let apps = parse_apps("1 /sbin/launchd\n2 /usr/libexec/logd").unwrap();
+fn non_positive_pid_is_skipped() {
+ let command = b"/Applications/Mail.app/Contents/MacOS/Mail";
- assert!(apps.is_empty());
+ assert!(app_from_command(0, command).unwrap().is_none());
+ assert!(app_from_command(-1, command).unwrap().is_none());
}
#[test]
fn inaccessible_cross_uid_process_is_skipped() {
- let apps = parse_apps(
- "42 /Applications/Visible.app/Contents/MacOS/Visible\n43 /Applications/Private.app/Contents/MacOS/Private",
- )
- .unwrap();
+ let apps = apps_from(&[
+ (42, "/Applications/Visible.app/Contents/MacOS/Visible"),
+ (43, "/Applications/Private.app/Contents/MacOS/Private"),
+ ]);
let enriched = enrich_process_instances(apps, |pid| {
if pid == 43 {
Err(
@@ -130,10 +139,10 @@ fn inaccessible_cross_uid_process_is_skipped() {
#[test]
fn process_that_exits_during_identity_enrichment_is_skipped() {
- let apps = parse_apps(
- "42 /Applications/Visible.app/Contents/MacOS/Visible\n43 /Applications/Exited.app/Contents/MacOS/Exited",
- )
- .unwrap();
+ let apps = apps_from(&[
+ (42, "/Applications/Visible.app/Contents/MacOS/Visible"),
+ (43, "/Applications/Exited.app/Contents/MacOS/Exited"),
+ ]);
let enriched = enrich_process_instances(apps, |pid| {
if pid == 43 {
Ok(None)
@@ -149,7 +158,7 @@ fn process_that_exits_during_identity_enrichment_is_skipped() {
#[test]
fn process_identity_failure_other_than_cross_uid_permission_is_not_hidden() {
- let apps = parse_apps("42 /Applications/Broken.app/Contents/MacOS/Broken").unwrap();
+ let apps = apps_from(&[(42, "/Applications/Broken.app/Contents/MacOS/Broken")]);
let error = enrich_process_instances(apps, |_| {
Err(AdapterError::new(
ErrorCode::AppUnresponsive,
diff --git a/crates/macos/src/system/process/process_arguments.rs b/crates/macos/src/system/process/process_arguments.rs
new file mode 100644
index 000000000..b1ed4b0ac
--- /dev/null
+++ b/crates/macos/src/system/process/process_arguments.rs
@@ -0,0 +1,139 @@
+//! Reads process launch commands from the kernel with libproc and `KERN_PROCARGS2`.
+
+use agent_desktop_core::{AdapterError, ErrorCode};
+use std::mem::size_of;
+use std::time::Instant;
+
+pub(crate) const PROC_ALL_PIDS: u32 = 1;
+pub(crate) const PROC_UID_ONLY: u32 = 4;
+
+/// Calls `visit` with the pid and launch command (`argv[0]`, the value `ps -o comm` prints) of
+/// every process whose arguments are readable. Processes that exit during the walk, zombies and
+/// processes of other users have no readable arguments and are skipped.
+pub(crate) fn visit_commands_until(
+ deadline: Instant,
+ mut visit: impl FnMut(libc::pid_t, &[u8]) -> Result<(), AdapterError>,
+) -> Result<(), AdapterError> {
+ let pids = require_pids(list_pids(PROC_ALL_PIDS, 0))?;
+ let mut buffer = argument_buffer().ok_or_else(|| {
+ listing_error("Could not read the kernel argument size limit".to_string())
+ })?;
+ for pid in pids {
+ if Instant::now() >= deadline {
+ return Err(AdapterError::timeout("process app inventory timed out"));
+ }
+ if let Some(command) = read_arguments(pid, &mut buffer).and_then(first_argument) {
+ visit(pid, command)?;
+ }
+ }
+ Ok(())
+}
+
+pub(crate) fn list_pids(kind: u32, info: u32) -> Option<Vec<libc::pid_t>> {
+ let size = unsafe { libc::proc_listpids(kind, info, std::ptr::null_mut(), 0) };
+ let size = usize::try_from(size).ok()?;
+ let mut pids = vec![0; size / size_of::<libc::pid_t>() + 1];
+ loop {
+ let bytes = pids.len().checked_mul(size_of::<libc::pid_t>())?;
+ let bytes = i32::try_from(bytes).ok()?;
+ let written = unsafe { libc::proc_listpids(kind, info, pids.as_mut_ptr().cast(), bytes) };
+ if written <= 0 {
+ return None;
+ }
+ if written < bytes {
+ pids.truncate(written as usize / size_of::<libc::pid_t>());
+ return Some(pids);
+ }
+ pids.resize(pids.len() * 2, 0);
+ }
+}
+
+pub(crate) fn argument_buffer() -> Option<Vec<u8>> {
+ let mut mib = [libc::CTL_KERN, libc::KERN_ARGMAX];
+ let mut max: libc::c_int = 0;
+ let mut size = size_of::<libc::c_int>();
+ let read = unsafe {
+ libc::sysctl(
+ mib.as_mut_ptr(),
+ 2,
+ (&mut max as *mut libc::c_int).cast(),
+ &mut size,
+ std::ptr::null_mut(),
+ 0,
+ )
+ };
+ if read != 0 {
+ return None;
+ }
+ usize::try_from(max)
+ .ok()
+ .filter(|max| *max > 0)
+ .map(|max| vec![0u8; max])
+}
+
+pub(crate) fn read_arguments(pid: libc::pid_t, buffer: &mut [u8]) -> Option<&[u8]> {
+ let mut mib = [libc::CTL_KERN, libc::KERN_PROCARGS2, pid];
+ let mut size = buffer.len();
+ let read = unsafe {
+ libc::sysctl(
+ mib.as_mut_ptr(),
+ 3,
+ buffer.as_mut_ptr().cast(),
+ &mut size,
+ std::ptr::null_mut(),
+ 0,
+ )
+ };
+ (read == 0 && size <= buffer.len()).then_some(&buffer[..size])
+}
+
+/// Alignment of the first argument from the start of the executable path for 64-bit processes:
+/// `exec_extract_strings` in XNU `bsd/kern/kern_exec.c` pads the path with NULs to it.
+const EXEC_PATH_ALIGNMENT: usize = 8;
+
+/// The argument count and the bytes from `argv[0]` onward of a `KERN_PROCARGS2` buffer: a
+/// native-endian argument count, the NUL-terminated executable path, NUL padding to
+/// `EXEC_PATH_ALIGNMENT`, then the arguments. The padding has a fixed length, so an empty
+/// `argv[0]` is not mistaken for more padding.
+pub(crate) fn arguments(procargs: &[u8]) -> Option<(usize, &[u8])> {
+ let (count, strings) = procargs.split_first_chunk::<4>()?;
+ let count = usize::try_from(i32::from_ne_bytes(*count))
+ .ok()
+ .filter(|count| *count > 0)?;
+ let path_end = strings.iter().position(|byte| *byte == 0)?;
+ let start = (path_end + 1).next_multiple_of(EXEC_PATH_ALIGNMENT);
+ let padding = strings.get(path_end + 1..start)?;
+ if padding.iter().any(|byte| *byte != 0) {
+ return None;
+ }
+ Some((count, &strings[start..]))
+}
+
+/// The non-empty first argument of a `KERN_PROCARGS2` buffer.
+pub(crate) fn first_argument(procargs: &[u8]) -> Option<&[u8]> {
+ let (_, arguments) = arguments(procargs)?;
+ let end = arguments.iter().position(|byte| *byte == 0)?;
+ Some(&arguments[..end]).filter(|command| !command.is_empty())
+}
+
+fn require_pids(pids: Option<Vec<libc::pid_t>>) -> Result<Vec<libc::pid_t>, AdapterError> {
+ pids.ok_or_else(|| listing_error("libproc could not list processes".to_string()))
+}
+
+fn listing_error(detail: String) -> AdapterError {
+ AdapterError::new(
+ ErrorCode::AppUnresponsive,
+ "process app inventory could not read the process list",
+ )
+ .with_suggestion("Retry after macOS finishes updating the process inventory")
+ .with_platform_detail(detail)
+ .with_details(serde_json::json!({
+ "kind": "inventory_source",
+ "source": "libproc",
+ "retryable": true,
+ }))
+}
+
+#[cfg(test)]
+#[path = "process_arguments_tests.rs"]
+mod tests;
diff --git a/crates/macos/src/system/process/process_arguments_tests.rs b/crates/macos/src/system/process/process_arguments_tests.rs
new file mode 100644
index 000000000..0f5de8da6
--- /dev/null
+++ b/crates/macos/src/system/process/process_arguments_tests.rs
@@ -0,0 +1,161 @@
+use super::*;
+use std::os::unix::ffi::OsStrExt;
+
+/// The executable path as the kernel lays it out: NUL-terminated, then NUL-padded to 8 bytes.
+fn padded_path(executable: &str) -> Vec<u8> {
+ let mut path = executable.as_bytes().to_vec();
+ path.push(0);
+ path.resize(path.len().next_multiple_of(8), 0);
+ path
+}
+
+fn procargs(executable: &str, arguments: &[&str]) -> Vec<u8> {
+ let mut buffer = (arguments.len() as i32).to_ne_bytes().to_vec();
+ buffer.extend_from_slice(&padded_path(executable));
+ for argument in arguments {
+ buffer.extend_from_slice(argument.as_bytes());
+ buffer.push(0);
+ }
+ buffer.extend_from_slice(b"HOME=/Users/a\0");
+ buffer
+}
+
+#[test]
+fn first_argument_is_the_launch_command_not_the_executable_path() {
+ let buffer = procargs(
+ "/Applications/Foo.app/Contents/MacOS/Foo",
+ &["com.example.renamed", "--flag"],
+ );
+
+ assert_eq!(first_argument(&buffer), Some(&b"com.example.renamed"[..]));
+}
+
+#[test]
+fn first_argument_keeps_spaces_in_the_command() {
+ let buffer = procargs(
+ "/Applications/Foo Bar.app/Contents/MacOS/Foo Bar",
+ &["/Applications/Foo Bar.app/Contents/MacOS/Foo Bar"],
+ );
+
+ assert_eq!(
+ first_argument(&buffer),
+ Some(&b"/Applications/Foo Bar.app/Contents/MacOS/Foo Bar"[..])
+ );
+}
+
+#[test]
+fn malformed_argument_blocks_have_no_command() {
+ assert_eq!(first_argument(&[1, 0]), None);
+ for count in [0_i32, -1] {
+ let mut buffer = procargs("/bin/zsh", &["-zsh"]);
+ buffer[..4].copy_from_slice(&count.to_ne_bytes());
+ assert_eq!(first_argument(&buffer), None);
+ }
+ let mut unterminated = 1_i32.to_ne_bytes().to_vec();
+ unterminated.extend_from_slice(&padded_path("/bin/zsh"));
+ unterminated.extend_from_slice(b"-zsh");
+ assert_eq!(first_argument(&unterminated), None);
+ let mut padding_only = 1_i32.to_ne_bytes().to_vec();
+ padding_only.extend_from_slice(b"/bin/zsh\0\0\0");
+ assert_eq!(first_argument(&padding_only), None);
+ let mut dirty_padding = procargs("/bin/zsh", &["-zsh"]);
+ dirty_padding[4 + "/bin/zsh".len() + 1] = b'x';
+ assert_eq!(first_argument(&dirty_padding), None);
+}
+
+#[test]
+fn an_empty_first_argument_is_not_read_as_the_next_one() {
+ let buffer = procargs(
+ "/bin/sleep",
+ &["", "/Applications/Fake.app/Contents/MacOS/Fake"],
+ );
+ assert_eq!(first_argument(&buffer), None);
+}
+
+#[test]
+fn a_path_that_ends_on_the_boundary_has_no_padding() {
+ let buffer = procargs("/bin/ab", &["-ab"]);
+ assert_eq!(&buffer[4..12], b"/bin/ab\0");
+ assert_eq!(first_argument(&buffer), Some(&b"-ab"[..]));
+}
+
+#[test]
+fn a_live_process_with_an_empty_first_argument_has_no_command() {
+ use std::os::unix::process::CommandExt;
+ let mut child = std::process::Command::new("/bin/sleep")
+ .arg0("")
+ .arg("30")
+ .spawn()
+ .unwrap();
+ let pid = libc::pid_t::try_from(child.id()).unwrap();
+ let mut buffer = argument_buffer().unwrap();
+ let mut read = None;
+ for _ in 0..100 {
+ read = read_arguments(pid, &mut buffer).map(<[u8]>::to_vec);
+ if read
+ .as_deref()
+ .and_then(arguments)
+ .is_some_and(|(count, _)| count == 2)
+ {
+ break;
+ }
+ std::thread::sleep(std::time::Duration::from_millis(10));
+ }
+ let _ = child.kill();
+ let _ = child.wait();
+ let read = read.unwrap();
+ assert_eq!(arguments(&read).map(|(count, _)| count), Some(2));
+ assert_eq!(first_argument(&read), None);
+}
+
+#[test]
+fn failed_process_listing_is_not_an_empty_inventory() {
+ let error = require_pids(None).unwrap_err();
+
+ assert_eq!(error.code, ErrorCode::AppUnresponsive);
+ assert!(error.is_explicitly_retryable());
+ assert_eq!(error.details.unwrap()["source"], "libproc");
+}
+
+#[test]
+fn current_process_command_matches_its_first_argument() {
+ let own_pid = std::process::id() as libc::pid_t;
+ let expected = std::env::args_os().next().unwrap();
+ let mut seen = None;
+
+ visit_commands_until(
+ Instant::now() + std::time::Duration::from_secs(5),
+ |pid, command| {
+ if pid == own_pid {
+ seen = Some(command.to_vec());
+ }
+ Ok(())
+ },
+ )
+ .unwrap();
+
+ assert_eq!(seen.as_deref(), Some(expected.as_bytes()));
+}
+
+#[test]
+fn expired_deadline_stops_the_process_walk() {
+ let mut visited = 0;
+ let error = visit_commands_until(Instant::now(), |_, _| {
+ visited += 1;
+ Ok(())
+ })
+ .unwrap_err();
+
+ assert_eq!(error.code, ErrorCode::Timeout);
+ assert_eq!(visited, 0);
+}
+
+#[test]
+fn other_users_processes_have_no_readable_arguments() {
+ if unsafe { libc::geteuid() } == 0 {
+ return;
+ }
+ let mut buffer = argument_buffer().unwrap();
+
+ assert!(read_arguments(1, &mut buffer).is_none());
+}