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