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