Revert "Added incident report for variations seed signature mismatch."
[chromium-blink-merge.git] / content / browser / browser_main_loop.cc
blob433dbcaba5b05f28e2f3d21c8c5c6dd5b7fc1e36
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/path_service.h"
15 #include "base/pending_task.h"
16 #include "base/power_monitor/power_monitor.h"
17 #include "base/power_monitor/power_monitor_device_source.h"
18 #include "base/process/process_metrics.h"
19 #include "base/run_loop.h"
20 #include "base/strings/string_number_conversions.h"
21 #include "base/system_monitor/system_monitor.h"
22 #include "base/thread_task_runner_handle.h"
23 #include "base/threading/thread_restrictions.h"
24 #include "base/timer/hi_res_timer_manager.h"
25 #include "content/browser/battery_status/battery_status_service.h"
26 #include "content/browser/browser_thread_impl.h"
27 #include "content/browser/device_sensors/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/renderer_host/media/media_stream_manager.h"
40 #include "content/browser/speech/speech_recognition_manager_impl.h"
41 #include "content/browser/startup_task_runner.h"
42 #include "content/browser/time_zone_monitor.h"
43 #include "content/browser/webui/content_web_ui_controller_factory.h"
44 #include "content/browser/webui/url_data_manager.h"
45 #include "content/public/browser/browser_main_parts.h"
46 #include "content/public/browser/browser_shutdown.h"
47 #include "content/public/browser/content_browser_client.h"
48 #include "content/public/browser/render_process_host.h"
49 #include "content/public/browser/tracing_controller.h"
50 #include "content/public/common/content_switches.h"
51 #include "content/public/common/main_function_params.h"
52 #include "content/public/common/result_codes.h"
53 #include "crypto/nss_util.h"
54 #include "media/audio/audio_manager.h"
55 #include "media/base/media.h"
56 #include "media/base/user_input_monitor.h"
57 #include "media/midi/midi_manager.h"
58 #include "net/base/network_change_notifier.h"
59 #include "net/socket/client_socket_factory.h"
60 #include "net/ssl/ssl_config_service.h"
61 #include "ui/base/clipboard/clipboard.h"
63 #if defined(USE_AURA) || (defined(OS_MACOSX) && !defined(OS_IOS))
64 #include "content/browser/compositor/image_transport_factory.h"
65 #endif
67 #if defined(USE_AURA)
68 #include "content/public/browser/context_factory.h"
69 #include "ui/aura/env.h"
70 #endif
72 #if !defined(OS_IOS)
73 #include "content/browser/renderer_host/render_process_host_impl.h"
74 #endif
76 #if defined(OS_ANDROID)
77 #include "base/android/jni_android.h"
78 #include "content/browser/android/browser_startup_controller.h"
79 #include "content/browser/android/browser_surface_texture_manager.h"
80 #include "content/browser/android/tracing_controller_android.h"
81 #include "content/browser/screen_orientation/screen_orientation_delegate_android.h"
82 #include "content/public/browser/screen_orientation_provider.h"
83 #include "ui/gl/gl_surface.h"
84 #endif
86 #if defined(OS_MACOSX) && !defined(OS_IOS)
87 #include "content/browser/bootstrap_sandbox_mac.h"
88 #include "content/browser/cocoa/system_hotkey_helper_mac.h"
89 #include "content/browser/theme_helper_mac.h"
90 #endif
92 #if defined(OS_WIN)
93 #include <windows.h>
94 #include <commctrl.h>
95 #include <shellapi.h>
97 #include "content/browser/system_message_window_win.h"
98 #include "content/common/sandbox_win.h"
99 #include "net/base/winsock_init.h"
100 #include "ui/base/l10n/l10n_util_win.h"
101 #endif
103 #if defined(USE_GLIB)
104 #include <glib-object.h>
105 #endif
107 #if defined(OS_LINUX) && defined(USE_UDEV)
108 #include "content/browser/device_monitor_udev.h"
109 #elif defined(OS_MACOSX) && !defined(OS_IOS)
110 #include "content/browser/device_monitor_mac.h"
111 #endif
113 #if defined(OS_POSIX) && !defined(OS_MACOSX)
114 #include "content/browser/renderer_host/render_sandbox_host_linux.h"
115 #include "content/browser/zygote_host/zygote_host_impl_linux.h"
116 #include "sandbox/linux/suid/client/setuid_sandbox_client.h"
117 #endif
119 #if defined(ENABLE_PLUGINS)
120 #include "content/browser/plugin_service_impl.h"
121 #endif
123 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
124 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
125 #endif
127 #if defined(USE_X11)
128 #include "ui/gfx/x/x11_connection.h"
129 #include "ui/gfx/x/x11_types.h"
130 #endif
132 // One of the linux specific headers defines this as a macro.
133 #ifdef DestroyAll
134 #undef DestroyAll
135 #endif
137 namespace content {
138 namespace {
140 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
141 void SetupSandbox(const base::CommandLine& parsed_command_line) {
142 TRACE_EVENT0("startup", "SetupSandbox");
143 base::FilePath sandbox_binary;
145 scoped_ptr<sandbox::SetuidSandboxClient> setuid_sandbox_client(
146 sandbox::SetuidSandboxClient::Create());
148 const bool want_setuid_sandbox =
149 !parsed_command_line.HasSwitch(switches::kNoSandbox) &&
150 !parsed_command_line.HasSwitch(switches::kDisableSetuidSandbox) &&
151 !setuid_sandbox_client->IsDisabledViaEnvironment();
153 static const char no_suid_error[] =
154 "Running without the SUID sandbox! See "
155 "https://code.google.com/p/chromium/wiki/LinuxSUIDSandboxDevelopment "
156 "for more information on developing with the sandbox on.";
157 if (want_setuid_sandbox) {
158 sandbox_binary = setuid_sandbox_client->GetSandboxBinaryPath();
159 if (sandbox_binary.empty()) {
160 // This needs to be fatal. Talk to security@chromium.org if you feel
161 // otherwise.
162 LOG(FATAL) << no_suid_error;
164 } else {
165 LOG(ERROR) << no_suid_error;
168 // Tickle the sandbox host and zygote host so they fork now.
169 RenderSandboxHostLinux::GetInstance()->Init();
170 ZygoteHostImpl::GetInstance()->Init(sandbox_binary.value());
172 #endif
174 #if defined(USE_GLIB)
175 static void GLibLogHandler(const gchar* log_domain,
176 GLogLevelFlags log_level,
177 const gchar* message,
178 gpointer userdata) {
179 if (!log_domain)
180 log_domain = "<unknown>";
181 if (!message)
182 message = "<no message>";
184 if (strstr(message, "Unable to retrieve the file info for")) {
185 LOG(ERROR) << "GTK File code error: " << message;
186 } else if (strstr(message, "Could not find the icon") &&
187 strstr(log_domain, "Gtk")) {
188 LOG(ERROR) << "GTK icon error: " << message;
189 } else if (strstr(message, "Theme file for default has no") ||
190 strstr(message, "Theme directory") ||
191 strstr(message, "theme pixmap") ||
192 strstr(message, "locate theme engine")) {
193 LOG(ERROR) << "GTK theme error: " << message;
194 } else if (strstr(message, "Unable to create Ubuntu Menu Proxy") &&
195 strstr(log_domain, "<unknown>")) {
196 LOG(ERROR) << "GTK menu proxy create failed";
197 } else if (strstr(message, "Out of memory") &&
198 strstr(log_domain, "<unknown>")) {
199 LOG(ERROR) << "DBus call timeout or out of memory: "
200 << "http://crosbug.com/15496";
201 } else if (strstr(message, "Could not connect: Connection refused") &&
202 strstr(log_domain, "<unknown>")) {
203 LOG(ERROR) << "DConf settings backend could not connect to session bus: "
204 << "http://crbug.com/179797";
205 } else if (strstr(message, "Attempting to store changes into") ||
206 strstr(message, "Attempting to set the permissions of")) {
207 LOG(ERROR) << message << " (http://bugs.chromium.org/161366)";
208 } else if (strstr(message, "drawable is not a native X11 window")) {
209 LOG(ERROR) << message << " (http://bugs.chromium.org/329991)";
210 } else {
211 LOG(DFATAL) << log_domain << ": " << message;
215 static void SetUpGLibLogHandler() {
216 // Register GLib-handled assertions to go through our logging system.
217 const char* kLogDomains[] = { NULL, "Gtk", "Gdk", "GLib", "GLib-GObject" };
218 for (size_t i = 0; i < arraysize(kLogDomains); i++) {
219 g_log_set_handler(kLogDomains[i],
220 static_cast<GLogLevelFlags>(G_LOG_FLAG_RECURSION |
221 G_LOG_FLAG_FATAL |
222 G_LOG_LEVEL_ERROR |
223 G_LOG_LEVEL_CRITICAL |
224 G_LOG_LEVEL_WARNING),
225 GLibLogHandler,
226 NULL);
229 #endif
231 void OnStoppedStartupTracing(const base::FilePath& trace_file) {
232 VLOG(0) << "Completed startup tracing to " << trace_file.value();
235 #if defined(USE_AURA)
236 bool ShouldInitializeBrowserGpuChannelAndTransportSurface() {
237 return true;
239 #elif defined(OS_MACOSX) && !defined(OS_IOS)
240 bool ShouldInitializeBrowserGpuChannelAndTransportSurface() {
241 return IsDelegatedRendererEnabled();
243 #endif
245 // Disable optimizations for this block of functions so the compiler doesn't
246 // merge them all together. This makes it possible to tell what thread was
247 // unresponsive by inspecting the callstack.
248 MSVC_DISABLE_OPTIMIZE()
249 MSVC_PUSH_DISABLE_WARNING(4748)
251 NOINLINE void ResetThread_DB(scoped_ptr<BrowserProcessSubThread> thread) {
252 thread.reset();
255 NOINLINE void ResetThread_FILE(scoped_ptr<BrowserProcessSubThread> thread) {
256 thread.reset();
259 NOINLINE void ResetThread_FILE_USER_BLOCKING(
260 scoped_ptr<BrowserProcessSubThread> thread) {
261 thread.reset();
264 NOINLINE void ResetThread_PROCESS_LAUNCHER(
265 scoped_ptr<BrowserProcessSubThread> thread) {
266 thread.reset();
269 NOINLINE void ResetThread_CACHE(scoped_ptr<BrowserProcessSubThread> thread) {
270 thread.reset();
273 NOINLINE void ResetThread_IO(scoped_ptr<BrowserProcessSubThread> thread) {
274 thread.reset();
277 #if !defined(OS_IOS)
278 NOINLINE void ResetThread_IndexedDb(scoped_ptr<base::Thread> thread) {
279 thread.reset();
281 #endif
283 MSVC_POP_WARNING()
284 MSVC_ENABLE_OPTIMIZE();
286 } // namespace
288 // The currently-running BrowserMainLoop. There can be one or zero.
289 BrowserMainLoop* g_current_browser_main_loop = NULL;
291 // This is just to be able to keep ShutdownThreadsAndCleanUp out of
292 // the public interface of BrowserMainLoop.
293 class BrowserShutdownImpl {
294 public:
295 static void ImmediateShutdownAndExitProcess() {
296 DCHECK(g_current_browser_main_loop);
297 g_current_browser_main_loop->ShutdownThreadsAndCleanUp();
299 #if defined(OS_WIN)
300 // At this point the message loop is still running yet we've shut everything
301 // down. If any messages are processed we'll likely crash. Exit now.
302 ExitProcess(RESULT_CODE_NORMAL_EXIT);
303 #elif defined(OS_POSIX) && !defined(OS_MACOSX)
304 _exit(RESULT_CODE_NORMAL_EXIT);
305 #else
306 NOTIMPLEMENTED();
307 #endif
311 void ImmediateShutdownAndExitProcess() {
312 BrowserShutdownImpl::ImmediateShutdownAndExitProcess();
315 // For measuring memory usage after each task. Behind a command line flag.
316 class BrowserMainLoop::MemoryObserver : public base::MessageLoop::TaskObserver {
317 public:
318 MemoryObserver() {}
319 ~MemoryObserver() override {}
321 void WillProcessTask(const base::PendingTask& pending_task) override {}
323 void DidProcessTask(const base::PendingTask& pending_task) override {
324 #if !defined(OS_IOS) // No ProcessMetrics on IOS.
325 scoped_ptr<base::ProcessMetrics> process_metrics(
326 base::ProcessMetrics::CreateProcessMetrics(
327 #if defined(OS_MACOSX)
328 base::GetCurrentProcessHandle(), NULL));
329 #else
330 base::GetCurrentProcessHandle()));
331 #endif
332 size_t private_bytes;
333 process_metrics->GetMemoryBytes(&private_bytes, NULL);
334 LOCAL_HISTOGRAM_MEMORY_KB("Memory.BrowserUsed", private_bytes >> 10);
335 #endif
337 private:
338 DISALLOW_COPY_AND_ASSIGN(MemoryObserver);
342 // BrowserMainLoop construction / destruction =============================
344 BrowserMainLoop* BrowserMainLoop::GetInstance() {
345 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
346 return g_current_browser_main_loop;
349 BrowserMainLoop::BrowserMainLoop(const MainFunctionParams& parameters)
350 : parameters_(parameters),
351 parsed_command_line_(parameters.command_line),
352 result_code_(RESULT_CODE_NORMAL_EXIT),
353 created_threads_(false),
354 // ContentMainRunner should have enabled tracing of the browser process
355 // when kTraceStartup is in the command line.
356 is_tracing_startup_(
357 parameters.command_line.HasSwitch(switches::kTraceStartup)) {
358 DCHECK(!g_current_browser_main_loop);
359 g_current_browser_main_loop = this;
362 BrowserMainLoop::~BrowserMainLoop() {
363 DCHECK_EQ(this, g_current_browser_main_loop);
364 #if !defined(OS_IOS)
365 ui::Clipboard::DestroyClipboardForCurrentThread();
366 #endif // !defined(OS_IOS)
367 g_current_browser_main_loop = NULL;
370 void BrowserMainLoop::Init() {
371 TRACE_EVENT0("startup", "BrowserMainLoop::Init");
372 parts_.reset(
373 GetContentClient()->browser()->CreateBrowserMainParts(parameters_));
376 // BrowserMainLoop stages ==================================================
378 void BrowserMainLoop::EarlyInitialization() {
379 TRACE_EVENT0("startup", "BrowserMainLoop::EarlyInitialization");
381 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
382 // No thread should be created before this call, as SetupSandbox()
383 // will end-up using fork().
384 SetupSandbox(parsed_command_line_);
385 #endif
387 #if defined(USE_X11)
388 if (parsed_command_line_.HasSwitch(switches::kSingleProcess) ||
389 parsed_command_line_.HasSwitch(switches::kInProcessGPU)) {
390 if (!gfx::InitializeThreadedX11()) {
391 LOG(ERROR) << "Failed to put Xlib into threaded mode.";
394 #endif
396 // GLib's spawning of new processes is buggy, so it's important that at this
397 // point GLib does not need to start DBUS. Chrome should always start with
398 // DBUS_SESSION_BUS_ADDRESS properly set. See crbug.com/309093.
399 #if defined(USE_GLIB)
400 // g_type_init will be deprecated in 2.36. 2.35 is the development
401 // version for 2.36, hence do not call g_type_init starting 2.35.
402 // http://developer.gnome.org/gobject/unstable/gobject-Type-Information.html#g-type-init
403 #if !GLIB_CHECK_VERSION(2, 35, 0)
404 // GLib type system initialization. Needed at least for gconf,
405 // used in net/proxy/proxy_config_service_linux.cc. Most likely
406 // this is superfluous as gtk_init() ought to do this. It's
407 // definitely harmless, so retained as a reminder of this
408 // requirement for gconf.
409 g_type_init();
410 #endif
412 SetUpGLibLogHandler();
413 #endif
415 if (parts_)
416 parts_->PreEarlyInitialization();
418 #if defined(OS_MACOSX)
419 // We use quite a few file descriptors for our IPC, and the default limit on
420 // the Mac is low (256), so bump it up.
421 base::SetFdLimit(1024);
422 #endif
424 #if defined(OS_WIN)
425 net::EnsureWinsockInit();
426 #endif
428 #if !defined(USE_OPENSSL)
429 // We want to be sure to init NSPR on the main thread.
430 crypto::EnsureNSPRInit();
431 #endif // !defined(USE_OPENSSL)
433 #if !defined(OS_IOS)
434 if (parsed_command_line_.HasSwitch(switches::kRendererProcessLimit)) {
435 std::string limit_string = parsed_command_line_.GetSwitchValueASCII(
436 switches::kRendererProcessLimit);
437 size_t process_limit;
438 if (base::StringToSizeT(limit_string, &process_limit)) {
439 RenderProcessHost::SetMaxRendererProcessCount(process_limit);
442 #endif // !defined(OS_IOS)
444 if (parts_)
445 parts_->PostEarlyInitialization();
448 void BrowserMainLoop::MainMessageLoopStart() {
449 TRACE_EVENT0("startup", "BrowserMainLoop::MainMessageLoopStart");
450 if (parts_) {
451 TRACE_EVENT0("startup",
452 "BrowserMainLoop::MainMessageLoopStart:PreMainMessageLoopStart");
453 parts_->PreMainMessageLoopStart();
456 #if defined(OS_WIN)
457 // If we're running tests (ui_task is non-null), then the ResourceBundle
458 // has already been initialized.
459 if (!parameters_.ui_task) {
460 // Override the configured locale with the user's preferred UI language.
461 l10n_util::OverrideLocaleWithUILanguageList();
463 #endif
465 // Create a MessageLoop if one does not already exist for the current thread.
466 if (!base::MessageLoop::current())
467 main_message_loop_.reset(new base::MessageLoopForUI);
469 InitializeMainThread();
472 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SystemMonitor");
473 system_monitor_.reset(new base::SystemMonitor);
476 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:PowerMonitor");
477 scoped_ptr<base::PowerMonitorSource> power_monitor_source(
478 new base::PowerMonitorDeviceSource());
479 power_monitor_.reset(new base::PowerMonitor(power_monitor_source.Pass()));
482 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:HighResTimerManager");
483 hi_res_timer_manager_.reset(new base::HighResolutionTimerManager);
486 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:NetworkChangeNotifier");
487 network_change_notifier_.reset(net::NetworkChangeNotifier::Create());
490 #if !defined(OS_IOS)
492 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MediaFeatures");
493 media::InitializeCPUSpecificMediaFeatures();
496 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:AudioMan");
497 audio_manager_.reset(media::AudioManager::Create(
498 MediaInternals::GetInstance()));
501 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MidiManager");
502 midi_manager_.reset(media::MidiManager::Create());
505 TRACE_EVENT0("startup",
506 "BrowserMainLoop::Subsystem:ContentWebUIController");
507 WebUIControllerFactory::RegisterFactory(
508 ContentWebUIControllerFactory::GetInstance());
512 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:OnlineStateObserver");
513 online_state_observer_.reset(new BrowserOnlineStateObserver);
517 system_stats_monitor_.reset(new base::debug::TraceEventSystemStatsMonitor(
518 base::ThreadTaskRunnerHandle::Get()));
520 #endif // !defined(OS_IOS)
522 #if defined(OS_WIN)
523 system_message_window_.reset(new SystemMessageWindowWin);
524 #endif
526 if (parts_)
527 parts_->PostMainMessageLoopStart();
529 #if !defined(OS_IOS)
530 // Start tracing to a file if needed. Only do this after starting the main
531 // message loop to avoid calling MessagePumpForUI::ScheduleWork() before
532 // MessagePumpForUI::Start() as it will crash the browser.
533 if (is_tracing_startup_) {
534 TRACE_EVENT0("startup", "BrowserMainLoop::InitStartupTracing");
535 InitStartupTracing(parsed_command_line_);
537 #endif // !defined(OS_IOS)
539 #if defined(OS_ANDROID)
541 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SurfaceTextureManager");
542 SurfaceTextureManager::InitInstance(new BrowserSurfaceTextureManager);
546 TRACE_EVENT0("startup",
547 "BrowserMainLoop::Subsystem:ScreenOrientationProvider");
548 screen_orientation_delegate_.reset(
549 new ScreenOrientationDelegateAndroid());
550 ScreenOrientationProvider::SetDelegate(screen_orientation_delegate_.get());
552 #endif
554 if (parsed_command_line_.HasSwitch(switches::kMemoryMetrics)) {
555 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MemoryObserver");
556 memory_observer_.reset(new MemoryObserver());
557 base::MessageLoop::current()->AddTaskObserver(memory_observer_.get());
560 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
561 trace_memory_controller_.reset(new base::debug::TraceMemoryController(
562 base::MessageLoop::current()->message_loop_proxy(),
563 ::HeapProfilerWithPseudoStackStart,
564 ::HeapProfilerStop,
565 ::GetHeapProfile));
566 #endif
569 int BrowserMainLoop::PreCreateThreads() {
570 if (parts_) {
571 TRACE_EVENT0("startup",
572 "BrowserMainLoop::CreateThreads:PreCreateThreads");
573 result_code_ = parts_->PreCreateThreads();
576 #if defined(ENABLE_PLUGINS)
577 // Prior to any processing happening on the io thread, we create the
578 // plugin service as it is predominantly used from the io thread,
579 // but must be created on the main thread. The service ctor is
580 // inexpensive and does not invoke the io_thread() accessor.
582 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads:PluginService");
583 PluginService::GetInstance()->Init();
585 #endif
587 #if !defined(OS_IOS) && (!defined(GOOGLE_CHROME_BUILD) || defined(OS_ANDROID))
588 // Single-process is an unsupported and not fully tested mode, so
589 // don't enable it for official Chrome builds (except on Android).
590 if (parsed_command_line_.HasSwitch(switches::kSingleProcess))
591 RenderProcessHost::SetRunRendererInProcess(true);
592 #endif
593 return result_code_;
596 void BrowserMainLoop::CreateStartupTasks() {
597 TRACE_EVENT0("startup", "BrowserMainLoop::CreateStartupTasks");
599 // First time through, we really want to create all the tasks
600 if (!startup_task_runner_.get()) {
601 #if defined(OS_ANDROID)
602 startup_task_runner_ = make_scoped_ptr(new StartupTaskRunner(
603 base::Bind(&BrowserStartupComplete),
604 base::MessageLoop::current()->message_loop_proxy()));
605 #else
606 startup_task_runner_ = make_scoped_ptr(new StartupTaskRunner(
607 base::Callback<void(int)>(),
608 base::MessageLoop::current()->message_loop_proxy()));
609 #endif
610 StartupTask pre_create_threads =
611 base::Bind(&BrowserMainLoop::PreCreateThreads, base::Unretained(this));
612 startup_task_runner_->AddTask(pre_create_threads);
614 StartupTask create_threads =
615 base::Bind(&BrowserMainLoop::CreateThreads, base::Unretained(this));
616 startup_task_runner_->AddTask(create_threads);
618 StartupTask browser_thread_started = base::Bind(
619 &BrowserMainLoop::BrowserThreadsStarted, base::Unretained(this));
620 startup_task_runner_->AddTask(browser_thread_started);
622 StartupTask pre_main_message_loop_run = base::Bind(
623 &BrowserMainLoop::PreMainMessageLoopRun, base::Unretained(this));
624 startup_task_runner_->AddTask(pre_main_message_loop_run);
626 #if defined(OS_ANDROID)
627 if (BrowserMayStartAsynchronously()) {
628 startup_task_runner_->StartRunningTasksAsync();
630 #endif
632 #if defined(OS_ANDROID)
633 if (!BrowserMayStartAsynchronously()) {
634 // A second request for asynchronous startup can be ignored, so
635 // StartupRunningTasksAsync is only called first time through. If, however,
636 // this is a request for synchronous startup then it must override any
637 // previous call for async startup, so we call RunAllTasksNow()
638 // unconditionally.
639 startup_task_runner_->RunAllTasksNow();
641 #else
642 startup_task_runner_->RunAllTasksNow();
643 #endif
646 int BrowserMainLoop::CreateThreads() {
647 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads");
649 base::Thread::Options io_message_loop_options;
650 io_message_loop_options.message_loop_type = base::MessageLoop::TYPE_IO;
651 base::Thread::Options ui_message_loop_options;
652 ui_message_loop_options.message_loop_type = base::MessageLoop::TYPE_UI;
654 // Start threads in the order they occur in the BrowserThread::ID
655 // enumeration, except for BrowserThread::UI which is the main
656 // thread.
658 // Must be size_t so we can increment it.
659 for (size_t thread_id = BrowserThread::UI + 1;
660 thread_id < BrowserThread::ID_COUNT;
661 ++thread_id) {
662 scoped_ptr<BrowserProcessSubThread>* thread_to_start = NULL;
663 base::Thread::Options options;
665 switch (thread_id) {
666 case BrowserThread::DB:
667 TRACE_EVENT_BEGIN1("startup",
668 "BrowserMainLoop::CreateThreads:start",
669 "Thread", "BrowserThread::DB");
670 thread_to_start = &db_thread_;
671 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
672 break;
673 case BrowserThread::FILE_USER_BLOCKING:
674 TRACE_EVENT_BEGIN1("startup",
675 "BrowserMainLoop::CreateThreads:start",
676 "Thread", "BrowserThread::FILE_USER_BLOCKING");
677 thread_to_start = &file_user_blocking_thread_;
678 break;
679 case BrowserThread::FILE:
680 TRACE_EVENT_BEGIN1("startup",
681 "BrowserMainLoop::CreateThreads:start",
682 "Thread", "BrowserThread::FILE");
683 thread_to_start = &file_thread_;
684 #if defined(OS_WIN)
685 // On Windows, the FILE thread needs to be have a UI message loop
686 // which pumps messages in such a way that Google Update can
687 // communicate back to us.
688 options = ui_message_loop_options;
689 #else
690 options = io_message_loop_options;
691 #endif
692 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
693 break;
694 case BrowserThread::PROCESS_LAUNCHER:
695 TRACE_EVENT_BEGIN1("startup",
696 "BrowserMainLoop::CreateThreads:start",
697 "Thread", "BrowserThread::PROCESS_LAUNCHER");
698 thread_to_start = &process_launcher_thread_;
699 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
700 break;
701 case BrowserThread::CACHE:
702 TRACE_EVENT_BEGIN1("startup",
703 "BrowserMainLoop::CreateThreads:start",
704 "Thread", "BrowserThread::CACHE");
705 thread_to_start = &cache_thread_;
706 options = io_message_loop_options;
707 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
708 break;
709 case BrowserThread::IO:
710 TRACE_EVENT_BEGIN1("startup",
711 "BrowserMainLoop::CreateThreads:start",
712 "Thread", "BrowserThread::IO");
713 thread_to_start = &io_thread_;
714 options = io_message_loop_options;
715 break;
716 case BrowserThread::UI:
717 case BrowserThread::ID_COUNT:
718 default:
719 NOTREACHED();
720 break;
723 BrowserThread::ID id = static_cast<BrowserThread::ID>(thread_id);
725 if (thread_to_start) {
726 (*thread_to_start).reset(new BrowserProcessSubThread(id));
727 if (!(*thread_to_start)->StartWithOptions(options)) {
728 LOG(FATAL) << "Failed to start the browser thread: id == " << id;
730 } else {
731 NOTREACHED();
734 TRACE_EVENT_END0("startup", "BrowserMainLoop::CreateThreads:start");
736 created_threads_ = true;
737 return result_code_;
740 int BrowserMainLoop::PreMainMessageLoopRun() {
741 if (parts_) {
742 TRACE_EVENT0("startup",
743 "BrowserMainLoop::CreateThreads:PreMainMessageLoopRun");
744 parts_->PreMainMessageLoopRun();
747 // If the UI thread blocks, the whole UI is unresponsive.
748 // Do not allow disk IO from the UI thread.
749 base::ThreadRestrictions::SetIOAllowed(false);
750 base::ThreadRestrictions::DisallowWaiting();
751 return result_code_;
754 void BrowserMainLoop::RunMainMessageLoopParts() {
755 TRACE_EVENT_BEGIN_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
757 bool ran_main_loop = false;
758 if (parts_)
759 ran_main_loop = parts_->MainMessageLoopRun(&result_code_);
761 if (!ran_main_loop)
762 MainMessageLoopRun();
764 TRACE_EVENT_END_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
767 void BrowserMainLoop::ShutdownThreadsAndCleanUp() {
768 if (!created_threads_) {
769 // Called early, nothing to do
770 return;
772 TRACE_EVENT0("shutdown", "BrowserMainLoop::ShutdownThreadsAndCleanUp");
774 // Teardown may start in PostMainMessageLoopRun, and during teardown we
775 // need to be able to perform IO.
776 base::ThreadRestrictions::SetIOAllowed(true);
777 BrowserThread::PostTask(
778 BrowserThread::IO, FROM_HERE,
779 base::Bind(base::IgnoreResult(&base::ThreadRestrictions::SetIOAllowed),
780 true));
782 #if !defined(OS_IOS)
783 if (RenderProcessHost::run_renderer_in_process())
784 RenderProcessHostImpl::ShutDownInProcessRenderer();
785 #endif
787 if (parts_) {
788 TRACE_EVENT0("shutdown",
789 "BrowserMainLoop::Subsystem:PostMainMessageLoopRun");
790 parts_->PostMainMessageLoopRun();
793 trace_memory_controller_.reset();
794 system_stats_monitor_.reset();
796 #if !defined(OS_IOS)
797 // Destroying the GpuProcessHostUIShims on the UI thread posts a task to
798 // delete related objects on the GPU thread. This must be done before
799 // stopping the GPU thread. The GPU thread will close IPC channels to renderer
800 // processes so this has to happen before stopping the IO thread.
802 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUProcessHostShim");
803 GpuProcessHostUIShim::DestroyAll();
805 // Cancel pending requests and prevent new requests.
806 if (resource_dispatcher_host_) {
807 TRACE_EVENT0("shutdown",
808 "BrowserMainLoop::Subsystem:ResourceDispatcherHost");
809 resource_dispatcher_host_.get()->Shutdown();
812 #if defined(USE_AURA) || defined(OS_MACOSX)
813 if (ShouldInitializeBrowserGpuChannelAndTransportSurface()) {
814 TRACE_EVENT0("shutdown",
815 "BrowserMainLoop::Subsystem:ImageTransportFactory");
816 ImageTransportFactory::Terminate();
818 #endif
820 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
821 ZygoteHostImpl::GetInstance()->TearDownAfterLastChild();
822 #endif // defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
824 // The device monitors are using |system_monitor_| as dependency, so delete
825 // them before |system_monitor_| goes away.
826 // On Mac and windows, the monitor needs to be destroyed on the same thread
827 // as they were created. On Linux, the monitor will be deleted when IO thread
828 // goes away.
829 #if defined(OS_WIN)
830 system_message_window_.reset();
831 #elif defined(OS_MACOSX)
832 device_monitor_mac_.reset();
833 #endif
834 #endif // !defined(OS_IOS)
836 // Must be size_t so we can subtract from it.
837 for (size_t thread_id = BrowserThread::ID_COUNT - 1;
838 thread_id >= (BrowserThread::UI + 1);
839 --thread_id) {
840 // Find the thread object we want to stop. Looping over all valid
841 // BrowserThread IDs and DCHECKing on a missing case in the switch
842 // statement helps avoid a mismatch between this code and the
843 // BrowserThread::ID enumeration.
845 // The destruction order is the reverse order of occurrence in the
846 // BrowserThread::ID list. The rationale for the order is as
847 // follows (need to be filled in a bit):
850 // - The IO thread is the only user of the CACHE thread.
852 // - The PROCESS_LAUNCHER thread must be stopped after IO in case
853 // the IO thread posted a task to terminate a process on the
854 // process launcher thread.
856 // - (Not sure why DB stops last.)
857 switch (thread_id) {
858 case BrowserThread::DB: {
859 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DBThread");
860 ResetThread_DB(db_thread_.Pass());
861 break;
863 case BrowserThread::FILE: {
864 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:FileThread");
865 #if !defined(OS_IOS)
866 // Clean up state that lives on or uses the file_thread_ before
867 // it goes away.
868 if (resource_dispatcher_host_)
869 resource_dispatcher_host_.get()->save_file_manager()->Shutdown();
870 #endif // !defined(OS_IOS)
871 ResetThread_FILE(file_thread_.Pass());
872 break;
874 case BrowserThread::FILE_USER_BLOCKING: {
875 TRACE_EVENT0("shutdown",
876 "BrowserMainLoop::Subsystem:FileUserBlockingThread");
877 ResetThread_FILE_USER_BLOCKING(file_user_blocking_thread_.Pass());
878 break;
880 case BrowserThread::PROCESS_LAUNCHER: {
881 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:LauncherThread");
882 ResetThread_PROCESS_LAUNCHER(process_launcher_thread_.Pass());
883 break;
885 case BrowserThread::CACHE: {
886 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:CacheThread");
887 ResetThread_CACHE(cache_thread_.Pass());
888 break;
890 case BrowserThread::IO: {
891 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IOThread");
892 ResetThread_IO(io_thread_.Pass());
893 break;
895 case BrowserThread::UI:
896 case BrowserThread::ID_COUNT:
897 default:
898 NOTREACHED();
899 break;
903 #if !defined(OS_IOS)
905 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IndexedDBThread");
906 ResetThread_IndexedDb(indexed_db_thread_.Pass());
908 #endif
910 // Close the blocking I/O pool after the other threads. Other threads such
911 // as the I/O thread may need to schedule work like closing files or flushing
912 // data during shutdown, so the blocking pool needs to be available. There
913 // may also be slow operations pending that will blcok shutdown, so closing
914 // it here (which will block until required operations are complete) gives
915 // more head start for those operations to finish.
917 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:ThreadPool");
918 BrowserThreadImpl::ShutdownThreadPool();
921 #if !defined(OS_IOS)
922 // Must happen after the IO thread is shutdown since this may be accessed from
923 // it.
925 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUChannelFactory");
926 if (BrowserGpuChannelHostFactory::instance())
927 BrowserGpuChannelHostFactory::Terminate();
930 // Must happen after the I/O thread is shutdown since this class lives on the
931 // I/O thread and isn't threadsafe.
933 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GamepadService");
934 GamepadService::GetInstance()->Terminate();
937 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:SensorService");
938 DeviceInertialSensorService::GetInstance()->Shutdown();
941 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:BatteryStatusService");
942 BatteryStatusService::GetInstance()->Shutdown();
945 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DeleteDataSources");
946 URLDataManager::DeleteDataSources();
948 #endif // !defined(OS_IOS)
950 if (parts_) {
951 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:PostDestroyThreads");
952 parts_->PostDestroyThreads();
956 void BrowserMainLoop::StopStartupTracingTimer() {
957 startup_trace_timer_.Stop();
960 void BrowserMainLoop::InitializeMainThread() {
961 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeMainThread");
962 const char* kThreadName = "CrBrowserMain";
963 base::PlatformThread::SetName(kThreadName);
964 if (main_message_loop_)
965 main_message_loop_->set_thread_name(kThreadName);
967 // Register the main thread by instantiating it, but don't call any methods.
968 main_thread_.reset(
969 new BrowserThreadImpl(BrowserThread::UI, base::MessageLoop::current()));
972 int BrowserMainLoop::BrowserThreadsStarted() {
973 TRACE_EVENT0("startup", "BrowserMainLoop::BrowserThreadsStarted");
975 #if !defined(OS_IOS)
976 indexed_db_thread_.reset(new base::Thread("IndexedDB"));
977 indexed_db_thread_->Start();
978 #endif
980 #if defined(OS_ANDROID)
981 // Up the priority of anything that touches with display tasks
982 // (this thread is UI thread, and io_thread_ is for IPCs).
983 io_thread_->SetPriority(base::kThreadPriority_Display);
984 base::PlatformThread::SetThreadPriority(
985 base::PlatformThread::CurrentHandle(),
986 base::kThreadPriority_Display);
987 #endif
989 #if !defined(OS_IOS)
990 HistogramSynchronizer::GetInstance();
992 bool initialize_gpu_data_manager = true;
993 #if defined(OS_ANDROID)
994 // On Android, GLSurface::InitializeOneOff() must be called before initalizing
995 // the GpuDataManagerImpl as it uses the GL bindings. crbug.com/326295
996 if (!gfx::GLSurface::InitializeOneOff()) {
997 LOG(ERROR) << "GLSurface::InitializeOneOff failed";
998 initialize_gpu_data_manager = false;
1000 #endif
1002 // Initialize the GpuDataManager before we set up the MessageLoops because
1003 // otherwise we'll trigger the assertion about doing IO on the UI thread.
1004 if (initialize_gpu_data_manager)
1005 GpuDataManagerImpl::GetInstance()->Initialize();
1007 bool always_uses_gpu = true;
1008 bool established_gpu_channel = false;
1009 #if defined(USE_AURA) || defined(OS_MACOSX)
1010 if (ShouldInitializeBrowserGpuChannelAndTransportSurface()) {
1011 established_gpu_channel = true;
1012 if (!GpuDataManagerImpl::GetInstance()->CanUseGpuBrowserCompositor()) {
1013 established_gpu_channel = always_uses_gpu = false;
1015 BrowserGpuChannelHostFactory::Initialize(established_gpu_channel);
1016 ImageTransportFactory::Initialize();
1017 #if defined(USE_AURA)
1018 if (aura::Env::GetInstance()) {
1019 aura::Env::GetInstance()->set_context_factory(GetContextFactory());
1021 #endif
1023 #elif defined(OS_ANDROID)
1024 established_gpu_channel = true;
1025 BrowserGpuChannelHostFactory::Initialize(established_gpu_channel);
1026 #endif
1028 #if defined(OS_LINUX) && defined(USE_UDEV)
1029 device_monitor_linux_.reset(new DeviceMonitorLinux());
1030 #elif defined(OS_MACOSX)
1031 device_monitor_mac_.reset(new DeviceMonitorMac());
1032 #endif
1034 // RDH needs the IO thread to be created
1036 TRACE_EVENT0("startup",
1037 "BrowserMainLoop::BrowserThreadsStarted:InitResourceDispatcherHost");
1038 resource_dispatcher_host_.reset(new ResourceDispatcherHostImpl());
1041 // MediaStreamManager needs the IO thread to be created.
1043 TRACE_EVENT0("startup",
1044 "BrowserMainLoop::BrowserThreadsStarted:InitMediaStreamManager");
1045 media_stream_manager_.reset(new MediaStreamManager(audio_manager_.get()));
1049 TRACE_EVENT0("startup",
1050 "BrowserMainLoop::BrowserThreadsStarted:InitSpeechRecognition");
1051 speech_recognition_manager_.reset(new SpeechRecognitionManagerImpl(
1052 audio_manager_.get(), media_stream_manager_.get()));
1056 TRACE_EVENT0(
1057 "startup",
1058 "BrowserMainLoop::BrowserThreadsStarted::InitUserInputMonitor");
1059 user_input_monitor_ = media::UserInputMonitor::Create(
1060 io_thread_->message_loop_proxy(), main_thread_->message_loop_proxy());
1064 TRACE_EVENT0("startup",
1065 "BrowserMainLoop::BrowserThreadsStarted::TimeZoneMonitor");
1066 time_zone_monitor_ = TimeZoneMonitor::Create();
1069 // Alert the clipboard class to which threads are allowed to access the
1070 // clipboard:
1071 std::vector<base::PlatformThreadId> allowed_clipboard_threads;
1072 // The current thread is the UI thread.
1073 allowed_clipboard_threads.push_back(base::PlatformThread::CurrentId());
1074 #if defined(OS_WIN)
1075 // On Windows, clipboards are also used on the File or IO threads.
1076 allowed_clipboard_threads.push_back(file_thread_->thread_id());
1077 allowed_clipboard_threads.push_back(io_thread_->thread_id());
1078 #endif
1079 ui::Clipboard::SetAllowedThreads(allowed_clipboard_threads);
1081 // When running the GPU thread in-process, avoid optimistically starting it
1082 // since creating the GPU thread races against creation of the one-and-only
1083 // ChildProcess instance which is created by the renderer thread.
1084 if (GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL) &&
1085 !established_gpu_channel &&
1086 always_uses_gpu &&
1087 !parsed_command_line_.HasSwitch(switches::kSingleProcess) &&
1088 !parsed_command_line_.HasSwitch(switches::kInProcessGPU)) {
1089 TRACE_EVENT_INSTANT0("gpu", "Post task to launch GPU process",
1090 TRACE_EVENT_SCOPE_THREAD);
1091 BrowserThread::PostTask(
1092 BrowserThread::IO, FROM_HERE, base::Bind(
1093 base::IgnoreResult(&GpuProcessHost::Get),
1094 GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED,
1095 CAUSE_FOR_GPU_LAUNCH_BROWSER_STARTUP));
1098 #if defined(OS_MACOSX)
1099 ThemeHelperMac::GetInstance();
1100 SystemHotkeyHelperMac::GetInstance()->DeferredLoadSystemHotkeys();
1101 if (ShouldEnableBootstrapSandbox()) {
1102 TRACE_EVENT0("startup",
1103 "BrowserMainLoop::BrowserThreadsStarted:BootstrapSandbox");
1104 CHECK(GetBootstrapSandbox());
1106 #endif // defined(OS_MACOSX)
1108 #endif // !defined(OS_IOS)
1110 return result_code_;
1113 bool BrowserMainLoop::InitializeToolkit() {
1114 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeToolkit");
1115 // TODO(evan): this function is rather subtle, due to the variety
1116 // of intersecting ifdefs we have. To keep it easy to follow, there
1117 // are no #else branches on any #ifs.
1118 // TODO(stevenjb): Move platform specific code into platform specific Parts
1119 // (Need to add InitializeToolkit stage to BrowserParts).
1120 // See also GTK setup in EarlyInitialization, above, and associated comments.
1122 #if defined(OS_WIN)
1123 // Init common control sex.
1124 INITCOMMONCONTROLSEX config;
1125 config.dwSize = sizeof(config);
1126 config.dwICC = ICC_WIN95_CLASSES;
1127 if (!InitCommonControlsEx(&config))
1128 PLOG(FATAL);
1129 #endif
1131 #if defined(USE_AURA)
1133 #if defined(USE_X11)
1134 if (!gfx::GetXDisplay())
1135 return false;
1136 #endif
1138 // Env creates the compositor. Aura widgets need the compositor to be created
1139 // before they can be initialized by the browser.
1140 aura::Env::CreateInstance(true);
1141 #endif // defined(USE_AURA)
1143 if (parts_)
1144 parts_->ToolkitInitialized();
1146 return true;
1149 void BrowserMainLoop::MainMessageLoopRun() {
1150 #if defined(OS_ANDROID)
1151 // Android's main message loop is the Java message loop.
1152 NOTREACHED();
1153 #else
1154 DCHECK(base::MessageLoopForUI::IsCurrent());
1155 if (parameters_.ui_task)
1156 base::MessageLoopForUI::current()->PostTask(FROM_HERE,
1157 *parameters_.ui_task);
1159 base::RunLoop run_loop;
1160 run_loop.Run();
1161 #endif
1164 base::FilePath BrowserMainLoop::GetStartupTraceFileName(
1165 const base::CommandLine& command_line) const {
1166 base::FilePath trace_file = command_line.GetSwitchValuePath(
1167 switches::kTraceStartupFile);
1168 // trace_file = "none" means that startup events will show up for the next
1169 // begin/end tracing (via about:tracing or AutomationProxy::BeginTracing/
1170 // EndTracing, for example).
1171 if (trace_file == base::FilePath().AppendASCII("none"))
1172 return trace_file;
1174 if (trace_file.empty()) {
1175 #if defined(OS_ANDROID)
1176 TracingControllerAndroid::GenerateTracingFilePath(&trace_file);
1177 #else
1178 // Default to saving the startup trace into the current dir.
1179 trace_file = base::FilePath().AppendASCII("chrometrace.log");
1180 #endif
1183 return trace_file;
1186 void BrowserMainLoop::InitStartupTracing(
1187 const base::CommandLine& command_line) {
1188 DCHECK(is_tracing_startup_);
1190 startup_trace_file_ = GetStartupTraceFileName(parsed_command_line_);
1192 std::string delay_str = command_line.GetSwitchValueASCII(
1193 switches::kTraceStartupDuration);
1194 int delay_secs = 5;
1195 if (!delay_str.empty() && !base::StringToInt(delay_str, &delay_secs)) {
1196 DLOG(WARNING) << "Could not parse --" << switches::kTraceStartupDuration
1197 << "=" << delay_str << " defaulting to 5 (secs)";
1198 delay_secs = 5;
1201 startup_trace_timer_.Start(FROM_HERE,
1202 base::TimeDelta::FromSeconds(delay_secs),
1203 this,
1204 &BrowserMainLoop::EndStartupTracing);
1207 void BrowserMainLoop::EndStartupTracing() {
1208 is_tracing_startup_ = false;
1209 TracingController::GetInstance()->DisableRecording(
1210 TracingController::CreateFileSink(
1211 startup_trace_file_,
1212 base::Bind(OnStoppedStartupTracing, startup_trace_file_)));
1215 } // namespace content