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