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 watcher_data_directory
;
196 if (!PathService::Get(chrome::DIR_WATCHER_DATA
, &watcher_data_directory
))
197 return chrome::RESULT_CODE_MISSING_DATA
;
199 // Intentionally leaked.
200 HMODULE watcher_dll
= Load(&version
, &file
);
202 return chrome::RESULT_CODE_MISSING_DATA
;
204 ChromeWatcherMainFunction watcher_main
=
205 reinterpret_cast<ChromeWatcherMainFunction
>(
206 ::GetProcAddress(watcher_dll
, kChromeWatcherDLLEntrypoint
));
207 return watcher_main(chrome::kBrowserExitCodesRegistryPath
,
208 parent_process
.Take(), on_initialized_event
.Take(),
209 watcher_data_directory
.value().c_str());
212 // Initialize the sandbox services.
213 sandbox::SandboxInterfaceInfo sandbox_info
= {0};
214 content::InitializeSandboxInfo(&sandbox_info
);
216 crash_reporter::SetCrashReporterClient(g_chrome_crash_client
.Pointer());
217 bool exit_now
= true;
218 if (process_type_
.empty()) {
219 if (breakpad::ShowRestartDialogIfCrashed(&exit_now
)) {
220 // We restarted because of a previous crash. Ask user if we should
221 // Relaunch. Only for the browser process. See crbug.com/132119.
223 return content::RESULT_CODE_NORMAL_EXIT
;
226 breakpad::InitCrashReporter(process_type_
);
228 dll_
= Load(&version
, &file
);
230 return chrome::RESULT_CODE_MISSING_DATA
;
232 scoped_ptr
<base::Environment
> env(base::Environment::Create());
233 env
->SetVar(chrome::kChromeVersionEnvVar
, base::WideToUTF8(version
));
235 OnBeforeLaunch(process_type_
, file
);
236 DLL_MAIN chrome_main
=
237 reinterpret_cast<DLL_MAIN
>(::GetProcAddress(dll_
, "ChromeMain"));
238 int rc
= chrome_main(instance
, &sandbox_info
);
239 rc
= OnBeforeExit(rc
, file
);
240 // Sandboxed processes close some system DLL handles after lockdown so ignore
241 // EXCEPTION_INVALID_HANDLE generated on Windows 10 during shutdown of these
243 // TODO(wfh): Check whether MS have fixed this in Win10 RTM. crbug.com/456193
244 if (base::win::GetVersion() >= base::win::VERSION_WIN10
)
245 breakpad::ConsumeInvalidHandleExceptions();
249 void MainDllLoader::RelaunchChromeBrowserWithNewCommandLineIfNeeded() {
253 RelaunchChromeBrowserWithNewCommandLineIfNeededFunc relaunch_function
=
254 reinterpret_cast<RelaunchChromeBrowserWithNewCommandLineIfNeededFunc
>(
255 ::GetProcAddress(dll_
,
256 "RelaunchChromeBrowserWithNewCommandLineIfNeeded"));
257 if (!relaunch_function
) {
258 LOG(ERROR
) << "Could not find exported function "
259 << "RelaunchChromeBrowserWithNewCommandLineIfNeeded";
265 //=============================================================================
267 class ChromeDllLoader
: public MainDllLoader
{
269 // MainDllLoader implementation.
270 void OnBeforeLaunch(const std::string
& process_type
,
271 const base::FilePath
& dll_path
) override
;
272 int OnBeforeExit(int return_code
, const base::FilePath
& dll_path
) override
;
275 scoped_ptr
<ChromeWatcherClient
> chrome_watcher_client_
;
276 #if defined(SYZYASAN)
277 scoped_ptr
<KaskoClient
> kasko_client_
;
281 void ChromeDllLoader::OnBeforeLaunch(const std::string
& process_type
,
282 const base::FilePath
& dll_path
) {
283 if (process_type
.empty()) {
284 RecordDidRun(dll_path
);
286 // Launch the watcher process if stats collection consent has been granted.
287 if (g_chrome_crash_client
.Get().GetCollectStatsConsent()) {
288 base::FilePath exe_path
;
289 if (PathService::Get(base::FILE_EXE
, &exe_path
)) {
290 chrome_watcher_client_
.reset(new ChromeWatcherClient(
291 base::Bind(&GenerateChromeWatcherCommandLine
, exe_path
)));
292 if (chrome_watcher_client_
->LaunchWatcher()) {
293 #if defined(SYZYASAN)
294 kasko_client_
.reset(new KaskoClient(chrome_watcher_client_
.get()));
302 int ChromeDllLoader::OnBeforeExit(int return_code
,
303 const base::FilePath
& dll_path
) {
304 // NORMAL_EXIT_CANCEL is used for experiments when the user cancels
305 // so we need to reset the did_run signal so omaha does not count
306 // this run as active usage.
307 if (chrome::RESULT_CODE_NORMAL_EXIT_CANCEL
== return_code
) {
308 ClearDidRun(dll_path
);
311 #if defined(SYZYASAN)
312 kasko_client_
.reset();
314 chrome_watcher_client_
.reset();
319 //=============================================================================
321 class ChromiumDllLoader
: public MainDllLoader
{
323 void OnBeforeLaunch(const std::string
& process_type
,
324 const base::FilePath
& dll_path
) override
{}
325 int OnBeforeExit(int return_code
, const base::FilePath
& dll_path
) override
{
330 MainDllLoader
* MakeMainDllLoader() {
331 #if defined(GOOGLE_CHROME_BUILD)
332 return new ChromeDllLoader();
334 return new ChromiumDllLoader();