Revert of aura: Require explicit ownership of the Env instance. (patchset #7 id:12000...
[chromium-blink-merge.git] / content / browser / browser_main_loop.cc
blobe5ee0cfc3ae607054efc2437abbda88c43ac6914
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/location.h"
10 #include "base/logging.h"
11 #include "base/memory/memory_pressure_monitor.h"
12 #include "base/metrics/field_trial.h"
13 #include "base/metrics/histogram.h"
14 #include "base/pending_task.h"
15 #include "base/power_monitor/power_monitor.h"
16 #include "base/power_monitor/power_monitor_device_source.h"
17 #include "base/process/process_metrics.h"
18 #include "base/profiler/scoped_profile.h"
19 #include "base/run_loop.h"
20 #include "base/single_thread_task_runner.h"
21 #include "base/strings/string_number_conversions.h"
22 #include "base/strings/string_split.h"
23 #include "base/system_monitor/system_monitor.h"
24 #include "base/thread_task_runner_handle.h"
25 #include "base/threading/thread_restrictions.h"
26 #include "base/timer/hi_res_timer_manager.h"
27 #include "base/trace_event/memory_dump_manager.h"
28 #include "base/trace_event/trace_event.h"
29 #include "content/browser/browser_thread_impl.h"
30 #include "content/browser/device_sensors/device_inertial_sensor_service.h"
31 #include "content/browser/dom_storage/dom_storage_area.h"
32 #include "content/browser/download/save_file_manager.h"
33 #include "content/browser/gamepad/gamepad_service.h"
34 #include "content/browser/gpu/browser_gpu_channel_host_factory.h"
35 #include "content/browser/gpu/browser_gpu_memory_buffer_manager.h"
36 #include "content/browser/gpu/compositor_util.h"
37 #include "content/browser/gpu/gpu_data_manager_impl.h"
38 #include "content/browser/gpu/gpu_process_host.h"
39 #include "content/browser/gpu/gpu_process_host_ui_shim.h"
40 #include "content/browser/histogram_synchronizer.h"
41 #include "content/browser/loader/resource_dispatcher_host_impl.h"
42 #include "content/browser/media/media_internals.h"
43 #include "content/browser/mojo/mojo_shell_context.h"
44 #include "content/browser/net/browser_online_state_observer.h"
45 #include "content/browser/renderer_host/media/media_stream_manager.h"
46 #include "content/browser/speech/speech_recognition_manager_impl.h"
47 #include "content/browser/startup_task_runner.h"
48 #include "content/browser/time_zone_monitor.h"
49 #include "content/browser/webui/content_web_ui_controller_factory.h"
50 #include "content/browser/webui/url_data_manager.h"
51 #include "content/common/content_switches_internal.h"
52 #include "content/common/host_discardable_shared_memory_manager.h"
53 #include "content/common/host_shared_bitmap_manager.h"
54 #include "content/public/browser/browser_main_parts.h"
55 #include "content/public/browser/content_browser_client.h"
56 #include "content/public/browser/render_process_host.h"
57 #include "content/public/browser/tracing_controller.h"
58 #include "content/public/common/content_switches.h"
59 #include "content/public/common/main_function_params.h"
60 #include "content/public/common/result_codes.h"
61 #include "crypto/nss_util.h"
62 #include "device/battery/battery_status_service.h"
63 #include "media/audio/audio_manager.h"
64 #include "media/base/media.h"
65 #include "media/base/user_input_monitor.h"
66 #include "media/midi/midi_manager.h"
67 #include "net/base/network_change_notifier.h"
68 #include "net/socket/client_socket_factory.h"
69 #include "net/ssl/ssl_config_service.h"
70 #include "skia/ext/skia_memory_dump_provider.h"
71 #include "ui/base/clipboard/clipboard.h"
73 #if defined(USE_AURA) || (defined(OS_MACOSX) && !defined(OS_IOS))
74 #include "content/browser/compositor/image_transport_factory.h"
75 #endif
77 #if defined(USE_AURA)
78 #include "content/public/browser/context_factory.h"
79 #include "ui/aura/env.h"
80 #endif
82 #if !defined(OS_IOS)
83 #include "content/browser/renderer_host/render_process_host_impl.h"
84 #endif
86 #if defined(OS_ANDROID)
87 #include "base/android/jni_android.h"
88 #include "content/browser/android/browser_startup_controller.h"
89 #include "content/browser/android/browser_surface_texture_manager.h"
90 #include "content/browser/android/in_process_surface_texture_manager.h"
91 #include "content/browser/android/tracing_controller_android.h"
92 #include "content/browser/screen_orientation/screen_orientation_delegate_android.h"
93 #include "content/public/browser/screen_orientation_provider.h"
94 #include "ui/gl/gl_surface.h"
95 #endif
97 #if defined(OS_MACOSX)
98 #include "media/base/mac/avfoundation_glue.h"
99 #endif
101 #if defined(OS_MACOSX) && !defined(OS_IOS)
102 #include "base/memory/memory_pressure_monitor_mac.h"
103 #include "content/browser/bootstrap_sandbox_mac.h"
104 #include "content/browser/browser_io_surface_manager_mac.h"
105 #include "content/browser/cocoa/system_hotkey_helper_mac.h"
106 #include "content/browser/compositor/browser_compositor_view_mac.h"
107 #include "content/browser/in_process_io_surface_manager_mac.h"
108 #include "content/browser/theme_helper_mac.h"
109 #endif
111 #if defined(USE_OZONE)
112 #include "ui/ozone/public/client_native_pixmap_factory.h"
113 #endif
115 #if defined(OS_WIN)
116 #include <windows.h>
117 #include <commctrl.h>
118 #include <shellapi.h>
120 #include "base/memory/memory_pressure_monitor_win.h"
121 #include "content/browser/system_message_window_win.h"
122 #include "content/common/sandbox_win.h"
123 #include "net/base/winsock_init.h"
124 #include "ui/base/l10n/l10n_util_win.h"
125 #endif
127 #if defined(OS_CHROMEOS)
128 #include "base/memory/memory_pressure_monitor_chromeos.h"
129 #include "chromeos/chromeos_switches.h"
130 #endif
132 #if defined(USE_GLIB)
133 #include <glib-object.h>
134 #endif
136 #if defined(OS_LINUX) && defined(USE_UDEV)
137 #include "content/browser/device_monitor_udev.h"
138 #elif defined(OS_MACOSX) && !defined(OS_IOS)
139 #include "content/browser/device_monitor_mac.h"
140 #endif
142 #if defined(OS_POSIX) && !defined(OS_MACOSX)
143 #include "content/browser/renderer_host/render_sandbox_host_linux.h"
144 #include "content/browser/zygote_host/zygote_host_impl_linux.h"
145 #include "sandbox/linux/suid/client/setuid_sandbox_host.h"
146 #endif
148 #if defined(ENABLE_PLUGINS)
149 #include "content/browser/plugin_service_impl.h"
150 #endif
152 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
153 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
154 #endif
156 #if defined(USE_X11)
157 #include "ui/gfx/x/x11_connection.h"
158 #include "ui/gfx/x/x11_types.h"
159 #endif
161 // One of the linux specific headers defines this as a macro.
162 #ifdef DestroyAll
163 #undef DestroyAll
164 #endif
166 namespace content {
167 namespace {
169 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
170 void SetupSandbox(const base::CommandLine& parsed_command_line) {
171 TRACE_EVENT0("startup", "SetupSandbox");
172 base::FilePath sandbox_binary;
174 scoped_ptr<sandbox::SetuidSandboxHost> setuid_sandbox_host(
175 sandbox::SetuidSandboxHost::Create());
177 const bool want_setuid_sandbox =
178 !parsed_command_line.HasSwitch(switches::kNoSandbox) &&
179 !parsed_command_line.HasSwitch(switches::kDisableSetuidSandbox) &&
180 !setuid_sandbox_host->IsDisabledViaEnvironment();
182 static const char no_suid_error[] =
183 "Running without the SUID sandbox! See "
184 "https://code.google.com/p/chromium/wiki/LinuxSUIDSandboxDevelopment "
185 "for more information on developing with the sandbox on.";
186 if (want_setuid_sandbox) {
187 sandbox_binary = setuid_sandbox_host->GetSandboxBinaryPath();
188 if (sandbox_binary.empty()) {
189 // This needs to be fatal. Talk to security@chromium.org if you feel
190 // otherwise.
191 LOG(FATAL) << no_suid_error;
193 } else {
194 LOG(ERROR) << no_suid_error;
197 // Tickle the sandbox host and zygote host so they fork now.
198 RenderSandboxHostLinux::GetInstance()->Init();
199 ZygoteHostImpl::GetInstance()->Init(sandbox_binary.value());
201 #endif
203 #if defined(USE_GLIB)
204 static void GLibLogHandler(const gchar* log_domain,
205 GLogLevelFlags log_level,
206 const gchar* message,
207 gpointer userdata) {
208 if (!log_domain)
209 log_domain = "<unknown>";
210 if (!message)
211 message = "<no message>";
213 if (strstr(message, "Unable to retrieve the file info for")) {
214 LOG(ERROR) << "GTK File code error: " << message;
215 } else if (strstr(message, "Could not find the icon") &&
216 strstr(log_domain, "Gtk")) {
217 LOG(ERROR) << "GTK icon error: " << message;
218 } else if (strstr(message, "Theme file for default has no") ||
219 strstr(message, "Theme directory") ||
220 strstr(message, "theme pixmap") ||
221 strstr(message, "locate theme engine")) {
222 LOG(ERROR) << "GTK theme error: " << message;
223 } else if (strstr(message, "Unable to create Ubuntu Menu Proxy") &&
224 strstr(log_domain, "<unknown>")) {
225 LOG(ERROR) << "GTK menu proxy create failed";
226 } else if (strstr(message, "Out of memory") &&
227 strstr(log_domain, "<unknown>")) {
228 LOG(ERROR) << "DBus call timeout or out of memory: "
229 << "http://crosbug.com/15496";
230 } else if (strstr(message, "Could not connect: Connection refused") &&
231 strstr(log_domain, "<unknown>")) {
232 LOG(ERROR) << "DConf settings backend could not connect to session bus: "
233 << "http://crbug.com/179797";
234 } else if (strstr(message, "Attempting to store changes into") ||
235 strstr(message, "Attempting to set the permissions of")) {
236 LOG(ERROR) << message << " (http://bugs.chromium.org/161366)";
237 } else if (strstr(message, "drawable is not a native X11 window")) {
238 LOG(ERROR) << message << " (http://bugs.chromium.org/329991)";
239 } else if (strstr(message, "Cannot do system-bus activation with no user")) {
240 LOG(ERROR) << message << " (http://crbug.com/431005)";
241 } else {
242 LOG(DFATAL) << log_domain << ": " << message;
246 static void SetUpGLibLogHandler() {
247 // Register GLib-handled assertions to go through our logging system.
248 const char* kLogDomains[] = { NULL, "Gtk", "Gdk", "GLib", "GLib-GObject" };
249 for (size_t i = 0; i < arraysize(kLogDomains); i++) {
250 g_log_set_handler(kLogDomains[i],
251 static_cast<GLogLevelFlags>(G_LOG_FLAG_RECURSION |
252 G_LOG_FLAG_FATAL |
253 G_LOG_LEVEL_ERROR |
254 G_LOG_LEVEL_CRITICAL |
255 G_LOG_LEVEL_WARNING),
256 GLibLogHandler,
257 NULL);
260 #endif
262 void OnStoppedStartupTracing(const base::FilePath& trace_file) {
263 VLOG(0) << "Completed startup tracing to " << trace_file.value();
266 // Disable optimizations for this block of functions so the compiler doesn't
267 // merge them all together. This makes it possible to tell what thread was
268 // unresponsive by inspecting the callstack.
269 MSVC_DISABLE_OPTIMIZE()
270 MSVC_PUSH_DISABLE_WARNING(4748)
272 NOINLINE void ResetThread_DB(scoped_ptr<BrowserProcessSubThread> thread) {
273 volatile int inhibit_comdat = __LINE__;
274 ALLOW_UNUSED_LOCAL(inhibit_comdat);
275 thread.reset();
278 NOINLINE void ResetThread_FILE(scoped_ptr<BrowserProcessSubThread> thread) {
279 volatile int inhibit_comdat = __LINE__;
280 ALLOW_UNUSED_LOCAL(inhibit_comdat);
281 thread.reset();
284 NOINLINE void ResetThread_FILE_USER_BLOCKING(
285 scoped_ptr<BrowserProcessSubThread> thread) {
286 volatile int inhibit_comdat = __LINE__;
287 ALLOW_UNUSED_LOCAL(inhibit_comdat);
288 thread.reset();
291 NOINLINE void ResetThread_PROCESS_LAUNCHER(
292 scoped_ptr<BrowserProcessSubThread> thread) {
293 volatile int inhibit_comdat = __LINE__;
294 ALLOW_UNUSED_LOCAL(inhibit_comdat);
295 thread.reset();
298 NOINLINE void ResetThread_CACHE(scoped_ptr<BrowserProcessSubThread> thread) {
299 volatile int inhibit_comdat = __LINE__;
300 ALLOW_UNUSED_LOCAL(inhibit_comdat);
301 thread.reset();
304 NOINLINE void ResetThread_IO(scoped_ptr<BrowserProcessSubThread> thread) {
305 volatile int inhibit_comdat = __LINE__;
306 ALLOW_UNUSED_LOCAL(inhibit_comdat);
307 thread.reset();
310 #if !defined(OS_IOS)
311 NOINLINE void ResetThread_IndexedDb(scoped_ptr<base::Thread> thread) {
312 volatile int inhibit_comdat = __LINE__;
313 ALLOW_UNUSED_LOCAL(inhibit_comdat);
314 thread.reset();
316 #endif
318 MSVC_POP_WARNING()
319 MSVC_ENABLE_OPTIMIZE();
321 #if defined(OS_WIN)
322 // Creates a memory pressure monitor using automatic thresholds, or those
323 // specified on the command-line. Ownership is passed to the caller.
324 base::win::MemoryPressureMonitor* CreateWinMemoryPressureMonitor(
325 const base::CommandLine& parsed_command_line) {
326 std::vector<std::string> thresholds = base::SplitString(
327 parsed_command_line.GetSwitchValueASCII(
328 switches::kMemoryPressureThresholdsMb),
329 ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
331 int moderate_threshold_mb = 0;
332 int critical_threshold_mb = 0;
333 if (thresholds.size() == 2 &&
334 base::StringToInt(thresholds[0], &moderate_threshold_mb) &&
335 base::StringToInt(thresholds[1], &critical_threshold_mb) &&
336 moderate_threshold_mb >= critical_threshold_mb &&
337 critical_threshold_mb >= 0) {
338 return new base::win::MemoryPressureMonitor(moderate_threshold_mb,
339 critical_threshold_mb);
342 // In absence of valid switches use the automatic defaults.
343 return new base::win::MemoryPressureMonitor();
345 #endif // defined(OS_WIN)
347 } // namespace
349 // The currently-running BrowserMainLoop. There can be one or zero.
350 BrowserMainLoop* g_current_browser_main_loop = NULL;
352 // For measuring memory usage after each task. Behind a command line flag.
353 class BrowserMainLoop::MemoryObserver : public base::MessageLoop::TaskObserver {
354 public:
355 MemoryObserver() {}
356 ~MemoryObserver() override {}
358 void WillProcessTask(const base::PendingTask& pending_task) override {}
360 void DidProcessTask(const base::PendingTask& pending_task) override {
361 #if !defined(OS_IOS) // No ProcessMetrics on IOS.
362 scoped_ptr<base::ProcessMetrics> process_metrics(
363 base::ProcessMetrics::CreateProcessMetrics(
364 #if defined(OS_MACOSX)
365 base::GetCurrentProcessHandle(), NULL));
366 #else
367 base::GetCurrentProcessHandle()));
368 #endif
369 size_t private_bytes;
370 process_metrics->GetMemoryBytes(&private_bytes, NULL);
371 LOCAL_HISTOGRAM_MEMORY_KB("Memory.BrowserUsed", private_bytes >> 10);
372 #endif
374 private:
375 DISALLOW_COPY_AND_ASSIGN(MemoryObserver);
379 // BrowserMainLoop construction / destruction =============================
381 BrowserMainLoop* BrowserMainLoop::GetInstance() {
382 DCHECK_CURRENTLY_ON(BrowserThread::UI);
383 return g_current_browser_main_loop;
386 BrowserMainLoop::BrowserMainLoop(const MainFunctionParams& parameters)
387 : parameters_(parameters),
388 parsed_command_line_(parameters.command_line),
389 result_code_(RESULT_CODE_NORMAL_EXIT),
390 created_threads_(false),
391 // ContentMainRunner should have enabled tracing of the browser process
392 // when kTraceStartup is in the command line.
393 is_tracing_startup_(
394 parameters.command_line.HasSwitch(switches::kTraceStartup)) {
395 DCHECK(!g_current_browser_main_loop);
396 g_current_browser_main_loop = this;
399 BrowserMainLoop::~BrowserMainLoop() {
400 DCHECK_EQ(this, g_current_browser_main_loop);
401 #if !defined(OS_IOS)
402 ui::Clipboard::DestroyClipboardForCurrentThread();
403 #endif // !defined(OS_IOS)
404 g_current_browser_main_loop = NULL;
407 void BrowserMainLoop::Init() {
408 TRACE_EVENT0("startup", "BrowserMainLoop::Init");
409 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::Init");
411 parts_.reset(
412 GetContentClient()->browser()->CreateBrowserMainParts(parameters_));
415 // BrowserMainLoop stages ==================================================
417 void BrowserMainLoop::EarlyInitialization() {
418 TRACE_EVENT0("startup", "BrowserMainLoop::EarlyInitialization");
419 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::EarlyInitialization");
421 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
422 // No thread should be created before this call, as SetupSandbox()
423 // will end-up using fork().
424 SetupSandbox(parsed_command_line_);
425 #endif
427 #if defined(USE_X11)
428 if (UsingInProcessGpu()) {
429 if (!gfx::InitializeThreadedX11()) {
430 LOG(ERROR) << "Failed to put Xlib into threaded mode.";
433 #endif
435 // GLib's spawning of new processes is buggy, so it's important that at this
436 // point GLib does not need to start DBUS. Chrome should always start with
437 // DBUS_SESSION_BUS_ADDRESS properly set. See crbug.com/309093.
438 #if defined(USE_GLIB)
439 // g_type_init will be deprecated in 2.36. 2.35 is the development
440 // version for 2.36, hence do not call g_type_init starting 2.35.
441 // http://developer.gnome.org/gobject/unstable/gobject-Type-Information.html#g-type-init
442 #if !GLIB_CHECK_VERSION(2, 35, 0)
443 // GLib type system initialization. Needed at least for gconf,
444 // used in net/proxy/proxy_config_service_linux.cc. Most likely
445 // this is superfluous as gtk_init() ought to do this. It's
446 // definitely harmless, so retained as a reminder of this
447 // requirement for gconf.
448 g_type_init();
449 #endif
451 SetUpGLibLogHandler();
452 #endif
454 if (parts_)
455 parts_->PreEarlyInitialization();
457 #if defined(OS_MACOSX)
458 // We use quite a few file descriptors for our IPC, and the default limit on
459 // the Mac is low (256), so bump it up.
460 base::SetFdLimit(1024);
461 #endif
463 #if defined(OS_WIN)
464 net::EnsureWinsockInit();
465 #endif
467 #if !defined(USE_OPENSSL)
468 // We want to be sure to init NSPR on the main thread.
469 crypto::EnsureNSPRInit();
470 #endif // !defined(USE_OPENSSL)
472 #if !defined(OS_IOS)
473 if (parsed_command_line_.HasSwitch(switches::kRendererProcessLimit)) {
474 std::string limit_string = parsed_command_line_.GetSwitchValueASCII(
475 switches::kRendererProcessLimit);
476 size_t process_limit;
477 if (base::StringToSizeT(limit_string, &process_limit)) {
478 RenderProcessHost::SetMaxRendererProcessCount(process_limit);
481 #endif // !defined(OS_IOS)
483 // TODO(boliu): kSingleProcess check is a temporary workaround for
484 // in-process Android WebView. crbug.com/503724 tracks proper fix.
485 if (!parsed_command_line_.HasSwitch(switches::kSingleProcess)) {
486 base::DiscardableMemoryAllocator::SetInstance(
487 HostDiscardableSharedMemoryManager::current());
490 if (parts_)
491 parts_->PostEarlyInitialization();
494 void BrowserMainLoop::PreMainMessageLoopStart() {
495 if (parts_) {
496 TRACE_EVENT0("startup",
497 "BrowserMainLoop::MainMessageLoopStart:PreMainMessageLoopStart");
498 parts_->PreMainMessageLoopStart();
501 #if defined(OS_WIN)
502 // If we're running tests (ui_task is non-null), then the ResourceBundle
503 // has already been initialized.
504 if (!parameters_.ui_task) {
505 // Override the configured locale with the user's preferred UI language.
506 l10n_util::OverrideLocaleWithUILanguageList();
508 #endif
511 void BrowserMainLoop::MainMessageLoopStart() {
512 // DO NOT add more code here. Use PreMainMessageLoopStart() above or
513 // PostMainMessageLoopStart() below.
515 TRACE_EVENT0("startup", "BrowserMainLoop::MainMessageLoopStart");
516 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::MainMessageLoopStart");
518 // Create a MessageLoop if one does not already exist for the current thread.
519 if (!base::MessageLoop::current())
520 main_message_loop_.reset(new base::MessageLoopForUI);
522 InitializeMainThread();
525 void BrowserMainLoop::PostMainMessageLoopStart() {
527 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SystemMonitor");
528 system_monitor_.reset(new base::SystemMonitor);
531 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:PowerMonitor");
532 scoped_ptr<base::PowerMonitorSource> power_monitor_source(
533 new base::PowerMonitorDeviceSource());
534 power_monitor_.reset(new base::PowerMonitor(power_monitor_source.Pass()));
537 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:HighResTimerManager");
538 hi_res_timer_manager_.reset(new base::HighResolutionTimerManager);
541 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:NetworkChangeNotifier");
542 network_change_notifier_.reset(net::NetworkChangeNotifier::Create());
545 #if !defined(OS_IOS)
547 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MediaFeatures");
548 media::InitializeMediaLibrary();
551 TRACE_EVENT0("startup",
552 "BrowserMainLoop::Subsystem:ContentWebUIController");
553 WebUIControllerFactory::RegisterFactory(
554 ContentWebUIControllerFactory::GetInstance());
558 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:OnlineStateObserver");
559 online_state_observer_.reset(new BrowserOnlineStateObserver);
563 system_stats_monitor_.reset(
564 new base::trace_event::TraceEventSystemStatsMonitor(
565 base::ThreadTaskRunnerHandle::Get()));
567 #endif // !defined(OS_IOS)
569 #if defined(OS_WIN)
570 system_message_window_.reset(new SystemMessageWindowWin);
571 #endif
573 if (parts_)
574 parts_->PostMainMessageLoopStart();
576 #if !defined(OS_IOS)
577 // Start tracing to a file if needed. Only do this after starting the main
578 // message loop to avoid calling MessagePumpForUI::ScheduleWork() before
579 // MessagePumpForUI::Start() as it will crash the browser.
580 if (is_tracing_startup_) {
581 TRACE_EVENT0("startup", "BrowserMainLoop::InitStartupTracing");
582 InitStartupTracing(parsed_command_line_);
584 #endif // !defined(OS_IOS)
586 #if defined(OS_ANDROID)
588 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SurfaceTextureManager");
589 if (parsed_command_line_.HasSwitch(switches::kSingleProcess)) {
590 SurfaceTextureManager::SetInstance(
591 InProcessSurfaceTextureManager::GetInstance());
592 } else {
593 SurfaceTextureManager::SetInstance(
594 BrowserSurfaceTextureManager::GetInstance());
598 if (!parsed_command_line_.HasSwitch(
599 switches::kDisableScreenOrientationLock)) {
600 TRACE_EVENT0("startup",
601 "BrowserMainLoop::Subsystem:ScreenOrientationProvider");
602 screen_orientation_delegate_.reset(
603 new ScreenOrientationDelegateAndroid());
604 ScreenOrientationProvider::SetDelegate(screen_orientation_delegate_.get());
606 #endif
608 #if defined(OS_MACOSX) && !defined(OS_IOS)
610 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:IOSurfaceManager");
611 if (parsed_command_line_.HasSwitch(switches::kSingleProcess)) {
612 IOSurfaceManager::SetInstance(InProcessIOSurfaceManager::GetInstance());
613 } else {
614 IOSurfaceManager::SetInstance(BrowserIOSurfaceManager::GetInstance());
617 #endif
619 #if defined(USE_OZONE)
620 client_native_pixmap_factory_ = ui::ClientNativePixmapFactory::Create();
621 ui::ClientNativePixmapFactory::SetInstance(
622 client_native_pixmap_factory_.get());
623 #endif
625 if (parsed_command_line_.HasSwitch(switches::kMemoryMetrics)) {
626 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MemoryObserver");
627 memory_observer_.reset(new MemoryObserver());
628 base::MessageLoop::current()->AddTaskObserver(memory_observer_.get());
631 if (parsed_command_line_.HasSwitch(
632 switches::kEnableAggressiveDOMStorageFlushing)) {
633 TRACE_EVENT0("startup",
634 "BrowserMainLoop::Subsystem:EnableAggressiveCommitDelay");
635 DOMStorageArea::EnableAggressiveCommitDelay();
638 base::trace_event::MemoryDumpManager::GetInstance()->Initialize();
640 // Enable the dump providers.
641 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
642 HostSharedBitmapManager::current());
643 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
644 skia::SkiaMemoryDumpProvider::GetInstance());
646 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
647 trace_memory_controller_.reset(new base::trace_event::TraceMemoryController(
648 base::MessageLoop::current()->task_runner(),
649 ::HeapProfilerWithPseudoStackStart, ::HeapProfilerStop,
650 ::GetHeapProfile));
651 #endif
654 int BrowserMainLoop::PreCreateThreads() {
655 // Need to initialize in-process GpuDataManager before creating threads.
656 // It's unsafe to append the gpu command line switches to the global
657 // CommandLine::ForCurrentProcess object after threads are created.
658 // Also need to initialize before BrowserMainParts::PreCreateThreads, so
659 // BrowserMainParts has a hook to set GpuDataManager strings before
660 // starting Gpu process.
661 GpuDataManagerImpl::GetInstance()->Initialize();
663 if (parts_) {
664 TRACE_EVENT0("startup",
665 "BrowserMainLoop::CreateThreads:PreCreateThreads");
666 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::PreCreateThreads");
668 result_code_ = parts_->PreCreateThreads();
671 // TODO(chrisha): Abstract away this construction mess to a helper function,
672 // once MemoryPressureMonitor is made a concrete class.
673 #if defined(OS_CHROMEOS)
674 if (chromeos::switches::MemoryPressureHandlingEnabled()) {
675 memory_pressure_monitor_.reset(new base::chromeos::MemoryPressureMonitor(
676 chromeos::switches::GetMemoryPressureThresholds()));
678 #elif defined(OS_MACOSX) && !defined(OS_IOS)
679 memory_pressure_monitor_.reset(new base::mac::MemoryPressureMonitor());
680 #elif defined(OS_WIN)
681 memory_pressure_monitor_.reset(CreateWinMemoryPressureMonitor(
682 parsed_command_line_));
683 #endif
685 #if defined(ENABLE_PLUGINS)
686 // Prior to any processing happening on the io thread, we create the
687 // plugin service as it is predominantly used from the io thread,
688 // but must be created on the main thread. The service ctor is
689 // inexpensive and does not invoke the io_thread() accessor.
691 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads:PluginService");
692 PluginService::GetInstance()->Init();
694 #endif
696 #if defined(OS_MACOSX)
698 // Initialize AVFoundation if supported, for audio and video.
699 TRACE_EVENT0("startup",
700 "BrowserMainLoop::CreateThreads:InitializeAVFoundation");
701 AVFoundationGlue::InitializeAVFoundation();
703 #endif
705 #if !defined(OS_IOS) && (!defined(GOOGLE_CHROME_BUILD) || defined(OS_ANDROID))
706 // Single-process is an unsupported and not fully tested mode, so
707 // don't enable it for official Chrome builds (except on Android).
708 if (parsed_command_line_.HasSwitch(switches::kSingleProcess))
709 RenderProcessHost::SetRunRendererInProcess(true);
710 #endif
712 return result_code_;
715 void BrowserMainLoop::CreateStartupTasks() {
716 TRACE_EVENT0("startup", "BrowserMainLoop::CreateStartupTasks");
717 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::CreateStartupTasks");
719 // First time through, we really want to create all the tasks
720 if (!startup_task_runner_.get()) {
721 #if defined(OS_ANDROID)
722 startup_task_runner_ = make_scoped_ptr(
723 new StartupTaskRunner(base::Bind(&BrowserStartupComplete),
724 base::ThreadTaskRunnerHandle::Get()));
725 #else
726 startup_task_runner_ = make_scoped_ptr(
727 new StartupTaskRunner(base::Callback<void(int)>(),
728 base::ThreadTaskRunnerHandle::Get()));
729 #endif
730 StartupTask pre_create_threads =
731 base::Bind(&BrowserMainLoop::PreCreateThreads, base::Unretained(this));
732 startup_task_runner_->AddTask(pre_create_threads);
734 StartupTask create_threads =
735 base::Bind(&BrowserMainLoop::CreateThreads, base::Unretained(this));
736 startup_task_runner_->AddTask(create_threads);
738 StartupTask browser_thread_started = base::Bind(
739 &BrowserMainLoop::BrowserThreadsStarted, base::Unretained(this));
740 startup_task_runner_->AddTask(browser_thread_started);
742 StartupTask pre_main_message_loop_run = base::Bind(
743 &BrowserMainLoop::PreMainMessageLoopRun, base::Unretained(this));
744 startup_task_runner_->AddTask(pre_main_message_loop_run);
746 #if defined(OS_ANDROID)
747 if (BrowserMayStartAsynchronously()) {
748 startup_task_runner_->StartRunningTasksAsync();
750 #endif
752 #if defined(OS_ANDROID)
753 if (!BrowserMayStartAsynchronously()) {
754 // A second request for asynchronous startup can be ignored, so
755 // StartupRunningTasksAsync is only called first time through. If, however,
756 // this is a request for synchronous startup then it must override any
757 // previous call for async startup, so we call RunAllTasksNow()
758 // unconditionally.
759 startup_task_runner_->RunAllTasksNow();
761 #else
762 startup_task_runner_->RunAllTasksNow();
763 #endif
766 int BrowserMainLoop::CreateThreads() {
767 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads");
768 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::CreateThreads");
770 base::Thread::Options io_message_loop_options;
771 io_message_loop_options.message_loop_type = base::MessageLoop::TYPE_IO;
772 base::Thread::Options ui_message_loop_options;
773 ui_message_loop_options.message_loop_type = base::MessageLoop::TYPE_UI;
775 // Start threads in the order they occur in the BrowserThread::ID
776 // enumeration, except for BrowserThread::UI which is the main
777 // thread.
779 // Must be size_t so we can increment it.
780 for (size_t thread_id = BrowserThread::UI + 1;
781 thread_id < BrowserThread::ID_COUNT;
782 ++thread_id) {
783 scoped_ptr<BrowserProcessSubThread>* thread_to_start = NULL;
784 base::Thread::Options options;
786 switch (thread_id) {
787 case BrowserThread::DB:
788 TRACE_EVENT_BEGIN1("startup",
789 "BrowserMainLoop::CreateThreads:start",
790 "Thread", "BrowserThread::DB");
791 thread_to_start = &db_thread_;
792 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
793 break;
794 case BrowserThread::FILE_USER_BLOCKING:
795 TRACE_EVENT_BEGIN1("startup",
796 "BrowserMainLoop::CreateThreads:start",
797 "Thread", "BrowserThread::FILE_USER_BLOCKING");
798 thread_to_start = &file_user_blocking_thread_;
799 break;
800 case BrowserThread::FILE:
801 TRACE_EVENT_BEGIN1("startup",
802 "BrowserMainLoop::CreateThreads:start",
803 "Thread", "BrowserThread::FILE");
804 thread_to_start = &file_thread_;
805 #if defined(OS_WIN)
806 // On Windows, the FILE thread needs to be have a UI message loop
807 // which pumps messages in such a way that Google Update can
808 // communicate back to us.
809 options = ui_message_loop_options;
810 #else
811 options = io_message_loop_options;
812 #endif
813 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
814 break;
815 case BrowserThread::PROCESS_LAUNCHER:
816 TRACE_EVENT_BEGIN1("startup",
817 "BrowserMainLoop::CreateThreads:start",
818 "Thread", "BrowserThread::PROCESS_LAUNCHER");
819 thread_to_start = &process_launcher_thread_;
820 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
821 break;
822 case BrowserThread::CACHE:
823 TRACE_EVENT_BEGIN1("startup",
824 "BrowserMainLoop::CreateThreads:start",
825 "Thread", "BrowserThread::CACHE");
826 thread_to_start = &cache_thread_;
827 options = io_message_loop_options;
828 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
829 break;
830 case BrowserThread::IO:
831 TRACE_EVENT_BEGIN1("startup",
832 "BrowserMainLoop::CreateThreads:start",
833 "Thread", "BrowserThread::IO");
834 thread_to_start = &io_thread_;
835 options = io_message_loop_options;
836 #if defined(OS_ANDROID)
837 // Up the priority of the |io_thread_| as some of its IPCs relate to
838 // display tasks.
839 options.priority = base::ThreadPriority::DISPLAY;
840 #endif
841 break;
842 case BrowserThread::UI:
843 case BrowserThread::ID_COUNT:
844 default:
845 NOTREACHED();
846 break;
849 BrowserThread::ID id = static_cast<BrowserThread::ID>(thread_id);
851 if (thread_to_start) {
852 (*thread_to_start).reset(new BrowserProcessSubThread(id));
853 if (!(*thread_to_start)->StartWithOptions(options)) {
854 LOG(FATAL) << "Failed to start the browser thread: id == " << id;
856 } else {
857 NOTREACHED();
860 TRACE_EVENT_END0("startup", "BrowserMainLoop::CreateThreads:start");
862 created_threads_ = true;
863 return result_code_;
866 int BrowserMainLoop::PreMainMessageLoopRun() {
867 if (parts_) {
868 TRACE_EVENT0("startup",
869 "BrowserMainLoop::CreateThreads:PreMainMessageLoopRun");
870 TRACK_SCOPED_REGION(
871 "Startup", "BrowserMainLoop::PreMainMessageLoopRun");
873 parts_->PreMainMessageLoopRun();
876 // If the UI thread blocks, the whole UI is unresponsive.
877 // Do not allow disk IO from the UI thread.
878 base::ThreadRestrictions::SetIOAllowed(false);
879 base::ThreadRestrictions::DisallowWaiting();
880 return result_code_;
883 void BrowserMainLoop::RunMainMessageLoopParts() {
884 TRACE_EVENT_BEGIN_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
886 bool ran_main_loop = false;
887 if (parts_)
888 ran_main_loop = parts_->MainMessageLoopRun(&result_code_);
890 if (!ran_main_loop)
891 MainMessageLoopRun();
893 TRACE_EVENT_END_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
896 void BrowserMainLoop::ShutdownThreadsAndCleanUp() {
897 if (!created_threads_) {
898 // Called early, nothing to do
899 return;
901 TRACE_EVENT0("shutdown", "BrowserMainLoop::ShutdownThreadsAndCleanUp");
903 // Teardown may start in PostMainMessageLoopRun, and during teardown we
904 // need to be able to perform IO.
905 base::ThreadRestrictions::SetIOAllowed(true);
906 BrowserThread::PostTask(
907 BrowserThread::IO, FROM_HERE,
908 base::Bind(base::IgnoreResult(&base::ThreadRestrictions::SetIOAllowed),
909 true));
911 mojo_shell_context_.reset();
913 #if !defined(OS_IOS)
914 if (RenderProcessHost::run_renderer_in_process())
915 RenderProcessHostImpl::ShutDownInProcessRenderer();
916 #endif
918 if (parts_) {
919 TRACE_EVENT0("shutdown",
920 "BrowserMainLoop::Subsystem:PostMainMessageLoopRun");
921 parts_->PostMainMessageLoopRun();
924 #if defined(USE_AURA)
925 aura::Env::DeleteInstance();
926 #endif
928 trace_memory_controller_.reset();
929 system_stats_monitor_.reset();
931 #if !defined(OS_IOS)
932 // Destroying the GpuProcessHostUIShims on the UI thread posts a task to
933 // delete related objects on the GPU thread. This must be done before
934 // stopping the GPU thread. The GPU thread will close IPC channels to renderer
935 // processes so this has to happen before stopping the IO thread.
937 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUProcessHostShim");
938 GpuProcessHostUIShim::DestroyAll();
940 // Cancel pending requests and prevent new requests.
941 if (resource_dispatcher_host_) {
942 TRACE_EVENT0("shutdown",
943 "BrowserMainLoop::Subsystem:ResourceDispatcherHost");
944 resource_dispatcher_host_.get()->Shutdown();
947 memory_pressure_monitor_.reset();
949 #if defined(OS_MACOSX)
950 BrowserCompositorMac::DisableRecyclingForShutdown();
951 #endif
953 #if defined(USE_AURA) || defined(OS_MACOSX)
955 TRACE_EVENT0("shutdown",
956 "BrowserMainLoop::Subsystem:ImageTransportFactory");
957 ImageTransportFactory::Terminate();
959 #endif
961 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
962 ZygoteHostImpl::GetInstance()->TearDownAfterLastChild();
963 #endif // defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
965 // The device monitors are using |system_monitor_| as dependency, so delete
966 // them before |system_monitor_| goes away.
967 // On Mac and windows, the monitor needs to be destroyed on the same thread
968 // as they were created. On Linux, the monitor will be deleted when IO thread
969 // goes away.
970 #if defined(OS_WIN)
971 system_message_window_.reset();
972 #elif defined(OS_MACOSX)
973 device_monitor_mac_.reset();
974 #endif
975 #endif // !defined(OS_IOS)
977 // Must be size_t so we can subtract from it.
978 for (size_t thread_id = BrowserThread::ID_COUNT - 1;
979 thread_id >= (BrowserThread::UI + 1);
980 --thread_id) {
981 // Find the thread object we want to stop. Looping over all valid
982 // BrowserThread IDs and DCHECKing on a missing case in the switch
983 // statement helps avoid a mismatch between this code and the
984 // BrowserThread::ID enumeration.
986 // The destruction order is the reverse order of occurrence in the
987 // BrowserThread::ID list. The rationale for the order is as
988 // follows (need to be filled in a bit):
991 // - The IO thread is the only user of the CACHE thread.
993 // - The PROCESS_LAUNCHER thread must be stopped after IO in case
994 // the IO thread posted a task to terminate a process on the
995 // process launcher thread.
997 // - (Not sure why DB stops last.)
998 switch (thread_id) {
999 case BrowserThread::DB: {
1000 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DBThread");
1001 ResetThread_DB(db_thread_.Pass());
1002 break;
1004 case BrowserThread::FILE: {
1005 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:FileThread");
1006 #if !defined(OS_IOS)
1007 // Clean up state that lives on or uses the file_thread_ before
1008 // it goes away.
1009 if (resource_dispatcher_host_)
1010 resource_dispatcher_host_.get()->save_file_manager()->Shutdown();
1011 #endif // !defined(OS_IOS)
1012 ResetThread_FILE(file_thread_.Pass());
1013 break;
1015 case BrowserThread::FILE_USER_BLOCKING: {
1016 TRACE_EVENT0("shutdown",
1017 "BrowserMainLoop::Subsystem:FileUserBlockingThread");
1018 ResetThread_FILE_USER_BLOCKING(file_user_blocking_thread_.Pass());
1019 break;
1021 case BrowserThread::PROCESS_LAUNCHER: {
1022 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:LauncherThread");
1023 ResetThread_PROCESS_LAUNCHER(process_launcher_thread_.Pass());
1024 break;
1026 case BrowserThread::CACHE: {
1027 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:CacheThread");
1028 ResetThread_CACHE(cache_thread_.Pass());
1029 break;
1031 case BrowserThread::IO: {
1032 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IOThread");
1033 ResetThread_IO(io_thread_.Pass());
1034 break;
1036 case BrowserThread::UI:
1037 case BrowserThread::ID_COUNT:
1038 default:
1039 NOTREACHED();
1040 break;
1044 #if !defined(OS_IOS)
1046 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IndexedDBThread");
1047 ResetThread_IndexedDb(indexed_db_thread_.Pass());
1049 #endif
1051 // Close the blocking I/O pool after the other threads. Other threads such
1052 // as the I/O thread may need to schedule work like closing files or flushing
1053 // data during shutdown, so the blocking pool needs to be available. There
1054 // may also be slow operations pending that will blcok shutdown, so closing
1055 // it here (which will block until required operations are complete) gives
1056 // more head start for those operations to finish.
1058 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:ThreadPool");
1059 BrowserThreadImpl::ShutdownThreadPool();
1062 #if !defined(OS_IOS)
1063 // Must happen after the IO thread is shutdown since this may be accessed from
1064 // it.
1066 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUChannelFactory");
1067 if (BrowserGpuChannelHostFactory::instance())
1068 BrowserGpuChannelHostFactory::Terminate();
1071 // Must happen after the I/O thread is shutdown since this class lives on the
1072 // I/O thread and isn't threadsafe.
1074 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GamepadService");
1075 GamepadService::GetInstance()->Terminate();
1078 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:SensorService");
1079 DeviceInertialSensorService::GetInstance()->Shutdown();
1082 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:BatteryStatusService");
1083 device::BatteryStatusService::GetInstance()->Shutdown();
1086 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DeleteDataSources");
1087 URLDataManager::DeleteDataSources();
1089 #endif // !defined(OS_IOS)
1091 if (parts_) {
1092 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:PostDestroyThreads");
1093 parts_->PostDestroyThreads();
1097 void BrowserMainLoop::StopStartupTracingTimer() {
1098 startup_trace_timer_.Stop();
1101 void BrowserMainLoop::InitializeMainThread() {
1102 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeMainThread");
1103 static const char kThreadName[] = "CrBrowserMain";
1104 base::PlatformThread::SetName(kThreadName);
1105 if (main_message_loop_)
1106 main_message_loop_->set_thread_name(kThreadName);
1108 // Register the main thread by instantiating it, but don't call any methods.
1109 main_thread_.reset(
1110 new BrowserThreadImpl(BrowserThread::UI, base::MessageLoop::current()));
1113 int BrowserMainLoop::BrowserThreadsStarted() {
1114 TRACE_EVENT0("startup", "BrowserMainLoop::BrowserThreadsStarted");
1116 #if !defined(OS_IOS)
1117 indexed_db_thread_.reset(new base::Thread("IndexedDB"));
1118 indexed_db_thread_->Start();
1119 #endif
1121 #if !defined(OS_IOS)
1122 HistogramSynchronizer::GetInstance();
1124 #if defined(OS_ANDROID)
1125 // Up the priority of the UI thread.
1126 base::PlatformThread::SetCurrentThreadPriority(base::ThreadPriority::DISPLAY);
1127 #endif
1129 bool always_uses_gpu = true;
1130 bool established_gpu_channel = false;
1131 #if defined(OS_ANDROID)
1132 // TODO(crbug.com/439322): This should be set to |true|.
1133 established_gpu_channel = false;
1134 BrowserGpuChannelHostFactory::Initialize(established_gpu_channel);
1135 #elif defined(USE_AURA) || defined(OS_MACOSX)
1136 established_gpu_channel = true;
1137 if (!GpuDataManagerImpl::GetInstance()->CanUseGpuBrowserCompositor() ||
1138 parsed_command_line_.HasSwitch(switches::kDisableGpuEarlyInit)) {
1139 established_gpu_channel = always_uses_gpu = false;
1141 BrowserGpuChannelHostFactory::Initialize(established_gpu_channel);
1142 ImageTransportFactory::Initialize();
1143 #if defined(USE_AURA)
1144 if (aura::Env::GetInstance()) {
1145 aura::Env::GetInstance()->set_context_factory(GetContextFactory());
1147 #endif // defined(USE_AURA)
1148 #endif // defined(OS_ANDROID)
1150 // Enable the GpuMemoryBuffer dump provider with IO thread affinity. Note that
1151 // unregistration happens on the IO thread (See
1152 // BrowserProcessSubThread::IOThreadPreCleanUp).
1153 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
1154 BrowserGpuMemoryBufferManager::current(), io_thread_->task_runner());
1157 TRACE_EVENT0("startup", "BrowserThreadsStarted::Subsystem:AudioMan");
1158 audio_manager_.reset(media::AudioManager::CreateWithHangTimer(
1159 MediaInternals::GetInstance(), io_thread_->task_runner()));
1163 TRACE_EVENT0("startup", "BrowserThreadsStarted::Subsystem:MidiManager");
1164 midi_manager_.reset(media::midi::MidiManager::Create());
1167 #if defined(OS_LINUX) && defined(USE_UDEV)
1168 device_monitor_linux_.reset(new DeviceMonitorLinux());
1169 #elif defined(OS_MACOSX)
1170 device_monitor_mac_.reset(new DeviceMonitorMac());
1171 #endif
1173 #if defined(OS_WIN)
1174 UMA_HISTOGRAM_BOOLEAN("Windows.Win32kRendererLockdown",
1175 IsWin32kRendererLockdownEnabled());
1176 #endif
1177 // RDH needs the IO thread to be created
1179 TRACE_EVENT0("startup",
1180 "BrowserMainLoop::BrowserThreadsStarted:InitResourceDispatcherHost");
1181 resource_dispatcher_host_.reset(new ResourceDispatcherHostImpl());
1184 // MediaStreamManager needs the IO thread to be created.
1186 TRACE_EVENT0("startup",
1187 "BrowserMainLoop::BrowserThreadsStarted:InitMediaStreamManager");
1188 media_stream_manager_.reset(new MediaStreamManager(audio_manager_.get()));
1192 TRACE_EVENT0("startup",
1193 "BrowserMainLoop::BrowserThreadsStarted:InitSpeechRecognition");
1194 speech_recognition_manager_.reset(new SpeechRecognitionManagerImpl(
1195 audio_manager_.get(), media_stream_manager_.get()));
1199 TRACE_EVENT0(
1200 "startup",
1201 "BrowserMainLoop::BrowserThreadsStarted::InitUserInputMonitor");
1202 user_input_monitor_ = media::UserInputMonitor::Create(
1203 io_thread_->task_runner(), main_thread_->task_runner());
1207 TRACE_EVENT0("startup",
1208 "BrowserMainLoop::BrowserThreadsStarted::TimeZoneMonitor");
1209 time_zone_monitor_ = TimeZoneMonitor::Create();
1212 // Alert the clipboard class to which threads are allowed to access the
1213 // clipboard:
1214 std::vector<base::PlatformThreadId> allowed_clipboard_threads;
1215 // The current thread is the UI thread.
1216 allowed_clipboard_threads.push_back(base::PlatformThread::CurrentId());
1217 #if defined(OS_WIN)
1218 // On Windows, clipboards are also used on the FILE or IO threads.
1219 allowed_clipboard_threads.push_back(file_thread_->GetThreadId());
1220 allowed_clipboard_threads.push_back(io_thread_->GetThreadId());
1221 #endif
1222 ui::Clipboard::SetAllowedThreads(allowed_clipboard_threads);
1224 // When running the GPU thread in-process, avoid optimistically starting it
1225 // since creating the GPU thread races against creation of the one-and-only
1226 // ChildProcess instance which is created by the renderer thread.
1227 if (GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL) &&
1228 !established_gpu_channel &&
1229 always_uses_gpu &&
1230 !UsingInProcessGpu()) {
1231 TRACE_EVENT_INSTANT0("gpu", "Post task to launch GPU process",
1232 TRACE_EVENT_SCOPE_THREAD);
1233 BrowserThread::PostTask(
1234 BrowserThread::IO, FROM_HERE,
1235 base::Bind(base::IgnoreResult(&GpuProcessHost::Get),
1236 GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED,
1237 CAUSE_FOR_GPU_LAUNCH_BROWSER_STARTUP));
1240 #if defined(OS_MACOSX)
1241 ThemeHelperMac::GetInstance();
1242 SystemHotkeyHelperMac::GetInstance()->DeferredLoadSystemHotkeys();
1243 if (ShouldEnableBootstrapSandbox()) {
1244 TRACE_EVENT0("startup",
1245 "BrowserMainLoop::BrowserThreadsStarted:BootstrapSandbox");
1246 CHECK(GetBootstrapSandbox());
1248 #endif // defined(OS_MACOSX)
1250 #endif // !defined(OS_IOS)
1252 mojo_shell_context_.reset(new MojoShellContext);
1254 return result_code_;
1257 bool BrowserMainLoop::UsingInProcessGpu() const {
1258 return parsed_command_line_.HasSwitch(switches::kSingleProcess) ||
1259 parsed_command_line_.HasSwitch(switches::kInProcessGPU);
1262 bool BrowserMainLoop::InitializeToolkit() {
1263 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeToolkit");
1264 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::InitializeToolkit");
1266 // TODO(evan): this function is rather subtle, due to the variety
1267 // of intersecting ifdefs we have. To keep it easy to follow, there
1268 // are no #else branches on any #ifs.
1269 // TODO(stevenjb): Move platform specific code into platform specific Parts
1270 // (Need to add InitializeToolkit stage to BrowserParts).
1271 // See also GTK setup in EarlyInitialization, above, and associated comments.
1273 #if defined(OS_WIN)
1274 // Init common control sex.
1275 INITCOMMONCONTROLSEX config;
1276 config.dwSize = sizeof(config);
1277 config.dwICC = ICC_WIN95_CLASSES;
1278 if (!InitCommonControlsEx(&config))
1279 PLOG(FATAL);
1280 #endif
1282 #if defined(USE_AURA)
1284 #if defined(USE_X11)
1285 if (!gfx::GetXDisplay())
1286 return false;
1287 #endif
1289 // Env creates the compositor. Aura widgets need the compositor to be created
1290 // before they can be initialized by the browser.
1291 aura::Env::CreateInstance(true);
1292 #endif // defined(USE_AURA)
1294 if (parts_)
1295 parts_->ToolkitInitialized();
1297 return true;
1300 void BrowserMainLoop::MainMessageLoopRun() {
1301 #if defined(OS_ANDROID)
1302 // Android's main message loop is the Java message loop.
1303 NOTREACHED();
1304 #else
1305 DCHECK(base::MessageLoopForUI::IsCurrent());
1306 if (parameters_.ui_task) {
1307 base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
1308 *parameters_.ui_task);
1311 base::RunLoop run_loop;
1312 run_loop.Run();
1313 #endif
1316 base::FilePath BrowserMainLoop::GetStartupTraceFileName(
1317 const base::CommandLine& command_line) const {
1318 base::FilePath trace_file = command_line.GetSwitchValuePath(
1319 switches::kTraceStartupFile);
1320 // trace_file = "none" means that startup events will show up for the next
1321 // begin/end tracing (via about:tracing or AutomationProxy::BeginTracing/
1322 // EndTracing, for example).
1323 if (trace_file == base::FilePath().AppendASCII("none"))
1324 return trace_file;
1326 if (trace_file.empty()) {
1327 #if defined(OS_ANDROID)
1328 TracingControllerAndroid::GenerateTracingFilePath(&trace_file);
1329 #else
1330 // Default to saving the startup trace into the current dir.
1331 trace_file = base::FilePath().AppendASCII("chrometrace.log");
1332 #endif
1335 return trace_file;
1338 void BrowserMainLoop::InitStartupTracing(
1339 const base::CommandLine& command_line) {
1340 DCHECK(is_tracing_startup_);
1342 startup_trace_file_ = GetStartupTraceFileName(parsed_command_line_);
1344 std::string delay_str = command_line.GetSwitchValueASCII(
1345 switches::kTraceStartupDuration);
1346 int delay_secs = 5;
1347 if (!delay_str.empty() && !base::StringToInt(delay_str, &delay_secs)) {
1348 DLOG(WARNING) << "Could not parse --" << switches::kTraceStartupDuration
1349 << "=" << delay_str << " defaulting to 5 (secs)";
1350 delay_secs = 5;
1353 startup_trace_timer_.Start(FROM_HERE,
1354 base::TimeDelta::FromSeconds(delay_secs),
1355 this,
1356 &BrowserMainLoop::EndStartupTracing);
1359 void BrowserMainLoop::EndStartupTracing() {
1360 DCHECK(is_tracing_startup_);
1362 is_tracing_startup_ = false;
1363 TracingController::GetInstance()->DisableRecording(
1364 TracingController::CreateFileSink(
1365 startup_trace_file_,
1366 base::Bind(OnStoppedStartupTracing, startup_trace_file_)));
1369 } // namespace content