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/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"
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());
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;
66 ImagePreReader::PartialPreReadImage(module
.value().c_str(), percent
,
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
);
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();
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
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
126 HMODULE
MainDllLoader::Load(base::string16
* version
, base::FilePath
* module
) {
127 const base::char16
* dll_name
= nullptr;
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
;
135 #if defined(CHROME_MULTIPLE_DLL)
136 dll_name
= installer::kChromeChildDll
;
138 dll_name
= installer::kChromeDll
;
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
);
147 base::string16
version_string(GetCurrentModuleVersion());
148 if (version_string
.empty()) {
149 LOG(ERROR
) << "No valid Chrome version found";
152 *version
= version_string
;
153 *module
= module_dir
.Append(version_string
).Append(dll_name
);
154 dll
= LoadModuleWithDirectory(*module
, pre_read
);
156 PLOG(ERROR
) << "Failed to load Chrome DLL from " << module
->value();
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
;
176 HMODULE metro_dll
= Load(&version
, &file
);
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 if (!InterpretChromeWatcherCommandLine(cmd_line
, &parent_process
,
191 &on_initialized_event
)) {
192 return chrome::RESULT_CODE_UNSUPPORTED_PARAM
;
195 base::FilePath default_user_data_directory
;
196 if (!PathService::Get(chrome::DIR_USER_DATA
, &default_user_data_directory
))
197 return chrome::RESULT_CODE_MISSING_DATA
;
198 // The actual user data directory may differ from the default according to
199 // policy and command-line arguments evaluated in the browser process.
200 // The hang monitor will simply be disabled if a window with this name is
201 // never instantiated by the browser process. Since this should be
202 // exceptionally rare it should not impact stability efforts.
203 base::string16 message_window_name
= default_user_data_directory
.value();
205 base::FilePath watcher_data_directory
;
206 if (!PathService::Get(chrome::DIR_WATCHER_DATA
, &watcher_data_directory
))
207 return chrome::RESULT_CODE_MISSING_DATA
;
209 base::string16 channel_name
= GoogleUpdateSettings::GetChromeChannel(
210 !InstallUtil::IsPerUserInstall(cmd_line
.GetProgram()));
212 // Intentionally leaked.
213 HMODULE watcher_dll
= Load(&version
, &file
);
215 return chrome::RESULT_CODE_MISSING_DATA
;
217 ChromeWatcherMainFunction watcher_main
=
218 reinterpret_cast<ChromeWatcherMainFunction
>(
219 ::GetProcAddress(watcher_dll
, kChromeWatcherDLLEntrypoint
));
220 return watcher_main(chrome::kBrowserExitCodesRegistryPath
,
221 parent_process
.Take(), on_initialized_event
.Take(),
222 watcher_data_directory
.value().c_str(),
223 message_window_name
.c_str(), channel_name
.c_str());
226 // Initialize the sandbox services.
227 sandbox::SandboxInterfaceInfo sandbox_info
= {0};
228 content::InitializeSandboxInfo(&sandbox_info
);
230 crash_reporter::SetCrashReporterClient(g_chrome_crash_client
.Pointer());
231 bool exit_now
= true;
232 if (process_type_
.empty()) {
233 if (breakpad::ShowRestartDialogIfCrashed(&exit_now
)) {
234 // We restarted because of a previous crash. Ask user if we should
235 // Relaunch. Only for the browser process. See crbug.com/132119.
237 return content::RESULT_CODE_NORMAL_EXIT
;
240 breakpad::InitCrashReporter(process_type_
);
242 dll_
= Load(&version
, &file
);
244 return chrome::RESULT_CODE_MISSING_DATA
;
246 scoped_ptr
<base::Environment
> env(base::Environment::Create());
247 env
->SetVar(chrome::kChromeVersionEnvVar
, base::WideToUTF8(version
));
249 OnBeforeLaunch(process_type_
, file
);
250 DLL_MAIN chrome_main
=
251 reinterpret_cast<DLL_MAIN
>(::GetProcAddress(dll_
, "ChromeMain"));
252 int rc
= chrome_main(instance
, &sandbox_info
);
253 rc
= OnBeforeExit(rc
, file
);
254 // Sandboxed processes close some system DLL handles after lockdown so ignore
255 // EXCEPTION_INVALID_HANDLE generated on Windows 10 during shutdown of these
257 // TODO(wfh): Check whether MS have fixed this in Win10 RTM. crbug.com/456193
258 if (base::win::GetVersion() >= base::win::VERSION_WIN10
)
259 breakpad::ConsumeInvalidHandleExceptions();
263 void MainDllLoader::RelaunchChromeBrowserWithNewCommandLineIfNeeded() {
267 RelaunchChromeBrowserWithNewCommandLineIfNeededFunc relaunch_function
=
268 reinterpret_cast<RelaunchChromeBrowserWithNewCommandLineIfNeededFunc
>(
269 ::GetProcAddress(dll_
,
270 "RelaunchChromeBrowserWithNewCommandLineIfNeeded"));
271 if (!relaunch_function
) {
272 LOG(ERROR
) << "Could not find exported function "
273 << "RelaunchChromeBrowserWithNewCommandLineIfNeeded";
279 //=============================================================================
281 class ChromeDllLoader
: public MainDllLoader
{
283 // MainDllLoader implementation.
284 void OnBeforeLaunch(const std::string
& process_type
,
285 const base::FilePath
& dll_path
) override
;
286 int OnBeforeExit(int return_code
, const base::FilePath
& dll_path
) override
;
289 scoped_ptr
<ChromeWatcherClient
> chrome_watcher_client_
;
291 scoped_ptr
<KaskoClient
> kasko_client_
;
295 void ChromeDllLoader::OnBeforeLaunch(const std::string
& process_type
,
296 const base::FilePath
& dll_path
) {
297 if (process_type
.empty()) {
298 RecordDidRun(dll_path
);
300 // Launch the watcher process if stats collection consent has been granted.
301 if (g_chrome_crash_client
.Get().GetCollectStatsConsent()) {
302 base::FilePath exe_path
;
303 if (PathService::Get(base::FILE_EXE
, &exe_path
)) {
304 chrome_watcher_client_
.reset(new ChromeWatcherClient(
305 base::Bind(&GenerateChromeWatcherCommandLine
, exe_path
)));
306 if (chrome_watcher_client_
->LaunchWatcher()) {
308 kasko::api::MinidumpType minidump_type
= kasko::api::SMALL_DUMP_TYPE
;
309 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
310 switches::kFullMemoryCrashReport
)) {
311 minidump_type
= kasko::api::FULL_DUMP_TYPE
;
313 bool is_per_user_install
=
314 g_chrome_crash_client
.Get().GetIsPerUserInstall(
315 base::FilePath(exe_path
));
316 if (g_chrome_crash_client
.Get().GetShouldDumpLargerDumps(
317 is_per_user_install
)){
318 minidump_type
= kasko::api::LARGER_DUMP_TYPE
;
323 new KaskoClient(chrome_watcher_client_
.get(), minidump_type
));
329 // Set non-browser processes up to be killed by the system after the browser
330 // goes away. The browser uses the default shutdown order, which is 0x280.
331 // Note that lower numbers here denote "kill later" and higher numbers mean
333 // This gets rid of most of those unsighly sad tabs on logout and shutdown.
334 ::SetProcessShutdownParameters(0x280 - 1, SHUTDOWN_NORETRY
);
338 int ChromeDllLoader::OnBeforeExit(int return_code
,
339 const base::FilePath
& dll_path
) {
340 // NORMAL_EXIT_CANCEL is used for experiments when the user cancels
341 // so we need to reset the did_run signal so omaha does not count
342 // this run as active usage.
343 if (chrome::RESULT_CODE_NORMAL_EXIT_CANCEL
== return_code
) {
344 ClearDidRun(dll_path
);
348 kasko_client_
.reset();
350 chrome_watcher_client_
.reset();
355 //=============================================================================
357 class ChromiumDllLoader
: public MainDllLoader
{
359 void OnBeforeLaunch(const std::string
& process_type
,
360 const base::FilePath
& dll_path
) override
{}
361 int OnBeforeExit(int return_code
, const base::FilePath
& dll_path
) override
{
366 MainDllLoader
* MakeMainDllLoader() {
367 #if defined(GOOGLE_CHROME_BUILD)
368 return new ChromeDllLoader();
370 return new ChromiumDllLoader();