Implement getMediaDevices.
[chromium-blink-merge.git] / content / browser / browser_main_loop.cc
blob6aef2203bc85693c3124773b35134905b5bf99c7
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"
7 #include "base/bind.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/battery_status/battery_status_service.h"
27 #include "content/browser/browser_thread_impl.h"
28 #include "content/browser/device_sensors/device_inertial_sensor_service.h"
29 #include "content/browser/download/save_file_manager.h"
30 #include "content/browser/gamepad/gamepad_service.h"
31 #include "content/browser/gpu/browser_gpu_channel_host_factory.h"
32 #include "content/browser/gpu/compositor_util.h"
33 #include "content/browser/gpu/gpu_data_manager_impl.h"
34 #include "content/browser/gpu/gpu_process_host.h"
35 #include "content/browser/gpu/gpu_process_host_ui_shim.h"
36 #include "content/browser/histogram_synchronizer.h"
37 #include "content/browser/loader/resource_dispatcher_host_impl.h"
38 #include "content/browser/media/capture/audio_mirroring_manager.h"
39 #include "content/browser/media/media_internals.h"
40 #include "content/browser/net/browser_online_state_observer.h"
41 #include "content/browser/plugin_service_impl.h"
42 #include "content/browser/renderer_host/media/media_stream_manager.h"
43 #include "content/browser/speech/speech_recognition_manager_impl.h"
44 #include "content/browser/startup_task_runner.h"
45 #include "content/browser/time_zone_monitor.h"
46 #include "content/browser/webui/content_web_ui_controller_factory.h"
47 #include "content/browser/webui/url_data_manager.h"
48 #include "content/public/browser/browser_main_parts.h"
49 #include "content/public/browser/browser_shutdown.h"
50 #include "content/public/browser/content_browser_client.h"
51 #include "content/public/browser/render_process_host.h"
52 #include "content/public/browser/tracing_controller.h"
53 #include "content/public/common/content_switches.h"
54 #include "content/public/common/main_function_params.h"
55 #include "content/public/common/result_codes.h"
56 #include "crypto/nss_util.h"
57 #include "media/audio/audio_manager.h"
58 #include "media/base/media.h"
59 #include "media/base/user_input_monitor.h"
60 #include "media/midi/midi_manager.h"
61 #include "net/base/network_change_notifier.h"
62 #include "net/socket/client_socket_factory.h"
63 #include "net/ssl/ssl_config_service.h"
64 #include "ui/base/clipboard/clipboard.h"
66 #if defined(USE_AURA) || (defined(OS_MACOSX) && !defined(OS_IOS))
67 #include "content/browser/compositor/image_transport_factory.h"
68 #endif
70 #if defined(USE_AURA)
71 #include "content/public/browser/context_factory.h"
72 #include "ui/aura/env.h"
73 #endif
75 #if !defined(OS_IOS)
76 #include "content/browser/renderer_host/render_process_host_impl.h"
77 #endif
79 #if defined(OS_ANDROID)
80 #include "base/android/jni_android.h"
81 #include "content/browser/android/browser_startup_controller.h"
82 #include "content/browser/android/surface_texture_peer_browser_impl.h"
83 #include "content/browser/android/tracing_controller_android.h"
84 #include "ui/gl/gl_surface.h"
85 #endif
87 #if defined(OS_MACOSX) && !defined(OS_IOS)
88 #include "content/browser/theme_helper_mac.h"
89 #endif
91 #if defined(OS_WIN)
92 #include <windows.h>
93 #include <commctrl.h>
94 #include <shellapi.h>
96 #include "content/browser/system_message_window_win.h"
97 #include "content/common/sandbox_win.h"
98 #include "net/base/winsock_init.h"
99 #include "ui/base/l10n/l10n_util_win.h"
100 #endif
102 #if defined(USE_GLIB)
103 #include <glib-object.h>
104 #endif
106 #if defined(OS_LINUX) && defined(USE_UDEV)
107 #include "content/browser/device_monitor_udev.h"
108 #elif defined(OS_MACOSX) && !defined(OS_IOS)
109 #include "content/browser/device_monitor_mac.h"
110 #endif
112 #if defined(OS_POSIX) && !defined(OS_MACOSX)
113 #include "content/browser/renderer_host/render_sandbox_host_linux.h"
114 #include "content/browser/zygote_host/zygote_host_impl_linux.h"
115 #include "sandbox/linux/suid/client/setuid_sandbox_client.h"
116 #endif
118 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
119 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
120 #endif
122 #if defined(USE_X11)
123 #include "ui/gfx/x/x11_connection.h"
124 #include "ui/gfx/x/x11_types.h"
125 #endif
127 // One of the linux specific headers defines this as a macro.
128 #ifdef DestroyAll
129 #undef DestroyAll
130 #endif
132 namespace content {
133 namespace {
135 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
136 void SetupSandbox(const CommandLine& parsed_command_line) {
137 TRACE_EVENT0("startup", "SetupSandbox");
138 base::FilePath sandbox_binary;
140 scoped_ptr<sandbox::SetuidSandboxClient> setuid_sandbox_client(
141 sandbox::SetuidSandboxClient::Create());
143 const bool want_setuid_sandbox =
144 !parsed_command_line.HasSwitch(switches::kNoSandbox) &&
145 !parsed_command_line.HasSwitch(switches::kDisableSetuidSandbox) &&
146 !setuid_sandbox_client->IsDisabledViaEnvironment();
148 static const char no_suid_error[] =
149 "Running without the SUID sandbox! See "
150 "https://code.google.com/p/chromium/wiki/LinuxSUIDSandboxDevelopment "
151 "for more information on developing with the sandbox on.";
152 if (want_setuid_sandbox) {
153 sandbox_binary = setuid_sandbox_client->GetSandboxBinaryPath();
154 if (sandbox_binary.empty()) {
155 // This needs to be fatal. Talk to security@chromium.org if you feel
156 // otherwise.
157 LOG(FATAL) << no_suid_error;
159 } else {
160 LOG(ERROR) << no_suid_error;
163 // Tickle the sandbox host and zygote host so they fork now.
164 RenderSandboxHostLinux::GetInstance()->Init();
165 ZygoteHostImpl::GetInstance()->Init(sandbox_binary.value());
167 #endif
169 #if defined(USE_GLIB)
170 static void GLibLogHandler(const gchar* log_domain,
171 GLogLevelFlags log_level,
172 const gchar* message,
173 gpointer userdata) {
174 if (!log_domain)
175 log_domain = "<unknown>";
176 if (!message)
177 message = "<no message>";
179 if (strstr(message, "Unable to retrieve the file info for")) {
180 LOG(ERROR) << "GTK File code error: " << message;
181 } else if (strstr(message, "Could not find the icon") &&
182 strstr(log_domain, "Gtk")) {
183 LOG(ERROR) << "GTK icon error: " << message;
184 } else if (strstr(message, "Theme file for default has no") ||
185 strstr(message, "Theme directory") ||
186 strstr(message, "theme pixmap") ||
187 strstr(message, "locate theme engine")) {
188 LOG(ERROR) << "GTK theme error: " << message;
189 } else if (strstr(message, "Unable to create Ubuntu Menu Proxy") &&
190 strstr(log_domain, "<unknown>")) {
191 LOG(ERROR) << "GTK menu proxy create failed";
192 } else if (strstr(message, "Out of memory") &&
193 strstr(log_domain, "<unknown>")) {
194 LOG(ERROR) << "DBus call timeout or out of memory: "
195 << "http://crosbug.com/15496";
196 } else if (strstr(message, "Could not connect: Connection refused") &&
197 strstr(log_domain, "<unknown>")) {
198 LOG(ERROR) << "DConf settings backend could not connect to session bus: "
199 << "http://crbug.com/179797";
200 } else if (strstr(message, "Attempting to store changes into") ||
201 strstr(message, "Attempting to set the permissions of")) {
202 LOG(ERROR) << message << " (http://bugs.chromium.org/161366)";
203 } else if (strstr(message, "drawable is not a native X11 window")) {
204 LOG(ERROR) << message << " (http://bugs.chromium.org/329991)";
205 } else {
206 LOG(DFATAL) << log_domain << ": " << message;
210 static void SetUpGLibLogHandler() {
211 // Register GLib-handled assertions to go through our logging system.
212 const char* kLogDomains[] = { NULL, "Gtk", "Gdk", "GLib", "GLib-GObject" };
213 for (size_t i = 0; i < arraysize(kLogDomains); i++) {
214 g_log_set_handler(kLogDomains[i],
215 static_cast<GLogLevelFlags>(G_LOG_FLAG_RECURSION |
216 G_LOG_FLAG_FATAL |
217 G_LOG_LEVEL_ERROR |
218 G_LOG_LEVEL_CRITICAL |
219 G_LOG_LEVEL_WARNING),
220 GLibLogHandler,
221 NULL);
224 #endif
226 void OnStoppedStartupTracing(const base::FilePath& trace_file) {
227 VLOG(0) << "Completed startup tracing to " << trace_file.value();
230 #if defined(USE_AURA)
231 bool ShouldInitializeBrowserGpuChannelAndTransportSurface() {
232 return true;
234 #elif defined(OS_MACOSX) && !defined(OS_IOS)
235 bool ShouldInitializeBrowserGpuChannelAndTransportSurface() {
236 return IsDelegatedRendererEnabled();
238 #endif
240 } // namespace
242 // The currently-running BrowserMainLoop. There can be one or zero.
243 BrowserMainLoop* g_current_browser_main_loop = NULL;
245 // This is just to be able to keep ShutdownThreadsAndCleanUp out of
246 // the public interface of BrowserMainLoop.
247 class BrowserShutdownImpl {
248 public:
249 static void ImmediateShutdownAndExitProcess() {
250 DCHECK(g_current_browser_main_loop);
251 g_current_browser_main_loop->ShutdownThreadsAndCleanUp();
253 #if defined(OS_WIN)
254 // At this point the message loop is still running yet we've shut everything
255 // down. If any messages are processed we'll likely crash. Exit now.
256 ExitProcess(RESULT_CODE_NORMAL_EXIT);
257 #elif defined(OS_POSIX) && !defined(OS_MACOSX)
258 _exit(RESULT_CODE_NORMAL_EXIT);
259 #else
260 NOTIMPLEMENTED();
261 #endif
265 void ImmediateShutdownAndExitProcess() {
266 BrowserShutdownImpl::ImmediateShutdownAndExitProcess();
269 // For measuring memory usage after each task. Behind a command line flag.
270 class BrowserMainLoop::MemoryObserver : public base::MessageLoop::TaskObserver {
271 public:
272 MemoryObserver() {}
273 virtual ~MemoryObserver() {}
275 virtual void WillProcessTask(const base::PendingTask& pending_task) OVERRIDE {
278 virtual void DidProcessTask(const base::PendingTask& pending_task) OVERRIDE {
279 #if !defined(OS_IOS) // No ProcessMetrics on IOS.
280 scoped_ptr<base::ProcessMetrics> process_metrics(
281 base::ProcessMetrics::CreateProcessMetrics(
282 #if defined(OS_MACOSX)
283 base::GetCurrentProcessHandle(), NULL));
284 #else
285 base::GetCurrentProcessHandle()));
286 #endif
287 size_t private_bytes;
288 process_metrics->GetMemoryBytes(&private_bytes, NULL);
289 HISTOGRAM_MEMORY_KB("Memory.BrowserUsed", private_bytes >> 10);
290 #endif
292 private:
293 DISALLOW_COPY_AND_ASSIGN(MemoryObserver);
297 // BrowserMainLoop construction / destruction =============================
299 BrowserMainLoop* BrowserMainLoop::GetInstance() {
300 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
301 return g_current_browser_main_loop;
304 BrowserMainLoop::BrowserMainLoop(const MainFunctionParams& parameters)
305 : parameters_(parameters),
306 parsed_command_line_(parameters.command_line),
307 result_code_(RESULT_CODE_NORMAL_EXIT),
308 created_threads_(false),
309 // ContentMainRunner should have enabled tracing of the browser process
310 // when kTraceStartup is in the command line.
311 is_tracing_startup_(
312 parameters.command_line.HasSwitch(switches::kTraceStartup)) {
313 DCHECK(!g_current_browser_main_loop);
314 g_current_browser_main_loop = this;
317 BrowserMainLoop::~BrowserMainLoop() {
318 DCHECK_EQ(this, g_current_browser_main_loop);
319 #if !defined(OS_IOS)
320 ui::Clipboard::DestroyClipboardForCurrentThread();
321 #endif // !defined(OS_IOS)
322 g_current_browser_main_loop = NULL;
325 void BrowserMainLoop::Init() {
326 TRACE_EVENT0("startup", "BrowserMainLoop::Init");
327 parts_.reset(
328 GetContentClient()->browser()->CreateBrowserMainParts(parameters_));
331 // BrowserMainLoop stages ==================================================
333 void BrowserMainLoop::EarlyInitialization() {
334 TRACE_EVENT0("startup", "BrowserMainLoop::EarlyInitialization");
336 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
337 // No thread should be created before this call, as SetupSandbox()
338 // will end-up using fork().
339 SetupSandbox(parsed_command_line_);
340 #endif
342 #if defined(USE_X11)
343 if (parsed_command_line_.HasSwitch(switches::kSingleProcess) ||
344 parsed_command_line_.HasSwitch(switches::kInProcessGPU)) {
345 if (!gfx::InitializeThreadedX11()) {
346 LOG(ERROR) << "Failed to put Xlib into threaded mode.";
349 #endif
351 // GLib's spawning of new processes is buggy, so it's important that at this
352 // point GLib does not need to start DBUS. Chrome should always start with
353 // DBUS_SESSION_BUS_ADDRESS properly set. See crbug.com/309093.
354 #if defined(USE_GLIB)
355 // g_type_init will be deprecated in 2.36. 2.35 is the development
356 // version for 2.36, hence do not call g_type_init starting 2.35.
357 // http://developer.gnome.org/gobject/unstable/gobject-Type-Information.html#g-type-init
358 #if !GLIB_CHECK_VERSION(2, 35, 0)
359 // GLib type system initialization. Needed at least for gconf,
360 // used in net/proxy/proxy_config_service_linux.cc. Most likely
361 // this is superfluous as gtk_init() ought to do this. It's
362 // definitely harmless, so retained as a reminder of this
363 // requirement for gconf.
364 g_type_init();
365 #endif
367 SetUpGLibLogHandler();
368 #endif
370 if (parts_)
371 parts_->PreEarlyInitialization();
373 #if defined(OS_MACOSX)
374 // We use quite a few file descriptors for our IPC, and the default limit on
375 // the Mac is low (256), so bump it up.
376 base::SetFdLimit(1024);
377 #endif
379 #if defined(OS_WIN)
380 net::EnsureWinsockInit();
381 #endif
383 #if !defined(USE_OPENSSL)
384 // We want to be sure to init NSPR on the main thread.
385 crypto::EnsureNSPRInit();
386 #endif // !defined(USE_OPENSSL)
388 #if !defined(OS_IOS)
389 if (parsed_command_line_.HasSwitch(switches::kRendererProcessLimit)) {
390 std::string limit_string = parsed_command_line_.GetSwitchValueASCII(
391 switches::kRendererProcessLimit);
392 size_t process_limit;
393 if (base::StringToSizeT(limit_string, &process_limit)) {
394 RenderProcessHost::SetMaxRendererProcessCount(process_limit);
397 #endif // !defined(OS_IOS)
399 if (parts_)
400 parts_->PostEarlyInitialization();
403 void BrowserMainLoop::MainMessageLoopStart() {
404 TRACE_EVENT0("startup", "BrowserMainLoop::MainMessageLoopStart");
405 if (parts_) {
406 TRACE_EVENT0("startup",
407 "BrowserMainLoop::MainMessageLoopStart:PreMainMessageLoopStart");
408 parts_->PreMainMessageLoopStart();
411 #if defined(OS_WIN)
412 // If we're running tests (ui_task is non-null), then the ResourceBundle
413 // has already been initialized.
414 if (!parameters_.ui_task) {
415 // Override the configured locale with the user's preferred UI language.
416 l10n_util::OverrideLocaleWithUILanguageList();
418 #endif
420 // Create a MessageLoop if one does not already exist for the current thread.
421 if (!base::MessageLoop::current())
422 main_message_loop_.reset(new base::MessageLoopForUI);
424 InitializeMainThread();
427 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SystemMonitor");
428 system_monitor_.reset(new base::SystemMonitor);
431 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:PowerMonitor");
432 scoped_ptr<base::PowerMonitorSource> power_monitor_source(
433 new base::PowerMonitorDeviceSource());
434 power_monitor_.reset(new base::PowerMonitor(power_monitor_source.Pass()));
437 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:HighResTimerManager");
438 hi_res_timer_manager_.reset(new base::HighResolutionTimerManager);
441 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:NetworkChangeNotifier");
442 network_change_notifier_.reset(net::NetworkChangeNotifier::Create());
445 #if !defined(OS_IOS)
447 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MediaFeatures");
448 media::InitializeCPUSpecificMediaFeatures();
451 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:AudioMan");
452 audio_manager_.reset(media::AudioManager::Create(
453 MediaInternals::GetInstance()));
456 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MidiManager");
457 midi_manager_.reset(media::MidiManager::Create());
460 TRACE_EVENT0("startup",
461 "BrowserMainLoop::Subsystem:ContentWebUIController");
462 WebUIControllerFactory::RegisterFactory(
463 ContentWebUIControllerFactory::GetInstance());
467 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:AudioMirroringManager");
468 audio_mirroring_manager_.reset(new AudioMirroringManager());
471 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:OnlineStateObserver");
472 online_state_observer_.reset(new BrowserOnlineStateObserver);
476 system_stats_monitor_.reset(new base::debug::TraceEventSystemStatsMonitor(
477 base::ThreadTaskRunnerHandle::Get()));
479 #endif // !defined(OS_IOS)
481 #if defined(OS_WIN)
482 system_message_window_.reset(new SystemMessageWindowWin);
483 #endif
485 if (parts_)
486 parts_->PostMainMessageLoopStart();
488 #if !defined(OS_IOS)
489 // Start tracing to a file if needed. Only do this after starting the main
490 // message loop to avoid calling MessagePumpForUI::ScheduleWork() before
491 // MessagePumpForUI::Start() as it will crash the browser.
492 if (is_tracing_startup_) {
493 TRACE_EVENT0("startup", "BrowserMainLoop::InitStartupTracing");
494 InitStartupTracing(parsed_command_line_);
496 #endif // !defined(OS_IOS)
498 #if defined(OS_ANDROID)
500 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SurfaceTexturePeer");
501 SurfaceTexturePeer::InitInstance(new SurfaceTexturePeerBrowserImpl());
503 #endif
505 if (parsed_command_line_.HasSwitch(switches::kMemoryMetrics)) {
506 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MemoryObserver");
507 memory_observer_.reset(new MemoryObserver());
508 base::MessageLoop::current()->AddTaskObserver(memory_observer_.get());
511 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
512 trace_memory_controller_.reset(new base::debug::TraceMemoryController(
513 base::MessageLoop::current()->message_loop_proxy(),
514 ::HeapProfilerWithPseudoStackStart,
515 ::HeapProfilerStop,
516 ::GetHeapProfile));
517 #endif
520 int BrowserMainLoop::PreCreateThreads() {
522 if (parts_) {
523 TRACE_EVENT0("startup",
524 "BrowserMainLoop::CreateThreads:PreCreateThreads");
525 result_code_ = parts_->PreCreateThreads();
528 #if defined(ENABLE_PLUGINS)
529 // Prior to any processing happening on the io thread, we create the
530 // plugin service as it is predominantly used from the io thread,
531 // but must be created on the main thread. The service ctor is
532 // inexpensive and does not invoke the io_thread() accessor.
534 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads:PluginService");
535 PluginService::GetInstance()->Init();
537 #endif
539 #if !defined(OS_IOS) && (!defined(GOOGLE_CHROME_BUILD) || defined(OS_ANDROID))
540 // Single-process is an unsupported and not fully tested mode, so
541 // don't enable it for official Chrome builds (except on Android).
542 if (parsed_command_line_.HasSwitch(switches::kSingleProcess))
543 RenderProcessHost::SetRunRendererInProcess(true);
544 #endif
545 return result_code_;
548 void BrowserMainLoop::CreateStartupTasks() {
549 TRACE_EVENT0("startup", "BrowserMainLoop::CreateStartupTasks");
551 // First time through, we really want to create all the tasks
552 if (!startup_task_runner_.get()) {
553 #if defined(OS_ANDROID)
554 startup_task_runner_ = make_scoped_ptr(new StartupTaskRunner(
555 base::Bind(&BrowserStartupComplete),
556 base::MessageLoop::current()->message_loop_proxy()));
557 #else
558 startup_task_runner_ = make_scoped_ptr(new StartupTaskRunner(
559 base::Callback<void(int)>(),
560 base::MessageLoop::current()->message_loop_proxy()));
561 #endif
562 StartupTask pre_create_threads =
563 base::Bind(&BrowserMainLoop::PreCreateThreads, base::Unretained(this));
564 startup_task_runner_->AddTask(pre_create_threads);
566 StartupTask create_threads =
567 base::Bind(&BrowserMainLoop::CreateThreads, base::Unretained(this));
568 startup_task_runner_->AddTask(create_threads);
570 StartupTask browser_thread_started = base::Bind(
571 &BrowserMainLoop::BrowserThreadsStarted, base::Unretained(this));
572 startup_task_runner_->AddTask(browser_thread_started);
574 StartupTask pre_main_message_loop_run = base::Bind(
575 &BrowserMainLoop::PreMainMessageLoopRun, base::Unretained(this));
576 startup_task_runner_->AddTask(pre_main_message_loop_run);
578 #if defined(OS_ANDROID)
579 if (BrowserMayStartAsynchronously()) {
580 startup_task_runner_->StartRunningTasksAsync();
582 #endif
584 #if defined(OS_ANDROID)
585 if (!BrowserMayStartAsynchronously()) {
586 // A second request for asynchronous startup can be ignored, so
587 // StartupRunningTasksAsync is only called first time through. If, however,
588 // this is a request for synchronous startup then it must override any
589 // previous call for async startup, so we call RunAllTasksNow()
590 // unconditionally.
591 startup_task_runner_->RunAllTasksNow();
593 #else
594 startup_task_runner_->RunAllTasksNow();
595 #endif
598 int BrowserMainLoop::CreateThreads() {
599 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads");
601 base::Thread::Options default_options;
602 base::Thread::Options io_message_loop_options;
603 io_message_loop_options.message_loop_type = base::MessageLoop::TYPE_IO;
604 base::Thread::Options ui_message_loop_options;
605 ui_message_loop_options.message_loop_type = base::MessageLoop::TYPE_UI;
607 // Start threads in the order they occur in the BrowserThread::ID
608 // enumeration, except for BrowserThread::UI which is the main
609 // thread.
611 // Must be size_t so we can increment it.
612 for (size_t thread_id = BrowserThread::UI + 1;
613 thread_id < BrowserThread::ID_COUNT;
614 ++thread_id) {
615 scoped_ptr<BrowserProcessSubThread>* thread_to_start = NULL;
616 base::Thread::Options* options = &default_options;
618 switch (thread_id) {
619 case BrowserThread::DB:
620 TRACE_EVENT_BEGIN1("startup",
621 "BrowserMainLoop::CreateThreads:start",
622 "Thread", "BrowserThread::DB");
623 thread_to_start = &db_thread_;
624 break;
625 case BrowserThread::FILE_USER_BLOCKING:
626 TRACE_EVENT_BEGIN1("startup",
627 "BrowserMainLoop::CreateThreads:start",
628 "Thread", "BrowserThread::FILE_USER_BLOCKING");
629 thread_to_start = &file_user_blocking_thread_;
630 break;
631 case BrowserThread::FILE:
632 TRACE_EVENT_BEGIN1("startup",
633 "BrowserMainLoop::CreateThreads:start",
634 "Thread", "BrowserThread::FILE");
635 thread_to_start = &file_thread_;
636 #if defined(OS_WIN)
637 // On Windows, the FILE thread needs to be have a UI message loop
638 // which pumps messages in such a way that Google Update can
639 // communicate back to us.
640 options = &ui_message_loop_options;
641 #else
642 options = &io_message_loop_options;
643 #endif
644 break;
645 case BrowserThread::PROCESS_LAUNCHER:
646 TRACE_EVENT_BEGIN1("startup",
647 "BrowserMainLoop::CreateThreads:start",
648 "Thread", "BrowserThread::PROCESS_LAUNCHER");
649 thread_to_start = &process_launcher_thread_;
650 break;
651 case BrowserThread::CACHE:
652 TRACE_EVENT_BEGIN1("startup",
653 "BrowserMainLoop::CreateThreads:start",
654 "Thread", "BrowserThread::CACHE");
655 thread_to_start = &cache_thread_;
656 options = &io_message_loop_options;
657 break;
658 case BrowserThread::IO:
659 TRACE_EVENT_BEGIN1("startup",
660 "BrowserMainLoop::CreateThreads:start",
661 "Thread", "BrowserThread::IO");
662 thread_to_start = &io_thread_;
663 options = &io_message_loop_options;
664 break;
665 case BrowserThread::UI:
666 case BrowserThread::ID_COUNT:
667 default:
668 NOTREACHED();
669 break;
672 BrowserThread::ID id = static_cast<BrowserThread::ID>(thread_id);
674 if (thread_to_start) {
675 (*thread_to_start).reset(new BrowserProcessSubThread(id));
676 (*thread_to_start)->StartWithOptions(*options);
677 } else {
678 NOTREACHED();
681 TRACE_EVENT_END0("startup", "BrowserMainLoop::CreateThreads:start");
684 created_threads_ = true;
685 return result_code_;
688 int BrowserMainLoop::PreMainMessageLoopRun() {
689 if (parts_) {
690 TRACE_EVENT0("startup",
691 "BrowserMainLoop::CreateThreads:PreMainMessageLoopRun");
692 parts_->PreMainMessageLoopRun();
695 // If the UI thread blocks, the whole UI is unresponsive.
696 // Do not allow disk IO from the UI thread.
697 base::ThreadRestrictions::SetIOAllowed(false);
698 base::ThreadRestrictions::DisallowWaiting();
699 return result_code_;
702 void BrowserMainLoop::RunMainMessageLoopParts() {
703 TRACE_EVENT_BEGIN_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
705 bool ran_main_loop = false;
706 if (parts_)
707 ran_main_loop = parts_->MainMessageLoopRun(&result_code_);
709 if (!ran_main_loop)
710 MainMessageLoopRun();
712 TRACE_EVENT_END_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
715 void BrowserMainLoop::ShutdownThreadsAndCleanUp() {
716 if (!created_threads_) {
717 // Called early, nothing to do
718 return;
720 TRACE_EVENT0("shutdown", "BrowserMainLoop::ShutdownThreadsAndCleanUp");
722 // Teardown may start in PostMainMessageLoopRun, and during teardown we
723 // need to be able to perform IO.
724 base::ThreadRestrictions::SetIOAllowed(true);
725 BrowserThread::PostTask(
726 BrowserThread::IO, FROM_HERE,
727 base::Bind(base::IgnoreResult(&base::ThreadRestrictions::SetIOAllowed),
728 true));
730 #if !defined(OS_IOS)
731 if (RenderProcessHost::run_renderer_in_process())
732 RenderProcessHostImpl::ShutDownInProcessRenderer();
733 #endif
735 if (parts_) {
736 TRACE_EVENT0("shutdown",
737 "BrowserMainLoop::Subsystem:PostMainMessageLoopRun");
738 parts_->PostMainMessageLoopRun();
741 trace_memory_controller_.reset();
742 system_stats_monitor_.reset();
744 #if !defined(OS_IOS)
745 // Destroying the GpuProcessHostUIShims on the UI thread posts a task to
746 // delete related objects on the GPU thread. This must be done before
747 // stopping the GPU thread. The GPU thread will close IPC channels to renderer
748 // processes so this has to happen before stopping the IO thread.
750 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUProcessHostShim");
751 GpuProcessHostUIShim::DestroyAll();
753 // Cancel pending requests and prevent new requests.
754 if (resource_dispatcher_host_) {
755 TRACE_EVENT0("shutdown",
756 "BrowserMainLoop::Subsystem:ResourceDispatcherHost");
757 resource_dispatcher_host_.get()->Shutdown();
760 #if defined(USE_AURA) || defined(OS_MACOSX)
761 if (ShouldInitializeBrowserGpuChannelAndTransportSurface()) {
762 TRACE_EVENT0("shutdown",
763 "BrowserMainLoop::Subsystem:ImageTransportFactory");
764 ImageTransportFactory::Terminate();
766 #endif
768 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
769 ZygoteHostImpl::GetInstance()->TearDownAfterLastChild();
770 #endif // defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
772 // The device monitors are using |system_monitor_| as dependency, so delete
773 // them before |system_monitor_| goes away.
774 // On Mac and windows, the monitor needs to be destroyed on the same thread
775 // as they were created. On Linux, the monitor will be deleted when IO thread
776 // goes away.
777 #if defined(OS_WIN)
778 system_message_window_.reset();
779 #elif defined(OS_MACOSX)
780 device_monitor_mac_.reset();
781 #endif
782 #endif // !defined(OS_IOS)
784 // Must be size_t so we can subtract from it.
785 for (size_t thread_id = BrowserThread::ID_COUNT - 1;
786 thread_id >= (BrowserThread::UI + 1);
787 --thread_id) {
788 // Find the thread object we want to stop. Looping over all valid
789 // BrowserThread IDs and DCHECKing on a missing case in the switch
790 // statement helps avoid a mismatch between this code and the
791 // BrowserThread::ID enumeration.
793 // The destruction order is the reverse order of occurrence in the
794 // BrowserThread::ID list. The rationale for the order is as
795 // follows (need to be filled in a bit):
798 // - The IO thread is the only user of the CACHE thread.
800 // - The PROCESS_LAUNCHER thread must be stopped after IO in case
801 // the IO thread posted a task to terminate a process on the
802 // process launcher thread.
804 // - (Not sure why DB stops last.)
805 switch (thread_id) {
806 case BrowserThread::DB: {
807 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DBThread");
808 db_thread_.reset();
810 break;
811 case BrowserThread::FILE_USER_BLOCKING: {
812 TRACE_EVENT0("shutdown",
813 "BrowserMainLoop::Subsystem:FileUserBlockingThread");
814 file_user_blocking_thread_.reset();
816 break;
817 case BrowserThread::FILE: {
818 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:FileThread");
819 #if !defined(OS_IOS)
820 // Clean up state that lives on or uses the file_thread_ before
821 // it goes away.
822 if (resource_dispatcher_host_)
823 resource_dispatcher_host_.get()->save_file_manager()->Shutdown();
824 #endif // !defined(OS_IOS)
825 file_thread_.reset();
827 break;
828 case BrowserThread::PROCESS_LAUNCHER: {
829 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:LauncherThread");
830 process_launcher_thread_.reset();
832 break;
833 case BrowserThread::CACHE: {
834 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:CacheThread");
835 cache_thread_.reset();
837 break;
838 case BrowserThread::IO: {
839 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IOThread");
840 io_thread_.reset();
842 break;
843 case BrowserThread::UI:
844 case BrowserThread::ID_COUNT:
845 default:
846 NOTREACHED();
847 break;
851 #if !defined(OS_IOS)
853 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IndexedDBThread");
854 indexed_db_thread_.reset();
856 #endif
858 // Close the blocking I/O pool after the other threads. Other threads such
859 // as the I/O thread may need to schedule work like closing files or flushing
860 // data during shutdown, so the blocking pool needs to be available. There
861 // may also be slow operations pending that will blcok shutdown, so closing
862 // it here (which will block until required operations are complete) gives
863 // more head start for those operations to finish.
865 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:ThreadPool");
866 BrowserThreadImpl::ShutdownThreadPool();
869 #if !defined(OS_IOS)
870 // Must happen after the IO thread is shutdown since this may be accessed from
871 // it.
873 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUChannelFactory");
874 if (BrowserGpuChannelHostFactory::instance())
875 BrowserGpuChannelHostFactory::Terminate();
878 // Must happen after the I/O thread is shutdown since this class lives on the
879 // I/O thread and isn't threadsafe.
881 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GamepadService");
882 GamepadService::GetInstance()->Terminate();
885 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:SensorService");
886 DeviceInertialSensorService::GetInstance()->Shutdown();
889 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:BatteryStatusService");
890 BatteryStatusService::GetInstance()->Shutdown();
893 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DeleteDataSources");
894 URLDataManager::DeleteDataSources();
896 #endif // !defined(OS_IOS)
898 if (parts_) {
899 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:PostDestroyThreads");
900 parts_->PostDestroyThreads();
904 void BrowserMainLoop::InitializeMainThread() {
905 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeMainThread");
906 const char* kThreadName = "CrBrowserMain";
907 base::PlatformThread::SetName(kThreadName);
908 if (main_message_loop_)
909 main_message_loop_->set_thread_name(kThreadName);
911 // Register the main thread by instantiating it, but don't call any methods.
912 main_thread_.reset(
913 new BrowserThreadImpl(BrowserThread::UI, base::MessageLoop::current()));
916 int BrowserMainLoop::BrowserThreadsStarted() {
917 TRACE_EVENT0("startup", "BrowserMainLoop::BrowserThreadsStarted");
919 #if !defined(OS_IOS)
920 indexed_db_thread_.reset(new base::Thread("IndexedDB"));
921 indexed_db_thread_->Start();
922 #endif
924 #if defined(OS_ANDROID)
925 // Up the priority of anything that touches with display tasks
926 // (this thread is UI thread, and io_thread_ is for IPCs).
927 io_thread_->SetPriority(base::kThreadPriority_Display);
928 base::PlatformThread::SetThreadPriority(
929 base::PlatformThread::CurrentHandle(),
930 base::kThreadPriority_Display);
931 #endif
933 #if !defined(OS_IOS)
934 HistogramSynchronizer::GetInstance();
936 #if defined(OS_ANDROID)
937 // On Android, GLSurface::InitializeOneOff() must be called before initalizing
938 // the GpuDataManagerImpl as it uses the GL bindings. crbug.com/326295
939 if (!gfx::GLSurface::InitializeOneOff())
940 LOG(FATAL) << "GLSurface::InitializeOneOff failed";
941 #endif
943 // Initialize the GpuDataManager before we set up the MessageLoops because
944 // otherwise we'll trigger the assertion about doing IO on the UI thread.
945 GpuDataManagerImpl::GetInstance()->Initialize();
947 bool always_uses_gpu = true;
948 bool established_gpu_channel = false;
949 #if defined(USE_AURA) || defined(OS_MACOSX)
950 if (ShouldInitializeBrowserGpuChannelAndTransportSurface()) {
951 established_gpu_channel = true;
952 if (!GpuDataManagerImpl::GetInstance()->CanUseGpuBrowserCompositor()) {
953 established_gpu_channel = always_uses_gpu = false;
955 BrowserGpuChannelHostFactory::Initialize(established_gpu_channel);
956 ImageTransportFactory::Initialize();
957 #if defined(USE_AURA)
958 if (aura::Env::GetInstance()) {
959 aura::Env::GetInstance()->set_context_factory(
960 content::GetContextFactory());
962 #endif
964 #elif defined(OS_ANDROID)
965 established_gpu_channel = true;
966 BrowserGpuChannelHostFactory::Initialize(established_gpu_channel);
967 #endif
969 #if defined(OS_LINUX) && defined(USE_UDEV)
970 device_monitor_linux_.reset(new DeviceMonitorLinux());
971 #elif defined(OS_MACOSX)
972 device_monitor_mac_.reset(new DeviceMonitorMac());
973 #endif
975 // RDH needs the IO thread to be created
977 TRACE_EVENT0("startup",
978 "BrowserMainLoop::BrowserThreadsStarted:InitResourceDispatcherHost");
979 resource_dispatcher_host_.reset(new ResourceDispatcherHostImpl());
982 // MediaStreamManager needs the IO thread to be created.
984 TRACE_EVENT0("startup",
985 "BrowserMainLoop::BrowserThreadsStarted:InitMediaStreamManager");
986 media_stream_manager_.reset(new MediaStreamManager(audio_manager_.get()));
990 TRACE_EVENT0("startup",
991 "BrowserMainLoop::BrowserThreadsStarted:InitSpeechRecognition");
992 speech_recognition_manager_.reset(new SpeechRecognitionManagerImpl(
993 audio_manager_.get(), media_stream_manager_.get()));
997 TRACE_EVENT0(
998 "startup",
999 "BrowserMainLoop::BrowserThreadsStarted::InitUserInputMonitor");
1000 user_input_monitor_ = media::UserInputMonitor::Create(
1001 io_thread_->message_loop_proxy(), main_thread_->message_loop_proxy());
1005 TRACE_EVENT0("startup",
1006 "BrowserMainLoop::BrowserThreadsStarted::TimeZoneMonitor");
1007 time_zone_monitor_ = TimeZoneMonitor::Create();
1010 // Alert the clipboard class to which threads are allowed to access the
1011 // clipboard:
1012 std::vector<base::PlatformThreadId> allowed_clipboard_threads;
1013 // The current thread is the UI thread.
1014 allowed_clipboard_threads.push_back(base::PlatformThread::CurrentId());
1015 #if defined(OS_WIN)
1016 // On Windows, clipboards are also used on the File or IO threads.
1017 allowed_clipboard_threads.push_back(file_thread_->thread_id());
1018 allowed_clipboard_threads.push_back(io_thread_->thread_id());
1019 #endif
1020 ui::Clipboard::SetAllowedThreads(allowed_clipboard_threads);
1022 // When running the GPU thread in-process, avoid optimistically starting it
1023 // since creating the GPU thread races against creation of the one-and-only
1024 // ChildProcess instance which is created by the renderer thread.
1025 if (GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL) &&
1026 !established_gpu_channel &&
1027 always_uses_gpu &&
1028 !parsed_command_line_.HasSwitch(switches::kSingleProcess) &&
1029 !parsed_command_line_.HasSwitch(switches::kInProcessGPU)) {
1030 TRACE_EVENT_INSTANT0("gpu", "Post task to launch GPU process",
1031 TRACE_EVENT_SCOPE_THREAD);
1032 BrowserThread::PostTask(
1033 BrowserThread::IO, FROM_HERE, base::Bind(
1034 base::IgnoreResult(&GpuProcessHost::Get),
1035 GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED,
1036 CAUSE_FOR_GPU_LAUNCH_BROWSER_STARTUP));
1039 #if defined(OS_MACOSX)
1040 ThemeHelperMac::GetInstance();
1041 #endif
1042 #endif // !defined(OS_IOS)
1044 return result_code_;
1047 bool BrowserMainLoop::InitializeToolkit() {
1048 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeToolkit");
1049 // TODO(evan): this function is rather subtle, due to the variety
1050 // of intersecting ifdefs we have. To keep it easy to follow, there
1051 // are no #else branches on any #ifs.
1052 // TODO(stevenjb): Move platform specific code into platform specific Parts
1053 // (Need to add InitializeToolkit stage to BrowserParts).
1054 // See also GTK setup in EarlyInitialization, above, and associated comments.
1056 #if defined(TOOLKIT_GTK)
1057 // It is important for this to happen before the first run dialog, as it
1058 // styles the dialog as well.
1059 gfx::InitRCStyles();
1060 #endif
1062 #if defined(OS_WIN)
1063 // Init common control sex.
1064 INITCOMMONCONTROLSEX config;
1065 config.dwSize = sizeof(config);
1066 config.dwICC = ICC_WIN95_CLASSES;
1067 if (!InitCommonControlsEx(&config))
1068 PLOG(FATAL);
1069 #endif
1071 #if defined(USE_AURA)
1073 #if defined(USE_X11)
1074 if (!gfx::GetXDisplay())
1075 return false;
1076 #endif
1078 // Env creates the compositor. Aura widgets need the compositor to be created
1079 // before they can be initialized by the browser.
1080 aura::Env::CreateInstance(true);
1081 #endif // defined(USE_AURA)
1083 if (parts_)
1084 parts_->ToolkitInitialized();
1086 return true;
1089 void BrowserMainLoop::MainMessageLoopRun() {
1090 #if defined(OS_ANDROID)
1091 // Android's main message loop is the Java message loop.
1092 NOTREACHED();
1093 #else
1094 DCHECK(base::MessageLoopForUI::IsCurrent());
1095 if (parameters_.ui_task)
1096 base::MessageLoopForUI::current()->PostTask(FROM_HERE,
1097 *parameters_.ui_task);
1099 base::RunLoop run_loop;
1100 run_loop.Run();
1101 #endif
1104 void BrowserMainLoop::InitStartupTracing(const CommandLine& command_line) {
1105 DCHECK(is_tracing_startup_);
1107 base::FilePath trace_file = command_line.GetSwitchValuePath(
1108 switches::kTraceStartupFile);
1109 // trace_file = "none" means that startup events will show up for the next
1110 // begin/end tracing (via about:tracing or AutomationProxy::BeginTracing/
1111 // EndTracing, for example).
1112 if (trace_file == base::FilePath().AppendASCII("none"))
1113 return;
1115 if (trace_file.empty()) {
1116 #if defined(OS_ANDROID)
1117 TracingControllerAndroid::GenerateTracingFilePath(&trace_file);
1118 #else
1119 // Default to saving the startup trace into the current dir.
1120 trace_file = base::FilePath().AppendASCII("chrometrace.log");
1121 #endif
1124 std::string delay_str = command_line.GetSwitchValueASCII(
1125 switches::kTraceStartupDuration);
1126 int delay_secs = 5;
1127 if (!delay_str.empty() && !base::StringToInt(delay_str, &delay_secs)) {
1128 DLOG(WARNING) << "Could not parse --" << switches::kTraceStartupDuration
1129 << "=" << delay_str << " defaulting to 5 (secs)";
1130 delay_secs = 5;
1133 BrowserThread::PostDelayedTask(
1134 BrowserThread::UI, FROM_HERE,
1135 base::Bind(&BrowserMainLoop::EndStartupTracing,
1136 base::Unretained(this), trace_file),
1137 base::TimeDelta::FromSeconds(delay_secs));
1140 void BrowserMainLoop::EndStartupTracing(const base::FilePath& trace_file) {
1141 is_tracing_startup_ = false;
1142 TracingController::GetInstance()->DisableRecording(
1143 trace_file, base::Bind(&OnStoppedStartupTracing));
1146 } // namespace content