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.
10 #include <sys/resource.h>
12 #include <sys/types.h>
20 #include "base/allocator/type_profiler_control.h"
21 #include "base/command_line.h"
22 #include "base/compiler_specific.h"
23 #include "base/debug/debugger.h"
24 #include "base/debug/stack_trace.h"
25 #include "base/file_util.h"
26 #include "base/files/dir_reader_posix.h"
27 #include "base/logging.h"
28 #include "base/memory/scoped_ptr.h"
29 #include "base/posix/eintr_wrapper.h"
30 #include "base/process_util.h"
31 #include "base/stringprintf.h"
32 #include "base/synchronization/waitable_event.h"
33 #include "base/third_party/dynamic_annotations/dynamic_annotations.h"
34 #include "base/threading/platform_thread.h"
35 #include "base/threading/thread_restrictions.h"
37 #if defined(OS_CHROMEOS)
38 #include <sys/ioctl.h>
41 #if defined(OS_FREEBSD)
42 #include <sys/event.h>
43 #include <sys/ucontext.h>
46 #if defined(OS_MACOSX)
47 #include <crt_externs.h>
48 #include <sys/event.h>
50 extern char** environ
;
57 // Get the process's "environment" (i.e. the thing that setenv/getenv
59 char** GetEnvironment() {
60 #if defined(OS_MACOSX)
61 return *_NSGetEnviron();
67 // Set the process's "environment" (i.e. the thing that setenv/getenv
69 void SetEnvironment(char** env
) {
70 #if defined(OS_MACOSX)
71 *_NSGetEnviron() = env
;
77 int WaitpidWithTimeout(ProcessHandle handle
, int64 wait_milliseconds
,
79 // This POSIX version of this function only guarantees that we wait no less
80 // than |wait_milliseconds| for the process to exit. The child process may
81 // exit sometime before the timeout has ended but we may still block for up
82 // to 256 milliseconds after the fact.
84 // waitpid() has no direct support on POSIX for specifying a timeout, you can
85 // either ask it to block indefinitely or return immediately (WNOHANG).
86 // When a child process terminates a SIGCHLD signal is sent to the parent.
87 // Catching this signal would involve installing a signal handler which may
88 // affect other parts of the application and would be difficult to debug.
90 // Our strategy is to call waitpid() once up front to check if the process
91 // has already exited, otherwise to loop for wait_milliseconds, sleeping for
92 // at most 256 milliseconds each time using usleep() and then calling
93 // waitpid(). The amount of time we sleep starts out at 1 milliseconds, and
94 // we double it every 4 sleep cycles.
96 // usleep() is speced to exit if a signal is received for which a handler
97 // has been installed. This means that when a SIGCHLD is sent, it will exit
98 // depending on behavior external to this function.
100 // This function is used primarily for unit tests, if we want to use it in
101 // the application itself it would probably be best to examine other routes.
103 pid_t ret_pid
= HANDLE_EINTR(waitpid(handle
, &status
, WNOHANG
));
104 static const int64 kMaxSleepInMicroseconds
= 1 << 18; // ~256 milliseconds.
105 int64 max_sleep_time_usecs
= 1 << 10; // ~1 milliseconds.
106 int64 double_sleep_time
= 0;
108 // If the process hasn't exited yet, then sleep and try again.
109 Time wakeup_time
= Time::Now() +
110 TimeDelta::FromMilliseconds(wait_milliseconds
);
111 while (ret_pid
== 0) {
112 Time now
= Time::Now();
113 if (now
> wakeup_time
)
115 // Guaranteed to be non-negative!
116 int64 sleep_time_usecs
= (wakeup_time
- now
).InMicroseconds();
117 // Sleep for a bit while we wait for the process to finish.
118 if (sleep_time_usecs
> max_sleep_time_usecs
)
119 sleep_time_usecs
= max_sleep_time_usecs
;
121 // usleep() will return 0 and set errno to EINTR on receipt of a signal
123 usleep(sleep_time_usecs
);
124 ret_pid
= HANDLE_EINTR(waitpid(handle
, &status
, WNOHANG
));
126 if ((max_sleep_time_usecs
< kMaxSleepInMicroseconds
) &&
127 (double_sleep_time
++ % 4 == 0)) {
128 max_sleep_time_usecs
*= 2;
133 *success
= (ret_pid
!= -1);
138 void ResetChildSignalHandlersToDefaults() {
139 // The previous signal handlers are likely to be meaningless in the child's
140 // context so we reset them to the defaults for now. http://crbug.com/44953
141 // These signal handlers are set up at least in browser_main_posix.cc:
142 // BrowserMainPartsPosix::PreEarlyInitialization and stack_trace_posix.cc:
143 // EnableInProcessStackDumping.
144 signal(SIGHUP
, SIG_DFL
);
145 signal(SIGINT
, SIG_DFL
);
146 signal(SIGILL
, SIG_DFL
);
147 signal(SIGABRT
, SIG_DFL
);
148 signal(SIGFPE
, SIG_DFL
);
149 signal(SIGBUS
, SIG_DFL
);
150 signal(SIGSEGV
, SIG_DFL
);
151 signal(SIGSYS
, SIG_DFL
);
152 signal(SIGTERM
, SIG_DFL
);
155 TerminationStatus
GetTerminationStatusImpl(ProcessHandle handle
,
159 const pid_t result
= HANDLE_EINTR(waitpid(handle
, &status
,
160 can_block
? 0 : WNOHANG
));
162 DPLOG(ERROR
) << "waitpid(" << handle
<< ")";
165 return TERMINATION_STATUS_NORMAL_TERMINATION
;
166 } else if (result
== 0) {
167 // the child hasn't exited yet.
170 return TERMINATION_STATUS_STILL_RUNNING
;
176 if (WIFSIGNALED(status
)) {
177 switch (WTERMSIG(status
)) {
183 return TERMINATION_STATUS_PROCESS_CRASHED
;
187 return TERMINATION_STATUS_PROCESS_WAS_KILLED
;
193 if (WIFEXITED(status
) && WEXITSTATUS(status
) != 0)
194 return TERMINATION_STATUS_ABNORMAL_TERMINATION
;
196 return TERMINATION_STATUS_NORMAL_TERMINATION
;
199 } // anonymous namespace
201 ProcessId
GetCurrentProcId() {
205 ProcessHandle
GetCurrentProcessHandle() {
206 return GetCurrentProcId();
209 bool OpenProcessHandle(ProcessId pid
, ProcessHandle
* handle
) {
210 // On Posix platforms, process handles are the same as PIDs, so we
211 // don't need to do anything.
216 bool OpenPrivilegedProcessHandle(ProcessId pid
, ProcessHandle
* handle
) {
217 // On POSIX permissions are checked for each operation on process,
218 // not when opening a "handle".
219 return OpenProcessHandle(pid
, handle
);
222 bool OpenProcessHandleWithAccess(ProcessId pid
,
224 ProcessHandle
* handle
) {
225 // On POSIX permissions are checked for each operation on process,
226 // not when opening a "handle".
227 return OpenProcessHandle(pid
, handle
);
230 void CloseProcessHandle(ProcessHandle process
) {
231 // See OpenProcessHandle, nothing to do.
235 ProcessId
GetProcId(ProcessHandle process
) {
239 // Attempts to kill the process identified by the given process
240 // entry structure. Ignores specified exit_code; posix can't force that.
241 // Returns true if this is successful, false otherwise.
242 bool KillProcess(ProcessHandle process_id
, int exit_code
, bool wait
) {
243 DCHECK_GT(process_id
, 1) << " tried to kill invalid process_id";
246 bool result
= kill(process_id
, SIGTERM
) == 0;
247 if (result
&& wait
) {
250 if (RunningOnValgrind()) {
251 // Wait for some extra time when running under Valgrind since the child
252 // processes may take some time doing leak checking.
256 unsigned sleep_ms
= 4;
258 // The process may not end immediately due to pending I/O
260 while (tries
-- > 0) {
261 pid_t pid
= HANDLE_EINTR(waitpid(process_id
, NULL
, WNOHANG
));
262 if (pid
== process_id
) {
267 if (errno
== ECHILD
) {
268 // The wait may fail with ECHILD if another process also waited for
269 // the same pid, causing the process state to get cleaned up.
273 DPLOG(ERROR
) << "Error waiting for process " << process_id
;
276 usleep(sleep_ms
* 1000);
277 const unsigned kMaxSleepMs
= 1000;
278 if (sleep_ms
< kMaxSleepMs
)
282 // If we're waiting and the child hasn't died by now, force it
285 result
= kill(process_id
, SIGKILL
) == 0;
289 DPLOG(ERROR
) << "Unable to terminate process " << process_id
;
294 bool KillProcessGroup(ProcessHandle process_group_id
) {
295 bool result
= kill(-1 * process_group_id
, SIGKILL
) == 0;
297 DPLOG(ERROR
) << "Unable to terminate process group " << process_group_id
;
301 // A class to handle auto-closing of DIR*'s.
302 class ScopedDIRClose
{
304 inline void operator()(DIR* x
) const {
310 typedef scoped_ptr_malloc
<DIR, ScopedDIRClose
> ScopedDIR
;
312 #if defined(OS_LINUX)
313 static const rlim_t kSystemDefaultMaxFds
= 8192;
314 static const char kFDDir
[] = "/proc/self/fd";
315 #elif defined(OS_MACOSX)
316 static const rlim_t kSystemDefaultMaxFds
= 256;
317 static const char kFDDir
[] = "/dev/fd";
318 #elif defined(OS_SOLARIS)
319 static const rlim_t kSystemDefaultMaxFds
= 8192;
320 static const char kFDDir
[] = "/dev/fd";
321 #elif defined(OS_FREEBSD)
322 static const rlim_t kSystemDefaultMaxFds
= 8192;
323 static const char kFDDir
[] = "/dev/fd";
324 #elif defined(OS_OPENBSD)
325 static const rlim_t kSystemDefaultMaxFds
= 256;
326 static const char kFDDir
[] = "/dev/fd";
327 #elif defined(OS_ANDROID)
328 static const rlim_t kSystemDefaultMaxFds
= 1024;
329 static const char kFDDir
[] = "/proc/self/fd";
332 void CloseSuperfluousFds(const base::InjectiveMultimap
& saved_mapping
) {
333 // DANGER: no calls to malloc are allowed from now on:
334 // http://crbug.com/36678
336 // Get the maximum number of FDs possible.
337 struct rlimit nofile
;
339 if (getrlimit(RLIMIT_NOFILE
, &nofile
)) {
340 // getrlimit failed. Take a best guess.
341 max_fds
= kSystemDefaultMaxFds
;
342 RAW_LOG(ERROR
, "getrlimit(RLIMIT_NOFILE) failed");
344 max_fds
= nofile
.rlim_cur
;
347 if (max_fds
> INT_MAX
)
350 DirReaderPosix
fd_dir(kFDDir
);
352 if (!fd_dir
.IsValid()) {
353 // Fallback case: Try every possible fd.
354 for (rlim_t i
= 0; i
< max_fds
; ++i
) {
355 const int fd
= static_cast<int>(i
);
356 if (fd
== STDIN_FILENO
|| fd
== STDOUT_FILENO
|| fd
== STDERR_FILENO
)
358 InjectiveMultimap::const_iterator j
;
359 for (j
= saved_mapping
.begin(); j
!= saved_mapping
.end(); j
++) {
363 if (j
!= saved_mapping
.end())
366 // Since we're just trying to close anything we can find,
367 // ignore any error return values of close().
368 ignore_result(HANDLE_EINTR(close(fd
)));
373 const int dir_fd
= fd_dir
.fd();
375 for ( ; fd_dir
.Next(); ) {
376 // Skip . and .. entries.
377 if (fd_dir
.name()[0] == '.')
382 const long int fd
= strtol(fd_dir
.name(), &endptr
, 10);
383 if (fd_dir
.name()[0] == 0 || *endptr
|| fd
< 0 || errno
)
385 if (fd
== STDIN_FILENO
|| fd
== STDOUT_FILENO
|| fd
== STDERR_FILENO
)
387 InjectiveMultimap::const_iterator i
;
388 for (i
= saved_mapping
.begin(); i
!= saved_mapping
.end(); i
++) {
392 if (i
!= saved_mapping
.end())
397 // When running under Valgrind, Valgrind opens several FDs for its
398 // own use and will complain if we try to close them. All of
399 // these FDs are >= |max_fds|, so we can check against that here
400 // before closing. See https://bugs.kde.org/show_bug.cgi?id=191758
401 if (fd
< static_cast<int>(max_fds
)) {
402 int ret
= HANDLE_EINTR(close(fd
));
408 char** AlterEnvironment(const EnvironmentVector
& changes
,
409 const char* const* const env
) {
413 // First assume that all of the current environment will be included.
414 for (unsigned i
= 0; env
[i
]; i
++) {
415 const char *const pair
= env
[i
];
417 size
+= strlen(pair
) + 1 /* terminating NUL */;
420 for (EnvironmentVector::const_iterator j
= changes
.begin();
426 for (unsigned i
= 0; env
[i
]; i
++) {
428 const char *const equals
= strchr(pair
, '=');
431 const unsigned keylen
= equals
- pair
;
432 if (keylen
== j
->first
.size() &&
433 memcmp(pair
, j
->first
.data(), keylen
) == 0) {
439 // if found, we'll either be deleting or replacing this element.
442 size
-= strlen(pair
) + 1;
443 if (j
->second
.size())
447 // if !found, then we have a new element to add.
448 if (!found
&& !j
->second
.empty()) {
450 size
+= j
->first
.size() + 1 /* '=' */ + j
->second
.size() + 1 /* NUL */;
454 count
++; // for the final NULL
455 uint8_t *buffer
= new uint8_t[sizeof(char*) * count
+ size
];
456 char **const ret
= reinterpret_cast<char**>(buffer
);
458 char *scratch
= reinterpret_cast<char*>(buffer
+ sizeof(char*) * count
);
460 for (unsigned i
= 0; env
[i
]; i
++) {
461 const char *const pair
= env
[i
];
462 const char *const equals
= strchr(pair
, '=');
464 const unsigned len
= strlen(pair
);
466 memcpy(scratch
, pair
, len
+ 1);
470 const unsigned keylen
= equals
- pair
;
471 bool handled
= false;
472 for (EnvironmentVector::const_iterator
473 j
= changes
.begin(); j
!= changes
.end(); j
++) {
474 if (j
->first
.size() == keylen
&&
475 memcmp(j
->first
.data(), pair
, keylen
) == 0) {
476 if (!j
->second
.empty()) {
478 memcpy(scratch
, pair
, keylen
+ 1);
479 scratch
+= keylen
+ 1;
480 memcpy(scratch
, j
->second
.c_str(), j
->second
.size() + 1);
481 scratch
+= j
->second
.size() + 1;
489 const unsigned len
= strlen(pair
);
491 memcpy(scratch
, pair
, len
+ 1);
496 // Now handle new elements
497 for (EnvironmentVector::const_iterator
498 j
= changes
.begin(); j
!= changes
.end(); j
++) {
499 if (j
->second
.empty())
503 for (unsigned i
= 0; env
[i
]; i
++) {
504 const char *const pair
= env
[i
];
505 const char *const equals
= strchr(pair
, '=');
508 const unsigned keylen
= equals
- pair
;
509 if (keylen
== j
->first
.size() &&
510 memcmp(pair
, j
->first
.data(), keylen
) == 0) {
518 memcpy(scratch
, j
->first
.data(), j
->first
.size());
519 scratch
+= j
->first
.size();
521 memcpy(scratch
, j
->second
.c_str(), j
->second
.size() + 1);
522 scratch
+= j
->second
.size() + 1;
530 bool LaunchProcess(const std::vector
<std::string
>& argv
,
531 const LaunchOptions
& options
,
532 ProcessHandle
* process_handle
) {
533 size_t fd_shuffle_size
= 0;
534 if (options
.fds_to_remap
) {
535 fd_shuffle_size
= options
.fds_to_remap
->size();
538 #if defined(OS_MACOSX)
539 if (options
.synchronize
) {
540 // When synchronizing, the "read" end of the synchronization pipe needs
541 // to make it to the child process. This is handled by mapping it back to
545 #endif // defined(OS_MACOSX)
547 InjectiveMultimap fd_shuffle1
;
548 InjectiveMultimap fd_shuffle2
;
549 fd_shuffle1
.reserve(fd_shuffle_size
);
550 fd_shuffle2
.reserve(fd_shuffle_size
);
552 scoped_array
<char*> argv_cstr(new char*[argv
.size() + 1]);
553 scoped_array
<char*> new_environ
;
555 new_environ
.reset(AlterEnvironment(*options
.environ
, GetEnvironment()));
557 #if defined(OS_MACOSX)
558 int synchronization_pipe_fds
[2];
559 file_util::ScopedFD synchronization_read_fd
;
560 file_util::ScopedFD synchronization_write_fd
;
562 if (options
.synchronize
) {
563 // wait means "don't return from LaunchProcess until the child exits", and
564 // synchronize means "return from LaunchProcess but don't let the child
565 // run until LaunchSynchronize is called". These two options are highly
567 DCHECK(!options
.wait
);
569 // Create the pipe used for synchronization.
570 if (HANDLE_EINTR(pipe(synchronization_pipe_fds
)) != 0) {
571 DPLOG(ERROR
) << "pipe";
575 // The parent process will only use synchronization_write_fd as the write
576 // side of the pipe. It can close the read side as soon as the child
577 // process has forked off. The child process will only use
578 // synchronization_read_fd as the read side of the pipe. In that process,
579 // the write side can be closed as soon as it has forked.
580 synchronization_read_fd
.reset(&synchronization_pipe_fds
[0]);
581 synchronization_write_fd
.reset(&synchronization_pipe_fds
[1]);
586 #if defined(OS_LINUX)
587 if (options
.clone_flags
) {
588 pid
= syscall(__NR_clone
, options
.clone_flags
, 0, 0, 0);
596 DPLOG(ERROR
) << "fork";
598 } else if (pid
== 0) {
601 // DANGER: fork() rule: in the child, if you don't end up doing exec*(),
602 // you call _exit() instead of exit(). This is because _exit() does not
603 // call any previously-registered (in the parent) exit handlers, which
604 // might do things like block waiting for threads that don't even exist
607 // If a child process uses the readline library, the process block forever.
608 // In BSD like OSes including OS X it is safe to assign /dev/null as stdin.
609 // See http://crbug.com/56596.
610 int null_fd
= HANDLE_EINTR(open("/dev/null", O_RDONLY
));
612 RAW_LOG(ERROR
, "Failed to open /dev/null");
616 file_util::ScopedFD
null_fd_closer(&null_fd
);
617 int new_fd
= HANDLE_EINTR(dup2(null_fd
, STDIN_FILENO
));
618 if (new_fd
!= STDIN_FILENO
) {
619 RAW_LOG(ERROR
, "Failed to dup /dev/null for stdin");
623 if (options
.new_process_group
) {
624 // Instead of inheriting the process group ID of the parent, the child
625 // starts off a new process group with pgid equal to its process ID.
626 if (setpgid(0, 0) < 0) {
627 RAW_LOG(ERROR
, "setpgid failed");
632 // Stop type-profiler.
633 // The profiler should be stopped between fork and exec since it inserts
634 // locks at new/delete expressions. See http://crbug.com/36678.
635 base::type_profiler::Controller::Stop();
637 if (options
.maximize_rlimits
) {
638 // Some resource limits need to be maximal in this child.
639 std::set
<int>::const_iterator resource
;
640 for (resource
= options
.maximize_rlimits
->begin();
641 resource
!= options
.maximize_rlimits
->end();
644 if (getrlimit(*resource
, &limit
) < 0) {
645 RAW_LOG(WARNING
, "getrlimit failed");
646 } else if (limit
.rlim_cur
< limit
.rlim_max
) {
647 limit
.rlim_cur
= limit
.rlim_max
;
648 if (setrlimit(*resource
, &limit
) < 0) {
649 RAW_LOG(WARNING
, "setrlimit failed");
655 #if defined(OS_MACOSX)
656 RestoreDefaultExceptionHandler();
657 #endif // defined(OS_MACOSX)
659 ResetChildSignalHandlersToDefaults();
661 #if defined(OS_MACOSX)
662 if (options
.synchronize
) {
663 // The "write" side of the synchronization pipe belongs to the parent.
664 synchronization_write_fd
.reset(); // closes synchronization_pipe_fds[1]
666 #endif // defined(OS_MACOSX)
669 // When debugging it can be helpful to check that we really aren't making
670 // any hidden calls to malloc.
672 reinterpret_cast<void*>(reinterpret_cast<intptr_t>(malloc
) & ~4095);
673 mprotect(malloc_thunk
, 4096, PROT_READ
| PROT_WRITE
| PROT_EXEC
);
674 memset(reinterpret_cast<void*>(malloc
), 0xff, 8);
677 // DANGER: no calls to malloc are allowed from now on:
678 // http://crbug.com/36678
680 #if defined(OS_CHROMEOS)
681 if (options
.ctrl_terminal_fd
>= 0) {
682 // Set process' controlling terminal.
683 if (HANDLE_EINTR(setsid()) != -1) {
685 ioctl(options
.ctrl_terminal_fd
, TIOCSCTTY
, NULL
)) == -1) {
686 RAW_LOG(WARNING
, "ioctl(TIOCSCTTY), ctrl terminal not set");
689 RAW_LOG(WARNING
, "setsid failed, ctrl terminal not set");
692 #endif // defined(OS_CHROMEOS)
694 if (options
.fds_to_remap
) {
695 for (FileHandleMappingVector::const_iterator
696 it
= options
.fds_to_remap
->begin();
697 it
!= options
.fds_to_remap
->end(); ++it
) {
698 fd_shuffle1
.push_back(InjectionArc(it
->first
, it
->second
, false));
699 fd_shuffle2
.push_back(InjectionArc(it
->first
, it
->second
, false));
703 #if defined(OS_MACOSX)
704 if (options
.synchronize
) {
705 // Remap the read side of the synchronization pipe back onto itself,
706 // ensuring that it won't be closed by CloseSuperfluousFds.
707 int keep_fd
= *synchronization_read_fd
.get();
708 fd_shuffle1
.push_back(InjectionArc(keep_fd
, keep_fd
, false));
709 fd_shuffle2
.push_back(InjectionArc(keep_fd
, keep_fd
, false));
711 #endif // defined(OS_MACOSX)
714 SetEnvironment(new_environ
.get());
716 // fd_shuffle1 is mutated by this call because it cannot malloc.
717 if (!ShuffleFileDescriptors(&fd_shuffle1
))
720 CloseSuperfluousFds(fd_shuffle2
);
722 #if defined(OS_MACOSX)
723 if (options
.synchronize
) {
724 // Do a blocking read to wait until the parent says it's OK to proceed.
725 // The byte that's read here is written by LaunchSynchronize.
728 HANDLE_EINTR(read(*synchronization_read_fd
.get(), &read_char
, 1));
729 if (read_result
!= 1) {
730 RAW_LOG(ERROR
, "LaunchProcess: synchronization read: error");
734 // The pipe is no longer useful. Don't let it live on in the new process
736 synchronization_read_fd
.reset(); // closes synchronization_pipe_fds[0]
738 #endif // defined(OS_MACOSX)
740 for (size_t i
= 0; i
< argv
.size(); i
++)
741 argv_cstr
[i
] = const_cast<char*>(argv
[i
].c_str());
742 argv_cstr
[argv
.size()] = NULL
;
743 execvp(argv_cstr
[0], argv_cstr
.get());
745 RAW_LOG(ERROR
, "LaunchProcess: failed to execvp:");
746 RAW_LOG(ERROR
, argv_cstr
[0]);
751 // While this isn't strictly disk IO, waiting for another process to
752 // finish is the sort of thing ThreadRestrictions is trying to prevent.
753 base::ThreadRestrictions::AssertIOAllowed();
754 pid_t ret
= HANDLE_EINTR(waitpid(pid
, 0, 0));
759 *process_handle
= pid
;
761 #if defined(OS_MACOSX)
762 if (options
.synchronize
) {
763 // The "read" side of the synchronization pipe belongs to the child.
764 synchronization_read_fd
.reset(); // closes synchronization_pipe_fds[0]
765 *options
.synchronize
= new int(*synchronization_write_fd
.release());
767 #endif // defined(OS_MACOSX)
774 bool LaunchProcess(const CommandLine
& cmdline
,
775 const LaunchOptions
& options
,
776 ProcessHandle
* process_handle
) {
777 return LaunchProcess(cmdline
.argv(), options
, process_handle
);
780 #if defined(OS_MACOSX)
781 void LaunchSynchronize(LaunchSynchronizationHandle handle
) {
782 int synchronization_fd
= *handle
;
783 file_util::ScopedFD
synchronization_fd_closer(&synchronization_fd
);
786 // Write a '\0' character to the pipe.
787 if (HANDLE_EINTR(write(synchronization_fd
, "", 1)) != 1) {
788 DPLOG(ERROR
) << "write";
791 #endif // defined(OS_MACOSX)
793 ProcessMetrics::~ProcessMetrics() { }
795 void RaiseProcessToHighPriority() {
796 // On POSIX, we don't actually do anything here. We could try to nice() or
797 // setpriority() or sched_getscheduler, but these all require extra rights.
800 TerminationStatus
GetTerminationStatus(ProcessHandle handle
, int* exit_code
) {
801 return GetTerminationStatusImpl(handle
, false /* can_block */, exit_code
);
804 TerminationStatus
WaitForTerminationStatus(ProcessHandle handle
,
806 return GetTerminationStatusImpl(handle
, true /* can_block */, exit_code
);
809 bool WaitForExitCode(ProcessHandle handle
, int* exit_code
) {
811 if (HANDLE_EINTR(waitpid(handle
, &status
, 0)) == -1) {
816 if (WIFEXITED(status
)) {
817 *exit_code
= WEXITSTATUS(status
);
821 // If it didn't exit cleanly, it must have been signaled.
822 DCHECK(WIFSIGNALED(status
));
826 bool WaitForExitCodeWithTimeout(ProcessHandle handle
, int* exit_code
,
827 base::TimeDelta timeout
) {
828 bool waitpid_success
= false;
829 int status
= WaitpidWithTimeout(handle
, timeout
.InMilliseconds(),
833 if (!waitpid_success
)
835 if (WIFSIGNALED(status
)) {
839 if (WIFEXITED(status
)) {
840 *exit_code
= WEXITSTATUS(status
);
846 #if defined(OS_MACOSX)
847 // Using kqueue on Mac so that we can wait on non-child processes.
848 // We can't use kqueues on child processes because we need to reap
849 // our own children using wait.
850 static bool WaitForSingleNonChildProcess(ProcessHandle handle
,
851 base::TimeDelta wait
) {
852 DCHECK_GT(handle
, 0);
853 DCHECK(wait
.InMilliseconds() == base::kNoTimeout
|| wait
> base::TimeDelta());
857 DPLOG(ERROR
) << "kqueue";
860 file_util::ScopedFD
kq_closer(&kq
);
862 struct kevent change
= {0};
863 EV_SET(&change
, handle
, EVFILT_PROC
, EV_ADD
, NOTE_EXIT
, 0, NULL
);
864 int result
= HANDLE_EINTR(kevent(kq
, &change
, 1, NULL
, 0, NULL
));
866 if (errno
== ESRCH
) {
867 // If the process wasn't found, it must be dead.
871 DPLOG(ERROR
) << "kevent (setup " << handle
<< ")";
875 // Keep track of the elapsed time to be able to restart kevent if it's
877 bool wait_forever
= wait
.InMilliseconds() == base::kNoTimeout
;
878 base::TimeDelta remaining_delta
;
881 remaining_delta
= wait
;
882 deadline
= base::Time::Now() + remaining_delta
;
886 struct kevent event
= {0};
888 while (wait_forever
|| remaining_delta
> base::TimeDelta()) {
889 struct timespec remaining_timespec
;
890 struct timespec
* remaining_timespec_ptr
;
892 remaining_timespec_ptr
= NULL
;
894 remaining_timespec
= remaining_delta
.ToTimeSpec();
895 remaining_timespec_ptr
= &remaining_timespec
;
898 result
= kevent(kq
, NULL
, 0, &event
, 1, remaining_timespec_ptr
);
900 if (result
== -1 && errno
== EINTR
) {
902 remaining_delta
= deadline
- base::Time::Now();
911 DPLOG(ERROR
) << "kevent (wait " << handle
<< ")";
913 } else if (result
> 1) {
914 DLOG(ERROR
) << "kevent (wait " << handle
<< "): unexpected result "
917 } else if (result
== 0) {
922 DCHECK_EQ(result
, 1);
924 if (event
.filter
!= EVFILT_PROC
||
925 (event
.fflags
& NOTE_EXIT
) == 0 ||
926 event
.ident
!= static_cast<uintptr_t>(handle
)) {
927 DLOG(ERROR
) << "kevent (wait " << handle
928 << "): unexpected event: filter=" << event
.filter
929 << ", fflags=" << event
.fflags
930 << ", ident=" << event
.ident
;
938 bool WaitForSingleProcess(ProcessHandle handle
, base::TimeDelta wait
) {
939 ProcessHandle parent_pid
= GetParentProcessId(handle
);
940 ProcessHandle our_pid
= Process::Current().handle();
941 if (parent_pid
!= our_pid
) {
942 #if defined(OS_MACOSX)
943 // On Mac we can wait on non child processes.
944 return WaitForSingleNonChildProcess(handle
, wait
);
946 // Currently on Linux we can't handle non child processes.
951 bool waitpid_success
;
953 if (wait
.InMilliseconds() == base::kNoTimeout
) {
954 waitpid_success
= (HANDLE_EINTR(waitpid(handle
, &status
, 0)) != -1);
956 status
= WaitpidWithTimeout(
957 handle
, wait
.InMilliseconds(), &waitpid_success
);
961 DCHECK(waitpid_success
);
962 return WIFEXITED(status
);
968 int64
TimeValToMicroseconds(const struct timeval
& tv
) {
969 static const int kMicrosecondsPerSecond
= 1000000;
970 int64 ret
= tv
.tv_sec
; // Avoid (int * int) integer overflow.
971 ret
*= kMicrosecondsPerSecond
;
976 // Return value used by GetAppOutputInternal to encapsulate the various exit
977 // scenarios from the function.
978 enum GetAppOutputInternalResult
{
984 // Executes the application specified by |argv| and wait for it to exit. Stores
985 // the output (stdout) in |output|. If |do_search_path| is set, it searches the
986 // path for the application; in that case, |envp| must be null, and it will use
987 // the current environment. If |do_search_path| is false, |argv[0]| should fully
988 // specify the path of the application, and |envp| will be used as the
989 // environment. Redirects stderr to /dev/null.
990 // If we successfully start the application and get all requested output, we
991 // return GOT_MAX_OUTPUT, or if there is a problem starting or exiting
992 // the application we return RUN_FAILURE. Otherwise we return EXECUTE_SUCCESS.
993 // The GOT_MAX_OUTPUT return value exists so a caller that asks for limited
994 // output can treat this as a success, despite having an exit code of SIG_PIPE
995 // due to us closing the output pipe.
996 // In the case of EXECUTE_SUCCESS, the application exit code will be returned
997 // in |*exit_code|, which should be checked to determine if the application
999 static GetAppOutputInternalResult
GetAppOutputInternal(
1000 const std::vector
<std::string
>& argv
,
1002 std::string
* output
,
1004 bool do_search_path
,
1006 // Doing a blocking wait for another command to finish counts as IO.
1007 base::ThreadRestrictions::AssertIOAllowed();
1008 // exit_code must be supplied so calling function can determine success.
1010 *exit_code
= EXIT_FAILURE
;
1014 InjectiveMultimap fd_shuffle1
, fd_shuffle2
;
1015 scoped_array
<char*> argv_cstr(new char*[argv
.size() + 1]);
1017 fd_shuffle1
.reserve(3);
1018 fd_shuffle2
.reserve(3);
1020 // Either |do_search_path| should be false or |envp| should be null, but not
1022 DCHECK(!do_search_path
^ !envp
);
1024 if (pipe(pipe_fd
) < 0)
1025 return EXECUTE_FAILURE
;
1027 switch (pid
= fork()) {
1031 return EXECUTE_FAILURE
;
1034 #if defined(OS_MACOSX)
1035 RestoreDefaultExceptionHandler();
1037 // DANGER: no calls to malloc are allowed from now on:
1038 // http://crbug.com/36678
1040 // Obscure fork() rule: in the child, if you don't end up doing exec*(),
1041 // you call _exit() instead of exit(). This is because _exit() does not
1042 // call any previously-registered (in the parent) exit handlers, which
1043 // might do things like block waiting for threads that don't even exist
1045 int dev_null
= open("/dev/null", O_WRONLY
);
1049 // Stop type-profiler.
1050 // The profiler should be stopped between fork and exec since it inserts
1051 // locks at new/delete expressions. See http://crbug.com/36678.
1052 base::type_profiler::Controller::Stop();
1054 fd_shuffle1
.push_back(InjectionArc(pipe_fd
[1], STDOUT_FILENO
, true));
1055 fd_shuffle1
.push_back(InjectionArc(dev_null
, STDERR_FILENO
, true));
1056 fd_shuffle1
.push_back(InjectionArc(dev_null
, STDIN_FILENO
, true));
1057 // Adding another element here? Remeber to increase the argument to
1058 // reserve(), above.
1060 std::copy(fd_shuffle1
.begin(), fd_shuffle1
.end(),
1061 std::back_inserter(fd_shuffle2
));
1063 if (!ShuffleFileDescriptors(&fd_shuffle1
))
1066 CloseSuperfluousFds(fd_shuffle2
);
1068 for (size_t i
= 0; i
< argv
.size(); i
++)
1069 argv_cstr
[i
] = const_cast<char*>(argv
[i
].c_str());
1070 argv_cstr
[argv
.size()] = NULL
;
1072 execvp(argv_cstr
[0], argv_cstr
.get());
1074 execve(argv_cstr
[0], argv_cstr
.get(), envp
);
1079 // Close our writing end of pipe now. Otherwise later read would not
1080 // be able to detect end of child's output (in theory we could still
1081 // write to the pipe).
1086 size_t output_buf_left
= max_output
;
1087 ssize_t bytes_read
= 1; // A lie to properly handle |max_output == 0|
1088 // case in the logic below.
1090 while (output_buf_left
> 0) {
1091 bytes_read
= HANDLE_EINTR(read(pipe_fd
[0], buffer
,
1092 std::min(output_buf_left
, sizeof(buffer
))));
1093 if (bytes_read
<= 0)
1095 output
->append(buffer
, bytes_read
);
1096 output_buf_left
-= static_cast<size_t>(bytes_read
);
1100 // Always wait for exit code (even if we know we'll declare
1102 bool success
= WaitForExitCode(pid
, exit_code
);
1104 // If we stopped because we read as much as we wanted, we return
1105 // GOT_MAX_OUTPUT (because the child may exit due to |SIGPIPE|).
1106 if (!output_buf_left
&& bytes_read
> 0)
1107 return GOT_MAX_OUTPUT
;
1109 return EXECUTE_SUCCESS
;
1110 return EXECUTE_FAILURE
;
1115 bool GetAppOutput(const CommandLine
& cl
, std::string
* output
) {
1116 return GetAppOutput(cl
.argv(), output
);
1119 bool GetAppOutput(const std::vector
<std::string
>& argv
, std::string
* output
) {
1120 // Run |execve()| with the current environment and store "unlimited" data.
1122 GetAppOutputInternalResult result
= GetAppOutputInternal(
1123 argv
, NULL
, output
, std::numeric_limits
<std::size_t>::max(), true,
1125 return result
== EXECUTE_SUCCESS
&& exit_code
== EXIT_SUCCESS
;
1128 // TODO(viettrungluu): Conceivably, we should have a timeout as well, so we
1129 // don't hang if what we're calling hangs.
1130 bool GetAppOutputRestricted(const CommandLine
& cl
,
1131 std::string
* output
, size_t max_output
) {
1132 // Run |execve()| with the empty environment.
1133 char* const empty_environ
= NULL
;
1135 GetAppOutputInternalResult result
= GetAppOutputInternal(
1136 cl
.argv(), &empty_environ
, output
, max_output
, false, &exit_code
);
1137 return result
== GOT_MAX_OUTPUT
|| (result
== EXECUTE_SUCCESS
&&
1138 exit_code
== EXIT_SUCCESS
);
1141 bool GetAppOutputWithExitCode(const CommandLine
& cl
,
1142 std::string
* output
,
1144 // Run |execve()| with the current environment and store "unlimited" data.
1145 GetAppOutputInternalResult result
= GetAppOutputInternal(
1146 cl
.argv(), NULL
, output
, std::numeric_limits
<std::size_t>::max(), true,
1148 return result
== EXECUTE_SUCCESS
;
1151 bool WaitForProcessesToExit(const FilePath::StringType
& executable_name
,
1152 base::TimeDelta wait
,
1153 const ProcessFilter
* filter
) {
1154 bool result
= false;
1156 // TODO(port): This is inefficient, but works if there are multiple procs.
1157 // TODO(port): use waitpid to avoid leaving zombies around
1159 base::Time end_time
= base::Time::Now() + wait
;
1161 NamedProcessIterator
iter(executable_name
, filter
);
1162 if (!iter
.NextProcessEntry()) {
1166 base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(100));
1167 } while ((end_time
- base::Time::Now()) > base::TimeDelta());
1172 bool CleanupProcesses(const FilePath::StringType
& executable_name
,
1173 base::TimeDelta wait
,
1175 const ProcessFilter
* filter
) {
1176 bool exited_cleanly
= WaitForProcessesToExit(executable_name
, wait
, filter
);
1177 if (!exited_cleanly
)
1178 KillProcesses(executable_name
, exit_code
, filter
);
1179 return exited_cleanly
;
1182 #if !defined(OS_MACOSX)
1186 // Return true if the given child is dead. This will also reap the process.
1188 static bool IsChildDead(pid_t child
) {
1189 const pid_t result
= HANDLE_EINTR(waitpid(child
, NULL
, WNOHANG
));
1191 DPLOG(ERROR
) << "waitpid(" << child
<< ")";
1193 } else if (result
> 0) {
1194 // The child has died.
1201 // A thread class which waits for the given child to exit and reaps it.
1202 // If the child doesn't exit within a couple of seconds, kill it.
1203 class BackgroundReaper
: public PlatformThread::Delegate
{
1205 BackgroundReaper(pid_t child
, unsigned timeout
)
1210 // Overridden from PlatformThread::Delegate:
1211 virtual void ThreadMain() OVERRIDE
{
1212 WaitForChildToDie();
1216 void WaitForChildToDie() {
1217 // Wait forever case.
1218 if (timeout_
== 0) {
1219 pid_t r
= HANDLE_EINTR(waitpid(child_
, NULL
, 0));
1221 DPLOG(ERROR
) << "While waiting for " << child_
1222 << " to terminate, we got the following result: " << r
;
1227 // There's no good way to wait for a specific child to exit in a timed
1228 // fashion. (No kqueue on Linux), so we just loop and sleep.
1230 // Wait for 2 * timeout_ 500 milliseconds intervals.
1231 for (unsigned i
= 0; i
< 2 * timeout_
; ++i
) {
1232 PlatformThread::Sleep(TimeDelta::FromMilliseconds(500));
1233 if (IsChildDead(child_
))
1237 if (kill(child_
, SIGKILL
) == 0) {
1238 // SIGKILL is uncatchable. Since the signal was delivered, we can
1239 // just wait for the process to die now in a blocking manner.
1240 if (HANDLE_EINTR(waitpid(child_
, NULL
, 0)) < 0)
1241 DPLOG(WARNING
) << "waitpid";
1243 DLOG(ERROR
) << "While waiting for " << child_
<< " to terminate we"
1244 << " failed to deliver a SIGKILL signal (" << errno
<< ").";
1250 // Number of seconds to wait, if 0 then wait forever and do not attempt to
1252 const unsigned timeout_
;
1254 DISALLOW_COPY_AND_ASSIGN(BackgroundReaper
);
1259 void EnsureProcessTerminated(ProcessHandle process
) {
1260 // If the child is already dead, then there's nothing to do.
1261 if (IsChildDead(process
))
1264 const unsigned timeout
= 2; // seconds
1265 BackgroundReaper
* reaper
= new BackgroundReaper(process
, timeout
);
1266 PlatformThread::CreateNonJoinable(0, reaper
);
1269 void EnsureProcessGetsReaped(ProcessHandle process
) {
1270 // If the child is already dead, then there's nothing to do.
1271 if (IsChildDead(process
))
1274 BackgroundReaper
* reaper
= new BackgroundReaper(process
, 0);
1275 PlatformThread::CreateNonJoinable(0, reaper
);
1278 #endif // !defined(OS_MACOSX)