[go: nahoru, domu]

blob: d6aed0d377fe8c5afb16e8e3600c0141776c9f7d [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_
initial.commitd7cae122008-07-26 21:49:3810
paulg@google.com61659062008-08-06 01:04:1811#include "base/basictypes.h"
12
dkegel@google.comab0e2222008-10-31 20:19:4313#if defined(OS_WIN)
initial.commitd7cae122008-07-26 21:49:3814#include <windows.h>
15#include <tlhelp32.h>
wtc@chromium.org4a34ce02009-08-31 22:25:0016#elif defined(OS_MACOSX)
17// kinfo_proc is defined in <sys/sysctl.h>, but this forward declaration
18// is sufficient for the vector<kinfo_proc> below.
19struct kinfo_proc;
thakis@chromium.orgc0028792010-01-12 00:39:1520#include <mach/mach.h>
wtc@chromium.org4a34ce02009-08-31 22:25:0021#elif defined(OS_POSIX)
dkegel@google.comab0e2222008-10-31 20:19:4322#include <dirent.h>
23#include <limits.h>
24#include <sys/types.h>
paulg@google.com61659062008-08-06 01:04:1825#endif
initial.commitd7cae122008-07-26 21:49:3826
maruel@chromium.orgb6128aa2010-04-29 17:44:4227#include <list>
paulg@google.com61659062008-08-06 01:04:1828#include <string>
thestig@chromium.org9ec8db02009-07-21 07:00:1329#include <utility>
mark@chromium.org962dd312009-02-05 21:44:1330#include <vector>
paulg@google.com61659062008-08-06 01:04:1831
estade@chromium.orgfb7f9be2008-10-22 01:15:4732#include "base/command_line.h"
maruel@chromium.orga5a00b1d2010-04-08 15:52:4533#include "base/file_descriptor_shuffle.h"
dkegel@google.com78c6dd62009-06-08 23:29:1134#include "base/file_path.h"
initial.commitd7cae122008-07-26 21:49:3835#include "base/process.h"
36
evan@chromium.org93f21e42010-04-01 00:35:1537#ifndef NAME_MAX // Solaris and some BSDs have no NAME_MAX
38#ifdef MAXNAMLEN
39#define NAME_MAX MAXNAMLEN
40#else
41#define NAME_MAX 256
42#endif
43#endif
44
maruel@chromium.orga5a00b1d2010-04-08 15:52:4545namespace base {
46
paulg@google.com61659062008-08-06 01:04:1847#if defined(OS_WIN)
maruel@chromium.orga5a00b1d2010-04-08 15:52:4548
49struct ProcessEntry : public PROCESSENTRY32 {
maruel@chromium.orgb6128aa2010-04-29 17:44:4250 ProcessId pid() const { return th32ProcessID; }
51 ProcessId parent_pid() const { return th32ParentProcessID; }
52 const wchar_t* exe_file() const { return szExeFile; }
maruel@chromium.orga5a00b1d2010-04-08 15:52:4553};
maruel@chromium.orgb6128aa2010-04-29 17:44:4254
maruel@chromium.orga5a00b1d2010-04-08 15:52:4555struct IoCounters : public IO_COUNTERS {
56};
57
paulg@google.com61659062008-08-06 01:04:1858#elif defined(OS_POSIX)
maruel@chromium.orga5a00b1d2010-04-08 15:52:4559
dkegel@google.comab0e2222008-10-31 20:19:4360struct ProcessEntry {
maruel@chromium.orgb6128aa2010-04-29 17:44:4261 ProcessId pid_;
62 ProcessId ppid_;
63 ProcessId gid_;
64 std::string exe_file_;
65
66 ProcessId pid() const { return pid_; }
67 ProcessId parent_pid() const { return ppid_; }
68 const char* exe_file() const { return exe_file_.c_str(); }
dkegel@google.comab0e2222008-10-31 20:19:4369};
70
evanm@google.com0b100bc82008-10-14 20:49:1671struct IoCounters {
evan@chromium.org34b2b002009-11-20 06:53:2872 uint64_t ReadOperationCount;
73 uint64_t WriteOperationCount;
74 uint64_t OtherOperationCount;
75 uint64_t ReadTransferCount;
76 uint64_t WriteTransferCount;
77 uint64_t OtherTransferCount;
evanm@google.com0b100bc82008-10-14 20:49:1678};
agl@chromium.org3f04f2b2009-04-30 19:40:0379
maruel@chromium.orga5a00b1d2010-04-08 15:52:4580#endif // defined(OS_POSIX)
initial.commitd7cae122008-07-26 21:49:3881
cpu@google.comeef576f2008-11-03 23:28:0682// A minimalistic but hopefully cross-platform set of exit codes.
83// Do not change the enumeration values or you will break third-party
84// installers.
85enum {
thestig@chromium.orge68639f52010-04-08 19:52:2186 PROCESS_END_NORMAL_TERMINATION = 0,
87 PROCESS_END_KILLED_BY_USER = 1,
88 PROCESS_END_PROCESS_WAS_HUNG = 2
cpu@google.comeef576f2008-11-03 23:28:0689};
90
initial.commitd7cae122008-07-26 21:49:3891// Returns the id of the current process.
phajdan.jr@chromium.org43cf3252009-04-01 09:19:3792ProcessId GetCurrentProcId();
initial.commitd7cae122008-07-26 21:49:3893
erikkay@google.com113ab132008-09-18 20:42:5594// Returns the ProcessHandle of the current process.
95ProcessHandle GetCurrentProcessHandle();
maruel@chromium.org52a261f2009-03-03 15:01:1296
brettw@google.com5986ed22009-02-06 00:19:1797// Converts a PID to a process handle. This handle must be closed by
phajdan.jr@chromium.org6c6cc802009-04-03 17:01:3698// CloseProcessHandle when you are done with it. Returns true on success.
99bool OpenProcessHandle(ProcessId pid, ProcessHandle* handle);
maruel@chromium.org52a261f2009-03-03 15:01:12100
phajdan.jr@chromium.org5d438dbad2009-04-30 08:59:39101// Converts a PID to a process handle. On Windows the handle is opened
102// with more access rights and must only be used by trusted code.
103// You have to close returned handle using CloseProcessHandle. Returns true
104// on success.
105bool OpenPrivilegedProcessHandle(ProcessId pid, ProcessHandle* handle);
106
brettw@google.com5986ed22009-02-06 00:19:17107// Closes the process handle opened by OpenProcessHandle.
108void CloseProcessHandle(ProcessHandle process);
erikkay@google.com113ab132008-09-18 20:42:55109
cpu@google.comeef576f2008-11-03 23:28:06110// Returns the unique ID for the specified process. This is functionally the
initial.commitd7cae122008-07-26 21:49:38111// same as Windows' GetProcessId(), but works on versions of Windows before
112// Win XP SP1 as well.
phajdan.jr@chromium.org43cf3252009-04-01 09:19:37113ProcessId GetProcId(ProcessHandle process);
initial.commitd7cae122008-07-26 21:49:38114
dkegel@google.com78c6dd62009-06-08 23:29:11115#if defined(OS_LINUX)
116// Returns the ID for the parent of the given process.
117ProcessId GetParentProcessId(ProcessHandle process);
118
119// Returns the path to the executable of the given process.
120FilePath GetProcessExecutablePath(ProcessHandle process);
evan@chromium.orgd2ed23832009-09-19 01:57:39121
122// Parse the data found in /proc/<pid>/stat and return the sum of the
123// CPU-related ticks. Returns -1 on parse error.
124// Exposed for testing.
125int ParseProcStatCPU(const std::string& input);
thestig@chromium.orge5856a7a2009-12-10 02:08:10126
127static const char kAdjustOOMScoreSwitch[] = "--adjust-oom-score";
128
129// This adjusts /proc/process/oom_adj so the Linux OOM killer will prefer
130// certain process types over others. The range for the adjustment is
131// [-17,15], with [0,15] being user accessible.
132bool AdjustOOMScore(ProcessId process, int score);
dkegel@google.com78c6dd62009-06-08 23:29:11133#endif
134
jeremy@chromium.orgfa3097a6a52008-12-17 22:41:50135#if defined(OS_POSIX)
agl@chromium.org3f04f2b2009-04-30 19:40:03136// Close all file descriptors, expect those which are a destination in the
137// given multimap. Only call this function in a child process where you know
138// that there aren't any other threads.
maruel@chromium.orgb6128aa2010-04-29 17:44:42139void CloseSuperfluousFds(const InjectiveMultimap& saved_map);
jeremy@chromium.orgfa3097a6a52008-12-17 22:41:50140#endif
141
estade@chromium.orgfb7f9be2008-10-22 01:15:47142#if defined(OS_WIN)
initial.commitd7cae122008-07-26 21:49:38143// Runs the given application name with the given command line. Normally, the
144// first command line argument should be the path to the process, and don't
145// forget to quote it.
146//
147// If wait is true, it will block and wait for the other process to finish,
148// otherwise, it will just continue asynchronously.
149//
150// Example (including literal quotes)
151// cmdline = "c:\windows\explorer.exe" -foo "c:\bar\"
152//
153// If process_handle is non-NULL, the process handle of the launched app will be
154// stored there on a successful launch.
155// NOTE: In this case, the caller is responsible for closing the handle so
156// that it doesn't leak!
157bool LaunchApp(const std::wstring& cmdline,
estade@chromium.orgfb7f9be2008-10-22 01:15:47158 bool wait, bool start_hidden, ProcessHandle* process_handle);
cpu@chromium.orge50130b2010-02-01 03:28:47159
160// Runs the given application name with the given command line as if the user
161// represented by |token| had launched it. The caveats about |cmdline| and
162// |process_handle| explained for LaunchApp above apply as well.
163//
164// Whether the application is visible on the interactive desktop depends on
165// the token belonging to an interactive logon session.
166//
167// To avoid hard to diagnose problems, this function internally loads the
168// environment variables associated with the user and if this operation fails
169// the entire call fails as well.
170bool LaunchAppAsUser(UserTokenHandle token, const std::wstring& cmdline,
171 bool start_hidden, ProcessHandle* process_handle);
172
gwilson@google.comc020ddc2010-02-18 23:01:52173// Has the same behavior as LaunchAppAsUser, but offers the boolean option to
174// use an empty string for the desktop name.
175bool LaunchAppAsUser(UserTokenHandle token, const std::wstring& cmdline,
176 bool start_hidden, ProcessHandle* process_handle,
177 bool empty_desktop_name);
178
179
estade@chromium.orgfb7f9be2008-10-22 01:15:47180#elif defined(OS_POSIX)
181// Runs the application specified in argv[0] with the command line argv.
jeremy@chromium.orgfa3097a6a52008-12-17 22:41:50182// Before launching all FDs open in the parent process will be marked as
183// close-on-exec. |fds_to_remap| defines a mapping of src fd->dest fd to
184// propagate FDs into the child process.
estade@chromium.orgfb7f9be2008-10-22 01:15:47185//
186// As above, if wait is true, execute synchronously. The pid will be stored
187// in process_handle if that pointer is non-null.
188//
mattm@chromium.orgb74d21b32009-07-17 19:36:00189// Note that the first argument in argv must point to the executable filename.
190// If the filename is not fully specified, PATH will be searched.
jeremy@chromium.orgfa3097a6a52008-12-17 22:41:50191typedef std::vector<std::pair<int, int> > file_handle_mapping_vector;
estade@chromium.orgfb7f9be2008-10-22 01:15:47192bool LaunchApp(const std::vector<std::string>& argv,
jeremy@chromium.orgfa3097a6a52008-12-17 22:41:50193 const file_handle_mapping_vector& fds_to_remap,
estade@chromium.orgfb7f9be2008-10-22 01:15:47194 bool wait, ProcessHandle* process_handle);
stuartmorgan@google.com2aea9e092009-08-06 20:03:01195
thakis@chromium.orgc0028792010-01-12 00:39:15196// Similar to the above, but also (un)set environment variables in child process
thestig@chromium.org9ec8db02009-07-21 07:00:13197// through |environ|.
jam@chromium.org3d2217d2009-11-23 21:26:47198typedef std::vector<std::pair<std::string, std::string> > environment_vector;
thestig@chromium.org9ec8db02009-07-21 07:00:13199bool LaunchApp(const std::vector<std::string>& argv,
200 const environment_vector& environ,
201 const file_handle_mapping_vector& fds_to_remap,
202 bool wait, ProcessHandle* process_handle);
thakis@chromium.orgc0028792010-01-12 00:39:15203
agl@chromium.orgef73044e2010-03-11 15:25:54204// AlterEnvironment returns a modified environment vector, constructed from the
205// given environment and the list of changes given in |changes|. Each key in
206// the environment is matched against the first element of the pairs. In the
207// event of a match, the value is replaced by the second of the pair, unless
208// the second is empty, in which case the key-value is removed.
209//
210// The returned array is allocated using new[] and must be freed by the caller.
211char** AlterEnvironment(const environment_vector& changes,
212 const char* const* const env);
213
thakis@chromium.orgc0028792010-01-12 00:39:15214#if defined(OS_MACOSX)
215// Similar to the above, but also returns the new process's task_t if
216// |task_handle| is not NULL. If |task_handle| is not NULL, the caller is
217// responsible for calling |mach_port_deallocate()| on the returned handle.
218bool LaunchAppAndGetTask(const std::vector<std::string>& argv,
219 const environment_vector& environ,
220 const file_handle_mapping_vector& fds_to_remap,
221 bool wait,
222 task_t* task_handle,
223 ProcessHandle* process_handle);
224#endif // defined(OS_MACOSX)
thestig@chromium.org9ec8db02009-07-21 07:00:13225#endif // defined(OS_POSIX)
estade@chromium.orgfb7f9be2008-10-22 01:15:47226
jcampan@chromium.org1e312112009-04-21 21:44:12227// Executes the application specified by cl. This function delegates to one
estade@chromium.orgfb7f9be2008-10-22 01:15:47228// of the above two platform-specific functions.
229bool LaunchApp(const CommandLine& cl,
initial.commitd7cae122008-07-26 21:49:38230 bool wait, bool start_hidden, ProcessHandle* process_handle);
231
jcampan@chromium.org1e312112009-04-21 21:44:12232// Executes the application specified by |cl| and wait for it to exit. Stores
phajdan.jr@chromium.org1912cfe2009-04-21 08:09:30233// the output (stdout) in |output|. Redirects stderr to /dev/null. Returns true
234// on success (application launched and exited cleanly, with exit code
maruel@chromium.org96878a212010-06-10 18:26:33235// indicating success).
phajdan.jr@chromium.orgc0b210ee2009-04-17 09:57:52236bool GetAppOutput(const CommandLine& cl, std::string* output);
phajdan.jr@chromium.orgc0b210ee2009-04-17 09:57:52237
viettrungluu@chromium.orgf164cea2009-11-05 23:37:40238#if defined(OS_POSIX)
239// A restricted version of |GetAppOutput()| which (a) clears the environment,
240// and (b) stores at most |max_output| bytes; also, it doesn't search the path
241// for the command.
242bool GetAppOutputRestricted(const CommandLine& cl,
243 std::string* output, size_t max_output);
244#endif
245
initial.commitd7cae122008-07-26 21:49:38246// Used to filter processes by process ID.
247class ProcessFilter {
248 public:
249 // Returns true to indicate set-inclusion and false otherwise. This method
250 // should not have side-effects and should be idempotent.
maruel@chromium.orgb6128aa2010-04-29 17:44:42251 virtual bool Includes(const ProcessEntry& entry) const = 0;
initial.commitd7cae122008-07-26 21:49:38252};
253
254// Returns the number of processes on the machine that are running from the
255// given executable name. If filter is non-null, then only processes selected
256// by the filter will be counted.
257int GetProcessCount(const std::wstring& executable_name,
258 const ProcessFilter* filter);
259
260// Attempts to kill all the processes on the current machine that were launched
261// from the given executable name, ending them with the given exit code. If
262// filter is non-null, then only processes selected by the filter are killed.
263// Returns false if all processes were able to be killed off, false if at least
264// one couldn't be killed.
265bool KillProcesses(const std::wstring& executable_name, int exit_code,
266 const ProcessFilter* filter);
267
268// Attempts to kill the process identified by the given process
269// entry structure, giving it the specified exit code. If |wait| is true, wait
270// for the process to be actually terminated before returning.
271// Returns true if this is successful, false otherwise.
stoyan@chromium.orgcd4fd152009-02-09 19:28:41272bool KillProcess(ProcessHandle process, int exit_code, bool wait);
agl@chromium.orgdfe14862009-01-22 01:23:11273#if defined(OS_WIN)
phajdan.jr@chromium.org43cf3252009-04-01 09:19:37274bool KillProcessById(ProcessId process_id, int exit_code, bool wait);
agl@chromium.orgdfe14862009-01-22 01:23:11275#endif
initial.commitd7cae122008-07-26 21:49:38276
277// Get the termination status (exit code) of the process and return true if the
agl@chromium.org140a7cd2009-04-28 01:37:23278// status indicates the process crashed. |child_exited| is set to true iff the
279// child process has terminated. (|child_exited| may be NULL.)
agl@chromium.org140a7cd2009-04-28 01:37:23280bool DidProcessCrash(bool* child_exited, ProcessHandle handle);
initial.commitd7cae122008-07-26 21:49:38281
phajdan.jr@chromium.orgc7856632009-01-13 17:38:49282// Waits for process to exit. In POSIX systems, if the process hasn't been
283// signaled then puts the exit code in |exit_code|; otherwise it's considered
284// a failure. On Windows |exit_code| is always filled. Returns true on success,
285// and closes |handle| in any case.
286bool WaitForExitCode(ProcessHandle handle, int* exit_code);
287
phajdan.jr@chromium.org8004e682010-03-16 07:41:22288// Waits for process to exit. If it did exit within |timeout_milliseconds|,
289// then puts the exit code in |exit_code|, closes |handle|, and returns true.
290// In POSIX systems, if the process has been signaled then |exit_code| is set
291// to -1. Returns false on failure (the caller is then responsible for closing
292// |handle|).
293bool WaitForExitCodeWithTimeout(ProcessHandle handle, int* exit_code,
294 int64 timeout_milliseconds);
295
initial.commitd7cae122008-07-26 21:49:38296// Wait for all the processes based on the named executable to exit. If filter
297// is non-null, then only processes selected by the filter are waited on.
298// Returns after all processes have exited or wait_milliseconds have expired.
299// Returns true if all the processes exited, false otherwise.
300bool WaitForProcessesToExit(const std::wstring& executable_name,
phajdan.jr@chromium.org743ace42009-06-17 17:23:51301 int64 wait_milliseconds,
initial.commitd7cae122008-07-26 21:49:38302 const ProcessFilter* filter);
303
estade@chromium.orgfb7f9be2008-10-22 01:15:47304// Wait for a single process to exit. Return true if it exited cleanly within
305// the given time limit.
306bool WaitForSingleProcess(ProcessHandle handle,
phajdan.jr@chromium.org743ace42009-06-17 17:23:51307 int64 wait_milliseconds);
estade@chromium.orgfb7f9be2008-10-22 01:15:47308
phajdan.jr@chromium.org076bf0b62009-03-04 20:57:58309// Returns true when |wait_milliseconds| have elapsed and the process
310// is still running.
phajdan.jr@chromium.org743ace42009-06-17 17:23:51311bool CrashAwareSleep(ProcessHandle handle, int64 wait_milliseconds);
phajdan.jr@chromium.org076bf0b62009-03-04 20:57:58312
initial.commitd7cae122008-07-26 21:49:38313// Waits a certain amount of time (can be 0) for all the processes with a given
314// executable name to exit, then kills off any of them that are still around.
315// If filter is non-null, then only processes selected by the filter are waited
316// on. Killed processes are ended with the given exit code. Returns false if
317// any processes needed to be killed, true if they all exited cleanly within
318// the wait_milliseconds delay.
319bool CleanupProcesses(const std::wstring& executable_name,
phajdan.jr@chromium.org743ace42009-06-17 17:23:51320 int64 wait_milliseconds,
initial.commitd7cae122008-07-26 21:49:38321 int exit_code,
322 const ProcessFilter* filter);
323
maruel@chromium.orgb6128aa2010-04-29 17:44:42324// This class provides a way to iterate through a list of processes on the
325// current machine with a specified filter.
326// To use, create an instance and then call NextProcessEntry() until it returns
327// false.
328class ProcessIterator {
initial.commitd7cae122008-07-26 21:49:38329 public:
maruel@chromium.orgb6128aa2010-04-29 17:44:42330 explicit ProcessIterator(const ProcessFilter* filter);
331 virtual ~ProcessIterator();
initial.commitd7cae122008-07-26 21:49:38332
333 // If there's another process that matches the given executable name,
334 // returns a const pointer to the corresponding PROCESSENTRY32.
335 // If there are no more matching processes, returns NULL.
336 // The returned pointer will remain valid until NextProcessEntry()
337 // is called again or this NamedProcessIterator goes out of scope.
338 const ProcessEntry* NextProcessEntry();
339
maruel@chromium.orgb6128aa2010-04-29 17:44:42340 // Takes a snapshot of all the ProcessEntry found.
341 std::list<ProcessEntry> Snapshot();
342
343 protected:
344 virtual bool IncludeEntry();
345 const ProcessEntry& entry() { return entry_; }
346
initial.commitd7cae122008-07-26 21:49:38347 private:
348 // Determines whether there's another process (regardless of executable)
349 // left in the list of all processes. Returns true and sets entry_ to
350 // that process's info if there is one, false otherwise.
351 bool CheckForNextProcess();
352
initial.commitd7cae122008-07-26 21:49:38353 // Initializes a PROCESSENTRY32 data structure so that it's ready for
354 // use with Process32First/Process32Next.
355 void InitProcessEntry(ProcessEntry* entry);
dkegel@google.comab0e2222008-10-31 20:19:43356
357#if defined(OS_WIN)
initial.commitd7cae122008-07-26 21:49:38358 HANDLE snapshot_;
initial.commitd7cae122008-07-26 21:49:38359 bool started_iteration_;
dkegel@google.comab0e2222008-10-31 20:19:43360#elif defined(OS_MACOSX)
mark@chromium.org962dd312009-02-05 21:44:13361 std::vector<kinfo_proc> kinfo_procs_;
362 size_t index_of_kinfo_proc_;
wtc@chromium.org4a34ce02009-08-31 22:25:00363#elif defined(OS_POSIX)
364 DIR *procfs_dir_;
dkegel@google.comab0e2222008-10-31 20:19:43365#endif
initial.commitd7cae122008-07-26 21:49:38366 ProcessEntry entry_;
367 const ProcessFilter* filter_;
368
maruel@chromium.orgb6128aa2010-04-29 17:44:42369 DISALLOW_COPY_AND_ASSIGN(ProcessIterator);
370};
371
372// This class provides a way to iterate through the list of processes
373// on the current machine that were started from the given executable
374// name. To use, create an instance and then call NextProcessEntry()
375// until it returns false.
376class NamedProcessIterator : public ProcessIterator {
377 public:
378 NamedProcessIterator(const std::wstring& executable_name,
379 const ProcessFilter* filter);
380 virtual ~NamedProcessIterator();
381
382 protected:
383 virtual bool IncludeEntry();
384
385 private:
386 std::wstring executable_name_;
387
388 DISALLOW_COPY_AND_ASSIGN(NamedProcessIterator);
initial.commitd7cae122008-07-26 21:49:38389};
390
391// Working Set (resident) memory usage broken down by
agl@chromium.org54fd1d32009-09-01 00:12:58392//
393// On Windows:
initial.commitd7cae122008-07-26 21:49:38394// priv (private): These pages (kbytes) cannot be shared with any other process.
395// shareable: These pages (kbytes) can be shared with other processes under
396// the right circumstances.
397// shared : These pages (kbytes) are currently shared with at least one
398// other process.
agl@chromium.org54fd1d32009-09-01 00:12:58399//
400// On Linux:
401// priv: Pages mapped only by this process
402// shared: PSS or 0 if the kernel doesn't support this
403// shareable: 0
viettrungluu@chromium.org3740cb9b52009-12-19 04:50:04404//
405// On OS X: TODO(thakis): Revise.
406// priv: Memory.
407// shared: 0
408// shareable: 0
initial.commitd7cae122008-07-26 21:49:38409struct WorkingSetKBytes {
agl@chromium.org54fd1d32009-09-01 00:12:58410 WorkingSetKBytes() : priv(0), shareable(0), shared(0) {}
initial.commitd7cae122008-07-26 21:49:38411 size_t priv;
412 size_t shareable;
413 size_t shared;
414};
415
416// Committed (resident + paged) memory usage broken down by
417// private: These pages cannot be shared with any other process.
418// mapped: These pages are mapped into the view of a section (backed by
419// pagefile.sys)
420// image: These pages are mapped into the view of an image section (backed by
421// file system)
422struct CommittedKBytes {
agl@chromium.org54fd1d32009-09-01 00:12:58423 CommittedKBytes() : priv(0), mapped(0), image(0) {}
initial.commitd7cae122008-07-26 21:49:38424 size_t priv;
425 size_t mapped;
426 size_t image;
427};
428
429// Free memory (Megabytes marked as free) in the 2G process address space.
430// total : total amount in megabytes marked as free. Maximum value is 2048.
431// largest : size of the largest contiguous amount of memory found. It is
432// always smaller or equal to FreeMBytes::total.
433// largest_ptr: starting address of the largest memory block.
434struct FreeMBytes {
435 size_t total;
436 size_t largest;
437 void* largest_ptr;
438};
439
evan@chromium.orgd2ed23832009-09-19 01:57:39440// Convert a POSIX timeval to microseconds.
441int64 TimeValToMicroseconds(const struct timeval& tv);
442
initial.commitd7cae122008-07-26 21:49:38443// Provides performance metrics for a specified process (CPU usage, memory and
444// IO counters). To use it, invoke CreateProcessMetrics() to get an instance
445// for a specific process, then access the information with the different get
446// methods.
447class ProcessMetrics {
448 public:
449 // Creates a ProcessMetrics for the specified process.
450 // The caller owns the returned object.
viettrungluu@chromium.org3740cb9b52009-12-19 04:50:04451#if !defined(OS_MACOSX)
initial.commitd7cae122008-07-26 21:49:38452 static ProcessMetrics* CreateProcessMetrics(ProcessHandle process);
viettrungluu@chromium.org3740cb9b52009-12-19 04:50:04453#else
454 class PortProvider {
455 public:
thakis@chromium.orgb2e8e082009-12-21 17:44:20456 // Should return the mach task for |process| if possible, or else
457 // |MACH_PORT_NULL|. Only processes that this returns tasks for will have
458 // metrics on OS X (except for the current process, which always gets
459 // metrics).
viettrungluu@chromium.org3740cb9b52009-12-19 04:50:04460 virtual mach_port_t TaskForPid(ProcessHandle process) const = 0;
461 };
462
463 // The port provider needs to outlive the ProcessMetrics object returned by
464 // this function. If NULL is passed as provider, the returned object
465 // only returns valid metrics if |process| is the current process.
466 static ProcessMetrics* CreateProcessMetrics(ProcessHandle process,
467 PortProvider* port_provider);
maruel@chromium.orgb6128aa2010-04-29 17:44:42468#endif // !defined(OS_MACOSX)
initial.commitd7cae122008-07-26 21:49:38469
470 ~ProcessMetrics();
471
472 // Returns the current space allocated for the pagefile, in bytes (these pages
thomasvl@chromium.org796da7c2009-06-11 12:45:45473 // may or may not be in memory). On Linux, this returns the total virtual
474 // memory size.
phajdan.jr@chromium.orgd043c2cc2009-03-25 18:30:45475 size_t GetPagefileUsage() const;
initial.commitd7cae122008-07-26 21:49:38476 // Returns the peak space allocated for the pagefile, in bytes.
phajdan.jr@chromium.orgd043c2cc2009-03-25 18:30:45477 size_t GetPeakPagefileUsage() const;
thomasvl@chromium.org796da7c2009-06-11 12:45:45478 // Returns the current working set size, in bytes. On Linux, this returns
479 // the resident set size.
phajdan.jr@chromium.orgd043c2cc2009-03-25 18:30:45480 size_t GetWorkingSetSize() const;
tc@google.com0c557f12009-05-11 23:35:52481 // Returns the peak working set size, in bytes.
482 size_t GetPeakWorkingSetSize() const;
erg@chromium.org98947a02010-05-11 17:46:08483 // Returns private and sharedusage, in bytes. Private bytes is the amount of
484 // memory currently allocated to a process that cannot be shared. Returns
485 // false on platform specific error conditions. Note: |private_bytes|
486 // returns 0 on unsupported OSes: prior to XP SP2.
487 bool GetMemoryBytes(size_t* private_bytes,
488 size_t* shared_bytes);
initial.commitd7cae122008-07-26 21:49:38489 // Fills a CommittedKBytes with both resident and paged
490 // memory usage as per definition of CommittedBytes.
phajdan.jr@chromium.orgd043c2cc2009-03-25 18:30:45491 void GetCommittedKBytes(CommittedKBytes* usage) const;
initial.commitd7cae122008-07-26 21:49:38492 // Fills a WorkingSetKBytes containing resident private and shared memory
493 // usage in bytes, as per definition of WorkingSetBytes.
phajdan.jr@chromium.orgd043c2cc2009-03-25 18:30:45494 bool GetWorkingSetKBytes(WorkingSetKBytes* ws_usage) const;
initial.commitd7cae122008-07-26 21:49:38495
496 // Computes the current process available memory for allocation.
497 // It does a linear scan of the address space querying each memory region
498 // for its free (unallocated) status. It is useful for estimating the memory
499 // load and fragmentation.
phajdan.jr@chromium.orgd043c2cc2009-03-25 18:30:45500 bool CalculateFreeMemory(FreeMBytes* free) const;
initial.commitd7cae122008-07-26 21:49:38501
502 // Returns the CPU usage in percent since the last time this method was
503 // called. The first time this method is called it returns 0 and will return
504 // the actual CPU info on subsequent calls.
thakis@chromium.org022eab62010-01-13 04:55:06505 // On Windows, the CPU usage value is for all CPUs. So if you have 2 CPUs and
506 // your process is using all the cycles of 1 CPU and not the other CPU, this
507 // method returns 50.
508 double GetCPUUsage();
initial.commitd7cae122008-07-26 21:49:38509
510 // Retrieves accounting information for all I/O operations performed by the
511 // process.
512 // If IO information is retrieved successfully, the function returns true
513 // and fills in the IO_COUNTERS passed in. The function returns false
514 // otherwise.
phajdan.jr@chromium.orgd043c2cc2009-03-25 18:30:45515 bool GetIOCounters(IoCounters* io_counters) const;
initial.commitd7cae122008-07-26 21:49:38516
517 private:
viettrungluu@chromium.org3740cb9b52009-12-19 04:50:04518#if !defined(OS_MACOSX)
initial.commitd7cae122008-07-26 21:49:38519 explicit ProcessMetrics(ProcessHandle process);
viettrungluu@chromium.org3740cb9b52009-12-19 04:50:04520#else
521 ProcessMetrics(ProcessHandle process, PortProvider* port_provider);
maruel@chromium.orgb6128aa2010-04-29 17:44:42522#endif // !defined(OS_MACOSX)
initial.commitd7cae122008-07-26 21:49:38523
524 ProcessHandle process_;
525
526 int processor_count_;
527
evan@chromium.orgd2ed23832009-09-19 01:57:39528 // Used to store the previous times and CPU usage counts so we can
529 // compute the CPU usage between calls.
initial.commitd7cae122008-07-26 21:49:38530 int64 last_time_;
531 int64 last_system_time_;
532
viettrungluu@chromium.org3740cb9b52009-12-19 04:50:04533#if defined(OS_MACOSX)
534 // Queries the port provider if it's set.
535 mach_port_t TaskForPid(ProcessHandle process) const;
536
537 PortProvider* port_provider_;
pvalchev@google.com66700d42010-03-10 07:46:43538#elif defined(OS_POSIX)
539 // Jiffie count at the last_time_ we updated.
540 int last_cpu_;
maruel@chromium.orgb6128aa2010-04-29 17:44:42541#endif // defined(OS_MACOSX)
viettrungluu@chromium.org3740cb9b52009-12-19 04:50:04542
maruel@chromium.orgb6128aa2010-04-29 17:44:42543 DISALLOW_COPY_AND_ASSIGN(ProcessMetrics);
initial.commitd7cae122008-07-26 21:49:38544};
545
sgk@chromium.orged26d942009-11-09 06:57:28546// Returns the memory commited by the system in KBytes.
547// Returns 0 if it can't compute the commit charge.
548size_t GetSystemCommitCharge();
549
initial.commitd7cae122008-07-26 21:49:38550// Enables low fragmentation heap (LFH) for every heaps of this process. This
551// won't have any effect on heaps created after this function call. It will not
552// modify data allocated in the heaps before calling this function. So it is
553// better to call this function early in initialization and again before
554// entering the main loop.
555// Note: Returns true on Windows 2000 without doing anything.
556bool EnableLowFragmentationHeap();
557
maruel@chromium.orgd6fc9fd2009-10-27 18:03:47558// Enables 'terminate on heap corruption' flag. Helps protect against heap
maruel@google.comc9d40872008-09-24 12:58:37559// overflow. Has no effect if the OS doesn't provide the necessary facility.
560void EnableTerminationOnHeapCorruption();
561
avi@chromium.orgcccb21212009-11-12 20:39:56562#if !defined(OS_WIN)
563// Turns on process termination if memory runs out. This is handled on Windows
564// inside RegisterInvalidParamHandler().
565void EnableTerminationOnOutOfMemory();
566#endif
567
maruel@chromium.orgd6fc9fd2009-10-27 18:03:47568#if defined(UNIT_TEST)
569// Enables stack dump to console output on exception and signals.
570// When enabled, the process will quit immediately. This is meant to be used in
571// unit_tests only!
572bool EnableInProcessStackDumping();
573#endif // defined(UNIT_TEST)
574
deanm@google.comdb717282008-08-27 13:48:03575// If supported on the platform, and the user has sufficent rights, increase
576// the current process's scheduling priority to a high priority.
577void RaiseProcessToHighPriority();
578
mark@chromium.orge9a8c19f2009-09-03 21:27:36579#if defined(OS_MACOSX)
580// Restore the default exception handler, setting it to Apple Crash Reporter
581// (ReportCrash). When forking and execing a new process, the child will
582// inherit the parent's exception ports, which may be set to the Breakpad
583// instance running inside the parent. The parent's Breakpad instance should
584// not handle the child's exceptions. Calling RestoreDefaultExceptionHandler
585// in the child after forking will restore the standard exception handler.
586// See http://crbug.com/20371/ for more details.
587void RestoreDefaultExceptionHandler();
maruel@chromium.orgb6128aa2010-04-29 17:44:42588#endif // defined(OS_MACOSX)
mark@chromium.orge9a8c19f2009-09-03 21:27:36589
brettw@google.com176aa482008-11-14 03:25:15590} // namespace base
initial.commitd7cae122008-07-26 21:49:38591
deanm@google.comdb717282008-08-27 13:48:03592#endif // BASE_PROCESS_UTIL_H_