Another take on menu's. This uses the hosting menu scroll view container as a menuba...
[chromium-blink-merge.git] / base / process_util.h
blobdbb0f1323c9ed105e3d1796a38f42ef45d1e9401
1 // Copyright (c) 2010 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 // This file/namespace contains utility functions for enumerating, ending and
6 // computing statistics of processes.
8 #ifndef BASE_PROCESS_UTIL_H_
9 #define BASE_PROCESS_UTIL_H_
10 #pragma once
12 #include "base/basictypes.h"
14 #if defined(OS_WIN)
15 #include <windows.h>
16 #include <tlhelp32.h>
17 #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.
20 struct kinfo_proc;
21 // malloc_zone_t is defined in <malloc/malloc.h>, but this forward declaration
22 // is sufficient for GetPurgeableZone() below.
23 typedef struct _malloc_zone_t malloc_zone_t;
24 #include <mach/mach.h>
25 #elif defined(OS_POSIX)
26 #include <dirent.h>
27 #include <limits.h>
28 #include <sys/types.h>
29 #endif
31 #include <list>
32 #include <string>
33 #include <utility>
34 #include <vector>
36 #include "base/file_descriptor_shuffle.h"
37 #include "base/process.h"
39 #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
47 class CommandLine;
48 class FilePath;
50 namespace base {
52 #if defined(OS_WIN)
54 struct ProcessEntry : public PROCESSENTRY32 {
55 ProcessId pid() const { return th32ProcessID; }
56 ProcessId parent_pid() const { return th32ParentProcessID; }
57 const wchar_t* exe_file() const { return szExeFile; }
60 struct IoCounters : public IO_COUNTERS {
63 #elif defined(OS_POSIX)
65 struct ProcessEntry {
66 ProcessId pid_;
67 ProcessId ppid_;
68 ProcessId gid_;
69 std::string exe_file_;
71 ProcessId pid() const { return pid_; }
72 ProcessId parent_pid() const { return ppid_; }
73 const char* exe_file() const { return exe_file_.c_str(); }
76 struct IoCounters {
77 uint64_t ReadOperationCount;
78 uint64_t WriteOperationCount;
79 uint64_t OtherOperationCount;
80 uint64_t ReadTransferCount;
81 uint64_t WriteTransferCount;
82 uint64_t OtherTransferCount;
85 #endif // defined(OS_POSIX)
87 // 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.
90 enum {
91 PROCESS_END_NORMAL_TERMINATION = 0,
92 PROCESS_END_KILLED_BY_USER = 1,
93 PROCESS_END_PROCESS_WAS_HUNG = 2
96 // Returns the id of the current process.
97 ProcessId GetCurrentProcId();
99 // Returns the ProcessHandle of the current process.
100 ProcessHandle GetCurrentProcessHandle();
102 // Converts a PID to a process handle. This handle must be closed by
103 // CloseProcessHandle when you are done with it. Returns true on success.
104 bool OpenProcessHandle(ProcessId pid, ProcessHandle* handle);
106 // 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.
110 bool OpenPrivilegedProcessHandle(ProcessId pid, ProcessHandle* handle);
112 // Closes the process handle opened by OpenProcessHandle.
113 void CloseProcessHandle(ProcessHandle process);
115 // Returns the unique ID for the specified process. This is functionally the
116 // same as Windows' GetProcessId(), but works on versions of Windows before
117 // Win XP SP1 as well.
118 ProcessId GetProcId(ProcessHandle process);
120 #if defined(OS_LINUX)
121 // Returns the ID for the parent of the given process.
122 ProcessId GetParentProcessId(ProcessHandle process);
124 // Returns the path to the executable of the given process.
125 FilePath GetProcessExecutablePath(ProcessHandle process);
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.
130 int ParseProcStatCPU(const std::string& input);
132 static const char kAdjustOOMScoreSwitch[] = "--adjust-oom-score";
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.
137 bool AdjustOOMScore(ProcessId process, int score);
138 #endif
140 #if defined(OS_POSIX)
141 // 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.
144 void CloseSuperfluousFds(const InjectiveMultimap& saved_map);
145 #endif
147 #if defined(OS_WIN)
148 // 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.
152 // If wait is true, it will block and wait for the other process to finish,
153 // otherwise, it will just continue asynchronously.
155 // Example (including literal quotes)
156 // cmdline = "c:\windows\explorer.exe" -foo "c:\bar\"
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!
162 bool LaunchApp(const std::wstring& cmdline,
163 bool wait, bool start_hidden, ProcessHandle* process_handle);
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.
169 // Whether the application is visible on the interactive desktop depends on
170 // the token belonging to an interactive logon session.
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.
175 bool LaunchAppAsUser(UserTokenHandle token, const std::wstring& cmdline,
176 bool start_hidden, ProcessHandle* process_handle);
178 // Has the same behavior as LaunchAppAsUser, but offers the boolean option to
179 // use an empty string for the desktop name.
180 bool LaunchAppAsUser(UserTokenHandle token, const std::wstring& cmdline,
181 bool start_hidden, ProcessHandle* process_handle,
182 bool empty_desktop_name);
185 #elif defined(OS_POSIX)
186 // Runs the application specified in argv[0] with the command line argv.
187 // 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.
191 // As above, if wait is true, execute synchronously. The pid will be stored
192 // in process_handle if that pointer is non-null.
194 // 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.
196 typedef std::vector<std::pair<int, int> > file_handle_mapping_vector;
197 bool LaunchApp(const std::vector<std::string>& argv,
198 const file_handle_mapping_vector& fds_to_remap,
199 bool wait, ProcessHandle* process_handle);
201 // Similar to the above, but also (un)set environment variables in child process
202 // through |environ|.
203 typedef std::vector<std::pair<std::string, std::string> > environment_vector;
204 bool 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);
209 // 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.
215 // The returned array is allocated using new[] and must be freed by the caller.
216 char** AlterEnvironment(const environment_vector& changes,
217 const char* const* const env);
219 #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.
223 bool 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)
230 #endif // defined(OS_POSIX)
232 // Executes the application specified by cl. This function delegates to one
233 // of the above two platform-specific functions.
234 bool LaunchApp(const CommandLine& cl,
235 bool wait, bool start_hidden, ProcessHandle* process_handle);
237 // Executes the application specified by |cl| and wait for it to exit. Stores
238 // the output (stdout) in |output|. Redirects stderr to /dev/null. Returns true
239 // on success (application launched and exited cleanly, with exit code
240 // indicating success).
241 bool GetAppOutput(const CommandLine& cl, std::string* output);
243 #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.
247 bool GetAppOutputRestricted(const CommandLine& cl,
248 std::string* output, size_t max_output);
249 #endif
251 // Used to filter processes by process ID.
252 class 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.
256 virtual bool Includes(const ProcessEntry& entry) const = 0;
258 protected:
259 virtual ~ProcessFilter() {}
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.
265 int GetProcessCount(const std::wstring& executable_name,
266 const ProcessFilter* filter);
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.
273 bool KillProcesses(const std::wstring& executable_name, int exit_code,
274 const ProcessFilter* filter);
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.
280 bool KillProcess(ProcessHandle process, int exit_code, bool wait);
281 #if defined(OS_WIN)
282 bool KillProcessById(ProcessId process_id, int exit_code, bool wait);
283 #endif
285 // Get the termination status (exit code) of the process and return true if the
286 // status indicates the process crashed. |child_exited| is set to true iff the
287 // child process has terminated. (|child_exited| may be NULL.)
288 bool DidProcessCrash(bool* child_exited, ProcessHandle handle);
290 // 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.
294 bool WaitForExitCode(ProcessHandle handle, int* exit_code);
296 // 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|).
301 bool WaitForExitCodeWithTimeout(ProcessHandle handle, int* exit_code,
302 int64 timeout_milliseconds);
304 // 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.
308 bool WaitForProcessesToExit(const std::wstring& executable_name,
309 int64 wait_milliseconds,
310 const ProcessFilter* filter);
312 // Wait for a single process to exit. Return true if it exited cleanly within
313 // the given time limit.
314 bool WaitForSingleProcess(ProcessHandle handle,
315 int64 wait_milliseconds);
317 // Returns true when |wait_milliseconds| have elapsed and the process
318 // is still running.
319 bool CrashAwareSleep(ProcessHandle handle, int64 wait_milliseconds);
321 // 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.
327 bool CleanupProcesses(const std::wstring& executable_name,
328 int64 wait_milliseconds,
329 int exit_code,
330 const ProcessFilter* filter);
332 // 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.
336 class ProcessIterator {
337 public:
338 typedef std::list<ProcessEntry> ProcessEntries;
340 explicit ProcessIterator(const ProcessFilter* filter);
341 virtual ~ProcessIterator();
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();
350 // Takes a snapshot of all the ProcessEntry found.
351 ProcessEntries Snapshot();
353 protected:
354 virtual bool IncludeEntry();
355 const ProcessEntry& entry() { return entry_; }
357 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();
363 // Initializes a PROCESSENTRY32 data structure so that it's ready for
364 // use with Process32First/Process32Next.
365 void InitProcessEntry(ProcessEntry* entry);
367 #if defined(OS_WIN)
368 HANDLE snapshot_;
369 bool started_iteration_;
370 #elif defined(OS_MACOSX)
371 std::vector<kinfo_proc> kinfo_procs_;
372 size_t index_of_kinfo_proc_;
373 #elif defined(OS_POSIX)
374 DIR *procfs_dir_;
375 #endif
376 ProcessEntry entry_;
377 const ProcessFilter* filter_;
379 DISALLOW_COPY_AND_ASSIGN(ProcessIterator);
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.
386 class NamedProcessIterator : public ProcessIterator {
387 public:
388 NamedProcessIterator(const std::wstring& executable_name,
389 const ProcessFilter* filter);
390 virtual ~NamedProcessIterator();
392 protected:
393 virtual bool IncludeEntry();
395 private:
396 std::wstring executable_name_;
398 DISALLOW_COPY_AND_ASSIGN(NamedProcessIterator);
401 // Working Set (resident) memory usage broken down by
403 // On Windows:
404 // 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.
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
415 // On OS X: TODO(thakis): Revise.
416 // priv: Memory.
417 // shared: 0
418 // shareable: 0
419 struct WorkingSetKBytes {
420 WorkingSetKBytes() : priv(0), shareable(0), shared(0) {}
421 size_t priv;
422 size_t shareable;
423 size_t shared;
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)
432 struct CommittedKBytes {
433 CommittedKBytes() : priv(0), mapped(0), image(0) {}
434 size_t priv;
435 size_t mapped;
436 size_t image;
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.
444 struct FreeMBytes {
445 size_t total;
446 size_t largest;
447 void* largest_ptr;
450 // Convert a POSIX timeval to microseconds.
451 int64 TimeValToMicroseconds(const struct timeval& tv);
453 // 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.
457 class ProcessMetrics {
458 public:
459 // Creates a ProcessMetrics for the specified process.
460 // The caller owns the returned object.
461 #if !defined(OS_MACOSX)
462 static ProcessMetrics* CreateProcessMetrics(ProcessHandle process);
463 #else
464 class PortProvider {
465 public:
466 // 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).
470 virtual mach_port_t TaskForPid(ProcessHandle process) const = 0;
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);
478 #endif // !defined(OS_MACOSX)
480 ~ProcessMetrics();
482 // Returns the current space allocated for the pagefile, in bytes (these pages
483 // may or may not be in memory). On Linux, this returns the total virtual
484 // memory size.
485 size_t GetPagefileUsage() const;
486 // Returns the peak space allocated for the pagefile, in bytes.
487 size_t GetPeakPagefileUsage() const;
488 // Returns the current working set size, in bytes. On Linux, this returns
489 // the resident set size.
490 size_t GetWorkingSetSize() const;
491 // Returns the peak working set size, in bytes.
492 size_t GetPeakWorkingSetSize() const;
493 // 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);
499 // Fills a CommittedKBytes with both resident and paged
500 // memory usage as per definition of CommittedBytes.
501 void GetCommittedKBytes(CommittedKBytes* usage) const;
502 // Fills a WorkingSetKBytes containing resident private and shared memory
503 // usage in bytes, as per definition of WorkingSetBytes.
504 bool GetWorkingSetKBytes(WorkingSetKBytes* ws_usage) const;
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.
510 bool CalculateFreeMemory(FreeMBytes* free) const;
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.
515 // 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();
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.
525 bool GetIOCounters(IoCounters* io_counters) const;
527 private:
528 #if !defined(OS_MACOSX)
529 explicit ProcessMetrics(ProcessHandle process);
530 #else
531 ProcessMetrics(ProcessHandle process, PortProvider* port_provider);
532 #endif // !defined(OS_MACOSX)
534 ProcessHandle process_;
536 int processor_count_;
538 // Used to store the previous times and CPU usage counts so we can
539 // compute the CPU usage between calls.
540 int64 last_time_;
541 int64 last_system_time_;
543 #if defined(OS_MACOSX)
544 // Queries the port provider if it's set.
545 mach_port_t TaskForPid(ProcessHandle process) const;
547 PortProvider* port_provider_;
548 #elif defined(OS_POSIX)
549 // Jiffie count at the last_time_ we updated.
550 int last_cpu_;
551 #endif // defined(OS_MACOSX)
553 DISALLOW_COPY_AND_ASSIGN(ProcessMetrics);
556 // Returns the memory commited by the system in KBytes.
557 // Returns 0 if it can't compute the commit charge.
558 size_t GetSystemCommitCharge();
560 // 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.
566 bool EnableLowFragmentationHeap();
568 // Enables 'terminate on heap corruption' flag. Helps protect against heap
569 // overflow. Has no effect if the OS doesn't provide the necessary facility.
570 void EnableTerminationOnHeapCorruption();
572 #if !defined(OS_WIN)
573 // Turns on process termination if memory runs out. This is handled on Windows
574 // inside RegisterInvalidParamHandler().
575 void EnableTerminationOnOutOfMemory();
576 #if defined(OS_MACOSX)
577 // Exposed for testing.
578 malloc_zone_t* GetPurgeableZone();
579 #endif
580 #endif
582 #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!
586 bool EnableInProcessStackDumping();
587 #endif // defined(UNIT_TEST)
589 // If supported on the platform, and the user has sufficent rights, increase
590 // the current process's scheduling priority to a high priority.
591 void RaiseProcessToHighPriority();
593 #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.
601 void RestoreDefaultExceptionHandler();
602 #endif // defined(OS_MACOSX)
604 } // namespace base
606 #endif // BASE_PROCESS_UTIL_H_