Apply _RELATIVE relocations ahead of others.
[chromium-blink-merge.git] / content / browser / browser_main_runner.cc
blob4a74b6eb5f828130b17bdead0497b5f4e13e14f2
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 "content/public/browser/browser_main_runner.h"
7 #include "base/allocator/allocator_shim.h"
8 #include "base/base_switches.h"
9 #include "base/command_line.h"
10 #include "base/debug/leak_annotations.h"
11 #include "base/debug/trace_event.h"
12 #include "base/logging.h"
13 #include "base/metrics/histogram.h"
14 #include "base/metrics/statistics_recorder.h"
15 #include "content/browser/browser_main_loop.h"
16 #include "content/browser/browser_shutdown_profile_dumper.h"
17 #include "content/browser/notification_service_impl.h"
18 #include "content/public/common/content_switches.h"
19 #include "content/public/common/main_function_params.h"
20 #include "ui/base/ime/input_method_initializer.h"
22 #if defined(OS_WIN)
23 #include <dwrite.h>
24 #include "base/win/win_util.h"
25 #include "base/win/windows_version.h"
26 #include "net/cert/sha256_legacy_support_win.h"
27 #include "sandbox/win/src/sidestep/preamble_patcher.h"
28 #include "skia/ext/fontmgr_default_win.h"
29 #include "third_party/skia/include/ports/SkFontMgr.h"
30 #include "third_party/skia/include/ports/SkTypeface_win.h"
31 #include "ui/base/win/scoped_ole_initializer.h"
32 #include "ui/gfx/platform_font_win.h"
33 #include "ui/gfx/switches.h"
34 #include "ui/gfx/win/direct_write.h"
35 #endif
37 bool g_exited_main_message_loop = false;
39 namespace content {
41 #if defined(OS_WIN)
42 namespace {
44 // Pointer to the original CryptVerifyCertificateSignatureEx function.
45 net::sha256_interception::CryptVerifyCertificateSignatureExFunc
46 g_real_crypt_verify_signature_stub = NULL;
48 // Stub function that is called whenever the Crypt32 function
49 // CryptVerifyCertificateSignatureEx is called. It just defers to net to perform
50 // the actual verification.
51 BOOL WINAPI CryptVerifyCertificateSignatureExStub(
52 HCRYPTPROV_LEGACY provider,
53 DWORD encoding_type,
54 DWORD subject_type,
55 void* subject_data,
56 DWORD issuer_type,
57 void* issuer_data,
58 DWORD flags,
59 void* extra) {
60 return net::sha256_interception::CryptVerifyCertificateSignatureExHook(
61 g_real_crypt_verify_signature_stub, provider, encoding_type, subject_type,
62 subject_data, issuer_type, issuer_data, flags, extra);
65 // If necessary, install an interception
66 void InstallSha256LegacyHooks() {
67 #if defined(_WIN64)
68 // Interception on x64 is not supported.
69 return;
70 #else
71 if (base::win::MaybeHasSHA256Support())
72 return;
74 net::sha256_interception::CryptVerifyCertificateSignatureExFunc
75 cert_verify_signature_ptr = reinterpret_cast<
76 net::sha256_interception::CryptVerifyCertificateSignatureExFunc>(
77 ::GetProcAddress(::GetModuleHandle(L"crypt32.dll"),
78 "CryptVerifyCertificateSignatureEx"));
79 CHECK(cert_verify_signature_ptr);
81 DWORD old_protect = 0;
82 if (!::VirtualProtect(cert_verify_signature_ptr, 5, PAGE_EXECUTE_READWRITE,
83 &old_protect)) {
84 return;
87 g_real_crypt_verify_signature_stub =
88 reinterpret_cast<
89 net::sha256_interception::CryptVerifyCertificateSignatureExFunc>(
90 VirtualAllocEx(::GetCurrentProcess(), NULL,
91 sidestep::kMaxPreambleStubSize, MEM_COMMIT,
92 PAGE_EXECUTE_READWRITE));
93 if (g_real_crypt_verify_signature_stub == NULL) {
94 CHECK(::VirtualProtect(cert_verify_signature_ptr, 5, old_protect,
95 &old_protect));
96 return;
99 sidestep::SideStepError patch_result =
100 sidestep::PreamblePatcher::Patch(
101 cert_verify_signature_ptr, CryptVerifyCertificateSignatureExStub,
102 g_real_crypt_verify_signature_stub, sidestep::kMaxPreambleStubSize);
103 if (patch_result != sidestep::SIDESTEP_SUCCESS) {
104 CHECK(::VirtualFreeEx(::GetCurrentProcess(),
105 g_real_crypt_verify_signature_stub, 0,
106 MEM_RELEASE));
107 CHECK(::VirtualProtect(cert_verify_signature_ptr, 5, old_protect,
108 &old_protect));
109 return;
112 DWORD dummy = 0;
113 CHECK(::VirtualProtect(cert_verify_signature_ptr, 5, old_protect, &dummy));
114 CHECK(::VirtualProtect(g_real_crypt_verify_signature_stub,
115 sidestep::kMaxPreambleStubSize, old_protect,
116 &old_protect));
117 #endif // _WIN64
120 void MaybeEnableDirectWriteFontRendering() {
121 if (gfx::win::ShouldUseDirectWrite() &&
122 CommandLine::ForCurrentProcess()->HasSwitch(
123 switches::kEnableDirectWriteForUI) &&
124 !CommandLine::ForCurrentProcess()->HasSwitch(
125 switches::kDisableHarfBuzzRenderText)) {
126 typedef decltype(DWriteCreateFactory)* DWriteCreateFactoryProc;
127 HMODULE dwrite_dll = LoadLibraryW(L"dwrite.dll");
128 if (!dwrite_dll)
129 return;
131 DWriteCreateFactoryProc dwrite_create_factory_proc =
132 reinterpret_cast<DWriteCreateFactoryProc>(
133 GetProcAddress(dwrite_dll, "DWriteCreateFactory"));
134 // Not finding the DWriteCreateFactory function indicates a corrupt dll.
135 CHECK(dwrite_create_factory_proc);
137 IDWriteFactory* factory = NULL;
139 CHECK(SUCCEEDED(
140 dwrite_create_factory_proc(DWRITE_FACTORY_TYPE_SHARED,
141 __uuidof(IDWriteFactory),
142 reinterpret_cast<IUnknown**>(&factory))));
143 SetDefaultSkiaFactory(SkFontMgr_New_DirectWrite(factory));
144 gfx::PlatformFontWin::set_use_skia_for_font_metrics(true);
148 } // namespace
150 #endif // OS_WIN
152 class BrowserMainRunnerImpl : public BrowserMainRunner {
153 public:
154 BrowserMainRunnerImpl()
155 : initialization_started_(false), is_shutdown_(false) {}
157 ~BrowserMainRunnerImpl() override {
158 if (initialization_started_ && !is_shutdown_)
159 Shutdown();
162 int Initialize(const MainFunctionParams& parameters) override {
163 TRACE_EVENT0("startup", "BrowserMainRunnerImpl::Initialize");
164 // On Android we normally initialize the browser in a series of UI thread
165 // tasks. While this is happening a second request can come from the OS or
166 // another application to start the browser. If this happens then we must
167 // not run these parts of initialization twice.
168 if (!initialization_started_) {
169 initialization_started_ = true;
171 #if !defined(OS_IOS)
172 if (parameters.command_line.HasSwitch(switches::kWaitForDebugger))
173 base::debug::WaitForDebugger(60, true);
174 #endif
176 #if defined(OS_WIN)
177 if (base::win::GetVersion() < base::win::VERSION_VISTA) {
178 // When "Extend support of advanced text services to all programs"
179 // (a.k.a. Cicero Unaware Application Support; CUAS) is enabled on
180 // Windows XP and handwriting modules shipped with Office 2003 are
181 // installed, "penjpn.dll" and "skchui.dll" will be loaded and then
182 // crash unless a user installs Office 2003 SP3. To prevent these
183 // modules from being loaded, disable TSF entirely. crbug.com/160914.
184 // TODO(yukawa): Add a high-level wrapper for this instead of calling
185 // Win32 API here directly.
186 ImmDisableTextFrameService(static_cast<DWORD>(-1));
188 InstallSha256LegacyHooks();
189 #endif // OS_WIN
191 base::StatisticsRecorder::Initialize();
193 notification_service_.reset(new NotificationServiceImpl);
195 #if defined(OS_WIN)
196 // Ole must be initialized before starting message pump, so that TSF
197 // (Text Services Framework) module can interact with the message pump
198 // on Windows 8 Metro mode.
199 ole_initializer_.reset(new ui::ScopedOleInitializer);
200 // Enable DirectWrite font rendering if needed.
201 MaybeEnableDirectWriteFontRendering();
202 #endif // OS_WIN
204 main_loop_.reset(new BrowserMainLoop(parameters));
206 main_loop_->Init();
208 main_loop_->EarlyInitialization();
210 // Must happen before we try to use a message loop or display any UI.
211 if (!main_loop_->InitializeToolkit())
212 return 1;
214 main_loop_->MainMessageLoopStart();
216 // WARNING: If we get a WM_ENDSESSION, objects created on the stack here
217 // are NOT deleted. If you need something to run during WM_ENDSESSION add it
218 // to browser_shutdown::Shutdown or BrowserProcess::EndSession.
220 #if defined(OS_WIN) && !defined(NO_TCMALLOC)
221 // When linking shared libraries, NO_TCMALLOC is defined, and dynamic
222 // allocator selection is not supported.
224 // Make this call before going multithreaded, or spawning any
225 // subprocesses.
226 base::allocator::SetupSubprocessAllocator();
227 #endif
228 ui::InitializeInputMethod();
230 main_loop_->CreateStartupTasks();
231 int result_code = main_loop_->GetResultCode();
232 if (result_code > 0)
233 return result_code;
235 // Return -1 to indicate no early termination.
236 return -1;
239 int Run() override {
240 DCHECK(initialization_started_);
241 DCHECK(!is_shutdown_);
242 main_loop_->RunMainMessageLoopParts();
243 return main_loop_->GetResultCode();
246 void Shutdown() override {
247 DCHECK(initialization_started_);
248 DCHECK(!is_shutdown_);
249 #ifdef LEAK_SANITIZER
250 // Invoke leak detection now, to avoid dealing with shutdown-only leaks.
251 // Normally this will have already happened in
252 // BroserProcessImpl::ReleaseModule(), so this call has no effect. This is
253 // only for processes which do not instantiate a BrowserProcess.
254 // If leaks are found, the process will exit here.
255 __lsan_do_leak_check();
256 #endif
257 // If startup tracing has not been finished yet, replace it's dumper
258 // with special version, which would save trace file on exit (i.e.
259 // startup tracing becomes a version of shutdown tracing).
260 scoped_ptr<BrowserShutdownProfileDumper> startup_profiler;
261 if (main_loop_->is_tracing_startup()) {
262 main_loop_->StopStartupTracingTimer();
263 if (main_loop_->startup_trace_file() !=
264 base::FilePath().AppendASCII("none")) {
265 startup_profiler.reset(
266 new BrowserShutdownProfileDumper(main_loop_->startup_trace_file()));
270 // The shutdown tracing got enabled in AttemptUserExit earlier, but someone
271 // needs to write the result to disc. For that a dumper needs to get created
272 // which will dump the traces to disc when it gets destroyed.
273 const base::CommandLine& command_line =
274 *base::CommandLine::ForCurrentProcess();
275 scoped_ptr<BrowserShutdownProfileDumper> shutdown_profiler;
276 if (command_line.HasSwitch(switches::kTraceShutdown)) {
277 shutdown_profiler.reset(new BrowserShutdownProfileDumper(
278 BrowserShutdownProfileDumper::GetShutdownProfileFileName()));
282 // The trace event has to stay between profiler creation and destruction.
283 TRACE_EVENT0("shutdown", "BrowserMainRunner");
284 g_exited_main_message_loop = true;
286 main_loop_->ShutdownThreadsAndCleanUp();
288 ui::ShutdownInputMethod();
289 #if defined(OS_WIN)
290 ole_initializer_.reset(NULL);
291 #endif
292 #if defined(OS_ANDROID)
293 // Forcefully terminates the RunLoop inside MessagePumpForUI, ensuring
294 // proper shutdown for content_browsertests. Shutdown() is not used by
295 // the actual browser.
296 base::MessageLoop::current()->QuitNow();
297 #endif
298 main_loop_.reset(NULL);
300 notification_service_.reset(NULL);
302 is_shutdown_ = true;
306 protected:
307 // True if we have started to initialize the runner.
308 bool initialization_started_;
310 // True if the runner has been shut down.
311 bool is_shutdown_;
313 scoped_ptr<NotificationServiceImpl> notification_service_;
314 scoped_ptr<BrowserMainLoop> main_loop_;
315 #if defined(OS_WIN)
316 scoped_ptr<ui::ScopedOleInitializer> ole_initializer_;
317 #endif
319 DISALLOW_COPY_AND_ASSIGN(BrowserMainRunnerImpl);
322 // static
323 BrowserMainRunner* BrowserMainRunner::Create() {
324 return new BrowserMainRunnerImpl();
327 } // namespace content