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 // This file contains routines for gathering resource statistics for processes
      6 // running on the system.
      7 
      8 #ifndef BASE_PROCESS_PROCESS_METRICS_H_
      9 #define BASE_PROCESS_PROCESS_METRICS_H_
     10 
     11 #include <string>
     12 
     13 #include "base/base_export.h"
     14 #include "base/basictypes.h"
     15 #include "base/process/process_handle.h"
     16 #include "base/time/time.h"
     17 
     18 #if defined(OS_MACOSX)
     19 #include <mach/mach.h>
     20 #endif
     21 
     22 namespace base {
     23 
     24 #if defined(OS_WIN)
     25 struct IoCounters : public IO_COUNTERS {
     26 };
     27 #elif defined(OS_POSIX)
     28 struct IoCounters {
     29   uint64_t ReadOperationCount;
     30   uint64_t WriteOperationCount;
     31   uint64_t OtherOperationCount;
     32   uint64_t ReadTransferCount;
     33   uint64_t WriteTransferCount;
     34   uint64_t OtherTransferCount;
     35 };
     36 #endif
     37 
     38 // Working Set (resident) memory usage broken down by
     39 //
     40 // On Windows:
     41 // priv (private): These pages (kbytes) cannot be shared with any other process.
     42 // shareable:      These pages (kbytes) can be shared with other processes under
     43 //                 the right circumstances.
     44 // shared :        These pages (kbytes) are currently shared with at least one
     45 //                 other process.
     46 //
     47 // On Linux:
     48 // priv:           Pages mapped only by this process.
     49 // shared:         PSS or 0 if the kernel doesn't support this.
     50 // shareable:      0
     51 
     52 // On ChromeOS:
     53 // priv:           Pages mapped only by this process.
     54 // shared:         PSS or 0 if the kernel doesn't support this.
     55 // shareable:      0
     56 // swapped         Pages swapped out to zram.
     57 //
     58 // On OS X: TODO(thakis): Revise.
     59 // priv:           Memory.
     60 // shared:         0
     61 // shareable:      0
     62 //
     63 struct WorkingSetKBytes {
     64   WorkingSetKBytes() : priv(0), shareable(0), shared(0) {}
     65   size_t priv;
     66   size_t shareable;
     67   size_t shared;
     68 #if defined(OS_CHROMEOS)
     69   size_t swapped;
     70 #endif
     71 };
     72 
     73 // Committed (resident + paged) memory usage broken down by
     74 // private: These pages cannot be shared with any other process.
     75 // mapped:  These pages are mapped into the view of a section (backed by
     76 //          pagefile.sys)
     77 // image:   These pages are mapped into the view of an image section (backed by
     78 //          file system)
     79 struct CommittedKBytes {
     80   CommittedKBytes() : priv(0), mapped(0), image(0) {}
     81   size_t priv;
     82   size_t mapped;
     83   size_t image;
     84 };
     85 
     86 // Free memory (Megabytes marked as free) in the 2G process address space.
     87 // total : total amount in megabytes marked as free. Maximum value is 2048.
     88 // largest : size of the largest contiguous amount of memory found. It is
     89 //   always smaller or equal to FreeMBytes::total.
     90 // largest_ptr: starting address of the largest memory block.
     91 struct FreeMBytes {
     92   size_t total;
     93   size_t largest;
     94   void* largest_ptr;
     95 };
     96 
     97 // Convert a POSIX timeval to microseconds.
     98 BASE_EXPORT int64 TimeValToMicroseconds(const struct timeval& tv);
     99 
    100 // Provides performance metrics for a specified process (CPU usage, memory and
    101 // IO counters). To use it, invoke CreateProcessMetrics() to get an instance
    102 // for a specific process, then access the information with the different get
    103 // methods.
    104 class BASE_EXPORT ProcessMetrics {
    105  public:
    106   ~ProcessMetrics();
    107 
    108   // Creates a ProcessMetrics for the specified process.
    109   // The caller owns the returned object.
    110 #if !defined(OS_MACOSX) || defined(OS_IOS)
    111   static ProcessMetrics* CreateProcessMetrics(ProcessHandle process);
    112 #else
    113   class PortProvider {
    114    public:
    115     virtual ~PortProvider() {}
    116 
    117     // Should return the mach task for |process| if possible, or else
    118     // |MACH_PORT_NULL|. Only processes that this returns tasks for will have
    119     // metrics on OS X (except for the current process, which always gets
    120     // metrics).
    121     virtual mach_port_t TaskForPid(ProcessHandle process) const = 0;
    122   };
    123 
    124   // The port provider needs to outlive the ProcessMetrics object returned by
    125   // this function. If NULL is passed as provider, the returned object
    126   // only returns valid metrics if |process| is the current process.
    127   static ProcessMetrics* CreateProcessMetrics(ProcessHandle process,
    128                                               PortProvider* port_provider);
    129 #endif  // !defined(OS_MACOSX) || defined(OS_IOS)
    130 
    131   // Returns the current space allocated for the pagefile, in bytes (these pages
    132   // may or may not be in memory).  On Linux, this returns the total virtual
    133   // memory size.
    134   size_t GetPagefileUsage() const;
    135   // Returns the peak space allocated for the pagefile, in bytes.
    136   size_t GetPeakPagefileUsage() const;
    137   // Returns the current working set size, in bytes.  On Linux, this returns
    138   // the resident set size.
    139   size_t GetWorkingSetSize() const;
    140   // Returns the peak working set size, in bytes.
    141   size_t GetPeakWorkingSetSize() const;
    142   // Returns private and sharedusage, in bytes. Private bytes is the amount of
    143   // memory currently allocated to a process that cannot be shared. Returns
    144   // false on platform specific error conditions.  Note: |private_bytes|
    145   // returns 0 on unsupported OSes: prior to XP SP2.
    146   bool GetMemoryBytes(size_t* private_bytes,
    147                       size_t* shared_bytes);
    148   // Fills a CommittedKBytes with both resident and paged
    149   // memory usage as per definition of CommittedBytes.
    150   void GetCommittedKBytes(CommittedKBytes* usage) const;
    151   // Fills a WorkingSetKBytes containing resident private and shared memory
    152   // usage in bytes, as per definition of WorkingSetBytes.
    153   bool GetWorkingSetKBytes(WorkingSetKBytes* ws_usage) const;
    154 
    155   // Computes the current process available memory for allocation.
    156   // It does a linear scan of the address space querying each memory region
    157   // for its free (unallocated) status. It is useful for estimating the memory
    158   // load and fragmentation.
    159   bool CalculateFreeMemory(FreeMBytes* free) const;
    160 
    161   // Returns the CPU usage in percent since the last time this method was
    162   // called. The first time this method is called it returns 0 and will return
    163   // the actual CPU info on subsequent calls.
    164   // On Windows, the CPU usage value is for all CPUs. So if you have 2 CPUs and
    165   // your process is using all the cycles of 1 CPU and not the other CPU, this
    166   // method returns 50.
    167   double GetCPUUsage();
    168 
    169   // Retrieves accounting information for all I/O operations performed by the
    170   // process.
    171   // If IO information is retrieved successfully, the function returns true
    172   // and fills in the IO_COUNTERS passed in. The function returns false
    173   // otherwise.
    174   bool GetIOCounters(IoCounters* io_counters) const;
    175 
    176  private:
    177 #if !defined(OS_MACOSX) || defined(OS_IOS)
    178   explicit ProcessMetrics(ProcessHandle process);
    179 #else
    180   ProcessMetrics(ProcessHandle process, PortProvider* port_provider);
    181 #endif  // !defined(OS_MACOSX) || defined(OS_IOS)
    182 
    183 #if defined(OS_LINUX) || defined(OS_ANDROID)
    184   bool GetWorkingSetKBytesStatm(WorkingSetKBytes* ws_usage) const;
    185 #endif
    186 
    187 #if defined(OS_CHROMEOS)
    188   bool GetWorkingSetKBytesTotmaps(WorkingSetKBytes *ws_usage) const;
    189 #endif
    190 
    191   ProcessHandle process_;
    192 
    193   int processor_count_;
    194 
    195   // Used to store the previous times and CPU usage counts so we can
    196   // compute the CPU usage between calls.
    197   int64 last_time_;
    198   int64 last_system_time_;
    199 
    200 #if !defined(OS_IOS)
    201 #if defined(OS_MACOSX)
    202   // Queries the port provider if it's set.
    203   mach_port_t TaskForPid(ProcessHandle process) const;
    204 
    205   PortProvider* port_provider_;
    206 #elif defined(OS_POSIX)
    207   // Jiffie count at the last_time_ we updated.
    208   int last_cpu_;
    209 #endif  // defined(OS_POSIX)
    210 #endif  // !defined(OS_IOS)
    211 
    212   DISALLOW_COPY_AND_ASSIGN(ProcessMetrics);
    213 };
    214 
    215 // Returns the memory committed by the system in KBytes.
    216 // Returns 0 if it can't compute the commit charge.
    217 BASE_EXPORT size_t GetSystemCommitCharge();
    218 
    219 #if defined(OS_LINUX) || defined(OS_ANDROID)
    220 // Parse the data found in /proc/<pid>/stat and return the sum of the
    221 // CPU-related ticks.  Returns -1 on parse error.
    222 // Exposed for testing.
    223 BASE_EXPORT int ParseProcStatCPU(const std::string& input);
    224 
    225 // Data from /proc/meminfo about system-wide memory consumption.
    226 // Values are in KB.
    227 struct BASE_EXPORT SystemMemoryInfoKB {
    228   SystemMemoryInfoKB();
    229 
    230   int total;
    231   int free;
    232   int buffers;
    233   int cached;
    234   int active_anon;
    235   int inactive_anon;
    236   int active_file;
    237   int inactive_file;
    238   int shmem;
    239 
    240   // Gem data will be -1 if not supported.
    241   int gem_objects;
    242   long long gem_size;
    243 };
    244 // Retrieves data from /proc/meminfo about system-wide memory consumption.
    245 // Fills in the provided |meminfo| structure. Returns true on success.
    246 // Exposed for memory debugging widget.
    247 BASE_EXPORT bool GetSystemMemoryInfo(SystemMemoryInfoKB* meminfo);
    248 #endif  // defined(OS_LINUX) || defined(OS_ANDROID)
    249 
    250 #if defined(OS_LINUX) || defined(OS_ANDROID)
    251 // Get the number of threads of |process| as available in /proc/<pid>/stat.
    252 // This should be used with care as no synchronization with running threads is
    253 // done. This is mostly useful to guarantee being single-threaded.
    254 // Returns 0 on failure.
    255 BASE_EXPORT int GetNumberOfThreads(ProcessHandle process);
    256 
    257 // /proc/self/exe refers to the current executable.
    258 BASE_EXPORT extern const char kProcSelfExe[];
    259 #endif  // defined(OS_LINUX) || defined(OS_ANDROID)
    260 
    261 #if defined(OS_POSIX)
    262 // Returns the maximum number of file descriptors that can be open by a process
    263 // at once. If the number is unavailable, a conservative best guess is returned.
    264 size_t GetMaxFds();
    265 #endif  // defined(OS_POSIX)
    266 
    267 }  // namespace base
    268 
    269 #endif  // BASE_PROCESS_PROCESS_METRICS_H_
    270