Debian Codegraph @

debian/rust-vendor/num_threads/src/apple.rs

raw
1 extern crate libc;
2
3 use std::num::NonZeroUsize;
4
5 use self::libc::{
6 kern_return_t, mach_port_t, natural_t, task_threads, thread_act_array_t, vm_size_t,
7 };
8
9 #[allow(non_camel_case_types)]
10 // https://developer.apple.com/documentation/kernel/mach_port_name_t
11 type mach_port_name_t = natural_t;
12
13 extern "C" {
14 // https://developer.apple.com/documentation/kernel/1402285-mach_vm_deallocate
15 fn mach_vm_deallocate(
16 target_task: mach_port_t,
17 address: *mut u32,
18 size: vm_size_t,
19 ) -> kern_return_t;
20
21 // https://developer.apple.com/documentation/kernel/1578777-mach_port_deallocate
22 fn mach_port_deallocate(task: mach_port_t, name: mach_port_name_t) -> kern_return_t;
23 }
24
25 pub(crate) fn num_threads() -> Option<NonZeroUsize> {
26 // https://developer.apple.com/documentation/kernel/1537751-task_threads
27 let mut thread_list: thread_act_array_t = std::ptr::null_mut();
28 let mut thread_count = 0;
29
30 // Safety:
31 // - `mach_task_self` always returns a valid value,
32 // - `thread_list` is a pointer that will point to kernel allocated memory that needs to be
33 // deallocated if the call succeeds
34 let task = unsafe { libc::mach_task_self() };
35 let result = unsafe { task_threads(task, &mut thread_list, &mut thread_count) };
36
37 if result == libc::KERN_SUCCESS {
38 // Deallocate the mach port rights for the threads
39 for thread in 0..thread_count {
40 unsafe {
41 mach_port_deallocate(task, *(thread_list.offset(thread as isize)) as u32);
42 }
43 }
44 // Deallocate the thread list
45 unsafe {
46 mach_vm_deallocate(
47 task,
48 thread_list,
49 std::mem::size_of::<mach_port_t>() * thread_count as usize,
50 );
51 }
52
53 NonZeroUsize::new(thread_count as usize)
54 } else {
55 None
56 }
57 }