Protect WebURLLoaderImpl::Context while receiving responses.
[chromium-blink-merge.git] / base / process_util.h
blob0bec8e0848e0d7e961e4ec80fc248943db60f0ca
1 // Copyright (c) 2012 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_
11 #include "base/basictypes.h"
12 #include "base/time.h"
14 #if defined(OS_WIN)
15 #include <windows.h>
16 #include <tlhelp32.h>
17 #elif defined(OS_MACOSX) || defined(OS_BSD)
18 // malloc_zone_t is defined in <malloc/malloc.h>, but this forward declaration
19 // is sufficient for GetPurgeableZone() below.
20 typedef struct _malloc_zone_t malloc_zone_t;
21 #if !defined(OS_BSD)
22 #include <mach/mach.h>
23 #endif
24 #elif defined(OS_POSIX)
25 #include <dirent.h>
26 #include <limits.h>
27 #include <sys/types.h>
28 #endif
30 #include <list>
31 #include <set>
32 #include <string>
33 #include <utility>
34 #include <vector>
36 #include "base/base_export.h"
37 #include "base/files/file_path.h"
38 #include "base/process.h"
39 #include "base/process/process_iterator.h"
40 #include "base/process/process_metrics.h"
42 #if defined(OS_POSIX)
43 #include "base/posix/file_descriptor_shuffle.h"
44 #endif
46 class CommandLine;
48 namespace base {
50 // Return status values from GetTerminationStatus. Don't use these as
51 // exit code arguments to KillProcess*(), use platform/application
52 // specific values instead.
53 enum TerminationStatus {
54 TERMINATION_STATUS_NORMAL_TERMINATION, // zero exit status
55 TERMINATION_STATUS_ABNORMAL_TERMINATION, // non-zero exit status
56 TERMINATION_STATUS_PROCESS_WAS_KILLED, // e.g. SIGKILL or task manager kill
57 TERMINATION_STATUS_PROCESS_CRASHED, // e.g. Segmentation fault
58 TERMINATION_STATUS_STILL_RUNNING, // child hasn't exited yet
59 TERMINATION_STATUS_MAX_ENUM
62 #if defined(USE_LINUX_BREAKPAD)
63 BASE_EXPORT extern size_t g_oom_size;
64 #endif
66 #if defined(OS_WIN)
67 // Output multi-process printf, cout, cerr, etc to the cmd.exe console that ran
68 // chrome. This is not thread-safe: only call from main thread.
69 BASE_EXPORT void RouteStdioToConsole();
70 #endif
72 // Returns the id of the current process.
73 BASE_EXPORT ProcessId GetCurrentProcId();
75 // Returns the ProcessHandle of the current process.
76 BASE_EXPORT ProcessHandle GetCurrentProcessHandle();
78 #if defined(OS_WIN)
79 // Returns the module handle to which an address belongs. The reference count
80 // of the module is not incremented.
81 BASE_EXPORT HMODULE GetModuleFromAddress(void* address);
82 #endif
84 // Converts a PID to a process handle. This handle must be closed by
85 // CloseProcessHandle when you are done with it. Returns true on success.
86 BASE_EXPORT bool OpenProcessHandle(ProcessId pid, ProcessHandle* handle);
88 // Converts a PID to a process handle. On Windows the handle is opened
89 // with more access rights and must only be used by trusted code.
90 // You have to close returned handle using CloseProcessHandle. Returns true
91 // on success.
92 // TODO(sanjeevr): Replace all calls to OpenPrivilegedProcessHandle with the
93 // more specific OpenProcessHandleWithAccess method and delete this.
94 BASE_EXPORT bool OpenPrivilegedProcessHandle(ProcessId pid,
95 ProcessHandle* handle);
97 // Converts a PID to a process handle using the desired access flags. Use a
98 // combination of the kProcessAccess* flags defined above for |access_flags|.
99 BASE_EXPORT bool OpenProcessHandleWithAccess(ProcessId pid,
100 uint32 access_flags,
101 ProcessHandle* handle);
103 // Closes the process handle opened by OpenProcessHandle.
104 BASE_EXPORT void CloseProcessHandle(ProcessHandle process);
106 // Returns the unique ID for the specified process. This is functionally the
107 // same as Windows' GetProcessId(), but works on versions of Windows before
108 // Win XP SP1 as well.
109 BASE_EXPORT ProcessId GetProcId(ProcessHandle process);
111 #if defined(OS_LINUX) || defined(OS_ANDROID) || defined(OS_BSD)
112 // Returns the path to the executable of the given process.
113 BASE_EXPORT FilePath GetProcessExecutablePath(ProcessHandle process);
114 #endif
116 #if defined(OS_LINUX) || defined(OS_ANDROID)
117 // Get the number of threads of |process| as available in /proc/<pid>/stat.
118 // This should be used with care as no synchronization with running threads is
119 // done. This is mostly useful to guarantee being single-threaded.
120 // Returns 0 on failure.
121 BASE_EXPORT int GetNumberOfThreads(ProcessHandle process);
123 // The maximum allowed value for the OOM score.
124 const int kMaxOomScore = 1000;
126 // This adjusts /proc/<pid>/oom_score_adj so the Linux OOM killer will
127 // prefer to kill certain process types over others. The range for the
128 // adjustment is [-1000, 1000], with [0, 1000] being user accessible.
129 // If the Linux system doesn't support the newer oom_score_adj range
130 // of [0, 1000], then we revert to using the older oom_adj, and
131 // translate the given value into [0, 15]. Some aliasing of values
132 // may occur in that case, of course.
133 BASE_EXPORT bool AdjustOOMScore(ProcessId process, int score);
135 // /proc/self/exe refers to the current executable.
136 BASE_EXPORT extern const char kProcSelfExe[];
137 #endif // defined(OS_LINUX) || defined(OS_ANDROID)
139 #if defined(OS_POSIX)
140 // Returns the ID for the parent of the given process.
141 BASE_EXPORT ProcessId GetParentProcessId(ProcessHandle process);
143 // Returns the maximum number of file descriptors that can be open by a process
144 // at once. If the number is unavailable, a conservative best guess is returned.
145 size_t GetMaxFds();
147 // Close all file descriptors, except those which are a destination in the
148 // given multimap. Only call this function in a child process where you know
149 // that there aren't any other threads.
150 BASE_EXPORT void CloseSuperfluousFds(const InjectiveMultimap& saved_map);
151 #endif // defined(OS_POSIX)
153 typedef std::vector<std::pair<std::string, std::string> > EnvironmentVector;
154 typedef std::vector<std::pair<int, int> > FileHandleMappingVector;
156 // Options for launching a subprocess that are passed to LaunchProcess().
157 // The default constructor constructs the object with default options.
158 struct LaunchOptions {
159 LaunchOptions()
160 : wait(false),
161 #if defined(OS_WIN)
162 start_hidden(false),
163 inherit_handles(false),
164 as_user(NULL),
165 empty_desktop_name(false),
166 job_handle(NULL),
167 stdin_handle(NULL),
168 stdout_handle(NULL),
169 stderr_handle(NULL),
170 force_breakaway_from_job_(false)
171 #else
172 environ(NULL),
173 fds_to_remap(NULL),
174 maximize_rlimits(NULL),
175 new_process_group(false)
176 #if defined(OS_LINUX)
177 , clone_flags(0)
178 #endif // OS_LINUX
179 #if defined(OS_CHROMEOS)
180 , ctrl_terminal_fd(-1)
181 #endif // OS_CHROMEOS
182 #endif // !defined(OS_WIN)
185 // If true, wait for the process to complete.
186 bool wait;
188 #if defined(OS_WIN)
189 bool start_hidden;
191 // If true, the new process inherits handles from the parent. In production
192 // code this flag should be used only when running short-lived, trusted
193 // binaries, because open handles from other libraries and subsystems will
194 // leak to the child process, causing errors such as open socket hangs.
195 bool inherit_handles;
197 // If non-NULL, runs as if the user represented by the token had launched it.
198 // Whether the application is visible on the interactive desktop depends on
199 // the token belonging to an interactive logon session.
201 // To avoid hard to diagnose problems, when specified this loads the
202 // environment variables associated with the user and if this operation fails
203 // the entire call fails as well.
204 UserTokenHandle as_user;
206 // If true, use an empty string for the desktop name.
207 bool empty_desktop_name;
209 // If non-NULL, launches the application in that job object. The process will
210 // be terminated immediately and LaunchProcess() will fail if assignment to
211 // the job object fails.
212 HANDLE job_handle;
214 // Handles for the redirection of stdin, stdout and stderr. The handles must
215 // be inheritable. Caller should either set all three of them or none (i.e.
216 // there is no way to redirect stderr without redirecting stdin). The
217 // |inherit_handles| flag must be set to true when redirecting stdio stream.
218 HANDLE stdin_handle;
219 HANDLE stdout_handle;
220 HANDLE stderr_handle;
222 // If set to true, ensures that the child process is launched with the
223 // CREATE_BREAKAWAY_FROM_JOB flag which allows it to breakout of the parent
224 // job if any.
225 bool force_breakaway_from_job_;
226 #else
227 // If non-NULL, set/unset environment variables.
228 // See documentation of AlterEnvironment().
229 // This pointer is owned by the caller and must live through the
230 // call to LaunchProcess().
231 const EnvironmentVector* environ;
233 // If non-NULL, remap file descriptors according to the mapping of
234 // src fd->dest fd to propagate FDs into the child process.
235 // This pointer is owned by the caller and must live through the
236 // call to LaunchProcess().
237 const FileHandleMappingVector* fds_to_remap;
239 // Each element is an RLIMIT_* constant that should be raised to its
240 // rlim_max. This pointer is owned by the caller and must live through
241 // the call to LaunchProcess().
242 const std::set<int>* maximize_rlimits;
244 // If true, start the process in a new process group, instead of
245 // inheriting the parent's process group. The pgid of the child process
246 // will be the same as its pid.
247 bool new_process_group;
249 #if defined(OS_LINUX)
250 // If non-zero, start the process using clone(), using flags as provided.
251 int clone_flags;
252 #endif // defined(OS_LINUX)
254 #if defined(OS_CHROMEOS)
255 // If non-negative, the specified file descriptor will be set as the launched
256 // process' controlling terminal.
257 int ctrl_terminal_fd;
258 #endif // defined(OS_CHROMEOS)
260 #endif // !defined(OS_WIN)
263 // Launch a process via the command line |cmdline|.
264 // See the documentation of LaunchOptions for details on |options|.
266 // Returns true upon success.
268 // Upon success, if |process_handle| is non-NULL, it will be filled in with the
269 // handle of the launched process. NOTE: In this case, the caller is
270 // responsible for closing the handle so that it doesn't leak!
271 // Otherwise, the process handle will be implicitly closed.
273 // Unix-specific notes:
274 // - All file descriptors open in the parent process will be closed in the
275 // child process except for any preserved by options::fds_to_remap, and
276 // stdin, stdout, and stderr. If not remapped by options::fds_to_remap,
277 // stdin is reopened as /dev/null, and the child is allowed to inherit its
278 // parent's stdout and stderr.
279 // - If the first argument on the command line does not contain a slash,
280 // PATH will be searched. (See man execvp.)
281 BASE_EXPORT bool LaunchProcess(const CommandLine& cmdline,
282 const LaunchOptions& options,
283 ProcessHandle* process_handle);
285 #if defined(OS_WIN)
287 enum IntegrityLevel {
288 INTEGRITY_UNKNOWN,
289 LOW_INTEGRITY,
290 MEDIUM_INTEGRITY,
291 HIGH_INTEGRITY,
293 // Determine the integrity level of the specified process. Returns false
294 // if the system does not support integrity levels (pre-Vista) or in the case
295 // of an underlying system failure.
296 BASE_EXPORT bool GetProcessIntegrityLevel(ProcessHandle process,
297 IntegrityLevel* level);
299 // Windows-specific LaunchProcess that takes the command line as a
300 // string. Useful for situations where you need to control the
301 // command line arguments directly, but prefer the CommandLine version
302 // if launching Chrome itself.
304 // The first command line argument should be the path to the process,
305 // and don't forget to quote it.
307 // Example (including literal quotes)
308 // cmdline = "c:\windows\explorer.exe" -foo "c:\bar\"
309 BASE_EXPORT bool LaunchProcess(const string16& cmdline,
310 const LaunchOptions& options,
311 ProcessHandle* process_handle);
313 #elif defined(OS_POSIX)
314 // A POSIX-specific version of LaunchProcess that takes an argv array
315 // instead of a CommandLine. Useful for situations where you need to
316 // control the command line arguments directly, but prefer the
317 // CommandLine version if launching Chrome itself.
318 BASE_EXPORT bool LaunchProcess(const std::vector<std::string>& argv,
319 const LaunchOptions& options,
320 ProcessHandle* process_handle);
322 // AlterEnvironment returns a modified environment vector, constructed from the
323 // given environment and the list of changes given in |changes|. Each key in
324 // the environment is matched against the first element of the pairs. In the
325 // event of a match, the value is replaced by the second of the pair, unless
326 // the second is empty, in which case the key-value is removed.
328 // The returned array is allocated using new[] and must be freed by the caller.
329 BASE_EXPORT char** AlterEnvironment(const EnvironmentVector& changes,
330 const char* const* const env);
331 #endif // defined(OS_POSIX)
333 #if defined(OS_WIN)
334 // Set JOBOBJECT_EXTENDED_LIMIT_INFORMATION to JobObject |job_object|.
335 // As its limit_info.BasicLimitInformation.LimitFlags has
336 // JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE.
337 // When the provide JobObject |job_object| is closed, the binded process will
338 // be terminated.
339 BASE_EXPORT bool SetJobObjectAsKillOnJobClose(HANDLE job_object);
340 #endif // defined(OS_WIN)
342 // Executes the application specified by |cl| and wait for it to exit. Stores
343 // the output (stdout) in |output|. Redirects stderr to /dev/null. Returns true
344 // on success (application launched and exited cleanly, with exit code
345 // indicating success).
346 BASE_EXPORT bool GetAppOutput(const CommandLine& cl, std::string* output);
348 #if defined(OS_POSIX)
349 // A POSIX-specific version of GetAppOutput that takes an argv array
350 // instead of a CommandLine. Useful for situations where you need to
351 // control the command line arguments directly.
352 BASE_EXPORT bool GetAppOutput(const std::vector<std::string>& argv,
353 std::string* output);
355 // A restricted version of |GetAppOutput()| which (a) clears the environment,
356 // and (b) stores at most |max_output| bytes; also, it doesn't search the path
357 // for the command.
358 BASE_EXPORT bool GetAppOutputRestricted(const CommandLine& cl,
359 std::string* output, size_t max_output);
361 // A version of |GetAppOutput()| which also returns the exit code of the
362 // executed command. Returns true if the application runs and exits cleanly. If
363 // this is the case the exit code of the application is available in
364 // |*exit_code|.
365 BASE_EXPORT bool GetAppOutputWithExitCode(const CommandLine& cl,
366 std::string* output, int* exit_code);
367 #endif // defined(OS_POSIX)
369 // Attempts to kill all the processes on the current machine that were launched
370 // from the given executable name, ending them with the given exit code. If
371 // filter is non-null, then only processes selected by the filter are killed.
372 // Returns true if all processes were able to be killed off, false if at least
373 // one couldn't be killed.
374 BASE_EXPORT bool KillProcesses(const FilePath::StringType& executable_name,
375 int exit_code, const ProcessFilter* filter);
377 // Attempts to kill the process identified by the given process
378 // entry structure, giving it the specified exit code. If |wait| is true, wait
379 // for the process to be actually terminated before returning.
380 // Returns true if this is successful, false otherwise.
381 BASE_EXPORT bool KillProcess(ProcessHandle process, int exit_code, bool wait);
383 #if defined(OS_POSIX)
384 // Attempts to kill the process group identified by |process_group_id|. Returns
385 // true on success.
386 BASE_EXPORT bool KillProcessGroup(ProcessHandle process_group_id);
387 #endif // defined(OS_POSIX)
389 #if defined(OS_WIN)
390 BASE_EXPORT bool KillProcessById(ProcessId process_id, int exit_code,
391 bool wait);
392 #endif // defined(OS_WIN)
394 // Get the termination status of the process by interpreting the
395 // circumstances of the child process' death. |exit_code| is set to
396 // the status returned by waitpid() on POSIX, and from
397 // GetExitCodeProcess() on Windows. |exit_code| may be NULL if the
398 // caller is not interested in it. Note that on Linux, this function
399 // will only return a useful result the first time it is called after
400 // the child exits (because it will reap the child and the information
401 // will no longer be available).
402 BASE_EXPORT TerminationStatus GetTerminationStatus(ProcessHandle handle,
403 int* exit_code);
405 #if defined(OS_POSIX)
406 // Wait for the process to exit and get the termination status. See
407 // GetTerminationStatus for more information. On POSIX systems, we can't call
408 // WaitForExitCode and then GetTerminationStatus as the child will be reaped
409 // when WaitForExitCode return and this information will be lost.
410 BASE_EXPORT TerminationStatus WaitForTerminationStatus(ProcessHandle handle,
411 int* exit_code);
412 #endif // defined(OS_POSIX)
414 // Waits for process to exit. On POSIX systems, if the process hasn't been
415 // signaled then puts the exit code in |exit_code|; otherwise it's considered
416 // a failure. On Windows |exit_code| is always filled. Returns true on success,
417 // and closes |handle| in any case.
418 BASE_EXPORT bool WaitForExitCode(ProcessHandle handle, int* exit_code);
420 // Waits for process to exit. If it did exit within |timeout_milliseconds|,
421 // then puts the exit code in |exit_code|, and returns true.
422 // In POSIX systems, if the process has been signaled then |exit_code| is set
423 // to -1. Returns false on failure (the caller is then responsible for closing
424 // |handle|).
425 // The caller is always responsible for closing the |handle|.
426 BASE_EXPORT bool WaitForExitCodeWithTimeout(ProcessHandle handle,
427 int* exit_code,
428 base::TimeDelta timeout);
430 // Wait for all the processes based on the named executable to exit. If filter
431 // is non-null, then only processes selected by the filter are waited on.
432 // Returns after all processes have exited or wait_milliseconds have expired.
433 // Returns true if all the processes exited, false otherwise.
434 BASE_EXPORT bool WaitForProcessesToExit(
435 const FilePath::StringType& executable_name,
436 base::TimeDelta wait,
437 const ProcessFilter* filter);
439 // Wait for a single process to exit. Return true if it exited cleanly within
440 // the given time limit. On Linux |handle| must be a child process, however
441 // on Mac and Windows it can be any process.
442 BASE_EXPORT bool WaitForSingleProcess(ProcessHandle handle,
443 base::TimeDelta wait);
445 // Waits a certain amount of time (can be 0) for all the processes with a given
446 // executable name to exit, then kills off any of them that are still around.
447 // If filter is non-null, then only processes selected by the filter are waited
448 // on. Killed processes are ended with the given exit code. Returns false if
449 // any processes needed to be killed, true if they all exited cleanly within
450 // the wait_milliseconds delay.
451 BASE_EXPORT bool CleanupProcesses(const FilePath::StringType& executable_name,
452 base::TimeDelta wait,
453 int exit_code,
454 const ProcessFilter* filter);
456 // This method ensures that the specified process eventually terminates, and
457 // then it closes the given process handle.
459 // It assumes that the process has already been signalled to exit, and it
460 // begins by waiting a small amount of time for it to exit. If the process
461 // does not appear to have exited, then this function starts to become
462 // aggressive about ensuring that the process terminates.
464 // On Linux this method does not block the calling thread.
465 // On OS X this method may block for up to 2 seconds.
467 // NOTE: The process handle must have been opened with the PROCESS_TERMINATE
468 // and SYNCHRONIZE permissions.
470 BASE_EXPORT void EnsureProcessTerminated(ProcessHandle process_handle);
472 #if defined(OS_POSIX) && !defined(OS_MACOSX)
473 // The nicer version of EnsureProcessTerminated() that is patient and will
474 // wait for |process_handle| to finish and then reap it.
475 BASE_EXPORT void EnsureProcessGetsReaped(ProcessHandle process_handle);
476 #endif
478 // Enables low fragmentation heap (LFH) for every heaps of this process. This
479 // won't have any effect on heaps created after this function call. It will not
480 // modify data allocated in the heaps before calling this function. So it is
481 // better to call this function early in initialization and again before
482 // entering the main loop.
483 // Note: Returns true on Windows 2000 without doing anything.
484 BASE_EXPORT bool EnableLowFragmentationHeap();
486 // Enables 'terminate on heap corruption' flag. Helps protect against heap
487 // overflow. Has no effect if the OS doesn't provide the necessary facility.
488 BASE_EXPORT void EnableTerminationOnHeapCorruption();
490 // Turns on process termination if memory runs out.
491 BASE_EXPORT void EnableTerminationOnOutOfMemory();
493 // If supported on the platform, and the user has sufficent rights, increase
494 // the current process's scheduling priority to a high priority.
495 BASE_EXPORT void RaiseProcessToHighPriority();
497 #if defined(OS_MACOSX)
498 // Restore the default exception handler, setting it to Apple Crash Reporter
499 // (ReportCrash). When forking and execing a new process, the child will
500 // inherit the parent's exception ports, which may be set to the Breakpad
501 // instance running inside the parent. The parent's Breakpad instance should
502 // not handle the child's exceptions. Calling RestoreDefaultExceptionHandler
503 // in the child after forking will restore the standard exception handler.
504 // See http://crbug.com/20371/ for more details.
505 void RestoreDefaultExceptionHandler();
506 #endif // defined(OS_MACOSX)
508 #if defined(OS_MACOSX)
509 // Very large images or svg canvases can cause huge mallocs. Skia
510 // does tricks on tcmalloc-based systems to allow malloc to fail with
511 // a NULL rather than hit the oom crasher. This replicates that for
512 // OSX.
514 // IF YOU USE THIS WITHOUT CONSULTING YOUR FRIENDLY OSX DEVELOPER,
515 // YOUR CODE IS LIKELY TO BE REVERTED. THANK YOU.
517 // TODO(shess): Weird place to put it, but this is where the OOM
518 // killer currently lives.
519 BASE_EXPORT void* UncheckedMalloc(size_t size);
520 #endif // defined(OS_MACOSX)
522 } // namespace base
524 #endif // BASE_PROCESS_UTIL_H_