Move android_app_version_* into an inner variables dict.
[chromium-blink-merge.git] / base / process / launch_posix.cc
blob77edc1283191c9a6ad77b9a323cbd9cdf7d00153
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 <sched.h>
11 #include <setjmp.h>
12 #include <signal.h>
13 #include <stdlib.h>
14 #include <sys/resource.h>
15 #include <sys/syscall.h>
16 #include <sys/time.h>
17 #include <sys/types.h>
18 #include <sys/wait.h>
19 #include <unistd.h>
21 #include <iterator>
22 #include <limits>
23 #include <set>
25 #include "base/allocator/type_profiler_control.h"
26 #include "base/command_line.h"
27 #include "base/compiler_specific.h"
28 #include "base/debug/debugger.h"
29 #include "base/debug/stack_trace.h"
30 #include "base/files/dir_reader_posix.h"
31 #include "base/files/file_util.h"
32 #include "base/files/scoped_file.h"
33 #include "base/logging.h"
34 #include "base/memory/scoped_ptr.h"
35 #include "base/posix/eintr_wrapper.h"
36 #include "base/process/process.h"
37 #include "base/process/process_metrics.h"
38 #include "base/strings/stringprintf.h"
39 #include "base/synchronization/waitable_event.h"
40 #include "base/third_party/dynamic_annotations/dynamic_annotations.h"
41 #include "base/third_party/valgrind/valgrind.h"
42 #include "base/threading/platform_thread.h"
43 #include "base/threading/thread_restrictions.h"
44 #include "build/build_config.h"
46 #if defined(OS_LINUX)
47 #include <sys/prctl.h>
48 #endif
50 #if defined(OS_CHROMEOS)
51 #include <sys/ioctl.h>
52 #endif
54 #if defined(OS_FREEBSD)
55 #include <sys/event.h>
56 #include <sys/ucontext.h>
57 #endif
59 #if defined(OS_MACOSX)
60 #include <crt_externs.h>
61 #include <sys/event.h>
62 #else
63 extern char** environ;
64 #endif
66 namespace base {
68 namespace {
70 // Get the process's "environment" (i.e. the thing that setenv/getenv
71 // work with).
72 char** GetEnvironment() {
73 #if defined(OS_MACOSX)
74 return *_NSGetEnviron();
75 #else
76 return environ;
77 #endif
80 // Set the process's "environment" (i.e. the thing that setenv/getenv
81 // work with).
82 void SetEnvironment(char** env) {
83 #if defined(OS_MACOSX)
84 *_NSGetEnviron() = env;
85 #else
86 environ = env;
87 #endif
90 // Set the calling thread's signal mask to new_sigmask and return
91 // the previous signal mask.
92 sigset_t SetSignalMask(const sigset_t& new_sigmask) {
93 sigset_t old_sigmask;
94 #if defined(OS_ANDROID)
95 // POSIX says pthread_sigmask() must be used in multi-threaded processes,
96 // but Android's pthread_sigmask() was broken until 4.1:
97 // https://code.google.com/p/android/issues/detail?id=15337
98 // http://stackoverflow.com/questions/13777109/pthread-sigmask-on-android-not-working
99 RAW_CHECK(sigprocmask(SIG_SETMASK, &new_sigmask, &old_sigmask) == 0);
100 #else
101 RAW_CHECK(pthread_sigmask(SIG_SETMASK, &new_sigmask, &old_sigmask) == 0);
102 #endif
103 return old_sigmask;
106 #if !defined(OS_LINUX) || \
107 (!defined(__i386__) && !defined(__x86_64__) && !defined(__arm__))
108 void ResetChildSignalHandlersToDefaults() {
109 // The previous signal handlers are likely to be meaningless in the child's
110 // context so we reset them to the defaults for now. http://crbug.com/44953
111 // These signal handlers are set up at least in browser_main_posix.cc:
112 // BrowserMainPartsPosix::PreEarlyInitialization and stack_trace_posix.cc:
113 // EnableInProcessStackDumping.
114 signal(SIGHUP, SIG_DFL);
115 signal(SIGINT, SIG_DFL);
116 signal(SIGILL, SIG_DFL);
117 signal(SIGABRT, SIG_DFL);
118 signal(SIGFPE, SIG_DFL);
119 signal(SIGBUS, SIG_DFL);
120 signal(SIGSEGV, SIG_DFL);
121 signal(SIGSYS, SIG_DFL);
122 signal(SIGTERM, SIG_DFL);
125 #else
127 // TODO(jln): remove the Linux special case once kernels are fixed.
129 // Internally the kernel makes sigset_t an array of long large enough to have
130 // one bit per signal.
131 typedef uint64_t kernel_sigset_t;
133 // This is what struct sigaction looks like to the kernel at least on X86 and
134 // ARM. MIPS, for instance, is very different.
135 struct kernel_sigaction {
136 void* k_sa_handler; // For this usage it only needs to be a generic pointer.
137 unsigned long k_sa_flags;
138 void* k_sa_restorer; // For this usage it only needs to be a generic pointer.
139 kernel_sigset_t k_sa_mask;
142 // glibc's sigaction() will prevent access to sa_restorer, so we need to roll
143 // our own.
144 int sys_rt_sigaction(int sig, const struct kernel_sigaction* act,
145 struct kernel_sigaction* oact) {
146 return syscall(SYS_rt_sigaction, sig, act, oact, sizeof(kernel_sigset_t));
149 // This function is intended to be used in between fork() and execve() and will
150 // reset all signal handlers to the default.
151 // The motivation for going through all of them is that sa_restorer can leak
152 // from parents and help defeat ASLR on buggy kernels. We reset it to NULL.
153 // See crbug.com/177956.
154 void ResetChildSignalHandlersToDefaults(void) {
155 for (int signum = 1; ; ++signum) {
156 struct kernel_sigaction act = {0};
157 int sigaction_get_ret = sys_rt_sigaction(signum, NULL, &act);
158 if (sigaction_get_ret && errno == EINVAL) {
159 #if !defined(NDEBUG)
160 // Linux supports 32 real-time signals from 33 to 64.
161 // If the number of signals in the Linux kernel changes, someone should
162 // look at this code.
163 const int kNumberOfSignals = 64;
164 RAW_CHECK(signum == kNumberOfSignals + 1);
165 #endif // !defined(NDEBUG)
166 break;
168 // All other failures are fatal.
169 if (sigaction_get_ret) {
170 RAW_LOG(FATAL, "sigaction (get) failed.");
173 // The kernel won't allow to re-set SIGKILL or SIGSTOP.
174 if (signum != SIGSTOP && signum != SIGKILL) {
175 act.k_sa_handler = reinterpret_cast<void*>(SIG_DFL);
176 act.k_sa_restorer = NULL;
177 if (sys_rt_sigaction(signum, &act, NULL)) {
178 RAW_LOG(FATAL, "sigaction (set) failed.");
181 #if !defined(NDEBUG)
182 // Now ask the kernel again and check that no restorer will leak.
183 if (sys_rt_sigaction(signum, NULL, &act) || act.k_sa_restorer) {
184 RAW_LOG(FATAL, "Cound not fix sa_restorer.");
186 #endif // !defined(NDEBUG)
189 #endif // !defined(OS_LINUX) ||
190 // (!defined(__i386__) && !defined(__x86_64__) && !defined(__arm__))
192 #if defined(OS_LINUX)
193 bool IsRunningOnValgrind() {
194 return RUNNING_ON_VALGRIND;
197 // This function runs on the stack specified on the clone call. It uses longjmp
198 // to switch back to the original stack so the child can return from sys_clone.
199 int CloneHelper(void* arg) {
200 jmp_buf* env_ptr = reinterpret_cast<jmp_buf*>(arg);
201 longjmp(*env_ptr, 1);
203 // Should not be reached.
204 RAW_CHECK(false);
205 return 1;
208 // This function is noinline to ensure that stack_buf is below the stack pointer
209 // that is saved when setjmp is called below. This is needed because when
210 // compiled with FORTIFY_SOURCE, glibc's longjmp checks that the stack is moved
211 // upwards. See crbug.com/442912 for more details.
212 #if defined(ADDRESS_SANITIZER)
213 // Disable AddressSanitizer instrumentation for this function to make sure
214 // |stack_buf| is allocated on thread stack instead of ASan's fake stack.
215 // Under ASan longjmp() will attempt to clean up the area between the old and
216 // new stack pointers and print a warning that may confuse the user.
217 __attribute__((no_sanitize_address))
218 #endif
219 NOINLINE pid_t CloneAndLongjmpInChild(unsigned long flags,
220 pid_t* ptid,
221 pid_t* ctid,
222 jmp_buf* env) {
223 // We use the libc clone wrapper instead of making the syscall
224 // directly because making the syscall may fail to update the libc's
225 // internal pid cache. The libc interface unfortunately requires
226 // specifying a new stack, so we use setjmp/longjmp to emulate
227 // fork-like behavior.
228 char stack_buf[PTHREAD_STACK_MIN];
229 #if defined(ARCH_CPU_X86_FAMILY) || defined(ARCH_CPU_ARM_FAMILY) || \
230 defined(ARCH_CPU_MIPS64_FAMILY) || defined(ARCH_CPU_MIPS_FAMILY)
231 // The stack grows downward.
232 void* stack = stack_buf + sizeof(stack_buf);
233 #else
234 #error "Unsupported architecture"
235 #endif
236 return clone(&CloneHelper, stack, flags, env, ptid, nullptr, ctid);
238 #endif // defined(OS_LINUX)
240 } // anonymous namespace
242 // Functor for |ScopedDIR| (below).
243 struct ScopedDIRClose {
244 inline void operator()(DIR* x) const {
245 if (x)
246 closedir(x);
250 // Automatically closes |DIR*|s.
251 typedef scoped_ptr<DIR, ScopedDIRClose> ScopedDIR;
253 #if defined(OS_LINUX)
254 static const char kFDDir[] = "/proc/self/fd";
255 #elif defined(OS_MACOSX)
256 static const char kFDDir[] = "/dev/fd";
257 #elif defined(OS_SOLARIS)
258 static const char kFDDir[] = "/dev/fd";
259 #elif defined(OS_FREEBSD)
260 static const char kFDDir[] = "/dev/fd";
261 #elif defined(OS_OPENBSD)
262 static const char kFDDir[] = "/dev/fd";
263 #elif defined(OS_ANDROID)
264 static const char kFDDir[] = "/proc/self/fd";
265 #endif
267 void CloseSuperfluousFds(const base::InjectiveMultimap& saved_mapping) {
268 // DANGER: no calls to malloc or locks are allowed from now on:
269 // http://crbug.com/36678
271 // Get the maximum number of FDs possible.
272 size_t max_fds = GetMaxFds();
274 DirReaderPosix fd_dir(kFDDir);
275 if (!fd_dir.IsValid()) {
276 // Fallback case: Try every possible fd.
277 for (size_t i = 0; i < max_fds; ++i) {
278 const int fd = static_cast<int>(i);
279 if (fd == STDIN_FILENO || fd == STDOUT_FILENO || fd == STDERR_FILENO)
280 continue;
281 // Cannot use STL iterators here, since debug iterators use locks.
282 size_t j;
283 for (j = 0; j < saved_mapping.size(); j++) {
284 if (fd == saved_mapping[j].dest)
285 break;
287 if (j < saved_mapping.size())
288 continue;
290 // Since we're just trying to close anything we can find,
291 // ignore any error return values of close().
292 close(fd);
294 return;
297 const int dir_fd = fd_dir.fd();
299 for ( ; fd_dir.Next(); ) {
300 // Skip . and .. entries.
301 if (fd_dir.name()[0] == '.')
302 continue;
304 char *endptr;
305 errno = 0;
306 const long int fd = strtol(fd_dir.name(), &endptr, 10);
307 if (fd_dir.name()[0] == 0 || *endptr || fd < 0 || errno)
308 continue;
309 if (fd == STDIN_FILENO || fd == STDOUT_FILENO || fd == STDERR_FILENO)
310 continue;
311 // Cannot use STL iterators here, since debug iterators use locks.
312 size_t i;
313 for (i = 0; i < saved_mapping.size(); i++) {
314 if (fd == saved_mapping[i].dest)
315 break;
317 if (i < saved_mapping.size())
318 continue;
319 if (fd == dir_fd)
320 continue;
322 // When running under Valgrind, Valgrind opens several FDs for its
323 // own use and will complain if we try to close them. All of
324 // these FDs are >= |max_fds|, so we can check against that here
325 // before closing. See https://bugs.kde.org/show_bug.cgi?id=191758
326 if (fd < static_cast<int>(max_fds)) {
327 int ret = IGNORE_EINTR(close(fd));
328 DPCHECK(ret == 0);
333 Process LaunchProcess(const CommandLine& cmdline,
334 const LaunchOptions& options) {
335 return LaunchProcess(cmdline.argv(), options);
338 Process LaunchProcess(const std::vector<std::string>& argv,
339 const LaunchOptions& options) {
340 size_t fd_shuffle_size = 0;
341 if (options.fds_to_remap) {
342 fd_shuffle_size = options.fds_to_remap->size();
345 InjectiveMultimap fd_shuffle1;
346 InjectiveMultimap fd_shuffle2;
347 fd_shuffle1.reserve(fd_shuffle_size);
348 fd_shuffle2.reserve(fd_shuffle_size);
350 scoped_ptr<char* []> argv_cstr(new char* [argv.size() + 1]);
351 for (size_t i = 0; i < argv.size(); i++) {
352 argv_cstr[i] = const_cast<char*>(argv[i].c_str());
354 argv_cstr[argv.size()] = NULL;
356 scoped_ptr<char*[]> new_environ;
357 char* const empty_environ = NULL;
358 char* const* old_environ = GetEnvironment();
359 if (options.clear_environ)
360 old_environ = &empty_environ;
361 if (!options.environ.empty())
362 new_environ = AlterEnvironment(old_environ, options.environ);
364 sigset_t full_sigset;
365 sigfillset(&full_sigset);
366 const sigset_t orig_sigmask = SetSignalMask(full_sigset);
368 const char* current_directory = nullptr;
369 if (!options.current_directory.empty()) {
370 current_directory = options.current_directory.value().c_str();
373 pid_t pid;
374 #if defined(OS_LINUX)
375 if (options.clone_flags) {
376 // Signal handling in this function assumes the creation of a new
377 // process, so we check that a thread is not being created by mistake
378 // and that signal handling follows the process-creation rules.
379 RAW_CHECK(
380 !(options.clone_flags & (CLONE_SIGHAND | CLONE_THREAD | CLONE_VM)));
382 // We specify a null ptid and ctid.
383 RAW_CHECK(
384 !(options.clone_flags &
385 (CLONE_CHILD_CLEARTID | CLONE_CHILD_SETTID | CLONE_PARENT_SETTID)));
387 // Since we use waitpid, we do not support custom termination signals in the
388 // clone flags.
389 RAW_CHECK((options.clone_flags & 0xff) == 0);
391 pid = ForkWithFlags(options.clone_flags | SIGCHLD, nullptr, nullptr);
392 } else
393 #endif
395 pid = fork();
398 // Always restore the original signal mask in the parent.
399 if (pid != 0) {
400 SetSignalMask(orig_sigmask);
403 if (pid < 0) {
404 DPLOG(ERROR) << "fork";
405 return Process();
406 } else if (pid == 0) {
407 // Child process
409 // DANGER: no calls to malloc or locks are allowed from now on:
410 // http://crbug.com/36678
412 // DANGER: fork() rule: in the child, if you don't end up doing exec*(),
413 // you call _exit() instead of exit(). This is because _exit() does not
414 // call any previously-registered (in the parent) exit handlers, which
415 // might do things like block waiting for threads that don't even exist
416 // in the child.
418 // If a child process uses the readline library, the process block forever.
419 // In BSD like OSes including OS X it is safe to assign /dev/null as stdin.
420 // See http://crbug.com/56596.
421 base::ScopedFD null_fd(HANDLE_EINTR(open("/dev/null", O_RDONLY)));
422 if (!null_fd.is_valid()) {
423 RAW_LOG(ERROR, "Failed to open /dev/null");
424 _exit(127);
427 int new_fd = HANDLE_EINTR(dup2(null_fd.get(), STDIN_FILENO));
428 if (new_fd != STDIN_FILENO) {
429 RAW_LOG(ERROR, "Failed to dup /dev/null for stdin");
430 _exit(127);
433 if (options.new_process_group) {
434 // Instead of inheriting the process group ID of the parent, the child
435 // starts off a new process group with pgid equal to its process ID.
436 if (setpgid(0, 0) < 0) {
437 RAW_LOG(ERROR, "setpgid failed");
438 _exit(127);
442 // Stop type-profiler.
443 // The profiler should be stopped between fork and exec since it inserts
444 // locks at new/delete expressions. See http://crbug.com/36678.
445 base::type_profiler::Controller::Stop();
447 if (options.maximize_rlimits) {
448 // Some resource limits need to be maximal in this child.
449 for (size_t i = 0; i < options.maximize_rlimits->size(); ++i) {
450 const int resource = (*options.maximize_rlimits)[i];
451 struct rlimit limit;
452 if (getrlimit(resource, &limit) < 0) {
453 RAW_LOG(WARNING, "getrlimit failed");
454 } else if (limit.rlim_cur < limit.rlim_max) {
455 limit.rlim_cur = limit.rlim_max;
456 if (setrlimit(resource, &limit) < 0) {
457 RAW_LOG(WARNING, "setrlimit failed");
463 #if defined(OS_MACOSX)
464 RestoreDefaultExceptionHandler();
465 if (!options.replacement_bootstrap_name.empty())
466 ReplaceBootstrapPort(options.replacement_bootstrap_name);
467 #endif // defined(OS_MACOSX)
469 ResetChildSignalHandlersToDefaults();
470 SetSignalMask(orig_sigmask);
472 #if 0
473 // When debugging it can be helpful to check that we really aren't making
474 // any hidden calls to malloc.
475 void *malloc_thunk =
476 reinterpret_cast<void*>(reinterpret_cast<intptr_t>(malloc) & ~4095);
477 mprotect(malloc_thunk, 4096, PROT_READ | PROT_WRITE | PROT_EXEC);
478 memset(reinterpret_cast<void*>(malloc), 0xff, 8);
479 #endif // 0
481 #if defined(OS_CHROMEOS)
482 if (options.ctrl_terminal_fd >= 0) {
483 // Set process' controlling terminal.
484 if (HANDLE_EINTR(setsid()) != -1) {
485 if (HANDLE_EINTR(
486 ioctl(options.ctrl_terminal_fd, TIOCSCTTY, NULL)) == -1) {
487 RAW_LOG(WARNING, "ioctl(TIOCSCTTY), ctrl terminal not set");
489 } else {
490 RAW_LOG(WARNING, "setsid failed, ctrl terminal not set");
493 #endif // defined(OS_CHROMEOS)
495 if (options.fds_to_remap) {
496 // Cannot use STL iterators here, since debug iterators use locks.
497 for (size_t i = 0; i < options.fds_to_remap->size(); ++i) {
498 const FileHandleMappingVector::value_type& value =
499 (*options.fds_to_remap)[i];
500 fd_shuffle1.push_back(InjectionArc(value.first, value.second, false));
501 fd_shuffle2.push_back(InjectionArc(value.first, value.second, false));
505 if (!options.environ.empty() || options.clear_environ)
506 SetEnvironment(new_environ.get());
508 // fd_shuffle1 is mutated by this call because it cannot malloc.
509 if (!ShuffleFileDescriptors(&fd_shuffle1))
510 _exit(127);
512 CloseSuperfluousFds(fd_shuffle2);
514 // Set NO_NEW_PRIVS by default. Since NO_NEW_PRIVS only exists in kernel
515 // 3.5+, do not check the return value of prctl here.
516 #if defined(OS_LINUX)
517 #ifndef PR_SET_NO_NEW_PRIVS
518 #define PR_SET_NO_NEW_PRIVS 38
519 #endif
520 if (!options.allow_new_privs) {
521 if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) && errno != EINVAL) {
522 // Only log if the error is not EINVAL (i.e. not supported).
523 RAW_LOG(FATAL, "prctl(PR_SET_NO_NEW_PRIVS) failed");
527 if (options.kill_on_parent_death) {
528 if (prctl(PR_SET_PDEATHSIG, SIGKILL) != 0) {
529 RAW_LOG(ERROR, "prctl(PR_SET_PDEATHSIG) failed");
530 _exit(127);
533 #endif
535 if (current_directory != nullptr) {
536 RAW_CHECK(chdir(current_directory) == 0);
539 if (options.pre_exec_delegate != nullptr) {
540 options.pre_exec_delegate->RunAsyncSafe();
543 execvp(argv_cstr[0], argv_cstr.get());
545 RAW_LOG(ERROR, "LaunchProcess: failed to execvp:");
546 RAW_LOG(ERROR, argv_cstr[0]);
547 _exit(127);
548 } else {
549 // Parent process
550 if (options.wait) {
551 // While this isn't strictly disk IO, waiting for another process to
552 // finish is the sort of thing ThreadRestrictions is trying to prevent.
553 base::ThreadRestrictions::AssertIOAllowed();
554 pid_t ret = HANDLE_EINTR(waitpid(pid, 0, 0));
555 DPCHECK(ret > 0);
559 return Process(pid);
562 void RaiseProcessToHighPriority() {
563 // On POSIX, we don't actually do anything here. We could try to nice() or
564 // setpriority() or sched_getscheduler, but these all require extra rights.
567 // Return value used by GetAppOutputInternal to encapsulate the various exit
568 // scenarios from the function.
569 enum GetAppOutputInternalResult {
570 EXECUTE_FAILURE,
571 EXECUTE_SUCCESS,
572 GOT_MAX_OUTPUT,
575 // Executes the application specified by |argv| and wait for it to exit. Stores
576 // the output (stdout) in |output|. If |do_search_path| is set, it searches the
577 // path for the application; in that case, |envp| must be null, and it will use
578 // the current environment. If |do_search_path| is false, |argv[0]| should fully
579 // specify the path of the application, and |envp| will be used as the
580 // environment. Redirects stderr to /dev/null.
581 // If we successfully start the application and get all requested output, we
582 // return GOT_MAX_OUTPUT, or if there is a problem starting or exiting
583 // the application we return RUN_FAILURE. Otherwise we return EXECUTE_SUCCESS.
584 // The GOT_MAX_OUTPUT return value exists so a caller that asks for limited
585 // output can treat this as a success, despite having an exit code of SIG_PIPE
586 // due to us closing the output pipe.
587 // In the case of EXECUTE_SUCCESS, the application exit code will be returned
588 // in |*exit_code|, which should be checked to determine if the application
589 // ran successfully.
590 static GetAppOutputInternalResult GetAppOutputInternal(
591 const std::vector<std::string>& argv,
592 char* const envp[],
593 std::string* output,
594 size_t max_output,
595 bool do_search_path,
596 int* exit_code) {
597 // Doing a blocking wait for another command to finish counts as IO.
598 base::ThreadRestrictions::AssertIOAllowed();
599 // exit_code must be supplied so calling function can determine success.
600 DCHECK(exit_code);
601 *exit_code = EXIT_FAILURE;
603 int pipe_fd[2];
604 pid_t pid;
605 InjectiveMultimap fd_shuffle1, fd_shuffle2;
606 scoped_ptr<char*[]> argv_cstr(new char*[argv.size() + 1]);
608 fd_shuffle1.reserve(3);
609 fd_shuffle2.reserve(3);
611 // Either |do_search_path| should be false or |envp| should be null, but not
612 // both.
613 DCHECK(!do_search_path ^ !envp);
615 if (pipe(pipe_fd) < 0)
616 return EXECUTE_FAILURE;
618 switch (pid = fork()) {
619 case -1: // error
620 close(pipe_fd[0]);
621 close(pipe_fd[1]);
622 return EXECUTE_FAILURE;
623 case 0: // child
625 // DANGER: no calls to malloc or locks are allowed from now on:
626 // http://crbug.com/36678
628 #if defined(OS_MACOSX)
629 RestoreDefaultExceptionHandler();
630 #endif
632 // Obscure fork() rule: in the child, if you don't end up doing exec*(),
633 // you call _exit() instead of exit(). This is because _exit() does not
634 // call any previously-registered (in the parent) exit handlers, which
635 // might do things like block waiting for threads that don't even exist
636 // in the child.
637 int dev_null = open("/dev/null", O_WRONLY);
638 if (dev_null < 0)
639 _exit(127);
641 // Stop type-profiler.
642 // The profiler should be stopped between fork and exec since it inserts
643 // locks at new/delete expressions. See http://crbug.com/36678.
644 base::type_profiler::Controller::Stop();
646 fd_shuffle1.push_back(InjectionArc(pipe_fd[1], STDOUT_FILENO, true));
647 fd_shuffle1.push_back(InjectionArc(dev_null, STDERR_FILENO, true));
648 fd_shuffle1.push_back(InjectionArc(dev_null, STDIN_FILENO, true));
649 // Adding another element here? Remeber to increase the argument to
650 // reserve(), above.
652 for (size_t i = 0; i < fd_shuffle1.size(); ++i)
653 fd_shuffle2.push_back(fd_shuffle1[i]);
655 if (!ShuffleFileDescriptors(&fd_shuffle1))
656 _exit(127);
658 CloseSuperfluousFds(fd_shuffle2);
660 for (size_t i = 0; i < argv.size(); i++)
661 argv_cstr[i] = const_cast<char*>(argv[i].c_str());
662 argv_cstr[argv.size()] = NULL;
663 if (do_search_path)
664 execvp(argv_cstr[0], argv_cstr.get());
665 else
666 execve(argv_cstr[0], argv_cstr.get(), envp);
667 _exit(127);
669 default: // parent
671 // Close our writing end of pipe now. Otherwise later read would not
672 // be able to detect end of child's output (in theory we could still
673 // write to the pipe).
674 close(pipe_fd[1]);
676 output->clear();
677 char buffer[256];
678 size_t output_buf_left = max_output;
679 ssize_t bytes_read = 1; // A lie to properly handle |max_output == 0|
680 // case in the logic below.
682 while (output_buf_left > 0) {
683 bytes_read = HANDLE_EINTR(read(pipe_fd[0], buffer,
684 std::min(output_buf_left, sizeof(buffer))));
685 if (bytes_read <= 0)
686 break;
687 output->append(buffer, bytes_read);
688 output_buf_left -= static_cast<size_t>(bytes_read);
690 close(pipe_fd[0]);
692 // Always wait for exit code (even if we know we'll declare
693 // GOT_MAX_OUTPUT).
694 Process process(pid);
695 bool success = process.WaitForExit(exit_code);
697 // If we stopped because we read as much as we wanted, we return
698 // GOT_MAX_OUTPUT (because the child may exit due to |SIGPIPE|).
699 if (!output_buf_left && bytes_read > 0)
700 return GOT_MAX_OUTPUT;
701 else if (success)
702 return EXECUTE_SUCCESS;
703 return EXECUTE_FAILURE;
708 bool GetAppOutput(const CommandLine& cl, std::string* output) {
709 return GetAppOutput(cl.argv(), output);
712 bool GetAppOutput(const std::vector<std::string>& argv, std::string* output) {
713 // Run |execve()| with the current environment and store "unlimited" data.
714 int exit_code;
715 GetAppOutputInternalResult result = GetAppOutputInternal(
716 argv, NULL, output, std::numeric_limits<std::size_t>::max(), true,
717 &exit_code);
718 return result == EXECUTE_SUCCESS && exit_code == EXIT_SUCCESS;
721 // TODO(viettrungluu): Conceivably, we should have a timeout as well, so we
722 // don't hang if what we're calling hangs.
723 bool GetAppOutputRestricted(const CommandLine& cl,
724 std::string* output, size_t max_output) {
725 // Run |execve()| with the empty environment.
726 char* const empty_environ = NULL;
727 int exit_code;
728 GetAppOutputInternalResult result = GetAppOutputInternal(
729 cl.argv(), &empty_environ, output, max_output, false, &exit_code);
730 return result == GOT_MAX_OUTPUT || (result == EXECUTE_SUCCESS &&
731 exit_code == EXIT_SUCCESS);
734 bool GetAppOutputWithExitCode(const CommandLine& cl,
735 std::string* output,
736 int* exit_code) {
737 // Run |execve()| with the current environment and store "unlimited" data.
738 GetAppOutputInternalResult result = GetAppOutputInternal(
739 cl.argv(), NULL, output, std::numeric_limits<std::size_t>::max(), true,
740 exit_code);
741 return result == EXECUTE_SUCCESS;
744 #if defined(OS_LINUX)
745 pid_t ForkWithFlags(unsigned long flags, pid_t* ptid, pid_t* ctid) {
746 const bool clone_tls_used = flags & CLONE_SETTLS;
747 const bool invalid_ctid =
748 (flags & (CLONE_CHILD_SETTID | CLONE_CHILD_CLEARTID)) && !ctid;
749 const bool invalid_ptid = (flags & CLONE_PARENT_SETTID) && !ptid;
751 // We do not support CLONE_VM.
752 const bool clone_vm_used = flags & CLONE_VM;
754 if (clone_tls_used || invalid_ctid || invalid_ptid || clone_vm_used) {
755 RAW_LOG(FATAL, "Invalid usage of ForkWithFlags");
758 // Valgrind's clone implementation does not support specifiying a child_stack
759 // without CLONE_VM, so we cannot use libc's clone wrapper when running under
760 // Valgrind. As a result, the libc pid cache may be incorrect under Valgrind.
761 // See crbug.com/442817 for more details.
762 if (IsRunningOnValgrind()) {
763 // See kernel/fork.c in Linux. There is different ordering of sys_clone
764 // parameters depending on CONFIG_CLONE_BACKWARDS* configuration options.
765 #if defined(ARCH_CPU_X86_64)
766 return syscall(__NR_clone, flags, nullptr, ptid, ctid, nullptr);
767 #elif defined(ARCH_CPU_X86) || defined(ARCH_CPU_ARM_FAMILY) || \
768 defined(ARCH_CPU_MIPS_FAMILY) || defined(ARCH_CPU_MIPS64_FAMILY)
769 // CONFIG_CLONE_BACKWARDS defined.
770 return syscall(__NR_clone, flags, nullptr, ptid, nullptr, ctid);
771 #else
772 #error "Unsupported architecture"
773 #endif
776 jmp_buf env;
777 if (setjmp(env) == 0) {
778 return CloneAndLongjmpInChild(flags, ptid, ctid, &env);
781 return 0;
783 #endif // defined(OS_LINUX)
785 } // namespace base