Move prefs::kLastPolicyStatisticsUpdate to the policy component.
[chromium-blink-merge.git] / base / process / launch_posix.cc
blobde6286da26b17cb161465b99d2a6b627c1a2b878
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 #include "base/process/launch.h"
7 #include <dirent.h>
8 #include <errno.h>
9 #include <fcntl.h>
10 #include <signal.h>
11 #include <stdlib.h>
12 #include <sys/resource.h>
13 #include <sys/time.h>
14 #include <sys/types.h>
15 #include <sys/wait.h>
16 #include <unistd.h>
18 #include <iterator>
19 #include <limits>
20 #include <set>
22 #include "base/allocator/type_profiler_control.h"
23 #include "base/command_line.h"
24 #include "base/compiler_specific.h"
25 #include "base/debug/debugger.h"
26 #include "base/debug/stack_trace.h"
27 #include "base/file_util.h"
28 #include "base/files/dir_reader_posix.h"
29 #include "base/logging.h"
30 #include "base/memory/scoped_ptr.h"
31 #include "base/posix/eintr_wrapper.h"
32 #include "base/process/kill.h"
33 #include "base/process/process_metrics.h"
34 #include "base/strings/stringprintf.h"
35 #include "base/synchronization/waitable_event.h"
36 #include "base/third_party/dynamic_annotations/dynamic_annotations.h"
37 #include "base/threading/platform_thread.h"
38 #include "base/threading/thread_restrictions.h"
40 #if defined(OS_CHROMEOS)
41 #include <sys/ioctl.h>
42 #endif
44 #if defined(OS_FREEBSD)
45 #include <sys/event.h>
46 #include <sys/ucontext.h>
47 #endif
49 #if defined(OS_MACOSX)
50 #include <crt_externs.h>
51 #include <sys/event.h>
52 #else
53 extern char** environ;
54 #endif
56 namespace base {
58 namespace {
60 // Get the process's "environment" (i.e. the thing that setenv/getenv
61 // work with).
62 char** GetEnvironment() {
63 #if defined(OS_MACOSX)
64 return *_NSGetEnviron();
65 #else
66 return environ;
67 #endif
70 // Set the process's "environment" (i.e. the thing that setenv/getenv
71 // work with).
72 void SetEnvironment(char** env) {
73 #if defined(OS_MACOSX)
74 *_NSGetEnviron() = env;
75 #else
76 environ = env;
77 #endif
80 // Set the calling thread's signal mask to new_sigmask and return
81 // the previous signal mask.
82 sigset_t SetSignalMask(const sigset_t& new_sigmask) {
83 sigset_t old_sigmask;
84 #if defined(OS_ANDROID)
85 // POSIX says pthread_sigmask() must be used in multi-threaded processes,
86 // but Android's pthread_sigmask() was broken until 4.1:
87 // https://code.google.com/p/android/issues/detail?id=15337
88 // http://stackoverflow.com/questions/13777109/pthread-sigmask-on-android-not-working
89 RAW_CHECK(sigprocmask(SIG_SETMASK, &new_sigmask, &old_sigmask) == 0);
90 #else
91 RAW_CHECK(pthread_sigmask(SIG_SETMASK, &new_sigmask, &old_sigmask) == 0);
92 #endif
93 return old_sigmask;
96 #if !defined(OS_LINUX) || \
97 (!defined(__i386__) && !defined(__x86_64__) && !defined(__arm__))
98 void ResetChildSignalHandlersToDefaults() {
99 // The previous signal handlers are likely to be meaningless in the child's
100 // context so we reset them to the defaults for now. http://crbug.com/44953
101 // These signal handlers are set up at least in browser_main_posix.cc:
102 // BrowserMainPartsPosix::PreEarlyInitialization and stack_trace_posix.cc:
103 // EnableInProcessStackDumping.
104 signal(SIGHUP, SIG_DFL);
105 signal(SIGINT, SIG_DFL);
106 signal(SIGILL, SIG_DFL);
107 signal(SIGABRT, SIG_DFL);
108 signal(SIGFPE, SIG_DFL);
109 signal(SIGBUS, SIG_DFL);
110 signal(SIGSEGV, SIG_DFL);
111 signal(SIGSYS, SIG_DFL);
112 signal(SIGTERM, SIG_DFL);
115 #else
117 // TODO(jln): remove the Linux special case once kernels are fixed.
119 // Internally the kernel makes sigset_t an array of long large enough to have
120 // one bit per signal.
121 typedef uint64_t kernel_sigset_t;
123 // This is what struct sigaction looks like to the kernel at least on X86 and
124 // ARM. MIPS, for instance, is very different.
125 struct kernel_sigaction {
126 void* k_sa_handler; // For this usage it only needs to be a generic pointer.
127 unsigned long k_sa_flags;
128 void* k_sa_restorer; // For this usage it only needs to be a generic pointer.
129 kernel_sigset_t k_sa_mask;
132 // glibc's sigaction() will prevent access to sa_restorer, so we need to roll
133 // our own.
134 int sys_rt_sigaction(int sig, const struct kernel_sigaction* act,
135 struct kernel_sigaction* oact) {
136 return syscall(SYS_rt_sigaction, sig, act, oact, sizeof(kernel_sigset_t));
139 // This function is intended to be used in between fork() and execve() and will
140 // reset all signal handlers to the default.
141 // The motivation for going through all of them is that sa_restorer can leak
142 // from parents and help defeat ASLR on buggy kernels. We reset it to NULL.
143 // See crbug.com/177956.
144 void ResetChildSignalHandlersToDefaults(void) {
145 for (int signum = 1; ; ++signum) {
146 struct kernel_sigaction act = {0};
147 int sigaction_get_ret = sys_rt_sigaction(signum, NULL, &act);
148 if (sigaction_get_ret && errno == EINVAL) {
149 #if !defined(NDEBUG)
150 // Linux supports 32 real-time signals from 33 to 64.
151 // If the number of signals in the Linux kernel changes, someone should
152 // look at this code.
153 const int kNumberOfSignals = 64;
154 RAW_CHECK(signum == kNumberOfSignals + 1);
155 #endif // !defined(NDEBUG)
156 break;
158 // All other failures are fatal.
159 if (sigaction_get_ret) {
160 RAW_LOG(FATAL, "sigaction (get) failed.");
163 // The kernel won't allow to re-set SIGKILL or SIGSTOP.
164 if (signum != SIGSTOP && signum != SIGKILL) {
165 act.k_sa_handler = reinterpret_cast<void*>(SIG_DFL);
166 act.k_sa_restorer = NULL;
167 if (sys_rt_sigaction(signum, &act, NULL)) {
168 RAW_LOG(FATAL, "sigaction (set) failed.");
171 #if !defined(NDEBUG)
172 // Now ask the kernel again and check that no restorer will leak.
173 if (sys_rt_sigaction(signum, NULL, &act) || act.k_sa_restorer) {
174 RAW_LOG(FATAL, "Cound not fix sa_restorer.");
176 #endif // !defined(NDEBUG)
179 #endif // !defined(OS_LINUX) ||
180 // (!defined(__i386__) && !defined(__x86_64__) && !defined(__arm__))
182 } // anonymous namespace
184 // A class to handle auto-closing of DIR*'s.
185 class ScopedDIRClose {
186 public:
187 inline void operator()(DIR* x) const {
188 if (x) {
189 closedir(x);
193 typedef scoped_ptr_malloc<DIR, ScopedDIRClose> ScopedDIR;
195 #if defined(OS_LINUX)
196 static const char kFDDir[] = "/proc/self/fd";
197 #elif defined(OS_MACOSX)
198 static const char kFDDir[] = "/dev/fd";
199 #elif defined(OS_SOLARIS)
200 static const char kFDDir[] = "/dev/fd";
201 #elif defined(OS_FREEBSD)
202 static const char kFDDir[] = "/dev/fd";
203 #elif defined(OS_OPENBSD)
204 static const char kFDDir[] = "/dev/fd";
205 #elif defined(OS_ANDROID)
206 static const char kFDDir[] = "/proc/self/fd";
207 #endif
209 void CloseSuperfluousFds(const base::InjectiveMultimap& saved_mapping) {
210 // DANGER: no calls to malloc are allowed from now on:
211 // http://crbug.com/36678
213 // Get the maximum number of FDs possible.
214 size_t max_fds = GetMaxFds();
216 DirReaderPosix fd_dir(kFDDir);
217 if (!fd_dir.IsValid()) {
218 // Fallback case: Try every possible fd.
219 for (size_t i = 0; i < max_fds; ++i) {
220 const int fd = static_cast<int>(i);
221 if (fd == STDIN_FILENO || fd == STDOUT_FILENO || fd == STDERR_FILENO)
222 continue;
223 InjectiveMultimap::const_iterator j;
224 for (j = saved_mapping.begin(); j != saved_mapping.end(); j++) {
225 if (fd == j->dest)
226 break;
228 if (j != saved_mapping.end())
229 continue;
231 // Since we're just trying to close anything we can find,
232 // ignore any error return values of close().
233 ignore_result(HANDLE_EINTR(close(fd)));
235 return;
238 const int dir_fd = fd_dir.fd();
240 for ( ; fd_dir.Next(); ) {
241 // Skip . and .. entries.
242 if (fd_dir.name()[0] == '.')
243 continue;
245 char *endptr;
246 errno = 0;
247 const long int fd = strtol(fd_dir.name(), &endptr, 10);
248 if (fd_dir.name()[0] == 0 || *endptr || fd < 0 || errno)
249 continue;
250 if (fd == STDIN_FILENO || fd == STDOUT_FILENO || fd == STDERR_FILENO)
251 continue;
252 InjectiveMultimap::const_iterator i;
253 for (i = saved_mapping.begin(); i != saved_mapping.end(); i++) {
254 if (fd == i->dest)
255 break;
257 if (i != saved_mapping.end())
258 continue;
259 if (fd == dir_fd)
260 continue;
262 // When running under Valgrind, Valgrind opens several FDs for its
263 // own use and will complain if we try to close them. All of
264 // these FDs are >= |max_fds|, so we can check against that here
265 // before closing. See https://bugs.kde.org/show_bug.cgi?id=191758
266 if (fd < static_cast<int>(max_fds)) {
267 int ret = HANDLE_EINTR(close(fd));
268 DPCHECK(ret == 0);
273 bool LaunchProcess(const std::vector<std::string>& argv,
274 const LaunchOptions& options,
275 ProcessHandle* process_handle) {
276 size_t fd_shuffle_size = 0;
277 if (options.fds_to_remap) {
278 fd_shuffle_size = options.fds_to_remap->size();
281 InjectiveMultimap fd_shuffle1;
282 InjectiveMultimap fd_shuffle2;
283 fd_shuffle1.reserve(fd_shuffle_size);
284 fd_shuffle2.reserve(fd_shuffle_size);
286 scoped_ptr<char*[]> argv_cstr(new char*[argv.size() + 1]);
287 scoped_ptr<char*[]> new_environ;
288 if (!options.environ.empty())
289 new_environ = AlterEnvironment(GetEnvironment(), options.environ);
291 sigset_t full_sigset;
292 sigfillset(&full_sigset);
293 const sigset_t orig_sigmask = SetSignalMask(full_sigset);
295 pid_t pid;
296 #if defined(OS_LINUX)
297 if (options.clone_flags) {
298 // Signal handling in this function assumes the creation of a new
299 // process, so we check that a thread is not being created by mistake
300 // and that signal handling follows the process-creation rules.
301 RAW_CHECK(
302 !(options.clone_flags & (CLONE_SIGHAND | CLONE_THREAD | CLONE_VM)));
303 pid = syscall(__NR_clone, options.clone_flags, 0, 0, 0);
304 } else
305 #endif
307 pid = fork();
310 // Always restore the original signal mask in the parent.
311 if (pid != 0) {
312 SetSignalMask(orig_sigmask);
315 if (pid < 0) {
316 DPLOG(ERROR) << "fork";
317 return false;
318 } else if (pid == 0) {
319 // Child process
321 // DANGER: fork() rule: in the child, if you don't end up doing exec*(),
322 // you call _exit() instead of exit(). This is because _exit() does not
323 // call any previously-registered (in the parent) exit handlers, which
324 // might do things like block waiting for threads that don't even exist
325 // in the child.
327 // If a child process uses the readline library, the process block forever.
328 // In BSD like OSes including OS X it is safe to assign /dev/null as stdin.
329 // See http://crbug.com/56596.
330 int null_fd = HANDLE_EINTR(open("/dev/null", O_RDONLY));
331 if (null_fd < 0) {
332 RAW_LOG(ERROR, "Failed to open /dev/null");
333 _exit(127);
336 file_util::ScopedFD null_fd_closer(&null_fd);
337 int new_fd = HANDLE_EINTR(dup2(null_fd, STDIN_FILENO));
338 if (new_fd != STDIN_FILENO) {
339 RAW_LOG(ERROR, "Failed to dup /dev/null for stdin");
340 _exit(127);
343 if (options.new_process_group) {
344 // Instead of inheriting the process group ID of the parent, the child
345 // starts off a new process group with pgid equal to its process ID.
346 if (setpgid(0, 0) < 0) {
347 RAW_LOG(ERROR, "setpgid failed");
348 _exit(127);
352 // Stop type-profiler.
353 // The profiler should be stopped between fork and exec since it inserts
354 // locks at new/delete expressions. See http://crbug.com/36678.
355 base::type_profiler::Controller::Stop();
357 if (options.maximize_rlimits) {
358 // Some resource limits need to be maximal in this child.
359 std::set<int>::const_iterator resource;
360 for (resource = options.maximize_rlimits->begin();
361 resource != options.maximize_rlimits->end();
362 ++resource) {
363 struct rlimit limit;
364 if (getrlimit(*resource, &limit) < 0) {
365 RAW_LOG(WARNING, "getrlimit failed");
366 } else if (limit.rlim_cur < limit.rlim_max) {
367 limit.rlim_cur = limit.rlim_max;
368 if (setrlimit(*resource, &limit) < 0) {
369 RAW_LOG(WARNING, "setrlimit failed");
375 #if defined(OS_MACOSX)
376 RestoreDefaultExceptionHandler();
377 #endif // defined(OS_MACOSX)
379 ResetChildSignalHandlersToDefaults();
380 SetSignalMask(orig_sigmask);
382 #if 0
383 // When debugging it can be helpful to check that we really aren't making
384 // any hidden calls to malloc.
385 void *malloc_thunk =
386 reinterpret_cast<void*>(reinterpret_cast<intptr_t>(malloc) & ~4095);
387 mprotect(malloc_thunk, 4096, PROT_READ | PROT_WRITE | PROT_EXEC);
388 memset(reinterpret_cast<void*>(malloc), 0xff, 8);
389 #endif // 0
391 // DANGER: no calls to malloc are allowed from now on:
392 // http://crbug.com/36678
394 #if defined(OS_CHROMEOS)
395 if (options.ctrl_terminal_fd >= 0) {
396 // Set process' controlling terminal.
397 if (HANDLE_EINTR(setsid()) != -1) {
398 if (HANDLE_EINTR(
399 ioctl(options.ctrl_terminal_fd, TIOCSCTTY, NULL)) == -1) {
400 RAW_LOG(WARNING, "ioctl(TIOCSCTTY), ctrl terminal not set");
402 } else {
403 RAW_LOG(WARNING, "setsid failed, ctrl terminal not set");
406 #endif // defined(OS_CHROMEOS)
408 if (options.fds_to_remap) {
409 for (FileHandleMappingVector::const_iterator
410 it = options.fds_to_remap->begin();
411 it != options.fds_to_remap->end(); ++it) {
412 fd_shuffle1.push_back(InjectionArc(it->first, it->second, false));
413 fd_shuffle2.push_back(InjectionArc(it->first, it->second, false));
417 if (!options.environ.empty())
418 SetEnvironment(new_environ.get());
420 // fd_shuffle1 is mutated by this call because it cannot malloc.
421 if (!ShuffleFileDescriptors(&fd_shuffle1))
422 _exit(127);
424 CloseSuperfluousFds(fd_shuffle2);
426 for (size_t i = 0; i < argv.size(); i++)
427 argv_cstr[i] = const_cast<char*>(argv[i].c_str());
428 argv_cstr[argv.size()] = NULL;
429 execvp(argv_cstr[0], argv_cstr.get());
431 RAW_LOG(ERROR, "LaunchProcess: failed to execvp:");
432 RAW_LOG(ERROR, argv_cstr[0]);
433 _exit(127);
434 } else {
435 // Parent process
436 if (options.wait) {
437 // While this isn't strictly disk IO, waiting for another process to
438 // finish is the sort of thing ThreadRestrictions is trying to prevent.
439 base::ThreadRestrictions::AssertIOAllowed();
440 pid_t ret = HANDLE_EINTR(waitpid(pid, 0, 0));
441 DPCHECK(ret > 0);
444 if (process_handle)
445 *process_handle = pid;
448 return true;
452 bool LaunchProcess(const CommandLine& cmdline,
453 const LaunchOptions& options,
454 ProcessHandle* process_handle) {
455 return LaunchProcess(cmdline.argv(), options, process_handle);
458 void RaiseProcessToHighPriority() {
459 // On POSIX, we don't actually do anything here. We could try to nice() or
460 // setpriority() or sched_getscheduler, but these all require extra rights.
463 // Return value used by GetAppOutputInternal to encapsulate the various exit
464 // scenarios from the function.
465 enum GetAppOutputInternalResult {
466 EXECUTE_FAILURE,
467 EXECUTE_SUCCESS,
468 GOT_MAX_OUTPUT,
471 // Executes the application specified by |argv| and wait for it to exit. Stores
472 // the output (stdout) in |output|. If |do_search_path| is set, it searches the
473 // path for the application; in that case, |envp| must be null, and it will use
474 // the current environment. If |do_search_path| is false, |argv[0]| should fully
475 // specify the path of the application, and |envp| will be used as the
476 // environment. Redirects stderr to /dev/null.
477 // If we successfully start the application and get all requested output, we
478 // return GOT_MAX_OUTPUT, or if there is a problem starting or exiting
479 // the application we return RUN_FAILURE. Otherwise we return EXECUTE_SUCCESS.
480 // The GOT_MAX_OUTPUT return value exists so a caller that asks for limited
481 // output can treat this as a success, despite having an exit code of SIG_PIPE
482 // due to us closing the output pipe.
483 // In the case of EXECUTE_SUCCESS, the application exit code will be returned
484 // in |*exit_code|, which should be checked to determine if the application
485 // ran successfully.
486 static GetAppOutputInternalResult GetAppOutputInternal(
487 const std::vector<std::string>& argv,
488 char* const envp[],
489 std::string* output,
490 size_t max_output,
491 bool do_search_path,
492 int* exit_code) {
493 // Doing a blocking wait for another command to finish counts as IO.
494 base::ThreadRestrictions::AssertIOAllowed();
495 // exit_code must be supplied so calling function can determine success.
496 DCHECK(exit_code);
497 *exit_code = EXIT_FAILURE;
499 int pipe_fd[2];
500 pid_t pid;
501 InjectiveMultimap fd_shuffle1, fd_shuffle2;
502 scoped_ptr<char*[]> argv_cstr(new char*[argv.size() + 1]);
504 fd_shuffle1.reserve(3);
505 fd_shuffle2.reserve(3);
507 // Either |do_search_path| should be false or |envp| should be null, but not
508 // both.
509 DCHECK(!do_search_path ^ !envp);
511 if (pipe(pipe_fd) < 0)
512 return EXECUTE_FAILURE;
514 switch (pid = fork()) {
515 case -1: // error
516 close(pipe_fd[0]);
517 close(pipe_fd[1]);
518 return EXECUTE_FAILURE;
519 case 0: // child
521 #if defined(OS_MACOSX)
522 RestoreDefaultExceptionHandler();
523 #endif
524 // DANGER: no calls to malloc are allowed from now on:
525 // http://crbug.com/36678
527 // Obscure fork() rule: in the child, if you don't end up doing exec*(),
528 // you call _exit() instead of exit(). This is because _exit() does not
529 // call any previously-registered (in the parent) exit handlers, which
530 // might do things like block waiting for threads that don't even exist
531 // in the child.
532 int dev_null = open("/dev/null", O_WRONLY);
533 if (dev_null < 0)
534 _exit(127);
536 // Stop type-profiler.
537 // The profiler should be stopped between fork and exec since it inserts
538 // locks at new/delete expressions. See http://crbug.com/36678.
539 base::type_profiler::Controller::Stop();
541 fd_shuffle1.push_back(InjectionArc(pipe_fd[1], STDOUT_FILENO, true));
542 fd_shuffle1.push_back(InjectionArc(dev_null, STDERR_FILENO, true));
543 fd_shuffle1.push_back(InjectionArc(dev_null, STDIN_FILENO, true));
544 // Adding another element here? Remeber to increase the argument to
545 // reserve(), above.
547 std::copy(fd_shuffle1.begin(), fd_shuffle1.end(),
548 std::back_inserter(fd_shuffle2));
550 if (!ShuffleFileDescriptors(&fd_shuffle1))
551 _exit(127);
553 CloseSuperfluousFds(fd_shuffle2);
555 for (size_t i = 0; i < argv.size(); i++)
556 argv_cstr[i] = const_cast<char*>(argv[i].c_str());
557 argv_cstr[argv.size()] = NULL;
558 if (do_search_path)
559 execvp(argv_cstr[0], argv_cstr.get());
560 else
561 execve(argv_cstr[0], argv_cstr.get(), envp);
562 _exit(127);
564 default: // parent
566 // Close our writing end of pipe now. Otherwise later read would not
567 // be able to detect end of child's output (in theory we could still
568 // write to the pipe).
569 close(pipe_fd[1]);
571 output->clear();
572 char buffer[256];
573 size_t output_buf_left = max_output;
574 ssize_t bytes_read = 1; // A lie to properly handle |max_output == 0|
575 // case in the logic below.
577 while (output_buf_left > 0) {
578 bytes_read = HANDLE_EINTR(read(pipe_fd[0], buffer,
579 std::min(output_buf_left, sizeof(buffer))));
580 if (bytes_read <= 0)
581 break;
582 output->append(buffer, bytes_read);
583 output_buf_left -= static_cast<size_t>(bytes_read);
585 close(pipe_fd[0]);
587 // Always wait for exit code (even if we know we'll declare
588 // GOT_MAX_OUTPUT).
589 bool success = WaitForExitCode(pid, exit_code);
591 // If we stopped because we read as much as we wanted, we return
592 // GOT_MAX_OUTPUT (because the child may exit due to |SIGPIPE|).
593 if (!output_buf_left && bytes_read > 0)
594 return GOT_MAX_OUTPUT;
595 else if (success)
596 return EXECUTE_SUCCESS;
597 return EXECUTE_FAILURE;
602 bool GetAppOutput(const CommandLine& cl, std::string* output) {
603 return GetAppOutput(cl.argv(), output);
606 bool GetAppOutput(const std::vector<std::string>& argv, std::string* output) {
607 // Run |execve()| with the current environment and store "unlimited" data.
608 int exit_code;
609 GetAppOutputInternalResult result = GetAppOutputInternal(
610 argv, NULL, output, std::numeric_limits<std::size_t>::max(), true,
611 &exit_code);
612 return result == EXECUTE_SUCCESS && exit_code == EXIT_SUCCESS;
615 // TODO(viettrungluu): Conceivably, we should have a timeout as well, so we
616 // don't hang if what we're calling hangs.
617 bool GetAppOutputRestricted(const CommandLine& cl,
618 std::string* output, size_t max_output) {
619 // Run |execve()| with the empty environment.
620 char* const empty_environ = NULL;
621 int exit_code;
622 GetAppOutputInternalResult result = GetAppOutputInternal(
623 cl.argv(), &empty_environ, output, max_output, false, &exit_code);
624 return result == GOT_MAX_OUTPUT || (result == EXECUTE_SUCCESS &&
625 exit_code == EXIT_SUCCESS);
628 bool GetAppOutputWithExitCode(const CommandLine& cl,
629 std::string* output,
630 int* exit_code) {
631 // Run |execve()| with the current environment and store "unlimited" data.
632 GetAppOutputInternalResult result = GetAppOutputInternal(
633 cl.argv(), NULL, output, std::numeric_limits<std::size_t>::max(), true,
634 exit_code);
635 return result == EXECUTE_SUCCESS;
638 } // namespace base