ozone: evdev: Sync caps lock LED state to evdev
[chromium-blink-merge.git] / chrome / browser / process_singleton_win.cc
blob63a0c48fe990fecb472cd33787b2ab50ef3c8209
1 // Copyright (c) 2012 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 "chrome/browser/process_singleton.h"
7 #include <shellapi.h>
9 #include "base/base_paths.h"
10 #include "base/bind.h"
11 #include "base/command_line.h"
12 #include "base/files/file_path.h"
13 #include "base/process/kill.h"
14 #include "base/process/process_info.h"
15 #include "base/strings/string_number_conversions.h"
16 #include "base/strings/stringprintf.h"
17 #include "base/strings/utf_string_conversions.h"
18 #include "base/time/time.h"
19 #include "base/win/metro.h"
20 #include "base/win/registry.h"
21 #include "base/win/scoped_handle.h"
22 #include "base/win/windows_version.h"
23 #include "chrome/browser/browser_process.h"
24 #include "chrome/browser/browser_process_platform_part.h"
25 #include "chrome/browser/chrome_process_finder_win.h"
26 #include "chrome/browser/metro_utils/metro_chrome_win.h"
27 #include "chrome/browser/shell_integration.h"
28 #include "chrome/browser/ui/simple_message_box.h"
29 #include "chrome/common/chrome_constants.h"
30 #include "chrome/common/chrome_paths.h"
31 #include "chrome/common/chrome_paths_internal.h"
32 #include "chrome/common/chrome_switches.h"
33 #include "chrome/grit/chromium_strings.h"
34 #include "chrome/installer/util/wmi.h"
35 #include "content/public/common/result_codes.h"
36 #include "net/base/escape.h"
37 #include "ui/base/l10n/l10n_util.h"
38 #include "ui/gfx/win/hwnd_util.h"
40 namespace {
42 const char kLockfile[] = "lockfile";
44 const int kMetroChromeActivationTimeoutMs = 3000;
46 // A helper class that acquires the given |mutex| while the AutoLockMutex is in
47 // scope.
48 class AutoLockMutex {
49 public:
50 explicit AutoLockMutex(HANDLE mutex) : mutex_(mutex) {
51 DWORD result = ::WaitForSingleObject(mutex_, INFINITE);
52 DPCHECK(result == WAIT_OBJECT_0) << "Result = " << result;
55 ~AutoLockMutex() {
56 BOOL released = ::ReleaseMutex(mutex_);
57 DPCHECK(released);
60 private:
61 HANDLE mutex_;
62 DISALLOW_COPY_AND_ASSIGN(AutoLockMutex);
65 // A helper class that releases the given |mutex| while the AutoUnlockMutex is
66 // in scope and immediately re-acquires it when going out of scope.
67 class AutoUnlockMutex {
68 public:
69 explicit AutoUnlockMutex(HANDLE mutex) : mutex_(mutex) {
70 BOOL released = ::ReleaseMutex(mutex_);
71 DPCHECK(released);
74 ~AutoUnlockMutex() {
75 DWORD result = ::WaitForSingleObject(mutex_, INFINITE);
76 DPCHECK(result == WAIT_OBJECT_0) << "Result = " << result;
79 private:
80 HANDLE mutex_;
81 DISALLOW_COPY_AND_ASSIGN(AutoUnlockMutex);
84 // Checks the visibility of the enumerated window and signals once a visible
85 // window has been found.
86 BOOL CALLBACK BrowserWindowEnumeration(HWND window, LPARAM param) {
87 bool* result = reinterpret_cast<bool*>(param);
88 *result = ::IsWindowVisible(window) != 0;
89 // Stops enumeration if a visible window has been found.
90 return !*result;
93 bool ParseCommandLine(const COPYDATASTRUCT* cds,
94 base::CommandLine* parsed_command_line,
95 base::FilePath* current_directory) {
96 // We should have enough room for the shortest command (min_message_size)
97 // and also be a multiple of wchar_t bytes. The shortest command
98 // possible is L"START\0\0" (empty current directory and command line).
99 static const int min_message_size = 7;
100 if (cds->cbData < min_message_size * sizeof(wchar_t) ||
101 cds->cbData % sizeof(wchar_t) != 0) {
102 LOG(WARNING) << "Invalid WM_COPYDATA, length = " << cds->cbData;
103 return false;
106 // We split the string into 4 parts on NULLs.
107 DCHECK(cds->lpData);
108 const std::wstring msg(static_cast<wchar_t*>(cds->lpData),
109 cds->cbData / sizeof(wchar_t));
110 const std::wstring::size_type first_null = msg.find_first_of(L'\0');
111 if (first_null == 0 || first_null == std::wstring::npos) {
112 // no NULL byte, don't know what to do
113 LOG(WARNING) << "Invalid WM_COPYDATA, length = " << msg.length() <<
114 ", first null = " << first_null;
115 return false;
118 // Decode the command, which is everything until the first NULL.
119 if (msg.substr(0, first_null) == L"START") {
120 // Another instance is starting parse the command line & do what it would
121 // have done.
122 VLOG(1) << "Handling STARTUP request from another process";
123 const std::wstring::size_type second_null =
124 msg.find_first_of(L'\0', first_null + 1);
125 if (second_null == std::wstring::npos ||
126 first_null == msg.length() - 1 || second_null == msg.length()) {
127 LOG(WARNING) << "Invalid format for start command, we need a string in 4 "
128 "parts separated by NULLs";
129 return false;
132 // Get current directory.
133 *current_directory = base::FilePath(msg.substr(first_null + 1,
134 second_null - first_null));
136 const std::wstring::size_type third_null =
137 msg.find_first_of(L'\0', second_null + 1);
138 if (third_null == std::wstring::npos ||
139 third_null == msg.length()) {
140 LOG(WARNING) << "Invalid format for start command, we need a string in 4 "
141 "parts separated by NULLs";
144 // Get command line.
145 const std::wstring cmd_line =
146 msg.substr(second_null + 1, third_null - second_null);
147 *parsed_command_line = base::CommandLine::FromString(cmd_line);
148 return true;
150 return false;
153 bool ProcessLaunchNotification(
154 const ProcessSingleton::NotificationCallback& notification_callback,
155 UINT message,
156 WPARAM wparam,
157 LPARAM lparam,
158 LRESULT* result) {
159 if (message != WM_COPYDATA)
160 return false;
162 // Handle the WM_COPYDATA message from another process.
163 const COPYDATASTRUCT* cds = reinterpret_cast<COPYDATASTRUCT*>(lparam);
165 base::CommandLine parsed_command_line(base::CommandLine::NO_PROGRAM);
166 base::FilePath current_directory;
167 if (!ParseCommandLine(cds, &parsed_command_line, &current_directory)) {
168 *result = TRUE;
169 return true;
172 *result = notification_callback.Run(parsed_command_line, current_directory) ?
173 TRUE : FALSE;
174 return true;
177 // Returns true if Chrome needs to be relaunched into Windows 8 immersive mode.
178 // Following conditions apply:-
179 // 1. Windows 8 or greater.
180 // 2. Not in Windows 8 immersive mode.
181 // 3. Chrome is default browser.
182 // 4. Process integrity level is not high.
183 // 5. The profile data directory is the default directory.
184 // 6. Last used mode was immersive/machine is a tablet.
185 // TODO(ananta)
186 // Move this function to a common place as the Windows 8 delegate_execute
187 // handler can possibly use this.
188 bool ShouldLaunchInWindows8ImmersiveMode(const base::FilePath& user_data_dir) {
189 // Returning false from this function doesn't mean we don't launch immersive
190 // mode in Aura. This function is specifically called in case when we need
191 // to relaunch desktop launched chrome into immersive mode through 'relaunch'
192 // menu. In case of Aura, we will use delegate_execute to do the relaunch.
193 return false;
196 } // namespace
198 // Microsoft's Softricity virtualization breaks the sandbox processes.
199 // So, if we detect the Softricity DLL we use WMI Win32_Process.Create to
200 // break out of the virtualization environment.
201 // http://code.google.com/p/chromium/issues/detail?id=43650
202 bool ProcessSingleton::EscapeVirtualization(
203 const base::FilePath& user_data_dir) {
204 if (::GetModuleHandle(L"sftldr_wow64.dll") ||
205 ::GetModuleHandle(L"sftldr.dll")) {
206 int process_id;
207 if (!installer::WMIProcess::Launch(::GetCommandLineW(), &process_id))
208 return false;
209 is_virtualized_ = true;
210 // The new window was spawned from WMI, and won't be in the foreground.
211 // So, first we sleep while the new chrome.exe instance starts (because
212 // WaitForInputIdle doesn't work here). Then we poll for up to two more
213 // seconds and make the window foreground if we find it (or we give up).
214 HWND hwnd = 0;
215 ::Sleep(90);
216 for (int tries = 200; tries; --tries) {
217 hwnd = chrome::FindRunningChromeWindow(user_data_dir);
218 if (hwnd) {
219 ::SetForegroundWindow(hwnd);
220 break;
222 ::Sleep(10);
224 return true;
226 return false;
229 ProcessSingleton::ProcessSingleton(
230 const base::FilePath& user_data_dir,
231 const NotificationCallback& notification_callback)
232 : notification_callback_(notification_callback),
233 is_virtualized_(false), lock_file_(INVALID_HANDLE_VALUE),
234 user_data_dir_(user_data_dir) {
237 ProcessSingleton::~ProcessSingleton() {
238 if (lock_file_ != INVALID_HANDLE_VALUE)
239 ::CloseHandle(lock_file_);
242 // Code roughly based on Mozilla.
243 ProcessSingleton::NotifyResult ProcessSingleton::NotifyOtherProcess() {
244 if (is_virtualized_)
245 return PROCESS_NOTIFIED; // We already spawned the process in this case.
246 if (lock_file_ == INVALID_HANDLE_VALUE && !remote_window_) {
247 return LOCK_ERROR;
248 } else if (!remote_window_) {
249 return PROCESS_NONE;
252 switch (chrome::AttemptToNotifyRunningChrome(remote_window_, false)) {
253 case chrome::NOTIFY_SUCCESS:
254 return PROCESS_NOTIFIED;
255 case chrome::NOTIFY_FAILED:
256 remote_window_ = NULL;
257 return PROCESS_NONE;
258 case chrome::NOTIFY_WINDOW_HUNG:
259 remote_window_ = NULL;
260 break;
263 DWORD process_id = 0;
264 DWORD thread_id = ::GetWindowThreadProcessId(remote_window_, &process_id);
265 if (!thread_id || !process_id) {
266 remote_window_ = NULL;
267 return PROCESS_NONE;
270 // 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));
276 // If there is a visible browser window, ask the user before killing it.
277 if (visible_window &&
278 chrome::ShowMessageBox(
279 NULL,
280 l10n_util::GetStringUTF16(IDS_PRODUCT_NAME),
281 l10n_util::GetStringUTF16(IDS_BROWSER_HUNGBROWSER_MESSAGE),
282 chrome::MESSAGE_BOX_TYPE_QUESTION) == chrome::MESSAGE_BOX_RESULT_NO) {
283 // The user denied. Quit silently.
284 return PROCESS_NOTIFIED;
287 // Time to take action. Kill the browser process.
288 base::KillProcessById(process_id, content::RESULT_CODE_HUNG, true);
289 remote_window_ = NULL;
290 return PROCESS_NONE;
293 ProcessSingleton::NotifyResult
294 ProcessSingleton::NotifyOtherProcessOrCreate() {
295 ProcessSingleton::NotifyResult result = PROCESS_NONE;
296 if (!Create()) {
297 result = NotifyOtherProcess();
298 if (result == PROCESS_NONE)
299 result = PROFILE_IN_USE;
300 } else {
301 g_browser_process->platform_part()->PlatformSpecificCommandLineProcessing(
302 *base::CommandLine::ForCurrentProcess());
304 return result;
307 // Look for a Chrome instance that uses the same profile directory. If there
308 // isn't one, create a message window with its title set to the profile
309 // directory path.
310 bool ProcessSingleton::Create() {
311 static const wchar_t kMutexName[] = L"Local\\ChromeProcessSingletonStartup!";
312 static const wchar_t kMetroActivationEventName[] =
313 L"Local\\ChromeProcessSingletonStartupMetroActivation!";
315 remote_window_ = chrome::FindRunningChromeWindow(user_data_dir_);
316 if (!remote_window_ && !EscapeVirtualization(user_data_dir_)) {
317 // Make sure we will be the one and only process creating the window.
318 // We use a named Mutex since we are protecting against multi-process
319 // access. As documented, it's clearer to NOT request ownership on creation
320 // since it isn't guaranteed we will get it. It is better to create it
321 // without ownership and explicitly get the ownership afterward.
322 base::win::ScopedHandle only_me(::CreateMutex(NULL, FALSE, kMutexName));
323 if (!only_me.IsValid()) {
324 DPLOG(FATAL) << "CreateMutex failed";
325 return false;
328 AutoLockMutex auto_lock_only_me(only_me.Get());
330 // We now own the mutex so we are the only process that can create the
331 // window at this time, but we must still check if someone created it
332 // between the time where we looked for it above and the time the mutex
333 // was given to us.
334 remote_window_ = chrome::FindRunningChromeWindow(user_data_dir_);
337 // In Win8+, a new Chrome process launched in Desktop mode may need to be
338 // transmuted into Metro Chrome (see ShouldLaunchInWindows8ImmersiveMode for
339 // heuristics). To accomplish this, the current Chrome activates Metro
340 // Chrome, releases the startup mutex, and waits for metro Chrome to take
341 // the singleton. From that point onward, the command line for this Chrome
342 // process will be sent to Metro Chrome by the usual channels.
343 if (!remote_window_ && base::win::GetVersion() >= base::win::VERSION_WIN8 &&
344 !base::win::IsMetroProcess()) {
345 // |metro_activation_event| is created right before activating a Metro
346 // Chrome (note that there can only be one Metro Chrome process; by OS
347 // design); all following Desktop processes will then wait for this event
348 // to be signaled by Metro Chrome which will do so as soon as it grabs
349 // this singleton (should any of the waiting processes timeout waiting for
350 // the signal they will try to grab the singleton for themselves which
351 // will result in a forced Desktop Chrome launch in the worst case).
352 base::win::ScopedHandle metro_activation_event(
353 ::OpenEvent(SYNCHRONIZE, FALSE, kMetroActivationEventName));
354 if (!metro_activation_event.IsValid() &&
355 ShouldLaunchInWindows8ImmersiveMode(user_data_dir_)) {
356 // No Metro activation is under way, but the desire is to launch in
357 // Metro mode: activate and rendez-vous with the activated process.
358 metro_activation_event.Set(
359 ::CreateEvent(NULL, TRUE, FALSE, kMetroActivationEventName));
360 if (!chrome::ActivateMetroChrome()) {
361 // Failed to launch immersive Chrome, default to launching on Desktop.
362 LOG(ERROR) << "Failed to launch immersive chrome";
363 metro_activation_event.Close();
367 if (metro_activation_event.IsValid()) {
368 // Release |only_me| (to let Metro Chrome grab this singleton) and wait
369 // until the event is signaled (i.e. Metro Chrome was successfully
370 // activated). Ignore timeout waiting for |metro_activation_event|.
372 AutoUnlockMutex auto_unlock_only_me(only_me.Get());
374 DWORD result = ::WaitForSingleObject(metro_activation_event.Get(),
375 kMetroChromeActivationTimeoutMs);
376 DPCHECK(result == WAIT_OBJECT_0 || result == WAIT_TIMEOUT)
377 << "Result = " << result;
380 // Check if this singleton was successfully grabbed by another process
381 // (hopefully Metro Chrome). Failing to do so, this process will grab
382 // the singleton and launch in Desktop mode.
383 remote_window_ = chrome::FindRunningChromeWindow(user_data_dir_);
387 if (!remote_window_) {
388 // We have to make sure there is no Chrome instance running on another
389 // machine that uses the same profile.
390 base::FilePath lock_file_path = user_data_dir_.AppendASCII(kLockfile);
391 lock_file_ = ::CreateFile(lock_file_path.value().c_str(),
392 GENERIC_WRITE,
393 FILE_SHARE_READ,
394 NULL,
395 CREATE_ALWAYS,
396 FILE_ATTRIBUTE_NORMAL |
397 FILE_FLAG_DELETE_ON_CLOSE,
398 NULL);
399 DWORD error = ::GetLastError();
400 LOG_IF(WARNING, lock_file_ != INVALID_HANDLE_VALUE &&
401 error == ERROR_ALREADY_EXISTS) << "Lock file exists but is writable.";
402 LOG_IF(ERROR, lock_file_ == INVALID_HANDLE_VALUE)
403 << "Lock file can not be created! Error code: " << error;
405 if (lock_file_ != INVALID_HANDLE_VALUE) {
406 // Set the window's title to the path of our user data directory so
407 // other Chrome instances can decide if they should forward to us.
408 bool result = window_.CreateNamed(
409 base::Bind(&ProcessLaunchNotification, notification_callback_),
410 user_data_dir_.value());
411 CHECK(result && window_.hwnd());
414 if (base::win::GetVersion() >= base::win::VERSION_WIN8) {
415 // Make sure no one is still waiting on Metro activation whether it
416 // succeeded (i.e., this is the Metro process) or failed.
417 base::win::ScopedHandle metro_activation_event(
418 ::OpenEvent(EVENT_MODIFY_STATE, FALSE, kMetroActivationEventName));
419 if (metro_activation_event.IsValid())
420 ::SetEvent(metro_activation_event.Get());
425 return window_.hwnd() != NULL;
428 void ProcessSingleton::Cleanup() {