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