Roll src/third_party/WebKit d9c6159:8139f33 (svn 201974:201975)
[chromium-blink-merge.git] / content / browser / browser_main_runner.cc
blob8ab69d9f64ffcff8e2c84d494169ab6b6127f74d
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/base_switches.h"
8 #include "base/command_line.h"
9 #include "base/debug/leak_annotations.h"
10 #include "base/logging.h"
11 #include "base/metrics/histogram.h"
12 #include "base/metrics/statistics_recorder.h"
13 #include "base/profiler/scoped_profile.h"
14 #include "base/profiler/scoped_tracker.h"
15 #include "base/trace_event/trace_event.h"
16 #include "base/tracked_objects.h"
17 #include "components/tracing/trace_config_file.h"
18 #include "components/tracing/tracing_switches.h"
19 #include "content/browser/browser_main_loop.h"
20 #include "content/browser/browser_shutdown_profile_dumper.h"
21 #include "content/browser/notification_service_impl.h"
22 #include "content/public/browser/tracing_controller.h"
23 #include "content/public/common/content_switches.h"
24 #include "content/public/common/main_function_params.h"
25 #include "ui/base/ime/input_method_initializer.h"
27 #if defined(OS_ANDROID)
28 #include "content/browser/android/tracing_controller_android.h"
29 #endif
31 #if defined(OS_WIN)
32 #include "base/win/win_util.h"
33 #include "base/win/windows_version.h"
34 #include "net/cert/sha256_legacy_support_win.h"
35 #include "sandbox/win/src/sidestep/preamble_patcher.h"
36 #include "ui/base/win/scoped_ole_initializer.h"
37 #include "ui/gfx/switches.h"
38 #include "ui/gfx/win/direct_write.h"
39 #endif
41 namespace content {
43 namespace {
45 bool g_exited_main_message_loop = false;
47 #if defined(OS_WIN)
48 #if !defined(_WIN64)
49 // Pointer to the original CryptVerifyCertificateSignatureEx function.
50 net::sha256_interception::CryptVerifyCertificateSignatureExFunc
51 g_real_crypt_verify_signature_stub = NULL;
53 // Stub function that is called whenever the Crypt32 function
54 // CryptVerifyCertificateSignatureEx is called. It just defers to net to perform
55 // the actual verification.
56 BOOL WINAPI CryptVerifyCertificateSignatureExStub(
57 HCRYPTPROV_LEGACY provider,
58 DWORD encoding_type,
59 DWORD subject_type,
60 void* subject_data,
61 DWORD issuer_type,
62 void* issuer_data,
63 DWORD flags,
64 void* extra) {
65 return net::sha256_interception::CryptVerifyCertificateSignatureExHook(
66 g_real_crypt_verify_signature_stub, provider, encoding_type, subject_type,
67 subject_data, issuer_type, issuer_data, flags, extra);
69 #endif // !defined(_WIN64)
71 // If necessary, install an interception
72 void InstallSha256LegacyHooks() {
73 #if defined(_WIN64)
74 // Interception on x64 is not supported.
75 return;
76 #else
77 if (base::win::MaybeHasSHA256Support())
78 return;
80 net::sha256_interception::CryptVerifyCertificateSignatureExFunc
81 cert_verify_signature_ptr = reinterpret_cast<
82 net::sha256_interception::CryptVerifyCertificateSignatureExFunc>(
83 ::GetProcAddress(::GetModuleHandle(L"crypt32.dll"),
84 "CryptVerifyCertificateSignatureEx"));
85 CHECK(cert_verify_signature_ptr);
87 DWORD old_protect = 0;
88 if (!::VirtualProtect(cert_verify_signature_ptr, 5, PAGE_EXECUTE_READWRITE,
89 &old_protect)) {
90 return;
93 g_real_crypt_verify_signature_stub =
94 reinterpret_cast<
95 net::sha256_interception::CryptVerifyCertificateSignatureExFunc>(
96 VirtualAllocEx(::GetCurrentProcess(), NULL,
97 sidestep::kMaxPreambleStubSize, MEM_COMMIT,
98 PAGE_EXECUTE_READWRITE));
99 if (g_real_crypt_verify_signature_stub == NULL) {
100 CHECK(::VirtualProtect(cert_verify_signature_ptr, 5, old_protect,
101 &old_protect));
102 return;
105 sidestep::SideStepError patch_result =
106 sidestep::PreamblePatcher::Patch(
107 cert_verify_signature_ptr, CryptVerifyCertificateSignatureExStub,
108 g_real_crypt_verify_signature_stub, sidestep::kMaxPreambleStubSize);
109 if (patch_result != sidestep::SIDESTEP_SUCCESS) {
110 CHECK(::VirtualFreeEx(::GetCurrentProcess(),
111 g_real_crypt_verify_signature_stub, 0,
112 MEM_RELEASE));
113 CHECK(::VirtualProtect(cert_verify_signature_ptr, 5, old_protect,
114 &old_protect));
115 return;
118 DWORD dummy = 0;
119 CHECK(::VirtualProtect(cert_verify_signature_ptr, 5, old_protect, &dummy));
120 CHECK(::VirtualProtect(g_real_crypt_verify_signature_stub,
121 sidestep::kMaxPreambleStubSize, old_protect,
122 &old_protect));
123 #endif // _WIN64
125 #endif // OS_WIN
127 } // namespace
129 class BrowserMainRunnerImpl : public BrowserMainRunner {
130 public:
131 BrowserMainRunnerImpl()
132 : initialization_started_(false), is_shutdown_(false) {}
134 ~BrowserMainRunnerImpl() override {
135 if (initialization_started_ && !is_shutdown_)
136 Shutdown();
139 int Initialize(const MainFunctionParams& parameters) override {
140 // TODO(vadimt, yiyaoliu): Remove all tracked_objects references below once
141 // crbug.com/453640 is fixed.
142 tracked_objects::ThreadData::InitializeThreadContext("CrBrowserMain");
143 TRACK_SCOPED_REGION(
144 "Startup", "BrowserMainRunnerImpl::Initialize");
145 TRACE_EVENT0("startup", "BrowserMainRunnerImpl::Initialize");
147 // On Android we normally initialize the browser in a series of UI thread
148 // tasks. While this is happening a second request can come from the OS or
149 // another application to start the browser. If this happens then we must
150 // not run these parts of initialization twice.
151 if (!initialization_started_) {
152 initialization_started_ = true;
154 #if !defined(OS_IOS)
155 if (parameters.command_line.HasSwitch(switches::kWaitForDebugger))
156 base::debug::WaitForDebugger(60, true);
157 #endif
159 #if defined(OS_WIN)
160 if (base::win::GetVersion() < base::win::VERSION_VISTA) {
161 // When "Extend support of advanced text services to all programs"
162 // (a.k.a. Cicero Unaware Application Support; CUAS) is enabled on
163 // Windows XP and handwriting modules shipped with Office 2003 are
164 // installed, "penjpn.dll" and "skchui.dll" will be loaded and then
165 // crash unless a user installs Office 2003 SP3. To prevent these
166 // modules from being loaded, disable TSF entirely. crbug.com/160914.
167 // TODO(yukawa): Add a high-level wrapper for this instead of calling
168 // Win32 API here directly.
169 ImmDisableTextFrameService(static_cast<DWORD>(-1));
171 InstallSha256LegacyHooks();
172 #endif // OS_WIN
174 base::StatisticsRecorder::Initialize();
176 notification_service_.reset(new NotificationServiceImpl);
178 #if defined(OS_WIN)
179 // Ole must be initialized before starting message pump, so that TSF
180 // (Text Services Framework) module can interact with the message pump
181 // on Windows 8 Metro mode.
182 ole_initializer_.reset(new ui::ScopedOleInitializer);
183 // Enable DirectWrite font rendering if needed.
184 gfx::win::MaybeInitializeDirectWrite();
185 #endif // OS_WIN
187 main_loop_.reset(new BrowserMainLoop(parameters));
189 main_loop_->Init();
191 main_loop_->EarlyInitialization();
193 // Must happen before we try to use a message loop or display any UI.
194 if (!main_loop_->InitializeToolkit())
195 return 1;
197 main_loop_->PreMainMessageLoopStart();
198 main_loop_->MainMessageLoopStart();
199 main_loop_->PostMainMessageLoopStart();
201 // WARNING: If we get a WM_ENDSESSION, objects created on the stack here
202 // are NOT deleted. If you need something to run during WM_ENDSESSION add it
203 // to browser_shutdown::Shutdown or BrowserProcess::EndSession.
205 ui::InitializeInputMethod();
207 main_loop_->CreateStartupTasks();
208 int result_code = main_loop_->GetResultCode();
209 if (result_code > 0)
210 return result_code;
212 // Return -1 to indicate no early termination.
213 return -1;
216 int Run() override {
217 DCHECK(initialization_started_);
218 DCHECK(!is_shutdown_);
219 main_loop_->RunMainMessageLoopParts();
220 return main_loop_->GetResultCode();
223 void Shutdown() override {
224 DCHECK(initialization_started_);
225 DCHECK(!is_shutdown_);
226 #ifdef LEAK_SANITIZER
227 // Invoke leak detection now, to avoid dealing with shutdown-only leaks.
228 // Normally this will have already happened in
229 // BroserProcessImpl::ReleaseModule(), so this call has no effect. This is
230 // only for processes which do not instantiate a BrowserProcess.
231 // If leaks are found, the process will exit here.
232 __lsan_do_leak_check();
233 #endif
234 // If startup tracing has not been finished yet, replace it's dumper
235 // with special version, which would save trace file on exit (i.e.
236 // startup tracing becomes a version of shutdown tracing).
237 // There are two cases:
238 // 1. Startup duration is not reached.
239 // 2. Or startup duration is not specified for --trace-config-file flag.
240 scoped_ptr<BrowserShutdownProfileDumper> startup_profiler;
241 if (main_loop_->is_tracing_startup_for_duration()) {
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()));
248 } else if (tracing::TraceConfigFile::GetInstance()->IsEnabled() &&
249 TracingController::GetInstance()->IsRecording()) {
250 base::FilePath result_file;
251 #if defined(OS_ANDROID)
252 TracingControllerAndroid::GenerateTracingFilePath(&result_file);
253 #else
254 result_file = tracing::TraceConfigFile::GetInstance()->GetResultFile();
255 #endif
256 startup_profiler.reset(new BrowserShutdownProfileDumper(result_file));
259 // The shutdown tracing got enabled in AttemptUserExit earlier, but someone
260 // needs to write the result to disc. For that a dumper needs to get created
261 // which will dump the traces to disc when it gets destroyed.
262 const base::CommandLine& command_line =
263 *base::CommandLine::ForCurrentProcess();
264 scoped_ptr<BrowserShutdownProfileDumper> shutdown_profiler;
265 if (command_line.HasSwitch(switches::kTraceShutdown)) {
266 shutdown_profiler.reset(new BrowserShutdownProfileDumper(
267 BrowserShutdownProfileDumper::GetShutdownProfileFileName()));
271 // The trace event has to stay between profiler creation and destruction.
272 TRACE_EVENT0("shutdown", "BrowserMainRunner");
273 g_exited_main_message_loop = true;
275 main_loop_->ShutdownThreadsAndCleanUp();
277 ui::ShutdownInputMethod();
278 #if defined(OS_WIN)
279 ole_initializer_.reset(NULL);
280 #endif
281 #if defined(OS_ANDROID)
282 // Forcefully terminates the RunLoop inside MessagePumpForUI, ensuring
283 // proper shutdown for content_browsertests. Shutdown() is not used by
284 // the actual browser.
285 if (base::MessageLoop::current()->is_running())
286 base::MessageLoop::current()->QuitNow();
287 #endif
288 main_loop_.reset(NULL);
290 notification_service_.reset(NULL);
292 is_shutdown_ = true;
296 protected:
297 // True if we have started to initialize the runner.
298 bool initialization_started_;
300 // True if the runner has been shut down.
301 bool is_shutdown_;
303 scoped_ptr<NotificationServiceImpl> notification_service_;
304 scoped_ptr<BrowserMainLoop> main_loop_;
305 #if defined(OS_WIN)
306 scoped_ptr<ui::ScopedOleInitializer> ole_initializer_;
307 #endif
309 private:
310 DISALLOW_COPY_AND_ASSIGN(BrowserMainRunnerImpl);
313 // static
314 BrowserMainRunner* BrowserMainRunner::Create() {
315 return new BrowserMainRunnerImpl();
318 // static
319 bool BrowserMainRunner::ExitedMainMessageLoop() {
320 return g_exited_main_message_loop;
323 } // namespace content