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.
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"
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());
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;
60 ImagePreReader::PartialPreReadImage(module
.value().c_str(), percent
,
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
);
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();
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
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
120 HMODULE
MainDllLoader::Load(base::string16
* version
, base::FilePath
* module
) {
121 const base::char16
* dll_name
= nullptr;
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
;
129 #if defined(CHROME_MULTIPLE_DLL)
130 dll_name
= installer::kChromeChildDll
;
132 dll_name
= installer::kChromeDll
;
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
);
141 base::string16
version_string(GetCurrentModuleVersion());
142 if (version_string
.empty()) {
143 LOG(ERROR
) << "No valid Chrome version found";
146 *version
= version_string
;
147 *module
= module_dir
.Append(version_string
).Append(dll_name
);
148 dll
= LoadModuleWithDirectory(*module
, pre_read
);
150 PLOG(ERROR
) << "Failed to load Chrome DLL from " << module
->value();
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
;
170 HMODULE metro_dll
= Load(&version
, &file
);
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
);
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.
204 return content::RESULT_CODE_NORMAL_EXIT
;
207 breakpad::InitCrashReporter(process_type_
);
209 dll_
= Load(&version
, &file
);
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() {
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";
239 //=============================================================================
241 class ChromeDllLoader
: public MainDllLoader
{
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
);
278 //=============================================================================
280 class ChromiumDllLoader
: public MainDllLoader
{
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
{
289 MainDllLoader
* MakeMainDllLoader() {
290 #if defined(GOOGLE_CHROME_BUILD)
291 return new ChromeDllLoader();
293 return new ChromiumDllLoader();