Add partial pre-read functionality to browser startup (Windows).
[chromium-blink-merge.git] / base / process_util.h
blobbd138982afb60f17fae6a024161fc02906061629
1 // Copyright (c) 2012 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.
5 // This file/namespace contains utility functions for enumerating, ending and
6 // computing statistics of processes.
8 #ifndef BASE_PROCESS_UTIL_H_
9 #define BASE_PROCESS_UTIL_H_
10 #pragma once
12 #include "base/basictypes.h"
14 #if defined(OS_WIN)
15 #include <windows.h>
16 #include <tlhelp32.h>
17 #elif defined(OS_MACOSX) || defined(OS_BSD)
18 // kinfo_proc is defined in <sys/sysctl.h>, but this forward declaration
19 // is sufficient for the vector<kinfo_proc> below.
20 struct kinfo_proc;
21 // malloc_zone_t is defined in <malloc/malloc.h>, but this forward declaration
22 // is sufficient for GetPurgeableZone() below.
23 typedef struct _malloc_zone_t malloc_zone_t;
24 #if !defined(OS_BSD)
25 #include <mach/mach.h>
26 #endif
27 #elif defined(OS_POSIX)
28 #include <dirent.h>
29 #include <limits.h>
30 #include <sys/types.h>
31 #endif
33 #include <list>
34 #include <set>
35 #include <string>
36 #include <utility>
37 #include <vector>
39 #include "base/base_export.h"
40 #include "base/file_descriptor_shuffle.h"
41 #include "base/file_path.h"
42 #include "base/process.h"
44 class CommandLine;
46 namespace base {
48 #if defined(OS_WIN)
49 struct ProcessEntry : public PROCESSENTRY32 {
50 ProcessId pid() const { return th32ProcessID; }
51 ProcessId parent_pid() const { return th32ParentProcessID; }
52 const wchar_t* exe_file() const { return szExeFile; }
55 struct IoCounters : public IO_COUNTERS {
58 // Process access masks. These constants provide platform-independent
59 // definitions for the standard Windows access masks.
60 // See http://msdn.microsoft.com/en-us/library/ms684880(VS.85).aspx for
61 // the specific semantics of each mask value.
62 const uint32 kProcessAccessTerminate = PROCESS_TERMINATE;
63 const uint32 kProcessAccessCreateThread = PROCESS_CREATE_THREAD;
64 const uint32 kProcessAccessSetSessionId = PROCESS_SET_SESSIONID;
65 const uint32 kProcessAccessVMOperation = PROCESS_VM_OPERATION;
66 const uint32 kProcessAccessVMRead = PROCESS_VM_READ;
67 const uint32 kProcessAccessVMWrite = PROCESS_VM_WRITE;
68 const uint32 kProcessAccessDuplicateHandle = PROCESS_DUP_HANDLE;
69 const uint32 kProcessAccessCreateProcess = PROCESS_CREATE_PROCESS;
70 const uint32 kProcessAccessSetQuota = PROCESS_SET_QUOTA;
71 const uint32 kProcessAccessSetInformation = PROCESS_SET_INFORMATION;
72 const uint32 kProcessAccessQueryInformation = PROCESS_QUERY_INFORMATION;
73 const uint32 kProcessAccessSuspendResume = PROCESS_SUSPEND_RESUME;
74 const uint32 kProcessAccessQueryLimitedInfomation =
75 PROCESS_QUERY_LIMITED_INFORMATION;
76 const uint32 kProcessAccessWaitForTermination = SYNCHRONIZE;
77 #elif defined(OS_POSIX)
79 struct ProcessEntry {
80 ProcessEntry();
81 ~ProcessEntry();
83 ProcessId pid() const { return pid_; }
84 ProcessId parent_pid() const { return ppid_; }
85 ProcessId gid() const { return gid_; }
86 const char* exe_file() const { return exe_file_.c_str(); }
87 const std::vector<std::string>& cmd_line_args() const {
88 return cmd_line_args_;
91 ProcessId pid_;
92 ProcessId ppid_;
93 ProcessId gid_;
94 std::string exe_file_;
95 std::vector<std::string> cmd_line_args_;
98 struct IoCounters {
99 uint64_t ReadOperationCount;
100 uint64_t WriteOperationCount;
101 uint64_t OtherOperationCount;
102 uint64_t ReadTransferCount;
103 uint64_t WriteTransferCount;
104 uint64_t OtherTransferCount;
107 // Process access masks. They are not used on Posix because access checking
108 // does not happen during handle creation.
109 const uint32 kProcessAccessTerminate = 0;
110 const uint32 kProcessAccessCreateThread = 0;
111 const uint32 kProcessAccessSetSessionId = 0;
112 const uint32 kProcessAccessVMOperation = 0;
113 const uint32 kProcessAccessVMRead = 0;
114 const uint32 kProcessAccessVMWrite = 0;
115 const uint32 kProcessAccessDuplicateHandle = 0;
116 const uint32 kProcessAccessCreateProcess = 0;
117 const uint32 kProcessAccessSetQuota = 0;
118 const uint32 kProcessAccessSetInformation = 0;
119 const uint32 kProcessAccessQueryInformation = 0;
120 const uint32 kProcessAccessSuspendResume = 0;
121 const uint32 kProcessAccessQueryLimitedInfomation = 0;
122 const uint32 kProcessAccessWaitForTermination = 0;
123 #endif // defined(OS_POSIX)
125 // Return status values from GetTerminationStatus. Don't use these as
126 // exit code arguments to KillProcess*(), use platform/application
127 // specific values instead.
128 enum TerminationStatus {
129 TERMINATION_STATUS_NORMAL_TERMINATION, // zero exit status
130 TERMINATION_STATUS_ABNORMAL_TERMINATION, // non-zero exit status
131 TERMINATION_STATUS_PROCESS_WAS_KILLED, // e.g. SIGKILL or task manager kill
132 TERMINATION_STATUS_PROCESS_CRASHED, // e.g. Segmentation fault
133 TERMINATION_STATUS_STILL_RUNNING, // child hasn't exited yet
134 TERMINATION_STATUS_MAX_ENUM
137 // Returns the id of the current process.
138 BASE_EXPORT ProcessId GetCurrentProcId();
140 // Returns the ProcessHandle of the current process.
141 BASE_EXPORT ProcessHandle GetCurrentProcessHandle();
143 // Converts a PID to a process handle. This handle must be closed by
144 // CloseProcessHandle when you are done with it. Returns true on success.
145 BASE_EXPORT bool OpenProcessHandle(ProcessId pid, ProcessHandle* handle);
147 // Converts a PID to a process handle. On Windows the handle is opened
148 // with more access rights and must only be used by trusted code.
149 // You have to close returned handle using CloseProcessHandle. Returns true
150 // on success.
151 // TODO(sanjeevr): Replace all calls to OpenPrivilegedProcessHandle with the
152 // more specific OpenProcessHandleWithAccess method and delete this.
153 BASE_EXPORT bool OpenPrivilegedProcessHandle(ProcessId pid,
154 ProcessHandle* handle);
156 // Converts a PID to a process handle using the desired access flags. Use a
157 // combination of the kProcessAccess* flags defined above for |access_flags|.
158 BASE_EXPORT bool OpenProcessHandleWithAccess(ProcessId pid,
159 uint32 access_flags,
160 ProcessHandle* handle);
162 // Closes the process handle opened by OpenProcessHandle.
163 BASE_EXPORT void CloseProcessHandle(ProcessHandle process);
165 // Returns the unique ID for the specified process. This is functionally the
166 // same as Windows' GetProcessId(), but works on versions of Windows before
167 // Win XP SP1 as well.
168 BASE_EXPORT ProcessId GetProcId(ProcessHandle process);
170 #if defined(OS_LINUX) || defined(OS_ANDROID) || defined(OS_BSD)
171 // Returns the path to the executable of the given process.
172 BASE_EXPORT FilePath GetProcessExecutablePath(ProcessHandle process);
173 #endif
175 #if defined(OS_LINUX) || defined(OS_ANDROID)
176 // Parse the data found in /proc/<pid>/stat and return the sum of the
177 // CPU-related ticks. Returns -1 on parse error.
178 // Exposed for testing.
179 BASE_EXPORT int ParseProcStatCPU(const std::string& input);
181 // The maximum allowed value for the OOM score.
182 const int kMaxOomScore = 1000;
184 // This adjusts /proc/<pid>/oom_score_adj so the Linux OOM killer will
185 // prefer to kill certain process types over others. The range for the
186 // adjustment is [-1000, 1000], with [0, 1000] being user accessible.
187 // If the Linux system doesn't support the newer oom_score_adj range
188 // of [0, 1000], then we revert to using the older oom_adj, and
189 // translate the given value into [0, 15]. Some aliasing of values
190 // may occur in that case, of course.
191 BASE_EXPORT bool AdjustOOMScore(ProcessId process, int score);
192 #endif // defined(OS_LINUX) || defined(OS_ANDROID)
194 #if defined(OS_POSIX)
195 // Returns the ID for the parent of the given process.
196 BASE_EXPORT ProcessId GetParentProcessId(ProcessHandle process);
198 // Close all file descriptors, except those which are a destination in the
199 // given multimap. Only call this function in a child process where you know
200 // that there aren't any other threads.
201 BASE_EXPORT void CloseSuperfluousFds(const InjectiveMultimap& saved_map);
202 #endif // defined(OS_POSIX)
204 // TODO(evan): rename these to use StudlyCaps.
205 typedef std::vector<std::pair<std::string, std::string> > environment_vector;
206 typedef std::vector<std::pair<int, int> > file_handle_mapping_vector;
208 #if defined(OS_MACOSX)
209 // Used with LaunchOptions::synchronize and LaunchSynchronize, a
210 // LaunchSynchronizationHandle is an opaque value that LaunchProcess will
211 // create and set, and that LaunchSynchronize will consume and destroy.
212 typedef int* LaunchSynchronizationHandle;
213 #endif // defined(OS_MACOSX)
215 // Options for launching a subprocess that are passed to LaunchProcess().
216 // The default constructor constructs the object with default options.
217 struct LaunchOptions {
218 LaunchOptions() : wait(false),
219 #if defined(OS_WIN)
220 start_hidden(false), inherit_handles(false), as_user(NULL),
221 empty_desktop_name(false), job_handle(NULL)
222 #else
223 environ(NULL), fds_to_remap(NULL), maximize_rlimits(NULL),
224 new_process_group(false)
225 #if defined(OS_LINUX)
226 , clone_flags(0)
227 #endif // OS_LINUX
228 #if defined(OS_CHROMEOS)
229 , ctrl_terminal_fd(-1)
230 #endif // OS_CHROMEOS
231 #if defined(OS_MACOSX)
232 , synchronize(NULL)
233 #endif // defined(OS_MACOSX)
234 #endif // !defined(OS_WIN)
237 // If true, wait for the process to complete.
238 bool wait;
240 #if defined(OS_WIN)
241 bool start_hidden;
243 // If true, the new process inherits handles from the parent.
244 bool inherit_handles;
246 // If non-NULL, runs as if the user represented by the token had launched it.
247 // Whether the application is visible on the interactive desktop depends on
248 // the token belonging to an interactive logon session.
250 // To avoid hard to diagnose problems, when specified this loads the
251 // environment variables associated with the user and if this operation fails
252 // the entire call fails as well.
253 UserTokenHandle as_user;
255 // If true, use an empty string for the desktop name.
256 bool empty_desktop_name;
258 // If non-NULL, launches the application in that job object.
259 HANDLE job_handle;
260 #else
261 // If non-NULL, set/unset environment variables.
262 // See documentation of AlterEnvironment().
263 // This pointer is owned by the caller and must live through the
264 // call to LaunchProcess().
265 const environment_vector* environ;
267 // If non-NULL, remap file descriptors according to the mapping of
268 // src fd->dest fd to propagate FDs into the child process.
269 // This pointer is owned by the caller and must live through the
270 // call to LaunchProcess().
271 const file_handle_mapping_vector* fds_to_remap;
273 // Each element is an RLIMIT_* constant that should be raised to its
274 // rlim_max. This pointer is owned by the caller and must live through
275 // the call to LaunchProcess().
276 const std::set<int>* maximize_rlimits;
278 // If true, start the process in a new process group, instead of
279 // inheriting the parent's process group. The pgid of the child process
280 // will be the same as its pid.
281 bool new_process_group;
283 #if defined(OS_LINUX)
284 // If non-zero, start the process using clone(), using flags as provided.
285 int clone_flags;
286 #endif // defined(OS_LINUX)
288 #if defined(OS_CHROMEOS)
289 // If non-negative, the specified file descriptor will be set as the launched
290 // process' controlling terminal.
291 int ctrl_terminal_fd;
292 #endif // defined(OS_CHROMEOS)
294 #if defined(OS_MACOSX)
295 // When non-NULL, a new LaunchSynchronizationHandle will be created and
296 // stored in *synchronize whenever LaunchProcess returns true in the parent
297 // process. The child process will have been created (with fork) but will
298 // be waiting (before exec) for the parent to call LaunchSynchronize with
299 // this handle. Only when LaunchSynchronize is called will the child be
300 // permitted to continue execution and call exec. LaunchSynchronize
301 // destroys the handle created by LaunchProcess.
303 // When synchronize is non-NULL, the parent must call LaunchSynchronize
304 // whenever LaunchProcess returns true. No exceptions.
306 // Synchronization is useful when the parent process needs to guarantee that
307 // it can take some action (such as recording the newly-forked child's
308 // process ID) before the child does something (such as using its process ID
309 // to communicate with its parent).
311 // |synchronize| and |wait| must not both be set simultaneously.
312 LaunchSynchronizationHandle* synchronize;
313 #endif // defined(OS_MACOSX)
315 #endif // !defined(OS_WIN)
318 // Launch a process via the command line |cmdline|.
319 // See the documentation of LaunchOptions for details on |options|.
321 // If |process_handle| is non-NULL, it will be filled in with the
322 // handle of the launched process. NOTE: In this case, the caller is
323 // responsible for closing the handle so that it doesn't leak!
324 // Otherwise, the process handle will be implicitly closed.
326 // Unix-specific notes:
327 // - All file descriptors open in the parent process will be closed in the
328 // child process except for any preserved by options::fds_to_remap, and
329 // stdin, stdout, and stderr. If not remapped by options::fds_to_remap,
330 // stdin is reopened as /dev/null, and the child is allowed to inherit its
331 // parent's stdout and stderr.
332 // - If the first argument on the command line does not contain a slash,
333 // PATH will be searched. (See man execvp.)
334 BASE_EXPORT bool LaunchProcess(const CommandLine& cmdline,
335 const LaunchOptions& options,
336 ProcessHandle* process_handle);
338 #if defined(OS_WIN)
340 enum IntegrityLevel {
341 INTEGRITY_UNKNOWN,
342 LOW_INTEGRITY,
343 MEDIUM_INTEGRITY,
344 HIGH_INTEGRITY,
346 // Determine the integrity level of the specified process. Returns false
347 // if the system does not support integrity levels (pre-Vista) or in the case
348 // of an underlying system failure.
349 BASE_EXPORT bool GetProcessIntegrityLevel(ProcessHandle process,
350 IntegrityLevel *level);
352 // Windows-specific LaunchProcess that takes the command line as a
353 // string. Useful for situations where you need to control the
354 // command line arguments directly, but prefer the CommandLine version
355 // if launching Chrome itself.
357 // The first command line argument should be the path to the process,
358 // and don't forget to quote it.
360 // Example (including literal quotes)
361 // cmdline = "c:\windows\explorer.exe" -foo "c:\bar\"
362 BASE_EXPORT bool LaunchProcess(const string16& cmdline,
363 const LaunchOptions& options,
364 ProcessHandle* process_handle);
366 #elif defined(OS_POSIX)
367 // A POSIX-specific version of LaunchProcess that takes an argv array
368 // instead of a CommandLine. Useful for situations where you need to
369 // control the command line arguments directly, but prefer the
370 // CommandLine version if launching Chrome itself.
371 BASE_EXPORT bool LaunchProcess(const std::vector<std::string>& argv,
372 const LaunchOptions& options,
373 ProcessHandle* process_handle);
375 // AlterEnvironment returns a modified environment vector, constructed from the
376 // given environment and the list of changes given in |changes|. Each key in
377 // the environment is matched against the first element of the pairs. In the
378 // event of a match, the value is replaced by the second of the pair, unless
379 // the second is empty, in which case the key-value is removed.
381 // The returned array is allocated using new[] and must be freed by the caller.
382 BASE_EXPORT char** AlterEnvironment(const environment_vector& changes,
383 const char* const* const env);
385 #if defined(OS_MACOSX)
387 // After a successful call to LaunchProcess with LaunchOptions::synchronize
388 // set, the parent process must call LaunchSynchronize to allow the child
389 // process to proceed, and to destroy the LaunchSynchronizationHandle.
390 BASE_EXPORT void LaunchSynchronize(LaunchSynchronizationHandle handle);
392 #endif // defined(OS_MACOSX)
393 #endif // defined(OS_POSIX)
395 #if defined(OS_WIN)
396 // Set JOBOBJECT_EXTENDED_LIMIT_INFORMATION to JobObject |job_object|.
397 // As its limit_info.BasicLimitInformation.LimitFlags has
398 // JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE.
399 // When the provide JobObject |job_object| is closed, the binded process will
400 // be terminated.
401 BASE_EXPORT bool SetJobObjectAsKillOnJobClose(HANDLE job_object);
402 #endif // defined(OS_WIN)
404 // Executes the application specified by |cl| and wait for it to exit. Stores
405 // the output (stdout) in |output|. Redirects stderr to /dev/null. Returns true
406 // on success (application launched and exited cleanly, with exit code
407 // indicating success).
408 BASE_EXPORT bool GetAppOutput(const CommandLine& cl, std::string* output);
410 #if defined(OS_POSIX)
411 // A restricted version of |GetAppOutput()| which (a) clears the environment,
412 // and (b) stores at most |max_output| bytes; also, it doesn't search the path
413 // for the command.
414 BASE_EXPORT bool GetAppOutputRestricted(const CommandLine& cl,
415 std::string* output, size_t max_output);
417 // A version of |GetAppOutput()| which also returns the exit code of the
418 // executed command. Returns true if the application runs and exits cleanly. If
419 // this is the case the exit code of the application is available in
420 // |*exit_code|.
421 BASE_EXPORT bool GetAppOutputWithExitCode(const CommandLine& cl,
422 std::string* output, int* exit_code);
423 #endif // defined(OS_POSIX)
425 // Used to filter processes by process ID.
426 class ProcessFilter {
427 public:
428 // Returns true to indicate set-inclusion and false otherwise. This method
429 // should not have side-effects and should be idempotent.
430 virtual bool Includes(const ProcessEntry& entry) const = 0;
432 protected:
433 virtual ~ProcessFilter() {}
436 // Returns the number of processes on the machine that are running from the
437 // given executable name. If filter is non-null, then only processes selected
438 // by the filter will be counted.
439 BASE_EXPORT int GetProcessCount(const FilePath::StringType& executable_name,
440 const ProcessFilter* filter);
442 // Attempts to kill all the processes on the current machine that were launched
443 // from the given executable name, ending them with the given exit code. If
444 // filter is non-null, then only processes selected by the filter are killed.
445 // Returns true if all processes were able to be killed off, false if at least
446 // one couldn't be killed.
447 BASE_EXPORT bool KillProcesses(const FilePath::StringType& executable_name,
448 int exit_code, const ProcessFilter* filter);
450 // Attempts to kill the process identified by the given process
451 // entry structure, giving it the specified exit code. If |wait| is true, wait
452 // for the process to be actually terminated before returning.
453 // Returns true if this is successful, false otherwise.
454 BASE_EXPORT bool KillProcess(ProcessHandle process, int exit_code, bool wait);
456 #if defined(OS_POSIX)
457 // Attempts to kill the process group identified by |process_group_id|. Returns
458 // true on success.
459 BASE_EXPORT bool KillProcessGroup(ProcessHandle process_group_id);
460 #endif // defined(OS_POSIX)
462 #if defined(OS_WIN)
463 BASE_EXPORT bool KillProcessById(ProcessId process_id, int exit_code,
464 bool wait);
465 #endif // defined(OS_WIN)
467 // Get the termination status of the process by interpreting the
468 // circumstances of the child process' death. |exit_code| is set to
469 // the status returned by waitpid() on POSIX, and from
470 // GetExitCodeProcess() on Windows. |exit_code| may be NULL if the
471 // caller is not interested in it. Note that on Linux, this function
472 // will only return a useful result the first time it is called after
473 // the child exits (because it will reap the child and the information
474 // will no longer be available).
475 BASE_EXPORT TerminationStatus GetTerminationStatus(ProcessHandle handle,
476 int* exit_code);
478 // Waits for process to exit. On POSIX systems, if the process hasn't been
479 // signaled then puts the exit code in |exit_code|; otherwise it's considered
480 // a failure. On Windows |exit_code| is always filled. Returns true on success,
481 // and closes |handle| in any case.
482 BASE_EXPORT bool WaitForExitCode(ProcessHandle handle, int* exit_code);
484 // Waits for process to exit. If it did exit within |timeout_milliseconds|,
485 // then puts the exit code in |exit_code|, and returns true.
486 // In POSIX systems, if the process has been signaled then |exit_code| is set
487 // to -1. Returns false on failure (the caller is then responsible for closing
488 // |handle|).
489 // The caller is always responsible for closing the |handle|.
490 BASE_EXPORT bool WaitForExitCodeWithTimeout(ProcessHandle handle,
491 int* exit_code,
492 int64 timeout_milliseconds);
494 // Wait for all the processes based on the named executable to exit. If filter
495 // is non-null, then only processes selected by the filter are waited on.
496 // Returns after all processes have exited or wait_milliseconds have expired.
497 // Returns true if all the processes exited, false otherwise.
498 BASE_EXPORT bool WaitForProcessesToExit(
499 const FilePath::StringType& executable_name,
500 int64 wait_milliseconds,
501 const ProcessFilter* filter);
503 // Wait for a single process to exit. Return true if it exited cleanly within
504 // the given time limit. On Linux |handle| must be a child process, however
505 // on Mac and Windows it can be any process.
506 BASE_EXPORT bool WaitForSingleProcess(ProcessHandle handle,
507 int64 wait_milliseconds);
509 // Waits a certain amount of time (can be 0) for all the processes with a given
510 // executable name to exit, then kills off any of them that are still around.
511 // If filter is non-null, then only processes selected by the filter are waited
512 // on. Killed processes are ended with the given exit code. Returns false if
513 // any processes needed to be killed, true if they all exited cleanly within
514 // the wait_milliseconds delay.
515 BASE_EXPORT bool CleanupProcesses(const FilePath::StringType& executable_name,
516 int64 wait_milliseconds,
517 int exit_code,
518 const ProcessFilter* filter);
520 // This method ensures that the specified process eventually terminates, and
521 // then it closes the given process handle.
523 // It assumes that the process has already been signalled to exit, and it
524 // begins by waiting a small amount of time for it to exit. If the process
525 // does not appear to have exited, then this function starts to become
526 // aggressive about ensuring that the process terminates.
528 // On Linux this method does not block the calling thread.
529 // On OS X this method may block for up to 2 seconds.
531 // NOTE: The process handle must have been opened with the PROCESS_TERMINATE
532 // and SYNCHRONIZE permissions.
534 BASE_EXPORT void EnsureProcessTerminated(ProcessHandle process_handle);
536 #if defined(OS_POSIX) && !defined(OS_MACOSX)
537 // The nicer version of EnsureProcessTerminated() that is patient and will
538 // wait for |process_handle| to finish and then reap it.
539 BASE_EXPORT void EnsureProcessGetsReaped(ProcessHandle process_handle);
540 #endif
542 // This class provides a way to iterate through a list of processes on the
543 // current machine with a specified filter.
544 // To use, create an instance and then call NextProcessEntry() until it returns
545 // false.
546 class BASE_EXPORT ProcessIterator {
547 public:
548 typedef std::list<ProcessEntry> ProcessEntries;
550 explicit ProcessIterator(const ProcessFilter* filter);
551 virtual ~ProcessIterator();
553 // If there's another process that matches the given executable name,
554 // returns a const pointer to the corresponding PROCESSENTRY32.
555 // If there are no more matching processes, returns NULL.
556 // The returned pointer will remain valid until NextProcessEntry()
557 // is called again or this NamedProcessIterator goes out of scope.
558 const ProcessEntry* NextProcessEntry();
560 // Takes a snapshot of all the ProcessEntry found.
561 ProcessEntries Snapshot();
563 protected:
564 virtual bool IncludeEntry();
565 const ProcessEntry& entry() { return entry_; }
567 private:
568 // Determines whether there's another process (regardless of executable)
569 // left in the list of all processes. Returns true and sets entry_ to
570 // that process's info if there is one, false otherwise.
571 bool CheckForNextProcess();
573 // Initializes a PROCESSENTRY32 data structure so that it's ready for
574 // use with Process32First/Process32Next.
575 void InitProcessEntry(ProcessEntry* entry);
577 #if defined(OS_WIN)
578 HANDLE snapshot_;
579 bool started_iteration_;
580 #elif defined(OS_MACOSX) || defined(OS_BSD)
581 std::vector<kinfo_proc> kinfo_procs_;
582 size_t index_of_kinfo_proc_;
583 #elif defined(OS_POSIX)
584 DIR *procfs_dir_;
585 #endif
586 ProcessEntry entry_;
587 const ProcessFilter* filter_;
589 DISALLOW_COPY_AND_ASSIGN(ProcessIterator);
592 // This class provides a way to iterate through the list of processes
593 // on the current machine that were started from the given executable
594 // name. To use, create an instance and then call NextProcessEntry()
595 // until it returns false.
596 class BASE_EXPORT NamedProcessIterator : public ProcessIterator {
597 public:
598 NamedProcessIterator(const FilePath::StringType& executable_name,
599 const ProcessFilter* filter);
600 virtual ~NamedProcessIterator();
602 protected:
603 virtual bool IncludeEntry() OVERRIDE;
605 private:
606 FilePath::StringType executable_name_;
608 DISALLOW_COPY_AND_ASSIGN(NamedProcessIterator);
611 // Working Set (resident) memory usage broken down by
613 // On Windows:
614 // priv (private): These pages (kbytes) cannot be shared with any other process.
615 // shareable: These pages (kbytes) can be shared with other processes under
616 // the right circumstances.
617 // shared : These pages (kbytes) are currently shared with at least one
618 // other process.
620 // On Linux:
621 // priv: Pages mapped only by this process
622 // shared: PSS or 0 if the kernel doesn't support this
623 // shareable: 0
625 // On OS X: TODO(thakis): Revise.
626 // priv: Memory.
627 // shared: 0
628 // shareable: 0
629 struct WorkingSetKBytes {
630 WorkingSetKBytes() : priv(0), shareable(0), shared(0) {}
631 size_t priv;
632 size_t shareable;
633 size_t shared;
636 // Committed (resident + paged) memory usage broken down by
637 // private: These pages cannot be shared with any other process.
638 // mapped: These pages are mapped into the view of a section (backed by
639 // pagefile.sys)
640 // image: These pages are mapped into the view of an image section (backed by
641 // file system)
642 struct CommittedKBytes {
643 CommittedKBytes() : priv(0), mapped(0), image(0) {}
644 size_t priv;
645 size_t mapped;
646 size_t image;
649 // Free memory (Megabytes marked as free) in the 2G process address space.
650 // total : total amount in megabytes marked as free. Maximum value is 2048.
651 // largest : size of the largest contiguous amount of memory found. It is
652 // always smaller or equal to FreeMBytes::total.
653 // largest_ptr: starting address of the largest memory block.
654 struct FreeMBytes {
655 size_t total;
656 size_t largest;
657 void* largest_ptr;
660 // Convert a POSIX timeval to microseconds.
661 BASE_EXPORT int64 TimeValToMicroseconds(const struct timeval& tv);
663 // Provides performance metrics for a specified process (CPU usage, memory and
664 // IO counters). To use it, invoke CreateProcessMetrics() to get an instance
665 // for a specific process, then access the information with the different get
666 // methods.
667 class BASE_EXPORT ProcessMetrics {
668 public:
669 ~ProcessMetrics();
671 // Creates a ProcessMetrics for the specified process.
672 // The caller owns the returned object.
673 #if !defined(OS_MACOSX)
674 static ProcessMetrics* CreateProcessMetrics(ProcessHandle process);
675 #else
676 class PortProvider {
677 public:
678 // Should return the mach task for |process| if possible, or else
679 // |MACH_PORT_NULL|. Only processes that this returns tasks for will have
680 // metrics on OS X (except for the current process, which always gets
681 // metrics).
682 virtual mach_port_t TaskForPid(ProcessHandle process) const = 0;
685 // The port provider needs to outlive the ProcessMetrics object returned by
686 // this function. If NULL is passed as provider, the returned object
687 // only returns valid metrics if |process| is the current process.
688 static ProcessMetrics* CreateProcessMetrics(ProcessHandle process,
689 PortProvider* port_provider);
690 #endif // !defined(OS_MACOSX)
692 // Returns the current space allocated for the pagefile, in bytes (these pages
693 // may or may not be in memory). On Linux, this returns the total virtual
694 // memory size.
695 size_t GetPagefileUsage() const;
696 // Returns the peak space allocated for the pagefile, in bytes.
697 size_t GetPeakPagefileUsage() const;
698 // Returns the current working set size, in bytes. On Linux, this returns
699 // the resident set size.
700 size_t GetWorkingSetSize() const;
701 // Returns the peak working set size, in bytes.
702 size_t GetPeakWorkingSetSize() const;
703 // Returns private and sharedusage, in bytes. Private bytes is the amount of
704 // memory currently allocated to a process that cannot be shared. Returns
705 // false on platform specific error conditions. Note: |private_bytes|
706 // returns 0 on unsupported OSes: prior to XP SP2.
707 bool GetMemoryBytes(size_t* private_bytes,
708 size_t* shared_bytes);
709 // Fills a CommittedKBytes with both resident and paged
710 // memory usage as per definition of CommittedBytes.
711 void GetCommittedKBytes(CommittedKBytes* usage) const;
712 // Fills a WorkingSetKBytes containing resident private and shared memory
713 // usage in bytes, as per definition of WorkingSetBytes.
714 bool GetWorkingSetKBytes(WorkingSetKBytes* ws_usage) const;
716 // Computes the current process available memory for allocation.
717 // It does a linear scan of the address space querying each memory region
718 // for its free (unallocated) status. It is useful for estimating the memory
719 // load and fragmentation.
720 bool CalculateFreeMemory(FreeMBytes* free) const;
722 // Returns the CPU usage in percent since the last time this method was
723 // called. The first time this method is called it returns 0 and will return
724 // the actual CPU info on subsequent calls.
725 // On Windows, the CPU usage value is for all CPUs. So if you have 2 CPUs and
726 // your process is using all the cycles of 1 CPU and not the other CPU, this
727 // method returns 50.
728 double GetCPUUsage();
730 // Retrieves accounting information for all I/O operations performed by the
731 // process.
732 // If IO information is retrieved successfully, the function returns true
733 // and fills in the IO_COUNTERS passed in. The function returns false
734 // otherwise.
735 bool GetIOCounters(IoCounters* io_counters) const;
737 private:
738 #if !defined(OS_MACOSX)
739 explicit ProcessMetrics(ProcessHandle process);
740 #else
741 ProcessMetrics(ProcessHandle process, PortProvider* port_provider);
742 #endif // defined(OS_MACOSX)
744 ProcessHandle process_;
746 int processor_count_;
748 // Used to store the previous times and CPU usage counts so we can
749 // compute the CPU usage between calls.
750 int64 last_time_;
751 int64 last_system_time_;
753 #if defined(OS_MACOSX)
754 // Queries the port provider if it's set.
755 mach_port_t TaskForPid(ProcessHandle process) const;
757 PortProvider* port_provider_;
758 #elif defined(OS_POSIX)
759 // Jiffie count at the last_time_ we updated.
760 int last_cpu_;
761 #endif // defined(OS_POSIX)
763 DISALLOW_COPY_AND_ASSIGN(ProcessMetrics);
766 #if defined(OS_LINUX) || defined(OS_ANDROID)
767 // Data from /proc/meminfo about system-wide memory consumption.
768 // Values are in KB.
769 struct SystemMemoryInfoKB {
770 SystemMemoryInfoKB() : total(0), free(0), buffers(0), cached(0),
771 active_anon(0), inactive_anon(0), shmem(0) {}
772 int total;
773 int free;
774 int buffers;
775 int cached;
776 int active_anon;
777 int inactive_anon;
778 int shmem;
780 // Retrieves data from /proc/meminfo about system-wide memory consumption.
781 // Fills in the provided |meminfo| structure. Returns true on success.
782 // Exposed for memory debugging widget.
783 BASE_EXPORT bool GetSystemMemoryInfo(SystemMemoryInfoKB* meminfo);
784 #endif // defined(OS_LINUX) || defined(OS_ANDROID)
786 // Returns the memory committed by the system in KBytes.
787 // Returns 0 if it can't compute the commit charge.
788 BASE_EXPORT size_t GetSystemCommitCharge();
790 // Enables low fragmentation heap (LFH) for every heaps of this process. This
791 // won't have any effect on heaps created after this function call. It will not
792 // modify data allocated in the heaps before calling this function. So it is
793 // better to call this function early in initialization and again before
794 // entering the main loop.
795 // Note: Returns true on Windows 2000 without doing anything.
796 BASE_EXPORT bool EnableLowFragmentationHeap();
798 // Enables 'terminate on heap corruption' flag. Helps protect against heap
799 // overflow. Has no effect if the OS doesn't provide the necessary facility.
800 BASE_EXPORT void EnableTerminationOnHeapCorruption();
802 // Turns on process termination if memory runs out.
803 BASE_EXPORT void EnableTerminationOnOutOfMemory();
805 #if defined(OS_MACOSX)
806 // Exposed for testing.
807 BASE_EXPORT malloc_zone_t* GetPurgeableZone();
808 #endif // defined(OS_MACOSX)
810 // Enables stack dump to console output on exception and signals.
811 // When enabled, the process will quit immediately. This is meant to be used in
812 // unit_tests only!
813 BASE_EXPORT bool EnableInProcessStackDumping();
815 // If supported on the platform, and the user has sufficent rights, increase
816 // the current process's scheduling priority to a high priority.
817 BASE_EXPORT void RaiseProcessToHighPriority();
819 #if defined(OS_MACOSX)
820 // Restore the default exception handler, setting it to Apple Crash Reporter
821 // (ReportCrash). When forking and execing a new process, the child will
822 // inherit the parent's exception ports, which may be set to the Breakpad
823 // instance running inside the parent. The parent's Breakpad instance should
824 // not handle the child's exceptions. Calling RestoreDefaultExceptionHandler
825 // in the child after forking will restore the standard exception handler.
826 // See http://crbug.com/20371/ for more details.
827 void RestoreDefaultExceptionHandler();
828 #endif // defined(OS_MACOSX)
830 } // namespace base
832 #endif // BASE_PROCESS_UTIL_H_