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 now;
    199   FILETIME creation_time;
    200   FILETIME exit_time;
    201   FILETIME kernel_time;
    202   FILETIME user_time;
    203 
    204   GetSystemTimeAsFileTime(&now);
    205 
    206   if (!GetProcessTimes(process_, &creation_time, &exit_time,
    207                        &kernel_time, &user_time)) {
    208     // We don't assert here because in some cases (such as in the Task Manager)
    209     // we may call this function on a process that has just exited but we have
    210     // not yet received the notification.
    211     return 0;
    212   }
    213   int64 system_time = (FileTimeToUTC(kernel_time) + FileTimeToUTC(user_time)) /
    214                         processor_count_;
    215   int64 time = FileTimeToUTC(now);
    216 
    217   if ((last_system_time_ == 0) || (last_time_ == 0)) {
    218     // First call, just set the last values.
    219     last_system_time_ = system_time;
    220     last_time_ = time;
    221     return 0;
    222   }
    223 
    224   int64 system_time_delta = system_time - last_system_time_;
    225   int64 time_delta = time - last_time_;
    226   DCHECK_NE(0U, time_delta);
    227   if (time_delta == 0)
    228     return 0;
    229 
    230   // We add time_delta / 2 so the result is rounded.
    231   int cpu = static_cast<int>((system_time_delta * 100 + time_delta / 2) /
    232                              time_delta);
    233 
    234   last_system_time_ = system_time;
    235   last_time_ = time;
    236 
    237   return cpu;
    238 }
    239 
    240 bool ProcessMetrics::CalculateFreeMemory(FreeMBytes* free) const {
    241   const SIZE_T kTopAddress = 0x7F000000;
    242   const SIZE_T kMegabyte = 1024 * 1024;
    243   SIZE_T accumulated = 0;
    244 
    245   MEMORY_BASIC_INFORMATION largest = {0};
    246   UINT_PTR scan = 0;
    247   while (scan < kTopAddress) {
    248     MEMORY_BASIC_INFORMATION info;
    249     if (!::VirtualQueryEx(process_, reinterpret_cast<void*>(scan),
    250                           &info, sizeof(info)))
    251       return false;
    252     if (info.State == MEM_FREE) {
    253       accumulated += info.RegionSize;
    254       if (info.RegionSize > largest.RegionSize)
    255         largest = info;
    256     }
    257     scan += info.RegionSize;
    258   }
    259   free->largest = largest.RegionSize / kMegabyte;
    260   free->largest_ptr = largest.BaseAddress;
    261   free->total = accumulated / kMegabyte;
    262   return true;
    263 }
    264 
    265 bool ProcessMetrics::GetIOCounters(IoCounters* io_counters) const {
    266   return GetProcessIoCounters(process_, io_counters) != FALSE;
    267 }
    268 
    269 ProcessMetrics::ProcessMetrics(ProcessHandle process)
    270     : process_(process),
    271       processor_count_(base::SysInfo::NumberOfProcessors()),
    272       last_time_(0),
    273       last_system_time_(0) {
    274 }
    275 
    276 // GetPerformanceInfo is not available on WIN2K.  So we'll
    277 // load it on-the-fly.
    278 const wchar_t kPsapiDllName[] = L"psapi.dll";
    279 typedef BOOL (WINAPI *GetPerformanceInfoFunction) (
    280     PPERFORMANCE_INFORMATION pPerformanceInformation,
    281     DWORD cb);
    282 
    283 // Beware of races if called concurrently from multiple threads.
    284 static BOOL InternalGetPerformanceInfo(
    285     PPERFORMANCE_INFORMATION pPerformanceInformation, DWORD cb) {
    286   static GetPerformanceInfoFunction GetPerformanceInfo_func = NULL;
    287   if (!GetPerformanceInfo_func) {
    288     HMODULE psapi_dll = ::GetModuleHandle(kPsapiDllName);
    289     if (psapi_dll)
    290       GetPerformanceInfo_func = reinterpret_cast<GetPerformanceInfoFunction>(
    291           GetProcAddress(psapi_dll, "GetPerformanceInfo"));
    292 
    293     if (!GetPerformanceInfo_func) {
    294       // The function could be loaded!
    295       memset(pPerformanceInformation, 0, cb);
    296       return FALSE;
    297     }
    298   }
    299   return GetPerformanceInfo_func(pPerformanceInformation, cb);
    300 }
    301 
    302 size_t GetSystemCommitCharge() {
    303   // Get the System Page Size.
    304   SYSTEM_INFO system_info;
    305   GetSystemInfo(&system_info);
    306 
    307   PERFORMANCE_INFORMATION info;
    308   if (!InternalGetPerformanceInfo(&info, sizeof(info))) {
    309     DLOG(ERROR) << "Failed to fetch internal performance info.";
    310     return 0;
    311   }
    312   return (info.CommitTotal * system_info.dwPageSize) / 1024;
    313 }
    314 
    315 }  // namespace base
    316