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