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.
4
5 #include "base/process/kill.h"
6
7 #include <errno.h>
8 #include <signal.h>
9 #include <sys/types.h>
10 #include <sys/wait.h>
11 #include <unistd.h>
12
13 #include "base/files/file_util.h"
14 #include "base/files/scoped_file.h"
15 #include "base/logging.h"
16 #include "base/macros.h"
17 #include "base/posix/eintr_wrapper.h"
18 #include "base/process/process_iterator.h"
19 #include "base/synchronization/waitable_event.h"
20 #include "base/threading/platform_thread.h"
21 #include "build/build_config.h"
22
23 namespace base {
24
25 namespace {
26
GetTerminationStatusImpl(ProcessHandle handle,bool can_block,int * exit_code)27 TerminationStatus GetTerminationStatusImpl(ProcessHandle handle,
28 bool can_block,
29 int* exit_code) {
30 int status = 0;
31 const pid_t result = HANDLE_EINTR(waitpid(handle, &status,
32 can_block ? 0 : WNOHANG));
33 if (result == -1) {
34 DPLOG(ERROR) << "waitpid(" << handle << ")";
35 if (exit_code)
36 *exit_code = 0;
37 return TERMINATION_STATUS_NORMAL_TERMINATION;
38 } else if (result == 0) {
39 // the child hasn't exited yet.
40 if (exit_code)
41 *exit_code = 0;
42 return TERMINATION_STATUS_STILL_RUNNING;
43 }
44
45 if (exit_code)
46 *exit_code = status;
47
48 if (WIFSIGNALED(status)) {
49 switch (WTERMSIG(status)) {
50 case SIGABRT:
51 case SIGBUS:
52 case SIGFPE:
53 case SIGILL:
54 case SIGSEGV:
55 return TERMINATION_STATUS_PROCESS_CRASHED;
56 case SIGKILL:
57 #if defined(OS_CHROMEOS)
58 // On ChromeOS, only way a process gets kill by SIGKILL
59 // is by oom-killer.
60 return TERMINATION_STATUS_PROCESS_WAS_KILLED_BY_OOM;
61 #endif
62 case SIGINT:
63 case SIGTERM:
64 return TERMINATION_STATUS_PROCESS_WAS_KILLED;
65 default:
66 break;
67 }
68 }
69
70 if (WIFEXITED(status) && WEXITSTATUS(status) != 0)
71 return TERMINATION_STATUS_ABNORMAL_TERMINATION;
72
73 return TERMINATION_STATUS_NORMAL_TERMINATION;
74 }
75
76 } // namespace
77
78 #if !defined(OS_NACL_NONSFI)
KillProcessGroup(ProcessHandle process_group_id)79 bool KillProcessGroup(ProcessHandle process_group_id) {
80 bool result = kill(-1 * process_group_id, SIGKILL) == 0;
81 if (!result)
82 DPLOG(ERROR) << "Unable to terminate process group " << process_group_id;
83 return result;
84 }
85 #endif // !defined(OS_NACL_NONSFI)
86
GetTerminationStatus(ProcessHandle handle,int * exit_code)87 TerminationStatus GetTerminationStatus(ProcessHandle handle, int* exit_code) {
88 return GetTerminationStatusImpl(handle, false /* can_block */, exit_code);
89 }
90
GetKnownDeadTerminationStatus(ProcessHandle handle,int * exit_code)91 TerminationStatus GetKnownDeadTerminationStatus(ProcessHandle handle,
92 int* exit_code) {
93 bool result = kill(handle, SIGKILL) == 0;
94
95 if (!result)
96 DPLOG(ERROR) << "Unable to terminate process " << handle;
97
98 return GetTerminationStatusImpl(handle, true /* can_block */, exit_code);
99 }
100
101 #if !defined(OS_NACL_NONSFI)
WaitForProcessesToExit(const FilePath::StringType & executable_name,TimeDelta wait,const ProcessFilter * filter)102 bool WaitForProcessesToExit(const FilePath::StringType& executable_name,
103 TimeDelta wait,
104 const ProcessFilter* filter) {
105 bool result = false;
106
107 // TODO(port): This is inefficient, but works if there are multiple procs.
108 // TODO(port): use waitpid to avoid leaving zombies around
109
110 TimeTicks end_time = TimeTicks::Now() + wait;
111 do {
112 NamedProcessIterator iter(executable_name, filter);
113 if (!iter.NextProcessEntry()) {
114 result = true;
115 break;
116 }
117 PlatformThread::Sleep(TimeDelta::FromMilliseconds(100));
118 } while ((end_time - TimeTicks::Now()) > TimeDelta());
119
120 return result;
121 }
122
CleanupProcesses(const FilePath::StringType & executable_name,TimeDelta wait,int exit_code,const ProcessFilter * filter)123 bool CleanupProcesses(const FilePath::StringType& executable_name,
124 TimeDelta wait,
125 int exit_code,
126 const ProcessFilter* filter) {
127 bool exited_cleanly = WaitForProcessesToExit(executable_name, wait, filter);
128 if (!exited_cleanly)
129 KillProcesses(executable_name, exit_code, filter);
130 return exited_cleanly;
131 }
132
133 #if !defined(OS_MACOSX)
134
135 namespace {
136
137 // Return true if the given child is dead. This will also reap the process.
138 // Doesn't block.
IsChildDead(pid_t child)139 static bool IsChildDead(pid_t child) {
140 const pid_t result = HANDLE_EINTR(waitpid(child, NULL, WNOHANG));
141 if (result == -1) {
142 DPLOG(ERROR) << "waitpid(" << child << ")";
143 NOTREACHED();
144 } else if (result > 0) {
145 // The child has died.
146 return true;
147 }
148
149 return false;
150 }
151
152 // A thread class which waits for the given child to exit and reaps it.
153 // If the child doesn't exit within a couple of seconds, kill it.
154 class BackgroundReaper : public PlatformThread::Delegate {
155 public:
BackgroundReaper(pid_t child,unsigned timeout)156 BackgroundReaper(pid_t child, unsigned timeout)
157 : child_(child),
158 timeout_(timeout) {
159 }
160
161 // Overridden from PlatformThread::Delegate:
ThreadMain()162 void ThreadMain() override {
163 WaitForChildToDie();
164 delete this;
165 }
166
WaitForChildToDie()167 void WaitForChildToDie() {
168 // Wait forever case.
169 if (timeout_ == 0) {
170 pid_t r = HANDLE_EINTR(waitpid(child_, NULL, 0));
171 if (r != child_) {
172 DPLOG(ERROR) << "While waiting for " << child_
173 << " to terminate, we got the following result: " << r;
174 }
175 return;
176 }
177
178 // There's no good way to wait for a specific child to exit in a timed
179 // fashion. (No kqueue on Linux), so we just loop and sleep.
180
181 // Wait for 2 * timeout_ 500 milliseconds intervals.
182 for (unsigned i = 0; i < 2 * timeout_; ++i) {
183 PlatformThread::Sleep(TimeDelta::FromMilliseconds(500));
184 if (IsChildDead(child_))
185 return;
186 }
187
188 if (kill(child_, SIGKILL) == 0) {
189 // SIGKILL is uncatchable. Since the signal was delivered, we can
190 // just wait for the process to die now in a blocking manner.
191 if (HANDLE_EINTR(waitpid(child_, NULL, 0)) < 0)
192 DPLOG(WARNING) << "waitpid";
193 } else {
194 DLOG(ERROR) << "While waiting for " << child_ << " to terminate we"
195 << " failed to deliver a SIGKILL signal (" << errno << ").";
196 }
197 }
198
199 private:
200 const pid_t child_;
201 // Number of seconds to wait, if 0 then wait forever and do not attempt to
202 // kill |child_|.
203 const unsigned timeout_;
204
205 DISALLOW_COPY_AND_ASSIGN(BackgroundReaper);
206 };
207
208 } // namespace
209
EnsureProcessTerminated(Process process)210 void EnsureProcessTerminated(Process process) {
211 // If the child is already dead, then there's nothing to do.
212 if (IsChildDead(process.Pid()))
213 return;
214
215 const unsigned timeout = 2; // seconds
216 BackgroundReaper* reaper = new BackgroundReaper(process.Pid(), timeout);
217 PlatformThread::CreateNonJoinable(0, reaper);
218 }
219
EnsureProcessGetsReaped(ProcessId pid)220 void EnsureProcessGetsReaped(ProcessId pid) {
221 // If the child is already dead, then there's nothing to do.
222 if (IsChildDead(pid))
223 return;
224
225 BackgroundReaper* reaper = new BackgroundReaper(pid, 0);
226 PlatformThread::CreateNonJoinable(0, reaper);
227 }
228
229 #endif // !defined(OS_MACOSX)
230 #endif // !defined(OS_NACL_NONSFI)
231
232 } // namespace base
233