Blink roll 25b6bd3a7a131ffe68d809546ad1a20707915cdc:3a503f41ae42e5b79cfcd2ff10e65afde...
[chromium-blink-merge.git] / content / browser / browser_main_loop.cc
blob034b3f5a995b4b843ad9994968798486dd122840
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/logging.h"
11 #include "base/message_loop/message_loop.h"
12 #include "base/metrics/field_trial.h"
13 #include "base/metrics/histogram.h"
14 #include "base/pending_task.h"
15 #include "base/power_monitor/power_monitor.h"
16 #include "base/power_monitor/power_monitor_device_source.h"
17 #include "base/process/process_metrics.h"
18 #include "base/run_loop.h"
19 #include "base/strings/string_number_conversions.h"
20 #include "base/system_monitor/system_monitor.h"
21 #include "base/thread_task_runner_handle.h"
22 #include "base/threading/thread_restrictions.h"
23 #include "base/timer/hi_res_timer_manager.h"
24 #include "content/browser/browser_thread_impl.h"
25 #include "content/browser/device_sensors/device_inertial_sensor_service.h"
26 #include "content/browser/download/save_file_manager.h"
27 #include "content/browser/gamepad/gamepad_service.h"
28 #include "content/browser/gpu/browser_gpu_channel_host_factory.h"
29 #include "content/browser/gpu/compositor_util.h"
30 #include "content/browser/gpu/gpu_data_manager_impl.h"
31 #include "content/browser/gpu/gpu_process_host.h"
32 #include "content/browser/gpu/gpu_process_host_ui_shim.h"
33 #include "content/browser/histogram_synchronizer.h"
34 #include "content/browser/loader/resource_dispatcher_host_impl.h"
35 #include "content/browser/media/media_internals.h"
36 #include "content/browser/net/browser_online_state_observer.h"
37 #include "content/browser/renderer_host/media/media_stream_manager.h"
38 #include "content/browser/speech/speech_recognition_manager_impl.h"
39 #include "content/browser/startup_task_runner.h"
40 #include "content/browser/time_zone_monitor.h"
41 #include "content/browser/webui/content_web_ui_controller_factory.h"
42 #include "content/browser/webui/url_data_manager.h"
43 #include "content/public/browser/browser_main_parts.h"
44 #include "content/public/browser/browser_shutdown.h"
45 #include "content/public/browser/content_browser_client.h"
46 #include "content/public/browser/render_process_host.h"
47 #include "content/public/browser/tracing_controller.h"
48 #include "content/public/common/content_switches.h"
49 #include "content/public/common/main_function_params.h"
50 #include "content/public/common/result_codes.h"
51 #include "crypto/nss_util.h"
52 #include "device/battery/battery_status_service.h"
53 #include "media/audio/audio_manager.h"
54 #include "media/base/media.h"
55 #include "media/base/user_input_monitor.h"
56 #include "media/midi/midi_manager.h"
57 #include "net/base/network_change_notifier.h"
58 #include "net/socket/client_socket_factory.h"
59 #include "net/ssl/ssl_config_service.h"
60 #include "ui/base/clipboard/clipboard.h"
62 #if defined(USE_AURA) || (defined(OS_MACOSX) && !defined(OS_IOS))
63 #include "content/browser/compositor/image_transport_factory.h"
64 #endif
66 #if defined(USE_AURA)
67 #include "content/public/browser/context_factory.h"
68 #include "ui/aura/env.h"
69 #endif
71 #if !defined(OS_IOS)
72 #include "content/browser/renderer_host/render_process_host_impl.h"
73 #endif
75 #if defined(OS_ANDROID)
76 #include "base/android/jni_android.h"
77 #include "content/browser/android/browser_startup_controller.h"
78 #include "content/browser/android/browser_surface_texture_manager.h"
79 #include "content/browser/android/tracing_controller_android.h"
80 #include "content/browser/screen_orientation/screen_orientation_delegate_android.h"
81 #include "content/public/browser/screen_orientation_provider.h"
82 #include "ui/gl/gl_surface.h"
83 #endif
85 #if defined(OS_MACOSX) && !defined(OS_IOS)
86 #include "content/browser/bootstrap_sandbox_mac.h"
87 #include "content/browser/cocoa/system_hotkey_helper_mac.h"
88 #include "content/browser/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(ENABLE_PLUGINS)
119 #include "content/browser/plugin_service_impl.h"
120 #endif
122 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
123 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
124 #endif
126 #if defined(USE_X11)
127 #include "ui/gfx/x/x11_connection.h"
128 #include "ui/gfx/x/x11_types.h"
129 #endif
131 // One of the linux specific headers defines this as a macro.
132 #ifdef DestroyAll
133 #undef DestroyAll
134 #endif
136 namespace content {
137 namespace {
139 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
140 void SetupSandbox(const base::CommandLine& parsed_command_line) {
141 TRACE_EVENT0("startup", "SetupSandbox");
142 base::FilePath sandbox_binary;
144 scoped_ptr<sandbox::SetuidSandboxClient> setuid_sandbox_client(
145 sandbox::SetuidSandboxClient::Create());
147 const bool want_setuid_sandbox =
148 !parsed_command_line.HasSwitch(switches::kNoSandbox) &&
149 !parsed_command_line.HasSwitch(switches::kDisableSetuidSandbox) &&
150 !setuid_sandbox_client->IsDisabledViaEnvironment();
152 static const char no_suid_error[] =
153 "Running without the SUID sandbox! See "
154 "https://code.google.com/p/chromium/wiki/LinuxSUIDSandboxDevelopment "
155 "for more information on developing with the sandbox on.";
156 if (want_setuid_sandbox) {
157 sandbox_binary = setuid_sandbox_client->GetSandboxBinaryPath();
158 if (sandbox_binary.empty()) {
159 // This needs to be fatal. Talk to security@chromium.org if you feel
160 // otherwise.
161 LOG(FATAL) << no_suid_error;
163 } else {
164 LOG(ERROR) << no_suid_error;
167 // Tickle the sandbox host and zygote host so they fork now.
168 RenderSandboxHostLinux::GetInstance()->Init();
169 ZygoteHostImpl::GetInstance()->Init(sandbox_binary.value());
171 #endif
173 #if defined(USE_GLIB)
174 static void GLibLogHandler(const gchar* log_domain,
175 GLogLevelFlags log_level,
176 const gchar* message,
177 gpointer userdata) {
178 if (!log_domain)
179 log_domain = "<unknown>";
180 if (!message)
181 message = "<no message>";
183 if (strstr(message, "Unable to retrieve the file info for")) {
184 LOG(ERROR) << "GTK File code error: " << message;
185 } else if (strstr(message, "Could not find the icon") &&
186 strstr(log_domain, "Gtk")) {
187 LOG(ERROR) << "GTK icon error: " << message;
188 } else if (strstr(message, "Theme file for default has no") ||
189 strstr(message, "Theme directory") ||
190 strstr(message, "theme pixmap") ||
191 strstr(message, "locate theme engine")) {
192 LOG(ERROR) << "GTK theme error: " << message;
193 } else if (strstr(message, "Unable to create Ubuntu Menu Proxy") &&
194 strstr(log_domain, "<unknown>")) {
195 LOG(ERROR) << "GTK menu proxy create failed";
196 } else if (strstr(message, "Out of memory") &&
197 strstr(log_domain, "<unknown>")) {
198 LOG(ERROR) << "DBus call timeout or out of memory: "
199 << "http://crosbug.com/15496";
200 } else if (strstr(message, "Could not connect: Connection refused") &&
201 strstr(log_domain, "<unknown>")) {
202 LOG(ERROR) << "DConf settings backend could not connect to session bus: "
203 << "http://crbug.com/179797";
204 } else if (strstr(message, "Attempting to store changes into") ||
205 strstr(message, "Attempting to set the permissions of")) {
206 LOG(ERROR) << message << " (http://bugs.chromium.org/161366)";
207 } else if (strstr(message, "drawable is not a native X11 window")) {
208 LOG(ERROR) << message << " (http://bugs.chromium.org/329991)";
209 } else {
210 LOG(DFATAL) << log_domain << ": " << message;
214 static void SetUpGLibLogHandler() {
215 // Register GLib-handled assertions to go through our logging system.
216 const char* kLogDomains[] = { NULL, "Gtk", "Gdk", "GLib", "GLib-GObject" };
217 for (size_t i = 0; i < arraysize(kLogDomains); i++) {
218 g_log_set_handler(kLogDomains[i],
219 static_cast<GLogLevelFlags>(G_LOG_FLAG_RECURSION |
220 G_LOG_FLAG_FATAL |
221 G_LOG_LEVEL_ERROR |
222 G_LOG_LEVEL_CRITICAL |
223 G_LOG_LEVEL_WARNING),
224 GLibLogHandler,
225 NULL);
228 #endif
230 void OnStoppedStartupTracing(const base::FilePath& trace_file) {
231 VLOG(0) << "Completed startup tracing to " << trace_file.value();
234 // Disable optimizations for this block of functions so the compiler doesn't
235 // merge them all together. This makes it possible to tell what thread was
236 // unresponsive by inspecting the callstack.
237 MSVC_DISABLE_OPTIMIZE()
238 MSVC_PUSH_DISABLE_WARNING(4748)
240 NOINLINE void ResetThread_DB(scoped_ptr<BrowserProcessSubThread> thread) {
241 thread.reset();
244 NOINLINE void ResetThread_FILE(scoped_ptr<BrowserProcessSubThread> thread) {
245 thread.reset();
248 NOINLINE void ResetThread_FILE_USER_BLOCKING(
249 scoped_ptr<BrowserProcessSubThread> thread) {
250 thread.reset();
253 NOINLINE void ResetThread_PROCESS_LAUNCHER(
254 scoped_ptr<BrowserProcessSubThread> thread) {
255 thread.reset();
258 NOINLINE void ResetThread_CACHE(scoped_ptr<BrowserProcessSubThread> thread) {
259 thread.reset();
262 NOINLINE void ResetThread_IO(scoped_ptr<BrowserProcessSubThread> thread) {
263 thread.reset();
266 #if !defined(OS_IOS)
267 NOINLINE void ResetThread_IndexedDb(scoped_ptr<base::Thread> thread) {
268 thread.reset();
270 #endif
272 MSVC_POP_WARNING()
273 MSVC_ENABLE_OPTIMIZE();
275 } // namespace
277 // The currently-running BrowserMainLoop. There can be one or zero.
278 BrowserMainLoop* g_current_browser_main_loop = NULL;
280 // This is just to be able to keep ShutdownThreadsAndCleanUp out of
281 // the public interface of BrowserMainLoop.
282 class BrowserShutdownImpl {
283 public:
284 static void ImmediateShutdownAndExitProcess() {
285 DCHECK(g_current_browser_main_loop);
286 g_current_browser_main_loop->ShutdownThreadsAndCleanUp();
288 #if defined(OS_WIN)
289 // At this point the message loop is still running yet we've shut everything
290 // down. If any messages are processed we'll likely crash. Exit now.
291 ExitProcess(RESULT_CODE_NORMAL_EXIT);
292 #elif defined(OS_POSIX) && !defined(OS_MACOSX)
293 _exit(RESULT_CODE_NORMAL_EXIT);
294 #else
295 NOTIMPLEMENTED();
296 #endif
300 void ImmediateShutdownAndExitProcess() {
301 BrowserShutdownImpl::ImmediateShutdownAndExitProcess();
304 // For measuring memory usage after each task. Behind a command line flag.
305 class BrowserMainLoop::MemoryObserver : public base::MessageLoop::TaskObserver {
306 public:
307 MemoryObserver() {}
308 ~MemoryObserver() override {}
310 void WillProcessTask(const base::PendingTask& pending_task) override {}
312 void DidProcessTask(const base::PendingTask& pending_task) override {
313 #if !defined(OS_IOS) // No ProcessMetrics on IOS.
314 scoped_ptr<base::ProcessMetrics> process_metrics(
315 base::ProcessMetrics::CreateProcessMetrics(
316 #if defined(OS_MACOSX)
317 base::GetCurrentProcessHandle(), NULL));
318 #else
319 base::GetCurrentProcessHandle()));
320 #endif
321 size_t private_bytes;
322 process_metrics->GetMemoryBytes(&private_bytes, NULL);
323 LOCAL_HISTOGRAM_MEMORY_KB("Memory.BrowserUsed", private_bytes >> 10);
324 #endif
326 private:
327 DISALLOW_COPY_AND_ASSIGN(MemoryObserver);
331 // BrowserMainLoop construction / destruction =============================
333 BrowserMainLoop* BrowserMainLoop::GetInstance() {
334 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
335 return g_current_browser_main_loop;
338 BrowserMainLoop::BrowserMainLoop(const MainFunctionParams& parameters)
339 : parameters_(parameters),
340 parsed_command_line_(parameters.command_line),
341 result_code_(RESULT_CODE_NORMAL_EXIT),
342 created_threads_(false),
343 // ContentMainRunner should have enabled tracing of the browser process
344 // when kTraceStartup is in the command line.
345 is_tracing_startup_(
346 parameters.command_line.HasSwitch(switches::kTraceStartup)) {
347 DCHECK(!g_current_browser_main_loop);
348 g_current_browser_main_loop = this;
351 BrowserMainLoop::~BrowserMainLoop() {
352 DCHECK_EQ(this, g_current_browser_main_loop);
353 #if !defined(OS_IOS)
354 ui::Clipboard::DestroyClipboardForCurrentThread();
355 #endif // !defined(OS_IOS)
356 g_current_browser_main_loop = NULL;
359 void BrowserMainLoop::Init() {
360 TRACE_EVENT0("startup", "BrowserMainLoop::Init");
361 parts_.reset(
362 GetContentClient()->browser()->CreateBrowserMainParts(parameters_));
365 // BrowserMainLoop stages ==================================================
367 void BrowserMainLoop::EarlyInitialization() {
368 TRACE_EVENT0("startup", "BrowserMainLoop::EarlyInitialization");
370 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
371 // No thread should be created before this call, as SetupSandbox()
372 // will end-up using fork().
373 SetupSandbox(parsed_command_line_);
374 #endif
376 #if defined(USE_X11)
377 if (parsed_command_line_.HasSwitch(switches::kSingleProcess) ||
378 parsed_command_line_.HasSwitch(switches::kInProcessGPU)) {
379 if (!gfx::InitializeThreadedX11()) {
380 LOG(ERROR) << "Failed to put Xlib into threaded mode.";
383 #endif
385 // GLib's spawning of new processes is buggy, so it's important that at this
386 // point GLib does not need to start DBUS. Chrome should always start with
387 // DBUS_SESSION_BUS_ADDRESS properly set. See crbug.com/309093.
388 #if defined(USE_GLIB)
389 // g_type_init will be deprecated in 2.36. 2.35 is the development
390 // version for 2.36, hence do not call g_type_init starting 2.35.
391 // http://developer.gnome.org/gobject/unstable/gobject-Type-Information.html#g-type-init
392 #if !GLIB_CHECK_VERSION(2, 35, 0)
393 // GLib type system initialization. Needed at least for gconf,
394 // used in net/proxy/proxy_config_service_linux.cc. Most likely
395 // this is superfluous as gtk_init() ought to do this. It's
396 // definitely harmless, so retained as a reminder of this
397 // requirement for gconf.
398 g_type_init();
399 #endif
401 SetUpGLibLogHandler();
402 #endif
404 if (parts_)
405 parts_->PreEarlyInitialization();
407 #if defined(OS_MACOSX)
408 // We use quite a few file descriptors for our IPC, and the default limit on
409 // the Mac is low (256), so bump it up.
410 base::SetFdLimit(1024);
411 #endif
413 #if defined(OS_WIN)
414 net::EnsureWinsockInit();
415 #endif
417 #if !defined(USE_OPENSSL)
418 // We want to be sure to init NSPR on the main thread.
419 crypto::EnsureNSPRInit();
420 #endif // !defined(USE_OPENSSL)
422 #if !defined(OS_IOS)
423 if (parsed_command_line_.HasSwitch(switches::kRendererProcessLimit)) {
424 std::string limit_string = parsed_command_line_.GetSwitchValueASCII(
425 switches::kRendererProcessLimit);
426 size_t process_limit;
427 if (base::StringToSizeT(limit_string, &process_limit)) {
428 RenderProcessHost::SetMaxRendererProcessCount(process_limit);
431 #endif // !defined(OS_IOS)
433 if (parts_)
434 parts_->PostEarlyInitialization();
437 void BrowserMainLoop::MainMessageLoopStart() {
438 TRACE_EVENT0("startup", "BrowserMainLoop::MainMessageLoopStart");
439 if (parts_) {
440 TRACE_EVENT0("startup",
441 "BrowserMainLoop::MainMessageLoopStart:PreMainMessageLoopStart");
442 parts_->PreMainMessageLoopStart();
445 #if defined(OS_WIN)
446 // If we're running tests (ui_task is non-null), then the ResourceBundle
447 // has already been initialized.
448 if (!parameters_.ui_task) {
449 // Override the configured locale with the user's preferred UI language.
450 l10n_util::OverrideLocaleWithUILanguageList();
452 #endif
454 // Create a MessageLoop if one does not already exist for the current thread.
455 if (!base::MessageLoop::current())
456 main_message_loop_.reset(new base::MessageLoopForUI);
458 InitializeMainThread();
461 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SystemMonitor");
462 system_monitor_.reset(new base::SystemMonitor);
465 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:PowerMonitor");
466 scoped_ptr<base::PowerMonitorSource> power_monitor_source(
467 new base::PowerMonitorDeviceSource());
468 power_monitor_.reset(new base::PowerMonitor(power_monitor_source.Pass()));
471 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:HighResTimerManager");
472 hi_res_timer_manager_.reset(new base::HighResolutionTimerManager);
475 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:NetworkChangeNotifier");
476 network_change_notifier_.reset(net::NetworkChangeNotifier::Create());
479 #if !defined(OS_IOS)
481 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MediaFeatures");
482 media::InitializeCPUSpecificMediaFeatures();
485 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:AudioMan");
486 audio_manager_.reset(media::AudioManager::Create(
487 MediaInternals::GetInstance()));
490 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MidiManager");
491 midi_manager_.reset(media::MidiManager::Create());
494 TRACE_EVENT0("startup",
495 "BrowserMainLoop::Subsystem:ContentWebUIController");
496 WebUIControllerFactory::RegisterFactory(
497 ContentWebUIControllerFactory::GetInstance());
501 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:OnlineStateObserver");
502 online_state_observer_.reset(new BrowserOnlineStateObserver);
506 system_stats_monitor_.reset(new base::debug::TraceEventSystemStatsMonitor(
507 base::ThreadTaskRunnerHandle::Get()));
509 #endif // !defined(OS_IOS)
511 #if defined(OS_WIN)
512 system_message_window_.reset(new SystemMessageWindowWin);
513 #endif
515 if (parts_)
516 parts_->PostMainMessageLoopStart();
518 #if !defined(OS_IOS)
519 // Start tracing to a file if needed. Only do this after starting the main
520 // message loop to avoid calling MessagePumpForUI::ScheduleWork() before
521 // MessagePumpForUI::Start() as it will crash the browser.
522 if (is_tracing_startup_) {
523 TRACE_EVENT0("startup", "BrowserMainLoop::InitStartupTracing");
524 InitStartupTracing(parsed_command_line_);
526 #endif // !defined(OS_IOS)
528 #if defined(OS_ANDROID)
530 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SurfaceTextureManager");
531 SurfaceTextureManager::InitInstance(new BrowserSurfaceTextureManager);
535 TRACE_EVENT0("startup",
536 "BrowserMainLoop::Subsystem:ScreenOrientationProvider");
537 screen_orientation_delegate_.reset(
538 new ScreenOrientationDelegateAndroid());
539 ScreenOrientationProvider::SetDelegate(screen_orientation_delegate_.get());
541 #endif
543 if (parsed_command_line_.HasSwitch(switches::kMemoryMetrics)) {
544 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MemoryObserver");
545 memory_observer_.reset(new MemoryObserver());
546 base::MessageLoop::current()->AddTaskObserver(memory_observer_.get());
549 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
550 trace_memory_controller_.reset(new base::debug::TraceMemoryController(
551 base::MessageLoop::current()->message_loop_proxy(),
552 ::HeapProfilerWithPseudoStackStart,
553 ::HeapProfilerStop,
554 ::GetHeapProfile));
555 #endif
558 int BrowserMainLoop::PreCreateThreads() {
559 if (parts_) {
560 TRACE_EVENT0("startup",
561 "BrowserMainLoop::CreateThreads:PreCreateThreads");
562 result_code_ = parts_->PreCreateThreads();
565 #if defined(ENABLE_PLUGINS)
566 // Prior to any processing happening on the io thread, we create the
567 // plugin service as it is predominantly used from the io thread,
568 // but must be created on the main thread. The service ctor is
569 // inexpensive and does not invoke the io_thread() accessor.
571 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads:PluginService");
572 PluginService::GetInstance()->Init();
574 #endif
576 #if !defined(OS_IOS) && (!defined(GOOGLE_CHROME_BUILD) || defined(OS_ANDROID))
577 // Single-process is an unsupported and not fully tested mode, so
578 // don't enable it for official Chrome builds (except on Android).
579 if (parsed_command_line_.HasSwitch(switches::kSingleProcess))
580 RenderProcessHost::SetRunRendererInProcess(true);
581 #endif
582 return result_code_;
585 void BrowserMainLoop::CreateStartupTasks() {
586 TRACE_EVENT0("startup", "BrowserMainLoop::CreateStartupTasks");
588 // First time through, we really want to create all the tasks
589 if (!startup_task_runner_.get()) {
590 #if defined(OS_ANDROID)
591 startup_task_runner_ = make_scoped_ptr(new StartupTaskRunner(
592 base::Bind(&BrowserStartupComplete),
593 base::MessageLoop::current()->message_loop_proxy()));
594 #else
595 startup_task_runner_ = make_scoped_ptr(new StartupTaskRunner(
596 base::Callback<void(int)>(),
597 base::MessageLoop::current()->message_loop_proxy()));
598 #endif
599 StartupTask pre_create_threads =
600 base::Bind(&BrowserMainLoop::PreCreateThreads, base::Unretained(this));
601 startup_task_runner_->AddTask(pre_create_threads);
603 StartupTask create_threads =
604 base::Bind(&BrowserMainLoop::CreateThreads, base::Unretained(this));
605 startup_task_runner_->AddTask(create_threads);
607 StartupTask browser_thread_started = base::Bind(
608 &BrowserMainLoop::BrowserThreadsStarted, base::Unretained(this));
609 startup_task_runner_->AddTask(browser_thread_started);
611 StartupTask pre_main_message_loop_run = base::Bind(
612 &BrowserMainLoop::PreMainMessageLoopRun, base::Unretained(this));
613 startup_task_runner_->AddTask(pre_main_message_loop_run);
615 #if defined(OS_ANDROID)
616 if (BrowserMayStartAsynchronously()) {
617 startup_task_runner_->StartRunningTasksAsync();
619 #endif
621 #if defined(OS_ANDROID)
622 if (!BrowserMayStartAsynchronously()) {
623 // A second request for asynchronous startup can be ignored, so
624 // StartupRunningTasksAsync is only called first time through. If, however,
625 // this is a request for synchronous startup then it must override any
626 // previous call for async startup, so we call RunAllTasksNow()
627 // unconditionally.
628 startup_task_runner_->RunAllTasksNow();
630 #else
631 startup_task_runner_->RunAllTasksNow();
632 #endif
635 int BrowserMainLoop::CreateThreads() {
636 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads");
638 base::Thread::Options io_message_loop_options;
639 io_message_loop_options.message_loop_type = base::MessageLoop::TYPE_IO;
640 base::Thread::Options ui_message_loop_options;
641 ui_message_loop_options.message_loop_type = base::MessageLoop::TYPE_UI;
643 // Start threads in the order they occur in the BrowserThread::ID
644 // enumeration, except for BrowserThread::UI which is the main
645 // thread.
647 // Must be size_t so we can increment it.
648 for (size_t thread_id = BrowserThread::UI + 1;
649 thread_id < BrowserThread::ID_COUNT;
650 ++thread_id) {
651 scoped_ptr<BrowserProcessSubThread>* thread_to_start = NULL;
652 base::Thread::Options options;
654 switch (thread_id) {
655 case BrowserThread::DB:
656 TRACE_EVENT_BEGIN1("startup",
657 "BrowserMainLoop::CreateThreads:start",
658 "Thread", "BrowserThread::DB");
659 thread_to_start = &db_thread_;
660 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
661 break;
662 case BrowserThread::FILE_USER_BLOCKING:
663 TRACE_EVENT_BEGIN1("startup",
664 "BrowserMainLoop::CreateThreads:start",
665 "Thread", "BrowserThread::FILE_USER_BLOCKING");
666 thread_to_start = &file_user_blocking_thread_;
667 break;
668 case BrowserThread::FILE:
669 TRACE_EVENT_BEGIN1("startup",
670 "BrowserMainLoop::CreateThreads:start",
671 "Thread", "BrowserThread::FILE");
672 thread_to_start = &file_thread_;
673 #if defined(OS_WIN)
674 // On Windows, the FILE thread needs to be have a UI message loop
675 // which pumps messages in such a way that Google Update can
676 // communicate back to us.
677 options = ui_message_loop_options;
678 #else
679 options = io_message_loop_options;
680 #endif
681 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
682 break;
683 case BrowserThread::PROCESS_LAUNCHER:
684 TRACE_EVENT_BEGIN1("startup",
685 "BrowserMainLoop::CreateThreads:start",
686 "Thread", "BrowserThread::PROCESS_LAUNCHER");
687 thread_to_start = &process_launcher_thread_;
688 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
689 break;
690 case BrowserThread::CACHE:
691 TRACE_EVENT_BEGIN1("startup",
692 "BrowserMainLoop::CreateThreads:start",
693 "Thread", "BrowserThread::CACHE");
694 thread_to_start = &cache_thread_;
695 options = io_message_loop_options;
696 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
697 break;
698 case BrowserThread::IO:
699 TRACE_EVENT_BEGIN1("startup",
700 "BrowserMainLoop::CreateThreads:start",
701 "Thread", "BrowserThread::IO");
702 thread_to_start = &io_thread_;
703 options = io_message_loop_options;
704 break;
705 case BrowserThread::UI:
706 case BrowserThread::ID_COUNT:
707 default:
708 NOTREACHED();
709 break;
712 BrowserThread::ID id = static_cast<BrowserThread::ID>(thread_id);
714 if (thread_to_start) {
715 (*thread_to_start).reset(new BrowserProcessSubThread(id));
716 if (!(*thread_to_start)->StartWithOptions(options)) {
717 LOG(FATAL) << "Failed to start the browser thread: id == " << id;
719 } else {
720 NOTREACHED();
723 TRACE_EVENT_END0("startup", "BrowserMainLoop::CreateThreads:start");
725 created_threads_ = true;
726 return result_code_;
729 int BrowserMainLoop::PreMainMessageLoopRun() {
730 if (parts_) {
731 TRACE_EVENT0("startup",
732 "BrowserMainLoop::CreateThreads:PreMainMessageLoopRun");
733 parts_->PreMainMessageLoopRun();
736 // If the UI thread blocks, the whole UI is unresponsive.
737 // Do not allow disk IO from the UI thread.
738 base::ThreadRestrictions::SetIOAllowed(false);
739 base::ThreadRestrictions::DisallowWaiting();
740 return result_code_;
743 void BrowserMainLoop::RunMainMessageLoopParts() {
744 TRACE_EVENT_BEGIN_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
746 bool ran_main_loop = false;
747 if (parts_)
748 ran_main_loop = parts_->MainMessageLoopRun(&result_code_);
750 if (!ran_main_loop)
751 MainMessageLoopRun();
753 TRACE_EVENT_END_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
756 void BrowserMainLoop::ShutdownThreadsAndCleanUp() {
757 if (!created_threads_) {
758 // Called early, nothing to do
759 return;
761 TRACE_EVENT0("shutdown", "BrowserMainLoop::ShutdownThreadsAndCleanUp");
763 // Teardown may start in PostMainMessageLoopRun, and during teardown we
764 // need to be able to perform IO.
765 base::ThreadRestrictions::SetIOAllowed(true);
766 BrowserThread::PostTask(
767 BrowserThread::IO, FROM_HERE,
768 base::Bind(base::IgnoreResult(&base::ThreadRestrictions::SetIOAllowed),
769 true));
771 #if !defined(OS_IOS)
772 if (RenderProcessHost::run_renderer_in_process())
773 RenderProcessHostImpl::ShutDownInProcessRenderer();
774 #endif
776 if (parts_) {
777 TRACE_EVENT0("shutdown",
778 "BrowserMainLoop::Subsystem:PostMainMessageLoopRun");
779 parts_->PostMainMessageLoopRun();
782 trace_memory_controller_.reset();
783 system_stats_monitor_.reset();
785 #if !defined(OS_IOS)
786 // Destroying the GpuProcessHostUIShims on the UI thread posts a task to
787 // delete related objects on the GPU thread. This must be done before
788 // stopping the GPU thread. The GPU thread will close IPC channels to renderer
789 // processes so this has to happen before stopping the IO thread.
791 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUProcessHostShim");
792 GpuProcessHostUIShim::DestroyAll();
794 // Cancel pending requests and prevent new requests.
795 if (resource_dispatcher_host_) {
796 TRACE_EVENT0("shutdown",
797 "BrowserMainLoop::Subsystem:ResourceDispatcherHost");
798 resource_dispatcher_host_.get()->Shutdown();
801 #if defined(USE_AURA) || defined(OS_MACOSX)
803 TRACE_EVENT0("shutdown",
804 "BrowserMainLoop::Subsystem:ImageTransportFactory");
805 ImageTransportFactory::Terminate();
807 #endif
809 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
810 ZygoteHostImpl::GetInstance()->TearDownAfterLastChild();
811 #endif // defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
813 // The device monitors are using |system_monitor_| as dependency, so delete
814 // them before |system_monitor_| goes away.
815 // On Mac and windows, the monitor needs to be destroyed on the same thread
816 // as they were created. On Linux, the monitor will be deleted when IO thread
817 // goes away.
818 #if defined(OS_WIN)
819 system_message_window_.reset();
820 #elif defined(OS_MACOSX)
821 device_monitor_mac_.reset();
822 #endif
823 #endif // !defined(OS_IOS)
825 // Must be size_t so we can subtract from it.
826 for (size_t thread_id = BrowserThread::ID_COUNT - 1;
827 thread_id >= (BrowserThread::UI + 1);
828 --thread_id) {
829 // Find the thread object we want to stop. Looping over all valid
830 // BrowserThread IDs and DCHECKing on a missing case in the switch
831 // statement helps avoid a mismatch between this code and the
832 // BrowserThread::ID enumeration.
834 // The destruction order is the reverse order of occurrence in the
835 // BrowserThread::ID list. The rationale for the order is as
836 // follows (need to be filled in a bit):
839 // - The IO thread is the only user of the CACHE thread.
841 // - The PROCESS_LAUNCHER thread must be stopped after IO in case
842 // the IO thread posted a task to terminate a process on the
843 // process launcher thread.
845 // - (Not sure why DB stops last.)
846 switch (thread_id) {
847 case BrowserThread::DB: {
848 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DBThread");
849 ResetThread_DB(db_thread_.Pass());
850 break;
852 case BrowserThread::FILE: {
853 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:FileThread");
854 #if !defined(OS_IOS)
855 // Clean up state that lives on or uses the file_thread_ before
856 // it goes away.
857 if (resource_dispatcher_host_)
858 resource_dispatcher_host_.get()->save_file_manager()->Shutdown();
859 #endif // !defined(OS_IOS)
860 ResetThread_FILE(file_thread_.Pass());
861 break;
863 case BrowserThread::FILE_USER_BLOCKING: {
864 TRACE_EVENT0("shutdown",
865 "BrowserMainLoop::Subsystem:FileUserBlockingThread");
866 ResetThread_FILE_USER_BLOCKING(file_user_blocking_thread_.Pass());
867 break;
869 case BrowserThread::PROCESS_LAUNCHER: {
870 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:LauncherThread");
871 ResetThread_PROCESS_LAUNCHER(process_launcher_thread_.Pass());
872 break;
874 case BrowserThread::CACHE: {
875 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:CacheThread");
876 ResetThread_CACHE(cache_thread_.Pass());
877 break;
879 case BrowserThread::IO: {
880 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IOThread");
881 ResetThread_IO(io_thread_.Pass());
882 break;
884 case BrowserThread::UI:
885 case BrowserThread::ID_COUNT:
886 default:
887 NOTREACHED();
888 break;
892 #if !defined(OS_IOS)
894 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IndexedDBThread");
895 ResetThread_IndexedDb(indexed_db_thread_.Pass());
897 #endif
899 // Close the blocking I/O pool after the other threads. Other threads such
900 // as the I/O thread may need to schedule work like closing files or flushing
901 // data during shutdown, so the blocking pool needs to be available. There
902 // may also be slow operations pending that will blcok shutdown, so closing
903 // it here (which will block until required operations are complete) gives
904 // more head start for those operations to finish.
906 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:ThreadPool");
907 BrowserThreadImpl::ShutdownThreadPool();
910 #if !defined(OS_IOS)
911 // Must happen after the IO thread is shutdown since this may be accessed from
912 // it.
914 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUChannelFactory");
915 if (BrowserGpuChannelHostFactory::instance())
916 BrowserGpuChannelHostFactory::Terminate();
919 // Must happen after the I/O thread is shutdown since this class lives on the
920 // I/O thread and isn't threadsafe.
922 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GamepadService");
923 GamepadService::GetInstance()->Terminate();
926 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:SensorService");
927 DeviceInertialSensorService::GetInstance()->Shutdown();
930 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:BatteryStatusService");
931 device::BatteryStatusService::GetInstance()->Shutdown();
934 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DeleteDataSources");
935 URLDataManager::DeleteDataSources();
937 #endif // !defined(OS_IOS)
939 if (parts_) {
940 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:PostDestroyThreads");
941 parts_->PostDestroyThreads();
945 void BrowserMainLoop::StopStartupTracingTimer() {
946 startup_trace_timer_.Stop();
949 void BrowserMainLoop::InitializeMainThread() {
950 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeMainThread");
951 const char* kThreadName = "CrBrowserMain";
952 base::PlatformThread::SetName(kThreadName);
953 if (main_message_loop_)
954 main_message_loop_->set_thread_name(kThreadName);
956 // Register the main thread by instantiating it, but don't call any methods.
957 main_thread_.reset(
958 new BrowserThreadImpl(BrowserThread::UI, base::MessageLoop::current()));
961 int BrowserMainLoop::BrowserThreadsStarted() {
962 TRACE_EVENT0("startup", "BrowserMainLoop::BrowserThreadsStarted");
964 #if !defined(OS_IOS)
965 indexed_db_thread_.reset(new base::Thread("IndexedDB"));
966 indexed_db_thread_->Start();
967 #endif
969 #if defined(OS_ANDROID)
970 // Up the priority of anything that touches with display tasks
971 // (this thread is UI thread, and io_thread_ is for IPCs).
972 io_thread_->SetPriority(base::kThreadPriority_Display);
973 base::PlatformThread::SetThreadPriority(
974 base::PlatformThread::CurrentHandle(),
975 base::kThreadPriority_Display);
976 #endif
978 #if !defined(OS_IOS)
979 HistogramSynchronizer::GetInstance();
981 bool initialize_gpu_data_manager = true;
982 #if defined(OS_ANDROID)
983 // On Android, GLSurface::InitializeOneOff() must be called before initalizing
984 // the GpuDataManagerImpl as it uses the GL bindings. crbug.com/326295
985 if (!gfx::GLSurface::InitializeOneOff()) {
986 LOG(ERROR) << "GLSurface::InitializeOneOff failed";
987 initialize_gpu_data_manager = false;
989 #endif
991 // Initialize the GpuDataManager before we set up the MessageLoops because
992 // otherwise we'll trigger the assertion about doing IO on the UI thread.
993 if (initialize_gpu_data_manager)
994 GpuDataManagerImpl::GetInstance()->Initialize();
996 bool always_uses_gpu = true;
997 bool established_gpu_channel = false;
998 #if defined(USE_AURA) || defined(OS_MACOSX)
999 established_gpu_channel = true;
1000 if (!GpuDataManagerImpl::GetInstance()->CanUseGpuBrowserCompositor()) {
1001 established_gpu_channel = always_uses_gpu = false;
1003 BrowserGpuChannelHostFactory::Initialize(established_gpu_channel);
1004 ImageTransportFactory::Initialize();
1005 #if defined(USE_AURA)
1006 if (aura::Env::GetInstance()) {
1007 aura::Env::GetInstance()->set_context_factory(GetContextFactory());
1009 #endif
1010 #elif defined(OS_ANDROID)
1011 established_gpu_channel = true;
1012 BrowserGpuChannelHostFactory::Initialize(established_gpu_channel);
1013 #endif
1015 #if defined(OS_LINUX) && defined(USE_UDEV)
1016 device_monitor_linux_.reset(new DeviceMonitorLinux());
1017 #elif defined(OS_MACOSX)
1018 device_monitor_mac_.reset(new DeviceMonitorMac());
1019 #endif
1021 // RDH needs the IO thread to be created
1023 TRACE_EVENT0("startup",
1024 "BrowserMainLoop::BrowserThreadsStarted:InitResourceDispatcherHost");
1025 resource_dispatcher_host_.reset(new ResourceDispatcherHostImpl());
1028 // MediaStreamManager needs the IO thread to be created.
1030 TRACE_EVENT0("startup",
1031 "BrowserMainLoop::BrowserThreadsStarted:InitMediaStreamManager");
1032 media_stream_manager_.reset(new MediaStreamManager(audio_manager_.get()));
1036 TRACE_EVENT0("startup",
1037 "BrowserMainLoop::BrowserThreadsStarted:InitSpeechRecognition");
1038 speech_recognition_manager_.reset(new SpeechRecognitionManagerImpl(
1039 audio_manager_.get(), media_stream_manager_.get()));
1043 TRACE_EVENT0(
1044 "startup",
1045 "BrowserMainLoop::BrowserThreadsStarted::InitUserInputMonitor");
1046 user_input_monitor_ = media::UserInputMonitor::Create(
1047 io_thread_->message_loop_proxy(), main_thread_->message_loop_proxy());
1051 TRACE_EVENT0("startup",
1052 "BrowserMainLoop::BrowserThreadsStarted::TimeZoneMonitor");
1053 time_zone_monitor_ = TimeZoneMonitor::Create();
1056 // Alert the clipboard class to which threads are allowed to access the
1057 // clipboard:
1058 std::vector<base::PlatformThreadId> allowed_clipboard_threads;
1059 // The current thread is the UI thread.
1060 allowed_clipboard_threads.push_back(base::PlatformThread::CurrentId());
1061 #if defined(OS_WIN)
1062 // On Windows, clipboards are also used on the File or IO threads.
1063 allowed_clipboard_threads.push_back(file_thread_->thread_id());
1064 allowed_clipboard_threads.push_back(io_thread_->thread_id());
1065 #endif
1066 ui::Clipboard::SetAllowedThreads(allowed_clipboard_threads);
1068 // When running the GPU thread in-process, avoid optimistically starting it
1069 // since creating the GPU thread races against creation of the one-and-only
1070 // ChildProcess instance which is created by the renderer thread.
1071 if (GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL) &&
1072 !established_gpu_channel &&
1073 always_uses_gpu &&
1074 !parsed_command_line_.HasSwitch(switches::kSingleProcess) &&
1075 !parsed_command_line_.HasSwitch(switches::kInProcessGPU)) {
1076 TRACE_EVENT_INSTANT0("gpu", "Post task to launch GPU process",
1077 TRACE_EVENT_SCOPE_THREAD);
1078 BrowserThread::PostTask(
1079 BrowserThread::IO, FROM_HERE, base::Bind(
1080 base::IgnoreResult(&GpuProcessHost::Get),
1081 GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED,
1082 CAUSE_FOR_GPU_LAUNCH_BROWSER_STARTUP));
1085 #if defined(OS_MACOSX)
1086 ThemeHelperMac::GetInstance();
1087 SystemHotkeyHelperMac::GetInstance()->DeferredLoadSystemHotkeys();
1088 if (ShouldEnableBootstrapSandbox()) {
1089 TRACE_EVENT0("startup",
1090 "BrowserMainLoop::BrowserThreadsStarted:BootstrapSandbox");
1091 CHECK(GetBootstrapSandbox());
1093 #endif // defined(OS_MACOSX)
1095 #endif // !defined(OS_IOS)
1097 return result_code_;
1100 bool BrowserMainLoop::InitializeToolkit() {
1101 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeToolkit");
1102 // TODO(evan): this function is rather subtle, due to the variety
1103 // of intersecting ifdefs we have. To keep it easy to follow, there
1104 // are no #else branches on any #ifs.
1105 // TODO(stevenjb): Move platform specific code into platform specific Parts
1106 // (Need to add InitializeToolkit stage to BrowserParts).
1107 // See also GTK setup in EarlyInitialization, above, and associated comments.
1109 #if defined(OS_WIN)
1110 // Init common control sex.
1111 INITCOMMONCONTROLSEX config;
1112 config.dwSize = sizeof(config);
1113 config.dwICC = ICC_WIN95_CLASSES;
1114 if (!InitCommonControlsEx(&config))
1115 PLOG(FATAL);
1116 #endif
1118 #if defined(USE_AURA)
1120 #if defined(USE_X11)
1121 if (!gfx::GetXDisplay())
1122 return false;
1123 #endif
1125 // Env creates the compositor. Aura widgets need the compositor to be created
1126 // before they can be initialized by the browser.
1127 aura::Env::CreateInstance(true);
1128 #endif // defined(USE_AURA)
1130 if (parts_)
1131 parts_->ToolkitInitialized();
1133 return true;
1136 void BrowserMainLoop::MainMessageLoopRun() {
1137 #if defined(OS_ANDROID)
1138 // Android's main message loop is the Java message loop.
1139 NOTREACHED();
1140 #else
1141 DCHECK(base::MessageLoopForUI::IsCurrent());
1142 if (parameters_.ui_task)
1143 base::MessageLoopForUI::current()->PostTask(FROM_HERE,
1144 *parameters_.ui_task);
1146 base::RunLoop run_loop;
1147 run_loop.Run();
1148 #endif
1151 base::FilePath BrowserMainLoop::GetStartupTraceFileName(
1152 const base::CommandLine& command_line) const {
1153 base::FilePath trace_file = command_line.GetSwitchValuePath(
1154 switches::kTraceStartupFile);
1155 // trace_file = "none" means that startup events will show up for the next
1156 // begin/end tracing (via about:tracing or AutomationProxy::BeginTracing/
1157 // EndTracing, for example).
1158 if (trace_file == base::FilePath().AppendASCII("none"))
1159 return trace_file;
1161 if (trace_file.empty()) {
1162 #if defined(OS_ANDROID)
1163 TracingControllerAndroid::GenerateTracingFilePath(&trace_file);
1164 #else
1165 // Default to saving the startup trace into the current dir.
1166 trace_file = base::FilePath().AppendASCII("chrometrace.log");
1167 #endif
1170 return trace_file;
1173 void BrowserMainLoop::InitStartupTracing(
1174 const base::CommandLine& command_line) {
1175 DCHECK(is_tracing_startup_);
1177 startup_trace_file_ = GetStartupTraceFileName(parsed_command_line_);
1179 std::string delay_str = command_line.GetSwitchValueASCII(
1180 switches::kTraceStartupDuration);
1181 int delay_secs = 5;
1182 if (!delay_str.empty() && !base::StringToInt(delay_str, &delay_secs)) {
1183 DLOG(WARNING) << "Could not parse --" << switches::kTraceStartupDuration
1184 << "=" << delay_str << " defaulting to 5 (secs)";
1185 delay_secs = 5;
1188 startup_trace_timer_.Start(FROM_HERE,
1189 base::TimeDelta::FromSeconds(delay_secs),
1190 this,
1191 &BrowserMainLoop::EndStartupTracing);
1194 void BrowserMainLoop::EndStartupTracing() {
1195 is_tracing_startup_ = false;
1196 TracingController::GetInstance()->DisableRecording(
1197 TracingController::CreateFileSink(
1198 startup_trace_file_,
1199 base::Bind(OnStoppedStartupTracing, startup_trace_file_)));
1202 } // namespace content