[go: nahoru, domu]

blob: dac063576fed7cb3eca4a733ba480e44c106e0e9 [file] [log] [blame]
erg@google.coma502bbe72011-01-07 18:06:451// Copyright (c) 2011 The Chromium Authors. All rights reserved.
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commitd7cae122008-07-26 21:49:384
5// This file/namespace contains utility functions for enumerating, ending and
6// computing statistics of processes.
7
deanm@google.comdb717282008-08-27 13:48:038#ifndef BASE_PROCESS_UTIL_H_
9#define BASE_PROCESS_UTIL_H_
thakis@chromium.org32b76ef2010-07-26 23:08:2410#pragma once
initial.commitd7cae122008-07-26 21:49:3811
paulg@google.com61659062008-08-06 01:04:1812#include "base/basictypes.h"
13
dkegel@google.comab0e2222008-10-31 20:19:4314#if defined(OS_WIN)
initial.commitd7cae122008-07-26 21:49:3815#include <windows.h>
16#include <tlhelp32.h>
wtc@chromium.org4a34ce02009-08-31 22:25:0017#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;
avi@chromium.org6cfa3392010-07-01 20:11:4321// 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;
thakis@chromium.orgc0028792010-01-12 00:39:1524#include <mach/mach.h>
wtc@chromium.org4a34ce02009-08-31 22:25:0025#elif defined(OS_POSIX)
dkegel@google.comab0e2222008-10-31 20:19:4326#include <dirent.h>
27#include <limits.h>
28#include <sys/types.h>
paulg@google.com61659062008-08-06 01:04:1829#endif
initial.commitd7cae122008-07-26 21:49:3830
maruel@chromium.orgb6128aa2010-04-29 17:44:4231#include <list>
paulg@google.com61659062008-08-06 01:04:1832#include <string>
thestig@chromium.org9ec8db02009-07-21 07:00:1333#include <utility>
mark@chromium.org962dd312009-02-05 21:44:1334#include <vector>
paulg@google.com61659062008-08-06 01:04:1835
rvargas@google.comf5661ca2011-03-24 19:00:2036#include "base/base_api.h"
maruel@chromium.orga5a00b1d2010-04-08 15:52:4537#include "base/file_descriptor_shuffle.h"
avi@chromium.org4f260d02010-12-23 18:35:4238#include "base/file_path.h"
initial.commitd7cae122008-07-26 21:49:3839#include "base/process.h"
40
erg@google.com5d91c9e2010-07-28 17:25:2841class CommandLine;
erg@google.com5d91c9e2010-07-28 17:25:2842
maruel@chromium.orga5a00b1d2010-04-08 15:52:4543namespace base {
44
paulg@google.com61659062008-08-06 01:04:1845#if defined(OS_WIN)
maruel@chromium.orga5a00b1d2010-04-08 15:52:4546struct ProcessEntry : public PROCESSENTRY32 {
maruel@chromium.orgb6128aa2010-04-29 17:44:4247 ProcessId pid() const { return th32ProcessID; }
48 ProcessId parent_pid() const { return th32ParentProcessID; }
49 const wchar_t* exe_file() const { return szExeFile; }
maruel@chromium.orga5a00b1d2010-04-08 15:52:4550};
maruel@chromium.orgb6128aa2010-04-29 17:44:4251
maruel@chromium.orga5a00b1d2010-04-08 15:52:4552struct IoCounters : public IO_COUNTERS {
53};
54
sanjeevr@chromium.org7d11f6d52010-10-12 21:44:2355// Process access masks. These constants provide platform-independent
56// definitions for the standard Windows access masks.
57// See http://msdn.microsoft.com/en-us/library/ms684880(VS.85).aspx for
58// the specific semantics of each mask value.
59const uint32 kProcessAccessTerminate = PROCESS_TERMINATE;
60const uint32 kProcessAccessCreateThread = PROCESS_CREATE_THREAD;
61const uint32 kProcessAccessSetSessionId = PROCESS_SET_SESSIONID;
62const uint32 kProcessAccessVMOperation = PROCESS_VM_OPERATION;
63const uint32 kProcessAccessVMRead = PROCESS_VM_READ;
64const uint32 kProcessAccessVMWrite = PROCESS_VM_WRITE;
65const uint32 kProcessAccessDuplicateHandle = PROCESS_DUP_HANDLE;
66const uint32 kProcessAccessCreateProcess = PROCESS_CREATE_PROCESS;
67const uint32 kProcessAccessSetQuota = PROCESS_SET_QUOTA;
68const uint32 kProcessAccessSetInformation = PROCESS_SET_INFORMATION;
69const uint32 kProcessAccessQueryInformation = PROCESS_QUERY_INFORMATION;
70const uint32 kProcessAccessSuspendResume = PROCESS_SUSPEND_RESUME;
71const uint32 kProcessAccessQueryLimitedInfomation =
72 PROCESS_QUERY_LIMITED_INFORMATION;
73const uint32 kProcessAccessWaitForTermination = SYNCHRONIZE;
paulg@google.com61659062008-08-06 01:04:1874#elif defined(OS_POSIX)
maruel@chromium.orga5a00b1d2010-04-08 15:52:4575
dkegel@google.comab0e2222008-10-31 20:19:4376struct ProcessEntry {
erg@google.combbf94a32010-10-13 17:44:1577 ProcessEntry();
78 ~ProcessEntry();
79
maruel@chromium.orgb6128aa2010-04-29 17:44:4280 ProcessId pid() const { return pid_; }
81 ProcessId parent_pid() const { return ppid_; }
rsimha@chromium.orgc47d81d2010-10-05 23:41:0482 ProcessId gid() const { return gid_; }
maruel@chromium.orgb6128aa2010-04-29 17:44:4283 const char* exe_file() const { return exe_file_.c_str(); }
rsimha@chromium.orgc47d81d2010-10-05 23:41:0484 const std::vector<std::string>& cmd_line_args() const {
85 return cmd_line_args_;
86 }
erg@google.coma502bbe72011-01-07 18:06:4587
88 ProcessId pid_;
89 ProcessId ppid_;
90 ProcessId gid_;
91 std::string exe_file_;
92 std::vector<std::string> cmd_line_args_;
dkegel@google.comab0e2222008-10-31 20:19:4393};
94
evanm@google.com0b100bc82008-10-14 20:49:1695struct IoCounters {
evan@chromium.org34b2b002009-11-20 06:53:2896 uint64_t ReadOperationCount;
97 uint64_t WriteOperationCount;
98 uint64_t OtherOperationCount;
99 uint64_t ReadTransferCount;
100 uint64_t WriteTransferCount;
101 uint64_t OtherTransferCount;
evanm@google.com0b100bc82008-10-14 20:49:16102};
agl@chromium.org3f04f2b2009-04-30 19:40:03103
sanjeevr@chromium.org7d11f6d52010-10-12 21:44:23104// Process access masks. They are not used on Posix because access checking
105// does not happen during handle creation.
106const uint32 kProcessAccessTerminate = 0;
107const uint32 kProcessAccessCreateThread = 0;
108const uint32 kProcessAccessSetSessionId = 0;
109const uint32 kProcessAccessVMOperation = 0;
110const uint32 kProcessAccessVMRead = 0;
111const uint32 kProcessAccessVMWrite = 0;
112const uint32 kProcessAccessDuplicateHandle = 0;
113const uint32 kProcessAccessCreateProcess = 0;
114const uint32 kProcessAccessSetQuota = 0;
115const uint32 kProcessAccessSetInformation = 0;
116const uint32 kProcessAccessQueryInformation = 0;
117const uint32 kProcessAccessSuspendResume = 0;
118const uint32 kProcessAccessQueryLimitedInfomation = 0;
119const uint32 kProcessAccessWaitForTermination = 0;
maruel@chromium.orga5a00b1d2010-04-08 15:52:45120#endif // defined(OS_POSIX)
initial.commitd7cae122008-07-26 21:49:38121
gspencer@chromium.org443b80e2010-12-14 00:42:23122// Return status values from GetTerminationStatus. Don't use these as
123// exit code arguments to KillProcess*(), use platform/application
124// specific values instead.
125enum TerminationStatus {
126 TERMINATION_STATUS_NORMAL_TERMINATION, // zero exit status
127 TERMINATION_STATUS_ABNORMAL_TERMINATION, // non-zero exit status
128 TERMINATION_STATUS_PROCESS_WAS_KILLED, // e.g. SIGKILL or task manager kill
129 TERMINATION_STATUS_PROCESS_CRASHED, // e.g. Segmentation fault
130 TERMINATION_STATUS_STILL_RUNNING // child hasn't exited yet
cpu@google.comeef576f2008-11-03 23:28:06131};
132
initial.commitd7cae122008-07-26 21:49:38133// Returns the id of the current process.
rvargas@google.com26fbf802011-03-25 18:48:03134BASE_API ProcessId GetCurrentProcId();
initial.commitd7cae122008-07-26 21:49:38135
erikkay@google.com113ab132008-09-18 20:42:55136// Returns the ProcessHandle of the current process.
rvargas@google.com26fbf802011-03-25 18:48:03137BASE_API ProcessHandle GetCurrentProcessHandle();
maruel@chromium.org52a261f2009-03-03 15:01:12138
brettw@google.com5986ed22009-02-06 00:19:17139// Converts a PID to a process handle. This handle must be closed by
phajdan.jr@chromium.org6c6cc802009-04-03 17:01:36140// CloseProcessHandle when you are done with it. Returns true on success.
rvargas@google.com26fbf802011-03-25 18:48:03141BASE_API bool OpenProcessHandle(ProcessId pid, ProcessHandle* handle);
maruel@chromium.org52a261f2009-03-03 15:01:12142
phajdan.jr@chromium.org5d438dbad2009-04-30 08:59:39143// Converts a PID to a process handle. On Windows the handle is opened
144// with more access rights and must only be used by trusted code.
145// You have to close returned handle using CloseProcessHandle. Returns true
146// on success.
sanjeevr@chromium.org7d11f6d52010-10-12 21:44:23147// TODO(sanjeevr): Replace all calls to OpenPrivilegedProcessHandle with the
148// more specific OpenProcessHandleWithAccess method and delete this.
rvargas@google.com26fbf802011-03-25 18:48:03149BASE_API bool OpenPrivilegedProcessHandle(ProcessId pid, ProcessHandle* handle);
phajdan.jr@chromium.org5d438dbad2009-04-30 08:59:39150
sanjeevr@chromium.org7d11f6d52010-10-12 21:44:23151// Converts a PID to a process handle using the desired access flags. Use a
152// combination of the kProcessAccess* flags defined above for |access_flags|.
rvargas@google.com26fbf802011-03-25 18:48:03153BASE_API bool OpenProcessHandleWithAccess(ProcessId pid,
154 uint32 access_flags,
155 ProcessHandle* handle);
sanjeevr@chromium.org7d11f6d52010-10-12 21:44:23156
brettw@google.com5986ed22009-02-06 00:19:17157// Closes the process handle opened by OpenProcessHandle.
rvargas@google.com26fbf802011-03-25 18:48:03158BASE_API void CloseProcessHandle(ProcessHandle process);
erikkay@google.com113ab132008-09-18 20:42:55159
cpu@google.comeef576f2008-11-03 23:28:06160// Returns the unique ID for the specified process. This is functionally the
initial.commitd7cae122008-07-26 21:49:38161// same as Windows' GetProcessId(), but works on versions of Windows before
162// Win XP SP1 as well.
rvargas@google.com26fbf802011-03-25 18:48:03163BASE_API ProcessId GetProcId(ProcessHandle process);
initial.commitd7cae122008-07-26 21:49:38164
dkegel@google.com78c6dd62009-06-08 23:29:11165#if defined(OS_LINUX)
dkegel@google.com78c6dd62009-06-08 23:29:11166// Returns the path to the executable of the given process.
167FilePath GetProcessExecutablePath(ProcessHandle process);
evan@chromium.orgd2ed23832009-09-19 01:57:39168
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);
thestig@chromium.orge5856a7a2009-12-10 02:08:10173
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);
dkegel@google.com78c6dd62009-06-08 23:29:11180#endif
181
jeremy@chromium.orgfa3097a6a52008-12-17 22:41:50182#if defined(OS_POSIX)
dmaclach@chromium.org56f0f262011-02-24 17:14:36183// Returns the ID for the parent of the given process.
184ProcessId GetParentProcessId(ProcessHandle process);
185
gspencer@chromium.org443b80e2010-12-14 00:42:23186// Close all file descriptors, except those which are a destination in the
agl@chromium.org3f04f2b2009-04-30 19:40:03187// given multimap. Only call this function in a child process where you know
188// that there aren't any other threads.
maruel@chromium.orgb6128aa2010-04-29 17:44:42189void CloseSuperfluousFds(const InjectiveMultimap& saved_map);
jeremy@chromium.orgfa3097a6a52008-12-17 22:41:50190#endif
191
estade@chromium.orgfb7f9be2008-10-22 01:15:47192#if defined(OS_WIN)
tommi@chromium.org48dc9e12010-08-26 19:49:57193
194enum IntegrityLevel {
195 INTEGRITY_UNKNOWN,
196 LOW_INTEGRITY,
197 MEDIUM_INTEGRITY,
198 HIGH_INTEGRITY,
199};
200// Determine the integrity level of the specified process. Returns false
201// if the system does not support integrity levels (pre-Vista) or in the case
202// of an underlying system failure.
rvargas@google.com26fbf802011-03-25 18:48:03203BASE_API bool GetProcessIntegrityLevel(ProcessHandle process,
204 IntegrityLevel *level);
tommi@chromium.org48dc9e12010-08-26 19:49:57205
initial.commitd7cae122008-07-26 21:49:38206// Runs the given application name with the given command line. Normally, the
207// first command line argument should be the path to the process, and don't
208// forget to quote it.
209//
210// If wait is true, it will block and wait for the other process to finish,
211// otherwise, it will just continue asynchronously.
212//
213// Example (including literal quotes)
214// cmdline = "c:\windows\explorer.exe" -foo "c:\bar\"
215//
216// If process_handle is non-NULL, the process handle of the launched app will be
217// stored there on a successful launch.
218// NOTE: In this case, the caller is responsible for closing the handle so
219// that it doesn't leak!
rvargas@google.com26fbf802011-03-25 18:48:03220BASE_API bool LaunchApp(const std::wstring& cmdline,
221 bool wait, bool start_hidden,
222 ProcessHandle* process_handle);
cpu@chromium.orge50130b2010-02-01 03:28:47223
finnur@chromium.org81e32602010-09-07 14:01:31224// Same as LaunchApp, except allows the new process to inherit handles of the
225// parent process.
rvargas@google.com26fbf802011-03-25 18:48:03226BASE_API bool LaunchAppWithHandleInheritance(const std::wstring& cmdline,
227 bool wait, bool start_hidden,
228 ProcessHandle* process_handle);
finnur@chromium.org81e32602010-09-07 14:01:31229
cpu@chromium.orge50130b2010-02-01 03:28:47230// Runs the given application name with the given command line as if the user
231// represented by |token| had launched it. The caveats about |cmdline| and
232// |process_handle| explained for LaunchApp above apply as well.
233//
234// Whether the application is visible on the interactive desktop depends on
235// the token belonging to an interactive logon session.
236//
237// To avoid hard to diagnose problems, this function internally loads the
238// environment variables associated with the user and if this operation fails
239// the entire call fails as well.
rvargas@google.com26fbf802011-03-25 18:48:03240BASE_API bool LaunchAppAsUser(UserTokenHandle token,
241 const std::wstring& cmdline,
242 bool start_hidden,
243 ProcessHandle* process_handle);
cpu@chromium.orge50130b2010-02-01 03:28:47244
gwilson@google.comc020ddc2010-02-18 23:01:52245// Has the same behavior as LaunchAppAsUser, but offers the boolean option to
finnur@chromium.org81e32602010-09-07 14:01:31246// use an empty string for the desktop name and a boolean for allowing the
247// child process to inherit handles from its parent.
rvargas@google.com26fbf802011-03-25 18:48:03248BASE_API bool LaunchAppAsUser(UserTokenHandle token,
249 const std::wstring& cmdline,
250 bool start_hidden, ProcessHandle* process_handle,
251 bool empty_desktop_name, bool inherit_handles);
gwilson@google.comc020ddc2010-02-18 23:01:52252
253
estade@chromium.orgfb7f9be2008-10-22 01:15:47254#elif defined(OS_POSIX)
255// Runs the application specified in argv[0] with the command line argv.
jeremy@chromium.orgfa3097a6a52008-12-17 22:41:50256// Before launching all FDs open in the parent process will be marked as
257// close-on-exec. |fds_to_remap| defines a mapping of src fd->dest fd to
258// propagate FDs into the child process.
estade@chromium.orgfb7f9be2008-10-22 01:15:47259//
260// As above, if wait is true, execute synchronously. The pid will be stored
261// in process_handle if that pointer is non-null.
262//
mattm@chromium.orgb74d21b32009-07-17 19:36:00263// Note that the first argument in argv must point to the executable filename.
264// If the filename is not fully specified, PATH will be searched.
jeremy@chromium.orgfa3097a6a52008-12-17 22:41:50265typedef std::vector<std::pair<int, int> > file_handle_mapping_vector;
estade@chromium.orgfb7f9be2008-10-22 01:15:47266bool LaunchApp(const std::vector<std::string>& argv,
jeremy@chromium.orgfa3097a6a52008-12-17 22:41:50267 const file_handle_mapping_vector& fds_to_remap,
estade@chromium.orgfb7f9be2008-10-22 01:15:47268 bool wait, ProcessHandle* process_handle);
stuartmorgan@google.com2aea9e092009-08-06 20:03:01269
thakis@chromium.orgc0028792010-01-12 00:39:15270// Similar to the above, but also (un)set environment variables in child process
thestig@chromium.org9ec8db02009-07-21 07:00:13271// through |environ|.
jam@chromium.org3d2217d2009-11-23 21:26:47272typedef std::vector<std::pair<std::string, std::string> > environment_vector;
thestig@chromium.org9ec8db02009-07-21 07:00:13273bool LaunchApp(const std::vector<std::string>& argv,
274 const environment_vector& environ,
275 const file_handle_mapping_vector& fds_to_remap,
276 bool wait, ProcessHandle* process_handle);
thakis@chromium.orgc0028792010-01-12 00:39:15277
rsimha@chromium.org61b93f88f2010-09-22 17:28:30278// Similar to the above two methods, but starts the child process in a process
279// group of its own, instead of allowing it to inherit the parent's process
280// group. The pgid of the child process will be the same as its pid.
281bool LaunchAppInNewProcessGroup(const std::vector<std::string>& argv,
282 const environment_vector& environ,
283 const file_handle_mapping_vector& fds_to_remap,
284 bool wait, ProcessHandle* process_handle);
285
agl@chromium.orgef73044e2010-03-11 15:25:54286// AlterEnvironment returns a modified environment vector, constructed from the
287// given environment and the list of changes given in |changes|. Each key in
288// the environment is matched against the first element of the pairs. In the
289// event of a match, the value is replaced by the second of the pair, unless
290// the second is empty, in which case the key-value is removed.
291//
292// The returned array is allocated using new[] and must be freed by the caller.
293char** AlterEnvironment(const environment_vector& changes,
294 const char* const* const env);
thestig@chromium.org9ec8db02009-07-21 07:00:13295#endif // defined(OS_POSIX)
estade@chromium.orgfb7f9be2008-10-22 01:15:47296
jcampan@chromium.org1e312112009-04-21 21:44:12297// Executes the application specified by cl. This function delegates to one
estade@chromium.orgfb7f9be2008-10-22 01:15:47298// of the above two platform-specific functions.
rvargas@google.com26fbf802011-03-25 18:48:03299BASE_API bool LaunchApp(const CommandLine& cl, bool wait, bool start_hidden,
300 ProcessHandle* process_handle);
initial.commitd7cae122008-07-26 21:49:38301
jcampan@chromium.org1e312112009-04-21 21:44:12302// Executes the application specified by |cl| and wait for it to exit. Stores
phajdan.jr@chromium.org1912cfe2009-04-21 08:09:30303// the output (stdout) in |output|. Redirects stderr to /dev/null. Returns true
304// on success (application launched and exited cleanly, with exit code
maruel@chromium.org96878a212010-06-10 18:26:33305// indicating success).
rvargas@google.com26fbf802011-03-25 18:48:03306BASE_API bool GetAppOutput(const CommandLine& cl, std::string* output);
phajdan.jr@chromium.orgc0b210ee2009-04-17 09:57:52307
viettrungluu@chromium.orgf164cea2009-11-05 23:37:40308#if defined(OS_POSIX)
309// A restricted version of |GetAppOutput()| which (a) clears the environment,
310// and (b) stores at most |max_output| bytes; also, it doesn't search the path
311// for the command.
312bool GetAppOutputRestricted(const CommandLine& cl,
313 std::string* output, size_t max_output);
314#endif
315
initial.commitd7cae122008-07-26 21:49:38316// Used to filter processes by process ID.
317class ProcessFilter {
318 public:
319 // Returns true to indicate set-inclusion and false otherwise. This method
320 // should not have side-effects and should be idempotent.
maruel@chromium.orgb6128aa2010-04-29 17:44:42321 virtual bool Includes(const ProcessEntry& entry) const = 0;
ziadh@chromium.org695092f2010-08-02 16:34:16322
323 protected:
324 virtual ~ProcessFilter() {}
initial.commitd7cae122008-07-26 21:49:38325};
326
327// Returns the number of processes on the machine that are running from the
328// given executable name. If filter is non-null, then only processes selected
329// by the filter will be counted.
rvargas@google.com26fbf802011-03-25 18:48:03330BASE_API int GetProcessCount(const FilePath::StringType& executable_name,
331 const ProcessFilter* filter);
initial.commitd7cae122008-07-26 21:49:38332
333// Attempts to kill all the processes on the current machine that were launched
334// from the given executable name, ending them with the given exit code. If
335// filter is non-null, then only processes selected by the filter are killed.
rsimha@chromium.org61b93f88f2010-09-22 17:28:30336// Returns true if all processes were able to be killed off, false if at least
initial.commitd7cae122008-07-26 21:49:38337// one couldn't be killed.
rvargas@google.com26fbf802011-03-25 18:48:03338BASE_API bool KillProcesses(const FilePath::StringType& executable_name,
339 int exit_code, const ProcessFilter* filter);
initial.commitd7cae122008-07-26 21:49:38340
341// Attempts to kill the process identified by the given process
342// entry structure, giving it the specified exit code. If |wait| is true, wait
343// for the process to be actually terminated before returning.
344// Returns true if this is successful, false otherwise.
rvargas@google.com26fbf802011-03-25 18:48:03345BASE_API bool KillProcess(ProcessHandle process, int exit_code, bool wait);
rsimha@chromium.org61b93f88f2010-09-22 17:28:30346
347#if defined(OS_POSIX)
348// Attempts to kill the process group identified by |process_group_id|. Returns
349// true on success.
350bool KillProcessGroup(ProcessHandle process_group_id);
351#endif
352
agl@chromium.orgdfe14862009-01-22 01:23:11353#if defined(OS_WIN)
rvargas@google.com26fbf802011-03-25 18:48:03354BASE_API bool KillProcessById(ProcessId process_id, int exit_code, bool wait);
agl@chromium.orgdfe14862009-01-22 01:23:11355#endif
initial.commitd7cae122008-07-26 21:49:38356
gspencer@chromium.org443b80e2010-12-14 00:42:23357// Get the termination status of the process by interpreting the
358// circumstances of the child process' death. |exit_code| is set to
359// the status returned by waitpid() on POSIX, and from
360// GetExitCodeProcess() on Windows. |exit_code| may be NULL if the
361// caller is not interested in it. Note that on Linux, this function
362// will only return a useful result the first time it is called after
363// the child exits (because it will reap the child and the information
364// will no longer be available).
rvargas@google.com26fbf802011-03-25 18:48:03365BASE_API TerminationStatus GetTerminationStatus(ProcessHandle handle,
366 int* exit_code);
initial.commitd7cae122008-07-26 21:49:38367
dmaclach@chromium.org56f0f262011-02-24 17:14:36368// Waits for process to exit. On POSIX systems, if the process hasn't been
phajdan.jr@chromium.orgc7856632009-01-13 17:38:49369// signaled then puts the exit code in |exit_code|; otherwise it's considered
370// a failure. On Windows |exit_code| is always filled. Returns true on success,
371// and closes |handle| in any case.
rvargas@google.com26fbf802011-03-25 18:48:03372BASE_API bool WaitForExitCode(ProcessHandle handle, int* exit_code);
phajdan.jr@chromium.orgc7856632009-01-13 17:38:49373
phajdan.jr@chromium.org8004e682010-03-16 07:41:22374// Waits for process to exit. If it did exit within |timeout_milliseconds|,
375// then puts the exit code in |exit_code|, closes |handle|, and returns true.
376// In POSIX systems, if the process has been signaled then |exit_code| is set
377// to -1. Returns false on failure (the caller is then responsible for closing
378// |handle|).
rvargas@google.com26fbf802011-03-25 18:48:03379BASE_API bool WaitForExitCodeWithTimeout(ProcessHandle handle, int* exit_code,
380 int64 timeout_milliseconds);
phajdan.jr@chromium.org8004e682010-03-16 07:41:22381
initial.commitd7cae122008-07-26 21:49:38382// Wait for all the processes based on the named executable to exit. If filter
383// is non-null, then only processes selected by the filter are waited on.
384// Returns after all processes have exited or wait_milliseconds have expired.
385// Returns true if all the processes exited, false otherwise.
rvargas@google.com26fbf802011-03-25 18:48:03386BASE_API bool WaitForProcessesToExit(
387 const FilePath::StringType& executable_name,
388 int64 wait_milliseconds,
389 const ProcessFilter* filter);
initial.commitd7cae122008-07-26 21:49:38390
estade@chromium.orgfb7f9be2008-10-22 01:15:47391// Wait for a single process to exit. Return true if it exited cleanly within
dmaclach@chromium.org56f0f262011-02-24 17:14:36392// the given time limit. On Linux |handle| must be a child process, however
393// on Mac and Windows it can be any process.
rvargas@google.com26fbf802011-03-25 18:48:03394BASE_API bool WaitForSingleProcess(ProcessHandle handle,
395 int64 wait_milliseconds);
estade@chromium.orgfb7f9be2008-10-22 01:15:47396
phajdan.jr@chromium.org076bf0b62009-03-04 20:57:58397// Returns true when |wait_milliseconds| have elapsed and the process
398// is still running.
rvargas@google.com26fbf802011-03-25 18:48:03399BASE_API bool CrashAwareSleep(ProcessHandle handle, int64 wait_milliseconds);
phajdan.jr@chromium.org076bf0b62009-03-04 20:57:58400
initial.commitd7cae122008-07-26 21:49:38401// Waits a certain amount of time (can be 0) for all the processes with a given
402// executable name to exit, then kills off any of them that are still around.
403// If filter is non-null, then only processes selected by the filter are waited
404// on. Killed processes are ended with the given exit code. Returns false if
405// any processes needed to be killed, true if they all exited cleanly within
406// the wait_milliseconds delay.
rvargas@google.com26fbf802011-03-25 18:48:03407BASE_API bool CleanupProcesses(const FilePath::StringType& executable_name,
408 int64 wait_milliseconds,
409 int exit_code,
410 const ProcessFilter* filter);
initial.commitd7cae122008-07-26 21:49:38411
maruel@chromium.orgb6128aa2010-04-29 17:44:42412// This class provides a way to iterate through a list of processes on the
413// current machine with a specified filter.
414// To use, create an instance and then call NextProcessEntry() until it returns
415// false.
rvargas@google.com26fbf802011-03-25 18:48:03416class BASE_API ProcessIterator {
initial.commitd7cae122008-07-26 21:49:38417 public:
maruel@chromium.orgbaead4f2010-06-11 19:10:30418 typedef std::list<ProcessEntry> ProcessEntries;
419
maruel@chromium.orgb6128aa2010-04-29 17:44:42420 explicit ProcessIterator(const ProcessFilter* filter);
421 virtual ~ProcessIterator();
initial.commitd7cae122008-07-26 21:49:38422
423 // If there's another process that matches the given executable name,
424 // returns a const pointer to the corresponding PROCESSENTRY32.
425 // If there are no more matching processes, returns NULL.
426 // The returned pointer will remain valid until NextProcessEntry()
427 // is called again or this NamedProcessIterator goes out of scope.
428 const ProcessEntry* NextProcessEntry();
429
maruel@chromium.orgb6128aa2010-04-29 17:44:42430 // Takes a snapshot of all the ProcessEntry found.
maruel@chromium.orgbaead4f2010-06-11 19:10:30431 ProcessEntries Snapshot();
maruel@chromium.orgb6128aa2010-04-29 17:44:42432
433 protected:
434 virtual bool IncludeEntry();
435 const ProcessEntry& entry() { return entry_; }
436
initial.commitd7cae122008-07-26 21:49:38437 private:
438 // Determines whether there's another process (regardless of executable)
439 // left in the list of all processes. Returns true and sets entry_ to
440 // that process's info if there is one, false otherwise.
441 bool CheckForNextProcess();
442
initial.commitd7cae122008-07-26 21:49:38443 // Initializes a PROCESSENTRY32 data structure so that it's ready for
444 // use with Process32First/Process32Next.
445 void InitProcessEntry(ProcessEntry* entry);
dkegel@google.comab0e2222008-10-31 20:19:43446
447#if defined(OS_WIN)
initial.commitd7cae122008-07-26 21:49:38448 HANDLE snapshot_;
initial.commitd7cae122008-07-26 21:49:38449 bool started_iteration_;
dkegel@google.comab0e2222008-10-31 20:19:43450#elif defined(OS_MACOSX)
mark@chromium.org962dd312009-02-05 21:44:13451 std::vector<kinfo_proc> kinfo_procs_;
452 size_t index_of_kinfo_proc_;
wtc@chromium.org4a34ce02009-08-31 22:25:00453#elif defined(OS_POSIX)
454 DIR *procfs_dir_;
dkegel@google.comab0e2222008-10-31 20:19:43455#endif
initial.commitd7cae122008-07-26 21:49:38456 ProcessEntry entry_;
457 const ProcessFilter* filter_;
458
maruel@chromium.orgb6128aa2010-04-29 17:44:42459 DISALLOW_COPY_AND_ASSIGN(ProcessIterator);
460};
461
462// This class provides a way to iterate through the list of processes
463// on the current machine that were started from the given executable
464// name. To use, create an instance and then call NextProcessEntry()
465// until it returns false.
rvargas@google.com26fbf802011-03-25 18:48:03466class BASE_API NamedProcessIterator : public ProcessIterator {
maruel@chromium.orgb6128aa2010-04-29 17:44:42467 public:
avi@chromium.org4f260d02010-12-23 18:35:42468 NamedProcessIterator(const FilePath::StringType& executable_name,
maruel@chromium.orgb6128aa2010-04-29 17:44:42469 const ProcessFilter* filter);
470 virtual ~NamedProcessIterator();
471
472 protected:
473 virtual bool IncludeEntry();
474
475 private:
avi@chromium.org4f260d02010-12-23 18:35:42476 FilePath::StringType executable_name_;
maruel@chromium.orgb6128aa2010-04-29 17:44:42477
478 DISALLOW_COPY_AND_ASSIGN(NamedProcessIterator);
initial.commitd7cae122008-07-26 21:49:38479};
480
481// Working Set (resident) memory usage broken down by
agl@chromium.org54fd1d32009-09-01 00:12:58482//
483// On Windows:
initial.commitd7cae122008-07-26 21:49:38484// priv (private): These pages (kbytes) cannot be shared with any other process.
485// shareable: These pages (kbytes) can be shared with other processes under
486// the right circumstances.
487// shared : These pages (kbytes) are currently shared with at least one
488// other process.
agl@chromium.org54fd1d32009-09-01 00:12:58489//
490// On Linux:
491// priv: Pages mapped only by this process
492// shared: PSS or 0 if the kernel doesn't support this
493// shareable: 0
viettrungluu@chromium.org3740cb9b52009-12-19 04:50:04494//
495// On OS X: TODO(thakis): Revise.
496// priv: Memory.
497// shared: 0
498// shareable: 0
initial.commitd7cae122008-07-26 21:49:38499struct WorkingSetKBytes {
agl@chromium.org54fd1d32009-09-01 00:12:58500 WorkingSetKBytes() : priv(0), shareable(0), shared(0) {}
initial.commitd7cae122008-07-26 21:49:38501 size_t priv;
502 size_t shareable;
503 size_t shared;
504};
505
506// Committed (resident + paged) memory usage broken down by
507// private: These pages cannot be shared with any other process.
508// mapped: These pages are mapped into the view of a section (backed by
509// pagefile.sys)
510// image: These pages are mapped into the view of an image section (backed by
511// file system)
512struct CommittedKBytes {
agl@chromium.org54fd1d32009-09-01 00:12:58513 CommittedKBytes() : priv(0), mapped(0), image(0) {}
initial.commitd7cae122008-07-26 21:49:38514 size_t priv;
515 size_t mapped;
516 size_t image;
517};
518
519// Free memory (Megabytes marked as free) in the 2G process address space.
520// total : total amount in megabytes marked as free. Maximum value is 2048.
521// largest : size of the largest contiguous amount of memory found. It is
522// always smaller or equal to FreeMBytes::total.
523// largest_ptr: starting address of the largest memory block.
524struct FreeMBytes {
525 size_t total;
526 size_t largest;
527 void* largest_ptr;
528};
529
evan@chromium.orgd2ed23832009-09-19 01:57:39530// Convert a POSIX timeval to microseconds.
rvargas@google.com26fbf802011-03-25 18:48:03531BASE_API int64 TimeValToMicroseconds(const struct timeval& tv);
evan@chromium.orgd2ed23832009-09-19 01:57:39532
initial.commitd7cae122008-07-26 21:49:38533// Provides performance metrics for a specified process (CPU usage, memory and
534// IO counters). To use it, invoke CreateProcessMetrics() to get an instance
535// for a specific process, then access the information with the different get
536// methods.
rvargas@google.com26fbf802011-03-25 18:48:03537class BASE_API ProcessMetrics {
initial.commitd7cae122008-07-26 21:49:38538 public:
erg@google.coma502bbe72011-01-07 18:06:45539 ~ProcessMetrics();
540
initial.commitd7cae122008-07-26 21:49:38541 // Creates a ProcessMetrics for the specified process.
542 // The caller owns the returned object.
viettrungluu@chromium.org3740cb9b52009-12-19 04:50:04543#if !defined(OS_MACOSX)
initial.commitd7cae122008-07-26 21:49:38544 static ProcessMetrics* CreateProcessMetrics(ProcessHandle process);
viettrungluu@chromium.org3740cb9b52009-12-19 04:50:04545#else
546 class PortProvider {
547 public:
thakis@chromium.orgb2e8e082009-12-21 17:44:20548 // Should return the mach task for |process| if possible, or else
549 // |MACH_PORT_NULL|. Only processes that this returns tasks for will have
550 // metrics on OS X (except for the current process, which always gets
551 // metrics).
viettrungluu@chromium.org3740cb9b52009-12-19 04:50:04552 virtual mach_port_t TaskForPid(ProcessHandle process) const = 0;
553 };
554
555 // The port provider needs to outlive the ProcessMetrics object returned by
556 // this function. If NULL is passed as provider, the returned object
557 // only returns valid metrics if |process| is the current process.
558 static ProcessMetrics* CreateProcessMetrics(ProcessHandle process,
559 PortProvider* port_provider);
maruel@chromium.orgb6128aa2010-04-29 17:44:42560#endif // !defined(OS_MACOSX)
initial.commitd7cae122008-07-26 21:49:38561
562 // Returns the current space allocated for the pagefile, in bytes (these pages
thomasvl@chromium.org796da7c2009-06-11 12:45:45563 // may or may not be in memory). On Linux, this returns the total virtual
564 // memory size.
phajdan.jr@chromium.orgd043c2cc2009-03-25 18:30:45565 size_t GetPagefileUsage() const;
initial.commitd7cae122008-07-26 21:49:38566 // Returns the peak space allocated for the pagefile, in bytes.
phajdan.jr@chromium.orgd043c2cc2009-03-25 18:30:45567 size_t GetPeakPagefileUsage() const;
thomasvl@chromium.org796da7c2009-06-11 12:45:45568 // Returns the current working set size, in bytes. On Linux, this returns
569 // the resident set size.
phajdan.jr@chromium.orgd043c2cc2009-03-25 18:30:45570 size_t GetWorkingSetSize() const;
tc@google.com0c557f12009-05-11 23:35:52571 // Returns the peak working set size, in bytes.
572 size_t GetPeakWorkingSetSize() const;
erg@chromium.org98947a02010-05-11 17:46:08573 // Returns private and sharedusage, in bytes. Private bytes is the amount of
574 // memory currently allocated to a process that cannot be shared. Returns
575 // false on platform specific error conditions. Note: |private_bytes|
576 // returns 0 on unsupported OSes: prior to XP SP2.
577 bool GetMemoryBytes(size_t* private_bytes,
578 size_t* shared_bytes);
initial.commitd7cae122008-07-26 21:49:38579 // Fills a CommittedKBytes with both resident and paged
580 // memory usage as per definition of CommittedBytes.
phajdan.jr@chromium.orgd043c2cc2009-03-25 18:30:45581 void GetCommittedKBytes(CommittedKBytes* usage) const;
initial.commitd7cae122008-07-26 21:49:38582 // Fills a WorkingSetKBytes containing resident private and shared memory
583 // usage in bytes, as per definition of WorkingSetBytes.
phajdan.jr@chromium.orgd043c2cc2009-03-25 18:30:45584 bool GetWorkingSetKBytes(WorkingSetKBytes* ws_usage) const;
initial.commitd7cae122008-07-26 21:49:38585
586 // Computes the current process available memory for allocation.
587 // It does a linear scan of the address space querying each memory region
588 // for its free (unallocated) status. It is useful for estimating the memory
589 // load and fragmentation.
phajdan.jr@chromium.orgd043c2cc2009-03-25 18:30:45590 bool CalculateFreeMemory(FreeMBytes* free) const;
initial.commitd7cae122008-07-26 21:49:38591
592 // Returns the CPU usage in percent since the last time this method was
593 // called. The first time this method is called it returns 0 and will return
594 // the actual CPU info on subsequent calls.
thakis@chromium.org022eab62010-01-13 04:55:06595 // On Windows, the CPU usage value is for all CPUs. So if you have 2 CPUs and
596 // your process is using all the cycles of 1 CPU and not the other CPU, this
597 // method returns 50.
598 double GetCPUUsage();
initial.commitd7cae122008-07-26 21:49:38599
600 // Retrieves accounting information for all I/O operations performed by the
601 // process.
602 // If IO information is retrieved successfully, the function returns true
603 // and fills in the IO_COUNTERS passed in. The function returns false
604 // otherwise.
phajdan.jr@chromium.orgd043c2cc2009-03-25 18:30:45605 bool GetIOCounters(IoCounters* io_counters) const;
initial.commitd7cae122008-07-26 21:49:38606
607 private:
viettrungluu@chromium.org3740cb9b52009-12-19 04:50:04608#if !defined(OS_MACOSX)
initial.commitd7cae122008-07-26 21:49:38609 explicit ProcessMetrics(ProcessHandle process);
viettrungluu@chromium.org3740cb9b52009-12-19 04:50:04610#else
611 ProcessMetrics(ProcessHandle process, PortProvider* port_provider);
maruel@chromium.orgb6128aa2010-04-29 17:44:42612#endif // !defined(OS_MACOSX)
initial.commitd7cae122008-07-26 21:49:38613
614 ProcessHandle process_;
615
616 int processor_count_;
617
evan@chromium.orgd2ed23832009-09-19 01:57:39618 // Used to store the previous times and CPU usage counts so we can
619 // compute the CPU usage between calls.
initial.commitd7cae122008-07-26 21:49:38620 int64 last_time_;
621 int64 last_system_time_;
622
viettrungluu@chromium.org3740cb9b52009-12-19 04:50:04623#if defined(OS_MACOSX)
624 // Queries the port provider if it's set.
625 mach_port_t TaskForPid(ProcessHandle process) const;
626
627 PortProvider* port_provider_;
pvalchev@google.com66700d42010-03-10 07:46:43628#elif defined(OS_POSIX)
629 // Jiffie count at the last_time_ we updated.
630 int last_cpu_;
maruel@chromium.orgb6128aa2010-04-29 17:44:42631#endif // defined(OS_MACOSX)
viettrungluu@chromium.org3740cb9b52009-12-19 04:50:04632
maruel@chromium.orgb6128aa2010-04-29 17:44:42633 DISALLOW_COPY_AND_ASSIGN(ProcessMetrics);
initial.commitd7cae122008-07-26 21:49:38634};
635
sgk@chromium.orged26d942009-11-09 06:57:28636// Returns the memory commited by the system in KBytes.
637// Returns 0 if it can't compute the commit charge.
rvargas@google.com26fbf802011-03-25 18:48:03638BASE_API size_t GetSystemCommitCharge();
sgk@chromium.orged26d942009-11-09 06:57:28639
initial.commitd7cae122008-07-26 21:49:38640// Enables low fragmentation heap (LFH) for every heaps of this process. This
641// won't have any effect on heaps created after this function call. It will not
642// modify data allocated in the heaps before calling this function. So it is
643// better to call this function early in initialization and again before
644// entering the main loop.
645// Note: Returns true on Windows 2000 without doing anything.
rvargas@google.com26fbf802011-03-25 18:48:03646BASE_API bool EnableLowFragmentationHeap();
initial.commitd7cae122008-07-26 21:49:38647
maruel@chromium.orgd6fc9fd2009-10-27 18:03:47648// Enables 'terminate on heap corruption' flag. Helps protect against heap
maruel@google.comc9d40872008-09-24 12:58:37649// overflow. Has no effect if the OS doesn't provide the necessary facility.
rvargas@google.comf5661ca2011-03-24 19:00:20650BASE_API void EnableTerminationOnHeapCorruption();
maruel@google.comc9d40872008-09-24 12:58:37651
avi@chromium.orgcccb21212009-11-12 20:39:56652#if !defined(OS_WIN)
653// Turns on process termination if memory runs out. This is handled on Windows
654// inside RegisterInvalidParamHandler().
655void EnableTerminationOnOutOfMemory();
avi@chromium.org6cfa3392010-07-01 20:11:43656#if defined(OS_MACOSX)
657// Exposed for testing.
658malloc_zone_t* GetPurgeableZone();
659#endif
avi@chromium.orgcccb21212009-11-12 20:39:56660#endif
661
maruel@chromium.orgd6fc9fd2009-10-27 18:03:47662// Enables stack dump to console output on exception and signals.
663// When enabled, the process will quit immediately. This is meant to be used in
664// unit_tests only!
rvargas@google.com26fbf802011-03-25 18:48:03665BASE_API bool EnableInProcessStackDumping();
maruel@chromium.orgd6fc9fd2009-10-27 18:03:47666
deanm@google.comdb717282008-08-27 13:48:03667// If supported on the platform, and the user has sufficent rights, increase
668// the current process's scheduling priority to a high priority.
rvargas@google.com26fbf802011-03-25 18:48:03669BASE_API void RaiseProcessToHighPriority();
deanm@google.comdb717282008-08-27 13:48:03670
mark@chromium.orge9a8c19f2009-09-03 21:27:36671#if defined(OS_MACOSX)
672// Restore the default exception handler, setting it to Apple Crash Reporter
673// (ReportCrash). When forking and execing a new process, the child will
674// inherit the parent's exception ports, which may be set to the Breakpad
675// instance running inside the parent. The parent's Breakpad instance should
676// not handle the child's exceptions. Calling RestoreDefaultExceptionHandler
677// in the child after forking will restore the standard exception handler.
678// See http://crbug.com/20371/ for more details.
679void RestoreDefaultExceptionHandler();
maruel@chromium.orgb6128aa2010-04-29 17:44:42680#endif // defined(OS_MACOSX)
mark@chromium.orge9a8c19f2009-09-03 21:27:36681
brettw@google.com176aa482008-11-14 03:25:15682} // namespace base
initial.commitd7cae122008-07-26 21:49:38683
deanm@google.comdb717282008-08-27 13:48:03684#endif // BASE_PROCESS_UTIL_H_