1 // Copyright 2023 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "base/process/process_metrics.h"
6
7 #include <AvailabilityMacros.h>
8 #include <mach/mach.h>
9 #include <mach/mach_time.h>
10 #include <stddef.h>
11 #include <stdint.h>
12 #include <sys/sysctl.h>
13
14 #include "base/apple/mach_logging.h"
15 #include "base/apple/scoped_mach_port.h"
16 #include "base/logging.h"
17 #include "base/mac/mac_util.h"
18 #include "base/memory/ptr_util.h"
19 #include "base/numerics/safe_math.h"
20 #include "base/time/time.h"
21 #include "build/build_config.h"
22
23 #if BUILDFLAG(IS_MAC)
24 #include <libproc.h>
25 #include <mach/mach_vm.h>
26 #include <mach/shared_region.h>
27 #else
28 #include <mach/vm_region.h>
29 #if BUILDFLAG(USE_BLINK)
30 #include "base/ios/sim_header_shims.h"
31 #endif // BUILDFLAG(USE_BLINK)
32 #endif
33
34 namespace base {
35
36 #define TIME_VALUE_TO_TIMEVAL(a, r) \
37 do { \
38 (r)->tv_sec = (a)->seconds; \
39 (r)->tv_usec = (a)->microseconds; \
40 } while (0)
41
42 namespace {
43
GetTaskInfo(mach_port_t task,task_basic_info_64 * task_info_data)44 bool GetTaskInfo(mach_port_t task, task_basic_info_64* task_info_data) {
45 if (task == MACH_PORT_NULL) {
46 return false;
47 }
48 mach_msg_type_number_t count = TASK_BASIC_INFO_64_COUNT;
49 kern_return_t kr =
50 task_info(task, TASK_BASIC_INFO_64,
51 reinterpret_cast<task_info_t>(task_info_data), &count);
52 // Most likely cause for failure: |task| is a zombie.
53 return kr == KERN_SUCCESS;
54 }
55
ParseOutputFromMachVMRegion(kern_return_t kr)56 MachVMRegionResult ParseOutputFromMachVMRegion(kern_return_t kr) {
57 if (kr == KERN_INVALID_ADDRESS) {
58 // We're at the end of the address space.
59 return MachVMRegionResult::Finished;
60 } else if (kr != KERN_SUCCESS) {
61 return MachVMRegionResult::Error;
62 }
63 return MachVMRegionResult::Success;
64 }
65
GetPowerInfo(mach_port_t task,task_power_info * power_info_data)66 bool GetPowerInfo(mach_port_t task, task_power_info* power_info_data) {
67 if (task == MACH_PORT_NULL) {
68 return false;
69 }
70
71 mach_msg_type_number_t power_info_count = TASK_POWER_INFO_COUNT;
72 kern_return_t kr = task_info(task, TASK_POWER_INFO,
73 reinterpret_cast<task_info_t>(power_info_data),
74 &power_info_count);
75 // Most likely cause for failure: |task| is a zombie.
76 return kr == KERN_SUCCESS;
77 }
78
79 } // namespace
80
81 // Implementations of ProcessMetrics class shared by Mac and iOS.
TaskForPid(ProcessHandle process) const82 mach_port_t ProcessMetrics::TaskForPid(ProcessHandle process) const {
83 mach_port_t task = MACH_PORT_NULL;
84 #if BUILDFLAG(IS_MAC)
85 if (port_provider_) {
86 task = port_provider_->TaskForPid(process_);
87 }
88 #endif
89 if (task == MACH_PORT_NULL && process_ == getpid()) {
90 task = mach_task_self();
91 }
92 return task;
93 }
94
GetCumulativeCPUUsage()95 TimeDelta ProcessMetrics::GetCumulativeCPUUsage() {
96 mach_port_t task = TaskForPid(process_);
97 if (task == MACH_PORT_NULL) {
98 return TimeDelta();
99 }
100
101 // Libtop explicitly loops over the threads (libtop_pinfo_update_cpu_usage()
102 // in libtop.c), but this is more concise and gives the same results:
103 task_thread_times_info thread_info_data;
104 mach_msg_type_number_t thread_info_count = TASK_THREAD_TIMES_INFO_COUNT;
105 kern_return_t kr = task_info(task, TASK_THREAD_TIMES_INFO,
106 reinterpret_cast<task_info_t>(&thread_info_data),
107 &thread_info_count);
108 if (kr != KERN_SUCCESS) {
109 // Most likely cause: |task| is a zombie.
110 return TimeDelta();
111 }
112
113 task_basic_info_64 task_info_data;
114 if (!GetTaskInfo(task, &task_info_data)) {
115 return TimeDelta();
116 }
117
118 /* Set total_time. */
119 // thread info contains live time...
120 struct timeval user_timeval, system_timeval, task_timeval;
121 TIME_VALUE_TO_TIMEVAL(&thread_info_data.user_time, &user_timeval);
122 TIME_VALUE_TO_TIMEVAL(&thread_info_data.system_time, &system_timeval);
123 timeradd(&user_timeval, &system_timeval, &task_timeval);
124
125 // ... task info contains terminated time.
126 TIME_VALUE_TO_TIMEVAL(&task_info_data.user_time, &user_timeval);
127 TIME_VALUE_TO_TIMEVAL(&task_info_data.system_time, &system_timeval);
128 timeradd(&user_timeval, &task_timeval, &task_timeval);
129 timeradd(&system_timeval, &task_timeval, &task_timeval);
130
131 const TimeDelta measured_cpu =
132 Microseconds(TimeValToMicroseconds(task_timeval));
133 if (measured_cpu < last_measured_cpu_) {
134 // When a thread terminates, its CPU time is immediately removed from the
135 // running thread times returned by TASK_THREAD_TIMES_INFO, but there can be
136 // a lag before it shows up in the terminated thread times returned by
137 // GetTaskInfo(). Make sure CPU usage doesn't appear to go backwards if
138 // GetCumulativeCPUUsage() is called in the interval.
139 return last_measured_cpu_;
140 }
141 last_measured_cpu_ = measured_cpu;
142 return measured_cpu;
143 }
144
GetPackageIdleWakeupsPerSecond()145 int ProcessMetrics::GetPackageIdleWakeupsPerSecond() {
146 mach_port_t task = TaskForPid(process_);
147 task_power_info power_info_data;
148
149 GetPowerInfo(task, &power_info_data);
150
151 // The task_power_info struct contains two wakeup counters:
152 // task_interrupt_wakeups and task_platform_idle_wakeups.
153 // task_interrupt_wakeups is the total number of wakeups generated by the
154 // process, and is the number that Activity Monitor reports.
155 // task_platform_idle_wakeups is a subset of task_interrupt_wakeups that
156 // tallies the number of times the processor was taken out of its low-power
157 // idle state to handle a wakeup. task_platform_idle_wakeups therefore result
158 // in a greater power increase than the other interrupts which occur while the
159 // CPU is already working, and reducing them has a greater overall impact on
160 // power usage. See the powermetrics man page for more info.
161 return CalculatePackageIdleWakeupsPerSecond(
162 power_info_data.task_platform_idle_wakeups);
163 }
164
GetIdleWakeupsPerSecond()165 int ProcessMetrics::GetIdleWakeupsPerSecond() {
166 mach_port_t task = TaskForPid(process_);
167 task_power_info power_info_data;
168
169 GetPowerInfo(task, &power_info_data);
170
171 return CalculateIdleWakeupsPerSecond(power_info_data.task_interrupt_wakeups);
172 }
173
174 // Bytes committed by the system.
GetSystemCommitCharge()175 size_t GetSystemCommitCharge() {
176 base::apple::ScopedMachSendRight host(mach_host_self());
177 mach_msg_type_number_t count = HOST_VM_INFO_COUNT;
178 vm_statistics_data_t data;
179 kern_return_t kr = host_statistics(
180 host.get(), HOST_VM_INFO, reinterpret_cast<host_info_t>(&data), &count);
181 if (kr != KERN_SUCCESS) {
182 MACH_DLOG(WARNING, kr) << "host_statistics";
183 return 0;
184 }
185
186 return (data.active_count * PAGE_SIZE) / 1024;
187 }
188
GetSystemMemoryInfo(SystemMemoryInfoKB * meminfo)189 bool GetSystemMemoryInfo(SystemMemoryInfoKB* meminfo) {
190 struct host_basic_info hostinfo;
191 mach_msg_type_number_t count = HOST_BASIC_INFO_COUNT;
192 base::apple::ScopedMachSendRight host(mach_host_self());
193 int result = host_info(host.get(), HOST_BASIC_INFO,
194 reinterpret_cast<host_info_t>(&hostinfo), &count);
195 if (result != KERN_SUCCESS) {
196 return false;
197 }
198
199 DCHECK_EQ(HOST_BASIC_INFO_COUNT, count);
200 meminfo->total = static_cast<int>(hostinfo.max_mem / 1024);
201
202 vm_statistics64_data_t vm_info;
203 count = HOST_VM_INFO64_COUNT;
204
205 if (host_statistics64(host.get(), HOST_VM_INFO64,
206 reinterpret_cast<host_info64_t>(&vm_info),
207 &count) != KERN_SUCCESS) {
208 return false;
209 }
210 DCHECK_EQ(HOST_VM_INFO64_COUNT, count);
211
212 #if defined(ARCH_CPU_ARM64) || \
213 MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_16
214 // PAGE_SIZE is vm_page_size on arm or for deployment targets >= 10.16,
215 // and vm_page_size isn't constexpr.
216 DCHECK_EQ(PAGE_SIZE % 1024, 0u) << "Invalid page size";
217 #else
218 static_assert(PAGE_SIZE % 1024 == 0, "Invalid page size");
219 #endif
220
221 if (vm_info.speculative_count <= vm_info.free_count) {
222 meminfo->free = saturated_cast<int>(
223 PAGE_SIZE / 1024 * (vm_info.free_count - vm_info.speculative_count));
224 } else {
225 // Inside the `host_statistics64` call above, `speculative_count` is
226 // computed later than `free_count`, so these values are snapshots of two
227 // (slightly) different points in time. As a result, it is possible for
228 // `speculative_count` to have increased significantly since `free_count`
229 // was computed, even to a point where `speculative_count` is greater than
230 // the computed value of `free_count`. See
231 // https://github.com/apple-oss-distributions/xnu/blob/aca3beaa3dfbd42498b42c5e5ce20a938e6554e5/osfmk/kern/host.c#L788
232 // In this case, 0 is the best approximation for `meminfo->free`. This is
233 // inexact, but even in the case where `speculative_count` is less than
234 // `free_count`, the computed `meminfo->free` will only be an approximation
235 // given that the two inputs come from different points in time.
236 meminfo->free = 0;
237 }
238
239 meminfo->speculative =
240 saturated_cast<int>(PAGE_SIZE / 1024 * vm_info.speculative_count);
241 meminfo->file_backed =
242 saturated_cast<int>(PAGE_SIZE / 1024 * vm_info.external_page_count);
243 meminfo->purgeable =
244 saturated_cast<int>(PAGE_SIZE / 1024 * vm_info.purgeable_count);
245
246 return true;
247 }
248
249 // Both |size| and |address| are in-out parameters.
250 // |info| is an output parameter, only valid on Success.
GetTopInfo(mach_port_t task,mach_vm_size_t * size,mach_vm_address_t * address,vm_region_top_info_data_t * info)251 MachVMRegionResult GetTopInfo(mach_port_t task,
252 mach_vm_size_t* size,
253 mach_vm_address_t* address,
254 vm_region_top_info_data_t* info) {
255 mach_msg_type_number_t info_count = VM_REGION_TOP_INFO_COUNT;
256 // The kernel always returns a null object for VM_REGION_TOP_INFO, but
257 // balance it with a deallocate in case this ever changes. See 10.9.2
258 // xnu-2422.90.20/osfmk/vm/vm_map.c vm_map_region.
259 apple::ScopedMachSendRight object_name;
260
261 kern_return_t kr =
262 #if BUILDFLAG(IS_MAC)
263 mach_vm_region(task, address, size, VM_REGION_TOP_INFO,
264 reinterpret_cast<vm_region_info_t>(info), &info_count,
265 apple::ScopedMachSendRight::Receiver(object_name).get());
266 #else
267 vm_region_64(task, reinterpret_cast<vm_address_t*>(address),
268 reinterpret_cast<vm_size_t*>(size), VM_REGION_TOP_INFO,
269 reinterpret_cast<vm_region_info_t>(info), &info_count,
270 apple::ScopedMachSendRight::Receiver(object_name).get());
271 #endif
272 return ParseOutputFromMachVMRegion(kr);
273 }
274
GetBasicInfo(mach_port_t task,mach_vm_size_t * size,mach_vm_address_t * address,vm_region_basic_info_64 * info)275 MachVMRegionResult GetBasicInfo(mach_port_t task,
276 mach_vm_size_t* size,
277 mach_vm_address_t* address,
278 vm_region_basic_info_64* info) {
279 mach_msg_type_number_t info_count = VM_REGION_BASIC_INFO_COUNT_64;
280 // The kernel always returns a null object for VM_REGION_BASIC_INFO_64, but
281 // balance it with a deallocate in case this ever changes. See 10.9.2
282 // xnu-2422.90.20/osfmk/vm/vm_map.c vm_map_region.
283 apple::ScopedMachSendRight object_name;
284
285 kern_return_t kr =
286 #if BUILDFLAG(IS_MAC)
287 mach_vm_region(task, address, size, VM_REGION_BASIC_INFO_64,
288 reinterpret_cast<vm_region_info_t>(info), &info_count,
289 apple::ScopedMachSendRight::Receiver(object_name).get());
290
291 #else
292 vm_region_64(task, reinterpret_cast<vm_address_t*>(address),
293 reinterpret_cast<vm_size_t*>(size), VM_REGION_BASIC_INFO_64,
294 reinterpret_cast<vm_region_info_t>(info), &info_count,
295 apple::ScopedMachSendRight::Receiver(object_name).get());
296 #endif
297 return ParseOutputFromMachVMRegion(kr);
298 }
299
GetOpenFdCount() const300 int ProcessMetrics::GetOpenFdCount() const {
301 #if BUILDFLAG(USE_BLINK)
302 // In order to get a true count of the open number of FDs, PROC_PIDLISTFDS
303 // is used. This is done twice: first to get the appropriate size of a
304 // buffer, and then secondly to fill the buffer with the actual FD info.
305 //
306 // The buffer size returned in the first call is an estimate, based on the
307 // number of allocated fileproc structures in the kernel. This number can be
308 // greater than the actual number of open files, since the structures are
309 // allocated in slabs. The value returned in proc_bsdinfo::pbi_nfiles is
310 // also the number of allocated fileprocs, not the number in use.
311 //
312 // However, the buffer size returned in the second call is an accurate count
313 // of the open number of descriptors. The contents of the buffer are unused.
314 int rv = proc_pidinfo(process_, PROC_PIDLISTFDS, 0, nullptr, 0);
315 if (rv < 0) {
316 return -1;
317 }
318
319 std::unique_ptr<char[]> buffer(new char[static_cast<size_t>(rv)]);
320 rv = proc_pidinfo(process_, PROC_PIDLISTFDS, 0, buffer.get(), rv);
321 if (rv < 0) {
322 return -1;
323 }
324 return static_cast<int>(static_cast<unsigned long>(rv) / PROC_PIDLISTFD_SIZE);
325 #else
326 NOTIMPLEMENTED_LOG_ONCE();
327 return -1;
328 #endif // BUILDFLAG(USE_BLINK)
329 }
330
GetOpenFdSoftLimit() const331 int ProcessMetrics::GetOpenFdSoftLimit() const {
332 return checked_cast<int>(GetMaxFds());
333 }
334
335 } // namespace base
336