Skip to content

Commit e8a9d3a

Browse files
committed
Call vm_deallocate on OSX for CPU statistics
Apparently StackOverflow doesn't have all the answers. The examples there I lifted this from didn't account to call `vm_deallocate` because it looks like we're handed allocated memory! Indeed running the previous state capture in a loop it infinitely allocated memory, but now it holds steady when called in a loop.
1 parent 400221e commit e8a9d3a

File tree

1 file changed

+18
-2
lines changed

1 file changed

+18
-2
lines changed

src/cargo/util/cpu.rs

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,10 @@ mod imp {
9494

9595
type host_t = u32;
9696
type mach_port_t = u32;
97+
type vm_map_t = mach_port_t;
98+
type vm_offset_t = usize;
99+
type vm_size_t = usize;
100+
type vm_address_t = vm_offset_t;
97101
type processor_flavor_t = i32;
98102
type natural_t = u32;
99103
type processor_info_array_t = *mut i32;
@@ -107,6 +111,8 @@ mod imp {
107111
const CPU_STATE_NICE: usize = 3;
108112

109113
extern "C" {
114+
static mut mach_task_self_: mach_port_t;
115+
110116
fn mach_host_self() -> mach_port_t;
111117
fn host_processor_info(
112118
host: host_t,
@@ -115,6 +121,11 @@ mod imp {
115121
out_processor_info: *mut processor_info_array_t,
116122
out_processor_infoCnt: *mut mach_msg_type_number_t,
117123
) -> kern_return_t;
124+
fn vm_deallocate(
125+
target_task: vm_map_t,
126+
address: vm_address_t,
127+
size: vm_size_t,
128+
) -> kern_return_t;
118129
}
119130

120131
pub struct State {
@@ -139,19 +150,24 @@ mod imp {
139150
if err != 0 {
140151
return Err(io::Error::last_os_error());
141152
}
142-
let cpu_info = slice::from_raw_parts(cpu_info, cpu_info_cnt as usize);
153+
let cpu_info_slice = slice::from_raw_parts(cpu_info, cpu_info_cnt as usize);
143154
let mut ret = State {
144155
user: 0,
145156
system: 0,
146157
idle: 0,
147158
nice: 0,
148159
};
149-
for chunk in cpu_info.chunks(num_cpus_u as usize) {
160+
for chunk in cpu_info_slice.chunks(num_cpus_u as usize) {
150161
ret.user += chunk[CPU_STATE_USER] as u64;
151162
ret.system += chunk[CPU_STATE_SYSTEM] as u64;
152163
ret.idle += chunk[CPU_STATE_IDLE] as u64;
153164
ret.nice += chunk[CPU_STATE_NICE] as u64;
154165
}
166+
vm_deallocate(
167+
mach_task_self_,
168+
cpu_info as vm_address_t,
169+
cpu_info_cnt as usize,
170+
);
155171
Ok(ret)
156172
}
157173
}

0 commit comments

Comments
 (0)