Skip to content

Commit 0cd2b02

Browse files
authored
macOS: Avoid heap allocation (#5)
This also avoids leaking memory in the event of the syscall failing for some reason.
1 parent b166317 commit 0cd2b02

File tree

1 file changed

+6
-13
lines changed

1 file changed

+6
-13
lines changed

src/macos.rs

+6-13
Original file line numberDiff line numberDiff line change
@@ -6,28 +6,21 @@ use std::num::NonZeroUsize;
66
const PROC_TASKINFO_SIZE: usize = mem::size_of::<libc::proc_taskinfo>();
77

88
pub(crate) fn num_threads() -> Option<NonZeroUsize> {
9-
let buffer = unsafe { libc::malloc(PROC_TASKINFO_SIZE) };
10-
if buffer.is_null() {
11-
return None;
12-
}
9+
let mut pti: libc::proc_taskinfo = unsafe { mem::zeroed() };
1310

1411
let result = unsafe {
1512
libc::proc_pidinfo(
1613
libc::getpid(),
1714
libc::PROC_PIDTASKINFO,
1815
0,
19-
buffer,
16+
&mut pti as *mut libc::proc_taskinfo as *mut libc::c_void,
2017
PROC_TASKINFO_SIZE as libc::c_int,
2118
)
2219
};
23-
if result != PROC_TASKINFO_SIZE as libc::c_int {
24-
return None;
25-
}
2620

27-
let pti = buffer as *mut libc::proc_taskinfo;
28-
// Safety: `malloc`ed memory is aligned for repr(C) structs, so dereference is safe.
29-
let num_threads = NonZeroUsize::new(unsafe { pti.as_ref() }?.pti_threadnum as usize);
21+
if result == PROC_TASKINFO_SIZE as libc::c_int {
22+
return NonZeroUsize::new(pti.pti_threadnum as usize);
23+
}
3024

31-
unsafe { libc::free(pti as *mut libc::c_void) };
32-
num_threads
25+
None
3326
}

0 commit comments

Comments
 (0)