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