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/file_util.h"
11 #include "base/logging.h"
12 #include "base/message_loop/message_loop.h"
13 #include "base/metrics/field_trial.h"
14 #include "base/metrics/histogram.h"
15 #include "base/path_service.h"
16 #include "base/pending_task.h"
17 #include "base/power_monitor/power_monitor.h"
18 #include "base/power_monitor/power_monitor_device_source.h"
19 #include "base/process/process_metrics.h"
20 #include "base/run_loop.h"
21 #include "base/strings/string_number_conversions.h"
22 #include "base/system_monitor/system_monitor.h"
23 #include "base/thread_task_runner_handle.h"
24 #include "base/threading/thread_restrictions.h"
25 #include "base/timer/hi_res_timer_manager.h"
26 #include "content/browser/browser_thread_impl.h"
27 #include "content/browser/device_sensors/device_inertial_sensor_service.h"
28 #include "content/browser/download/save_file_manager.h"
29 #include "content/browser/gamepad/gamepad_service.h"
30 #include "content/browser/gpu/browser_gpu_channel_host_factory.h"
31 #include "content/browser/gpu/compositor_util.h"
32 #include "content/browser/gpu/gpu_data_manager_impl.h"
33 #include "content/browser/gpu/gpu_process_host.h"
34 #include "content/browser/gpu/gpu_process_host_ui_shim.h"
35 #include "content/browser/histogram_synchronizer.h"
36 #include "content/browser/loader/resource_dispatcher_host_impl.h"
37 #include "content/browser/media/capture/audio_mirroring_manager.h"
38 #include "content/browser/media/media_internals.h"
39 #include "content/browser/net/browser_online_state_observer.h"
40 #include "content/browser/plugin_service_impl.h"
41 #include "content/browser/renderer_host/media/media_stream_manager.h"
42 #include "content/browser/speech/speech_recognition_manager_impl.h"
43 #include "content/browser/startup_task_runner.h"
44 #include "content/browser/time_zone_monitor.h"
45 #include "content/browser/webui/content_web_ui_controller_factory.h"
46 #include "content/browser/webui/url_data_manager.h"
47 #include "content/public/browser/browser_main_parts.h"
48 #include "content/public/browser/browser_shutdown.h"
49 #include "content/public/browser/content_browser_client.h"
50 #include "content/public/browser/render_process_host.h"
51 #include "content/public/browser/tracing_controller.h"
52 #include "content/public/common/content_switches.h"
53 #include "content/public/common/main_function_params.h"
54 #include "content/public/common/result_codes.h"
55 #include "crypto/nss_util.h"
56 #include "media/audio/audio_manager.h"
57 #include "media/base/media.h"
58 #include "media/base/user_input_monitor.h"
59 #include "media/midi/midi_manager.h"
60 #include "net/base/network_change_notifier.h"
61 #include "net/socket/client_socket_factory.h"
62 #include "net/ssl/ssl_config_service.h"
63 #include "ui/base/clipboard/clipboard.h"
65 #if defined(USE_AURA) || (defined(OS_MACOSX) && !defined(OS_IOS))
66 #include "content/browser/compositor/image_transport_factory.h"
70 #include "ui/aura/env.h"
74 #include "content/browser/renderer_host/render_process_host_impl.h"
77 #if defined(OS_ANDROID)
78 #include "base/android/jni_android.h"
79 #include "content/browser/android/browser_startup_controller.h"
80 #include "content/browser/android/surface_texture_peer_browser_impl.h"
81 #include "content/browser/android/tracing_controller_android.h"
82 #include "ui/gl/gl_surface.h"
85 #if defined(OS_MACOSX) && !defined(OS_IOS)
86 #include "content/browser/theme_helper_mac.h"
94 #include "content/browser/system_message_window_win.h"
95 #include "content/common/sandbox_win.h"
96 #include "net/base/winsock_init.h"
97 #include "ui/base/l10n/l10n_util_win.h"
100 #if defined(USE_GLIB)
101 #include <glib-object.h>
104 #if defined(OS_LINUX) && defined(USE_UDEV)
105 #include "content/browser/device_monitor_udev.h"
106 #elif defined(OS_MACOSX) && !defined(OS_IOS)
107 #include "content/browser/device_monitor_mac.h"
110 #if defined(OS_POSIX) && !defined(OS_MACOSX)
111 #include "content/browser/renderer_host/render_sandbox_host_linux.h"
112 #include "content/browser/zygote_host/zygote_host_impl_linux.h"
113 #include "sandbox/linux/suid/client/setuid_sandbox_client.h"
116 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
117 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
121 #include "ui/gfx/x/x11_connection.h"
122 #include "ui/gfx/x/x11_types.h"
125 #if defined(USE_OZONE)
126 #include "ui/ozone/ozone_platform.h"
127 #include "ui/events/ozone/event_factory_ozone.h"
128 #include "ozone/content/ozone_channel_host_factory.h"
131 // One of the linux specific headers defines this as a macro.
139 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
140 void SetupSandbox(const CommandLine& parsed_command_line) {
141 TRACE_EVENT0("startup", "SetupSandbox");
142 base::FilePath sandbox_binary;
144 scoped_ptr<sandbox::SetuidSandboxClient> setuid_sandbox_client(
145 sandbox::SetuidSandboxClient::Create());
147 const bool want_setuid_sandbox =
148 !parsed_command_line.HasSwitch(switches::kNoSandbox) &&
149 !parsed_command_line.HasSwitch(switches::kDisableSetuidSandbox) &&
150 !setuid_sandbox_client->IsDisabledViaEnvironment();
152 static const char no_suid_error[] =
153 "Running without the SUID sandbox! See "
154 "https://code.google.com/p/chromium/wiki/LinuxSUIDSandboxDevelopment "
155 "for more information on developing with the sandbox on.";
156 if (want_setuid_sandbox) {
157 sandbox_binary = setuid_sandbox_client->GetSandboxBinaryPath();
158 if (sandbox_binary.empty()) {
159 // This needs to be fatal. Talk to security@chromium.org if you feel
161 LOG(FATAL) << no_suid_error;
164 LOG(ERROR) << no_suid_error;
167 // Tickle the sandbox host and zygote host so they fork now.
168 RenderSandboxHostLinux::GetInstance()->Init(sandbox_binary.value());
169 ZygoteHostImpl::GetInstance()->Init(sandbox_binary.value());
173 #if defined(USE_GLIB)
174 static void GLibLogHandler(const gchar* log_domain,
175 GLogLevelFlags log_level,
176 const gchar* message,
179 log_domain = "<unknown>";
181 message = "<no message>";
183 if (strstr(message, "Unable to retrieve the file info for")) {
184 LOG(ERROR) << "GTK File code error: " << message;
185 } else if (strstr(message, "Could not find the icon") &&
186 strstr(log_domain, "Gtk")) {
187 LOG(ERROR) << "GTK icon error: " << message;
188 } else if (strstr(message, "Theme file for default has no") ||
189 strstr(message, "Theme directory") ||
190 strstr(message, "theme pixmap") ||
191 strstr(message, "locate theme engine")) {
192 LOG(ERROR) << "GTK theme error: " << message;
193 } else if (strstr(message, "Unable to create Ubuntu Menu Proxy") &&
194 strstr(log_domain, "<unknown>")) {
195 LOG(ERROR) << "GTK menu proxy create failed";
196 } else if (strstr(message, "Out of memory") &&
197 strstr(log_domain, "<unknown>")) {
198 LOG(ERROR) << "DBus call timeout or out of memory: "
199 << "http://crosbug.com/15496";
200 } else if (strstr(message, "Could not connect: Connection refused") &&
201 strstr(log_domain, "<unknown>")) {
202 LOG(ERROR) << "DConf settings backend could not connect to session bus: "
203 << "http://crbug.com/179797";
204 } else if (strstr(message, "Attempting to store changes into") ||
205 strstr(message, "Attempting to set the permissions of")) {
206 LOG(ERROR) << message << " (http://bugs.chromium.org/161366)";
207 } else if (strstr(message, "drawable is not a native X11 window")) {
208 LOG(ERROR) << message << " (http://bugs.chromium.org/329991)";
210 LOG(DFATAL) << log_domain << ": " << message;
214 static void SetUpGLibLogHandler() {
215 // Register GLib-handled assertions to go through our logging system.
216 const char* kLogDomains[] = { NULL, "Gtk", "Gdk", "GLib", "GLib-GObject" };
217 for (size_t i = 0; i < arraysize(kLogDomains); i++) {
218 g_log_set_handler(kLogDomains[i],
219 static_cast<GLogLevelFlags>(G_LOG_FLAG_RECURSION |
222 G_LOG_LEVEL_CRITICAL |
223 G_LOG_LEVEL_WARNING),
230 void OnStoppedStartupTracing(const base::FilePath& trace_file) {
231 VLOG(0) << "Completed startup tracing to " << trace_file.value();
234 #if defined(USE_AURA)
235 bool ShouldInitializeBrowserGpuChannelAndTransportSurface() {
238 #elif defined(OS_MACOSX) && !defined(OS_IOS)
239 bool ShouldInitializeBrowserGpuChannelAndTransportSurface() {
240 return IsDelegatedRendererEnabled();
246 // The currently-running BrowserMainLoop. There can be one or zero.
247 BrowserMainLoop* g_current_browser_main_loop = NULL;
249 // This is just to be able to keep ShutdownThreadsAndCleanUp out of
250 // the public interface of BrowserMainLoop.
251 class BrowserShutdownImpl {
253 static void ImmediateShutdownAndExitProcess() {
254 DCHECK(g_current_browser_main_loop);
255 g_current_browser_main_loop->ShutdownThreadsAndCleanUp();
258 // At this point the message loop is still running yet we've shut everything
259 // down. If any messages are processed we'll likely crash. Exit now.
260 ExitProcess(RESULT_CODE_NORMAL_EXIT);
261 #elif defined(OS_POSIX) && !defined(OS_MACOSX)
262 _exit(RESULT_CODE_NORMAL_EXIT);
269 void ImmediateShutdownAndExitProcess() {
270 BrowserShutdownImpl::ImmediateShutdownAndExitProcess();
273 // For measuring memory usage after each task. Behind a command line flag.
274 class BrowserMainLoop::MemoryObserver : public base::MessageLoop::TaskObserver {
277 virtual ~MemoryObserver() {}
279 virtual void WillProcessTask(const base::PendingTask& pending_task) OVERRIDE {
282 virtual void DidProcessTask(const base::PendingTask& pending_task) OVERRIDE {
283 #if !defined(OS_IOS) // No ProcessMetrics on IOS.
284 scoped_ptr<base::ProcessMetrics> process_metrics(
285 base::ProcessMetrics::CreateProcessMetrics(
286 #if defined(OS_MACOSX)
287 base::GetCurrentProcessHandle(), NULL));
289 base::GetCurrentProcessHandle()));
291 size_t private_bytes;
292 process_metrics->GetMemoryBytes(&private_bytes, NULL);
293 HISTOGRAM_MEMORY_KB("Memory.BrowserUsed", private_bytes >> 10);
297 DISALLOW_COPY_AND_ASSIGN(MemoryObserver);
301 // BrowserMainLoop construction / destruction =============================
303 BrowserMainLoop* BrowserMainLoop::GetInstance() {
304 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
305 return g_current_browser_main_loop;
308 BrowserMainLoop::BrowserMainLoop(const MainFunctionParams& parameters)
309 : parameters_(parameters),
310 parsed_command_line_(parameters.command_line),
311 result_code_(RESULT_CODE_NORMAL_EXIT),
312 created_threads_(false),
313 // ContentMainRunner should have enabled tracing of the browser process
314 // when kTraceStartup is in the command line.
316 parameters.command_line.HasSwitch(switches::kTraceStartup)) {
317 DCHECK(!g_current_browser_main_loop);
318 g_current_browser_main_loop = this;
321 BrowserMainLoop::~BrowserMainLoop() {
322 DCHECK_EQ(this, g_current_browser_main_loop);
324 ui::Clipboard::DestroyClipboardForCurrentThread();
325 #endif // !defined(OS_IOS)
326 g_current_browser_main_loop = NULL;
329 void BrowserMainLoop::Init() {
330 TRACE_EVENT0("startup", "BrowserMainLoop::Init");
332 GetContentClient()->browser()->CreateBrowserMainParts(parameters_));
335 // BrowserMainLoop stages ==================================================
337 void BrowserMainLoop::EarlyInitialization() {
338 TRACE_EVENT0("startup", "BrowserMainLoop::EarlyInitialization");
340 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
341 // No thread should be created before this call, as SetupSandbox()
342 // will end-up using fork().
343 SetupSandbox(parsed_command_line_);
347 if (parsed_command_line_.HasSwitch(switches::kSingleProcess) ||
348 parsed_command_line_.HasSwitch(switches::kInProcessGPU)) {
349 if (!gfx::InitializeThreadedX11()) {
350 LOG(ERROR) << "Failed to put Xlib into threaded mode.";
355 // GLib's spawning of new processes is buggy, so it's important that at this
356 // point GLib does not need to start DBUS. Chrome should always start with
357 // DBUS_SESSION_BUS_ADDRESS properly set. See crbug.com/309093.
358 #if defined(USE_GLIB)
359 // g_type_init will be deprecated in 2.36. 2.35 is the development
360 // version for 2.36, hence do not call g_type_init starting 2.35.
361 // http://developer.gnome.org/gobject/unstable/gobject-Type-Information.html#g-type-init
362 #if !GLIB_CHECK_VERSION(2, 35, 0)
363 // GLib type system initialization. Needed at least for gconf,
364 // used in net/proxy/proxy_config_service_linux.cc. Most likely
365 // this is superfluous as gtk_init() ought to do this. It's
366 // definitely harmless, so retained as a reminder of this
367 // requirement for gconf.
371 SetUpGLibLogHandler();
375 parts_->PreEarlyInitialization();
378 net::EnsureWinsockInit();
381 #if !defined(USE_OPENSSL)
382 // We want to be sure to init NSPR on the main thread.
383 crypto::EnsureNSPRInit();
384 #endif // !defined(USE_OPENSSL)
387 if (parsed_command_line_.HasSwitch(switches::kRendererProcessLimit)) {
388 std::string limit_string = parsed_command_line_.GetSwitchValueASCII(
389 switches::kRendererProcessLimit);
390 size_t process_limit;
391 if (base::StringToSizeT(limit_string, &process_limit)) {
392 RenderProcessHost::SetMaxRendererProcessCount(process_limit);
395 #endif // !defined(OS_IOS)
398 parts_->PostEarlyInitialization();
401 void BrowserMainLoop::MainMessageLoopStart() {
402 TRACE_EVENT0("startup", "BrowserMainLoop::MainMessageLoopStart");
404 TRACE_EVENT0("startup",
405 "BrowserMainLoop::MainMessageLoopStart:PreMainMessageLoopStart");
406 parts_->PreMainMessageLoopStart();
410 // If we're running tests (ui_task is non-null), then the ResourceBundle
411 // has already been initialized.
412 if (!parameters_.ui_task) {
413 // Override the configured locale with the user's preferred UI language.
414 l10n_util::OverrideLocaleWithUILanguageList();
418 // Create a MessageLoop if one does not already exist for the current thread.
419 if (!base::MessageLoop::current())
420 main_message_loop_.reset(new base::MessageLoopForUI);
422 InitializeMainThread();
425 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SystemMonitor");
426 system_monitor_.reset(new base::SystemMonitor);
429 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:PowerMonitor");
430 scoped_ptr<base::PowerMonitorSource> power_monitor_source(
431 new base::PowerMonitorDeviceSource());
432 power_monitor_.reset(new base::PowerMonitor(power_monitor_source.Pass()));
435 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:HighResTimerManager");
436 hi_res_timer_manager_.reset(new base::HighResolutionTimerManager);
439 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:NetworkChangeNotifier");
440 network_change_notifier_.reset(net::NetworkChangeNotifier::Create());
445 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MediaFeatures");
446 media::InitializeCPUSpecificMediaFeatures();
449 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:AudioMan");
450 audio_manager_.reset(media::AudioManager::Create(
451 MediaInternals::GetInstance()));
454 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MidiManager");
455 midi_manager_.reset(media::MidiManager::Create());
458 TRACE_EVENT0("startup",
459 "BrowserMainLoop::Subsystem:ContentWebUIController");
460 WebUIControllerFactory::RegisterFactory(
461 ContentWebUIControllerFactory::GetInstance());
465 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:AudioMirroringManager");
466 audio_mirroring_manager_.reset(new AudioMirroringManager());
469 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:OnlineStateObserver");
470 online_state_observer_.reset(new BrowserOnlineStateObserver);
474 system_stats_monitor_.reset(new base::debug::TraceEventSystemStatsMonitor(
475 base::ThreadTaskRunnerHandle::Get()));
477 #endif // !defined(OS_IOS)
480 system_message_window_.reset(new SystemMessageWindowWin);
484 parts_->PostMainMessageLoopStart();
487 // Start tracing to a file if needed. Only do this after starting the main
488 // message loop to avoid calling MessagePumpForUI::ScheduleWork() before
489 // MessagePumpForUI::Start() as it will crash the browser.
490 if (is_tracing_startup_) {
491 TRACE_EVENT0("startup", "BrowserMainLoop::InitStartupTracing");
492 InitStartupTracing(parsed_command_line_);
494 #endif // !defined(OS_IOS)
496 #if defined(OS_ANDROID)
498 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SurfaceTexturePeer");
499 SurfaceTexturePeer::InitInstance(new SurfaceTexturePeerBrowserImpl());
503 if (parsed_command_line_.HasSwitch(switches::kMemoryMetrics)) {
504 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MemoryObserver");
505 memory_observer_.reset(new MemoryObserver());
506 base::MessageLoop::current()->AddTaskObserver(memory_observer_.get());
509 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
510 trace_memory_controller_.reset(new base::debug::TraceMemoryController(
511 base::MessageLoop::current()->message_loop_proxy(),
512 ::HeapProfilerWithPseudoStackStart,
518 int BrowserMainLoop::PreCreateThreads() {
521 TRACE_EVENT0("startup",
522 "BrowserMainLoop::CreateThreads:PreCreateThreads");
523 result_code_ = parts_->PreCreateThreads();
526 #if defined(ENABLE_PLUGINS)
527 // Prior to any processing happening on the io thread, we create the
528 // plugin service as it is predominantly used from the io thread,
529 // but must be created on the main thread. The service ctor is
530 // inexpensive and does not invoke the io_thread() accessor.
532 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads:PluginService");
533 PluginService::GetInstance()->Init();
537 #if !defined(OS_IOS) && (!defined(GOOGLE_CHROME_BUILD) || defined(OS_ANDROID))
538 // Single-process is an unsupported and not fully tested mode, so
539 // don't enable it for official Chrome builds (except on Android).
540 if (parsed_command_line_.HasSwitch(switches::kSingleProcess))
541 RenderProcessHost::SetRunRendererInProcess(true);
546 void BrowserMainLoop::CreateStartupTasks() {
547 TRACE_EVENT0("startup", "BrowserMainLoop::CreateStartupTasks");
549 // First time through, we really want to create all the tasks
550 if (!startup_task_runner_.get()) {
551 #if defined(OS_ANDROID)
552 startup_task_runner_ = make_scoped_ptr(new StartupTaskRunner(
553 base::Bind(&BrowserStartupComplete),
554 base::MessageLoop::current()->message_loop_proxy()));
556 startup_task_runner_ = make_scoped_ptr(new StartupTaskRunner(
557 base::Callback<void(int)>(),
558 base::MessageLoop::current()->message_loop_proxy()));
560 StartupTask pre_create_threads =
561 base::Bind(&BrowserMainLoop::PreCreateThreads, base::Unretained(this));
562 startup_task_runner_->AddTask(pre_create_threads);
564 StartupTask create_threads =
565 base::Bind(&BrowserMainLoop::CreateThreads, base::Unretained(this));
566 startup_task_runner_->AddTask(create_threads);
568 StartupTask browser_thread_started = base::Bind(
569 &BrowserMainLoop::BrowserThreadsStarted, base::Unretained(this));
570 startup_task_runner_->AddTask(browser_thread_started);
572 StartupTask pre_main_message_loop_run = base::Bind(
573 &BrowserMainLoop::PreMainMessageLoopRun, base::Unretained(this));
574 startup_task_runner_->AddTask(pre_main_message_loop_run);
576 #if defined(OS_ANDROID)
577 if (BrowserMayStartAsynchronously()) {
578 startup_task_runner_->StartRunningTasksAsync();
582 #if defined(OS_ANDROID)
583 if (!BrowserMayStartAsynchronously()) {
584 // A second request for asynchronous startup can be ignored, so
585 // StartupRunningTasksAsync is only called first time through. If, however,
586 // this is a request for synchronous startup then it must override any
587 // previous call for async startup, so we call RunAllTasksNow()
589 startup_task_runner_->RunAllTasksNow();
592 startup_task_runner_->RunAllTasksNow();
596 int BrowserMainLoop::CreateThreads() {
597 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads");
599 base::Thread::Options default_options;
600 base::Thread::Options io_message_loop_options;
601 io_message_loop_options.message_loop_type = base::MessageLoop::TYPE_IO;
602 base::Thread::Options ui_message_loop_options;
603 ui_message_loop_options.message_loop_type = base::MessageLoop::TYPE_UI;
605 // Start threads in the order they occur in the BrowserThread::ID
606 // enumeration, except for BrowserThread::UI which is the main
609 // Must be size_t so we can increment it.
610 for (size_t thread_id = BrowserThread::UI + 1;
611 thread_id < BrowserThread::ID_COUNT;
613 scoped_ptr<BrowserProcessSubThread>* thread_to_start = NULL;
614 base::Thread::Options* options = &default_options;
617 case BrowserThread::DB:
618 TRACE_EVENT_BEGIN1("startup",
619 "BrowserMainLoop::CreateThreads:start",
620 "Thread", "BrowserThread::DB");
621 thread_to_start = &db_thread_;
623 case BrowserThread::FILE_USER_BLOCKING:
624 TRACE_EVENT_BEGIN1("startup",
625 "BrowserMainLoop::CreateThreads:start",
626 "Thread", "BrowserThread::FILE_USER_BLOCKING");
627 thread_to_start = &file_user_blocking_thread_;
629 case BrowserThread::FILE:
630 TRACE_EVENT_BEGIN1("startup",
631 "BrowserMainLoop::CreateThreads:start",
632 "Thread", "BrowserThread::FILE");
633 thread_to_start = &file_thread_;
635 // On Windows, the FILE thread needs to be have a UI message loop
636 // which pumps messages in such a way that Google Update can
637 // communicate back to us.
638 options = &ui_message_loop_options;
640 options = &io_message_loop_options;
643 case BrowserThread::PROCESS_LAUNCHER:
644 TRACE_EVENT_BEGIN1("startup",
645 "BrowserMainLoop::CreateThreads:start",
646 "Thread", "BrowserThread::PROCESS_LAUNCHER");
647 thread_to_start = &process_launcher_thread_;
649 case BrowserThread::CACHE:
650 TRACE_EVENT_BEGIN1("startup",
651 "BrowserMainLoop::CreateThreads:start",
652 "Thread", "BrowserThread::CACHE");
653 thread_to_start = &cache_thread_;
654 options = &io_message_loop_options;
656 case BrowserThread::IO:
657 TRACE_EVENT_BEGIN1("startup",
658 "BrowserMainLoop::CreateThreads:start",
659 "Thread", "BrowserThread::IO");
660 thread_to_start = &io_thread_;
661 options = &io_message_loop_options;
663 case BrowserThread::UI:
664 case BrowserThread::ID_COUNT:
670 BrowserThread::ID id = static_cast<BrowserThread::ID>(thread_id);
672 if (thread_to_start) {
673 (*thread_to_start).reset(new BrowserProcessSubThread(id));
674 (*thread_to_start)->StartWithOptions(*options);
679 TRACE_EVENT_END0("startup", "BrowserMainLoop::CreateThreads:start");
682 created_threads_ = true;
686 int BrowserMainLoop::PreMainMessageLoopRun() {
688 TRACE_EVENT0("startup",
689 "BrowserMainLoop::CreateThreads:PreMainMessageLoopRun");
690 parts_->PreMainMessageLoopRun();
693 // If the UI thread blocks, the whole UI is unresponsive.
694 // Do not allow disk IO from the UI thread.
695 base::ThreadRestrictions::SetIOAllowed(false);
696 base::ThreadRestrictions::DisallowWaiting();
700 void BrowserMainLoop::RunMainMessageLoopParts() {
701 TRACE_EVENT_BEGIN_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
703 bool ran_main_loop = false;
705 ran_main_loop = parts_->MainMessageLoopRun(&result_code_);
708 MainMessageLoopRun();
710 TRACE_EVENT_END_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
713 void BrowserMainLoop::ShutdownThreadsAndCleanUp() {
714 if (!created_threads_) {
715 // Called early, nothing to do
718 TRACE_EVENT0("shutdown", "BrowserMainLoop::ShutdownThreadsAndCleanUp");
720 // Teardown may start in PostMainMessageLoopRun, and during teardown we
721 // need to be able to perform IO.
722 base::ThreadRestrictions::SetIOAllowed(true);
723 BrowserThread::PostTask(
724 BrowserThread::IO, FROM_HERE,
725 base::Bind(base::IgnoreResult(&base::ThreadRestrictions::SetIOAllowed),
729 if (RenderProcessHost::run_renderer_in_process())
730 RenderProcessHostImpl::ShutDownInProcessRenderer();
734 TRACE_EVENT0("shutdown",
735 "BrowserMainLoop::Subsystem:PostMainMessageLoopRun");
736 parts_->PostMainMessageLoopRun();
739 trace_memory_controller_.reset();
740 system_stats_monitor_.reset();
743 // Destroying the GpuProcessHostUIShims on the UI thread posts a task to
744 // delete related objects on the GPU thread. This must be done before
745 // stopping the GPU thread. The GPU thread will close IPC channels to renderer
746 // processes so this has to happen before stopping the IO thread.
748 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUProcessHostShim");
749 GpuProcessHostUIShim::DestroyAll();
751 // Cancel pending requests and prevent new requests.
752 if (resource_dispatcher_host_) {
753 TRACE_EVENT0("shutdown",
754 "BrowserMainLoop::Subsystem:ResourceDispatcherHost");
755 resource_dispatcher_host_.get()->Shutdown();
758 #if defined(USE_AURA)
760 TRACE_EVENT0("shutdown",
761 "BrowserMainLoop::Subsystem:ImageTransportFactory");
762 ImageTransportFactory::Terminate();
766 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
767 ZygoteHostImpl::GetInstance()->TearDownAfterLastChild();
768 #endif // defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
770 // The device monitors are using |system_monitor_| as dependency, so delete
771 // them before |system_monitor_| goes away.
772 // On Mac and windows, the monitor needs to be destroyed on the same thread
773 // as they were created. On Linux, the monitor will be deleted when IO thread
776 system_message_window_.reset();
777 #elif defined(OS_MACOSX)
778 device_monitor_mac_.reset();
780 #endif // !defined(OS_IOS)
782 // Must be size_t so we can subtract from it.
783 for (size_t thread_id = BrowserThread::ID_COUNT - 1;
784 thread_id >= (BrowserThread::UI + 1);
786 // Find the thread object we want to stop. Looping over all valid
787 // BrowserThread IDs and DCHECKing on a missing case in the switch
788 // statement helps avoid a mismatch between this code and the
789 // BrowserThread::ID enumeration.
791 // The destruction order is the reverse order of occurrence in the
792 // BrowserThread::ID list. The rationale for the order is as
793 // follows (need to be filled in a bit):
796 // - The IO thread is the only user of the CACHE thread.
798 // - The PROCESS_LAUNCHER thread must be stopped after IO in case
799 // the IO thread posted a task to terminate a process on the
800 // process launcher thread.
802 // - (Not sure why DB stops last.)
804 case BrowserThread::DB: {
805 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DBThread");
809 case BrowserThread::FILE_USER_BLOCKING: {
810 TRACE_EVENT0("shutdown",
811 "BrowserMainLoop::Subsystem:FileUserBlockingThread");
812 file_user_blocking_thread_.reset();
815 case BrowserThread::FILE: {
816 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:FileThread");
818 // Clean up state that lives on or uses the file_thread_ before
820 if (resource_dispatcher_host_)
821 resource_dispatcher_host_.get()->save_file_manager()->Shutdown();
822 #endif // !defined(OS_IOS)
823 file_thread_.reset();
826 case BrowserThread::PROCESS_LAUNCHER: {
827 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:LauncherThread");
828 process_launcher_thread_.reset();
831 case BrowserThread::CACHE: {
832 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:CacheThread");
833 cache_thread_.reset();
836 case BrowserThread::IO: {
837 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IOThread");
841 case BrowserThread::UI:
842 case BrowserThread::ID_COUNT:
851 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IndexedDBThread");
852 indexed_db_thread_.reset();
856 // Close the blocking I/O pool after the other threads. Other threads such
857 // as the I/O thread may need to schedule work like closing files or flushing
858 // data during shutdown, so the blocking pool needs to be available. There
859 // may also be slow operations pending that will blcok shutdown, so closing
860 // it here (which will block until required operations are complete) gives
861 // more head start for those operations to finish.
863 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:ThreadPool");
864 BrowserThreadImpl::ShutdownThreadPool();
868 // Must happen after the IO thread is shutdown since this may be accessed from
871 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUChannelFactory");
872 if (BrowserGpuChannelHostFactory::instance())
873 BrowserGpuChannelHostFactory::Terminate();
874 #if defined(USE_OZONE)
875 if (OzoneChannelHostFactory::instance())
876 OzoneChannelHostFactory::Terminate();
880 // Must happen after the I/O thread is shutdown since this class lives on the
881 // I/O thread and isn't threadsafe.
883 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GamepadService");
884 GamepadService::GetInstance()->Terminate();
887 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:SensorService");
888 DeviceInertialSensorService::GetInstance()->Shutdown();
891 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DeleteDataSources");
892 URLDataManager::DeleteDataSources();
894 #endif // !defined(OS_IOS)
897 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:PostDestroyThreads");
898 parts_->PostDestroyThreads();
902 void BrowserMainLoop::InitializeMainThread() {
903 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeMainThread");
904 const char* kThreadName = "CrBrowserMain";
905 base::PlatformThread::SetName(kThreadName);
906 if (main_message_loop_)
907 main_message_loop_->set_thread_name(kThreadName);
909 // Register the main thread by instantiating it, but don't call any methods.
911 new BrowserThreadImpl(BrowserThread::UI, base::MessageLoop::current()));
914 int BrowserMainLoop::BrowserThreadsStarted() {
915 TRACE_EVENT0("startup", "BrowserMainLoop::BrowserThreadsStarted");
918 indexed_db_thread_.reset(new base::Thread("IndexedDB"));
919 indexed_db_thread_->Start();
922 #if defined(OS_ANDROID)
923 // Up the priority of anything that touches with display tasks
924 // (this thread is UI thread, and io_thread_ is for IPCs).
925 io_thread_->SetPriority(base::kThreadPriority_Display);
926 base::PlatformThread::SetThreadPriority(
927 base::PlatformThread::CurrentHandle(),
928 base::kThreadPriority_Display);
932 HistogramSynchronizer::GetInstance();
934 #if defined(OS_ANDROID)
935 // On Android, GLSurface::InitializeOneOff() must be called before initalizing
936 // the GpuDataManagerImpl as it uses the GL bindings. crbug.com/326295
937 if (!gfx::GLSurface::InitializeOneOff())
938 LOG(FATAL) << "GLSurface::InitializeOneOff failed";
941 // Initialize the GpuDataManager before we set up the MessageLoops because
942 // otherwise we'll trigger the assertion about doing IO on the UI thread.
943 GpuDataManagerImpl::GetInstance()->Initialize();
945 bool always_uses_gpu = true;
946 bool established_gpu_channel = false;
947 #if defined(USE_AURA) || defined(OS_MACOSX)
948 if (ShouldInitializeBrowserGpuChannelAndTransportSurface()) {
949 established_gpu_channel = true;
950 if (!GpuDataManagerImpl::GetInstance()->CanUseGpuBrowserCompositor()) {
951 established_gpu_channel = always_uses_gpu = false;
953 BrowserGpuChannelHostFactory::Initialize(established_gpu_channel);
954 ImageTransportFactory::Initialize();
956 #elif defined(OS_ANDROID)
957 established_gpu_channel = true;
958 BrowserGpuChannelHostFactory::Initialize(established_gpu_channel);
961 #if defined(OS_LINUX) && defined(USE_UDEV)
962 device_monitor_linux_.reset(new DeviceMonitorLinux());
963 #elif defined(OS_MACOSX)
964 device_monitor_mac_.reset(new DeviceMonitorMac());
967 #if defined(USE_OZONE)
968 ui::OzonePlatform::Initialize();
969 ui::EventFactoryOzone::GetInstance()->SetFileTaskRunner(
970 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE));
973 // RDH needs the IO thread to be created
975 TRACE_EVENT0("startup",
976 "BrowserMainLoop::BrowserThreadsStarted:InitResourceDispatcherHost");
977 resource_dispatcher_host_.reset(new ResourceDispatcherHostImpl());
980 // MediaStreamManager needs the IO thread to be created.
982 TRACE_EVENT0("startup",
983 "BrowserMainLoop::BrowserThreadsStarted:InitMediaStreamManager");
984 media_stream_manager_.reset(new MediaStreamManager(audio_manager_.get()));
988 TRACE_EVENT0("startup",
989 "BrowserMainLoop::BrowserThreadsStarted:InitSpeechRecognition");
990 speech_recognition_manager_.reset(new SpeechRecognitionManagerImpl(
991 audio_manager_.get(), media_stream_manager_.get()));
997 "BrowserMainLoop::BrowserThreadsStarted::InitUserInputMonitor");
998 user_input_monitor_ = media::UserInputMonitor::Create(
999 io_thread_->message_loop_proxy(), main_thread_->message_loop_proxy());
1003 TRACE_EVENT0("startup",
1004 "BrowserMainLoop::BrowserThreadsStarted::TimeZoneMonitor");
1005 time_zone_monitor_ = TimeZoneMonitor::Create();
1008 // Alert the clipboard class to which threads are allowed to access the
1010 std::vector<base::PlatformThreadId> allowed_clipboard_threads;
1011 // The current thread is the UI thread.
1012 allowed_clipboard_threads.push_back(base::PlatformThread::CurrentId());
1014 // On Windows, clipboards are also used on the File or IO threads.
1015 allowed_clipboard_threads.push_back(file_thread_->thread_id());
1016 allowed_clipboard_threads.push_back(io_thread_->thread_id());
1018 ui::Clipboard::SetAllowedThreads(allowed_clipboard_threads);
1020 // When running the GPU thread in-process, avoid optimistically starting it
1021 // since creating the GPU thread races against creation of the one-and-only
1022 // ChildProcess instance which is created by the renderer thread.
1023 if (GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL) &&
1024 !established_gpu_channel &&
1026 !parsed_command_line_.HasSwitch(switches::kSingleProcess) &&
1027 !parsed_command_line_.HasSwitch(switches::kInProcessGPU)) {
1028 TRACE_EVENT_INSTANT0("gpu", "Post task to launch GPU process",
1029 TRACE_EVENT_SCOPE_THREAD);
1030 BrowserThread::PostTask(
1031 BrowserThread::IO, FROM_HERE, base::Bind(
1032 base::IgnoreResult(&GpuProcessHost::Get),
1033 GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED,
1034 CAUSE_FOR_GPU_LAUNCH_BROWSER_STARTUP));
1037 #if defined(OS_MACOSX)
1038 ThemeHelperMac::GetInstance();
1041 #if defined(USE_OZONE)
1042 bool using_gpu_process =
1043 established_gpu_channel &&
1044 !parsed_command_line_.HasSwitch(switches::kSingleProcess) &&
1045 !parsed_command_line_.HasSwitch(switches::kInProcessGPU);
1046 OzoneChannelHostFactory::Initialize(using_gpu_process);
1048 #endif // !defined(OS_IOS)
1050 return result_code_;
1053 bool BrowserMainLoop::InitializeToolkit() {
1054 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeToolkit");
1055 // TODO(evan): this function is rather subtle, due to the variety
1056 // of intersecting ifdefs we have. To keep it easy to follow, there
1057 // are no #else branches on any #ifs.
1058 // TODO(stevenjb): Move platform specific code into platform specific Parts
1059 // (Need to add InitializeToolkit stage to BrowserParts).
1060 // See also GTK setup in EarlyInitialization, above, and associated comments.
1062 #if defined(TOOLKIT_GTK)
1063 // It is important for this to happen before the first run dialog, as it
1064 // styles the dialog as well.
1065 gfx::InitRCStyles();
1069 // Init common control sex.
1070 INITCOMMONCONTROLSEX config;
1071 config.dwSize = sizeof(config);
1072 config.dwICC = ICC_WIN95_CLASSES;
1073 if (!InitCommonControlsEx(&config))
1074 LOG_GETLASTERROR(FATAL);
1077 #if defined(USE_AURA)
1079 #if defined(USE_X11)
1080 if (!gfx::GetXDisplay())
1084 // Env creates the compositor. Aura widgets need the compositor to be created
1085 // before they can be initialized by the browser.
1086 aura::Env::CreateInstance(true);
1087 #endif // defined(USE_AURA)
1090 parts_->ToolkitInitialized();
1095 void BrowserMainLoop::MainMessageLoopRun() {
1096 #if defined(OS_ANDROID)
1097 // Android's main message loop is the Java message loop.
1100 DCHECK(base::MessageLoopForUI::IsCurrent());
1101 if (parameters_.ui_task)
1102 base::MessageLoopForUI::current()->PostTask(FROM_HERE,
1103 *parameters_.ui_task);
1105 base::RunLoop run_loop;
1110 void BrowserMainLoop::InitStartupTracing(const CommandLine& command_line) {
1111 DCHECK(is_tracing_startup_);
1113 base::FilePath trace_file = command_line.GetSwitchValuePath(
1114 switches::kTraceStartupFile);
1115 // trace_file = "none" means that startup events will show up for the next
1116 // begin/end tracing (via about:tracing or AutomationProxy::BeginTracing/
1117 // EndTracing, for example).
1118 if (trace_file == base::FilePath().AppendASCII("none"))
1121 if (trace_file.empty()) {
1122 #if defined(OS_ANDROID)
1123 TracingControllerAndroid::GenerateTracingFilePath(&trace_file);
1125 // Default to saving the startup trace into the current dir.
1126 trace_file = base::FilePath().AppendASCII("chrometrace.log");
1130 std::string delay_str = command_line.GetSwitchValueASCII(
1131 switches::kTraceStartupDuration);
1133 if (!delay_str.empty() && !base::StringToInt(delay_str, &delay_secs)) {
1134 DLOG(WARNING) << "Could not parse --" << switches::kTraceStartupDuration
1135 << "=" << delay_str << " defaulting to 5 (secs)";
1139 BrowserThread::PostDelayedTask(
1140 BrowserThread::UI, FROM_HERE,
1141 base::Bind(&BrowserMainLoop::EndStartupTracing,
1142 base::Unretained(this), trace_file),
1143 base::TimeDelta::FromSeconds(delay_secs));
1146 void BrowserMainLoop::EndStartupTracing(const base::FilePath& trace_file) {
1147 is_tracing_startup_ = false;
1148 TracingController::GetInstance()->DisableRecording(
1149 trace_file, base::Bind(&OnStoppedStartupTracing));
1152 } // namespace content