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/browser/browser_main_loop.h"
8 #include "base/command_line.h"
9 #include "base/debug/trace_event.h"
10 #include "base/logging.h"
11 #include "base/message_loop/message_loop.h"
12 #include "base/metrics/field_trial.h"
13 #include "base/metrics/histogram.h"
14 #include "base/pending_task.h"
15 #include "base/power_monitor/power_monitor.h"
16 #include "base/power_monitor/power_monitor_device_source.h"
17 #include "base/process/process_metrics.h"
18 #include "base/run_loop.h"
19 #include "base/strings/string_number_conversions.h"
20 #include "base/system_monitor/system_monitor.h"
21 #include "base/thread_task_runner_handle.h"
22 #include "base/threading/thread_restrictions.h"
23 #include "base/timer/hi_res_timer_manager.h"
24 #include "content/browser/browser_thread_impl.h"
25 #include "content/browser/device_sensors/device_inertial_sensor_service.h"
26 #include "content/browser/download/save_file_manager.h"
27 #include "content/browser/gamepad/gamepad_service.h"
28 #include "content/browser/gpu/browser_gpu_channel_host_factory.h"
29 #include "content/browser/gpu/compositor_util.h"
30 #include "content/browser/gpu/gpu_data_manager_impl.h"
31 #include "content/browser/gpu/gpu_process_host.h"
32 #include "content/browser/gpu/gpu_process_host_ui_shim.h"
33 #include "content/browser/histogram_synchronizer.h"
34 #include "content/browser/loader/resource_dispatcher_host_impl.h"
35 #include "content/browser/media/media_internals.h"
36 #include "content/browser/net/browser_online_state_observer.h"
37 #include "content/browser/renderer_host/media/media_stream_manager.h"
38 #include "content/browser/speech/speech_recognition_manager_impl.h"
39 #include "content/browser/startup_task_runner.h"
40 #include "content/browser/time_zone_monitor.h"
41 #include "content/browser/webui/content_web_ui_controller_factory.h"
42 #include "content/browser/webui/url_data_manager.h"
43 #include "content/public/browser/browser_main_parts.h"
44 #include "content/public/browser/browser_shutdown.h"
45 #include "content/public/browser/content_browser_client.h"
46 #include "content/public/browser/render_process_host.h"
47 #include "content/public/browser/tracing_controller.h"
48 #include "content/public/common/content_switches.h"
49 #include "content/public/common/main_function_params.h"
50 #include "content/public/common/result_codes.h"
51 #include "crypto/nss_util.h"
52 #include "device/battery/battery_status_service.h"
53 #include "media/audio/audio_manager.h"
54 #include "media/base/media.h"
55 #include "media/base/user_input_monitor.h"
56 #include "media/midi/midi_manager.h"
57 #include "net/base/network_change_notifier.h"
58 #include "net/socket/client_socket_factory.h"
59 #include "net/ssl/ssl_config_service.h"
60 #include "ui/base/clipboard/clipboard.h"
62 #if defined(USE_AURA) || (defined(OS_MACOSX) && !defined(OS_IOS))
63 #include "content/browser/compositor/image_transport_factory.h"
67 #include "content/public/browser/context_factory.h"
68 #include "ui/aura/env.h"
72 #include "content/browser/renderer_host/render_process_host_impl.h"
75 #if defined(OS_ANDROID)
76 #include "base/android/jni_android.h"
77 #include "content/browser/android/browser_startup_controller.h"
78 #include "content/browser/android/browser_surface_texture_manager.h"
79 #include "content/browser/android/tracing_controller_android.h"
80 #include "content/browser/screen_orientation/screen_orientation_delegate_android.h"
81 #include "content/public/browser/screen_orientation_provider.h"
82 #include "ui/gl/gl_surface.h"
85 #if defined(OS_MACOSX) && !defined(OS_IOS)
86 #include "content/browser/bootstrap_sandbox_mac.h"
87 #include "content/browser/cocoa/system_hotkey_helper_mac.h"
88 #include "content/browser/compositor/browser_compositor_view_mac.h"
89 #include "content/browser/theme_helper_mac.h"
97 #include "content/browser/system_message_window_win.h"
98 #include "content/common/sandbox_win.h"
99 #include "net/base/winsock_init.h"
100 #include "ui/base/l10n/l10n_util_win.h"
103 #if defined(USE_GLIB)
104 #include <glib-object.h>
107 #if defined(OS_LINUX) && defined(USE_UDEV)
108 #include "content/browser/device_monitor_udev.h"
109 #elif defined(OS_MACOSX) && !defined(OS_IOS)
110 #include "content/browser/device_monitor_mac.h"
113 #if defined(OS_POSIX) && !defined(OS_MACOSX)
114 #include "content/browser/renderer_host/render_sandbox_host_linux.h"
115 #include "content/browser/zygote_host/zygote_host_impl_linux.h"
116 #include "sandbox/linux/suid/client/setuid_sandbox_client.h"
119 #if defined(ENABLE_PLUGINS)
120 #include "content/browser/plugin_service_impl.h"
123 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
124 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
128 #include "ui/gfx/x/x11_connection.h"
129 #include "ui/gfx/x/x11_types.h"
132 // One of the linux specific headers defines this as a macro.
140 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
141 void SetupSandbox(const base::CommandLine
& parsed_command_line
) {
142 TRACE_EVENT0("startup", "SetupSandbox");
143 base::FilePath sandbox_binary
;
145 scoped_ptr
<sandbox::SetuidSandboxClient
> setuid_sandbox_client(
146 sandbox::SetuidSandboxClient::Create());
148 const bool want_setuid_sandbox
=
149 !parsed_command_line
.HasSwitch(switches::kNoSandbox
) &&
150 !parsed_command_line
.HasSwitch(switches::kDisableSetuidSandbox
) &&
151 !setuid_sandbox_client
->IsDisabledViaEnvironment();
153 static const char no_suid_error
[] =
154 "Running without the SUID sandbox! See "
155 "https://code.google.com/p/chromium/wiki/LinuxSUIDSandboxDevelopment "
156 "for more information on developing with the sandbox on.";
157 if (want_setuid_sandbox
) {
158 sandbox_binary
= setuid_sandbox_client
->GetSandboxBinaryPath();
159 if (sandbox_binary
.empty()) {
160 // This needs to be fatal. Talk to security@chromium.org if you feel
162 LOG(FATAL
) << no_suid_error
;
165 LOG(ERROR
) << no_suid_error
;
168 // Tickle the sandbox host and zygote host so they fork now.
169 RenderSandboxHostLinux::GetInstance()->Init();
170 ZygoteHostImpl::GetInstance()->Init(sandbox_binary
.value());
174 #if defined(USE_GLIB)
175 static void GLibLogHandler(const gchar
* log_domain
,
176 GLogLevelFlags log_level
,
177 const gchar
* message
,
180 log_domain
= "<unknown>";
182 message
= "<no message>";
184 if (strstr(message
, "Unable to retrieve the file info for")) {
185 LOG(ERROR
) << "GTK File code error: " << message
;
186 } else if (strstr(message
, "Could not find the icon") &&
187 strstr(log_domain
, "Gtk")) {
188 LOG(ERROR
) << "GTK icon error: " << message
;
189 } else if (strstr(message
, "Theme file for default has no") ||
190 strstr(message
, "Theme directory") ||
191 strstr(message
, "theme pixmap") ||
192 strstr(message
, "locate theme engine")) {
193 LOG(ERROR
) << "GTK theme error: " << message
;
194 } else if (strstr(message
, "Unable to create Ubuntu Menu Proxy") &&
195 strstr(log_domain
, "<unknown>")) {
196 LOG(ERROR
) << "GTK menu proxy create failed";
197 } else if (strstr(message
, "Out of memory") &&
198 strstr(log_domain
, "<unknown>")) {
199 LOG(ERROR
) << "DBus call timeout or out of memory: "
200 << "http://crosbug.com/15496";
201 } else if (strstr(message
, "Could not connect: Connection refused") &&
202 strstr(log_domain
, "<unknown>")) {
203 LOG(ERROR
) << "DConf settings backend could not connect to session bus: "
204 << "http://crbug.com/179797";
205 } else if (strstr(message
, "Attempting to store changes into") ||
206 strstr(message
, "Attempting to set the permissions of")) {
207 LOG(ERROR
) << message
<< " (http://bugs.chromium.org/161366)";
208 } else if (strstr(message
, "drawable is not a native X11 window")) {
209 LOG(ERROR
) << message
<< " (http://bugs.chromium.org/329991)";
211 LOG(DFATAL
) << log_domain
<< ": " << message
;
215 static void SetUpGLibLogHandler() {
216 // Register GLib-handled assertions to go through our logging system.
217 const char* kLogDomains
[] = { NULL
, "Gtk", "Gdk", "GLib", "GLib-GObject" };
218 for (size_t i
= 0; i
< arraysize(kLogDomains
); i
++) {
219 g_log_set_handler(kLogDomains
[i
],
220 static_cast<GLogLevelFlags
>(G_LOG_FLAG_RECURSION
|
223 G_LOG_LEVEL_CRITICAL
|
224 G_LOG_LEVEL_WARNING
),
231 void OnStoppedStartupTracing(const base::FilePath
& trace_file
) {
232 VLOG(0) << "Completed startup tracing to " << trace_file
.value();
235 // Disable optimizations for this block of functions so the compiler doesn't
236 // merge them all together. This makes it possible to tell what thread was
237 // unresponsive by inspecting the callstack.
238 MSVC_DISABLE_OPTIMIZE()
239 MSVC_PUSH_DISABLE_WARNING(4748)
241 NOINLINE
void ResetThread_DB(scoped_ptr
<BrowserProcessSubThread
> thread
) {
242 volatile int inhibit_comdat
= __LINE__
;
243 ALLOW_UNUSED_LOCAL(inhibit_comdat
);
247 NOINLINE
void ResetThread_FILE(scoped_ptr
<BrowserProcessSubThread
> thread
) {
248 volatile int inhibit_comdat
= __LINE__
;
249 ALLOW_UNUSED_LOCAL(inhibit_comdat
);
253 NOINLINE
void ResetThread_FILE_USER_BLOCKING(
254 scoped_ptr
<BrowserProcessSubThread
> thread
) {
255 volatile int inhibit_comdat
= __LINE__
;
256 ALLOW_UNUSED_LOCAL(inhibit_comdat
);
260 NOINLINE
void ResetThread_PROCESS_LAUNCHER(
261 scoped_ptr
<BrowserProcessSubThread
> thread
) {
262 volatile int inhibit_comdat
= __LINE__
;
263 ALLOW_UNUSED_LOCAL(inhibit_comdat
);
267 NOINLINE
void ResetThread_CACHE(scoped_ptr
<BrowserProcessSubThread
> thread
) {
268 volatile int inhibit_comdat
= __LINE__
;
269 ALLOW_UNUSED_LOCAL(inhibit_comdat
);
273 NOINLINE
void ResetThread_IO(scoped_ptr
<BrowserProcessSubThread
> thread
) {
274 volatile int inhibit_comdat
= __LINE__
;
275 ALLOW_UNUSED_LOCAL(inhibit_comdat
);
280 NOINLINE
void ResetThread_IndexedDb(scoped_ptr
<base::Thread
> thread
) {
281 volatile int inhibit_comdat
= __LINE__
;
282 ALLOW_UNUSED_LOCAL(inhibit_comdat
);
288 MSVC_ENABLE_OPTIMIZE();
292 // The currently-running BrowserMainLoop. There can be one or zero.
293 BrowserMainLoop
* g_current_browser_main_loop
= NULL
;
295 // This is just to be able to keep ShutdownThreadsAndCleanUp out of
296 // the public interface of BrowserMainLoop.
297 class BrowserShutdownImpl
{
299 static void ImmediateShutdownAndExitProcess() {
300 DCHECK(g_current_browser_main_loop
);
301 g_current_browser_main_loop
->ShutdownThreadsAndCleanUp();
304 // At this point the message loop is still running yet we've shut everything
305 // down. If any messages are processed we'll likely crash. Exit now.
306 ExitProcess(RESULT_CODE_NORMAL_EXIT
);
307 #elif defined(OS_POSIX) && !defined(OS_MACOSX)
308 _exit(RESULT_CODE_NORMAL_EXIT
);
315 void ImmediateShutdownAndExitProcess() {
316 BrowserShutdownImpl::ImmediateShutdownAndExitProcess();
319 // For measuring memory usage after each task. Behind a command line flag.
320 class BrowserMainLoop::MemoryObserver
: public base::MessageLoop::TaskObserver
{
323 ~MemoryObserver() override
{}
325 void WillProcessTask(const base::PendingTask
& pending_task
) override
{}
327 void DidProcessTask(const base::PendingTask
& pending_task
) override
{
328 #if !defined(OS_IOS) // No ProcessMetrics on IOS.
329 scoped_ptr
<base::ProcessMetrics
> process_metrics(
330 base::ProcessMetrics::CreateProcessMetrics(
331 #if defined(OS_MACOSX)
332 base::GetCurrentProcessHandle(), NULL
));
334 base::GetCurrentProcessHandle()));
336 size_t private_bytes
;
337 process_metrics
->GetMemoryBytes(&private_bytes
, NULL
);
338 LOCAL_HISTOGRAM_MEMORY_KB("Memory.BrowserUsed", private_bytes
>> 10);
342 DISALLOW_COPY_AND_ASSIGN(MemoryObserver
);
346 // BrowserMainLoop construction / destruction =============================
348 BrowserMainLoop
* BrowserMainLoop::GetInstance() {
349 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
350 return g_current_browser_main_loop
;
353 BrowserMainLoop::BrowserMainLoop(const MainFunctionParams
& parameters
)
354 : parameters_(parameters
),
355 parsed_command_line_(parameters
.command_line
),
356 result_code_(RESULT_CODE_NORMAL_EXIT
),
357 created_threads_(false),
358 // ContentMainRunner should have enabled tracing of the browser process
359 // when kTraceStartup is in the command line.
361 parameters
.command_line
.HasSwitch(switches::kTraceStartup
)) {
362 DCHECK(!g_current_browser_main_loop
);
363 g_current_browser_main_loop
= this;
366 BrowserMainLoop::~BrowserMainLoop() {
367 DCHECK_EQ(this, g_current_browser_main_loop
);
369 ui::Clipboard::DestroyClipboardForCurrentThread();
370 #endif // !defined(OS_IOS)
371 g_current_browser_main_loop
= NULL
;
374 void BrowserMainLoop::Init() {
375 TRACE_EVENT0("startup", "BrowserMainLoop::Init");
377 GetContentClient()->browser()->CreateBrowserMainParts(parameters_
));
380 // BrowserMainLoop stages ==================================================
382 void BrowserMainLoop::EarlyInitialization() {
383 TRACE_EVENT0("startup", "BrowserMainLoop::EarlyInitialization");
385 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
386 // No thread should be created before this call, as SetupSandbox()
387 // will end-up using fork().
388 SetupSandbox(parsed_command_line_
);
392 if (parsed_command_line_
.HasSwitch(switches::kSingleProcess
) ||
393 parsed_command_line_
.HasSwitch(switches::kInProcessGPU
)) {
394 if (!gfx::InitializeThreadedX11()) {
395 LOG(ERROR
) << "Failed to put Xlib into threaded mode.";
400 // GLib's spawning of new processes is buggy, so it's important that at this
401 // point GLib does not need to start DBUS. Chrome should always start with
402 // DBUS_SESSION_BUS_ADDRESS properly set. See crbug.com/309093.
403 #if defined(USE_GLIB)
404 // g_type_init will be deprecated in 2.36. 2.35 is the development
405 // version for 2.36, hence do not call g_type_init starting 2.35.
406 // http://developer.gnome.org/gobject/unstable/gobject-Type-Information.html#g-type-init
407 #if !GLIB_CHECK_VERSION(2, 35, 0)
408 // GLib type system initialization. Needed at least for gconf,
409 // used in net/proxy/proxy_config_service_linux.cc. Most likely
410 // this is superfluous as gtk_init() ought to do this. It's
411 // definitely harmless, so retained as a reminder of this
412 // requirement for gconf.
416 SetUpGLibLogHandler();
420 parts_
->PreEarlyInitialization();
422 #if defined(OS_MACOSX)
423 // We use quite a few file descriptors for our IPC, and the default limit on
424 // the Mac is low (256), so bump it up.
425 base::SetFdLimit(1024);
429 net::EnsureWinsockInit();
432 #if !defined(USE_OPENSSL)
433 // We want to be sure to init NSPR on the main thread.
434 crypto::EnsureNSPRInit();
435 #endif // !defined(USE_OPENSSL)
438 if (parsed_command_line_
.HasSwitch(switches::kRendererProcessLimit
)) {
439 std::string limit_string
= parsed_command_line_
.GetSwitchValueASCII(
440 switches::kRendererProcessLimit
);
441 size_t process_limit
;
442 if (base::StringToSizeT(limit_string
, &process_limit
)) {
443 RenderProcessHost::SetMaxRendererProcessCount(process_limit
);
446 #endif // !defined(OS_IOS)
448 if (parsed_command_line_
.HasSwitch(switches::kEnableNativeGpuMemoryBuffers
)) {
449 BrowserGpuChannelHostFactory::EnableGpuMemoryBufferFactoryUsage(
450 gfx::GpuMemoryBuffer::MAP
);
453 #if defined(USE_OZONE)
454 BrowserGpuChannelHostFactory::EnableGpuMemoryBufferFactoryUsage(
455 gfx::GpuMemoryBuffer::SCANOUT
);
459 parts_
->PostEarlyInitialization();
462 void BrowserMainLoop::MainMessageLoopStart() {
463 TRACE_EVENT0("startup", "BrowserMainLoop::MainMessageLoopStart");
465 TRACE_EVENT0("startup",
466 "BrowserMainLoop::MainMessageLoopStart:PreMainMessageLoopStart");
467 parts_
->PreMainMessageLoopStart();
471 // If we're running tests (ui_task is non-null), then the ResourceBundle
472 // has already been initialized.
473 if (!parameters_
.ui_task
) {
474 // Override the configured locale with the user's preferred UI language.
475 l10n_util::OverrideLocaleWithUILanguageList();
479 // Create a MessageLoop if one does not already exist for the current thread.
480 if (!base::MessageLoop::current())
481 main_message_loop_
.reset(new base::MessageLoopForUI
);
483 InitializeMainThread();
486 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SystemMonitor");
487 system_monitor_
.reset(new base::SystemMonitor
);
490 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:PowerMonitor");
491 scoped_ptr
<base::PowerMonitorSource
> power_monitor_source(
492 new base::PowerMonitorDeviceSource());
493 power_monitor_
.reset(new base::PowerMonitor(power_monitor_source
.Pass()));
496 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:HighResTimerManager");
497 hi_res_timer_manager_
.reset(new base::HighResolutionTimerManager
);
500 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:NetworkChangeNotifier");
501 network_change_notifier_
.reset(net::NetworkChangeNotifier::Create());
506 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MediaFeatures");
507 media::InitializeCPUSpecificMediaFeatures();
510 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:AudioMan");
511 audio_manager_
.reset(media::AudioManager::Create(
512 MediaInternals::GetInstance()));
515 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MidiManager");
516 midi_manager_
.reset(media::MidiManager::Create());
519 TRACE_EVENT0("startup",
520 "BrowserMainLoop::Subsystem:ContentWebUIController");
521 WebUIControllerFactory::RegisterFactory(
522 ContentWebUIControllerFactory::GetInstance());
526 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:OnlineStateObserver");
527 online_state_observer_
.reset(new BrowserOnlineStateObserver
);
531 system_stats_monitor_
.reset(new base::debug::TraceEventSystemStatsMonitor(
532 base::ThreadTaskRunnerHandle::Get()));
534 #endif // !defined(OS_IOS)
537 system_message_window_
.reset(new SystemMessageWindowWin
);
541 parts_
->PostMainMessageLoopStart();
544 // Start tracing to a file if needed. Only do this after starting the main
545 // message loop to avoid calling MessagePumpForUI::ScheduleWork() before
546 // MessagePumpForUI::Start() as it will crash the browser.
547 if (is_tracing_startup_
) {
548 TRACE_EVENT0("startup", "BrowserMainLoop::InitStartupTracing");
549 InitStartupTracing(parsed_command_line_
);
551 #endif // !defined(OS_IOS)
553 #if defined(OS_ANDROID)
555 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SurfaceTextureManager");
556 SurfaceTextureManager::InitInstance(new BrowserSurfaceTextureManager
);
560 TRACE_EVENT0("startup",
561 "BrowserMainLoop::Subsystem:ScreenOrientationProvider");
562 screen_orientation_delegate_
.reset(
563 new ScreenOrientationDelegateAndroid());
564 ScreenOrientationProvider::SetDelegate(screen_orientation_delegate_
.get());
568 if (parsed_command_line_
.HasSwitch(switches::kMemoryMetrics
)) {
569 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MemoryObserver");
570 memory_observer_
.reset(new MemoryObserver());
571 base::MessageLoop::current()->AddTaskObserver(memory_observer_
.get());
574 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
575 trace_memory_controller_
.reset(new base::debug::TraceMemoryController(
576 base::MessageLoop::current()->message_loop_proxy(),
577 ::HeapProfilerWithPseudoStackStart
,
583 int BrowserMainLoop::PreCreateThreads() {
585 TRACE_EVENT0("startup",
586 "BrowserMainLoop::CreateThreads:PreCreateThreads");
587 result_code_
= parts_
->PreCreateThreads();
590 #if defined(ENABLE_PLUGINS)
591 // Prior to any processing happening on the io thread, we create the
592 // plugin service as it is predominantly used from the io thread,
593 // but must be created on the main thread. The service ctor is
594 // inexpensive and does not invoke the io_thread() accessor.
596 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads:PluginService");
597 PluginService::GetInstance()->Init();
601 #if !defined(OS_IOS) && (!defined(GOOGLE_CHROME_BUILD) || defined(OS_ANDROID))
602 // Single-process is an unsupported and not fully tested mode, so
603 // don't enable it for official Chrome builds (except on Android).
604 if (parsed_command_line_
.HasSwitch(switches::kSingleProcess
))
605 RenderProcessHost::SetRunRendererInProcess(true);
610 void BrowserMainLoop::CreateStartupTasks() {
611 TRACE_EVENT0("startup", "BrowserMainLoop::CreateStartupTasks");
613 // First time through, we really want to create all the tasks
614 if (!startup_task_runner_
.get()) {
615 #if defined(OS_ANDROID)
616 startup_task_runner_
= make_scoped_ptr(new StartupTaskRunner(
617 base::Bind(&BrowserStartupComplete
),
618 base::MessageLoop::current()->message_loop_proxy()));
620 startup_task_runner_
= make_scoped_ptr(new StartupTaskRunner(
621 base::Callback
<void(int)>(),
622 base::MessageLoop::current()->message_loop_proxy()));
624 StartupTask pre_create_threads
=
625 base::Bind(&BrowserMainLoop::PreCreateThreads
, base::Unretained(this));
626 startup_task_runner_
->AddTask(pre_create_threads
);
628 StartupTask create_threads
=
629 base::Bind(&BrowserMainLoop::CreateThreads
, base::Unretained(this));
630 startup_task_runner_
->AddTask(create_threads
);
632 StartupTask browser_thread_started
= base::Bind(
633 &BrowserMainLoop::BrowserThreadsStarted
, base::Unretained(this));
634 startup_task_runner_
->AddTask(browser_thread_started
);
636 StartupTask pre_main_message_loop_run
= base::Bind(
637 &BrowserMainLoop::PreMainMessageLoopRun
, base::Unretained(this));
638 startup_task_runner_
->AddTask(pre_main_message_loop_run
);
640 #if defined(OS_ANDROID)
641 if (BrowserMayStartAsynchronously()) {
642 startup_task_runner_
->StartRunningTasksAsync();
646 #if defined(OS_ANDROID)
647 if (!BrowserMayStartAsynchronously()) {
648 // A second request for asynchronous startup can be ignored, so
649 // StartupRunningTasksAsync is only called first time through. If, however,
650 // this is a request for synchronous startup then it must override any
651 // previous call for async startup, so we call RunAllTasksNow()
653 startup_task_runner_
->RunAllTasksNow();
656 startup_task_runner_
->RunAllTasksNow();
660 int BrowserMainLoop::CreateThreads() {
661 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads");
663 base::Thread::Options io_message_loop_options
;
664 io_message_loop_options
.message_loop_type
= base::MessageLoop::TYPE_IO
;
665 base::Thread::Options ui_message_loop_options
;
666 ui_message_loop_options
.message_loop_type
= base::MessageLoop::TYPE_UI
;
668 // Start threads in the order they occur in the BrowserThread::ID
669 // enumeration, except for BrowserThread::UI which is the main
672 // Must be size_t so we can increment it.
673 for (size_t thread_id
= BrowserThread::UI
+ 1;
674 thread_id
< BrowserThread::ID_COUNT
;
676 scoped_ptr
<BrowserProcessSubThread
>* thread_to_start
= NULL
;
677 base::Thread::Options options
;
680 case BrowserThread::DB
:
681 TRACE_EVENT_BEGIN1("startup",
682 "BrowserMainLoop::CreateThreads:start",
683 "Thread", "BrowserThread::DB");
684 thread_to_start
= &db_thread_
;
685 options
.timer_slack
= base::TIMER_SLACK_MAXIMUM
;
687 case BrowserThread::FILE_USER_BLOCKING
:
688 TRACE_EVENT_BEGIN1("startup",
689 "BrowserMainLoop::CreateThreads:start",
690 "Thread", "BrowserThread::FILE_USER_BLOCKING");
691 thread_to_start
= &file_user_blocking_thread_
;
693 case BrowserThread::FILE:
694 TRACE_EVENT_BEGIN1("startup",
695 "BrowserMainLoop::CreateThreads:start",
696 "Thread", "BrowserThread::FILE");
697 thread_to_start
= &file_thread_
;
699 // On Windows, the FILE thread needs to be have a UI message loop
700 // which pumps messages in such a way that Google Update can
701 // communicate back to us.
702 options
= ui_message_loop_options
;
704 options
= io_message_loop_options
;
706 options
.timer_slack
= base::TIMER_SLACK_MAXIMUM
;
708 case BrowserThread::PROCESS_LAUNCHER
:
709 TRACE_EVENT_BEGIN1("startup",
710 "BrowserMainLoop::CreateThreads:start",
711 "Thread", "BrowserThread::PROCESS_LAUNCHER");
712 thread_to_start
= &process_launcher_thread_
;
713 options
.timer_slack
= base::TIMER_SLACK_MAXIMUM
;
715 case BrowserThread::CACHE
:
716 TRACE_EVENT_BEGIN1("startup",
717 "BrowserMainLoop::CreateThreads:start",
718 "Thread", "BrowserThread::CACHE");
719 thread_to_start
= &cache_thread_
;
720 options
= io_message_loop_options
;
721 options
.timer_slack
= base::TIMER_SLACK_MAXIMUM
;
723 case BrowserThread::IO
:
724 TRACE_EVENT_BEGIN1("startup",
725 "BrowserMainLoop::CreateThreads:start",
726 "Thread", "BrowserThread::IO");
727 thread_to_start
= &io_thread_
;
728 options
= io_message_loop_options
;
730 case BrowserThread::UI
:
731 case BrowserThread::ID_COUNT
:
737 BrowserThread::ID id
= static_cast<BrowserThread::ID
>(thread_id
);
739 if (thread_to_start
) {
740 (*thread_to_start
).reset(new BrowserProcessSubThread(id
));
741 if (!(*thread_to_start
)->StartWithOptions(options
)) {
742 LOG(FATAL
) << "Failed to start the browser thread: id == " << id
;
748 TRACE_EVENT_END0("startup", "BrowserMainLoop::CreateThreads:start");
750 created_threads_
= true;
754 int BrowserMainLoop::PreMainMessageLoopRun() {
756 TRACE_EVENT0("startup",
757 "BrowserMainLoop::CreateThreads:PreMainMessageLoopRun");
758 parts_
->PreMainMessageLoopRun();
761 // If the UI thread blocks, the whole UI is unresponsive.
762 // Do not allow disk IO from the UI thread.
763 base::ThreadRestrictions::SetIOAllowed(false);
764 base::ThreadRestrictions::DisallowWaiting();
768 void BrowserMainLoop::RunMainMessageLoopParts() {
769 TRACE_EVENT_BEGIN_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
771 bool ran_main_loop
= false;
773 ran_main_loop
= parts_
->MainMessageLoopRun(&result_code_
);
776 MainMessageLoopRun();
778 TRACE_EVENT_END_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
781 void BrowserMainLoop::ShutdownThreadsAndCleanUp() {
782 if (!created_threads_
) {
783 // Called early, nothing to do
786 TRACE_EVENT0("shutdown", "BrowserMainLoop::ShutdownThreadsAndCleanUp");
788 // Teardown may start in PostMainMessageLoopRun, and during teardown we
789 // need to be able to perform IO.
790 base::ThreadRestrictions::SetIOAllowed(true);
791 BrowserThread::PostTask(
792 BrowserThread::IO
, FROM_HERE
,
793 base::Bind(base::IgnoreResult(&base::ThreadRestrictions::SetIOAllowed
),
797 if (RenderProcessHost::run_renderer_in_process())
798 RenderProcessHostImpl::ShutDownInProcessRenderer();
802 TRACE_EVENT0("shutdown",
803 "BrowserMainLoop::Subsystem:PostMainMessageLoopRun");
804 parts_
->PostMainMessageLoopRun();
807 trace_memory_controller_
.reset();
808 system_stats_monitor_
.reset();
811 // Destroying the GpuProcessHostUIShims on the UI thread posts a task to
812 // delete related objects on the GPU thread. This must be done before
813 // stopping the GPU thread. The GPU thread will close IPC channels to renderer
814 // processes so this has to happen before stopping the IO thread.
816 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUProcessHostShim");
817 GpuProcessHostUIShim::DestroyAll();
819 // Cancel pending requests and prevent new requests.
820 if (resource_dispatcher_host_
) {
821 TRACE_EVENT0("shutdown",
822 "BrowserMainLoop::Subsystem:ResourceDispatcherHost");
823 resource_dispatcher_host_
.get()->Shutdown();
826 #if defined(OS_MACOSX)
827 BrowserCompositorMac::DisableRecyclingForShutdown();
830 #if defined(USE_AURA) || defined(OS_MACOSX)
832 TRACE_EVENT0("shutdown",
833 "BrowserMainLoop::Subsystem:ImageTransportFactory");
834 ImageTransportFactory::Terminate();
838 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
839 ZygoteHostImpl::GetInstance()->TearDownAfterLastChild();
840 #endif // defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
842 // The device monitors are using |system_monitor_| as dependency, so delete
843 // them before |system_monitor_| goes away.
844 // On Mac and windows, the monitor needs to be destroyed on the same thread
845 // as they were created. On Linux, the monitor will be deleted when IO thread
848 system_message_window_
.reset();
849 #elif defined(OS_MACOSX)
850 device_monitor_mac_
.reset();
852 #endif // !defined(OS_IOS)
854 // Must be size_t so we can subtract from it.
855 for (size_t thread_id
= BrowserThread::ID_COUNT
- 1;
856 thread_id
>= (BrowserThread::UI
+ 1);
858 // Find the thread object we want to stop. Looping over all valid
859 // BrowserThread IDs and DCHECKing on a missing case in the switch
860 // statement helps avoid a mismatch between this code and the
861 // BrowserThread::ID enumeration.
863 // The destruction order is the reverse order of occurrence in the
864 // BrowserThread::ID list. The rationale for the order is as
865 // follows (need to be filled in a bit):
868 // - The IO thread is the only user of the CACHE thread.
870 // - The PROCESS_LAUNCHER thread must be stopped after IO in case
871 // the IO thread posted a task to terminate a process on the
872 // process launcher thread.
874 // - (Not sure why DB stops last.)
876 case BrowserThread::DB
: {
877 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DBThread");
878 ResetThread_DB(db_thread_
.Pass());
881 case BrowserThread::FILE: {
882 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:FileThread");
884 // Clean up state that lives on or uses the file_thread_ before
886 if (resource_dispatcher_host_
)
887 resource_dispatcher_host_
.get()->save_file_manager()->Shutdown();
888 #endif // !defined(OS_IOS)
889 ResetThread_FILE(file_thread_
.Pass());
892 case BrowserThread::FILE_USER_BLOCKING
: {
893 TRACE_EVENT0("shutdown",
894 "BrowserMainLoop::Subsystem:FileUserBlockingThread");
895 ResetThread_FILE_USER_BLOCKING(file_user_blocking_thread_
.Pass());
898 case BrowserThread::PROCESS_LAUNCHER
: {
899 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:LauncherThread");
900 ResetThread_PROCESS_LAUNCHER(process_launcher_thread_
.Pass());
903 case BrowserThread::CACHE
: {
904 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:CacheThread");
905 ResetThread_CACHE(cache_thread_
.Pass());
908 case BrowserThread::IO
: {
909 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IOThread");
910 ResetThread_IO(io_thread_
.Pass());
913 case BrowserThread::UI
:
914 case BrowserThread::ID_COUNT
:
923 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IndexedDBThread");
924 ResetThread_IndexedDb(indexed_db_thread_
.Pass());
928 // Close the blocking I/O pool after the other threads. Other threads such
929 // as the I/O thread may need to schedule work like closing files or flushing
930 // data during shutdown, so the blocking pool needs to be available. There
931 // may also be slow operations pending that will blcok shutdown, so closing
932 // it here (which will block until required operations are complete) gives
933 // more head start for those operations to finish.
935 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:ThreadPool");
936 BrowserThreadImpl::ShutdownThreadPool();
940 // Must happen after the IO thread is shutdown since this may be accessed from
943 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUChannelFactory");
944 if (BrowserGpuChannelHostFactory::instance())
945 BrowserGpuChannelHostFactory::Terminate();
948 // Must happen after the I/O thread is shutdown since this class lives on the
949 // I/O thread and isn't threadsafe.
951 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GamepadService");
952 GamepadService::GetInstance()->Terminate();
955 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:SensorService");
956 DeviceInertialSensorService::GetInstance()->Shutdown();
959 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:BatteryStatusService");
960 device::BatteryStatusService::GetInstance()->Shutdown();
963 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DeleteDataSources");
964 URLDataManager::DeleteDataSources();
966 #endif // !defined(OS_IOS)
969 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:PostDestroyThreads");
970 parts_
->PostDestroyThreads();
974 void BrowserMainLoop::StopStartupTracingTimer() {
975 startup_trace_timer_
.Stop();
978 void BrowserMainLoop::InitializeMainThread() {
979 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeMainThread");
980 const char* kThreadName
= "CrBrowserMain";
981 base::PlatformThread::SetName(kThreadName
);
982 if (main_message_loop_
)
983 main_message_loop_
->set_thread_name(kThreadName
);
985 // Register the main thread by instantiating it, but don't call any methods.
987 new BrowserThreadImpl(BrowserThread::UI
, base::MessageLoop::current()));
990 int BrowserMainLoop::BrowserThreadsStarted() {
991 TRACE_EVENT0("startup", "BrowserMainLoop::BrowserThreadsStarted");
994 indexed_db_thread_
.reset(new base::Thread("IndexedDB"));
995 indexed_db_thread_
->Start();
998 #if defined(OS_ANDROID)
999 // Up the priority of anything that touches with display tasks
1000 // (this thread is UI thread, and io_thread_ is for IPCs).
1001 io_thread_
->SetPriority(base::kThreadPriority_Display
);
1002 base::PlatformThread::SetThreadPriority(
1003 base::PlatformThread::CurrentHandle(),
1004 base::kThreadPriority_Display
);
1007 #if !defined(OS_IOS)
1008 HistogramSynchronizer::GetInstance();
1010 bool initialize_gpu_data_manager
= true;
1011 #if defined(OS_ANDROID)
1012 // On Android, GLSurface::InitializeOneOff() must be called before initalizing
1013 // the GpuDataManagerImpl as it uses the GL bindings. crbug.com/326295
1014 if (!gfx::GLSurface::InitializeOneOff()) {
1015 LOG(ERROR
) << "GLSurface::InitializeOneOff failed";
1016 initialize_gpu_data_manager
= false;
1020 // Initialize the GpuDataManager before we set up the MessageLoops because
1021 // otherwise we'll trigger the assertion about doing IO on the UI thread.
1022 if (initialize_gpu_data_manager
)
1023 GpuDataManagerImpl::GetInstance()->Initialize();
1025 bool always_uses_gpu
= true;
1026 bool established_gpu_channel
= false;
1027 #if defined(USE_AURA) || defined(OS_MACOSX)
1028 established_gpu_channel
= true;
1029 if (!GpuDataManagerImpl::GetInstance()->CanUseGpuBrowserCompositor()) {
1030 established_gpu_channel
= always_uses_gpu
= false;
1032 BrowserGpuChannelHostFactory::Initialize(established_gpu_channel
);
1033 ImageTransportFactory::Initialize();
1034 #if defined(USE_AURA)
1035 if (aura::Env::GetInstance()) {
1036 aura::Env::GetInstance()->set_context_factory(GetContextFactory());
1039 #elif defined(OS_ANDROID)
1040 // TODO(crbug.com/439322): This should be set to |true|.
1041 established_gpu_channel
= false;
1042 BrowserGpuChannelHostFactory::Initialize(established_gpu_channel
);
1045 #if defined(OS_LINUX) && defined(USE_UDEV)
1046 device_monitor_linux_
.reset(new DeviceMonitorLinux());
1047 #elif defined(OS_MACOSX)
1048 device_monitor_mac_
.reset(new DeviceMonitorMac());
1051 // RDH needs the IO thread to be created
1053 TRACE_EVENT0("startup",
1054 "BrowserMainLoop::BrowserThreadsStarted:InitResourceDispatcherHost");
1055 resource_dispatcher_host_
.reset(new ResourceDispatcherHostImpl());
1058 // MediaStreamManager needs the IO thread to be created.
1060 TRACE_EVENT0("startup",
1061 "BrowserMainLoop::BrowserThreadsStarted:InitMediaStreamManager");
1062 media_stream_manager_
.reset(new MediaStreamManager(audio_manager_
.get()));
1066 TRACE_EVENT0("startup",
1067 "BrowserMainLoop::BrowserThreadsStarted:InitSpeechRecognition");
1068 speech_recognition_manager_
.reset(new SpeechRecognitionManagerImpl(
1069 audio_manager_
.get(), media_stream_manager_
.get()));
1075 "BrowserMainLoop::BrowserThreadsStarted::InitUserInputMonitor");
1076 user_input_monitor_
= media::UserInputMonitor::Create(
1077 io_thread_
->message_loop_proxy(), main_thread_
->message_loop_proxy());
1081 TRACE_EVENT0("startup",
1082 "BrowserMainLoop::BrowserThreadsStarted::TimeZoneMonitor");
1083 time_zone_monitor_
= TimeZoneMonitor::Create();
1086 // Alert the clipboard class to which threads are allowed to access the
1088 std::vector
<base::PlatformThreadId
> allowed_clipboard_threads
;
1089 // The current thread is the UI thread.
1090 allowed_clipboard_threads
.push_back(base::PlatformThread::CurrentId());
1092 // On Windows, clipboards are also used on the File or IO threads.
1093 allowed_clipboard_threads
.push_back(file_thread_
->thread_id());
1094 allowed_clipboard_threads
.push_back(io_thread_
->thread_id());
1096 ui::Clipboard::SetAllowedThreads(allowed_clipboard_threads
);
1098 // When running the GPU thread in-process, avoid optimistically starting it
1099 // since creating the GPU thread races against creation of the one-and-only
1100 // ChildProcess instance which is created by the renderer thread.
1101 if (GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL
) &&
1102 !established_gpu_channel
&&
1104 !parsed_command_line_
.HasSwitch(switches::kSingleProcess
) &&
1105 !parsed_command_line_
.HasSwitch(switches::kInProcessGPU
)) {
1106 TRACE_EVENT_INSTANT0("gpu", "Post task to launch GPU process",
1107 TRACE_EVENT_SCOPE_THREAD
);
1108 BrowserThread::PostTask(
1109 BrowserThread::IO
, FROM_HERE
, base::Bind(
1110 base::IgnoreResult(&GpuProcessHost::Get
),
1111 GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED
,
1112 CAUSE_FOR_GPU_LAUNCH_BROWSER_STARTUP
));
1115 #if defined(OS_MACOSX)
1116 ThemeHelperMac::GetInstance();
1117 SystemHotkeyHelperMac::GetInstance()->DeferredLoadSystemHotkeys();
1118 if (ShouldEnableBootstrapSandbox()) {
1119 TRACE_EVENT0("startup",
1120 "BrowserMainLoop::BrowserThreadsStarted:BootstrapSandbox");
1121 CHECK(GetBootstrapSandbox());
1123 #endif // defined(OS_MACOSX)
1125 #endif // !defined(OS_IOS)
1127 return result_code_
;
1130 bool BrowserMainLoop::InitializeToolkit() {
1131 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeToolkit");
1132 // TODO(evan): this function is rather subtle, due to the variety
1133 // of intersecting ifdefs we have. To keep it easy to follow, there
1134 // are no #else branches on any #ifs.
1135 // TODO(stevenjb): Move platform specific code into platform specific Parts
1136 // (Need to add InitializeToolkit stage to BrowserParts).
1137 // See also GTK setup in EarlyInitialization, above, and associated comments.
1140 // Init common control sex.
1141 INITCOMMONCONTROLSEX config
;
1142 config
.dwSize
= sizeof(config
);
1143 config
.dwICC
= ICC_WIN95_CLASSES
;
1144 if (!InitCommonControlsEx(&config
))
1148 #if defined(USE_AURA)
1150 #if defined(USE_X11)
1151 if (!gfx::GetXDisplay())
1155 // Env creates the compositor. Aura widgets need the compositor to be created
1156 // before they can be initialized by the browser.
1157 aura::Env::CreateInstance(true);
1158 #endif // defined(USE_AURA)
1161 parts_
->ToolkitInitialized();
1166 void BrowserMainLoop::MainMessageLoopRun() {
1167 #if defined(OS_ANDROID)
1168 // Android's main message loop is the Java message loop.
1171 DCHECK(base::MessageLoopForUI::IsCurrent());
1172 if (parameters_
.ui_task
)
1173 base::MessageLoopForUI::current()->PostTask(FROM_HERE
,
1174 *parameters_
.ui_task
);
1176 base::RunLoop run_loop
;
1181 base::FilePath
BrowserMainLoop::GetStartupTraceFileName(
1182 const base::CommandLine
& command_line
) const {
1183 base::FilePath trace_file
= command_line
.GetSwitchValuePath(
1184 switches::kTraceStartupFile
);
1185 // trace_file = "none" means that startup events will show up for the next
1186 // begin/end tracing (via about:tracing or AutomationProxy::BeginTracing/
1187 // EndTracing, for example).
1188 if (trace_file
== base::FilePath().AppendASCII("none"))
1191 if (trace_file
.empty()) {
1192 #if defined(OS_ANDROID)
1193 TracingControllerAndroid::GenerateTracingFilePath(&trace_file
);
1195 // Default to saving the startup trace into the current dir.
1196 trace_file
= base::FilePath().AppendASCII("chrometrace.log");
1203 void BrowserMainLoop::InitStartupTracing(
1204 const base::CommandLine
& command_line
) {
1205 DCHECK(is_tracing_startup_
);
1207 startup_trace_file_
= GetStartupTraceFileName(parsed_command_line_
);
1209 std::string delay_str
= command_line
.GetSwitchValueASCII(
1210 switches::kTraceStartupDuration
);
1212 if (!delay_str
.empty() && !base::StringToInt(delay_str
, &delay_secs
)) {
1213 DLOG(WARNING
) << "Could not parse --" << switches::kTraceStartupDuration
1214 << "=" << delay_str
<< " defaulting to 5 (secs)";
1218 startup_trace_timer_
.Start(FROM_HERE
,
1219 base::TimeDelta::FromSeconds(delay_secs
),
1221 &BrowserMainLoop::EndStartupTracing
);
1224 void BrowserMainLoop::EndStartupTracing() {
1225 is_tracing_startup_
= false;
1226 TracingController::GetInstance()->DisableRecording(
1227 TracingController::CreateFileSink(
1228 startup_trace_file_
,
1229 base::Bind(OnStoppedStartupTracing
, startup_trace_file_
)));
1232 } // namespace content