[go: nahoru, domu]

blob: dbb0f1323c9ed105e3d1796a38f42ef45d1e9401 [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_;
70
71 ProcessId pid() const { return pid_; }
72 ProcessId parent_pid() const { return ppid_; }
73 const char* exe_file() const { return exe_file_.c_str(); }
dkegel@google.comab0e2222008-10-31 20:19:4374};
75
evanm@google.com0b100bc82008-10-14 20:49:1676struct IoCounters {
evan@chromium.org34b2b002009-11-20 06:53:2877 uint64_t ReadOperationCount;
78 uint64_t WriteOperationCount;
79 uint64_t OtherOperationCount;
80 uint64_t ReadTransferCount;
81 uint64_t WriteTransferCount;
82 uint64_t OtherTransferCount;
evanm@google.com0b100bc82008-10-14 20:49:1683};
agl@chromium.org3f04f2b2009-04-30 19:40:0384
maruel@chromium.orga5a00b1d2010-04-08 15:52:4585#endif // defined(OS_POSIX)
initial.commitd7cae122008-07-26 21:49:3886
cpu@google.comeef576f2008-11-03 23:28:0687// A minimalistic but hopefully cross-platform set of exit codes.
88// Do not change the enumeration values or you will break third-party
89// installers.
90enum {
thestig@chromium.orge68639f52010-04-08 19:52:2191 PROCESS_END_NORMAL_TERMINATION = 0,
92 PROCESS_END_KILLED_BY_USER = 1,
93 PROCESS_END_PROCESS_WAS_HUNG = 2
cpu@google.comeef576f2008-11-03 23:28:0694};
95
initial.commitd7cae122008-07-26 21:49:3896// Returns the id of the current process.
phajdan.jr@chromium.org43cf3252009-04-01 09:19:3797ProcessId GetCurrentProcId();
initial.commitd7cae122008-07-26 21:49:3898
erikkay@google.com113ab132008-09-18 20:42:5599// Returns the ProcessHandle of the current process.
100ProcessHandle GetCurrentProcessHandle();
maruel@chromium.org52a261f2009-03-03 15:01:12101
brettw@google.com5986ed22009-02-06 00:19:17102// Converts a PID to a process handle. This handle must be closed by
phajdan.jr@chromium.org6c6cc802009-04-03 17:01:36103// CloseProcessHandle when you are done with it. Returns true on success.
104bool OpenProcessHandle(ProcessId pid, ProcessHandle* handle);
maruel@chromium.org52a261f2009-03-03 15:01:12105
phajdan.jr@chromium.org5d438dbad2009-04-30 08:59:39106// Converts a PID to a process handle. On Windows the handle is opened
107// with more access rights and must only be used by trusted code.
108// You have to close returned handle using CloseProcessHandle. Returns true
109// on success.
110bool OpenPrivilegedProcessHandle(ProcessId pid, ProcessHandle* handle);
111
brettw@google.com5986ed22009-02-06 00:19:17112// Closes the process handle opened by OpenProcessHandle.
113void CloseProcessHandle(ProcessHandle process);
erikkay@google.com113ab132008-09-18 20:42:55114
cpu@google.comeef576f2008-11-03 23:28:06115// Returns the unique ID for the specified process. This is functionally the
initial.commitd7cae122008-07-26 21:49:38116// same as Windows' GetProcessId(), but works on versions of Windows before
117// Win XP SP1 as well.
phajdan.jr@chromium.org43cf3252009-04-01 09:19:37118ProcessId GetProcId(ProcessHandle process);
initial.commitd7cae122008-07-26 21:49:38119
dkegel@google.com78c6dd62009-06-08 23:29:11120#if defined(OS_LINUX)
121// Returns the ID for the parent of the given process.
122ProcessId GetParentProcessId(ProcessHandle process);
123
124// Returns the path to the executable of the given process.
125FilePath GetProcessExecutablePath(ProcessHandle process);
evan@chromium.orgd2ed23832009-09-19 01:57:39126
127// Parse the data found in /proc/<pid>/stat and return the sum of the
128// CPU-related ticks. Returns -1 on parse error.
129// Exposed for testing.
130int ParseProcStatCPU(const std::string& input);
thestig@chromium.orge5856a7a2009-12-10 02:08:10131
132static const char kAdjustOOMScoreSwitch[] = "--adjust-oom-score";
133
134// This adjusts /proc/process/oom_adj so the Linux OOM killer will prefer
135// certain process types over others. The range for the adjustment is
136// [-17,15], with [0,15] being user accessible.
137bool AdjustOOMScore(ProcessId process, int score);
dkegel@google.com78c6dd62009-06-08 23:29:11138#endif
139
jeremy@chromium.orgfa3097a6a52008-12-17 22:41:50140#if defined(OS_POSIX)
agl@chromium.org3f04f2b2009-04-30 19:40:03141// Close all file descriptors, expect those which are a destination in the
142// given multimap. Only call this function in a child process where you know
143// that there aren't any other threads.
maruel@chromium.orgb6128aa2010-04-29 17:44:42144void CloseSuperfluousFds(const InjectiveMultimap& saved_map);
jeremy@chromium.orgfa3097a6a52008-12-17 22:41:50145#endif
146
estade@chromium.orgfb7f9be2008-10-22 01:15:47147#if defined(OS_WIN)
initial.commitd7cae122008-07-26 21:49:38148// Runs the given application name with the given command line. Normally, the
149// first command line argument should be the path to the process, and don't
150// forget to quote it.
151//
152// If wait is true, it will block and wait for the other process to finish,
153// otherwise, it will just continue asynchronously.
154//
155// Example (including literal quotes)
156// cmdline = "c:\windows\explorer.exe" -foo "c:\bar\"
157//
158// If process_handle is non-NULL, the process handle of the launched app will be
159// stored there on a successful launch.
160// NOTE: In this case, the caller is responsible for closing the handle so
161// that it doesn't leak!
162bool LaunchApp(const std::wstring& cmdline,
estade@chromium.orgfb7f9be2008-10-22 01:15:47163 bool wait, bool start_hidden, ProcessHandle* process_handle);
cpu@chromium.orge50130b2010-02-01 03:28:47164
165// Runs the given application name with the given command line as if the user
166// represented by |token| had launched it. The caveats about |cmdline| and
167// |process_handle| explained for LaunchApp above apply as well.
168//
169// Whether the application is visible on the interactive desktop depends on
170// the token belonging to an interactive logon session.
171//
172// To avoid hard to diagnose problems, this function internally loads the
173// environment variables associated with the user and if this operation fails
174// the entire call fails as well.
175bool LaunchAppAsUser(UserTokenHandle token, const std::wstring& cmdline,
176 bool start_hidden, ProcessHandle* process_handle);
177
gwilson@google.comc020ddc2010-02-18 23:01:52178// Has the same behavior as LaunchAppAsUser, but offers the boolean option to
179// use an empty string for the desktop name.
180bool LaunchAppAsUser(UserTokenHandle token, const std::wstring& cmdline,
181 bool start_hidden, ProcessHandle* process_handle,
182 bool empty_desktop_name);
183
184
estade@chromium.orgfb7f9be2008-10-22 01:15:47185#elif defined(OS_POSIX)
186// Runs the application specified in argv[0] with the command line argv.
jeremy@chromium.orgfa3097a6a52008-12-17 22:41:50187// Before launching all FDs open in the parent process will be marked as
188// close-on-exec. |fds_to_remap| defines a mapping of src fd->dest fd to
189// propagate FDs into the child process.
estade@chromium.orgfb7f9be2008-10-22 01:15:47190//
191// As above, if wait is true, execute synchronously. The pid will be stored
192// in process_handle if that pointer is non-null.
193//
mattm@chromium.orgb74d21b32009-07-17 19:36:00194// Note that the first argument in argv must point to the executable filename.
195// If the filename is not fully specified, PATH will be searched.
jeremy@chromium.orgfa3097a6a52008-12-17 22:41:50196typedef std::vector<std::pair<int, int> > file_handle_mapping_vector;
estade@chromium.orgfb7f9be2008-10-22 01:15:47197bool LaunchApp(const std::vector<std::string>& argv,
jeremy@chromium.orgfa3097a6a52008-12-17 22:41:50198 const file_handle_mapping_vector& fds_to_remap,
estade@chromium.orgfb7f9be2008-10-22 01:15:47199 bool wait, ProcessHandle* process_handle);
stuartmorgan@google.com2aea9e092009-08-06 20:03:01200
thakis@chromium.orgc0028792010-01-12 00:39:15201// Similar to the above, but also (un)set environment variables in child process
thestig@chromium.org9ec8db02009-07-21 07:00:13202// through |environ|.
jam@chromium.org3d2217d2009-11-23 21:26:47203typedef std::vector<std::pair<std::string, std::string> > environment_vector;
thestig@chromium.org9ec8db02009-07-21 07:00:13204bool LaunchApp(const std::vector<std::string>& argv,
205 const environment_vector& environ,
206 const file_handle_mapping_vector& fds_to_remap,
207 bool wait, ProcessHandle* process_handle);
thakis@chromium.orgc0028792010-01-12 00:39:15208
agl@chromium.orgef73044e2010-03-11 15:25:54209// AlterEnvironment returns a modified environment vector, constructed from the
210// given environment and the list of changes given in |changes|. Each key in
211// the environment is matched against the first element of the pairs. In the
212// event of a match, the value is replaced by the second of the pair, unless
213// the second is empty, in which case the key-value is removed.
214//
215// The returned array is allocated using new[] and must be freed by the caller.
216char** AlterEnvironment(const environment_vector& changes,
217 const char* const* const env);
218
thakis@chromium.orgc0028792010-01-12 00:39:15219#if defined(OS_MACOSX)
220// Similar to the above, but also returns the new process's task_t if
221// |task_handle| is not NULL. If |task_handle| is not NULL, the caller is
222// responsible for calling |mach_port_deallocate()| on the returned handle.
223bool LaunchAppAndGetTask(const std::vector<std::string>& argv,
224 const environment_vector& environ,
225 const file_handle_mapping_vector& fds_to_remap,
226 bool wait,
227 task_t* task_handle,
228 ProcessHandle* process_handle);
229#endif // defined(OS_MACOSX)
thestig@chromium.org9ec8db02009-07-21 07:00:13230#endif // defined(OS_POSIX)
estade@chromium.orgfb7f9be2008-10-22 01:15:47231
jcampan@chromium.org1e312112009-04-21 21:44:12232// Executes the application specified by cl. This function delegates to one
estade@chromium.orgfb7f9be2008-10-22 01:15:47233// of the above two platform-specific functions.
234bool LaunchApp(const CommandLine& cl,
initial.commitd7cae122008-07-26 21:49:38235 bool wait, bool start_hidden, ProcessHandle* process_handle);
236
jcampan@chromium.org1e312112009-04-21 21:44:12237// Executes the application specified by |cl| and wait for it to exit. Stores
phajdan.jr@chromium.org1912cfe2009-04-21 08:09:30238// the output (stdout) in |output|. Redirects stderr to /dev/null. Returns true
239// on success (application launched and exited cleanly, with exit code
maruel@chromium.org96878a212010-06-10 18:26:33240// indicating success).
phajdan.jr@chromium.orgc0b210ee2009-04-17 09:57:52241bool GetAppOutput(const CommandLine& cl, std::string* output);
phajdan.jr@chromium.orgc0b210ee2009-04-17 09:57:52242
viettrungluu@chromium.orgf164cea2009-11-05 23:37:40243#if defined(OS_POSIX)
244// A restricted version of |GetAppOutput()| which (a) clears the environment,
245// and (b) stores at most |max_output| bytes; also, it doesn't search the path
246// for the command.
247bool GetAppOutputRestricted(const CommandLine& cl,
248 std::string* output, size_t max_output);
249#endif
250
initial.commitd7cae122008-07-26 21:49:38251// Used to filter processes by process ID.
252class ProcessFilter {
253 public:
254 // Returns true to indicate set-inclusion and false otherwise. This method
255 // should not have side-effects and should be idempotent.
maruel@chromium.orgb6128aa2010-04-29 17:44:42256 virtual bool Includes(const ProcessEntry& entry) const = 0;
ziadh@chromium.org695092f2010-08-02 16:34:16257
258 protected:
259 virtual ~ProcessFilter() {}
initial.commitd7cae122008-07-26 21:49:38260};
261
262// Returns the number of processes on the machine that are running from the
263// given executable name. If filter is non-null, then only processes selected
264// by the filter will be counted.
265int GetProcessCount(const std::wstring& executable_name,
266 const ProcessFilter* filter);
267
268// Attempts to kill all the processes on the current machine that were launched
269// from the given executable name, ending them with the given exit code. If
270// filter is non-null, then only processes selected by the filter are killed.
271// Returns false if all processes were able to be killed off, false if at least
272// one couldn't be killed.
273bool KillProcesses(const std::wstring& executable_name, int exit_code,
274 const ProcessFilter* filter);
275
276// Attempts to kill the process identified by the given process
277// entry structure, giving it the specified exit code. If |wait| is true, wait
278// for the process to be actually terminated before returning.
279// Returns true if this is successful, false otherwise.
stoyan@chromium.orgcd4fd152009-02-09 19:28:41280bool KillProcess(ProcessHandle process, int exit_code, bool wait);
agl@chromium.orgdfe14862009-01-22 01:23:11281#if defined(OS_WIN)
phajdan.jr@chromium.org43cf3252009-04-01 09:19:37282bool KillProcessById(ProcessId process_id, int exit_code, bool wait);
agl@chromium.orgdfe14862009-01-22 01:23:11283#endif
initial.commitd7cae122008-07-26 21:49:38284
285// Get the termination status (exit code) of the process and return true if the
agl@chromium.org140a7cd2009-04-28 01:37:23286// status indicates the process crashed. |child_exited| is set to true iff the
287// child process has terminated. (|child_exited| may be NULL.)
agl@chromium.org140a7cd2009-04-28 01:37:23288bool DidProcessCrash(bool* child_exited, ProcessHandle handle);
initial.commitd7cae122008-07-26 21:49:38289
phajdan.jr@chromium.orgc7856632009-01-13 17:38:49290// Waits for process to exit. In POSIX systems, if the process hasn't been
291// signaled then puts the exit code in |exit_code|; otherwise it's considered
292// a failure. On Windows |exit_code| is always filled. Returns true on success,
293// and closes |handle| in any case.
294bool WaitForExitCode(ProcessHandle handle, int* exit_code);
295
phajdan.jr@chromium.org8004e682010-03-16 07:41:22296// Waits for process to exit. If it did exit within |timeout_milliseconds|,
297// then puts the exit code in |exit_code|, closes |handle|, and returns true.
298// In POSIX systems, if the process has been signaled then |exit_code| is set
299// to -1. Returns false on failure (the caller is then responsible for closing
300// |handle|).
301bool WaitForExitCodeWithTimeout(ProcessHandle handle, int* exit_code,
302 int64 timeout_milliseconds);
303
initial.commitd7cae122008-07-26 21:49:38304// Wait for all the processes based on the named executable to exit. If filter
305// is non-null, then only processes selected by the filter are waited on.
306// Returns after all processes have exited or wait_milliseconds have expired.
307// Returns true if all the processes exited, false otherwise.
308bool WaitForProcessesToExit(const std::wstring& executable_name,
phajdan.jr@chromium.org743ace42009-06-17 17:23:51309 int64 wait_milliseconds,
initial.commitd7cae122008-07-26 21:49:38310 const ProcessFilter* filter);
311
estade@chromium.orgfb7f9be2008-10-22 01:15:47312// Wait for a single process to exit. Return true if it exited cleanly within
313// the given time limit.
314bool WaitForSingleProcess(ProcessHandle handle,
phajdan.jr@chromium.org743ace42009-06-17 17:23:51315 int64 wait_milliseconds);
estade@chromium.orgfb7f9be2008-10-22 01:15:47316
phajdan.jr@chromium.org076bf0b62009-03-04 20:57:58317// Returns true when |wait_milliseconds| have elapsed and the process
318// is still running.
phajdan.jr@chromium.org743ace42009-06-17 17:23:51319bool CrashAwareSleep(ProcessHandle handle, int64 wait_milliseconds);
phajdan.jr@chromium.org076bf0b62009-03-04 20:57:58320
initial.commitd7cae122008-07-26 21:49:38321// Waits a certain amount of time (can be 0) for all the processes with a given
322// executable name to exit, then kills off any of them that are still around.
323// If filter is non-null, then only processes selected by the filter are waited
324// on. Killed processes are ended with the given exit code. Returns false if
325// any processes needed to be killed, true if they all exited cleanly within
326// the wait_milliseconds delay.
327bool CleanupProcesses(const std::wstring& executable_name,
phajdan.jr@chromium.org743ace42009-06-17 17:23:51328 int64 wait_milliseconds,
initial.commitd7cae122008-07-26 21:49:38329 int exit_code,
330 const ProcessFilter* filter);
331
maruel@chromium.orgb6128aa2010-04-29 17:44:42332// This class provides a way to iterate through a list of processes on the
333// current machine with a specified filter.
334// To use, create an instance and then call NextProcessEntry() until it returns
335// false.
336class ProcessIterator {
initial.commitd7cae122008-07-26 21:49:38337 public:
maruel@chromium.orgbaead4f2010-06-11 19:10:30338 typedef std::list<ProcessEntry> ProcessEntries;
339
maruel@chromium.orgb6128aa2010-04-29 17:44:42340 explicit ProcessIterator(const ProcessFilter* filter);
341 virtual ~ProcessIterator();
initial.commitd7cae122008-07-26 21:49:38342
343 // If there's another process that matches the given executable name,
344 // returns a const pointer to the corresponding PROCESSENTRY32.
345 // If there are no more matching processes, returns NULL.
346 // The returned pointer will remain valid until NextProcessEntry()
347 // is called again or this NamedProcessIterator goes out of scope.
348 const ProcessEntry* NextProcessEntry();
349
maruel@chromium.orgb6128aa2010-04-29 17:44:42350 // Takes a snapshot of all the ProcessEntry found.
maruel@chromium.orgbaead4f2010-06-11 19:10:30351 ProcessEntries Snapshot();
maruel@chromium.orgb6128aa2010-04-29 17:44:42352
353 protected:
354 virtual bool IncludeEntry();
355 const ProcessEntry& entry() { return entry_; }
356
initial.commitd7cae122008-07-26 21:49:38357 private:
358 // Determines whether there's another process (regardless of executable)
359 // left in the list of all processes. Returns true and sets entry_ to
360 // that process's info if there is one, false otherwise.
361 bool CheckForNextProcess();
362
initial.commitd7cae122008-07-26 21:49:38363 // Initializes a PROCESSENTRY32 data structure so that it's ready for
364 // use with Process32First/Process32Next.
365 void InitProcessEntry(ProcessEntry* entry);
dkegel@google.comab0e2222008-10-31 20:19:43366
367#if defined(OS_WIN)
initial.commitd7cae122008-07-26 21:49:38368 HANDLE snapshot_;
initial.commitd7cae122008-07-26 21:49:38369 bool started_iteration_;
dkegel@google.comab0e2222008-10-31 20:19:43370#elif defined(OS_MACOSX)
mark@chromium.org962dd312009-02-05 21:44:13371 std::vector<kinfo_proc> kinfo_procs_;
372 size_t index_of_kinfo_proc_;
wtc@chromium.org4a34ce02009-08-31 22:25:00373#elif defined(OS_POSIX)
374 DIR *procfs_dir_;
dkegel@google.comab0e2222008-10-31 20:19:43375#endif
initial.commitd7cae122008-07-26 21:49:38376 ProcessEntry entry_;
377 const ProcessFilter* filter_;
378
maruel@chromium.orgb6128aa2010-04-29 17:44:42379 DISALLOW_COPY_AND_ASSIGN(ProcessIterator);
380};
381
382// This class provides a way to iterate through the list of processes
383// on the current machine that were started from the given executable
384// name. To use, create an instance and then call NextProcessEntry()
385// until it returns false.
386class NamedProcessIterator : public ProcessIterator {
387 public:
388 NamedProcessIterator(const std::wstring& executable_name,
389 const ProcessFilter* filter);
390 virtual ~NamedProcessIterator();
391
392 protected:
393 virtual bool IncludeEntry();
394
395 private:
396 std::wstring executable_name_;
397
398 DISALLOW_COPY_AND_ASSIGN(NamedProcessIterator);
initial.commitd7cae122008-07-26 21:49:38399};
400
401// Working Set (resident) memory usage broken down by
agl@chromium.org54fd1d32009-09-01 00:12:58402//
403// On Windows:
initial.commitd7cae122008-07-26 21:49:38404// priv (private): These pages (kbytes) cannot be shared with any other process.
405// shareable: These pages (kbytes) can be shared with other processes under
406// the right circumstances.
407// shared : These pages (kbytes) are currently shared with at least one
408// other process.
agl@chromium.org54fd1d32009-09-01 00:12:58409//
410// On Linux:
411// priv: Pages mapped only by this process
412// shared: PSS or 0 if the kernel doesn't support this
413// shareable: 0
viettrungluu@chromium.org3740cb9b52009-12-19 04:50:04414//
415// On OS X: TODO(thakis): Revise.
416// priv: Memory.
417// shared: 0
418// shareable: 0
initial.commitd7cae122008-07-26 21:49:38419struct WorkingSetKBytes {
agl@chromium.org54fd1d32009-09-01 00:12:58420 WorkingSetKBytes() : priv(0), shareable(0), shared(0) {}
initial.commitd7cae122008-07-26 21:49:38421 size_t priv;
422 size_t shareable;
423 size_t shared;
424};
425
426// Committed (resident + paged) memory usage broken down by
427// private: These pages cannot be shared with any other process.
428// mapped: These pages are mapped into the view of a section (backed by
429// pagefile.sys)
430// image: These pages are mapped into the view of an image section (backed by
431// file system)
432struct CommittedKBytes {
agl@chromium.org54fd1d32009-09-01 00:12:58433 CommittedKBytes() : priv(0), mapped(0), image(0) {}
initial.commitd7cae122008-07-26 21:49:38434 size_t priv;
435 size_t mapped;
436 size_t image;
437};
438
439// Free memory (Megabytes marked as free) in the 2G process address space.
440// total : total amount in megabytes marked as free. Maximum value is 2048.
441// largest : size of the largest contiguous amount of memory found. It is
442// always smaller or equal to FreeMBytes::total.
443// largest_ptr: starting address of the largest memory block.
444struct FreeMBytes {
445 size_t total;
446 size_t largest;
447 void* largest_ptr;
448};
449
evan@chromium.orgd2ed23832009-09-19 01:57:39450// Convert a POSIX timeval to microseconds.
451int64 TimeValToMicroseconds(const struct timeval& tv);
452
initial.commitd7cae122008-07-26 21:49:38453// Provides performance metrics for a specified process (CPU usage, memory and
454// IO counters). To use it, invoke CreateProcessMetrics() to get an instance
455// for a specific process, then access the information with the different get
456// methods.
457class ProcessMetrics {
458 public:
459 // Creates a ProcessMetrics for the specified process.
460 // The caller owns the returned object.
viettrungluu@chromium.org3740cb9b52009-12-19 04:50:04461#if !defined(OS_MACOSX)
initial.commitd7cae122008-07-26 21:49:38462 static ProcessMetrics* CreateProcessMetrics(ProcessHandle process);
viettrungluu@chromium.org3740cb9b52009-12-19 04:50:04463#else
464 class PortProvider {
465 public:
thakis@chromium.orgb2e8e082009-12-21 17:44:20466 // Should return the mach task for |process| if possible, or else
467 // |MACH_PORT_NULL|. Only processes that this returns tasks for will have
468 // metrics on OS X (except for the current process, which always gets
469 // metrics).
viettrungluu@chromium.org3740cb9b52009-12-19 04:50:04470 virtual mach_port_t TaskForPid(ProcessHandle process) const = 0;
471 };
472
473 // The port provider needs to outlive the ProcessMetrics object returned by
474 // this function. If NULL is passed as provider, the returned object
475 // only returns valid metrics if |process| is the current process.
476 static ProcessMetrics* CreateProcessMetrics(ProcessHandle process,
477 PortProvider* port_provider);
maruel@chromium.orgb6128aa2010-04-29 17:44:42478#endif // !defined(OS_MACOSX)
initial.commitd7cae122008-07-26 21:49:38479
480 ~ProcessMetrics();
481
482 // Returns the current space allocated for the pagefile, in bytes (these pages
thomasvl@chromium.org796da7c2009-06-11 12:45:45483 // may or may not be in memory). On Linux, this returns the total virtual
484 // memory size.
phajdan.jr@chromium.orgd043c2cc2009-03-25 18:30:45485 size_t GetPagefileUsage() const;
initial.commitd7cae122008-07-26 21:49:38486 // Returns the peak space allocated for the pagefile, in bytes.
phajdan.jr@chromium.orgd043c2cc2009-03-25 18:30:45487 size_t GetPeakPagefileUsage() const;
thomasvl@chromium.org796da7c2009-06-11 12:45:45488 // Returns the current working set size, in bytes. On Linux, this returns
489 // the resident set size.
phajdan.jr@chromium.orgd043c2cc2009-03-25 18:30:45490 size_t GetWorkingSetSize() const;
tc@google.com0c557f12009-05-11 23:35:52491 // Returns the peak working set size, in bytes.
492 size_t GetPeakWorkingSetSize() const;
erg@chromium.org98947a02010-05-11 17:46:08493 // Returns private and sharedusage, in bytes. Private bytes is the amount of
494 // memory currently allocated to a process that cannot be shared. Returns
495 // false on platform specific error conditions. Note: |private_bytes|
496 // returns 0 on unsupported OSes: prior to XP SP2.
497 bool GetMemoryBytes(size_t* private_bytes,
498 size_t* shared_bytes);
initial.commitd7cae122008-07-26 21:49:38499 // Fills a CommittedKBytes with both resident and paged
500 // memory usage as per definition of CommittedBytes.
phajdan.jr@chromium.orgd043c2cc2009-03-25 18:30:45501 void GetCommittedKBytes(CommittedKBytes* usage) const;
initial.commitd7cae122008-07-26 21:49:38502 // Fills a WorkingSetKBytes containing resident private and shared memory
503 // usage in bytes, as per definition of WorkingSetBytes.
phajdan.jr@chromium.orgd043c2cc2009-03-25 18:30:45504 bool GetWorkingSetKBytes(WorkingSetKBytes* ws_usage) const;
initial.commitd7cae122008-07-26 21:49:38505
506 // Computes the current process available memory for allocation.
507 // It does a linear scan of the address space querying each memory region
508 // for its free (unallocated) status. It is useful for estimating the memory
509 // load and fragmentation.
phajdan.jr@chromium.orgd043c2cc2009-03-25 18:30:45510 bool CalculateFreeMemory(FreeMBytes* free) const;
initial.commitd7cae122008-07-26 21:49:38511
512 // Returns the CPU usage in percent since the last time this method was
513 // called. The first time this method is called it returns 0 and will return
514 // the actual CPU info on subsequent calls.
thakis@chromium.org022eab62010-01-13 04:55:06515 // On Windows, the CPU usage value is for all CPUs. So if you have 2 CPUs and
516 // your process is using all the cycles of 1 CPU and not the other CPU, this
517 // method returns 50.
518 double GetCPUUsage();
initial.commitd7cae122008-07-26 21:49:38519
520 // Retrieves accounting information for all I/O operations performed by the
521 // process.
522 // If IO information is retrieved successfully, the function returns true
523 // and fills in the IO_COUNTERS passed in. The function returns false
524 // otherwise.
phajdan.jr@chromium.orgd043c2cc2009-03-25 18:30:45525 bool GetIOCounters(IoCounters* io_counters) const;
initial.commitd7cae122008-07-26 21:49:38526
527 private:
viettrungluu@chromium.org3740cb9b52009-12-19 04:50:04528#if !defined(OS_MACOSX)
initial.commitd7cae122008-07-26 21:49:38529 explicit ProcessMetrics(ProcessHandle process);
viettrungluu@chromium.org3740cb9b52009-12-19 04:50:04530#else
531 ProcessMetrics(ProcessHandle process, PortProvider* port_provider);
maruel@chromium.orgb6128aa2010-04-29 17:44:42532#endif // !defined(OS_MACOSX)
initial.commitd7cae122008-07-26 21:49:38533
534 ProcessHandle process_;
535
536 int processor_count_;
537
evan@chromium.orgd2ed23832009-09-19 01:57:39538 // Used to store the previous times and CPU usage counts so we can
539 // compute the CPU usage between calls.
initial.commitd7cae122008-07-26 21:49:38540 int64 last_time_;
541 int64 last_system_time_;
542
viettrungluu@chromium.org3740cb9b52009-12-19 04:50:04543#if defined(OS_MACOSX)
544 // Queries the port provider if it's set.
545 mach_port_t TaskForPid(ProcessHandle process) const;
546
547 PortProvider* port_provider_;
pvalchev@google.com66700d42010-03-10 07:46:43548#elif defined(OS_POSIX)
549 // Jiffie count at the last_time_ we updated.
550 int last_cpu_;
maruel@chromium.orgb6128aa2010-04-29 17:44:42551#endif // defined(OS_MACOSX)
viettrungluu@chromium.org3740cb9b52009-12-19 04:50:04552
maruel@chromium.orgb6128aa2010-04-29 17:44:42553 DISALLOW_COPY_AND_ASSIGN(ProcessMetrics);
initial.commitd7cae122008-07-26 21:49:38554};
555
sgk@chromium.orged26d942009-11-09 06:57:28556// Returns the memory commited by the system in KBytes.
557// Returns 0 if it can't compute the commit charge.
558size_t GetSystemCommitCharge();
559
initial.commitd7cae122008-07-26 21:49:38560// Enables low fragmentation heap (LFH) for every heaps of this process. This
561// won't have any effect on heaps created after this function call. It will not
562// modify data allocated in the heaps before calling this function. So it is
563// better to call this function early in initialization and again before
564// entering the main loop.
565// Note: Returns true on Windows 2000 without doing anything.
566bool EnableLowFragmentationHeap();
567
maruel@chromium.orgd6fc9fd2009-10-27 18:03:47568// Enables 'terminate on heap corruption' flag. Helps protect against heap
maruel@google.comc9d40872008-09-24 12:58:37569// overflow. Has no effect if the OS doesn't provide the necessary facility.
570void EnableTerminationOnHeapCorruption();
571
avi@chromium.orgcccb21212009-11-12 20:39:56572#if !defined(OS_WIN)
573// Turns on process termination if memory runs out. This is handled on Windows
574// inside RegisterInvalidParamHandler().
575void EnableTerminationOnOutOfMemory();
avi@chromium.org6cfa3392010-07-01 20:11:43576#if defined(OS_MACOSX)
577// Exposed for testing.
578malloc_zone_t* GetPurgeableZone();
579#endif
avi@chromium.orgcccb21212009-11-12 20:39:56580#endif
581
maruel@chromium.orgd6fc9fd2009-10-27 18:03:47582#if defined(UNIT_TEST)
583// Enables stack dump to console output on exception and signals.
584// When enabled, the process will quit immediately. This is meant to be used in
585// unit_tests only!
586bool EnableInProcessStackDumping();
587#endif // defined(UNIT_TEST)
588
deanm@google.comdb717282008-08-27 13:48:03589// If supported on the platform, and the user has sufficent rights, increase
590// the current process's scheduling priority to a high priority.
591void RaiseProcessToHighPriority();
592
mark@chromium.orge9a8c19f2009-09-03 21:27:36593#if defined(OS_MACOSX)
594// Restore the default exception handler, setting it to Apple Crash Reporter
595// (ReportCrash). When forking and execing a new process, the child will
596// inherit the parent's exception ports, which may be set to the Breakpad
597// instance running inside the parent. The parent's Breakpad instance should
598// not handle the child's exceptions. Calling RestoreDefaultExceptionHandler
599// in the child after forking will restore the standard exception handler.
600// See http://crbug.com/20371/ for more details.
601void RestoreDefaultExceptionHandler();
maruel@chromium.orgb6128aa2010-04-29 17:44:42602#endif // defined(OS_MACOSX)
mark@chromium.orge9a8c19f2009-09-03 21:27:36603
brettw@google.com176aa482008-11-14 03:25:15604} // namespace base
initial.commitd7cae122008-07-26 21:49:38605
deanm@google.comdb717282008-08-27 13:48:03606#endif // BASE_PROCESS_UTIL_H_