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"
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"
35 bool g_exited_main_message_loop
= false;
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
,
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() {
66 // Interception on x64 is not supported.
69 if (base::win::MaybeHasSHA256Support())
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
,
85 g_real_crypt_verify_signature_stub
=
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
,
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,
105 CHECK(::VirtualProtect(cert_verify_signature_ptr
, 5, old_protect
,
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
,
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
));
132 class BrowserMainRunnerImpl
: public BrowserMainRunner
{
134 BrowserMainRunnerImpl()
135 : initialization_started_(false), is_shutdown_(false) {}
137 ~BrowserMainRunnerImpl() override
{
138 if (initialization_started_
&& !is_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;
152 if (parameters
.command_line
.HasSwitch(switches::kWaitForDebugger
))
153 base::debug::WaitForDebugger(60, true);
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();
171 base::StatisticsRecorder::Initialize();
173 notification_service_
.reset(new NotificationServiceImpl
);
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();
184 main_loop_
.reset(new BrowserMainLoop(parameters
));
188 main_loop_
->EarlyInitialization();
190 // Must happen before we try to use a message loop or display any UI.
191 if (!main_loop_
->InitializeToolkit())
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
206 base::allocator::SetupSubprocessAllocator();
208 ui::InitializeInputMethod();
210 main_loop_
->CreateStartupTasks();
211 int result_code
= main_loop_
->GetResultCode();
215 // Return -1 to indicate no early termination.
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();
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();
270 ole_initializer_
.reset(NULL
);
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();
278 main_loop_
.reset(NULL
);
280 notification_service_
.reset(NULL
);
287 // True if we have started to initialize the runner.
288 bool initialization_started_
;
290 // True if the runner has been shut down.
293 scoped_ptr
<NotificationServiceImpl
> notification_service_
;
294 scoped_ptr
<BrowserMainLoop
> main_loop_
;
296 scoped_ptr
<ui::ScopedOleInitializer
> ole_initializer_
;
299 DISALLOW_COPY_AND_ASSIGN(BrowserMainRunnerImpl
);
303 BrowserMainRunner
* BrowserMainRunner::Create() {
304 return new BrowserMainRunnerImpl();
307 } // namespace content