[go: nahoru, domu]

blob: 6876e8859c0aa0af17a558ceb119a502c4aaabe8 [file] [log] [blame]
maruel@chromium.orga5a00b1d2010-04-08 15:52:451// Copyright (c) 2010 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
maruel@chromium.orga5a00b1d2010-04-08 15:52:4536#include "base/file_descriptor_shuffle.h"
initial.commitd7cae122008-07-26 21:49:3837#include "base/process.h"
38
evan@chromium.org93f21e42010-04-01 00:35:1539#ifndef NAME_MAX // Solaris and some BSDs have no NAME_MAX
40#ifdef MAXNAMLEN
41#define NAME_MAX MAXNAMLEN
42#else
43#define NAME_MAX 256
44#endif
45#endif
46
erg@google.com5d91c9e2010-07-28 17:25:2847class CommandLine;
48class FilePath;
49
maruel@chromium.orga5a00b1d2010-04-08 15:52:4550namespace base {
51
paulg@google.com61659062008-08-06 01:04:1852#if defined(OS_WIN)
maruel@chromium.orga5a00b1d2010-04-08 15:52:4553
54struct ProcessEntry : public PROCESSENTRY32 {
maruel@chromium.orgb6128aa2010-04-29 17:44:4255 ProcessId pid() const { return th32ProcessID; }
56 ProcessId parent_pid() const { return th32ParentProcessID; }
57 const wchar_t* exe_file() const { return szExeFile; }
maruel@chromium.orga5a00b1d2010-04-08 15:52:4558};
maruel@chromium.orgb6128aa2010-04-29 17:44:4259
maruel@chromium.orga5a00b1d2010-04-08 15:52:4560struct IoCounters : public IO_COUNTERS {
61};
62
paulg@google.com61659062008-08-06 01:04:1863#elif defined(OS_POSIX)
maruel@chromium.orga5a00b1d2010-04-08 15:52:4564
dkegel@google.comab0e2222008-10-31 20:19:4365struct ProcessEntry {
maruel@chromium.orgb6128aa2010-04-29 17:44:4266 ProcessId pid_;
67 ProcessId ppid_;
68 ProcessId gid_;
69 std::string exe_file_;
rsimha@chromium.orgc47d81d2010-10-05 23:41:0470 std::vector<std::string> cmd_line_args_;
maruel@chromium.orgb6128aa2010-04-29 17:44:4271
72 ProcessId pid() const { return pid_; }
73 ProcessId parent_pid() const { return ppid_; }
rsimha@chromium.orgc47d81d2010-10-05 23:41:0474 ProcessId gid() const { return gid_; }
maruel@chromium.orgb6128aa2010-04-29 17:44:4275 const char* exe_file() const { return exe_file_.c_str(); }
rsimha@chromium.orgc47d81d2010-10-05 23:41:0476 const std::vector<std::string>& cmd_line_args() const {
77 return cmd_line_args_;
78 }
dkegel@google.comab0e2222008-10-31 20:19:4379};
80
evanm@google.com0b100bc82008-10-14 20:49:1681struct IoCounters {
evan@chromium.org34b2b002009-11-20 06:53:2882 uint64_t ReadOperationCount;
83 uint64_t WriteOperationCount;
84 uint64_t OtherOperationCount;
85 uint64_t ReadTransferCount;
86 uint64_t WriteTransferCount;
87 uint64_t OtherTransferCount;
evanm@google.com0b100bc82008-10-14 20:49:1688};
agl@chromium.org3f04f2b2009-04-30 19:40:0389
maruel@chromium.orga5a00b1d2010-04-08 15:52:4590#endif // defined(OS_POSIX)
initial.commitd7cae122008-07-26 21:49:3891
cpu@google.comeef576f2008-11-03 23:28:0692// A minimalistic but hopefully cross-platform set of exit codes.
93// Do not change the enumeration values or you will break third-party
94// installers.
95enum {
thestig@chromium.orge68639f52010-04-08 19:52:2196 PROCESS_END_NORMAL_TERMINATION = 0,
97 PROCESS_END_KILLED_BY_USER = 1,
98 PROCESS_END_PROCESS_WAS_HUNG = 2
cpu@google.comeef576f2008-11-03 23:28:0699};
100
initial.commitd7cae122008-07-26 21:49:38101// Returns the id of the current process.
phajdan.jr@chromium.org43cf3252009-04-01 09:19:37102ProcessId GetCurrentProcId();
initial.commitd7cae122008-07-26 21:49:38103
erikkay@google.com113ab132008-09-18 20:42:55104// Returns the ProcessHandle of the current process.
105ProcessHandle GetCurrentProcessHandle();
maruel@chromium.org52a261f2009-03-03 15:01:12106
brettw@google.com5986ed22009-02-06 00:19:17107// Converts a PID to a process handle. This handle must be closed by
phajdan.jr@chromium.org6c6cc802009-04-03 17:01:36108// CloseProcessHandle when you are done with it. Returns true on success.
109bool OpenProcessHandle(ProcessId pid, ProcessHandle* handle);
maruel@chromium.org52a261f2009-03-03 15:01:12110
phajdan.jr@chromium.org5d438dbad2009-04-30 08:59:39111// Converts a PID to a process handle. On Windows the handle is opened
112// with more access rights and must only be used by trusted code.
113// You have to close returned handle using CloseProcessHandle. Returns true
114// on success.
115bool OpenPrivilegedProcessHandle(ProcessId pid, ProcessHandle* handle);
116
brettw@google.com5986ed22009-02-06 00:19:17117// Closes the process handle opened by OpenProcessHandle.
118void CloseProcessHandle(ProcessHandle process);
erikkay@google.com113ab132008-09-18 20:42:55119
cpu@google.comeef576f2008-11-03 23:28:06120// Returns the unique ID for the specified process. This is functionally the
initial.commitd7cae122008-07-26 21:49:38121// same as Windows' GetProcessId(), but works on versions of Windows before
122// Win XP SP1 as well.
phajdan.jr@chromium.org43cf3252009-04-01 09:19:37123ProcessId GetProcId(ProcessHandle process);
initial.commitd7cae122008-07-26 21:49:38124
dkegel@google.com78c6dd62009-06-08 23:29:11125#if defined(OS_LINUX)
126// Returns the ID for the parent of the given process.
127ProcessId GetParentProcessId(ProcessHandle process);
128
129// Returns the path to the executable of the given process.
130FilePath GetProcessExecutablePath(ProcessHandle process);
evan@chromium.orgd2ed23832009-09-19 01:57:39131
132// Parse the data found in /proc/<pid>/stat and return the sum of the
133// CPU-related ticks. Returns -1 on parse error.
134// Exposed for testing.
135int ParseProcStatCPU(const std::string& input);
thestig@chromium.orge5856a7a2009-12-10 02:08:10136
137static const char kAdjustOOMScoreSwitch[] = "--adjust-oom-score";
138
139// This adjusts /proc/process/oom_adj so the Linux OOM killer will prefer
140// certain process types over others. The range for the adjustment is
141// [-17,15], with [0,15] being user accessible.
142bool AdjustOOMScore(ProcessId process, int score);
dkegel@google.com78c6dd62009-06-08 23:29:11143#endif
144
jeremy@chromium.orgfa3097a6a52008-12-17 22:41:50145#if defined(OS_POSIX)
agl@chromium.org3f04f2b2009-04-30 19:40:03146// Close all file descriptors, expect those which are a destination in the
147// given multimap. Only call this function in a child process where you know
148// that there aren't any other threads.
maruel@chromium.orgb6128aa2010-04-29 17:44:42149void CloseSuperfluousFds(const InjectiveMultimap& saved_map);
jeremy@chromium.orgfa3097a6a52008-12-17 22:41:50150#endif
151
estade@chromium.orgfb7f9be2008-10-22 01:15:47152#if defined(OS_WIN)
tommi@chromium.org48dc9e12010-08-26 19:49:57153
154enum IntegrityLevel {
155 INTEGRITY_UNKNOWN,
156 LOW_INTEGRITY,
157 MEDIUM_INTEGRITY,
158 HIGH_INTEGRITY,
159};
160// Determine the integrity level of the specified process. Returns false
161// if the system does not support integrity levels (pre-Vista) or in the case
162// of an underlying system failure.
163bool GetProcessIntegrityLevel(ProcessHandle process, IntegrityLevel *level);
164
initial.commitd7cae122008-07-26 21:49:38165// Runs the given application name with the given command line. Normally, the
166// first command line argument should be the path to the process, and don't
167// forget to quote it.
168//
169// If wait is true, it will block and wait for the other process to finish,
170// otherwise, it will just continue asynchronously.
171//
172// Example (including literal quotes)
173// cmdline = "c:\windows\explorer.exe" -foo "c:\bar\"
174//
175// If process_handle is non-NULL, the process handle of the launched app will be
176// stored there on a successful launch.
177// NOTE: In this case, the caller is responsible for closing the handle so
178// that it doesn't leak!
179bool LaunchApp(const std::wstring& cmdline,
estade@chromium.orgfb7f9be2008-10-22 01:15:47180 bool wait, bool start_hidden, ProcessHandle* process_handle);
cpu@chromium.orge50130b2010-02-01 03:28:47181
finnur@chromium.org81e32602010-09-07 14:01:31182// Same as LaunchApp, except allows the new process to inherit handles of the
183// parent process.
184bool LaunchAppWithHandleInheritance(const std::wstring& cmdline,
185 bool wait,
186 bool start_hidden,
187 ProcessHandle* process_handle);
188
cpu@chromium.orge50130b2010-02-01 03:28:47189// Runs the given application name with the given command line as if the user
190// represented by |token| had launched it. The caveats about |cmdline| and
191// |process_handle| explained for LaunchApp above apply as well.
192//
193// Whether the application is visible on the interactive desktop depends on
194// the token belonging to an interactive logon session.
195//
196// To avoid hard to diagnose problems, this function internally loads the
197// environment variables associated with the user and if this operation fails
198// the entire call fails as well.
199bool LaunchAppAsUser(UserTokenHandle token, const std::wstring& cmdline,
200 bool start_hidden, ProcessHandle* process_handle);
201
gwilson@google.comc020ddc2010-02-18 23:01:52202// Has the same behavior as LaunchAppAsUser, but offers the boolean option to
finnur@chromium.org81e32602010-09-07 14:01:31203// use an empty string for the desktop name and a boolean for allowing the
204// child process to inherit handles from its parent.
gwilson@google.comc020ddc2010-02-18 23:01:52205bool LaunchAppAsUser(UserTokenHandle token, const std::wstring& cmdline,
206 bool start_hidden, ProcessHandle* process_handle,
finnur@chromium.org81e32602010-09-07 14:01:31207 bool empty_desktop_name, bool inherit_handles);
gwilson@google.comc020ddc2010-02-18 23:01:52208
209
estade@chromium.orgfb7f9be2008-10-22 01:15:47210#elif defined(OS_POSIX)
211// Runs the application specified in argv[0] with the command line argv.
jeremy@chromium.orgfa3097a6a52008-12-17 22:41:50212// Before launching all FDs open in the parent process will be marked as
213// close-on-exec. |fds_to_remap| defines a mapping of src fd->dest fd to
214// propagate FDs into the child process.
estade@chromium.orgfb7f9be2008-10-22 01:15:47215//
216// As above, if wait is true, execute synchronously. The pid will be stored
217// in process_handle if that pointer is non-null.
218//
mattm@chromium.orgb74d21b32009-07-17 19:36:00219// Note that the first argument in argv must point to the executable filename.
220// If the filename is not fully specified, PATH will be searched.
jeremy@chromium.orgfa3097a6a52008-12-17 22:41:50221typedef std::vector<std::pair<int, int> > file_handle_mapping_vector;
estade@chromium.orgfb7f9be2008-10-22 01:15:47222bool LaunchApp(const std::vector<std::string>& argv,
jeremy@chromium.orgfa3097a6a52008-12-17 22:41:50223 const file_handle_mapping_vector& fds_to_remap,
estade@chromium.orgfb7f9be2008-10-22 01:15:47224 bool wait, ProcessHandle* process_handle);
stuartmorgan@google.com2aea9e092009-08-06 20:03:01225
thakis@chromium.orgc0028792010-01-12 00:39:15226// Similar to the above, but also (un)set environment variables in child process
thestig@chromium.org9ec8db02009-07-21 07:00:13227// through |environ|.
jam@chromium.org3d2217d2009-11-23 21:26:47228typedef std::vector<std::pair<std::string, std::string> > environment_vector;
thestig@chromium.org9ec8db02009-07-21 07:00:13229bool LaunchApp(const std::vector<std::string>& argv,
230 const environment_vector& environ,
231 const file_handle_mapping_vector& fds_to_remap,
232 bool wait, ProcessHandle* process_handle);
thakis@chromium.orgc0028792010-01-12 00:39:15233
rsimha@chromium.org61b93f88f2010-09-22 17:28:30234// Similar to the above two methods, but starts the child process in a process
235// group of its own, instead of allowing it to inherit the parent's process
236// group. The pgid of the child process will be the same as its pid.
237bool LaunchAppInNewProcessGroup(const std::vector<std::string>& argv,
238 const environment_vector& environ,
239 const file_handle_mapping_vector& fds_to_remap,
240 bool wait, ProcessHandle* process_handle);
241
agl@chromium.orgef73044e2010-03-11 15:25:54242// AlterEnvironment returns a modified environment vector, constructed from the
243// given environment and the list of changes given in |changes|. Each key in
244// the environment is matched against the first element of the pairs. In the
245// event of a match, the value is replaced by the second of the pair, unless
246// the second is empty, in which case the key-value is removed.
247//
248// The returned array is allocated using new[] and must be freed by the caller.
249char** AlterEnvironment(const environment_vector& changes,
250 const char* const* const env);
thestig@chromium.org9ec8db02009-07-21 07:00:13251#endif // defined(OS_POSIX)
estade@chromium.orgfb7f9be2008-10-22 01:15:47252
jcampan@chromium.org1e312112009-04-21 21:44:12253// Executes the application specified by cl. This function delegates to one
estade@chromium.orgfb7f9be2008-10-22 01:15:47254// of the above two platform-specific functions.
255bool LaunchApp(const CommandLine& cl,
initial.commitd7cae122008-07-26 21:49:38256 bool wait, bool start_hidden, ProcessHandle* process_handle);
257
jcampan@chromium.org1e312112009-04-21 21:44:12258// Executes the application specified by |cl| and wait for it to exit. Stores
phajdan.jr@chromium.org1912cfe2009-04-21 08:09:30259// the output (stdout) in |output|. Redirects stderr to /dev/null. Returns true
260// on success (application launched and exited cleanly, with exit code
maruel@chromium.org96878a212010-06-10 18:26:33261// indicating success).
phajdan.jr@chromium.orgc0b210ee2009-04-17 09:57:52262bool GetAppOutput(const CommandLine& cl, std::string* output);
phajdan.jr@chromium.orgc0b210ee2009-04-17 09:57:52263
viettrungluu@chromium.orgf164cea2009-11-05 23:37:40264#if defined(OS_POSIX)
265// A restricted version of |GetAppOutput()| which (a) clears the environment,
266// and (b) stores at most |max_output| bytes; also, it doesn't search the path
267// for the command.
268bool GetAppOutputRestricted(const CommandLine& cl,
269 std::string* output, size_t max_output);
270#endif
271
initial.commitd7cae122008-07-26 21:49:38272// Used to filter processes by process ID.
273class ProcessFilter {
274 public:
275 // Returns true to indicate set-inclusion and false otherwise. This method
276 // should not have side-effects and should be idempotent.
maruel@chromium.orgb6128aa2010-04-29 17:44:42277 virtual bool Includes(const ProcessEntry& entry) const = 0;
ziadh@chromium.org695092f2010-08-02 16:34:16278
279 protected:
280 virtual ~ProcessFilter() {}
initial.commitd7cae122008-07-26 21:49:38281};
282
283// Returns the number of processes on the machine that are running from the
284// given executable name. If filter is non-null, then only processes selected
285// by the filter will be counted.
286int GetProcessCount(const std::wstring& executable_name,
287 const ProcessFilter* filter);
288
289// Attempts to kill all the processes on the current machine that were launched
290// from the given executable name, ending them with the given exit code. If
291// filter is non-null, then only processes selected by the filter are killed.
rsimha@chromium.org61b93f88f2010-09-22 17:28:30292// Returns true if all processes were able to be killed off, false if at least
initial.commitd7cae122008-07-26 21:49:38293// one couldn't be killed.
294bool KillProcesses(const std::wstring& executable_name, int exit_code,
295 const ProcessFilter* filter);
296
297// Attempts to kill the process identified by the given process
298// entry structure, giving it the specified exit code. If |wait| is true, wait
299// for the process to be actually terminated before returning.
300// Returns true if this is successful, false otherwise.
stoyan@chromium.orgcd4fd152009-02-09 19:28:41301bool KillProcess(ProcessHandle process, int exit_code, bool wait);
rsimha@chromium.org61b93f88f2010-09-22 17:28:30302
303#if defined(OS_POSIX)
304// Attempts to kill the process group identified by |process_group_id|. Returns
305// true on success.
306bool KillProcessGroup(ProcessHandle process_group_id);
307#endif
308
agl@chromium.orgdfe14862009-01-22 01:23:11309#if defined(OS_WIN)
phajdan.jr@chromium.org43cf3252009-04-01 09:19:37310bool KillProcessById(ProcessId process_id, int exit_code, bool wait);
agl@chromium.orgdfe14862009-01-22 01:23:11311#endif
initial.commitd7cae122008-07-26 21:49:38312
313// Get the termination status (exit code) of the process and return true if the
agl@chromium.org140a7cd2009-04-28 01:37:23314// status indicates the process crashed. |child_exited| is set to true iff the
315// child process has terminated. (|child_exited| may be NULL.)
agl@chromium.org140a7cd2009-04-28 01:37:23316bool DidProcessCrash(bool* child_exited, ProcessHandle handle);
initial.commitd7cae122008-07-26 21:49:38317
phajdan.jr@chromium.orgc7856632009-01-13 17:38:49318// Waits for process to exit. In POSIX systems, if the process hasn't been
319// signaled then puts the exit code in |exit_code|; otherwise it's considered
320// a failure. On Windows |exit_code| is always filled. Returns true on success,
321// and closes |handle| in any case.
322bool WaitForExitCode(ProcessHandle handle, int* exit_code);
323
phajdan.jr@chromium.org8004e682010-03-16 07:41:22324// Waits for process to exit. If it did exit within |timeout_milliseconds|,
325// then puts the exit code in |exit_code|, closes |handle|, and returns true.
326// In POSIX systems, if the process has been signaled then |exit_code| is set
327// to -1. Returns false on failure (the caller is then responsible for closing
328// |handle|).
329bool WaitForExitCodeWithTimeout(ProcessHandle handle, int* exit_code,
330 int64 timeout_milliseconds);
331
initial.commitd7cae122008-07-26 21:49:38332// Wait for all the processes based on the named executable to exit. If filter
333// is non-null, then only processes selected by the filter are waited on.
334// Returns after all processes have exited or wait_milliseconds have expired.
335// Returns true if all the processes exited, false otherwise.
336bool WaitForProcessesToExit(const std::wstring& executable_name,
phajdan.jr@chromium.org743ace42009-06-17 17:23:51337 int64 wait_milliseconds,
initial.commitd7cae122008-07-26 21:49:38338 const ProcessFilter* filter);
339
estade@chromium.orgfb7f9be2008-10-22 01:15:47340// Wait for a single process to exit. Return true if it exited cleanly within
341// the given time limit.
342bool WaitForSingleProcess(ProcessHandle handle,
phajdan.jr@chromium.org743ace42009-06-17 17:23:51343 int64 wait_milliseconds);
estade@chromium.orgfb7f9be2008-10-22 01:15:47344
phajdan.jr@chromium.org076bf0b62009-03-04 20:57:58345// Returns true when |wait_milliseconds| have elapsed and the process
346// is still running.
phajdan.jr@chromium.org743ace42009-06-17 17:23:51347bool CrashAwareSleep(ProcessHandle handle, int64 wait_milliseconds);
phajdan.jr@chromium.org076bf0b62009-03-04 20:57:58348
initial.commitd7cae122008-07-26 21:49:38349// Waits a certain amount of time (can be 0) for all the processes with a given
350// executable name to exit, then kills off any of them that are still around.
351// If filter is non-null, then only processes selected by the filter are waited
352// on. Killed processes are ended with the given exit code. Returns false if
353// any processes needed to be killed, true if they all exited cleanly within
354// the wait_milliseconds delay.
355bool CleanupProcesses(const std::wstring& executable_name,
phajdan.jr@chromium.org743ace42009-06-17 17:23:51356 int64 wait_milliseconds,
initial.commitd7cae122008-07-26 21:49:38357 int exit_code,
358 const ProcessFilter* filter);
359
maruel@chromium.orgb6128aa2010-04-29 17:44:42360// This class provides a way to iterate through a list of processes on the
361// current machine with a specified filter.
362// To use, create an instance and then call NextProcessEntry() until it returns
363// false.
364class ProcessIterator {
initial.commitd7cae122008-07-26 21:49:38365 public:
maruel@chromium.orgbaead4f2010-06-11 19:10:30366 typedef std::list<ProcessEntry> ProcessEntries;
367
maruel@chromium.orgb6128aa2010-04-29 17:44:42368 explicit ProcessIterator(const ProcessFilter* filter);
369 virtual ~ProcessIterator();
initial.commitd7cae122008-07-26 21:49:38370
371 // If there's another process that matches the given executable name,
372 // returns a const pointer to the corresponding PROCESSENTRY32.
373 // If there are no more matching processes, returns NULL.
374 // The returned pointer will remain valid until NextProcessEntry()
375 // is called again or this NamedProcessIterator goes out of scope.
376 const ProcessEntry* NextProcessEntry();
377
maruel@chromium.orgb6128aa2010-04-29 17:44:42378 // Takes a snapshot of all the ProcessEntry found.
maruel@chromium.orgbaead4f2010-06-11 19:10:30379 ProcessEntries Snapshot();
maruel@chromium.orgb6128aa2010-04-29 17:44:42380
381 protected:
382 virtual bool IncludeEntry();
383 const ProcessEntry& entry() { return entry_; }
384
initial.commitd7cae122008-07-26 21:49:38385 private:
386 // Determines whether there's another process (regardless of executable)
387 // left in the list of all processes. Returns true and sets entry_ to
388 // that process's info if there is one, false otherwise.
389 bool CheckForNextProcess();
390
initial.commitd7cae122008-07-26 21:49:38391 // Initializes a PROCESSENTRY32 data structure so that it's ready for
392 // use with Process32First/Process32Next.
393 void InitProcessEntry(ProcessEntry* entry);
dkegel@google.comab0e2222008-10-31 20:19:43394
395#if defined(OS_WIN)
initial.commitd7cae122008-07-26 21:49:38396 HANDLE snapshot_;
initial.commitd7cae122008-07-26 21:49:38397 bool started_iteration_;
dkegel@google.comab0e2222008-10-31 20:19:43398#elif defined(OS_MACOSX)
mark@chromium.org962dd312009-02-05 21:44:13399 std::vector<kinfo_proc> kinfo_procs_;
400 size_t index_of_kinfo_proc_;
wtc@chromium.org4a34ce02009-08-31 22:25:00401#elif defined(OS_POSIX)
402 DIR *procfs_dir_;
dkegel@google.comab0e2222008-10-31 20:19:43403#endif
initial.commitd7cae122008-07-26 21:49:38404 ProcessEntry entry_;
405 const ProcessFilter* filter_;
406
maruel@chromium.orgb6128aa2010-04-29 17:44:42407 DISALLOW_COPY_AND_ASSIGN(ProcessIterator);
408};
409
410// This class provides a way to iterate through the list of processes
411// on the current machine that were started from the given executable
412// name. To use, create an instance and then call NextProcessEntry()
413// until it returns false.
414class NamedProcessIterator : public ProcessIterator {
415 public:
416 NamedProcessIterator(const std::wstring& executable_name,
417 const ProcessFilter* filter);
418 virtual ~NamedProcessIterator();
419
420 protected:
421 virtual bool IncludeEntry();
422
423 private:
424 std::wstring executable_name_;
425
426 DISALLOW_COPY_AND_ASSIGN(NamedProcessIterator);
initial.commitd7cae122008-07-26 21:49:38427};
428
429// Working Set (resident) memory usage broken down by
agl@chromium.org54fd1d32009-09-01 00:12:58430//
431// On Windows:
initial.commitd7cae122008-07-26 21:49:38432// priv (private): These pages (kbytes) cannot be shared with any other process.
433// shareable: These pages (kbytes) can be shared with other processes under
434// the right circumstances.
435// shared : These pages (kbytes) are currently shared with at least one
436// other process.
agl@chromium.org54fd1d32009-09-01 00:12:58437//
438// On Linux:
439// priv: Pages mapped only by this process
440// shared: PSS or 0 if the kernel doesn't support this
441// shareable: 0
viettrungluu@chromium.org3740cb9b52009-12-19 04:50:04442//
443// On OS X: TODO(thakis): Revise.
444// priv: Memory.
445// shared: 0
446// shareable: 0
initial.commitd7cae122008-07-26 21:49:38447struct WorkingSetKBytes {
agl@chromium.org54fd1d32009-09-01 00:12:58448 WorkingSetKBytes() : priv(0), shareable(0), shared(0) {}
initial.commitd7cae122008-07-26 21:49:38449 size_t priv;
450 size_t shareable;
451 size_t shared;
452};
453
454// Committed (resident + paged) memory usage broken down by
455// private: These pages cannot be shared with any other process.
456// mapped: These pages are mapped into the view of a section (backed by
457// pagefile.sys)
458// image: These pages are mapped into the view of an image section (backed by
459// file system)
460struct CommittedKBytes {
agl@chromium.org54fd1d32009-09-01 00:12:58461 CommittedKBytes() : priv(0), mapped(0), image(0) {}
initial.commitd7cae122008-07-26 21:49:38462 size_t priv;
463 size_t mapped;
464 size_t image;
465};
466
467// Free memory (Megabytes marked as free) in the 2G process address space.
468// total : total amount in megabytes marked as free. Maximum value is 2048.
469// largest : size of the largest contiguous amount of memory found. It is
470// always smaller or equal to FreeMBytes::total.
471// largest_ptr: starting address of the largest memory block.
472struct FreeMBytes {
473 size_t total;
474 size_t largest;
475 void* largest_ptr;
476};
477
evan@chromium.orgd2ed23832009-09-19 01:57:39478// Convert a POSIX timeval to microseconds.
479int64 TimeValToMicroseconds(const struct timeval& tv);
480
initial.commitd7cae122008-07-26 21:49:38481// Provides performance metrics for a specified process (CPU usage, memory and
482// IO counters). To use it, invoke CreateProcessMetrics() to get an instance
483// for a specific process, then access the information with the different get
484// methods.
485class ProcessMetrics {
486 public:
487 // Creates a ProcessMetrics for the specified process.
488 // The caller owns the returned object.
viettrungluu@chromium.org3740cb9b52009-12-19 04:50:04489#if !defined(OS_MACOSX)
initial.commitd7cae122008-07-26 21:49:38490 static ProcessMetrics* CreateProcessMetrics(ProcessHandle process);
viettrungluu@chromium.org3740cb9b52009-12-19 04:50:04491#else
492 class PortProvider {
493 public:
thakis@chromium.orgb2e8e082009-12-21 17:44:20494 // Should return the mach task for |process| if possible, or else
495 // |MACH_PORT_NULL|. Only processes that this returns tasks for will have
496 // metrics on OS X (except for the current process, which always gets
497 // metrics).
viettrungluu@chromium.org3740cb9b52009-12-19 04:50:04498 virtual mach_port_t TaskForPid(ProcessHandle process) const = 0;
499 };
500
501 // The port provider needs to outlive the ProcessMetrics object returned by
502 // this function. If NULL is passed as provider, the returned object
503 // only returns valid metrics if |process| is the current process.
504 static ProcessMetrics* CreateProcessMetrics(ProcessHandle process,
505 PortProvider* port_provider);
maruel@chromium.orgb6128aa2010-04-29 17:44:42506#endif // !defined(OS_MACOSX)
initial.commitd7cae122008-07-26 21:49:38507
508 ~ProcessMetrics();
509
510 // Returns the current space allocated for the pagefile, in bytes (these pages
thomasvl@chromium.org796da7c2009-06-11 12:45:45511 // may or may not be in memory). On Linux, this returns the total virtual
512 // memory size.
phajdan.jr@chromium.orgd043c2cc2009-03-25 18:30:45513 size_t GetPagefileUsage() const;
initial.commitd7cae122008-07-26 21:49:38514 // Returns the peak space allocated for the pagefile, in bytes.
phajdan.jr@chromium.orgd043c2cc2009-03-25 18:30:45515 size_t GetPeakPagefileUsage() const;
thomasvl@chromium.org796da7c2009-06-11 12:45:45516 // Returns the current working set size, in bytes. On Linux, this returns
517 // the resident set size.
phajdan.jr@chromium.orgd043c2cc2009-03-25 18:30:45518 size_t GetWorkingSetSize() const;
tc@google.com0c557f12009-05-11 23:35:52519 // Returns the peak working set size, in bytes.
520 size_t GetPeakWorkingSetSize() const;
erg@chromium.org98947a02010-05-11 17:46:08521 // Returns private and sharedusage, in bytes. Private bytes is the amount of
522 // memory currently allocated to a process that cannot be shared. Returns
523 // false on platform specific error conditions. Note: |private_bytes|
524 // returns 0 on unsupported OSes: prior to XP SP2.
525 bool GetMemoryBytes(size_t* private_bytes,
526 size_t* shared_bytes);
initial.commitd7cae122008-07-26 21:49:38527 // Fills a CommittedKBytes with both resident and paged
528 // memory usage as per definition of CommittedBytes.
phajdan.jr@chromium.orgd043c2cc2009-03-25 18:30:45529 void GetCommittedKBytes(CommittedKBytes* usage) const;
initial.commitd7cae122008-07-26 21:49:38530 // Fills a WorkingSetKBytes containing resident private and shared memory
531 // usage in bytes, as per definition of WorkingSetBytes.
phajdan.jr@chromium.orgd043c2cc2009-03-25 18:30:45532 bool GetWorkingSetKBytes(WorkingSetKBytes* ws_usage) const;
initial.commitd7cae122008-07-26 21:49:38533
534 // Computes the current process available memory for allocation.
535 // It does a linear scan of the address space querying each memory region
536 // for its free (unallocated) status. It is useful for estimating the memory
537 // load and fragmentation.
phajdan.jr@chromium.orgd043c2cc2009-03-25 18:30:45538 bool CalculateFreeMemory(FreeMBytes* free) const;
initial.commitd7cae122008-07-26 21:49:38539
540 // Returns the CPU usage in percent since the last time this method was
541 // called. The first time this method is called it returns 0 and will return
542 // the actual CPU info on subsequent calls.
thakis@chromium.org022eab62010-01-13 04:55:06543 // On Windows, the CPU usage value is for all CPUs. So if you have 2 CPUs and
544 // your process is using all the cycles of 1 CPU and not the other CPU, this
545 // method returns 50.
546 double GetCPUUsage();
initial.commitd7cae122008-07-26 21:49:38547
548 // Retrieves accounting information for all I/O operations performed by the
549 // process.
550 // If IO information is retrieved successfully, the function returns true
551 // and fills in the IO_COUNTERS passed in. The function returns false
552 // otherwise.
phajdan.jr@chromium.orgd043c2cc2009-03-25 18:30:45553 bool GetIOCounters(IoCounters* io_counters) const;
initial.commitd7cae122008-07-26 21:49:38554
555 private:
viettrungluu@chromium.org3740cb9b52009-12-19 04:50:04556#if !defined(OS_MACOSX)
initial.commitd7cae122008-07-26 21:49:38557 explicit ProcessMetrics(ProcessHandle process);
viettrungluu@chromium.org3740cb9b52009-12-19 04:50:04558#else
559 ProcessMetrics(ProcessHandle process, PortProvider* port_provider);
maruel@chromium.orgb6128aa2010-04-29 17:44:42560#endif // !defined(OS_MACOSX)
initial.commitd7cae122008-07-26 21:49:38561
562 ProcessHandle process_;
563
564 int processor_count_;
565
evan@chromium.orgd2ed23832009-09-19 01:57:39566 // Used to store the previous times and CPU usage counts so we can
567 // compute the CPU usage between calls.
initial.commitd7cae122008-07-26 21:49:38568 int64 last_time_;
569 int64 last_system_time_;
570
viettrungluu@chromium.org3740cb9b52009-12-19 04:50:04571#if defined(OS_MACOSX)
572 // Queries the port provider if it's set.
573 mach_port_t TaskForPid(ProcessHandle process) const;
574
575 PortProvider* port_provider_;
pvalchev@google.com66700d42010-03-10 07:46:43576#elif defined(OS_POSIX)
577 // Jiffie count at the last_time_ we updated.
578 int last_cpu_;
maruel@chromium.orgb6128aa2010-04-29 17:44:42579#endif // defined(OS_MACOSX)
viettrungluu@chromium.org3740cb9b52009-12-19 04:50:04580
maruel@chromium.orgb6128aa2010-04-29 17:44:42581 DISALLOW_COPY_AND_ASSIGN(ProcessMetrics);
initial.commitd7cae122008-07-26 21:49:38582};
583
sgk@chromium.orged26d942009-11-09 06:57:28584// Returns the memory commited by the system in KBytes.
585// Returns 0 if it can't compute the commit charge.
586size_t GetSystemCommitCharge();
587
initial.commitd7cae122008-07-26 21:49:38588// Enables low fragmentation heap (LFH) for every heaps of this process. This
589// won't have any effect on heaps created after this function call. It will not
590// modify data allocated in the heaps before calling this function. So it is
591// better to call this function early in initialization and again before
592// entering the main loop.
593// Note: Returns true on Windows 2000 without doing anything.
594bool EnableLowFragmentationHeap();
595
maruel@chromium.orgd6fc9fd2009-10-27 18:03:47596// Enables 'terminate on heap corruption' flag. Helps protect against heap
maruel@google.comc9d40872008-09-24 12:58:37597// overflow. Has no effect if the OS doesn't provide the necessary facility.
598void EnableTerminationOnHeapCorruption();
599
avi@chromium.orgcccb21212009-11-12 20:39:56600#if !defined(OS_WIN)
601// Turns on process termination if memory runs out. This is handled on Windows
602// inside RegisterInvalidParamHandler().
603void EnableTerminationOnOutOfMemory();
avi@chromium.org6cfa3392010-07-01 20:11:43604#if defined(OS_MACOSX)
605// Exposed for testing.
606malloc_zone_t* GetPurgeableZone();
607#endif
avi@chromium.orgcccb21212009-11-12 20:39:56608#endif
609
maruel@chromium.orgd6fc9fd2009-10-27 18:03:47610#if defined(UNIT_TEST)
611// Enables stack dump to console output on exception and signals.
612// When enabled, the process will quit immediately. This is meant to be used in
613// unit_tests only!
614bool EnableInProcessStackDumping();
615#endif // defined(UNIT_TEST)
616
deanm@google.comdb717282008-08-27 13:48:03617// If supported on the platform, and the user has sufficent rights, increase
618// the current process's scheduling priority to a high priority.
619void RaiseProcessToHighPriority();
620
mark@chromium.orge9a8c19f2009-09-03 21:27:36621#if defined(OS_MACOSX)
622// Restore the default exception handler, setting it to Apple Crash Reporter
623// (ReportCrash). When forking and execing a new process, the child will
624// inherit the parent's exception ports, which may be set to the Breakpad
625// instance running inside the parent. The parent's Breakpad instance should
626// not handle the child's exceptions. Calling RestoreDefaultExceptionHandler
627// in the child after forking will restore the standard exception handler.
628// See http://crbug.com/20371/ for more details.
629void RestoreDefaultExceptionHandler();
maruel@chromium.orgb6128aa2010-04-29 17:44:42630#endif // defined(OS_MACOSX)
mark@chromium.orge9a8c19f2009-09-03 21:27:36631
brettw@google.com176aa482008-11-14 03:25:15632} // namespace base
initial.commitd7cae122008-07-26 21:49:38633
deanm@google.comdb717282008-08-27 13:48:03634#endif // BASE_PROCESS_UTIL_H_