blob: d198254ae7e3efdb56c325e34d4cdaf025ded51b [file] [log] [blame]
[email protected]fc14cef2009-01-27 22:17:291// Copyright (c) 2009 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.
4
5#include "chrome/browser/message_window.h"
6
7#include "base/base_paths.h"
8#include "base/command_line.h"
9#include "base/process_util.h"
10#include "base/win_util.h"
11#include "chrome/app/result_codes.h"
12#include "chrome/browser/browser_init.h"
13#include "chrome/browser/browser_process.h"
14#include "chrome/browser/profile.h"
15#include "chrome/browser/profile_manager.h"
16#include "chrome/common/chrome_constants.h"
17#include "chrome/common/chrome_paths.h"
18#include "chrome/common/l10n_util.h"
19#include "chrome/common/win_util.h"
20
21#include "chromium_strings.h"
22#include "generated_resources.h"
23
24namespace {
25
26// Checks the visiblilty of the enumerated window and signals once a visible
27// window has been found.
28BOOL CALLBACK BrowserWindowEnumeration(HWND window, LPARAM param) {
29 bool* result = reinterpret_cast<bool*>(param);
30 *result = IsWindowVisible(window) != 0;
31 // Stops enumeration if a visible window has been found.
32 return !*result;
33}
34
35} // namespace
36
[email protected]f7011fcb2009-01-28 21:54:3237MessageWindow::MessageWindow(const FilePath& user_data_dir)
[email protected]fc14cef2009-01-27 22:17:2938 : window_(NULL),
39 locked_(false) {
40 // Look for a Chrome instance that uses the same profile directory:
41 remote_window_ = FindWindowEx(HWND_MESSAGE,
42 NULL,
43 chrome::kMessageWindowClass,
[email protected]f7011fcb2009-01-28 21:54:3244 user_data_dir.ToWStringHack().c_str());
[email protected]fc14cef2009-01-27 22:17:2945}
46
47MessageWindow::~MessageWindow() {
48 if (window_)
49 DestroyWindow(window_);
50}
51
52bool MessageWindow::NotifyOtherProcess() {
53 if (!remote_window_)
54 return false;
55
56 // Found another window, send our command line to it
57 // format is "START\0<<<current directory>>>\0<<<commandline>>>".
58 std::wstring to_send(L"START\0", 6); // want the NULL in the string.
59 std::wstring cur_dir;
60 if (!PathService::Get(base::DIR_CURRENT, &cur_dir))
61 return false;
62 to_send.append(cur_dir);
63 to_send.append(L"\0", 1); // Null separator.
64 to_send.append(GetCommandLineW());
65 to_send.append(L"\0", 1); // Null separator.
66
67 // Allow the current running browser window making itself the foreground
68 // window (otherwise it will just flash in the taskbar).
69 DWORD process_id = 0;
70 DWORD thread_id = GetWindowThreadProcessId(remote_window_, &process_id);
71 DCHECK(process_id);
72 AllowSetForegroundWindow(process_id);
73
74 // Gives 20 seconds timeout for the current browser process to respond.
75 const int kTimeout = 20000;
76 COPYDATASTRUCT cds;
77 cds.dwData = 0;
78 cds.cbData = static_cast<DWORD>((to_send.length() + 1) * sizeof(wchar_t));
79 cds.lpData = const_cast<wchar_t*>(to_send.c_str());
80 DWORD_PTR result = 0;
81 if (SendMessageTimeout(remote_window_,
82 WM_COPYDATA,
83 NULL,
84 reinterpret_cast<LPARAM>(&cds),
85 SMTO_ABORTIFHUNG,
86 kTimeout,
87 &result)) {
88 return true;
89 }
90
91 // The window is hung. Scan for every window to find a visible one.
92 bool visible_window = false;
93 EnumThreadWindows(thread_id,
94 &BrowserWindowEnumeration,
95 reinterpret_cast<LPARAM>(&visible_window));
96
97 // If there is a visible browser window, ask the user before killing it.
98 if (visible_window) {
99 std::wstring text = l10n_util::GetString(IDS_BROWSER_HUNGBROWSER_MESSAGE);
100 std::wstring caption = l10n_util::GetString(IDS_PRODUCT_NAME);
101 if (IDYES != win_util::MessageBox(NULL, text, caption,
102 MB_YESNO | MB_ICONSTOP | MB_TOPMOST)) {
103 // The user denied. Quit silently.
104 return true;
105 }
106 }
107
108 // Time to take action. Kill the browser process.
[email protected]cd4fd152009-02-09 19:28:41109 base::KillProcessById(process_id, ResultCodes::HUNG, true);
[email protected]fc14cef2009-01-27 22:17:29110 remote_window_ = NULL;
111 return false;
112}
113
114void MessageWindow::Create() {
115 DCHECK(!window_);
116 DCHECK(!remote_window_);
117 HINSTANCE hinst = GetModuleHandle(NULL);
118
119 WNDCLASSEX wc = {0};
120 wc.cbSize = sizeof(wc);
121 wc.lpfnWndProc = MessageWindow::WndProcStatic;
122 wc.hInstance = hinst;
123 wc.lpszClassName = chrome::kMessageWindowClass;
124 RegisterClassEx(&wc);
125
126 std::wstring user_data_dir;
127 PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);
128
129 // Set the window's title to the path of our user data directory so other
130 // Chrome instances can decide if they should forward to us or not.
131 window_ = CreateWindow(chrome::kMessageWindowClass, user_data_dir.c_str(),
132 0, 0, 0, 0, 0, HWND_MESSAGE, 0, hinst, 0);
133 DCHECK(window_);
134
135 win_util::SetWindowUserData(window_, this);
136}
137
138LRESULT MessageWindow::OnCopyData(HWND hwnd, const COPYDATASTRUCT* cds) {
139 // Ignore the request if the browser process is already in shutdown path.
140 if (!g_browser_process || g_browser_process->IsShuttingDown())
141 return TRUE;
142
143 // If locked, it means we are not ready to process this message because
144 // we are probably in a first run critical phase.
145 if (locked_)
146 return TRUE;
147
148 // We should have enough room for the shortest command (min_message_size)
149 // and also be a multiple of wchar_t bytes.
150 static const int min_message_size = 7;
151 if (cds->cbData < min_message_size || cds->cbData % sizeof(wchar_t) != 0) {
152 LOG(WARNING) << "Invalid WM_COPYDATA, length = " << cds->cbData;
153 return TRUE;
154 }
155
156 // We split the string into 4 parts on NULLs.
157 const std::wstring msg(static_cast<wchar_t*>(cds->lpData),
158 cds->cbData / sizeof(wchar_t));
159 const std::wstring::size_type first_null = msg.find_first_of(L'\0');
160 if (first_null == 0 || first_null == std::wstring::npos) {
161 // no NULL byte, don't know what to do
162 LOG(WARNING) << "Invalid WM_COPYDATA, length = " << msg.length() <<
163 ", first null = " << first_null;
164 return TRUE;
165 }
166
167 // Decode the command, which is everything until the first NULL.
168 if (msg.substr(0, first_null) == L"START") {
169 // Another instance is starting parse the command line & do what it would
170 // have done.
171 LOG(INFO) << "Handling STARTUP request from another process";
172 const std::wstring::size_type second_null =
173 msg.find_first_of(L'\0', first_null + 1);
174 if (second_null == std::wstring::npos ||
175 first_null == msg.length() - 1 || second_null == msg.length()) {
176 LOG(WARNING) << "Invalid format for start command, we need a string in 4 "
177 "parts separated by NULLs";
178 return TRUE;
179 }
180
181 // Get current directory.
182 const std::wstring cur_dir =
183 msg.substr(first_null + 1, second_null - first_null);
184
185 const std::wstring::size_type third_null =
186 msg.find_first_of(L'\0', second_null + 1);
187 if (third_null == std::wstring::npos ||
188 third_null == msg.length()) {
189 LOG(WARNING) << "Invalid format for start command, we need a string in 4 "
190 "parts separated by NULLs";
191 }
192
193 // Get command line.
194 const std::wstring cmd_line =
195 msg.substr(second_null + 1, third_null - second_null);
196
197 CommandLine parsed_command_line(L"");
198 parsed_command_line.ParseFromString(cmd_line);
199 PrefService* prefs = g_browser_process->local_state();
200 DCHECK(prefs);
201
[email protected]f7011fcb2009-01-28 21:54:32202 FilePath user_data_dir;
[email protected]fc14cef2009-01-27 22:17:29203 PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);
204 ProfileManager* profile_manager = g_browser_process->profile_manager();
205 Profile* profile = profile_manager->GetDefaultProfile(user_data_dir);
206 if (!profile) {
207 // We should only be able to get here if the profile already exists and
208 // has been created.
209 NOTREACHED();
210 return TRUE;
211 }
[email protected]0303f31c2009-02-02 06:42:05212
213 // Run the browser startup sequence again, with the command line of the
214 // signalling process.
215 BrowserInit::ProcessCommandLine(parsed_command_line, cur_dir, prefs, false,
216 profile, NULL);
[email protected]fc14cef2009-01-27 22:17:29217 return TRUE;
218 }
219 return TRUE;
220}
221
222LRESULT CALLBACK MessageWindow::WndProc(HWND hwnd, UINT message,
223 WPARAM wparam, LPARAM lparam) {
224 switch (message) {
225 case WM_COPYDATA:
226 return OnCopyData(reinterpret_cast<HWND>(wparam),
227 reinterpret_cast<COPYDATASTRUCT*>(lparam));
228 default:
229 break;
230 }
231
232 return ::DefWindowProc(hwnd, message, wparam, lparam);
233}
234
235void MessageWindow::HuntForZombieChromeProcesses() {
236 // Detecting dead renderers is simple:
237 // - The process is named chrome.exe.
238 // - The process' parent doesn't exist anymore.
239 // - The process doesn't have a chrome::kMessageWindowClass window.
240 // If these conditions hold, the process is a zombie renderer or plugin.
241
242 // Retrieve the list of browser processes on start. This list is then used to
243 // detect zombie renderer process or plugin process.
244 class ZombieDetector : public base::ProcessFilter {
245 public:
246 ZombieDetector() {
247 for (HWND window = NULL;;) {
248 window = FindWindowEx(HWND_MESSAGE,
249 window,
250 chrome::kMessageWindowClass,
251 NULL);
252 if (!window)
253 break;
254 DWORD process = 0;
255 GetWindowThreadProcessId(window, &process);
256 if (process)
257 browsers_.push_back(process);
258 }
259 // We are also a browser, regardless of having the window or not.
260 browsers_.push_back(::GetCurrentProcessId());
261 }
262
263 virtual bool Includes(uint32 pid, uint32 parent_pid) const {
264 // Don't kill ourself eh.
265 if (GetCurrentProcessId() == pid)
266 return false;
267
268 // Is this a browser? If so, ignore it.
269 if (std::find(browsers_.begin(), browsers_.end(), pid) != browsers_.end())
270 return false;
271
272 // Is the parent a browser? If so, ignore it.
273 if (std::find(browsers_.begin(), browsers_.end(), parent_pid)
274 != browsers_.end())
275 return false;
276
277 // The chrome process is orphan.
278 return true;
279 }
280
281 protected:
282 std::vector<uint32> browsers_;
283 };
284
285 ZombieDetector zombie_detector;
286 base::KillProcesses(L"chrome.exe", ResultCodes::HUNG, &zombie_detector);
287}