[go: nahoru, domu]

blob: 057590312a27a3a4f5dfe983c5c9f50ec57abebc [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
scheib@chromium.orgbcb2c772011-04-01 20:20:53130 TERMINATION_STATUS_STILL_RUNNING, // child hasn't exited yet
131 TERMINATION_STATUS_MAX_ENUM
cpu@google.comeef576f2008-11-03 23:28:06132};
133
initial.commitd7cae122008-07-26 21:49:38134// Returns the id of the current process.
rvargas@google.com26fbf802011-03-25 18:48:03135BASE_API ProcessId GetCurrentProcId();
initial.commitd7cae122008-07-26 21:49:38136
erikkay@google.com113ab132008-09-18 20:42:55137// Returns the ProcessHandle of the current process.
rvargas@google.com26fbf802011-03-25 18:48:03138BASE_API ProcessHandle GetCurrentProcessHandle();
maruel@chromium.org52a261f2009-03-03 15:01:12139
brettw@google.com5986ed22009-02-06 00:19:17140// Converts a PID to a process handle. This handle must be closed by
phajdan.jr@chromium.org6c6cc802009-04-03 17:01:36141// CloseProcessHandle when you are done with it. Returns true on success.
rvargas@google.com26fbf802011-03-25 18:48:03142BASE_API bool OpenProcessHandle(ProcessId pid, ProcessHandle* handle);
maruel@chromium.org52a261f2009-03-03 15:01:12143
phajdan.jr@chromium.org5d438dbad2009-04-30 08:59:39144// Converts a PID to a process handle. On Windows the handle is opened
145// with more access rights and must only be used by trusted code.
146// You have to close returned handle using CloseProcessHandle. Returns true
147// on success.
sanjeevr@chromium.org7d11f6d52010-10-12 21:44:23148// TODO(sanjeevr): Replace all calls to OpenPrivilegedProcessHandle with the
149// more specific OpenProcessHandleWithAccess method and delete this.
rvargas@google.com26fbf802011-03-25 18:48:03150BASE_API bool OpenPrivilegedProcessHandle(ProcessId pid, ProcessHandle* handle);
phajdan.jr@chromium.org5d438dbad2009-04-30 08:59:39151
sanjeevr@chromium.org7d11f6d52010-10-12 21:44:23152// Converts a PID to a process handle using the desired access flags. Use a
153// combination of the kProcessAccess* flags defined above for |access_flags|.
rvargas@google.com26fbf802011-03-25 18:48:03154BASE_API bool OpenProcessHandleWithAccess(ProcessId pid,
155 uint32 access_flags,
156 ProcessHandle* handle);
sanjeevr@chromium.org7d11f6d52010-10-12 21:44:23157
brettw@google.com5986ed22009-02-06 00:19:17158// Closes the process handle opened by OpenProcessHandle.
rvargas@google.com26fbf802011-03-25 18:48:03159BASE_API void CloseProcessHandle(ProcessHandle process);
erikkay@google.com113ab132008-09-18 20:42:55160
cpu@google.comeef576f2008-11-03 23:28:06161// Returns the unique ID for the specified process. This is functionally the
initial.commitd7cae122008-07-26 21:49:38162// same as Windows' GetProcessId(), but works on versions of Windows before
163// Win XP SP1 as well.
rvargas@google.com26fbf802011-03-25 18:48:03164BASE_API ProcessId GetProcId(ProcessHandle process);
initial.commitd7cae122008-07-26 21:49:38165
dkegel@google.com78c6dd62009-06-08 23:29:11166#if defined(OS_LINUX)
dkegel@google.com78c6dd62009-06-08 23:29:11167// Returns the path to the executable of the given process.
evan@chromium.org68a008e2011-05-02 17:54:14168BASE_API FilePath GetProcessExecutablePath(ProcessHandle process);
evan@chromium.orgd2ed23832009-09-19 01:57:39169
170// Parse the data found in /proc/<pid>/stat and return the sum of the
171// CPU-related ticks. Returns -1 on parse error.
172// Exposed for testing.
evan@chromium.org91d91fa2011-04-29 20:45:22173BASE_API int ParseProcStatCPU(const std::string& input);
thestig@chromium.orge5856a7a2009-12-10 02:08:10174
175static const char kAdjustOOMScoreSwitch[] = "--adjust-oom-score";
176
177// This adjusts /proc/process/oom_adj so the Linux OOM killer will prefer
178// certain process types over others. The range for the adjustment is
179// [-17,15], with [0,15] being user accessible.
evan@chromium.org68a008e2011-05-02 17:54:14180BASE_API bool AdjustOOMScore(ProcessId process, int score);
dkegel@google.com78c6dd62009-06-08 23:29:11181#endif
182
jeremy@chromium.orgfa3097a6a52008-12-17 22:41:50183#if defined(OS_POSIX)
dmaclach@chromium.org56f0f262011-02-24 17:14:36184// Returns the ID for the parent of the given process.
evan@chromium.org91d91fa2011-04-29 20:45:22185BASE_API ProcessId GetParentProcessId(ProcessHandle process);
dmaclach@chromium.org56f0f262011-02-24 17:14:36186
gspencer@chromium.org443b80e2010-12-14 00:42:23187// Close all file descriptors, except those which are a destination in the
agl@chromium.org3f04f2b2009-04-30 19:40:03188// given multimap. Only call this function in a child process where you know
189// that there aren't any other threads.
evan@chromium.org68a008e2011-05-02 17:54:14190BASE_API void CloseSuperfluousFds(const InjectiveMultimap& saved_map);
jeremy@chromium.orgfa3097a6a52008-12-17 22:41:50191#endif
192
evan@chromium.org898a81a2011-06-30 22:56:15193// TODO(evan): rename these to use StudlyCaps.
194typedef std::vector<std::pair<std::string, std::string> > environment_vector;
195typedef std::vector<std::pair<int, int> > file_handle_mapping_vector;
196
197// Options for launching a subprocess that are passed to LaunchApp().
198struct LaunchOptions {
199 LaunchOptions() : wait(false), process_handle(NULL),
200#if defined(OS_WIN)
201 start_hidden(false), inherit_handles(false), as_user(NULL),
202 empty_desktop_name(false)
203#else
204 environ(NULL), fds_to_remap(NULL), new_process_group(false)
205#endif
206 {}
207
208 // If true, wait for the process to complete.
209 bool wait;
210
211 // If non-NULL, will be filled in with the handle of the launched process.
212 // NOTE: In this case, the caller is responsible for closing the handle so
213 // that it doesn't leak! Otherwise, the handle will be implicitly
214 // closed.
215 // Not especially useful unless |wait| is false.
216 ProcessHandle* process_handle;
217
218#if defined(OS_WIN)
219 bool start_hidden;
220
221 // If true, the new process inherits handles from the parent.
222 bool inherit_handles;
223
224 // If non-NULL, runs as if the user represented by the token had launched it.
225 // Whether the application is visible on the interactive desktop depends on
226 // the token belonging to an interactive logon session.
227 //
228 // To avoid hard to diagnose problems, when specified this loads the
229 // environment variables associated with the user and if this operation fails
230 // the entire call fails as well.
231 UserTokenHandle as_user;
232
233 // If true, use an empty string for the desktop name.
234 bool empty_desktop_name;
235#else
236 // If non-NULL, set/unset environment variables.
237 // See documentation of AlterEnvironment().
238 // This pointer is owned by the caller and must live through the
239 // call to LaunchProcess().
240 const environment_vector* environ;
241
242 // If non-NULL, remap file descriptors according to the mapping of
243 // src fd->dest fd to propagate FDs into the child process.
244 // This pointer is owned by the caller and must live through the
245 // call to LaunchProcess().
246 const file_handle_mapping_vector* fds_to_remap;
247
248 // If true, start the process in a new process group, instead of
249 // inheriting the parent's process group. The pgid of the child process
250 // will be the same as its pid.
251 bool new_process_group;
252#endif
253};
254
255// Launch a process via the command line |cmdline|.
256// See the documentation of LaunchOptions for details on launching options.
257//
258// Unix-specific notes:
259// - Before launching, all FDs open in the parent process will be marked as
260// close-on-exec.
261// - If the first argument on the command line does not contain a slash,
262// PATH will be searched. (See man execvp.)
263BASE_API bool LaunchProcess(const CommandLine& cmdline,
264 const LaunchOptions& options);
265
estade@chromium.orgfb7f9be2008-10-22 01:15:47266#if defined(OS_WIN)
tommi@chromium.org48dc9e12010-08-26 19:49:57267
268enum IntegrityLevel {
269 INTEGRITY_UNKNOWN,
270 LOW_INTEGRITY,
271 MEDIUM_INTEGRITY,
272 HIGH_INTEGRITY,
273};
274// Determine the integrity level of the specified process. Returns false
275// if the system does not support integrity levels (pre-Vista) or in the case
276// of an underlying system failure.
rvargas@google.com26fbf802011-03-25 18:48:03277BASE_API bool GetProcessIntegrityLevel(ProcessHandle process,
278 IntegrityLevel *level);
tommi@chromium.org48dc9e12010-08-26 19:49:57279
evan@chromium.org898a81a2011-06-30 22:56:15280// Windows-specific LaunchProcess that takes the command line as a
281// string. Useful for situations where you need to control the
282// command line arguments directly, but prefer the CommandLine version
283// if launching Chrome itself.
initial.commitd7cae122008-07-26 21:49:38284//
evan@chromium.org898a81a2011-06-30 22:56:15285// The first command line argument should be the path to the process,
286// and don't forget to quote it.
initial.commitd7cae122008-07-26 21:49:38287//
288// Example (including literal quotes)
289// cmdline = "c:\windows\explorer.exe" -foo "c:\bar\"
evan@chromium.org898a81a2011-06-30 22:56:15290BASE_API bool LaunchProcess(const string16& cmdline,
291 const LaunchOptions& options);
cpu@chromium.orge50130b2010-02-01 03:28:47292
evan@chromium.org898a81a2011-06-30 22:56:15293// TODO(evan): deprecated; change callers to use LaunchProcess, remove.
294inline bool LaunchApp(const std::wstring& cmdline,
295 bool wait, bool start_hidden,
296 ProcessHandle* process_handle) {
297 LaunchOptions options;
298 options.wait = wait;
299 options.start_hidden = start_hidden;
300 options.process_handle = process_handle;
301 return LaunchProcess(cmdline, options);
302}
finnur@chromium.org81e32602010-09-07 14:01:31303
evan@chromium.org898a81a2011-06-30 22:56:15304// TODO(evan): deprecated; change callers to use LaunchProcess, remove.
305inline bool LaunchAppWithHandleInheritance(const std::wstring& cmdline,
306 bool wait, bool start_hidden,
307 ProcessHandle* process_handle) {
308 LaunchOptions options;
309 options.wait = wait;
310 options.start_hidden = start_hidden;
311 options.process_handle = process_handle;
312 options.inherit_handles = true;
313 return LaunchProcess(cmdline, options);
314}
cpu@chromium.orge50130b2010-02-01 03:28:47315
evan@chromium.org898a81a2011-06-30 22:56:15316// TODO(evan): deprecated; change callers to use LaunchProcess, remove.
317inline bool LaunchAppAsUser(UserTokenHandle token,
318 const std::wstring& cmdline,
319 bool start_hidden,
320 ProcessHandle* process_handle) {
321 LaunchOptions options;
322 options.start_hidden = start_hidden;
323 options.process_handle = process_handle;
324 options.as_user = token;
325 return LaunchProcess(cmdline, options);
326}
gwilson@google.comc020ddc2010-02-18 23:01:52327
evan@chromium.org898a81a2011-06-30 22:56:15328// TODO(evan): deprecated; change callers to use LaunchProcess, remove.
329inline bool LaunchAppAsUser(UserTokenHandle token,
330 const std::wstring& cmdline,
331 bool start_hidden, ProcessHandle* process_handle,
332 bool empty_desktop_name, bool inherit_handles) {
333 LaunchOptions options;
334 options.start_hidden = start_hidden;
335 options.process_handle = process_handle;
336 options.as_user = token;
337 options.empty_desktop_name = empty_desktop_name;
338 options.inherit_handles = inherit_handles;
339 return LaunchProcess(cmdline, options);
340}
gwilson@google.comc020ddc2010-02-18 23:01:52341
estade@chromium.orgfb7f9be2008-10-22 01:15:47342#elif defined(OS_POSIX)
evan@chromium.org898a81a2011-06-30 22:56:15343// A POSIX-specific version of LaunchProcess that takes an argv array
344// instead of a CommandLine. Useful for situations where you need to
345// control the command line arguments directly, but prefer the
346// CommandLine version if launching Chrome itself.
347BASE_API bool LaunchProcess(const std::vector<std::string>& argv,
348 const LaunchOptions& options);
stuartmorgan@google.com2aea9e092009-08-06 20:03:01349
evan@chromium.org898a81a2011-06-30 22:56:15350// TODO(evan): deprecated; change callers to use LaunchProcess, remove.
351inline bool LaunchApp(const std::vector<std::string>& argv,
352 const file_handle_mapping_vector& fds_to_remap,
353 bool wait, ProcessHandle* process_handle) {
354 LaunchOptions options;
355 options.fds_to_remap = &fds_to_remap;
356 options.wait = wait;
357 options.process_handle = process_handle;
358 return LaunchProcess(argv, options);
359}
thakis@chromium.orgc0028792010-01-12 00:39:15360
evan@chromium.org898a81a2011-06-30 22:56:15361// TODO(evan): deprecated; change callers to use LaunchProcess, remove.
362inline bool LaunchApp(const std::vector<std::string>& argv,
363 const environment_vector& environ,
364 const file_handle_mapping_vector& fds_to_remap,
365 bool wait, ProcessHandle* process_handle) {
366 LaunchOptions options;
367 options.environ = &environ;
368 options.fds_to_remap = &fds_to_remap;
369 options.wait = wait;
370 options.process_handle = process_handle;
371 return LaunchProcess(argv, options);
372}
373
374// TODO(evan): deprecated; change callers to use LaunchProcess, remove.
375inline bool LaunchAppInNewProcessGroup(
evan@chromium.orgc48d8602011-05-09 21:46:08376 const std::vector<std::string>& argv,
377 const environment_vector& environ,
378 const file_handle_mapping_vector& fds_to_remap,
379 bool wait,
evan@chromium.org898a81a2011-06-30 22:56:15380 ProcessHandle* process_handle) {
381 LaunchOptions options;
382 options.environ = &environ;
383 options.fds_to_remap = &fds_to_remap;
384 options.wait = wait;
385 options.process_handle = process_handle;
386 options.new_process_group = true;
387 return LaunchProcess(argv, options);
388}
rsimha@chromium.org61b93f88f2010-09-22 17:28:30389
agl@chromium.orgef73044e2010-03-11 15:25:54390// AlterEnvironment returns a modified environment vector, constructed from the
391// given environment and the list of changes given in |changes|. Each key in
392// the environment is matched against the first element of the pairs. In the
393// event of a match, the value is replaced by the second of the pair, unless
394// the second is empty, in which case the key-value is removed.
395//
396// The returned array is allocated using new[] and must be freed by the caller.
evan@chromium.org91d91fa2011-04-29 20:45:22397BASE_API char** AlterEnvironment(const environment_vector& changes,
398 const char* const* const env);
thestig@chromium.org9ec8db02009-07-21 07:00:13399#endif // defined(OS_POSIX)
estade@chromium.orgfb7f9be2008-10-22 01:15:47400
jcampan@chromium.org1e312112009-04-21 21:44:12401// Executes the application specified by cl. This function delegates to one
evan@chromium.org898a81a2011-06-30 22:56:15402// of the above platform-specific functions.
403// TODO(evan): deprecated; change callers to use LaunchProcess, remove.
404inline bool LaunchApp(const CommandLine& cl, bool wait, bool start_hidden,
405 ProcessHandle* process_handle) {
406 LaunchOptions options;
407 options.wait = wait;
408 options.process_handle = process_handle;
409
410 return LaunchProcess(cl, options);
411}
initial.commitd7cae122008-07-26 21:49:38412
jcampan@chromium.org1e312112009-04-21 21:44:12413// Executes the application specified by |cl| and wait for it to exit. Stores
phajdan.jr@chromium.org1912cfe2009-04-21 08:09:30414// the output (stdout) in |output|. Redirects stderr to /dev/null. Returns true
415// on success (application launched and exited cleanly, with exit code
maruel@chromium.org96878a212010-06-10 18:26:33416// indicating success).
rvargas@google.com26fbf802011-03-25 18:48:03417BASE_API bool GetAppOutput(const CommandLine& cl, std::string* output);
phajdan.jr@chromium.orgc0b210ee2009-04-17 09:57:52418
viettrungluu@chromium.orgf164cea2009-11-05 23:37:40419#if defined(OS_POSIX)
420// A restricted version of |GetAppOutput()| which (a) clears the environment,
421// and (b) stores at most |max_output| bytes; also, it doesn't search the path
422// for the command.
evan@chromium.org91d91fa2011-04-29 20:45:22423BASE_API bool GetAppOutputRestricted(const CommandLine& cl,
424 std::string* output, size_t max_output);
viettrungluu@chromium.orgf164cea2009-11-05 23:37:40425#endif
426
initial.commitd7cae122008-07-26 21:49:38427// Used to filter processes by process ID.
428class ProcessFilter {
429 public:
430 // Returns true to indicate set-inclusion and false otherwise. This method
431 // should not have side-effects and should be idempotent.
maruel@chromium.orgb6128aa2010-04-29 17:44:42432 virtual bool Includes(const ProcessEntry& entry) const = 0;
ziadh@chromium.org695092f2010-08-02 16:34:16433
434 protected:
435 virtual ~ProcessFilter() {}
initial.commitd7cae122008-07-26 21:49:38436};
437
438// Returns the number of processes on the machine that are running from the
439// given executable name. If filter is non-null, then only processes selected
440// by the filter will be counted.
rvargas@google.com26fbf802011-03-25 18:48:03441BASE_API int GetProcessCount(const FilePath::StringType& executable_name,
442 const ProcessFilter* filter);
initial.commitd7cae122008-07-26 21:49:38443
444// Attempts to kill all the processes on the current machine that were launched
445// from the given executable name, ending them with the given exit code. If
446// filter is non-null, then only processes selected by the filter are killed.
rsimha@chromium.org61b93f88f2010-09-22 17:28:30447// Returns true if all processes were able to be killed off, false if at least
initial.commitd7cae122008-07-26 21:49:38448// one couldn't be killed.
rvargas@google.com26fbf802011-03-25 18:48:03449BASE_API bool KillProcesses(const FilePath::StringType& executable_name,
450 int exit_code, const ProcessFilter* filter);
initial.commitd7cae122008-07-26 21:49:38451
452// Attempts to kill the process identified by the given process
453// entry structure, giving it the specified exit code. If |wait| is true, wait
454// for the process to be actually terminated before returning.
455// Returns true if this is successful, false otherwise.
rvargas@google.com26fbf802011-03-25 18:48:03456BASE_API bool KillProcess(ProcessHandle process, int exit_code, bool wait);
rsimha@chromium.org61b93f88f2010-09-22 17:28:30457
458#if defined(OS_POSIX)
459// Attempts to kill the process group identified by |process_group_id|. Returns
460// true on success.
evan@chromium.orgc48d8602011-05-09 21:46:08461BASE_API bool KillProcessGroup(ProcessHandle process_group_id);
rsimha@chromium.org61b93f88f2010-09-22 17:28:30462#endif
463
agl@chromium.orgdfe14862009-01-22 01:23:11464#if defined(OS_WIN)
rvargas@google.com26fbf802011-03-25 18:48:03465BASE_API bool KillProcessById(ProcessId process_id, int exit_code, bool wait);
agl@chromium.orgdfe14862009-01-22 01:23:11466#endif
initial.commitd7cae122008-07-26 21:49:38467
gspencer@chromium.org443b80e2010-12-14 00:42:23468// Get the termination status of the process by interpreting the
469// circumstances of the child process' death. |exit_code| is set to
470// the status returned by waitpid() on POSIX, and from
471// GetExitCodeProcess() on Windows. |exit_code| may be NULL if the
472// caller is not interested in it. Note that on Linux, this function
473// will only return a useful result the first time it is called after
474// the child exits (because it will reap the child and the information
475// will no longer be available).
rvargas@google.com26fbf802011-03-25 18:48:03476BASE_API TerminationStatus GetTerminationStatus(ProcessHandle handle,
477 int* exit_code);
initial.commitd7cae122008-07-26 21:49:38478
dmaclach@chromium.org56f0f262011-02-24 17:14:36479// Waits for process to exit. On POSIX systems, if the process hasn't been
phajdan.jr@chromium.orgc7856632009-01-13 17:38:49480// signaled then puts the exit code in |exit_code|; otherwise it's considered
481// a failure. On Windows |exit_code| is always filled. Returns true on success,
482// and closes |handle| in any case.
rvargas@google.com26fbf802011-03-25 18:48:03483BASE_API bool WaitForExitCode(ProcessHandle handle, int* exit_code);
phajdan.jr@chromium.orgc7856632009-01-13 17:38:49484
phajdan.jr@chromium.org8004e682010-03-16 07:41:22485// Waits for process to exit. If it did exit within |timeout_milliseconds|,
phajdan.jr@chromium.org40bbe592011-04-06 12:18:20486// then puts the exit code in |exit_code|, and returns true.
phajdan.jr@chromium.org8004e682010-03-16 07:41:22487// In POSIX systems, if the process has been signaled then |exit_code| is set
488// to -1. Returns false on failure (the caller is then responsible for closing
489// |handle|).
phajdan.jr@chromium.org40bbe592011-04-06 12:18:20490// The caller is always responsible for closing the |handle|.
rvargas@google.com26fbf802011-03-25 18:48:03491BASE_API bool WaitForExitCodeWithTimeout(ProcessHandle handle, int* exit_code,
492 int64 timeout_milliseconds);
phajdan.jr@chromium.org8004e682010-03-16 07:41:22493
initial.commitd7cae122008-07-26 21:49:38494// 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.
rvargas@google.com26fbf802011-03-25 18:48:03498BASE_API bool WaitForProcessesToExit(
499 const FilePath::StringType& executable_name,
500 int64 wait_milliseconds,
501 const ProcessFilter* filter);
initial.commitd7cae122008-07-26 21:49:38502
estade@chromium.orgfb7f9be2008-10-22 01:15:47503// Wait for a single process to exit. Return true if it exited cleanly within
dmaclach@chromium.org56f0f262011-02-24 17:14:36504// the given time limit. On Linux |handle| must be a child process, however
505// on Mac and Windows it can be any process.
rvargas@google.com26fbf802011-03-25 18:48:03506BASE_API bool WaitForSingleProcess(ProcessHandle handle,
507 int64 wait_milliseconds);
phajdan.jr@chromium.orgc7c980972011-04-05 18:05:34508
initial.commitd7cae122008-07-26 21:49:38509// 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.
rvargas@google.com26fbf802011-03-25 18:48:03515BASE_API bool CleanupProcesses(const FilePath::StringType& executable_name,
516 int64 wait_milliseconds,
517 int exit_code,
518 const ProcessFilter* filter);
initial.commitd7cae122008-07-26 21:49:38519
maruel@chromium.orgb6128aa2010-04-29 17:44:42520// This class provides a way to iterate through a list of processes on the
521// current machine with a specified filter.
522// To use, create an instance and then call NextProcessEntry() until it returns
523// false.
rvargas@google.com26fbf802011-03-25 18:48:03524class BASE_API ProcessIterator {
initial.commitd7cae122008-07-26 21:49:38525 public:
maruel@chromium.orgbaead4f2010-06-11 19:10:30526 typedef std::list<ProcessEntry> ProcessEntries;
527
maruel@chromium.orgb6128aa2010-04-29 17:44:42528 explicit ProcessIterator(const ProcessFilter* filter);
529 virtual ~ProcessIterator();
initial.commitd7cae122008-07-26 21:49:38530
531 // If there's another process that matches the given executable name,
532 // returns a const pointer to the corresponding PROCESSENTRY32.
533 // If there are no more matching processes, returns NULL.
534 // The returned pointer will remain valid until NextProcessEntry()
535 // is called again or this NamedProcessIterator goes out of scope.
536 const ProcessEntry* NextProcessEntry();
537
maruel@chromium.orgb6128aa2010-04-29 17:44:42538 // Takes a snapshot of all the ProcessEntry found.
maruel@chromium.orgbaead4f2010-06-11 19:10:30539 ProcessEntries Snapshot();
maruel@chromium.orgb6128aa2010-04-29 17:44:42540
541 protected:
542 virtual bool IncludeEntry();
543 const ProcessEntry& entry() { return entry_; }
544
initial.commitd7cae122008-07-26 21:49:38545 private:
546 // Determines whether there's another process (regardless of executable)
547 // left in the list of all processes. Returns true and sets entry_ to
548 // that process's info if there is one, false otherwise.
549 bool CheckForNextProcess();
550
initial.commitd7cae122008-07-26 21:49:38551 // Initializes a PROCESSENTRY32 data structure so that it's ready for
552 // use with Process32First/Process32Next.
553 void InitProcessEntry(ProcessEntry* entry);
dkegel@google.comab0e2222008-10-31 20:19:43554
555#if defined(OS_WIN)
initial.commitd7cae122008-07-26 21:49:38556 HANDLE snapshot_;
initial.commitd7cae122008-07-26 21:49:38557 bool started_iteration_;
dkegel@google.comab0e2222008-10-31 20:19:43558#elif defined(OS_MACOSX)
mark@chromium.org962dd312009-02-05 21:44:13559 std::vector<kinfo_proc> kinfo_procs_;
560 size_t index_of_kinfo_proc_;
wtc@chromium.org4a34ce02009-08-31 22:25:00561#elif defined(OS_POSIX)
562 DIR *procfs_dir_;
dkegel@google.comab0e2222008-10-31 20:19:43563#endif
initial.commitd7cae122008-07-26 21:49:38564 ProcessEntry entry_;
565 const ProcessFilter* filter_;
566
maruel@chromium.orgb6128aa2010-04-29 17:44:42567 DISALLOW_COPY_AND_ASSIGN(ProcessIterator);
568};
569
570// This class provides a way to iterate through the list of processes
571// on the current machine that were started from the given executable
572// name. To use, create an instance and then call NextProcessEntry()
573// until it returns false.
rvargas@google.com26fbf802011-03-25 18:48:03574class BASE_API NamedProcessIterator : public ProcessIterator {
maruel@chromium.orgb6128aa2010-04-29 17:44:42575 public:
avi@chromium.org4f260d02010-12-23 18:35:42576 NamedProcessIterator(const FilePath::StringType& executable_name,
maruel@chromium.orgb6128aa2010-04-29 17:44:42577 const ProcessFilter* filter);
578 virtual ~NamedProcessIterator();
579
580 protected:
581 virtual bool IncludeEntry();
582
583 private:
avi@chromium.org4f260d02010-12-23 18:35:42584 FilePath::StringType executable_name_;
maruel@chromium.orgb6128aa2010-04-29 17:44:42585
586 DISALLOW_COPY_AND_ASSIGN(NamedProcessIterator);
initial.commitd7cae122008-07-26 21:49:38587};
588
589// Working Set (resident) memory usage broken down by
agl@chromium.org54fd1d32009-09-01 00:12:58590//
591// On Windows:
initial.commitd7cae122008-07-26 21:49:38592// priv (private): These pages (kbytes) cannot be shared with any other process.
593// shareable: These pages (kbytes) can be shared with other processes under
594// the right circumstances.
595// shared : These pages (kbytes) are currently shared with at least one
596// other process.
agl@chromium.org54fd1d32009-09-01 00:12:58597//
598// On Linux:
599// priv: Pages mapped only by this process
600// shared: PSS or 0 if the kernel doesn't support this
601// shareable: 0
viettrungluu@chromium.org3740cb9b52009-12-19 04:50:04602//
603// On OS X: TODO(thakis): Revise.
604// priv: Memory.
605// shared: 0
606// shareable: 0
initial.commitd7cae122008-07-26 21:49:38607struct WorkingSetKBytes {
agl@chromium.org54fd1d32009-09-01 00:12:58608 WorkingSetKBytes() : priv(0), shareable(0), shared(0) {}
initial.commitd7cae122008-07-26 21:49:38609 size_t priv;
610 size_t shareable;
611 size_t shared;
612};
613
614// Committed (resident + paged) memory usage broken down by
615// private: These pages cannot be shared with any other process.
616// mapped: These pages are mapped into the view of a section (backed by
617// pagefile.sys)
618// image: These pages are mapped into the view of an image section (backed by
619// file system)
620struct CommittedKBytes {
agl@chromium.org54fd1d32009-09-01 00:12:58621 CommittedKBytes() : priv(0), mapped(0), image(0) {}
initial.commitd7cae122008-07-26 21:49:38622 size_t priv;
623 size_t mapped;
624 size_t image;
625};
626
627// Free memory (Megabytes marked as free) in the 2G process address space.
628// total : total amount in megabytes marked as free. Maximum value is 2048.
629// largest : size of the largest contiguous amount of memory found. It is
630// always smaller or equal to FreeMBytes::total.
631// largest_ptr: starting address of the largest memory block.
632struct FreeMBytes {
633 size_t total;
634 size_t largest;
635 void* largest_ptr;
636};
637
evan@chromium.orgd2ed23832009-09-19 01:57:39638// Convert a POSIX timeval to microseconds.
rvargas@google.com26fbf802011-03-25 18:48:03639BASE_API int64 TimeValToMicroseconds(const struct timeval& tv);
evan@chromium.orgd2ed23832009-09-19 01:57:39640
initial.commitd7cae122008-07-26 21:49:38641// Provides performance metrics for a specified process (CPU usage, memory and
642// IO counters). To use it, invoke CreateProcessMetrics() to get an instance
643// for a specific process, then access the information with the different get
644// methods.
rvargas@google.com26fbf802011-03-25 18:48:03645class BASE_API ProcessMetrics {
initial.commitd7cae122008-07-26 21:49:38646 public:
erg@google.coma502bbe72011-01-07 18:06:45647 ~ProcessMetrics();
648
initial.commitd7cae122008-07-26 21:49:38649 // Creates a ProcessMetrics for the specified process.
650 // The caller owns the returned object.
viettrungluu@chromium.org3740cb9b52009-12-19 04:50:04651#if !defined(OS_MACOSX)
initial.commitd7cae122008-07-26 21:49:38652 static ProcessMetrics* CreateProcessMetrics(ProcessHandle process);
viettrungluu@chromium.org3740cb9b52009-12-19 04:50:04653#else
654 class PortProvider {
655 public:
thakis@chromium.orgb2e8e082009-12-21 17:44:20656 // Should return the mach task for |process| if possible, or else
657 // |MACH_PORT_NULL|. Only processes that this returns tasks for will have
658 // metrics on OS X (except for the current process, which always gets
659 // metrics).
viettrungluu@chromium.org3740cb9b52009-12-19 04:50:04660 virtual mach_port_t TaskForPid(ProcessHandle process) const = 0;
661 };
662
663 // The port provider needs to outlive the ProcessMetrics object returned by
664 // this function. If NULL is passed as provider, the returned object
665 // only returns valid metrics if |process| is the current process.
666 static ProcessMetrics* CreateProcessMetrics(ProcessHandle process,
667 PortProvider* port_provider);
maruel@chromium.orgb6128aa2010-04-29 17:44:42668#endif // !defined(OS_MACOSX)
initial.commitd7cae122008-07-26 21:49:38669
670 // Returns the current space allocated for the pagefile, in bytes (these pages
thomasvl@chromium.org796da7c2009-06-11 12:45:45671 // may or may not be in memory). On Linux, this returns the total virtual
672 // memory size.
phajdan.jr@chromium.orgd043c2cc2009-03-25 18:30:45673 size_t GetPagefileUsage() const;
initial.commitd7cae122008-07-26 21:49:38674 // Returns the peak space allocated for the pagefile, in bytes.
phajdan.jr@chromium.orgd043c2cc2009-03-25 18:30:45675 size_t GetPeakPagefileUsage() const;
thomasvl@chromium.org796da7c2009-06-11 12:45:45676 // Returns the current working set size, in bytes. On Linux, this returns
677 // the resident set size.
phajdan.jr@chromium.orgd043c2cc2009-03-25 18:30:45678 size_t GetWorkingSetSize() const;
tc@google.com0c557f12009-05-11 23:35:52679 // Returns the peak working set size, in bytes.
680 size_t GetPeakWorkingSetSize() const;
erg@chromium.org98947a02010-05-11 17:46:08681 // Returns private and sharedusage, in bytes. Private bytes is the amount of
682 // memory currently allocated to a process that cannot be shared. Returns
683 // false on platform specific error conditions. Note: |private_bytes|
684 // returns 0 on unsupported OSes: prior to XP SP2.
685 bool GetMemoryBytes(size_t* private_bytes,
686 size_t* shared_bytes);
initial.commitd7cae122008-07-26 21:49:38687 // Fills a CommittedKBytes with both resident and paged
688 // memory usage as per definition of CommittedBytes.
phajdan.jr@chromium.orgd043c2cc2009-03-25 18:30:45689 void GetCommittedKBytes(CommittedKBytes* usage) const;
initial.commitd7cae122008-07-26 21:49:38690 // Fills a WorkingSetKBytes containing resident private and shared memory
691 // usage in bytes, as per definition of WorkingSetBytes.
phajdan.jr@chromium.orgd043c2cc2009-03-25 18:30:45692 bool GetWorkingSetKBytes(WorkingSetKBytes* ws_usage) const;
initial.commitd7cae122008-07-26 21:49:38693
694 // Computes the current process available memory for allocation.
695 // It does a linear scan of the address space querying each memory region
696 // for its free (unallocated) status. It is useful for estimating the memory
697 // load and fragmentation.
phajdan.jr@chromium.orgd043c2cc2009-03-25 18:30:45698 bool CalculateFreeMemory(FreeMBytes* free) const;
initial.commitd7cae122008-07-26 21:49:38699
700 // Returns the CPU usage in percent since the last time this method was
701 // called. The first time this method is called it returns 0 and will return
702 // the actual CPU info on subsequent calls.
thakis@chromium.org022eab62010-01-13 04:55:06703 // On Windows, the CPU usage value is for all CPUs. So if you have 2 CPUs and
704 // your process is using all the cycles of 1 CPU and not the other CPU, this
705 // method returns 50.
706 double GetCPUUsage();
initial.commitd7cae122008-07-26 21:49:38707
708 // Retrieves accounting information for all I/O operations performed by the
709 // process.
710 // If IO information is retrieved successfully, the function returns true
711 // and fills in the IO_COUNTERS passed in. The function returns false
712 // otherwise.
phajdan.jr@chromium.orgd043c2cc2009-03-25 18:30:45713 bool GetIOCounters(IoCounters* io_counters) const;
initial.commitd7cae122008-07-26 21:49:38714
715 private:
viettrungluu@chromium.org3740cb9b52009-12-19 04:50:04716#if !defined(OS_MACOSX)
initial.commitd7cae122008-07-26 21:49:38717 explicit ProcessMetrics(ProcessHandle process);
viettrungluu@chromium.org3740cb9b52009-12-19 04:50:04718#else
719 ProcessMetrics(ProcessHandle process, PortProvider* port_provider);
maruel@chromium.orgb6128aa2010-04-29 17:44:42720#endif // !defined(OS_MACOSX)
initial.commitd7cae122008-07-26 21:49:38721
722 ProcessHandle process_;
723
724 int processor_count_;
725
evan@chromium.orgd2ed23832009-09-19 01:57:39726 // Used to store the previous times and CPU usage counts so we can
727 // compute the CPU usage between calls.
initial.commitd7cae122008-07-26 21:49:38728 int64 last_time_;
729 int64 last_system_time_;
730
viettrungluu@chromium.org3740cb9b52009-12-19 04:50:04731#if defined(OS_MACOSX)
732 // Queries the port provider if it's set.
733 mach_port_t TaskForPid(ProcessHandle process) const;
734
735 PortProvider* port_provider_;
pvalchev@google.com66700d42010-03-10 07:46:43736#elif defined(OS_POSIX)
737 // Jiffie count at the last_time_ we updated.
738 int last_cpu_;
maruel@chromium.orgb6128aa2010-04-29 17:44:42739#endif // defined(OS_MACOSX)
viettrungluu@chromium.org3740cb9b52009-12-19 04:50:04740
maruel@chromium.orgb6128aa2010-04-29 17:44:42741 DISALLOW_COPY_AND_ASSIGN(ProcessMetrics);
initial.commitd7cae122008-07-26 21:49:38742};
743
sgk@chromium.orged26d942009-11-09 06:57:28744// Returns the memory commited by the system in KBytes.
745// Returns 0 if it can't compute the commit charge.
rvargas@google.com26fbf802011-03-25 18:48:03746BASE_API size_t GetSystemCommitCharge();
sgk@chromium.orged26d942009-11-09 06:57:28747
initial.commitd7cae122008-07-26 21:49:38748// Enables low fragmentation heap (LFH) for every heaps of this process. This
749// won't have any effect on heaps created after this function call. It will not
750// modify data allocated in the heaps before calling this function. So it is
751// better to call this function early in initialization and again before
752// entering the main loop.
753// Note: Returns true on Windows 2000 without doing anything.
rvargas@google.com26fbf802011-03-25 18:48:03754BASE_API bool EnableLowFragmentationHeap();
initial.commitd7cae122008-07-26 21:49:38755
maruel@chromium.orgd6fc9fd2009-10-27 18:03:47756// Enables 'terminate on heap corruption' flag. Helps protect against heap
maruel@google.comc9d40872008-09-24 12:58:37757// overflow. Has no effect if the OS doesn't provide the necessary facility.
rvargas@google.comf5661ca2011-03-24 19:00:20758BASE_API void EnableTerminationOnHeapCorruption();
maruel@google.comc9d40872008-09-24 12:58:37759
avi@chromium.orgcccb21212009-11-12 20:39:56760#if !defined(OS_WIN)
761// Turns on process termination if memory runs out. This is handled on Windows
762// inside RegisterInvalidParamHandler().
evan@chromium.org91d91fa2011-04-29 20:45:22763BASE_API void EnableTerminationOnOutOfMemory();
avi@chromium.org6cfa3392010-07-01 20:11:43764#if defined(OS_MACOSX)
765// Exposed for testing.
766malloc_zone_t* GetPurgeableZone();
767#endif
avi@chromium.orgcccb21212009-11-12 20:39:56768#endif
769
maruel@chromium.orgd6fc9fd2009-10-27 18:03:47770// Enables stack dump to console output on exception and signals.
771// When enabled, the process will quit immediately. This is meant to be used in
772// unit_tests only!
rvargas@google.com26fbf802011-03-25 18:48:03773BASE_API bool EnableInProcessStackDumping();
maruel@chromium.orgd6fc9fd2009-10-27 18:03:47774
deanm@google.comdb717282008-08-27 13:48:03775// If supported on the platform, and the user has sufficent rights, increase
776// the current process's scheduling priority to a high priority.
rvargas@google.com26fbf802011-03-25 18:48:03777BASE_API void RaiseProcessToHighPriority();
deanm@google.comdb717282008-08-27 13:48:03778
mark@chromium.orge9a8c19f2009-09-03 21:27:36779#if defined(OS_MACOSX)
780// Restore the default exception handler, setting it to Apple Crash Reporter
781// (ReportCrash). When forking and execing a new process, the child will
782// inherit the parent's exception ports, which may be set to the Breakpad
783// instance running inside the parent. The parent's Breakpad instance should
784// not handle the child's exceptions. Calling RestoreDefaultExceptionHandler
785// in the child after forking will restore the standard exception handler.
786// See http://crbug.com/20371/ for more details.
787void RestoreDefaultExceptionHandler();
maruel@chromium.orgb6128aa2010-04-29 17:44:42788#endif // defined(OS_MACOSX)
mark@chromium.orge9a8c19f2009-09-03 21:27:36789
brettw@google.com176aa482008-11-14 03:25:15790} // namespace base
initial.commitd7cae122008-07-26 21:49:38791
deanm@google.comdb717282008-08-27 13:48:03792#endif // BASE_PROCESS_UTIL_H_