Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / chrome / app / client_util.cc
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.
4
5 #include <windows.h>
6 #include <shlwapi.h>
7
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/crash/app/breakpad_win.h"
34 #include "components/crash/app/crash_reporter_client.h"
35 #include "components/metrics/client_info.h"
36 #include "content/public/app/startup_helper_win.h"
37 #include "sandbox/win/src/sandbox.h"
38
39 namespace {
40 // The entry point signature of chrome.dll.
41 typedef int (*DLL_MAIN)(HINSTANCE, sandbox::SandboxInterfaceInfo*);
42
43 typedef void (*RelaunchChromeBrowserWithNewCommandLineIfNeededFunc)();
44
45 base::LazyInstance<chrome::ChromeCrashReporterClient>::Leaky
46     g_chrome_crash_client = LAZY_INSTANCE_INITIALIZER;
47
48 // Expects that |dir| has a trailing backslash. |dir| is modified so it
49 // contains the full path that was tried. Caller must check for the return
50 // value not being null to determine if this path contains a valid dll.
51 HMODULE LoadModuleWithDirectory(base::string16* dir,
52                                 const wchar_t* dll_name,
53                                 bool pre_read) {
54   ::SetCurrentDirectoryW(dir->c_str());
55   dir->append(dll_name);
56
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(dir->c_str(), percent, kStepSize);
63   }
64
65   return ::LoadLibraryExW(dir->c_str(), NULL,
66                           LOAD_WITH_ALTERED_SEARCH_PATH);
67 }
68
69 void RecordDidRun(const base::string16& dll_path) {
70   bool system_level = !InstallUtil::IsPerUserInstall(dll_path.c_str());
71   GoogleUpdateSettings::UpdateDidRunState(true, system_level);
72 }
73
74 void ClearDidRun(const base::string16& dll_path) {
75   bool system_level = !InstallUtil::IsPerUserInstall(dll_path.c_str());
76   GoogleUpdateSettings::UpdateDidRunState(false, system_level);
77 }
78
79 bool InMetroMode() {
80   return (wcsstr(
81       ::GetCommandLineW(), L" -ServerName:DefaultBrowserServer") != NULL);
82 }
83
84 typedef int (*InitMetro)();
85
86 }  // namespace
87
88 base::string16 GetExecutablePath() {
89   wchar_t path[MAX_PATH];
90   ::GetModuleFileNameW(NULL, path, MAX_PATH);
91   if (!::PathRemoveFileSpecW(path))
92     return base::string16();
93   base::string16 exe_path(path);
94   return exe_path.append(1, L'\\');
95 }
96
97 base::string16 GetCurrentModuleVersion() {
98   scoped_ptr<FileVersionInfo> file_version_info(
99       FileVersionInfo::CreateFileVersionInfoForCurrentModule());
100   if (file_version_info.get()) {
101     base::string16 version_string(file_version_info->file_version());
102     if (Version(base::UTF16ToASCII(version_string)).IsValid())
103       return version_string;
104   }
105   return base::string16();
106 }
107
108 //=============================================================================
109
110 MainDllLoader::MainDllLoader()
111   : dll_(NULL), metro_mode_(InMetroMode()) {
112 }
113
114 MainDllLoader::~MainDllLoader() {
115 }
116
117 // Loading chrome is an interesting affair. First we try loading from the
118 // current directory to support run-what-you-compile and other development
119 // scenarios.
120 // If that fails then we look at the version resource in the current
121 // module. This is the expected path for chrome.exe browser instances in an
122 // installed build.
123 HMODULE MainDllLoader::Load(base::string16* version,
124                             base::string16* out_file) {
125   const base::string16 executable_dir(GetExecutablePath());
126   *out_file = executable_dir;
127
128   const wchar_t* dll_name = metro_mode_ ?
129       installer::kChromeMetroDll :
130 #if !defined(CHROME_MULTIPLE_DLL)
131       installer::kChromeDll;
132 #else
133       (process_type_ == "service")  || process_type_.empty() ?
134           installer::kChromeDll :
135           installer::kChromeChildDll;
136 #endif
137   const bool pre_read = !metro_mode_;
138   HMODULE dll = LoadModuleWithDirectory(out_file, dll_name, pre_read);
139   if (!dll) {
140     base::string16 version_string(GetCurrentModuleVersion());
141     if (version_string.empty()) {
142       LOG(ERROR) << "No valid Chrome version found";
143       return NULL;
144     }
145     *out_file = executable_dir;
146     *version = version_string;
147     out_file->append(version_string).append(1, L'\\');
148     dll = LoadModuleWithDirectory(out_file, dll_name, pre_read);
149     if (!dll) {
150       PLOG(ERROR) << "Failed to load Chrome DLL from " << *out_file;
151       return NULL;
152     }
153   }
154
155   DCHECK(dll);
156   return dll;
157 }
158
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);
165
166   base::string16 version;
167   base::string16 file;
168
169   if (metro_mode_) {
170     HMODULE metro_dll = Load(&version, &file);
171     if (!metro_dll)
172       return chrome::RESULT_CODE_MISSING_DATA;
173
174     InitMetro chrome_metro_main =
175         reinterpret_cast<InitMetro>(::GetProcAddress(metro_dll, "InitMetro"));
176     return chrome_metro_main();
177   }
178
179   // Initialize the sandbox services.
180   sandbox::SandboxInterfaceInfo sandbox_info = {0};
181   content::InitializeSandboxInfo(&sandbox_info);
182
183   crash_reporter::SetCrashReporterClient(g_chrome_crash_client.Pointer());
184   bool exit_now = true;
185   if (process_type_.empty()) {
186     if (breakpad::ShowRestartDialogIfCrashed(&exit_now)) {
187       // We restarted because of a previous crash. Ask user if we should
188       // Relaunch. Only for the browser process. See crbug.com/132119.
189       if (exit_now)
190         return content::RESULT_CODE_NORMAL_EXIT;
191     }
192   }
193   breakpad::InitCrashReporter(process_type_);
194
195   dll_ = Load(&version, &file);
196   if (!dll_)
197     return chrome::RESULT_CODE_MISSING_DATA;
198
199   scoped_ptr<base::Environment> env(base::Environment::Create());
200   env->SetVar(chrome::kChromeVersionEnvVar, base::WideToUTF8(version));
201
202   OnBeforeLaunch(file);
203   DLL_MAIN chrome_main =
204       reinterpret_cast<DLL_MAIN>(::GetProcAddress(dll_, "ChromeMain"));
205   int rc = chrome_main(instance, &sandbox_info);
206   return OnBeforeExit(rc, file);
207 }
208
209 void MainDllLoader::RelaunchChromeBrowserWithNewCommandLineIfNeeded() {
210   if (!dll_)
211     return;
212
213   RelaunchChromeBrowserWithNewCommandLineIfNeededFunc relaunch_function =
214       reinterpret_cast<RelaunchChromeBrowserWithNewCommandLineIfNeededFunc>(
215           ::GetProcAddress(dll_,
216                            "RelaunchChromeBrowserWithNewCommandLineIfNeeded"));
217   if (!relaunch_function) {
218     LOG(ERROR) << "Could not find exported function "
219                << "RelaunchChromeBrowserWithNewCommandLineIfNeeded";
220   } else {
221     relaunch_function();
222   }
223 }
224
225 //=============================================================================
226
227 class ChromeDllLoader : public MainDllLoader {
228  protected:
229   virtual void OnBeforeLaunch(const base::string16& dll_path) {
230     RecordDidRun(dll_path);
231   }
232
233   virtual int OnBeforeExit(int return_code, const base::string16& dll_path) {
234     // NORMAL_EXIT_CANCEL is used for experiments when the user cancels
235     // so we need to reset the did_run signal so omaha does not count
236     // this run as active usage.
237     if (chrome::RESULT_CODE_NORMAL_EXIT_CANCEL == return_code) {
238       ClearDidRun(dll_path);
239     }
240     return return_code;
241   }
242 };
243
244 //=============================================================================
245
246 class ChromiumDllLoader : public MainDllLoader {
247  protected:
248   virtual void OnBeforeLaunch(const base::string16& dll_path) override {
249   }
250   virtual int OnBeforeExit(int return_code,
251                            const base::string16& dll_path) override {
252     return return_code;
253   }
254 };
255
256 MainDllLoader* MakeMainDllLoader() {
257 #if defined(GOOGLE_CHROME_BUILD)
258   return new ChromeDllLoader();
259 #else
260   return new ChromiumDllLoader();
261 #endif
262 }