blob: fc55aac7a49da6a507b46cfd219f835ba3b4ae93 [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]edf04b512012-02-23 09:47:4360bool ParseCommandLine(const COPYDATASTRUCT* cds,
61 CommandLine* parsed_command_line,
62 FilePath* current_directory) {
63 // We should have enough room for the shortest command (min_message_size)
64 // and also be a multiple of wchar_t bytes. The shortest command
65 // possible is L"START\0\0" (empty current directory and command line).
66 static const int min_message_size = 7;
67 if (cds->cbData < min_message_size * sizeof(wchar_t) ||
68 cds->cbData % sizeof(wchar_t) != 0) {
69 LOG(WARNING) << "Invalid WM_COPYDATA, length = " << cds->cbData;
70 return false;
71 }
72
73 // We split the string into 4 parts on NULLs.
74 DCHECK(cds->lpData);
75 const std::wstring msg(static_cast<wchar_t*>(cds->lpData),
76 cds->cbData / sizeof(wchar_t));
77 const std::wstring::size_type first_null = msg.find_first_of(L'\0');
78 if (first_null == 0 || first_null == std::wstring::npos) {
79 // no NULL byte, don't know what to do
80 LOG(WARNING) << "Invalid WM_COPYDATA, length = " << msg.length() <<
81 ", first null = " << first_null;
82 return false;
83 }
84
85 // Decode the command, which is everything until the first NULL.
86 if (msg.substr(0, first_null) == L"START") {
87 // Another instance is starting parse the command line & do what it would
88 // have done.
89 VLOG(1) << "Handling STARTUP request from another process";
90 const std::wstring::size_type second_null =
91 msg.find_first_of(L'\0', first_null + 1);
92 if (second_null == std::wstring::npos ||
93 first_null == msg.length() - 1 || second_null == msg.length()) {
94 LOG(WARNING) << "Invalid format for start command, we need a string in 4 "
95 "parts separated by NULLs";
96 return false;
97 }
98
99 // Get current directory.
100 *current_directory = FilePath(msg.substr(first_null + 1,
101 second_null - first_null));
102
103 const std::wstring::size_type third_null =
104 msg.find_first_of(L'\0', second_null + 1);
105 if (third_null == std::wstring::npos ||
106 third_null == msg.length()) {
107 LOG(WARNING) << "Invalid format for start command, we need a string in 4 "
108 "parts separated by NULLs";
109 }
110
111 // Get command line.
112 const std::wstring cmd_line =
113 msg.substr(second_null + 1, third_null - second_null);
114 *parsed_command_line = CommandLine::FromString(cmd_line);
115 return true;
116 }
117 return false;
118}
119
[email protected]fc14cef2009-01-27 22:17:29120} // namespace
121
[email protected]0a194552011-09-14 17:53:35122// Microsoft's Softricity virtualization breaks the sandbox processes.
123// So, if we detect the Softricity DLL we use WMI Win32_Process.Create to
124// break out of the virtualization environment.
125// http://code.google.com/p/chromium/issues/detail?id=43650
126bool ProcessSingleton::EscapeVirtualization(const FilePath& user_data_dir) {
127 if (::GetModuleHandle(L"sftldr_wow64.dll") ||
128 ::GetModuleHandle(L"sftldr.dll")) {
129 int process_id;
130 if (!installer::WMIProcess::Launch(GetCommandLineW(), &process_id))
131 return false;
132 is_virtualized_ = true;
133 // The new window was spawned from WMI, and won't be in the foreground.
134 // So, first we sleep while the new chrome.exe instance starts (because
135 // WaitForInputIdle doesn't work here). Then we poll for up to two more
136 // seconds and make the window foreground if we find it (or we give up).
137 HWND hwnd = 0;
138 ::Sleep(90);
139 for (int tries = 200; tries; --tries) {
140 hwnd = FindWindowEx(HWND_MESSAGE, NULL, chrome::kMessageWindowClass,
141 user_data_dir.value().c_str());
142 if (hwnd) {
143 ::SetForegroundWindow(hwnd);
144 break;
145 }
146 ::Sleep(10);
147 }
148 return true;
149 }
150 return false;
151}
152
[email protected]f891fb32009-04-08 00:20:32153// Look for a Chrome instance that uses the same profile directory.
[email protected]9a182832012-02-10 18:45:58154// If there isn't one, create a message window with its title set to
155// the profile directory path.
[email protected]7c47ae3e2009-02-18 00:34:21156ProcessSingleton::ProcessSingleton(const FilePath& user_data_dir)
[email protected]0a194552011-09-14 17:53:35157 : window_(NULL), locked_(false), foreground_window_(NULL),
158 is_virtualized_(false) {
[email protected]bbef41f02010-03-04 16:16:19159 remote_window_ = FindWindowEx(HWND_MESSAGE, NULL,
160 chrome::kMessageWindowClass,
[email protected]8a205c02011-02-04 20:41:33161 user_data_dir.value().c_str());
[email protected]0a194552011-09-14 17:53:35162 if (!remote_window_ && !EscapeVirtualization(user_data_dir)) {
[email protected]bbef41f02010-03-04 16:16:19163 // Make sure we will be the one and only process creating the window.
164 // We use a named Mutex since we are protecting against multi-process
165 // access. As documented, it's clearer to NOT request ownership on creation
166 // since it isn't guaranteed we will get it. It is better to create it
167 // without ownership and explicitly get the ownership afterward.
[email protected]e132804b2010-12-22 12:48:25168 std::wstring mutex_name(L"Local\\ChromeProcessSingletonStartup!");
[email protected]b90d7e802011-01-09 16:32:20169 base::win::ScopedHandle only_me(
170 CreateMutex(NULL, FALSE, mutex_name.c_str()));
[email protected]bbef41f02010-03-04 16:16:19171 DCHECK(only_me.Get() != NULL) << "GetLastError = " << GetLastError();
172
173 // This is how we acquire the mutex (as opposed to the initial ownership).
174 DWORD result = WaitForSingleObject(only_me, INFINITE);
175 DCHECK(result == WAIT_OBJECT_0) << "Result = " << result <<
176 "GetLastError = " << GetLastError();
177
178 // We now own the mutex so we are the only process that can create the
179 // window at this time, but we must still check if someone created it
180 // between the time where we looked for it above and the time the mutex
181 // was given to us.
182 remote_window_ = FindWindowEx(HWND_MESSAGE, NULL,
183 chrome::kMessageWindowClass,
[email protected]8a205c02011-02-04 20:41:33184 user_data_dir.value().c_str());
[email protected]9a182832012-02-10 18:45:58185 if (!remote_window_) {
186 HINSTANCE hinst = base::GetModuleFromAddress(&ThunkWndProc);
187
188 WNDCLASSEX wc = {0};
189 wc.cbSize = sizeof(wc);
190 wc.lpfnWndProc = base::win::WrappedWindowProc<ThunkWndProc>;
191 wc.hInstance = hinst;
192 wc.lpszClassName = chrome::kMessageWindowClass;
193 ATOM clazz = ::RegisterClassEx(&wc);
194 DCHECK(clazz);
195
196 FilePath user_data_dir;
197 PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);
198
199 // Set the window's title to the path of our user data directory so other
200 // Chrome instances can decide if they should forward to us or not.
201 window_ = ::CreateWindow(MAKEINTATOM(clazz),
202 user_data_dir.value().c_str(),
203 0, 0, 0, 0, 0, HWND_MESSAGE, 0, hinst, this);
204 CHECK(window_);
205 }
[email protected]bbef41f02010-03-04 16:16:19206 BOOL success = ReleaseMutex(only_me);
207 DCHECK(success) << "GetLastError = " << GetLastError();
208 }
[email protected]fc14cef2009-01-27 22:17:29209}
210
[email protected]7c47ae3e2009-02-18 00:34:21211ProcessSingleton::~ProcessSingleton() {
[email protected]9a182832012-02-10 18:45:58212 Cleanup();
[email protected]fc14cef2009-01-27 22:17:29213}
214
[email protected]9f20a6d02009-08-21 01:18:37215ProcessSingleton::NotifyResult ProcessSingleton::NotifyOtherProcess() {
[email protected]0a194552011-09-14 17:53:35216 if (is_virtualized_)
217 return PROCESS_NOTIFIED; // We already spawned the process in this case.
218 else if (!remote_window_)
[email protected]9f20a6d02009-08-21 01:18:37219 return PROCESS_NONE;
[email protected]fc14cef2009-01-27 22:17:29220
221 // Found another window, send our command line to it
222 // format is "START\0<<<current directory>>>\0<<<commandline>>>".
223 std::wstring to_send(L"START\0", 6); // want the NULL in the string.
[email protected]b9696482010-11-30 23:56:18224 FilePath cur_dir;
[email protected]fc14cef2009-01-27 22:17:29225 if (!PathService::Get(base::DIR_CURRENT, &cur_dir))
[email protected]9f20a6d02009-08-21 01:18:37226 return PROCESS_NONE;
[email protected]b9696482010-11-30 23:56:18227 to_send.append(cur_dir.value());
[email protected]fc14cef2009-01-27 22:17:29228 to_send.append(L"\0", 1); // Null separator.
229 to_send.append(GetCommandLineW());
230 to_send.append(L"\0", 1); // Null separator.
231
232 // Allow the current running browser window making itself the foreground
233 // window (otherwise it will just flash in the taskbar).
234 DWORD process_id = 0;
235 DWORD thread_id = GetWindowThreadProcessId(remote_window_, &process_id);
[email protected]0815b6d2009-02-11 00:39:37236 // It is possible that the process owning this window may have died by now.
237 if (!thread_id || !process_id) {
238 remote_window_ = NULL;
[email protected]9f20a6d02009-08-21 01:18:37239 return PROCESS_NONE;
[email protected]0815b6d2009-02-11 00:39:37240 }
241
[email protected]fc14cef2009-01-27 22:17:29242 AllowSetForegroundWindow(process_id);
243
[email protected]fc14cef2009-01-27 22:17:29244 COPYDATASTRUCT cds;
245 cds.dwData = 0;
246 cds.cbData = static_cast<DWORD>((to_send.length() + 1) * sizeof(wchar_t));
247 cds.lpData = const_cast<wchar_t*>(to_send.c_str());
248 DWORD_PTR result = 0;
249 if (SendMessageTimeout(remote_window_,
250 WM_COPYDATA,
251 NULL,
252 reinterpret_cast<LPARAM>(&cds),
253 SMTO_ABORTIFHUNG,
[email protected]8b08cbd2009-08-04 05:34:19254 kTimeoutInSeconds * 1000,
[email protected]fc14cef2009-01-27 22:17:29255 &result)) {
[email protected]0815b6d2009-02-11 00:39:37256 // It is possible that the process owning this window may have died by now.
257 if (!result) {
258 remote_window_ = NULL;
[email protected]9f20a6d02009-08-21 01:18:37259 return PROCESS_NONE;
[email protected]0815b6d2009-02-11 00:39:37260 }
[email protected]9f20a6d02009-08-21 01:18:37261 return PROCESS_NOTIFIED;
[email protected]fc14cef2009-01-27 22:17:29262 }
263
[email protected]0815b6d2009-02-11 00:39:37264 // It is possible that the process owning this window may have died by now.
265 if (!IsWindow(remote_window_)) {
266 remote_window_ = NULL;
[email protected]9f20a6d02009-08-21 01:18:37267 return PROCESS_NONE;
[email protected]0815b6d2009-02-11 00:39:37268 }
269
[email protected]fc14cef2009-01-27 22:17:29270 // The window is hung. Scan for every window to find a visible one.
271 bool visible_window = false;
272 EnumThreadWindows(thread_id,
273 &BrowserWindowEnumeration,
274 reinterpret_cast<LPARAM>(&visible_window));
275
276 // If there is a visible browser window, ask the user before killing it.
277 if (visible_window) {
[email protected]80772ed2011-08-09 21:11:38278 string16 text = l10n_util::GetStringUTF16(IDS_BROWSER_HUNGBROWSER_MESSAGE);
279 string16 caption = l10n_util::GetStringUTF16(IDS_PRODUCT_NAME);
280 if (!browser::ShowYesNoBox(NULL, caption, text)) {
[email protected]fc14cef2009-01-27 22:17:29281 // The user denied. Quit silently.
[email protected]9f20a6d02009-08-21 01:18:37282 return PROCESS_NOTIFIED;
[email protected]fc14cef2009-01-27 22:17:29283 }
284 }
285
286 // Time to take action. Kill the browser process.
[email protected]1fcfb202011-07-19 19:53:14287 base::KillProcessById(process_id, content::RESULT_CODE_HUNG, true);
[email protected]fc14cef2009-01-27 22:17:29288 remote_window_ = NULL;
[email protected]9f20a6d02009-08-21 01:18:37289 return PROCESS_NONE;
[email protected]fc14cef2009-01-27 22:17:29290}
291
[email protected]4a44bc32010-05-28 22:22:44292ProcessSingleton::NotifyResult ProcessSingleton::NotifyOtherProcessOrCreate() {
293 NotifyResult result = NotifyOtherProcess();
294 if (result != PROCESS_NONE)
295 return result;
[email protected]9a182832012-02-10 18:45:58296 return window_ ? PROCESS_NONE : PROFILE_IN_USE;
[email protected]4a44bc32010-05-28 22:22:44297}
298
[email protected]9a182832012-02-10 18:45:58299// On Windows, there is no need to call Create() since the message
300// window is created in the constructor but to avoid having more
301// platform specific code in browser_main.cc we tolerate calls to
302// Create(), which will do nothing.
[email protected]4dd42242010-04-07 02:21:15303bool ProcessSingleton::Create() {
[email protected]fc14cef2009-01-27 22:17:29304 DCHECK(!remote_window_);
[email protected]9a182832012-02-10 18:45:58305 return window_ != NULL;
[email protected]fc14cef2009-01-27 22:17:29306}
307
[email protected]9f20a6d02009-08-21 01:18:37308void ProcessSingleton::Cleanup() {
[email protected]9a182832012-02-10 18:45:58309 // Window classes registered by DLLs are not cleaned up automatically on
310 // process exit, so we must unregister at the earliest chance possible.
311 // During the fast shutdown sequence, ProcessSingleton::Cleanup() is
312 // called if our process was the first to start. Therefore we try cleaning
313 // up here, and again in the destructor if needed to catch as many cases
314 // as possible.
315 if (window_) {
316 ::DestroyWindow(window_);
317 ::UnregisterClass(chrome::kMessageWindowClass,
318 base::GetModuleFromAddress(&ThunkWndProc));
319 window_ = NULL;
320 }
[email protected]9f20a6d02009-08-21 01:18:37321}
322
[email protected]7c47ae3e2009-02-18 00:34:21323LRESULT ProcessSingleton::OnCopyData(HWND hwnd, const COPYDATASTRUCT* cds) {
[email protected]175a7a22009-05-03 15:57:53324 // If locked, it means we are not ready to process this message because
[email protected]afd20c022010-06-10 00:48:20325 // we are probably in a first run critical phase.
[email protected]175a7a22009-05-03 15:57:53326 if (locked_) {
[email protected]95259c62011-10-25 23:23:53327#if defined(USE_AURA)
328 NOTIMPLEMENTED();
329#else
[email protected]175a7a22009-05-03 15:57:53330 // Attempt to place ourselves in the foreground / flash the task bar.
[email protected]edf04b512012-02-23 09:47:43331 if (foreground_window_ != NULL && IsWindow(foreground_window_)) {
[email protected]175a7a22009-05-03 15:57:53332 SetForegroundWindow(foreground_window_);
[email protected]edf04b512012-02-23 09:47:43333 } else {
334 // Read the command line and store it. It will be replayed when the
335 // ProcessSingleton becomes unlocked.
336 CommandLine parsed_command_line(CommandLine::NO_PROGRAM);
337 FilePath current_directory;
338 if (ParseCommandLine(cds, &parsed_command_line, &current_directory))
339 saved_startup_messages_.push_back(
340 std::make_pair(parsed_command_line.argv(), current_directory));
341 }
[email protected]95259c62011-10-25 23:23:53342#endif
[email protected]175a7a22009-05-03 15:57:53343 return TRUE;
344 }
345
[email protected]fc14cef2009-01-27 22:17:29346 // Ignore the request if the browser process is already in shutdown path.
[email protected]0815b6d2009-02-11 00:39:37347 if (!g_browser_process || g_browser_process->IsShuttingDown()) {
348 LOG(WARNING) << "Not handling WM_COPYDATA as browser is shutting down";
349 return FALSE;
350 }
[email protected]fc14cef2009-01-27 22:17:29351
[email protected]edf04b512012-02-23 09:47:43352 CommandLine parsed_command_line(CommandLine::NO_PROGRAM);
353 FilePath current_directory;
354 if (!ParseCommandLine(cds, &parsed_command_line, &current_directory))
[email protected]fc14cef2009-01-27 22:17:29355 return TRUE;
[email protected]edf04b512012-02-23 09:47:43356 ProcessCommandLine(parsed_command_line, current_directory);
[email protected]fc14cef2009-01-27 22:17:29357 return TRUE;
358}
359
[email protected]e3ce40a2012-01-31 03:03:03360LRESULT ProcessSingleton::WndProc(HWND hwnd, UINT message,
361 WPARAM wparam, LPARAM lparam) {
[email protected]fc14cef2009-01-27 22:17:29362 switch (message) {
363 case WM_COPYDATA:
364 return OnCopyData(reinterpret_cast<HWND>(wparam),
365 reinterpret_cast<COPYDATASTRUCT*>(lparam));
366 default:
367 break;
368 }
369
370 return ::DefWindowProc(hwnd, message, wparam, lparam);
371}
[email protected]edf04b512012-02-23 09:47:43372
373void ProcessSingleton::ProcessCommandLine(const CommandLine& command_line,
374 const FilePath& current_directory) {
375 PrefService* prefs = g_browser_process->local_state();
376 DCHECK(prefs);
377
378 // Handle the --uninstall-extension startup action. This needs to done here
379 // in the process that is running with the target profile, otherwise the
380 // uninstall will fail to unload and remove all components.
381 if (command_line.HasSwitch(switches::kUninstallExtension)) {
382 // The uninstall extension switch can't be combined with the profile
383 // directory switch.
384 DCHECK(!command_line.HasSwitch(switches::kProfileDirectory));
385
386 Profile* profile = ProfileManager::GetLastUsedProfile();
387 if (!profile) {
388 // We should only be able to get here if the profile already exists and
389 // has been created.
390 NOTREACHED();
391 return;
392 }
393
394 ExtensionsStartupUtil ext_startup_util;
395 ext_startup_util.UninstallExtension(command_line, profile);
396 return;
397 }
398
399 // Run the browser startup sequence again, with the command line of the
400 // signalling process.
401 BrowserInit::ProcessCommandLineAlreadyRunning(command_line,
402 current_directory);
403}