blob: 4d20415b10d1a88f3d4eeecf19e6f9345216f262 [file] [log] [blame]
[email protected]e3ce40a2012-01-31 03:03:031// Copyright (c) 2012 The Chromium Authors. All rights reserved.
[email protected]fc14cef2009-01-27 22:17:292// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
[email protected]7c47ae3e2009-02-18 00:34:215#include "chrome/browser/process_singleton.h"
[email protected]fc14cef2009-01-27 22:17:296
7#include "base/base_paths.h"
8#include "base/command_line.h"
[email protected]f805fe82010-08-03 22:47:109#include "base/file_path.h"
[email protected]9e9b6e8e2009-12-02 08:45:0110#include "base/path_service.h"
[email protected]fc14cef2009-01-27 22:17:2911#include "base/process_util.h"
[email protected]0f26d7b2011-01-05 19:10:4412#include "base/utf_string_conversions.h"
[email protected]b90d7e802011-01-09 16:32:2013#include "base/win/scoped_handle.h"
[email protected]ecb924c2011-03-17 00:34:0914#include "base/win/wrapped_window_proc.h"
[email protected]fc14cef2009-01-27 22:17:2915#include "chrome/browser/browser_process.h"
[email protected]6aeac8342010-10-01 20:21:1816#include "chrome/browser/extensions/extensions_startup.h"
[email protected]8ecad5e2010-12-02 21:18:3317#include "chrome/browser/profiles/profile.h"
18#include "chrome/browser/profiles/profile_manager.h"
[email protected]80772ed2011-08-09 21:11:3819#include "chrome/browser/simple_message_box.h"
[email protected]f7002802010-11-12 19:50:2820#include "chrome/browser/ui/browser_init.h"
[email protected]fc14cef2009-01-27 22:17:2921#include "chrome/common/chrome_constants.h"
22#include "chrome/common/chrome_paths.h"
[email protected]6aeac8342010-10-01 20:21:1823#include "chrome/common/chrome_switches.h"
[email protected]0a194552011-09-14 17:53:3524#include "chrome/installer/util/wmi.h"
[email protected]b39ef1cb2011-10-25 04:46:5525#include "content/public/common/result_codes.h"
[email protected]34ac8f32009-02-22 23:03:2726#include "grit/chromium_strings.h"
27#include "grit/generated_resources.h"
[email protected]c051a1b2011-01-21 23:30:1728#include "ui/base/l10n/l10n_util.h"
[email protected]e7661062011-01-19 22:16:5329#include "ui/base/win/hwnd_util.h"
[email protected]fc14cef2009-01-27 22:17:2930
31namespace {
32
[email protected]f891fb32009-04-08 00:20:3233// Checks the visibility of the enumerated window and signals once a visible
[email protected]fc14cef2009-01-27 22:17:2934// window has been found.
35BOOL CALLBACK BrowserWindowEnumeration(HWND window, LPARAM param) {
36 bool* result = reinterpret_cast<bool*>(param);
37 *result = IsWindowVisible(window) != 0;
38 // Stops enumeration if a visible window has been found.
39 return !*result;
40}
41
[email protected]e3ce40a2012-01-31 03:03:0342// This function thunks to the object's version of the windowproc, taking in
43// consideration that there are several messages being dispatched before
44// WM_NCCREATE which we let windows handle.
45LRESULT CALLBACK ThunkWndProc(HWND hwnd, UINT message,
46 WPARAM wparam, LPARAM lparam) {
47 ProcessSingleton* singleton =
48 reinterpret_cast<ProcessSingleton*>(ui::GetWindowUserData(hwnd));
49 if (message == WM_NCCREATE) {
50 CREATESTRUCT* cs = reinterpret_cast<CREATESTRUCT*>(lparam);
51 singleton = reinterpret_cast<ProcessSingleton*>(cs->lpCreateParams);
52 CHECK(singleton);
53 ui::SetWindowUserData(hwnd, singleton);
54 } else if (!singleton) {
55 return ::DefWindowProc(hwnd, message, wparam, lparam);
56 }
57 return singleton->WndProc(hwnd, message, wparam, lparam);
58}
59
[email protected]fc14cef2009-01-27 22:17:2960} // namespace
61
[email protected]0a194552011-09-14 17:53:3562// Microsoft's Softricity virtualization breaks the sandbox processes.
63// So, if we detect the Softricity DLL we use WMI Win32_Process.Create to
64// break out of the virtualization environment.
65// http://code.google.com/p/chromium/issues/detail?id=43650
66bool ProcessSingleton::EscapeVirtualization(const FilePath& user_data_dir) {
67 if (::GetModuleHandle(L"sftldr_wow64.dll") ||
68 ::GetModuleHandle(L"sftldr.dll")) {
69 int process_id;
70 if (!installer::WMIProcess::Launch(GetCommandLineW(), &process_id))
71 return false;
72 is_virtualized_ = true;
73 // The new window was spawned from WMI, and won't be in the foreground.
74 // So, first we sleep while the new chrome.exe instance starts (because
75 // WaitForInputIdle doesn't work here). Then we poll for up to two more
76 // seconds and make the window foreground if we find it (or we give up).
77 HWND hwnd = 0;
78 ::Sleep(90);
79 for (int tries = 200; tries; --tries) {
80 hwnd = FindWindowEx(HWND_MESSAGE, NULL, chrome::kMessageWindowClass,
81 user_data_dir.value().c_str());
82 if (hwnd) {
83 ::SetForegroundWindow(hwnd);
84 break;
85 }
86 ::Sleep(10);
87 }
88 return true;
89 }
90 return false;
91}
92
[email protected]f891fb32009-04-08 00:20:3293// Look for a Chrome instance that uses the same profile directory.
[email protected]9a182832012-02-10 18:45:5894// If there isn't one, create a message window with its title set to
95// the profile directory path.
[email protected]7c47ae3e2009-02-18 00:34:2196ProcessSingleton::ProcessSingleton(const FilePath& user_data_dir)
[email protected]0a194552011-09-14 17:53:3597 : window_(NULL), locked_(false), foreground_window_(NULL),
98 is_virtualized_(false) {
[email protected]bbef41f02010-03-04 16:16:1999 remote_window_ = FindWindowEx(HWND_MESSAGE, NULL,
100 chrome::kMessageWindowClass,
[email protected]8a205c02011-02-04 20:41:33101 user_data_dir.value().c_str());
[email protected]0a194552011-09-14 17:53:35102 if (!remote_window_ && !EscapeVirtualization(user_data_dir)) {
[email protected]bbef41f02010-03-04 16:16:19103 // Make sure we will be the one and only process creating the window.
104 // We use a named Mutex since we are protecting against multi-process
105 // access. As documented, it's clearer to NOT request ownership on creation
106 // since it isn't guaranteed we will get it. It is better to create it
107 // without ownership and explicitly get the ownership afterward.
[email protected]e132804b2010-12-22 12:48:25108 std::wstring mutex_name(L"Local\\ChromeProcessSingletonStartup!");
[email protected]b90d7e802011-01-09 16:32:20109 base::win::ScopedHandle only_me(
110 CreateMutex(NULL, FALSE, mutex_name.c_str()));
[email protected]bbef41f02010-03-04 16:16:19111 DCHECK(only_me.Get() != NULL) << "GetLastError = " << GetLastError();
112
113 // This is how we acquire the mutex (as opposed to the initial ownership).
114 DWORD result = WaitForSingleObject(only_me, INFINITE);
115 DCHECK(result == WAIT_OBJECT_0) << "Result = " << result <<
116 "GetLastError = " << GetLastError();
117
118 // We now own the mutex so we are the only process that can create the
119 // window at this time, but we must still check if someone created it
120 // between the time where we looked for it above and the time the mutex
121 // was given to us.
122 remote_window_ = FindWindowEx(HWND_MESSAGE, NULL,
123 chrome::kMessageWindowClass,
[email protected]8a205c02011-02-04 20:41:33124 user_data_dir.value().c_str());
[email protected]9a182832012-02-10 18:45:58125 if (!remote_window_) {
126 HINSTANCE hinst = base::GetModuleFromAddress(&ThunkWndProc);
127
128 WNDCLASSEX wc = {0};
129 wc.cbSize = sizeof(wc);
130 wc.lpfnWndProc = base::win::WrappedWindowProc<ThunkWndProc>;
131 wc.hInstance = hinst;
132 wc.lpszClassName = chrome::kMessageWindowClass;
133 ATOM clazz = ::RegisterClassEx(&wc);
134 DCHECK(clazz);
135
136 FilePath user_data_dir;
137 PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);
138
139 // Set the window's title to the path of our user data directory so other
140 // Chrome instances can decide if they should forward to us or not.
141 window_ = ::CreateWindow(MAKEINTATOM(clazz),
142 user_data_dir.value().c_str(),
143 0, 0, 0, 0, 0, HWND_MESSAGE, 0, hinst, this);
144 CHECK(window_);
145 }
[email protected]bbef41f02010-03-04 16:16:19146 BOOL success = ReleaseMutex(only_me);
147 DCHECK(success) << "GetLastError = " << GetLastError();
148 }
[email protected]fc14cef2009-01-27 22:17:29149}
150
[email protected]7c47ae3e2009-02-18 00:34:21151ProcessSingleton::~ProcessSingleton() {
[email protected]9a182832012-02-10 18:45:58152 Cleanup();
[email protected]fc14cef2009-01-27 22:17:29153}
154
[email protected]9f20a6d02009-08-21 01:18:37155ProcessSingleton::NotifyResult ProcessSingleton::NotifyOtherProcess() {
[email protected]0a194552011-09-14 17:53:35156 if (is_virtualized_)
157 return PROCESS_NOTIFIED; // We already spawned the process in this case.
158 else if (!remote_window_)
[email protected]9f20a6d02009-08-21 01:18:37159 return PROCESS_NONE;
[email protected]fc14cef2009-01-27 22:17:29160
161 // Found another window, send our command line to it
162 // format is "START\0<<<current directory>>>\0<<<commandline>>>".
163 std::wstring to_send(L"START\0", 6); // want the NULL in the string.
[email protected]b9696482010-11-30 23:56:18164 FilePath cur_dir;
[email protected]fc14cef2009-01-27 22:17:29165 if (!PathService::Get(base::DIR_CURRENT, &cur_dir))
[email protected]9f20a6d02009-08-21 01:18:37166 return PROCESS_NONE;
[email protected]b9696482010-11-30 23:56:18167 to_send.append(cur_dir.value());
[email protected]fc14cef2009-01-27 22:17:29168 to_send.append(L"\0", 1); // Null separator.
169 to_send.append(GetCommandLineW());
170 to_send.append(L"\0", 1); // Null separator.
171
172 // Allow the current running browser window making itself the foreground
173 // window (otherwise it will just flash in the taskbar).
174 DWORD process_id = 0;
175 DWORD thread_id = GetWindowThreadProcessId(remote_window_, &process_id);
[email protected]0815b6d2009-02-11 00:39:37176 // It is possible that the process owning this window may have died by now.
177 if (!thread_id || !process_id) {
178 remote_window_ = NULL;
[email protected]9f20a6d02009-08-21 01:18:37179 return PROCESS_NONE;
[email protected]0815b6d2009-02-11 00:39:37180 }
181
[email protected]fc14cef2009-01-27 22:17:29182 AllowSetForegroundWindow(process_id);
183
[email protected]fc14cef2009-01-27 22:17:29184 COPYDATASTRUCT cds;
185 cds.dwData = 0;
186 cds.cbData = static_cast<DWORD>((to_send.length() + 1) * sizeof(wchar_t));
187 cds.lpData = const_cast<wchar_t*>(to_send.c_str());
188 DWORD_PTR result = 0;
189 if (SendMessageTimeout(remote_window_,
190 WM_COPYDATA,
191 NULL,
192 reinterpret_cast<LPARAM>(&cds),
193 SMTO_ABORTIFHUNG,
[email protected]8b08cbd2009-08-04 05:34:19194 kTimeoutInSeconds * 1000,
[email protected]fc14cef2009-01-27 22:17:29195 &result)) {
[email protected]0815b6d2009-02-11 00:39:37196 // It is possible that the process owning this window may have died by now.
197 if (!result) {
198 remote_window_ = NULL;
[email protected]9f20a6d02009-08-21 01:18:37199 return PROCESS_NONE;
[email protected]0815b6d2009-02-11 00:39:37200 }
[email protected]9f20a6d02009-08-21 01:18:37201 return PROCESS_NOTIFIED;
[email protected]fc14cef2009-01-27 22:17:29202 }
203
[email protected]0815b6d2009-02-11 00:39:37204 // It is possible that the process owning this window may have died by now.
205 if (!IsWindow(remote_window_)) {
206 remote_window_ = NULL;
[email protected]9f20a6d02009-08-21 01:18:37207 return PROCESS_NONE;
[email protected]0815b6d2009-02-11 00:39:37208 }
209
[email protected]fc14cef2009-01-27 22:17:29210 // The window is hung. Scan for every window to find a visible one.
211 bool visible_window = false;
212 EnumThreadWindows(thread_id,
213 &BrowserWindowEnumeration,
214 reinterpret_cast<LPARAM>(&visible_window));
215
216 // If there is a visible browser window, ask the user before killing it.
217 if (visible_window) {
[email protected]80772ed2011-08-09 21:11:38218 string16 text = l10n_util::GetStringUTF16(IDS_BROWSER_HUNGBROWSER_MESSAGE);
219 string16 caption = l10n_util::GetStringUTF16(IDS_PRODUCT_NAME);
220 if (!browser::ShowYesNoBox(NULL, caption, text)) {
[email protected]fc14cef2009-01-27 22:17:29221 // The user denied. Quit silently.
[email protected]9f20a6d02009-08-21 01:18:37222 return PROCESS_NOTIFIED;
[email protected]fc14cef2009-01-27 22:17:29223 }
224 }
225
226 // Time to take action. Kill the browser process.
[email protected]1fcfb202011-07-19 19:53:14227 base::KillProcessById(process_id, content::RESULT_CODE_HUNG, true);
[email protected]fc14cef2009-01-27 22:17:29228 remote_window_ = NULL;
[email protected]9f20a6d02009-08-21 01:18:37229 return PROCESS_NONE;
[email protected]fc14cef2009-01-27 22:17:29230}
231
[email protected]4a44bc32010-05-28 22:22:44232ProcessSingleton::NotifyResult ProcessSingleton::NotifyOtherProcessOrCreate() {
233 NotifyResult result = NotifyOtherProcess();
234 if (result != PROCESS_NONE)
235 return result;
[email protected]9a182832012-02-10 18:45:58236 return window_ ? PROCESS_NONE : PROFILE_IN_USE;
[email protected]4a44bc32010-05-28 22:22:44237}
238
[email protected]9a182832012-02-10 18:45:58239// On Windows, there is no need to call Create() since the message
240// window is created in the constructor but to avoid having more
241// platform specific code in browser_main.cc we tolerate calls to
242// Create(), which will do nothing.
[email protected]4dd42242010-04-07 02:21:15243bool ProcessSingleton::Create() {
[email protected]fc14cef2009-01-27 22:17:29244 DCHECK(!remote_window_);
[email protected]9a182832012-02-10 18:45:58245 return window_ != NULL;
[email protected]fc14cef2009-01-27 22:17:29246}
247
[email protected]9f20a6d02009-08-21 01:18:37248void ProcessSingleton::Cleanup() {
[email protected]9a182832012-02-10 18:45:58249 // Window classes registered by DLLs are not cleaned up automatically on
250 // process exit, so we must unregister at the earliest chance possible.
251 // During the fast shutdown sequence, ProcessSingleton::Cleanup() is
252 // called if our process was the first to start. Therefore we try cleaning
253 // up here, and again in the destructor if needed to catch as many cases
254 // as possible.
255 if (window_) {
256 ::DestroyWindow(window_);
257 ::UnregisterClass(chrome::kMessageWindowClass,
258 base::GetModuleFromAddress(&ThunkWndProc));
259 window_ = NULL;
260 }
[email protected]9f20a6d02009-08-21 01:18:37261}
262
[email protected]7c47ae3e2009-02-18 00:34:21263LRESULT ProcessSingleton::OnCopyData(HWND hwnd, const COPYDATASTRUCT* cds) {
[email protected]175a7a22009-05-03 15:57:53264 // If locked, it means we are not ready to process this message because
[email protected]afd20c022010-06-10 00:48:20265 // we are probably in a first run critical phase.
[email protected]175a7a22009-05-03 15:57:53266 if (locked_) {
[email protected]95259c62011-10-25 23:23:53267#if defined(USE_AURA)
268 NOTIMPLEMENTED();
269#else
[email protected]175a7a22009-05-03 15:57:53270 // Attempt to place ourselves in the foreground / flash the task bar.
271 if (IsWindow(foreground_window_))
272 SetForegroundWindow(foreground_window_);
[email protected]95259c62011-10-25 23:23:53273#endif
[email protected]175a7a22009-05-03 15:57:53274 return TRUE;
275 }
276
[email protected]fc14cef2009-01-27 22:17:29277 // Ignore the request if the browser process is already in shutdown path.
[email protected]0815b6d2009-02-11 00:39:37278 if (!g_browser_process || g_browser_process->IsShuttingDown()) {
279 LOG(WARNING) << "Not handling WM_COPYDATA as browser is shutting down";
280 return FALSE;
281 }
[email protected]fc14cef2009-01-27 22:17:29282
[email protected]fc14cef2009-01-27 22:17:29283 // We should have enough room for the shortest command (min_message_size)
[email protected]366ffe52009-04-24 22:02:23284 // and also be a multiple of wchar_t bytes. The shortest command
285 // possible is L"START\0\0" (empty current directory and command line).
[email protected]fc14cef2009-01-27 22:17:29286 static const int min_message_size = 7;
[email protected]366ffe52009-04-24 22:02:23287 if (cds->cbData < min_message_size * sizeof(wchar_t) ||
288 cds->cbData % sizeof(wchar_t) != 0) {
[email protected]fc14cef2009-01-27 22:17:29289 LOG(WARNING) << "Invalid WM_COPYDATA, length = " << cds->cbData;
290 return TRUE;
291 }
292
293 // We split the string into 4 parts on NULLs.
[email protected]366ffe52009-04-24 22:02:23294 DCHECK(cds->lpData);
[email protected]fc14cef2009-01-27 22:17:29295 const std::wstring msg(static_cast<wchar_t*>(cds->lpData),
296 cds->cbData / sizeof(wchar_t));
297 const std::wstring::size_type first_null = msg.find_first_of(L'\0');
298 if (first_null == 0 || first_null == std::wstring::npos) {
299 // no NULL byte, don't know what to do
300 LOG(WARNING) << "Invalid WM_COPYDATA, length = " << msg.length() <<
301 ", first null = " << first_null;
302 return TRUE;
303 }
304
305 // Decode the command, which is everything until the first NULL.
306 if (msg.substr(0, first_null) == L"START") {
307 // Another instance is starting parse the command line & do what it would
308 // have done.
[email protected]8e96e502010-10-21 20:57:12309 VLOG(1) << "Handling STARTUP request from another process";
[email protected]fc14cef2009-01-27 22:17:29310 const std::wstring::size_type second_null =
311 msg.find_first_of(L'\0', first_null + 1);
312 if (second_null == std::wstring::npos ||
313 first_null == msg.length() - 1 || second_null == msg.length()) {
314 LOG(WARNING) << "Invalid format for start command, we need a string in 4 "
315 "parts separated by NULLs";
316 return TRUE;
317 }
318
319 // Get current directory.
[email protected]f805fe82010-08-03 22:47:10320 const FilePath cur_dir(msg.substr(first_null + 1,
321 second_null - first_null));
[email protected]fc14cef2009-01-27 22:17:29322
323 const std::wstring::size_type third_null =
324 msg.find_first_of(L'\0', second_null + 1);
325 if (third_null == std::wstring::npos ||
326 third_null == msg.length()) {
327 LOG(WARNING) << "Invalid format for start command, we need a string in 4 "
328 "parts separated by NULLs";
329 }
330
331 // Get command line.
332 const std::wstring cmd_line =
333 msg.substr(second_null + 1, third_null - second_null);
334
[email protected]51343d5a2009-10-26 22:39:33335 CommandLine parsed_command_line = CommandLine::FromString(cmd_line);
[email protected]fc14cef2009-01-27 22:17:29336 PrefService* prefs = g_browser_process->local_state();
337 DCHECK(prefs);
338
[email protected]6aeac8342010-10-01 20:21:18339 // Handle the --uninstall-extension startup action. This needs to done here
340 // in the process that is running with the target profile, otherwise the
341 // uninstall will fail to unload and remove all components.
342 if (parsed_command_line.HasSwitch(switches::kUninstallExtension)) {
[email protected]37b89ca2011-12-08 02:21:14343 // The uninstall extension switch can't be combined with the profile
344 // directory switch.
345 DCHECK(!parsed_command_line.HasSwitch(switches::kProfileDirectory));
346
347 Profile* profile = ProfileManager::GetLastUsedProfile();
348 if (!profile) {
349 // We should only be able to get here if the profile already exists and
350 // has been created.
351 NOTREACHED();
352 return TRUE;
353 }
354
[email protected]ccd875e72010-12-13 23:49:02355 ExtensionsStartupUtil ext_startup_util;
356 ext_startup_util.UninstallExtension(parsed_command_line, profile);
[email protected]6aeac8342010-10-01 20:21:18357 return TRUE;
358 }
359
[email protected]0303f31c2009-02-02 06:42:05360 // Run the browser startup sequence again, with the command line of the
361 // signalling process.
[email protected]37b89ca2011-12-08 02:21:14362 BrowserInit::ProcessCommandLineAlreadyRunning(parsed_command_line, cur_dir);
[email protected]fc14cef2009-01-27 22:17:29363 return TRUE;
364 }
365 return TRUE;
366}
367
[email protected]e3ce40a2012-01-31 03:03:03368LRESULT ProcessSingleton::WndProc(HWND hwnd, UINT message,
369 WPARAM wparam, LPARAM lparam) {
[email protected]fc14cef2009-01-27 22:17:29370 switch (message) {
371 case WM_COPYDATA:
372 return OnCopyData(reinterpret_cast<HWND>(wparam),
373 reinterpret_cast<COPYDATASTRUCT*>(lparam));
374 default:
375 break;
376 }
377
378 return ::DefWindowProc(hwnd, message, wparam, lparam);
379}