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