Home | History | Annotate | Download | only in process
      1 // Copyright 2011 The Chromium Authors. All rights reserved.
      2 // Use of this source code is governed by a BSD-style license that can be
      3 // found in the LICENSE file.
      4 
      5 #include "base/process/process.h"
      6 
      7 #include <errno.h>
      8 #include <stdint.h>
      9 #include <sys/resource.h>
     10 #include <sys/wait.h>
     11 
     12 #include "base/files/scoped_file.h"
     13 #include "base/logging.h"
     14 #include "base/posix/eintr_wrapper.h"
     15 #include "base/process/kill.h"
     16 #include "base/third_party/dynamic_annotations/dynamic_annotations.h"
     17 #include "build/build_config.h"
     18 
     19 #if defined(OS_MACOSX)
     20 #include <sys/event.h>
     21 #endif
     22 
     23 namespace {
     24 
     25 #if !defined(OS_NACL_NONSFI)
     26 
     27 bool WaitpidWithTimeout(base::ProcessHandle handle,
     28                         int* status,
     29                         base::TimeDelta wait) {
     30   // This POSIX version of this function only guarantees that we wait no less
     31   // than |wait| for the process to exit.  The child process may
     32   // exit sometime before the timeout has ended but we may still block for up
     33   // to 256 milliseconds after the fact.
     34   //
     35   // waitpid() has no direct support on POSIX for specifying a timeout, you can
     36   // either ask it to block indefinitely or return immediately (WNOHANG).
     37   // When a child process terminates a SIGCHLD signal is sent to the parent.
     38   // Catching this signal would involve installing a signal handler which may
     39   // affect other parts of the application and would be difficult to debug.
     40   //
     41   // Our strategy is to call waitpid() once up front to check if the process
     42   // has already exited, otherwise to loop for |wait|, sleeping for
     43   // at most 256 milliseconds each time using usleep() and then calling
     44   // waitpid().  The amount of time we sleep starts out at 1 milliseconds, and
     45   // we double it every 4 sleep cycles.
     46   //
     47   // usleep() is speced to exit if a signal is received for which a handler
     48   // has been installed.  This means that when a SIGCHLD is sent, it will exit
     49   // depending on behavior external to this function.
     50   //
     51   // This function is used primarily for unit tests, if we want to use it in
     52   // the application itself it would probably be best to examine other routes.
     53 
     54   if (wait == base::TimeDelta::Max()) {
     55     return HANDLE_EINTR(waitpid(handle, status, 0)) > 0;
     56   }
     57 
     58   pid_t ret_pid = HANDLE_EINTR(waitpid(handle, status, WNOHANG));
     59   static const int64_t kMaxSleepInMicroseconds = 1 << 18;  // ~256 milliseconds.
     60   int64_t max_sleep_time_usecs = 1 << 10;                  // ~1 milliseconds.
     61   int64_t double_sleep_time = 0;
     62 
     63   // If the process hasn't exited yet, then sleep and try again.
     64   base::TimeTicks wakeup_time = base::TimeTicks::Now() + wait;
     65   while (ret_pid == 0) {
     66     base::TimeTicks now = base::TimeTicks::Now();
     67     if (now > wakeup_time)
     68       break;
     69     // Guaranteed to be non-negative!
     70     int64_t sleep_time_usecs = (wakeup_time - now).InMicroseconds();
     71     // Sleep for a bit while we wait for the process to finish.
     72     if (sleep_time_usecs > max_sleep_time_usecs)
     73       sleep_time_usecs = max_sleep_time_usecs;
     74 
     75     // usleep() will return 0 and set errno to EINTR on receipt of a signal
     76     // such as SIGCHLD.
     77     usleep(sleep_time_usecs);
     78     ret_pid = HANDLE_EINTR(waitpid(handle, status, WNOHANG));
     79 
     80     if ((max_sleep_time_usecs < kMaxSleepInMicroseconds) &&
     81         (double_sleep_time++ % 4 == 0)) {
     82       max_sleep_time_usecs *= 2;
     83     }
     84   }
     85 
     86   return ret_pid > 0;
     87 }
     88 
     89 #if defined(OS_MACOSX)
     90 // Using kqueue on Mac so that we can wait on non-child processes.
     91 // We can't use kqueues on child processes because we need to reap
     92 // our own children using wait.
     93 static bool WaitForSingleNonChildProcess(base::ProcessHandle handle,
     94                                          base::TimeDelta wait) {
     95   DCHECK_GT(handle, 0);
     96   DCHECK_GT(wait, base::TimeDelta());
     97 
     98   base::ScopedFD kq(kqueue());
     99   if (!kq.is_valid()) {
    100     DPLOG(ERROR) << "kqueue";
    101     return false;
    102   }
    103 
    104 #if defined(ANDROID)
    105   struct kevent change;
    106   memset(&change, 0, sizeof(change));
    107 #else
    108   struct kevent change = {0};
    109 #endif
    110   EV_SET(&change, handle, EVFILT_PROC, EV_ADD, NOTE_EXIT, 0, NULL);
    111   int result = HANDLE_EINTR(kevent(kq.get(), &change, 1, NULL, 0, NULL));
    112   if (result == -1) {
    113     if (errno == ESRCH) {
    114       // If the process wasn't found, it must be dead.
    115       return true;
    116     }
    117 
    118     DPLOG(ERROR) << "kevent (setup " << handle << ")";
    119     return false;
    120   }
    121 
    122   // Keep track of the elapsed time to be able to restart kevent if it's
    123   // interrupted.
    124   bool wait_forever = (wait == base::TimeDelta::Max());
    125   base::TimeDelta remaining_delta;
    126   base::TimeTicks deadline;
    127   if (!wait_forever) {
    128     remaining_delta = wait;
    129     deadline = base::TimeTicks::Now() + remaining_delta;
    130   }
    131 
    132   result = -1;
    133 #if defined(ANDROID)
    134   struct kevent event;
    135   memset(&event, 0, sizeof(event));
    136 #else
    137   struct kevent event = {0};
    138 #endif
    139 
    140   while (wait_forever || remaining_delta > base::TimeDelta()) {
    141     struct timespec remaining_timespec;
    142     struct timespec* remaining_timespec_ptr;
    143     if (wait_forever) {
    144       remaining_timespec_ptr = NULL;
    145     } else {
    146       remaining_timespec = remaining_delta.ToTimeSpec();
    147       remaining_timespec_ptr = &remaining_timespec;
    148     }
    149 
    150     result = kevent(kq.get(), NULL, 0, &event, 1, remaining_timespec_ptr);
    151 
    152     if (result == -1 && errno == EINTR) {
    153       if (!wait_forever) {
    154         remaining_delta = deadline - base::TimeTicks::Now();
    155       }
    156       result = 0;
    157     } else {
    158       break;
    159     }
    160   }
    161 
    162   if (result < 0) {
    163     DPLOG(ERROR) << "kevent (wait " << handle << ")";
    164     return false;
    165   } else if (result > 1) {
    166     DLOG(ERROR) << "kevent (wait " << handle << "): unexpected result "
    167                 << result;
    168     return false;
    169   } else if (result == 0) {
    170     // Timed out.
    171     return false;
    172   }
    173 
    174   DCHECK_EQ(result, 1);
    175 
    176   if (event.filter != EVFILT_PROC ||
    177       (event.fflags & NOTE_EXIT) == 0 ||
    178       event.ident != static_cast<uintptr_t>(handle)) {
    179     DLOG(ERROR) << "kevent (wait " << handle
    180                 << "): unexpected event: filter=" << event.filter
    181                 << ", fflags=" << event.fflags
    182                 << ", ident=" << event.ident;
    183     return false;
    184   }
    185 
    186   return true;
    187 }
    188 #endif  // OS_MACOSX
    189 
    190 bool WaitForExitWithTimeoutImpl(base::ProcessHandle handle,
    191                                 int* exit_code,
    192                                 base::TimeDelta timeout) {
    193   base::ProcessHandle parent_pid = base::GetParentProcessId(handle);
    194   base::ProcessHandle our_pid = base::GetCurrentProcessHandle();
    195   if (parent_pid != our_pid) {
    196 #if defined(OS_MACOSX)
    197     // On Mac we can wait on non child processes.
    198     return WaitForSingleNonChildProcess(handle, timeout);
    199 #else
    200     // Currently on Linux we can't handle non child processes.
    201     NOTIMPLEMENTED();
    202 #endif  // OS_MACOSX
    203   }
    204 
    205   int status;
    206   if (!WaitpidWithTimeout(handle, &status, timeout))
    207     return false;
    208   if (WIFSIGNALED(status)) {
    209     if (exit_code)
    210       *exit_code = -1;
    211     return true;
    212   }
    213   if (WIFEXITED(status)) {
    214     if (exit_code)
    215       *exit_code = WEXITSTATUS(status);
    216     return true;
    217   }
    218   return false;
    219 }
    220 #endif  // !defined(OS_NACL_NONSFI)
    221 
    222 }  // namespace
    223 
    224 namespace base {
    225 
    226 Process::Process(ProcessHandle handle) : process_(handle) {
    227 }
    228 
    229 Process::~Process() {
    230 }
    231 
    232 Process::Process(Process&& other) : process_(other.process_) {
    233   other.Close();
    234 }
    235 
    236 Process& Process::operator=(Process&& other) {
    237   DCHECK_NE(this, &other);
    238   process_ = other.process_;
    239   other.Close();
    240   return *this;
    241 }
    242 
    243 // static
    244 Process Process::Current() {
    245   return Process(GetCurrentProcessHandle());
    246 }
    247 
    248 // static
    249 Process Process::Open(ProcessId pid) {
    250   if (pid == GetCurrentProcId())
    251     return Current();
    252 
    253   // On POSIX process handles are the same as PIDs.
    254   return Process(pid);
    255 }
    256 
    257 // static
    258 Process Process::OpenWithExtraPrivileges(ProcessId pid) {
    259   // On POSIX there are no privileges to set.
    260   return Open(pid);
    261 }
    262 
    263 // static
    264 Process Process::DeprecatedGetProcessFromHandle(ProcessHandle handle) {
    265   DCHECK_NE(handle, GetCurrentProcessHandle());
    266   return Process(handle);
    267 }
    268 
    269 #if !defined(OS_LINUX)
    270 // static
    271 bool Process::CanBackgroundProcesses() {
    272   return false;
    273 }
    274 #endif  // !defined(OS_LINUX)
    275 
    276 bool Process::IsValid() const {
    277   return process_ != kNullProcessHandle;
    278 }
    279 
    280 ProcessHandle Process::Handle() const {
    281   return process_;
    282 }
    283 
    284 Process Process::Duplicate() const {
    285   if (is_current())
    286     return Current();
    287 
    288   return Process(process_);
    289 }
    290 
    291 ProcessId Process::Pid() const {
    292   DCHECK(IsValid());
    293   return GetProcId(process_);
    294 }
    295 
    296 bool Process::is_current() const {
    297   return process_ == GetCurrentProcessHandle();
    298 }
    299 
    300 void Process::Close() {
    301   process_ = kNullProcessHandle;
    302   // if the process wasn't terminated (so we waited) or the state
    303   // wasn't already collected w/ a wait from process_utils, we're gonna
    304   // end up w/ a zombie when it does finally exit.
    305 }
    306 
    307 #if !defined(OS_NACL_NONSFI)
    308 bool Process::Terminate(int /*exit_code*/, bool wait) const {
    309   // exit_code isn't supportable.
    310   DCHECK(IsValid());
    311   CHECK_GT(process_, 0);
    312 
    313   bool result = kill(process_, SIGTERM) == 0;
    314   if (result && wait) {
    315     int tries = 60;
    316 
    317     unsigned sleep_ms = 4;
    318 
    319     // The process may not end immediately due to pending I/O
    320     bool exited = false;
    321     while (tries-- > 0) {
    322       pid_t pid = HANDLE_EINTR(waitpid(process_, NULL, WNOHANG));
    323       if (pid == process_) {
    324         exited = true;
    325         break;
    326       }
    327       if (pid == -1) {
    328         if (errno == ECHILD) {
    329           // The wait may fail with ECHILD if another process also waited for
    330           // the same pid, causing the process state to get cleaned up.
    331           exited = true;
    332           break;
    333         }
    334         DPLOG(ERROR) << "Error waiting for process " << process_;
    335       }
    336 
    337       usleep(sleep_ms * 1000);
    338       const unsigned kMaxSleepMs = 1000;
    339       if (sleep_ms < kMaxSleepMs)
    340         sleep_ms *= 2;
    341     }
    342 
    343     // If we're waiting and the child hasn't died by now, force it
    344     // with a SIGKILL.
    345     if (!exited)
    346       result = kill(process_, SIGKILL) == 0;
    347   }
    348 
    349   if (!result)
    350     DPLOG(ERROR) << "Unable to terminate process " << process_;
    351 
    352   return result;
    353 }
    354 #endif  // !defined(OS_NACL_NONSFI)
    355 
    356 bool Process::WaitForExit(int* exit_code) {
    357   return WaitForExitWithTimeout(TimeDelta::Max(), exit_code);
    358 }
    359 
    360 bool Process::WaitForExitWithTimeout(TimeDelta timeout, int* exit_code) {
    361   return WaitForExitWithTimeoutImpl(Handle(), exit_code, timeout);
    362 }
    363 
    364 #if !defined(OS_LINUX)
    365 bool Process::IsProcessBackgrounded() const {
    366   // See SetProcessBackgrounded().
    367   DCHECK(IsValid());
    368   return false;
    369 }
    370 
    371 bool Process::SetProcessBackgrounded(bool /*value*/) {
    372   // Not implemented for POSIX systems other than Linux. With POSIX, if we were
    373   // to lower the process priority we wouldn't be able to raise it back to its
    374   // initial priority.
    375   NOTIMPLEMENTED();
    376   return false;
    377 }
    378 #endif  // !defined(OS_LINUX)
    379 
    380 int Process::GetPriority() const {
    381   DCHECK(IsValid());
    382   return getpriority(PRIO_PROCESS, process_);
    383 }
    384 
    385 }  // namespace base
    386