[go: nahoru, domu]

blob: b9abef0f796008059ecde932a028493ac82b49a8 [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
paulg@google.com61659062008-08-06 01:04:1827#include <string>
thestig@chromium.org9ec8db02009-07-21 07:00:1328#include <utility>
mark@chromium.org962dd312009-02-05 21:44:1329#include <vector>
paulg@google.com61659062008-08-06 01:04:1830
estade@chromium.orgfb7f9be2008-10-22 01:15:4731#include "base/command_line.h"
maruel@chromium.orga5a00b1d2010-04-08 15:52:4532#include "base/file_descriptor_shuffle.h"
dkegel@google.com78c6dd62009-06-08 23:29:1133#include "base/file_path.h"
initial.commitd7cae122008-07-26 21:49:3834#include "base/process.h"
35
evan@chromium.org93f21e42010-04-01 00:35:1536#ifndef NAME_MAX // Solaris and some BSDs have no NAME_MAX
37#ifdef MAXNAMLEN
38#define NAME_MAX MAXNAMLEN
39#else
40#define NAME_MAX 256
41#endif
42#endif
43
maruel@chromium.orga5a00b1d2010-04-08 15:52:4544namespace base {
45
paulg@google.com61659062008-08-06 01:04:1846#if defined(OS_WIN)
maruel@chromium.orga5a00b1d2010-04-08 15:52:4547
48struct ProcessEntry : public PROCESSENTRY32 {
49};
50struct IoCounters : public IO_COUNTERS {
51};
52
paulg@google.com61659062008-08-06 01:04:1853#elif defined(OS_POSIX)
maruel@chromium.orga5a00b1d2010-04-08 15:52:4554
dkegel@google.comab0e2222008-10-31 20:19:4355struct ProcessEntry {
viettrungluu@chromium.orga4dc33f2009-10-20 15:09:5556 base::ProcessId pid;
57 base::ProcessId ppid;
mark@chromium.org962dd312009-02-05 21:44:1358 char szExeFile[NAME_MAX + 1];
dkegel@google.comab0e2222008-10-31 20:19:4359};
60
evanm@google.com0b100bc82008-10-14 20:49:1661struct IoCounters {
evan@chromium.org34b2b002009-11-20 06:53:2862 uint64_t ReadOperationCount;
63 uint64_t WriteOperationCount;
64 uint64_t OtherOperationCount;
65 uint64_t ReadTransferCount;
66 uint64_t WriteTransferCount;
67 uint64_t OtherTransferCount;
evanm@google.com0b100bc82008-10-14 20:49:1668};
agl@chromium.org3f04f2b2009-04-30 19:40:0369
maruel@chromium.orga5a00b1d2010-04-08 15:52:4570#endif // defined(OS_POSIX)
initial.commitd7cae122008-07-26 21:49:3871
cpu@google.comeef576f2008-11-03 23:28:0672// A minimalistic but hopefully cross-platform set of exit codes.
73// Do not change the enumeration values or you will break third-party
74// installers.
75enum {
76 PROCESS_END_NORMAL_TERMINATON = 0,
77 PROCESS_END_KILLED_BY_USER = 1,
78 PROCESS_END_PROCESS_WAS_HUNG = 2
79};
80
initial.commitd7cae122008-07-26 21:49:3881// Returns the id of the current process.
phajdan.jr@chromium.org43cf3252009-04-01 09:19:3782ProcessId GetCurrentProcId();
initial.commitd7cae122008-07-26 21:49:3883
erikkay@google.com113ab132008-09-18 20:42:5584// Returns the ProcessHandle of the current process.
85ProcessHandle GetCurrentProcessHandle();
maruel@chromium.org52a261f2009-03-03 15:01:1286
brettw@google.com5986ed22009-02-06 00:19:1787// Converts a PID to a process handle. This handle must be closed by
phajdan.jr@chromium.org6c6cc802009-04-03 17:01:3688// CloseProcessHandle when you are done with it. Returns true on success.
89bool OpenProcessHandle(ProcessId pid, ProcessHandle* handle);
maruel@chromium.org52a261f2009-03-03 15:01:1290
phajdan.jr@chromium.org5d438dbad2009-04-30 08:59:3991// Converts a PID to a process handle. On Windows the handle is opened
92// with more access rights and must only be used by trusted code.
93// You have to close returned handle using CloseProcessHandle. Returns true
94// on success.
95bool OpenPrivilegedProcessHandle(ProcessId pid, ProcessHandle* handle);
96
brettw@google.com5986ed22009-02-06 00:19:1797// Closes the process handle opened by OpenProcessHandle.
98void CloseProcessHandle(ProcessHandle process);
erikkay@google.com113ab132008-09-18 20:42:5599
cpu@google.comeef576f2008-11-03 23:28:06100// Returns the unique ID for the specified process. This is functionally the
initial.commitd7cae122008-07-26 21:49:38101// same as Windows' GetProcessId(), but works on versions of Windows before
102// Win XP SP1 as well.
phajdan.jr@chromium.org43cf3252009-04-01 09:19:37103ProcessId GetProcId(ProcessHandle process);
initial.commitd7cae122008-07-26 21:49:38104
dkegel@google.com78c6dd62009-06-08 23:29:11105#if defined(OS_LINUX)
106// Returns the ID for the parent of the given process.
107ProcessId GetParentProcessId(ProcessHandle process);
108
109// Returns the path to the executable of the given process.
110FilePath GetProcessExecutablePath(ProcessHandle process);
evan@chromium.orgd2ed23832009-09-19 01:57:39111
112// Parse the data found in /proc/<pid>/stat and return the sum of the
113// CPU-related ticks. Returns -1 on parse error.
114// Exposed for testing.
115int ParseProcStatCPU(const std::string& input);
thestig@chromium.orge5856a7a2009-12-10 02:08:10116
117static const char kAdjustOOMScoreSwitch[] = "--adjust-oom-score";
118
119// This adjusts /proc/process/oom_adj so the Linux OOM killer will prefer
120// certain process types over others. The range for the adjustment is
121// [-17,15], with [0,15] being user accessible.
122bool AdjustOOMScore(ProcessId process, int score);
dkegel@google.com78c6dd62009-06-08 23:29:11123#endif
124
jeremy@chromium.orgfa3097a6a52008-12-17 22:41:50125#if defined(OS_POSIX)
agl@chromium.org3f04f2b2009-04-30 19:40:03126// Close all file descriptors, expect those which are a destination in the
127// given multimap. Only call this function in a child process where you know
128// that there aren't any other threads.
129void CloseSuperfluousFds(const base::InjectiveMultimap& saved_map);
jeremy@chromium.orgfa3097a6a52008-12-17 22:41:50130#endif
131
estade@chromium.orgfb7f9be2008-10-22 01:15:47132#if defined(OS_WIN)
initial.commitd7cae122008-07-26 21:49:38133// Runs the given application name with the given command line. Normally, the
134// first command line argument should be the path to the process, and don't
135// forget to quote it.
136//
137// If wait is true, it will block and wait for the other process to finish,
138// otherwise, it will just continue asynchronously.
139//
140// Example (including literal quotes)
141// cmdline = "c:\windows\explorer.exe" -foo "c:\bar\"
142//
143// If process_handle is non-NULL, the process handle of the launched app will be
144// stored there on a successful launch.
145// NOTE: In this case, the caller is responsible for closing the handle so
146// that it doesn't leak!
147bool LaunchApp(const std::wstring& cmdline,
estade@chromium.orgfb7f9be2008-10-22 01:15:47148 bool wait, bool start_hidden, ProcessHandle* process_handle);
cpu@chromium.orge50130b2010-02-01 03:28:47149
150// Runs the given application name with the given command line as if the user
151// represented by |token| had launched it. The caveats about |cmdline| and
152// |process_handle| explained for LaunchApp above apply as well.
153//
154// Whether the application is visible on the interactive desktop depends on
155// the token belonging to an interactive logon session.
156//
157// To avoid hard to diagnose problems, this function internally loads the
158// environment variables associated with the user and if this operation fails
159// the entire call fails as well.
160bool LaunchAppAsUser(UserTokenHandle token, const std::wstring& cmdline,
161 bool start_hidden, ProcessHandle* process_handle);
162
gwilson@google.comc020ddc2010-02-18 23:01:52163// Has the same behavior as LaunchAppAsUser, but offers the boolean option to
164// use an empty string for the desktop name.
165bool LaunchAppAsUser(UserTokenHandle token, const std::wstring& cmdline,
166 bool start_hidden, ProcessHandle* process_handle,
167 bool empty_desktop_name);
168
169
estade@chromium.orgfb7f9be2008-10-22 01:15:47170#elif defined(OS_POSIX)
171// Runs the application specified in argv[0] with the command line argv.
jeremy@chromium.orgfa3097a6a52008-12-17 22:41:50172// Before launching all FDs open in the parent process will be marked as
173// close-on-exec. |fds_to_remap| defines a mapping of src fd->dest fd to
174// propagate FDs into the child process.
estade@chromium.orgfb7f9be2008-10-22 01:15:47175//
176// As above, if wait is true, execute synchronously. The pid will be stored
177// in process_handle if that pointer is non-null.
178//
mattm@chromium.orgb74d21b32009-07-17 19:36:00179// Note that the first argument in argv must point to the executable filename.
180// If the filename is not fully specified, PATH will be searched.
jeremy@chromium.orgfa3097a6a52008-12-17 22:41:50181typedef std::vector<std::pair<int, int> > file_handle_mapping_vector;
estade@chromium.orgfb7f9be2008-10-22 01:15:47182bool LaunchApp(const std::vector<std::string>& argv,
jeremy@chromium.orgfa3097a6a52008-12-17 22:41:50183 const file_handle_mapping_vector& fds_to_remap,
estade@chromium.orgfb7f9be2008-10-22 01:15:47184 bool wait, ProcessHandle* process_handle);
stuartmorgan@google.com2aea9e092009-08-06 20:03:01185
thakis@chromium.orgc0028792010-01-12 00:39:15186// Similar to the above, but also (un)set environment variables in child process
thestig@chromium.org9ec8db02009-07-21 07:00:13187// through |environ|.
jam@chromium.org3d2217d2009-11-23 21:26:47188typedef std::vector<std::pair<std::string, std::string> > environment_vector;
thestig@chromium.org9ec8db02009-07-21 07:00:13189bool LaunchApp(const std::vector<std::string>& argv,
190 const environment_vector& environ,
191 const file_handle_mapping_vector& fds_to_remap,
192 bool wait, ProcessHandle* process_handle);
thakis@chromium.orgc0028792010-01-12 00:39:15193
agl@chromium.orgef73044e2010-03-11 15:25:54194// AlterEnvironment returns a modified environment vector, constructed from the
195// given environment and the list of changes given in |changes|. Each key in
196// the environment is matched against the first element of the pairs. In the
197// event of a match, the value is replaced by the second of the pair, unless
198// the second is empty, in which case the key-value is removed.
199//
200// The returned array is allocated using new[] and must be freed by the caller.
201char** AlterEnvironment(const environment_vector& changes,
202 const char* const* const env);
203
thakis@chromium.orgc0028792010-01-12 00:39:15204#if defined(OS_MACOSX)
205// Similar to the above, but also returns the new process's task_t if
206// |task_handle| is not NULL. If |task_handle| is not NULL, the caller is
207// responsible for calling |mach_port_deallocate()| on the returned handle.
208bool LaunchAppAndGetTask(const std::vector<std::string>& argv,
209 const environment_vector& environ,
210 const file_handle_mapping_vector& fds_to_remap,
211 bool wait,
212 task_t* task_handle,
213 ProcessHandle* process_handle);
214#endif // defined(OS_MACOSX)
thestig@chromium.org9ec8db02009-07-21 07:00:13215#endif // defined(OS_POSIX)
estade@chromium.orgfb7f9be2008-10-22 01:15:47216
jcampan@chromium.org1e312112009-04-21 21:44:12217// Executes the application specified by cl. This function delegates to one
estade@chromium.orgfb7f9be2008-10-22 01:15:47218// of the above two platform-specific functions.
219bool LaunchApp(const CommandLine& cl,
initial.commitd7cae122008-07-26 21:49:38220 bool wait, bool start_hidden, ProcessHandle* process_handle);
221
jcampan@chromium.org1e312112009-04-21 21:44:12222// Executes the application specified by |cl| and wait for it to exit. Stores
phajdan.jr@chromium.org1912cfe2009-04-21 08:09:30223// the output (stdout) in |output|. Redirects stderr to /dev/null. Returns true
224// on success (application launched and exited cleanly, with exit code
225// indicating success). |output| is modified only when the function finished
226// successfully.
phajdan.jr@chromium.orgc0b210ee2009-04-17 09:57:52227bool GetAppOutput(const CommandLine& cl, std::string* output);
phajdan.jr@chromium.orgc0b210ee2009-04-17 09:57:52228
viettrungluu@chromium.orgf164cea2009-11-05 23:37:40229#if defined(OS_POSIX)
230// A restricted version of |GetAppOutput()| which (a) clears the environment,
231// and (b) stores at most |max_output| bytes; also, it doesn't search the path
232// for the command.
233bool GetAppOutputRestricted(const CommandLine& cl,
234 std::string* output, size_t max_output);
235#endif
236
initial.commitd7cae122008-07-26 21:49:38237// Used to filter processes by process ID.
238class ProcessFilter {
239 public:
240 // Returns true to indicate set-inclusion and false otherwise. This method
241 // should not have side-effects and should be idempotent.
phajdan.jr@chromium.org43cf3252009-04-01 09:19:37242 virtual bool Includes(ProcessId pid, ProcessId parent_pid) const = 0;
initial.commitd7cae122008-07-26 21:49:38243};
244
245// Returns the number of processes on the machine that are running from the
246// given executable name. If filter is non-null, then only processes selected
247// by the filter will be counted.
248int GetProcessCount(const std::wstring& executable_name,
249 const ProcessFilter* filter);
250
251// Attempts to kill all the processes on the current machine that were launched
252// from the given executable name, ending them with the given exit code. If
253// filter is non-null, then only processes selected by the filter are killed.
254// Returns false if all processes were able to be killed off, false if at least
255// one couldn't be killed.
256bool KillProcesses(const std::wstring& executable_name, int exit_code,
257 const ProcessFilter* filter);
258
259// Attempts to kill the process identified by the given process
260// entry structure, giving it the specified exit code. If |wait| is true, wait
261// for the process to be actually terminated before returning.
262// Returns true if this is successful, false otherwise.
stoyan@chromium.orgcd4fd152009-02-09 19:28:41263bool KillProcess(ProcessHandle process, int exit_code, bool wait);
agl@chromium.orgdfe14862009-01-22 01:23:11264#if defined(OS_WIN)
phajdan.jr@chromium.org43cf3252009-04-01 09:19:37265bool KillProcessById(ProcessId process_id, int exit_code, bool wait);
agl@chromium.orgdfe14862009-01-22 01:23:11266#endif
initial.commitd7cae122008-07-26 21:49:38267
268// Get the termination status (exit code) of the process and return true if the
agl@chromium.org140a7cd2009-04-28 01:37:23269// status indicates the process crashed. |child_exited| is set to true iff the
270// child process has terminated. (|child_exited| may be NULL.)
agl@chromium.org140a7cd2009-04-28 01:37:23271bool DidProcessCrash(bool* child_exited, ProcessHandle handle);
initial.commitd7cae122008-07-26 21:49:38272
phajdan.jr@chromium.orgc7856632009-01-13 17:38:49273// Waits for process to exit. In POSIX systems, if the process hasn't been
274// signaled then puts the exit code in |exit_code|; otherwise it's considered
275// a failure. On Windows |exit_code| is always filled. Returns true on success,
276// and closes |handle| in any case.
277bool WaitForExitCode(ProcessHandle handle, int* exit_code);
278
phajdan.jr@chromium.org8004e682010-03-16 07:41:22279// Waits for process to exit. If it did exit within |timeout_milliseconds|,
280// then puts the exit code in |exit_code|, closes |handle|, and returns true.
281// In POSIX systems, if the process has been signaled then |exit_code| is set
282// to -1. Returns false on failure (the caller is then responsible for closing
283// |handle|).
284bool WaitForExitCodeWithTimeout(ProcessHandle handle, int* exit_code,
285 int64 timeout_milliseconds);
286
initial.commitd7cae122008-07-26 21:49:38287// Wait for all the processes based on the named executable to exit. If filter
288// is non-null, then only processes selected by the filter are waited on.
289// Returns after all processes have exited or wait_milliseconds have expired.
290// Returns true if all the processes exited, false otherwise.
291bool WaitForProcessesToExit(const std::wstring& executable_name,
phajdan.jr@chromium.org743ace42009-06-17 17:23:51292 int64 wait_milliseconds,
initial.commitd7cae122008-07-26 21:49:38293 const ProcessFilter* filter);
294
estade@chromium.orgfb7f9be2008-10-22 01:15:47295// Wait for a single process to exit. Return true if it exited cleanly within
296// the given time limit.
297bool WaitForSingleProcess(ProcessHandle handle,
phajdan.jr@chromium.org743ace42009-06-17 17:23:51298 int64 wait_milliseconds);
estade@chromium.orgfb7f9be2008-10-22 01:15:47299
phajdan.jr@chromium.org076bf0b62009-03-04 20:57:58300// Returns true when |wait_milliseconds| have elapsed and the process
301// is still running.
phajdan.jr@chromium.org743ace42009-06-17 17:23:51302bool CrashAwareSleep(ProcessHandle handle, int64 wait_milliseconds);
phajdan.jr@chromium.org076bf0b62009-03-04 20:57:58303
initial.commitd7cae122008-07-26 21:49:38304// Waits a certain amount of time (can be 0) for all the processes with a given
305// executable name to exit, then kills off any of them that are still around.
306// If filter is non-null, then only processes selected by the filter are waited
307// on. Killed processes are ended with the given exit code. Returns false if
308// any processes needed to be killed, true if they all exited cleanly within
309// the wait_milliseconds delay.
310bool CleanupProcesses(const std::wstring& executable_name,
phajdan.jr@chromium.org743ace42009-06-17 17:23:51311 int64 wait_milliseconds,
initial.commitd7cae122008-07-26 21:49:38312 int exit_code,
313 const ProcessFilter* filter);
314
315// This class provides a way to iterate through the list of processes
316// on the current machine that were started from the given executable
317// name. To use, create an instance and then call NextProcessEntry()
318// until it returns false.
319class NamedProcessIterator {
320 public:
321 NamedProcessIterator(const std::wstring& executable_name,
322 const ProcessFilter* filter);
323 ~NamedProcessIterator();
324
325 // If there's another process that matches the given executable name,
326 // returns a const pointer to the corresponding PROCESSENTRY32.
327 // If there are no more matching processes, returns NULL.
328 // The returned pointer will remain valid until NextProcessEntry()
329 // is called again or this NamedProcessIterator goes out of scope.
330 const ProcessEntry* NextProcessEntry();
331
332 private:
333 // Determines whether there's another process (regardless of executable)
334 // left in the list of all processes. Returns true and sets entry_ to
335 // that process's info if there is one, false otherwise.
336 bool CheckForNextProcess();
337
338 bool IncludeEntry();
339
340 // Initializes a PROCESSENTRY32 data structure so that it's ready for
341 // use with Process32First/Process32Next.
342 void InitProcessEntry(ProcessEntry* entry);
343
344 std::wstring executable_name_;
dkegel@google.comab0e2222008-10-31 20:19:43345
346#if defined(OS_WIN)
initial.commitd7cae122008-07-26 21:49:38347 HANDLE snapshot_;
initial.commitd7cae122008-07-26 21:49:38348 bool started_iteration_;
dkegel@google.comab0e2222008-10-31 20:19:43349#elif defined(OS_MACOSX)
mark@chromium.org962dd312009-02-05 21:44:13350 std::vector<kinfo_proc> kinfo_procs_;
351 size_t index_of_kinfo_proc_;
wtc@chromium.org4a34ce02009-08-31 22:25:00352#elif defined(OS_POSIX)
353 DIR *procfs_dir_;
dkegel@google.comab0e2222008-10-31 20:19:43354#endif
initial.commitd7cae122008-07-26 21:49:38355 ProcessEntry entry_;
356 const ProcessFilter* filter_;
357
358 DISALLOW_EVIL_CONSTRUCTORS(NamedProcessIterator);
359};
360
361// Working Set (resident) memory usage broken down by
agl@chromium.org54fd1d32009-09-01 00:12:58362//
363// On Windows:
initial.commitd7cae122008-07-26 21:49:38364// priv (private): These pages (kbytes) cannot be shared with any other process.
365// shareable: These pages (kbytes) can be shared with other processes under
366// the right circumstances.
367// shared : These pages (kbytes) are currently shared with at least one
368// other process.
agl@chromium.org54fd1d32009-09-01 00:12:58369//
370// On Linux:
371// priv: Pages mapped only by this process
372// shared: PSS or 0 if the kernel doesn't support this
373// shareable: 0
viettrungluu@chromium.org3740cb9b52009-12-19 04:50:04374//
375// On OS X: TODO(thakis): Revise.
376// priv: Memory.
377// shared: 0
378// shareable: 0
initial.commitd7cae122008-07-26 21:49:38379struct WorkingSetKBytes {
agl@chromium.org54fd1d32009-09-01 00:12:58380 WorkingSetKBytes() : priv(0), shareable(0), shared(0) {}
initial.commitd7cae122008-07-26 21:49:38381 size_t priv;
382 size_t shareable;
383 size_t shared;
384};
385
386// Committed (resident + paged) memory usage broken down by
387// private: These pages cannot be shared with any other process.
388// mapped: These pages are mapped into the view of a section (backed by
389// pagefile.sys)
390// image: These pages are mapped into the view of an image section (backed by
391// file system)
392struct CommittedKBytes {
agl@chromium.org54fd1d32009-09-01 00:12:58393 CommittedKBytes() : priv(0), mapped(0), image(0) {}
initial.commitd7cae122008-07-26 21:49:38394 size_t priv;
395 size_t mapped;
396 size_t image;
397};
398
399// Free memory (Megabytes marked as free) in the 2G process address space.
400// total : total amount in megabytes marked as free. Maximum value is 2048.
401// largest : size of the largest contiguous amount of memory found. It is
402// always smaller or equal to FreeMBytes::total.
403// largest_ptr: starting address of the largest memory block.
404struct FreeMBytes {
405 size_t total;
406 size_t largest;
407 void* largest_ptr;
408};
409
evan@chromium.orgd2ed23832009-09-19 01:57:39410// Convert a POSIX timeval to microseconds.
411int64 TimeValToMicroseconds(const struct timeval& tv);
412
initial.commitd7cae122008-07-26 21:49:38413// Provides performance metrics for a specified process (CPU usage, memory and
414// IO counters). To use it, invoke CreateProcessMetrics() to get an instance
415// for a specific process, then access the information with the different get
416// methods.
417class ProcessMetrics {
418 public:
419 // Creates a ProcessMetrics for the specified process.
420 // The caller owns the returned object.
viettrungluu@chromium.org3740cb9b52009-12-19 04:50:04421#if !defined(OS_MACOSX)
initial.commitd7cae122008-07-26 21:49:38422 static ProcessMetrics* CreateProcessMetrics(ProcessHandle process);
viettrungluu@chromium.org3740cb9b52009-12-19 04:50:04423#else
424 class PortProvider {
425 public:
thakis@chromium.orgb2e8e082009-12-21 17:44:20426 // Should return the mach task for |process| if possible, or else
427 // |MACH_PORT_NULL|. Only processes that this returns tasks for will have
428 // metrics on OS X (except for the current process, which always gets
429 // metrics).
viettrungluu@chromium.org3740cb9b52009-12-19 04:50:04430 virtual mach_port_t TaskForPid(ProcessHandle process) const = 0;
431 };
432
433 // The port provider needs to outlive the ProcessMetrics object returned by
434 // this function. If NULL is passed as provider, the returned object
435 // only returns valid metrics if |process| is the current process.
436 static ProcessMetrics* CreateProcessMetrics(ProcessHandle process,
437 PortProvider* port_provider);
438#endif
initial.commitd7cae122008-07-26 21:49:38439
440 ~ProcessMetrics();
441
442 // Returns the current space allocated for the pagefile, in bytes (these pages
thomasvl@chromium.org796da7c2009-06-11 12:45:45443 // may or may not be in memory). On Linux, this returns the total virtual
444 // memory size.
phajdan.jr@chromium.orgd043c2cc2009-03-25 18:30:45445 size_t GetPagefileUsage() const;
initial.commitd7cae122008-07-26 21:49:38446 // Returns the peak space allocated for the pagefile, in bytes.
phajdan.jr@chromium.orgd043c2cc2009-03-25 18:30:45447 size_t GetPeakPagefileUsage() const;
thomasvl@chromium.org796da7c2009-06-11 12:45:45448 // Returns the current working set size, in bytes. On Linux, this returns
449 // the resident set size.
phajdan.jr@chromium.orgd043c2cc2009-03-25 18:30:45450 size_t GetWorkingSetSize() const;
tc@google.com0c557f12009-05-11 23:35:52451 // Returns the peak working set size, in bytes.
452 size_t GetPeakWorkingSetSize() const;
initial.commitd7cae122008-07-26 21:49:38453 // Returns private usage, in bytes. Private bytes is the amount
454 // of memory currently allocated to a process that cannot be shared.
455 // Note: returns 0 on unsupported OSes: prior to XP SP2.
phajdan.jr@chromium.orgd043c2cc2009-03-25 18:30:45456 size_t GetPrivateBytes() const;
initial.commitd7cae122008-07-26 21:49:38457 // Fills a CommittedKBytes with both resident and paged
458 // memory usage as per definition of CommittedBytes.
phajdan.jr@chromium.orgd043c2cc2009-03-25 18:30:45459 void GetCommittedKBytes(CommittedKBytes* usage) const;
initial.commitd7cae122008-07-26 21:49:38460 // Fills a WorkingSetKBytes containing resident private and shared memory
461 // usage in bytes, as per definition of WorkingSetBytes.
phajdan.jr@chromium.orgd043c2cc2009-03-25 18:30:45462 bool GetWorkingSetKBytes(WorkingSetKBytes* ws_usage) const;
initial.commitd7cae122008-07-26 21:49:38463
464 // Computes the current process available memory for allocation.
465 // It does a linear scan of the address space querying each memory region
466 // for its free (unallocated) status. It is useful for estimating the memory
467 // load and fragmentation.
phajdan.jr@chromium.orgd043c2cc2009-03-25 18:30:45468 bool CalculateFreeMemory(FreeMBytes* free) const;
initial.commitd7cae122008-07-26 21:49:38469
470 // Returns the CPU usage in percent since the last time this method was
471 // called. The first time this method is called it returns 0 and will return
472 // the actual CPU info on subsequent calls.
thakis@chromium.org022eab62010-01-13 04:55:06473 // On Windows, the CPU usage value is for all CPUs. So if you have 2 CPUs and
474 // your process is using all the cycles of 1 CPU and not the other CPU, this
475 // method returns 50.
476 double GetCPUUsage();
initial.commitd7cae122008-07-26 21:49:38477
478 // Retrieves accounting information for all I/O operations performed by the
479 // process.
480 // If IO information is retrieved successfully, the function returns true
481 // and fills in the IO_COUNTERS passed in. The function returns false
482 // otherwise.
phajdan.jr@chromium.orgd043c2cc2009-03-25 18:30:45483 bool GetIOCounters(IoCounters* io_counters) const;
initial.commitd7cae122008-07-26 21:49:38484
485 private:
viettrungluu@chromium.org3740cb9b52009-12-19 04:50:04486#if !defined(OS_MACOSX)
initial.commitd7cae122008-07-26 21:49:38487 explicit ProcessMetrics(ProcessHandle process);
viettrungluu@chromium.org3740cb9b52009-12-19 04:50:04488#else
489 ProcessMetrics(ProcessHandle process, PortProvider* port_provider);
490#endif
initial.commitd7cae122008-07-26 21:49:38491
492 ProcessHandle process_;
493
494 int processor_count_;
495
evan@chromium.orgd2ed23832009-09-19 01:57:39496 // Used to store the previous times and CPU usage counts so we can
497 // compute the CPU usage between calls.
initial.commitd7cae122008-07-26 21:49:38498 int64 last_time_;
499 int64 last_system_time_;
500
viettrungluu@chromium.org3740cb9b52009-12-19 04:50:04501#if defined(OS_MACOSX)
502 // Queries the port provider if it's set.
503 mach_port_t TaskForPid(ProcessHandle process) const;
504
505 PortProvider* port_provider_;
pvalchev@google.com66700d42010-03-10 07:46:43506#elif defined(OS_POSIX)
507 // Jiffie count at the last_time_ we updated.
508 int last_cpu_;
viettrungluu@chromium.org3740cb9b52009-12-19 04:50:04509#endif
510
initial.commitd7cae122008-07-26 21:49:38511 DISALLOW_EVIL_CONSTRUCTORS(ProcessMetrics);
512};
513
sgk@chromium.orged26d942009-11-09 06:57:28514// Returns the memory commited by the system in KBytes.
515// Returns 0 if it can't compute the commit charge.
516size_t GetSystemCommitCharge();
517
initial.commitd7cae122008-07-26 21:49:38518// Enables low fragmentation heap (LFH) for every heaps of this process. This
519// won't have any effect on heaps created after this function call. It will not
520// modify data allocated in the heaps before calling this function. So it is
521// better to call this function early in initialization and again before
522// entering the main loop.
523// Note: Returns true on Windows 2000 without doing anything.
524bool EnableLowFragmentationHeap();
525
maruel@chromium.orgd6fc9fd2009-10-27 18:03:47526// Enables 'terminate on heap corruption' flag. Helps protect against heap
maruel@google.comc9d40872008-09-24 12:58:37527// overflow. Has no effect if the OS doesn't provide the necessary facility.
528void EnableTerminationOnHeapCorruption();
529
avi@chromium.orgcccb21212009-11-12 20:39:56530#if !defined(OS_WIN)
531// Turns on process termination if memory runs out. This is handled on Windows
532// inside RegisterInvalidParamHandler().
533void EnableTerminationOnOutOfMemory();
534#endif
535
maruel@chromium.orgd6fc9fd2009-10-27 18:03:47536#if defined(UNIT_TEST)
537// Enables stack dump to console output on exception and signals.
538// When enabled, the process will quit immediately. This is meant to be used in
539// unit_tests only!
540bool EnableInProcessStackDumping();
541#endif // defined(UNIT_TEST)
542
deanm@google.comdb717282008-08-27 13:48:03543// If supported on the platform, and the user has sufficent rights, increase
544// the current process's scheduling priority to a high priority.
545void RaiseProcessToHighPriority();
546
mark@chromium.orge9a8c19f2009-09-03 21:27:36547#if defined(OS_MACOSX)
548// Restore the default exception handler, setting it to Apple Crash Reporter
549// (ReportCrash). When forking and execing a new process, the child will
550// inherit the parent's exception ports, which may be set to the Breakpad
551// instance running inside the parent. The parent's Breakpad instance should
552// not handle the child's exceptions. Calling RestoreDefaultExceptionHandler
553// in the child after forking will restore the standard exception handler.
554// See http://crbug.com/20371/ for more details.
555void RestoreDefaultExceptionHandler();
556#endif
557
brettw@google.com176aa482008-11-14 03:25:15558} // namespace base
initial.commitd7cae122008-07-26 21:49:38559
deanm@google.comdb717282008-08-27 13:48:03560#endif // BASE_PROCESS_UTIL_H_