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/profiler/scoped_tracker.h"
16 #include "base/win/object_watcher.h"
22 // Exit codes with special meanings on Windows.
23 const DWORD kNormalTerminationExitCode
= 0;
24 const DWORD kDebuggerInactiveExitCode
= 0xC0000354;
25 const DWORD kKeyboardInterruptExitCode
= 0xC000013A;
26 const DWORD kDebuggerTerminatedExitCode
= 0x40010004;
28 // This exit code is used by the Windows task manager when it kills a
29 // process. It's value is obviously not that unique, and it's
30 // surprising to me that the task manager uses this value, but it
31 // seems to be common practice on Windows to test for it as an
32 // indication that the task manager has killed something if the
34 const DWORD kProcessKilledExitCode
= 1;
36 // Maximum amount of time (in milliseconds) to wait for the process to exit.
37 static const int kWaitInterval
= 2000;
39 class TimerExpiredTask
: public win::ObjectWatcher::Delegate
{
41 explicit TimerExpiredTask(Process process
);
46 // MessageLoop::Watcher -----------------------------------------------------
47 virtual void OnObjectSignaled(HANDLE object
);
52 // The process that we are watching.
55 win::ObjectWatcher watcher_
;
57 DISALLOW_COPY_AND_ASSIGN(TimerExpiredTask
);
60 TimerExpiredTask::TimerExpiredTask(Process process
) : process_(process
.Pass()) {
61 watcher_
.StartWatching(process_
.Handle(), this);
64 TimerExpiredTask::~TimerExpiredTask() {
68 void TimerExpiredTask::TimedOut() {
69 if (process_
.IsValid())
73 void TimerExpiredTask::OnObjectSignaled(HANDLE object
) {
74 // TODO(vadimt): Remove ScopedTracker below once crbug.com/418183 is fixed.
75 tracked_objects::ScopedTracker
tracking_profile(
76 FROM_HERE_WITH_EXPLICIT_FUNCTION("TimerExpiredTask_OnObjectSignaled"));
81 void TimerExpiredTask::KillProcess() {
82 // Stop watching the process handle since we're killing it.
83 watcher_
.StopWatching();
85 // OK, time to get frisky. We don't actually care when the process
86 // terminates. We just care that it eventually terminates, and that's what
87 // TerminateProcess should do for us. Don't check for the result code since
88 // it fails quite often. This should be investigated eventually.
89 base::KillProcess(process_
.Handle(), kProcessKilledExitCode
, false);
91 // Now, just cleanup as if the process exited normally.
92 OnObjectSignaled(process_
.Handle());
97 bool KillProcess(ProcessHandle process
, int exit_code
, bool wait
) {
98 bool result
= (TerminateProcess(process
, exit_code
) != FALSE
);
100 // The process may not end immediately due to pending I/O
101 if (WAIT_OBJECT_0
!= WaitForSingleObject(process
, 60 * 1000))
102 DPLOG(ERROR
) << "Error waiting for process exit";
103 } else if (!result
) {
104 DPLOG(ERROR
) << "Unable to terminate process";
109 // Attempts to kill the process identified by the given process
110 // entry structure, giving it the specified exit code.
111 // Returns true if this is successful, false otherwise.
112 bool KillProcessById(ProcessId process_id
, int exit_code
, bool wait
) {
113 HANDLE process
= OpenProcess(PROCESS_TERMINATE
| SYNCHRONIZE
,
114 FALSE
, // Don't inherit handle
117 DPLOG(ERROR
) << "Unable to open process " << process_id
;
120 bool ret
= KillProcess(process
, exit_code
, wait
);
121 CloseHandle(process
);
125 TerminationStatus
GetTerminationStatus(ProcessHandle handle
, int* exit_code
) {
126 DWORD tmp_exit_code
= 0;
128 if (!::GetExitCodeProcess(handle
, &tmp_exit_code
)) {
129 DPLOG(FATAL
) << "GetExitCodeProcess() failed";
131 // This really is a random number. We haven't received any
132 // information about the exit code, presumably because this
133 // process doesn't have permission to get the exit code, or
134 // because of some other cause for GetExitCodeProcess to fail
135 // (MSDN docs don't give the possible failure error codes for
136 // this function, so it could be anything). But we don't want
137 // to leave exit_code uninitialized, since that could cause
138 // random interpretations of the exit code. So we assume it
139 // terminated "normally" in this case.
140 *exit_code
= kNormalTerminationExitCode
;
142 // Assume the child has exited normally if we can't get the exit
144 return TERMINATION_STATUS_NORMAL_TERMINATION
;
146 if (tmp_exit_code
== STILL_ACTIVE
) {
147 DWORD wait_result
= WaitForSingleObject(handle
, 0);
148 if (wait_result
== WAIT_TIMEOUT
) {
150 *exit_code
= wait_result
;
151 return TERMINATION_STATUS_STILL_RUNNING
;
154 if (wait_result
== WAIT_FAILED
) {
155 DPLOG(ERROR
) << "WaitForSingleObject() failed";
157 DCHECK_EQ(WAIT_OBJECT_0
, wait_result
);
159 // Strange, the process used 0x103 (STILL_ACTIVE) as exit code.
163 return TERMINATION_STATUS_ABNORMAL_TERMINATION
;
167 *exit_code
= tmp_exit_code
;
169 switch (tmp_exit_code
) {
170 case kNormalTerminationExitCode
:
171 return TERMINATION_STATUS_NORMAL_TERMINATION
;
172 case kDebuggerInactiveExitCode
: // STATUS_DEBUGGER_INACTIVE.
173 case kKeyboardInterruptExitCode
: // Control-C/end session.
174 case kDebuggerTerminatedExitCode
: // Debugger terminated process.
175 case kProcessKilledExitCode
: // Task manager kill.
176 return TERMINATION_STATUS_PROCESS_WAS_KILLED
;
178 // All other exit codes indicate crashes.
179 return TERMINATION_STATUS_PROCESS_CRASHED
;
183 bool WaitForExitCode(ProcessHandle handle
, int* exit_code
) {
184 bool success
= WaitForExitCodeWithTimeout(
185 handle
, exit_code
, base::TimeDelta::FromMilliseconds(INFINITE
));
186 CloseProcessHandle(handle
);
190 bool WaitForExitCodeWithTimeout(ProcessHandle handle
,
192 base::TimeDelta timeout
) {
193 if (::WaitForSingleObject(
194 handle
, static_cast<DWORD
>(timeout
.InMilliseconds())) != WAIT_OBJECT_0
)
196 DWORD temp_code
; // Don't clobber out-parameters in case of failure.
197 if (!::GetExitCodeProcess(handle
, &temp_code
))
200 *exit_code
= temp_code
;
204 bool WaitForProcessesToExit(const FilePath::StringType
& executable_name
,
205 base::TimeDelta wait
,
206 const ProcessFilter
* filter
) {
208 DWORD start_time
= GetTickCount();
210 NamedProcessIterator
iter(executable_name
, filter
);
211 for (const ProcessEntry
* entry
= iter
.NextProcessEntry(); entry
;
212 entry
= iter
.NextProcessEntry()) {
213 DWORD remaining_wait
= static_cast<DWORD
>(std::max(
214 static_cast<int64
>(0),
215 wait
.InMilliseconds() - (GetTickCount() - start_time
)));
216 HANDLE process
= OpenProcess(SYNCHRONIZE
,
218 entry
->th32ProcessID
);
219 DWORD wait_result
= WaitForSingleObject(process
, remaining_wait
);
220 CloseHandle(process
);
221 result
&= (wait_result
== WAIT_OBJECT_0
);
227 bool WaitForSingleProcess(ProcessHandle handle
, base::TimeDelta wait
) {
229 return WaitForExitCodeWithTimeout(handle
, &exit_code
, wait
) && exit_code
== 0;
232 bool CleanupProcesses(const FilePath::StringType
& executable_name
,
233 base::TimeDelta wait
,
235 const ProcessFilter
* filter
) {
236 if (WaitForProcessesToExit(executable_name
, wait
, filter
))
238 KillProcesses(executable_name
, exit_code
, filter
);
242 void EnsureProcessTerminated(Process process
) {
243 DCHECK(!process
.is_current());
245 // If already signaled, then we are done!
246 if (WaitForSingleObject(process
.Handle(), 0) == WAIT_OBJECT_0
) {
250 MessageLoop::current()->PostDelayedTask(
252 base::Bind(&TimerExpiredTask::TimedOut
,
253 base::Owned(new TimerExpiredTask(process
.Pass()))),
254 base::TimeDelta::FromMilliseconds(kWaitInterval
));