cc: Make picture pile base thread safe.
[chromium-blink-merge.git] / content / browser / browser_main_runner.cc
blob981ed02ba92494b5449b7691dfd779caa40b95ca
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 "base/win/win_util.h"
24 #include "base/win/windows_version.h"
25 #include "net/cert/sha256_legacy_support_win.h"
26 #include "sandbox/win/src/sidestep/preamble_patcher.h"
27 #include "skia/ext/fontmgr_default_win.h"
28 #include "third_party/skia/include/ports/SkFontMgr.h"
29 #include "third_party/skia/include/ports/SkTypeface_win.h"
30 #include "ui/base/win/scoped_ole_initializer.h"
31 #include "ui/gfx/switches.h"
32 #include "ui/gfx/win/direct_write.h"
33 #endif
35 bool g_exited_main_message_loop = false;
37 namespace content {
39 #if defined(OS_WIN)
40 namespace {
42 // Pointer to the original CryptVerifyCertificateSignatureEx function.
43 net::sha256_interception::CryptVerifyCertificateSignatureExFunc
44 g_real_crypt_verify_signature_stub = NULL;
46 // Stub function that is called whenever the Crypt32 function
47 // CryptVerifyCertificateSignatureEx is called. It just defers to net to perform
48 // the actual verification.
49 BOOL WINAPI CryptVerifyCertificateSignatureExStub(
50 HCRYPTPROV_LEGACY provider,
51 DWORD encoding_type,
52 DWORD subject_type,
53 void* subject_data,
54 DWORD issuer_type,
55 void* issuer_data,
56 DWORD flags,
57 void* extra) {
58 return net::sha256_interception::CryptVerifyCertificateSignatureExHook(
59 g_real_crypt_verify_signature_stub, provider, encoding_type, subject_type,
60 subject_data, issuer_type, issuer_data, flags, extra);
63 // If necessary, install an interception
64 void InstallSha256LegacyHooks() {
65 #if defined(_WIN64)
66 // Interception on x64 is not supported.
67 return;
68 #else
69 if (base::win::MaybeHasSHA256Support())
70 return;
72 net::sha256_interception::CryptVerifyCertificateSignatureExFunc
73 cert_verify_signature_ptr = reinterpret_cast<
74 net::sha256_interception::CryptVerifyCertificateSignatureExFunc>(
75 ::GetProcAddress(::GetModuleHandle(L"crypt32.dll"),
76 "CryptVerifyCertificateSignatureEx"));
77 CHECK(cert_verify_signature_ptr);
79 DWORD old_protect = 0;
80 if (!::VirtualProtect(cert_verify_signature_ptr, 5, PAGE_EXECUTE_READWRITE,
81 &old_protect)) {
82 return;
85 g_real_crypt_verify_signature_stub =
86 reinterpret_cast<
87 net::sha256_interception::CryptVerifyCertificateSignatureExFunc>(
88 VirtualAllocEx(::GetCurrentProcess(), NULL,
89 sidestep::kMaxPreambleStubSize, MEM_COMMIT,
90 PAGE_EXECUTE_READWRITE));
91 if (g_real_crypt_verify_signature_stub == NULL) {
92 CHECK(::VirtualProtect(cert_verify_signature_ptr, 5, old_protect,
93 &old_protect));
94 return;
97 sidestep::SideStepError patch_result =
98 sidestep::PreamblePatcher::Patch(
99 cert_verify_signature_ptr, CryptVerifyCertificateSignatureExStub,
100 g_real_crypt_verify_signature_stub, sidestep::kMaxPreambleStubSize);
101 if (patch_result != sidestep::SIDESTEP_SUCCESS) {
102 CHECK(::VirtualFreeEx(::GetCurrentProcess(),
103 g_real_crypt_verify_signature_stub, 0,
104 MEM_RELEASE));
105 CHECK(::VirtualProtect(cert_verify_signature_ptr, 5, old_protect,
106 &old_protect));
107 return;
110 DWORD dummy = 0;
111 CHECK(::VirtualProtect(cert_verify_signature_ptr, 5, old_protect, &dummy));
112 CHECK(::VirtualProtect(g_real_crypt_verify_signature_stub,
113 sidestep::kMaxPreambleStubSize, old_protect,
114 &old_protect));
115 #endif // _WIN64
118 void MaybeEnableDirectWriteFontRendering() {
119 if (gfx::win::ShouldUseDirectWrite() &&
120 CommandLine::ForCurrentProcess()->HasSwitch(
121 switches::kEnableDirectWriteForUI) &&
122 CommandLine::ForCurrentProcess()->HasSwitch(
123 switches::kEnableHarfBuzzRenderText)) {
124 SetDefaultSkiaFactory(SkFontMgr_New_DirectWrite(NULL));
128 } // namespace
130 #endif // OS_WIN
132 class BrowserMainRunnerImpl : public BrowserMainRunner {
133 public:
134 BrowserMainRunnerImpl()
135 : initialization_started_(false), is_shutdown_(false) {}
137 ~BrowserMainRunnerImpl() override {
138 if (initialization_started_ && !is_shutdown_)
139 Shutdown();
142 int Initialize(const MainFunctionParams& parameters) override {
143 TRACE_EVENT0("startup", "BrowserMainRunnerImpl::Initialize");
144 // On Android we normally initialize the browser in a series of UI thread
145 // tasks. While this is happening a second request can come from the OS or
146 // another application to start the browser. If this happens then we must
147 // not run these parts of initialization twice.
148 if (!initialization_started_) {
149 initialization_started_ = true;
151 #if !defined(OS_IOS)
152 if (parameters.command_line.HasSwitch(switches::kWaitForDebugger))
153 base::debug::WaitForDebugger(60, true);
154 #endif
156 #if defined(OS_WIN)
157 if (base::win::GetVersion() < base::win::VERSION_VISTA) {
158 // When "Extend support of advanced text services to all programs"
159 // (a.k.a. Cicero Unaware Application Support; CUAS) is enabled on
160 // Windows XP and handwriting modules shipped with Office 2003 are
161 // installed, "penjpn.dll" and "skchui.dll" will be loaded and then
162 // crash unless a user installs Office 2003 SP3. To prevent these
163 // modules from being loaded, disable TSF entirely. crbug.com/160914.
164 // TODO(yukawa): Add a high-level wrapper for this instead of calling
165 // Win32 API here directly.
166 ImmDisableTextFrameService(static_cast<DWORD>(-1));
168 InstallSha256LegacyHooks();
169 #endif // OS_WIN
171 base::StatisticsRecorder::Initialize();
173 notification_service_.reset(new NotificationServiceImpl);
175 #if defined(OS_WIN)
176 // Ole must be initialized before starting message pump, so that TSF
177 // (Text Services Framework) module can interact with the message pump
178 // on Windows 8 Metro mode.
179 ole_initializer_.reset(new ui::ScopedOleInitializer);
180 // Enable DirectWrite font rendering if needed.
181 MaybeEnableDirectWriteFontRendering();
182 #endif // OS_WIN
184 main_loop_.reset(new BrowserMainLoop(parameters));
186 main_loop_->Init();
188 main_loop_->EarlyInitialization();
190 // Must happen before we try to use a message loop or display any UI.
191 if (!main_loop_->InitializeToolkit())
192 return 1;
194 main_loop_->MainMessageLoopStart();
196 // WARNING: If we get a WM_ENDSESSION, objects created on the stack here
197 // are NOT deleted. If you need something to run during WM_ENDSESSION add it
198 // to browser_shutdown::Shutdown or BrowserProcess::EndSession.
200 #if defined(OS_WIN) && !defined(NO_TCMALLOC)
201 // When linking shared libraries, NO_TCMALLOC is defined, and dynamic
202 // allocator selection is not supported.
204 // Make this call before going multithreaded, or spawning any
205 // subprocesses.
206 base::allocator::SetupSubprocessAllocator();
207 #endif
208 ui::InitializeInputMethod();
210 main_loop_->CreateStartupTasks();
211 int result_code = main_loop_->GetResultCode();
212 if (result_code > 0)
213 return result_code;
215 // Return -1 to indicate no early termination.
216 return -1;
219 int Run() override {
220 DCHECK(initialization_started_);
221 DCHECK(!is_shutdown_);
222 main_loop_->RunMainMessageLoopParts();
223 return main_loop_->GetResultCode();
226 void Shutdown() override {
227 DCHECK(initialization_started_);
228 DCHECK(!is_shutdown_);
229 #ifdef LEAK_SANITIZER
230 // Invoke leak detection now, to avoid dealing with shutdown-only leaks.
231 // Normally this will have already happened in
232 // BroserProcessImpl::ReleaseModule(), so this call has no effect. This is
233 // only for processes which do not instantiate a BrowserProcess.
234 // If leaks are found, the process will exit here.
235 __lsan_do_leak_check();
236 #endif
237 // If startup tracing has not been finished yet, replace it's dumper
238 // with special version, which would save trace file on exit (i.e.
239 // startup tracing becomes a version of shutdown tracing).
240 scoped_ptr<BrowserShutdownProfileDumper> startup_profiler;
241 if (main_loop_->is_tracing_startup()) {
242 main_loop_->StopStartupTracingTimer();
243 if (main_loop_->startup_trace_file() !=
244 base::FilePath().AppendASCII("none")) {
245 startup_profiler.reset(
246 new BrowserShutdownProfileDumper(main_loop_->startup_trace_file()));
250 // The shutdown tracing got enabled in AttemptUserExit earlier, but someone
251 // needs to write the result to disc. For that a dumper needs to get created
252 // which will dump the traces to disc when it gets destroyed.
253 const base::CommandLine& command_line =
254 *base::CommandLine::ForCurrentProcess();
255 scoped_ptr<BrowserShutdownProfileDumper> shutdown_profiler;
256 if (command_line.HasSwitch(switches::kTraceShutdown)) {
257 shutdown_profiler.reset(new BrowserShutdownProfileDumper(
258 BrowserShutdownProfileDumper::GetShutdownProfileFileName()));
262 // The trace event has to stay between profiler creation and destruction.
263 TRACE_EVENT0("shutdown", "BrowserMainRunner");
264 g_exited_main_message_loop = true;
266 main_loop_->ShutdownThreadsAndCleanUp();
268 ui::ShutdownInputMethod();
269 #if defined(OS_WIN)
270 ole_initializer_.reset(NULL);
271 #endif
272 #if defined(OS_ANDROID)
273 // Forcefully terminates the RunLoop inside MessagePumpForUI, ensuring
274 // proper shutdown for content_browsertests. Shutdown() is not used by
275 // the actual browser.
276 base::MessageLoop::current()->QuitNow();
277 #endif
278 main_loop_.reset(NULL);
280 notification_service_.reset(NULL);
282 is_shutdown_ = true;
286 protected:
287 // True if we have started to initialize the runner.
288 bool initialization_started_;
290 // True if the runner has been shut down.
291 bool is_shutdown_;
293 scoped_ptr<NotificationServiceImpl> notification_service_;
294 scoped_ptr<BrowserMainLoop> main_loop_;
295 #if defined(OS_WIN)
296 scoped_ptr<ui::ScopedOleInitializer> ole_initializer_;
297 #endif
299 DISALLOW_COPY_AND_ASSIGN(BrowserMainRunnerImpl);
302 // static
303 BrowserMainRunner* BrowserMainRunner::Create() {
304 return new BrowserMainRunnerImpl();
307 } // namespace content