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/debug/trace_event.h"
11 #include "base/logging.h"
12 #include "base/metrics/histogram.h"
13 #include "base/metrics/statistics_recorder.h"
14 #include "content/browser/browser_main_loop.h"
15 #include "content/browser/browser_shutdown_profile_dumper.h"
16 #include "content/browser/notification_service_impl.h"
17 #include "content/public/common/content_switches.h"
18 #include "content/public/common/main_function_params.h"
19 #include "ui/base/ime/input_method_initializer.h"
22 #include "base/win/win_util.h"
23 #include "base/win/windows_version.h"
24 #include "net/cert/sha256_legacy_support_win.h"
25 #include "sandbox/win/src/sidestep/preamble_patcher.h"
26 #include "ui/base/win/scoped_ole_initializer.h"
27 #include "ui/gfx/switches.h"
28 #include "ui/gfx/win/direct_write.h"
31 bool g_exited_main_message_loop
= false;
38 // Pointer to the original CryptVerifyCertificateSignatureEx function.
39 net::sha256_interception::CryptVerifyCertificateSignatureExFunc
40 g_real_crypt_verify_signature_stub
= NULL
;
42 // Stub function that is called whenever the Crypt32 function
43 // CryptVerifyCertificateSignatureEx is called. It just defers to net to perform
44 // the actual verification.
45 BOOL WINAPI
CryptVerifyCertificateSignatureExStub(
46 HCRYPTPROV_LEGACY provider
,
54 return net::sha256_interception::CryptVerifyCertificateSignatureExHook(
55 g_real_crypt_verify_signature_stub
, provider
, encoding_type
, subject_type
,
56 subject_data
, issuer_type
, issuer_data
, flags
, extra
);
59 // If necessary, install an interception
60 void InstallSha256LegacyHooks() {
62 // Interception on x64 is not supported.
65 if (base::win::MaybeHasSHA256Support())
68 net::sha256_interception::CryptVerifyCertificateSignatureExFunc
69 cert_verify_signature_ptr
= reinterpret_cast<
70 net::sha256_interception::CryptVerifyCertificateSignatureExFunc
>(
71 ::GetProcAddress(::GetModuleHandle(L
"crypt32.dll"),
72 "CryptVerifyCertificateSignatureEx"));
73 CHECK(cert_verify_signature_ptr
);
75 DWORD old_protect
= 0;
76 if (!::VirtualProtect(cert_verify_signature_ptr
, 5, PAGE_EXECUTE_READWRITE
,
81 g_real_crypt_verify_signature_stub
=
83 net::sha256_interception::CryptVerifyCertificateSignatureExFunc
>(
84 VirtualAllocEx(::GetCurrentProcess(), NULL
,
85 sidestep::kMaxPreambleStubSize
, MEM_COMMIT
,
86 PAGE_EXECUTE_READWRITE
));
87 if (g_real_crypt_verify_signature_stub
== NULL
) {
88 CHECK(::VirtualProtect(cert_verify_signature_ptr
, 5, old_protect
,
93 sidestep::SideStepError patch_result
=
94 sidestep::PreamblePatcher::Patch(
95 cert_verify_signature_ptr
, CryptVerifyCertificateSignatureExStub
,
96 g_real_crypt_verify_signature_stub
, sidestep::kMaxPreambleStubSize
);
97 if (patch_result
!= sidestep::SIDESTEP_SUCCESS
) {
98 CHECK(::VirtualFreeEx(::GetCurrentProcess(),
99 g_real_crypt_verify_signature_stub
, 0,
101 CHECK(::VirtualProtect(cert_verify_signature_ptr
, 5, old_protect
,
107 CHECK(::VirtualProtect(cert_verify_signature_ptr
, 5, old_protect
, &dummy
));
108 CHECK(::VirtualProtect(g_real_crypt_verify_signature_stub
,
109 sidestep::kMaxPreambleStubSize
, old_protect
,
118 class BrowserMainRunnerImpl
: public BrowserMainRunner
{
120 BrowserMainRunnerImpl()
121 : initialization_started_(false), is_shutdown_(false) {}
123 ~BrowserMainRunnerImpl() override
{
124 if (initialization_started_
&& !is_shutdown_
)
128 int Initialize(const MainFunctionParams
& parameters
) override
{
129 TRACE_EVENT0("startup", "BrowserMainRunnerImpl::Initialize");
130 // On Android we normally initialize the browser in a series of UI thread
131 // tasks. While this is happening a second request can come from the OS or
132 // another application to start the browser. If this happens then we must
133 // not run these parts of initialization twice.
134 if (!initialization_started_
) {
135 initialization_started_
= true;
138 if (parameters
.command_line
.HasSwitch(switches::kWaitForDebugger
))
139 base::debug::WaitForDebugger(60, true);
143 if (base::win::GetVersion() < base::win::VERSION_VISTA
) {
144 // When "Extend support of advanced text services to all programs"
145 // (a.k.a. Cicero Unaware Application Support; CUAS) is enabled on
146 // Windows XP and handwriting modules shipped with Office 2003 are
147 // installed, "penjpn.dll" and "skchui.dll" will be loaded and then
148 // crash unless a user installs Office 2003 SP3. To prevent these
149 // modules from being loaded, disable TSF entirely. crbug.com/160914.
150 // TODO(yukawa): Add a high-level wrapper for this instead of calling
151 // Win32 API here directly.
152 ImmDisableTextFrameService(static_cast<DWORD
>(-1));
154 InstallSha256LegacyHooks();
157 base::StatisticsRecorder::Initialize();
159 notification_service_
.reset(new NotificationServiceImpl
);
162 // Ole must be initialized before starting message pump, so that TSF
163 // (Text Services Framework) module can interact with the message pump
164 // on Windows 8 Metro mode.
165 ole_initializer_
.reset(new ui::ScopedOleInitializer
);
166 // Enable DirectWrite font rendering if needed.
167 gfx::win::MaybeInitializeDirectWrite();
170 main_loop_
.reset(new BrowserMainLoop(parameters
));
174 main_loop_
->EarlyInitialization();
176 // Must happen before we try to use a message loop or display any UI.
177 if (!main_loop_
->InitializeToolkit())
180 main_loop_
->MainMessageLoopStart();
182 // WARNING: If we get a WM_ENDSESSION, objects created on the stack here
183 // are NOT deleted. If you need something to run during WM_ENDSESSION add it
184 // to browser_shutdown::Shutdown or BrowserProcess::EndSession.
186 ui::InitializeInputMethod();
188 main_loop_
->CreateStartupTasks();
189 int result_code
= main_loop_
->GetResultCode();
193 // Return -1 to indicate no early termination.
198 DCHECK(initialization_started_
);
199 DCHECK(!is_shutdown_
);
200 main_loop_
->RunMainMessageLoopParts();
201 return main_loop_
->GetResultCode();
204 void Shutdown() override
{
205 DCHECK(initialization_started_
);
206 DCHECK(!is_shutdown_
);
207 #ifdef LEAK_SANITIZER
208 // Invoke leak detection now, to avoid dealing with shutdown-only leaks.
209 // Normally this will have already happened in
210 // BroserProcessImpl::ReleaseModule(), so this call has no effect. This is
211 // only for processes which do not instantiate a BrowserProcess.
212 // If leaks are found, the process will exit here.
213 __lsan_do_leak_check();
215 // If startup tracing has not been finished yet, replace it's dumper
216 // with special version, which would save trace file on exit (i.e.
217 // startup tracing becomes a version of shutdown tracing).
218 scoped_ptr
<BrowserShutdownProfileDumper
> startup_profiler
;
219 if (main_loop_
->is_tracing_startup()) {
220 main_loop_
->StopStartupTracingTimer();
221 if (main_loop_
->startup_trace_file() !=
222 base::FilePath().AppendASCII("none")) {
223 startup_profiler
.reset(
224 new BrowserShutdownProfileDumper(main_loop_
->startup_trace_file()));
228 // The shutdown tracing got enabled in AttemptUserExit earlier, but someone
229 // needs to write the result to disc. For that a dumper needs to get created
230 // which will dump the traces to disc when it gets destroyed.
231 const base::CommandLine
& command_line
=
232 *base::CommandLine::ForCurrentProcess();
233 scoped_ptr
<BrowserShutdownProfileDumper
> shutdown_profiler
;
234 if (command_line
.HasSwitch(switches::kTraceShutdown
)) {
235 shutdown_profiler
.reset(new BrowserShutdownProfileDumper(
236 BrowserShutdownProfileDumper::GetShutdownProfileFileName()));
240 // The trace event has to stay between profiler creation and destruction.
241 TRACE_EVENT0("shutdown", "BrowserMainRunner");
242 g_exited_main_message_loop
= true;
244 main_loop_
->ShutdownThreadsAndCleanUp();
246 ui::ShutdownInputMethod();
248 ole_initializer_
.reset(NULL
);
250 #if defined(OS_ANDROID)
251 // Forcefully terminates the RunLoop inside MessagePumpForUI, ensuring
252 // proper shutdown for content_browsertests. Shutdown() is not used by
253 // the actual browser.
254 if (base::MessageLoop::current()->is_running())
255 base::MessageLoop::current()->QuitNow();
257 main_loop_
.reset(NULL
);
259 notification_service_
.reset(NULL
);
266 // True if we have started to initialize the runner.
267 bool initialization_started_
;
269 // True if the runner has been shut down.
272 scoped_ptr
<NotificationServiceImpl
> notification_service_
;
273 scoped_ptr
<BrowserMainLoop
> main_loop_
;
275 scoped_ptr
<ui::ScopedOleInitializer
> ole_initializer_
;
278 DISALLOW_COPY_AND_ASSIGN(BrowserMainRunnerImpl
);
282 BrowserMainRunner
* BrowserMainRunner::Create() {
283 return new BrowserMainRunnerImpl();
286 } // namespace content