Delete chrome.mediaGalleriesPrivate because the functionality unique to it has since...
[chromium-blink-merge.git] / base / process / launch_posix.cc
blobce93d5056fd838bf332da563186c5bc704130e22
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/kill.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 scoped_ptr<char*[]> new_environ;
352 char* const empty_environ = NULL;
353 char* const* old_environ = GetEnvironment();
354 if (options.clear_environ)
355 old_environ = &empty_environ;
356 if (!options.environ.empty())
357 new_environ = AlterEnvironment(old_environ, options.environ);
359 sigset_t full_sigset;
360 sigfillset(&full_sigset);
361 const sigset_t orig_sigmask = SetSignalMask(full_sigset);
363 pid_t pid;
364 #if defined(OS_LINUX)
365 if (options.clone_flags) {
366 // Signal handling in this function assumes the creation of a new
367 // process, so we check that a thread is not being created by mistake
368 // and that signal handling follows the process-creation rules.
369 RAW_CHECK(
370 !(options.clone_flags & (CLONE_SIGHAND | CLONE_THREAD | CLONE_VM)));
372 // We specify a null ptid and ctid.
373 RAW_CHECK(
374 !(options.clone_flags &
375 (CLONE_CHILD_CLEARTID | CLONE_CHILD_SETTID | CLONE_PARENT_SETTID)));
377 // Since we use waitpid, we do not support custom termination signals in the
378 // clone flags.
379 RAW_CHECK((options.clone_flags & 0xff) == 0);
381 pid = ForkWithFlags(options.clone_flags | SIGCHLD, nullptr, nullptr);
382 } else
383 #endif
385 pid = fork();
388 // Always restore the original signal mask in the parent.
389 if (pid != 0) {
390 SetSignalMask(orig_sigmask);
393 if (pid < 0) {
394 DPLOG(ERROR) << "fork";
395 return Process();
396 } else if (pid == 0) {
397 // Child process
399 // DANGER: no calls to malloc or locks are allowed from now on:
400 // http://crbug.com/36678
402 // DANGER: fork() rule: in the child, if you don't end up doing exec*(),
403 // you call _exit() instead of exit(). This is because _exit() does not
404 // call any previously-registered (in the parent) exit handlers, which
405 // might do things like block waiting for threads that don't even exist
406 // in the child.
408 // If a child process uses the readline library, the process block forever.
409 // In BSD like OSes including OS X it is safe to assign /dev/null as stdin.
410 // See http://crbug.com/56596.
411 base::ScopedFD null_fd(HANDLE_EINTR(open("/dev/null", O_RDONLY)));
412 if (!null_fd.is_valid()) {
413 RAW_LOG(ERROR, "Failed to open /dev/null");
414 _exit(127);
417 int new_fd = HANDLE_EINTR(dup2(null_fd.get(), STDIN_FILENO));
418 if (new_fd != STDIN_FILENO) {
419 RAW_LOG(ERROR, "Failed to dup /dev/null for stdin");
420 _exit(127);
423 if (options.new_process_group) {
424 // Instead of inheriting the process group ID of the parent, the child
425 // starts off a new process group with pgid equal to its process ID.
426 if (setpgid(0, 0) < 0) {
427 RAW_LOG(ERROR, "setpgid failed");
428 _exit(127);
432 // Stop type-profiler.
433 // The profiler should be stopped between fork and exec since it inserts
434 // locks at new/delete expressions. See http://crbug.com/36678.
435 base::type_profiler::Controller::Stop();
437 if (options.maximize_rlimits) {
438 // Some resource limits need to be maximal in this child.
439 for (size_t i = 0; i < options.maximize_rlimits->size(); ++i) {
440 const int resource = (*options.maximize_rlimits)[i];
441 struct rlimit limit;
442 if (getrlimit(resource, &limit) < 0) {
443 RAW_LOG(WARNING, "getrlimit failed");
444 } else if (limit.rlim_cur < limit.rlim_max) {
445 limit.rlim_cur = limit.rlim_max;
446 if (setrlimit(resource, &limit) < 0) {
447 RAW_LOG(WARNING, "setrlimit failed");
453 #if defined(OS_MACOSX)
454 RestoreDefaultExceptionHandler();
455 if (!options.replacement_bootstrap_name.empty())
456 ReplaceBootstrapPort(options.replacement_bootstrap_name);
457 #endif // defined(OS_MACOSX)
459 ResetChildSignalHandlersToDefaults();
460 SetSignalMask(orig_sigmask);
462 #if 0
463 // When debugging it can be helpful to check that we really aren't making
464 // any hidden calls to malloc.
465 void *malloc_thunk =
466 reinterpret_cast<void*>(reinterpret_cast<intptr_t>(malloc) & ~4095);
467 mprotect(malloc_thunk, 4096, PROT_READ | PROT_WRITE | PROT_EXEC);
468 memset(reinterpret_cast<void*>(malloc), 0xff, 8);
469 #endif // 0
471 #if defined(OS_CHROMEOS)
472 if (options.ctrl_terminal_fd >= 0) {
473 // Set process' controlling terminal.
474 if (HANDLE_EINTR(setsid()) != -1) {
475 if (HANDLE_EINTR(
476 ioctl(options.ctrl_terminal_fd, TIOCSCTTY, NULL)) == -1) {
477 RAW_LOG(WARNING, "ioctl(TIOCSCTTY), ctrl terminal not set");
479 } else {
480 RAW_LOG(WARNING, "setsid failed, ctrl terminal not set");
483 #endif // defined(OS_CHROMEOS)
485 if (options.fds_to_remap) {
486 // Cannot use STL iterators here, since debug iterators use locks.
487 for (size_t i = 0; i < options.fds_to_remap->size(); ++i) {
488 const FileHandleMappingVector::value_type& value =
489 (*options.fds_to_remap)[i];
490 fd_shuffle1.push_back(InjectionArc(value.first, value.second, false));
491 fd_shuffle2.push_back(InjectionArc(value.first, value.second, false));
495 if (!options.environ.empty() || options.clear_environ)
496 SetEnvironment(new_environ.get());
498 // fd_shuffle1 is mutated by this call because it cannot malloc.
499 if (!ShuffleFileDescriptors(&fd_shuffle1))
500 _exit(127);
502 CloseSuperfluousFds(fd_shuffle2);
504 // Set NO_NEW_PRIVS by default. Since NO_NEW_PRIVS only exists in kernel
505 // 3.5+, do not check the return value of prctl here.
506 #if defined(OS_LINUX)
507 #ifndef PR_SET_NO_NEW_PRIVS
508 #define PR_SET_NO_NEW_PRIVS 38
509 #endif
510 if (!options.allow_new_privs) {
511 if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) && errno != EINVAL) {
512 // Only log if the error is not EINVAL (i.e. not supported).
513 RAW_LOG(FATAL, "prctl(PR_SET_NO_NEW_PRIVS) failed");
516 #endif
518 #if defined(OS_POSIX)
519 if (options.pre_exec_delegate != nullptr) {
520 options.pre_exec_delegate->RunAsyncSafe();
522 #endif
524 for (size_t i = 0; i < argv.size(); i++)
525 argv_cstr[i] = const_cast<char*>(argv[i].c_str());
526 argv_cstr[argv.size()] = NULL;
527 execvp(argv_cstr[0], argv_cstr.get());
529 RAW_LOG(ERROR, "LaunchProcess: failed to execvp:");
530 RAW_LOG(ERROR, argv_cstr[0]);
531 _exit(127);
532 } else {
533 // Parent process
534 if (options.wait) {
535 // While this isn't strictly disk IO, waiting for another process to
536 // finish is the sort of thing ThreadRestrictions is trying to prevent.
537 base::ThreadRestrictions::AssertIOAllowed();
538 pid_t ret = HANDLE_EINTR(waitpid(pid, 0, 0));
539 DPCHECK(ret > 0);
543 return Process(pid);
546 void RaiseProcessToHighPriority() {
547 // On POSIX, we don't actually do anything here. We could try to nice() or
548 // setpriority() or sched_getscheduler, but these all require extra rights.
551 // Return value used by GetAppOutputInternal to encapsulate the various exit
552 // scenarios from the function.
553 enum GetAppOutputInternalResult {
554 EXECUTE_FAILURE,
555 EXECUTE_SUCCESS,
556 GOT_MAX_OUTPUT,
559 // Executes the application specified by |argv| and wait for it to exit. Stores
560 // the output (stdout) in |output|. If |do_search_path| is set, it searches the
561 // path for the application; in that case, |envp| must be null, and it will use
562 // the current environment. If |do_search_path| is false, |argv[0]| should fully
563 // specify the path of the application, and |envp| will be used as the
564 // environment. Redirects stderr to /dev/null.
565 // If we successfully start the application and get all requested output, we
566 // return GOT_MAX_OUTPUT, or if there is a problem starting or exiting
567 // the application we return RUN_FAILURE. Otherwise we return EXECUTE_SUCCESS.
568 // The GOT_MAX_OUTPUT return value exists so a caller that asks for limited
569 // output can treat this as a success, despite having an exit code of SIG_PIPE
570 // due to us closing the output pipe.
571 // In the case of EXECUTE_SUCCESS, the application exit code will be returned
572 // in |*exit_code|, which should be checked to determine if the application
573 // ran successfully.
574 static GetAppOutputInternalResult GetAppOutputInternal(
575 const std::vector<std::string>& argv,
576 char* const envp[],
577 std::string* output,
578 size_t max_output,
579 bool do_search_path,
580 int* exit_code) {
581 // Doing a blocking wait for another command to finish counts as IO.
582 base::ThreadRestrictions::AssertIOAllowed();
583 // exit_code must be supplied so calling function can determine success.
584 DCHECK(exit_code);
585 *exit_code = EXIT_FAILURE;
587 int pipe_fd[2];
588 pid_t pid;
589 InjectiveMultimap fd_shuffle1, fd_shuffle2;
590 scoped_ptr<char*[]> argv_cstr(new char*[argv.size() + 1]);
592 fd_shuffle1.reserve(3);
593 fd_shuffle2.reserve(3);
595 // Either |do_search_path| should be false or |envp| should be null, but not
596 // both.
597 DCHECK(!do_search_path ^ !envp);
599 if (pipe(pipe_fd) < 0)
600 return EXECUTE_FAILURE;
602 switch (pid = fork()) {
603 case -1: // error
604 close(pipe_fd[0]);
605 close(pipe_fd[1]);
606 return EXECUTE_FAILURE;
607 case 0: // child
609 // DANGER: no calls to malloc or locks are allowed from now on:
610 // http://crbug.com/36678
612 #if defined(OS_MACOSX)
613 RestoreDefaultExceptionHandler();
614 #endif
616 // Obscure fork() rule: in the child, if you don't end up doing exec*(),
617 // you call _exit() instead of exit(). This is because _exit() does not
618 // call any previously-registered (in the parent) exit handlers, which
619 // might do things like block waiting for threads that don't even exist
620 // in the child.
621 int dev_null = open("/dev/null", O_WRONLY);
622 if (dev_null < 0)
623 _exit(127);
625 // Stop type-profiler.
626 // The profiler should be stopped between fork and exec since it inserts
627 // locks at new/delete expressions. See http://crbug.com/36678.
628 base::type_profiler::Controller::Stop();
630 fd_shuffle1.push_back(InjectionArc(pipe_fd[1], STDOUT_FILENO, true));
631 fd_shuffle1.push_back(InjectionArc(dev_null, STDERR_FILENO, true));
632 fd_shuffle1.push_back(InjectionArc(dev_null, STDIN_FILENO, true));
633 // Adding another element here? Remeber to increase the argument to
634 // reserve(), above.
636 for (size_t i = 0; i < fd_shuffle1.size(); ++i)
637 fd_shuffle2.push_back(fd_shuffle1[i]);
639 if (!ShuffleFileDescriptors(&fd_shuffle1))
640 _exit(127);
642 CloseSuperfluousFds(fd_shuffle2);
644 for (size_t i = 0; i < argv.size(); i++)
645 argv_cstr[i] = const_cast<char*>(argv[i].c_str());
646 argv_cstr[argv.size()] = NULL;
647 if (do_search_path)
648 execvp(argv_cstr[0], argv_cstr.get());
649 else
650 execve(argv_cstr[0], argv_cstr.get(), envp);
651 _exit(127);
653 default: // parent
655 // Close our writing end of pipe now. Otherwise later read would not
656 // be able to detect end of child's output (in theory we could still
657 // write to the pipe).
658 close(pipe_fd[1]);
660 output->clear();
661 char buffer[256];
662 size_t output_buf_left = max_output;
663 ssize_t bytes_read = 1; // A lie to properly handle |max_output == 0|
664 // case in the logic below.
666 while (output_buf_left > 0) {
667 bytes_read = HANDLE_EINTR(read(pipe_fd[0], buffer,
668 std::min(output_buf_left, sizeof(buffer))));
669 if (bytes_read <= 0)
670 break;
671 output->append(buffer, bytes_read);
672 output_buf_left -= static_cast<size_t>(bytes_read);
674 close(pipe_fd[0]);
676 // Always wait for exit code (even if we know we'll declare
677 // GOT_MAX_OUTPUT).
678 bool success = WaitForExitCode(pid, exit_code);
680 // If we stopped because we read as much as we wanted, we return
681 // GOT_MAX_OUTPUT (because the child may exit due to |SIGPIPE|).
682 if (!output_buf_left && bytes_read > 0)
683 return GOT_MAX_OUTPUT;
684 else if (success)
685 return EXECUTE_SUCCESS;
686 return EXECUTE_FAILURE;
691 bool GetAppOutput(const CommandLine& cl, std::string* output) {
692 return GetAppOutput(cl.argv(), output);
695 bool GetAppOutput(const std::vector<std::string>& argv, std::string* output) {
696 // Run |execve()| with the current environment and store "unlimited" data.
697 int exit_code;
698 GetAppOutputInternalResult result = GetAppOutputInternal(
699 argv, NULL, output, std::numeric_limits<std::size_t>::max(), true,
700 &exit_code);
701 return result == EXECUTE_SUCCESS && exit_code == EXIT_SUCCESS;
704 // TODO(viettrungluu): Conceivably, we should have a timeout as well, so we
705 // don't hang if what we're calling hangs.
706 bool GetAppOutputRestricted(const CommandLine& cl,
707 std::string* output, size_t max_output) {
708 // Run |execve()| with the empty environment.
709 char* const empty_environ = NULL;
710 int exit_code;
711 GetAppOutputInternalResult result = GetAppOutputInternal(
712 cl.argv(), &empty_environ, output, max_output, false, &exit_code);
713 return result == GOT_MAX_OUTPUT || (result == EXECUTE_SUCCESS &&
714 exit_code == EXIT_SUCCESS);
717 bool GetAppOutputWithExitCode(const CommandLine& cl,
718 std::string* output,
719 int* exit_code) {
720 // Run |execve()| with the current environment and store "unlimited" data.
721 GetAppOutputInternalResult result = GetAppOutputInternal(
722 cl.argv(), NULL, output, std::numeric_limits<std::size_t>::max(), true,
723 exit_code);
724 return result == EXECUTE_SUCCESS;
727 #if defined(OS_LINUX)
728 pid_t ForkWithFlags(unsigned long flags, pid_t* ptid, pid_t* ctid) {
729 const bool clone_tls_used = flags & CLONE_SETTLS;
730 const bool invalid_ctid =
731 (flags & (CLONE_CHILD_SETTID | CLONE_CHILD_CLEARTID)) && !ctid;
732 const bool invalid_ptid = (flags & CLONE_PARENT_SETTID) && !ptid;
734 // We do not support CLONE_VM.
735 const bool clone_vm_used = flags & CLONE_VM;
737 if (clone_tls_used || invalid_ctid || invalid_ptid || clone_vm_used) {
738 RAW_LOG(FATAL, "Invalid usage of ForkWithFlags");
741 // Valgrind's clone implementation does not support specifiying a child_stack
742 // without CLONE_VM, so we cannot use libc's clone wrapper when running under
743 // Valgrind. As a result, the libc pid cache may be incorrect under Valgrind.
744 // See crbug.com/442817 for more details.
745 if (IsRunningOnValgrind()) {
746 // See kernel/fork.c in Linux. There is different ordering of sys_clone
747 // parameters depending on CONFIG_CLONE_BACKWARDS* configuration options.
748 #if defined(ARCH_CPU_X86_64)
749 return syscall(__NR_clone, flags, nullptr, ptid, ctid, nullptr);
750 #elif defined(ARCH_CPU_X86) || defined(ARCH_CPU_ARM_FAMILY) || \
751 defined(ARCH_CPU_MIPS_FAMILY) || defined(ARCH_CPU_MIPS64_FAMILY)
752 // CONFIG_CLONE_BACKWARDS defined.
753 return syscall(__NR_clone, flags, nullptr, ptid, nullptr, ctid);
754 #else
755 #error "Unsupported architecture"
756 #endif
759 jmp_buf env;
760 if (setjmp(env) == 0) {
761 return CloneAndLongjmpInChild(flags, ptid, ctid, &env);
764 return 0;
766 #endif // defined(OS_LINUX)
768 } // namespace base