Supervised user SafeSites: Add a field trial to turn on/off.
[chromium-blink-merge.git] / chrome / app / client_util.cc
blob1912b4f2881b1b39c3cf361aca06e3a5fcfc098f
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/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"
47 namespace {
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());
61 if (pre_read) {
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;
65 size_t percent = 100;
66 ImagePreReader::PartialPreReadImage(module.value().c_str(), percent,
67 kStepSize);
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);
84 bool InMetroMode() {
85 return (wcsstr(
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();
98 } // namespace
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
122 // scenarios.
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
125 // installed build.
126 HMODULE MainDllLoader::Load(base::string16* version, base::FilePath* module) {
127 const base::char16* dll_name = nullptr;
128 if (metro_mode_) {
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;
134 } else {
135 #if defined(CHROME_MULTIPLE_DLL)
136 dll_name = installer::kChromeChildDll;
137 #else
138 dll_name = installer::kChromeDll;
139 #endif
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);
146 if (!dll) {
147 base::string16 version_string(GetCurrentModuleVersion());
148 if (version_string.empty()) {
149 LOG(ERROR) << "No valid Chrome version found";
150 return nullptr;
152 *version = version_string;
153 *module = module_dir.Append(version_string).Append(dll_name);
154 dll = LoadModuleWithDirectory(*module, pre_read);
155 if (!dll) {
156 PLOG(ERROR) << "Failed to load Chrome DLL from " << module->value();
157 return nullptr;
161 DCHECK(dll);
162 return dll;
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;
173 base::FilePath file;
175 if (metro_mode_) {
176 HMODULE metro_dll = Load(&version, &file);
177 if (!metro_dll)
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);
201 if (!watcher_dll)
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.
222 if (exit_now)
223 return content::RESULT_CODE_NORMAL_EXIT;
226 breakpad::InitCrashReporter(process_type_);
228 dll_ = Load(&version, &file);
229 if (!dll_)
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
242 // processes.
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();
246 return rc;
249 void MainDllLoader::RelaunchChromeBrowserWithNewCommandLineIfNeeded() {
250 if (!dll_)
251 return;
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";
260 } else {
261 relaunch_function();
265 //=============================================================================
267 class ChromeDllLoader : public MainDllLoader {
268 protected:
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;
274 private:
275 scoped_ptr<ChromeWatcherClient> chrome_watcher_client_;
276 #if defined(KASKO)
277 scoped_ptr<KaskoClient> kasko_client_;
278 #endif // KASKO
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(KASKO)
294 kasko::api::MinidumpType minidump_type = kasko::api::SMALL_DUMP_TYPE;
295 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
296 switches::kFullMemoryCrashReport)) {
297 minidump_type = kasko::api::FULL_DUMP_TYPE;
298 } else {
299 bool is_per_user_install =
300 g_chrome_crash_client.Get().GetIsPerUserInstall(
301 base::FilePath(exe_path));
302 if (g_chrome_crash_client.Get().GetShouldDumpLargerDumps(
303 is_per_user_install)){
304 minidump_type = kasko::api::LARGER_DUMP_TYPE;
308 kasko_client_.reset(
309 new KaskoClient(chrome_watcher_client_.get(), minidump_type));
310 #endif // KASKO
317 int ChromeDllLoader::OnBeforeExit(int return_code,
318 const base::FilePath& dll_path) {
319 // NORMAL_EXIT_CANCEL is used for experiments when the user cancels
320 // so we need to reset the did_run signal so omaha does not count
321 // this run as active usage.
322 if (chrome::RESULT_CODE_NORMAL_EXIT_CANCEL == return_code) {
323 ClearDidRun(dll_path);
326 #if defined(KASKO)
327 kasko_client_.reset();
328 #endif // KASKO
329 chrome_watcher_client_.reset();
331 return return_code;
334 //=============================================================================
336 class ChromiumDllLoader : public MainDllLoader {
337 protected:
338 void OnBeforeLaunch(const std::string& process_type,
339 const base::FilePath& dll_path) override {}
340 int OnBeforeExit(int return_code, const base::FilePath& dll_path) override {
341 return return_code;
345 MainDllLoader* MakeMainDllLoader() {
346 #if defined(GOOGLE_CHROME_BUILD)
347 return new ChromeDllLoader();
348 #else
349 return new ChromiumDllLoader();
350 #endif