OLD | NEW |
| (Empty) |
1 // Copyright 2003-2009 Google Inc. | |
2 // | |
3 // Licensed under the Apache License, Version 2.0 (the "License"); | |
4 // you may not use this file except in compliance with the License. | |
5 // You may obtain a copy of the License at | |
6 // | |
7 // http://www.apache.org/licenses/LICENSE-2.0 | |
8 // | |
9 // Unless required by applicable law or agreed to in writing, software | |
10 // distributed under the License is distributed on an "AS IS" BASIS, | |
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
12 // See the License for the specific language governing permissions and | |
13 // limitations under the License. | |
14 // ======================================================================== | |
15 // | |
16 // proc_utils.cpp | |
17 // | |
18 // Useful functions that relate to process/thread manipulation/information | |
19 // (Originally moved from utils.cpp) | |
20 | |
21 #include "omaha/base/proc_utils.h" | |
22 | |
23 #include <psapi.h> | |
24 #include "base/scoped_ptr.h" | |
25 #include "omaha/base/app_util.h" | |
26 #include "omaha/base/const_config.h" | |
27 #include "omaha/base/const_timeouts.h" | |
28 #include "omaha/base/debug.h" | |
29 #include "omaha/base/error.h" | |
30 #include "omaha/base/logging.h" | |
31 #include "omaha/base/process.h" | |
32 #include "omaha/base/reg_key.h" | |
33 #include "omaha/base/scoped_any.h" | |
34 #include "omaha/base/string.h" | |
35 #include "omaha/base/utils.h" | |
36 #include "omaha/base/window_utils.h" | |
37 | |
38 namespace omaha { | |
39 | |
40 ProcessTerminator::ProcessTerminator(const CString& process_name) | |
41 : recursion_level_(0), | |
42 process_name_(process_name), | |
43 flash_window_(false), | |
44 session_id_(INVALID_SESSION_ID) { | |
45 MakeLowerCString(process_name_); | |
46 } | |
47 | |
48 ProcessTerminator::ProcessTerminator(const CString& process_name, | |
49 const CString& user_sid) | |
50 : recursion_level_(0), | |
51 user_sid_(user_sid), | |
52 process_name_(process_name), | |
53 flash_window_(false), | |
54 session_id_(INVALID_SESSION_ID) { | |
55 MakeLowerCString(process_name_); | |
56 } | |
57 | |
58 ProcessTerminator::ProcessTerminator(const CString& process_name, | |
59 const CString& user_sid, | |
60 int session_id) | |
61 : recursion_level_(0), | |
62 user_sid_(user_sid), | |
63 session_id_(session_id), | |
64 process_name_(process_name), | |
65 flash_window_(false) { | |
66 MakeLowerCString(process_name_); | |
67 } | |
68 | |
69 ProcessTerminator::~ProcessTerminator() { | |
70 CloseAllHandles(); | |
71 } | |
72 | |
73 // Will close all currently opened handles. | |
74 void ProcessTerminator::CloseAllHandles() { | |
75 UTIL_LOG(L3, (_T("[CloseAllHandles]"))); | |
76 // Do clean up if we have opened handles. | |
77 for (size_t i = 0; i < process_handles_.size(); i++) { | |
78 VERIFY1(::CloseHandle(process_handles_[i])); | |
79 } | |
80 | |
81 process_handles_.clear(); | |
82 } | |
83 | |
84 // Wait for a while till all process instances will die. | |
85 bool ProcessTerminator::WaitForProcessInstancesToDie( | |
86 uint32 timeout_msec) const { | |
87 UTIL_LOG(L3, (_T("[WaitForProcessInstancesToDie]"))); | |
88 size_t size = process_handles_.size(); | |
89 scoped_array<HANDLE> handles(new HANDLE[size]); | |
90 | |
91 for (size_t i = 0; i < size; i++) { | |
92 handles[i] = process_handles_[i]; | |
93 } | |
94 | |
95 DWORD wait_result = ::WaitForMultipleObjectsEx(size, | |
96 handles.get(), | |
97 true, | |
98 timeout_msec, | |
99 false); | |
100 #pragma warning(disable : 4296) | |
101 // C4296: '>=' : expression is always true | |
102 if ((wait_result >= WAIT_OBJECT_0) && | |
103 (wait_result < WAIT_OBJECT_0 + size)) { | |
104 return true; | |
105 } | |
106 #pragma warning(default : 4296) | |
107 | |
108 UTIL_LOG(L3, (_T("WaitForProcessToDie timed out for '%s'. Waited for %d ms."), | |
109 process_name_, timeout_msec)); | |
110 return false; | |
111 } | |
112 | |
113 // Finds all process ids for the process of a given name. | |
114 bool ProcessTerminator::FindProcessInstances() { | |
115 UTIL_LOG(L3, (_T("[FindProcessInstances]"))); | |
116 | |
117 DWORD exclude_mask = EXCLUDE_CURRENT_PROCESS; | |
118 if (!user_sid_.IsEmpty()) { | |
119 exclude_mask |= INCLUDE_ONLY_PROCESS_OWNED_BY_USER; | |
120 } | |
121 | |
122 std::vector<CString> command_lines; | |
123 HRESULT hr = S_OK; | |
124 if (session_id_ != INVALID_SESSION_ID) { | |
125 hr = Process::FindProcessesInSession(session_id_, | |
126 exclude_mask, | |
127 process_name_, | |
128 true, | |
129 user_sid_, | |
130 command_lines, | |
131 &process_ids_); | |
132 } else { | |
133 hr = Process::FindProcesses(exclude_mask, | |
134 process_name_, | |
135 true, | |
136 user_sid_, | |
137 command_lines, | |
138 &process_ids_); | |
139 } | |
140 | |
141 return SUCCEEDED(hr) && !process_ids_.empty(); | |
142 } | |
143 | |
144 // Tries to kill all instances of the process that was specified in the | |
145 // constructor. | |
146 // 'method_mask' determines which technique to attempt. | |
147 // 'was_found' is optional and can be NULL. | |
148 // Returns S_OK if all instances were killed, S_FALSE if process wasn't running, | |
149 // and E_FAIL if one or more instances weren't killed. | |
150 // Always sets 'was_found' correctly, regardless of return value. | |
151 HRESULT ProcessTerminator::KillTheProcess(uint32 timeout_msec, | |
152 bool* was_found, | |
153 uint32 method_mask, | |
154 bool flash_window) { | |
155 UTIL_LOG(L3, (_T("[KillTheProcess]"))); | |
156 if (!FindProcessInstances()) { | |
157 if (was_found != NULL) { | |
158 *was_found = false; | |
159 } | |
160 return S_FALSE; // process is not running, so don't return a FAILED hr | |
161 } | |
162 | |
163 // If got here, found at least one process to kill | |
164 if (was_found != NULL) { | |
165 *was_found = true; | |
166 } | |
167 | |
168 flash_window_ = flash_window; | |
169 // Try the nicest, cleanest method of closing a process: window messages | |
170 if (method_mask & KILL_METHOD_1_WINDOW_MESSAGE) { | |
171 if (PrepareToKill(KILL_METHOD_1_WINDOW_MESSAGE)) { | |
172 KillProcessViaWndMessages(timeout_msec); | |
173 } | |
174 | |
175 // Are any instances of the process still running? | |
176 if (!FindProcessInstances()) { | |
177 return S_OK; // killed them all | |
178 } | |
179 } | |
180 | |
181 // Also nice method | |
182 if (method_mask & KILL_METHOD_2_THREAD_MESSAGE) { | |
183 if (PrepareToKill(KILL_METHOD_2_THREAD_MESSAGE)) { | |
184 KillProcessViaThreadMessages(timeout_msec); | |
185 } | |
186 // Are any instances of the process still running? | |
187 if (!FindProcessInstances()) { | |
188 return S_OK; // killed them all | |
189 } | |
190 } | |
191 | |
192 // the crude one. | |
193 if (method_mask & KILL_METHOD_4_TERMINATE_PROCESS) { | |
194 if (PrepareToKill(KILL_METHOD_4_TERMINATE_PROCESS)) { | |
195 KillProcessViaTerminate(timeout_msec); | |
196 } | |
197 // Are any instances of the process still running? | |
198 if (!FindProcessInstances()) { | |
199 return S_OK; // killed them all | |
200 } | |
201 | |
202 UTIL_LOG(LEVEL_ERROR, (_T("[ProcessTerminator::KillTheProcess]") | |
203 _T("[totally unable to kill process '%s']"), | |
204 process_name_)); | |
205 } | |
206 | |
207 return E_FAIL; | |
208 } | |
209 | |
210 HRESULT ProcessTerminator::WaitForAllToDie(uint32 timeout_msec) { | |
211 UTIL_LOG(L3, (_T("[WaitForAllToDie]"))); | |
212 if (!FindProcessInstances()) { | |
213 return S_OK; | |
214 } | |
215 | |
216 if (PrepareToKill(KILL_METHOD_1_WINDOW_MESSAGE)) { | |
217 return WaitForProcessInstancesToDie(timeout_msec) ? S_OK : | |
218 HRESULT_FROM_WIN32(WAIT_TIMEOUT); | |
219 } | |
220 | |
221 return E_FAIL; | |
222 } | |
223 | |
224 // Given process_ids array will try to | |
225 // open handle to each instance. | |
226 // Leaves process handles open (in member process_handles_) | |
227 // Will use access rights for opening appropriate for the purpose_of_opening. | |
228 // This function recursively calls itself if by the time it tries to open | |
229 // handles to process instances some of the processes died or naturally exited. | |
230 bool ProcessTerminator::PrepareToKill(uint32 method_mask) { | |
231 UTIL_LOG(L3, (_T("[PrepareToKill]"))); | |
232 uint32 desired_access = 0; | |
233 | |
234 if (method_mask & KILL_METHOD_4_TERMINATE_PROCESS) { | |
235 desired_access = SYNCHRONIZE | | |
236 PROCESS_TERMINATE | | |
237 PROCESS_QUERY_INFORMATION; | |
238 } else { | |
239 desired_access = SYNCHRONIZE | PROCESS_QUERY_INFORMATION | PROCESS_VM_READ; | |
240 } | |
241 | |
242 // do clean up in case some handles are opened. | |
243 CloseAllHandles(); | |
244 | |
245 if (process_ids_.empty()) { | |
246 // no instances are running. | |
247 return false; | |
248 } | |
249 | |
250 for (size_t i = 0; i < process_ids_.size(); i++) { | |
251 HANDLE handle = ::OpenProcess(desired_access, false, process_ids_[i]); | |
252 if (handle) { | |
253 process_handles_.push_back(handle); | |
254 } else { | |
255 if (::GetLastError() == ERROR_ACCESS_DENIED) { | |
256 // If we are here that means that we do not have enough priveleges to | |
257 // open the process for a given kill method. No reason to attempt other | |
258 // instances. Just clean up and return false. | |
259 UTIL_LOG(L3, (_T("PrepareToKill failed for '%s'. Kill method %d."), | |
260 process_name_, method_mask)); | |
261 CloseAllHandles(); | |
262 return false; | |
263 } | |
264 } | |
265 } | |
266 // We already handled the case when we don't have enough privileges to open | |
267 // the process. So if we have less handles than process ids -> some of the | |
268 // processes have died since we made a snapshot untill the time we tried to | |
269 // open handles. We need to do another snapshot and try to open handles one | |
270 // more time. We need number of handles and number of ids to be equal. | |
271 // We can do it with recursion. The idea is: make the next snapshot and open | |
272 // handles. Hopefully the number will be equal. Stop recursion at the third | |
273 // level. | |
274 | |
275 if (process_handles_.size() != process_ids_.size()) { | |
276 recursion_level_++; | |
277 | |
278 // we have a disbalance here. This is pretty bad. | |
279 // Some of the processes died already so let's try | |
280 // to balance them. | |
281 if (!FindProcessInstances()) { | |
282 // they are all dead. | |
283 recursion_level_ = 0; | |
284 return false; | |
285 } | |
286 | |
287 // try to balance three times no more. | |
288 if (recursion_level_ >= 3) { | |
289 recursion_level_ = 0; | |
290 UTIL_LOG(L3, (_T("Recursion level too deep in PrepareToKill for '%s'."), | |
291 process_name_)); | |
292 return false; | |
293 } | |
294 | |
295 // recursively call the function | |
296 return PrepareToKill(method_mask); | |
297 } | |
298 recursion_level_ = 0; | |
299 return true; | |
300 } | |
301 | |
302 // ProcessTerminator::FindProcessWindows | |
303 // Just calls enumeration function | |
304 bool ProcessTerminator::FindProcessWindows() { | |
305 window_handles_.clear(); | |
306 return ::EnumWindows(EnumAllWindowsProc, reinterpret_cast<LPARAM>(this)) && | |
307 !window_handles_.empty(); | |
308 } | |
309 | |
310 // ProcessTerminator::EnumAllWindowsProc | |
311 // During enumeration this function will try to find a match between | |
312 // process id we already found and process id obtained from each window. | |
313 // if there is a match, we record the window in an array | |
314 BOOL ProcessTerminator::EnumAllWindowsProc(HWND hwnd, LPARAM lparam) { | |
315 ProcessTerminator* this_pointer = | |
316 reinterpret_cast<ProcessTerminator*>(lparam); | |
317 ASSERT1(this_pointer); | |
318 | |
319 uint32 process_id = 0; | |
320 uint32 thread_id = | |
321 ::GetWindowThreadProcessId(hwnd, reinterpret_cast<DWORD*>(&process_id)); | |
322 | |
323 typedef std::vector<uint32>::const_iterator ProcessIdIterator; | |
324 for (ProcessIdIterator it = this_pointer->process_ids_.begin(); | |
325 it != this_pointer->process_ids_.end(); | |
326 ++it) { | |
327 if (*it == process_id) { | |
328 // The main idea is: Find all top level windows (NO PARENT!!!) | |
329 // AND this windows must have system menu and be visible. So we make sure | |
330 // that we send WM_CLOSE ONLY to the windows that user might close | |
331 // interactively. This way we are safe. The last thing to check is if it | |
332 // is tr hidden window. | |
333 if (WindowUtils::IsMainWindow(hwnd) && WindowUtils::HasSystemMenu(hwnd)) { | |
334 this_pointer->window_handles_.push_back(hwnd); | |
335 } | |
336 } | |
337 } | |
338 return TRUE; | |
339 } | |
340 | |
341 // ProcessTerminator::KillProcessViaWndMessages() | |
342 // try to post a windows message | |
343 bool ProcessTerminator::KillProcessViaWndMessages(uint32 timeout_msec) { | |
344 UTIL_LOG(L3, (_T("[KillProcessViaWndMessages]"))); | |
345 if (!FindProcessWindows()) { | |
346 UTIL_LOG(L1, (_T("[KillProcessViaWndMessages]") | |
347 _T("[failed to find any windows for '%s']"), process_name_)); | |
348 return false; | |
349 } | |
350 | |
351 bool post_messages_succeeded = false; | |
352 | |
353 for (size_t i = 0; i < window_handles_.size(); i++) { | |
354 // Previous method used WM_CLOSE, WM_SYSCOMMAND+SC_CLOSE is slightly better. | |
355 // It closes our apps, and also works correctly on AOL! | |
356 if (::PostMessage(window_handles_[i], WM_SYSCOMMAND, SC_CLOSE, 0)) { | |
357 if (flash_window_) { | |
358 UTIL_LOG(L3, (_T("[PostMessageSucceeded flashing window]"))); | |
359 ::FlashWindow(window_handles_[i], true); | |
360 } | |
361 post_messages_succeeded = true; | |
362 } | |
363 } | |
364 | |
365 if (!post_messages_succeeded) { | |
366 UTIL_LOG(L3, (_T("[KillProcessViaWndMessages]") | |
367 _T("[failed to PostMessage to windows of '%s']"), | |
368 process_name_)); | |
369 } | |
370 // If we succeeded in posting message at least one time we have to wait. | |
371 // We don't know the relationship between windows in the process. | |
372 return post_messages_succeeded && WaitForProcessInstancesToDie(timeout_msec); | |
373 } | |
374 | |
375 // Try to post a thread message. | |
376 bool ProcessTerminator::KillProcessViaThreadMessages(uint32 timeout_msec) { | |
377 UTIL_LOG(L3, (_T("[KillProcessViaThreadMessages]"))); | |
378 std::vector<uint32> thread_ids; | |
379 | |
380 if (!FindProcessThreads(&thread_ids)) { | |
381 UTIL_LOG(L3, (_T("[KillProcessViaThreadMessages]") | |
382 _T("[failed to find any threads for '%s']"), process_name_)); | |
383 return false; | |
384 } | |
385 | |
386 bool post_messages_succeeded = false; | |
387 for (size_t i = 0; i < thread_ids.size(); i++) { | |
388 if (::PostThreadMessage(thread_ids[i], WM_CLOSE, 0, 0)) { | |
389 post_messages_succeeded = true; | |
390 } | |
391 } | |
392 | |
393 if (!post_messages_succeeded) { | |
394 UTIL_LOG(L3, (_T("[KillProcessViaWndMessages]") | |
395 _T("[failed to PostMessage to threads of '%s'."), | |
396 process_name_)); | |
397 } | |
398 // If we succeded in posting message to at least one thread we have to wait. | |
399 // We don't know the relationship between threads in the process. | |
400 return post_messages_succeeded && WaitForProcessInstancesToDie(timeout_msec); | |
401 } | |
402 | |
403 // find all the threads running in a given process. | |
404 bool ProcessTerminator::FindProcessThreads(std::vector<uint32>* thread_ids) { | |
405 HANDLE process_snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); | |
406 if (process_snapshot == INVALID_HANDLE_VALUE) { | |
407 return false; | |
408 } | |
409 | |
410 THREADENTRY32 thread_info = {0}; // zero it out just in case. | |
411 thread_info.dwSize = sizeof(THREADENTRY32); | |
412 | |
413 if (::Thread32First(process_snapshot, &thread_info)) { | |
414 do { | |
415 for (std::vector<uint32>::const_iterator it = process_ids_.begin(); | |
416 it != process_ids_.end(); ++it) { | |
417 if (*it == thread_info.th32OwnerProcessID) { | |
418 // we have found it. | |
419 thread_ids->push_back(thread_info.th32ThreadID); | |
420 } | |
421 } | |
422 // system changes this value, do not forget to reset to | |
423 // max possible. | |
424 thread_info.dwSize = sizeof(THREADENTRY32); | |
425 } while (::Thread32Next(process_snapshot, &thread_info)); | |
426 } | |
427 | |
428 return !thread_ids->empty(); | |
429 } | |
430 | |
431 // Last and crude method to kill the process. Should be used only | |
432 // if all other methods have failed. | |
433 bool ProcessTerminator::KillProcessViaTerminate(uint32 timeout_msec) { | |
434 UTIL_LOG(L3, (_T("[KillProcessViaTerminate]"))); | |
435 bool at_least_one_terminated = false; | |
436 | |
437 for (size_t i = 0; i < process_handles_.size(); i++) { | |
438 if (!::TerminateProcess(process_handles_[i], 0)) { | |
439 UTIL_LOG(L3, (_T("[KillProcessViaTerminate]") | |
440 _T("[failed for instance of '%s'][System error %d]"), | |
441 process_name_, ::GetLastError())); | |
442 } else { | |
443 at_least_one_terminated = true; | |
444 } | |
445 } | |
446 return at_least_one_terminated ? WaitForProcessInstancesToDie(timeout_msec) : | |
447 false; | |
448 } | |
449 | |
450 HRESULT SetProcessSilentShutdown() { | |
451 DWORD shut_down_level(0), shut_down_flags(0); | |
452 if (!::GetProcessShutdownParameters(&shut_down_level, &shut_down_flags)) { | |
453 return HRESULTFromLastError(); | |
454 } | |
455 shut_down_flags |= SHUTDOWN_NORETRY; | |
456 if (!::SetProcessShutdownParameters(shut_down_level, shut_down_flags)) { | |
457 return HRESULTFromLastError(); | |
458 } | |
459 return S_OK; | |
460 } | |
461 | |
462 } // namespace omaha | |
463 | |
OLD | NEW |