[CleanUp] Move PowerApiManager to power_api and Rename
[chromium-blink-merge.git] / base / process / kill_win.cc
blob387c9e2b3b53881901c0800f6309950039f60a27
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/win/object_watcher.h"
17 namespace base {
19 namespace {
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
32 // process goes away.
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 {
39 public:
40 explicit TimerExpiredTask(Process process);
41 ~TimerExpiredTask();
43 void TimedOut();
45 // MessageLoop::Watcher -----------------------------------------------------
46 virtual void OnObjectSignaled(HANDLE object);
48 private:
49 void KillProcess();
51 // The process that we are watching.
52 Process process_;
54 win::ObjectWatcher watcher_;
56 DISALLOW_COPY_AND_ASSIGN(TimerExpiredTask);
59 TimerExpiredTask::TimerExpiredTask(Process process) : process_(process.Pass()) {
60 watcher_.StartWatching(process_.Handle(), this);
63 TimerExpiredTask::~TimerExpiredTask() {
64 TimedOut();
67 void TimerExpiredTask::TimedOut() {
68 if (process_.IsValid())
69 KillProcess();
72 void TimerExpiredTask::OnObjectSignaled(HANDLE object) {
73 process_.Close();
76 void TimerExpiredTask::KillProcess() {
77 // Stop watching the process handle since we're killing it.
78 watcher_.StopWatching();
80 // OK, time to get frisky. We don't actually care when the process
81 // terminates. We just care that it eventually terminates, and that's what
82 // TerminateProcess should do for us. Don't check for the result code since
83 // it fails quite often. This should be investigated eventually.
84 base::KillProcess(process_.Handle(), kProcessKilledExitCode, false);
86 // Now, just cleanup as if the process exited normally.
87 OnObjectSignaled(process_.Handle());
90 } // namespace
92 bool KillProcess(ProcessHandle process, int exit_code, bool wait) {
93 bool result = (TerminateProcess(process, exit_code) != FALSE);
94 if (result && wait) {
95 // The process may not end immediately due to pending I/O
96 if (WAIT_OBJECT_0 != WaitForSingleObject(process, 60 * 1000))
97 DPLOG(ERROR) << "Error waiting for process exit";
98 } else if (!result) {
99 DPLOG(ERROR) << "Unable to terminate process";
101 return result;
104 // Attempts to kill the process identified by the given process
105 // entry structure, giving it the specified exit code.
106 // Returns true if this is successful, false otherwise.
107 bool KillProcessById(ProcessId process_id, int exit_code, bool wait) {
108 HANDLE process = OpenProcess(PROCESS_TERMINATE | SYNCHRONIZE,
109 FALSE, // Don't inherit handle
110 process_id);
111 if (!process) {
112 DPLOG(ERROR) << "Unable to open process " << process_id;
113 return false;
115 bool ret = KillProcess(process, exit_code, wait);
116 CloseHandle(process);
117 return ret;
120 TerminationStatus GetTerminationStatus(ProcessHandle handle, int* exit_code) {
121 DWORD tmp_exit_code = 0;
123 if (!::GetExitCodeProcess(handle, &tmp_exit_code)) {
124 DPLOG(FATAL) << "GetExitCodeProcess() failed";
125 if (exit_code) {
126 // This really is a random number. We haven't received any
127 // information about the exit code, presumably because this
128 // process doesn't have permission to get the exit code, or
129 // because of some other cause for GetExitCodeProcess to fail
130 // (MSDN docs don't give the possible failure error codes for
131 // this function, so it could be anything). But we don't want
132 // to leave exit_code uninitialized, since that could cause
133 // random interpretations of the exit code. So we assume it
134 // terminated "normally" in this case.
135 *exit_code = kNormalTerminationExitCode;
137 // Assume the child has exited normally if we can't get the exit
138 // code.
139 return TERMINATION_STATUS_NORMAL_TERMINATION;
141 if (tmp_exit_code == STILL_ACTIVE) {
142 DWORD wait_result = WaitForSingleObject(handle, 0);
143 if (wait_result == WAIT_TIMEOUT) {
144 if (exit_code)
145 *exit_code = wait_result;
146 return TERMINATION_STATUS_STILL_RUNNING;
149 if (wait_result == WAIT_FAILED) {
150 DPLOG(ERROR) << "WaitForSingleObject() failed";
151 } else {
152 DCHECK_EQ(WAIT_OBJECT_0, wait_result);
154 // Strange, the process used 0x103 (STILL_ACTIVE) as exit code.
155 NOTREACHED();
158 return TERMINATION_STATUS_ABNORMAL_TERMINATION;
161 if (exit_code)
162 *exit_code = tmp_exit_code;
164 switch (tmp_exit_code) {
165 case kNormalTerminationExitCode:
166 return TERMINATION_STATUS_NORMAL_TERMINATION;
167 case kDebuggerInactiveExitCode: // STATUS_DEBUGGER_INACTIVE.
168 case kKeyboardInterruptExitCode: // Control-C/end session.
169 case kDebuggerTerminatedExitCode: // Debugger terminated process.
170 case kProcessKilledExitCode: // Task manager kill.
171 return TERMINATION_STATUS_PROCESS_WAS_KILLED;
172 default:
173 // All other exit codes indicate crashes.
174 return TERMINATION_STATUS_PROCESS_CRASHED;
178 bool WaitForExitCode(ProcessHandle handle, int* exit_code) {
179 // TODO(rvargas) crbug.com/417532: Remove this function.
180 Process process(handle);
181 return process.WaitForExit(exit_code);
184 bool WaitForExitCodeWithTimeout(ProcessHandle handle,
185 int* exit_code,
186 TimeDelta timeout) {
187 if (::WaitForSingleObject(
188 handle, static_cast<DWORD>(timeout.InMilliseconds())) != WAIT_OBJECT_0)
189 return false;
190 DWORD temp_code; // Don't clobber out-parameters in case of failure.
191 if (!::GetExitCodeProcess(handle, &temp_code))
192 return false;
194 *exit_code = temp_code;
195 return true;
198 bool WaitForProcessesToExit(const FilePath::StringType& executable_name,
199 TimeDelta wait,
200 const ProcessFilter* filter) {
201 bool result = true;
202 DWORD start_time = GetTickCount();
204 NamedProcessIterator iter(executable_name, filter);
205 for (const ProcessEntry* entry = iter.NextProcessEntry(); entry;
206 entry = iter.NextProcessEntry()) {
207 DWORD remaining_wait = static_cast<DWORD>(std::max(
208 static_cast<int64>(0),
209 wait.InMilliseconds() - (GetTickCount() - start_time)));
210 HANDLE process = OpenProcess(SYNCHRONIZE,
211 FALSE,
212 entry->th32ProcessID);
213 DWORD wait_result = WaitForSingleObject(process, remaining_wait);
214 CloseHandle(process);
215 result &= (wait_result == WAIT_OBJECT_0);
218 return result;
221 bool CleanupProcesses(const FilePath::StringType& executable_name,
222 TimeDelta wait,
223 int exit_code,
224 const ProcessFilter* filter) {
225 if (WaitForProcessesToExit(executable_name, wait, filter))
226 return true;
227 KillProcesses(executable_name, exit_code, filter);
228 return false;
231 void EnsureProcessTerminated(Process process) {
232 DCHECK(!process.is_current());
234 // If already signaled, then we are done!
235 if (WaitForSingleObject(process.Handle(), 0) == WAIT_OBJECT_0) {
236 return;
239 MessageLoop::current()->PostDelayedTask(
240 FROM_HERE,
241 Bind(&TimerExpiredTask::TimedOut,
242 Owned(new TimerExpiredTask(process.Pass()))),
243 TimeDelta::FromMilliseconds(kWaitInterval));
246 } // namespace base