Fix crash when JS alert from background page appears during lock screen
[chromium-blink-merge.git] / base / process_util_posix.cc
blob9b05b989650e54c4da0a36a3573b1e3e354645da
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 void RaiseProcessToHighPriority() {
775 // On POSIX, we don't actually do anything here. We could try to nice() or
776 // setpriority() or sched_getscheduler, but these all require extra rights.
779 TerminationStatus GetTerminationStatus(ProcessHandle handle, int* exit_code) {
780 return GetTerminationStatusImpl(handle, false /* can_block */, exit_code);
783 TerminationStatus WaitForTerminationStatus(ProcessHandle handle,
784 int* exit_code) {
785 return GetTerminationStatusImpl(handle, true /* can_block */, exit_code);
788 bool WaitForExitCode(ProcessHandle handle, int* exit_code) {
789 int status;
790 if (HANDLE_EINTR(waitpid(handle, &status, 0)) == -1) {
791 NOTREACHED();
792 return false;
795 if (WIFEXITED(status)) {
796 *exit_code = WEXITSTATUS(status);
797 return true;
800 // If it didn't exit cleanly, it must have been signaled.
801 DCHECK(WIFSIGNALED(status));
802 return false;
805 bool WaitForExitCodeWithTimeout(ProcessHandle handle, int* exit_code,
806 base::TimeDelta timeout) {
807 bool waitpid_success = false;
808 int status = WaitpidWithTimeout(handle, timeout.InMilliseconds(),
809 &waitpid_success);
810 if (status == -1)
811 return false;
812 if (!waitpid_success)
813 return false;
814 if (WIFSIGNALED(status)) {
815 *exit_code = -1;
816 return true;
818 if (WIFEXITED(status)) {
819 *exit_code = WEXITSTATUS(status);
820 return true;
822 return false;
825 #if defined(OS_MACOSX)
826 // Using kqueue on Mac so that we can wait on non-child processes.
827 // We can't use kqueues on child processes because we need to reap
828 // our own children using wait.
829 static bool WaitForSingleNonChildProcess(ProcessHandle handle,
830 base::TimeDelta wait) {
831 DCHECK_GT(handle, 0);
832 DCHECK(wait.InMilliseconds() == base::kNoTimeout || wait > base::TimeDelta());
834 int kq = kqueue();
835 if (kq == -1) {
836 DPLOG(ERROR) << "kqueue";
837 return false;
839 file_util::ScopedFD kq_closer(&kq);
841 struct kevent change = {0};
842 EV_SET(&change, handle, EVFILT_PROC, EV_ADD, NOTE_EXIT, 0, NULL);
843 int result = HANDLE_EINTR(kevent(kq, &change, 1, NULL, 0, NULL));
844 if (result == -1) {
845 if (errno == ESRCH) {
846 // If the process wasn't found, it must be dead.
847 return true;
850 DPLOG(ERROR) << "kevent (setup " << handle << ")";
851 return false;
854 // Keep track of the elapsed time to be able to restart kevent if it's
855 // interrupted.
856 bool wait_forever = wait.InMilliseconds() == base::kNoTimeout;
857 base::TimeDelta remaining_delta;
858 base::TimeTicks deadline;
859 if (!wait_forever) {
860 remaining_delta = wait;
861 deadline = base::TimeTicks::Now() + remaining_delta;
864 result = -1;
865 struct kevent event = {0};
867 while (wait_forever || remaining_delta > base::TimeDelta()) {
868 struct timespec remaining_timespec;
869 struct timespec* remaining_timespec_ptr;
870 if (wait_forever) {
871 remaining_timespec_ptr = NULL;
872 } else {
873 remaining_timespec = remaining_delta.ToTimeSpec();
874 remaining_timespec_ptr = &remaining_timespec;
877 result = kevent(kq, NULL, 0, &event, 1, remaining_timespec_ptr);
879 if (result == -1 && errno == EINTR) {
880 if (!wait_forever) {
881 remaining_delta = deadline - base::TimeTicks::Now();
883 result = 0;
884 } else {
885 break;
889 if (result < 0) {
890 DPLOG(ERROR) << "kevent (wait " << handle << ")";
891 return false;
892 } else if (result > 1) {
893 DLOG(ERROR) << "kevent (wait " << handle << "): unexpected result "
894 << result;
895 return false;
896 } else if (result == 0) {
897 // Timed out.
898 return false;
901 DCHECK_EQ(result, 1);
903 if (event.filter != EVFILT_PROC ||
904 (event.fflags & NOTE_EXIT) == 0 ||
905 event.ident != static_cast<uintptr_t>(handle)) {
906 DLOG(ERROR) << "kevent (wait " << handle
907 << "): unexpected event: filter=" << event.filter
908 << ", fflags=" << event.fflags
909 << ", ident=" << event.ident;
910 return false;
913 return true;
915 #endif // OS_MACOSX
917 bool WaitForSingleProcess(ProcessHandle handle, base::TimeDelta wait) {
918 ProcessHandle parent_pid = GetParentProcessId(handle);
919 ProcessHandle our_pid = Process::Current().handle();
920 if (parent_pid != our_pid) {
921 #if defined(OS_MACOSX)
922 // On Mac we can wait on non child processes.
923 return WaitForSingleNonChildProcess(handle, wait);
924 #else
925 // Currently on Linux we can't handle non child processes.
926 NOTIMPLEMENTED();
927 #endif // OS_MACOSX
930 bool waitpid_success;
931 int status = -1;
932 if (wait.InMilliseconds() == base::kNoTimeout) {
933 waitpid_success = (HANDLE_EINTR(waitpid(handle, &status, 0)) != -1);
934 } else {
935 status = WaitpidWithTimeout(
936 handle, wait.InMilliseconds(), &waitpid_success);
939 if (status != -1) {
940 DCHECK(waitpid_success);
941 return WIFEXITED(status);
942 } else {
943 return false;
947 // Return value used by GetAppOutputInternal to encapsulate the various exit
948 // scenarios from the function.
949 enum GetAppOutputInternalResult {
950 EXECUTE_FAILURE,
951 EXECUTE_SUCCESS,
952 GOT_MAX_OUTPUT,
955 // Executes the application specified by |argv| and wait for it to exit. Stores
956 // the output (stdout) in |output|. If |do_search_path| is set, it searches the
957 // path for the application; in that case, |envp| must be null, and it will use
958 // the current environment. If |do_search_path| is false, |argv[0]| should fully
959 // specify the path of the application, and |envp| will be used as the
960 // environment. Redirects stderr to /dev/null.
961 // If we successfully start the application and get all requested output, we
962 // return GOT_MAX_OUTPUT, or if there is a problem starting or exiting
963 // the application we return RUN_FAILURE. Otherwise we return EXECUTE_SUCCESS.
964 // The GOT_MAX_OUTPUT return value exists so a caller that asks for limited
965 // output can treat this as a success, despite having an exit code of SIG_PIPE
966 // due to us closing the output pipe.
967 // In the case of EXECUTE_SUCCESS, the application exit code will be returned
968 // in |*exit_code|, which should be checked to determine if the application
969 // ran successfully.
970 static GetAppOutputInternalResult GetAppOutputInternal(
971 const std::vector<std::string>& argv,
972 char* const envp[],
973 std::string* output,
974 size_t max_output,
975 bool do_search_path,
976 int* exit_code) {
977 // Doing a blocking wait for another command to finish counts as IO.
978 base::ThreadRestrictions::AssertIOAllowed();
979 // exit_code must be supplied so calling function can determine success.
980 DCHECK(exit_code);
981 *exit_code = EXIT_FAILURE;
983 int pipe_fd[2];
984 pid_t pid;
985 InjectiveMultimap fd_shuffle1, fd_shuffle2;
986 scoped_ptr<char*[]> argv_cstr(new char*[argv.size() + 1]);
988 fd_shuffle1.reserve(3);
989 fd_shuffle2.reserve(3);
991 // Either |do_search_path| should be false or |envp| should be null, but not
992 // both.
993 DCHECK(!do_search_path ^ !envp);
995 if (pipe(pipe_fd) < 0)
996 return EXECUTE_FAILURE;
998 switch (pid = fork()) {
999 case -1: // error
1000 close(pipe_fd[0]);
1001 close(pipe_fd[1]);
1002 return EXECUTE_FAILURE;
1003 case 0: // child
1005 #if defined(OS_MACOSX)
1006 RestoreDefaultExceptionHandler();
1007 #endif
1008 // DANGER: no calls to malloc are allowed from now on:
1009 // http://crbug.com/36678
1011 // Obscure fork() rule: in the child, if you don't end up doing exec*(),
1012 // you call _exit() instead of exit(). This is because _exit() does not
1013 // call any previously-registered (in the parent) exit handlers, which
1014 // might do things like block waiting for threads that don't even exist
1015 // in the child.
1016 int dev_null = open("/dev/null", O_WRONLY);
1017 if (dev_null < 0)
1018 _exit(127);
1020 // Stop type-profiler.
1021 // The profiler should be stopped between fork and exec since it inserts
1022 // locks at new/delete expressions. See http://crbug.com/36678.
1023 base::type_profiler::Controller::Stop();
1025 fd_shuffle1.push_back(InjectionArc(pipe_fd[1], STDOUT_FILENO, true));
1026 fd_shuffle1.push_back(InjectionArc(dev_null, STDERR_FILENO, true));
1027 fd_shuffle1.push_back(InjectionArc(dev_null, STDIN_FILENO, true));
1028 // Adding another element here? Remeber to increase the argument to
1029 // reserve(), above.
1031 std::copy(fd_shuffle1.begin(), fd_shuffle1.end(),
1032 std::back_inserter(fd_shuffle2));
1034 if (!ShuffleFileDescriptors(&fd_shuffle1))
1035 _exit(127);
1037 CloseSuperfluousFds(fd_shuffle2);
1039 for (size_t i = 0; i < argv.size(); i++)
1040 argv_cstr[i] = const_cast<char*>(argv[i].c_str());
1041 argv_cstr[argv.size()] = NULL;
1042 if (do_search_path)
1043 execvp(argv_cstr[0], argv_cstr.get());
1044 else
1045 execve(argv_cstr[0], argv_cstr.get(), envp);
1046 _exit(127);
1048 default: // parent
1050 // Close our writing end of pipe now. Otherwise later read would not
1051 // be able to detect end of child's output (in theory we could still
1052 // write to the pipe).
1053 close(pipe_fd[1]);
1055 output->clear();
1056 char buffer[256];
1057 size_t output_buf_left = max_output;
1058 ssize_t bytes_read = 1; // A lie to properly handle |max_output == 0|
1059 // case in the logic below.
1061 while (output_buf_left > 0) {
1062 bytes_read = HANDLE_EINTR(read(pipe_fd[0], buffer,
1063 std::min(output_buf_left, sizeof(buffer))));
1064 if (bytes_read <= 0)
1065 break;
1066 output->append(buffer, bytes_read);
1067 output_buf_left -= static_cast<size_t>(bytes_read);
1069 close(pipe_fd[0]);
1071 // Always wait for exit code (even if we know we'll declare
1072 // GOT_MAX_OUTPUT).
1073 bool success = WaitForExitCode(pid, exit_code);
1075 // If we stopped because we read as much as we wanted, we return
1076 // GOT_MAX_OUTPUT (because the child may exit due to |SIGPIPE|).
1077 if (!output_buf_left && bytes_read > 0)
1078 return GOT_MAX_OUTPUT;
1079 else if (success)
1080 return EXECUTE_SUCCESS;
1081 return EXECUTE_FAILURE;
1086 bool GetAppOutput(const CommandLine& cl, std::string* output) {
1087 return GetAppOutput(cl.argv(), output);
1090 bool GetAppOutput(const std::vector<std::string>& argv, std::string* output) {
1091 // Run |execve()| with the current environment and store "unlimited" data.
1092 int exit_code;
1093 GetAppOutputInternalResult result = GetAppOutputInternal(
1094 argv, NULL, output, std::numeric_limits<std::size_t>::max(), true,
1095 &exit_code);
1096 return result == EXECUTE_SUCCESS && exit_code == EXIT_SUCCESS;
1099 // TODO(viettrungluu): Conceivably, we should have a timeout as well, so we
1100 // don't hang if what we're calling hangs.
1101 bool GetAppOutputRestricted(const CommandLine& cl,
1102 std::string* output, size_t max_output) {
1103 // Run |execve()| with the empty environment.
1104 char* const empty_environ = NULL;
1105 int exit_code;
1106 GetAppOutputInternalResult result = GetAppOutputInternal(
1107 cl.argv(), &empty_environ, output, max_output, false, &exit_code);
1108 return result == GOT_MAX_OUTPUT || (result == EXECUTE_SUCCESS &&
1109 exit_code == EXIT_SUCCESS);
1112 bool GetAppOutputWithExitCode(const CommandLine& cl,
1113 std::string* output,
1114 int* exit_code) {
1115 // Run |execve()| with the current environment and store "unlimited" data.
1116 GetAppOutputInternalResult result = GetAppOutputInternal(
1117 cl.argv(), NULL, output, std::numeric_limits<std::size_t>::max(), true,
1118 exit_code);
1119 return result == EXECUTE_SUCCESS;
1122 bool WaitForProcessesToExit(const FilePath::StringType& executable_name,
1123 base::TimeDelta wait,
1124 const ProcessFilter* filter) {
1125 bool result = false;
1127 // TODO(port): This is inefficient, but works if there are multiple procs.
1128 // TODO(port): use waitpid to avoid leaving zombies around
1130 base::TimeTicks end_time = base::TimeTicks::Now() + wait;
1131 do {
1132 NamedProcessIterator iter(executable_name, filter);
1133 if (!iter.NextProcessEntry()) {
1134 result = true;
1135 break;
1137 base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(100));
1138 } while ((end_time - base::TimeTicks::Now()) > base::TimeDelta());
1140 return result;
1143 bool CleanupProcesses(const FilePath::StringType& executable_name,
1144 base::TimeDelta wait,
1145 int exit_code,
1146 const ProcessFilter* filter) {
1147 bool exited_cleanly = WaitForProcessesToExit(executable_name, wait, filter);
1148 if (!exited_cleanly)
1149 KillProcesses(executable_name, exit_code, filter);
1150 return exited_cleanly;
1153 #if !defined(OS_MACOSX)
1155 namespace {
1157 // Return true if the given child is dead. This will also reap the process.
1158 // Doesn't block.
1159 static bool IsChildDead(pid_t child) {
1160 const pid_t result = HANDLE_EINTR(waitpid(child, NULL, WNOHANG));
1161 if (result == -1) {
1162 DPLOG(ERROR) << "waitpid(" << child << ")";
1163 NOTREACHED();
1164 } else if (result > 0) {
1165 // The child has died.
1166 return true;
1169 return false;
1172 // A thread class which waits for the given child to exit and reaps it.
1173 // If the child doesn't exit within a couple of seconds, kill it.
1174 class BackgroundReaper : public PlatformThread::Delegate {
1175 public:
1176 BackgroundReaper(pid_t child, unsigned timeout)
1177 : child_(child),
1178 timeout_(timeout) {
1181 // Overridden from PlatformThread::Delegate:
1182 virtual void ThreadMain() OVERRIDE {
1183 WaitForChildToDie();
1184 delete this;
1187 void WaitForChildToDie() {
1188 // Wait forever case.
1189 if (timeout_ == 0) {
1190 pid_t r = HANDLE_EINTR(waitpid(child_, NULL, 0));
1191 if (r != child_) {
1192 DPLOG(ERROR) << "While waiting for " << child_
1193 << " to terminate, we got the following result: " << r;
1195 return;
1198 // There's no good way to wait for a specific child to exit in a timed
1199 // fashion. (No kqueue on Linux), so we just loop and sleep.
1201 // Wait for 2 * timeout_ 500 milliseconds intervals.
1202 for (unsigned i = 0; i < 2 * timeout_; ++i) {
1203 PlatformThread::Sleep(TimeDelta::FromMilliseconds(500));
1204 if (IsChildDead(child_))
1205 return;
1208 if (kill(child_, SIGKILL) == 0) {
1209 // SIGKILL is uncatchable. Since the signal was delivered, we can
1210 // just wait for the process to die now in a blocking manner.
1211 if (HANDLE_EINTR(waitpid(child_, NULL, 0)) < 0)
1212 DPLOG(WARNING) << "waitpid";
1213 } else {
1214 DLOG(ERROR) << "While waiting for " << child_ << " to terminate we"
1215 << " failed to deliver a SIGKILL signal (" << errno << ").";
1219 private:
1220 const pid_t child_;
1221 // Number of seconds to wait, if 0 then wait forever and do not attempt to
1222 // kill |child_|.
1223 const unsigned timeout_;
1225 DISALLOW_COPY_AND_ASSIGN(BackgroundReaper);
1228 } // namespace
1230 void EnsureProcessTerminated(ProcessHandle process) {
1231 // If the child is already dead, then there's nothing to do.
1232 if (IsChildDead(process))
1233 return;
1235 const unsigned timeout = 2; // seconds
1236 BackgroundReaper* reaper = new BackgroundReaper(process, timeout);
1237 PlatformThread::CreateNonJoinable(0, reaper);
1240 void EnsureProcessGetsReaped(ProcessHandle process) {
1241 // If the child is already dead, then there's nothing to do.
1242 if (IsChildDead(process))
1243 return;
1245 BackgroundReaper* reaper = new BackgroundReaper(process, 0);
1246 PlatformThread::CreateNonJoinable(0, reaper);
1249 #endif // !defined(OS_MACOSX)
1251 } // namespace base