Roll src/third_party/WebKit f298044:aa8346d (svn 202628:202629)
[chromium-blink-merge.git] / content / browser / browser_main_runner.cc
blobc7c805866569719544cdb89c1e5b793aae2ec8ed
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 "third_party/skia/include/core/SkGraphics.h"
26 #include "ui/base/ime/input_method_initializer.h"
28 #if defined(OS_ANDROID)
29 #include "content/browser/android/tracing_controller_android.h"
30 #endif
32 #if defined(OS_WIN)
33 #include "base/win/win_util.h"
34 #include "base/win/windows_version.h"
35 #include "net/cert/sha256_legacy_support_win.h"
36 #include "sandbox/win/src/sidestep/preamble_patcher.h"
37 #include "ui/base/win/scoped_ole_initializer.h"
38 #include "ui/gfx/switches.h"
39 #include "ui/gfx/win/direct_write.h"
40 #endif
42 namespace content {
44 namespace {
46 bool g_exited_main_message_loop = false;
48 #if defined(OS_WIN)
49 #if !defined(_WIN64)
50 // Pointer to the original CryptVerifyCertificateSignatureEx function.
51 net::sha256_interception::CryptVerifyCertificateSignatureExFunc
52 g_real_crypt_verify_signature_stub = NULL;
54 // Stub function that is called whenever the Crypt32 function
55 // CryptVerifyCertificateSignatureEx is called. It just defers to net to perform
56 // the actual verification.
57 BOOL WINAPI CryptVerifyCertificateSignatureExStub(
58 HCRYPTPROV_LEGACY provider,
59 DWORD encoding_type,
60 DWORD subject_type,
61 void* subject_data,
62 DWORD issuer_type,
63 void* issuer_data,
64 DWORD flags,
65 void* extra) {
66 return net::sha256_interception::CryptVerifyCertificateSignatureExHook(
67 g_real_crypt_verify_signature_stub, provider, encoding_type, subject_type,
68 subject_data, issuer_type, issuer_data, flags, extra);
70 #endif // !defined(_WIN64)
72 // If necessary, install an interception
73 void InstallSha256LegacyHooks() {
74 #if defined(_WIN64)
75 // Interception on x64 is not supported.
76 return;
77 #else
78 if (base::win::MaybeHasSHA256Support())
79 return;
81 net::sha256_interception::CryptVerifyCertificateSignatureExFunc
82 cert_verify_signature_ptr = reinterpret_cast<
83 net::sha256_interception::CryptVerifyCertificateSignatureExFunc>(
84 ::GetProcAddress(::GetModuleHandle(L"crypt32.dll"),
85 "CryptVerifyCertificateSignatureEx"));
86 CHECK(cert_verify_signature_ptr);
88 DWORD old_protect = 0;
89 if (!::VirtualProtect(cert_verify_signature_ptr, 5, PAGE_EXECUTE_READWRITE,
90 &old_protect)) {
91 return;
94 g_real_crypt_verify_signature_stub =
95 reinterpret_cast<
96 net::sha256_interception::CryptVerifyCertificateSignatureExFunc>(
97 VirtualAllocEx(::GetCurrentProcess(), NULL,
98 sidestep::kMaxPreambleStubSize, MEM_COMMIT,
99 PAGE_EXECUTE_READWRITE));
100 if (g_real_crypt_verify_signature_stub == NULL) {
101 CHECK(::VirtualProtect(cert_verify_signature_ptr, 5, old_protect,
102 &old_protect));
103 return;
106 sidestep::SideStepError patch_result =
107 sidestep::PreamblePatcher::Patch(
108 cert_verify_signature_ptr, CryptVerifyCertificateSignatureExStub,
109 g_real_crypt_verify_signature_stub, sidestep::kMaxPreambleStubSize);
110 if (patch_result != sidestep::SIDESTEP_SUCCESS) {
111 CHECK(::VirtualFreeEx(::GetCurrentProcess(),
112 g_real_crypt_verify_signature_stub, 0,
113 MEM_RELEASE));
114 CHECK(::VirtualProtect(cert_verify_signature_ptr, 5, old_protect,
115 &old_protect));
116 return;
119 DWORD dummy = 0;
120 CHECK(::VirtualProtect(cert_verify_signature_ptr, 5, old_protect, &dummy));
121 CHECK(::VirtualProtect(g_real_crypt_verify_signature_stub,
122 sidestep::kMaxPreambleStubSize, old_protect,
123 &old_protect));
124 #endif // _WIN64
126 #endif // OS_WIN
128 } // namespace
130 class BrowserMainRunnerImpl : public BrowserMainRunner {
131 public:
132 BrowserMainRunnerImpl()
133 : initialization_started_(false), is_shutdown_(false) {}
135 ~BrowserMainRunnerImpl() override {
136 if (initialization_started_ && !is_shutdown_)
137 Shutdown();
140 int Initialize(const MainFunctionParams& parameters) override {
141 // TODO(vadimt, yiyaoliu): Remove all tracked_objects references below once
142 // crbug.com/453640 is fixed.
143 tracked_objects::ThreadData::InitializeThreadContext("CrBrowserMain");
144 TRACK_SCOPED_REGION(
145 "Startup", "BrowserMainRunnerImpl::Initialize");
146 TRACE_EVENT0("startup", "BrowserMainRunnerImpl::Initialize");
148 // On Android we normally initialize the browser in a series of UI thread
149 // tasks. While this is happening a second request can come from the OS or
150 // another application to start the browser. If this happens then we must
151 // not run these parts of initialization twice.
152 if (!initialization_started_) {
153 initialization_started_ = true;
155 SkGraphics::Init();
157 #if !defined(OS_IOS)
158 if (parameters.command_line.HasSwitch(switches::kWaitForDebugger))
159 base::debug::WaitForDebugger(60, true);
160 #endif
162 #if defined(OS_WIN)
163 if (base::win::GetVersion() < base::win::VERSION_VISTA) {
164 // When "Extend support of advanced text services to all programs"
165 // (a.k.a. Cicero Unaware Application Support; CUAS) is enabled on
166 // Windows XP and handwriting modules shipped with Office 2003 are
167 // installed, "penjpn.dll" and "skchui.dll" will be loaded and then
168 // crash unless a user installs Office 2003 SP3. To prevent these
169 // modules from being loaded, disable TSF entirely. crbug.com/160914.
170 // TODO(yukawa): Add a high-level wrapper for this instead of calling
171 // Win32 API here directly.
172 ImmDisableTextFrameService(static_cast<DWORD>(-1));
174 InstallSha256LegacyHooks();
175 #endif // OS_WIN
177 base::StatisticsRecorder::Initialize();
179 notification_service_.reset(new NotificationServiceImpl);
181 #if defined(OS_WIN)
182 // Ole must be initialized before starting message pump, so that TSF
183 // (Text Services Framework) module can interact with the message pump
184 // on Windows 8 Metro mode.
185 ole_initializer_.reset(new ui::ScopedOleInitializer);
186 // Enable DirectWrite font rendering if needed.
187 gfx::win::MaybeInitializeDirectWrite();
188 #endif // OS_WIN
190 main_loop_.reset(new BrowserMainLoop(parameters));
192 main_loop_->Init();
194 main_loop_->EarlyInitialization();
196 // Must happen before we try to use a message loop or display any UI.
197 if (!main_loop_->InitializeToolkit())
198 return 1;
200 main_loop_->PreMainMessageLoopStart();
201 main_loop_->MainMessageLoopStart();
202 main_loop_->PostMainMessageLoopStart();
204 // WARNING: If we get a WM_ENDSESSION, objects created on the stack here
205 // are NOT deleted. If you need something to run during WM_ENDSESSION add it
206 // to browser_shutdown::Shutdown or BrowserProcess::EndSession.
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 // There are two cases:
241 // 1. Startup duration is not reached.
242 // 2. Or startup duration is not specified for --trace-config-file flag.
243 scoped_ptr<BrowserShutdownProfileDumper> startup_profiler;
244 if (main_loop_->is_tracing_startup_for_duration()) {
245 main_loop_->StopStartupTracingTimer();
246 if (main_loop_->startup_trace_file() !=
247 base::FilePath().AppendASCII("none")) {
248 startup_profiler.reset(
249 new BrowserShutdownProfileDumper(main_loop_->startup_trace_file()));
251 } else if (tracing::TraceConfigFile::GetInstance()->IsEnabled() &&
252 TracingController::GetInstance()->IsRecording()) {
253 base::FilePath result_file;
254 #if defined(OS_ANDROID)
255 TracingControllerAndroid::GenerateTracingFilePath(&result_file);
256 #else
257 result_file = tracing::TraceConfigFile::GetInstance()->GetResultFile();
258 #endif
259 startup_profiler.reset(new BrowserShutdownProfileDumper(result_file));
262 // The shutdown tracing got enabled in AttemptUserExit earlier, but someone
263 // needs to write the result to disc. For that a dumper needs to get created
264 // which will dump the traces to disc when it gets destroyed.
265 const base::CommandLine& command_line =
266 *base::CommandLine::ForCurrentProcess();
267 scoped_ptr<BrowserShutdownProfileDumper> shutdown_profiler;
268 if (command_line.HasSwitch(switches::kTraceShutdown)) {
269 shutdown_profiler.reset(new BrowserShutdownProfileDumper(
270 BrowserShutdownProfileDumper::GetShutdownProfileFileName()));
274 // The trace event has to stay between profiler creation and destruction.
275 TRACE_EVENT0("shutdown", "BrowserMainRunner");
276 g_exited_main_message_loop = true;
278 main_loop_->ShutdownThreadsAndCleanUp();
280 ui::ShutdownInputMethod();
281 #if defined(OS_WIN)
282 ole_initializer_.reset(NULL);
283 #endif
284 #if defined(OS_ANDROID)
285 // Forcefully terminates the RunLoop inside MessagePumpForUI, ensuring
286 // proper shutdown for content_browsertests. Shutdown() is not used by
287 // the actual browser.
288 if (base::MessageLoop::current()->is_running())
289 base::MessageLoop::current()->QuitNow();
290 #endif
291 main_loop_.reset(NULL);
293 notification_service_.reset(NULL);
295 is_shutdown_ = true;
299 protected:
300 // True if we have started to initialize the runner.
301 bool initialization_started_;
303 // True if the runner has been shut down.
304 bool is_shutdown_;
306 scoped_ptr<NotificationServiceImpl> notification_service_;
307 scoped_ptr<BrowserMainLoop> main_loop_;
308 #if defined(OS_WIN)
309 scoped_ptr<ui::ScopedOleInitializer> ole_initializer_;
310 #endif
312 private:
313 DISALLOW_COPY_AND_ASSIGN(BrowserMainRunnerImpl);
316 // static
317 BrowserMainRunner* BrowserMainRunner::Create() {
318 return new BrowserMainRunnerImpl();
321 // static
322 bool BrowserMainRunner::ExitedMainMessageLoop() {
323 return g_exited_main_message_loop;
326 } // namespace content