Adding owners for third_party
[chromium-blink-merge.git] / base / process_util_posix.cc
blobbc4c08ee5211cd79c8d67b58b762d63f04f822f7
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include <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 <iterator>
17 #include <limits>
18 #include <set>
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>
39 #endif
41 #if defined(OS_FREEBSD)
42 #include <sys/event.h>
43 #include <sys/ucontext.h>
44 #endif
46 #if defined(OS_MACOSX)
47 #include <crt_externs.h>
48 #include <sys/event.h>
49 #else
50 extern char** environ;
51 #endif
53 namespace base {
55 namespace {
57 // Get the process's "environment" (i.e. the thing that setenv/getenv
58 // work with).
59 char** GetEnvironment() {
60 #if defined(OS_MACOSX)
61 return *_NSGetEnviron();
62 #else
63 return environ;
64 #endif
67 // Set the process's "environment" (i.e. the thing that setenv/getenv
68 // work with).
69 void SetEnvironment(char** env) {
70 #if defined(OS_MACOSX)
71 *_NSGetEnviron() = env;
72 #else
73 environ = env;
74 #endif
77 int WaitpidWithTimeout(ProcessHandle handle, int64 wait_milliseconds,
78 bool* success) {
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.
102 int status = -1;
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 TimeTicks wakeup_time = TimeTicks::Now() +
110 TimeDelta::FromMilliseconds(wait_milliseconds);
111 while (ret_pid == 0) {
112 TimeTicks now = TimeTicks::Now();
113 if (now > wakeup_time)
114 break;
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
122 // such as SIGCHLD.
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;
132 if (success)
133 *success = (ret_pid != -1);
135 return status;
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,
156 bool can_block,
157 int* exit_code) {
158 int status = 0;
159 const pid_t result = HANDLE_EINTR(waitpid(handle, &status,
160 can_block ? 0 : WNOHANG));
161 if (result == -1) {
162 DPLOG(ERROR) << "waitpid(" << handle << ")";
163 if (exit_code)
164 *exit_code = 0;
165 return TERMINATION_STATUS_NORMAL_TERMINATION;
166 } else if (result == 0) {
167 // the child hasn't exited yet.
168 if (exit_code)
169 *exit_code = 0;
170 return TERMINATION_STATUS_STILL_RUNNING;
173 if (exit_code)
174 *exit_code = status;
176 if (WIFSIGNALED(status)) {
177 switch (WTERMSIG(status)) {
178 case SIGABRT:
179 case SIGBUS:
180 case SIGFPE:
181 case SIGILL:
182 case SIGSEGV:
183 return TERMINATION_STATUS_PROCESS_CRASHED;
184 case SIGINT:
185 case SIGKILL:
186 case SIGTERM:
187 return TERMINATION_STATUS_PROCESS_WAS_KILLED;
188 default:
189 break;
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() {
202 return getpid();
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.
212 *handle = pid;
213 return true;
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,
223 uint32 access_flags,
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.
232 return;
235 ProcessId GetProcId(ProcessHandle process) {
236 return 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";
244 if (process_id <= 1)
245 return false;
246 bool result = kill(process_id, SIGTERM) == 0;
247 if (result && wait) {
248 int tries = 60;
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.
253 tries *= 2;
256 unsigned sleep_ms = 4;
258 // The process may not end immediately due to pending I/O
259 bool exited = false;
260 while (tries-- > 0) {
261 pid_t pid = HANDLE_EINTR(waitpid(process_id, NULL, WNOHANG));
262 if (pid == process_id) {
263 exited = true;
264 break;
266 if (pid == -1) {
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.
270 exited = true;
271 break;
273 DPLOG(ERROR) << "Error waiting for process " << process_id;
276 usleep(sleep_ms * 1000);
277 const unsigned kMaxSleepMs = 1000;
278 if (sleep_ms < kMaxSleepMs)
279 sleep_ms *= 2;
282 // If we're waiting and the child hasn't died by now, force it
283 // with a SIGKILL.
284 if (!exited)
285 result = kill(process_id, SIGKILL) == 0;
288 if (!result)
289 DPLOG(ERROR) << "Unable to terminate process " << process_id;
291 return result;
294 bool KillProcessGroup(ProcessHandle process_group_id) {
295 bool result = kill(-1 * process_group_id, SIGKILL) == 0;
296 if (!result)
297 DPLOG(ERROR) << "Unable to terminate process group " << process_group_id;
298 return result;
301 // A class to handle auto-closing of DIR*'s.
302 class ScopedDIRClose {
303 public:
304 inline void operator()(DIR* x) const {
305 if (x) {
306 closedir(x);
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";
330 #endif
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;
338 rlim_t max_fds;
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");
343 } else {
344 max_fds = nofile.rlim_cur;
347 if (max_fds > INT_MAX)
348 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)
357 continue;
358 InjectiveMultimap::const_iterator j;
359 for (j = saved_mapping.begin(); j != saved_mapping.end(); j++) {
360 if (fd == j->dest)
361 break;
363 if (j != saved_mapping.end())
364 continue;
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)));
370 return;
373 const int dir_fd = fd_dir.fd();
375 for ( ; fd_dir.Next(); ) {
376 // Skip . and .. entries.
377 if (fd_dir.name()[0] == '.')
378 continue;
380 char *endptr;
381 errno = 0;
382 const long int fd = strtol(fd_dir.name(), &endptr, 10);
383 if (fd_dir.name()[0] == 0 || *endptr || fd < 0 || errno)
384 continue;
385 if (fd == STDIN_FILENO || fd == STDOUT_FILENO || fd == STDERR_FILENO)
386 continue;
387 InjectiveMultimap::const_iterator i;
388 for (i = saved_mapping.begin(); i != saved_mapping.end(); i++) {
389 if (fd == i->dest)
390 break;
392 if (i != saved_mapping.end())
393 continue;
394 if (fd == dir_fd)
395 continue;
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));
403 DPCHECK(ret == 0);
408 char** AlterEnvironment(const EnvironmentVector& changes,
409 const char* const* const env) {
410 unsigned count = 0;
411 unsigned size = 0;
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];
416 count++;
417 size += strlen(pair) + 1 /* terminating NUL */;
420 for (EnvironmentVector::const_iterator j = changes.begin();
421 j != changes.end();
422 ++j) {
423 bool found = false;
424 const char *pair;
426 for (unsigned i = 0; env[i]; i++) {
427 pair = env[i];
428 const char *const equals = strchr(pair, '=');
429 if (!equals)
430 continue;
431 const unsigned keylen = equals - pair;
432 if (keylen == j->first.size() &&
433 memcmp(pair, j->first.data(), keylen) == 0) {
434 found = true;
435 break;
439 // if found, we'll either be deleting or replacing this element.
440 if (found) {
441 count--;
442 size -= strlen(pair) + 1;
443 if (j->second.size())
444 found = false;
447 // if !found, then we have a new element to add.
448 if (!found && !j->second.empty()) {
449 count++;
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);
457 unsigned k = 0;
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, '=');
463 if (!equals) {
464 const unsigned len = strlen(pair);
465 ret[k++] = scratch;
466 memcpy(scratch, pair, len + 1);
467 scratch += len + 1;
468 continue;
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()) {
477 ret[k++] = scratch;
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;
483 handled = true;
484 break;
488 if (!handled) {
489 const unsigned len = strlen(pair);
490 ret[k++] = scratch;
491 memcpy(scratch, pair, len + 1);
492 scratch += 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())
500 continue;
502 bool found = false;
503 for (unsigned i = 0; env[i]; i++) {
504 const char *const pair = env[i];
505 const char *const equals = strchr(pair, '=');
506 if (!equals)
507 continue;
508 const unsigned keylen = equals - pair;
509 if (keylen == j->first.size() &&
510 memcmp(pair, j->first.data(), keylen) == 0) {
511 found = true;
512 break;
516 if (!found) {
517 ret[k++] = scratch;
518 memcpy(scratch, j->first.data(), j->first.size());
519 scratch += j->first.size();
520 *scratch++ = '=';
521 memcpy(scratch, j->second.c_str(), j->second.size() + 1);
522 scratch += j->second.size() + 1;
526 ret[k] = NULL;
527 return ret;
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
542 // itself.
543 ++fd_shuffle_size;
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_ptr<char*[]> argv_cstr(new char*[argv.size() + 1]);
553 scoped_ptr<char*[]> new_environ;
554 if (options.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
566 // incompatible.
567 DCHECK(!options.wait);
569 // Create the pipe used for synchronization.
570 if (HANDLE_EINTR(pipe(synchronization_pipe_fds)) != 0) {
571 DPLOG(ERROR) << "pipe";
572 return false;
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]);
583 #endif // OS_MACOSX
585 pid_t pid;
586 #if defined(OS_LINUX)
587 if (options.clone_flags) {
588 pid = syscall(__NR_clone, options.clone_flags, 0, 0, 0);
589 } else
590 #endif
592 pid = fork();
595 if (pid < 0) {
596 DPLOG(ERROR) << "fork";
597 return false;
598 } else if (pid == 0) {
599 // Child process
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
605 // in the child.
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));
611 if (null_fd < 0) {
612 RAW_LOG(ERROR, "Failed to open /dev/null");
613 _exit(127);
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");
620 _exit(127);
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");
628 _exit(127);
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();
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 defined(OS_CHROMEOS)
681 if (options.ctrl_terminal_fd >= 0) {
682 // Set process' controlling terminal.
683 if (HANDLE_EINTR(setsid()) != -1) {
684 if (HANDLE_EINTR(
685 ioctl(options.ctrl_terminal_fd, TIOCSCTTY, NULL)) == -1) {
686 RAW_LOG(WARNING, "ioctl(TIOCSCTTY), ctrl terminal not set");
688 } else {
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)
713 if (options.environ)
714 SetEnvironment(new_environ.get());
716 // fd_shuffle1 is mutated by this call because it cannot malloc.
717 if (!ShuffleFileDescriptors(&fd_shuffle1))
718 _exit(127);
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.
726 char read_char;
727 int read_result =
728 HANDLE_EINTR(read(*synchronization_read_fd.get(), &read_char, 1));
729 if (read_result != 1) {
730 RAW_LOG(ERROR, "LaunchProcess: synchronization read: error");
731 _exit(127);
734 // The pipe is no longer useful. Don't let it live on in the new process
735 // after exec.
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]);
747 _exit(127);
748 } else {
749 // Parent process
750 if (options.wait) {
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));
755 DPCHECK(ret > 0);
758 if (process_handle)
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)
770 return true;
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);
784 delete handle;
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,
805 int* exit_code) {
806 return GetTerminationStatusImpl(handle, true /* can_block */, exit_code);
809 bool WaitForExitCode(ProcessHandle handle, int* exit_code) {
810 int status;
811 if (HANDLE_EINTR(waitpid(handle, &status, 0)) == -1) {
812 NOTREACHED();
813 return false;
816 if (WIFEXITED(status)) {
817 *exit_code = WEXITSTATUS(status);
818 return true;
821 // If it didn't exit cleanly, it must have been signaled.
822 DCHECK(WIFSIGNALED(status));
823 return false;
826 bool WaitForExitCodeWithTimeout(ProcessHandle handle, int* exit_code,
827 base::TimeDelta timeout) {
828 bool waitpid_success = false;
829 int status = WaitpidWithTimeout(handle, timeout.InMilliseconds(),
830 &waitpid_success);
831 if (status == -1)
832 return false;
833 if (!waitpid_success)
834 return false;
835 if (WIFSIGNALED(status)) {
836 *exit_code = -1;
837 return true;
839 if (WIFEXITED(status)) {
840 *exit_code = WEXITSTATUS(status);
841 return true;
843 return false;
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());
855 int kq = kqueue();
856 if (kq == -1) {
857 DPLOG(ERROR) << "kqueue";
858 return false;
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));
865 if (result == -1) {
866 if (errno == ESRCH) {
867 // If the process wasn't found, it must be dead.
868 return true;
871 DPLOG(ERROR) << "kevent (setup " << handle << ")";
872 return false;
875 // Keep track of the elapsed time to be able to restart kevent if it's
876 // interrupted.
877 bool wait_forever = wait.InMilliseconds() == base::kNoTimeout;
878 base::TimeDelta remaining_delta;
879 base::TimeTicks deadline;
880 if (!wait_forever) {
881 remaining_delta = wait;
882 deadline = base::TimeTicks::Now() + remaining_delta;
885 result = -1;
886 struct kevent event = {0};
888 while (wait_forever || remaining_delta > base::TimeDelta()) {
889 struct timespec remaining_timespec;
890 struct timespec* remaining_timespec_ptr;
891 if (wait_forever) {
892 remaining_timespec_ptr = NULL;
893 } else {
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) {
901 if (!wait_forever) {
902 remaining_delta = deadline - base::TimeTicks::Now();
904 result = 0;
905 } else {
906 break;
910 if (result < 0) {
911 DPLOG(ERROR) << "kevent (wait " << handle << ")";
912 return false;
913 } else if (result > 1) {
914 DLOG(ERROR) << "kevent (wait " << handle << "): unexpected result "
915 << result;
916 return false;
917 } else if (result == 0) {
918 // Timed out.
919 return false;
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;
931 return false;
934 return true;
936 #endif // OS_MACOSX
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);
945 #else
946 // Currently on Linux we can't handle non child processes.
947 NOTIMPLEMENTED();
948 #endif // OS_MACOSX
951 bool waitpid_success;
952 int status = -1;
953 if (wait.InMilliseconds() == base::kNoTimeout) {
954 waitpid_success = (HANDLE_EINTR(waitpid(handle, &status, 0)) != -1);
955 } else {
956 status = WaitpidWithTimeout(
957 handle, wait.InMilliseconds(), &waitpid_success);
960 if (status != -1) {
961 DCHECK(waitpid_success);
962 return WIFEXITED(status);
963 } else {
964 return false;
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;
972 ret += tv.tv_usec;
973 return ret;
976 // Return value used by GetAppOutputInternal to encapsulate the various exit
977 // scenarios from the function.
978 enum GetAppOutputInternalResult {
979 EXECUTE_FAILURE,
980 EXECUTE_SUCCESS,
981 GOT_MAX_OUTPUT,
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
998 // ran successfully.
999 static GetAppOutputInternalResult GetAppOutputInternal(
1000 const std::vector<std::string>& argv,
1001 char* const envp[],
1002 std::string* output,
1003 size_t max_output,
1004 bool do_search_path,
1005 int* exit_code) {
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.
1009 DCHECK(exit_code);
1010 *exit_code = EXIT_FAILURE;
1012 int pipe_fd[2];
1013 pid_t pid;
1014 InjectiveMultimap fd_shuffle1, fd_shuffle2;
1015 scoped_ptr<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
1021 // both.
1022 DCHECK(!do_search_path ^ !envp);
1024 if (pipe(pipe_fd) < 0)
1025 return EXECUTE_FAILURE;
1027 switch (pid = fork()) {
1028 case -1: // error
1029 close(pipe_fd[0]);
1030 close(pipe_fd[1]);
1031 return EXECUTE_FAILURE;
1032 case 0: // child
1034 #if defined(OS_MACOSX)
1035 RestoreDefaultExceptionHandler();
1036 #endif
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
1044 // in the child.
1045 int dev_null = open("/dev/null", O_WRONLY);
1046 if (dev_null < 0)
1047 _exit(127);
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))
1064 _exit(127);
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;
1071 if (do_search_path)
1072 execvp(argv_cstr[0], argv_cstr.get());
1073 else
1074 execve(argv_cstr[0], argv_cstr.get(), envp);
1075 _exit(127);
1077 default: // parent
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).
1082 close(pipe_fd[1]);
1084 output->clear();
1085 char buffer[256];
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)
1094 break;
1095 output->append(buffer, bytes_read);
1096 output_buf_left -= static_cast<size_t>(bytes_read);
1098 close(pipe_fd[0]);
1100 // Always wait for exit code (even if we know we'll declare
1101 // GOT_MAX_OUTPUT).
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;
1108 else if (success)
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.
1121 int exit_code;
1122 GetAppOutputInternalResult result = GetAppOutputInternal(
1123 argv, NULL, output, std::numeric_limits<std::size_t>::max(), true,
1124 &exit_code);
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;
1134 int exit_code;
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,
1143 int* exit_code) {
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,
1147 exit_code);
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::TimeTicks end_time = base::TimeTicks::Now() + wait;
1160 do {
1161 NamedProcessIterator iter(executable_name, filter);
1162 if (!iter.NextProcessEntry()) {
1163 result = true;
1164 break;
1166 base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(100));
1167 } while ((end_time - base::TimeTicks::Now()) > base::TimeDelta());
1169 return result;
1172 bool CleanupProcesses(const FilePath::StringType& executable_name,
1173 base::TimeDelta wait,
1174 int exit_code,
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)
1184 namespace {
1186 // Return true if the given child is dead. This will also reap the process.
1187 // Doesn't block.
1188 static bool IsChildDead(pid_t child) {
1189 const pid_t result = HANDLE_EINTR(waitpid(child, NULL, WNOHANG));
1190 if (result == -1) {
1191 DPLOG(ERROR) << "waitpid(" << child << ")";
1192 NOTREACHED();
1193 } else if (result > 0) {
1194 // The child has died.
1195 return true;
1198 return false;
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 {
1204 public:
1205 BackgroundReaper(pid_t child, unsigned timeout)
1206 : child_(child),
1207 timeout_(timeout) {
1210 // Overridden from PlatformThread::Delegate:
1211 virtual void ThreadMain() OVERRIDE {
1212 WaitForChildToDie();
1213 delete this;
1216 void WaitForChildToDie() {
1217 // Wait forever case.
1218 if (timeout_ == 0) {
1219 pid_t r = HANDLE_EINTR(waitpid(child_, NULL, 0));
1220 if (r != child_) {
1221 DPLOG(ERROR) << "While waiting for " << child_
1222 << " to terminate, we got the following result: " << r;
1224 return;
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_))
1234 return;
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";
1242 } else {
1243 DLOG(ERROR) << "While waiting for " << child_ << " to terminate we"
1244 << " failed to deliver a SIGKILL signal (" << errno << ").";
1248 private:
1249 const pid_t child_;
1250 // Number of seconds to wait, if 0 then wait forever and do not attempt to
1251 // kill |child_|.
1252 const unsigned timeout_;
1254 DISALLOW_COPY_AND_ASSIGN(BackgroundReaper);
1257 } // namespace
1259 void EnsureProcessTerminated(ProcessHandle process) {
1260 // If the child is already dead, then there's nothing to do.
1261 if (IsChildDead(process))
1262 return;
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))
1272 return;
1274 BackgroundReaper* reaper = new BackgroundReaper(process, 0);
1275 PlatformThread::CreateNonJoinable(0, reaper);
1278 #endif // !defined(OS_MACOSX)
1280 } // namespace base