Home | History | Annotate | Download | only in process
      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 <windows.h>
      8 #include <psapi.h>
      9 
     10 #include "base/logging.h"
     11 #include "base/sys_info.h"
     12 
     13 namespace base {
     14 
     15 // System pagesize. This value remains constant on x86/64 architectures.
     16 const int PAGESIZE_KB = 4;
     17 
     18 ProcessMetrics::~ProcessMetrics() { }
     19 
     20 // static
     21 ProcessMetrics* ProcessMetrics::CreateProcessMetrics(ProcessHandle process) {
     22   return new ProcessMetrics(process);
     23 }
     24 
     25 size_t ProcessMetrics::GetPagefileUsage() const {
     26   PROCESS_MEMORY_COUNTERS pmc;
     27   if (GetProcessMemoryInfo(process_, &pmc, sizeof(pmc))) {
     28     return pmc.PagefileUsage;
     29   }
     30   return 0;
     31 }
     32 
     33 // Returns the peak space allocated for the pagefile, in bytes.
     34 size_t ProcessMetrics::GetPeakPagefileUsage() const {
     35   PROCESS_MEMORY_COUNTERS pmc;
     36   if (GetProcessMemoryInfo(process_, &pmc, sizeof(pmc))) {
     37     return pmc.PeakPagefileUsage;
     38   }
     39   return 0;
     40 }
     41 
     42 // Returns the current working set size, in bytes.
     43 size_t ProcessMetrics::GetWorkingSetSize() const {
     44   PROCESS_MEMORY_COUNTERS pmc;
     45   if (GetProcessMemoryInfo(process_, &pmc, sizeof(pmc))) {
     46     return pmc.WorkingSetSize;
     47   }
     48   return 0;
     49 }
     50 
     51 // Returns the peak working set size, in bytes.
     52 size_t ProcessMetrics::GetPeakWorkingSetSize() const {
     53   PROCESS_MEMORY_COUNTERS pmc;
     54   if (GetProcessMemoryInfo(process_, &pmc, sizeof(pmc))) {
     55     return pmc.PeakWorkingSetSize;
     56   }
     57   return 0;
     58 }
     59 
     60 bool ProcessMetrics::GetMemoryBytes(size_t* private_bytes,
     61                                     size_t* shared_bytes) {
     62   // PROCESS_MEMORY_COUNTERS_EX is not supported until XP SP2.
     63   // GetProcessMemoryInfo() will simply fail on prior OS. So the requested
     64   // information is simply not available. Hence, we will return 0 on unsupported
     65   // OSes. Unlike most Win32 API, we don't need to initialize the "cb" member.
     66   PROCESS_MEMORY_COUNTERS_EX pmcx;
     67   if (private_bytes &&
     68       GetProcessMemoryInfo(process_,
     69                            reinterpret_cast<PROCESS_MEMORY_COUNTERS*>(&pmcx),
     70                            sizeof(pmcx))) {
     71     *private_bytes = pmcx.PrivateUsage;
     72   }
     73 
     74   if (shared_bytes) {
     75     WorkingSetKBytes ws_usage;
     76     if (!GetWorkingSetKBytes(&ws_usage))
     77       return false;
     78 
     79     *shared_bytes = ws_usage.shared * 1024;
     80   }
     81 
     82   return true;
     83 }
     84 
     85 void ProcessMetrics::GetCommittedKBytes(CommittedKBytes* usage) const {
     86   MEMORY_BASIC_INFORMATION mbi = {0};
     87   size_t committed_private = 0;
     88   size_t committed_mapped = 0;
     89   size_t committed_image = 0;
     90   void* base_address = NULL;
     91   while (VirtualQueryEx(process_, base_address, &mbi, sizeof(mbi)) ==
     92       sizeof(mbi)) {
     93     if (mbi.State == MEM_COMMIT) {
     94       if (mbi.Type == MEM_PRIVATE) {
     95         committed_private += mbi.RegionSize;
     96       } else if (mbi.Type == MEM_MAPPED) {
     97         committed_mapped += mbi.RegionSize;
     98       } else if (mbi.Type == MEM_IMAGE) {
     99         committed_image += mbi.RegionSize;
    100       } else {
    101         NOTREACHED();
    102       }
    103     }
    104     void* new_base = (static_cast<BYTE*>(mbi.BaseAddress)) + mbi.RegionSize;
    105     // Avoid infinite loop by weird MEMORY_BASIC_INFORMATION.
    106     // If we query 64bit processes in a 32bit process, VirtualQueryEx()
    107     // returns such data.
    108     if (new_base <= base_address) {
    109       usage->image = 0;
    110       usage->mapped = 0;
    111       usage->priv = 0;
    112       return;
    113     }
    114     base_address = new_base;
    115   }
    116   usage->image = committed_image / 1024;
    117   usage->mapped = committed_mapped / 1024;
    118   usage->priv = committed_private / 1024;
    119 }
    120 
    121 bool ProcessMetrics::GetWorkingSetKBytes(WorkingSetKBytes* ws_usage) const {
    122   size_t ws_private = 0;
    123   size_t ws_shareable = 0;
    124   size_t ws_shared = 0;
    125 
    126   DCHECK(ws_usage);
    127   memset(ws_usage, 0, sizeof(*ws_usage));
    128 
    129   DWORD number_of_entries = 4096;  // Just a guess.
    130   PSAPI_WORKING_SET_INFORMATION* buffer = NULL;
    131   int retries = 5;
    132   for (;;) {
    133     DWORD buffer_size = sizeof(PSAPI_WORKING_SET_INFORMATION) +
    134                         (number_of_entries * sizeof(PSAPI_WORKING_SET_BLOCK));
    135 
    136     // if we can't expand the buffer, don't leak the previous
    137     // contents or pass a NULL pointer to QueryWorkingSet
    138     PSAPI_WORKING_SET_INFORMATION* new_buffer =
    139         reinterpret_cast<PSAPI_WORKING_SET_INFORMATION*>(
    140             realloc(buffer, buffer_size));
    141     if (!new_buffer) {
    142       free(buffer);
    143       return false;
    144     }
    145     buffer = new_buffer;
    146 
    147     // Call the function once to get number of items
    148     if (QueryWorkingSet(process_, buffer, buffer_size))
    149       break;  // Success
    150 
    151     if (GetLastError() != ERROR_BAD_LENGTH) {
    152       free(buffer);
    153       return false;
    154     }
    155 
    156     number_of_entries = static_cast<DWORD>(buffer->NumberOfEntries);
    157 
    158     // Maybe some entries are being added right now. Increase the buffer to
    159     // take that into account.
    160     number_of_entries = static_cast<DWORD>(number_of_entries * 1.25);
    161 
    162     if (--retries == 0) {
    163       free(buffer);  // If we're looping, eventually fail.
    164       return false;
    165     }
    166   }
    167 
    168   // On windows 2000 the function returns 1 even when the buffer is too small.
    169   // The number of entries that we are going to parse is the minimum between the
    170   // size we allocated and the real number of entries.
    171   number_of_entries =
    172       std::min(number_of_entries, static_cast<DWORD>(buffer->NumberOfEntries));
    173   for (unsigned int i = 0; i < number_of_entries; i++) {
    174     if (buffer->WorkingSetInfo[i].Shared) {
    175       ws_shareable++;
    176       if (buffer->WorkingSetInfo[i].ShareCount > 1)
    177         ws_shared++;
    178     } else {
    179       ws_private++;
    180     }
    181   }
    182 
    183   ws_usage->priv = ws_private * PAGESIZE_KB;
    184   ws_usage->shareable = ws_shareable * PAGESIZE_KB;
    185   ws_usage->shared = ws_shared * PAGESIZE_KB;
    186   free(buffer);
    187   return true;
    188 }
    189 
    190 static uint64 FileTimeToUTC(const FILETIME& ftime) {
    191   LARGE_INTEGER li;
    192   li.LowPart = ftime.dwLowDateTime;
    193   li.HighPart = ftime.dwHighDateTime;
    194   return li.QuadPart;
    195 }
    196 
    197 double ProcessMetrics::GetCPUUsage() {
    198   FILETIME creation_time;
    199   FILETIME exit_time;
    200   FILETIME kernel_time;
    201   FILETIME user_time;
    202 
    203   if (!GetProcessTimes(process_, &creation_time, &exit_time,
    204                        &kernel_time, &user_time)) {
    205     // We don't assert here because in some cases (such as in the Task Manager)
    206     // we may call this function on a process that has just exited but we have
    207     // not yet received the notification.
    208     return 0;
    209   }
    210   int64 system_time = (FileTimeToUTC(kernel_time) + FileTimeToUTC(user_time)) /
    211                         processor_count_;
    212   TimeTicks time = TimeTicks::Now();
    213 
    214   if (last_system_time_ == 0) {
    215     // First call, just set the last values.
    216     last_system_time_ = system_time;
    217     last_cpu_time_ = time;
    218     return 0;
    219   }
    220 
    221   int64 system_time_delta = system_time - last_system_time_;
    222   // FILETIME is in 100-nanosecond units, so this needs microseconds times 10.
    223   int64 time_delta = (time - last_cpu_time_).InMicroseconds() * 10;
    224   DCHECK_NE(0U, time_delta);
    225   if (time_delta == 0)
    226     return 0;
    227 
    228   // We add time_delta / 2 so the result is rounded.
    229   int cpu = static_cast<int>((system_time_delta * 100 + time_delta / 2) /
    230                              time_delta);
    231 
    232   last_system_time_ = system_time;
    233   last_cpu_time_ = time;
    234 
    235   return cpu;
    236 }
    237 
    238 bool ProcessMetrics::GetIOCounters(IoCounters* io_counters) const {
    239   return GetProcessIoCounters(process_, io_counters) != FALSE;
    240 }
    241 
    242 ProcessMetrics::ProcessMetrics(ProcessHandle process)
    243     : process_(process),
    244       processor_count_(base::SysInfo::NumberOfProcessors()),
    245       last_system_time_(0) {
    246 }
    247 
    248 // GetPerformanceInfo is not available on WIN2K.  So we'll
    249 // load it on-the-fly.
    250 const wchar_t kPsapiDllName[] = L"psapi.dll";
    251 typedef BOOL (WINAPI *GetPerformanceInfoFunction) (
    252     PPERFORMANCE_INFORMATION pPerformanceInformation,
    253     DWORD cb);
    254 
    255 // Beware of races if called concurrently from multiple threads.
    256 static BOOL InternalGetPerformanceInfo(
    257     PPERFORMANCE_INFORMATION pPerformanceInformation, DWORD cb) {
    258   static GetPerformanceInfoFunction GetPerformanceInfo_func = NULL;
    259   if (!GetPerformanceInfo_func) {
    260     HMODULE psapi_dll = ::GetModuleHandle(kPsapiDllName);
    261     if (psapi_dll)
    262       GetPerformanceInfo_func = reinterpret_cast<GetPerformanceInfoFunction>(
    263           GetProcAddress(psapi_dll, "GetPerformanceInfo"));
    264 
    265     if (!GetPerformanceInfo_func) {
    266       // The function could be loaded!
    267       memset(pPerformanceInformation, 0, cb);
    268       return FALSE;
    269     }
    270   }
    271   return GetPerformanceInfo_func(pPerformanceInformation, cb);
    272 }
    273 
    274 size_t GetSystemCommitCharge() {
    275   // Get the System Page Size.
    276   SYSTEM_INFO system_info;
    277   GetSystemInfo(&system_info);
    278 
    279   PERFORMANCE_INFORMATION info;
    280   if (!InternalGetPerformanceInfo(&info, sizeof(info))) {
    281     DLOG(ERROR) << "Failed to fetch internal performance info.";
    282     return 0;
    283   }
    284   return (info.CommitTotal * system_info.dwPageSize) / 1024;
    285 }
    286 
    287 }  // namespace base
    288