process_util.h revision ddb351dbec246cf1fab5ec20d2d5520909041de1
1// Copyright (c) 2011 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/namespace contains utility functions for enumerating, ending and
6// computing statistics of processes.
7
8#ifndef BASE_PROCESS_UTIL_H_
9#define BASE_PROCESS_UTIL_H_
10#pragma once
11
12#include "base/basictypes.h"
13
14#if defined(OS_WIN)
15#include <windows.h>
16#include <tlhelp32.h>
17#elif defined(OS_MACOSX)
18// kinfo_proc is defined in <sys/sysctl.h>, but this forward declaration
19// is sufficient for the vector<kinfo_proc> below.
20struct kinfo_proc;
21// malloc_zone_t is defined in <malloc/malloc.h>, but this forward declaration
22// is sufficient for GetPurgeableZone() below.
23typedef struct _malloc_zone_t malloc_zone_t;
24#include <mach/mach.h>
25#elif defined(OS_POSIX)
26#include <dirent.h>
27#include <limits.h>
28#include <sys/types.h>
29#endif
30
31#include <list>
32#include <string>
33#include <utility>
34#include <vector>
35
36#include "base/base_api.h"
37#include "base/file_descriptor_shuffle.h"
38#include "base/file_path.h"
39#include "base/process.h"
40
41class CommandLine;
42
43namespace base {
44
45#if defined(OS_WIN)
46struct ProcessEntry : public PROCESSENTRY32 {
47  ProcessId pid() const { return th32ProcessID; }
48  ProcessId parent_pid() const { return th32ParentProcessID; }
49  const wchar_t* exe_file() const { return szExeFile; }
50};
51
52struct IoCounters : public IO_COUNTERS {
53};
54
55// Process access masks. These constants provide platform-independent
56// definitions for the standard Windows access masks.
57// See http://msdn.microsoft.com/en-us/library/ms684880(VS.85).aspx for
58// the specific semantics of each mask value.
59const uint32 kProcessAccessTerminate              = PROCESS_TERMINATE;
60const uint32 kProcessAccessCreateThread           = PROCESS_CREATE_THREAD;
61const uint32 kProcessAccessSetSessionId           = PROCESS_SET_SESSIONID;
62const uint32 kProcessAccessVMOperation            = PROCESS_VM_OPERATION;
63const uint32 kProcessAccessVMRead                 = PROCESS_VM_READ;
64const uint32 kProcessAccessVMWrite                = PROCESS_VM_WRITE;
65const uint32 kProcessAccessDuplicateHandle        = PROCESS_DUP_HANDLE;
66const uint32 kProcessAccessCreateProcess          = PROCESS_CREATE_PROCESS;
67const uint32 kProcessAccessSetQuota               = PROCESS_SET_QUOTA;
68const uint32 kProcessAccessSetInformation         = PROCESS_SET_INFORMATION;
69const uint32 kProcessAccessQueryInformation       = PROCESS_QUERY_INFORMATION;
70const uint32 kProcessAccessSuspendResume          = PROCESS_SUSPEND_RESUME;
71const uint32 kProcessAccessQueryLimitedInfomation =
72    PROCESS_QUERY_LIMITED_INFORMATION;
73const uint32 kProcessAccessWaitForTermination     = SYNCHRONIZE;
74#elif defined(OS_POSIX)
75
76struct ProcessEntry {
77  ProcessEntry();
78  ~ProcessEntry();
79
80  ProcessId pid() const { return pid_; }
81  ProcessId parent_pid() const { return ppid_; }
82  ProcessId gid() const { return gid_; }
83  const char* exe_file() const { return exe_file_.c_str(); }
84  const std::vector<std::string>& cmd_line_args() const {
85    return cmd_line_args_;
86  }
87
88  ProcessId pid_;
89  ProcessId ppid_;
90  ProcessId gid_;
91  std::string exe_file_;
92  std::vector<std::string> cmd_line_args_;
93};
94
95struct IoCounters {
96  uint64_t ReadOperationCount;
97  uint64_t WriteOperationCount;
98  uint64_t OtherOperationCount;
99  uint64_t ReadTransferCount;
100  uint64_t WriteTransferCount;
101  uint64_t OtherTransferCount;
102};
103
104// Process access masks. They are not used on Posix because access checking
105// does not happen during handle creation.
106const uint32 kProcessAccessTerminate              = 0;
107const uint32 kProcessAccessCreateThread           = 0;
108const uint32 kProcessAccessSetSessionId           = 0;
109const uint32 kProcessAccessVMOperation            = 0;
110const uint32 kProcessAccessVMRead                 = 0;
111const uint32 kProcessAccessVMWrite                = 0;
112const uint32 kProcessAccessDuplicateHandle        = 0;
113const uint32 kProcessAccessCreateProcess          = 0;
114const uint32 kProcessAccessSetQuota               = 0;
115const uint32 kProcessAccessSetInformation         = 0;
116const uint32 kProcessAccessQueryInformation       = 0;
117const uint32 kProcessAccessSuspendResume          = 0;
118const uint32 kProcessAccessQueryLimitedInfomation = 0;
119const uint32 kProcessAccessWaitForTermination     = 0;
120#endif  // defined(OS_POSIX)
121
122// Return status values from GetTerminationStatus.  Don't use these as
123// exit code arguments to KillProcess*(), use platform/application
124// specific values instead.
125enum TerminationStatus {
126  TERMINATION_STATUS_NORMAL_TERMINATION,   // zero exit status
127  TERMINATION_STATUS_ABNORMAL_TERMINATION, // non-zero exit status
128  TERMINATION_STATUS_PROCESS_WAS_KILLED,   // e.g. SIGKILL or task manager kill
129  TERMINATION_STATUS_PROCESS_CRASHED,      // e.g. Segmentation fault
130  TERMINATION_STATUS_STILL_RUNNING,        // child hasn't exited yet
131  TERMINATION_STATUS_MAX_ENUM
132};
133
134// Returns the id of the current process.
135BASE_API ProcessId GetCurrentProcId();
136
137// Returns the ProcessHandle of the current process.
138BASE_API ProcessHandle GetCurrentProcessHandle();
139
140// Converts a PID to a process handle. This handle must be closed by
141// CloseProcessHandle when you are done with it. Returns true on success.
142BASE_API bool OpenProcessHandle(ProcessId pid, ProcessHandle* handle);
143
144// Converts a PID to a process handle. On Windows the handle is opened
145// with more access rights and must only be used by trusted code.
146// You have to close returned handle using CloseProcessHandle. Returns true
147// on success.
148// TODO(sanjeevr): Replace all calls to OpenPrivilegedProcessHandle with the
149// more specific OpenProcessHandleWithAccess method and delete this.
150BASE_API bool OpenPrivilegedProcessHandle(ProcessId pid, ProcessHandle* handle);
151
152// Converts a PID to a process handle using the desired access flags. Use a
153// combination of the kProcessAccess* flags defined above for |access_flags|.
154BASE_API bool OpenProcessHandleWithAccess(ProcessId pid,
155                                          uint32 access_flags,
156                                          ProcessHandle* handle);
157
158// Closes the process handle opened by OpenProcessHandle.
159BASE_API void CloseProcessHandle(ProcessHandle process);
160
161// Returns the unique ID for the specified process. This is functionally the
162// same as Windows' GetProcessId(), but works on versions of Windows before
163// Win XP SP1 as well.
164BASE_API ProcessId GetProcId(ProcessHandle process);
165
166#if defined(OS_LINUX)
167// Returns the path to the executable of the given process.
168FilePath GetProcessExecutablePath(ProcessHandle process);
169
170// Parse the data found in /proc/<pid>/stat and return the sum of the
171// CPU-related ticks.  Returns -1 on parse error.
172// Exposed for testing.
173int ParseProcStatCPU(const std::string& input);
174
175static const char kAdjustOOMScoreSwitch[] = "--adjust-oom-score";
176
177// This adjusts /proc/process/oom_adj so the Linux OOM killer will prefer
178// certain process types over others. The range for the adjustment is
179// [-17,15], with [0,15] being user accessible.
180bool AdjustOOMScore(ProcessId process, int score);
181#endif
182
183#if defined(OS_POSIX)
184// Returns the ID for the parent of the given process.
185ProcessId GetParentProcessId(ProcessHandle process);
186
187// Close all file descriptors, except those which are a destination in the
188// given multimap. Only call this function in a child process where you know
189// that there aren't any other threads.
190void CloseSuperfluousFds(const InjectiveMultimap& saved_map);
191#endif
192
193#if defined(OS_WIN)
194
195enum IntegrityLevel {
196  INTEGRITY_UNKNOWN,
197  LOW_INTEGRITY,
198  MEDIUM_INTEGRITY,
199  HIGH_INTEGRITY,
200};
201// Determine the integrity level of the specified process. Returns false
202// if the system does not support integrity levels (pre-Vista) or in the case
203// of an underlying system failure.
204BASE_API bool GetProcessIntegrityLevel(ProcessHandle process,
205                                       IntegrityLevel *level);
206
207// Runs the given application name with the given command line. Normally, the
208// first command line argument should be the path to the process, and don't
209// forget to quote it.
210//
211// If wait is true, it will block and wait for the other process to finish,
212// otherwise, it will just continue asynchronously.
213//
214// Example (including literal quotes)
215//  cmdline = "c:\windows\explorer.exe" -foo "c:\bar\"
216//
217// If process_handle is non-NULL, the process handle of the launched app will be
218// stored there on a successful launch.
219// NOTE: In this case, the caller is responsible for closing the handle so
220//       that it doesn't leak!
221BASE_API bool LaunchApp(const std::wstring& cmdline,
222                        bool wait, bool start_hidden,
223                        ProcessHandle* process_handle);
224
225// Same as LaunchApp, except allows the new process to inherit handles of the
226// parent process.
227BASE_API bool LaunchAppWithHandleInheritance(const std::wstring& cmdline,
228                                             bool wait, bool start_hidden,
229                                             ProcessHandle* process_handle);
230
231// Runs the given application name with the given command line as if the user
232// represented by |token| had launched it. The caveats about |cmdline| and
233// |process_handle| explained for LaunchApp above apply as well.
234//
235// Whether the application is visible on the interactive desktop depends on
236// the token belonging to an interactive logon session.
237//
238// To avoid hard to diagnose problems, this function internally loads the
239// environment variables associated with the user and if this operation fails
240// the entire call fails as well.
241BASE_API bool LaunchAppAsUser(UserTokenHandle token,
242                              const std::wstring& cmdline,
243                              bool start_hidden,
244                              ProcessHandle* process_handle);
245
246// Has the same behavior as LaunchAppAsUser, but offers the boolean option to
247// use an empty string for the desktop name and a boolean for allowing the
248// child process to inherit handles from its parent.
249BASE_API bool LaunchAppAsUser(UserTokenHandle token,
250                              const std::wstring& cmdline,
251                              bool start_hidden, ProcessHandle* process_handle,
252                              bool empty_desktop_name, bool inherit_handles);
253
254
255#elif defined(OS_POSIX)
256// Runs the application specified in argv[0] with the command line argv.
257// Before launching all FDs open in the parent process will be marked as
258// close-on-exec.  |fds_to_remap| defines a mapping of src fd->dest fd to
259// propagate FDs into the child process.
260//
261// As above, if wait is true, execute synchronously. The pid will be stored
262// in process_handle if that pointer is non-null.
263//
264// Note that the first argument in argv must point to the executable filename.
265// If the filename is not fully specified, PATH will be searched.
266typedef std::vector<std::pair<int, int> > file_handle_mapping_vector;
267bool LaunchApp(const std::vector<std::string>& argv,
268               const file_handle_mapping_vector& fds_to_remap,
269               bool wait, ProcessHandle* process_handle);
270
271// Similar to the above, but also (un)set environment variables in child process
272// through |environ|.
273typedef std::vector<std::pair<std::string, std::string> > environment_vector;
274bool LaunchApp(const std::vector<std::string>& argv,
275               const environment_vector& environ,
276               const file_handle_mapping_vector& fds_to_remap,
277               bool wait, ProcessHandle* process_handle);
278
279// Similar to the above two methods, but starts the child process in a process
280// group of its own, instead of allowing it to inherit the parent's process
281// group. The pgid of the child process will be the same as its pid.
282bool LaunchAppInNewProcessGroup(const std::vector<std::string>& argv,
283                                const environment_vector& environ,
284                                const file_handle_mapping_vector& fds_to_remap,
285                                bool wait, ProcessHandle* process_handle);
286
287// AlterEnvironment returns a modified environment vector, constructed from the
288// given environment and the list of changes given in |changes|. Each key in
289// the environment is matched against the first element of the pairs. In the
290// event of a match, the value is replaced by the second of the pair, unless
291// the second is empty, in which case the key-value is removed.
292//
293// The returned array is allocated using new[] and must be freed by the caller.
294char** AlterEnvironment(const environment_vector& changes,
295                        const char* const* const env);
296#endif  // defined(OS_POSIX)
297
298// Executes the application specified by cl. This function delegates to one
299// of the above two platform-specific functions.
300BASE_API bool LaunchApp(const CommandLine& cl, bool wait, bool start_hidden,
301                        ProcessHandle* process_handle);
302
303// Executes the application specified by |cl| and wait for it to exit. Stores
304// the output (stdout) in |output|. Redirects stderr to /dev/null. Returns true
305// on success (application launched and exited cleanly, with exit code
306// indicating success).
307BASE_API bool GetAppOutput(const CommandLine& cl, std::string* output);
308
309#if defined(OS_POSIX)
310// A restricted version of |GetAppOutput()| which (a) clears the environment,
311// and (b) stores at most |max_output| bytes; also, it doesn't search the path
312// for the command.
313bool GetAppOutputRestricted(const CommandLine& cl,
314                            std::string* output, size_t max_output);
315#endif
316
317// Used to filter processes by process ID.
318class ProcessFilter {
319 public:
320  // Returns true to indicate set-inclusion and false otherwise.  This method
321  // should not have side-effects and should be idempotent.
322  virtual bool Includes(const ProcessEntry& entry) const = 0;
323
324 protected:
325  virtual ~ProcessFilter() {}
326};
327
328// Returns the number of processes on the machine that are running from the
329// given executable name.  If filter is non-null, then only processes selected
330// by the filter will be counted.
331BASE_API int GetProcessCount(const FilePath::StringType& executable_name,
332                             const ProcessFilter* filter);
333
334// Attempts to kill all the processes on the current machine that were launched
335// from the given executable name, ending them with the given exit code.  If
336// filter is non-null, then only processes selected by the filter are killed.
337// Returns true if all processes were able to be killed off, false if at least
338// one couldn't be killed.
339BASE_API bool KillProcesses(const FilePath::StringType& executable_name,
340                            int exit_code, const ProcessFilter* filter);
341
342// Attempts to kill the process identified by the given process
343// entry structure, giving it the specified exit code. If |wait| is true, wait
344// for the process to be actually terminated before returning.
345// Returns true if this is successful, false otherwise.
346BASE_API bool KillProcess(ProcessHandle process, int exit_code, bool wait);
347
348#if defined(OS_POSIX)
349// Attempts to kill the process group identified by |process_group_id|. Returns
350// true on success.
351bool KillProcessGroup(ProcessHandle process_group_id);
352#endif
353
354#if defined(OS_WIN)
355BASE_API bool KillProcessById(ProcessId process_id, int exit_code, bool wait);
356#endif
357
358// Get the termination status of the process by interpreting the
359// circumstances of the child process' death. |exit_code| is set to
360// the status returned by waitpid() on POSIX, and from
361// GetExitCodeProcess() on Windows.  |exit_code| may be NULL if the
362// caller is not interested in it.  Note that on Linux, this function
363// will only return a useful result the first time it is called after
364// the child exits (because it will reap the child and the information
365// will no longer be available).
366BASE_API TerminationStatus GetTerminationStatus(ProcessHandle handle,
367                                                int* exit_code);
368
369// Waits for process to exit. On POSIX systems, if the process hasn't been
370// signaled then puts the exit code in |exit_code|; otherwise it's considered
371// a failure. On Windows |exit_code| is always filled. Returns true on success,
372// and closes |handle| in any case.
373BASE_API bool WaitForExitCode(ProcessHandle handle, int* exit_code);
374
375// Waits for process to exit. If it did exit within |timeout_milliseconds|,
376// then puts the exit code in |exit_code|, and returns true.
377// In POSIX systems, if the process has been signaled then |exit_code| is set
378// to -1. Returns false on failure (the caller is then responsible for closing
379// |handle|).
380// The caller is always responsible for closing the |handle|.
381BASE_API bool WaitForExitCodeWithTimeout(ProcessHandle handle, int* exit_code,
382                                         int64 timeout_milliseconds);
383
384// Wait for all the processes based on the named executable to exit.  If filter
385// is non-null, then only processes selected by the filter are waited on.
386// Returns after all processes have exited or wait_milliseconds have expired.
387// Returns true if all the processes exited, false otherwise.
388BASE_API bool WaitForProcessesToExit(
389    const FilePath::StringType& executable_name,
390    int64 wait_milliseconds,
391    const ProcessFilter* filter);
392
393// Wait for a single process to exit. Return true if it exited cleanly within
394// the given time limit. On Linux |handle| must be a child process, however
395// on Mac and Windows it can be any process.
396BASE_API bool WaitForSingleProcess(ProcessHandle handle,
397                                   int64 wait_milliseconds);
398
399// Waits a certain amount of time (can be 0) for all the processes with a given
400// executable name to exit, then kills off any of them that are still around.
401// If filter is non-null, then only processes selected by the filter are waited
402// on.  Killed processes are ended with the given exit code.  Returns false if
403// any processes needed to be killed, true if they all exited cleanly within
404// the wait_milliseconds delay.
405BASE_API bool CleanupProcesses(const FilePath::StringType& executable_name,
406                               int64 wait_milliseconds,
407                               int exit_code,
408                               const ProcessFilter* filter);
409
410// This class provides a way to iterate through a list of processes on the
411// current machine with a specified filter.
412// To use, create an instance and then call NextProcessEntry() until it returns
413// false.
414class BASE_API ProcessIterator {
415 public:
416  typedef std::list<ProcessEntry> ProcessEntries;
417
418  explicit ProcessIterator(const ProcessFilter* filter);
419  virtual ~ProcessIterator();
420
421  // If there's another process that matches the given executable name,
422  // returns a const pointer to the corresponding PROCESSENTRY32.
423  // If there are no more matching processes, returns NULL.
424  // The returned pointer will remain valid until NextProcessEntry()
425  // is called again or this NamedProcessIterator goes out of scope.
426  const ProcessEntry* NextProcessEntry();
427
428  // Takes a snapshot of all the ProcessEntry found.
429  ProcessEntries Snapshot();
430
431 protected:
432  virtual bool IncludeEntry();
433  const ProcessEntry& entry() { return entry_; }
434
435 private:
436  // Determines whether there's another process (regardless of executable)
437  // left in the list of all processes.  Returns true and sets entry_ to
438  // that process's info if there is one, false otherwise.
439  bool CheckForNextProcess();
440
441  // Initializes a PROCESSENTRY32 data structure so that it's ready for
442  // use with Process32First/Process32Next.
443  void InitProcessEntry(ProcessEntry* entry);
444
445#if defined(OS_WIN)
446  HANDLE snapshot_;
447  bool started_iteration_;
448#elif defined(OS_MACOSX)
449  std::vector<kinfo_proc> kinfo_procs_;
450  size_t index_of_kinfo_proc_;
451#elif defined(OS_POSIX)
452  DIR *procfs_dir_;
453#endif
454  ProcessEntry entry_;
455  const ProcessFilter* filter_;
456
457  DISALLOW_COPY_AND_ASSIGN(ProcessIterator);
458};
459
460// This class provides a way to iterate through the list of processes
461// on the current machine that were started from the given executable
462// name.  To use, create an instance and then call NextProcessEntry()
463// until it returns false.
464class BASE_API NamedProcessIterator : public ProcessIterator {
465 public:
466  NamedProcessIterator(const FilePath::StringType& executable_name,
467                       const ProcessFilter* filter);
468  virtual ~NamedProcessIterator();
469
470 protected:
471  virtual bool IncludeEntry();
472
473 private:
474  FilePath::StringType executable_name_;
475
476  DISALLOW_COPY_AND_ASSIGN(NamedProcessIterator);
477};
478
479// Working Set (resident) memory usage broken down by
480//
481// On Windows:
482// priv (private): These pages (kbytes) cannot be shared with any other process.
483// shareable:      These pages (kbytes) can be shared with other processes under
484//                 the right circumstances.
485// shared :        These pages (kbytes) are currently shared with at least one
486//                 other process.
487//
488// On Linux:
489// priv:           Pages mapped only by this process
490// shared:         PSS or 0 if the kernel doesn't support this
491// shareable:      0
492//
493// On OS X: TODO(thakis): Revise.
494// priv:           Memory.
495// shared:         0
496// shareable:      0
497struct WorkingSetKBytes {
498  WorkingSetKBytes() : priv(0), shareable(0), shared(0) {}
499  size_t priv;
500  size_t shareable;
501  size_t shared;
502};
503
504// Committed (resident + paged) memory usage broken down by
505// private: These pages cannot be shared with any other process.
506// mapped:  These pages are mapped into the view of a section (backed by
507//          pagefile.sys)
508// image:   These pages are mapped into the view of an image section (backed by
509//          file system)
510struct CommittedKBytes {
511  CommittedKBytes() : priv(0), mapped(0), image(0) {}
512  size_t priv;
513  size_t mapped;
514  size_t image;
515};
516
517// Free memory (Megabytes marked as free) in the 2G process address space.
518// total : total amount in megabytes marked as free. Maximum value is 2048.
519// largest : size of the largest contiguous amount of memory found. It is
520//   always smaller or equal to FreeMBytes::total.
521// largest_ptr: starting address of the largest memory block.
522struct FreeMBytes {
523  size_t total;
524  size_t largest;
525  void* largest_ptr;
526};
527
528// Convert a POSIX timeval to microseconds.
529BASE_API int64 TimeValToMicroseconds(const struct timeval& tv);
530
531// Provides performance metrics for a specified process (CPU usage, memory and
532// IO counters). To use it, invoke CreateProcessMetrics() to get an instance
533// for a specific process, then access the information with the different get
534// methods.
535class BASE_API ProcessMetrics {
536 public:
537  ~ProcessMetrics();
538
539  // Creates a ProcessMetrics for the specified process.
540  // The caller owns the returned object.
541#if !defined(OS_MACOSX)
542  static ProcessMetrics* CreateProcessMetrics(ProcessHandle process);
543#else
544  class PortProvider {
545   public:
546    // Should return the mach task for |process| if possible, or else
547    // |MACH_PORT_NULL|. Only processes that this returns tasks for will have
548    // metrics on OS X (except for the current process, which always gets
549    // metrics).
550    virtual mach_port_t TaskForPid(ProcessHandle process) const = 0;
551  };
552
553  // The port provider needs to outlive the ProcessMetrics object returned by
554  // this function. If NULL is passed as provider, the returned object
555  // only returns valid metrics if |process| is the current process.
556  static ProcessMetrics* CreateProcessMetrics(ProcessHandle process,
557                                              PortProvider* port_provider);
558#endif  // !defined(OS_MACOSX)
559
560  // Returns the current space allocated for the pagefile, in bytes (these pages
561  // may or may not be in memory).  On Linux, this returns the total virtual
562  // memory size.
563  size_t GetPagefileUsage() const;
564  // Returns the peak space allocated for the pagefile, in bytes.
565  size_t GetPeakPagefileUsage() const;
566  // Returns the current working set size, in bytes.  On Linux, this returns
567  // the resident set size.
568  size_t GetWorkingSetSize() const;
569  // Returns the peak working set size, in bytes.
570  size_t GetPeakWorkingSetSize() const;
571  // Returns private and sharedusage, in bytes. Private bytes is the amount of
572  // memory currently allocated to a process that cannot be shared. Returns
573  // false on platform specific error conditions.  Note: |private_bytes|
574  // returns 0 on unsupported OSes: prior to XP SP2.
575  bool GetMemoryBytes(size_t* private_bytes,
576                      size_t* shared_bytes);
577  // Fills a CommittedKBytes with both resident and paged
578  // memory usage as per definition of CommittedBytes.
579  void GetCommittedKBytes(CommittedKBytes* usage) const;
580  // Fills a WorkingSetKBytes containing resident private and shared memory
581  // usage in bytes, as per definition of WorkingSetBytes.
582  bool GetWorkingSetKBytes(WorkingSetKBytes* ws_usage) const;
583
584  // Computes the current process available memory for allocation.
585  // It does a linear scan of the address space querying each memory region
586  // for its free (unallocated) status. It is useful for estimating the memory
587  // load and fragmentation.
588  bool CalculateFreeMemory(FreeMBytes* free) const;
589
590  // Returns the CPU usage in percent since the last time this method was
591  // called. The first time this method is called it returns 0 and will return
592  // the actual CPU info on subsequent calls.
593  // On Windows, the CPU usage value is for all CPUs. So if you have 2 CPUs and
594  // your process is using all the cycles of 1 CPU and not the other CPU, this
595  // method returns 50.
596  double GetCPUUsage();
597
598  // Retrieves accounting information for all I/O operations performed by the
599  // process.
600  // If IO information is retrieved successfully, the function returns true
601  // and fills in the IO_COUNTERS passed in. The function returns false
602  // otherwise.
603  bool GetIOCounters(IoCounters* io_counters) const;
604
605 private:
606#if !defined(OS_MACOSX)
607  explicit ProcessMetrics(ProcessHandle process);
608#else
609  ProcessMetrics(ProcessHandle process, PortProvider* port_provider);
610#endif  // !defined(OS_MACOSX)
611
612  ProcessHandle process_;
613
614  int processor_count_;
615
616  // Used to store the previous times and CPU usage counts so we can
617  // compute the CPU usage between calls.
618  int64 last_time_;
619  int64 last_system_time_;
620
621#if defined(OS_MACOSX)
622  // Queries the port provider if it's set.
623  mach_port_t TaskForPid(ProcessHandle process) const;
624
625  PortProvider* port_provider_;
626#elif defined(OS_POSIX)
627  // Jiffie count at the last_time_ we updated.
628  int last_cpu_;
629#endif  // defined(OS_MACOSX)
630
631  DISALLOW_COPY_AND_ASSIGN(ProcessMetrics);
632};
633
634// Returns the memory commited by the system in KBytes.
635// Returns 0 if it can't compute the commit charge.
636BASE_API size_t GetSystemCommitCharge();
637
638// Enables low fragmentation heap (LFH) for every heaps of this process. This
639// won't have any effect on heaps created after this function call. It will not
640// modify data allocated in the heaps before calling this function. So it is
641// better to call this function early in initialization and again before
642// entering the main loop.
643// Note: Returns true on Windows 2000 without doing anything.
644BASE_API bool EnableLowFragmentationHeap();
645
646// Enables 'terminate on heap corruption' flag. Helps protect against heap
647// overflow. Has no effect if the OS doesn't provide the necessary facility.
648BASE_API void EnableTerminationOnHeapCorruption();
649
650#if !defined(OS_WIN)
651// Turns on process termination if memory runs out. This is handled on Windows
652// inside RegisterInvalidParamHandler().
653void EnableTerminationOnOutOfMemory();
654#if defined(OS_MACOSX)
655// Exposed for testing.
656malloc_zone_t* GetPurgeableZone();
657#endif
658#endif
659
660// Enables stack dump to console output on exception and signals.
661// When enabled, the process will quit immediately. This is meant to be used in
662// unit_tests only!
663BASE_API bool EnableInProcessStackDumping();
664
665// If supported on the platform, and the user has sufficent rights, increase
666// the current process's scheduling priority to a high priority.
667BASE_API void RaiseProcessToHighPriority();
668
669#if defined(OS_MACOSX)
670// Restore the default exception handler, setting it to Apple Crash Reporter
671// (ReportCrash).  When forking and execing a new process, the child will
672// inherit the parent's exception ports, which may be set to the Breakpad
673// instance running inside the parent.  The parent's Breakpad instance should
674// not handle the child's exceptions.  Calling RestoreDefaultExceptionHandler
675// in the child after forking will restore the standard exception handler.
676// See http://crbug.com/20371/ for more details.
677void RestoreDefaultExceptionHandler();
678#endif  // defined(OS_MACOSX)
679
680}  // namespace base
681
682#endif  // BASE_PROCESS_UTIL_H_
683