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/tracing_switches.h"
18 #include "content/browser/browser_main_loop.h"
19 #include "content/browser/browser_shutdown_profile_dumper.h"
20 #include "content/browser/notification_service_impl.h"
21 #include "content/public/common/content_switches.h"
22 #include "content/public/common/main_function_params.h"
23 #include "ui/base/ime/input_method_initializer.h"
26 #include "base/win/win_util.h"
27 #include "base/win/windows_version.h"
28 #include "net/cert/sha256_legacy_support_win.h"
29 #include "sandbox/win/src/sidestep/preamble_patcher.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;
43 // Pointer to the original CryptVerifyCertificateSignatureEx function.
44 net::sha256_interception::CryptVerifyCertificateSignatureExFunc
45 g_real_crypt_verify_signature_stub
= NULL
;
47 // Stub function that is called whenever the Crypt32 function
48 // CryptVerifyCertificateSignatureEx is called. It just defers to net to perform
49 // the actual verification.
50 BOOL WINAPI
CryptVerifyCertificateSignatureExStub(
51 HCRYPTPROV_LEGACY provider
,
59 return net::sha256_interception::CryptVerifyCertificateSignatureExHook(
60 g_real_crypt_verify_signature_stub
, provider
, encoding_type
, subject_type
,
61 subject_data
, issuer_type
, issuer_data
, flags
, extra
);
63 #endif // !defined(_WIN64)
65 // If necessary, install an interception
66 void InstallSha256LegacyHooks() {
68 // Interception on x64 is not supported.
71 if (base::win::MaybeHasSHA256Support())
74 net::sha256_interception::CryptVerifyCertificateSignatureExFunc
75 cert_verify_signature_ptr
= reinterpret_cast<
76 net::sha256_interception::CryptVerifyCertificateSignatureExFunc
>(
77 ::GetProcAddress(::GetModuleHandle(L
"crypt32.dll"),
78 "CryptVerifyCertificateSignatureEx"));
79 CHECK(cert_verify_signature_ptr
);
81 DWORD old_protect
= 0;
82 if (!::VirtualProtect(cert_verify_signature_ptr
, 5, PAGE_EXECUTE_READWRITE
,
87 g_real_crypt_verify_signature_stub
=
89 net::sha256_interception::CryptVerifyCertificateSignatureExFunc
>(
90 VirtualAllocEx(::GetCurrentProcess(), NULL
,
91 sidestep::kMaxPreambleStubSize
, MEM_COMMIT
,
92 PAGE_EXECUTE_READWRITE
));
93 if (g_real_crypt_verify_signature_stub
== NULL
) {
94 CHECK(::VirtualProtect(cert_verify_signature_ptr
, 5, old_protect
,
99 sidestep::SideStepError patch_result
=
100 sidestep::PreamblePatcher::Patch(
101 cert_verify_signature_ptr
, CryptVerifyCertificateSignatureExStub
,
102 g_real_crypt_verify_signature_stub
, sidestep::kMaxPreambleStubSize
);
103 if (patch_result
!= sidestep::SIDESTEP_SUCCESS
) {
104 CHECK(::VirtualFreeEx(::GetCurrentProcess(),
105 g_real_crypt_verify_signature_stub
, 0,
107 CHECK(::VirtualProtect(cert_verify_signature_ptr
, 5, old_protect
,
113 CHECK(::VirtualProtect(cert_verify_signature_ptr
, 5, old_protect
, &dummy
));
114 CHECK(::VirtualProtect(g_real_crypt_verify_signature_stub
,
115 sidestep::kMaxPreambleStubSize
, old_protect
,
124 class BrowserMainRunnerImpl
: public BrowserMainRunner
{
126 BrowserMainRunnerImpl()
127 : initialization_started_(false), is_shutdown_(false) {}
129 ~BrowserMainRunnerImpl() override
{
130 if (initialization_started_
&& !is_shutdown_
)
134 int Initialize(const MainFunctionParams
& parameters
) override
{
135 // TODO(vadimt, yiyaoliu): Remove all tracked_objects references below once
136 // crbug.com/453640 is fixed.
137 tracked_objects::ThreadData::InitializeThreadContext("CrBrowserMain");
139 "Startup", "BrowserMainRunnerImpl::Initialize");
140 TRACE_EVENT0("startup", "BrowserMainRunnerImpl::Initialize");
142 // On Android we normally initialize the browser in a series of UI thread
143 // tasks. While this is happening a second request can come from the OS or
144 // another application to start the browser. If this happens then we must
145 // not run these parts of initialization twice.
146 if (!initialization_started_
) {
147 initialization_started_
= true;
150 if (parameters
.command_line
.HasSwitch(switches::kWaitForDebugger
))
151 base::debug::WaitForDebugger(60, true);
155 if (base::win::GetVersion() < base::win::VERSION_VISTA
) {
156 // When "Extend support of advanced text services to all programs"
157 // (a.k.a. Cicero Unaware Application Support; CUAS) is enabled on
158 // Windows XP and handwriting modules shipped with Office 2003 are
159 // installed, "penjpn.dll" and "skchui.dll" will be loaded and then
160 // crash unless a user installs Office 2003 SP3. To prevent these
161 // modules from being loaded, disable TSF entirely. crbug.com/160914.
162 // TODO(yukawa): Add a high-level wrapper for this instead of calling
163 // Win32 API here directly.
164 ImmDisableTextFrameService(static_cast<DWORD
>(-1));
166 InstallSha256LegacyHooks();
169 base::StatisticsRecorder::Initialize();
171 notification_service_
.reset(new NotificationServiceImpl
);
174 // Ole must be initialized before starting message pump, so that TSF
175 // (Text Services Framework) module can interact with the message pump
176 // on Windows 8 Metro mode.
177 ole_initializer_
.reset(new ui::ScopedOleInitializer
);
178 // Enable DirectWrite font rendering if needed.
179 gfx::win::MaybeInitializeDirectWrite();
182 main_loop_
.reset(new BrowserMainLoop(parameters
));
186 main_loop_
->EarlyInitialization();
188 // Must happen before we try to use a message loop or display any UI.
189 if (!main_loop_
->InitializeToolkit())
192 main_loop_
->PreMainMessageLoopStart();
193 main_loop_
->MainMessageLoopStart();
194 main_loop_
->PostMainMessageLoopStart();
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 ui::InitializeInputMethod();
202 main_loop_
->CreateStartupTasks();
203 int result_code
= main_loop_
->GetResultCode();
207 // Return -1 to indicate no early termination.
212 DCHECK(initialization_started_
);
213 DCHECK(!is_shutdown_
);
214 main_loop_
->RunMainMessageLoopParts();
215 return main_loop_
->GetResultCode();
218 void Shutdown() override
{
219 DCHECK(initialization_started_
);
220 DCHECK(!is_shutdown_
);
221 #ifdef LEAK_SANITIZER
222 // Invoke leak detection now, to avoid dealing with shutdown-only leaks.
223 // Normally this will have already happened in
224 // BroserProcessImpl::ReleaseModule(), so this call has no effect. This is
225 // only for processes which do not instantiate a BrowserProcess.
226 // If leaks are found, the process will exit here.
227 __lsan_do_leak_check();
229 // If startup tracing has not been finished yet, replace it's dumper
230 // with special version, which would save trace file on exit (i.e.
231 // startup tracing becomes a version of shutdown tracing).
232 scoped_ptr
<BrowserShutdownProfileDumper
> startup_profiler
;
233 if (main_loop_
->is_tracing_startup()) {
234 main_loop_
->StopStartupTracingTimer();
235 if (main_loop_
->startup_trace_file() !=
236 base::FilePath().AppendASCII("none")) {
237 startup_profiler
.reset(
238 new BrowserShutdownProfileDumper(main_loop_
->startup_trace_file()));
242 // The shutdown tracing got enabled in AttemptUserExit earlier, but someone
243 // needs to write the result to disc. For that a dumper needs to get created
244 // which will dump the traces to disc when it gets destroyed.
245 const base::CommandLine
& command_line
=
246 *base::CommandLine::ForCurrentProcess();
247 scoped_ptr
<BrowserShutdownProfileDumper
> shutdown_profiler
;
248 if (command_line
.HasSwitch(switches::kTraceShutdown
)) {
249 shutdown_profiler
.reset(new BrowserShutdownProfileDumper(
250 BrowserShutdownProfileDumper::GetShutdownProfileFileName()));
254 // The trace event has to stay between profiler creation and destruction.
255 TRACE_EVENT0("shutdown", "BrowserMainRunner");
256 g_exited_main_message_loop
= true;
258 main_loop_
->ShutdownThreadsAndCleanUp();
260 ui::ShutdownInputMethod();
262 ole_initializer_
.reset(NULL
);
264 #if defined(OS_ANDROID)
265 // Forcefully terminates the RunLoop inside MessagePumpForUI, ensuring
266 // proper shutdown for content_browsertests. Shutdown() is not used by
267 // the actual browser.
268 if (base::MessageLoop::current()->is_running())
269 base::MessageLoop::current()->QuitNow();
271 main_loop_
.reset(NULL
);
273 notification_service_
.reset(NULL
);
280 // True if we have started to initialize the runner.
281 bool initialization_started_
;
283 // True if the runner has been shut down.
286 scoped_ptr
<NotificationServiceImpl
> notification_service_
;
287 scoped_ptr
<BrowserMainLoop
> main_loop_
;
289 scoped_ptr
<ui::ScopedOleInitializer
> ole_initializer_
;
292 DISALLOW_COPY_AND_ASSIGN(BrowserMainRunnerImpl
);
296 BrowserMainRunner
* BrowserMainRunner::Create() {
297 return new BrowserMainRunnerImpl();
300 } // namespace content