[android_webview] Disable AwSettingsTest broken by Blink roll.
[chromium-blink-merge.git] / base / process_util_posix.cc
blob6f1513073f493cd7cdca67aca2402789ecebb7a5
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 #if !defined(OS_LINUX) || \
139 (!defined(__i386__) && !defined(__x86_64__) && !defined(__arm__))
140 void ResetChildSignalHandlersToDefaults() {
141 // The previous signal handlers are likely to be meaningless in the child's
142 // context so we reset them to the defaults for now. http://crbug.com/44953
143 // These signal handlers are set up at least in browser_main_posix.cc:
144 // BrowserMainPartsPosix::PreEarlyInitialization and stack_trace_posix.cc:
145 // EnableInProcessStackDumping.
146 signal(SIGHUP, SIG_DFL);
147 signal(SIGINT, SIG_DFL);
148 signal(SIGILL, SIG_DFL);
149 signal(SIGABRT, SIG_DFL);
150 signal(SIGFPE, SIG_DFL);
151 signal(SIGBUS, SIG_DFL);
152 signal(SIGSEGV, SIG_DFL);
153 signal(SIGSYS, SIG_DFL);
154 signal(SIGTERM, SIG_DFL);
157 #else
159 // TODO(jln): remove the Linux special case once kernels are fixed.
161 // Internally the kernel makes sigset_t an array of long large enough to have
162 // one bit per signal.
163 typedef uint64_t kernel_sigset_t;
165 // This is what struct sigaction looks like to the kernel at least on X86 and
166 // ARM. MIPS, for instance, is very different.
167 struct kernel_sigaction {
168 void* k_sa_handler; // For this usage it only needs to be a generic pointer.
169 unsigned long k_sa_flags;
170 void* k_sa_restorer; // For this usage it only needs to be a generic pointer.
171 kernel_sigset_t k_sa_mask;
174 // glibc's sigaction() will prevent access to sa_restorer, so we need to roll
175 // our own.
176 int sys_rt_sigaction(int sig, const struct kernel_sigaction* act,
177 struct kernel_sigaction* oact) {
178 return syscall(SYS_rt_sigaction, sig, act, oact, sizeof(kernel_sigset_t));
181 // This function is intended to be used in between fork() and execve() and will
182 // reset all signal handlers to the default.
183 // The motivation for going through all of them is that sa_restorer can leak
184 // from parents and help defeat ASLR on buggy kernels. We reset it to NULL.
185 // See crbug.com/177956.
186 void ResetChildSignalHandlersToDefaults(void) {
187 for (int signum = 1; ; ++signum) {
188 struct kernel_sigaction act = {0};
189 int sigaction_get_ret = sys_rt_sigaction(signum, NULL, &act);
190 if (sigaction_get_ret && errno == EINVAL) {
191 #if !defined(NDEBUG)
192 // Linux supports 32 real-time signals from 33 to 64.
193 // If the number of signals in the Linux kernel changes, someone should
194 // look at this code.
195 const int kNumberOfSignals = 64;
196 RAW_CHECK(signum == kNumberOfSignals + 1);
197 #endif // !defined(NDEBUG)
198 break;
200 // All other failures are fatal.
201 if (sigaction_get_ret) {
202 RAW_LOG(FATAL, "sigaction (get) failed.");
205 // The kernel won't allow to re-set SIGKILL or SIGSTOP.
206 if (signum != SIGSTOP && signum != SIGKILL) {
207 act.k_sa_handler = reinterpret_cast<void*>(SIG_DFL);
208 act.k_sa_restorer = NULL;
209 if (sys_rt_sigaction(signum, &act, NULL)) {
210 RAW_LOG(FATAL, "sigaction (set) failed.");
213 #if !defined(NDEBUG)
214 // Now ask the kernel again and check that no restorer will leak.
215 if (sys_rt_sigaction(signum, NULL, &act) || act.k_sa_restorer) {
216 RAW_LOG(FATAL, "Cound not fix sa_restorer.");
218 #endif // !defined(NDEBUG)
221 #endif // !defined(OS_LINUX) ||
222 // (!defined(__i386__) && !defined(__x86_64__) && !defined(__arm__))
224 TerminationStatus GetTerminationStatusImpl(ProcessHandle handle,
225 bool can_block,
226 int* exit_code) {
227 int status = 0;
228 const pid_t result = HANDLE_EINTR(waitpid(handle, &status,
229 can_block ? 0 : WNOHANG));
230 if (result == -1) {
231 DPLOG(ERROR) << "waitpid(" << handle << ")";
232 if (exit_code)
233 *exit_code = 0;
234 return TERMINATION_STATUS_NORMAL_TERMINATION;
235 } else if (result == 0) {
236 // the child hasn't exited yet.
237 if (exit_code)
238 *exit_code = 0;
239 return TERMINATION_STATUS_STILL_RUNNING;
242 if (exit_code)
243 *exit_code = status;
245 if (WIFSIGNALED(status)) {
246 switch (WTERMSIG(status)) {
247 case SIGABRT:
248 case SIGBUS:
249 case SIGFPE:
250 case SIGILL:
251 case SIGSEGV:
252 return TERMINATION_STATUS_PROCESS_CRASHED;
253 case SIGINT:
254 case SIGKILL:
255 case SIGTERM:
256 return TERMINATION_STATUS_PROCESS_WAS_KILLED;
257 default:
258 break;
262 if (WIFEXITED(status) && WEXITSTATUS(status) != 0)
263 return TERMINATION_STATUS_ABNORMAL_TERMINATION;
265 return TERMINATION_STATUS_NORMAL_TERMINATION;
268 } // anonymous namespace
270 ProcessId GetCurrentProcId() {
271 return getpid();
274 ProcessHandle GetCurrentProcessHandle() {
275 return GetCurrentProcId();
278 bool OpenProcessHandle(ProcessId pid, ProcessHandle* handle) {
279 // On Posix platforms, process handles are the same as PIDs, so we
280 // don't need to do anything.
281 *handle = pid;
282 return true;
285 bool OpenPrivilegedProcessHandle(ProcessId pid, ProcessHandle* handle) {
286 // On POSIX permissions are checked for each operation on process,
287 // not when opening a "handle".
288 return OpenProcessHandle(pid, handle);
291 bool OpenProcessHandleWithAccess(ProcessId pid,
292 uint32 access_flags,
293 ProcessHandle* handle) {
294 // On POSIX permissions are checked for each operation on process,
295 // not when opening a "handle".
296 return OpenProcessHandle(pid, handle);
299 void CloseProcessHandle(ProcessHandle process) {
300 // See OpenProcessHandle, nothing to do.
301 return;
304 ProcessId GetProcId(ProcessHandle process) {
305 return process;
308 // Attempts to kill the process identified by the given process
309 // entry structure. Ignores specified exit_code; posix can't force that.
310 // Returns true if this is successful, false otherwise.
311 bool KillProcess(ProcessHandle process_id, int exit_code, bool wait) {
312 DCHECK_GT(process_id, 1) << " tried to kill invalid process_id";
313 if (process_id <= 1)
314 return false;
315 bool result = kill(process_id, SIGTERM) == 0;
316 if (result && wait) {
317 int tries = 60;
319 if (RunningOnValgrind()) {
320 // Wait for some extra time when running under Valgrind since the child
321 // processes may take some time doing leak checking.
322 tries *= 2;
325 unsigned sleep_ms = 4;
327 // The process may not end immediately due to pending I/O
328 bool exited = false;
329 while (tries-- > 0) {
330 pid_t pid = HANDLE_EINTR(waitpid(process_id, NULL, WNOHANG));
331 if (pid == process_id) {
332 exited = true;
333 break;
335 if (pid == -1) {
336 if (errno == ECHILD) {
337 // The wait may fail with ECHILD if another process also waited for
338 // the same pid, causing the process state to get cleaned up.
339 exited = true;
340 break;
342 DPLOG(ERROR) << "Error waiting for process " << process_id;
345 usleep(sleep_ms * 1000);
346 const unsigned kMaxSleepMs = 1000;
347 if (sleep_ms < kMaxSleepMs)
348 sleep_ms *= 2;
351 // If we're waiting and the child hasn't died by now, force it
352 // with a SIGKILL.
353 if (!exited)
354 result = kill(process_id, SIGKILL) == 0;
357 if (!result)
358 DPLOG(ERROR) << "Unable to terminate process " << process_id;
360 return result;
363 bool KillProcessGroup(ProcessHandle process_group_id) {
364 bool result = kill(-1 * process_group_id, SIGKILL) == 0;
365 if (!result)
366 DPLOG(ERROR) << "Unable to terminate process group " << process_group_id;
367 return result;
370 // A class to handle auto-closing of DIR*'s.
371 class ScopedDIRClose {
372 public:
373 inline void operator()(DIR* x) const {
374 if (x) {
375 closedir(x);
379 typedef scoped_ptr_malloc<DIR, ScopedDIRClose> ScopedDIR;
381 #if defined(OS_LINUX)
382 static const rlim_t kSystemDefaultMaxFds = 8192;
383 static const char kFDDir[] = "/proc/self/fd";
384 #elif defined(OS_MACOSX)
385 static const rlim_t kSystemDefaultMaxFds = 256;
386 static const char kFDDir[] = "/dev/fd";
387 #elif defined(OS_SOLARIS)
388 static const rlim_t kSystemDefaultMaxFds = 8192;
389 static const char kFDDir[] = "/dev/fd";
390 #elif defined(OS_FREEBSD)
391 static const rlim_t kSystemDefaultMaxFds = 8192;
392 static const char kFDDir[] = "/dev/fd";
393 #elif defined(OS_OPENBSD)
394 static const rlim_t kSystemDefaultMaxFds = 256;
395 static const char kFDDir[] = "/dev/fd";
396 #elif defined(OS_ANDROID)
397 static const rlim_t kSystemDefaultMaxFds = 1024;
398 static const char kFDDir[] = "/proc/self/fd";
399 #endif
401 size_t GetMaxFds() {
402 rlim_t max_fds;
403 struct rlimit nofile;
404 if (getrlimit(RLIMIT_NOFILE, &nofile)) {
405 // getrlimit failed. Take a best guess.
406 max_fds = kSystemDefaultMaxFds;
407 RAW_LOG(ERROR, "getrlimit(RLIMIT_NOFILE) failed");
408 } else {
409 max_fds = nofile.rlim_cur;
412 if (max_fds > INT_MAX)
413 max_fds = INT_MAX;
415 return static_cast<size_t>(max_fds);
418 void CloseSuperfluousFds(const base::InjectiveMultimap& saved_mapping) {
419 // DANGER: no calls to malloc are allowed from now on:
420 // http://crbug.com/36678
422 // Get the maximum number of FDs possible.
423 size_t max_fds = GetMaxFds();
425 DirReaderPosix fd_dir(kFDDir);
426 if (!fd_dir.IsValid()) {
427 // Fallback case: Try every possible fd.
428 for (size_t i = 0; i < max_fds; ++i) {
429 const int fd = static_cast<int>(i);
430 if (fd == STDIN_FILENO || fd == STDOUT_FILENO || fd == STDERR_FILENO)
431 continue;
432 InjectiveMultimap::const_iterator j;
433 for (j = saved_mapping.begin(); j != saved_mapping.end(); j++) {
434 if (fd == j->dest)
435 break;
437 if (j != saved_mapping.end())
438 continue;
440 // Since we're just trying to close anything we can find,
441 // ignore any error return values of close().
442 ignore_result(HANDLE_EINTR(close(fd)));
444 return;
447 const int dir_fd = fd_dir.fd();
449 for ( ; fd_dir.Next(); ) {
450 // Skip . and .. entries.
451 if (fd_dir.name()[0] == '.')
452 continue;
454 char *endptr;
455 errno = 0;
456 const long int fd = strtol(fd_dir.name(), &endptr, 10);
457 if (fd_dir.name()[0] == 0 || *endptr || fd < 0 || errno)
458 continue;
459 if (fd == STDIN_FILENO || fd == STDOUT_FILENO || fd == STDERR_FILENO)
460 continue;
461 InjectiveMultimap::const_iterator i;
462 for (i = saved_mapping.begin(); i != saved_mapping.end(); i++) {
463 if (fd == i->dest)
464 break;
466 if (i != saved_mapping.end())
467 continue;
468 if (fd == dir_fd)
469 continue;
471 // When running under Valgrind, Valgrind opens several FDs for its
472 // own use and will complain if we try to close them. All of
473 // these FDs are >= |max_fds|, so we can check against that here
474 // before closing. See https://bugs.kde.org/show_bug.cgi?id=191758
475 if (fd < static_cast<int>(max_fds)) {
476 int ret = HANDLE_EINTR(close(fd));
477 DPCHECK(ret == 0);
482 char** AlterEnvironment(const EnvironmentVector& changes,
483 const char* const* const env) {
484 unsigned count = 0;
485 unsigned size = 0;
487 // First assume that all of the current environment will be included.
488 for (unsigned i = 0; env[i]; i++) {
489 const char *const pair = env[i];
490 count++;
491 size += strlen(pair) + 1 /* terminating NUL */;
494 for (EnvironmentVector::const_iterator j = changes.begin();
495 j != changes.end();
496 ++j) {
497 bool found = false;
498 const char *pair;
500 for (unsigned i = 0; env[i]; i++) {
501 pair = env[i];
502 const char *const equals = strchr(pair, '=');
503 if (!equals)
504 continue;
505 const unsigned keylen = equals - pair;
506 if (keylen == j->first.size() &&
507 memcmp(pair, j->first.data(), keylen) == 0) {
508 found = true;
509 break;
513 // if found, we'll either be deleting or replacing this element.
514 if (found) {
515 count--;
516 size -= strlen(pair) + 1;
517 if (j->second.size())
518 found = false;
521 // if !found, then we have a new element to add.
522 if (!found && !j->second.empty()) {
523 count++;
524 size += j->first.size() + 1 /* '=' */ + j->second.size() + 1 /* NUL */;
528 count++; // for the final NULL
529 uint8_t *buffer = new uint8_t[sizeof(char*) * count + size];
530 char **const ret = reinterpret_cast<char**>(buffer);
531 unsigned k = 0;
532 char *scratch = reinterpret_cast<char*>(buffer + sizeof(char*) * count);
534 for (unsigned i = 0; env[i]; i++) {
535 const char *const pair = env[i];
536 const char *const equals = strchr(pair, '=');
537 if (!equals) {
538 const unsigned len = strlen(pair);
539 ret[k++] = scratch;
540 memcpy(scratch, pair, len + 1);
541 scratch += len + 1;
542 continue;
544 const unsigned keylen = equals - pair;
545 bool handled = false;
546 for (EnvironmentVector::const_iterator
547 j = changes.begin(); j != changes.end(); j++) {
548 if (j->first.size() == keylen &&
549 memcmp(j->first.data(), pair, keylen) == 0) {
550 if (!j->second.empty()) {
551 ret[k++] = scratch;
552 memcpy(scratch, pair, keylen + 1);
553 scratch += keylen + 1;
554 memcpy(scratch, j->second.c_str(), j->second.size() + 1);
555 scratch += j->second.size() + 1;
557 handled = true;
558 break;
562 if (!handled) {
563 const unsigned len = strlen(pair);
564 ret[k++] = scratch;
565 memcpy(scratch, pair, len + 1);
566 scratch += len + 1;
570 // Now handle new elements
571 for (EnvironmentVector::const_iterator
572 j = changes.begin(); j != changes.end(); j++) {
573 if (j->second.empty())
574 continue;
576 bool found = false;
577 for (unsigned i = 0; env[i]; i++) {
578 const char *const pair = env[i];
579 const char *const equals = strchr(pair, '=');
580 if (!equals)
581 continue;
582 const unsigned keylen = equals - pair;
583 if (keylen == j->first.size() &&
584 memcmp(pair, j->first.data(), keylen) == 0) {
585 found = true;
586 break;
590 if (!found) {
591 ret[k++] = scratch;
592 memcpy(scratch, j->first.data(), j->first.size());
593 scratch += j->first.size();
594 *scratch++ = '=';
595 memcpy(scratch, j->second.c_str(), j->second.size() + 1);
596 scratch += j->second.size() + 1;
600 ret[k] = NULL;
601 return ret;
604 bool LaunchProcess(const std::vector<std::string>& argv,
605 const LaunchOptions& options,
606 ProcessHandle* process_handle) {
607 size_t fd_shuffle_size = 0;
608 if (options.fds_to_remap) {
609 fd_shuffle_size = options.fds_to_remap->size();
612 InjectiveMultimap fd_shuffle1;
613 InjectiveMultimap fd_shuffle2;
614 fd_shuffle1.reserve(fd_shuffle_size);
615 fd_shuffle2.reserve(fd_shuffle_size);
617 scoped_ptr<char*[]> argv_cstr(new char*[argv.size() + 1]);
618 scoped_ptr<char*[]> new_environ;
619 if (options.environ)
620 new_environ.reset(AlterEnvironment(*options.environ, GetEnvironment()));
622 pid_t pid;
623 #if defined(OS_LINUX)
624 if (options.clone_flags) {
625 pid = syscall(__NR_clone, options.clone_flags, 0, 0, 0);
626 } else
627 #endif
629 pid = fork();
632 if (pid < 0) {
633 DPLOG(ERROR) << "fork";
634 return false;
635 } else if (pid == 0) {
636 // Child process
638 // DANGER: fork() rule: in the child, if you don't end up doing exec*(),
639 // you call _exit() instead of exit(). This is because _exit() does not
640 // call any previously-registered (in the parent) exit handlers, which
641 // might do things like block waiting for threads that don't even exist
642 // in the child.
644 // If a child process uses the readline library, the process block forever.
645 // In BSD like OSes including OS X it is safe to assign /dev/null as stdin.
646 // See http://crbug.com/56596.
647 int null_fd = HANDLE_EINTR(open("/dev/null", O_RDONLY));
648 if (null_fd < 0) {
649 RAW_LOG(ERROR, "Failed to open /dev/null");
650 _exit(127);
653 file_util::ScopedFD null_fd_closer(&null_fd);
654 int new_fd = HANDLE_EINTR(dup2(null_fd, STDIN_FILENO));
655 if (new_fd != STDIN_FILENO) {
656 RAW_LOG(ERROR, "Failed to dup /dev/null for stdin");
657 _exit(127);
660 if (options.new_process_group) {
661 // Instead of inheriting the process group ID of the parent, the child
662 // starts off a new process group with pgid equal to its process ID.
663 if (setpgid(0, 0) < 0) {
664 RAW_LOG(ERROR, "setpgid failed");
665 _exit(127);
669 // Stop type-profiler.
670 // The profiler should be stopped between fork and exec since it inserts
671 // locks at new/delete expressions. See http://crbug.com/36678.
672 base::type_profiler::Controller::Stop();
674 if (options.maximize_rlimits) {
675 // Some resource limits need to be maximal in this child.
676 std::set<int>::const_iterator resource;
677 for (resource = options.maximize_rlimits->begin();
678 resource != options.maximize_rlimits->end();
679 ++resource) {
680 struct rlimit limit;
681 if (getrlimit(*resource, &limit) < 0) {
682 RAW_LOG(WARNING, "getrlimit failed");
683 } else if (limit.rlim_cur < limit.rlim_max) {
684 limit.rlim_cur = limit.rlim_max;
685 if (setrlimit(*resource, &limit) < 0) {
686 RAW_LOG(WARNING, "setrlimit failed");
692 #if defined(OS_MACOSX)
693 RestoreDefaultExceptionHandler();
694 #endif // defined(OS_MACOSX)
696 ResetChildSignalHandlersToDefaults();
698 #if 0
699 // When debugging it can be helpful to check that we really aren't making
700 // any hidden calls to malloc.
701 void *malloc_thunk =
702 reinterpret_cast<void*>(reinterpret_cast<intptr_t>(malloc) & ~4095);
703 mprotect(malloc_thunk, 4096, PROT_READ | PROT_WRITE | PROT_EXEC);
704 memset(reinterpret_cast<void*>(malloc), 0xff, 8);
705 #endif // 0
707 // DANGER: no calls to malloc are allowed from now on:
708 // http://crbug.com/36678
710 #if defined(OS_CHROMEOS)
711 if (options.ctrl_terminal_fd >= 0) {
712 // Set process' controlling terminal.
713 if (HANDLE_EINTR(setsid()) != -1) {
714 if (HANDLE_EINTR(
715 ioctl(options.ctrl_terminal_fd, TIOCSCTTY, NULL)) == -1) {
716 RAW_LOG(WARNING, "ioctl(TIOCSCTTY), ctrl terminal not set");
718 } else {
719 RAW_LOG(WARNING, "setsid failed, ctrl terminal not set");
722 #endif // defined(OS_CHROMEOS)
724 if (options.fds_to_remap) {
725 for (FileHandleMappingVector::const_iterator
726 it = options.fds_to_remap->begin();
727 it != options.fds_to_remap->end(); ++it) {
728 fd_shuffle1.push_back(InjectionArc(it->first, it->second, false));
729 fd_shuffle2.push_back(InjectionArc(it->first, it->second, false));
733 if (options.environ)
734 SetEnvironment(new_environ.get());
736 // fd_shuffle1 is mutated by this call because it cannot malloc.
737 if (!ShuffleFileDescriptors(&fd_shuffle1))
738 _exit(127);
740 CloseSuperfluousFds(fd_shuffle2);
742 for (size_t i = 0; i < argv.size(); i++)
743 argv_cstr[i] = const_cast<char*>(argv[i].c_str());
744 argv_cstr[argv.size()] = NULL;
745 execvp(argv_cstr[0], argv_cstr.get());
747 RAW_LOG(ERROR, "LaunchProcess: failed to execvp:");
748 RAW_LOG(ERROR, argv_cstr[0]);
749 _exit(127);
750 } else {
751 // Parent process
752 if (options.wait) {
753 // While this isn't strictly disk IO, waiting for another process to
754 // finish is the sort of thing ThreadRestrictions is trying to prevent.
755 base::ThreadRestrictions::AssertIOAllowed();
756 pid_t ret = HANDLE_EINTR(waitpid(pid, 0, 0));
757 DPCHECK(ret > 0);
760 if (process_handle)
761 *process_handle = pid;
764 return true;
768 bool LaunchProcess(const CommandLine& cmdline,
769 const LaunchOptions& options,
770 ProcessHandle* process_handle) {
771 return LaunchProcess(cmdline.argv(), options, process_handle);
774 ProcessMetrics::~ProcessMetrics() { }
776 void RaiseProcessToHighPriority() {
777 // On POSIX, we don't actually do anything here. We could try to nice() or
778 // setpriority() or sched_getscheduler, but these all require extra rights.
781 TerminationStatus GetTerminationStatus(ProcessHandle handle, int* exit_code) {
782 return GetTerminationStatusImpl(handle, false /* can_block */, exit_code);
785 TerminationStatus WaitForTerminationStatus(ProcessHandle handle,
786 int* exit_code) {
787 return GetTerminationStatusImpl(handle, true /* can_block */, exit_code);
790 bool WaitForExitCode(ProcessHandle handle, int* exit_code) {
791 int status;
792 if (HANDLE_EINTR(waitpid(handle, &status, 0)) == -1) {
793 NOTREACHED();
794 return false;
797 if (WIFEXITED(status)) {
798 *exit_code = WEXITSTATUS(status);
799 return true;
802 // If it didn't exit cleanly, it must have been signaled.
803 DCHECK(WIFSIGNALED(status));
804 return false;
807 bool WaitForExitCodeWithTimeout(ProcessHandle handle, int* exit_code,
808 base::TimeDelta timeout) {
809 bool waitpid_success = false;
810 int status = WaitpidWithTimeout(handle, timeout.InMilliseconds(),
811 &waitpid_success);
812 if (status == -1)
813 return false;
814 if (!waitpid_success)
815 return false;
816 if (WIFSIGNALED(status)) {
817 *exit_code = -1;
818 return true;
820 if (WIFEXITED(status)) {
821 *exit_code = WEXITSTATUS(status);
822 return true;
824 return false;
827 #if defined(OS_MACOSX)
828 // Using kqueue on Mac so that we can wait on non-child processes.
829 // We can't use kqueues on child processes because we need to reap
830 // our own children using wait.
831 static bool WaitForSingleNonChildProcess(ProcessHandle handle,
832 base::TimeDelta wait) {
833 DCHECK_GT(handle, 0);
834 DCHECK(wait.InMilliseconds() == base::kNoTimeout || wait > base::TimeDelta());
836 int kq = kqueue();
837 if (kq == -1) {
838 DPLOG(ERROR) << "kqueue";
839 return false;
841 file_util::ScopedFD kq_closer(&kq);
843 struct kevent change = {0};
844 EV_SET(&change, handle, EVFILT_PROC, EV_ADD, NOTE_EXIT, 0, NULL);
845 int result = HANDLE_EINTR(kevent(kq, &change, 1, NULL, 0, NULL));
846 if (result == -1) {
847 if (errno == ESRCH) {
848 // If the process wasn't found, it must be dead.
849 return true;
852 DPLOG(ERROR) << "kevent (setup " << handle << ")";
853 return false;
856 // Keep track of the elapsed time to be able to restart kevent if it's
857 // interrupted.
858 bool wait_forever = wait.InMilliseconds() == base::kNoTimeout;
859 base::TimeDelta remaining_delta;
860 base::TimeTicks deadline;
861 if (!wait_forever) {
862 remaining_delta = wait;
863 deadline = base::TimeTicks::Now() + remaining_delta;
866 result = -1;
867 struct kevent event = {0};
869 while (wait_forever || remaining_delta > base::TimeDelta()) {
870 struct timespec remaining_timespec;
871 struct timespec* remaining_timespec_ptr;
872 if (wait_forever) {
873 remaining_timespec_ptr = NULL;
874 } else {
875 remaining_timespec = remaining_delta.ToTimeSpec();
876 remaining_timespec_ptr = &remaining_timespec;
879 result = kevent(kq, NULL, 0, &event, 1, remaining_timespec_ptr);
881 if (result == -1 && errno == EINTR) {
882 if (!wait_forever) {
883 remaining_delta = deadline - base::TimeTicks::Now();
885 result = 0;
886 } else {
887 break;
891 if (result < 0) {
892 DPLOG(ERROR) << "kevent (wait " << handle << ")";
893 return false;
894 } else if (result > 1) {
895 DLOG(ERROR) << "kevent (wait " << handle << "): unexpected result "
896 << result;
897 return false;
898 } else if (result == 0) {
899 // Timed out.
900 return false;
903 DCHECK_EQ(result, 1);
905 if (event.filter != EVFILT_PROC ||
906 (event.fflags & NOTE_EXIT) == 0 ||
907 event.ident != static_cast<uintptr_t>(handle)) {
908 DLOG(ERROR) << "kevent (wait " << handle
909 << "): unexpected event: filter=" << event.filter
910 << ", fflags=" << event.fflags
911 << ", ident=" << event.ident;
912 return false;
915 return true;
917 #endif // OS_MACOSX
919 bool WaitForSingleProcess(ProcessHandle handle, base::TimeDelta wait) {
920 ProcessHandle parent_pid = GetParentProcessId(handle);
921 ProcessHandle our_pid = Process::Current().handle();
922 if (parent_pid != our_pid) {
923 #if defined(OS_MACOSX)
924 // On Mac we can wait on non child processes.
925 return WaitForSingleNonChildProcess(handle, wait);
926 #else
927 // Currently on Linux we can't handle non child processes.
928 NOTIMPLEMENTED();
929 #endif // OS_MACOSX
932 bool waitpid_success;
933 int status = -1;
934 if (wait.InMilliseconds() == base::kNoTimeout) {
935 waitpid_success = (HANDLE_EINTR(waitpid(handle, &status, 0)) != -1);
936 } else {
937 status = WaitpidWithTimeout(
938 handle, wait.InMilliseconds(), &waitpid_success);
941 if (status != -1) {
942 DCHECK(waitpid_success);
943 return WIFEXITED(status);
944 } else {
945 return false;
949 int64 TimeValToMicroseconds(const struct timeval& tv) {
950 static const int kMicrosecondsPerSecond = 1000000;
951 int64 ret = tv.tv_sec; // Avoid (int * int) integer overflow.
952 ret *= kMicrosecondsPerSecond;
953 ret += tv.tv_usec;
954 return ret;
957 // Return value used by GetAppOutputInternal to encapsulate the various exit
958 // scenarios from the function.
959 enum GetAppOutputInternalResult {
960 EXECUTE_FAILURE,
961 EXECUTE_SUCCESS,
962 GOT_MAX_OUTPUT,
965 // Executes the application specified by |argv| and wait for it to exit. Stores
966 // the output (stdout) in |output|. If |do_search_path| is set, it searches the
967 // path for the application; in that case, |envp| must be null, and it will use
968 // the current environment. If |do_search_path| is false, |argv[0]| should fully
969 // specify the path of the application, and |envp| will be used as the
970 // environment. Redirects stderr to /dev/null.
971 // If we successfully start the application and get all requested output, we
972 // return GOT_MAX_OUTPUT, or if there is a problem starting or exiting
973 // the application we return RUN_FAILURE. Otherwise we return EXECUTE_SUCCESS.
974 // The GOT_MAX_OUTPUT return value exists so a caller that asks for limited
975 // output can treat this as a success, despite having an exit code of SIG_PIPE
976 // due to us closing the output pipe.
977 // In the case of EXECUTE_SUCCESS, the application exit code will be returned
978 // in |*exit_code|, which should be checked to determine if the application
979 // ran successfully.
980 static GetAppOutputInternalResult GetAppOutputInternal(
981 const std::vector<std::string>& argv,
982 char* const envp[],
983 std::string* output,
984 size_t max_output,
985 bool do_search_path,
986 int* exit_code) {
987 // Doing a blocking wait for another command to finish counts as IO.
988 base::ThreadRestrictions::AssertIOAllowed();
989 // exit_code must be supplied so calling function can determine success.
990 DCHECK(exit_code);
991 *exit_code = EXIT_FAILURE;
993 int pipe_fd[2];
994 pid_t pid;
995 InjectiveMultimap fd_shuffle1, fd_shuffle2;
996 scoped_ptr<char*[]> argv_cstr(new char*[argv.size() + 1]);
998 fd_shuffle1.reserve(3);
999 fd_shuffle2.reserve(3);
1001 // Either |do_search_path| should be false or |envp| should be null, but not
1002 // both.
1003 DCHECK(!do_search_path ^ !envp);
1005 if (pipe(pipe_fd) < 0)
1006 return EXECUTE_FAILURE;
1008 switch (pid = fork()) {
1009 case -1: // error
1010 close(pipe_fd[0]);
1011 close(pipe_fd[1]);
1012 return EXECUTE_FAILURE;
1013 case 0: // child
1015 #if defined(OS_MACOSX)
1016 RestoreDefaultExceptionHandler();
1017 #endif
1018 // DANGER: no calls to malloc are allowed from now on:
1019 // http://crbug.com/36678
1021 // Obscure fork() rule: in the child, if you don't end up doing exec*(),
1022 // you call _exit() instead of exit(). This is because _exit() does not
1023 // call any previously-registered (in the parent) exit handlers, which
1024 // might do things like block waiting for threads that don't even exist
1025 // in the child.
1026 int dev_null = open("/dev/null", O_WRONLY);
1027 if (dev_null < 0)
1028 _exit(127);
1030 // Stop type-profiler.
1031 // The profiler should be stopped between fork and exec since it inserts
1032 // locks at new/delete expressions. See http://crbug.com/36678.
1033 base::type_profiler::Controller::Stop();
1035 fd_shuffle1.push_back(InjectionArc(pipe_fd[1], STDOUT_FILENO, true));
1036 fd_shuffle1.push_back(InjectionArc(dev_null, STDERR_FILENO, true));
1037 fd_shuffle1.push_back(InjectionArc(dev_null, STDIN_FILENO, true));
1038 // Adding another element here? Remeber to increase the argument to
1039 // reserve(), above.
1041 std::copy(fd_shuffle1.begin(), fd_shuffle1.end(),
1042 std::back_inserter(fd_shuffle2));
1044 if (!ShuffleFileDescriptors(&fd_shuffle1))
1045 _exit(127);
1047 CloseSuperfluousFds(fd_shuffle2);
1049 for (size_t i = 0; i < argv.size(); i++)
1050 argv_cstr[i] = const_cast<char*>(argv[i].c_str());
1051 argv_cstr[argv.size()] = NULL;
1052 if (do_search_path)
1053 execvp(argv_cstr[0], argv_cstr.get());
1054 else
1055 execve(argv_cstr[0], argv_cstr.get(), envp);
1056 _exit(127);
1058 default: // parent
1060 // Close our writing end of pipe now. Otherwise later read would not
1061 // be able to detect end of child's output (in theory we could still
1062 // write to the pipe).
1063 close(pipe_fd[1]);
1065 output->clear();
1066 char buffer[256];
1067 size_t output_buf_left = max_output;
1068 ssize_t bytes_read = 1; // A lie to properly handle |max_output == 0|
1069 // case in the logic below.
1071 while (output_buf_left > 0) {
1072 bytes_read = HANDLE_EINTR(read(pipe_fd[0], buffer,
1073 std::min(output_buf_left, sizeof(buffer))));
1074 if (bytes_read <= 0)
1075 break;
1076 output->append(buffer, bytes_read);
1077 output_buf_left -= static_cast<size_t>(bytes_read);
1079 close(pipe_fd[0]);
1081 // Always wait for exit code (even if we know we'll declare
1082 // GOT_MAX_OUTPUT).
1083 bool success = WaitForExitCode(pid, exit_code);
1085 // If we stopped because we read as much as we wanted, we return
1086 // GOT_MAX_OUTPUT (because the child may exit due to |SIGPIPE|).
1087 if (!output_buf_left && bytes_read > 0)
1088 return GOT_MAX_OUTPUT;
1089 else if (success)
1090 return EXECUTE_SUCCESS;
1091 return EXECUTE_FAILURE;
1096 bool GetAppOutput(const CommandLine& cl, std::string* output) {
1097 return GetAppOutput(cl.argv(), output);
1100 bool GetAppOutput(const std::vector<std::string>& argv, std::string* output) {
1101 // Run |execve()| with the current environment and store "unlimited" data.
1102 int exit_code;
1103 GetAppOutputInternalResult result = GetAppOutputInternal(
1104 argv, NULL, output, std::numeric_limits<std::size_t>::max(), true,
1105 &exit_code);
1106 return result == EXECUTE_SUCCESS && exit_code == EXIT_SUCCESS;
1109 // TODO(viettrungluu): Conceivably, we should have a timeout as well, so we
1110 // don't hang if what we're calling hangs.
1111 bool GetAppOutputRestricted(const CommandLine& cl,
1112 std::string* output, size_t max_output) {
1113 // Run |execve()| with the empty environment.
1114 char* const empty_environ = NULL;
1115 int exit_code;
1116 GetAppOutputInternalResult result = GetAppOutputInternal(
1117 cl.argv(), &empty_environ, output, max_output, false, &exit_code);
1118 return result == GOT_MAX_OUTPUT || (result == EXECUTE_SUCCESS &&
1119 exit_code == EXIT_SUCCESS);
1122 bool GetAppOutputWithExitCode(const CommandLine& cl,
1123 std::string* output,
1124 int* exit_code) {
1125 // Run |execve()| with the current environment and store "unlimited" data.
1126 GetAppOutputInternalResult result = GetAppOutputInternal(
1127 cl.argv(), NULL, output, std::numeric_limits<std::size_t>::max(), true,
1128 exit_code);
1129 return result == EXECUTE_SUCCESS;
1132 bool WaitForProcessesToExit(const FilePath::StringType& executable_name,
1133 base::TimeDelta wait,
1134 const ProcessFilter* filter) {
1135 bool result = false;
1137 // TODO(port): This is inefficient, but works if there are multiple procs.
1138 // TODO(port): use waitpid to avoid leaving zombies around
1140 base::TimeTicks end_time = base::TimeTicks::Now() + wait;
1141 do {
1142 NamedProcessIterator iter(executable_name, filter);
1143 if (!iter.NextProcessEntry()) {
1144 result = true;
1145 break;
1147 base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(100));
1148 } while ((end_time - base::TimeTicks::Now()) > base::TimeDelta());
1150 return result;
1153 bool CleanupProcesses(const FilePath::StringType& executable_name,
1154 base::TimeDelta wait,
1155 int exit_code,
1156 const ProcessFilter* filter) {
1157 bool exited_cleanly = WaitForProcessesToExit(executable_name, wait, filter);
1158 if (!exited_cleanly)
1159 KillProcesses(executable_name, exit_code, filter);
1160 return exited_cleanly;
1163 #if !defined(OS_MACOSX)
1165 namespace {
1167 // Return true if the given child is dead. This will also reap the process.
1168 // Doesn't block.
1169 static bool IsChildDead(pid_t child) {
1170 const pid_t result = HANDLE_EINTR(waitpid(child, NULL, WNOHANG));
1171 if (result == -1) {
1172 DPLOG(ERROR) << "waitpid(" << child << ")";
1173 NOTREACHED();
1174 } else if (result > 0) {
1175 // The child has died.
1176 return true;
1179 return false;
1182 // A thread class which waits for the given child to exit and reaps it.
1183 // If the child doesn't exit within a couple of seconds, kill it.
1184 class BackgroundReaper : public PlatformThread::Delegate {
1185 public:
1186 BackgroundReaper(pid_t child, unsigned timeout)
1187 : child_(child),
1188 timeout_(timeout) {
1191 // Overridden from PlatformThread::Delegate:
1192 virtual void ThreadMain() OVERRIDE {
1193 WaitForChildToDie();
1194 delete this;
1197 void WaitForChildToDie() {
1198 // Wait forever case.
1199 if (timeout_ == 0) {
1200 pid_t r = HANDLE_EINTR(waitpid(child_, NULL, 0));
1201 if (r != child_) {
1202 DPLOG(ERROR) << "While waiting for " << child_
1203 << " to terminate, we got the following result: " << r;
1205 return;
1208 // There's no good way to wait for a specific child to exit in a timed
1209 // fashion. (No kqueue on Linux), so we just loop and sleep.
1211 // Wait for 2 * timeout_ 500 milliseconds intervals.
1212 for (unsigned i = 0; i < 2 * timeout_; ++i) {
1213 PlatformThread::Sleep(TimeDelta::FromMilliseconds(500));
1214 if (IsChildDead(child_))
1215 return;
1218 if (kill(child_, SIGKILL) == 0) {
1219 // SIGKILL is uncatchable. Since the signal was delivered, we can
1220 // just wait for the process to die now in a blocking manner.
1221 if (HANDLE_EINTR(waitpid(child_, NULL, 0)) < 0)
1222 DPLOG(WARNING) << "waitpid";
1223 } else {
1224 DLOG(ERROR) << "While waiting for " << child_ << " to terminate we"
1225 << " failed to deliver a SIGKILL signal (" << errno << ").";
1229 private:
1230 const pid_t child_;
1231 // Number of seconds to wait, if 0 then wait forever and do not attempt to
1232 // kill |child_|.
1233 const unsigned timeout_;
1235 DISALLOW_COPY_AND_ASSIGN(BackgroundReaper);
1238 } // namespace
1240 void EnsureProcessTerminated(ProcessHandle process) {
1241 // If the child is already dead, then there's nothing to do.
1242 if (IsChildDead(process))
1243 return;
1245 const unsigned timeout = 2; // seconds
1246 BackgroundReaper* reaper = new BackgroundReaper(process, timeout);
1247 PlatformThread::CreateNonJoinable(0, reaper);
1250 void EnsureProcessGetsReaped(ProcessHandle process) {
1251 // If the child is already dead, then there's nothing to do.
1252 if (IsChildDead(process))
1253 return;
1255 BackgroundReaper* reaper = new BackgroundReaper(process, 0);
1256 PlatformThread::CreateNonJoinable(0, reaper);
1259 #endif // !defined(OS_MACOSX)
1261 } // namespace base