Unregister from GCM when the only GCM app is removed
[chromium-blink-merge.git] / chrome / app / client_util.cc
blob738ae9e2d314a608a3dec05d6d8c02293ad5e784
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/environment.h"
11 #include "base/file_version_info.h"
12 #include "base/lazy_instance.h"
13 #include "base/logging.h"
14 #include "base/memory/scoped_ptr.h"
15 #include "base/strings/string16.h"
16 #include "base/strings/string_util.h"
17 #include "base/strings/stringprintf.h"
18 #include "base/strings/utf_string_conversions.h"
19 #include "base/trace_event/trace_event.h"
20 #include "base/version.h"
21 #include "base/win/scoped_handle.h"
22 #include "base/win/windows_version.h"
23 #include "chrome/app/chrome_crash_reporter_client.h"
24 #include "chrome/app/chrome_watcher_client_win.h"
25 #include "chrome/app/chrome_watcher_command_line_win.h"
26 #include "chrome/app/client_util.h"
27 #include "chrome/app/image_pre_reader_win.h"
28 #include "chrome/chrome_watcher/chrome_watcher_main_api.h"
29 #include "chrome/common/chrome_constants.h"
30 #include "chrome/common/chrome_result_codes.h"
31 #include "chrome/common/chrome_switches.h"
32 #include "chrome/common/env_vars.h"
33 #include "chrome/installer/util/google_update_constants.h"
34 #include "chrome/installer/util/google_update_settings.h"
35 #include "chrome/installer/util/install_util.h"
36 #include "chrome/installer/util/util_constants.h"
37 #include "components/crash/app/breakpad_win.h"
38 #include "components/crash/app/crash_reporter_client.h"
39 #include "components/metrics/client_info.h"
40 #include "content/public/app/startup_helper_win.h"
41 #include "sandbox/win/src/sandbox.h"
43 namespace {
44 // The entry point signature of chrome.dll.
45 typedef int (*DLL_MAIN)(HINSTANCE, sandbox::SandboxInterfaceInfo*);
47 typedef void (*RelaunchChromeBrowserWithNewCommandLineIfNeededFunc)();
49 base::LazyInstance<chrome::ChromeCrashReporterClient>::Leaky
50 g_chrome_crash_client = LAZY_INSTANCE_INITIALIZER;
52 // Loads |module| after setting the CWD to |module|'s directory. Returns a
53 // reference to the loaded module on success, or null on error.
54 HMODULE LoadModuleWithDirectory(const base::FilePath& module, bool pre_read) {
55 ::SetCurrentDirectoryW(module.DirName().value().c_str());
57 if (pre_read) {
58 // We pre-read the binary to warm the memory caches (fewer hard faults to
59 // page parts of the binary in).
60 const size_t kStepSize = 1024 * 1024;
61 size_t percent = 100;
62 ImagePreReader::PartialPreReadImage(module.value().c_str(), percent,
63 kStepSize);
66 return ::LoadLibraryExW(module.value().c_str(), nullptr,
67 LOAD_WITH_ALTERED_SEARCH_PATH);
70 void RecordDidRun(const base::FilePath& dll_path) {
71 bool system_level = !InstallUtil::IsPerUserInstall(dll_path);
72 GoogleUpdateSettings::UpdateDidRunState(true, system_level);
75 void ClearDidRun(const base::FilePath& dll_path) {
76 bool system_level = !InstallUtil::IsPerUserInstall(dll_path);
77 GoogleUpdateSettings::UpdateDidRunState(false, system_level);
80 bool InMetroMode() {
81 return (wcsstr(
82 ::GetCommandLineW(), L" -ServerName:DefaultBrowserServer") != nullptr);
85 typedef int (*InitMetro)();
87 // Returns the directory in which the currently running executable resides.
88 base::FilePath GetExecutableDir() {
89 base::char16 path[MAX_PATH];
90 ::GetModuleFileNameW(nullptr, path, MAX_PATH);
91 return base::FilePath(path).DirName();
94 } // namespace
96 base::string16 GetCurrentModuleVersion() {
97 scoped_ptr<FileVersionInfo> file_version_info(
98 FileVersionInfo::CreateFileVersionInfoForCurrentModule());
99 if (file_version_info.get()) {
100 base::string16 version_string(file_version_info->file_version());
101 if (Version(base::UTF16ToASCII(version_string)).IsValid())
102 return version_string;
104 return base::string16();
107 //=============================================================================
109 MainDllLoader::MainDllLoader()
110 : dll_(nullptr), metro_mode_(InMetroMode()) {
113 MainDllLoader::~MainDllLoader() {
116 // Loading chrome is an interesting affair. First we try loading from the
117 // current directory to support run-what-you-compile and other development
118 // scenarios.
119 // If that fails then we look at the version resource in the current
120 // module. This is the expected path for chrome.exe browser instances in an
121 // installed build.
122 HMODULE MainDllLoader::Load(base::string16* version, base::FilePath* module) {
123 const base::char16* dll_name = nullptr;
124 if (metro_mode_) {
125 dll_name = installer::kChromeMetroDll;
126 } else if (process_type_ == "service" || process_type_.empty()) {
127 dll_name = installer::kChromeDll;
128 } else if (process_type_ == "watcher") {
129 dll_name = kChromeWatcherDll;
130 } else {
131 #if defined(CHROME_MULTIPLE_DLL)
132 dll_name = installer::kChromeChildDll;
133 #else
134 dll_name = installer::kChromeDll;
135 #endif
138 const bool pre_read = !metro_mode_;
139 base::FilePath module_dir = GetExecutableDir();
140 *module = module_dir.Append(dll_name);
141 HMODULE dll = LoadModuleWithDirectory(*module, pre_read);
142 if (!dll) {
143 base::string16 version_string(GetCurrentModuleVersion());
144 if (version_string.empty()) {
145 LOG(ERROR) << "No valid Chrome version found";
146 return nullptr;
148 *version = version_string;
149 *module = module_dir.Append(version_string).Append(dll_name);
150 dll = LoadModuleWithDirectory(*module, pre_read);
151 if (!dll) {
152 PLOG(ERROR) << "Failed to load Chrome DLL from " << module->value();
153 return nullptr;
157 DCHECK(dll);
158 return dll;
161 // Launching is a matter of loading the right dll, setting the CHROME_VERSION
162 // environment variable and just calling the entry point. Derived classes can
163 // add custom code in the OnBeforeLaunch callback.
164 int MainDllLoader::Launch(HINSTANCE instance) {
165 const base::CommandLine& cmd_line = *base::CommandLine::ForCurrentProcess();
166 process_type_ = cmd_line.GetSwitchValueASCII(switches::kProcessType);
168 base::string16 version;
169 base::FilePath file;
171 if (metro_mode_) {
172 HMODULE metro_dll = Load(&version, &file);
173 if (!metro_dll)
174 return chrome::RESULT_CODE_MISSING_DATA;
176 InitMetro chrome_metro_main =
177 reinterpret_cast<InitMetro>(::GetProcAddress(metro_dll, "InitMetro"));
178 return chrome_metro_main();
181 if (process_type_ == "watcher") {
182 base::win::ScopedHandle parent_process;
183 base::win::ScopedHandle on_initialized_event;
184 if (!InterpretChromeWatcherCommandLine(cmd_line, &parent_process,
185 &on_initialized_event)) {
186 return chrome::RESULT_CODE_UNSUPPORTED_PARAM;
189 // Intentionally leaked.
190 HMODULE watcher_dll = Load(&version, &file);
191 if (!watcher_dll)
192 return chrome::RESULT_CODE_MISSING_DATA;
194 ChromeWatcherMainFunction watcher_main =
195 reinterpret_cast<ChromeWatcherMainFunction>(
196 ::GetProcAddress(watcher_dll, kChromeWatcherDLLEntrypoint));
197 return watcher_main(chrome::kBrowserExitCodesRegistryPath,
198 parent_process.Take(), on_initialized_event.Take());
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::FilePath& dll_path) override;
253 int OnBeforeExit(int return_code, const base::FilePath& dll_path) override;
256 void ChromeDllLoader::OnBeforeLaunch(const std::string& process_type,
257 const base::FilePath& dll_path) {
258 if (process_type.empty()) {
259 RecordDidRun(dll_path);
261 // Launch the watcher process if stats collection consent has been granted.
262 if (g_chrome_crash_client.Get().GetCollectStatsConsent()) {
263 base::char16 exe_path[MAX_PATH];
264 ::GetModuleFileNameW(nullptr, exe_path, arraysize(exe_path));
265 ChromeWatcherClient watcher_client(base::Bind(
266 &GenerateChromeWatcherCommandLine, base::FilePath(exe_path)));
267 watcher_client.LaunchWatcher();
272 int ChromeDllLoader::OnBeforeExit(int return_code,
273 const base::FilePath& dll_path) {
274 // NORMAL_EXIT_CANCEL is used for experiments when the user cancels
275 // so we need to reset the did_run signal so omaha does not count
276 // this run as active usage.
277 if (chrome::RESULT_CODE_NORMAL_EXIT_CANCEL == return_code) {
278 ClearDidRun(dll_path);
280 return return_code;
283 //=============================================================================
285 class ChromiumDllLoader : public MainDllLoader {
286 protected:
287 void OnBeforeLaunch(const std::string& process_type,
288 const base::FilePath& dll_path) override {}
289 int OnBeforeExit(int return_code, const base::FilePath& dll_path) override {
290 return return_code;
294 MainDllLoader* MakeMainDllLoader() {
295 #if defined(GOOGLE_CHROME_BUILD)
296 return new ChromeDllLoader();
297 #else
298 return new ChromiumDllLoader();
299 #endif