Release the Settings API.
[chromium-blink-merge.git] / base / process / kill_posix.cc
blob8187c38926cd2ce0551861f0e6a09d24db84f8b6
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/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 int WaitpidWithTimeout(ProcessHandle handle,
26 int64 wait_milliseconds,
27 bool* success) {
28 // This POSIX version of this function only guarantees that we wait no less
29 // than |wait_milliseconds| for the process to exit. The child process may
30 // exit sometime before the timeout has ended but we may still block for up
31 // to 256 milliseconds after the fact.
33 // waitpid() has no direct support on POSIX for specifying a timeout, you can
34 // either ask it to block indefinitely or return immediately (WNOHANG).
35 // When a child process terminates a SIGCHLD signal is sent to the parent.
36 // Catching this signal would involve installing a signal handler which may
37 // affect other parts of the application and would be difficult to debug.
39 // Our strategy is to call waitpid() once up front to check if the process
40 // has already exited, otherwise to loop for wait_milliseconds, sleeping for
41 // at most 256 milliseconds each time using usleep() and then calling
42 // waitpid(). The amount of time we sleep starts out at 1 milliseconds, and
43 // we double it every 4 sleep cycles.
45 // usleep() is speced to exit if a signal is received for which a handler
46 // has been installed. This means that when a SIGCHLD is sent, it will exit
47 // depending on behavior external to this function.
49 // This function is used primarily for unit tests, if we want to use it in
50 // the application itself it would probably be best to examine other routes.
51 int status = -1;
52 pid_t ret_pid = HANDLE_EINTR(waitpid(handle, &status, WNOHANG));
53 static const int64 kMaxSleepInMicroseconds = 1 << 18; // ~256 milliseconds.
54 int64 max_sleep_time_usecs = 1 << 10; // ~1 milliseconds.
55 int64 double_sleep_time = 0;
57 // If the process hasn't exited yet, then sleep and try again.
58 TimeTicks wakeup_time = TimeTicks::Now() +
59 TimeDelta::FromMilliseconds(wait_milliseconds);
60 while (ret_pid == 0) {
61 TimeTicks now = TimeTicks::Now();
62 if (now > wakeup_time)
63 break;
64 // Guaranteed to be non-negative!
65 int64 sleep_time_usecs = (wakeup_time - now).InMicroseconds();
66 // Sleep for a bit while we wait for the process to finish.
67 if (sleep_time_usecs > max_sleep_time_usecs)
68 sleep_time_usecs = max_sleep_time_usecs;
70 // usleep() will return 0 and set errno to EINTR on receipt of a signal
71 // such as SIGCHLD.
72 usleep(sleep_time_usecs);
73 ret_pid = HANDLE_EINTR(waitpid(handle, &status, WNOHANG));
75 if ((max_sleep_time_usecs < kMaxSleepInMicroseconds) &&
76 (double_sleep_time++ % 4 == 0)) {
77 max_sleep_time_usecs *= 2;
81 if (success)
82 *success = (ret_pid != -1);
84 return status;
87 TerminationStatus GetTerminationStatusImpl(ProcessHandle handle,
88 bool can_block,
89 int* exit_code) {
90 int status = 0;
91 const pid_t result = HANDLE_EINTR(waitpid(handle, &status,
92 can_block ? 0 : WNOHANG));
93 if (result == -1) {
94 DPLOG(ERROR) << "waitpid(" << handle << ")";
95 if (exit_code)
96 *exit_code = 0;
97 return TERMINATION_STATUS_NORMAL_TERMINATION;
98 } else if (result == 0) {
99 // the child hasn't exited yet.
100 if (exit_code)
101 *exit_code = 0;
102 return TERMINATION_STATUS_STILL_RUNNING;
105 if (exit_code)
106 *exit_code = status;
108 if (WIFSIGNALED(status)) {
109 switch (WTERMSIG(status)) {
110 case SIGABRT:
111 case SIGBUS:
112 case SIGFPE:
113 case SIGILL:
114 case SIGSEGV:
115 return TERMINATION_STATUS_PROCESS_CRASHED;
116 case SIGINT:
117 case SIGKILL:
118 case SIGTERM:
119 return TERMINATION_STATUS_PROCESS_WAS_KILLED;
120 default:
121 break;
125 if (WIFEXITED(status) && WEXITSTATUS(status) != 0)
126 return TERMINATION_STATUS_ABNORMAL_TERMINATION;
128 return TERMINATION_STATUS_NORMAL_TERMINATION;
131 } // namespace
133 // Attempts to kill the process identified by the given process
134 // entry structure. Ignores specified exit_code; posix can't force that.
135 // Returns true if this is successful, false otherwise.
136 bool KillProcess(ProcessHandle process_id, int exit_code, bool wait) {
137 DCHECK_GT(process_id, 1) << " tried to kill invalid process_id";
138 if (process_id <= 1)
139 return false;
140 bool result = kill(process_id, SIGTERM) == 0;
141 if (result && wait) {
142 int tries = 60;
144 if (RunningOnValgrind()) {
145 // Wait for some extra time when running under Valgrind since the child
146 // processes may take some time doing leak checking.
147 tries *= 2;
150 unsigned sleep_ms = 4;
152 // The process may not end immediately due to pending I/O
153 bool exited = false;
154 while (tries-- > 0) {
155 pid_t pid = HANDLE_EINTR(waitpid(process_id, NULL, WNOHANG));
156 if (pid == process_id) {
157 exited = true;
158 break;
160 if (pid == -1) {
161 if (errno == ECHILD) {
162 // The wait may fail with ECHILD if another process also waited for
163 // the same pid, causing the process state to get cleaned up.
164 exited = true;
165 break;
167 DPLOG(ERROR) << "Error waiting for process " << process_id;
170 usleep(sleep_ms * 1000);
171 const unsigned kMaxSleepMs = 1000;
172 if (sleep_ms < kMaxSleepMs)
173 sleep_ms *= 2;
176 // If we're waiting and the child hasn't died by now, force it
177 // with a SIGKILL.
178 if (!exited)
179 result = kill(process_id, SIGKILL) == 0;
182 if (!result)
183 DPLOG(ERROR) << "Unable to terminate process " << process_id;
185 return result;
188 bool KillProcessGroup(ProcessHandle process_group_id) {
189 bool result = kill(-1 * process_group_id, SIGKILL) == 0;
190 if (!result)
191 DPLOG(ERROR) << "Unable to terminate process group " << process_group_id;
192 return result;
195 TerminationStatus GetTerminationStatus(ProcessHandle handle, int* exit_code) {
196 return GetTerminationStatusImpl(handle, false /* can_block */, exit_code);
199 TerminationStatus GetKnownDeadTerminationStatus(ProcessHandle handle,
200 int* exit_code) {
201 bool result = kill(handle, SIGKILL) == 0;
203 if (!result)
204 DPLOG(ERROR) << "Unable to terminate process " << handle;
206 return GetTerminationStatusImpl(handle, true /* can_block */, exit_code);
209 bool WaitForExitCode(ProcessHandle handle, int* exit_code) {
210 int status;
211 if (HANDLE_EINTR(waitpid(handle, &status, 0)) == -1) {
212 NOTREACHED();
213 return false;
216 if (WIFEXITED(status)) {
217 *exit_code = WEXITSTATUS(status);
218 return true;
221 // If it didn't exit cleanly, it must have been signaled.
222 DCHECK(WIFSIGNALED(status));
223 return false;
226 bool WaitForExitCodeWithTimeout(ProcessHandle handle,
227 int* exit_code,
228 base::TimeDelta timeout) {
229 bool waitpid_success = false;
230 int status = WaitpidWithTimeout(handle, timeout.InMilliseconds(),
231 &waitpid_success);
232 if (status == -1)
233 return false;
234 if (!waitpid_success)
235 return false;
236 if (WIFSIGNALED(status)) {
237 *exit_code = -1;
238 return true;
240 if (WIFEXITED(status)) {
241 *exit_code = WEXITSTATUS(status);
242 return true;
244 return false;
247 bool WaitForProcessesToExit(const FilePath::StringType& executable_name,
248 base::TimeDelta wait,
249 const ProcessFilter* filter) {
250 bool result = false;
252 // TODO(port): This is inefficient, but works if there are multiple procs.
253 // TODO(port): use waitpid to avoid leaving zombies around
255 base::TimeTicks end_time = base::TimeTicks::Now() + wait;
256 do {
257 NamedProcessIterator iter(executable_name, filter);
258 if (!iter.NextProcessEntry()) {
259 result = true;
260 break;
262 base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(100));
263 } while ((end_time - base::TimeTicks::Now()) > base::TimeDelta());
265 return result;
268 #if defined(OS_MACOSX)
269 // Using kqueue on Mac so that we can wait on non-child processes.
270 // We can't use kqueues on child processes because we need to reap
271 // our own children using wait.
272 static bool WaitForSingleNonChildProcess(ProcessHandle handle,
273 base::TimeDelta wait) {
274 DCHECK_GT(handle, 0);
275 DCHECK(wait.InMilliseconds() == base::kNoTimeout || wait > base::TimeDelta());
277 ScopedFD kq(kqueue());
278 if (!kq.is_valid()) {
279 DPLOG(ERROR) << "kqueue";
280 return false;
283 struct kevent change = {0};
284 EV_SET(&change, handle, EVFILT_PROC, EV_ADD, NOTE_EXIT, 0, NULL);
285 int result = HANDLE_EINTR(kevent(kq.get(), &change, 1, NULL, 0, NULL));
286 if (result == -1) {
287 if (errno == ESRCH) {
288 // If the process wasn't found, it must be dead.
289 return true;
292 DPLOG(ERROR) << "kevent (setup " << handle << ")";
293 return false;
296 // Keep track of the elapsed time to be able to restart kevent if it's
297 // interrupted.
298 bool wait_forever = wait.InMilliseconds() == base::kNoTimeout;
299 base::TimeDelta remaining_delta;
300 base::TimeTicks deadline;
301 if (!wait_forever) {
302 remaining_delta = wait;
303 deadline = base::TimeTicks::Now() + remaining_delta;
306 result = -1;
307 struct kevent event = {0};
309 while (wait_forever || remaining_delta > base::TimeDelta()) {
310 struct timespec remaining_timespec;
311 struct timespec* remaining_timespec_ptr;
312 if (wait_forever) {
313 remaining_timespec_ptr = NULL;
314 } else {
315 remaining_timespec = remaining_delta.ToTimeSpec();
316 remaining_timespec_ptr = &remaining_timespec;
319 result = kevent(kq.get(), NULL, 0, &event, 1, remaining_timespec_ptr);
321 if (result == -1 && errno == EINTR) {
322 if (!wait_forever) {
323 remaining_delta = deadline - base::TimeTicks::Now();
325 result = 0;
326 } else {
327 break;
331 if (result < 0) {
332 DPLOG(ERROR) << "kevent (wait " << handle << ")";
333 return false;
334 } else if (result > 1) {
335 DLOG(ERROR) << "kevent (wait " << handle << "): unexpected result "
336 << result;
337 return false;
338 } else if (result == 0) {
339 // Timed out.
340 return false;
343 DCHECK_EQ(result, 1);
345 if (event.filter != EVFILT_PROC ||
346 (event.fflags & NOTE_EXIT) == 0 ||
347 event.ident != static_cast<uintptr_t>(handle)) {
348 DLOG(ERROR) << "kevent (wait " << handle
349 << "): unexpected event: filter=" << event.filter
350 << ", fflags=" << event.fflags
351 << ", ident=" << event.ident;
352 return false;
355 return true;
357 #endif // OS_MACOSX
359 bool WaitForSingleProcess(ProcessHandle handle, base::TimeDelta wait) {
360 ProcessHandle parent_pid = GetParentProcessId(handle);
361 ProcessHandle our_pid = Process::Current().handle();
362 if (parent_pid != our_pid) {
363 #if defined(OS_MACOSX)
364 // On Mac we can wait on non child processes.
365 return WaitForSingleNonChildProcess(handle, wait);
366 #else
367 // Currently on Linux we can't handle non child processes.
368 NOTIMPLEMENTED();
369 #endif // OS_MACOSX
372 bool waitpid_success;
373 int status = -1;
374 if (wait.InMilliseconds() == base::kNoTimeout) {
375 waitpid_success = (HANDLE_EINTR(waitpid(handle, &status, 0)) != -1);
376 } else {
377 status = WaitpidWithTimeout(
378 handle, wait.InMilliseconds(), &waitpid_success);
381 if (status != -1) {
382 DCHECK(waitpid_success);
383 return WIFEXITED(status);
384 } else {
385 return false;
389 bool CleanupProcesses(const FilePath::StringType& executable_name,
390 base::TimeDelta wait,
391 int exit_code,
392 const ProcessFilter* filter) {
393 bool exited_cleanly = WaitForProcessesToExit(executable_name, wait, filter);
394 if (!exited_cleanly)
395 KillProcesses(executable_name, exit_code, filter);
396 return exited_cleanly;
399 #if !defined(OS_MACOSX)
401 namespace {
403 // Return true if the given child is dead. This will also reap the process.
404 // Doesn't block.
405 static bool IsChildDead(pid_t child) {
406 const pid_t result = HANDLE_EINTR(waitpid(child, NULL, WNOHANG));
407 if (result == -1) {
408 DPLOG(ERROR) << "waitpid(" << child << ")";
409 NOTREACHED();
410 } else if (result > 0) {
411 // The child has died.
412 return true;
415 return false;
418 // A thread class which waits for the given child to exit and reaps it.
419 // If the child doesn't exit within a couple of seconds, kill it.
420 class BackgroundReaper : public PlatformThread::Delegate {
421 public:
422 BackgroundReaper(pid_t child, unsigned timeout)
423 : child_(child),
424 timeout_(timeout) {
427 // Overridden from PlatformThread::Delegate:
428 virtual void ThreadMain() OVERRIDE {
429 WaitForChildToDie();
430 delete this;
433 void WaitForChildToDie() {
434 // Wait forever case.
435 if (timeout_ == 0) {
436 pid_t r = HANDLE_EINTR(waitpid(child_, NULL, 0));
437 if (r != child_) {
438 DPLOG(ERROR) << "While waiting for " << child_
439 << " to terminate, we got the following result: " << r;
441 return;
444 // There's no good way to wait for a specific child to exit in a timed
445 // fashion. (No kqueue on Linux), so we just loop and sleep.
447 // Wait for 2 * timeout_ 500 milliseconds intervals.
448 for (unsigned i = 0; i < 2 * timeout_; ++i) {
449 PlatformThread::Sleep(TimeDelta::FromMilliseconds(500));
450 if (IsChildDead(child_))
451 return;
454 if (kill(child_, SIGKILL) == 0) {
455 // SIGKILL is uncatchable. Since the signal was delivered, we can
456 // just wait for the process to die now in a blocking manner.
457 if (HANDLE_EINTR(waitpid(child_, NULL, 0)) < 0)
458 DPLOG(WARNING) << "waitpid";
459 } else {
460 DLOG(ERROR) << "While waiting for " << child_ << " to terminate we"
461 << " failed to deliver a SIGKILL signal (" << errno << ").";
465 private:
466 const pid_t child_;
467 // Number of seconds to wait, if 0 then wait forever and do not attempt to
468 // kill |child_|.
469 const unsigned timeout_;
471 DISALLOW_COPY_AND_ASSIGN(BackgroundReaper);
474 } // namespace
476 void EnsureProcessTerminated(ProcessHandle process) {
477 // If the child is already dead, then there's nothing to do.
478 if (IsChildDead(process))
479 return;
481 const unsigned timeout = 2; // seconds
482 BackgroundReaper* reaper = new BackgroundReaper(process, timeout);
483 PlatformThread::CreateNonJoinable(0, reaper);
486 void EnsureProcessGetsReaped(ProcessHandle process) {
487 // If the child is already dead, then there's nothing to do.
488 if (IsChildDead(process))
489 return;
491 BackgroundReaper* reaper = new BackgroundReaper(process, 0);
492 PlatformThread::CreateNonJoinable(0, reaper);
495 #endif // !defined(OS_MACOSX)
497 } // namespace base