1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "base/process/launch.h"
12 #include <sys/resource.h>
14 #include <sys/types.h>
22 #include "base/allocator/type_profiler_control.h"
23 #include "base/command_line.h"
24 #include "base/compiler_specific.h"
25 #include "base/debug/debugger.h"
26 #include "base/debug/stack_trace.h"
27 #include "base/file_util.h"
28 #include "base/files/dir_reader_posix.h"
29 #include "base/logging.h"
30 #include "base/memory/scoped_ptr.h"
31 #include "base/posix/eintr_wrapper.h"
32 #include "base/process/kill.h"
33 #include "base/process/process_metrics.h"
34 #include "base/strings/stringprintf.h"
35 #include "base/synchronization/waitable_event.h"
36 #include "base/third_party/dynamic_annotations/dynamic_annotations.h"
37 #include "base/threading/platform_thread.h"
38 #include "base/threading/thread_restrictions.h"
40 #if defined(OS_CHROMEOS)
41 #include <sys/ioctl.h>
44 #if defined(OS_FREEBSD)
45 #include <sys/event.h>
46 #include <sys/ucontext.h>
49 #if defined(OS_MACOSX)
50 #include <crt_externs.h>
51 #include <sys/event.h>
53 extern char** environ
;
60 // Get the process's "environment" (i.e. the thing that setenv/getenv
62 char** GetEnvironment() {
63 #if defined(OS_MACOSX)
64 return *_NSGetEnviron();
70 // Set the process's "environment" (i.e. the thing that setenv/getenv
72 void SetEnvironment(char** env
) {
73 #if defined(OS_MACOSX)
74 *_NSGetEnviron() = env
;
80 // Set the calling thread's signal mask to new_sigmask and return
81 // the previous signal mask.
82 sigset_t
SetSignalMask(const sigset_t
& new_sigmask
) {
84 #if defined(OS_ANDROID)
85 // POSIX says pthread_sigmask() must be used in multi-threaded processes,
86 // but Android's pthread_sigmask() was broken until 4.1:
87 // https://code.google.com/p/android/issues/detail?id=15337
88 // http://stackoverflow.com/questions/13777109/pthread-sigmask-on-android-not-working
89 RAW_CHECK(sigprocmask(SIG_SETMASK
, &new_sigmask
, &old_sigmask
) == 0);
91 RAW_CHECK(pthread_sigmask(SIG_SETMASK
, &new_sigmask
, &old_sigmask
) == 0);
96 #if !defined(OS_LINUX) || \
97 (!defined(__i386__) && !defined(__x86_64__) && !defined(__arm__))
98 void ResetChildSignalHandlersToDefaults() {
99 // The previous signal handlers are likely to be meaningless in the child's
100 // context so we reset them to the defaults for now. http://crbug.com/44953
101 // These signal handlers are set up at least in browser_main_posix.cc:
102 // BrowserMainPartsPosix::PreEarlyInitialization and stack_trace_posix.cc:
103 // EnableInProcessStackDumping.
104 signal(SIGHUP
, SIG_DFL
);
105 signal(SIGINT
, SIG_DFL
);
106 signal(SIGILL
, SIG_DFL
);
107 signal(SIGABRT
, SIG_DFL
);
108 signal(SIGFPE
, SIG_DFL
);
109 signal(SIGBUS
, SIG_DFL
);
110 signal(SIGSEGV
, SIG_DFL
);
111 signal(SIGSYS
, SIG_DFL
);
112 signal(SIGTERM
, SIG_DFL
);
117 // TODO(jln): remove the Linux special case once kernels are fixed.
119 // Internally the kernel makes sigset_t an array of long large enough to have
120 // one bit per signal.
121 typedef uint64_t kernel_sigset_t
;
123 // This is what struct sigaction looks like to the kernel at least on X86 and
124 // ARM. MIPS, for instance, is very different.
125 struct kernel_sigaction
{
126 void* k_sa_handler
; // For this usage it only needs to be a generic pointer.
127 unsigned long k_sa_flags
;
128 void* k_sa_restorer
; // For this usage it only needs to be a generic pointer.
129 kernel_sigset_t k_sa_mask
;
132 // glibc's sigaction() will prevent access to sa_restorer, so we need to roll
134 int sys_rt_sigaction(int sig
, const struct kernel_sigaction
* act
,
135 struct kernel_sigaction
* oact
) {
136 return syscall(SYS_rt_sigaction
, sig
, act
, oact
, sizeof(kernel_sigset_t
));
139 // This function is intended to be used in between fork() and execve() and will
140 // reset all signal handlers to the default.
141 // The motivation for going through all of them is that sa_restorer can leak
142 // from parents and help defeat ASLR on buggy kernels. We reset it to NULL.
143 // See crbug.com/177956.
144 void ResetChildSignalHandlersToDefaults(void) {
145 for (int signum
= 1; ; ++signum
) {
146 struct kernel_sigaction act
= {0};
147 int sigaction_get_ret
= sys_rt_sigaction(signum
, NULL
, &act
);
148 if (sigaction_get_ret
&& errno
== EINVAL
) {
150 // Linux supports 32 real-time signals from 33 to 64.
151 // If the number of signals in the Linux kernel changes, someone should
152 // look at this code.
153 const int kNumberOfSignals
= 64;
154 RAW_CHECK(signum
== kNumberOfSignals
+ 1);
155 #endif // !defined(NDEBUG)
158 // All other failures are fatal.
159 if (sigaction_get_ret
) {
160 RAW_LOG(FATAL
, "sigaction (get) failed.");
163 // The kernel won't allow to re-set SIGKILL or SIGSTOP.
164 if (signum
!= SIGSTOP
&& signum
!= SIGKILL
) {
165 act
.k_sa_handler
= reinterpret_cast<void*>(SIG_DFL
);
166 act
.k_sa_restorer
= NULL
;
167 if (sys_rt_sigaction(signum
, &act
, NULL
)) {
168 RAW_LOG(FATAL
, "sigaction (set) failed.");
172 // Now ask the kernel again and check that no restorer will leak.
173 if (sys_rt_sigaction(signum
, NULL
, &act
) || act
.k_sa_restorer
) {
174 RAW_LOG(FATAL
, "Cound not fix sa_restorer.");
176 #endif // !defined(NDEBUG)
179 #endif // !defined(OS_LINUX) ||
180 // (!defined(__i386__) && !defined(__x86_64__) && !defined(__arm__))
182 } // anonymous namespace
184 // A class to handle auto-closing of DIR*'s.
185 class ScopedDIRClose
{
187 inline void operator()(DIR* x
) const {
193 typedef scoped_ptr_malloc
<DIR, ScopedDIRClose
> ScopedDIR
;
195 #if defined(OS_LINUX)
196 static const char kFDDir
[] = "/proc/self/fd";
197 #elif defined(OS_MACOSX)
198 static const char kFDDir
[] = "/dev/fd";
199 #elif defined(OS_SOLARIS)
200 static const char kFDDir
[] = "/dev/fd";
201 #elif defined(OS_FREEBSD)
202 static const char kFDDir
[] = "/dev/fd";
203 #elif defined(OS_OPENBSD)
204 static const char kFDDir
[] = "/dev/fd";
205 #elif defined(OS_ANDROID)
206 static const char kFDDir
[] = "/proc/self/fd";
209 void CloseSuperfluousFds(const base::InjectiveMultimap
& saved_mapping
) {
210 // DANGER: no calls to malloc are allowed from now on:
211 // http://crbug.com/36678
213 // Get the maximum number of FDs possible.
214 size_t max_fds
= GetMaxFds();
216 DirReaderPosix
fd_dir(kFDDir
);
217 if (!fd_dir
.IsValid()) {
218 // Fallback case: Try every possible fd.
219 for (size_t i
= 0; i
< max_fds
; ++i
) {
220 const int fd
= static_cast<int>(i
);
221 if (fd
== STDIN_FILENO
|| fd
== STDOUT_FILENO
|| fd
== STDERR_FILENO
)
223 InjectiveMultimap::const_iterator j
;
224 for (j
= saved_mapping
.begin(); j
!= saved_mapping
.end(); j
++) {
228 if (j
!= saved_mapping
.end())
231 // Since we're just trying to close anything we can find,
232 // ignore any error return values of close().
233 ignore_result(HANDLE_EINTR(close(fd
)));
238 const int dir_fd
= fd_dir
.fd();
240 for ( ; fd_dir
.Next(); ) {
241 // Skip . and .. entries.
242 if (fd_dir
.name()[0] == '.')
247 const long int fd
= strtol(fd_dir
.name(), &endptr
, 10);
248 if (fd_dir
.name()[0] == 0 || *endptr
|| fd
< 0 || errno
)
250 if (fd
== STDIN_FILENO
|| fd
== STDOUT_FILENO
|| fd
== STDERR_FILENO
)
252 InjectiveMultimap::const_iterator i
;
253 for (i
= saved_mapping
.begin(); i
!= saved_mapping
.end(); i
++) {
257 if (i
!= saved_mapping
.end())
262 // When running under Valgrind, Valgrind opens several FDs for its
263 // own use and will complain if we try to close them. All of
264 // these FDs are >= |max_fds|, so we can check against that here
265 // before closing. See https://bugs.kde.org/show_bug.cgi?id=191758
266 if (fd
< static_cast<int>(max_fds
)) {
267 int ret
= HANDLE_EINTR(close(fd
));
273 bool LaunchProcess(const std::vector
<std::string
>& argv
,
274 const LaunchOptions
& options
,
275 ProcessHandle
* process_handle
) {
276 size_t fd_shuffle_size
= 0;
277 if (options
.fds_to_remap
) {
278 fd_shuffle_size
= options
.fds_to_remap
->size();
281 InjectiveMultimap fd_shuffle1
;
282 InjectiveMultimap fd_shuffle2
;
283 fd_shuffle1
.reserve(fd_shuffle_size
);
284 fd_shuffle2
.reserve(fd_shuffle_size
);
286 scoped_ptr
<char*[]> argv_cstr(new char*[argv
.size() + 1]);
287 scoped_ptr
<char*[]> new_environ
;
288 if (!options
.environ
.empty())
289 new_environ
= AlterEnvironment(GetEnvironment(), options
.environ
);
291 sigset_t full_sigset
;
292 sigfillset(&full_sigset
);
293 const sigset_t orig_sigmask
= SetSignalMask(full_sigset
);
296 #if defined(OS_LINUX)
297 if (options
.clone_flags
) {
298 // Signal handling in this function assumes the creation of a new
299 // process, so we check that a thread is not being created by mistake
300 // and that signal handling follows the process-creation rules.
302 !(options
.clone_flags
& (CLONE_SIGHAND
| CLONE_THREAD
| CLONE_VM
)));
303 pid
= syscall(__NR_clone
, options
.clone_flags
, 0, 0, 0);
310 // Always restore the original signal mask in the parent.
312 SetSignalMask(orig_sigmask
);
316 DPLOG(ERROR
) << "fork";
318 } else if (pid
== 0) {
321 // DANGER: fork() rule: in the child, if you don't end up doing exec*(),
322 // you call _exit() instead of exit(). This is because _exit() does not
323 // call any previously-registered (in the parent) exit handlers, which
324 // might do things like block waiting for threads that don't even exist
327 // If a child process uses the readline library, the process block forever.
328 // In BSD like OSes including OS X it is safe to assign /dev/null as stdin.
329 // See http://crbug.com/56596.
330 int null_fd
= HANDLE_EINTR(open("/dev/null", O_RDONLY
));
332 RAW_LOG(ERROR
, "Failed to open /dev/null");
336 file_util::ScopedFD
null_fd_closer(&null_fd
);
337 int new_fd
= HANDLE_EINTR(dup2(null_fd
, STDIN_FILENO
));
338 if (new_fd
!= STDIN_FILENO
) {
339 RAW_LOG(ERROR
, "Failed to dup /dev/null for stdin");
343 if (options
.new_process_group
) {
344 // Instead of inheriting the process group ID of the parent, the child
345 // starts off a new process group with pgid equal to its process ID.
346 if (setpgid(0, 0) < 0) {
347 RAW_LOG(ERROR
, "setpgid failed");
352 // Stop type-profiler.
353 // The profiler should be stopped between fork and exec since it inserts
354 // locks at new/delete expressions. See http://crbug.com/36678.
355 base::type_profiler::Controller::Stop();
357 if (options
.maximize_rlimits
) {
358 // Some resource limits need to be maximal in this child.
359 std::set
<int>::const_iterator resource
;
360 for (resource
= options
.maximize_rlimits
->begin();
361 resource
!= options
.maximize_rlimits
->end();
364 if (getrlimit(*resource
, &limit
) < 0) {
365 RAW_LOG(WARNING
, "getrlimit failed");
366 } else if (limit
.rlim_cur
< limit
.rlim_max
) {
367 limit
.rlim_cur
= limit
.rlim_max
;
368 if (setrlimit(*resource
, &limit
) < 0) {
369 RAW_LOG(WARNING
, "setrlimit failed");
375 #if defined(OS_MACOSX)
376 RestoreDefaultExceptionHandler();
377 #endif // defined(OS_MACOSX)
379 ResetChildSignalHandlersToDefaults();
380 SetSignalMask(orig_sigmask
);
383 // When debugging it can be helpful to check that we really aren't making
384 // any hidden calls to malloc.
386 reinterpret_cast<void*>(reinterpret_cast<intptr_t>(malloc
) & ~4095);
387 mprotect(malloc_thunk
, 4096, PROT_READ
| PROT_WRITE
| PROT_EXEC
);
388 memset(reinterpret_cast<void*>(malloc
), 0xff, 8);
391 // DANGER: no calls to malloc are allowed from now on:
392 // http://crbug.com/36678
394 #if defined(OS_CHROMEOS)
395 if (options
.ctrl_terminal_fd
>= 0) {
396 // Set process' controlling terminal.
397 if (HANDLE_EINTR(setsid()) != -1) {
399 ioctl(options
.ctrl_terminal_fd
, TIOCSCTTY
, NULL
)) == -1) {
400 RAW_LOG(WARNING
, "ioctl(TIOCSCTTY), ctrl terminal not set");
403 RAW_LOG(WARNING
, "setsid failed, ctrl terminal not set");
406 #endif // defined(OS_CHROMEOS)
408 if (options
.fds_to_remap
) {
409 for (FileHandleMappingVector::const_iterator
410 it
= options
.fds_to_remap
->begin();
411 it
!= options
.fds_to_remap
->end(); ++it
) {
412 fd_shuffle1
.push_back(InjectionArc(it
->first
, it
->second
, false));
413 fd_shuffle2
.push_back(InjectionArc(it
->first
, it
->second
, false));
417 if (!options
.environ
.empty())
418 SetEnvironment(new_environ
.get());
420 // fd_shuffle1 is mutated by this call because it cannot malloc.
421 if (!ShuffleFileDescriptors(&fd_shuffle1
))
424 CloseSuperfluousFds(fd_shuffle2
);
426 for (size_t i
= 0; i
< argv
.size(); i
++)
427 argv_cstr
[i
] = const_cast<char*>(argv
[i
].c_str());
428 argv_cstr
[argv
.size()] = NULL
;
429 execvp(argv_cstr
[0], argv_cstr
.get());
431 RAW_LOG(ERROR
, "LaunchProcess: failed to execvp:");
432 RAW_LOG(ERROR
, argv_cstr
[0]);
437 // While this isn't strictly disk IO, waiting for another process to
438 // finish is the sort of thing ThreadRestrictions is trying to prevent.
439 base::ThreadRestrictions::AssertIOAllowed();
440 pid_t ret
= HANDLE_EINTR(waitpid(pid
, 0, 0));
445 *process_handle
= pid
;
452 bool LaunchProcess(const CommandLine
& cmdline
,
453 const LaunchOptions
& options
,
454 ProcessHandle
* process_handle
) {
455 return LaunchProcess(cmdline
.argv(), options
, process_handle
);
458 void RaiseProcessToHighPriority() {
459 // On POSIX, we don't actually do anything here. We could try to nice() or
460 // setpriority() or sched_getscheduler, but these all require extra rights.
463 // Return value used by GetAppOutputInternal to encapsulate the various exit
464 // scenarios from the function.
465 enum GetAppOutputInternalResult
{
471 // Executes the application specified by |argv| and wait for it to exit. Stores
472 // the output (stdout) in |output|. If |do_search_path| is set, it searches the
473 // path for the application; in that case, |envp| must be null, and it will use
474 // the current environment. If |do_search_path| is false, |argv[0]| should fully
475 // specify the path of the application, and |envp| will be used as the
476 // environment. Redirects stderr to /dev/null.
477 // If we successfully start the application and get all requested output, we
478 // return GOT_MAX_OUTPUT, or if there is a problem starting or exiting
479 // the application we return RUN_FAILURE. Otherwise we return EXECUTE_SUCCESS.
480 // The GOT_MAX_OUTPUT return value exists so a caller that asks for limited
481 // output can treat this as a success, despite having an exit code of SIG_PIPE
482 // due to us closing the output pipe.
483 // In the case of EXECUTE_SUCCESS, the application exit code will be returned
484 // in |*exit_code|, which should be checked to determine if the application
486 static GetAppOutputInternalResult
GetAppOutputInternal(
487 const std::vector
<std::string
>& argv
,
493 // Doing a blocking wait for another command to finish counts as IO.
494 base::ThreadRestrictions::AssertIOAllowed();
495 // exit_code must be supplied so calling function can determine success.
497 *exit_code
= EXIT_FAILURE
;
501 InjectiveMultimap fd_shuffle1
, fd_shuffle2
;
502 scoped_ptr
<char*[]> argv_cstr(new char*[argv
.size() + 1]);
504 fd_shuffle1
.reserve(3);
505 fd_shuffle2
.reserve(3);
507 // Either |do_search_path| should be false or |envp| should be null, but not
509 DCHECK(!do_search_path
^ !envp
);
511 if (pipe(pipe_fd
) < 0)
512 return EXECUTE_FAILURE
;
514 switch (pid
= fork()) {
518 return EXECUTE_FAILURE
;
521 #if defined(OS_MACOSX)
522 RestoreDefaultExceptionHandler();
524 // DANGER: no calls to malloc are allowed from now on:
525 // http://crbug.com/36678
527 // Obscure fork() rule: in the child, if you don't end up doing exec*(),
528 // you call _exit() instead of exit(). This is because _exit() does not
529 // call any previously-registered (in the parent) exit handlers, which
530 // might do things like block waiting for threads that don't even exist
532 int dev_null
= open("/dev/null", O_WRONLY
);
536 // Stop type-profiler.
537 // The profiler should be stopped between fork and exec since it inserts
538 // locks at new/delete expressions. See http://crbug.com/36678.
539 base::type_profiler::Controller::Stop();
541 fd_shuffle1
.push_back(InjectionArc(pipe_fd
[1], STDOUT_FILENO
, true));
542 fd_shuffle1
.push_back(InjectionArc(dev_null
, STDERR_FILENO
, true));
543 fd_shuffle1
.push_back(InjectionArc(dev_null
, STDIN_FILENO
, true));
544 // Adding another element here? Remeber to increase the argument to
547 std::copy(fd_shuffle1
.begin(), fd_shuffle1
.end(),
548 std::back_inserter(fd_shuffle2
));
550 if (!ShuffleFileDescriptors(&fd_shuffle1
))
553 CloseSuperfluousFds(fd_shuffle2
);
555 for (size_t i
= 0; i
< argv
.size(); i
++)
556 argv_cstr
[i
] = const_cast<char*>(argv
[i
].c_str());
557 argv_cstr
[argv
.size()] = NULL
;
559 execvp(argv_cstr
[0], argv_cstr
.get());
561 execve(argv_cstr
[0], argv_cstr
.get(), envp
);
566 // Close our writing end of pipe now. Otherwise later read would not
567 // be able to detect end of child's output (in theory we could still
568 // write to the pipe).
573 size_t output_buf_left
= max_output
;
574 ssize_t bytes_read
= 1; // A lie to properly handle |max_output == 0|
575 // case in the logic below.
577 while (output_buf_left
> 0) {
578 bytes_read
= HANDLE_EINTR(read(pipe_fd
[0], buffer
,
579 std::min(output_buf_left
, sizeof(buffer
))));
582 output
->append(buffer
, bytes_read
);
583 output_buf_left
-= static_cast<size_t>(bytes_read
);
587 // Always wait for exit code (even if we know we'll declare
589 bool success
= WaitForExitCode(pid
, exit_code
);
591 // If we stopped because we read as much as we wanted, we return
592 // GOT_MAX_OUTPUT (because the child may exit due to |SIGPIPE|).
593 if (!output_buf_left
&& bytes_read
> 0)
594 return GOT_MAX_OUTPUT
;
596 return EXECUTE_SUCCESS
;
597 return EXECUTE_FAILURE
;
602 bool GetAppOutput(const CommandLine
& cl
, std::string
* output
) {
603 return GetAppOutput(cl
.argv(), output
);
606 bool GetAppOutput(const std::vector
<std::string
>& argv
, std::string
* output
) {
607 // Run |execve()| with the current environment and store "unlimited" data.
609 GetAppOutputInternalResult result
= GetAppOutputInternal(
610 argv
, NULL
, output
, std::numeric_limits
<std::size_t>::max(), true,
612 return result
== EXECUTE_SUCCESS
&& exit_code
== EXIT_SUCCESS
;
615 // TODO(viettrungluu): Conceivably, we should have a timeout as well, so we
616 // don't hang if what we're calling hangs.
617 bool GetAppOutputRestricted(const CommandLine
& cl
,
618 std::string
* output
, size_t max_output
) {
619 // Run |execve()| with the empty environment.
620 char* const empty_environ
= NULL
;
622 GetAppOutputInternalResult result
= GetAppOutputInternal(
623 cl
.argv(), &empty_environ
, output
, max_output
, false, &exit_code
);
624 return result
== GOT_MAX_OUTPUT
|| (result
== EXECUTE_SUCCESS
&&
625 exit_code
== EXIT_SUCCESS
);
628 bool GetAppOutputWithExitCode(const CommandLine
& cl
,
631 // Run |execve()| with the current environment and store "unlimited" data.
632 GetAppOutputInternalResult result
= GetAppOutputInternal(
633 cl
.argv(), NULL
, output
, std::numeric_limits
<std::size_t>::max(), true,
635 return result
== EXECUTE_SUCCESS
;