Add support for indeterminate checkbox on Windows classic theme.
[chromium-blink-merge.git] / base / process_util.h
blob54d8533ce61231f838dc8fbae25b5156764acfc4
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_
11 #include "base/basictypes.h"
12 #include "base/time.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/files/file_path.h"
41 #include "base/process.h"
43 #if defined(OS_POSIX)
44 #include "base/posix/file_descriptor_shuffle.h"
45 #endif
47 class CommandLine;
49 namespace base {
51 #if defined(OS_WIN)
52 struct 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; }
58 struct IoCounters : public IO_COUNTERS {
61 // Process access masks. These constants provide platform-independent
62 // definitions for the standard Windows access masks.
63 // See http://msdn.microsoft.com/en-us/library/ms684880(VS.85).aspx for
64 // the specific semantics of each mask value.
65 const uint32 kProcessAccessTerminate = PROCESS_TERMINATE;
66 const uint32 kProcessAccessCreateThread = PROCESS_CREATE_THREAD;
67 const uint32 kProcessAccessSetSessionId = PROCESS_SET_SESSIONID;
68 const uint32 kProcessAccessVMOperation = PROCESS_VM_OPERATION;
69 const uint32 kProcessAccessVMRead = PROCESS_VM_READ;
70 const uint32 kProcessAccessVMWrite = PROCESS_VM_WRITE;
71 const uint32 kProcessAccessDuplicateHandle = PROCESS_DUP_HANDLE;
72 const uint32 kProcessAccessCreateProcess = PROCESS_CREATE_PROCESS;
73 const uint32 kProcessAccessSetQuota = PROCESS_SET_QUOTA;
74 const uint32 kProcessAccessSetInformation = PROCESS_SET_INFORMATION;
75 const uint32 kProcessAccessQueryInformation = PROCESS_QUERY_INFORMATION;
76 const uint32 kProcessAccessSuspendResume = PROCESS_SUSPEND_RESUME;
77 const uint32 kProcessAccessQueryLimitedInfomation =
78 PROCESS_QUERY_LIMITED_INFORMATION;
79 const uint32 kProcessAccessWaitForTermination = SYNCHRONIZE;
80 #elif defined(OS_POSIX)
82 struct BASE_EXPORT ProcessEntry {
83 ProcessEntry();
84 ~ProcessEntry();
86 ProcessId pid() const { return pid_; }
87 ProcessId parent_pid() const { return ppid_; }
88 ProcessId gid() const { return gid_; }
89 const char* exe_file() const { return exe_file_.c_str(); }
90 const std::vector<std::string>& cmd_line_args() const {
91 return cmd_line_args_;
94 ProcessId pid_;
95 ProcessId ppid_;
96 ProcessId gid_;
97 std::string exe_file_;
98 std::vector<std::string> cmd_line_args_;
101 struct IoCounters {
102 uint64_t ReadOperationCount;
103 uint64_t WriteOperationCount;
104 uint64_t OtherOperationCount;
105 uint64_t ReadTransferCount;
106 uint64_t WriteTransferCount;
107 uint64_t OtherTransferCount;
110 // Process access masks. They are not used on Posix because access checking
111 // does not happen during handle creation.
112 const uint32 kProcessAccessTerminate = 0;
113 const uint32 kProcessAccessCreateThread = 0;
114 const uint32 kProcessAccessSetSessionId = 0;
115 const uint32 kProcessAccessVMOperation = 0;
116 const uint32 kProcessAccessVMRead = 0;
117 const uint32 kProcessAccessVMWrite = 0;
118 const uint32 kProcessAccessDuplicateHandle = 0;
119 const uint32 kProcessAccessCreateProcess = 0;
120 const uint32 kProcessAccessSetQuota = 0;
121 const uint32 kProcessAccessSetInformation = 0;
122 const uint32 kProcessAccessQueryInformation = 0;
123 const uint32 kProcessAccessSuspendResume = 0;
124 const uint32 kProcessAccessQueryLimitedInfomation = 0;
125 const uint32 kProcessAccessWaitForTermination = 0;
126 #endif // defined(OS_POSIX)
128 // Return status values from GetTerminationStatus. Don't use these as
129 // exit code arguments to KillProcess*(), use platform/application
130 // specific values instead.
131 enum TerminationStatus {
132 TERMINATION_STATUS_NORMAL_TERMINATION, // zero exit status
133 TERMINATION_STATUS_ABNORMAL_TERMINATION, // non-zero exit status
134 TERMINATION_STATUS_PROCESS_WAS_KILLED, // e.g. SIGKILL or task manager kill
135 TERMINATION_STATUS_PROCESS_CRASHED, // e.g. Segmentation fault
136 TERMINATION_STATUS_STILL_RUNNING, // child hasn't exited yet
137 TERMINATION_STATUS_MAX_ENUM
140 #if defined(USE_LINUX_BREAKPAD)
141 BASE_EXPORT extern size_t g_oom_size;
142 #endif
144 #if defined(OS_WIN)
145 // Output multi-process printf, cout, cerr, etc to the cmd.exe console that ran
146 // chrome. This is not thread-safe: only call from main thread.
147 BASE_EXPORT void RouteStdioToConsole();
148 #endif
150 // Returns the id of the current process.
151 BASE_EXPORT ProcessId GetCurrentProcId();
153 // Returns the ProcessHandle of the current process.
154 BASE_EXPORT ProcessHandle GetCurrentProcessHandle();
156 #if defined(OS_WIN)
157 // Returns the module handle to which an address belongs. The reference count
158 // of the module is not incremented.
159 BASE_EXPORT HMODULE GetModuleFromAddress(void* address);
160 #endif
162 // Converts a PID to a process handle. This handle must be closed by
163 // CloseProcessHandle when you are done with it. Returns true on success.
164 BASE_EXPORT bool OpenProcessHandle(ProcessId pid, ProcessHandle* handle);
166 // Converts a PID to a process handle. On Windows the handle is opened
167 // with more access rights and must only be used by trusted code.
168 // You have to close returned handle using CloseProcessHandle. Returns true
169 // on success.
170 // TODO(sanjeevr): Replace all calls to OpenPrivilegedProcessHandle with the
171 // more specific OpenProcessHandleWithAccess method and delete this.
172 BASE_EXPORT bool OpenPrivilegedProcessHandle(ProcessId pid,
173 ProcessHandle* handle);
175 // Converts a PID to a process handle using the desired access flags. Use a
176 // combination of the kProcessAccess* flags defined above for |access_flags|.
177 BASE_EXPORT bool OpenProcessHandleWithAccess(ProcessId pid,
178 uint32 access_flags,
179 ProcessHandle* handle);
181 // Closes the process handle opened by OpenProcessHandle.
182 BASE_EXPORT void CloseProcessHandle(ProcessHandle process);
184 // Returns the unique ID for the specified process. This is functionally the
185 // same as Windows' GetProcessId(), but works on versions of Windows before
186 // Win XP SP1 as well.
187 BASE_EXPORT ProcessId GetProcId(ProcessHandle process);
189 #if defined(OS_LINUX) || defined(OS_ANDROID) || defined(OS_BSD)
190 // Returns the path to the executable of the given process.
191 BASE_EXPORT FilePath GetProcessExecutablePath(ProcessHandle process);
192 #endif
194 #if defined(OS_LINUX) || defined(OS_ANDROID)
195 // Parse the data found in /proc/<pid>/stat and return the sum of the
196 // CPU-related ticks. Returns -1 on parse error.
197 // Exposed for testing.
198 BASE_EXPORT int ParseProcStatCPU(const std::string& input);
200 // Get the number of threads of |process| as available in /proc/<pid>/stat.
201 // This should be used with care as no synchronization with running threads is
202 // done. This is mostly useful to guarantee being single-threaded.
203 // Returns 0 on failure.
204 BASE_EXPORT int GetNumberOfThreads(ProcessHandle process);
206 // The maximum allowed value for the OOM score.
207 const int kMaxOomScore = 1000;
209 // This adjusts /proc/<pid>/oom_score_adj so the Linux OOM killer will
210 // prefer to kill certain process types over others. The range for the
211 // adjustment is [-1000, 1000], with [0, 1000] being user accessible.
212 // If the Linux system doesn't support the newer oom_score_adj range
213 // of [0, 1000], then we revert to using the older oom_adj, and
214 // translate the given value into [0, 15]. Some aliasing of values
215 // may occur in that case, of course.
216 BASE_EXPORT bool AdjustOOMScore(ProcessId process, int score);
218 // /proc/self/exe refers to the current executable.
219 BASE_EXPORT extern const char kProcSelfExe[];
220 #endif // defined(OS_LINUX) || defined(OS_ANDROID)
222 #if defined(OS_POSIX)
223 // Returns the ID for the parent of the given process.
224 BASE_EXPORT ProcessId GetParentProcessId(ProcessHandle process);
226 // Close all file descriptors, except those which are a destination in the
227 // given multimap. Only call this function in a child process where you know
228 // that there aren't any other threads.
229 BASE_EXPORT void CloseSuperfluousFds(const InjectiveMultimap& saved_map);
230 #endif // defined(OS_POSIX)
232 typedef std::vector<std::pair<std::string, std::string> > EnvironmentVector;
233 typedef std::vector<std::pair<int, int> > FileHandleMappingVector;
235 #if defined(OS_MACOSX)
236 // Used with LaunchOptions::synchronize and LaunchSynchronize, a
237 // LaunchSynchronizationHandle is an opaque value that LaunchProcess will
238 // create and set, and that LaunchSynchronize will consume and destroy.
239 typedef int* LaunchSynchronizationHandle;
240 #endif // defined(OS_MACOSX)
242 // Options for launching a subprocess that are passed to LaunchProcess().
243 // The default constructor constructs the object with default options.
244 struct LaunchOptions {
245 LaunchOptions()
246 : wait(false),
247 debug(false),
248 #if defined(OS_WIN)
249 start_hidden(false),
250 inherit_handles(false),
251 as_user(NULL),
252 empty_desktop_name(false),
253 job_handle(NULL),
254 stdin_handle(NULL),
255 stdout_handle(NULL),
256 stderr_handle(NULL),
257 force_breakaway_from_job_(false)
258 #else
259 environ(NULL),
260 fds_to_remap(NULL),
261 maximize_rlimits(NULL),
262 new_process_group(false)
263 #if defined(OS_LINUX)
264 , clone_flags(0)
265 #endif // OS_LINUX
266 #if defined(OS_CHROMEOS)
267 , ctrl_terminal_fd(-1)
268 #endif // OS_CHROMEOS
269 #if defined(OS_MACOSX)
270 , synchronize(NULL)
271 #endif // defined(OS_MACOSX)
272 #endif // !defined(OS_WIN)
275 // If true, wait for the process to complete.
276 bool wait;
278 // If true, print more debugging info (OS-dependent).
279 bool debug;
281 #if defined(OS_WIN)
282 bool start_hidden;
284 // If true, the new process inherits handles from the parent. In production
285 // code this flag should be used only when running short-lived, trusted
286 // binaries, because open handles from other libraries and subsystems will
287 // leak to the child process, causing errors such as open socket hangs.
288 bool inherit_handles;
290 // If non-NULL, runs as if the user represented by the token had launched it.
291 // Whether the application is visible on the interactive desktop depends on
292 // the token belonging to an interactive logon session.
294 // To avoid hard to diagnose problems, when specified this loads the
295 // environment variables associated with the user and if this operation fails
296 // the entire call fails as well.
297 UserTokenHandle as_user;
299 // If true, use an empty string for the desktop name.
300 bool empty_desktop_name;
302 // If non-NULL, launches the application in that job object. The process will
303 // be terminated immediately and LaunchProcess() will fail if assignment to
304 // the job object fails.
305 HANDLE job_handle;
307 // Handles for the redirection of stdin, stdout and stderr. The handles must
308 // be inheritable. Caller should either set all three of them or none (i.e.
309 // there is no way to redirect stderr without redirecting stdin). The
310 // |inherit_handles| flag must be set to true when redirecting stdio stream.
311 HANDLE stdin_handle;
312 HANDLE stdout_handle;
313 HANDLE stderr_handle;
315 // If set to true, ensures that the child process is launched with the
316 // CREATE_BREAKAWAY_FROM_JOB flag which allows it to breakout of the parent
317 // job if any.
318 bool force_breakaway_from_job_;
319 #else
320 // If non-NULL, set/unset environment variables.
321 // See documentation of AlterEnvironment().
322 // This pointer is owned by the caller and must live through the
323 // call to LaunchProcess().
324 const EnvironmentVector* environ;
326 // If non-NULL, remap file descriptors according to the mapping of
327 // src fd->dest fd to propagate FDs into the child process.
328 // This pointer is owned by the caller and must live through the
329 // call to LaunchProcess().
330 const FileHandleMappingVector* fds_to_remap;
332 // Each element is an RLIMIT_* constant that should be raised to its
333 // rlim_max. This pointer is owned by the caller and must live through
334 // the call to LaunchProcess().
335 const std::set<int>* maximize_rlimits;
337 // If true, start the process in a new process group, instead of
338 // inheriting the parent's process group. The pgid of the child process
339 // will be the same as its pid.
340 bool new_process_group;
342 #if defined(OS_LINUX)
343 // If non-zero, start the process using clone(), using flags as provided.
344 int clone_flags;
345 #endif // defined(OS_LINUX)
347 #if defined(OS_CHROMEOS)
348 // If non-negative, the specified file descriptor will be set as the launched
349 // process' controlling terminal.
350 int ctrl_terminal_fd;
351 #endif // defined(OS_CHROMEOS)
353 #if defined(OS_MACOSX)
354 // When non-NULL, a new LaunchSynchronizationHandle will be created and
355 // stored in *synchronize whenever LaunchProcess returns true in the parent
356 // process. The child process will have been created (with fork) but will
357 // be waiting (before exec) for the parent to call LaunchSynchronize with
358 // this handle. Only when LaunchSynchronize is called will the child be
359 // permitted to continue execution and call exec. LaunchSynchronize
360 // destroys the handle created by LaunchProcess.
362 // When synchronize is non-NULL, the parent must call LaunchSynchronize
363 // whenever LaunchProcess returns true. No exceptions.
365 // Synchronization is useful when the parent process needs to guarantee that
366 // it can take some action (such as recording the newly-forked child's
367 // process ID) before the child does something (such as using its process ID
368 // to communicate with its parent).
370 // |synchronize| and |wait| must not both be set simultaneously.
371 LaunchSynchronizationHandle* synchronize;
372 #endif // defined(OS_MACOSX)
374 #endif // !defined(OS_WIN)
377 // Launch a process via the command line |cmdline|.
378 // See the documentation of LaunchOptions for details on |options|.
380 // Returns true upon success.
382 // Upon success, if |process_handle| is non-NULL, it will be filled in with the
383 // handle of the launched process. NOTE: In this case, the caller is
384 // responsible for closing the handle so that it doesn't leak!
385 // Otherwise, the process handle will be implicitly closed.
387 // Unix-specific notes:
388 // - All file descriptors open in the parent process will be closed in the
389 // child process except for any preserved by options::fds_to_remap, and
390 // stdin, stdout, and stderr. If not remapped by options::fds_to_remap,
391 // stdin is reopened as /dev/null, and the child is allowed to inherit its
392 // parent's stdout and stderr.
393 // - If the first argument on the command line does not contain a slash,
394 // PATH will be searched. (See man execvp.)
395 BASE_EXPORT bool LaunchProcess(const CommandLine& cmdline,
396 const LaunchOptions& options,
397 ProcessHandle* process_handle);
399 #if defined(OS_WIN)
401 enum IntegrityLevel {
402 INTEGRITY_UNKNOWN,
403 LOW_INTEGRITY,
404 MEDIUM_INTEGRITY,
405 HIGH_INTEGRITY,
407 // Determine the integrity level of the specified process. Returns false
408 // if the system does not support integrity levels (pre-Vista) or in the case
409 // of an underlying system failure.
410 BASE_EXPORT bool GetProcessIntegrityLevel(ProcessHandle process,
411 IntegrityLevel* level);
413 // Windows-specific LaunchProcess that takes the command line as a
414 // string. Useful for situations where you need to control the
415 // command line arguments directly, but prefer the CommandLine version
416 // if launching Chrome itself.
418 // The first command line argument should be the path to the process,
419 // and don't forget to quote it.
421 // Example (including literal quotes)
422 // cmdline = "c:\windows\explorer.exe" -foo "c:\bar\"
423 BASE_EXPORT bool LaunchProcess(const string16& cmdline,
424 const LaunchOptions& options,
425 ProcessHandle* process_handle);
427 #elif defined(OS_POSIX)
428 // A POSIX-specific version of LaunchProcess that takes an argv array
429 // instead of a CommandLine. Useful for situations where you need to
430 // control the command line arguments directly, but prefer the
431 // CommandLine version if launching Chrome itself.
432 BASE_EXPORT bool LaunchProcess(const std::vector<std::string>& argv,
433 const LaunchOptions& options,
434 ProcessHandle* process_handle);
436 // AlterEnvironment returns a modified environment vector, constructed from the
437 // given environment and the list of changes given in |changes|. Each key in
438 // the environment is matched against the first element of the pairs. In the
439 // event of a match, the value is replaced by the second of the pair, unless
440 // the second is empty, in which case the key-value is removed.
442 // The returned array is allocated using new[] and must be freed by the caller.
443 BASE_EXPORT char** AlterEnvironment(const EnvironmentVector& changes,
444 const char* const* const env);
446 #if defined(OS_MACOSX)
448 // After a successful call to LaunchProcess with LaunchOptions::synchronize
449 // set, the parent process must call LaunchSynchronize to allow the child
450 // process to proceed, and to destroy the LaunchSynchronizationHandle.
451 BASE_EXPORT void LaunchSynchronize(LaunchSynchronizationHandle handle);
453 #endif // defined(OS_MACOSX)
454 #endif // defined(OS_POSIX)
456 #if defined(OS_WIN)
457 // Set JOBOBJECT_EXTENDED_LIMIT_INFORMATION to JobObject |job_object|.
458 // As its limit_info.BasicLimitInformation.LimitFlags has
459 // JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE.
460 // When the provide JobObject |job_object| is closed, the binded process will
461 // be terminated.
462 BASE_EXPORT bool SetJobObjectAsKillOnJobClose(HANDLE job_object);
463 #endif // defined(OS_WIN)
465 // Executes the application specified by |cl| and wait for it to exit. Stores
466 // the output (stdout) in |output|. Redirects stderr to /dev/null. Returns true
467 // on success (application launched and exited cleanly, with exit code
468 // indicating success).
469 BASE_EXPORT bool GetAppOutput(const CommandLine& cl, std::string* output);
471 #if defined(OS_POSIX)
472 // A POSIX-specific version of GetAppOutput that takes an argv array
473 // instead of a CommandLine. Useful for situations where you need to
474 // control the command line arguments directly.
475 BASE_EXPORT bool GetAppOutput(const std::vector<std::string>& argv,
476 std::string* output);
478 // A restricted version of |GetAppOutput()| which (a) clears the environment,
479 // and (b) stores at most |max_output| bytes; also, it doesn't search the path
480 // for the command.
481 BASE_EXPORT bool GetAppOutputRestricted(const CommandLine& cl,
482 std::string* output, size_t max_output);
484 // A version of |GetAppOutput()| which also returns the exit code of the
485 // executed command. Returns true if the application runs and exits cleanly. If
486 // this is the case the exit code of the application is available in
487 // |*exit_code|.
488 BASE_EXPORT bool GetAppOutputWithExitCode(const CommandLine& cl,
489 std::string* output, int* exit_code);
490 #endif // defined(OS_POSIX)
492 // Used to filter processes by process ID.
493 class ProcessFilter {
494 public:
495 // Returns true to indicate set-inclusion and false otherwise. This method
496 // should not have side-effects and should be idempotent.
497 virtual bool Includes(const ProcessEntry& entry) const = 0;
499 protected:
500 virtual ~ProcessFilter() {}
503 // Returns the number of processes on the machine that are running from the
504 // given executable name. If filter is non-null, then only processes selected
505 // by the filter will be counted.
506 BASE_EXPORT int GetProcessCount(const FilePath::StringType& executable_name,
507 const ProcessFilter* filter);
509 // Attempts to kill all the processes on the current machine that were launched
510 // from the given executable name, ending them with the given exit code. If
511 // filter is non-null, then only processes selected by the filter are killed.
512 // Returns true if all processes were able to be killed off, false if at least
513 // one couldn't be killed.
514 BASE_EXPORT bool KillProcesses(const FilePath::StringType& executable_name,
515 int exit_code, const ProcessFilter* filter);
517 // Attempts to kill the process identified by the given process
518 // entry structure, giving it the specified exit code. If |wait| is true, wait
519 // for the process to be actually terminated before returning.
520 // Returns true if this is successful, false otherwise.
521 BASE_EXPORT bool KillProcess(ProcessHandle process, int exit_code, bool wait);
523 #if defined(OS_POSIX)
524 // Attempts to kill the process group identified by |process_group_id|. Returns
525 // true on success.
526 BASE_EXPORT bool KillProcessGroup(ProcessHandle process_group_id);
527 #endif // defined(OS_POSIX)
529 #if defined(OS_WIN)
530 BASE_EXPORT bool KillProcessById(ProcessId process_id, int exit_code,
531 bool wait);
532 #endif // defined(OS_WIN)
534 // Get the termination status of the process by interpreting the
535 // circumstances of the child process' death. |exit_code| is set to
536 // the status returned by waitpid() on POSIX, and from
537 // GetExitCodeProcess() on Windows. |exit_code| may be NULL if the
538 // caller is not interested in it. Note that on Linux, this function
539 // will only return a useful result the first time it is called after
540 // the child exits (because it will reap the child and the information
541 // will no longer be available).
542 BASE_EXPORT TerminationStatus GetTerminationStatus(ProcessHandle handle,
543 int* exit_code);
545 #if defined(OS_POSIX)
546 // Wait for the process to exit and get the termination status. See
547 // GetTerminationStatus for more information. On POSIX systems, we can't call
548 // WaitForExitCode and then GetTerminationStatus as the child will be reaped
549 // when WaitForExitCode return and this information will be lost.
550 BASE_EXPORT TerminationStatus WaitForTerminationStatus(ProcessHandle handle,
551 int* exit_code);
552 #endif // defined(OS_POSIX)
554 // Waits for process to exit. On POSIX systems, if the process hasn't been
555 // signaled then puts the exit code in |exit_code|; otherwise it's considered
556 // a failure. On Windows |exit_code| is always filled. Returns true on success,
557 // and closes |handle| in any case.
558 BASE_EXPORT bool WaitForExitCode(ProcessHandle handle, int* exit_code);
560 // Waits for process to exit. If it did exit within |timeout_milliseconds|,
561 // then puts the exit code in |exit_code|, and returns true.
562 // In POSIX systems, if the process has been signaled then |exit_code| is set
563 // to -1. Returns false on failure (the caller is then responsible for closing
564 // |handle|).
565 // The caller is always responsible for closing the |handle|.
566 BASE_EXPORT bool WaitForExitCodeWithTimeout(ProcessHandle handle,
567 int* exit_code,
568 base::TimeDelta timeout);
570 // Wait for all the processes based on the named executable to exit. If filter
571 // is non-null, then only processes selected by the filter are waited on.
572 // Returns after all processes have exited or wait_milliseconds have expired.
573 // Returns true if all the processes exited, false otherwise.
574 BASE_EXPORT bool WaitForProcessesToExit(
575 const FilePath::StringType& executable_name,
576 base::TimeDelta wait,
577 const ProcessFilter* filter);
579 // Wait for a single process to exit. Return true if it exited cleanly within
580 // the given time limit. On Linux |handle| must be a child process, however
581 // on Mac and Windows it can be any process.
582 BASE_EXPORT bool WaitForSingleProcess(ProcessHandle handle,
583 base::TimeDelta wait);
585 // Waits a certain amount of time (can be 0) for all the processes with a given
586 // executable name to exit, then kills off any of them that are still around.
587 // If filter is non-null, then only processes selected by the filter are waited
588 // on. Killed processes are ended with the given exit code. Returns false if
589 // any processes needed to be killed, true if they all exited cleanly within
590 // the wait_milliseconds delay.
591 BASE_EXPORT bool CleanupProcesses(const FilePath::StringType& executable_name,
592 base::TimeDelta wait,
593 int exit_code,
594 const ProcessFilter* filter);
596 // This method ensures that the specified process eventually terminates, and
597 // then it closes the given process handle.
599 // It assumes that the process has already been signalled to exit, and it
600 // begins by waiting a small amount of time for it to exit. If the process
601 // does not appear to have exited, then this function starts to become
602 // aggressive about ensuring that the process terminates.
604 // On Linux this method does not block the calling thread.
605 // On OS X this method may block for up to 2 seconds.
607 // NOTE: The process handle must have been opened with the PROCESS_TERMINATE
608 // and SYNCHRONIZE permissions.
610 BASE_EXPORT void EnsureProcessTerminated(ProcessHandle process_handle);
612 #if defined(OS_POSIX) && !defined(OS_MACOSX)
613 // The nicer version of EnsureProcessTerminated() that is patient and will
614 // wait for |process_handle| to finish and then reap it.
615 BASE_EXPORT void EnsureProcessGetsReaped(ProcessHandle process_handle);
616 #endif
618 // This class provides a way to iterate through a list of processes on the
619 // current machine with a specified filter.
620 // To use, create an instance and then call NextProcessEntry() until it returns
621 // false.
622 class BASE_EXPORT ProcessIterator {
623 public:
624 typedef std::list<ProcessEntry> ProcessEntries;
626 explicit ProcessIterator(const ProcessFilter* filter);
627 virtual ~ProcessIterator();
629 // If there's another process that matches the given executable name,
630 // returns a const pointer to the corresponding PROCESSENTRY32.
631 // If there are no more matching processes, returns NULL.
632 // The returned pointer will remain valid until NextProcessEntry()
633 // is called again or this NamedProcessIterator goes out of scope.
634 const ProcessEntry* NextProcessEntry();
636 // Takes a snapshot of all the ProcessEntry found.
637 ProcessEntries Snapshot();
639 protected:
640 virtual bool IncludeEntry();
641 const ProcessEntry& entry() { return entry_; }
643 private:
644 // Determines whether there's another process (regardless of executable)
645 // left in the list of all processes. Returns true and sets entry_ to
646 // that process's info if there is one, false otherwise.
647 bool CheckForNextProcess();
649 // Initializes a PROCESSENTRY32 data structure so that it's ready for
650 // use with Process32First/Process32Next.
651 void InitProcessEntry(ProcessEntry* entry);
653 #if defined(OS_WIN)
654 HANDLE snapshot_;
655 bool started_iteration_;
656 #elif defined(OS_MACOSX) || defined(OS_BSD)
657 std::vector<kinfo_proc> kinfo_procs_;
658 size_t index_of_kinfo_proc_;
659 #elif defined(OS_POSIX)
660 DIR* procfs_dir_;
661 #endif
662 ProcessEntry entry_;
663 const ProcessFilter* filter_;
665 DISALLOW_COPY_AND_ASSIGN(ProcessIterator);
668 // This class provides a way to iterate through the list of processes
669 // on the current machine that were started from the given executable
670 // name. To use, create an instance and then call NextProcessEntry()
671 // until it returns false.
672 class BASE_EXPORT NamedProcessIterator : public ProcessIterator {
673 public:
674 NamedProcessIterator(const FilePath::StringType& executable_name,
675 const ProcessFilter* filter);
676 virtual ~NamedProcessIterator();
678 protected:
679 virtual bool IncludeEntry() OVERRIDE;
681 private:
682 FilePath::StringType executable_name_;
684 DISALLOW_COPY_AND_ASSIGN(NamedProcessIterator);
687 // Working Set (resident) memory usage broken down by
689 // On Windows:
690 // priv (private): These pages (kbytes) cannot be shared with any other process.
691 // shareable: These pages (kbytes) can be shared with other processes under
692 // the right circumstances.
693 // shared : These pages (kbytes) are currently shared with at least one
694 // other process.
696 // On Linux:
697 // priv: Pages mapped only by this process
698 // shared: PSS or 0 if the kernel doesn't support this
699 // shareable: 0
701 // On OS X: TODO(thakis): Revise.
702 // priv: Memory.
703 // shared: 0
704 // shareable: 0
705 struct WorkingSetKBytes {
706 WorkingSetKBytes() : priv(0), shareable(0), shared(0) {}
707 size_t priv;
708 size_t shareable;
709 size_t shared;
712 // Committed (resident + paged) memory usage broken down by
713 // private: These pages cannot be shared with any other process.
714 // mapped: These pages are mapped into the view of a section (backed by
715 // pagefile.sys)
716 // image: These pages are mapped into the view of an image section (backed by
717 // file system)
718 struct CommittedKBytes {
719 CommittedKBytes() : priv(0), mapped(0), image(0) {}
720 size_t priv;
721 size_t mapped;
722 size_t image;
725 // Free memory (Megabytes marked as free) in the 2G process address space.
726 // total : total amount in megabytes marked as free. Maximum value is 2048.
727 // largest : size of the largest contiguous amount of memory found. It is
728 // always smaller or equal to FreeMBytes::total.
729 // largest_ptr: starting address of the largest memory block.
730 struct FreeMBytes {
731 size_t total;
732 size_t largest;
733 void* largest_ptr;
736 // Convert a POSIX timeval to microseconds.
737 BASE_EXPORT int64 TimeValToMicroseconds(const struct timeval& tv);
739 // Provides performance metrics for a specified process (CPU usage, memory and
740 // IO counters). To use it, invoke CreateProcessMetrics() to get an instance
741 // for a specific process, then access the information with the different get
742 // methods.
743 class BASE_EXPORT ProcessMetrics {
744 public:
745 ~ProcessMetrics();
747 // Creates a ProcessMetrics for the specified process.
748 // The caller owns the returned object.
749 #if !defined(OS_MACOSX) || defined(OS_IOS)
750 static ProcessMetrics* CreateProcessMetrics(ProcessHandle process);
751 #else
752 class PortProvider {
753 public:
754 virtual ~PortProvider() {}
756 // Should return the mach task for |process| if possible, or else
757 // |MACH_PORT_NULL|. Only processes that this returns tasks for will have
758 // metrics on OS X (except for the current process, which always gets
759 // metrics).
760 virtual mach_port_t TaskForPid(ProcessHandle process) const = 0;
763 // The port provider needs to outlive the ProcessMetrics object returned by
764 // this function. If NULL is passed as provider, the returned object
765 // only returns valid metrics if |process| is the current process.
766 static ProcessMetrics* CreateProcessMetrics(ProcessHandle process,
767 PortProvider* port_provider);
768 #endif // !defined(OS_MACOSX) || defined(OS_IOS)
770 // Returns the current space allocated for the pagefile, in bytes (these pages
771 // may or may not be in memory). On Linux, this returns the total virtual
772 // memory size.
773 size_t GetPagefileUsage() const;
774 // Returns the peak space allocated for the pagefile, in bytes.
775 size_t GetPeakPagefileUsage() const;
776 // Returns the current working set size, in bytes. On Linux, this returns
777 // the resident set size.
778 size_t GetWorkingSetSize() const;
779 // Returns the peak working set size, in bytes.
780 size_t GetPeakWorkingSetSize() const;
781 // Returns private and sharedusage, in bytes. Private bytes is the amount of
782 // memory currently allocated to a process that cannot be shared. Returns
783 // false on platform specific error conditions. Note: |private_bytes|
784 // returns 0 on unsupported OSes: prior to XP SP2.
785 bool GetMemoryBytes(size_t* private_bytes,
786 size_t* shared_bytes);
787 // Fills a CommittedKBytes with both resident and paged
788 // memory usage as per definition of CommittedBytes.
789 void GetCommittedKBytes(CommittedKBytes* usage) const;
790 // Fills a WorkingSetKBytes containing resident private and shared memory
791 // usage in bytes, as per definition of WorkingSetBytes.
792 bool GetWorkingSetKBytes(WorkingSetKBytes* ws_usage) const;
794 // Computes the current process available memory for allocation.
795 // It does a linear scan of the address space querying each memory region
796 // for its free (unallocated) status. It is useful for estimating the memory
797 // load and fragmentation.
798 bool CalculateFreeMemory(FreeMBytes* free) const;
800 // Returns the CPU usage in percent since the last time this method was
801 // called. The first time this method is called it returns 0 and will return
802 // the actual CPU info on subsequent calls.
803 // On Windows, the CPU usage value is for all CPUs. So if you have 2 CPUs and
804 // your process is using all the cycles of 1 CPU and not the other CPU, this
805 // method returns 50.
806 double GetCPUUsage();
808 // Retrieves accounting information for all I/O operations performed by the
809 // process.
810 // If IO information is retrieved successfully, the function returns true
811 // and fills in the IO_COUNTERS passed in. The function returns false
812 // otherwise.
813 bool GetIOCounters(IoCounters* io_counters) const;
815 private:
816 #if !defined(OS_MACOSX) || defined(OS_IOS)
817 explicit ProcessMetrics(ProcessHandle process);
818 #else
819 ProcessMetrics(ProcessHandle process, PortProvider* port_provider);
820 #endif // !defined(OS_MACOSX) || defined(OS_IOS)
822 ProcessHandle process_;
824 int processor_count_;
826 // Used to store the previous times and CPU usage counts so we can
827 // compute the CPU usage between calls.
828 int64 last_time_;
829 int64 last_system_time_;
831 #if !defined(OS_IOS)
832 #if defined(OS_MACOSX)
833 // Queries the port provider if it's set.
834 mach_port_t TaskForPid(ProcessHandle process) const;
836 PortProvider* port_provider_;
837 #elif defined(OS_POSIX)
838 // Jiffie count at the last_time_ we updated.
839 int last_cpu_;
840 #endif // defined(OS_POSIX)
841 #endif // !defined(OS_IOS)
843 DISALLOW_COPY_AND_ASSIGN(ProcessMetrics);
846 #if defined(OS_LINUX) || defined(OS_ANDROID)
847 // Data from /proc/meminfo about system-wide memory consumption.
848 // Values are in KB.
849 struct BASE_EXPORT SystemMemoryInfoKB {
850 SystemMemoryInfoKB();
852 int total;
853 int free;
854 int buffers;
855 int cached;
856 int active_anon;
857 int inactive_anon;
858 int active_file;
859 int inactive_file;
860 int shmem;
862 // Gem data will be -1 if not supported.
863 int gem_objects;
864 long long gem_size;
866 // Retrieves data from /proc/meminfo about system-wide memory consumption.
867 // Fills in the provided |meminfo| structure. Returns true on success.
868 // Exposed for memory debugging widget.
869 BASE_EXPORT bool GetSystemMemoryInfo(SystemMemoryInfoKB* meminfo);
870 #endif // defined(OS_LINUX) || defined(OS_ANDROID)
872 // Returns the memory committed by the system in KBytes.
873 // Returns 0 if it can't compute the commit charge.
874 BASE_EXPORT size_t GetSystemCommitCharge();
876 // Enables low fragmentation heap (LFH) for every heaps of this process. This
877 // won't have any effect on heaps created after this function call. It will not
878 // modify data allocated in the heaps before calling this function. So it is
879 // better to call this function early in initialization and again before
880 // entering the main loop.
881 // Note: Returns true on Windows 2000 without doing anything.
882 BASE_EXPORT bool EnableLowFragmentationHeap();
884 // Enables 'terminate on heap corruption' flag. Helps protect against heap
885 // overflow. Has no effect if the OS doesn't provide the necessary facility.
886 BASE_EXPORT void EnableTerminationOnHeapCorruption();
888 // Turns on process termination if memory runs out.
889 BASE_EXPORT void EnableTerminationOnOutOfMemory();
891 // If supported on the platform, and the user has sufficent rights, increase
892 // the current process's scheduling priority to a high priority.
893 BASE_EXPORT void RaiseProcessToHighPriority();
895 #if defined(OS_MACOSX)
896 // Restore the default exception handler, setting it to Apple Crash Reporter
897 // (ReportCrash). When forking and execing a new process, the child will
898 // inherit the parent's exception ports, which may be set to the Breakpad
899 // instance running inside the parent. The parent's Breakpad instance should
900 // not handle the child's exceptions. Calling RestoreDefaultExceptionHandler
901 // in the child after forking will restore the standard exception handler.
902 // See http://crbug.com/20371/ for more details.
903 void RestoreDefaultExceptionHandler();
904 #endif // defined(OS_MACOSX)
906 #if defined(OS_MACOSX)
907 // Very large images or svg canvases can cause huge mallocs. Skia
908 // does tricks on tcmalloc-based systems to allow malloc to fail with
909 // a NULL rather than hit the oom crasher. This replicates that for
910 // OSX.
912 // IF YOU USE THIS WITHOUT CONSULTING YOUR FRIENDLY OSX DEVELOPER,
913 // YOUR CODE IS LIKELY TO BE REVERTED. THANK YOU.
915 // TODO(shess): Weird place to put it, but this is where the OOM
916 // killer currently lives.
917 BASE_EXPORT void* UncheckedMalloc(size_t size);
918 #endif // defined(OS_MACOSX)
920 } // namespace base
922 #endif // BASE_PROCESS_UTIL_H_