Reenable AutomationApiTest.DesktopLoadTabs.
[chromium-blink-merge.git] / chrome / app / client_util.cc
blobf73c472733746b04f0352d93d59dcc40344ce43f
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 // Expects that |dir| has a trailing backslash. |dir| is modified so it
51 // contains the full path that was tried. Caller must check for the return
52 // value not being null to determine if this path contains a valid dll.
53 HMODULE LoadModuleWithDirectory(base::string16* dir,
54 const base::char16* dll_name,
55 bool pre_read) {
56 ::SetCurrentDirectoryW(dir->c_str());
57 dir->append(dll_name);
59 if (pre_read) {
60 // We pre-read the binary to warm the memory caches (fewer hard faults to
61 // page parts of the binary in).
62 const size_t kStepSize = 1024 * 1024;
63 size_t percent = 100;
64 ImagePreReader::PartialPreReadImage(dir->c_str(), percent, kStepSize);
67 return ::LoadLibraryExW(dir->c_str(), nullptr,
68 LOAD_WITH_ALTERED_SEARCH_PATH);
71 void RecordDidRun(const base::string16& dll_path) {
72 bool system_level = !InstallUtil::IsPerUserInstall(dll_path.c_str());
73 GoogleUpdateSettings::UpdateDidRunState(true, system_level);
76 void ClearDidRun(const base::string16& dll_path) {
77 bool system_level = !InstallUtil::IsPerUserInstall(dll_path.c_str());
78 GoogleUpdateSettings::UpdateDidRunState(false, system_level);
81 bool InMetroMode() {
82 return (wcsstr(
83 ::GetCommandLineW(), L" -ServerName:DefaultBrowserServer") != nullptr);
86 typedef int (*InitMetro)();
88 } // namespace
90 base::string16 GetExecutablePath() {
91 base::char16 path[MAX_PATH];
92 ::GetModuleFileNameW(nullptr, path, MAX_PATH);
93 if (!::PathRemoveFileSpecW(path))
94 return base::string16();
95 base::string16 exe_path(path);
96 return exe_path.append(1, L'\\');
99 base::string16 GetCurrentModuleVersion() {
100 scoped_ptr<FileVersionInfo> file_version_info(
101 FileVersionInfo::CreateFileVersionInfoForCurrentModule());
102 if (file_version_info.get()) {
103 base::string16 version_string(file_version_info->file_version());
104 if (Version(base::UTF16ToASCII(version_string)).IsValid())
105 return version_string;
107 return base::string16();
110 //=============================================================================
112 MainDllLoader::MainDllLoader()
113 : dll_(nullptr), metro_mode_(InMetroMode()) {
116 MainDllLoader::~MainDllLoader() {
119 // Loading chrome is an interesting affair. First we try loading from the
120 // current directory to support run-what-you-compile and other development
121 // scenarios.
122 // If that fails then we look at the version resource in the current
123 // module. This is the expected path for chrome.exe browser instances in an
124 // installed build.
125 HMODULE MainDllLoader::Load(base::string16* version,
126 base::string16* out_file) {
127 const base::string16 executable_dir(GetExecutablePath());
128 *out_file = executable_dir;
130 const base::char16* dll_name = nullptr;
131 if (metro_mode_) {
132 dll_name = installer::kChromeMetroDll;
133 } else if (process_type_ == "service" || process_type_.empty()) {
134 dll_name = installer::kChromeDll;
135 } else if (process_type_ == "watcher") {
136 dll_name = browser_watcher::kWatcherDll;
137 } else {
138 #if defined(CHROME_MULTIPLE_DLL)
139 dll_name = installer::kChromeChildDll;
140 #else
141 dll_name = installer::kChromeDll;
142 #endif
145 const bool pre_read = !metro_mode_;
146 HMODULE dll = LoadModuleWithDirectory(out_file, dll_name, pre_read);
147 if (!dll) {
148 base::string16 version_string(GetCurrentModuleVersion());
149 if (version_string.empty()) {
150 LOG(ERROR) << "No valid Chrome version found";
151 return nullptr;
153 *out_file = executable_dir;
154 *version = version_string;
155 out_file->append(version_string).append(1, L'\\');
156 dll = LoadModuleWithDirectory(out_file, dll_name, pre_read);
157 if (!dll) {
158 PLOG(ERROR) << "Failed to load Chrome DLL from " << *out_file;
159 return nullptr;
163 DCHECK(dll);
164 return dll;
167 // Launching is a matter of loading the right dll, setting the CHROME_VERSION
168 // environment variable and just calling the entry point. Derived classes can
169 // add custom code in the OnBeforeLaunch callback.
170 int MainDllLoader::Launch(HINSTANCE instance) {
171 const CommandLine& cmd_line = *CommandLine::ForCurrentProcess();
172 process_type_ = cmd_line.GetSwitchValueASCII(switches::kProcessType);
174 base::string16 version;
175 base::string16 file;
177 if (metro_mode_) {
178 HMODULE metro_dll = Load(&version, &file);
179 if (!metro_dll)
180 return chrome::RESULT_CODE_MISSING_DATA;
182 InitMetro chrome_metro_main =
183 reinterpret_cast<InitMetro>(::GetProcAddress(metro_dll, "InitMetro"));
184 return chrome_metro_main();
187 if (process_type_ == "watcher") {
188 // Intentionally leaked.
189 HMODULE watcher_dll = Load(&version, &file);
190 if (!watcher_dll)
191 return chrome::RESULT_CODE_MISSING_DATA;
193 browser_watcher::WatcherMainFunction watcher_main =
194 reinterpret_cast<browser_watcher::WatcherMainFunction>(
195 ::GetProcAddress(watcher_dll,
196 browser_watcher::kWatcherDLLEntrypoint));
198 return watcher_main(chrome::kBrowserExitCodesRegistryPath);
201 // Initialize the sandbox services.
202 sandbox::SandboxInterfaceInfo sandbox_info = {0};
203 content::InitializeSandboxInfo(&sandbox_info);
205 crash_reporter::SetCrashReporterClient(g_chrome_crash_client.Pointer());
206 bool exit_now = true;
207 if (process_type_.empty()) {
208 if (breakpad::ShowRestartDialogIfCrashed(&exit_now)) {
209 // We restarted because of a previous crash. Ask user if we should
210 // Relaunch. Only for the browser process. See crbug.com/132119.
211 if (exit_now)
212 return content::RESULT_CODE_NORMAL_EXIT;
215 breakpad::InitCrashReporter(process_type_);
217 dll_ = Load(&version, &file);
218 if (!dll_)
219 return chrome::RESULT_CODE_MISSING_DATA;
221 scoped_ptr<base::Environment> env(base::Environment::Create());
222 env->SetVar(chrome::kChromeVersionEnvVar, base::WideToUTF8(version));
224 OnBeforeLaunch(process_type_, file);
225 DLL_MAIN chrome_main =
226 reinterpret_cast<DLL_MAIN>(::GetProcAddress(dll_, "ChromeMain"));
227 int rc = chrome_main(instance, &sandbox_info);
228 return OnBeforeExit(rc, file);
231 void MainDllLoader::RelaunchChromeBrowserWithNewCommandLineIfNeeded() {
232 if (!dll_)
233 return;
235 RelaunchChromeBrowserWithNewCommandLineIfNeededFunc relaunch_function =
236 reinterpret_cast<RelaunchChromeBrowserWithNewCommandLineIfNeededFunc>(
237 ::GetProcAddress(dll_,
238 "RelaunchChromeBrowserWithNewCommandLineIfNeeded"));
239 if (!relaunch_function) {
240 LOG(ERROR) << "Could not find exported function "
241 << "RelaunchChromeBrowserWithNewCommandLineIfNeeded";
242 } else {
243 relaunch_function();
247 //=============================================================================
249 class ChromeDllLoader : public MainDllLoader {
250 protected:
251 void OnBeforeLaunch(const std::string& process_type,
252 const base::string16& dll_path) override;
253 int OnBeforeExit(int return_code,
254 const base::string16& dll_path) override;
257 void ChromeDllLoader::OnBeforeLaunch(const std::string& process_type,
258 const base::string16& dll_path) {
259 if (process_type.empty()) {
260 RecordDidRun(dll_path);
262 // Launch the watcher process if stats collection consent has been granted.
263 if (g_chrome_crash_client.Get().GetCollectStatsConsent()) {
264 base::char16 exe_path[MAX_PATH];
265 ::GetModuleFileNameW(nullptr, exe_path, arraysize(exe_path));
267 base::CommandLine cmd_line = base::CommandLine(base::FilePath(exe_path));
268 cmd_line.AppendSwitchASCII(switches::kProcessType, "watcher");
269 browser_watcher::WatcherClient watcher_client(cmd_line);
271 watcher_client.LaunchWatcher();
276 int ChromeDllLoader::OnBeforeExit(int return_code,
277 const base::string16& dll_path) {
278 // NORMAL_EXIT_CANCEL is used for experiments when the user cancels
279 // so we need to reset the did_run signal so omaha does not count
280 // this run as active usage.
281 if (chrome::RESULT_CODE_NORMAL_EXIT_CANCEL == return_code) {
282 ClearDidRun(dll_path);
284 return return_code;
287 //=============================================================================
289 class ChromiumDllLoader : public MainDllLoader {
290 protected:
291 void OnBeforeLaunch(const std::string& process_type,
292 const base::string16& dll_path) override {
294 int OnBeforeExit(int return_code,
295 const base::string16& dll_path) override {
296 return return_code;
300 MainDllLoader* MakeMainDllLoader() {
301 #if defined(GOOGLE_CHROME_BUILD)
302 return new ChromeDllLoader();
303 #else
304 return new ChromiumDllLoader();
305 #endif