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_orientation/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/net/browser_online_state_observer.h"
38 #include "content/browser/plugin_service_impl.h"
39 #include "content/browser/renderer_host/media/audio_mirroring_manager.h"
40 #include "content/browser/renderer_host/media/media_stream_manager.h"
41 #include "content/browser/speech/speech_recognition_manager_impl.h"
42 #include "content/browser/startup_task_runner.h"
43 #include "content/browser/tracing/trace_controller_impl.h"
44 #include "content/browser/webui/content_web_ui_controller_factory.h"
45 #include "content/browser/webui/url_data_manager.h"
46 #include "content/public/browser/browser_main_parts.h"
47 #include "content/public/browser/browser_shutdown.h"
48 #include "content/public/browser/content_browser_client.h"
49 #include "content/public/browser/render_process_host.h"
50 #include "content/public/common/content_switches.h"
51 #include "content/public/common/main_function_params.h"
52 #include "content/public/common/result_codes.h"
53 #include "crypto/nss_util.h"
54 #include "media/audio/audio_manager.h"
55 #include "media/base/media.h"
56 #include "media/base/user_input_monitor.h"
57 #include "media/midi/midi_manager.h"
58 #include "net/base/network_change_notifier.h"
59 #include "net/socket/client_socket_factory.h"
60 #include "net/ssl/ssl_config_service.h"
61 #include "ui/base/clipboard/clipboard.h"
64 #include "content/browser/aura/image_transport_factory.h"
67 #if defined(OS_ANDROID)
68 #include "base/android/jni_android.h"
69 #include "content/browser/android/browser_startup_controller.h"
70 #include "content/browser/android/surface_texture_peer_browser_impl.h"
78 #include "base/win/text_services_message_filter.h"
79 #include "content/browser/system_message_window_win.h"
80 #include "content/common/sandbox_win.h"
81 #include "net/base/winsock_init.h"
82 #include "ui/base/l10n/l10n_util_win.h"
85 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
86 #include <glib-object.h>
90 #include "content/browser/device_monitor_linux.h"
91 #elif defined(OS_MACOSX) && !defined(OS_IOS)
92 #include "content/browser/device_monitor_mac.h"
95 #if defined(TOOLKIT_GTK)
96 #include "ui/gfx/gtk_util.h"
99 #if defined(OS_POSIX) && !defined(OS_MACOSX)
100 #include <sys/stat.h>
102 #include "content/browser/renderer_host/render_sandbox_host_linux.h"
103 #include "content/browser/zygote_host/zygote_host_impl_linux.h"
106 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
107 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
111 #include <X11/Xlib.h>
114 // One of the linux specific headers defines this as a macro.
122 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
123 void SetupSandbox(const CommandLine& parsed_command_line) {
124 TRACE_EVENT0("startup", "SetupSandbox");
125 // TODO(evanm): move this into SandboxWrapper; I'm just trying to move this
126 // code en masse out of chrome_main for now.
127 base::FilePath sandbox_binary;
128 bool env_chrome_devel_sandbox_set = false;
131 const bool want_setuid_sandbox =
132 !parsed_command_line.HasSwitch(switches::kNoSandbox) &&
133 !parsed_command_line.HasSwitch(switches::kDisableSetuidSandbox);
135 if (want_setuid_sandbox) {
136 base::FilePath exe_dir;
137 if (PathService::Get(base::DIR_EXE, &exe_dir)) {
138 base::FilePath sandbox_candidate = exe_dir.AppendASCII("chrome-sandbox");
139 if (base::PathExists(sandbox_candidate))
140 sandbox_binary = sandbox_candidate;
143 // In user-managed builds, including development builds, an environment
144 // variable is required to enable the sandbox. See
145 // http://code.google.com/p/chromium/wiki/LinuxSUIDSandboxDevelopment
146 if (sandbox_binary.empty() &&
147 stat(base::kProcSelfExe, &st) == 0 && st.st_uid == getuid()) {
148 const char* devel_sandbox_path = getenv("CHROME_DEVEL_SANDBOX");
149 if (devel_sandbox_path) {
150 env_chrome_devel_sandbox_set = true;
151 sandbox_binary = base::FilePath(devel_sandbox_path);
155 static const char no_suid_error[] = "Running without the SUID sandbox! See "
156 "https://code.google.com/p/chromium/wiki/LinuxSUIDSandboxDevelopment "
157 "for more information on developing with the sandbox on.";
158 if (sandbox_binary.empty()) {
159 if (!env_chrome_devel_sandbox_set) {
160 // This needs to be fatal. Talk to security@chromium.org if you feel
162 LOG(FATAL) << no_suid_error;
165 // TODO(jln): an empty CHROME_DEVEL_SANDBOX environment variable (as
166 // opposed to a non existing one) is not fatal yet. This is needed
167 // because of existing bots and scripts. Fix it (crbug.com/245376).
168 LOG(ERROR) << no_suid_error;
172 // Tickle the sandbox host and zygote host so they fork now.
173 RenderSandboxHostLinux::GetInstance()->Init(sandbox_binary.value());
174 ZygoteHostImpl::GetInstance()->Init(sandbox_binary.value());
178 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
179 static void GLibLogHandler(const gchar* log_domain,
180 GLogLevelFlags log_level,
181 const gchar* message,
184 log_domain = "<unknown>";
186 message = "<no message>";
188 if (strstr(message, "Loading IM context type") ||
189 strstr(message, "wrong ELF class: ELFCLASS64")) {
190 // http://crbug.com/9643
191 // Until we have a real 64-bit build or all of these 32-bit package issues
192 // are sorted out, don't fatal on ELF 32/64-bit mismatch warnings and don't
193 // spam the user with more than one of them.
194 static bool alerted = false;
196 LOG(ERROR) << "Bug 9643: " << log_domain << ": " << message;
199 } else if (strstr(message, "Unable to retrieve the file info for")) {
200 LOG(ERROR) << "GTK File code error: " << message;
201 } else if (strstr(message, "Could not find the icon") &&
202 strstr(log_domain, "Gtk")) {
203 LOG(ERROR) << "GTK icon error: " << message;
204 } else if (strstr(message, "Theme file for default has no") ||
205 strstr(message, "Theme directory") ||
206 strstr(message, "theme pixmap") ||
207 strstr(message, "locate theme engine")) {
208 LOG(ERROR) << "GTK theme error: " << message;
209 } else if (strstr(message, "Unable to create Ubuntu Menu Proxy") &&
210 strstr(log_domain, "<unknown>")) {
211 LOG(ERROR) << "GTK menu proxy create failed";
212 } else if (strstr(message, "gtk_drag_dest_leave: assertion")) {
213 LOG(ERROR) << "Drag destination deleted: http://crbug.com/18557";
214 } else if (strstr(message, "Out of memory") &&
215 strstr(log_domain, "<unknown>")) {
216 LOG(ERROR) << "DBus call timeout or out of memory: "
217 << "http://crosbug.com/15496";
218 } else if (strstr(message, "Could not connect: Connection refused") &&
219 strstr(log_domain, "<unknown>")) {
220 LOG(ERROR) << "DConf settings backend could not connect to session bus: "
221 << "http://crbug.com/179797";
222 } else if (strstr(message, "XDG_RUNTIME_DIR variable not set")) {
223 LOG(ERROR) << message << " (http://bugs.chromium.org/97293)";
224 } else if (strstr(message, "Attempting to store changes into") ||
225 strstr(message, "Attempting to set the permissions of")) {
226 LOG(ERROR) << message << " (http://bugs.chromium.org/161366)";
228 LOG(DFATAL) << log_domain << ": " << message;
232 static void SetUpGLibLogHandler() {
233 // Register GLib-handled assertions to go through our logging system.
234 const char* kLogDomains[] = { NULL, "Gtk", "Gdk", "GLib", "GLib-GObject" };
235 for (size_t i = 0; i < arraysize(kLogDomains); i++) {
236 g_log_set_handler(kLogDomains[i],
237 static_cast<GLogLevelFlags>(G_LOG_FLAG_RECURSION |
240 G_LOG_LEVEL_CRITICAL |
241 G_LOG_LEVEL_WARNING),
250 // The currently-running BrowserMainLoop. There can be one or zero.
251 BrowserMainLoop* g_current_browser_main_loop = NULL;
253 // This is just to be able to keep ShutdownThreadsAndCleanUp out of
254 // the public interface of BrowserMainLoop.
255 class BrowserShutdownImpl {
257 static void ImmediateShutdownAndExitProcess() {
258 DCHECK(g_current_browser_main_loop);
259 g_current_browser_main_loop->ShutdownThreadsAndCleanUp();
262 // At this point the message loop is still running yet we've shut everything
263 // down. If any messages are processed we'll likely crash. Exit now.
264 ExitProcess(RESULT_CODE_NORMAL_EXIT);
265 #elif defined(OS_POSIX) && !defined(OS_MACOSX)
266 _exit(RESULT_CODE_NORMAL_EXIT);
273 void ImmediateShutdownAndExitProcess() {
274 BrowserShutdownImpl::ImmediateShutdownAndExitProcess();
277 // For measuring memory usage after each task. Behind a command line flag.
278 class BrowserMainLoop::MemoryObserver : public base::MessageLoop::TaskObserver {
281 virtual ~MemoryObserver() {}
283 virtual void WillProcessTask(const base::PendingTask& pending_task) OVERRIDE {
286 virtual void DidProcessTask(const base::PendingTask& pending_task) OVERRIDE {
287 #if !defined(OS_IOS) // No ProcessMetrics on IOS.
288 scoped_ptr<base::ProcessMetrics> process_metrics(
289 base::ProcessMetrics::CreateProcessMetrics(
290 #if defined(OS_MACOSX)
291 base::GetCurrentProcessHandle(), NULL));
293 base::GetCurrentProcessHandle()));
295 size_t private_bytes;
296 process_metrics->GetMemoryBytes(&private_bytes, NULL);
297 HISTOGRAM_MEMORY_KB("Memory.BrowserUsed", private_bytes >> 10);
301 DISALLOW_COPY_AND_ASSIGN(MemoryObserver);
305 // BrowserMainLoop construction / destruction =============================
307 BrowserMainLoop* BrowserMainLoop::GetInstance() {
308 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
309 return g_current_browser_main_loop;
312 BrowserMainLoop::BrowserMainLoop(const MainFunctionParams& parameters)
313 : parameters_(parameters),
314 parsed_command_line_(parameters.command_line),
315 result_code_(RESULT_CODE_NORMAL_EXIT),
316 created_threads_(false) {
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 (parsed_command_line_.HasSwitch(switches::kSingleProcess) ||
341 parsed_command_line_.HasSwitch(switches::kInProcessGPU)) {
342 if (!XInitThreads()) {
343 LOG(ERROR) << "Failed to put Xlib into threaded mode.";
348 // Due to bugs in GLib we need to initialize GLib/GTK before we start threads;
349 // see crbug.com/309093. Sandbox setup spawns sub-processes and a thread
350 // running waitpid().
351 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
352 // g_type_init will be deprecated in 2.36. 2.35 is the development
353 // version for 2.36, hence do not call g_type_init starting 2.35.
354 // http://developer.gnome.org/gobject/unstable/gobject-Type-Information.html#g-type-init
355 #if !GLIB_CHECK_VERSION(2, 35, 0)
356 // GLib type system initialization. Needed at least for gconf,
357 // used in net/proxy/proxy_config_service_linux.cc. Most likely
358 // this is superfluous as gtk_init() ought to do this. It's
359 // definitely harmless, so retained as a reminder of this
360 // requirement for gconf.
364 #if !defined(USE_AURA)
365 gfx::GtkInitFromCommandLine(parsed_command_line_);
368 SetUpGLibLogHandler();
372 parts_->PreEarlyInitialization();
375 net::EnsureWinsockInit();
378 #if !defined(USE_OPENSSL)
379 // We want to be sure to init NSPR on the main thread.
380 crypto::EnsureNSPRInit();
381 #endif // !defined(USE_OPENSSL)
383 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
384 SetupSandbox(parsed_command_line_);
387 if (parsed_command_line_.HasSwitch(switches::kEnableSSLCachedInfo))
388 net::SSLConfigService::EnableCachedInfo();
391 if (parsed_command_line_.HasSwitch(switches::kRendererProcessLimit)) {
392 std::string limit_string = parsed_command_line_.GetSwitchValueASCII(
393 switches::kRendererProcessLimit);
394 size_t process_limit;
395 if (base::StringToSizeT(limit_string, &process_limit)) {
396 RenderProcessHost::SetMaxRendererProcessCount(process_limit);
399 #endif // !defined(OS_IOS)
402 parts_->PostEarlyInitialization();
405 void BrowserMainLoop::MainMessageLoopStart() {
406 TRACE_EVENT0("startup", "BrowserMainLoop::MainMessageLoopStart")
408 TRACE_EVENT0("startup",
409 "BrowserMainLoop::MainMessageLoopStart:PreMainMessageLoopStart");
410 parts_->PreMainMessageLoopStart();
414 // If we're running tests (ui_task is non-null), then the ResourceBundle
415 // has already been initialized.
416 if (!parameters_.ui_task) {
417 // Override the configured locale with the user's preferred UI language.
418 l10n_util::OverrideLocaleWithUILanguageList();
422 // Create a MessageLoop if one does not already exist for the current thread.
423 if (!base::MessageLoop::current())
424 main_message_loop_.reset(new base::MessageLoop(base::MessageLoop::TYPE_UI));
426 InitializeMainThread();
429 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SystemMonitor")
430 system_monitor_.reset(new base::SystemMonitor);
433 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:PowerMonitor")
434 scoped_ptr<base::PowerMonitorSource> power_monitor_source(
435 new base::PowerMonitorDeviceSource());
436 power_monitor_.reset(new base::PowerMonitor(power_monitor_source.Pass()));
439 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:HighResTimerManager")
440 hi_res_timer_manager_.reset(new base::HighResolutionTimerManager);
443 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:NetworkChangeNotifier")
444 network_change_notifier_.reset(net::NetworkChangeNotifier::Create());
449 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MediaFeatures")
450 media::InitializeCPUSpecificMediaFeatures();
453 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:AudioMan")
454 audio_manager_.reset(media::AudioManager::Create());
457 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MIDIManager")
458 midi_manager_.reset(media::MIDIManager::Create());
461 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:ContentWebUIController")
462 WebUIControllerFactory::RegisterFactory(
463 ContentWebUIControllerFactory::GetInstance());
467 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:AudioMirroringManager")
468 audio_mirroring_manager_.reset(new AudioMirroringManager());
471 // Start tracing to a file if needed.
472 if (base::debug::TraceLog::GetInstance()->IsEnabled()) {
473 TRACE_EVENT0("startup", "BrowserMainLoop::InitStartupTracing")
474 TraceControllerImpl::GetInstance()->InitStartupTracing(
475 parsed_command_line_);
479 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:OnlineStateObserver")
480 online_state_observer_.reset(new BrowserOnlineStateObserver);
484 system_stats_monitor_.reset(new base::debug::TraceEventSystemStatsMonitor(
485 base::ThreadTaskRunnerHandle::Get()));
487 #endif // !defined(OS_IOS)
490 system_message_window_.reset(new SystemMessageWindowWin);
492 if (base::win::IsTSFAwareRequired()) {
493 // Create a TSF message filter for the message loop. MessageLoop takes
494 // ownership of the filter.
495 scoped_ptr<base::win::TextServicesMessageFilter> tsf_message_filter(
496 new base::win::TextServicesMessageFilter);
497 if (tsf_message_filter->Init()) {
498 base::MessageLoopForUI::current()->SetMessageFilter(
499 tsf_message_filter.PassAs<base::MessageLoopForUI::MessageFilter>());
505 parts_->PostMainMessageLoopStart();
507 #if defined(OS_ANDROID)
509 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SurfaceTexturePeer")
510 SurfaceTexturePeer::InitInstance(new SurfaceTexturePeerBrowserImpl());
514 if (parsed_command_line_.HasSwitch(switches::kMemoryMetrics)) {
515 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MemoryObserver")
516 memory_observer_.reset(new MemoryObserver());
517 base::MessageLoop::current()->AddTaskObserver(memory_observer_.get());
520 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
521 trace_memory_controller_.reset(new base::debug::TraceMemoryController(
522 base::MessageLoop::current()->message_loop_proxy(),
523 ::HeapProfilerWithPseudoStackStart,
529 int BrowserMainLoop::PreCreateThreads() {
532 TRACE_EVENT0("startup",
533 "BrowserMainLoop::CreateThreads:PreCreateThreads");
534 result_code_ = parts_->PreCreateThreads();
537 #if defined(ENABLE_PLUGINS)
538 // Prior to any processing happening on the io thread, we create the
539 // plugin service as it is predominantly used from the io thread,
540 // but must be created on the main thread. The service ctor is
541 // inexpensive and does not invoke the io_thread() accessor.
543 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads:PluginService")
544 PluginService::GetInstance()->Init();
548 #if !defined(OS_IOS) && (!defined(GOOGLE_CHROME_BUILD) || defined(OS_ANDROID))
549 // Single-process is an unsupported and not fully tested mode, so
550 // don't enable it for official Chrome builds (except on Android).
551 if (parsed_command_line_.HasSwitch(switches::kSingleProcess))
552 RenderProcessHost::SetRunRendererInProcess(true);
557 void BrowserMainLoop::CreateStartupTasks() {
558 TRACE_EVENT0("startup", "BrowserMainLoop::CreateStartupTasks");
560 // First time through, we really want to create all the tasks
561 if (!startup_task_runner_.get()) {
562 #if defined(OS_ANDROID)
563 startup_task_runner_ = make_scoped_ptr(new StartupTaskRunner(
564 base::Bind(&BrowserStartupComplete),
565 base::MessageLoop::current()->message_loop_proxy()));
567 startup_task_runner_ = make_scoped_ptr(new StartupTaskRunner(
568 base::Callback<void(int)>(),
569 base::MessageLoop::current()->message_loop_proxy()));
571 StartupTask pre_create_threads =
572 base::Bind(&BrowserMainLoop::PreCreateThreads, base::Unretained(this));
573 startup_task_runner_->AddTask(pre_create_threads);
575 StartupTask create_threads =
576 base::Bind(&BrowserMainLoop::CreateThreads, base::Unretained(this));
577 startup_task_runner_->AddTask(create_threads);
579 StartupTask browser_thread_started = base::Bind(
580 &BrowserMainLoop::BrowserThreadsStarted, base::Unretained(this));
581 startup_task_runner_->AddTask(browser_thread_started);
583 StartupTask pre_main_message_loop_run = base::Bind(
584 &BrowserMainLoop::PreMainMessageLoopRun, base::Unretained(this));
585 startup_task_runner_->AddTask(pre_main_message_loop_run);
587 #if defined(OS_ANDROID)
588 if (BrowserMayStartAsynchronously()) {
589 startup_task_runner_->StartRunningTasksAsync();
593 #if defined(OS_ANDROID)
594 if (!BrowserMayStartAsynchronously()) {
595 // A second request for asynchronous startup can be ignored, so
596 // StartupRunningTasksAsync is only called first time through. If, however,
597 // this is a request for synchronous startup then it must override any
598 // previous call for async startup, so we call RunAllTasksNow()
600 startup_task_runner_->RunAllTasksNow();
603 startup_task_runner_->RunAllTasksNow();
607 int BrowserMainLoop::CreateThreads() {
608 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads");
610 base::Thread::Options default_options;
611 base::Thread::Options io_message_loop_options;
612 io_message_loop_options.message_loop_type = base::MessageLoop::TYPE_IO;
613 base::Thread::Options ui_message_loop_options;
614 ui_message_loop_options.message_loop_type = base::MessageLoop::TYPE_UI;
616 // Start threads in the order they occur in the BrowserThread::ID
617 // enumeration, except for BrowserThread::UI which is the main
620 // Must be size_t so we can increment it.
621 for (size_t thread_id = BrowserThread::UI + 1;
622 thread_id < BrowserThread::ID_COUNT;
624 scoped_ptr<BrowserProcessSubThread>* thread_to_start = NULL;
625 base::Thread::Options* options = &default_options;
628 case BrowserThread::DB:
629 TRACE_EVENT_BEGIN1("startup",
630 "BrowserMainLoop::CreateThreads:start",
631 "Thread", "BrowserThread::DB");
632 thread_to_start = &db_thread_;
634 case BrowserThread::FILE_USER_BLOCKING:
635 TRACE_EVENT_BEGIN1("startup",
636 "BrowserMainLoop::CreateThreads:start",
637 "Thread", "BrowserThread::FILE_USER_BLOCKING");
638 thread_to_start = &file_user_blocking_thread_;
640 case BrowserThread::FILE:
641 TRACE_EVENT_BEGIN1("startup",
642 "BrowserMainLoop::CreateThreads:start",
643 "Thread", "BrowserThread::FILE");
644 thread_to_start = &file_thread_;
646 // On Windows, the FILE thread needs to be have a UI message loop
647 // which pumps messages in such a way that Google Update can
648 // communicate back to us.
649 options = &ui_message_loop_options;
651 options = &io_message_loop_options;
654 case BrowserThread::PROCESS_LAUNCHER:
655 TRACE_EVENT_BEGIN1("startup",
656 "BrowserMainLoop::CreateThreads:start",
657 "Thread", "BrowserThread::PROCESS_LAUNCHER");
658 thread_to_start = &process_launcher_thread_;
660 case BrowserThread::CACHE:
661 TRACE_EVENT_BEGIN1("startup",
662 "BrowserMainLoop::CreateThreads:start",
663 "Thread", "BrowserThread::CACHE");
664 thread_to_start = &cache_thread_;
665 options = &io_message_loop_options;
667 case BrowserThread::IO:
668 TRACE_EVENT_BEGIN1("startup",
669 "BrowserMainLoop::CreateThreads:start",
670 "Thread", "BrowserThread::IO");
671 thread_to_start = &io_thread_;
672 options = &io_message_loop_options;
674 case BrowserThread::UI:
675 case BrowserThread::ID_COUNT:
681 BrowserThread::ID id = static_cast<BrowserThread::ID>(thread_id);
683 if (thread_to_start) {
684 (*thread_to_start).reset(new BrowserProcessSubThread(id));
685 (*thread_to_start)->StartWithOptions(*options);
690 TRACE_EVENT_END0("startup", "BrowserMainLoop::CreateThreads:start");
693 created_threads_ = true;
697 int BrowserMainLoop::PreMainMessageLoopRun() {
699 TRACE_EVENT0("startup",
700 "BrowserMainLoop::CreateThreads:PreMainMessageLoopRun");
701 parts_->PreMainMessageLoopRun();
704 // If the UI thread blocks, the whole UI is unresponsive.
705 // Do not allow disk IO from the UI thread.
706 base::ThreadRestrictions::SetIOAllowed(false);
707 base::ThreadRestrictions::DisallowWaiting();
711 void BrowserMainLoop::RunMainMessageLoopParts() {
712 TRACE_EVENT_BEGIN_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
714 bool ran_main_loop = false;
716 ran_main_loop = parts_->MainMessageLoopRun(&result_code_);
719 MainMessageLoopRun();
721 TRACE_EVENT_END_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
724 void BrowserMainLoop::ShutdownThreadsAndCleanUp() {
725 if (!created_threads_) {
726 // Called early, nothing to do
729 TRACE_EVENT0("shutdown", "BrowserMainLoop::ShutdownThreadsAndCleanUp")
731 // Teardown may start in PostMainMessageLoopRun, and during teardown we
732 // need to be able to perform IO.
733 base::ThreadRestrictions::SetIOAllowed(true);
734 BrowserThread::PostTask(
735 BrowserThread::IO, FROM_HERE,
736 base::Bind(base::IgnoreResult(&base::ThreadRestrictions::SetIOAllowed),
739 if (RenderProcessHost::run_renderer_in_process() &&
740 !RenderProcessHost::AllHostsIterator().IsAtEnd()) {
741 delete RenderProcessHost::AllHostsIterator().GetCurrentValue();
745 TRACE_EVENT0("shutdown",
746 "BrowserMainLoop::Subsystem:PostMainMessageLoopRun");
747 parts_->PostMainMessageLoopRun();
750 trace_memory_controller_.reset();
751 system_stats_monitor_.reset();
754 // Destroying the GpuProcessHostUIShims on the UI thread posts a task to
755 // delete related objects on the GPU thread. This must be done before
756 // stopping the GPU thread. The GPU thread will close IPC channels to renderer
757 // processes so this has to happen before stopping the IO thread.
759 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUProcessHostShim");
760 GpuProcessHostUIShim::DestroyAll();
762 // Cancel pending requests and prevent new requests.
763 if (resource_dispatcher_host_) {
764 TRACE_EVENT0("shutdown",
765 "BrowserMainLoop::Subsystem:ResourceDispatcherHost");
766 resource_dispatcher_host_.get()->Shutdown();
769 #if defined(USE_AURA)
771 TRACE_EVENT0("shutdown",
772 "BrowserMainLoop::Subsystem:ImageTransportFactory");
773 ImageTransportFactory::Terminate();
777 // The device monitors are using |system_monitor_| as dependency, so delete
778 // them before |system_monitor_| goes away.
779 // On Mac and windows, the monitor needs to be destroyed on the same thread
780 // as they were created. On Linux, the monitor will be deleted when IO thread
783 system_message_window_.reset();
784 #elif defined(OS_MACOSX)
785 device_monitor_mac_.reset();
787 #endif // !defined(OS_IOS)
789 // Must be size_t so we can subtract from it.
790 for (size_t thread_id = BrowserThread::ID_COUNT - 1;
791 thread_id >= (BrowserThread::UI + 1);
793 // Find the thread object we want to stop. Looping over all valid
794 // BrowserThread IDs and DCHECKing on a missing case in the switch
795 // statement helps avoid a mismatch between this code and the
796 // BrowserThread::ID enumeration.
798 // The destruction order is the reverse order of occurrence in the
799 // BrowserThread::ID list. The rationale for the order is as
800 // follows (need to be filled in a bit):
803 // - The IO thread is the only user of the CACHE thread.
805 // - The PROCESS_LAUNCHER thread must be stopped after IO in case
806 // the IO thread posted a task to terminate a process on the
807 // process launcher thread.
809 // - (Not sure why DB stops last.)
811 case BrowserThread::DB: {
812 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DBThread");
816 case BrowserThread::FILE_USER_BLOCKING: {
817 TRACE_EVENT0("shutdown",
818 "BrowserMainLoop::Subsystem:FileUserBlockingThread");
819 file_user_blocking_thread_.reset();
822 case BrowserThread::FILE: {
823 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:FileThread");
825 // Clean up state that lives on or uses the file_thread_ before
827 if (resource_dispatcher_host_)
828 resource_dispatcher_host_.get()->save_file_manager()->Shutdown();
829 #endif // !defined(OS_IOS)
830 file_thread_.reset();
833 case BrowserThread::PROCESS_LAUNCHER: {
834 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:LauncherThread");
835 process_launcher_thread_.reset();
838 case BrowserThread::CACHE: {
839 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:CacheThread");
840 cache_thread_.reset();
843 case BrowserThread::IO: {
844 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IOThread");
848 case BrowserThread::UI:
849 case BrowserThread::ID_COUNT:
858 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IndexedDBThread");
859 indexed_db_thread_.reset();
863 // Close the blocking I/O pool after the other threads. Other threads such
864 // as the I/O thread may need to schedule work like closing files or flushing
865 // data during shutdown, so the blocking pool needs to be available. There
866 // may also be slow operations pending that will blcok shutdown, so closing
867 // it here (which will block until required operations are complete) gives
868 // more head start for those operations to finish.
870 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:ThreadPool");
871 BrowserThreadImpl::ShutdownThreadPool();
875 // Must happen after the IO thread is shutdown since this may be accessed from
878 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUChannelFactory");
879 if (BrowserGpuChannelHostFactory::instance())
880 BrowserGpuChannelHostFactory::Terminate();
883 // Must happen after the I/O thread is shutdown since this class lives on the
884 // I/O thread and isn't threadsafe.
886 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GamepadService");
887 GamepadService::GetInstance()->Terminate();
890 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:SensorService");
891 DeviceInertialSensorService::GetInstance()->Shutdown();
894 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DeleteDataSources");
895 URLDataManager::DeleteDataSources();
897 #endif // !defined(OS_IOS)
900 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:PostDestroyThreads");
901 parts_->PostDestroyThreads();
905 void BrowserMainLoop::InitializeMainThread() {
906 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeMainThread")
907 const char* kThreadName = "CrBrowserMain";
908 base::PlatformThread::SetName(kThreadName);
909 if (main_message_loop_)
910 main_message_loop_->set_thread_name(kThreadName);
912 // Register the main thread by instantiating it, but don't call any methods.
914 new BrowserThreadImpl(BrowserThread::UI, base::MessageLoop::current()));
917 int BrowserMainLoop::BrowserThreadsStarted() {
918 TRACE_EVENT0("startup", "BrowserMainLoop::BrowserThreadsStarted")
921 indexed_db_thread_.reset(new base::Thread("IndexedDB"));
922 indexed_db_thread_->Start();
925 #if defined(OS_ANDROID)
926 // Up the priority of anything that touches with display tasks
927 // (this thread is UI thread, and io_thread_ is for IPCs).
928 io_thread_->SetPriority(base::kThreadPriority_Display);
929 base::PlatformThread::SetThreadPriority(
930 base::PlatformThread::CurrentHandle(),
931 base::kThreadPriority_Display);
935 HistogramSynchronizer::GetInstance();
937 // Initialize the GpuDataManager before we set up the MessageLoops because
938 // otherwise we'll trigger the assertion about doing IO on the UI thread.
939 GpuDataManagerImpl::GetInstance()->Initialize();
941 bool always_uses_gpu = IsForceCompositingModeEnabled();
942 bool established_gpu_channel = false;
943 #if defined(USE_AURA) || defined(OS_ANDROID)
944 established_gpu_channel =
945 !parsed_command_line_.HasSwitch(switches::kDisableGpuProcessPrelaunch) ||
946 parsed_command_line_.HasSwitch(switches::kSingleProcess) ||
947 parsed_command_line_.HasSwitch(switches::kInProcessGPU);
948 #if defined(USE_AURA)
949 if (!GpuDataManagerImpl::GetInstance()->CanUseGpuBrowserCompositor()) {
950 established_gpu_channel = always_uses_gpu = false;
952 BrowserGpuChannelHostFactory::Initialize(established_gpu_channel);
953 ImageTransportFactory::Initialize();
954 #elif defined(OS_ANDROID)
955 BrowserGpuChannelHostFactory::Initialize(established_gpu_channel);
959 #if defined(OS_LINUX)
960 device_monitor_linux_.reset(new DeviceMonitorLinux());
961 #elif defined(OS_MACOSX)
962 device_monitor_mac_.reset(new DeviceMonitorMac());
965 // RDH needs the IO thread to be created
967 TRACE_EVENT0("startup",
968 "BrowserMainLoop::BrowserThreadsStarted:InitResourceDispatcherHost");
969 resource_dispatcher_host_.reset(new ResourceDispatcherHostImpl());
972 // MediaStreamManager needs the IO thread to be created.
974 TRACE_EVENT0("startup",
975 "BrowserMainLoop::BrowserThreadsStarted:InitMediaStreamManager");
976 media_stream_manager_.reset(new MediaStreamManager(audio_manager_.get()));
980 TRACE_EVENT0("startup",
981 "BrowserMainLoop::BrowserThreadsStarted:InitSpeechRecognition");
982 speech_recognition_manager_.reset(new SpeechRecognitionManagerImpl(
983 audio_manager_.get(), media_stream_manager_.get()));
989 "BrowserMainLoop::BrowserThreadsStarted::InitUserInputMonitor");
990 user_input_monitor_ = media::UserInputMonitor::Create(
991 io_thread_->message_loop_proxy(), main_thread_->message_loop_proxy());
994 // Alert the clipboard class to which threads are allowed to access the
996 std::vector<base::PlatformThreadId> allowed_clipboard_threads;
997 // The current thread is the UI thread.
998 allowed_clipboard_threads.push_back(base::PlatformThread::CurrentId());
1000 // On Windows, clipboards are also used on the File or IO threads.
1001 allowed_clipboard_threads.push_back(file_thread_->thread_id());
1002 allowed_clipboard_threads.push_back(io_thread_->thread_id());
1004 ui::Clipboard::SetAllowedThreads(allowed_clipboard_threads);
1006 // When running the GPU thread in-process, avoid optimistically starting it
1007 // since creating the GPU thread races against creation of the one-and-only
1008 // ChildProcess instance which is created by the renderer thread.
1009 if (GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL) &&
1010 !established_gpu_channel &&
1012 !parsed_command_line_.HasSwitch(switches::kDisableGpuProcessPrelaunch) &&
1013 !parsed_command_line_.HasSwitch(switches::kSingleProcess) &&
1014 !parsed_command_line_.HasSwitch(switches::kInProcessGPU)) {
1015 TRACE_EVENT_INSTANT0("gpu", "Post task to launch GPU process",
1016 TRACE_EVENT_SCOPE_THREAD);
1017 BrowserThread::PostTask(
1018 BrowserThread::IO, FROM_HERE, base::Bind(
1019 base::IgnoreResult(&GpuProcessHost::Get),
1020 GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED,
1021 CAUSE_FOR_GPU_LAUNCH_BROWSER_STARTUP));
1023 #endif // !defined(OS_IOS)
1024 return result_code_;
1027 void BrowserMainLoop::InitializeToolkit() {
1028 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeToolkit")
1029 // TODO(evan): this function is rather subtle, due to the variety
1030 // of intersecting ifdefs we have. To keep it easy to follow, there
1031 // are no #else branches on any #ifs.
1032 // TODO(stevenjb): Move platform specific code into platform specific Parts
1033 // (Need to add InitializeToolkit stage to BrowserParts).
1034 // See also GTK setup in EarlyInitialization, above, and associated comments.
1036 #if defined(TOOLKIT_GTK)
1037 // It is important for this to happen before the first run dialog, as it
1038 // styles the dialog as well.
1039 gfx::InitRCStyles();
1043 // Init common control sex.
1044 INITCOMMONCONTROLSEX config;
1045 config.dwSize = sizeof(config);
1046 config.dwICC = ICC_WIN95_CLASSES;
1047 if (!InitCommonControlsEx(&config))
1048 LOG_GETLASTERROR(FATAL);
1052 parts_->ToolkitInitialized();
1055 void BrowserMainLoop::MainMessageLoopRun() {
1056 #if defined(OS_ANDROID)
1057 // Android's main message loop is the Java message loop.
1060 DCHECK_EQ(base::MessageLoop::TYPE_UI, base::MessageLoop::current()->type());
1061 if (parameters_.ui_task)
1062 base::MessageLoopForUI::current()->PostTask(FROM_HERE,
1063 *parameters_.ui_task);
1065 base::RunLoop run_loop;
1070 } // namespace content