IndexedDBFactory now ForceCloses databases.
[chromium-blink-merge.git] / content / browser / browser_main_loop.cc
blob2e7ccef8ddd5961c0a1ddc21eac4c4ccec45c925
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/browser_thread_impl.h"
27 #include "content/browser/device_orientation/device_inertial_sensor_service.h"
28 #include "content/browser/download/save_file_manager.h"
29 #include "content/browser/gamepad/gamepad_service.h"
30 #include "content/browser/gpu/browser_gpu_channel_host_factory.h"
31 #include "content/browser/gpu/compositor_util.h"
32 #include "content/browser/gpu/gpu_data_manager_impl.h"
33 #include "content/browser/gpu/gpu_process_host.h"
34 #include "content/browser/gpu/gpu_process_host_ui_shim.h"
35 #include "content/browser/histogram_synchronizer.h"
36 #include "content/browser/loader/resource_dispatcher_host_impl.h"
37 #include "content/browser/media/media_internals.h"
38 #include "content/browser/net/browser_online_state_observer.h"
39 #include "content/browser/plugin_service_impl.h"
40 #include "content/browser/renderer_host/media/audio_mirroring_manager.h"
41 #include "content/browser/renderer_host/media/media_stream_manager.h"
42 #include "content/browser/renderer_host/render_process_host_impl.h"
43 #include "content/browser/speech/speech_recognition_manager_impl.h"
44 #include "content/browser/startup_task_runner.h"
45 #include "content/browser/webui/content_web_ui_controller_factory.h"
46 #include "content/browser/webui/url_data_manager.h"
47 #include "content/public/browser/browser_main_parts.h"
48 #include "content/public/browser/browser_shutdown.h"
49 #include "content/public/browser/content_browser_client.h"
50 #include "content/public/browser/render_process_host.h"
51 #include "content/public/browser/tracing_controller.h"
52 #include "content/public/common/content_switches.h"
53 #include "content/public/common/main_function_params.h"
54 #include "content/public/common/result_codes.h"
55 #include "crypto/nss_util.h"
56 #include "media/audio/audio_manager.h"
57 #include "media/base/media.h"
58 #include "media/base/user_input_monitor.h"
59 #include "media/midi/midi_manager.h"
60 #include "net/base/network_change_notifier.h"
61 #include "net/socket/client_socket_factory.h"
62 #include "net/ssl/ssl_config_service.h"
63 #include "ui/base/clipboard/clipboard.h"
65 #if defined(USE_AURA)
66 #include "content/browser/aura/image_transport_factory.h"
67 #endif
69 #if defined(OS_ANDROID)
70 #include "base/android/jni_android.h"
71 #include "content/browser/android/browser_startup_controller.h"
72 #include "content/browser/android/surface_texture_peer_browser_impl.h"
73 #endif
75 #if defined(OS_MACOSX)
76 #include "content/browser/theme_helper_mac.h"
77 #endif
79 #if defined(OS_WIN)
80 #include <windows.h>
81 #include <commctrl.h>
82 #include <shellapi.h>
84 #include "base/win/text_services_message_filter.h"
85 #include "content/browser/system_message_window_win.h"
86 #include "content/common/sandbox_win.h"
87 #include "net/base/winsock_init.h"
88 #include "ui/base/l10n/l10n_util_win.h"
89 #endif
91 #if defined(USE_GLIB)
92 #include <glib-object.h>
93 #endif
95 #if defined(OS_LINUX) && defined(USE_UDEV)
96 #include "content/browser/device_monitor_udev.h"
97 #elif defined(OS_MACOSX) && !defined(OS_IOS)
98 #include "content/browser/device_monitor_mac.h"
99 #endif
101 #if defined(TOOLKIT_GTK)
102 #include "ui/gfx/gtk_util.h"
103 #endif
105 #if defined(OS_POSIX) && !defined(OS_MACOSX)
106 #include <sys/stat.h>
108 #include "content/browser/renderer_host/render_sandbox_host_linux.h"
109 #include "content/browser/zygote_host/zygote_host_impl_linux.h"
110 #endif
112 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
113 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
114 #endif
116 #if defined(USE_X11)
117 #include <X11/Xlib.h>
118 #endif
120 // One of the linux specific headers defines this as a macro.
121 #ifdef DestroyAll
122 #undef DestroyAll
123 #endif
125 namespace content {
126 namespace {
128 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
129 void SetupSandbox(const CommandLine& parsed_command_line) {
130 TRACE_EVENT0("startup", "SetupSandbox");
131 // TODO(evanm): move this into SandboxWrapper; I'm just trying to move this
132 // code en masse out of chrome_main for now.
133 base::FilePath sandbox_binary;
134 bool env_chrome_devel_sandbox_set = false;
135 struct stat st;
137 const bool want_setuid_sandbox =
138 !parsed_command_line.HasSwitch(switches::kNoSandbox) &&
139 !parsed_command_line.HasSwitch(switches::kDisableSetuidSandbox);
141 if (want_setuid_sandbox) {
142 base::FilePath exe_dir;
143 if (PathService::Get(base::DIR_EXE, &exe_dir)) {
144 base::FilePath sandbox_candidate = exe_dir.AppendASCII("chrome-sandbox");
145 if (base::PathExists(sandbox_candidate))
146 sandbox_binary = sandbox_candidate;
149 // In user-managed builds, including development builds, an environment
150 // variable is required to enable the sandbox. See
151 // http://code.google.com/p/chromium/wiki/LinuxSUIDSandboxDevelopment
152 if (sandbox_binary.empty() &&
153 stat(base::kProcSelfExe, &st) == 0 && st.st_uid == getuid()) {
154 const char* devel_sandbox_path = getenv("CHROME_DEVEL_SANDBOX");
155 if (devel_sandbox_path) {
156 env_chrome_devel_sandbox_set = true;
157 sandbox_binary = base::FilePath(devel_sandbox_path);
161 static const char no_suid_error[] = "Running without the SUID sandbox! See "
162 "https://code.google.com/p/chromium/wiki/LinuxSUIDSandboxDevelopment "
163 "for more information on developing with the sandbox on.";
164 if (sandbox_binary.empty()) {
165 if (!env_chrome_devel_sandbox_set) {
166 // This needs to be fatal. Talk to security@chromium.org if you feel
167 // otherwise.
168 LOG(FATAL) << no_suid_error;
171 // TODO(jln): an empty CHROME_DEVEL_SANDBOX environment variable (as
172 // opposed to a non existing one) is not fatal yet. This is needed
173 // because of existing bots and scripts. Fix it (crbug.com/245376).
174 LOG(ERROR) << no_suid_error;
178 // Tickle the sandbox host and zygote host so they fork now.
179 RenderSandboxHostLinux::GetInstance()->Init(sandbox_binary.value());
180 ZygoteHostImpl::GetInstance()->Init(sandbox_binary.value());
182 #endif
184 #if defined(USE_GLIB)
185 static void GLibLogHandler(const gchar* log_domain,
186 GLogLevelFlags log_level,
187 const gchar* message,
188 gpointer userdata) {
189 if (!log_domain)
190 log_domain = "<unknown>";
191 if (!message)
192 message = "<no message>";
194 if (strstr(message, "Loading IM context type") ||
195 strstr(message, "wrong ELF class: ELFCLASS64")) {
196 // http://crbug.com/9643
197 // Until we have a real 64-bit build or all of these 32-bit package issues
198 // are sorted out, don't fatal on ELF 32/64-bit mismatch warnings and don't
199 // spam the user with more than one of them.
200 static bool alerted = false;
201 if (!alerted) {
202 LOG(ERROR) << "Bug 9643: " << log_domain << ": " << message;
203 alerted = true;
205 } else if (strstr(message, "Unable to retrieve the file info for")) {
206 LOG(ERROR) << "GTK File code error: " << message;
207 } else if (strstr(message, "Could not find the icon") &&
208 strstr(log_domain, "Gtk")) {
209 LOG(ERROR) << "GTK icon error: " << message;
210 } else if (strstr(message, "Theme file for default has no") ||
211 strstr(message, "Theme directory") ||
212 strstr(message, "theme pixmap") ||
213 strstr(message, "locate theme engine")) {
214 LOG(ERROR) << "GTK theme error: " << message;
215 } else if (strstr(message, "Unable to create Ubuntu Menu Proxy") &&
216 strstr(log_domain, "<unknown>")) {
217 LOG(ERROR) << "GTK menu proxy create failed";
218 } else if (strstr(message, "gtk_drag_dest_leave: assertion")) {
219 LOG(ERROR) << "Drag destination deleted: http://crbug.com/18557";
220 } else if (strstr(message, "Out of memory") &&
221 strstr(log_domain, "<unknown>")) {
222 LOG(ERROR) << "DBus call timeout or out of memory: "
223 << "http://crosbug.com/15496";
224 } else if (strstr(message, "Could not connect: Connection refused") &&
225 strstr(log_domain, "<unknown>")) {
226 LOG(ERROR) << "DConf settings backend could not connect to session bus: "
227 << "http://crbug.com/179797";
228 } else if (strstr(message, "XDG_RUNTIME_DIR variable not set")) {
229 LOG(ERROR) << message << " (http://bugs.chromium.org/97293)";
230 } else if (strstr(message, "Attempting to store changes into") ||
231 strstr(message, "Attempting to set the permissions of")) {
232 LOG(ERROR) << message << " (http://bugs.chromium.org/161366)";
233 } else if (strstr(message, "drawable is not a native X11 window")) {
234 LOG(ERROR) << message << " (http://bugs.chromium.org/329991)";
235 } else {
236 LOG(DFATAL) << log_domain << ": " << message;
240 static void SetUpGLibLogHandler() {
241 // Register GLib-handled assertions to go through our logging system.
242 const char* kLogDomains[] = { NULL, "Gtk", "Gdk", "GLib", "GLib-GObject" };
243 for (size_t i = 0; i < arraysize(kLogDomains); i++) {
244 g_log_set_handler(kLogDomains[i],
245 static_cast<GLogLevelFlags>(G_LOG_FLAG_RECURSION |
246 G_LOG_FLAG_FATAL |
247 G_LOG_LEVEL_ERROR |
248 G_LOG_LEVEL_CRITICAL |
249 G_LOG_LEVEL_WARNING),
250 GLibLogHandler,
251 NULL);
254 #endif
256 } // namespace
258 // The currently-running BrowserMainLoop. There can be one or zero.
259 BrowserMainLoop* g_current_browser_main_loop = NULL;
261 // This is just to be able to keep ShutdownThreadsAndCleanUp out of
262 // the public interface of BrowserMainLoop.
263 class BrowserShutdownImpl {
264 public:
265 static void ImmediateShutdownAndExitProcess() {
266 DCHECK(g_current_browser_main_loop);
267 g_current_browser_main_loop->ShutdownThreadsAndCleanUp();
269 #if defined(OS_WIN)
270 // At this point the message loop is still running yet we've shut everything
271 // down. If any messages are processed we'll likely crash. Exit now.
272 ExitProcess(RESULT_CODE_NORMAL_EXIT);
273 #elif defined(OS_POSIX) && !defined(OS_MACOSX)
274 _exit(RESULT_CODE_NORMAL_EXIT);
275 #else
276 NOTIMPLEMENTED();
277 #endif
281 void ImmediateShutdownAndExitProcess() {
282 BrowserShutdownImpl::ImmediateShutdownAndExitProcess();
285 // For measuring memory usage after each task. Behind a command line flag.
286 class BrowserMainLoop::MemoryObserver : public base::MessageLoop::TaskObserver {
287 public:
288 MemoryObserver() {}
289 virtual ~MemoryObserver() {}
291 virtual void WillProcessTask(const base::PendingTask& pending_task) OVERRIDE {
294 virtual void DidProcessTask(const base::PendingTask& pending_task) OVERRIDE {
295 #if !defined(OS_IOS) // No ProcessMetrics on IOS.
296 scoped_ptr<base::ProcessMetrics> process_metrics(
297 base::ProcessMetrics::CreateProcessMetrics(
298 #if defined(OS_MACOSX)
299 base::GetCurrentProcessHandle(), NULL));
300 #else
301 base::GetCurrentProcessHandle()));
302 #endif
303 size_t private_bytes;
304 process_metrics->GetMemoryBytes(&private_bytes, NULL);
305 HISTOGRAM_MEMORY_KB("Memory.BrowserUsed", private_bytes >> 10);
306 #endif
308 private:
309 DISALLOW_COPY_AND_ASSIGN(MemoryObserver);
313 // BrowserMainLoop construction / destruction =============================
315 BrowserMainLoop* BrowserMainLoop::GetInstance() {
316 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
317 return g_current_browser_main_loop;
320 BrowserMainLoop::BrowserMainLoop(const MainFunctionParams& parameters)
321 : parameters_(parameters),
322 parsed_command_line_(parameters.command_line),
323 result_code_(RESULT_CODE_NORMAL_EXIT),
324 created_threads_(false),
325 // ContentMainRunner should have enabled tracing of the browser process
326 // when kTraceStartup is in the command line.
327 is_tracing_startup_(base::debug::TraceLog::GetInstance()->IsEnabled()) {
328 DCHECK(!g_current_browser_main_loop);
329 g_current_browser_main_loop = this;
332 BrowserMainLoop::~BrowserMainLoop() {
333 DCHECK_EQ(this, g_current_browser_main_loop);
334 #if !defined(OS_IOS)
335 ui::Clipboard::DestroyClipboardForCurrentThread();
336 #endif // !defined(OS_IOS)
337 g_current_browser_main_loop = NULL;
340 void BrowserMainLoop::Init() {
341 TRACE_EVENT0("startup", "BrowserMainLoop::Init")
342 parts_.reset(
343 GetContentClient()->browser()->CreateBrowserMainParts(parameters_));
346 // BrowserMainLoop stages ==================================================
348 void BrowserMainLoop::EarlyInitialization() {
349 TRACE_EVENT0("startup", "BrowserMainLoop::EarlyInitialization");
351 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
352 // No thread should be created before this call, as SetupSandbox()
353 // will end-up using fork().
354 SetupSandbox(parsed_command_line_);
355 #endif
357 #if defined(USE_X11)
358 if (parsed_command_line_.HasSwitch(switches::kSingleProcess) ||
359 parsed_command_line_.HasSwitch(switches::kInProcessGPU)) {
360 if (!XInitThreads()) {
361 LOG(ERROR) << "Failed to put Xlib into threaded mode.";
364 #endif
366 // GLib's spawning of new processes is buggy, so it's important that at this
367 // point GLib does not need to start DBUS. Chrome should always start with
368 // DBUS_SESSION_BUS_ADDRESS properly set. See crbug.com/309093.
369 #if defined(USE_GLIB)
370 // g_type_init will be deprecated in 2.36. 2.35 is the development
371 // version for 2.36, hence do not call g_type_init starting 2.35.
372 // http://developer.gnome.org/gobject/unstable/gobject-Type-Information.html#g-type-init
373 #if !GLIB_CHECK_VERSION(2, 35, 0)
374 // GLib type system initialization. Needed at least for gconf,
375 // used in net/proxy/proxy_config_service_linux.cc. Most likely
376 // this is superfluous as gtk_init() ought to do this. It's
377 // definitely harmless, so retained as a reminder of this
378 // requirement for gconf.
379 g_type_init();
380 #endif
382 #if !defined(USE_AURA)
383 gfx::GtkInitFromCommandLine(parsed_command_line_);
384 #endif
386 SetUpGLibLogHandler();
387 #endif
389 if (parts_)
390 parts_->PreEarlyInitialization();
392 #if defined(OS_WIN)
393 net::EnsureWinsockInit();
394 #endif
396 #if !defined(USE_OPENSSL)
397 // We want to be sure to init NSPR on the main thread.
398 crypto::EnsureNSPRInit();
399 #endif // !defined(USE_OPENSSL)
401 if (parsed_command_line_.HasSwitch(switches::kEnableSSLCachedInfo))
402 net::SSLConfigService::EnableCachedInfo();
404 #if !defined(OS_IOS)
405 if (parsed_command_line_.HasSwitch(switches::kRendererProcessLimit)) {
406 std::string limit_string = parsed_command_line_.GetSwitchValueASCII(
407 switches::kRendererProcessLimit);
408 size_t process_limit;
409 if (base::StringToSizeT(limit_string, &process_limit)) {
410 RenderProcessHost::SetMaxRendererProcessCount(process_limit);
413 #endif // !defined(OS_IOS)
415 if (parts_)
416 parts_->PostEarlyInitialization();
419 void BrowserMainLoop::MainMessageLoopStart() {
420 TRACE_EVENT0("startup", "BrowserMainLoop::MainMessageLoopStart")
421 if (parts_) {
422 TRACE_EVENT0("startup",
423 "BrowserMainLoop::MainMessageLoopStart:PreMainMessageLoopStart");
424 parts_->PreMainMessageLoopStart();
427 #if defined(OS_WIN)
428 // If we're running tests (ui_task is non-null), then the ResourceBundle
429 // has already been initialized.
430 if (!parameters_.ui_task) {
431 // Override the configured locale with the user's preferred UI language.
432 l10n_util::OverrideLocaleWithUILanguageList();
434 #endif
436 // Create a MessageLoop if one does not already exist for the current thread.
437 if (!base::MessageLoop::current())
438 main_message_loop_.reset(new base::MessageLoopForUI);
440 InitializeMainThread();
443 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SystemMonitor")
444 system_monitor_.reset(new base::SystemMonitor);
447 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:PowerMonitor")
448 scoped_ptr<base::PowerMonitorSource> power_monitor_source(
449 new base::PowerMonitorDeviceSource());
450 power_monitor_.reset(new base::PowerMonitor(power_monitor_source.Pass()));
453 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:HighResTimerManager")
454 hi_res_timer_manager_.reset(new base::HighResolutionTimerManager);
457 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:NetworkChangeNotifier")
458 network_change_notifier_.reset(net::NetworkChangeNotifier::Create());
461 #if !defined(OS_IOS)
463 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MediaFeatures")
464 media::InitializeCPUSpecificMediaFeatures();
467 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:AudioMan")
468 audio_manager_.reset(media::AudioManager::Create(
469 MediaInternals::GetInstance()));
472 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MIDIManager")
473 midi_manager_.reset(media::MIDIManager::Create());
476 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:ContentWebUIController")
477 WebUIControllerFactory::RegisterFactory(
478 ContentWebUIControllerFactory::GetInstance());
482 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:AudioMirroringManager")
483 audio_mirroring_manager_.reset(new AudioMirroringManager());
486 // Start tracing to a file if needed.
487 if (is_tracing_startup_) {
488 TRACE_EVENT0("startup", "BrowserMainLoop::InitStartupTracing")
489 InitStartupTracing(parsed_command_line_);
493 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:OnlineStateObserver")
494 online_state_observer_.reset(new BrowserOnlineStateObserver);
498 system_stats_monitor_.reset(new base::debug::TraceEventSystemStatsMonitor(
499 base::ThreadTaskRunnerHandle::Get()));
501 #endif // !defined(OS_IOS)
503 #if defined(OS_WIN)
504 system_message_window_.reset(new SystemMessageWindowWin);
506 if (base::win::IsTSFAwareRequired()) {
507 // Create a TSF message filter for the message loop. MessageLoop takes
508 // ownership of the filter.
509 scoped_ptr<base::win::TextServicesMessageFilter> tsf_message_filter(
510 new base::win::TextServicesMessageFilter);
511 if (tsf_message_filter->Init()) {
512 base::MessageLoopForUI::current()->SetMessageFilter(
513 tsf_message_filter.PassAs<base::MessageLoopForUI::MessageFilter>());
516 #endif
518 if (parts_)
519 parts_->PostMainMessageLoopStart();
521 #if defined(OS_ANDROID)
523 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SurfaceTexturePeer")
524 SurfaceTexturePeer::InitInstance(new SurfaceTexturePeerBrowserImpl());
526 #endif
528 if (parsed_command_line_.HasSwitch(switches::kMemoryMetrics)) {
529 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MemoryObserver")
530 memory_observer_.reset(new MemoryObserver());
531 base::MessageLoop::current()->AddTaskObserver(memory_observer_.get());
534 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
535 trace_memory_controller_.reset(new base::debug::TraceMemoryController(
536 base::MessageLoop::current()->message_loop_proxy(),
537 ::HeapProfilerWithPseudoStackStart,
538 ::HeapProfilerStop,
539 ::GetHeapProfile));
540 #endif
543 int BrowserMainLoop::PreCreateThreads() {
545 if (parts_) {
546 TRACE_EVENT0("startup",
547 "BrowserMainLoop::CreateThreads:PreCreateThreads");
548 result_code_ = parts_->PreCreateThreads();
551 #if defined(ENABLE_PLUGINS)
552 // Prior to any processing happening on the io thread, we create the
553 // plugin service as it is predominantly used from the io thread,
554 // but must be created on the main thread. The service ctor is
555 // inexpensive and does not invoke the io_thread() accessor.
557 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads:PluginService")
558 PluginService::GetInstance()->Init();
560 #endif
562 #if !defined(OS_IOS) && (!defined(GOOGLE_CHROME_BUILD) || defined(OS_ANDROID))
563 // Single-process is an unsupported and not fully tested mode, so
564 // don't enable it for official Chrome builds (except on Android).
565 if (parsed_command_line_.HasSwitch(switches::kSingleProcess))
566 RenderProcessHost::SetRunRendererInProcess(true);
567 #endif
568 return result_code_;
571 void BrowserMainLoop::CreateStartupTasks() {
572 TRACE_EVENT0("startup", "BrowserMainLoop::CreateStartupTasks");
574 // First time through, we really want to create all the tasks
575 if (!startup_task_runner_.get()) {
576 #if defined(OS_ANDROID)
577 startup_task_runner_ = make_scoped_ptr(new StartupTaskRunner(
578 base::Bind(&BrowserStartupComplete),
579 base::MessageLoop::current()->message_loop_proxy()));
580 #else
581 startup_task_runner_ = make_scoped_ptr(new StartupTaskRunner(
582 base::Callback<void(int)>(),
583 base::MessageLoop::current()->message_loop_proxy()));
584 #endif
585 StartupTask pre_create_threads =
586 base::Bind(&BrowserMainLoop::PreCreateThreads, base::Unretained(this));
587 startup_task_runner_->AddTask(pre_create_threads);
589 StartupTask create_threads =
590 base::Bind(&BrowserMainLoop::CreateThreads, base::Unretained(this));
591 startup_task_runner_->AddTask(create_threads);
593 StartupTask browser_thread_started = base::Bind(
594 &BrowserMainLoop::BrowserThreadsStarted, base::Unretained(this));
595 startup_task_runner_->AddTask(browser_thread_started);
597 StartupTask pre_main_message_loop_run = base::Bind(
598 &BrowserMainLoop::PreMainMessageLoopRun, base::Unretained(this));
599 startup_task_runner_->AddTask(pre_main_message_loop_run);
601 #if defined(OS_ANDROID)
602 if (BrowserMayStartAsynchronously()) {
603 startup_task_runner_->StartRunningTasksAsync();
605 #endif
607 #if defined(OS_ANDROID)
608 if (!BrowserMayStartAsynchronously()) {
609 // A second request for asynchronous startup can be ignored, so
610 // StartupRunningTasksAsync is only called first time through. If, however,
611 // this is a request for synchronous startup then it must override any
612 // previous call for async startup, so we call RunAllTasksNow()
613 // unconditionally.
614 startup_task_runner_->RunAllTasksNow();
616 #else
617 startup_task_runner_->RunAllTasksNow();
618 #endif
621 int BrowserMainLoop::CreateThreads() {
622 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads");
624 base::Thread::Options default_options;
625 base::Thread::Options io_message_loop_options;
626 io_message_loop_options.message_loop_type = base::MessageLoop::TYPE_IO;
627 base::Thread::Options ui_message_loop_options;
628 ui_message_loop_options.message_loop_type = base::MessageLoop::TYPE_UI;
630 // Start threads in the order they occur in the BrowserThread::ID
631 // enumeration, except for BrowserThread::UI which is the main
632 // thread.
634 // Must be size_t so we can increment it.
635 for (size_t thread_id = BrowserThread::UI + 1;
636 thread_id < BrowserThread::ID_COUNT;
637 ++thread_id) {
638 scoped_ptr<BrowserProcessSubThread>* thread_to_start = NULL;
639 base::Thread::Options* options = &default_options;
641 switch (thread_id) {
642 case BrowserThread::DB:
643 TRACE_EVENT_BEGIN1("startup",
644 "BrowserMainLoop::CreateThreads:start",
645 "Thread", "BrowserThread::DB");
646 thread_to_start = &db_thread_;
647 break;
648 case BrowserThread::FILE_USER_BLOCKING:
649 TRACE_EVENT_BEGIN1("startup",
650 "BrowserMainLoop::CreateThreads:start",
651 "Thread", "BrowserThread::FILE_USER_BLOCKING");
652 thread_to_start = &file_user_blocking_thread_;
653 break;
654 case BrowserThread::FILE:
655 TRACE_EVENT_BEGIN1("startup",
656 "BrowserMainLoop::CreateThreads:start",
657 "Thread", "BrowserThread::FILE");
658 thread_to_start = &file_thread_;
659 #if defined(OS_WIN)
660 // On Windows, the FILE thread needs to be have a UI message loop
661 // which pumps messages in such a way that Google Update can
662 // communicate back to us.
663 options = &ui_message_loop_options;
664 #else
665 options = &io_message_loop_options;
666 #endif
667 break;
668 case BrowserThread::PROCESS_LAUNCHER:
669 TRACE_EVENT_BEGIN1("startup",
670 "BrowserMainLoop::CreateThreads:start",
671 "Thread", "BrowserThread::PROCESS_LAUNCHER");
672 thread_to_start = &process_launcher_thread_;
673 break;
674 case BrowserThread::CACHE:
675 TRACE_EVENT_BEGIN1("startup",
676 "BrowserMainLoop::CreateThreads:start",
677 "Thread", "BrowserThread::CACHE");
678 thread_to_start = &cache_thread_;
679 options = &io_message_loop_options;
680 break;
681 case BrowserThread::IO:
682 TRACE_EVENT_BEGIN1("startup",
683 "BrowserMainLoop::CreateThreads:start",
684 "Thread", "BrowserThread::IO");
685 thread_to_start = &io_thread_;
686 options = &io_message_loop_options;
687 break;
688 case BrowserThread::UI:
689 case BrowserThread::ID_COUNT:
690 default:
691 NOTREACHED();
692 break;
695 BrowserThread::ID id = static_cast<BrowserThread::ID>(thread_id);
697 if (thread_to_start) {
698 (*thread_to_start).reset(new BrowserProcessSubThread(id));
699 (*thread_to_start)->StartWithOptions(*options);
700 } else {
701 NOTREACHED();
704 TRACE_EVENT_END0("startup", "BrowserMainLoop::CreateThreads:start");
707 created_threads_ = true;
708 return result_code_;
711 int BrowserMainLoop::PreMainMessageLoopRun() {
712 if (parts_) {
713 TRACE_EVENT0("startup",
714 "BrowserMainLoop::CreateThreads:PreMainMessageLoopRun");
715 parts_->PreMainMessageLoopRun();
718 // If the UI thread blocks, the whole UI is unresponsive.
719 // Do not allow disk IO from the UI thread.
720 base::ThreadRestrictions::SetIOAllowed(false);
721 base::ThreadRestrictions::DisallowWaiting();
722 return result_code_;
725 void BrowserMainLoop::RunMainMessageLoopParts() {
726 TRACE_EVENT_BEGIN_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
728 bool ran_main_loop = false;
729 if (parts_)
730 ran_main_loop = parts_->MainMessageLoopRun(&result_code_);
732 if (!ran_main_loop)
733 MainMessageLoopRun();
735 TRACE_EVENT_END_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
738 void BrowserMainLoop::ShutdownThreadsAndCleanUp() {
739 if (!created_threads_) {
740 // Called early, nothing to do
741 return;
743 TRACE_EVENT0("shutdown", "BrowserMainLoop::ShutdownThreadsAndCleanUp")
745 // Teardown may start in PostMainMessageLoopRun, and during teardown we
746 // need to be able to perform IO.
747 base::ThreadRestrictions::SetIOAllowed(true);
748 BrowserThread::PostTask(
749 BrowserThread::IO, FROM_HERE,
750 base::Bind(base::IgnoreResult(&base::ThreadRestrictions::SetIOAllowed),
751 true));
753 if (RenderProcessHost::run_renderer_in_process())
754 RenderProcessHostImpl::ShutDownInProcessRenderer();
756 if (parts_) {
757 TRACE_EVENT0("shutdown",
758 "BrowserMainLoop::Subsystem:PostMainMessageLoopRun");
759 parts_->PostMainMessageLoopRun();
762 trace_memory_controller_.reset();
763 system_stats_monitor_.reset();
765 #if !defined(OS_IOS)
766 // Destroying the GpuProcessHostUIShims on the UI thread posts a task to
767 // delete related objects on the GPU thread. This must be done before
768 // stopping the GPU thread. The GPU thread will close IPC channels to renderer
769 // processes so this has to happen before stopping the IO thread.
771 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUProcessHostShim");
772 GpuProcessHostUIShim::DestroyAll();
774 // Cancel pending requests and prevent new requests.
775 if (resource_dispatcher_host_) {
776 TRACE_EVENT0("shutdown",
777 "BrowserMainLoop::Subsystem:ResourceDispatcherHost");
778 resource_dispatcher_host_.get()->Shutdown();
781 #if defined(USE_AURA)
783 TRACE_EVENT0("shutdown",
784 "BrowserMainLoop::Subsystem:ImageTransportFactory");
785 ImageTransportFactory::Terminate();
787 #endif
789 // The device monitors are using |system_monitor_| as dependency, so delete
790 // them before |system_monitor_| goes away.
791 // On Mac and windows, the monitor needs to be destroyed on the same thread
792 // as they were created. On Linux, the monitor will be deleted when IO thread
793 // goes away.
794 #if defined(OS_WIN)
795 system_message_window_.reset();
796 #elif defined(OS_MACOSX)
797 device_monitor_mac_.reset();
798 #endif
799 #endif // !defined(OS_IOS)
801 // Must be size_t so we can subtract from it.
802 for (size_t thread_id = BrowserThread::ID_COUNT - 1;
803 thread_id >= (BrowserThread::UI + 1);
804 --thread_id) {
805 // Find the thread object we want to stop. Looping over all valid
806 // BrowserThread IDs and DCHECKing on a missing case in the switch
807 // statement helps avoid a mismatch between this code and the
808 // BrowserThread::ID enumeration.
810 // The destruction order is the reverse order of occurrence in the
811 // BrowserThread::ID list. The rationale for the order is as
812 // follows (need to be filled in a bit):
815 // - The IO thread is the only user of the CACHE thread.
817 // - The PROCESS_LAUNCHER thread must be stopped after IO in case
818 // the IO thread posted a task to terminate a process on the
819 // process launcher thread.
821 // - (Not sure why DB stops last.)
822 switch (thread_id) {
823 case BrowserThread::DB: {
824 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DBThread");
825 db_thread_.reset();
827 break;
828 case BrowserThread::FILE_USER_BLOCKING: {
829 TRACE_EVENT0("shutdown",
830 "BrowserMainLoop::Subsystem:FileUserBlockingThread");
831 file_user_blocking_thread_.reset();
833 break;
834 case BrowserThread::FILE: {
835 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:FileThread");
836 #if !defined(OS_IOS)
837 // Clean up state that lives on or uses the file_thread_ before
838 // it goes away.
839 if (resource_dispatcher_host_)
840 resource_dispatcher_host_.get()->save_file_manager()->Shutdown();
841 #endif // !defined(OS_IOS)
842 file_thread_.reset();
844 break;
845 case BrowserThread::PROCESS_LAUNCHER: {
846 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:LauncherThread");
847 process_launcher_thread_.reset();
849 break;
850 case BrowserThread::CACHE: {
851 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:CacheThread");
852 cache_thread_.reset();
854 break;
855 case BrowserThread::IO: {
856 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IOThread");
857 io_thread_.reset();
859 break;
860 case BrowserThread::UI:
861 case BrowserThread::ID_COUNT:
862 default:
863 NOTREACHED();
864 break;
868 #if !defined(OS_IOS)
870 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IndexedDBThread");
871 indexed_db_thread_.reset();
873 #endif
875 // Close the blocking I/O pool after the other threads. Other threads such
876 // as the I/O thread may need to schedule work like closing files or flushing
877 // data during shutdown, so the blocking pool needs to be available. There
878 // may also be slow operations pending that will blcok shutdown, so closing
879 // it here (which will block until required operations are complete) gives
880 // more head start for those operations to finish.
882 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:ThreadPool");
883 BrowserThreadImpl::ShutdownThreadPool();
886 #if !defined(OS_IOS)
887 // Must happen after the IO thread is shutdown since this may be accessed from
888 // it.
890 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUChannelFactory");
891 if (BrowserGpuChannelHostFactory::instance())
892 BrowserGpuChannelHostFactory::Terminate();
895 // Must happen after the I/O thread is shutdown since this class lives on the
896 // I/O thread and isn't threadsafe.
898 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GamepadService");
899 GamepadService::GetInstance()->Terminate();
902 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:SensorService");
903 DeviceInertialSensorService::GetInstance()->Shutdown();
906 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DeleteDataSources");
907 URLDataManager::DeleteDataSources();
909 #endif // !defined(OS_IOS)
911 if (parts_) {
912 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:PostDestroyThreads");
913 parts_->PostDestroyThreads();
917 void BrowserMainLoop::InitializeMainThread() {
918 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeMainThread")
919 const char* kThreadName = "CrBrowserMain";
920 base::PlatformThread::SetName(kThreadName);
921 if (main_message_loop_)
922 main_message_loop_->set_thread_name(kThreadName);
924 // Register the main thread by instantiating it, but don't call any methods.
925 main_thread_.reset(
926 new BrowserThreadImpl(BrowserThread::UI, base::MessageLoop::current()));
929 int BrowserMainLoop::BrowserThreadsStarted() {
930 TRACE_EVENT0("startup", "BrowserMainLoop::BrowserThreadsStarted")
932 #if !defined(OS_IOS)
933 indexed_db_thread_.reset(new base::Thread("IndexedDB"));
934 indexed_db_thread_->Start();
935 #endif
937 #if defined(OS_ANDROID)
938 // Up the priority of anything that touches with display tasks
939 // (this thread is UI thread, and io_thread_ is for IPCs).
940 io_thread_->SetPriority(base::kThreadPriority_Display);
941 base::PlatformThread::SetThreadPriority(
942 base::PlatformThread::CurrentHandle(),
943 base::kThreadPriority_Display);
944 #endif
946 #if !defined(OS_IOS)
947 HistogramSynchronizer::GetInstance();
949 // Initialize the GpuDataManager before we set up the MessageLoops because
950 // otherwise we'll trigger the assertion about doing IO on the UI thread.
951 GpuDataManagerImpl::GetInstance()->Initialize();
953 bool always_uses_gpu = IsForceCompositingModeEnabled();
954 bool established_gpu_channel = false;
955 #if defined(USE_AURA) || defined(OS_ANDROID)
956 established_gpu_channel =
957 !parsed_command_line_.HasSwitch(switches::kDisableGpuProcessPrelaunch) ||
958 parsed_command_line_.HasSwitch(switches::kSingleProcess) ||
959 parsed_command_line_.HasSwitch(switches::kInProcessGPU);
960 #if defined(USE_AURA)
961 if (!GpuDataManagerImpl::GetInstance()->CanUseGpuBrowserCompositor()) {
962 established_gpu_channel = always_uses_gpu = false;
964 BrowserGpuChannelHostFactory::Initialize(established_gpu_channel);
965 ImageTransportFactory::Initialize();
966 #elif defined(OS_ANDROID)
967 BrowserGpuChannelHostFactory::Initialize(established_gpu_channel);
968 #endif
969 #endif
971 #if defined(OS_LINUX) && defined(USE_UDEV)
972 device_monitor_linux_.reset(new DeviceMonitorLinux());
973 #elif defined(OS_MACOSX)
974 device_monitor_mac_.reset(new DeviceMonitorMac());
975 #endif
977 // RDH needs the IO thread to be created
979 TRACE_EVENT0("startup",
980 "BrowserMainLoop::BrowserThreadsStarted:InitResourceDispatcherHost");
981 resource_dispatcher_host_.reset(new ResourceDispatcherHostImpl());
984 // MediaStreamManager needs the IO thread to be created.
986 TRACE_EVENT0("startup",
987 "BrowserMainLoop::BrowserThreadsStarted:InitMediaStreamManager");
988 media_stream_manager_.reset(new MediaStreamManager(audio_manager_.get()));
992 TRACE_EVENT0("startup",
993 "BrowserMainLoop::BrowserThreadsStarted:InitSpeechRecognition");
994 speech_recognition_manager_.reset(new SpeechRecognitionManagerImpl(
995 audio_manager_.get(), media_stream_manager_.get()));
999 TRACE_EVENT0(
1000 "startup",
1001 "BrowserMainLoop::BrowserThreadsStarted::InitUserInputMonitor");
1002 user_input_monitor_ = media::UserInputMonitor::Create(
1003 io_thread_->message_loop_proxy(), main_thread_->message_loop_proxy());
1006 // Alert the clipboard class to which threads are allowed to access the
1007 // clipboard:
1008 std::vector<base::PlatformThreadId> allowed_clipboard_threads;
1009 // The current thread is the UI thread.
1010 allowed_clipboard_threads.push_back(base::PlatformThread::CurrentId());
1011 #if defined(OS_WIN)
1012 // On Windows, clipboards are also used on the File or IO threads.
1013 allowed_clipboard_threads.push_back(file_thread_->thread_id());
1014 allowed_clipboard_threads.push_back(io_thread_->thread_id());
1015 #endif
1016 ui::Clipboard::SetAllowedThreads(allowed_clipboard_threads);
1018 // When running the GPU thread in-process, avoid optimistically starting it
1019 // since creating the GPU thread races against creation of the one-and-only
1020 // ChildProcess instance which is created by the renderer thread.
1021 if (GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL) &&
1022 !established_gpu_channel &&
1023 always_uses_gpu &&
1024 !parsed_command_line_.HasSwitch(switches::kDisableGpuProcessPrelaunch) &&
1025 !parsed_command_line_.HasSwitch(switches::kSingleProcess) &&
1026 !parsed_command_line_.HasSwitch(switches::kInProcessGPU)) {
1027 TRACE_EVENT_INSTANT0("gpu", "Post task to launch GPU process",
1028 TRACE_EVENT_SCOPE_THREAD);
1029 BrowserThread::PostTask(
1030 BrowserThread::IO, FROM_HERE, base::Bind(
1031 base::IgnoreResult(&GpuProcessHost::Get),
1032 GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED,
1033 CAUSE_FOR_GPU_LAUNCH_BROWSER_STARTUP));
1035 #endif // !defined(OS_IOS)
1037 #if defined(OS_MACOSX)
1038 ThemeHelperMac::GetInstance();
1039 #endif
1040 return result_code_;
1043 void BrowserMainLoop::InitializeToolkit() {
1044 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeToolkit")
1045 // TODO(evan): this function is rather subtle, due to the variety
1046 // of intersecting ifdefs we have. To keep it easy to follow, there
1047 // are no #else branches on any #ifs.
1048 // TODO(stevenjb): Move platform specific code into platform specific Parts
1049 // (Need to add InitializeToolkit stage to BrowserParts).
1050 // See also GTK setup in EarlyInitialization, above, and associated comments.
1052 #if defined(TOOLKIT_GTK)
1053 // It is important for this to happen before the first run dialog, as it
1054 // styles the dialog as well.
1055 gfx::InitRCStyles();
1056 #endif
1058 #if defined(OS_WIN)
1059 // Init common control sex.
1060 INITCOMMONCONTROLSEX config;
1061 config.dwSize = sizeof(config);
1062 config.dwICC = ICC_WIN95_CLASSES;
1063 if (!InitCommonControlsEx(&config))
1064 LOG_GETLASTERROR(FATAL);
1065 #endif
1067 if (parts_)
1068 parts_->ToolkitInitialized();
1071 void BrowserMainLoop::MainMessageLoopRun() {
1072 #if defined(OS_ANDROID)
1073 // Android's main message loop is the Java message loop.
1074 NOTREACHED();
1075 #else
1076 DCHECK_EQ(base::MessageLoop::TYPE_UI, base::MessageLoop::current()->type());
1077 if (parameters_.ui_task)
1078 base::MessageLoopForUI::current()->PostTask(FROM_HERE,
1079 *parameters_.ui_task);
1081 base::RunLoop run_loop;
1082 run_loop.Run();
1083 #endif
1086 void BrowserMainLoop::InitStartupTracing(const CommandLine& command_line) {
1087 DCHECK(is_tracing_startup_);
1089 base::FilePath trace_file = command_line.GetSwitchValuePath(
1090 switches::kTraceStartupFile);
1091 // trace_file = "none" means that startup events will show up for the next
1092 // begin/end tracing (via about:tracing or AutomationProxy::BeginTracing/
1093 // EndTracing, for example).
1094 if (trace_file == base::FilePath().AppendASCII("none"))
1095 return;
1097 if (trace_file.empty()) {
1098 // Default to saving the startup trace into the current dir.
1099 trace_file = base::FilePath().AppendASCII("chrometrace.log");
1102 std::string delay_str = command_line.GetSwitchValueASCII(
1103 switches::kTraceStartupDuration);
1104 int delay_secs = 5;
1105 if (!delay_str.empty() && !base::StringToInt(delay_str, &delay_secs)) {
1106 DLOG(WARNING) << "Could not parse --" << switches::kTraceStartupDuration
1107 << "=" << delay_str << " defaulting to 5 (secs)";
1108 delay_secs = 5;
1111 BrowserThread::PostDelayedTask(
1112 BrowserThread::UI, FROM_HERE,
1113 base::Bind(&BrowserMainLoop::EndStartupTracing,
1114 base::Unretained(this), trace_file),
1115 base::TimeDelta::FromSeconds(delay_secs));
1118 void BrowserMainLoop::EndStartupTracing(const base::FilePath& trace_file) {
1119 is_tracing_startup_ = false;
1120 TracingController::GetInstance()->DisableRecording(
1121 trace_file, TracingController::TracingFileResultCallback());
1124 } // namespace content