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