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"
10 #include "base/bind.h"
11 #include "base/bind_helpers.h"
12 #include "base/logging.h"
13 #include "base/message_loop/message_loop.h"
14 #include "base/process/process_iterator.h"
15 #include "base/win/object_watcher.h"
21 // Exit codes with special meanings on Windows.
22 const DWORD kNormalTerminationExitCode
= 0;
23 const DWORD kDebuggerInactiveExitCode
= 0xC0000354;
24 const DWORD kKeyboardInterruptExitCode
= 0xC000013A;
25 const DWORD kDebuggerTerminatedExitCode
= 0x40010004;
27 // This exit code is used by the Windows task manager when it kills a
28 // process. It's value is obviously not that unique, and it's
29 // surprising to me that the task manager uses this value, but it
30 // seems to be common practice on Windows to test for it as an
31 // indication that the task manager has killed something if the
33 const DWORD kProcessKilledExitCode
= 1;
35 // Maximum amount of time (in milliseconds) to wait for the process to exit.
36 static const int kWaitInterval
= 2000;
38 class TimerExpiredTask
: public win::ObjectWatcher::Delegate
{
40 explicit TimerExpiredTask(ProcessHandle process
);
45 // MessageLoop::Watcher -----------------------------------------------------
46 virtual void OnObjectSignaled(HANDLE object
);
51 // The process that we are watching.
52 ProcessHandle process_
;
54 win::ObjectWatcher watcher_
;
56 DISALLOW_COPY_AND_ASSIGN(TimerExpiredTask
);
59 TimerExpiredTask::TimerExpiredTask(ProcessHandle process
) : process_(process
) {
60 watcher_
.StartWatching(process_
, this);
63 TimerExpiredTask::~TimerExpiredTask() {
65 DCHECK(!process_
) << "Make sure to close the handle.";
68 void TimerExpiredTask::TimedOut() {
73 void TimerExpiredTask::OnObjectSignaled(HANDLE object
) {
74 CloseHandle(process_
);
78 void TimerExpiredTask::KillProcess() {
79 // Stop watching the process handle since we're killing it.
80 watcher_
.StopWatching();
82 // OK, time to get frisky. We don't actually care when the process
83 // terminates. We just care that it eventually terminates, and that's what
84 // TerminateProcess should do for us. Don't check for the result code since
85 // it fails quite often. This should be investigated eventually.
86 base::KillProcess(process_
, kProcessKilledExitCode
, false);
88 // Now, just cleanup as if the process exited normally.
89 OnObjectSignaled(process_
);
94 bool KillProcess(ProcessHandle process
, int exit_code
, bool wait
) {
95 bool result
= (TerminateProcess(process
, exit_code
) != FALSE
);
97 // The process may not end immediately due to pending I/O
98 if (WAIT_OBJECT_0
!= WaitForSingleObject(process
, 60 * 1000))
99 DLOG_GETLASTERROR(ERROR
) << "Error waiting for process exit";
100 } else if (!result
) {
101 DLOG_GETLASTERROR(ERROR
) << "Unable to terminate process";
106 // Attempts to kill the process identified by the given process
107 // entry structure, giving it the specified exit code.
108 // Returns true if this is successful, false otherwise.
109 bool KillProcessById(ProcessId process_id
, int exit_code
, bool wait
) {
110 HANDLE process
= OpenProcess(PROCESS_TERMINATE
| SYNCHRONIZE
,
111 FALSE
, // Don't inherit handle
114 DLOG_GETLASTERROR(ERROR
) << "Unable to open process " << process_id
;
117 bool ret
= KillProcess(process
, exit_code
, wait
);
118 CloseHandle(process
);
122 TerminationStatus
GetTerminationStatus(ProcessHandle handle
, int* exit_code
) {
123 DWORD tmp_exit_code
= 0;
125 if (!::GetExitCodeProcess(handle
, &tmp_exit_code
)) {
126 DLOG_GETLASTERROR(FATAL
) << "GetExitCodeProcess() failed";
128 // This really is a random number. We haven't received any
129 // information about the exit code, presumably because this
130 // process doesn't have permission to get the exit code, or
131 // because of some other cause for GetExitCodeProcess to fail
132 // (MSDN docs don't give the possible failure error codes for
133 // this function, so it could be anything). But we don't want
134 // to leave exit_code uninitialized, since that could cause
135 // random interpretations of the exit code. So we assume it
136 // terminated "normally" in this case.
137 *exit_code
= kNormalTerminationExitCode
;
139 // Assume the child has exited normally if we can't get the exit
141 return TERMINATION_STATUS_NORMAL_TERMINATION
;
143 if (tmp_exit_code
== STILL_ACTIVE
) {
144 DWORD wait_result
= WaitForSingleObject(handle
, 0);
145 if (wait_result
== WAIT_TIMEOUT
) {
147 *exit_code
= wait_result
;
148 return TERMINATION_STATUS_STILL_RUNNING
;
151 if (wait_result
== WAIT_FAILED
) {
152 DLOG_GETLASTERROR(ERROR
) << "WaitForSingleObject() failed";
154 DCHECK_EQ(WAIT_OBJECT_0
, wait_result
);
156 // Strange, the process used 0x103 (STILL_ACTIVE) as exit code.
160 return TERMINATION_STATUS_ABNORMAL_TERMINATION
;
164 *exit_code
= tmp_exit_code
;
166 switch (tmp_exit_code
) {
167 case kNormalTerminationExitCode
:
168 return TERMINATION_STATUS_NORMAL_TERMINATION
;
169 case kDebuggerInactiveExitCode
: // STATUS_DEBUGGER_INACTIVE.
170 case kKeyboardInterruptExitCode
: // Control-C/end session.
171 case kDebuggerTerminatedExitCode
: // Debugger terminated process.
172 case kProcessKilledExitCode
: // Task manager kill.
173 return TERMINATION_STATUS_PROCESS_WAS_KILLED
;
175 // All other exit codes indicate crashes.
176 return TERMINATION_STATUS_PROCESS_CRASHED
;
180 bool WaitForExitCode(ProcessHandle handle
, int* exit_code
) {
181 bool success
= WaitForExitCodeWithTimeout(
182 handle
, exit_code
, base::TimeDelta::FromMilliseconds(INFINITE
));
183 CloseProcessHandle(handle
);
187 bool WaitForExitCodeWithTimeout(ProcessHandle handle
,
189 base::TimeDelta timeout
) {
190 if (::WaitForSingleObject(handle
, timeout
.InMilliseconds()) != WAIT_OBJECT_0
)
192 DWORD temp_code
; // Don't clobber out-parameters in case of failure.
193 if (!::GetExitCodeProcess(handle
, &temp_code
))
196 *exit_code
= temp_code
;
200 bool WaitForProcessesToExit(const FilePath::StringType
& executable_name
,
201 base::TimeDelta wait
,
202 const ProcessFilter
* filter
) {
203 const ProcessEntry
* entry
;
205 DWORD start_time
= GetTickCount();
207 NamedProcessIterator
iter(executable_name
, filter
);
208 while ((entry
= iter
.NextProcessEntry())) {
209 DWORD remaining_wait
= std::max
<int64
>(
210 0, wait
.InMilliseconds() - (GetTickCount() - start_time
));
211 HANDLE process
= OpenProcess(SYNCHRONIZE
,
213 entry
->th32ProcessID
);
214 DWORD wait_result
= WaitForSingleObject(process
, remaining_wait
);
215 CloseHandle(process
);
216 result
= result
&& (wait_result
== WAIT_OBJECT_0
);
222 bool WaitForSingleProcess(ProcessHandle handle
, base::TimeDelta wait
) {
224 if (!WaitForExitCodeWithTimeout(handle
, &exit_code
, wait
))
226 return exit_code
== 0;
229 bool CleanupProcesses(const FilePath::StringType
& executable_name
,
230 base::TimeDelta wait
,
232 const ProcessFilter
* filter
) {
233 bool exited_cleanly
= WaitForProcessesToExit(executable_name
, wait
, filter
);
235 KillProcesses(executable_name
, exit_code
, filter
);
236 return exited_cleanly
;
239 void EnsureProcessTerminated(ProcessHandle process
) {
240 DCHECK(process
!= GetCurrentProcess());
242 // If already signaled, then we are done!
243 if (WaitForSingleObject(process
, 0) == WAIT_OBJECT_0
) {
244 CloseHandle(process
);
248 MessageLoop::current()->PostDelayedTask(
250 base::Bind(&TimerExpiredTask::TimedOut
,
251 base::Owned(new TimerExpiredTask(process
))),
252 base::TimeDelta::FromMilliseconds(kWaitInterval
));