Rename Animate as Begin(Main)Frame
[chromium-blink-merge.git] / content / browser / browser_main_loop.cc
blobd2a642ca653af5188696820240568b8adbc60400
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 // Disable optimizations for this block of functions so the compiler doesn't
243 // merge them all together. This makes it possible to tell what thread was
244 // unresponsive by inspecting the callstack.
245 MSVC_DISABLE_OPTIMIZE()
246 MSVC_PUSH_DISABLE_WARNING(4748)
248 NOINLINE void ResetThread_DB(scoped_ptr<BrowserProcessSubThread> thread) {
249 thread.reset();
252 NOINLINE void ResetThread_FILE(scoped_ptr<BrowserProcessSubThread> thread) {
253 thread.reset();
256 NOINLINE void ResetThread_FILE_USER_BLOCKING(
257 scoped_ptr<BrowserProcessSubThread> thread) {
258 thread.reset();
261 NOINLINE void ResetThread_PROCESS_LAUNCHER(
262 scoped_ptr<BrowserProcessSubThread> thread) {
263 thread.reset();
266 NOINLINE void ResetThread_CACHE(scoped_ptr<BrowserProcessSubThread> thread) {
267 thread.reset();
270 NOINLINE void ResetThread_IO(scoped_ptr<BrowserProcessSubThread> thread) {
271 thread.reset();
274 #if !defined(OS_IOS)
275 NOINLINE void ResetThread_IndexedDb(scoped_ptr<base::Thread> thread) {
276 thread.reset();
278 #endif
280 MSVC_POP_WARNING()
281 MSVC_ENABLE_OPTIMIZE();
283 } // namespace
285 // The currently-running BrowserMainLoop. There can be one or zero.
286 BrowserMainLoop* g_current_browser_main_loop = NULL;
288 // This is just to be able to keep ShutdownThreadsAndCleanUp out of
289 // the public interface of BrowserMainLoop.
290 class BrowserShutdownImpl {
291 public:
292 static void ImmediateShutdownAndExitProcess() {
293 DCHECK(g_current_browser_main_loop);
294 g_current_browser_main_loop->ShutdownThreadsAndCleanUp();
296 #if defined(OS_WIN)
297 // At this point the message loop is still running yet we've shut everything
298 // down. If any messages are processed we'll likely crash. Exit now.
299 ExitProcess(RESULT_CODE_NORMAL_EXIT);
300 #elif defined(OS_POSIX) && !defined(OS_MACOSX)
301 _exit(RESULT_CODE_NORMAL_EXIT);
302 #else
303 NOTIMPLEMENTED();
304 #endif
308 void ImmediateShutdownAndExitProcess() {
309 BrowserShutdownImpl::ImmediateShutdownAndExitProcess();
312 // For measuring memory usage after each task. Behind a command line flag.
313 class BrowserMainLoop::MemoryObserver : public base::MessageLoop::TaskObserver {
314 public:
315 MemoryObserver() {}
316 virtual ~MemoryObserver() {}
318 virtual void WillProcessTask(const base::PendingTask& pending_task) OVERRIDE {
321 virtual void DidProcessTask(const base::PendingTask& pending_task) OVERRIDE {
322 #if !defined(OS_IOS) // No ProcessMetrics on IOS.
323 scoped_ptr<base::ProcessMetrics> process_metrics(
324 base::ProcessMetrics::CreateProcessMetrics(
325 #if defined(OS_MACOSX)
326 base::GetCurrentProcessHandle(), NULL));
327 #else
328 base::GetCurrentProcessHandle()));
329 #endif
330 size_t private_bytes;
331 process_metrics->GetMemoryBytes(&private_bytes, NULL);
332 HISTOGRAM_MEMORY_KB("Memory.BrowserUsed", private_bytes >> 10);
333 #endif
335 private:
336 DISALLOW_COPY_AND_ASSIGN(MemoryObserver);
340 // BrowserMainLoop construction / destruction =============================
342 BrowserMainLoop* BrowserMainLoop::GetInstance() {
343 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
344 return g_current_browser_main_loop;
347 BrowserMainLoop::BrowserMainLoop(const MainFunctionParams& parameters)
348 : parameters_(parameters),
349 parsed_command_line_(parameters.command_line),
350 result_code_(RESULT_CODE_NORMAL_EXIT),
351 created_threads_(false),
352 // ContentMainRunner should have enabled tracing of the browser process
353 // when kTraceStartup is in the command line.
354 is_tracing_startup_(
355 parameters.command_line.HasSwitch(switches::kTraceStartup)) {
356 DCHECK(!g_current_browser_main_loop);
357 g_current_browser_main_loop = this;
360 BrowserMainLoop::~BrowserMainLoop() {
361 DCHECK_EQ(this, g_current_browser_main_loop);
362 #if !defined(OS_IOS)
363 ui::Clipboard::DestroyClipboardForCurrentThread();
364 #endif // !defined(OS_IOS)
365 g_current_browser_main_loop = NULL;
368 void BrowserMainLoop::Init() {
369 TRACE_EVENT0("startup", "BrowserMainLoop::Init");
370 parts_.reset(
371 GetContentClient()->browser()->CreateBrowserMainParts(parameters_));
374 // BrowserMainLoop stages ==================================================
376 void BrowserMainLoop::EarlyInitialization() {
377 TRACE_EVENT0("startup", "BrowserMainLoop::EarlyInitialization");
379 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
380 // No thread should be created before this call, as SetupSandbox()
381 // will end-up using fork().
382 SetupSandbox(parsed_command_line_);
383 #endif
385 #if defined(USE_X11)
386 if (parsed_command_line_.HasSwitch(switches::kSingleProcess) ||
387 parsed_command_line_.HasSwitch(switches::kInProcessGPU)) {
388 if (!gfx::InitializeThreadedX11()) {
389 LOG(ERROR) << "Failed to put Xlib into threaded mode.";
392 #endif
394 // GLib's spawning of new processes is buggy, so it's important that at this
395 // point GLib does not need to start DBUS. Chrome should always start with
396 // DBUS_SESSION_BUS_ADDRESS properly set. See crbug.com/309093.
397 #if defined(USE_GLIB)
398 // g_type_init will be deprecated in 2.36. 2.35 is the development
399 // version for 2.36, hence do not call g_type_init starting 2.35.
400 // http://developer.gnome.org/gobject/unstable/gobject-Type-Information.html#g-type-init
401 #if !GLIB_CHECK_VERSION(2, 35, 0)
402 // GLib type system initialization. Needed at least for gconf,
403 // used in net/proxy/proxy_config_service_linux.cc. Most likely
404 // this is superfluous as gtk_init() ought to do this. It's
405 // definitely harmless, so retained as a reminder of this
406 // requirement for gconf.
407 g_type_init();
408 #endif
410 SetUpGLibLogHandler();
411 #endif
413 if (parts_)
414 parts_->PreEarlyInitialization();
416 #if defined(OS_MACOSX)
417 // We use quite a few file descriptors for our IPC, and the default limit on
418 // the Mac is low (256), so bump it up.
419 base::SetFdLimit(1024);
420 #endif
422 #if defined(OS_WIN)
423 net::EnsureWinsockInit();
424 #endif
426 #if !defined(USE_OPENSSL)
427 // We want to be sure to init NSPR on the main thread.
428 crypto::EnsureNSPRInit();
429 #endif // !defined(USE_OPENSSL)
431 #if !defined(OS_IOS)
432 if (parsed_command_line_.HasSwitch(switches::kRendererProcessLimit)) {
433 std::string limit_string = parsed_command_line_.GetSwitchValueASCII(
434 switches::kRendererProcessLimit);
435 size_t process_limit;
436 if (base::StringToSizeT(limit_string, &process_limit)) {
437 RenderProcessHost::SetMaxRendererProcessCount(process_limit);
440 #endif // !defined(OS_IOS)
442 if (parts_)
443 parts_->PostEarlyInitialization();
446 void BrowserMainLoop::MainMessageLoopStart() {
447 TRACE_EVENT0("startup", "BrowserMainLoop::MainMessageLoopStart");
448 if (parts_) {
449 TRACE_EVENT0("startup",
450 "BrowserMainLoop::MainMessageLoopStart:PreMainMessageLoopStart");
451 parts_->PreMainMessageLoopStart();
454 #if defined(OS_WIN)
455 // If we're running tests (ui_task is non-null), then the ResourceBundle
456 // has already been initialized.
457 if (!parameters_.ui_task) {
458 // Override the configured locale with the user's preferred UI language.
459 l10n_util::OverrideLocaleWithUILanguageList();
461 #endif
463 // Create a MessageLoop if one does not already exist for the current thread.
464 if (!base::MessageLoop::current())
465 main_message_loop_.reset(new base::MessageLoopForUI);
467 InitializeMainThread();
470 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SystemMonitor");
471 system_monitor_.reset(new base::SystemMonitor);
474 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:PowerMonitor");
475 scoped_ptr<base::PowerMonitorSource> power_monitor_source(
476 new base::PowerMonitorDeviceSource());
477 power_monitor_.reset(new base::PowerMonitor(power_monitor_source.Pass()));
480 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:HighResTimerManager");
481 hi_res_timer_manager_.reset(new base::HighResolutionTimerManager);
484 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:NetworkChangeNotifier");
485 network_change_notifier_.reset(net::NetworkChangeNotifier::Create());
488 #if !defined(OS_IOS)
490 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MediaFeatures");
491 media::InitializeCPUSpecificMediaFeatures();
494 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:AudioMan");
495 audio_manager_.reset(media::AudioManager::Create(
496 MediaInternals::GetInstance()));
499 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MidiManager");
500 midi_manager_.reset(media::MidiManager::Create());
503 TRACE_EVENT0("startup",
504 "BrowserMainLoop::Subsystem:ContentWebUIController");
505 WebUIControllerFactory::RegisterFactory(
506 ContentWebUIControllerFactory::GetInstance());
510 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:AudioMirroringManager");
511 audio_mirroring_manager_.reset(new AudioMirroringManager());
514 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:OnlineStateObserver");
515 online_state_observer_.reset(new BrowserOnlineStateObserver);
519 system_stats_monitor_.reset(new base::debug::TraceEventSystemStatsMonitor(
520 base::ThreadTaskRunnerHandle::Get()));
522 #endif // !defined(OS_IOS)
524 #if defined(OS_WIN)
525 system_message_window_.reset(new SystemMessageWindowWin);
526 #endif
528 if (parts_)
529 parts_->PostMainMessageLoopStart();
531 #if !defined(OS_IOS)
532 // Start tracing to a file if needed. Only do this after starting the main
533 // message loop to avoid calling MessagePumpForUI::ScheduleWork() before
534 // MessagePumpForUI::Start() as it will crash the browser.
535 if (is_tracing_startup_) {
536 TRACE_EVENT0("startup", "BrowserMainLoop::InitStartupTracing");
537 InitStartupTracing(parsed_command_line_);
539 #endif // !defined(OS_IOS)
541 #if defined(OS_ANDROID)
543 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SurfaceTexturePeer");
544 SurfaceTexturePeer::InitInstance(new SurfaceTexturePeerBrowserImpl());
546 #endif
548 if (parsed_command_line_.HasSwitch(switches::kMemoryMetrics)) {
549 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MemoryObserver");
550 memory_observer_.reset(new MemoryObserver());
551 base::MessageLoop::current()->AddTaskObserver(memory_observer_.get());
554 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
555 trace_memory_controller_.reset(new base::debug::TraceMemoryController(
556 base::MessageLoop::current()->message_loop_proxy(),
557 ::HeapProfilerWithPseudoStackStart,
558 ::HeapProfilerStop,
559 ::GetHeapProfile));
560 #endif
563 int BrowserMainLoop::PreCreateThreads() {
564 if (parts_) {
565 TRACE_EVENT0("startup",
566 "BrowserMainLoop::CreateThreads:PreCreateThreads");
567 result_code_ = parts_->PreCreateThreads();
570 #if defined(ENABLE_PLUGINS)
571 // Prior to any processing happening on the io thread, we create the
572 // plugin service as it is predominantly used from the io thread,
573 // but must be created on the main thread. The service ctor is
574 // inexpensive and does not invoke the io_thread() accessor.
576 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads:PluginService");
577 PluginService::GetInstance()->Init();
579 #endif
581 #if !defined(OS_IOS) && (!defined(GOOGLE_CHROME_BUILD) || defined(OS_ANDROID))
582 // Single-process is an unsupported and not fully tested mode, so
583 // don't enable it for official Chrome builds (except on Android).
584 if (parsed_command_line_.HasSwitch(switches::kSingleProcess))
585 RenderProcessHost::SetRunRendererInProcess(true);
586 #endif
587 return result_code_;
590 void BrowserMainLoop::CreateStartupTasks() {
591 TRACE_EVENT0("startup", "BrowserMainLoop::CreateStartupTasks");
593 // First time through, we really want to create all the tasks
594 if (!startup_task_runner_.get()) {
595 #if defined(OS_ANDROID)
596 startup_task_runner_ = make_scoped_ptr(new StartupTaskRunner(
597 base::Bind(&BrowserStartupComplete),
598 base::MessageLoop::current()->message_loop_proxy()));
599 #else
600 startup_task_runner_ = make_scoped_ptr(new StartupTaskRunner(
601 base::Callback<void(int)>(),
602 base::MessageLoop::current()->message_loop_proxy()));
603 #endif
604 StartupTask pre_create_threads =
605 base::Bind(&BrowserMainLoop::PreCreateThreads, base::Unretained(this));
606 startup_task_runner_->AddTask(pre_create_threads);
608 StartupTask create_threads =
609 base::Bind(&BrowserMainLoop::CreateThreads, base::Unretained(this));
610 startup_task_runner_->AddTask(create_threads);
612 StartupTask browser_thread_started = base::Bind(
613 &BrowserMainLoop::BrowserThreadsStarted, base::Unretained(this));
614 startup_task_runner_->AddTask(browser_thread_started);
616 StartupTask pre_main_message_loop_run = base::Bind(
617 &BrowserMainLoop::PreMainMessageLoopRun, base::Unretained(this));
618 startup_task_runner_->AddTask(pre_main_message_loop_run);
620 #if defined(OS_ANDROID)
621 if (BrowserMayStartAsynchronously()) {
622 startup_task_runner_->StartRunningTasksAsync();
624 #endif
626 #if defined(OS_ANDROID)
627 if (!BrowserMayStartAsynchronously()) {
628 // A second request for asynchronous startup can be ignored, so
629 // StartupRunningTasksAsync is only called first time through. If, however,
630 // this is a request for synchronous startup then it must override any
631 // previous call for async startup, so we call RunAllTasksNow()
632 // unconditionally.
633 startup_task_runner_->RunAllTasksNow();
635 #else
636 startup_task_runner_->RunAllTasksNow();
637 #endif
640 int BrowserMainLoop::CreateThreads() {
641 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads");
643 base::Thread::Options io_message_loop_options;
644 io_message_loop_options.message_loop_type = base::MessageLoop::TYPE_IO;
645 base::Thread::Options ui_message_loop_options;
646 ui_message_loop_options.message_loop_type = base::MessageLoop::TYPE_UI;
648 // Start threads in the order they occur in the BrowserThread::ID
649 // enumeration, except for BrowserThread::UI which is the main
650 // thread.
652 // Must be size_t so we can increment it.
653 for (size_t thread_id = BrowserThread::UI + 1;
654 thread_id < BrowserThread::ID_COUNT;
655 ++thread_id) {
656 scoped_ptr<BrowserProcessSubThread>* thread_to_start = NULL;
657 base::Thread::Options options;
659 switch (thread_id) {
660 case BrowserThread::DB:
661 TRACE_EVENT_BEGIN1("startup",
662 "BrowserMainLoop::CreateThreads:start",
663 "Thread", "BrowserThread::DB");
664 thread_to_start = &db_thread_;
665 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
666 break;
667 case BrowserThread::FILE_USER_BLOCKING:
668 TRACE_EVENT_BEGIN1("startup",
669 "BrowserMainLoop::CreateThreads:start",
670 "Thread", "BrowserThread::FILE_USER_BLOCKING");
671 thread_to_start = &file_user_blocking_thread_;
672 break;
673 case BrowserThread::FILE:
674 TRACE_EVENT_BEGIN1("startup",
675 "BrowserMainLoop::CreateThreads:start",
676 "Thread", "BrowserThread::FILE");
677 thread_to_start = &file_thread_;
678 #if defined(OS_WIN)
679 // On Windows, the FILE thread needs to be have a UI message loop
680 // which pumps messages in such a way that Google Update can
681 // communicate back to us.
682 options = ui_message_loop_options;
683 #else
684 options = io_message_loop_options;
685 #endif
686 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
687 break;
688 case BrowserThread::PROCESS_LAUNCHER:
689 TRACE_EVENT_BEGIN1("startup",
690 "BrowserMainLoop::CreateThreads:start",
691 "Thread", "BrowserThread::PROCESS_LAUNCHER");
692 thread_to_start = &process_launcher_thread_;
693 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
694 break;
695 case BrowserThread::CACHE:
696 TRACE_EVENT_BEGIN1("startup",
697 "BrowserMainLoop::CreateThreads:start",
698 "Thread", "BrowserThread::CACHE");
699 thread_to_start = &cache_thread_;
700 options = io_message_loop_options;
701 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
702 break;
703 case BrowserThread::IO:
704 TRACE_EVENT_BEGIN1("startup",
705 "BrowserMainLoop::CreateThreads:start",
706 "Thread", "BrowserThread::IO");
707 thread_to_start = &io_thread_;
708 options = io_message_loop_options;
709 break;
710 case BrowserThread::UI:
711 case BrowserThread::ID_COUNT:
712 default:
713 NOTREACHED();
714 break;
717 BrowserThread::ID id = static_cast<BrowserThread::ID>(thread_id);
719 if (thread_to_start) {
720 (*thread_to_start).reset(new BrowserProcessSubThread(id));
721 (*thread_to_start)->StartWithOptions(options);
722 } else {
723 NOTREACHED();
726 TRACE_EVENT_END0("startup", "BrowserMainLoop::CreateThreads:start");
728 created_threads_ = true;
729 return result_code_;
732 int BrowserMainLoop::PreMainMessageLoopRun() {
733 if (parts_) {
734 TRACE_EVENT0("startup",
735 "BrowserMainLoop::CreateThreads:PreMainMessageLoopRun");
736 parts_->PreMainMessageLoopRun();
739 // If the UI thread blocks, the whole UI is unresponsive.
740 // Do not allow disk IO from the UI thread.
741 base::ThreadRestrictions::SetIOAllowed(false);
742 base::ThreadRestrictions::DisallowWaiting();
743 return result_code_;
746 void BrowserMainLoop::RunMainMessageLoopParts() {
747 TRACE_EVENT_BEGIN_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
749 bool ran_main_loop = false;
750 if (parts_)
751 ran_main_loop = parts_->MainMessageLoopRun(&result_code_);
753 if (!ran_main_loop)
754 MainMessageLoopRun();
756 TRACE_EVENT_END_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
759 void BrowserMainLoop::ShutdownThreadsAndCleanUp() {
760 if (!created_threads_) {
761 // Called early, nothing to do
762 return;
764 TRACE_EVENT0("shutdown", "BrowserMainLoop::ShutdownThreadsAndCleanUp");
766 // Teardown may start in PostMainMessageLoopRun, and during teardown we
767 // need to be able to perform IO.
768 base::ThreadRestrictions::SetIOAllowed(true);
769 BrowserThread::PostTask(
770 BrowserThread::IO, FROM_HERE,
771 base::Bind(base::IgnoreResult(&base::ThreadRestrictions::SetIOAllowed),
772 true));
774 #if !defined(OS_IOS)
775 if (RenderProcessHost::run_renderer_in_process())
776 RenderProcessHostImpl::ShutDownInProcessRenderer();
777 #endif
779 if (parts_) {
780 TRACE_EVENT0("shutdown",
781 "BrowserMainLoop::Subsystem:PostMainMessageLoopRun");
782 parts_->PostMainMessageLoopRun();
785 trace_memory_controller_.reset();
786 system_stats_monitor_.reset();
788 #if !defined(OS_IOS)
789 // Destroying the GpuProcessHostUIShims on the UI thread posts a task to
790 // delete related objects on the GPU thread. This must be done before
791 // stopping the GPU thread. The GPU thread will close IPC channels to renderer
792 // processes so this has to happen before stopping the IO thread.
794 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUProcessHostShim");
795 GpuProcessHostUIShim::DestroyAll();
797 // Cancel pending requests and prevent new requests.
798 if (resource_dispatcher_host_) {
799 TRACE_EVENT0("shutdown",
800 "BrowserMainLoop::Subsystem:ResourceDispatcherHost");
801 resource_dispatcher_host_.get()->Shutdown();
804 #if defined(USE_AURA) || defined(OS_MACOSX)
805 if (ShouldInitializeBrowserGpuChannelAndTransportSurface()) {
806 TRACE_EVENT0("shutdown",
807 "BrowserMainLoop::Subsystem:ImageTransportFactory");
808 ImageTransportFactory::Terminate();
810 #endif
812 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
813 ZygoteHostImpl::GetInstance()->TearDownAfterLastChild();
814 #endif // defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
816 // The device monitors are using |system_monitor_| as dependency, so delete
817 // them before |system_monitor_| goes away.
818 // On Mac and windows, the monitor needs to be destroyed on the same thread
819 // as they were created. On Linux, the monitor will be deleted when IO thread
820 // goes away.
821 #if defined(OS_WIN)
822 system_message_window_.reset();
823 #elif defined(OS_MACOSX)
824 device_monitor_mac_.reset();
825 #endif
826 #endif // !defined(OS_IOS)
828 // Must be size_t so we can subtract from it.
829 for (size_t thread_id = BrowserThread::ID_COUNT - 1;
830 thread_id >= (BrowserThread::UI + 1);
831 --thread_id) {
832 // Find the thread object we want to stop. Looping over all valid
833 // BrowserThread IDs and DCHECKing on a missing case in the switch
834 // statement helps avoid a mismatch between this code and the
835 // BrowserThread::ID enumeration.
837 // The destruction order is the reverse order of occurrence in the
838 // BrowserThread::ID list. The rationale for the order is as
839 // follows (need to be filled in a bit):
842 // - The IO thread is the only user of the CACHE thread.
844 // - The PROCESS_LAUNCHER thread must be stopped after IO in case
845 // the IO thread posted a task to terminate a process on the
846 // process launcher thread.
848 // - (Not sure why DB stops last.)
849 switch (thread_id) {
850 case BrowserThread::DB: {
851 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DBThread");
852 ResetThread_DB(db_thread_.Pass());
853 break;
855 case BrowserThread::FILE: {
856 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:FileThread");
857 #if !defined(OS_IOS)
858 // Clean up state that lives on or uses the file_thread_ before
859 // it goes away.
860 if (resource_dispatcher_host_)
861 resource_dispatcher_host_.get()->save_file_manager()->Shutdown();
862 #endif // !defined(OS_IOS)
863 ResetThread_FILE(file_thread_.Pass());
864 break;
866 case BrowserThread::FILE_USER_BLOCKING: {
867 TRACE_EVENT0("shutdown",
868 "BrowserMainLoop::Subsystem:FileUserBlockingThread");
869 ResetThread_FILE_USER_BLOCKING(file_user_blocking_thread_.Pass());
870 break;
872 case BrowserThread::PROCESS_LAUNCHER: {
873 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:LauncherThread");
874 ResetThread_PROCESS_LAUNCHER(process_launcher_thread_.Pass());
875 break;
877 case BrowserThread::CACHE: {
878 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:CacheThread");
879 ResetThread_CACHE(cache_thread_.Pass());
880 break;
882 case BrowserThread::IO: {
883 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IOThread");
884 ResetThread_IO(io_thread_.Pass());
885 break;
887 case BrowserThread::UI:
888 case BrowserThread::ID_COUNT:
889 default:
890 NOTREACHED();
891 break;
895 #if !defined(OS_IOS)
897 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IndexedDBThread");
898 ResetThread_IndexedDb(indexed_db_thread_.Pass());
900 #endif
902 // Close the blocking I/O pool after the other threads. Other threads such
903 // as the I/O thread may need to schedule work like closing files or flushing
904 // data during shutdown, so the blocking pool needs to be available. There
905 // may also be slow operations pending that will blcok shutdown, so closing
906 // it here (which will block until required operations are complete) gives
907 // more head start for those operations to finish.
909 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:ThreadPool");
910 BrowserThreadImpl::ShutdownThreadPool();
913 #if !defined(OS_IOS)
914 // Must happen after the IO thread is shutdown since this may be accessed from
915 // it.
917 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUChannelFactory");
918 if (BrowserGpuChannelHostFactory::instance())
919 BrowserGpuChannelHostFactory::Terminate();
922 // Must happen after the I/O thread is shutdown since this class lives on the
923 // I/O thread and isn't threadsafe.
925 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GamepadService");
926 GamepadService::GetInstance()->Terminate();
929 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:SensorService");
930 DeviceInertialSensorService::GetInstance()->Shutdown();
933 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:BatteryStatusService");
934 BatteryStatusService::GetInstance()->Shutdown();
937 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DeleteDataSources");
938 URLDataManager::DeleteDataSources();
940 #endif // !defined(OS_IOS)
942 if (parts_) {
943 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:PostDestroyThreads");
944 parts_->PostDestroyThreads();
948 void BrowserMainLoop::StopStartupTracingTimer() {
949 startup_trace_timer_.Stop();
952 void BrowserMainLoop::InitializeMainThread() {
953 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeMainThread");
954 const char* kThreadName = "CrBrowserMain";
955 base::PlatformThread::SetName(kThreadName);
956 if (main_message_loop_)
957 main_message_loop_->set_thread_name(kThreadName);
959 // Register the main thread by instantiating it, but don't call any methods.
960 main_thread_.reset(
961 new BrowserThreadImpl(BrowserThread::UI, base::MessageLoop::current()));
964 int BrowserMainLoop::BrowserThreadsStarted() {
965 TRACE_EVENT0("startup", "BrowserMainLoop::BrowserThreadsStarted");
967 #if !defined(OS_IOS)
968 indexed_db_thread_.reset(new base::Thread("IndexedDB"));
969 indexed_db_thread_->Start();
970 #endif
972 #if defined(OS_ANDROID)
973 // Up the priority of anything that touches with display tasks
974 // (this thread is UI thread, and io_thread_ is for IPCs).
975 io_thread_->SetPriority(base::kThreadPriority_Display);
976 base::PlatformThread::SetThreadPriority(
977 base::PlatformThread::CurrentHandle(),
978 base::kThreadPriority_Display);
979 #endif
981 #if !defined(OS_IOS)
982 HistogramSynchronizer::GetInstance();
984 bool initialize_gpu_data_manager = true;
985 #if defined(OS_ANDROID)
986 // On Android, GLSurface::InitializeOneOff() must be called before initalizing
987 // the GpuDataManagerImpl as it uses the GL bindings. crbug.com/326295
988 if (!gfx::GLSurface::InitializeOneOff()) {
989 LOG(ERROR) << "GLSurface::InitializeOneOff failed";
990 initialize_gpu_data_manager = false;
992 #endif
994 // Initialize the GpuDataManager before we set up the MessageLoops because
995 // otherwise we'll trigger the assertion about doing IO on the UI thread.
996 if (initialize_gpu_data_manager)
997 GpuDataManagerImpl::GetInstance()->Initialize();
999 bool always_uses_gpu = true;
1000 bool established_gpu_channel = false;
1001 #if defined(USE_AURA) || defined(OS_MACOSX)
1002 if (ShouldInitializeBrowserGpuChannelAndTransportSurface()) {
1003 established_gpu_channel = true;
1004 if (!GpuDataManagerImpl::GetInstance()->CanUseGpuBrowserCompositor()) {
1005 established_gpu_channel = always_uses_gpu = false;
1007 BrowserGpuChannelHostFactory::Initialize(established_gpu_channel);
1008 ImageTransportFactory::Initialize();
1009 #if defined(USE_AURA)
1010 if (aura::Env::GetInstance()) {
1011 aura::Env::GetInstance()->set_context_factory(
1012 content::GetContextFactory());
1014 #endif
1016 #elif defined(OS_ANDROID)
1017 established_gpu_channel = true;
1018 BrowserGpuChannelHostFactory::Initialize(established_gpu_channel);
1019 #endif
1021 #if defined(OS_LINUX) && defined(USE_UDEV)
1022 device_monitor_linux_.reset(new DeviceMonitorLinux());
1023 #elif defined(OS_MACOSX)
1024 device_monitor_mac_.reset(new DeviceMonitorMac());
1025 #endif
1027 // RDH needs the IO thread to be created
1029 TRACE_EVENT0("startup",
1030 "BrowserMainLoop::BrowserThreadsStarted:InitResourceDispatcherHost");
1031 resource_dispatcher_host_.reset(new ResourceDispatcherHostImpl());
1034 // MediaStreamManager needs the IO thread to be created.
1036 TRACE_EVENT0("startup",
1037 "BrowserMainLoop::BrowserThreadsStarted:InitMediaStreamManager");
1038 media_stream_manager_.reset(new MediaStreamManager(audio_manager_.get()));
1042 TRACE_EVENT0("startup",
1043 "BrowserMainLoop::BrowserThreadsStarted:InitSpeechRecognition");
1044 speech_recognition_manager_.reset(new SpeechRecognitionManagerImpl(
1045 audio_manager_.get(), media_stream_manager_.get()));
1049 TRACE_EVENT0(
1050 "startup",
1051 "BrowserMainLoop::BrowserThreadsStarted::InitUserInputMonitor");
1052 user_input_monitor_ = media::UserInputMonitor::Create(
1053 io_thread_->message_loop_proxy(), main_thread_->message_loop_proxy());
1057 TRACE_EVENT0("startup",
1058 "BrowserMainLoop::BrowserThreadsStarted::TimeZoneMonitor");
1059 time_zone_monitor_ = TimeZoneMonitor::Create();
1062 // Alert the clipboard class to which threads are allowed to access the
1063 // clipboard:
1064 std::vector<base::PlatformThreadId> allowed_clipboard_threads;
1065 // The current thread is the UI thread.
1066 allowed_clipboard_threads.push_back(base::PlatformThread::CurrentId());
1067 #if defined(OS_WIN)
1068 // On Windows, clipboards are also used on the File or IO threads.
1069 allowed_clipboard_threads.push_back(file_thread_->thread_id());
1070 allowed_clipboard_threads.push_back(io_thread_->thread_id());
1071 #endif
1072 ui::Clipboard::SetAllowedThreads(allowed_clipboard_threads);
1074 // When running the GPU thread in-process, avoid optimistically starting it
1075 // since creating the GPU thread races against creation of the one-and-only
1076 // ChildProcess instance which is created by the renderer thread.
1077 if (GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL) &&
1078 !established_gpu_channel &&
1079 always_uses_gpu &&
1080 !parsed_command_line_.HasSwitch(switches::kSingleProcess) &&
1081 !parsed_command_line_.HasSwitch(switches::kInProcessGPU)) {
1082 TRACE_EVENT_INSTANT0("gpu", "Post task to launch GPU process",
1083 TRACE_EVENT_SCOPE_THREAD);
1084 BrowserThread::PostTask(
1085 BrowserThread::IO, FROM_HERE, base::Bind(
1086 base::IgnoreResult(&GpuProcessHost::Get),
1087 GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED,
1088 CAUSE_FOR_GPU_LAUNCH_BROWSER_STARTUP));
1091 #if defined(OS_MACOSX)
1092 ThemeHelperMac::GetInstance();
1093 SystemHotkeyHelperMac::GetInstance()->DeferredLoadSystemHotkeys();
1094 if (ShouldEnableBootstrapSandbox()) {
1095 TRACE_EVENT0("startup",
1096 "BrowserMainLoop::BrowserThreadsStarted:BootstrapSandbox");
1097 CHECK(GetBootstrapSandbox());
1099 #endif // defined(OS_MACOSX)
1101 #endif // !defined(OS_IOS)
1103 return result_code_;
1106 bool BrowserMainLoop::InitializeToolkit() {
1107 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeToolkit");
1108 // TODO(evan): this function is rather subtle, due to the variety
1109 // of intersecting ifdefs we have. To keep it easy to follow, there
1110 // are no #else branches on any #ifs.
1111 // TODO(stevenjb): Move platform specific code into platform specific Parts
1112 // (Need to add InitializeToolkit stage to BrowserParts).
1113 // See also GTK setup in EarlyInitialization, above, and associated comments.
1115 #if defined(OS_WIN)
1116 // Init common control sex.
1117 INITCOMMONCONTROLSEX config;
1118 config.dwSize = sizeof(config);
1119 config.dwICC = ICC_WIN95_CLASSES;
1120 if (!InitCommonControlsEx(&config))
1121 PLOG(FATAL);
1122 #endif
1124 #if defined(USE_AURA)
1126 #if defined(USE_X11)
1127 if (!gfx::GetXDisplay())
1128 return false;
1129 #endif
1131 // Env creates the compositor. Aura widgets need the compositor to be created
1132 // before they can be initialized by the browser.
1133 aura::Env::CreateInstance(true);
1134 #endif // defined(USE_AURA)
1136 if (parts_)
1137 parts_->ToolkitInitialized();
1139 return true;
1142 void BrowserMainLoop::MainMessageLoopRun() {
1143 #if defined(OS_ANDROID)
1144 // Android's main message loop is the Java message loop.
1145 NOTREACHED();
1146 #else
1147 DCHECK(base::MessageLoopForUI::IsCurrent());
1148 if (parameters_.ui_task)
1149 base::MessageLoopForUI::current()->PostTask(FROM_HERE,
1150 *parameters_.ui_task);
1152 base::RunLoop run_loop;
1153 run_loop.Run();
1154 #endif
1157 base::FilePath BrowserMainLoop::GetStartupTraceFileName(
1158 const base::CommandLine& command_line) const {
1159 base::FilePath trace_file = command_line.GetSwitchValuePath(
1160 switches::kTraceStartupFile);
1161 // trace_file = "none" means that startup events will show up for the next
1162 // begin/end tracing (via about:tracing or AutomationProxy::BeginTracing/
1163 // EndTracing, for example).
1164 if (trace_file == base::FilePath().AppendASCII("none"))
1165 return trace_file;
1167 if (trace_file.empty()) {
1168 #if defined(OS_ANDROID)
1169 TracingControllerAndroid::GenerateTracingFilePath(&trace_file);
1170 #else
1171 // Default to saving the startup trace into the current dir.
1172 trace_file = base::FilePath().AppendASCII("chrometrace.log");
1173 #endif
1176 return trace_file;
1179 void BrowserMainLoop::InitStartupTracing(
1180 const base::CommandLine& command_line) {
1181 DCHECK(is_tracing_startup_);
1183 startup_trace_file_ = GetStartupTraceFileName(parsed_command_line_);
1185 std::string delay_str = command_line.GetSwitchValueASCII(
1186 switches::kTraceStartupDuration);
1187 int delay_secs = 5;
1188 if (!delay_str.empty() && !base::StringToInt(delay_str, &delay_secs)) {
1189 DLOG(WARNING) << "Could not parse --" << switches::kTraceStartupDuration
1190 << "=" << delay_str << " defaulting to 5 (secs)";
1191 delay_secs = 5;
1194 startup_trace_timer_.Start(FROM_HERE,
1195 base::TimeDelta::FromSeconds(delay_secs),
1196 this,
1197 &BrowserMainLoop::EndStartupTracing);
1200 void BrowserMainLoop::EndStartupTracing() {
1201 is_tracing_startup_ = false;
1202 TracingController::GetInstance()->DisableRecording(
1203 startup_trace_file_, base::Bind(&OnStoppedStartupTracing));
1206 } // namespace content