Roll src/third_party/WebKit 8b42d1d:744641d (svn 186770:186771)
[chromium-blink-merge.git] / chrome / app / client_util.cc
bloba5271732e1ad742eb9b88ee173be0b958a9d5f81
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/command_line.h"
9 #include "base/compiler_specific.h"
10 #include "base/debug/trace_event.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/strings/string16.h"
17 #include "base/strings/string_util.h"
18 #include "base/strings/stringprintf.h"
19 #include "base/strings/utf_string_conversions.h"
20 #include "base/version.h"
21 #include "base/win/windows_version.h"
22 #include "chrome/app/chrome_crash_reporter_client.h"
23 #include "chrome/app/client_util.h"
24 #include "chrome/app/image_pre_reader_win.h"
25 #include "chrome/common/chrome_constants.h"
26 #include "chrome/common/chrome_result_codes.h"
27 #include "chrome/common/chrome_switches.h"
28 #include "chrome/common/env_vars.h"
29 #include "chrome/installer/util/google_update_constants.h"
30 #include "chrome/installer/util/google_update_settings.h"
31 #include "chrome/installer/util/install_util.h"
32 #include "chrome/installer/util/util_constants.h"
33 #include "components/browser_watcher/watcher_client_win.h"
34 #include "components/browser_watcher/watcher_main_api_win.h"
35 #include "components/crash/app/breakpad_win.h"
36 #include "components/crash/app/crash_reporter_client.h"
37 #include "components/metrics/client_info.h"
38 #include "content/public/app/startup_helper_win.h"
39 #include "sandbox/win/src/sandbox.h"
41 namespace {
42 // The entry point signature of chrome.dll.
43 typedef int (*DLL_MAIN)(HINSTANCE, sandbox::SandboxInterfaceInfo*);
45 typedef void (*RelaunchChromeBrowserWithNewCommandLineIfNeededFunc)();
47 base::LazyInstance<chrome::ChromeCrashReporterClient>::Leaky
48 g_chrome_crash_client = LAZY_INSTANCE_INITIALIZER;
50 // Loads |module| after setting the CWD to |module|'s directory. Returns a
51 // reference to the loaded module on success, or null on error.
52 HMODULE LoadModuleWithDirectory(const base::FilePath& module, bool pre_read) {
53 ::SetCurrentDirectoryW(module.DirName().value().c_str());
55 if (pre_read) {
56 // We pre-read the binary to warm the memory caches (fewer hard faults to
57 // page parts of the binary in).
58 const size_t kStepSize = 1024 * 1024;
59 size_t percent = 100;
60 ImagePreReader::PartialPreReadImage(module.value().c_str(), percent,
61 kStepSize);
64 return ::LoadLibraryExW(module.value().c_str(), nullptr,
65 LOAD_WITH_ALTERED_SEARCH_PATH);
68 void RecordDidRun(const base::FilePath& dll_path) {
69 bool system_level = !InstallUtil::IsPerUserInstall(dll_path);
70 GoogleUpdateSettings::UpdateDidRunState(true, system_level);
73 void ClearDidRun(const base::FilePath& dll_path) {
74 bool system_level = !InstallUtil::IsPerUserInstall(dll_path);
75 GoogleUpdateSettings::UpdateDidRunState(false, system_level);
78 bool InMetroMode() {
79 return (wcsstr(
80 ::GetCommandLineW(), L" -ServerName:DefaultBrowserServer") != nullptr);
83 typedef int (*InitMetro)();
85 // Returns the directory in which the currently running executable resides.
86 base::FilePath GetExecutableDir() {
87 base::char16 path[MAX_PATH];
88 ::GetModuleFileNameW(nullptr, path, MAX_PATH);
89 return base::FilePath(path).DirName();
92 } // namespace
94 base::string16 GetCurrentModuleVersion() {
95 scoped_ptr<FileVersionInfo> file_version_info(
96 FileVersionInfo::CreateFileVersionInfoForCurrentModule());
97 if (file_version_info.get()) {
98 base::string16 version_string(file_version_info->file_version());
99 if (Version(base::UTF16ToASCII(version_string)).IsValid())
100 return version_string;
102 return base::string16();
105 //=============================================================================
107 MainDllLoader::MainDllLoader()
108 : dll_(nullptr), metro_mode_(InMetroMode()) {
111 MainDllLoader::~MainDllLoader() {
114 // Loading chrome is an interesting affair. First we try loading from the
115 // current directory to support run-what-you-compile and other development
116 // scenarios.
117 // If that fails then we look at the version resource in the current
118 // module. This is the expected path for chrome.exe browser instances in an
119 // installed build.
120 HMODULE MainDllLoader::Load(base::string16* version, base::FilePath* module) {
121 const base::char16* dll_name = nullptr;
122 if (metro_mode_) {
123 dll_name = installer::kChromeMetroDll;
124 } else if (process_type_ == "service" || process_type_.empty()) {
125 dll_name = installer::kChromeDll;
126 } else if (process_type_ == "watcher") {
127 dll_name = browser_watcher::kWatcherDll;
128 } else {
129 #if defined(CHROME_MULTIPLE_DLL)
130 dll_name = installer::kChromeChildDll;
131 #else
132 dll_name = installer::kChromeDll;
133 #endif
136 const bool pre_read = !metro_mode_;
137 base::FilePath module_dir = GetExecutableDir();
138 *module = module_dir.Append(dll_name);
139 HMODULE dll = LoadModuleWithDirectory(*module, pre_read);
140 if (!dll) {
141 base::string16 version_string(GetCurrentModuleVersion());
142 if (version_string.empty()) {
143 LOG(ERROR) << "No valid Chrome version found";
144 return nullptr;
146 *version = version_string;
147 *module = module_dir.Append(version_string).Append(dll_name);
148 dll = LoadModuleWithDirectory(*module, pre_read);
149 if (!dll) {
150 PLOG(ERROR) << "Failed to load Chrome DLL from " << module->value();
151 return nullptr;
155 DCHECK(dll);
156 return dll;
159 // Launching is a matter of loading the right dll, setting the CHROME_VERSION
160 // environment variable and just calling the entry point. Derived classes can
161 // add custom code in the OnBeforeLaunch callback.
162 int MainDllLoader::Launch(HINSTANCE instance) {
163 const CommandLine& cmd_line = *CommandLine::ForCurrentProcess();
164 process_type_ = cmd_line.GetSwitchValueASCII(switches::kProcessType);
166 base::string16 version;
167 base::FilePath file;
169 if (metro_mode_) {
170 HMODULE metro_dll = Load(&version, &file);
171 if (!metro_dll)
172 return chrome::RESULT_CODE_MISSING_DATA;
174 InitMetro chrome_metro_main =
175 reinterpret_cast<InitMetro>(::GetProcAddress(metro_dll, "InitMetro"));
176 return chrome_metro_main();
179 if (process_type_ == "watcher") {
180 // Intentionally leaked.
181 HMODULE watcher_dll = Load(&version, &file);
182 if (!watcher_dll)
183 return chrome::RESULT_CODE_MISSING_DATA;
185 browser_watcher::WatcherMainFunction watcher_main =
186 reinterpret_cast<browser_watcher::WatcherMainFunction>(
187 ::GetProcAddress(watcher_dll,
188 browser_watcher::kWatcherDLLEntrypoint));
190 return watcher_main(chrome::kBrowserExitCodesRegistryPath);
193 // Initialize the sandbox services.
194 sandbox::SandboxInterfaceInfo sandbox_info = {0};
195 content::InitializeSandboxInfo(&sandbox_info);
197 crash_reporter::SetCrashReporterClient(g_chrome_crash_client.Pointer());
198 bool exit_now = true;
199 if (process_type_.empty()) {
200 if (breakpad::ShowRestartDialogIfCrashed(&exit_now)) {
201 // We restarted because of a previous crash. Ask user if we should
202 // Relaunch. Only for the browser process. See crbug.com/132119.
203 if (exit_now)
204 return content::RESULT_CODE_NORMAL_EXIT;
207 breakpad::InitCrashReporter(process_type_);
209 dll_ = Load(&version, &file);
210 if (!dll_)
211 return chrome::RESULT_CODE_MISSING_DATA;
213 scoped_ptr<base::Environment> env(base::Environment::Create());
214 env->SetVar(chrome::kChromeVersionEnvVar, base::WideToUTF8(version));
216 OnBeforeLaunch(process_type_, file);
217 DLL_MAIN chrome_main =
218 reinterpret_cast<DLL_MAIN>(::GetProcAddress(dll_, "ChromeMain"));
219 int rc = chrome_main(instance, &sandbox_info);
220 return OnBeforeExit(rc, file);
223 void MainDllLoader::RelaunchChromeBrowserWithNewCommandLineIfNeeded() {
224 if (!dll_)
225 return;
227 RelaunchChromeBrowserWithNewCommandLineIfNeededFunc relaunch_function =
228 reinterpret_cast<RelaunchChromeBrowserWithNewCommandLineIfNeededFunc>(
229 ::GetProcAddress(dll_,
230 "RelaunchChromeBrowserWithNewCommandLineIfNeeded"));
231 if (!relaunch_function) {
232 LOG(ERROR) << "Could not find exported function "
233 << "RelaunchChromeBrowserWithNewCommandLineIfNeeded";
234 } else {
235 relaunch_function();
239 //=============================================================================
241 class ChromeDllLoader : public MainDllLoader {
242 protected:
243 void OnBeforeLaunch(const std::string& process_type,
244 const base::FilePath& dll_path) override;
245 int OnBeforeExit(int return_code, const base::FilePath& dll_path) override;
248 void ChromeDllLoader::OnBeforeLaunch(const std::string& process_type,
249 const base::FilePath& dll_path) {
250 if (process_type.empty()) {
251 RecordDidRun(dll_path);
253 // Launch the watcher process if stats collection consent has been granted.
254 if (g_chrome_crash_client.Get().GetCollectStatsConsent()) {
255 base::char16 exe_path[MAX_PATH];
256 ::GetModuleFileNameW(nullptr, exe_path, arraysize(exe_path));
258 base::CommandLine cmd_line = base::CommandLine(base::FilePath(exe_path));
259 cmd_line.AppendSwitchASCII(switches::kProcessType, "watcher");
260 browser_watcher::WatcherClient watcher_client(cmd_line);
262 watcher_client.LaunchWatcher();
267 int ChromeDllLoader::OnBeforeExit(int return_code,
268 const base::FilePath& dll_path) {
269 // NORMAL_EXIT_CANCEL is used for experiments when the user cancels
270 // so we need to reset the did_run signal so omaha does not count
271 // this run as active usage.
272 if (chrome::RESULT_CODE_NORMAL_EXIT_CANCEL == return_code) {
273 ClearDidRun(dll_path);
275 return return_code;
278 //=============================================================================
280 class ChromiumDllLoader : public MainDllLoader {
281 protected:
282 void OnBeforeLaunch(const std::string& process_type,
283 const base::FilePath& dll_path) override {}
284 int OnBeforeExit(int return_code, const base::FilePath& dll_path) override {
285 return return_code;
289 MainDllLoader* MakeMainDllLoader() {
290 #if defined(GOOGLE_CHROME_BUILD)
291 return new ChromeDllLoader();
292 #else
293 return new ChromiumDllLoader();
294 #endif