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.
5 #include "base/process/process_metrics.h"
8 #include <mach/mach_vm.h>
9 #include <mach/shared_region.h>
10 #include <sys/sysctl.h>
12 #include "base/containers/hash_tables.h"
13 #include "base/logging.h"
14 #include "base/mac/mach_logging.h"
15 #include "base/mac/scoped_mach_port.h"
16 #include "base/sys_info.h"
18 #if !defined(TASK_POWER_INFO)
19 // Doesn't exist in the 10.6 or 10.7 SDKs.
20 #define TASK_POWER_INFO 21
21 struct task_power_info
{
23 uint64_t total_system
;
24 uint64_t task_interrupt_wakeups
;
25 uint64_t task_platform_idle_wakeups
;
26 uint64_t task_timer_wakeups_bin_1
;
27 uint64_t task_timer_wakeups_bin_2
;
29 typedef struct task_power_info task_power_info_data_t
;
30 typedef struct task_power_info
*task_power_info_t
;
31 #define TASK_POWER_INFO_COUNT ((mach_msg_type_number_t) \
32 (sizeof (task_power_info_data_t) / sizeof (natural_t)))
39 bool GetTaskInfo(mach_port_t task
, task_basic_info_64
* task_info_data
) {
40 if (task
== MACH_PORT_NULL
)
42 mach_msg_type_number_t count
= TASK_BASIC_INFO_64_COUNT
;
43 kern_return_t kr
= task_info(task
,
45 reinterpret_cast<task_info_t
>(task_info_data
),
47 // Most likely cause for failure: |task| is a zombie.
48 return kr
== KERN_SUCCESS
;
51 bool GetCPUTypeForProcess(pid_t pid
, cpu_type_t
* cpu_type
) {
52 size_t len
= sizeof(*cpu_type
);
53 int result
= sysctlbyname("sysctl.proc_cputype",
59 DPLOG(ERROR
) << "sysctlbyname(""sysctl.proc_cputype"")";
66 bool IsAddressInSharedRegion(mach_vm_address_t addr
, cpu_type_t type
) {
67 if (type
== CPU_TYPE_I386
) {
68 return addr
>= SHARED_REGION_BASE_I386
&&
69 addr
< (SHARED_REGION_BASE_I386
+ SHARED_REGION_SIZE_I386
);
70 } else if (type
== CPU_TYPE_X86_64
) {
71 return addr
>= SHARED_REGION_BASE_X86_64
&&
72 addr
< (SHARED_REGION_BASE_X86_64
+ SHARED_REGION_SIZE_X86_64
);
80 SystemMemoryInfoKB::SystemMemoryInfoKB() {
85 // Getting a mach task from a pid for another process requires permissions in
86 // general, so there doesn't really seem to be a way to do these (and spinning
87 // up ps to fetch each stats seems dangerous to put in a base api for anyone to
88 // call). Child processes ipc their port, so return something if available,
89 // otherwise return 0.
92 ProcessMetrics
* ProcessMetrics::CreateProcessMetrics(
93 ProcessHandle process
,
94 ProcessMetrics::PortProvider
* port_provider
) {
95 return new ProcessMetrics(process
, port_provider
);
98 size_t ProcessMetrics::GetPagefileUsage() const {
99 task_basic_info_64 task_info_data
;
100 if (!GetTaskInfo(TaskForPid(process_
), &task_info_data
))
102 return task_info_data
.virtual_size
;
105 size_t ProcessMetrics::GetPeakPagefileUsage() const {
109 size_t ProcessMetrics::GetWorkingSetSize() const {
110 task_basic_info_64 task_info_data
;
111 if (!GetTaskInfo(TaskForPid(process_
), &task_info_data
))
113 return task_info_data
.resident_size
;
116 size_t ProcessMetrics::GetPeakWorkingSetSize() const {
120 // This is a rough approximation of the algorithm that libtop uses.
121 // private_bytes is the size of private resident memory.
122 // shared_bytes is the size of shared resident memory.
123 bool ProcessMetrics::GetMemoryBytes(size_t* private_bytes
,
124 size_t* shared_bytes
) {
125 size_t private_pages_count
= 0;
126 size_t shared_pages_count
= 0;
128 if (!private_bytes
&& !shared_bytes
)
131 mach_port_t task
= TaskForPid(process_
);
132 if (task
== MACH_PORT_NULL
) {
133 DLOG(ERROR
) << "Invalid process";
138 if (!GetCPUTypeForProcess(process_
, &cpu_type
))
141 // The same region can be referenced multiple times. To avoid double counting
142 // we need to keep track of which regions we've already counted.
143 base::hash_set
<int> seen_objects
;
145 // We iterate through each VM region in the task's address map. For shared
146 // memory we add up all the pages that are marked as shared. Like libtop we
147 // try to avoid counting pages that are also referenced by other tasks. Since
148 // we don't have access to the VM regions of other tasks the only hint we have
149 // is if the address is in the shared region area.
151 // Private memory is much simpler. We simply count the pages that are marked
152 // as private or copy on write (COW).
154 // See libtop_update_vm_regions in
155 // http://www.opensource.apple.com/source/top/top-67/libtop.c
156 mach_vm_size_t size
= 0;
157 for (mach_vm_address_t address
= MACH_VM_MIN_ADDRESS
;; address
+= size
) {
158 vm_region_top_info_data_t info
;
159 mach_msg_type_number_t info_count
= VM_REGION_TOP_INFO_COUNT
;
160 mach_port_t object_name
;
161 kern_return_t kr
= mach_vm_region(task
,
165 reinterpret_cast<vm_region_info_t
>(&info
),
168 if (kr
== KERN_INVALID_ADDRESS
) {
169 // We're at the end of the address space.
171 } else if (kr
!= KERN_SUCCESS
) {
172 MACH_DLOG(ERROR
, kr
) << "mach_vm_region";
176 // The kernel always returns a null object for VM_REGION_TOP_INFO, but
177 // balance it with a deallocate in case this ever changes. See 10.9.2
178 // xnu-2422.90.20/osfmk/vm/vm_map.c vm_map_region.
179 mach_port_deallocate(mach_task_self(), object_name
);
181 if (IsAddressInSharedRegion(address
, cpu_type
) &&
182 info
.share_mode
!= SM_PRIVATE
)
185 if (info
.share_mode
== SM_COW
&& info
.ref_count
== 1)
186 info
.share_mode
= SM_PRIVATE
;
188 switch (info
.share_mode
) {
190 private_pages_count
+= info
.private_pages_resident
;
191 private_pages_count
+= info
.shared_pages_resident
;
194 private_pages_count
+= info
.private_pages_resident
;
197 if (seen_objects
.count(info
.obj_id
) == 0) {
198 // Only count the first reference to this region.
199 seen_objects
.insert(info
.obj_id
);
200 shared_pages_count
+= info
.shared_pages_resident
;
209 *private_bytes
= private_pages_count
* PAGE_SIZE
;
211 *shared_bytes
= shared_pages_count
* PAGE_SIZE
;
216 void ProcessMetrics::GetCommittedKBytes(CommittedKBytes
* usage
) const {
217 WorkingSetKBytes unused
;
218 if (!GetCommittedAndWorkingSetKBytes(usage
, &unused
)) {
219 *usage
= CommittedKBytes();
223 bool ProcessMetrics::GetWorkingSetKBytes(WorkingSetKBytes
* ws_usage
) const {
224 CommittedKBytes unused
;
225 return GetCommittedAndWorkingSetKBytes(&unused
, ws_usage
);
228 bool ProcessMetrics::GetCommittedAndWorkingSetKBytes(
229 CommittedKBytes
* usage
,
230 WorkingSetKBytes
* ws_usage
) const {
231 task_basic_info_64 task_info_data
;
232 if (!GetTaskInfo(TaskForPid(process_
), &task_info_data
))
235 usage
->priv
= task_info_data
.virtual_size
/ 1024;
239 ws_usage
->priv
= task_info_data
.resident_size
/ 1024;
240 ws_usage
->shareable
= 0;
241 ws_usage
->shared
= 0;
246 #define TIME_VALUE_TO_TIMEVAL(a, r) do { \
247 (r)->tv_sec = (a)->seconds; \
248 (r)->tv_usec = (a)->microseconds; \
251 double ProcessMetrics::GetCPUUsage() {
252 mach_port_t task
= TaskForPid(process_
);
253 if (task
== MACH_PORT_NULL
)
256 // Libtop explicitly loops over the threads (libtop_pinfo_update_cpu_usage()
257 // in libtop.c), but this is more concise and gives the same results:
258 task_thread_times_info thread_info_data
;
259 mach_msg_type_number_t thread_info_count
= TASK_THREAD_TIMES_INFO_COUNT
;
260 kern_return_t kr
= task_info(task
,
261 TASK_THREAD_TIMES_INFO
,
262 reinterpret_cast<task_info_t
>(&thread_info_data
),
264 if (kr
!= KERN_SUCCESS
) {
265 // Most likely cause: |task| is a zombie.
269 task_basic_info_64 task_info_data
;
270 if (!GetTaskInfo(task
, &task_info_data
))
273 /* Set total_time. */
274 // thread info contains live time...
275 struct timeval user_timeval
, system_timeval
, task_timeval
;
276 TIME_VALUE_TO_TIMEVAL(&thread_info_data
.user_time
, &user_timeval
);
277 TIME_VALUE_TO_TIMEVAL(&thread_info_data
.system_time
, &system_timeval
);
278 timeradd(&user_timeval
, &system_timeval
, &task_timeval
);
280 // ... task info contains terminated time.
281 TIME_VALUE_TO_TIMEVAL(&task_info_data
.user_time
, &user_timeval
);
282 TIME_VALUE_TO_TIMEVAL(&task_info_data
.system_time
, &system_timeval
);
283 timeradd(&user_timeval
, &task_timeval
, &task_timeval
);
284 timeradd(&system_timeval
, &task_timeval
, &task_timeval
);
286 TimeTicks time
= TimeTicks::Now();
287 int64 task_time
= TimeValToMicroseconds(task_timeval
);
289 if (last_system_time_
== 0) {
290 // First call, just set the last values.
291 last_cpu_time_
= time
;
292 last_system_time_
= task_time
;
296 int64 system_time_delta
= task_time
- last_system_time_
;
297 int64 time_delta
= (time
- last_cpu_time_
).InMicroseconds();
298 DCHECK_NE(0U, time_delta
);
302 last_cpu_time_
= time
;
303 last_system_time_
= task_time
;
305 return static_cast<double>(system_time_delta
* 100.0) / time_delta
;
308 int ProcessMetrics::GetIdleWakeupsPerSecond() {
309 mach_port_t task
= TaskForPid(process_
);
310 if (task
== MACH_PORT_NULL
)
313 task_power_info power_info_data
;
314 mach_msg_type_number_t power_info_count
= TASK_POWER_INFO_COUNT
;
315 kern_return_t kr
= task_info(task
,
317 reinterpret_cast<task_info_t
>(&power_info_data
),
319 if (kr
!= KERN_SUCCESS
) {
320 // Most likely cause: |task| is a zombie, or this is on a pre-10.8.4 system
321 // where TASK_POWER_INFO isn't supported yet.
324 return CalculateIdleWakeupsPerSecond(
325 power_info_data
.task_platform_idle_wakeups
);
328 bool ProcessMetrics::GetIOCounters(IoCounters
* io_counters
) const {
332 ProcessMetrics::ProcessMetrics(ProcessHandle process
,
333 ProcessMetrics::PortProvider
* port_provider
)
335 last_system_time_(0),
336 last_absolute_idle_wakeups_(0),
337 port_provider_(port_provider
) {
338 processor_count_
= SysInfo::NumberOfProcessors();
341 mach_port_t
ProcessMetrics::TaskForPid(ProcessHandle process
) const {
342 mach_port_t task
= MACH_PORT_NULL
;
344 task
= port_provider_
->TaskForPid(process_
);
345 if (task
== MACH_PORT_NULL
&& process_
== getpid())
346 task
= mach_task_self();
350 // Bytes committed by the system.
351 size_t GetSystemCommitCharge() {
352 base::mac::ScopedMachSendRight
host(mach_host_self());
353 mach_msg_type_number_t count
= HOST_VM_INFO_COUNT
;
354 vm_statistics_data_t data
;
355 kern_return_t kr
= host_statistics(host
, HOST_VM_INFO
,
356 reinterpret_cast<host_info_t
>(&data
),
358 if (kr
!= KERN_SUCCESS
) {
359 MACH_DLOG(WARNING
, kr
) << "host_statistics";
363 return (data
.active_count
* PAGE_SIZE
) / 1024;
366 // On Mac, We only get total memory and free memory from the system.
367 bool GetSystemMemoryInfo(SystemMemoryInfoKB
* meminfo
) {
368 struct host_basic_info hostinfo
;
369 mach_msg_type_number_t count
= HOST_BASIC_INFO_COUNT
;
370 base::mac::ScopedMachSendRight
host(mach_host_self());
371 int result
= host_info(host
, HOST_BASIC_INFO
,
372 reinterpret_cast<host_info_t
>(&hostinfo
), &count
);
373 if (result
!= KERN_SUCCESS
)
376 DCHECK_EQ(HOST_BASIC_INFO_COUNT
, count
);
377 meminfo
->total
= static_cast<int>(hostinfo
.max_mem
/ 1024);
379 vm_statistics_data_t vm_info
;
380 count
= HOST_VM_INFO_COUNT
;
382 if (host_statistics(host
.get(), HOST_VM_INFO
,
383 reinterpret_cast<host_info_t
>(&vm_info
),
384 &count
) != KERN_SUCCESS
) {
388 meminfo
->free
= static_cast<int>(
389 (vm_info
.free_count
- vm_info
.speculative_count
) * PAGE_SIZE
/ 1024);