cc: Fix MSAA when threaded GPU rasterization is enabled.
[chromium-blink-merge.git] / base / process / kill_posix.cc
blob5e8b61f6b86be7eb6ddc11ce503f733c37a74b8c
1 // Copyright (c) 2013 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 "base/process/kill.h"
7 #include <signal.h>
8 #include <sys/types.h>
9 #include <sys/wait.h>
10 #include <unistd.h>
12 #include "base/files/file_util.h"
13 #include "base/files/scoped_file.h"
14 #include "base/logging.h"
15 #include "base/posix/eintr_wrapper.h"
16 #include "base/process/process_iterator.h"
17 #include "base/synchronization/waitable_event.h"
18 #include "base/third_party/dynamic_annotations/dynamic_annotations.h"
19 #include "base/threading/platform_thread.h"
21 namespace base {
23 namespace {
25 #if !defined(OS_NACL_NONSFI)
26 bool WaitpidWithTimeout(ProcessHandle handle,
27 int* status,
28 base::TimeDelta wait) {
29 // This POSIX version of this function only guarantees that we wait no less
30 // than |wait| for the process to exit. The child process may
31 // exit sometime before the timeout has ended but we may still block for up
32 // to 256 milliseconds after the fact.
34 // waitpid() has no direct support on POSIX for specifying a timeout, you can
35 // either ask it to block indefinitely or return immediately (WNOHANG).
36 // When a child process terminates a SIGCHLD signal is sent to the parent.
37 // Catching this signal would involve installing a signal handler which may
38 // affect other parts of the application and would be difficult to debug.
40 // Our strategy is to call waitpid() once up front to check if the process
41 // has already exited, otherwise to loop for |wait|, sleeping for
42 // at most 256 milliseconds each time using usleep() and then calling
43 // waitpid(). The amount of time we sleep starts out at 1 milliseconds, and
44 // we double it every 4 sleep cycles.
46 // usleep() is speced to exit if a signal is received for which a handler
47 // has been installed. This means that when a SIGCHLD is sent, it will exit
48 // depending on behavior external to this function.
50 // This function is used primarily for unit tests, if we want to use it in
51 // the application itself it would probably be best to examine other routes.
53 if (wait.InMilliseconds() == base::kNoTimeout) {
54 return HANDLE_EINTR(waitpid(handle, status, 0)) > 0;
57 pid_t ret_pid = HANDLE_EINTR(waitpid(handle, status, WNOHANG));
58 static const int64 kMaxSleepInMicroseconds = 1 << 18; // ~256 milliseconds.
59 int64 max_sleep_time_usecs = 1 << 10; // ~1 milliseconds.
60 int64 double_sleep_time = 0;
62 // If the process hasn't exited yet, then sleep and try again.
63 TimeTicks wakeup_time = TimeTicks::Now() + wait;
64 while (ret_pid == 0) {
65 TimeTicks now = TimeTicks::Now();
66 if (now > wakeup_time)
67 break;
68 // Guaranteed to be non-negative!
69 int64 sleep_time_usecs = (wakeup_time - now).InMicroseconds();
70 // Sleep for a bit while we wait for the process to finish.
71 if (sleep_time_usecs > max_sleep_time_usecs)
72 sleep_time_usecs = max_sleep_time_usecs;
74 // usleep() will return 0 and set errno to EINTR on receipt of a signal
75 // such as SIGCHLD.
76 usleep(sleep_time_usecs);
77 ret_pid = HANDLE_EINTR(waitpid(handle, status, WNOHANG));
79 if ((max_sleep_time_usecs < kMaxSleepInMicroseconds) &&
80 (double_sleep_time++ % 4 == 0)) {
81 max_sleep_time_usecs *= 2;
85 return ret_pid > 0;
87 #endif // !defined(OS_NACL_NONSFI)
89 TerminationStatus GetTerminationStatusImpl(ProcessHandle handle,
90 bool can_block,
91 int* exit_code) {
92 int status = 0;
93 const pid_t result = HANDLE_EINTR(waitpid(handle, &status,
94 can_block ? 0 : WNOHANG));
95 if (result == -1) {
96 DPLOG(ERROR) << "waitpid(" << handle << ")";
97 if (exit_code)
98 *exit_code = 0;
99 return TERMINATION_STATUS_NORMAL_TERMINATION;
100 } else if (result == 0) {
101 // the child hasn't exited yet.
102 if (exit_code)
103 *exit_code = 0;
104 return TERMINATION_STATUS_STILL_RUNNING;
107 if (exit_code)
108 *exit_code = status;
110 if (WIFSIGNALED(status)) {
111 switch (WTERMSIG(status)) {
112 case SIGABRT:
113 case SIGBUS:
114 case SIGFPE:
115 case SIGILL:
116 case SIGSEGV:
117 return TERMINATION_STATUS_PROCESS_CRASHED;
118 case SIGINT:
119 case SIGKILL:
120 case SIGTERM:
121 return TERMINATION_STATUS_PROCESS_WAS_KILLED;
122 default:
123 break;
127 if (WIFEXITED(status) && WEXITSTATUS(status) != 0)
128 return TERMINATION_STATUS_ABNORMAL_TERMINATION;
130 return TERMINATION_STATUS_NORMAL_TERMINATION;
133 } // namespace
135 #if !defined(OS_NACL_NONSFI)
136 // Attempts to kill the process identified by the given process
137 // entry structure. Ignores specified exit_code; posix can't force that.
138 // Returns true if this is successful, false otherwise.
139 bool KillProcess(ProcessHandle process_id, int exit_code, bool wait) {
140 DCHECK_GT(process_id, 1) << " tried to kill invalid process_id";
141 if (process_id <= 1)
142 return false;
143 bool result = kill(process_id, SIGTERM) == 0;
144 if (result && wait) {
145 int tries = 60;
147 if (RunningOnValgrind()) {
148 // Wait for some extra time when running under Valgrind since the child
149 // processes may take some time doing leak checking.
150 tries *= 2;
153 unsigned sleep_ms = 4;
155 // The process may not end immediately due to pending I/O
156 bool exited = false;
157 while (tries-- > 0) {
158 pid_t pid = HANDLE_EINTR(waitpid(process_id, NULL, WNOHANG));
159 if (pid == process_id) {
160 exited = true;
161 break;
163 if (pid == -1) {
164 if (errno == ECHILD) {
165 // The wait may fail with ECHILD if another process also waited for
166 // the same pid, causing the process state to get cleaned up.
167 exited = true;
168 break;
170 DPLOG(ERROR) << "Error waiting for process " << process_id;
173 usleep(sleep_ms * 1000);
174 const unsigned kMaxSleepMs = 1000;
175 if (sleep_ms < kMaxSleepMs)
176 sleep_ms *= 2;
179 // If we're waiting and the child hasn't died by now, force it
180 // with a SIGKILL.
181 if (!exited)
182 result = kill(process_id, SIGKILL) == 0;
185 if (!result)
186 DPLOG(ERROR) << "Unable to terminate process " << process_id;
188 return result;
191 bool KillProcessGroup(ProcessHandle process_group_id) {
192 bool result = kill(-1 * process_group_id, SIGKILL) == 0;
193 if (!result)
194 DPLOG(ERROR) << "Unable to terminate process group " << process_group_id;
195 return result;
197 #endif // !defined(OS_NACL_NONSFI)
199 TerminationStatus GetTerminationStatus(ProcessHandle handle, int* exit_code) {
200 return GetTerminationStatusImpl(handle, false /* can_block */, exit_code);
203 TerminationStatus GetKnownDeadTerminationStatus(ProcessHandle handle,
204 int* exit_code) {
205 bool result = kill(handle, SIGKILL) == 0;
207 if (!result)
208 DPLOG(ERROR) << "Unable to terminate process " << handle;
210 return GetTerminationStatusImpl(handle, true /* can_block */, exit_code);
213 #if !defined(OS_NACL_NONSFI)
214 bool WaitForExitCode(ProcessHandle handle, int* exit_code) {
215 int status;
216 if (HANDLE_EINTR(waitpid(handle, &status, 0)) == -1) {
217 NOTREACHED();
218 return false;
221 if (WIFEXITED(status)) {
222 *exit_code = WEXITSTATUS(status);
223 return true;
226 // If it didn't exit cleanly, it must have been signaled.
227 DCHECK(WIFSIGNALED(status));
228 return false;
231 bool WaitForExitCodeWithTimeout(ProcessHandle handle,
232 int* exit_code,
233 base::TimeDelta timeout) {
234 int status;
235 if (!WaitpidWithTimeout(handle, &status, timeout))
236 return false;
237 if (WIFSIGNALED(status)) {
238 *exit_code = -1;
239 return true;
241 if (WIFEXITED(status)) {
242 *exit_code = WEXITSTATUS(status);
243 return true;
245 return false;
248 bool WaitForProcessesToExit(const FilePath::StringType& executable_name,
249 base::TimeDelta wait,
250 const ProcessFilter* filter) {
251 bool result = false;
253 // TODO(port): This is inefficient, but works if there are multiple procs.
254 // TODO(port): use waitpid to avoid leaving zombies around
256 base::TimeTicks end_time = base::TimeTicks::Now() + wait;
257 do {
258 NamedProcessIterator iter(executable_name, filter);
259 if (!iter.NextProcessEntry()) {
260 result = true;
261 break;
263 base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(100));
264 } while ((end_time - base::TimeTicks::Now()) > base::TimeDelta());
266 return result;
269 #if defined(OS_MACOSX)
270 // Using kqueue on Mac so that we can wait on non-child processes.
271 // We can't use kqueues on child processes because we need to reap
272 // our own children using wait.
273 static bool WaitForSingleNonChildProcess(ProcessHandle handle,
274 base::TimeDelta wait) {
275 DCHECK_GT(handle, 0);
276 DCHECK(wait.InMilliseconds() == base::kNoTimeout || wait > base::TimeDelta());
278 ScopedFD kq(kqueue());
279 if (!kq.is_valid()) {
280 DPLOG(ERROR) << "kqueue";
281 return false;
284 struct kevent change = {0};
285 EV_SET(&change, handle, EVFILT_PROC, EV_ADD, NOTE_EXIT, 0, NULL);
286 int result = HANDLE_EINTR(kevent(kq.get(), &change, 1, NULL, 0, NULL));
287 if (result == -1) {
288 if (errno == ESRCH) {
289 // If the process wasn't found, it must be dead.
290 return true;
293 DPLOG(ERROR) << "kevent (setup " << handle << ")";
294 return false;
297 // Keep track of the elapsed time to be able to restart kevent if it's
298 // interrupted.
299 bool wait_forever = wait.InMilliseconds() == base::kNoTimeout;
300 base::TimeDelta remaining_delta;
301 base::TimeTicks deadline;
302 if (!wait_forever) {
303 remaining_delta = wait;
304 deadline = base::TimeTicks::Now() + remaining_delta;
307 result = -1;
308 struct kevent event = {0};
310 while (wait_forever || remaining_delta > base::TimeDelta()) {
311 struct timespec remaining_timespec;
312 struct timespec* remaining_timespec_ptr;
313 if (wait_forever) {
314 remaining_timespec_ptr = NULL;
315 } else {
316 remaining_timespec = remaining_delta.ToTimeSpec();
317 remaining_timespec_ptr = &remaining_timespec;
320 result = kevent(kq.get(), NULL, 0, &event, 1, remaining_timespec_ptr);
322 if (result == -1 && errno == EINTR) {
323 if (!wait_forever) {
324 remaining_delta = deadline - base::TimeTicks::Now();
326 result = 0;
327 } else {
328 break;
332 if (result < 0) {
333 DPLOG(ERROR) << "kevent (wait " << handle << ")";
334 return false;
335 } else if (result > 1) {
336 DLOG(ERROR) << "kevent (wait " << handle << "): unexpected result "
337 << result;
338 return false;
339 } else if (result == 0) {
340 // Timed out.
341 return false;
344 DCHECK_EQ(result, 1);
346 if (event.filter != EVFILT_PROC ||
347 (event.fflags & NOTE_EXIT) == 0 ||
348 event.ident != static_cast<uintptr_t>(handle)) {
349 DLOG(ERROR) << "kevent (wait " << handle
350 << "): unexpected event: filter=" << event.filter
351 << ", fflags=" << event.fflags
352 << ", ident=" << event.ident;
353 return false;
356 return true;
358 #endif // OS_MACOSX
360 bool WaitForSingleProcess(ProcessHandle handle, base::TimeDelta wait) {
361 ProcessHandle parent_pid = GetParentProcessId(handle);
362 ProcessHandle our_pid = GetCurrentProcessHandle();
363 if (parent_pid != our_pid) {
364 #if defined(OS_MACOSX)
365 // On Mac we can wait on non child processes.
366 return WaitForSingleNonChildProcess(handle, wait);
367 #else
368 // Currently on Linux we can't handle non child processes.
369 NOTIMPLEMENTED();
370 #endif // OS_MACOSX
373 int status;
374 if (!WaitpidWithTimeout(handle, &status, wait))
375 return false;
376 return WIFEXITED(status);
379 bool CleanupProcesses(const FilePath::StringType& executable_name,
380 base::TimeDelta wait,
381 int exit_code,
382 const ProcessFilter* filter) {
383 bool exited_cleanly = WaitForProcessesToExit(executable_name, wait, filter);
384 if (!exited_cleanly)
385 KillProcesses(executable_name, exit_code, filter);
386 return exited_cleanly;
389 #if !defined(OS_MACOSX)
391 namespace {
393 // Return true if the given child is dead. This will also reap the process.
394 // Doesn't block.
395 static bool IsChildDead(pid_t child) {
396 const pid_t result = HANDLE_EINTR(waitpid(child, NULL, WNOHANG));
397 if (result == -1) {
398 DPLOG(ERROR) << "waitpid(" << child << ")";
399 NOTREACHED();
400 } else if (result > 0) {
401 // The child has died.
402 return true;
405 return false;
408 // A thread class which waits for the given child to exit and reaps it.
409 // If the child doesn't exit within a couple of seconds, kill it.
410 class BackgroundReaper : public PlatformThread::Delegate {
411 public:
412 BackgroundReaper(pid_t child, unsigned timeout)
413 : child_(child),
414 timeout_(timeout) {
417 // Overridden from PlatformThread::Delegate:
418 void ThreadMain() override {
419 WaitForChildToDie();
420 delete this;
423 void WaitForChildToDie() {
424 // Wait forever case.
425 if (timeout_ == 0) {
426 pid_t r = HANDLE_EINTR(waitpid(child_, NULL, 0));
427 if (r != child_) {
428 DPLOG(ERROR) << "While waiting for " << child_
429 << " to terminate, we got the following result: " << r;
431 return;
434 // There's no good way to wait for a specific child to exit in a timed
435 // fashion. (No kqueue on Linux), so we just loop and sleep.
437 // Wait for 2 * timeout_ 500 milliseconds intervals.
438 for (unsigned i = 0; i < 2 * timeout_; ++i) {
439 PlatformThread::Sleep(TimeDelta::FromMilliseconds(500));
440 if (IsChildDead(child_))
441 return;
444 if (kill(child_, SIGKILL) == 0) {
445 // SIGKILL is uncatchable. Since the signal was delivered, we can
446 // just wait for the process to die now in a blocking manner.
447 if (HANDLE_EINTR(waitpid(child_, NULL, 0)) < 0)
448 DPLOG(WARNING) << "waitpid";
449 } else {
450 DLOG(ERROR) << "While waiting for " << child_ << " to terminate we"
451 << " failed to deliver a SIGKILL signal (" << errno << ").";
455 private:
456 const pid_t child_;
457 // Number of seconds to wait, if 0 then wait forever and do not attempt to
458 // kill |child_|.
459 const unsigned timeout_;
461 DISALLOW_COPY_AND_ASSIGN(BackgroundReaper);
464 } // namespace
466 void EnsureProcessTerminated(Process process) {
467 // If the child is already dead, then there's nothing to do.
468 if (IsChildDead(process.Pid()))
469 return;
471 const unsigned timeout = 2; // seconds
472 BackgroundReaper* reaper = new BackgroundReaper(process.Pid(), timeout);
473 PlatformThread::CreateNonJoinable(0, reaper);
476 void EnsureProcessGetsReaped(ProcessId pid) {
477 // If the child is already dead, then there's nothing to do.
478 if (IsChildDead(pid))
479 return;
481 BackgroundReaper* reaper = new BackgroundReaper(pid, 0);
482 PlatformThread::CreateNonJoinable(0, reaper);
485 #endif // !defined(OS_MACOSX)
486 #endif // !defined(OS_NACL_NONSFI)
488 } // namespace base