Updating trunk VERSION from 1010.0 to 1011.0
[chromium-blink-merge.git] / base / process_util_posix.cc
blob5a1d4425bbb280f1a501c6bccfa08caf33ee1bcf
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"
35 #if defined(OS_FREEBSD)
36 #include <sys/event.h>
37 #include <sys/ucontext.h>
38 #endif
40 #if defined(OS_MACOSX)
41 #include <crt_externs.h>
42 #include <sys/event.h>
43 #else
44 extern char** environ;
45 #endif
47 namespace base {
49 namespace {
51 // Get the process's "environment" (i.e. the thing that setenv/getenv
52 // work with).
53 char** GetEnvironment() {
54 #if defined(OS_MACOSX)
55 return *_NSGetEnviron();
56 #else
57 return environ;
58 #endif
61 // Set the process's "environment" (i.e. the thing that setenv/getenv
62 // work with).
63 void SetEnvironment(char** env) {
64 #if defined(OS_MACOSX)
65 *_NSGetEnviron() = env;
66 #else
67 environ = env;
68 #endif
71 int WaitpidWithTimeout(ProcessHandle handle, int64 wait_milliseconds,
72 bool* success) {
73 // This POSIX version of this function only guarantees that we wait no less
74 // than |wait_milliseconds| for the process to exit. The child process may
75 // exit sometime before the timeout has ended but we may still block for up
76 // to 256 milliseconds after the fact.
78 // waitpid() has no direct support on POSIX for specifying a timeout, you can
79 // either ask it to block indefinitely or return immediately (WNOHANG).
80 // When a child process terminates a SIGCHLD signal is sent to the parent.
81 // Catching this signal would involve installing a signal handler which may
82 // affect other parts of the application and would be difficult to debug.
84 // Our strategy is to call waitpid() once up front to check if the process
85 // has already exited, otherwise to loop for wait_milliseconds, sleeping for
86 // at most 256 milliseconds each time using usleep() and then calling
87 // waitpid(). The amount of time we sleep starts out at 1 milliseconds, and
88 // we double it every 4 sleep cycles.
90 // usleep() is speced to exit if a signal is received for which a handler
91 // has been installed. This means that when a SIGCHLD is sent, it will exit
92 // depending on behavior external to this function.
94 // This function is used primarily for unit tests, if we want to use it in
95 // the application itself it would probably be best to examine other routes.
96 int status = -1;
97 pid_t ret_pid = HANDLE_EINTR(waitpid(handle, &status, WNOHANG));
98 static const int64 kMaxSleepInMicroseconds = 1 << 18; // ~256 milliseconds.
99 int64 max_sleep_time_usecs = 1 << 10; // ~1 milliseconds.
100 int64 double_sleep_time = 0;
102 // If the process hasn't exited yet, then sleep and try again.
103 Time wakeup_time = Time::Now() +
104 TimeDelta::FromMilliseconds(wait_milliseconds);
105 while (ret_pid == 0) {
106 Time now = Time::Now();
107 if (now > wakeup_time)
108 break;
109 // Guaranteed to be non-negative!
110 int64 sleep_time_usecs = (wakeup_time - now).InMicroseconds();
111 // Sleep for a bit while we wait for the process to finish.
112 if (sleep_time_usecs > max_sleep_time_usecs)
113 sleep_time_usecs = max_sleep_time_usecs;
115 // usleep() will return 0 and set errno to EINTR on receipt of a signal
116 // such as SIGCHLD.
117 usleep(sleep_time_usecs);
118 ret_pid = HANDLE_EINTR(waitpid(handle, &status, WNOHANG));
120 if ((max_sleep_time_usecs < kMaxSleepInMicroseconds) &&
121 (double_sleep_time++ % 4 == 0)) {
122 max_sleep_time_usecs *= 2;
126 if (success)
127 *success = (ret_pid != -1);
129 return status;
132 // Android has built-in crash handling.
133 #if !defined(OS_ANDROID)
134 void StackDumpSignalHandler(int signal, siginfo_t* info, ucontext_t* context) {
135 if (debug::BeingDebugged())
136 debug::BreakDebugger();
138 DLOG(ERROR) << "Received signal " << signal;
139 debug::StackTrace().PrintBacktrace();
141 // TODO(shess): Port to Linux.
142 #if defined(OS_MACOSX)
143 // TODO(shess): Port to 64-bit.
144 #if ARCH_CPU_32_BITS
145 char buf[1024];
146 size_t len;
148 // NOTE: Even |snprintf()| is not on the approved list for signal
149 // handlers, but buffered I/O is definitely not on the list due to
150 // potential for |malloc()|.
151 len = static_cast<size_t>(
152 snprintf(buf, sizeof(buf),
153 "ax: %x, bx: %x, cx: %x, dx: %x\n",
154 context->uc_mcontext->__ss.__eax,
155 context->uc_mcontext->__ss.__ebx,
156 context->uc_mcontext->__ss.__ecx,
157 context->uc_mcontext->__ss.__edx));
158 write(STDERR_FILENO, buf, std::min(len, sizeof(buf) - 1));
160 len = static_cast<size_t>(
161 snprintf(buf, sizeof(buf),
162 "di: %x, si: %x, bp: %x, sp: %x, ss: %x, flags: %x\n",
163 context->uc_mcontext->__ss.__edi,
164 context->uc_mcontext->__ss.__esi,
165 context->uc_mcontext->__ss.__ebp,
166 context->uc_mcontext->__ss.__esp,
167 context->uc_mcontext->__ss.__ss,
168 context->uc_mcontext->__ss.__eflags));
169 write(STDERR_FILENO, buf, std::min(len, sizeof(buf) - 1));
171 len = static_cast<size_t>(
172 snprintf(buf, sizeof(buf),
173 "ip: %x, cs: %x, ds: %x, es: %x, fs: %x, gs: %x\n",
174 context->uc_mcontext->__ss.__eip,
175 context->uc_mcontext->__ss.__cs,
176 context->uc_mcontext->__ss.__ds,
177 context->uc_mcontext->__ss.__es,
178 context->uc_mcontext->__ss.__fs,
179 context->uc_mcontext->__ss.__gs));
180 write(STDERR_FILENO, buf, std::min(len, sizeof(buf) - 1));
181 #endif // ARCH_CPU_32_BITS
182 #endif // defined(OS_MACOSX)
183 _exit(1);
185 #endif // !defined(OS_ANDROID)
187 void ResetChildSignalHandlersToDefaults() {
188 // The previous signal handlers are likely to be meaningless in the child's
189 // context so we reset them to the defaults for now. http://crbug.com/44953
190 // These signal handlers are set up at least in browser_main_posix.cc:
191 // BrowserMainPartsPosix::PreEarlyInitialization and process_util_posix.cc:
192 // EnableInProcessStackDumping.
193 signal(SIGHUP, SIG_DFL);
194 signal(SIGINT, SIG_DFL);
195 signal(SIGILL, SIG_DFL);
196 signal(SIGABRT, SIG_DFL);
197 signal(SIGFPE, SIG_DFL);
198 signal(SIGBUS, SIG_DFL);
199 signal(SIGSEGV, SIG_DFL);
200 signal(SIGSYS, SIG_DFL);
201 signal(SIGTERM, SIG_DFL);
204 } // anonymous namespace
206 ProcessId GetCurrentProcId() {
207 return getpid();
210 ProcessHandle GetCurrentProcessHandle() {
211 return GetCurrentProcId();
214 bool OpenProcessHandle(ProcessId pid, ProcessHandle* handle) {
215 // On Posix platforms, process handles are the same as PIDs, so we
216 // don't need to do anything.
217 *handle = pid;
218 return true;
221 bool OpenPrivilegedProcessHandle(ProcessId pid, ProcessHandle* handle) {
222 // On POSIX permissions are checked for each operation on process,
223 // not when opening a "handle".
224 return OpenProcessHandle(pid, handle);
227 bool OpenProcessHandleWithAccess(ProcessId pid,
228 uint32 access_flags,
229 ProcessHandle* handle) {
230 // On POSIX permissions are checked for each operation on process,
231 // not when opening a "handle".
232 return OpenProcessHandle(pid, handle);
235 void CloseProcessHandle(ProcessHandle process) {
236 // See OpenProcessHandle, nothing to do.
237 return;
240 ProcessId GetProcId(ProcessHandle process) {
241 return process;
244 // Attempts to kill the process identified by the given process
245 // entry structure. Ignores specified exit_code; posix can't force that.
246 // Returns true if this is successful, false otherwise.
247 bool KillProcess(ProcessHandle process_id, int exit_code, bool wait) {
248 DCHECK_GT(process_id, 1) << " tried to kill invalid process_id";
249 if (process_id <= 1)
250 return false;
251 static unsigned kMaxSleepMs = 1000;
252 unsigned sleep_ms = 4;
254 bool result = kill(process_id, SIGTERM) == 0;
256 if (result && wait) {
257 int tries = 60;
259 if (RunningOnValgrind()) {
260 // Wait for some extra time when running under Valgrind since the child
261 // processes may take some time doing leak checking.
262 tries *= 2;
265 // The process may not end immediately due to pending I/O
266 bool exited = false;
267 while (tries-- > 0) {
268 pid_t pid = HANDLE_EINTR(waitpid(process_id, NULL, WNOHANG));
269 if (pid == process_id) {
270 exited = true;
271 break;
273 if (pid == -1) {
274 if (errno == ECHILD) {
275 // The wait may fail with ECHILD if another process also waited for
276 // the same pid, causing the process state to get cleaned up.
277 exited = true;
278 break;
280 DPLOG(ERROR) << "Error waiting for process " << process_id;
283 usleep(sleep_ms * 1000);
284 if (sleep_ms < kMaxSleepMs)
285 sleep_ms *= 2;
288 // If we're waiting and the child hasn't died by now, force it
289 // with a SIGKILL.
290 if (!exited)
291 result = kill(process_id, SIGKILL) == 0;
294 if (!result)
295 DPLOG(ERROR) << "Unable to terminate process " << process_id;
297 return result;
300 bool KillProcessGroup(ProcessHandle process_group_id) {
301 bool result = kill(-1 * process_group_id, SIGKILL) == 0;
302 if (!result)
303 DPLOG(ERROR) << "Unable to terminate process group " << process_group_id;
304 return result;
307 // A class to handle auto-closing of DIR*'s.
308 class ScopedDIRClose {
309 public:
310 inline void operator()(DIR* x) const {
311 if (x) {
312 closedir(x);
316 typedef scoped_ptr_malloc<DIR, ScopedDIRClose> ScopedDIR;
318 #if defined(OS_LINUX)
319 static const rlim_t kSystemDefaultMaxFds = 8192;
320 static const char kFDDir[] = "/proc/self/fd";
321 #elif defined(OS_MACOSX)
322 static const rlim_t kSystemDefaultMaxFds = 256;
323 static const char kFDDir[] = "/dev/fd";
324 #elif defined(OS_SOLARIS)
325 static const rlim_t kSystemDefaultMaxFds = 8192;
326 static const char kFDDir[] = "/dev/fd";
327 #elif defined(OS_FREEBSD)
328 static const rlim_t kSystemDefaultMaxFds = 8192;
329 static const char kFDDir[] = "/dev/fd";
330 #elif defined(OS_OPENBSD)
331 static const rlim_t kSystemDefaultMaxFds = 256;
332 static const char kFDDir[] = "/dev/fd";
333 #elif defined(OS_ANDROID)
334 static const rlim_t kSystemDefaultMaxFds = 1024;
335 static const char kFDDir[] = "/proc/self/fd";
336 #endif
338 void CloseSuperfluousFds(const base::InjectiveMultimap& saved_mapping) {
339 // DANGER: no calls to malloc are allowed from now on:
340 // http://crbug.com/36678
342 // Get the maximum number of FDs possible.
343 struct rlimit nofile;
344 rlim_t max_fds;
345 if (getrlimit(RLIMIT_NOFILE, &nofile)) {
346 // getrlimit failed. Take a best guess.
347 max_fds = kSystemDefaultMaxFds;
348 RAW_LOG(ERROR, "getrlimit(RLIMIT_NOFILE) failed");
349 } else {
350 max_fds = nofile.rlim_cur;
353 if (max_fds > INT_MAX)
354 max_fds = INT_MAX;
356 DirReaderPosix fd_dir(kFDDir);
358 if (!fd_dir.IsValid()) {
359 // Fallback case: Try every possible fd.
360 for (rlim_t i = 0; i < max_fds; ++i) {
361 const int fd = static_cast<int>(i);
362 if (fd == STDIN_FILENO || fd == STDOUT_FILENO || fd == STDERR_FILENO)
363 continue;
364 InjectiveMultimap::const_iterator j;
365 for (j = saved_mapping.begin(); j != saved_mapping.end(); j++) {
366 if (fd == j->dest)
367 break;
369 if (j != saved_mapping.end())
370 continue;
372 // Since we're just trying to close anything we can find,
373 // ignore any error return values of close().
374 ignore_result(HANDLE_EINTR(close(fd)));
376 return;
379 const int dir_fd = fd_dir.fd();
381 for ( ; fd_dir.Next(); ) {
382 // Skip . and .. entries.
383 if (fd_dir.name()[0] == '.')
384 continue;
386 char *endptr;
387 errno = 0;
388 const long int fd = strtol(fd_dir.name(), &endptr, 10);
389 if (fd_dir.name()[0] == 0 || *endptr || fd < 0 || errno)
390 continue;
391 if (fd == STDIN_FILENO || fd == STDOUT_FILENO || fd == STDERR_FILENO)
392 continue;
393 InjectiveMultimap::const_iterator i;
394 for (i = saved_mapping.begin(); i != saved_mapping.end(); i++) {
395 if (fd == i->dest)
396 break;
398 if (i != saved_mapping.end())
399 continue;
400 if (fd == dir_fd)
401 continue;
403 // When running under Valgrind, Valgrind opens several FDs for its
404 // own use and will complain if we try to close them. All of
405 // these FDs are >= |max_fds|, so we can check against that here
406 // before closing. See https://bugs.kde.org/show_bug.cgi?id=191758
407 if (fd < static_cast<int>(max_fds)) {
408 int ret = HANDLE_EINTR(close(fd));
409 DPCHECK(ret == 0);
414 char** AlterEnvironment(const environment_vector& changes,
415 const char* const* const env) {
416 unsigned count = 0;
417 unsigned size = 0;
419 // First assume that all of the current environment will be included.
420 for (unsigned i = 0; env[i]; i++) {
421 const char *const pair = env[i];
422 count++;
423 size += strlen(pair) + 1 /* terminating NUL */;
426 for (environment_vector::const_iterator
427 j = changes.begin(); j != changes.end(); j++) {
428 bool found = false;
429 const char *pair;
431 for (unsigned i = 0; env[i]; i++) {
432 pair = env[i];
433 const char *const equals = strchr(pair, '=');
434 if (!equals)
435 continue;
436 const unsigned keylen = equals - pair;
437 if (keylen == j->first.size() &&
438 memcmp(pair, j->first.data(), keylen) == 0) {
439 found = true;
440 break;
444 // if found, we'll either be deleting or replacing this element.
445 if (found) {
446 count--;
447 size -= strlen(pair) + 1;
448 if (j->second.size())
449 found = false;
452 // if !found, then we have a new element to add.
453 if (!found && !j->second.empty()) {
454 count++;
455 size += j->first.size() + 1 /* '=' */ + j->second.size() + 1 /* NUL */;
459 count++; // for the final NULL
460 uint8_t *buffer = new uint8_t[sizeof(char*) * count + size];
461 char **const ret = reinterpret_cast<char**>(buffer);
462 unsigned k = 0;
463 char *scratch = reinterpret_cast<char*>(buffer + sizeof(char*) * count);
465 for (unsigned i = 0; env[i]; i++) {
466 const char *const pair = env[i];
467 const char *const equals = strchr(pair, '=');
468 if (!equals) {
469 const unsigned len = strlen(pair);
470 ret[k++] = scratch;
471 memcpy(scratch, pair, len + 1);
472 scratch += len + 1;
473 continue;
475 const unsigned keylen = equals - pair;
476 bool handled = false;
477 for (environment_vector::const_iterator
478 j = changes.begin(); j != changes.end(); j++) {
479 if (j->first.size() == keylen &&
480 memcmp(j->first.data(), pair, keylen) == 0) {
481 if (!j->second.empty()) {
482 ret[k++] = scratch;
483 memcpy(scratch, pair, keylen + 1);
484 scratch += keylen + 1;
485 memcpy(scratch, j->second.c_str(), j->second.size() + 1);
486 scratch += j->second.size() + 1;
488 handled = true;
489 break;
493 if (!handled) {
494 const unsigned len = strlen(pair);
495 ret[k++] = scratch;
496 memcpy(scratch, pair, len + 1);
497 scratch += len + 1;
501 // Now handle new elements
502 for (environment_vector::const_iterator
503 j = changes.begin(); j != changes.end(); j++) {
504 if (j->second.empty())
505 continue;
507 bool found = false;
508 for (unsigned i = 0; env[i]; i++) {
509 const char *const pair = env[i];
510 const char *const equals = strchr(pair, '=');
511 if (!equals)
512 continue;
513 const unsigned keylen = equals - pair;
514 if (keylen == j->first.size() &&
515 memcmp(pair, j->first.data(), keylen) == 0) {
516 found = true;
517 break;
521 if (!found) {
522 ret[k++] = scratch;
523 memcpy(scratch, j->first.data(), j->first.size());
524 scratch += j->first.size();
525 *scratch++ = '=';
526 memcpy(scratch, j->second.c_str(), j->second.size() + 1);
527 scratch += j->second.size() + 1;
531 ret[k] = NULL;
532 return ret;
535 bool LaunchProcess(const std::vector<std::string>& argv,
536 const LaunchOptions& options,
537 ProcessHandle* process_handle) {
538 size_t fd_shuffle_size = 0;
539 if (options.fds_to_remap) {
540 fd_shuffle_size = options.fds_to_remap->size();
543 #if defined(OS_MACOSX)
544 if (options.synchronize) {
545 // When synchronizing, the "read" end of the synchronization pipe needs
546 // to make it to the child process. This is handled by mapping it back to
547 // itself.
548 ++fd_shuffle_size;
550 #endif // defined(OS_MACOSX)
552 InjectiveMultimap fd_shuffle1;
553 InjectiveMultimap fd_shuffle2;
554 fd_shuffle1.reserve(fd_shuffle_size);
555 fd_shuffle2.reserve(fd_shuffle_size);
557 scoped_array<char*> argv_cstr(new char*[argv.size() + 1]);
558 scoped_array<char*> new_environ;
559 if (options.environ)
560 new_environ.reset(AlterEnvironment(*options.environ, GetEnvironment()));
562 #if defined(OS_MACOSX)
563 int synchronization_pipe_fds[2];
564 file_util::ScopedFD synchronization_read_fd;
565 file_util::ScopedFD synchronization_write_fd;
567 if (options.synchronize) {
568 // wait means "don't return from LaunchProcess until the child exits", and
569 // synchronize means "return from LaunchProcess but don't let the child
570 // run until LaunchSynchronize is called". These two options are highly
571 // incompatible.
572 DCHECK(!options.wait);
574 // Create the pipe used for synchronization.
575 if (HANDLE_EINTR(pipe(synchronization_pipe_fds)) != 0) {
576 DPLOG(ERROR) << "pipe";
577 return false;
580 // The parent process will only use synchronization_write_fd as the write
581 // side of the pipe. It can close the read side as soon as the child
582 // process has forked off. The child process will only use
583 // synchronization_read_fd as the read side of the pipe. In that process,
584 // the write side can be closed as soon as it has forked.
585 synchronization_read_fd.reset(&synchronization_pipe_fds[0]);
586 synchronization_write_fd.reset(&synchronization_pipe_fds[1]);
588 #endif // OS_MACOSX
590 pid_t pid;
591 #if defined(OS_LINUX)
592 if (options.clone_flags) {
593 pid = syscall(__NR_clone, options.clone_flags, 0, 0, 0);
594 } else
595 #endif
597 pid = fork();
600 if (pid < 0) {
601 DPLOG(ERROR) << "fork";
602 return false;
603 } else if (pid == 0) {
604 // Child process
606 // DANGER: fork() rule: in the child, if you don't end up doing exec*(),
607 // you call _exit() instead of exit(). This is because _exit() does not
608 // call any previously-registered (in the parent) exit handlers, which
609 // might do things like block waiting for threads that don't even exist
610 // in the child.
612 // If a child process uses the readline library, the process block forever.
613 // In BSD like OSes including OS X it is safe to assign /dev/null as stdin.
614 // See http://crbug.com/56596.
615 int null_fd = HANDLE_EINTR(open("/dev/null", O_RDONLY));
616 if (null_fd < 0) {
617 RAW_LOG(ERROR, "Failed to open /dev/null");
618 _exit(127);
621 file_util::ScopedFD null_fd_closer(&null_fd);
622 int new_fd = HANDLE_EINTR(dup2(null_fd, STDIN_FILENO));
623 if (new_fd != STDIN_FILENO) {
624 RAW_LOG(ERROR, "Failed to dup /dev/null for stdin");
625 _exit(127);
628 if (options.new_process_group) {
629 // Instead of inheriting the process group ID of the parent, the child
630 // starts off a new process group with pgid equal to its process ID.
631 if (setpgid(0, 0) < 0) {
632 RAW_LOG(ERROR, "setpgid failed");
633 _exit(127);
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();
642 ++resource) {
643 struct rlimit limit;
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)
668 #if 0
669 // When debugging it can be helpful to check that we really aren't making
670 // any hidden calls to malloc.
671 void *malloc_thunk =
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);
675 #endif // 0
677 // DANGER: no calls to malloc are allowed from now on:
678 // http://crbug.com/36678
680 if (options.fds_to_remap) {
681 for (file_handle_mapping_vector::const_iterator
682 it = options.fds_to_remap->begin();
683 it != options.fds_to_remap->end(); ++it) {
684 fd_shuffle1.push_back(InjectionArc(it->first, it->second, false));
685 fd_shuffle2.push_back(InjectionArc(it->first, it->second, false));
689 #if defined(OS_MACOSX)
690 if (options.synchronize) {
691 // Remap the read side of the synchronization pipe back onto itself,
692 // ensuring that it won't be closed by CloseSuperfluousFds.
693 int keep_fd = *synchronization_read_fd.get();
694 fd_shuffle1.push_back(InjectionArc(keep_fd, keep_fd, false));
695 fd_shuffle2.push_back(InjectionArc(keep_fd, keep_fd, false));
697 #endif // defined(OS_MACOSX)
699 if (options.environ)
700 SetEnvironment(new_environ.get());
702 // fd_shuffle1 is mutated by this call because it cannot malloc.
703 if (!ShuffleFileDescriptors(&fd_shuffle1))
704 _exit(127);
706 CloseSuperfluousFds(fd_shuffle2);
708 #if defined(OS_MACOSX)
709 if (options.synchronize) {
710 // Do a blocking read to wait until the parent says it's OK to proceed.
711 // The byte that's read here is written by LaunchSynchronize.
712 char read_char;
713 int read_result =
714 HANDLE_EINTR(read(*synchronization_read_fd.get(), &read_char, 1));
715 if (read_result != 1) {
716 RAW_LOG(ERROR, "LaunchProcess: synchronization read: error");
717 _exit(127);
720 // The pipe is no longer useful. Don't let it live on in the new process
721 // after exec.
722 synchronization_read_fd.reset(); // closes synchronization_pipe_fds[0]
724 #endif // defined(OS_MACOSX)
726 for (size_t i = 0; i < argv.size(); i++)
727 argv_cstr[i] = const_cast<char*>(argv[i].c_str());
728 argv_cstr[argv.size()] = NULL;
729 execvp(argv_cstr[0], argv_cstr.get());
731 RAW_LOG(ERROR, "LaunchProcess: failed to execvp:");
732 RAW_LOG(ERROR, argv_cstr[0]);
733 _exit(127);
734 } else {
735 // Parent process
736 if (options.wait) {
737 // While this isn't strictly disk IO, waiting for another process to
738 // finish is the sort of thing ThreadRestrictions is trying to prevent.
739 base::ThreadRestrictions::AssertIOAllowed();
740 pid_t ret = HANDLE_EINTR(waitpid(pid, 0, 0));
741 DPCHECK(ret > 0);
744 if (process_handle)
745 *process_handle = pid;
747 #if defined(OS_MACOSX)
748 if (options.synchronize) {
749 // The "read" side of the synchronization pipe belongs to the child.
750 synchronization_read_fd.reset(); // closes synchronization_pipe_fds[0]
751 *options.synchronize = new int(*synchronization_write_fd.release());
753 #endif // defined(OS_MACOSX)
756 return true;
760 bool LaunchProcess(const CommandLine& cmdline,
761 const LaunchOptions& options,
762 ProcessHandle* process_handle) {
763 return LaunchProcess(cmdline.argv(), options, process_handle);
766 #if defined(OS_MACOSX)
767 void LaunchSynchronize(LaunchSynchronizationHandle handle) {
768 int synchronization_fd = *handle;
769 file_util::ScopedFD synchronization_fd_closer(&synchronization_fd);
770 delete handle;
772 // Write a '\0' character to the pipe.
773 if (HANDLE_EINTR(write(synchronization_fd, "", 1)) != 1) {
774 DPLOG(ERROR) << "write";
777 #endif // defined(OS_MACOSX)
779 ProcessMetrics::~ProcessMetrics() { }
781 bool EnableInProcessStackDumping() {
782 // When running in an application, our code typically expects SIGPIPE
783 // to be ignored. Therefore, when testing that same code, it should run
784 // with SIGPIPE ignored as well.
785 struct sigaction action;
786 action.sa_handler = SIG_IGN;
787 action.sa_flags = 0;
788 sigemptyset(&action.sa_mask);
789 bool success = (sigaction(SIGPIPE, &action, NULL) == 0);
791 // Android has built-in crash handling, so no need to hook the signals.
792 #if !defined(OS_ANDROID)
793 sig_t handler = reinterpret_cast<sig_t>(&StackDumpSignalHandler);
794 success &= (signal(SIGILL, handler) != SIG_ERR);
795 success &= (signal(SIGABRT, handler) != SIG_ERR);
796 success &= (signal(SIGFPE, handler) != SIG_ERR);
797 success &= (signal(SIGBUS, handler) != SIG_ERR);
798 success &= (signal(SIGSEGV, handler) != SIG_ERR);
799 success &= (signal(SIGSYS, handler) != SIG_ERR);
800 #endif
802 return success;
805 void RaiseProcessToHighPriority() {
806 // On POSIX, we don't actually do anything here. We could try to nice() or
807 // setpriority() or sched_getscheduler, but these all require extra rights.
810 TerminationStatus GetTerminationStatus(ProcessHandle handle, int* exit_code) {
811 int status = 0;
812 const pid_t result = HANDLE_EINTR(waitpid(handle, &status, WNOHANG));
813 if (result == -1) {
814 DPLOG(ERROR) << "waitpid(" << handle << ")";
815 if (exit_code)
816 *exit_code = 0;
817 return TERMINATION_STATUS_NORMAL_TERMINATION;
818 } else if (result == 0) {
819 // the child hasn't exited yet.
820 if (exit_code)
821 *exit_code = 0;
822 return TERMINATION_STATUS_STILL_RUNNING;
825 if (exit_code)
826 *exit_code = status;
828 if (WIFSIGNALED(status)) {
829 switch (WTERMSIG(status)) {
830 case SIGABRT:
831 case SIGBUS:
832 case SIGFPE:
833 case SIGILL:
834 case SIGSEGV:
835 return TERMINATION_STATUS_PROCESS_CRASHED;
836 case SIGINT:
837 case SIGKILL:
838 case SIGTERM:
839 return TERMINATION_STATUS_PROCESS_WAS_KILLED;
840 default:
841 break;
845 if (WIFEXITED(status) && WEXITSTATUS(status) != 0)
846 return TERMINATION_STATUS_ABNORMAL_TERMINATION;
848 return TERMINATION_STATUS_NORMAL_TERMINATION;
851 bool WaitForExitCode(ProcessHandle handle, int* exit_code) {
852 int status;
853 if (HANDLE_EINTR(waitpid(handle, &status, 0)) == -1) {
854 NOTREACHED();
855 return false;
858 if (WIFEXITED(status)) {
859 *exit_code = WEXITSTATUS(status);
860 return true;
863 // If it didn't exit cleanly, it must have been signaled.
864 DCHECK(WIFSIGNALED(status));
865 return false;
868 bool WaitForExitCodeWithTimeout(ProcessHandle handle, int* exit_code,
869 int64 timeout_milliseconds) {
870 bool waitpid_success = false;
871 int status = WaitpidWithTimeout(handle, timeout_milliseconds,
872 &waitpid_success);
873 if (status == -1)
874 return false;
875 if (!waitpid_success)
876 return false;
877 if (WIFSIGNALED(status)) {
878 *exit_code = -1;
879 return true;
881 if (WIFEXITED(status)) {
882 *exit_code = WEXITSTATUS(status);
883 return true;
885 return false;
888 #if defined(OS_MACOSX)
889 // Using kqueue on Mac so that we can wait on non-child processes.
890 // We can't use kqueues on child processes because we need to reap
891 // our own children using wait.
892 static bool WaitForSingleNonChildProcess(ProcessHandle handle,
893 int64 wait_milliseconds) {
894 DCHECK_GT(handle, 0);
895 DCHECK(wait_milliseconds == base::kNoTimeout || wait_milliseconds > 0);
897 int kq = kqueue();
898 if (kq == -1) {
899 DPLOG(ERROR) << "kqueue";
900 return false;
902 file_util::ScopedFD kq_closer(&kq);
904 struct kevent change = {0};
905 EV_SET(&change, handle, EVFILT_PROC, EV_ADD, NOTE_EXIT, 0, NULL);
906 int result = HANDLE_EINTR(kevent(kq, &change, 1, NULL, 0, NULL));
907 if (result == -1) {
908 if (errno == ESRCH) {
909 // If the process wasn't found, it must be dead.
910 return true;
913 DPLOG(ERROR) << "kevent (setup " << handle << ")";
914 return false;
917 // Keep track of the elapsed time to be able to restart kevent if it's
918 // interrupted.
919 bool wait_forever = wait_milliseconds == base::kNoTimeout;
920 base::TimeDelta remaining_delta;
921 base::Time deadline;
922 if (!wait_forever) {
923 remaining_delta = base::TimeDelta::FromMilliseconds(wait_milliseconds);
924 deadline = base::Time::Now() + remaining_delta;
927 result = -1;
928 struct kevent event = {0};
930 while (wait_forever || remaining_delta.InMilliseconds() > 0) {
931 struct timespec remaining_timespec;
932 struct timespec* remaining_timespec_ptr;
933 if (wait_forever) {
934 remaining_timespec_ptr = NULL;
935 } else {
936 remaining_timespec = remaining_delta.ToTimeSpec();
937 remaining_timespec_ptr = &remaining_timespec;
940 result = kevent(kq, NULL, 0, &event, 1, remaining_timespec_ptr);
942 if (result == -1 && errno == EINTR) {
943 if (!wait_forever) {
944 remaining_delta = deadline - base::Time::Now();
946 result = 0;
947 } else {
948 break;
952 if (result < 0) {
953 DPLOG(ERROR) << "kevent (wait " << handle << ")";
954 return false;
955 } else if (result > 1) {
956 DLOG(ERROR) << "kevent (wait " << handle << "): unexpected result "
957 << result;
958 return false;
959 } else if (result == 0) {
960 // Timed out.
961 return false;
964 DCHECK_EQ(result, 1);
966 if (event.filter != EVFILT_PROC ||
967 (event.fflags & NOTE_EXIT) == 0 ||
968 event.ident != static_cast<uintptr_t>(handle)) {
969 DLOG(ERROR) << "kevent (wait " << handle
970 << "): unexpected event: filter=" << event.filter
971 << ", fflags=" << event.fflags
972 << ", ident=" << event.ident;
973 return false;
976 return true;
978 #endif // OS_MACOSX
980 bool WaitForSingleProcess(ProcessHandle handle, int64 wait_milliseconds) {
981 ProcessHandle parent_pid = GetParentProcessId(handle);
982 ProcessHandle our_pid = Process::Current().handle();
983 if (parent_pid != our_pid) {
984 #if defined(OS_MACOSX)
985 // On Mac we can wait on non child processes.
986 return WaitForSingleNonChildProcess(handle, wait_milliseconds);
987 #else
988 // Currently on Linux we can't handle non child processes.
989 NOTIMPLEMENTED();
990 #endif // OS_MACOSX
993 bool waitpid_success;
994 int status = -1;
995 if (wait_milliseconds == base::kNoTimeout)
996 waitpid_success = (HANDLE_EINTR(waitpid(handle, &status, 0)) != -1);
997 else
998 status = WaitpidWithTimeout(handle, wait_milliseconds, &waitpid_success);
1000 if (status != -1) {
1001 DCHECK(waitpid_success);
1002 return WIFEXITED(status);
1003 } else {
1004 return false;
1008 int64 TimeValToMicroseconds(const struct timeval& tv) {
1009 static const int kMicrosecondsPerSecond = 1000000;
1010 int64 ret = tv.tv_sec; // Avoid (int * int) integer overflow.
1011 ret *= kMicrosecondsPerSecond;
1012 ret += tv.tv_usec;
1013 return ret;
1016 // Return value used by GetAppOutputInternal to encapsulate the various exit
1017 // scenarios from the function.
1018 enum GetAppOutputInternalResult {
1019 EXECUTE_FAILURE,
1020 EXECUTE_SUCCESS,
1021 GOT_MAX_OUTPUT,
1024 // Executes the application specified by |cl| and wait for it to exit. Stores
1025 // the output (stdout) in |output|. If |do_search_path| is set, it searches the
1026 // path for the application; in that case, |envp| must be null, and it will use
1027 // the current environment. If |do_search_path| is false, |cl| should fully
1028 // specify the path of the application, and |envp| will be used as the
1029 // environment. Redirects stderr to /dev/null.
1030 // If we successfully start the application and get all requested output, we
1031 // return GOT_MAX_OUTPUT, or if there is a problem starting or exiting
1032 // the application we return RUN_FAILURE. Otherwise we return EXECUTE_SUCCESS.
1033 // The GOT_MAX_OUTPUT return value exists so a caller that asks for limited
1034 // output can treat this as a success, despite having an exit code of SIG_PIPE
1035 // due to us closing the output pipe.
1036 // In the case of EXECUTE_SUCCESS, the application exit code will be returned
1037 // in |*exit_code|, which should be checked to determine if the application
1038 // ran successfully.
1039 static GetAppOutputInternalResult GetAppOutputInternal(const CommandLine& cl,
1040 char* const envp[],
1041 std::string* output,
1042 size_t max_output,
1043 bool do_search_path,
1044 int* exit_code) {
1045 // Doing a blocking wait for another command to finish counts as IO.
1046 base::ThreadRestrictions::AssertIOAllowed();
1047 // exit_code must be supplied so calling function can determine success.
1048 DCHECK(exit_code);
1049 *exit_code = EXIT_FAILURE;
1051 int pipe_fd[2];
1052 pid_t pid;
1053 InjectiveMultimap fd_shuffle1, fd_shuffle2;
1054 const std::vector<std::string>& argv = cl.argv();
1055 scoped_array<char*> argv_cstr(new char*[argv.size() + 1]);
1057 fd_shuffle1.reserve(3);
1058 fd_shuffle2.reserve(3);
1060 // Either |do_search_path| should be false or |envp| should be null, but not
1061 // both.
1062 DCHECK(!do_search_path ^ !envp);
1064 if (pipe(pipe_fd) < 0)
1065 return EXECUTE_FAILURE;
1067 switch (pid = fork()) {
1068 case -1: // error
1069 close(pipe_fd[0]);
1070 close(pipe_fd[1]);
1071 return EXECUTE_FAILURE;
1072 case 0: // child
1074 #if defined(OS_MACOSX)
1075 RestoreDefaultExceptionHandler();
1076 #endif
1077 // DANGER: no calls to malloc are allowed from now on:
1078 // http://crbug.com/36678
1080 // Obscure fork() rule: in the child, if you don't end up doing exec*(),
1081 // you call _exit() instead of exit(). This is because _exit() does not
1082 // call any previously-registered (in the parent) exit handlers, which
1083 // might do things like block waiting for threads that don't even exist
1084 // in the child.
1085 int dev_null = open("/dev/null", O_WRONLY);
1086 if (dev_null < 0)
1087 _exit(127);
1089 fd_shuffle1.push_back(InjectionArc(pipe_fd[1], STDOUT_FILENO, true));
1090 fd_shuffle1.push_back(InjectionArc(dev_null, STDERR_FILENO, true));
1091 fd_shuffle1.push_back(InjectionArc(dev_null, STDIN_FILENO, true));
1092 // Adding another element here? Remeber to increase the argument to
1093 // reserve(), above.
1095 std::copy(fd_shuffle1.begin(), fd_shuffle1.end(),
1096 std::back_inserter(fd_shuffle2));
1098 if (!ShuffleFileDescriptors(&fd_shuffle1))
1099 _exit(127);
1101 CloseSuperfluousFds(fd_shuffle2);
1103 for (size_t i = 0; i < argv.size(); i++)
1104 argv_cstr[i] = const_cast<char*>(argv[i].c_str());
1105 argv_cstr[argv.size()] = NULL;
1106 if (do_search_path)
1107 execvp(argv_cstr[0], argv_cstr.get());
1108 else
1109 execve(argv_cstr[0], argv_cstr.get(), envp);
1110 _exit(127);
1112 default: // parent
1114 // Close our writing end of pipe now. Otherwise later read would not
1115 // be able to detect end of child's output (in theory we could still
1116 // write to the pipe).
1117 close(pipe_fd[1]);
1119 output->clear();
1120 char buffer[256];
1121 size_t output_buf_left = max_output;
1122 ssize_t bytes_read = 1; // A lie to properly handle |max_output == 0|
1123 // case in the logic below.
1125 while (output_buf_left > 0) {
1126 bytes_read = HANDLE_EINTR(read(pipe_fd[0], buffer,
1127 std::min(output_buf_left, sizeof(buffer))));
1128 if (bytes_read <= 0)
1129 break;
1130 output->append(buffer, bytes_read);
1131 output_buf_left -= static_cast<size_t>(bytes_read);
1133 close(pipe_fd[0]);
1135 // Always wait for exit code (even if we know we'll declare
1136 // GOT_MAX_OUTPUT).
1137 bool success = WaitForExitCode(pid, exit_code);
1139 // If we stopped because we read as much as we wanted, we return
1140 // GOT_MAX_OUTPUT (because the child may exit due to |SIGPIPE|).
1141 if (!output_buf_left && bytes_read > 0)
1142 return GOT_MAX_OUTPUT;
1143 else if (success)
1144 return EXECUTE_SUCCESS;
1145 return EXECUTE_FAILURE;
1150 bool GetAppOutput(const CommandLine& cl, std::string* output) {
1151 // Run |execve()| with the current environment and store "unlimited" data.
1152 int exit_code;
1153 GetAppOutputInternalResult result = GetAppOutputInternal(
1154 cl, NULL, output, std::numeric_limits<std::size_t>::max(), true,
1155 &exit_code);
1156 return result == EXECUTE_SUCCESS && exit_code == EXIT_SUCCESS;
1159 // TODO(viettrungluu): Conceivably, we should have a timeout as well, so we
1160 // don't hang if what we're calling hangs.
1161 bool GetAppOutputRestricted(const CommandLine& cl,
1162 std::string* output, size_t max_output) {
1163 // Run |execve()| with the empty environment.
1164 char* const empty_environ = NULL;
1165 int exit_code;
1166 GetAppOutputInternalResult result = GetAppOutputInternal(cl, &empty_environ,
1167 output, max_output,
1168 false, &exit_code);
1169 return result == GOT_MAX_OUTPUT || (result == EXECUTE_SUCCESS &&
1170 exit_code == EXIT_SUCCESS);
1173 bool GetAppOutputWithExitCode(const CommandLine& cl,
1174 std::string* output,
1175 int* exit_code) {
1176 // Run |execve()| with the current environment and store "unlimited" data.
1177 GetAppOutputInternalResult result = GetAppOutputInternal(
1178 cl, NULL, output, std::numeric_limits<std::size_t>::max(), true,
1179 exit_code);
1180 return result == EXECUTE_SUCCESS;
1183 bool WaitForProcessesToExit(const FilePath::StringType& executable_name,
1184 int64 wait_milliseconds,
1185 const ProcessFilter* filter) {
1186 bool result = false;
1188 // TODO(port): This is inefficient, but works if there are multiple procs.
1189 // TODO(port): use waitpid to avoid leaving zombies around
1191 base::Time end_time = base::Time::Now() +
1192 base::TimeDelta::FromMilliseconds(wait_milliseconds);
1193 do {
1194 NamedProcessIterator iter(executable_name, filter);
1195 if (!iter.NextProcessEntry()) {
1196 result = true;
1197 break;
1199 base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(100));
1200 } while ((end_time - base::Time::Now()) > base::TimeDelta());
1202 return result;
1205 bool CleanupProcesses(const FilePath::StringType& executable_name,
1206 int64 wait_milliseconds,
1207 int exit_code,
1208 const ProcessFilter* filter) {
1209 bool exited_cleanly =
1210 WaitForProcessesToExit(executable_name, wait_milliseconds,
1211 filter);
1212 if (!exited_cleanly)
1213 KillProcesses(executable_name, exit_code, filter);
1214 return exited_cleanly;
1217 #if !defined(OS_MACOSX)
1219 namespace {
1221 // Return true if the given child is dead. This will also reap the process.
1222 // Doesn't block.
1223 static bool IsChildDead(pid_t child) {
1224 const pid_t result = HANDLE_EINTR(waitpid(child, NULL, WNOHANG));
1225 if (result == -1) {
1226 DPLOG(ERROR) << "waitpid(" << child << ")";
1227 NOTREACHED();
1228 } else if (result > 0) {
1229 // The child has died.
1230 return true;
1233 return false;
1236 // A thread class which waits for the given child to exit and reaps it.
1237 // If the child doesn't exit within a couple of seconds, kill it.
1238 class BackgroundReaper : public PlatformThread::Delegate {
1239 public:
1240 BackgroundReaper(pid_t child, unsigned timeout)
1241 : child_(child),
1242 timeout_(timeout) {
1245 void ThreadMain() {
1246 WaitForChildToDie();
1247 delete this;
1250 void WaitForChildToDie() {
1251 // Wait forever case.
1252 if (timeout_ == 0) {
1253 pid_t r = HANDLE_EINTR(waitpid(child_, NULL, 0));
1254 if (r != child_) {
1255 DPLOG(ERROR) << "While waiting for " << child_
1256 << " to terminate, we got the following result: " << r;
1258 return;
1261 // There's no good way to wait for a specific child to exit in a timed
1262 // fashion. (No kqueue on Linux), so we just loop and sleep.
1264 // Wait for 2 * timeout_ 500 milliseconds intervals.
1265 for (unsigned i = 0; i < 2 * timeout_; ++i) {
1266 PlatformThread::Sleep(TimeDelta::FromMilliseconds(500));
1267 if (IsChildDead(child_))
1268 return;
1271 if (kill(child_, SIGKILL) == 0) {
1272 // SIGKILL is uncatchable. Since the signal was delivered, we can
1273 // just wait for the process to die now in a blocking manner.
1274 if (HANDLE_EINTR(waitpid(child_, NULL, 0)) < 0)
1275 DPLOG(WARNING) << "waitpid";
1276 } else {
1277 DLOG(ERROR) << "While waiting for " << child_ << " to terminate we"
1278 << " failed to deliver a SIGKILL signal (" << errno << ").";
1282 private:
1283 const pid_t child_;
1284 // Number of seconds to wait, if 0 then wait forever and do not attempt to
1285 // kill |child_|.
1286 const unsigned timeout_;
1288 DISALLOW_COPY_AND_ASSIGN(BackgroundReaper);
1291 } // namespace
1293 void EnsureProcessTerminated(ProcessHandle process) {
1294 // If the child is already dead, then there's nothing to do.
1295 if (IsChildDead(process))
1296 return;
1298 const unsigned timeout = 2; // seconds
1299 BackgroundReaper* reaper = new BackgroundReaper(process, timeout);
1300 PlatformThread::CreateNonJoinable(0, reaper);
1303 void EnsureProcessGetsReaped(ProcessHandle process) {
1304 // If the child is already dead, then there's nothing to do.
1305 if (IsChildDead(process))
1306 return;
1308 BackgroundReaper* reaper = new BackgroundReaper(process, 0);
1309 PlatformThread::CreateNonJoinable(0, reaper);
1312 #endif // !defined(OS_MACOSX)
1314 } // namespace base