Skip to content

Commit 5b2b917

Browse files
author
Artyom Khramov
committed
Fix listpids function
There are two problems in `lispids` function realization, both related to buffer expansion via [Vec#set_len](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.set_len). * Sometimes `proc_listpids` returns more than `MAXPIDS` (1024) processes. In this case we could expand the pids vector to the memory we do not own. * We used the `Vec#set_len` method with buffer size, whereas it accepts _items count_. That's why there could be trailing zeros in the result (see https://github.com/andrewdavidmackenzie/libproc-rs/pull/3/files/e7d2319eb6369e7cd5c7c983caa643441206f104#r94556438). This change * Sets `MAXPIDS` variable to the actual kernel-defined maximum number of PIDs * Renames `MAXPIDS` constant to `PID_MAX` to reflect kernel's naming. * Corrects listpid's `Vec#set_len` invocation to receive items count instead of buffer size. * Removes redundant "unpadding" behavior.
1 parent 903a7f8 commit 5b2b917

File tree

1 file changed

+7
-6
lines changed

1 file changed

+7
-6
lines changed

src/libproc/proc_pid.rs

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,9 @@ use std::mem;
2020
const MAXPATHLEN: usize = 1024;
2121
const PROC_PIDPATHINFO_MAXSIZE: usize = 4 * MAXPATHLEN;
2222

23-
// This constant is the maximum number of PIDs we will fetch and return from listpids - arbitrary choice
24-
const MAXPIDS: usize = 1024;
23+
// This constant is the maximum number of PIDs we will fetch and return from listpids
24+
// from https://opensource.apple.com/source/xnu/xnu-1699.24.23/bsd/sys/proc_internal.h
25+
const PID_MAX: usize = 99999;
2526

2627
// from http://opensource.apple.com//source/xnu/xnu-1456.1.26/bsd/sys/proc_info.h
2728
const MAXTHREADNAMESIZE : usize = 64;
@@ -228,7 +229,7 @@ pub fn get_errno_with_message(ret: i32) -> String {
228229
/// }
229230
/// ```
230231
pub fn listpids(proc_types: ProcType) -> Result<Vec<u32>, String> {
231-
let mut pids: Vec<u32> = Vec::with_capacity(MAXPIDS);
232+
let mut pids: Vec<u32> = Vec::with_capacity(PID_MAX);
232233
let buffer_ptr = pids.as_mut_ptr() as *mut c_void;
233234
let buffer_size = (pids.capacity() * 4) as u32;
234235
let ret: i32;
@@ -237,14 +238,14 @@ pub fn listpids(proc_types: ProcType) -> Result<Vec<u32>, String> {
237238
ret = proc_listpids(proc_types as u32, 0, buffer_ptr, buffer_size);
238239
}
239240

241+
let items_count = ret as usize / mem::size_of::<u32>() - 1;
242+
240243
if ret <= 0 {
241244
Err(get_errno_with_message(ret))
242245
} else {
243246
unsafe {
244-
pids.set_len(ret as usize);
247+
pids.set_len(items_count);
245248
}
246-
// Seems that the buffer is padded with a lot of pids set to zero
247-
pids.retain(|&p| p > 0);
248249

249250
Ok(pids)
250251
}

0 commit comments

Comments
 (0)