ozone: evdev: Sync caps lock LED state to evdev
[chromium-blink-merge.git] / base / process / kill_posix.cc
blob77705eeb6789b0a53a81ae11c468b2270e3a736e
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;
88 #if defined(OS_MACOSX)
89 // Using kqueue on Mac so that we can wait on non-child processes.
90 // We can't use kqueues on child processes because we need to reap
91 // our own children using wait.
92 static bool WaitForSingleNonChildProcess(ProcessHandle handle,
93 TimeDelta wait) {
94 DCHECK_GT(handle, 0);
95 DCHECK(wait.InMilliseconds() == kNoTimeout || wait > TimeDelta());
97 ScopedFD kq(kqueue());
98 if (!kq.is_valid()) {
99 DPLOG(ERROR) << "kqueue";
100 return false;
103 struct kevent change = {0};
104 EV_SET(&change, handle, EVFILT_PROC, EV_ADD, NOTE_EXIT, 0, NULL);
105 int result = HANDLE_EINTR(kevent(kq.get(), &change, 1, NULL, 0, NULL));
106 if (result == -1) {
107 if (errno == ESRCH) {
108 // If the process wasn't found, it must be dead.
109 return true;
112 DPLOG(ERROR) << "kevent (setup " << handle << ")";
113 return false;
116 // Keep track of the elapsed time to be able to restart kevent if it's
117 // interrupted.
118 bool wait_forever = wait.InMilliseconds() == kNoTimeout;
119 TimeDelta remaining_delta;
120 TimeTicks deadline;
121 if (!wait_forever) {
122 remaining_delta = wait;
123 deadline = TimeTicks::Now() + remaining_delta;
126 result = -1;
127 struct kevent event = {0};
129 while (wait_forever || remaining_delta > TimeDelta()) {
130 struct timespec remaining_timespec;
131 struct timespec* remaining_timespec_ptr;
132 if (wait_forever) {
133 remaining_timespec_ptr = NULL;
134 } else {
135 remaining_timespec = remaining_delta.ToTimeSpec();
136 remaining_timespec_ptr = &remaining_timespec;
139 result = kevent(kq.get(), NULL, 0, &event, 1, remaining_timespec_ptr);
141 if (result == -1 && errno == EINTR) {
142 if (!wait_forever) {
143 remaining_delta = deadline - TimeTicks::Now();
145 result = 0;
146 } else {
147 break;
151 if (result < 0) {
152 DPLOG(ERROR) << "kevent (wait " << handle << ")";
153 return false;
154 } else if (result > 1) {
155 DLOG(ERROR) << "kevent (wait " << handle << "): unexpected result "
156 << result;
157 return false;
158 } else if (result == 0) {
159 // Timed out.
160 return false;
163 DCHECK_EQ(result, 1);
165 if (event.filter != EVFILT_PROC ||
166 (event.fflags & NOTE_EXIT) == 0 ||
167 event.ident != static_cast<uintptr_t>(handle)) {
168 DLOG(ERROR) << "kevent (wait " << handle
169 << "): unexpected event: filter=" << event.filter
170 << ", fflags=" << event.fflags
171 << ", ident=" << event.ident;
172 return false;
175 return true;
177 #endif // OS_MACOSX
178 #endif // !defined(OS_NACL_NONSFI)
180 TerminationStatus GetTerminationStatusImpl(ProcessHandle handle,
181 bool can_block,
182 int* exit_code) {
183 int status = 0;
184 const pid_t result = HANDLE_EINTR(waitpid(handle, &status,
185 can_block ? 0 : WNOHANG));
186 if (result == -1) {
187 DPLOG(ERROR) << "waitpid(" << handle << ")";
188 if (exit_code)
189 *exit_code = 0;
190 return TERMINATION_STATUS_NORMAL_TERMINATION;
191 } else if (result == 0) {
192 // the child hasn't exited yet.
193 if (exit_code)
194 *exit_code = 0;
195 return TERMINATION_STATUS_STILL_RUNNING;
198 if (exit_code)
199 *exit_code = status;
201 if (WIFSIGNALED(status)) {
202 switch (WTERMSIG(status)) {
203 case SIGABRT:
204 case SIGBUS:
205 case SIGFPE:
206 case SIGILL:
207 case SIGSEGV:
208 return TERMINATION_STATUS_PROCESS_CRASHED;
209 case SIGINT:
210 case SIGKILL:
211 case SIGTERM:
212 return TERMINATION_STATUS_PROCESS_WAS_KILLED;
213 default:
214 break;
218 if (WIFEXITED(status) && WEXITSTATUS(status) != 0)
219 return TERMINATION_STATUS_ABNORMAL_TERMINATION;
221 return TERMINATION_STATUS_NORMAL_TERMINATION;
224 } // namespace
226 #if !defined(OS_NACL_NONSFI)
227 // Attempts to kill the process identified by the given process
228 // entry structure. Ignores specified exit_code; posix can't force that.
229 // Returns true if this is successful, false otherwise.
230 bool KillProcess(ProcessHandle process_id, int exit_code, bool wait) {
231 DCHECK_GT(process_id, 1) << " tried to kill invalid process_id";
232 if (process_id <= 1)
233 return false;
234 bool result = kill(process_id, SIGTERM) == 0;
235 if (result && wait) {
236 int tries = 60;
238 if (RunningOnValgrind()) {
239 // Wait for some extra time when running under Valgrind since the child
240 // processes may take some time doing leak checking.
241 tries *= 2;
244 unsigned sleep_ms = 4;
246 // The process may not end immediately due to pending I/O
247 bool exited = false;
248 while (tries-- > 0) {
249 pid_t pid = HANDLE_EINTR(waitpid(process_id, NULL, WNOHANG));
250 if (pid == process_id) {
251 exited = true;
252 break;
254 if (pid == -1) {
255 if (errno == ECHILD) {
256 // The wait may fail with ECHILD if another process also waited for
257 // the same pid, causing the process state to get cleaned up.
258 exited = true;
259 break;
261 DPLOG(ERROR) << "Error waiting for process " << process_id;
264 usleep(sleep_ms * 1000);
265 const unsigned kMaxSleepMs = 1000;
266 if (sleep_ms < kMaxSleepMs)
267 sleep_ms *= 2;
270 // If we're waiting and the child hasn't died by now, force it
271 // with a SIGKILL.
272 if (!exited)
273 result = kill(process_id, SIGKILL) == 0;
276 if (!result)
277 DPLOG(ERROR) << "Unable to terminate process " << process_id;
279 return result;
282 bool KillProcessGroup(ProcessHandle process_group_id) {
283 bool result = kill(-1 * process_group_id, SIGKILL) == 0;
284 if (!result)
285 DPLOG(ERROR) << "Unable to terminate process group " << process_group_id;
286 return result;
288 #endif // !defined(OS_NACL_NONSFI)
290 TerminationStatus GetTerminationStatus(ProcessHandle handle, int* exit_code) {
291 return GetTerminationStatusImpl(handle, false /* can_block */, exit_code);
294 TerminationStatus GetKnownDeadTerminationStatus(ProcessHandle handle,
295 int* exit_code) {
296 bool result = kill(handle, SIGKILL) == 0;
298 if (!result)
299 DPLOG(ERROR) << "Unable to terminate process " << handle;
301 return GetTerminationStatusImpl(handle, true /* can_block */, exit_code);
304 #if !defined(OS_NACL_NONSFI)
305 bool WaitForExitCode(ProcessHandle handle, int* exit_code) {
306 int status;
307 if (HANDLE_EINTR(waitpid(handle, &status, 0)) == -1) {
308 NOTREACHED();
309 return false;
312 if (WIFEXITED(status)) {
313 *exit_code = WEXITSTATUS(status);
314 return true;
317 // If it didn't exit cleanly, it must have been signaled.
318 DCHECK(WIFSIGNALED(status));
319 return false;
322 bool WaitForExitCodeWithTimeout(ProcessHandle handle,
323 int* exit_code,
324 TimeDelta timeout) {
325 ProcessHandle parent_pid = GetParentProcessId(handle);
326 ProcessHandle our_pid = GetCurrentProcessHandle();
327 if (parent_pid != our_pid) {
328 #if defined(OS_MACOSX)
329 // On Mac we can wait on non child processes.
330 return WaitForSingleNonChildProcess(handle, timeout);
331 #else
332 // Currently on Linux we can't handle non child processes.
333 NOTIMPLEMENTED();
334 #endif // OS_MACOSX
337 int status;
338 if (!WaitpidWithTimeout(handle, &status, timeout))
339 return false;
340 if (WIFSIGNALED(status)) {
341 *exit_code = -1;
342 return true;
344 if (WIFEXITED(status)) {
345 *exit_code = WEXITSTATUS(status);
346 return true;
348 return false;
351 bool WaitForProcessesToExit(const FilePath::StringType& executable_name,
352 TimeDelta wait,
353 const ProcessFilter* filter) {
354 bool result = false;
356 // TODO(port): This is inefficient, but works if there are multiple procs.
357 // TODO(port): use waitpid to avoid leaving zombies around
359 TimeTicks end_time = TimeTicks::Now() + wait;
360 do {
361 NamedProcessIterator iter(executable_name, filter);
362 if (!iter.NextProcessEntry()) {
363 result = true;
364 break;
366 PlatformThread::Sleep(TimeDelta::FromMilliseconds(100));
367 } while ((end_time - TimeTicks::Now()) > TimeDelta());
369 return result;
372 bool CleanupProcesses(const FilePath::StringType& executable_name,
373 TimeDelta wait,
374 int exit_code,
375 const ProcessFilter* filter) {
376 bool exited_cleanly = WaitForProcessesToExit(executable_name, wait, filter);
377 if (!exited_cleanly)
378 KillProcesses(executable_name, exit_code, filter);
379 return exited_cleanly;
382 #if !defined(OS_MACOSX)
384 namespace {
386 // Return true if the given child is dead. This will also reap the process.
387 // Doesn't block.
388 static bool IsChildDead(pid_t child) {
389 const pid_t result = HANDLE_EINTR(waitpid(child, NULL, WNOHANG));
390 if (result == -1) {
391 DPLOG(ERROR) << "waitpid(" << child << ")";
392 NOTREACHED();
393 } else if (result > 0) {
394 // The child has died.
395 return true;
398 return false;
401 // A thread class which waits for the given child to exit and reaps it.
402 // If the child doesn't exit within a couple of seconds, kill it.
403 class BackgroundReaper : public PlatformThread::Delegate {
404 public:
405 BackgroundReaper(pid_t child, unsigned timeout)
406 : child_(child),
407 timeout_(timeout) {
410 // Overridden from PlatformThread::Delegate:
411 void ThreadMain() override {
412 WaitForChildToDie();
413 delete this;
416 void WaitForChildToDie() {
417 // Wait forever case.
418 if (timeout_ == 0) {
419 pid_t r = HANDLE_EINTR(waitpid(child_, NULL, 0));
420 if (r != child_) {
421 DPLOG(ERROR) << "While waiting for " << child_
422 << " to terminate, we got the following result: " << r;
424 return;
427 // There's no good way to wait for a specific child to exit in a timed
428 // fashion. (No kqueue on Linux), so we just loop and sleep.
430 // Wait for 2 * timeout_ 500 milliseconds intervals.
431 for (unsigned i = 0; i < 2 * timeout_; ++i) {
432 PlatformThread::Sleep(TimeDelta::FromMilliseconds(500));
433 if (IsChildDead(child_))
434 return;
437 if (kill(child_, SIGKILL) == 0) {
438 // SIGKILL is uncatchable. Since the signal was delivered, we can
439 // just wait for the process to die now in a blocking manner.
440 if (HANDLE_EINTR(waitpid(child_, NULL, 0)) < 0)
441 DPLOG(WARNING) << "waitpid";
442 } else {
443 DLOG(ERROR) << "While waiting for " << child_ << " to terminate we"
444 << " failed to deliver a SIGKILL signal (" << errno << ").";
448 private:
449 const pid_t child_;
450 // Number of seconds to wait, if 0 then wait forever and do not attempt to
451 // kill |child_|.
452 const unsigned timeout_;
454 DISALLOW_COPY_AND_ASSIGN(BackgroundReaper);
457 } // namespace
459 void EnsureProcessTerminated(Process process) {
460 // If the child is already dead, then there's nothing to do.
461 if (IsChildDead(process.Pid()))
462 return;
464 const unsigned timeout = 2; // seconds
465 BackgroundReaper* reaper = new BackgroundReaper(process.Pid(), timeout);
466 PlatformThread::CreateNonJoinable(0, reaper);
469 void EnsureProcessGetsReaped(ProcessId pid) {
470 // If the child is already dead, then there's nothing to do.
471 if (IsChildDead(pid))
472 return;
474 BackgroundReaper* reaper = new BackgroundReaper(pid, 0);
475 PlatformThread::CreateNonJoinable(0, reaper);
478 #endif // !defined(OS_MACOSX)
479 #endif // !defined(OS_NACL_NONSFI)
481 } // namespace base