Add ICU message format support
[chromium-blink-merge.git] / chrome / app / client_util.cc
blobb01d86e25dd19f320897c8a0df0382de60300840
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 <windows.h>
6 #include <shlwapi.h>
8 #include "base/base_paths.h"
9 #include "base/command_line.h"
10 #include "base/compiler_specific.h"
11 #include "base/environment.h"
12 #include "base/file_version_info.h"
13 #include "base/lazy_instance.h"
14 #include "base/logging.h"
15 #include "base/memory/scoped_ptr.h"
16 #include "base/path_service.h"
17 #include "base/strings/string16.h"
18 #include "base/strings/string_util.h"
19 #include "base/strings/stringprintf.h"
20 #include "base/strings/utf_string_conversions.h"
21 #include "base/trace_event/trace_event.h"
22 #include "base/version.h"
23 #include "base/win/scoped_handle.h"
24 #include "base/win/windows_version.h"
25 #include "chrome/app/chrome_crash_reporter_client.h"
26 #include "chrome/app/chrome_watcher_client_win.h"
27 #include "chrome/app/chrome_watcher_command_line_win.h"
28 #include "chrome/app/client_util.h"
29 #include "chrome/app/image_pre_reader_win.h"
30 #include "chrome/app/kasko_client.h"
31 #include "chrome/chrome_watcher/chrome_watcher_main_api.h"
32 #include "chrome/common/chrome_constants.h"
33 #include "chrome/common/chrome_paths.h"
34 #include "chrome/common/chrome_result_codes.h"
35 #include "chrome/common/chrome_switches.h"
36 #include "chrome/common/env_vars.h"
37 #include "chrome/installer/util/google_update_constants.h"
38 #include "chrome/installer/util/google_update_settings.h"
39 #include "chrome/installer/util/install_util.h"
40 #include "chrome/installer/util/util_constants.h"
41 #include "components/crash/app/breakpad_win.h"
42 #include "components/crash/app/crash_reporter_client.h"
43 #include "components/metrics/client_info.h"
44 #include "content/public/app/startup_helper_win.h"
45 #include "sandbox/win/src/sandbox.h"
47 namespace {
48 // The entry point signature of chrome.dll.
49 typedef int (*DLL_MAIN)(HINSTANCE, sandbox::SandboxInterfaceInfo*);
51 typedef void (*RelaunchChromeBrowserWithNewCommandLineIfNeededFunc)();
53 base::LazyInstance<chrome::ChromeCrashReporterClient>::Leaky
54 g_chrome_crash_client = LAZY_INSTANCE_INITIALIZER;
56 // Loads |module| after setting the CWD to |module|'s directory. Returns a
57 // reference to the loaded module on success, or null on error.
58 HMODULE LoadModuleWithDirectory(const base::FilePath& module, bool pre_read) {
59 ::SetCurrentDirectoryW(module.DirName().value().c_str());
61 if (pre_read) {
62 // We pre-read the binary to warm the memory caches (fewer hard faults to
63 // page parts of the binary in).
64 const size_t kStepSize = 1024 * 1024;
65 size_t percent = 100;
66 ImagePreReader::PartialPreReadImage(module.value().c_str(), percent,
67 kStepSize);
70 return ::LoadLibraryExW(module.value().c_str(), nullptr,
71 LOAD_WITH_ALTERED_SEARCH_PATH);
74 void RecordDidRun(const base::FilePath& dll_path) {
75 bool system_level = !InstallUtil::IsPerUserInstall(dll_path);
76 GoogleUpdateSettings::UpdateDidRunState(true, system_level);
79 void ClearDidRun(const base::FilePath& dll_path) {
80 bool system_level = !InstallUtil::IsPerUserInstall(dll_path);
81 GoogleUpdateSettings::UpdateDidRunState(false, system_level);
84 bool InMetroMode() {
85 return (wcsstr(
86 ::GetCommandLineW(), L" -ServerName:DefaultBrowserServer") != nullptr);
89 typedef int (*InitMetro)();
91 // Returns the directory in which the currently running executable resides.
92 base::FilePath GetExecutableDir() {
93 base::char16 path[MAX_PATH];
94 ::GetModuleFileNameW(nullptr, path, MAX_PATH);
95 return base::FilePath(path).DirName();
98 } // namespace
100 base::string16 GetCurrentModuleVersion() {
101 scoped_ptr<FileVersionInfo> file_version_info(
102 FileVersionInfo::CreateFileVersionInfoForCurrentModule());
103 if (file_version_info.get()) {
104 base::string16 version_string(file_version_info->file_version());
105 if (Version(base::UTF16ToASCII(version_string)).IsValid())
106 return version_string;
108 return base::string16();
111 //=============================================================================
113 MainDllLoader::MainDllLoader()
114 : dll_(nullptr), metro_mode_(InMetroMode()) {
117 MainDllLoader::~MainDllLoader() {
120 // Loading chrome is an interesting affair. First we try loading from the
121 // current directory to support run-what-you-compile and other development
122 // scenarios.
123 // If that fails then we look at the version resource in the current
124 // module. This is the expected path for chrome.exe browser instances in an
125 // installed build.
126 HMODULE MainDllLoader::Load(base::string16* version, base::FilePath* module) {
127 const base::char16* dll_name = nullptr;
128 if (metro_mode_) {
129 dll_name = installer::kChromeMetroDll;
130 } else if (process_type_ == "service" || process_type_.empty()) {
131 dll_name = installer::kChromeDll;
132 } else if (process_type_ == "watcher") {
133 dll_name = kChromeWatcherDll;
134 } else {
135 #if defined(CHROME_MULTIPLE_DLL)
136 dll_name = installer::kChromeChildDll;
137 #else
138 dll_name = installer::kChromeDll;
139 #endif
142 const bool pre_read = !metro_mode_;
143 base::FilePath module_dir = GetExecutableDir();
144 *module = module_dir.Append(dll_name);
145 HMODULE dll = LoadModuleWithDirectory(*module, pre_read);
146 if (!dll) {
147 base::string16 version_string(GetCurrentModuleVersion());
148 if (version_string.empty()) {
149 LOG(ERROR) << "No valid Chrome version found";
150 return nullptr;
152 *version = version_string;
153 *module = module_dir.Append(version_string).Append(dll_name);
154 dll = LoadModuleWithDirectory(*module, pre_read);
155 if (!dll) {
156 PLOG(ERROR) << "Failed to load Chrome DLL from " << module->value();
157 return nullptr;
161 DCHECK(dll);
162 return dll;
165 // Launching is a matter of loading the right dll, setting the CHROME_VERSION
166 // environment variable and just calling the entry point. Derived classes can
167 // add custom code in the OnBeforeLaunch callback.
168 int MainDllLoader::Launch(HINSTANCE instance) {
169 const base::CommandLine& cmd_line = *base::CommandLine::ForCurrentProcess();
170 process_type_ = cmd_line.GetSwitchValueASCII(switches::kProcessType);
172 base::string16 version;
173 base::FilePath file;
175 if (metro_mode_) {
176 HMODULE metro_dll = Load(&version, &file);
177 if (!metro_dll)
178 return chrome::RESULT_CODE_MISSING_DATA;
180 InitMetro chrome_metro_main =
181 reinterpret_cast<InitMetro>(::GetProcAddress(metro_dll, "InitMetro"));
182 return chrome_metro_main();
185 if (process_type_ == "watcher") {
186 chrome::RegisterPathProvider();
188 base::win::ScopedHandle parent_process;
189 base::win::ScopedHandle on_initialized_event;
190 DWORD main_thread_id = 0;
191 if (!InterpretChromeWatcherCommandLine(cmd_line, &parent_process,
192 &main_thread_id,
193 &on_initialized_event)) {
194 return chrome::RESULT_CODE_UNSUPPORTED_PARAM;
197 base::FilePath default_user_data_directory;
198 if (!PathService::Get(chrome::DIR_USER_DATA, &default_user_data_directory))
199 return chrome::RESULT_CODE_MISSING_DATA;
200 // The actual user data directory may differ from the default according to
201 // policy and command-line arguments evaluated in the browser process.
202 // The hang monitor will simply be disabled if a window with this name is
203 // never instantiated by the browser process. Since this should be
204 // exceptionally rare it should not impact stability efforts.
205 base::string16 message_window_name = default_user_data_directory.value();
207 base::FilePath watcher_data_directory;
208 if (!PathService::Get(chrome::DIR_WATCHER_DATA, &watcher_data_directory))
209 return chrome::RESULT_CODE_MISSING_DATA;
211 base::string16 channel_name = GoogleUpdateSettings::GetChromeChannel(
212 !InstallUtil::IsPerUserInstall(cmd_line.GetProgram()));
214 // Intentionally leaked.
215 HMODULE watcher_dll = Load(&version, &file);
216 if (!watcher_dll)
217 return chrome::RESULT_CODE_MISSING_DATA;
219 ChromeWatcherMainFunction watcher_main =
220 reinterpret_cast<ChromeWatcherMainFunction>(
221 ::GetProcAddress(watcher_dll, kChromeWatcherDLLEntrypoint));
222 return watcher_main(chrome::kBrowserExitCodesRegistryPath,
223 parent_process.Take(), main_thread_id,
224 on_initialized_event.Take(),
225 watcher_data_directory.value().c_str(),
226 message_window_name.c_str(), channel_name.c_str());
229 // Initialize the sandbox services.
230 sandbox::SandboxInterfaceInfo sandbox_info = {0};
231 content::InitializeSandboxInfo(&sandbox_info);
233 crash_reporter::SetCrashReporterClient(g_chrome_crash_client.Pointer());
234 bool exit_now = true;
235 if (process_type_.empty()) {
236 if (breakpad::ShowRestartDialogIfCrashed(&exit_now)) {
237 // We restarted because of a previous crash. Ask user if we should
238 // Relaunch. Only for the browser process. See crbug.com/132119.
239 if (exit_now)
240 return content::RESULT_CODE_NORMAL_EXIT;
243 breakpad::InitCrashReporter(process_type_);
245 dll_ = Load(&version, &file);
246 if (!dll_)
247 return chrome::RESULT_CODE_MISSING_DATA;
249 scoped_ptr<base::Environment> env(base::Environment::Create());
250 env->SetVar(chrome::kChromeVersionEnvVar, base::WideToUTF8(version));
252 OnBeforeLaunch(process_type_, file);
253 DLL_MAIN chrome_main =
254 reinterpret_cast<DLL_MAIN>(::GetProcAddress(dll_, "ChromeMain"));
255 int rc = chrome_main(instance, &sandbox_info);
256 rc = OnBeforeExit(rc, file);
257 // Sandboxed processes close some system DLL handles after lockdown so ignore
258 // EXCEPTION_INVALID_HANDLE generated on Windows 10 during shutdown of these
259 // processes.
260 // TODO(wfh): Check whether MS have fixed this in Win10 RTM. crbug.com/456193
261 if (base::win::GetVersion() >= base::win::VERSION_WIN10)
262 breakpad::ConsumeInvalidHandleExceptions();
263 return rc;
266 void MainDllLoader::RelaunchChromeBrowserWithNewCommandLineIfNeeded() {
267 if (!dll_)
268 return;
270 RelaunchChromeBrowserWithNewCommandLineIfNeededFunc relaunch_function =
271 reinterpret_cast<RelaunchChromeBrowserWithNewCommandLineIfNeededFunc>(
272 ::GetProcAddress(dll_,
273 "RelaunchChromeBrowserWithNewCommandLineIfNeeded"));
274 if (!relaunch_function) {
275 LOG(ERROR) << "Could not find exported function "
276 << "RelaunchChromeBrowserWithNewCommandLineIfNeeded";
277 } else {
278 relaunch_function();
282 //=============================================================================
284 class ChromeDllLoader : public MainDllLoader {
285 protected:
286 // MainDllLoader implementation.
287 void OnBeforeLaunch(const std::string& process_type,
288 const base::FilePath& dll_path) override;
289 int OnBeforeExit(int return_code, const base::FilePath& dll_path) override;
291 private:
292 scoped_ptr<ChromeWatcherClient> chrome_watcher_client_;
293 #if defined(KASKO)
294 scoped_ptr<KaskoClient> kasko_client_;
295 #endif // KASKO
298 void ChromeDllLoader::OnBeforeLaunch(const std::string& process_type,
299 const base::FilePath& dll_path) {
300 if (process_type.empty()) {
301 RecordDidRun(dll_path);
303 // Launch the watcher process if stats collection consent has been granted.
304 if (g_chrome_crash_client.Get().GetCollectStatsConsent()) {
305 base::FilePath exe_path;
306 if (PathService::Get(base::FILE_EXE, &exe_path)) {
307 chrome_watcher_client_.reset(new ChromeWatcherClient(
308 base::Bind(&GenerateChromeWatcherCommandLine, exe_path)));
309 if (chrome_watcher_client_->LaunchWatcher()) {
310 #if defined(KASKO)
311 kasko::api::MinidumpType minidump_type = kasko::api::SMALL_DUMP_TYPE;
312 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
313 switches::kFullMemoryCrashReport)) {
314 minidump_type = kasko::api::FULL_DUMP_TYPE;
315 } else {
316 bool is_per_user_install =
317 g_chrome_crash_client.Get().GetIsPerUserInstall(
318 base::FilePath(exe_path));
319 if (g_chrome_crash_client.Get().GetShouldDumpLargerDumps(
320 is_per_user_install)){
321 minidump_type = kasko::api::LARGER_DUMP_TYPE;
325 kasko_client_.reset(
326 new KaskoClient(chrome_watcher_client_.get(), minidump_type));
327 #endif // KASKO
331 } else {
332 // Set non-browser processes up to be killed by the system after the browser
333 // goes away. The browser uses the default shutdown order, which is 0x280.
334 // Note that lower numbers here denote "kill later" and higher numbers mean
335 // "kill sooner".
336 // This gets rid of most of those unsighly sad tabs on logout and shutdown.
337 ::SetProcessShutdownParameters(0x280 - 1, SHUTDOWN_NORETRY);
341 int ChromeDllLoader::OnBeforeExit(int return_code,
342 const base::FilePath& dll_path) {
343 // NORMAL_EXIT_CANCEL is used for experiments when the user cancels
344 // so we need to reset the did_run signal so omaha does not count
345 // this run as active usage.
346 if (chrome::RESULT_CODE_NORMAL_EXIT_CANCEL == return_code) {
347 ClearDidRun(dll_path);
350 #if defined(KASKO)
351 kasko_client_.reset();
352 #endif // KASKO
353 chrome_watcher_client_.reset();
355 return return_code;
358 //=============================================================================
360 class ChromiumDllLoader : public MainDllLoader {
361 protected:
362 void OnBeforeLaunch(const std::string& process_type,
363 const base::FilePath& dll_path) override {}
364 int OnBeforeExit(int return_code, const base::FilePath& dll_path) override {
365 return return_code;
369 MainDllLoader* MakeMainDllLoader() {
370 #if defined(GOOGLE_CHROME_BUILD)
371 return new ChromeDllLoader();
372 #else
373 return new ChromiumDllLoader();
374 #endif