• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2013 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 <libproc.h>
9 #include <mach/mach.h>
10 #include <mach/mach_time.h>
11 #include <mach/mach_vm.h>
12 #include <mach/shared_region.h>
13 #include <stddef.h>
14 #include <stdint.h>
15 #include <sys/sysctl.h>
16 
17 #include "base/logging.h"
18 #include "base/mac/mac_util.h"
19 #include "base/mac/mach_logging.h"
20 #include "base/mac/scoped_mach_port.h"
21 #include "base/memory/ptr_util.h"
22 #include "base/numerics/safe_conversions.h"
23 #include "base/numerics/safe_math.h"
24 #include "base/process/process_metrics_iocounters.h"
25 #include "base/time/time.h"
26 #include "build/build_config.h"
27 
28 namespace {
29 
30 // This is a standin for the private pm_task_energy_data_t struct.
31 struct OpaquePMTaskEnergyData {
32   // Empirical size of the private struct.
33   uint8_t data[408];
34 };
35 
36 // Sample everything but network usage, since fetching network
37 // usage can hang.
38 static constexpr uint8_t kPMSampleFlags = 0xff & ~0x8;
39 
40 }  // namespace
41 
42 extern "C" {
43 
44 // From libpmsample.dylib
45 int pm_sample_task(mach_port_t task,
46                    OpaquePMTaskEnergyData* pm_energy,
47                    uint64_t mach_time,
48                    uint8_t flags);
49 
50 // From libpmenergy.dylib
51 double pm_energy_impact(OpaquePMTaskEnergyData* pm_energy);
52 
53 }  // extern "C"
54 
55 namespace base {
56 
57 namespace {
58 
GetTaskInfo(mach_port_t task,task_basic_info_64 * task_info_data)59 bool GetTaskInfo(mach_port_t task, task_basic_info_64* task_info_data) {
60   if (task == MACH_PORT_NULL)
61     return false;
62   mach_msg_type_number_t count = TASK_BASIC_INFO_64_COUNT;
63   kern_return_t kr = task_info(task,
64                                TASK_BASIC_INFO_64,
65                                reinterpret_cast<task_info_t>(task_info_data),
66                                &count);
67   // Most likely cause for failure: |task| is a zombie.
68   return kr == KERN_SUCCESS;
69 }
70 
ParseOutputFromMachVMRegion(kern_return_t kr)71 MachVMRegionResult ParseOutputFromMachVMRegion(kern_return_t kr) {
72   if (kr == KERN_INVALID_ADDRESS) {
73     // We're at the end of the address space.
74     return MachVMRegionResult::Finished;
75   } else if (kr != KERN_SUCCESS) {
76     return MachVMRegionResult::Error;
77   }
78   return MachVMRegionResult::Success;
79 }
80 
GetPowerInfo(mach_port_t task,task_power_info * power_info_data)81 bool GetPowerInfo(mach_port_t task, task_power_info* power_info_data) {
82   if (task == MACH_PORT_NULL)
83     return false;
84 
85   mach_msg_type_number_t power_info_count = TASK_POWER_INFO_COUNT;
86   kern_return_t kr = task_info(task, TASK_POWER_INFO,
87                                reinterpret_cast<task_info_t>(power_info_data),
88                                &power_info_count);
89   // Most likely cause for failure: |task| is a zombie.
90   return kr == KERN_SUCCESS;
91 }
92 
GetEnergyImpactInternal(mach_port_t task,uint64_t mach_time)93 double GetEnergyImpactInternal(mach_port_t task, uint64_t mach_time) {
94   OpaquePMTaskEnergyData energy_info{};
95 
96   if (pm_sample_task(task, &energy_info, mach_time, kPMSampleFlags) != 0)
97     return 0.0;
98   return pm_energy_impact(&energy_info);
99 }
100 
101 }  // namespace
102 
103 // Getting a mach task from a pid for another process requires permissions in
104 // general, so there doesn't really seem to be a way to do these (and spinning
105 // up ps to fetch each stats seems dangerous to put in a base api for anyone to
106 // call). Child processes ipc their port, so return something if available,
107 // otherwise return 0.
108 
109 // static
CreateProcessMetrics(ProcessHandle process,PortProvider * port_provider)110 std::unique_ptr<ProcessMetrics> ProcessMetrics::CreateProcessMetrics(
111     ProcessHandle process,
112     PortProvider* port_provider) {
113   return WrapUnique(new ProcessMetrics(process, port_provider));
114 }
115 
116 #define TIME_VALUE_TO_TIMEVAL(a, r) do {  \
117   (r)->tv_sec = (a)->seconds;             \
118   (r)->tv_usec = (a)->microseconds;       \
119 } while (0)
120 
GetCumulativeCPUUsage()121 TimeDelta ProcessMetrics::GetCumulativeCPUUsage() {
122   mach_port_t task = TaskForPid(process_);
123   if (task == MACH_PORT_NULL)
124     return TimeDelta();
125 
126   // Libtop explicitly loops over the threads (libtop_pinfo_update_cpu_usage()
127   // in libtop.c), but this is more concise and gives the same results:
128   task_thread_times_info thread_info_data;
129   mach_msg_type_number_t thread_info_count = TASK_THREAD_TIMES_INFO_COUNT;
130   kern_return_t kr = task_info(task,
131                                TASK_THREAD_TIMES_INFO,
132                                reinterpret_cast<task_info_t>(&thread_info_data),
133                                &thread_info_count);
134   if (kr != KERN_SUCCESS) {
135     // Most likely cause: |task| is a zombie.
136     return TimeDelta();
137   }
138 
139   task_basic_info_64 task_info_data;
140   if (!GetTaskInfo(task, &task_info_data))
141     return TimeDelta();
142 
143   /* Set total_time. */
144   // thread info contains live time...
145   struct timeval user_timeval, system_timeval, task_timeval;
146   TIME_VALUE_TO_TIMEVAL(&thread_info_data.user_time, &user_timeval);
147   TIME_VALUE_TO_TIMEVAL(&thread_info_data.system_time, &system_timeval);
148   timeradd(&user_timeval, &system_timeval, &task_timeval);
149 
150   // ... task info contains terminated time.
151   TIME_VALUE_TO_TIMEVAL(&task_info_data.user_time, &user_timeval);
152   TIME_VALUE_TO_TIMEVAL(&task_info_data.system_time, &system_timeval);
153   timeradd(&user_timeval, &task_timeval, &task_timeval);
154   timeradd(&system_timeval, &task_timeval, &task_timeval);
155 
156   return Microseconds(TimeValToMicroseconds(task_timeval));
157 }
158 
GetPackageIdleWakeupsPerSecond()159 int ProcessMetrics::GetPackageIdleWakeupsPerSecond() {
160   mach_port_t task = TaskForPid(process_);
161   task_power_info power_info_data;
162 
163   GetPowerInfo(task, &power_info_data);
164 
165   // The task_power_info struct contains two wakeup counters:
166   // task_interrupt_wakeups and task_platform_idle_wakeups.
167   // task_interrupt_wakeups is the total number of wakeups generated by the
168   // process, and is the number that Activity Monitor reports.
169   // task_platform_idle_wakeups is a subset of task_interrupt_wakeups that
170   // tallies the number of times the processor was taken out of its low-power
171   // idle state to handle a wakeup. task_platform_idle_wakeups therefore result
172   // in a greater power increase than the other interrupts which occur while the
173   // CPU is already working, and reducing them has a greater overall impact on
174   // power usage. See the powermetrics man page for more info.
175   return CalculatePackageIdleWakeupsPerSecond(
176       power_info_data.task_platform_idle_wakeups);
177 }
178 
GetIdleWakeupsPerSecond()179 int ProcessMetrics::GetIdleWakeupsPerSecond() {
180   mach_port_t task = TaskForPid(process_);
181   task_power_info power_info_data;
182 
183   GetPowerInfo(task, &power_info_data);
184 
185   return CalculateIdleWakeupsPerSecond(power_info_data.task_interrupt_wakeups);
186 }
187 
GetEnergyImpact()188 int ProcessMetrics::GetEnergyImpact() {
189   uint64_t now = mach_absolute_time();
190   if (last_energy_impact_ == 0) {
191     last_energy_impact_ = GetEnergyImpactInternal(TaskForPid(process_), now);
192     last_energy_impact_time_ = now;
193     return 0;
194   }
195 
196   double total_energy_impact =
197       GetEnergyImpactInternal(TaskForPid(process_), now);
198   uint64_t delta = now - last_energy_impact_time_;
199   if (delta == 0)
200     return 0;
201 
202   // Scale by 100 since the histogram is integral.
203   double seconds_since_last_measurement =
204       base::TimeTicks::FromMachAbsoluteTime(delta).since_origin().InSecondsF();
205   int energy_impact = 100 * (total_energy_impact - last_energy_impact_) /
206                       seconds_since_last_measurement;
207   last_energy_impact_ = total_energy_impact;
208   last_energy_impact_time_ = now;
209 
210   return energy_impact;
211 }
212 
GetOpenFdCount() const213 int ProcessMetrics::GetOpenFdCount() const {
214   // In order to get a true count of the open number of FDs, PROC_PIDLISTFDS
215   // is used. This is done twice: first to get the appropriate size of a
216   // buffer, and then secondly to fill the buffer with the actual FD info.
217   //
218   // The buffer size returned in the first call is an estimate, based on the
219   // number of allocated fileproc structures in the kernel. This number can be
220   // greater than the actual number of open files, since the structures are
221   // allocated in slabs. The value returned in proc_bsdinfo::pbi_nfiles is
222   // also the number of allocated fileprocs, not the number in use.
223   //
224   // However, the buffer size returned in the second call is an accurate count
225   // of the open number of descriptors. The contents of the buffer are unused.
226   int rv = proc_pidinfo(process_, PROC_PIDLISTFDS, 0, nullptr, 0);
227   if (rv < 0)
228     return -1;
229 
230   std::unique_ptr<char[]> buffer(new char[static_cast<size_t>(rv)]);
231   rv = proc_pidinfo(process_, PROC_PIDLISTFDS, 0, buffer.get(), rv);
232   if (rv < 0)
233     return -1;
234   return static_cast<int>(static_cast<unsigned long>(rv) / PROC_PIDLISTFD_SIZE);
235 }
236 
GetOpenFdSoftLimit() const237 int ProcessMetrics::GetOpenFdSoftLimit() const {
238   return checked_cast<int>(GetMaxFds());
239 }
240 
GetIOCounters(IoCounters * io_counters) const241 bool ProcessMetrics::GetIOCounters(IoCounters* io_counters) const {
242   return false;
243 }
244 
ProcessMetrics(ProcessHandle process,PortProvider * port_provider)245 ProcessMetrics::ProcessMetrics(ProcessHandle process,
246                                PortProvider* port_provider)
247     : process_(process),
248       last_absolute_idle_wakeups_(0),
249       last_absolute_package_idle_wakeups_(0),
250       last_energy_impact_(0),
251       port_provider_(port_provider) {}
252 
TaskForPid(ProcessHandle process) const253 mach_port_t ProcessMetrics::TaskForPid(ProcessHandle process) const {
254   mach_port_t task = MACH_PORT_NULL;
255   if (port_provider_)
256     task = port_provider_->TaskForPid(process_);
257   if (task == MACH_PORT_NULL && process_ == getpid())
258     task = mach_task_self();
259   return task;
260 }
261 
262 // Bytes committed by the system.
GetSystemCommitCharge()263 size_t GetSystemCommitCharge() {
264   base::mac::ScopedMachSendRight host(mach_host_self());
265   mach_msg_type_number_t count = HOST_VM_INFO_COUNT;
266   vm_statistics_data_t data;
267   kern_return_t kr = host_statistics(host.get(), HOST_VM_INFO,
268                                      reinterpret_cast<host_info_t>(&data),
269                                      &count);
270   if (kr != KERN_SUCCESS) {
271     MACH_DLOG(WARNING, kr) << "host_statistics";
272     return 0;
273   }
274 
275   return (data.active_count * PAGE_SIZE) / 1024;
276 }
277 
GetSystemMemoryInfo(SystemMemoryInfoKB * meminfo)278 bool GetSystemMemoryInfo(SystemMemoryInfoKB* meminfo) {
279   struct host_basic_info hostinfo;
280   mach_msg_type_number_t count = HOST_BASIC_INFO_COUNT;
281   base::mac::ScopedMachSendRight host(mach_host_self());
282   int result = host_info(host.get(), HOST_BASIC_INFO,
283                          reinterpret_cast<host_info_t>(&hostinfo), &count);
284   if (result != KERN_SUCCESS)
285     return false;
286 
287   DCHECK_EQ(HOST_BASIC_INFO_COUNT, count);
288   meminfo->total = static_cast<int>(hostinfo.max_mem / 1024);
289 
290   vm_statistics64_data_t vm_info;
291   count = HOST_VM_INFO64_COUNT;
292 
293   if (host_statistics64(host.get(), HOST_VM_INFO64,
294                         reinterpret_cast<host_info64_t>(&vm_info),
295                         &count) != KERN_SUCCESS) {
296     return false;
297   }
298   DCHECK_EQ(HOST_VM_INFO64_COUNT, count);
299 
300 #if defined(ARCH_CPU_ARM64) || \
301     MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_16
302   // PAGE_SIZE is vm_page_size on arm or for deployment targets >= 10.16,
303   // and vm_page_size isn't constexpr.
304   DCHECK_EQ(PAGE_SIZE % 1024, 0u) << "Invalid page size";
305 #else
306   static_assert(PAGE_SIZE % 1024 == 0, "Invalid page size");
307 #endif
308   meminfo->free = saturated_cast<int>(
309       PAGE_SIZE / 1024 * (vm_info.free_count - vm_info.speculative_count));
310   meminfo->speculative =
311       saturated_cast<int>(PAGE_SIZE / 1024 * vm_info.speculative_count);
312   meminfo->file_backed =
313       saturated_cast<int>(PAGE_SIZE / 1024 * vm_info.external_page_count);
314   meminfo->purgeable =
315       saturated_cast<int>(PAGE_SIZE / 1024 * vm_info.purgeable_count);
316 
317   return true;
318 }
319 
320 // Both |size| and |address| are in-out parameters.
321 // |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)322 MachVMRegionResult GetTopInfo(mach_port_t task,
323                               mach_vm_size_t* size,
324                               mach_vm_address_t* address,
325                               vm_region_top_info_data_t* info) {
326   mach_msg_type_number_t info_count = VM_REGION_TOP_INFO_COUNT;
327   // The kernel always returns a null object for VM_REGION_TOP_INFO, but
328   // balance it with a deallocate in case this ever changes. See 10.9.2
329   // xnu-2422.90.20/osfmk/vm/vm_map.c vm_map_region.
330   mac::ScopedMachSendRight object_name;
331   kern_return_t kr =
332       mach_vm_region(task, address, size, VM_REGION_TOP_INFO,
333                      reinterpret_cast<vm_region_info_t>(info), &info_count,
334                      mac::ScopedMachSendRight::Receiver(object_name).get());
335   return ParseOutputFromMachVMRegion(kr);
336 }
337 
GetBasicInfo(mach_port_t task,mach_vm_size_t * size,mach_vm_address_t * address,vm_region_basic_info_64 * info)338 MachVMRegionResult GetBasicInfo(mach_port_t task,
339                                 mach_vm_size_t* size,
340                                 mach_vm_address_t* address,
341                                 vm_region_basic_info_64* info) {
342   mach_msg_type_number_t info_count = VM_REGION_BASIC_INFO_COUNT_64;
343   // The kernel always returns a null object for VM_REGION_BASIC_INFO_64, but
344   // balance it with a deallocate in case this ever changes. See 10.9.2
345   // xnu-2422.90.20/osfmk/vm/vm_map.c vm_map_region.
346   mac::ScopedMachSendRight object_name;
347   kern_return_t kr =
348       mach_vm_region(task, address, size, VM_REGION_BASIC_INFO_64,
349                      reinterpret_cast<vm_region_info_t>(info), &info_count,
350                      mac::ScopedMachSendRight::Receiver(object_name).get());
351   return ParseOutputFromMachVMRegion(kr);
352 }
353 
354 }  // namespace base
355