WebKit roll 98705:98715
[chromium-blink-merge.git] / base / process_util_posix.cc
blob055edcc11a45b3103fb931ebb4145ed5699c7038
1 // Copyright (c) 2011 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 <dirent.h>
6 #include <errno.h>
7 #include <fcntl.h>
8 #include <signal.h>
9 #include <stdlib.h>
10 #include <sys/resource.h>
11 #include <sys/time.h>
12 #include <sys/types.h>
13 #include <sys/wait.h>
14 #include <unistd.h>
16 #include <limits>
17 #include <set>
19 #include "base/command_line.h"
20 #include "base/compiler_specific.h"
21 #include "base/debug/debugger.h"
22 #include "base/debug/stack_trace.h"
23 #include "base/dir_reader_posix.h"
24 #include "base/eintr_wrapper.h"
25 #include "base/file_util.h"
26 #include "base/logging.h"
27 #include "base/memory/scoped_ptr.h"
28 #include "base/process_util.h"
29 #include "base/stringprintf.h"
30 #include "base/synchronization/waitable_event.h"
31 #include "base/third_party/dynamic_annotations/dynamic_annotations.h"
32 #include "base/threading/platform_thread.h"
33 #include "base/threading/thread_restrictions.h"
34 #include "base/time.h"
36 #if defined(OS_MACOSX)
37 #include <crt_externs.h>
38 #include <sys/event.h>
39 #else
40 extern char** environ;
41 #endif
43 namespace base {
45 namespace {
47 // Get the process's "environment" (i.e. the thing that setenv/getenv
48 // work with).
49 char** GetEnvironment() {
50 #if defined(OS_MACOSX)
51 return *_NSGetEnviron();
52 #else
53 return environ;
54 #endif
57 // Set the process's "environment" (i.e. the thing that setenv/getenv
58 // work with).
59 void SetEnvironment(char** env) {
60 #if defined(OS_MACOSX)
61 *_NSGetEnviron() = env;
62 #else
63 environ = env;
64 #endif
67 int WaitpidWithTimeout(ProcessHandle handle, int64 wait_milliseconds,
68 bool* success) {
69 // This POSIX version of this function only guarantees that we wait no less
70 // than |wait_milliseconds| for the process to exit. The child process may
71 // exit sometime before the timeout has ended but we may still block for up
72 // to 256 milliseconds after the fact.
74 // waitpid() has no direct support on POSIX for specifying a timeout, you can
75 // either ask it to block indefinitely or return immediately (WNOHANG).
76 // When a child process terminates a SIGCHLD signal is sent to the parent.
77 // Catching this signal would involve installing a signal handler which may
78 // affect other parts of the application and would be difficult to debug.
80 // Our strategy is to call waitpid() once up front to check if the process
81 // has already exited, otherwise to loop for wait_milliseconds, sleeping for
82 // at most 256 milliseconds each time using usleep() and then calling
83 // waitpid(). The amount of time we sleep starts out at 1 milliseconds, and
84 // we double it every 4 sleep cycles.
86 // usleep() is speced to exit if a signal is received for which a handler
87 // has been installed. This means that when a SIGCHLD is sent, it will exit
88 // depending on behavior external to this function.
90 // This function is used primarily for unit tests, if we want to use it in
91 // the application itself it would probably be best to examine other routes.
92 int status = -1;
93 pid_t ret_pid = HANDLE_EINTR(waitpid(handle, &status, WNOHANG));
94 static const int64 kMaxSleepInMicroseconds = 1 << 18; // ~256 milliseconds.
95 int64 max_sleep_time_usecs = 1 << 10; // ~1 milliseconds.
96 int64 double_sleep_time = 0;
98 // If the process hasn't exited yet, then sleep and try again.
99 Time wakeup_time = Time::Now() +
100 TimeDelta::FromMilliseconds(wait_milliseconds);
101 while (ret_pid == 0) {
102 Time now = Time::Now();
103 if (now > wakeup_time)
104 break;
105 // Guaranteed to be non-negative!
106 int64 sleep_time_usecs = (wakeup_time - now).InMicroseconds();
107 // Sleep for a bit while we wait for the process to finish.
108 if (sleep_time_usecs > max_sleep_time_usecs)
109 sleep_time_usecs = max_sleep_time_usecs;
111 // usleep() will return 0 and set errno to EINTR on receipt of a signal
112 // such as SIGCHLD.
113 usleep(sleep_time_usecs);
114 ret_pid = HANDLE_EINTR(waitpid(handle, &status, WNOHANG));
116 if ((max_sleep_time_usecs < kMaxSleepInMicroseconds) &&
117 (double_sleep_time++ % 4 == 0)) {
118 max_sleep_time_usecs *= 2;
122 if (success)
123 *success = (ret_pid != -1);
125 return status;
128 // Android has built-in crash handling.
129 #if !defined(OS_ANDROID)
130 void StackDumpSignalHandler(int signal, siginfo_t* info, ucontext_t* context) {
131 if (debug::BeingDebugged())
132 debug::BreakDebugger();
134 DLOG(ERROR) << "Received signal " << signal;
135 debug::StackTrace().PrintBacktrace();
137 // TODO(shess): Port to Linux.
138 #if defined(OS_MACOSX)
139 // TODO(shess): Port to 64-bit.
140 #if ARCH_CPU_32_BITS
141 char buf[1024];
142 size_t len;
144 // NOTE: Even |snprintf()| is not on the approved list for signal
145 // handlers, but buffered I/O is definitely not on the list due to
146 // potential for |malloc()|.
147 len = static_cast<size_t>(
148 snprintf(buf, sizeof(buf),
149 "ax: %x, bx: %x, cx: %x, dx: %x\n",
150 context->uc_mcontext->__ss.__eax,
151 context->uc_mcontext->__ss.__ebx,
152 context->uc_mcontext->__ss.__ecx,
153 context->uc_mcontext->__ss.__edx));
154 write(STDERR_FILENO, buf, std::min(len, sizeof(buf) - 1));
156 len = static_cast<size_t>(
157 snprintf(buf, sizeof(buf),
158 "di: %x, si: %x, bp: %x, sp: %x, ss: %x, flags: %x\n",
159 context->uc_mcontext->__ss.__edi,
160 context->uc_mcontext->__ss.__esi,
161 context->uc_mcontext->__ss.__ebp,
162 context->uc_mcontext->__ss.__esp,
163 context->uc_mcontext->__ss.__ss,
164 context->uc_mcontext->__ss.__eflags));
165 write(STDERR_FILENO, buf, std::min(len, sizeof(buf) - 1));
167 len = static_cast<size_t>(
168 snprintf(buf, sizeof(buf),
169 "ip: %x, cs: %x, ds: %x, es: %x, fs: %x, gs: %x\n",
170 context->uc_mcontext->__ss.__eip,
171 context->uc_mcontext->__ss.__cs,
172 context->uc_mcontext->__ss.__ds,
173 context->uc_mcontext->__ss.__es,
174 context->uc_mcontext->__ss.__fs,
175 context->uc_mcontext->__ss.__gs));
176 write(STDERR_FILENO, buf, std::min(len, sizeof(buf) - 1));
177 #endif // ARCH_CPU_32_BITS
178 #endif // defined(OS_MACOSX)
179 _exit(1);
181 #endif // !defined(OS_ANDROID)
183 void ResetChildSignalHandlersToDefaults() {
184 // The previous signal handlers are likely to be meaningless in the child's
185 // context so we reset them to the defaults for now. http://crbug.com/44953
186 // These signal handlers are set up at least in browser_main_posix.cc:
187 // BrowserMainPartsPosix::PreEarlyInitialization and process_util_posix.cc:
188 // EnableInProcessStackDumping.
189 signal(SIGHUP, SIG_DFL);
190 signal(SIGINT, SIG_DFL);
191 signal(SIGILL, SIG_DFL);
192 signal(SIGABRT, SIG_DFL);
193 signal(SIGFPE, SIG_DFL);
194 signal(SIGBUS, SIG_DFL);
195 signal(SIGSEGV, SIG_DFL);
196 signal(SIGSYS, SIG_DFL);
197 signal(SIGTERM, SIG_DFL);
200 } // anonymous namespace
202 ProcessId GetCurrentProcId() {
203 return getpid();
206 ProcessHandle GetCurrentProcessHandle() {
207 return GetCurrentProcId();
210 bool OpenProcessHandle(ProcessId pid, ProcessHandle* handle) {
211 // On Posix platforms, process handles are the same as PIDs, so we
212 // don't need to do anything.
213 *handle = pid;
214 return true;
217 bool OpenPrivilegedProcessHandle(ProcessId pid, ProcessHandle* handle) {
218 // On POSIX permissions are checked for each operation on process,
219 // not when opening a "handle".
220 return OpenProcessHandle(pid, handle);
223 bool OpenProcessHandleWithAccess(ProcessId pid,
224 uint32 access_flags,
225 ProcessHandle* handle) {
226 // On POSIX permissions are checked for each operation on process,
227 // not when opening a "handle".
228 return OpenProcessHandle(pid, handle);
231 void CloseProcessHandle(ProcessHandle process) {
232 // See OpenProcessHandle, nothing to do.
233 return;
236 ProcessId GetProcId(ProcessHandle process) {
237 return process;
240 // Attempts to kill the process identified by the given process
241 // entry structure. Ignores specified exit_code; posix can't force that.
242 // Returns true if this is successful, false otherwise.
243 bool KillProcess(ProcessHandle process_id, int exit_code, bool wait) {
244 DCHECK_GT(process_id, 1) << " tried to kill invalid process_id";
245 if (process_id <= 1)
246 return false;
247 static unsigned kMaxSleepMs = 1000;
248 unsigned sleep_ms = 4;
250 bool result = kill(process_id, SIGTERM) == 0;
252 if (result && wait) {
253 int tries = 60;
255 if (RunningOnValgrind()) {
256 // Wait for some extra time when running under Valgrind since the child
257 // processes may take some time doing leak checking.
258 tries *= 2;
261 // The process may not end immediately due to pending I/O
262 bool exited = false;
263 while (tries-- > 0) {
264 pid_t pid = HANDLE_EINTR(waitpid(process_id, NULL, WNOHANG));
265 if (pid == process_id) {
266 exited = true;
267 break;
269 if (pid == -1) {
270 if (errno == ECHILD) {
271 // The wait may fail with ECHILD if another process also waited for
272 // the same pid, causing the process state to get cleaned up.
273 exited = true;
274 break;
276 DPLOG(ERROR) << "Error waiting for process " << process_id;
279 usleep(sleep_ms * 1000);
280 if (sleep_ms < kMaxSleepMs)
281 sleep_ms *= 2;
284 // If we're waiting and the child hasn't died by now, force it
285 // with a SIGKILL.
286 if (!exited)
287 result = kill(process_id, SIGKILL) == 0;
290 if (!result)
291 DPLOG(ERROR) << "Unable to terminate process " << process_id;
293 return result;
296 bool KillProcessGroup(ProcessHandle process_group_id) {
297 bool result = kill(-1 * process_group_id, SIGKILL) == 0;
298 if (!result)
299 DPLOG(ERROR) << "Unable to terminate process group " << process_group_id;
300 return result;
303 // A class to handle auto-closing of DIR*'s.
304 class ScopedDIRClose {
305 public:
306 inline void operator()(DIR* x) const {
307 if (x) {
308 closedir(x);
312 typedef scoped_ptr_malloc<DIR, ScopedDIRClose> ScopedDIR;
314 #if defined(OS_LINUX)
315 static const rlim_t kSystemDefaultMaxFds = 8192;
316 static const char kFDDir[] = "/proc/self/fd";
317 #elif defined(OS_MACOSX)
318 static const rlim_t kSystemDefaultMaxFds = 256;
319 static const char kFDDir[] = "/dev/fd";
320 #elif defined(OS_SOLARIS)
321 static const rlim_t kSystemDefaultMaxFds = 8192;
322 static const char kFDDir[] = "/dev/fd";
323 #elif defined(OS_FREEBSD)
324 static const rlim_t kSystemDefaultMaxFds = 8192;
325 static const char kFDDir[] = "/dev/fd";
326 #elif defined(OS_OPENBSD)
327 static const rlim_t kSystemDefaultMaxFds = 256;
328 static const char kFDDir[] = "/dev/fd";
329 #elif defined(OS_ANDROID)
330 static const rlim_t kSystemDefaultMaxFds = 1024;
331 static const char kFDDir[] = "/proc/self/fd";
332 #endif
334 void CloseSuperfluousFds(const base::InjectiveMultimap& saved_mapping) {
335 // DANGER: no calls to malloc are allowed from now on:
336 // http://crbug.com/36678
338 // Get the maximum number of FDs possible.
339 struct rlimit nofile;
340 rlim_t max_fds;
341 if (getrlimit(RLIMIT_NOFILE, &nofile)) {
342 // getrlimit failed. Take a best guess.
343 max_fds = kSystemDefaultMaxFds;
344 RAW_LOG(ERROR, "getrlimit(RLIMIT_NOFILE) failed");
345 } else {
346 max_fds = nofile.rlim_cur;
349 if (max_fds > INT_MAX)
350 max_fds = INT_MAX;
352 DirReaderPosix fd_dir(kFDDir);
354 if (!fd_dir.IsValid()) {
355 // Fallback case: Try every possible fd.
356 for (rlim_t i = 0; i < max_fds; ++i) {
357 const int fd = static_cast<int>(i);
358 if (fd == STDIN_FILENO || fd == STDOUT_FILENO || fd == STDERR_FILENO)
359 continue;
360 InjectiveMultimap::const_iterator j;
361 for (j = saved_mapping.begin(); j != saved_mapping.end(); j++) {
362 if (fd == j->dest)
363 break;
365 if (j != saved_mapping.end())
366 continue;
368 // Since we're just trying to close anything we can find,
369 // ignore any error return values of close().
370 ignore_result(HANDLE_EINTR(close(fd)));
372 return;
375 const int dir_fd = fd_dir.fd();
377 for ( ; fd_dir.Next(); ) {
378 // Skip . and .. entries.
379 if (fd_dir.name()[0] == '.')
380 continue;
382 char *endptr;
383 errno = 0;
384 const long int fd = strtol(fd_dir.name(), &endptr, 10);
385 if (fd_dir.name()[0] == 0 || *endptr || fd < 0 || errno)
386 continue;
387 if (fd == STDIN_FILENO || fd == STDOUT_FILENO || fd == STDERR_FILENO)
388 continue;
389 InjectiveMultimap::const_iterator i;
390 for (i = saved_mapping.begin(); i != saved_mapping.end(); i++) {
391 if (fd == i->dest)
392 break;
394 if (i != saved_mapping.end())
395 continue;
396 if (fd == dir_fd)
397 continue;
399 // When running under Valgrind, Valgrind opens several FDs for its
400 // own use and will complain if we try to close them. All of
401 // these FDs are >= |max_fds|, so we can check against that here
402 // before closing. See https://bugs.kde.org/show_bug.cgi?id=191758
403 if (fd < static_cast<int>(max_fds)) {
404 int ret = HANDLE_EINTR(close(fd));
405 DPCHECK(ret == 0);
410 char** AlterEnvironment(const environment_vector& changes,
411 const char* const* const env) {
412 unsigned count = 0;
413 unsigned size = 0;
415 // First assume that all of the current environment will be included.
416 for (unsigned i = 0; env[i]; i++) {
417 const char *const pair = env[i];
418 count++;
419 size += strlen(pair) + 1 /* terminating NUL */;
422 for (environment_vector::const_iterator
423 j = changes.begin(); j != changes.end(); j++) {
424 bool found = false;
425 const char *pair;
427 for (unsigned i = 0; env[i]; i++) {
428 pair = env[i];
429 const char *const equals = strchr(pair, '=');
430 if (!equals)
431 continue;
432 const unsigned keylen = equals - pair;
433 if (keylen == j->first.size() &&
434 memcmp(pair, j->first.data(), keylen) == 0) {
435 found = true;
436 break;
440 // if found, we'll either be deleting or replacing this element.
441 if (found) {
442 count--;
443 size -= strlen(pair) + 1;
444 if (j->second.size())
445 found = false;
448 // if !found, then we have a new element to add.
449 if (!found && !j->second.empty()) {
450 count++;
451 size += j->first.size() + 1 /* '=' */ + j->second.size() + 1 /* NUL */;
455 count++; // for the final NULL
456 uint8_t *buffer = new uint8_t[sizeof(char*) * count + size];
457 char **const ret = reinterpret_cast<char**>(buffer);
458 unsigned k = 0;
459 char *scratch = reinterpret_cast<char*>(buffer + sizeof(char*) * count);
461 for (unsigned i = 0; env[i]; i++) {
462 const char *const pair = env[i];
463 const char *const equals = strchr(pair, '=');
464 if (!equals) {
465 const unsigned len = strlen(pair);
466 ret[k++] = scratch;
467 memcpy(scratch, pair, len + 1);
468 scratch += len + 1;
469 continue;
471 const unsigned keylen = equals - pair;
472 bool handled = false;
473 for (environment_vector::const_iterator
474 j = changes.begin(); j != changes.end(); j++) {
475 if (j->first.size() == keylen &&
476 memcmp(j->first.data(), pair, keylen) == 0) {
477 if (!j->second.empty()) {
478 ret[k++] = scratch;
479 memcpy(scratch, pair, keylen + 1);
480 scratch += keylen + 1;
481 memcpy(scratch, j->second.c_str(), j->second.size() + 1);
482 scratch += j->second.size() + 1;
484 handled = true;
485 break;
489 if (!handled) {
490 const unsigned len = strlen(pair);
491 ret[k++] = scratch;
492 memcpy(scratch, pair, len + 1);
493 scratch += len + 1;
497 // Now handle new elements
498 for (environment_vector::const_iterator
499 j = changes.begin(); j != changes.end(); j++) {
500 if (j->second.empty())
501 continue;
503 bool found = false;
504 for (unsigned i = 0; env[i]; i++) {
505 const char *const pair = env[i];
506 const char *const equals = strchr(pair, '=');
507 if (!equals)
508 continue;
509 const unsigned keylen = equals - pair;
510 if (keylen == j->first.size() &&
511 memcmp(pair, j->first.data(), keylen) == 0) {
512 found = true;
513 break;
517 if (!found) {
518 ret[k++] = scratch;
519 memcpy(scratch, j->first.data(), j->first.size());
520 scratch += j->first.size();
521 *scratch++ = '=';
522 memcpy(scratch, j->second.c_str(), j->second.size() + 1);
523 scratch += j->second.size() + 1;
527 ret[k] = NULL;
528 return ret;
531 bool LaunchProcess(const std::vector<std::string>& argv,
532 const LaunchOptions& options,
533 ProcessHandle* process_handle) {
534 size_t fd_shuffle_size = 0;
535 if (options.fds_to_remap) {
536 fd_shuffle_size = options.fds_to_remap->size();
539 #if defined(OS_MACOSX)
540 if (options.synchronize) {
541 // When synchronizing, the "read" end of the synchronization pipe needs
542 // to make it to the child process. This is handled by mapping it back to
543 // itself.
544 ++fd_shuffle_size;
546 #endif // defined(OS_MACOSX)
548 InjectiveMultimap fd_shuffle1;
549 InjectiveMultimap fd_shuffle2;
550 fd_shuffle1.reserve(fd_shuffle_size);
551 fd_shuffle2.reserve(fd_shuffle_size);
553 scoped_array<char*> argv_cstr(new char*[argv.size() + 1]);
554 scoped_array<char*> new_environ;
555 if (options.environ)
556 new_environ.reset(AlterEnvironment(*options.environ, GetEnvironment()));
558 #if defined(OS_MACOSX)
559 int synchronization_pipe_fds[2];
560 file_util::ScopedFD synchronization_read_fd;
561 file_util::ScopedFD synchronization_write_fd;
563 if (options.synchronize) {
564 // wait means "don't return from LaunchProcess until the child exits", and
565 // synchronize means "return from LaunchProcess but don't let the child
566 // run until LaunchSynchronize is called". These two options are highly
567 // incompatible.
568 DCHECK(!options.wait);
570 // Create the pipe used for synchronization.
571 if (HANDLE_EINTR(pipe(synchronization_pipe_fds)) != 0) {
572 DPLOG(ERROR) << "pipe";
573 return false;
576 // The parent process will only use synchronization_write_fd as the write
577 // side of the pipe. It can close the read side as soon as the child
578 // process has forked off. The child process will only use
579 // synchronization_read_fd as the read side of the pipe. In that process,
580 // the write side can be closed as soon as it has forked.
581 synchronization_read_fd.reset(&synchronization_pipe_fds[0]);
582 synchronization_write_fd.reset(&synchronization_pipe_fds[1]);
584 #endif // OS_MACOSX
586 pid_t pid;
587 #if defined(OS_LINUX)
588 if (options.clone_flags) {
589 pid = syscall(__NR_clone, options.clone_flags, 0, 0, 0);
590 } else
591 #endif
593 pid = fork();
596 if (pid < 0) {
597 DPLOG(ERROR) << "fork";
598 return false;
599 } else if (pid == 0) {
600 // Child process
602 // DANGER: fork() rule: in the child, if you don't end up doing exec*(),
603 // you call _exit() instead of exit(). This is because _exit() does not
604 // call any previously-registered (in the parent) exit handlers, which
605 // might do things like block waiting for threads that don't even exist
606 // in the child.
608 // If a child process uses the readline library, the process block forever.
609 // In BSD like OSes including OS X it is safe to assign /dev/null as stdin.
610 // See http://crbug.com/56596.
611 int null_fd = HANDLE_EINTR(open("/dev/null", O_RDONLY));
612 if (null_fd < 0) {
613 RAW_LOG(ERROR, "Failed to open /dev/null");
614 _exit(127);
617 file_util::ScopedFD null_fd_closer(&null_fd);
618 int new_fd = HANDLE_EINTR(dup2(null_fd, STDIN_FILENO));
619 if (new_fd != STDIN_FILENO) {
620 RAW_LOG(ERROR, "Failed to dup /dev/null for stdin");
621 _exit(127);
624 if (options.new_process_group) {
625 // Instead of inheriting the process group ID of the parent, the child
626 // starts off a new process group with pgid equal to its process ID.
627 if (setpgid(0, 0) < 0) {
628 RAW_LOG(ERROR, "setpgid failed");
629 _exit(127);
633 #if defined(OS_MACOSX)
634 RestoreDefaultExceptionHandler();
635 #endif // defined(OS_MACOSX)
637 ResetChildSignalHandlersToDefaults();
639 #if defined(OS_MACOSX)
640 if (options.synchronize) {
641 // The "write" side of the synchronization pipe belongs to the parent.
642 synchronization_write_fd.reset(); // closes synchronization_pipe_fds[1]
644 #endif // defined(OS_MACOSX)
646 #if 0
647 // When debugging it can be helpful to check that we really aren't making
648 // any hidden calls to malloc.
649 void *malloc_thunk =
650 reinterpret_cast<void*>(reinterpret_cast<intptr_t>(malloc) & ~4095);
651 mprotect(malloc_thunk, 4096, PROT_READ | PROT_WRITE | PROT_EXEC);
652 memset(reinterpret_cast<void*>(malloc), 0xff, 8);
653 #endif // 0
655 // DANGER: no calls to malloc are allowed from now on:
656 // http://crbug.com/36678
658 if (options.fds_to_remap) {
659 for (file_handle_mapping_vector::const_iterator
660 it = options.fds_to_remap->begin();
661 it != options.fds_to_remap->end(); ++it) {
662 fd_shuffle1.push_back(InjectionArc(it->first, it->second, false));
663 fd_shuffle2.push_back(InjectionArc(it->first, it->second, false));
667 #if defined(OS_MACOSX)
668 if (options.synchronize) {
669 // Remap the read side of the synchronization pipe back onto itself,
670 // ensuring that it won't be closed by CloseSuperfluousFds.
671 int keep_fd = *synchronization_read_fd.get();
672 fd_shuffle1.push_back(InjectionArc(keep_fd, keep_fd, false));
673 fd_shuffle2.push_back(InjectionArc(keep_fd, keep_fd, false));
675 #endif // defined(OS_MACOSX)
677 if (options.environ)
678 SetEnvironment(new_environ.get());
680 // fd_shuffle1 is mutated by this call because it cannot malloc.
681 if (!ShuffleFileDescriptors(&fd_shuffle1))
682 _exit(127);
684 CloseSuperfluousFds(fd_shuffle2);
686 #if defined(OS_MACOSX)
687 if (options.synchronize) {
688 // Do a blocking read to wait until the parent says it's OK to proceed.
689 // The byte that's read here is written by LaunchSynchronize.
690 char read_char;
691 int read_result =
692 HANDLE_EINTR(read(*synchronization_read_fd.get(), &read_char, 1));
693 if (read_result != 1) {
694 RAW_LOG(ERROR, "LaunchProcess: synchronization read: error");
695 _exit(127);
698 // The pipe is no longer useful. Don't let it live on in the new process
699 // after exec.
700 synchronization_read_fd.reset(); // closes synchronization_pipe_fds[0]
702 #endif // defined(OS_MACOSX)
704 for (size_t i = 0; i < argv.size(); i++)
705 argv_cstr[i] = const_cast<char*>(argv[i].c_str());
706 argv_cstr[argv.size()] = NULL;
707 execvp(argv_cstr[0], argv_cstr.get());
709 RAW_LOG(ERROR, "LaunchProcess: failed to execvp:");
710 RAW_LOG(ERROR, argv_cstr[0]);
711 _exit(127);
712 } else {
713 // Parent process
714 if (options.wait) {
715 // While this isn't strictly disk IO, waiting for another process to
716 // finish is the sort of thing ThreadRestrictions is trying to prevent.
717 base::ThreadRestrictions::AssertIOAllowed();
718 pid_t ret = HANDLE_EINTR(waitpid(pid, 0, 0));
719 DPCHECK(ret > 0);
722 if (process_handle)
723 *process_handle = pid;
725 #if defined(OS_MACOSX)
726 if (options.synchronize) {
727 // The "read" side of the synchronization pipe belongs to the child.
728 synchronization_read_fd.reset(); // closes synchronization_pipe_fds[0]
729 *options.synchronize = new int(*synchronization_write_fd.release());
731 #endif // defined(OS_MACOSX)
734 return true;
738 bool LaunchProcess(const CommandLine& cmdline,
739 const LaunchOptions& options,
740 ProcessHandle* process_handle) {
741 return LaunchProcess(cmdline.argv(), options, process_handle);
744 #if defined(OS_MACOSX)
745 void LaunchSynchronize(LaunchSynchronizationHandle handle) {
746 int synchronization_fd = *handle;
747 file_util::ScopedFD synchronization_fd_closer(&synchronization_fd);
748 delete handle;
750 // Write a '\0' character to the pipe.
751 if (HANDLE_EINTR(write(synchronization_fd, "", 1)) != 1) {
752 DPLOG(ERROR) << "write";
755 #endif // defined(OS_MACOSX)
757 ProcessMetrics::~ProcessMetrics() { }
759 bool EnableInProcessStackDumping() {
760 // When running in an application, our code typically expects SIGPIPE
761 // to be ignored. Therefore, when testing that same code, it should run
762 // with SIGPIPE ignored as well.
763 struct sigaction action;
764 action.sa_handler = SIG_IGN;
765 action.sa_flags = 0;
766 sigemptyset(&action.sa_mask);
767 bool success = (sigaction(SIGPIPE, &action, NULL) == 0);
769 // Android has built-in crash handling, so no need to hook the signals.
770 #if !defined(OS_ANDROID)
771 sig_t handler = reinterpret_cast<sig_t>(&StackDumpSignalHandler);
772 success &= (signal(SIGILL, handler) != SIG_ERR);
773 success &= (signal(SIGABRT, handler) != SIG_ERR);
774 success &= (signal(SIGFPE, handler) != SIG_ERR);
775 success &= (signal(SIGBUS, handler) != SIG_ERR);
776 success &= (signal(SIGSEGV, handler) != SIG_ERR);
777 success &= (signal(SIGSYS, handler) != SIG_ERR);
778 #endif
780 return success;
783 void RaiseProcessToHighPriority() {
784 // On POSIX, we don't actually do anything here. We could try to nice() or
785 // setpriority() or sched_getscheduler, but these all require extra rights.
788 TerminationStatus GetTerminationStatus(ProcessHandle handle, int* exit_code) {
789 int status = 0;
790 const pid_t result = HANDLE_EINTR(waitpid(handle, &status, WNOHANG));
791 if (result == -1) {
792 DPLOG(ERROR) << "waitpid(" << handle << ")";
793 if (exit_code)
794 *exit_code = 0;
795 return TERMINATION_STATUS_NORMAL_TERMINATION;
796 } else if (result == 0) {
797 // the child hasn't exited yet.
798 if (exit_code)
799 *exit_code = 0;
800 return TERMINATION_STATUS_STILL_RUNNING;
803 if (exit_code)
804 *exit_code = status;
806 if (WIFSIGNALED(status)) {
807 switch (WTERMSIG(status)) {
808 case SIGABRT:
809 case SIGBUS:
810 case SIGFPE:
811 case SIGILL:
812 case SIGSEGV:
813 return TERMINATION_STATUS_PROCESS_CRASHED;
814 case SIGINT:
815 case SIGKILL:
816 case SIGTERM:
817 return TERMINATION_STATUS_PROCESS_WAS_KILLED;
818 default:
819 break;
823 if (WIFEXITED(status) && WEXITSTATUS(status) != 0)
824 return TERMINATION_STATUS_ABNORMAL_TERMINATION;
826 return TERMINATION_STATUS_NORMAL_TERMINATION;
829 bool WaitForExitCode(ProcessHandle handle, int* exit_code) {
830 int status;
831 if (HANDLE_EINTR(waitpid(handle, &status, 0)) == -1) {
832 NOTREACHED();
833 return false;
836 if (WIFEXITED(status)) {
837 *exit_code = WEXITSTATUS(status);
838 return true;
841 // If it didn't exit cleanly, it must have been signaled.
842 DCHECK(WIFSIGNALED(status));
843 return false;
846 bool WaitForExitCodeWithTimeout(ProcessHandle handle, int* exit_code,
847 int64 timeout_milliseconds) {
848 bool waitpid_success = false;
849 int status = WaitpidWithTimeout(handle, timeout_milliseconds,
850 &waitpid_success);
851 if (status == -1)
852 return false;
853 if (!waitpid_success)
854 return false;
855 if (WIFSIGNALED(status)) {
856 *exit_code = -1;
857 return true;
859 if (WIFEXITED(status)) {
860 *exit_code = WEXITSTATUS(status);
861 return true;
863 return false;
866 #if defined(OS_MACOSX)
867 // Using kqueue on Mac so that we can wait on non-child processes.
868 // We can't use kqueues on child processes because we need to reap
869 // our own children using wait.
870 static bool WaitForSingleNonChildProcess(ProcessHandle handle,
871 int64 wait_milliseconds) {
872 DCHECK_GT(handle, 0);
873 DCHECK(wait_milliseconds == base::kNoTimeout || wait_milliseconds > 0);
875 int kq = kqueue();
876 if (kq == -1) {
877 DPLOG(ERROR) << "kqueue";
878 return false;
880 file_util::ScopedFD kq_closer(&kq);
882 struct kevent change = {0};
883 EV_SET(&change, handle, EVFILT_PROC, EV_ADD, NOTE_EXIT, 0, NULL);
884 int result = HANDLE_EINTR(kevent(kq, &change, 1, NULL, 0, NULL));
885 if (result == -1) {
886 if (errno == ESRCH) {
887 // If the process wasn't found, it must be dead.
888 return true;
891 DPLOG(ERROR) << "kevent (setup " << handle << ")";
892 return false;
895 // Keep track of the elapsed time to be able to restart kevent if it's
896 // interrupted.
897 bool wait_forever = wait_milliseconds == base::kNoTimeout;
898 base::TimeDelta remaining_delta;
899 base::Time deadline;
900 if (!wait_forever) {
901 remaining_delta = base::TimeDelta::FromMilliseconds(wait_milliseconds);
902 deadline = base::Time::Now() + remaining_delta;
905 result = -1;
906 struct kevent event = {0};
908 while (wait_forever || remaining_delta.InMilliseconds() > 0) {
909 struct timespec remaining_timespec;
910 struct timespec* remaining_timespec_ptr;
911 if (wait_forever) {
912 remaining_timespec_ptr = NULL;
913 } else {
914 remaining_timespec = remaining_delta.ToTimeSpec();
915 remaining_timespec_ptr = &remaining_timespec;
918 result = kevent(kq, NULL, 0, &event, 1, remaining_timespec_ptr);
920 if (result == -1 && errno == EINTR) {
921 if (!wait_forever) {
922 remaining_delta = deadline - base::Time::Now();
924 result = 0;
925 } else {
926 break;
930 if (result < 0) {
931 DPLOG(ERROR) << "kevent (wait " << handle << ")";
932 return false;
933 } else if (result > 1) {
934 DLOG(ERROR) << "kevent (wait " << handle << "): unexpected result "
935 << result;
936 return false;
937 } else if (result == 0) {
938 // Timed out.
939 return false;
942 DCHECK_EQ(result, 1);
944 if (event.filter != EVFILT_PROC ||
945 (event.fflags & NOTE_EXIT) == 0 ||
946 event.ident != static_cast<uintptr_t>(handle)) {
947 DLOG(ERROR) << "kevent (wait " << handle
948 << "): unexpected event: filter=" << event.filter
949 << ", fflags=" << event.fflags
950 << ", ident=" << event.ident;
951 return false;
954 return true;
956 #endif // OS_MACOSX
958 bool WaitForSingleProcess(ProcessHandle handle, int64 wait_milliseconds) {
959 ProcessHandle parent_pid = GetParentProcessId(handle);
960 ProcessHandle our_pid = Process::Current().handle();
961 if (parent_pid != our_pid) {
962 #if defined(OS_MACOSX)
963 // On Mac we can wait on non child processes.
964 return WaitForSingleNonChildProcess(handle, wait_milliseconds);
965 #else
966 // Currently on Linux we can't handle non child processes.
967 NOTIMPLEMENTED();
968 #endif // OS_MACOSX
971 bool waitpid_success;
972 int status = -1;
973 if (wait_milliseconds == base::kNoTimeout)
974 waitpid_success = (HANDLE_EINTR(waitpid(handle, &status, 0)) != -1);
975 else
976 status = WaitpidWithTimeout(handle, wait_milliseconds, &waitpid_success);
978 if (status != -1) {
979 DCHECK(waitpid_success);
980 return WIFEXITED(status);
981 } else {
982 return false;
986 int64 TimeValToMicroseconds(const struct timeval& tv) {
987 static const int kMicrosecondsPerSecond = 1000000;
988 int64 ret = tv.tv_sec; // Avoid (int * int) integer overflow.
989 ret *= kMicrosecondsPerSecond;
990 ret += tv.tv_usec;
991 return ret;
994 // Return value used by GetAppOutputInternal to encapsulate the various exit
995 // scenarios from the function.
996 enum GetAppOutputInternalResult {
997 EXECUTE_FAILURE,
998 EXECUTE_SUCCESS,
999 GOT_MAX_OUTPUT,
1002 // Executes the application specified by |cl| and wait for it to exit. Stores
1003 // the output (stdout) in |output|. If |do_search_path| is set, it searches the
1004 // path for the application; in that case, |envp| must be null, and it will use
1005 // the current environment. If |do_search_path| is false, |cl| should fully
1006 // specify the path of the application, and |envp| will be used as the
1007 // environment. Redirects stderr to /dev/null.
1008 // If we successfully start the application and get all requested output, we
1009 // return GOT_MAX_OUTPUT, or if there is a problem starting or exiting
1010 // the application we return RUN_FAILURE. Otherwise we return EXECUTE_SUCCESS.
1011 // The GOT_MAX_OUTPUT return value exists so a caller that asks for limited
1012 // output can treat this as a success, despite having an exit code of SIG_PIPE
1013 // due to us closing the output pipe.
1014 // In the case of EXECUTE_SUCCESS, the application exit code will be returned
1015 // in |*exit_code|, which should be checked to determine if the application
1016 // ran successfully.
1017 static GetAppOutputInternalResult GetAppOutputInternal(const CommandLine& cl,
1018 char* const envp[],
1019 std::string* output,
1020 size_t max_output,
1021 bool do_search_path,
1022 int* exit_code) {
1023 // Doing a blocking wait for another command to finish counts as IO.
1024 base::ThreadRestrictions::AssertIOAllowed();
1025 // exit_code must be supplied so calling function can determine success.
1026 DCHECK(exit_code);
1027 *exit_code = EXIT_FAILURE;
1029 int pipe_fd[2];
1030 pid_t pid;
1031 InjectiveMultimap fd_shuffle1, fd_shuffle2;
1032 const std::vector<std::string>& argv = cl.argv();
1033 scoped_array<char*> argv_cstr(new char*[argv.size() + 1]);
1035 fd_shuffle1.reserve(3);
1036 fd_shuffle2.reserve(3);
1038 // Either |do_search_path| should be false or |envp| should be null, but not
1039 // both.
1040 DCHECK(!do_search_path ^ !envp);
1042 if (pipe(pipe_fd) < 0)
1043 return EXECUTE_FAILURE;
1045 switch (pid = fork()) {
1046 case -1: // error
1047 close(pipe_fd[0]);
1048 close(pipe_fd[1]);
1049 return EXECUTE_FAILURE;
1050 case 0: // child
1052 #if defined(OS_MACOSX)
1053 RestoreDefaultExceptionHandler();
1054 #endif
1055 // DANGER: no calls to malloc are allowed from now on:
1056 // http://crbug.com/36678
1058 // Obscure fork() rule: in the child, if you don't end up doing exec*(),
1059 // you call _exit() instead of exit(). This is because _exit() does not
1060 // call any previously-registered (in the parent) exit handlers, which
1061 // might do things like block waiting for threads that don't even exist
1062 // in the child.
1063 int dev_null = open("/dev/null", O_WRONLY);
1064 if (dev_null < 0)
1065 _exit(127);
1067 fd_shuffle1.push_back(InjectionArc(pipe_fd[1], STDOUT_FILENO, true));
1068 fd_shuffle1.push_back(InjectionArc(dev_null, STDERR_FILENO, true));
1069 fd_shuffle1.push_back(InjectionArc(dev_null, STDIN_FILENO, true));
1070 // Adding another element here? Remeber to increase the argument to
1071 // reserve(), above.
1073 std::copy(fd_shuffle1.begin(), fd_shuffle1.end(),
1074 std::back_inserter(fd_shuffle2));
1076 if (!ShuffleFileDescriptors(&fd_shuffle1))
1077 _exit(127);
1079 CloseSuperfluousFds(fd_shuffle2);
1081 for (size_t i = 0; i < argv.size(); i++)
1082 argv_cstr[i] = const_cast<char*>(argv[i].c_str());
1083 argv_cstr[argv.size()] = NULL;
1084 if (do_search_path)
1085 execvp(argv_cstr[0], argv_cstr.get());
1086 else
1087 execve(argv_cstr[0], argv_cstr.get(), envp);
1088 _exit(127);
1090 default: // parent
1092 // Close our writing end of pipe now. Otherwise later read would not
1093 // be able to detect end of child's output (in theory we could still
1094 // write to the pipe).
1095 close(pipe_fd[1]);
1097 output->clear();
1098 char buffer[256];
1099 size_t output_buf_left = max_output;
1100 ssize_t bytes_read = 1; // A lie to properly handle |max_output == 0|
1101 // case in the logic below.
1103 while (output_buf_left > 0) {
1104 bytes_read = HANDLE_EINTR(read(pipe_fd[0], buffer,
1105 std::min(output_buf_left, sizeof(buffer))));
1106 if (bytes_read <= 0)
1107 break;
1108 output->append(buffer, bytes_read);
1109 output_buf_left -= static_cast<size_t>(bytes_read);
1111 close(pipe_fd[0]);
1113 // Always wait for exit code (even if we know we'll declare
1114 // GOT_MAX_OUTPUT).
1115 bool success = WaitForExitCode(pid, exit_code);
1117 // If we stopped because we read as much as we wanted, we return
1118 // GOT_MAX_OUTPUT (because the child may exit due to |SIGPIPE|).
1119 if (!output_buf_left && bytes_read > 0)
1120 return GOT_MAX_OUTPUT;
1121 else if (success)
1122 return EXECUTE_SUCCESS;
1123 return EXECUTE_FAILURE;
1128 bool GetAppOutput(const CommandLine& cl, std::string* output) {
1129 // Run |execve()| with the current environment and store "unlimited" data.
1130 int exit_code;
1131 GetAppOutputInternalResult result = GetAppOutputInternal(
1132 cl, NULL, output, std::numeric_limits<std::size_t>::max(), true,
1133 &exit_code);
1134 return result == EXECUTE_SUCCESS && exit_code == EXIT_SUCCESS;
1137 // TODO(viettrungluu): Conceivably, we should have a timeout as well, so we
1138 // don't hang if what we're calling hangs.
1139 bool GetAppOutputRestricted(const CommandLine& cl,
1140 std::string* output, size_t max_output) {
1141 // Run |execve()| with the empty environment.
1142 char* const empty_environ = NULL;
1143 int exit_code;
1144 GetAppOutputInternalResult result = GetAppOutputInternal(cl, &empty_environ,
1145 output, max_output,
1146 false, &exit_code);
1147 return result == GOT_MAX_OUTPUT || (result == EXECUTE_SUCCESS &&
1148 exit_code == EXIT_SUCCESS);
1151 bool GetAppOutputWithExitCode(const CommandLine& cl,
1152 std::string* output,
1153 int* exit_code) {
1154 // Run |execve()| with the current environment and store "unlimited" data.
1155 GetAppOutputInternalResult result = GetAppOutputInternal(
1156 cl, NULL, output, std::numeric_limits<std::size_t>::max(), true,
1157 exit_code);
1158 return result == EXECUTE_SUCCESS;
1161 bool WaitForProcessesToExit(const FilePath::StringType& executable_name,
1162 int64 wait_milliseconds,
1163 const ProcessFilter* filter) {
1164 bool result = false;
1166 // TODO(port): This is inefficient, but works if there are multiple procs.
1167 // TODO(port): use waitpid to avoid leaving zombies around
1169 base::Time end_time = base::Time::Now() +
1170 base::TimeDelta::FromMilliseconds(wait_milliseconds);
1171 do {
1172 NamedProcessIterator iter(executable_name, filter);
1173 if (!iter.NextProcessEntry()) {
1174 result = true;
1175 break;
1177 base::PlatformThread::Sleep(100);
1178 } while ((end_time - base::Time::Now()) > base::TimeDelta());
1180 return result;
1183 bool CleanupProcesses(const FilePath::StringType& executable_name,
1184 int64 wait_milliseconds,
1185 int exit_code,
1186 const ProcessFilter* filter) {
1187 bool exited_cleanly =
1188 WaitForProcessesToExit(executable_name, wait_milliseconds,
1189 filter);
1190 if (!exited_cleanly)
1191 KillProcesses(executable_name, exit_code, filter);
1192 return exited_cleanly;
1195 } // namespace base