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