[Session restore] Rename group name Enabled to Restore.
[chromium-blink-merge.git] / content / browser / browser_main_runner.cc
blob524bdfb216d665b9c06e17878ae373fc2fab54f8
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_tracker.h"
14 #include "base/trace_event/trace_event.h"
15 #include "base/tracked_objects.h"
16 #include "content/browser/browser_main_loop.h"
17 #include "content/browser/browser_shutdown_profile_dumper.h"
18 #include "content/browser/notification_service_impl.h"
19 #include "content/public/common/content_switches.h"
20 #include "content/public/common/main_function_params.h"
21 #include "ui/base/ime/input_method_initializer.h"
23 #if defined(OS_WIN)
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 "ui/base/win/scoped_ole_initializer.h"
29 #include "ui/gfx/switches.h"
30 #include "ui/gfx/win/direct_write.h"
31 #endif
33 bool g_exited_main_message_loop = false;
35 namespace content {
37 #if defined(OS_WIN)
38 namespace {
40 // Pointer to the original CryptVerifyCertificateSignatureEx function.
41 net::sha256_interception::CryptVerifyCertificateSignatureExFunc
42 g_real_crypt_verify_signature_stub = NULL;
44 // Stub function that is called whenever the Crypt32 function
45 // CryptVerifyCertificateSignatureEx is called. It just defers to net to perform
46 // the actual verification.
47 BOOL WINAPI CryptVerifyCertificateSignatureExStub(
48 HCRYPTPROV_LEGACY provider,
49 DWORD encoding_type,
50 DWORD subject_type,
51 void* subject_data,
52 DWORD issuer_type,
53 void* issuer_data,
54 DWORD flags,
55 void* extra) {
56 return net::sha256_interception::CryptVerifyCertificateSignatureExHook(
57 g_real_crypt_verify_signature_stub, provider, encoding_type, subject_type,
58 subject_data, issuer_type, issuer_data, flags, extra);
61 // If necessary, install an interception
62 void InstallSha256LegacyHooks() {
63 #if defined(_WIN64)
64 // Interception on x64 is not supported.
65 return;
66 #else
67 if (base::win::MaybeHasSHA256Support())
68 return;
70 net::sha256_interception::CryptVerifyCertificateSignatureExFunc
71 cert_verify_signature_ptr = reinterpret_cast<
72 net::sha256_interception::CryptVerifyCertificateSignatureExFunc>(
73 ::GetProcAddress(::GetModuleHandle(L"crypt32.dll"),
74 "CryptVerifyCertificateSignatureEx"));
75 CHECK(cert_verify_signature_ptr);
77 DWORD old_protect = 0;
78 if (!::VirtualProtect(cert_verify_signature_ptr, 5, PAGE_EXECUTE_READWRITE,
79 &old_protect)) {
80 return;
83 g_real_crypt_verify_signature_stub =
84 reinterpret_cast<
85 net::sha256_interception::CryptVerifyCertificateSignatureExFunc>(
86 VirtualAllocEx(::GetCurrentProcess(), NULL,
87 sidestep::kMaxPreambleStubSize, MEM_COMMIT,
88 PAGE_EXECUTE_READWRITE));
89 if (g_real_crypt_verify_signature_stub == NULL) {
90 CHECK(::VirtualProtect(cert_verify_signature_ptr, 5, old_protect,
91 &old_protect));
92 return;
95 sidestep::SideStepError patch_result =
96 sidestep::PreamblePatcher::Patch(
97 cert_verify_signature_ptr, CryptVerifyCertificateSignatureExStub,
98 g_real_crypt_verify_signature_stub, sidestep::kMaxPreambleStubSize);
99 if (patch_result != sidestep::SIDESTEP_SUCCESS) {
100 CHECK(::VirtualFreeEx(::GetCurrentProcess(),
101 g_real_crypt_verify_signature_stub, 0,
102 MEM_RELEASE));
103 CHECK(::VirtualProtect(cert_verify_signature_ptr, 5, old_protect,
104 &old_protect));
105 return;
108 DWORD dummy = 0;
109 CHECK(::VirtualProtect(cert_verify_signature_ptr, 5, old_protect, &dummy));
110 CHECK(::VirtualProtect(g_real_crypt_verify_signature_stub,
111 sidestep::kMaxPreambleStubSize, old_protect,
112 &old_protect));
113 #endif // _WIN64
116 } // namespace
118 #endif // OS_WIN
120 class BrowserMainRunnerImpl : public BrowserMainRunner {
121 public:
122 BrowserMainRunnerImpl()
123 : initialization_started_(false), is_shutdown_(false) {}
125 ~BrowserMainRunnerImpl() override {
126 if (initialization_started_ && !is_shutdown_)
127 Shutdown();
130 int Initialize(const MainFunctionParams& parameters) override {
131 // TODO(vadimt, yiyaoliu): Remove all tracked_objects references below once
132 // crbug.com/453640 is fixed.
133 tracked_objects::ThreadData::InitializeThreadContext("CrBrowserMain");
134 tracked_objects::ScopedTracker tracking_profile(
135 FROM_HERE_WITH_EXPLICIT_FUNCTION(
136 "453640 BrowserMainRunnerImpl::Initialize"));
137 TRACE_EVENT0("startup", "BrowserMainRunnerImpl::Initialize");
139 // On Android we normally initialize the browser in a series of UI thread
140 // tasks. While this is happening a second request can come from the OS or
141 // another application to start the browser. If this happens then we must
142 // not run these parts of initialization twice.
143 if (!initialization_started_) {
144 initialization_started_ = true;
146 #if !defined(OS_IOS)
147 if (parameters.command_line.HasSwitch(switches::kWaitForDebugger))
148 base::debug::WaitForDebugger(60, true);
149 #endif
151 #if defined(OS_WIN)
152 if (base::win::GetVersion() < base::win::VERSION_VISTA) {
153 // When "Extend support of advanced text services to all programs"
154 // (a.k.a. Cicero Unaware Application Support; CUAS) is enabled on
155 // Windows XP and handwriting modules shipped with Office 2003 are
156 // installed, "penjpn.dll" and "skchui.dll" will be loaded and then
157 // crash unless a user installs Office 2003 SP3. To prevent these
158 // modules from being loaded, disable TSF entirely. crbug.com/160914.
159 // TODO(yukawa): Add a high-level wrapper for this instead of calling
160 // Win32 API here directly.
161 ImmDisableTextFrameService(static_cast<DWORD>(-1));
163 InstallSha256LegacyHooks();
164 #endif // OS_WIN
166 base::StatisticsRecorder::Initialize();
168 notification_service_.reset(new NotificationServiceImpl);
170 #if defined(OS_WIN)
171 // Ole must be initialized before starting message pump, so that TSF
172 // (Text Services Framework) module can interact with the message pump
173 // on Windows 8 Metro mode.
174 ole_initializer_.reset(new ui::ScopedOleInitializer);
175 // Enable DirectWrite font rendering if needed.
176 gfx::win::MaybeInitializeDirectWrite();
177 #endif // OS_WIN
179 main_loop_.reset(new BrowserMainLoop(parameters));
181 main_loop_->Init();
183 main_loop_->EarlyInitialization();
185 // Must happen before we try to use a message loop or display any UI.
186 if (!main_loop_->InitializeToolkit())
187 return 1;
189 main_loop_->MainMessageLoopStart();
191 // WARNING: If we get a WM_ENDSESSION, objects created on the stack here
192 // are NOT deleted. If you need something to run during WM_ENDSESSION add it
193 // to browser_shutdown::Shutdown or BrowserProcess::EndSession.
195 ui::InitializeInputMethod();
197 main_loop_->CreateStartupTasks();
198 int result_code = main_loop_->GetResultCode();
199 if (result_code > 0)
200 return result_code;
202 // Return -1 to indicate no early termination.
203 return -1;
206 int Run() override {
207 DCHECK(initialization_started_);
208 DCHECK(!is_shutdown_);
209 main_loop_->RunMainMessageLoopParts();
210 return main_loop_->GetResultCode();
213 void Shutdown() override {
214 DCHECK(initialization_started_);
215 DCHECK(!is_shutdown_);
216 #ifdef LEAK_SANITIZER
217 // Invoke leak detection now, to avoid dealing with shutdown-only leaks.
218 // Normally this will have already happened in
219 // BroserProcessImpl::ReleaseModule(), so this call has no effect. This is
220 // only for processes which do not instantiate a BrowserProcess.
221 // If leaks are found, the process will exit here.
222 __lsan_do_leak_check();
223 #endif
224 // If startup tracing has not been finished yet, replace it's dumper
225 // with special version, which would save trace file on exit (i.e.
226 // startup tracing becomes a version of shutdown tracing).
227 scoped_ptr<BrowserShutdownProfileDumper> startup_profiler;
228 if (main_loop_->is_tracing_startup()) {
229 main_loop_->StopStartupTracingTimer();
230 if (main_loop_->startup_trace_file() !=
231 base::FilePath().AppendASCII("none")) {
232 startup_profiler.reset(
233 new BrowserShutdownProfileDumper(main_loop_->startup_trace_file()));
237 // The shutdown tracing got enabled in AttemptUserExit earlier, but someone
238 // needs to write the result to disc. For that a dumper needs to get created
239 // which will dump the traces to disc when it gets destroyed.
240 const base::CommandLine& command_line =
241 *base::CommandLine::ForCurrentProcess();
242 scoped_ptr<BrowserShutdownProfileDumper> shutdown_profiler;
243 if (command_line.HasSwitch(switches::kTraceShutdown)) {
244 shutdown_profiler.reset(new BrowserShutdownProfileDumper(
245 BrowserShutdownProfileDumper::GetShutdownProfileFileName()));
249 // The trace event has to stay between profiler creation and destruction.
250 TRACE_EVENT0("shutdown", "BrowserMainRunner");
251 g_exited_main_message_loop = true;
253 main_loop_->ShutdownThreadsAndCleanUp();
255 ui::ShutdownInputMethod();
256 #if defined(OS_WIN)
257 ole_initializer_.reset(NULL);
258 #endif
259 #if defined(OS_ANDROID)
260 // Forcefully terminates the RunLoop inside MessagePumpForUI, ensuring
261 // proper shutdown for content_browsertests. Shutdown() is not used by
262 // the actual browser.
263 if (base::MessageLoop::current()->is_running())
264 base::MessageLoop::current()->QuitNow();
265 #endif
266 main_loop_.reset(NULL);
268 notification_service_.reset(NULL);
270 is_shutdown_ = true;
274 protected:
275 // True if we have started to initialize the runner.
276 bool initialization_started_;
278 // True if the runner has been shut down.
279 bool is_shutdown_;
281 scoped_ptr<NotificationServiceImpl> notification_service_;
282 scoped_ptr<BrowserMainLoop> main_loop_;
283 #if defined(OS_WIN)
284 scoped_ptr<ui::ScopedOleInitializer> ole_initializer_;
285 #endif
287 DISALLOW_COPY_AND_ASSIGN(BrowserMainRunnerImpl);
290 // static
291 BrowserMainRunner* BrowserMainRunner::Create() {
292 return new BrowserMainRunnerImpl();
295 } // namespace content