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