- remove mojo_view_manager_lib_unittests from chrome_tests.py
[chromium-blink-merge.git] / content / browser / browser_main_loop.cc
blobc5c50741838b03d2225f44d1dc340c610702d674
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/bootstrap_sandbox_mac.h"
89 #include "content/browser/cocoa/system_hotkey_helper_mac.h"
90 #include "content/browser/theme_helper_mac.h"
91 #endif
93 #if defined(OS_WIN)
94 #include <windows.h>
95 #include <commctrl.h>
96 #include <shellapi.h>
98 #include "content/browser/system_message_window_win.h"
99 #include "content/common/sandbox_win.h"
100 #include "net/base/winsock_init.h"
101 #include "ui/base/l10n/l10n_util_win.h"
102 #endif
104 #if defined(USE_GLIB)
105 #include <glib-object.h>
106 #endif
108 #if defined(OS_LINUX) && defined(USE_UDEV)
109 #include "content/browser/device_monitor_udev.h"
110 #elif defined(OS_MACOSX) && !defined(OS_IOS)
111 #include "content/browser/device_monitor_mac.h"
112 #endif
114 #if defined(OS_POSIX) && !defined(OS_MACOSX)
115 #include "content/browser/renderer_host/render_sandbox_host_linux.h"
116 #include "content/browser/zygote_host/zygote_host_impl_linux.h"
117 #include "sandbox/linux/suid/client/setuid_sandbox_client.h"
118 #endif
120 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
121 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
122 #endif
124 #if defined(USE_X11)
125 #include "ui/gfx/x/x11_connection.h"
126 #include "ui/gfx/x/x11_types.h"
127 #endif
129 // One of the linux specific headers defines this as a macro.
130 #ifdef DestroyAll
131 #undef DestroyAll
132 #endif
134 namespace content {
135 namespace {
137 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
138 void SetupSandbox(const base::CommandLine& parsed_command_line) {
139 TRACE_EVENT0("startup", "SetupSandbox");
140 base::FilePath sandbox_binary;
142 scoped_ptr<sandbox::SetuidSandboxClient> setuid_sandbox_client(
143 sandbox::SetuidSandboxClient::Create());
145 const bool want_setuid_sandbox =
146 !parsed_command_line.HasSwitch(switches::kNoSandbox) &&
147 !parsed_command_line.HasSwitch(switches::kDisableSetuidSandbox) &&
148 !setuid_sandbox_client->IsDisabledViaEnvironment();
150 static const char no_suid_error[] =
151 "Running without the SUID sandbox! See "
152 "https://code.google.com/p/chromium/wiki/LinuxSUIDSandboxDevelopment "
153 "for more information on developing with the sandbox on.";
154 if (want_setuid_sandbox) {
155 sandbox_binary = setuid_sandbox_client->GetSandboxBinaryPath();
156 if (sandbox_binary.empty()) {
157 // This needs to be fatal. Talk to security@chromium.org if you feel
158 // otherwise.
159 LOG(FATAL) << no_suid_error;
161 } else {
162 LOG(ERROR) << no_suid_error;
165 // Tickle the sandbox host and zygote host so they fork now.
166 RenderSandboxHostLinux::GetInstance()->Init();
167 ZygoteHostImpl::GetInstance()->Init(sandbox_binary.value());
169 #endif
171 #if defined(USE_GLIB)
172 static void GLibLogHandler(const gchar* log_domain,
173 GLogLevelFlags log_level,
174 const gchar* message,
175 gpointer userdata) {
176 if (!log_domain)
177 log_domain = "<unknown>";
178 if (!message)
179 message = "<no message>";
181 if (strstr(message, "Unable to retrieve the file info for")) {
182 LOG(ERROR) << "GTK File code error: " << message;
183 } else if (strstr(message, "Could not find the icon") &&
184 strstr(log_domain, "Gtk")) {
185 LOG(ERROR) << "GTK icon error: " << message;
186 } else if (strstr(message, "Theme file for default has no") ||
187 strstr(message, "Theme directory") ||
188 strstr(message, "theme pixmap") ||
189 strstr(message, "locate theme engine")) {
190 LOG(ERROR) << "GTK theme error: " << message;
191 } else if (strstr(message, "Unable to create Ubuntu Menu Proxy") &&
192 strstr(log_domain, "<unknown>")) {
193 LOG(ERROR) << "GTK menu proxy create failed";
194 } else if (strstr(message, "Out of memory") &&
195 strstr(log_domain, "<unknown>")) {
196 LOG(ERROR) << "DBus call timeout or out of memory: "
197 << "http://crosbug.com/15496";
198 } else if (strstr(message, "Could not connect: Connection refused") &&
199 strstr(log_domain, "<unknown>")) {
200 LOG(ERROR) << "DConf settings backend could not connect to session bus: "
201 << "http://crbug.com/179797";
202 } else if (strstr(message, "Attempting to store changes into") ||
203 strstr(message, "Attempting to set the permissions of")) {
204 LOG(ERROR) << message << " (http://bugs.chromium.org/161366)";
205 } else if (strstr(message, "drawable is not a native X11 window")) {
206 LOG(ERROR) << message << " (http://bugs.chromium.org/329991)";
207 } else {
208 LOG(DFATAL) << log_domain << ": " << message;
212 static void SetUpGLibLogHandler() {
213 // Register GLib-handled assertions to go through our logging system.
214 const char* kLogDomains[] = { NULL, "Gtk", "Gdk", "GLib", "GLib-GObject" };
215 for (size_t i = 0; i < arraysize(kLogDomains); i++) {
216 g_log_set_handler(kLogDomains[i],
217 static_cast<GLogLevelFlags>(G_LOG_FLAG_RECURSION |
218 G_LOG_FLAG_FATAL |
219 G_LOG_LEVEL_ERROR |
220 G_LOG_LEVEL_CRITICAL |
221 G_LOG_LEVEL_WARNING),
222 GLibLogHandler,
223 NULL);
226 #endif
228 void OnStoppedStartupTracing(const base::FilePath& trace_file) {
229 VLOG(0) << "Completed startup tracing to " << trace_file.value();
232 #if defined(USE_AURA)
233 bool ShouldInitializeBrowserGpuChannelAndTransportSurface() {
234 return true;
236 #elif defined(OS_MACOSX) && !defined(OS_IOS)
237 bool ShouldInitializeBrowserGpuChannelAndTransportSurface() {
238 return IsDelegatedRendererEnabled();
240 #endif
242 } // namespace
244 // The currently-running BrowserMainLoop. There can be one or zero.
245 BrowserMainLoop* g_current_browser_main_loop = NULL;
247 // This is just to be able to keep ShutdownThreadsAndCleanUp out of
248 // the public interface of BrowserMainLoop.
249 class BrowserShutdownImpl {
250 public:
251 static void ImmediateShutdownAndExitProcess() {
252 DCHECK(g_current_browser_main_loop);
253 g_current_browser_main_loop->ShutdownThreadsAndCleanUp();
255 #if defined(OS_WIN)
256 // At this point the message loop is still running yet we've shut everything
257 // down. If any messages are processed we'll likely crash. Exit now.
258 ExitProcess(RESULT_CODE_NORMAL_EXIT);
259 #elif defined(OS_POSIX) && !defined(OS_MACOSX)
260 _exit(RESULT_CODE_NORMAL_EXIT);
261 #else
262 NOTIMPLEMENTED();
263 #endif
267 void ImmediateShutdownAndExitProcess() {
268 BrowserShutdownImpl::ImmediateShutdownAndExitProcess();
271 // For measuring memory usage after each task. Behind a command line flag.
272 class BrowserMainLoop::MemoryObserver : public base::MessageLoop::TaskObserver {
273 public:
274 MemoryObserver() {}
275 virtual ~MemoryObserver() {}
277 virtual void WillProcessTask(const base::PendingTask& pending_task) OVERRIDE {
280 virtual void DidProcessTask(const base::PendingTask& pending_task) OVERRIDE {
281 #if !defined(OS_IOS) // No ProcessMetrics on IOS.
282 scoped_ptr<base::ProcessMetrics> process_metrics(
283 base::ProcessMetrics::CreateProcessMetrics(
284 #if defined(OS_MACOSX)
285 base::GetCurrentProcessHandle(), NULL));
286 #else
287 base::GetCurrentProcessHandle()));
288 #endif
289 size_t private_bytes;
290 process_metrics->GetMemoryBytes(&private_bytes, NULL);
291 HISTOGRAM_MEMORY_KB("Memory.BrowserUsed", private_bytes >> 10);
292 #endif
294 private:
295 DISALLOW_COPY_AND_ASSIGN(MemoryObserver);
299 // BrowserMainLoop construction / destruction =============================
301 BrowserMainLoop* BrowserMainLoop::GetInstance() {
302 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
303 return g_current_browser_main_loop;
306 BrowserMainLoop::BrowserMainLoop(const MainFunctionParams& parameters)
307 : parameters_(parameters),
308 parsed_command_line_(parameters.command_line),
309 result_code_(RESULT_CODE_NORMAL_EXIT),
310 created_threads_(false),
311 // ContentMainRunner should have enabled tracing of the browser process
312 // when kTraceStartup is in the command line.
313 is_tracing_startup_(
314 parameters.command_line.HasSwitch(switches::kTraceStartup)) {
315 DCHECK(!g_current_browser_main_loop);
316 g_current_browser_main_loop = this;
319 BrowserMainLoop::~BrowserMainLoop() {
320 DCHECK_EQ(this, g_current_browser_main_loop);
321 #if !defined(OS_IOS)
322 ui::Clipboard::DestroyClipboardForCurrentThread();
323 #endif // !defined(OS_IOS)
324 g_current_browser_main_loop = NULL;
327 void BrowserMainLoop::Init() {
328 TRACE_EVENT0("startup", "BrowserMainLoop::Init");
329 parts_.reset(
330 GetContentClient()->browser()->CreateBrowserMainParts(parameters_));
333 // BrowserMainLoop stages ==================================================
335 void BrowserMainLoop::EarlyInitialization() {
336 TRACE_EVENT0("startup", "BrowserMainLoop::EarlyInitialization");
338 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
339 // No thread should be created before this call, as SetupSandbox()
340 // will end-up using fork().
341 SetupSandbox(parsed_command_line_);
342 #endif
344 #if defined(USE_X11)
345 if (parsed_command_line_.HasSwitch(switches::kSingleProcess) ||
346 parsed_command_line_.HasSwitch(switches::kInProcessGPU)) {
347 if (!gfx::InitializeThreadedX11()) {
348 LOG(ERROR) << "Failed to put Xlib into threaded mode.";
351 #endif
353 // GLib's spawning of new processes is buggy, so it's important that at this
354 // point GLib does not need to start DBUS. Chrome should always start with
355 // DBUS_SESSION_BUS_ADDRESS properly set. See crbug.com/309093.
356 #if defined(USE_GLIB)
357 // g_type_init will be deprecated in 2.36. 2.35 is the development
358 // version for 2.36, hence do not call g_type_init starting 2.35.
359 // http://developer.gnome.org/gobject/unstable/gobject-Type-Information.html#g-type-init
360 #if !GLIB_CHECK_VERSION(2, 35, 0)
361 // GLib type system initialization. Needed at least for gconf,
362 // used in net/proxy/proxy_config_service_linux.cc. Most likely
363 // this is superfluous as gtk_init() ought to do this. It's
364 // definitely harmless, so retained as a reminder of this
365 // requirement for gconf.
366 g_type_init();
367 #endif
369 SetUpGLibLogHandler();
370 #endif
372 if (parts_)
373 parts_->PreEarlyInitialization();
375 #if defined(OS_MACOSX)
376 // We use quite a few file descriptors for our IPC, and the default limit on
377 // the Mac is low (256), so bump it up.
378 base::SetFdLimit(1024);
379 #endif
381 #if defined(OS_WIN)
382 net::EnsureWinsockInit();
383 #endif
385 #if !defined(USE_OPENSSL)
386 // We want to be sure to init NSPR on the main thread.
387 crypto::EnsureNSPRInit();
388 #endif // !defined(USE_OPENSSL)
390 #if !defined(OS_IOS)
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)
401 if (parts_)
402 parts_->PostEarlyInitialization();
405 void BrowserMainLoop::MainMessageLoopStart() {
406 TRACE_EVENT0("startup", "BrowserMainLoop::MainMessageLoopStart");
407 if (parts_) {
408 TRACE_EVENT0("startup",
409 "BrowserMainLoop::MainMessageLoopStart:PreMainMessageLoopStart");
410 parts_->PreMainMessageLoopStart();
413 #if defined(OS_WIN)
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();
420 #endif
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::MessageLoopForUI);
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());
447 #if !defined(OS_IOS)
449 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MediaFeatures");
450 media::InitializeCPUSpecificMediaFeatures();
453 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:AudioMan");
454 audio_manager_.reset(media::AudioManager::Create(
455 MediaInternals::GetInstance()));
458 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MidiManager");
459 midi_manager_.reset(media::MidiManager::Create());
462 TRACE_EVENT0("startup",
463 "BrowserMainLoop::Subsystem:ContentWebUIController");
464 WebUIControllerFactory::RegisterFactory(
465 ContentWebUIControllerFactory::GetInstance());
469 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:AudioMirroringManager");
470 audio_mirroring_manager_.reset(new AudioMirroringManager());
473 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:OnlineStateObserver");
474 online_state_observer_.reset(new BrowserOnlineStateObserver);
478 system_stats_monitor_.reset(new base::debug::TraceEventSystemStatsMonitor(
479 base::ThreadTaskRunnerHandle::Get()));
481 #endif // !defined(OS_IOS)
483 #if defined(OS_WIN)
484 system_message_window_.reset(new SystemMessageWindowWin);
485 #endif
487 if (parts_)
488 parts_->PostMainMessageLoopStart();
490 #if !defined(OS_IOS)
491 // Start tracing to a file if needed. Only do this after starting the main
492 // message loop to avoid calling MessagePumpForUI::ScheduleWork() before
493 // MessagePumpForUI::Start() as it will crash the browser.
494 if (is_tracing_startup_) {
495 TRACE_EVENT0("startup", "BrowserMainLoop::InitStartupTracing");
496 InitStartupTracing(parsed_command_line_);
498 #endif // !defined(OS_IOS)
500 #if defined(OS_ANDROID)
502 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SurfaceTexturePeer");
503 SurfaceTexturePeer::InitInstance(new SurfaceTexturePeerBrowserImpl());
505 #endif
507 if (parsed_command_line_.HasSwitch(switches::kMemoryMetrics)) {
508 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MemoryObserver");
509 memory_observer_.reset(new MemoryObserver());
510 base::MessageLoop::current()->AddTaskObserver(memory_observer_.get());
513 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
514 trace_memory_controller_.reset(new base::debug::TraceMemoryController(
515 base::MessageLoop::current()->message_loop_proxy(),
516 ::HeapProfilerWithPseudoStackStart,
517 ::HeapProfilerStop,
518 ::GetHeapProfile));
519 #endif
522 int BrowserMainLoop::PreCreateThreads() {
523 if (parts_) {
524 TRACE_EVENT0("startup",
525 "BrowserMainLoop::CreateThreads:PreCreateThreads");
526 result_code_ = parts_->PreCreateThreads();
529 #if defined(ENABLE_PLUGINS)
530 // Prior to any processing happening on the io thread, we create the
531 // plugin service as it is predominantly used from the io thread,
532 // but must be created on the main thread. The service ctor is
533 // inexpensive and does not invoke the io_thread() accessor.
535 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads:PluginService");
536 PluginService::GetInstance()->Init();
538 #endif
540 #if !defined(OS_IOS) && (!defined(GOOGLE_CHROME_BUILD) || defined(OS_ANDROID))
541 // Single-process is an unsupported and not fully tested mode, so
542 // don't enable it for official Chrome builds (except on Android).
543 if (parsed_command_line_.HasSwitch(switches::kSingleProcess))
544 RenderProcessHost::SetRunRendererInProcess(true);
545 #endif
546 return result_code_;
549 void BrowserMainLoop::CreateStartupTasks() {
550 TRACE_EVENT0("startup", "BrowserMainLoop::CreateStartupTasks");
552 // First time through, we really want to create all the tasks
553 if (!startup_task_runner_.get()) {
554 #if defined(OS_ANDROID)
555 startup_task_runner_ = make_scoped_ptr(new StartupTaskRunner(
556 base::Bind(&BrowserStartupComplete),
557 base::MessageLoop::current()->message_loop_proxy()));
558 #else
559 startup_task_runner_ = make_scoped_ptr(new StartupTaskRunner(
560 base::Callback<void(int)>(),
561 base::MessageLoop::current()->message_loop_proxy()));
562 #endif
563 StartupTask pre_create_threads =
564 base::Bind(&BrowserMainLoop::PreCreateThreads, base::Unretained(this));
565 startup_task_runner_->AddTask(pre_create_threads);
567 StartupTask create_threads =
568 base::Bind(&BrowserMainLoop::CreateThreads, base::Unretained(this));
569 startup_task_runner_->AddTask(create_threads);
571 StartupTask browser_thread_started = base::Bind(
572 &BrowserMainLoop::BrowserThreadsStarted, base::Unretained(this));
573 startup_task_runner_->AddTask(browser_thread_started);
575 StartupTask pre_main_message_loop_run = base::Bind(
576 &BrowserMainLoop::PreMainMessageLoopRun, base::Unretained(this));
577 startup_task_runner_->AddTask(pre_main_message_loop_run);
579 #if defined(OS_ANDROID)
580 if (BrowserMayStartAsynchronously()) {
581 startup_task_runner_->StartRunningTasksAsync();
583 #endif
585 #if defined(OS_ANDROID)
586 if (!BrowserMayStartAsynchronously()) {
587 // A second request for asynchronous startup can be ignored, so
588 // StartupRunningTasksAsync is only called first time through. If, however,
589 // this is a request for synchronous startup then it must override any
590 // previous call for async startup, so we call RunAllTasksNow()
591 // unconditionally.
592 startup_task_runner_->RunAllTasksNow();
594 #else
595 startup_task_runner_->RunAllTasksNow();
596 #endif
599 int BrowserMainLoop::CreateThreads() {
600 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads");
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;
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 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
625 break;
626 case BrowserThread::FILE_USER_BLOCKING:
627 TRACE_EVENT_BEGIN1("startup",
628 "BrowserMainLoop::CreateThreads:start",
629 "Thread", "BrowserThread::FILE_USER_BLOCKING");
630 thread_to_start = &file_user_blocking_thread_;
631 break;
632 case BrowserThread::FILE:
633 TRACE_EVENT_BEGIN1("startup",
634 "BrowserMainLoop::CreateThreads:start",
635 "Thread", "BrowserThread::FILE");
636 thread_to_start = &file_thread_;
637 #if defined(OS_WIN)
638 // On Windows, the FILE thread needs to be have a UI message loop
639 // which pumps messages in such a way that Google Update can
640 // communicate back to us.
641 options = ui_message_loop_options;
642 #else
643 options = io_message_loop_options;
644 #endif
645 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
646 break;
647 case BrowserThread::PROCESS_LAUNCHER:
648 TRACE_EVENT_BEGIN1("startup",
649 "BrowserMainLoop::CreateThreads:start",
650 "Thread", "BrowserThread::PROCESS_LAUNCHER");
651 thread_to_start = &process_launcher_thread_;
652 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
653 break;
654 case BrowserThread::CACHE:
655 TRACE_EVENT_BEGIN1("startup",
656 "BrowserMainLoop::CreateThreads:start",
657 "Thread", "BrowserThread::CACHE");
658 thread_to_start = &cache_thread_;
659 options = io_message_loop_options;
660 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
661 break;
662 case BrowserThread::IO:
663 TRACE_EVENT_BEGIN1("startup",
664 "BrowserMainLoop::CreateThreads:start",
665 "Thread", "BrowserThread::IO");
666 thread_to_start = &io_thread_;
667 options = io_message_loop_options;
668 break;
669 case BrowserThread::UI:
670 case BrowserThread::ID_COUNT:
671 default:
672 NOTREACHED();
673 break;
676 BrowserThread::ID id = static_cast<BrowserThread::ID>(thread_id);
678 if (thread_to_start) {
679 (*thread_to_start).reset(new BrowserProcessSubThread(id));
680 (*thread_to_start)->StartWithOptions(options);
681 } else {
682 NOTREACHED();
685 TRACE_EVENT_END0("startup", "BrowserMainLoop::CreateThreads:start");
687 created_threads_ = true;
688 return result_code_;
691 int BrowserMainLoop::PreMainMessageLoopRun() {
692 if (parts_) {
693 TRACE_EVENT0("startup",
694 "BrowserMainLoop::CreateThreads:PreMainMessageLoopRun");
695 parts_->PreMainMessageLoopRun();
698 // If the UI thread blocks, the whole UI is unresponsive.
699 // Do not allow disk IO from the UI thread.
700 base::ThreadRestrictions::SetIOAllowed(false);
701 base::ThreadRestrictions::DisallowWaiting();
702 return result_code_;
705 void BrowserMainLoop::RunMainMessageLoopParts() {
706 TRACE_EVENT_BEGIN_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
708 bool ran_main_loop = false;
709 if (parts_)
710 ran_main_loop = parts_->MainMessageLoopRun(&result_code_);
712 if (!ran_main_loop)
713 MainMessageLoopRun();
715 TRACE_EVENT_END_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
718 void BrowserMainLoop::ShutdownThreadsAndCleanUp() {
719 if (!created_threads_) {
720 // Called early, nothing to do
721 return;
723 TRACE_EVENT0("shutdown", "BrowserMainLoop::ShutdownThreadsAndCleanUp");
725 // Teardown may start in PostMainMessageLoopRun, and during teardown we
726 // need to be able to perform IO.
727 base::ThreadRestrictions::SetIOAllowed(true);
728 BrowserThread::PostTask(
729 BrowserThread::IO, FROM_HERE,
730 base::Bind(base::IgnoreResult(&base::ThreadRestrictions::SetIOAllowed),
731 true));
733 #if !defined(OS_IOS)
734 if (RenderProcessHost::run_renderer_in_process())
735 RenderProcessHostImpl::ShutDownInProcessRenderer();
736 #endif
738 if (parts_) {
739 TRACE_EVENT0("shutdown",
740 "BrowserMainLoop::Subsystem:PostMainMessageLoopRun");
741 parts_->PostMainMessageLoopRun();
744 trace_memory_controller_.reset();
745 system_stats_monitor_.reset();
747 #if !defined(OS_IOS)
748 // Destroying the GpuProcessHostUIShims on the UI thread posts a task to
749 // delete related objects on the GPU thread. This must be done before
750 // stopping the GPU thread. The GPU thread will close IPC channels to renderer
751 // processes so this has to happen before stopping the IO thread.
753 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUProcessHostShim");
754 GpuProcessHostUIShim::DestroyAll();
756 // Cancel pending requests and prevent new requests.
757 if (resource_dispatcher_host_) {
758 TRACE_EVENT0("shutdown",
759 "BrowserMainLoop::Subsystem:ResourceDispatcherHost");
760 resource_dispatcher_host_.get()->Shutdown();
763 #if defined(USE_AURA) || defined(OS_MACOSX)
764 if (ShouldInitializeBrowserGpuChannelAndTransportSurface()) {
765 TRACE_EVENT0("shutdown",
766 "BrowserMainLoop::Subsystem:ImageTransportFactory");
767 ImageTransportFactory::Terminate();
769 #endif
771 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
772 ZygoteHostImpl::GetInstance()->TearDownAfterLastChild();
773 #endif // defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
775 // The device monitors are using |system_monitor_| as dependency, so delete
776 // them before |system_monitor_| goes away.
777 // On Mac and windows, the monitor needs to be destroyed on the same thread
778 // as they were created. On Linux, the monitor will be deleted when IO thread
779 // goes away.
780 #if defined(OS_WIN)
781 system_message_window_.reset();
782 #elif defined(OS_MACOSX)
783 device_monitor_mac_.reset();
784 #endif
785 #endif // !defined(OS_IOS)
787 // Must be size_t so we can subtract from it.
788 for (size_t thread_id = BrowserThread::ID_COUNT - 1;
789 thread_id >= (BrowserThread::UI + 1);
790 --thread_id) {
791 // Find the thread object we want to stop. Looping over all valid
792 // BrowserThread IDs and DCHECKing on a missing case in the switch
793 // statement helps avoid a mismatch between this code and the
794 // BrowserThread::ID enumeration.
796 // The destruction order is the reverse order of occurrence in the
797 // BrowserThread::ID list. The rationale for the order is as
798 // follows (need to be filled in a bit):
801 // - The IO thread is the only user of the CACHE thread.
803 // - The PROCESS_LAUNCHER thread must be stopped after IO in case
804 // the IO thread posted a task to terminate a process on the
805 // process launcher thread.
807 // - (Not sure why DB stops last.)
808 switch (thread_id) {
809 case BrowserThread::DB: {
810 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DBThread");
811 db_thread_.reset();
813 break;
814 case BrowserThread::FILE_USER_BLOCKING: {
815 TRACE_EVENT0("shutdown",
816 "BrowserMainLoop::Subsystem:FileUserBlockingThread");
817 file_user_blocking_thread_.reset();
819 break;
820 case BrowserThread::FILE: {
821 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:FileThread");
822 #if !defined(OS_IOS)
823 // Clean up state that lives on or uses the file_thread_ before
824 // it goes away.
825 if (resource_dispatcher_host_)
826 resource_dispatcher_host_.get()->save_file_manager()->Shutdown();
827 #endif // !defined(OS_IOS)
828 file_thread_.reset();
830 break;
831 case BrowserThread::PROCESS_LAUNCHER: {
832 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:LauncherThread");
833 process_launcher_thread_.reset();
835 break;
836 case BrowserThread::CACHE: {
837 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:CacheThread");
838 cache_thread_.reset();
840 break;
841 case BrowserThread::IO: {
842 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IOThread");
843 io_thread_.reset();
845 break;
846 case BrowserThread::UI:
847 case BrowserThread::ID_COUNT:
848 default:
849 NOTREACHED();
850 break;
854 #if !defined(OS_IOS)
856 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IndexedDBThread");
857 indexed_db_thread_.reset();
859 #endif
861 // Close the blocking I/O pool after the other threads. Other threads such
862 // as the I/O thread may need to schedule work like closing files or flushing
863 // data during shutdown, so the blocking pool needs to be available. There
864 // may also be slow operations pending that will blcok shutdown, so closing
865 // it here (which will block until required operations are complete) gives
866 // more head start for those operations to finish.
868 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:ThreadPool");
869 BrowserThreadImpl::ShutdownThreadPool();
872 #if !defined(OS_IOS)
873 // Must happen after the IO thread is shutdown since this may be accessed from
874 // it.
876 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUChannelFactory");
877 if (BrowserGpuChannelHostFactory::instance())
878 BrowserGpuChannelHostFactory::Terminate();
881 // Must happen after the I/O thread is shutdown since this class lives on the
882 // I/O thread and isn't threadsafe.
884 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GamepadService");
885 GamepadService::GetInstance()->Terminate();
888 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:SensorService");
889 DeviceInertialSensorService::GetInstance()->Shutdown();
892 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:BatteryStatusService");
893 BatteryStatusService::GetInstance()->Shutdown();
896 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DeleteDataSources");
897 URLDataManager::DeleteDataSources();
899 #endif // !defined(OS_IOS)
901 if (parts_) {
902 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:PostDestroyThreads");
903 parts_->PostDestroyThreads();
907 void BrowserMainLoop::StopStartupTracingTimer() {
908 startup_trace_timer_.Stop();
911 void BrowserMainLoop::InitializeMainThread() {
912 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeMainThread");
913 const char* kThreadName = "CrBrowserMain";
914 base::PlatformThread::SetName(kThreadName);
915 if (main_message_loop_)
916 main_message_loop_->set_thread_name(kThreadName);
918 // Register the main thread by instantiating it, but don't call any methods.
919 main_thread_.reset(
920 new BrowserThreadImpl(BrowserThread::UI, base::MessageLoop::current()));
923 int BrowserMainLoop::BrowserThreadsStarted() {
924 TRACE_EVENT0("startup", "BrowserMainLoop::BrowserThreadsStarted");
926 #if !defined(OS_IOS)
927 indexed_db_thread_.reset(new base::Thread("IndexedDB"));
928 indexed_db_thread_->Start();
929 #endif
931 #if defined(OS_ANDROID)
932 // Up the priority of anything that touches with display tasks
933 // (this thread is UI thread, and io_thread_ is for IPCs).
934 io_thread_->SetPriority(base::kThreadPriority_Display);
935 base::PlatformThread::SetThreadPriority(
936 base::PlatformThread::CurrentHandle(),
937 base::kThreadPriority_Display);
938 #endif
940 #if !defined(OS_IOS)
941 HistogramSynchronizer::GetInstance();
943 bool initialize_gpu_data_manager = true;
944 #if defined(OS_ANDROID)
945 // On Android, GLSurface::InitializeOneOff() must be called before initalizing
946 // the GpuDataManagerImpl as it uses the GL bindings. crbug.com/326295
947 if (!gfx::GLSurface::InitializeOneOff()) {
948 LOG(ERROR) << "GLSurface::InitializeOneOff failed";
949 initialize_gpu_data_manager = false;
951 #endif
953 // Initialize the GpuDataManager before we set up the MessageLoops because
954 // otherwise we'll trigger the assertion about doing IO on the UI thread.
955 if (initialize_gpu_data_manager)
956 GpuDataManagerImpl::GetInstance()->Initialize();
958 bool always_uses_gpu = true;
959 bool established_gpu_channel = false;
960 #if defined(USE_AURA) || defined(OS_MACOSX)
961 if (ShouldInitializeBrowserGpuChannelAndTransportSurface()) {
962 established_gpu_channel = true;
963 if (!GpuDataManagerImpl::GetInstance()->CanUseGpuBrowserCompositor()) {
964 established_gpu_channel = always_uses_gpu = false;
966 BrowserGpuChannelHostFactory::Initialize(established_gpu_channel);
967 ImageTransportFactory::Initialize();
968 #if defined(USE_AURA)
969 if (aura::Env::GetInstance()) {
970 aura::Env::GetInstance()->set_context_factory(
971 content::GetContextFactory());
973 #endif
975 #elif defined(OS_ANDROID)
976 established_gpu_channel = true;
977 BrowserGpuChannelHostFactory::Initialize(established_gpu_channel);
978 #endif
980 #if defined(OS_LINUX) && defined(USE_UDEV)
981 device_monitor_linux_.reset(new DeviceMonitorLinux());
982 #elif defined(OS_MACOSX)
983 device_monitor_mac_.reset(new DeviceMonitorMac());
984 #endif
986 // RDH needs the IO thread to be created
988 TRACE_EVENT0("startup",
989 "BrowserMainLoop::BrowserThreadsStarted:InitResourceDispatcherHost");
990 resource_dispatcher_host_.reset(new ResourceDispatcherHostImpl());
993 // MediaStreamManager needs the IO thread to be created.
995 TRACE_EVENT0("startup",
996 "BrowserMainLoop::BrowserThreadsStarted:InitMediaStreamManager");
997 media_stream_manager_.reset(new MediaStreamManager(audio_manager_.get()));
1001 TRACE_EVENT0("startup",
1002 "BrowserMainLoop::BrowserThreadsStarted:InitSpeechRecognition");
1003 speech_recognition_manager_.reset(new SpeechRecognitionManagerImpl(
1004 audio_manager_.get(), media_stream_manager_.get()));
1008 TRACE_EVENT0(
1009 "startup",
1010 "BrowserMainLoop::BrowserThreadsStarted::InitUserInputMonitor");
1011 user_input_monitor_ = media::UserInputMonitor::Create(
1012 io_thread_->message_loop_proxy(), main_thread_->message_loop_proxy());
1016 TRACE_EVENT0("startup",
1017 "BrowserMainLoop::BrowserThreadsStarted::TimeZoneMonitor");
1018 time_zone_monitor_ = TimeZoneMonitor::Create();
1021 // Alert the clipboard class to which threads are allowed to access the
1022 // clipboard:
1023 std::vector<base::PlatformThreadId> allowed_clipboard_threads;
1024 // The current thread is the UI thread.
1025 allowed_clipboard_threads.push_back(base::PlatformThread::CurrentId());
1026 #if defined(OS_WIN)
1027 // On Windows, clipboards are also used on the File or IO threads.
1028 allowed_clipboard_threads.push_back(file_thread_->thread_id());
1029 allowed_clipboard_threads.push_back(io_thread_->thread_id());
1030 #endif
1031 ui::Clipboard::SetAllowedThreads(allowed_clipboard_threads);
1033 // When running the GPU thread in-process, avoid optimistically starting it
1034 // since creating the GPU thread races against creation of the one-and-only
1035 // ChildProcess instance which is created by the renderer thread.
1036 if (GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL) &&
1037 !established_gpu_channel &&
1038 always_uses_gpu &&
1039 !parsed_command_line_.HasSwitch(switches::kSingleProcess) &&
1040 !parsed_command_line_.HasSwitch(switches::kInProcessGPU)) {
1041 TRACE_EVENT_INSTANT0("gpu", "Post task to launch GPU process",
1042 TRACE_EVENT_SCOPE_THREAD);
1043 BrowserThread::PostTask(
1044 BrowserThread::IO, FROM_HERE, base::Bind(
1045 base::IgnoreResult(&GpuProcessHost::Get),
1046 GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED,
1047 CAUSE_FOR_GPU_LAUNCH_BROWSER_STARTUP));
1050 #if defined(OS_MACOSX)
1051 ThemeHelperMac::GetInstance();
1052 SystemHotkeyHelperMac::GetInstance()->DeferredLoadSystemHotkeys();
1053 if (ShouldEnableBootstrapSandbox()) {
1054 TRACE_EVENT0("startup",
1055 "BrowserMainLoop::BrowserThreadsStarted:BootstrapSandbox");
1056 CHECK(GetBootstrapSandbox());
1058 #endif // defined(OS_MACOSX)
1060 #endif // !defined(OS_IOS)
1062 return result_code_;
1065 bool BrowserMainLoop::InitializeToolkit() {
1066 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeToolkit");
1067 // TODO(evan): this function is rather subtle, due to the variety
1068 // of intersecting ifdefs we have. To keep it easy to follow, there
1069 // are no #else branches on any #ifs.
1070 // TODO(stevenjb): Move platform specific code into platform specific Parts
1071 // (Need to add InitializeToolkit stage to BrowserParts).
1072 // See also GTK setup in EarlyInitialization, above, and associated comments.
1074 #if defined(OS_WIN)
1075 // Init common control sex.
1076 INITCOMMONCONTROLSEX config;
1077 config.dwSize = sizeof(config);
1078 config.dwICC = ICC_WIN95_CLASSES;
1079 if (!InitCommonControlsEx(&config))
1080 PLOG(FATAL);
1081 #endif
1083 #if defined(USE_AURA)
1085 #if defined(USE_X11)
1086 if (!gfx::GetXDisplay())
1087 return false;
1088 #endif
1090 // Env creates the compositor. Aura widgets need the compositor to be created
1091 // before they can be initialized by the browser.
1092 aura::Env::CreateInstance(true);
1093 #endif // defined(USE_AURA)
1095 if (parts_)
1096 parts_->ToolkitInitialized();
1098 return true;
1101 void BrowserMainLoop::MainMessageLoopRun() {
1102 #if defined(OS_ANDROID)
1103 // Android's main message loop is the Java message loop.
1104 NOTREACHED();
1105 #else
1106 DCHECK(base::MessageLoopForUI::IsCurrent());
1107 if (parameters_.ui_task)
1108 base::MessageLoopForUI::current()->PostTask(FROM_HERE,
1109 *parameters_.ui_task);
1111 base::RunLoop run_loop;
1112 run_loop.Run();
1113 #endif
1116 base::FilePath BrowserMainLoop::GetStartupTraceFileName(
1117 const base::CommandLine& command_line) const {
1118 base::FilePath trace_file = command_line.GetSwitchValuePath(
1119 switches::kTraceStartupFile);
1120 // trace_file = "none" means that startup events will show up for the next
1121 // begin/end tracing (via about:tracing or AutomationProxy::BeginTracing/
1122 // EndTracing, for example).
1123 if (trace_file == base::FilePath().AppendASCII("none"))
1124 return trace_file;
1126 if (trace_file.empty()) {
1127 #if defined(OS_ANDROID)
1128 TracingControllerAndroid::GenerateTracingFilePath(&trace_file);
1129 #else
1130 // Default to saving the startup trace into the current dir.
1131 trace_file = base::FilePath().AppendASCII("chrometrace.log");
1132 #endif
1135 return trace_file;
1138 void BrowserMainLoop::InitStartupTracing(
1139 const base::CommandLine& command_line) {
1140 DCHECK(is_tracing_startup_);
1142 startup_trace_file_ = GetStartupTraceFileName(parsed_command_line_);
1144 std::string delay_str = command_line.GetSwitchValueASCII(
1145 switches::kTraceStartupDuration);
1146 int delay_secs = 5;
1147 if (!delay_str.empty() && !base::StringToInt(delay_str, &delay_secs)) {
1148 DLOG(WARNING) << "Could not parse --" << switches::kTraceStartupDuration
1149 << "=" << delay_str << " defaulting to 5 (secs)";
1150 delay_secs = 5;
1153 startup_trace_timer_.Start(FROM_HERE,
1154 base::TimeDelta::FromSeconds(delay_secs),
1155 this,
1156 &BrowserMainLoop::EndStartupTracing);
1159 void BrowserMainLoop::EndStartupTracing() {
1160 is_tracing_startup_ = false;
1161 TracingController::GetInstance()->DisableRecording(
1162 startup_trace_file_, base::Bind(&OnStoppedStartupTracing));
1165 } // namespace content