Fix for Hyperlinks do not open in new tab by Print preview window.
[chromium-blink-merge.git] / base / process / kill_win.cc
blob0a0c99c854276a3b2b1b141ee0ecccaabd876062
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 <io.h>
8 #include <windows.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"
18 namespace base {
20 namespace {
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
33 // process goes away.
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 {
40 public:
41 explicit TimerExpiredTask(Process process);
42 ~TimerExpiredTask();
44 void TimedOut();
46 // MessageLoop::Watcher -----------------------------------------------------
47 virtual void OnObjectSignaled(HANDLE object);
49 private:
50 void KillProcess();
52 // The process that we are watching.
53 Process process_;
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() {
65 TimedOut();
68 void TimerExpiredTask::TimedOut() {
69 if (process_.IsValid())
70 KillProcess();
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"));
78 process_.Close();
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());
95 } // namespace
97 bool KillProcess(ProcessHandle process, int exit_code, bool wait) {
98 bool result = (TerminateProcess(process, exit_code) != FALSE);
99 if (result && wait) {
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";
106 return result;
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
115 process_id);
116 if (!process) {
117 DPLOG(ERROR) << "Unable to open process " << process_id;
118 return false;
120 bool ret = KillProcess(process, exit_code, wait);
121 CloseHandle(process);
122 return ret;
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";
130 if (exit_code) {
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
143 // code.
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) {
149 if (exit_code)
150 *exit_code = wait_result;
151 return TERMINATION_STATUS_STILL_RUNNING;
154 if (wait_result == WAIT_FAILED) {
155 DPLOG(ERROR) << "WaitForSingleObject() failed";
156 } else {
157 DCHECK_EQ(WAIT_OBJECT_0, wait_result);
159 // Strange, the process used 0x103 (STILL_ACTIVE) as exit code.
160 NOTREACHED();
163 return TERMINATION_STATUS_ABNORMAL_TERMINATION;
166 if (exit_code)
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;
177 default:
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);
187 return success;
190 bool WaitForExitCodeWithTimeout(ProcessHandle handle,
191 int* exit_code,
192 base::TimeDelta timeout) {
193 if (::WaitForSingleObject(
194 handle, static_cast<DWORD>(timeout.InMilliseconds())) != WAIT_OBJECT_0)
195 return false;
196 DWORD temp_code; // Don't clobber out-parameters in case of failure.
197 if (!::GetExitCodeProcess(handle, &temp_code))
198 return false;
200 *exit_code = temp_code;
201 return true;
204 bool WaitForProcessesToExit(const FilePath::StringType& executable_name,
205 base::TimeDelta wait,
206 const ProcessFilter* filter) {
207 bool result = true;
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,
217 FALSE,
218 entry->th32ProcessID);
219 DWORD wait_result = WaitForSingleObject(process, remaining_wait);
220 CloseHandle(process);
221 result &= (wait_result == WAIT_OBJECT_0);
224 return result;
227 bool WaitForSingleProcess(ProcessHandle handle, base::TimeDelta wait) {
228 int exit_code;
229 return WaitForExitCodeWithTimeout(handle, &exit_code, wait) && exit_code == 0;
232 bool CleanupProcesses(const FilePath::StringType& executable_name,
233 base::TimeDelta wait,
234 int exit_code,
235 const ProcessFilter* filter) {
236 if (WaitForProcessesToExit(executable_name, wait, filter))
237 return true;
238 KillProcesses(executable_name, exit_code, filter);
239 return false;
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) {
247 return;
250 MessageLoop::current()->PostDelayedTask(
251 FROM_HERE,
252 base::Bind(&TimerExpiredTask::TimedOut,
253 base::Owned(new TimerExpiredTask(process.Pass()))),
254 base::TimeDelta::FromMilliseconds(kWaitInterval));
257 } // namespace base