Add google_apis_unittests, midi_unittests to GN swarming.
[chromium-blink-merge.git] / content / browser / browser_main_loop.cc
blobb5159df02a3e91b640f71dc37d0e5e82f77e634a
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 "components/tracing/tracing_switches.h"
30 #include "content/browser/browser_thread_impl.h"
31 #include "content/browser/device_sensors/device_inertial_sensor_service.h"
32 #include "content/browser/dom_storage/dom_storage_area.h"
33 #include "content/browser/download/save_file_manager.h"
34 #include "content/browser/gamepad/gamepad_service.h"
35 #include "content/browser/gpu/browser_gpu_channel_host_factory.h"
36 #include "content/browser/gpu/browser_gpu_memory_buffer_manager.h"
37 #include "content/browser/gpu/compositor_util.h"
38 #include "content/browser/gpu/gpu_data_manager_impl.h"
39 #include "content/browser/gpu/gpu_process_host.h"
40 #include "content/browser/gpu/gpu_process_host_ui_shim.h"
41 #include "content/browser/histogram_synchronizer.h"
42 #include "content/browser/loader/resource_dispatcher_host_impl.h"
43 #include "content/browser/media/media_internals.h"
44 #include "content/browser/mojo/mojo_shell_context.h"
45 #include "content/browser/net/browser_online_state_observer.h"
46 #include "content/browser/renderer_host/media/media_stream_manager.h"
47 #include "content/browser/speech/speech_recognition_manager_impl.h"
48 #include "content/browser/startup_task_runner.h"
49 #include "content/browser/time_zone_monitor.h"
50 #include "content/browser/webui/content_web_ui_controller_factory.h"
51 #include "content/browser/webui/url_data_manager.h"
52 #include "content/common/content_switches_internal.h"
53 #include "content/common/host_discardable_shared_memory_manager.h"
54 #include "content/common/host_shared_bitmap_manager.h"
55 #include "content/public/browser/browser_main_parts.h"
56 #include "content/public/browser/content_browser_client.h"
57 #include "content/public/browser/render_process_host.h"
58 #include "content/public/browser/tracing_controller.h"
59 #include "content/public/common/content_switches.h"
60 #include "content/public/common/main_function_params.h"
61 #include "content/public/common/result_codes.h"
62 #include "crypto/nss_util.h"
63 #include "device/battery/battery_status_service.h"
64 #include "media/audio/audio_manager.h"
65 #include "media/base/media.h"
66 #include "media/base/user_input_monitor.h"
67 #include "media/midi/midi_manager.h"
68 #include "net/base/network_change_notifier.h"
69 #include "net/socket/client_socket_factory.h"
70 #include "net/ssl/ssl_config_service.h"
71 #include "skia/ext/skia_memory_dump_provider.h"
72 #include "ui/base/clipboard/clipboard.h"
74 #if defined(USE_AURA) || (defined(OS_MACOSX) && !defined(OS_IOS))
75 #include "content/browser/compositor/image_transport_factory.h"
76 #endif
78 #if defined(USE_AURA)
79 #include "content/public/browser/context_factory.h"
80 #include "ui/aura/env.h"
81 #endif
83 #if !defined(OS_IOS)
84 #include "content/browser/renderer_host/render_process_host_impl.h"
85 #endif
87 #if defined(OS_ANDROID)
88 #include "base/android/jni_android.h"
89 #include "content/browser/android/browser_startup_controller.h"
90 #include "content/browser/android/browser_surface_texture_manager.h"
91 #include "content/browser/android/in_process_surface_texture_manager.h"
92 #include "content/browser/android/tracing_controller_android.h"
93 #include "content/browser/screen_orientation/screen_orientation_delegate_android.h"
94 #include "content/public/browser/screen_orientation_provider.h"
95 #include "ui/gl/gl_surface.h"
96 #endif
98 #if defined(OS_MACOSX)
99 #include "media/base/mac/avfoundation_glue.h"
100 #endif
102 #if defined(OS_MACOSX) && !defined(OS_IOS)
103 #include "base/memory/memory_pressure_monitor_mac.h"
104 #include "content/browser/bootstrap_sandbox_mac.h"
105 #include "content/browser/browser_io_surface_manager_mac.h"
106 #include "content/browser/cocoa/system_hotkey_helper_mac.h"
107 #include "content/browser/compositor/browser_compositor_view_mac.h"
108 #include "content/browser/in_process_io_surface_manager_mac.h"
109 #include "content/browser/theme_helper_mac.h"
110 #endif
112 #if defined(USE_OZONE)
113 #include "ui/ozone/public/client_native_pixmap_factory.h"
114 #endif
116 #if defined(OS_WIN)
117 #include <windows.h>
118 #include <commctrl.h>
119 #include <shellapi.h>
121 #include "base/memory/memory_pressure_monitor_win.h"
122 #include "content/browser/system_message_window_win.h"
123 #include "content/common/sandbox_win.h"
124 #include "net/base/winsock_init.h"
125 #include "ui/base/l10n/l10n_util_win.h"
126 #endif
128 #if defined(OS_CHROMEOS)
129 #include "base/memory/memory_pressure_monitor_chromeos.h"
130 #include "chromeos/chromeos_switches.h"
131 #endif
133 #if defined(USE_GLIB)
134 #include <glib-object.h>
135 #endif
137 #if defined(OS_LINUX) && defined(USE_UDEV)
138 #include "content/browser/device_monitor_udev.h"
139 #elif defined(OS_MACOSX) && !defined(OS_IOS)
140 #include "content/browser/device_monitor_mac.h"
141 #endif
143 #if defined(OS_POSIX) && !defined(OS_MACOSX)
144 #include "content/browser/renderer_host/render_sandbox_host_linux.h"
145 #include "content/browser/zygote_host/zygote_host_impl_linux.h"
146 #include "sandbox/linux/suid/client/setuid_sandbox_host.h"
147 #endif
149 #if defined(ENABLE_PLUGINS)
150 #include "content/browser/plugin_service_impl.h"
151 #endif
153 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
154 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
155 #endif
157 #if defined(USE_X11)
158 #include "ui/gfx/x/x11_connection.h"
159 #include "ui/gfx/x/x11_types.h"
160 #endif
162 // One of the linux specific headers defines this as a macro.
163 #ifdef DestroyAll
164 #undef DestroyAll
165 #endif
167 namespace content {
168 namespace {
170 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
171 void SetupSandbox(const base::CommandLine& parsed_command_line) {
172 TRACE_EVENT0("startup", "SetupSandbox");
173 base::FilePath sandbox_binary;
175 scoped_ptr<sandbox::SetuidSandboxHost> setuid_sandbox_host(
176 sandbox::SetuidSandboxHost::Create());
178 const bool want_setuid_sandbox =
179 !parsed_command_line.HasSwitch(switches::kNoSandbox) &&
180 !parsed_command_line.HasSwitch(switches::kDisableSetuidSandbox) &&
181 !setuid_sandbox_host->IsDisabledViaEnvironment();
183 static const char no_suid_error[] =
184 "Running without the SUID sandbox! See "
185 "https://code.google.com/p/chromium/wiki/LinuxSUIDSandboxDevelopment "
186 "for more information on developing with the sandbox on.";
187 if (want_setuid_sandbox) {
188 sandbox_binary = setuid_sandbox_host->GetSandboxBinaryPath();
189 if (sandbox_binary.empty()) {
190 // This needs to be fatal. Talk to security@chromium.org if you feel
191 // otherwise.
192 LOG(FATAL) << no_suid_error;
194 } else {
195 LOG(ERROR) << no_suid_error;
198 // Tickle the sandbox host and zygote host so they fork now.
199 RenderSandboxHostLinux::GetInstance()->Init();
200 ZygoteHostImpl::GetInstance()->Init(sandbox_binary.value());
202 #endif
204 #if defined(USE_GLIB)
205 static void GLibLogHandler(const gchar* log_domain,
206 GLogLevelFlags log_level,
207 const gchar* message,
208 gpointer userdata) {
209 if (!log_domain)
210 log_domain = "<unknown>";
211 if (!message)
212 message = "<no message>";
214 if (strstr(message, "Unable to retrieve the file info for")) {
215 LOG(ERROR) << "GTK File code error: " << message;
216 } else if (strstr(message, "Could not find the icon") &&
217 strstr(log_domain, "Gtk")) {
218 LOG(ERROR) << "GTK icon error: " << message;
219 } else if (strstr(message, "Theme file for default has no") ||
220 strstr(message, "Theme directory") ||
221 strstr(message, "theme pixmap") ||
222 strstr(message, "locate theme engine")) {
223 LOG(ERROR) << "GTK theme error: " << message;
224 } else if (strstr(message, "Unable to create Ubuntu Menu Proxy") &&
225 strstr(log_domain, "<unknown>")) {
226 LOG(ERROR) << "GTK menu proxy create failed";
227 } else if (strstr(message, "Out of memory") &&
228 strstr(log_domain, "<unknown>")) {
229 LOG(ERROR) << "DBus call timeout or out of memory: "
230 << "http://crosbug.com/15496";
231 } else if (strstr(message, "Could not connect: Connection refused") &&
232 strstr(log_domain, "<unknown>")) {
233 LOG(ERROR) << "DConf settings backend could not connect to session bus: "
234 << "http://crbug.com/179797";
235 } else if (strstr(message, "Attempting to store changes into") ||
236 strstr(message, "Attempting to set the permissions of")) {
237 LOG(ERROR) << message << " (http://bugs.chromium.org/161366)";
238 } else if (strstr(message, "drawable is not a native X11 window")) {
239 LOG(ERROR) << message << " (http://bugs.chromium.org/329991)";
240 } else if (strstr(message, "Cannot do system-bus activation with no user")) {
241 LOG(ERROR) << message << " (http://crbug.com/431005)";
242 } else {
243 LOG(DFATAL) << log_domain << ": " << message;
247 static void SetUpGLibLogHandler() {
248 // Register GLib-handled assertions to go through our logging system.
249 const char* kLogDomains[] = { NULL, "Gtk", "Gdk", "GLib", "GLib-GObject" };
250 for (size_t i = 0; i < arraysize(kLogDomains); i++) {
251 g_log_set_handler(kLogDomains[i],
252 static_cast<GLogLevelFlags>(G_LOG_FLAG_RECURSION |
253 G_LOG_FLAG_FATAL |
254 G_LOG_LEVEL_ERROR |
255 G_LOG_LEVEL_CRITICAL |
256 G_LOG_LEVEL_WARNING),
257 GLibLogHandler,
258 NULL);
261 #endif
263 void OnStoppedStartupTracing(const base::FilePath& trace_file) {
264 VLOG(0) << "Completed startup tracing to " << trace_file.value();
267 // Disable optimizations for this block of functions so the compiler doesn't
268 // merge them all together. This makes it possible to tell what thread was
269 // unresponsive by inspecting the callstack.
270 MSVC_DISABLE_OPTIMIZE()
271 MSVC_PUSH_DISABLE_WARNING(4748)
273 NOINLINE void ResetThread_DB(scoped_ptr<BrowserProcessSubThread> thread) {
274 volatile int inhibit_comdat = __LINE__;
275 ALLOW_UNUSED_LOCAL(inhibit_comdat);
276 thread.reset();
279 NOINLINE void ResetThread_FILE(scoped_ptr<BrowserProcessSubThread> thread) {
280 volatile int inhibit_comdat = __LINE__;
281 ALLOW_UNUSED_LOCAL(inhibit_comdat);
282 thread.reset();
285 NOINLINE void ResetThread_FILE_USER_BLOCKING(
286 scoped_ptr<BrowserProcessSubThread> thread) {
287 volatile int inhibit_comdat = __LINE__;
288 ALLOW_UNUSED_LOCAL(inhibit_comdat);
289 thread.reset();
292 NOINLINE void ResetThread_PROCESS_LAUNCHER(
293 scoped_ptr<BrowserProcessSubThread> thread) {
294 volatile int inhibit_comdat = __LINE__;
295 ALLOW_UNUSED_LOCAL(inhibit_comdat);
296 thread.reset();
299 NOINLINE void ResetThread_CACHE(scoped_ptr<BrowserProcessSubThread> thread) {
300 volatile int inhibit_comdat = __LINE__;
301 ALLOW_UNUSED_LOCAL(inhibit_comdat);
302 thread.reset();
305 NOINLINE void ResetThread_IO(scoped_ptr<BrowserProcessSubThread> thread) {
306 volatile int inhibit_comdat = __LINE__;
307 ALLOW_UNUSED_LOCAL(inhibit_comdat);
308 thread.reset();
311 #if !defined(OS_IOS)
312 NOINLINE void ResetThread_IndexedDb(scoped_ptr<base::Thread> thread) {
313 volatile int inhibit_comdat = __LINE__;
314 ALLOW_UNUSED_LOCAL(inhibit_comdat);
315 thread.reset();
317 #endif
319 MSVC_POP_WARNING()
320 MSVC_ENABLE_OPTIMIZE();
322 #if defined(OS_WIN)
323 // Creates a memory pressure monitor using automatic thresholds, or those
324 // specified on the command-line. Ownership is passed to the caller.
325 base::win::MemoryPressureMonitor* CreateWinMemoryPressureMonitor(
326 const base::CommandLine& parsed_command_line) {
327 std::vector<std::string> thresholds = base::SplitString(
328 parsed_command_line.GetSwitchValueASCII(
329 switches::kMemoryPressureThresholdsMb),
330 ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
332 int moderate_threshold_mb = 0;
333 int critical_threshold_mb = 0;
334 if (thresholds.size() == 2 &&
335 base::StringToInt(thresholds[0], &moderate_threshold_mb) &&
336 base::StringToInt(thresholds[1], &critical_threshold_mb) &&
337 moderate_threshold_mb >= critical_threshold_mb &&
338 critical_threshold_mb >= 0) {
339 return new base::win::MemoryPressureMonitor(moderate_threshold_mb,
340 critical_threshold_mb);
343 // In absence of valid switches use the automatic defaults.
344 return new base::win::MemoryPressureMonitor();
346 #endif // defined(OS_WIN)
348 } // namespace
350 // The currently-running BrowserMainLoop. There can be one or zero.
351 BrowserMainLoop* g_current_browser_main_loop = NULL;
353 // For measuring memory usage after each task. Behind a command line flag.
354 class BrowserMainLoop::MemoryObserver : public base::MessageLoop::TaskObserver {
355 public:
356 MemoryObserver() {}
357 ~MemoryObserver() override {}
359 void WillProcessTask(const base::PendingTask& pending_task) override {}
361 void DidProcessTask(const base::PendingTask& pending_task) override {
362 #if !defined(OS_IOS) // No ProcessMetrics on IOS.
363 scoped_ptr<base::ProcessMetrics> process_metrics(
364 base::ProcessMetrics::CreateProcessMetrics(
365 #if defined(OS_MACOSX)
366 base::GetCurrentProcessHandle(), NULL));
367 #else
368 base::GetCurrentProcessHandle()));
369 #endif
370 size_t private_bytes;
371 process_metrics->GetMemoryBytes(&private_bytes, NULL);
372 LOCAL_HISTOGRAM_MEMORY_KB("Memory.BrowserUsed", private_bytes >> 10);
373 #endif
375 private:
376 DISALLOW_COPY_AND_ASSIGN(MemoryObserver);
380 // BrowserMainLoop construction / destruction =============================
382 BrowserMainLoop* BrowserMainLoop::GetInstance() {
383 DCHECK_CURRENTLY_ON(BrowserThread::UI);
384 return g_current_browser_main_loop;
387 BrowserMainLoop::BrowserMainLoop(const MainFunctionParams& parameters)
388 : parameters_(parameters),
389 parsed_command_line_(parameters.command_line),
390 result_code_(RESULT_CODE_NORMAL_EXIT),
391 created_threads_(false),
392 // ContentMainRunner should have enabled tracing of the browser process
393 // when kTraceStartup is in the command line.
394 is_tracing_startup_(
395 parameters.command_line.HasSwitch(switches::kTraceStartup)) {
396 DCHECK(!g_current_browser_main_loop);
397 g_current_browser_main_loop = this;
400 BrowserMainLoop::~BrowserMainLoop() {
401 DCHECK_EQ(this, g_current_browser_main_loop);
402 #if !defined(OS_IOS)
403 ui::Clipboard::DestroyClipboardForCurrentThread();
404 #endif // !defined(OS_IOS)
405 g_current_browser_main_loop = NULL;
408 void BrowserMainLoop::Init() {
409 TRACE_EVENT0("startup", "BrowserMainLoop::Init");
410 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::Init");
412 parts_.reset(
413 GetContentClient()->browser()->CreateBrowserMainParts(parameters_));
416 // BrowserMainLoop stages ==================================================
418 void BrowserMainLoop::EarlyInitialization() {
419 TRACE_EVENT0("startup", "BrowserMainLoop::EarlyInitialization");
420 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::EarlyInitialization");
422 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
423 // No thread should be created before this call, as SetupSandbox()
424 // will end-up using fork().
425 SetupSandbox(parsed_command_line_);
426 #endif
428 #if defined(USE_X11)
429 if (UsingInProcessGpu()) {
430 if (!gfx::InitializeThreadedX11()) {
431 LOG(ERROR) << "Failed to put Xlib into threaded mode.";
434 #endif
436 // GLib's spawning of new processes is buggy, so it's important that at this
437 // point GLib does not need to start DBUS. Chrome should always start with
438 // DBUS_SESSION_BUS_ADDRESS properly set. See crbug.com/309093.
439 #if defined(USE_GLIB)
440 // g_type_init will be deprecated in 2.36. 2.35 is the development
441 // version for 2.36, hence do not call g_type_init starting 2.35.
442 // http://developer.gnome.org/gobject/unstable/gobject-Type-Information.html#g-type-init
443 #if !GLIB_CHECK_VERSION(2, 35, 0)
444 // GLib type system initialization. Needed at least for gconf,
445 // used in net/proxy/proxy_config_service_linux.cc. Most likely
446 // this is superfluous as gtk_init() ought to do this. It's
447 // definitely harmless, so retained as a reminder of this
448 // requirement for gconf.
449 g_type_init();
450 #endif
452 SetUpGLibLogHandler();
453 #endif
455 if (parts_)
456 parts_->PreEarlyInitialization();
458 #if defined(OS_MACOSX)
459 // We use quite a few file descriptors for our IPC, and the default limit on
460 // the Mac is low (256), so bump it up.
461 base::SetFdLimit(1024);
462 #endif
464 #if defined(OS_WIN)
465 net::EnsureWinsockInit();
466 #endif
468 #if !defined(USE_OPENSSL)
469 // We want to be sure to init NSPR on the main thread.
470 crypto::EnsureNSPRInit();
471 #endif // !defined(USE_OPENSSL)
473 #if !defined(OS_IOS)
474 if (parsed_command_line_.HasSwitch(switches::kRendererProcessLimit)) {
475 std::string limit_string = parsed_command_line_.GetSwitchValueASCII(
476 switches::kRendererProcessLimit);
477 size_t process_limit;
478 if (base::StringToSizeT(limit_string, &process_limit)) {
479 RenderProcessHost::SetMaxRendererProcessCount(process_limit);
482 #endif // !defined(OS_IOS)
484 // TODO(boliu): kSingleProcess check is a temporary workaround for
485 // in-process Android WebView. crbug.com/503724 tracks proper fix.
486 if (!parsed_command_line_.HasSwitch(switches::kSingleProcess)) {
487 base::DiscardableMemoryAllocator::SetInstance(
488 HostDiscardableSharedMemoryManager::current());
491 if (parts_)
492 parts_->PostEarlyInitialization();
495 void BrowserMainLoop::PreMainMessageLoopStart() {
496 if (parts_) {
497 TRACE_EVENT0("startup",
498 "BrowserMainLoop::MainMessageLoopStart:PreMainMessageLoopStart");
499 parts_->PreMainMessageLoopStart();
502 #if defined(OS_WIN)
503 // If we're running tests (ui_task is non-null), then the ResourceBundle
504 // has already been initialized.
505 if (!parameters_.ui_task) {
506 // Override the configured locale with the user's preferred UI language.
507 l10n_util::OverrideLocaleWithUILanguageList();
509 #endif
512 void BrowserMainLoop::MainMessageLoopStart() {
513 // DO NOT add more code here. Use PreMainMessageLoopStart() above or
514 // PostMainMessageLoopStart() below.
516 TRACE_EVENT0("startup", "BrowserMainLoop::MainMessageLoopStart");
517 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::MainMessageLoopStart");
519 // Create a MessageLoop if one does not already exist for the current thread.
520 if (!base::MessageLoop::current())
521 main_message_loop_.reset(new base::MessageLoopForUI);
523 InitializeMainThread();
526 void BrowserMainLoop::PostMainMessageLoopStart() {
528 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SystemMonitor");
529 system_monitor_.reset(new base::SystemMonitor);
532 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:PowerMonitor");
533 scoped_ptr<base::PowerMonitorSource> power_monitor_source(
534 new base::PowerMonitorDeviceSource());
535 power_monitor_.reset(new base::PowerMonitor(power_monitor_source.Pass()));
538 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:HighResTimerManager");
539 hi_res_timer_manager_.reset(new base::HighResolutionTimerManager);
542 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:NetworkChangeNotifier");
543 network_change_notifier_.reset(net::NetworkChangeNotifier::Create());
546 #if !defined(OS_IOS)
548 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MediaFeatures");
549 media::InitializeMediaLibrary();
552 TRACE_EVENT0("startup",
553 "BrowserMainLoop::Subsystem:ContentWebUIController");
554 WebUIControllerFactory::RegisterFactory(
555 ContentWebUIControllerFactory::GetInstance());
559 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:OnlineStateObserver");
560 online_state_observer_.reset(new BrowserOnlineStateObserver);
564 system_stats_monitor_.reset(
565 new base::trace_event::TraceEventSystemStatsMonitor(
566 base::ThreadTaskRunnerHandle::Get()));
568 #endif // !defined(OS_IOS)
570 #if defined(OS_WIN)
571 system_message_window_.reset(new SystemMessageWindowWin);
572 #endif
574 if (parts_)
575 parts_->PostMainMessageLoopStart();
577 #if !defined(OS_IOS)
578 // Start tracing to a file if needed. Only do this after starting the main
579 // message loop to avoid calling MessagePumpForUI::ScheduleWork() before
580 // MessagePumpForUI::Start() as it will crash the browser.
581 if (is_tracing_startup_) {
582 TRACE_EVENT0("startup", "BrowserMainLoop::InitStartupTracing");
583 InitStartupTracing(parsed_command_line_);
585 #endif // !defined(OS_IOS)
587 #if defined(OS_ANDROID)
589 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SurfaceTextureManager");
590 if (parsed_command_line_.HasSwitch(switches::kSingleProcess)) {
591 SurfaceTextureManager::SetInstance(
592 InProcessSurfaceTextureManager::GetInstance());
593 } else {
594 SurfaceTextureManager::SetInstance(
595 BrowserSurfaceTextureManager::GetInstance());
599 if (!parsed_command_line_.HasSwitch(
600 switches::kDisableScreenOrientationLock)) {
601 TRACE_EVENT0("startup",
602 "BrowserMainLoop::Subsystem:ScreenOrientationProvider");
603 screen_orientation_delegate_.reset(
604 new ScreenOrientationDelegateAndroid());
605 ScreenOrientationProvider::SetDelegate(screen_orientation_delegate_.get());
607 #endif
609 #if defined(OS_MACOSX) && !defined(OS_IOS)
611 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:IOSurfaceManager");
612 if (parsed_command_line_.HasSwitch(switches::kSingleProcess)) {
613 IOSurfaceManager::SetInstance(InProcessIOSurfaceManager::GetInstance());
614 } else {
615 IOSurfaceManager::SetInstance(BrowserIOSurfaceManager::GetInstance());
618 #endif
620 #if defined(USE_OZONE)
621 client_native_pixmap_factory_ = ui::ClientNativePixmapFactory::Create();
622 ui::ClientNativePixmapFactory::SetInstance(
623 client_native_pixmap_factory_.get());
624 #endif
626 if (parsed_command_line_.HasSwitch(switches::kMemoryMetrics)) {
627 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MemoryObserver");
628 memory_observer_.reset(new MemoryObserver());
629 base::MessageLoop::current()->AddTaskObserver(memory_observer_.get());
632 if (parsed_command_line_.HasSwitch(
633 switches::kEnableAggressiveDOMStorageFlushing)) {
634 TRACE_EVENT0("startup",
635 "BrowserMainLoop::Subsystem:EnableAggressiveCommitDelay");
636 DOMStorageArea::EnableAggressiveCommitDelay();
639 base::trace_event::MemoryDumpManager::GetInstance()->Initialize();
641 // Enable the dump providers.
642 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
643 HostSharedBitmapManager::current());
644 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
645 skia::SkiaMemoryDumpProvider::GetInstance());
647 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
648 trace_memory_controller_.reset(new base::trace_event::TraceMemoryController(
649 base::MessageLoop::current()->task_runner(),
650 ::HeapProfilerWithPseudoStackStart, ::HeapProfilerStop,
651 ::GetHeapProfile));
652 #endif
655 int BrowserMainLoop::PreCreateThreads() {
656 // Need to initialize in-process GpuDataManager before creating threads.
657 // It's unsafe to append the gpu command line switches to the global
658 // CommandLine::ForCurrentProcess object after threads are created.
659 // Also need to initialize before BrowserMainParts::PreCreateThreads, so
660 // BrowserMainParts has a hook to set GpuDataManager strings before
661 // starting Gpu process.
662 GpuDataManagerImpl::GetInstance()->Initialize();
664 if (parts_) {
665 TRACE_EVENT0("startup",
666 "BrowserMainLoop::CreateThreads:PreCreateThreads");
667 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::PreCreateThreads");
669 result_code_ = parts_->PreCreateThreads();
672 // TODO(chrisha): Abstract away this construction mess to a helper function,
673 // once MemoryPressureMonitor is made a concrete class.
674 #if defined(OS_CHROMEOS)
675 if (chromeos::switches::MemoryPressureHandlingEnabled()) {
676 memory_pressure_monitor_.reset(new base::chromeos::MemoryPressureMonitor(
677 chromeos::switches::GetMemoryPressureThresholds()));
679 #elif defined(OS_MACOSX) && !defined(OS_IOS)
680 memory_pressure_monitor_.reset(new base::mac::MemoryPressureMonitor());
681 #elif defined(OS_WIN)
682 memory_pressure_monitor_.reset(CreateWinMemoryPressureMonitor(
683 parsed_command_line_));
684 #endif
686 #if defined(ENABLE_PLUGINS)
687 // Prior to any processing happening on the io thread, we create the
688 // plugin service as it is predominantly used from the io thread,
689 // but must be created on the main thread. The service ctor is
690 // inexpensive and does not invoke the io_thread() accessor.
692 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads:PluginService");
693 PluginService::GetInstance()->Init();
695 #endif
697 #if defined(OS_MACOSX)
699 // Initialize AVFoundation if supported, for audio and video.
700 TRACE_EVENT0("startup",
701 "BrowserMainLoop::CreateThreads:InitializeAVFoundation");
702 AVFoundationGlue::InitializeAVFoundation();
704 #endif
706 #if !defined(OS_IOS) && (!defined(GOOGLE_CHROME_BUILD) || defined(OS_ANDROID))
707 // Single-process is an unsupported and not fully tested mode, so
708 // don't enable it for official Chrome builds (except on Android).
709 if (parsed_command_line_.HasSwitch(switches::kSingleProcess))
710 RenderProcessHost::SetRunRendererInProcess(true);
711 #endif
713 return result_code_;
716 void BrowserMainLoop::CreateStartupTasks() {
717 TRACE_EVENT0("startup", "BrowserMainLoop::CreateStartupTasks");
718 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::CreateStartupTasks");
720 // First time through, we really want to create all the tasks
721 if (!startup_task_runner_.get()) {
722 #if defined(OS_ANDROID)
723 startup_task_runner_ = make_scoped_ptr(
724 new StartupTaskRunner(base::Bind(&BrowserStartupComplete),
725 base::ThreadTaskRunnerHandle::Get()));
726 #else
727 startup_task_runner_ = make_scoped_ptr(
728 new StartupTaskRunner(base::Callback<void(int)>(),
729 base::ThreadTaskRunnerHandle::Get()));
730 #endif
731 StartupTask pre_create_threads =
732 base::Bind(&BrowserMainLoop::PreCreateThreads, base::Unretained(this));
733 startup_task_runner_->AddTask(pre_create_threads);
735 StartupTask create_threads =
736 base::Bind(&BrowserMainLoop::CreateThreads, base::Unretained(this));
737 startup_task_runner_->AddTask(create_threads);
739 StartupTask browser_thread_started = base::Bind(
740 &BrowserMainLoop::BrowserThreadsStarted, base::Unretained(this));
741 startup_task_runner_->AddTask(browser_thread_started);
743 StartupTask pre_main_message_loop_run = base::Bind(
744 &BrowserMainLoop::PreMainMessageLoopRun, base::Unretained(this));
745 startup_task_runner_->AddTask(pre_main_message_loop_run);
747 #if defined(OS_ANDROID)
748 if (BrowserMayStartAsynchronously()) {
749 startup_task_runner_->StartRunningTasksAsync();
751 #endif
753 #if defined(OS_ANDROID)
754 if (!BrowserMayStartAsynchronously()) {
755 // A second request for asynchronous startup can be ignored, so
756 // StartupRunningTasksAsync is only called first time through. If, however,
757 // this is a request for synchronous startup then it must override any
758 // previous call for async startup, so we call RunAllTasksNow()
759 // unconditionally.
760 startup_task_runner_->RunAllTasksNow();
762 #else
763 startup_task_runner_->RunAllTasksNow();
764 #endif
767 int BrowserMainLoop::CreateThreads() {
768 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads");
769 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::CreateThreads");
771 base::Thread::Options io_message_loop_options;
772 io_message_loop_options.message_loop_type = base::MessageLoop::TYPE_IO;
773 base::Thread::Options ui_message_loop_options;
774 ui_message_loop_options.message_loop_type = base::MessageLoop::TYPE_UI;
776 // Start threads in the order they occur in the BrowserThread::ID
777 // enumeration, except for BrowserThread::UI which is the main
778 // thread.
780 // Must be size_t so we can increment it.
781 for (size_t thread_id = BrowserThread::UI + 1;
782 thread_id < BrowserThread::ID_COUNT;
783 ++thread_id) {
784 scoped_ptr<BrowserProcessSubThread>* thread_to_start = NULL;
785 base::Thread::Options options;
787 switch (thread_id) {
788 case BrowserThread::DB:
789 TRACE_EVENT_BEGIN1("startup",
790 "BrowserMainLoop::CreateThreads:start",
791 "Thread", "BrowserThread::DB");
792 thread_to_start = &db_thread_;
793 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
794 break;
795 case BrowserThread::FILE_USER_BLOCKING:
796 TRACE_EVENT_BEGIN1("startup",
797 "BrowserMainLoop::CreateThreads:start",
798 "Thread", "BrowserThread::FILE_USER_BLOCKING");
799 thread_to_start = &file_user_blocking_thread_;
800 break;
801 case BrowserThread::FILE:
802 TRACE_EVENT_BEGIN1("startup",
803 "BrowserMainLoop::CreateThreads:start",
804 "Thread", "BrowserThread::FILE");
805 thread_to_start = &file_thread_;
806 #if defined(OS_WIN)
807 // On Windows, the FILE thread needs to be have a UI message loop
808 // which pumps messages in such a way that Google Update can
809 // communicate back to us.
810 options = ui_message_loop_options;
811 #else
812 options = io_message_loop_options;
813 #endif
814 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
815 break;
816 case BrowserThread::PROCESS_LAUNCHER:
817 TRACE_EVENT_BEGIN1("startup",
818 "BrowserMainLoop::CreateThreads:start",
819 "Thread", "BrowserThread::PROCESS_LAUNCHER");
820 thread_to_start = &process_launcher_thread_;
821 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
822 break;
823 case BrowserThread::CACHE:
824 TRACE_EVENT_BEGIN1("startup",
825 "BrowserMainLoop::CreateThreads:start",
826 "Thread", "BrowserThread::CACHE");
827 thread_to_start = &cache_thread_;
828 options = io_message_loop_options;
829 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
830 break;
831 case BrowserThread::IO:
832 TRACE_EVENT_BEGIN1("startup",
833 "BrowserMainLoop::CreateThreads:start",
834 "Thread", "BrowserThread::IO");
835 thread_to_start = &io_thread_;
836 options = io_message_loop_options;
837 #if defined(OS_ANDROID)
838 // Up the priority of the |io_thread_| as some of its IPCs relate to
839 // display tasks.
840 options.priority = base::ThreadPriority::DISPLAY;
841 #endif
842 break;
843 case BrowserThread::UI:
844 case BrowserThread::ID_COUNT:
845 default:
846 NOTREACHED();
847 break;
850 BrowserThread::ID id = static_cast<BrowserThread::ID>(thread_id);
852 if (thread_to_start) {
853 (*thread_to_start).reset(new BrowserProcessSubThread(id));
854 if (!(*thread_to_start)->StartWithOptions(options)) {
855 LOG(FATAL) << "Failed to start the browser thread: id == " << id;
857 } else {
858 NOTREACHED();
861 TRACE_EVENT_END0("startup", "BrowserMainLoop::CreateThreads:start");
863 created_threads_ = true;
864 return result_code_;
867 int BrowserMainLoop::PreMainMessageLoopRun() {
868 if (parts_) {
869 TRACE_EVENT0("startup",
870 "BrowserMainLoop::CreateThreads:PreMainMessageLoopRun");
871 TRACK_SCOPED_REGION(
872 "Startup", "BrowserMainLoop::PreMainMessageLoopRun");
874 parts_->PreMainMessageLoopRun();
877 // If the UI thread blocks, the whole UI is unresponsive.
878 // Do not allow disk IO from the UI thread.
879 base::ThreadRestrictions::SetIOAllowed(false);
880 base::ThreadRestrictions::DisallowWaiting();
881 return result_code_;
884 void BrowserMainLoop::RunMainMessageLoopParts() {
885 TRACE_EVENT_BEGIN_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
887 bool ran_main_loop = false;
888 if (parts_)
889 ran_main_loop = parts_->MainMessageLoopRun(&result_code_);
891 if (!ran_main_loop)
892 MainMessageLoopRun();
894 TRACE_EVENT_END_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
897 void BrowserMainLoop::ShutdownThreadsAndCleanUp() {
898 if (!created_threads_) {
899 // Called early, nothing to do
900 return;
902 TRACE_EVENT0("shutdown", "BrowserMainLoop::ShutdownThreadsAndCleanUp");
904 // Teardown may start in PostMainMessageLoopRun, and during teardown we
905 // need to be able to perform IO.
906 base::ThreadRestrictions::SetIOAllowed(true);
907 BrowserThread::PostTask(
908 BrowserThread::IO, FROM_HERE,
909 base::Bind(base::IgnoreResult(&base::ThreadRestrictions::SetIOAllowed),
910 true));
912 mojo_shell_context_.reset();
914 #if !defined(OS_IOS)
915 if (RenderProcessHost::run_renderer_in_process())
916 RenderProcessHostImpl::ShutDownInProcessRenderer();
917 #endif
919 if (parts_) {
920 TRACE_EVENT0("shutdown",
921 "BrowserMainLoop::Subsystem:PostMainMessageLoopRun");
922 parts_->PostMainMessageLoopRun();
925 #if defined(USE_AURA)
926 aura::Env::DeleteInstance();
927 #endif
929 trace_memory_controller_.reset();
930 system_stats_monitor_.reset();
932 #if !defined(OS_IOS)
933 // Destroying the GpuProcessHostUIShims on the UI thread posts a task to
934 // delete related objects on the GPU thread. This must be done before
935 // stopping the GPU thread. The GPU thread will close IPC channels to renderer
936 // processes so this has to happen before stopping the IO thread.
938 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUProcessHostShim");
939 GpuProcessHostUIShim::DestroyAll();
941 // Cancel pending requests and prevent new requests.
942 if (resource_dispatcher_host_) {
943 TRACE_EVENT0("shutdown",
944 "BrowserMainLoop::Subsystem:ResourceDispatcherHost");
945 resource_dispatcher_host_.get()->Shutdown();
948 memory_pressure_monitor_.reset();
950 #if defined(OS_MACOSX)
951 BrowserCompositorMac::DisableRecyclingForShutdown();
952 #endif
954 #if defined(USE_AURA) || defined(OS_MACOSX)
956 TRACE_EVENT0("shutdown",
957 "BrowserMainLoop::Subsystem:ImageTransportFactory");
958 ImageTransportFactory::Terminate();
960 #endif
962 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
963 ZygoteHostImpl::GetInstance()->TearDownAfterLastChild();
964 #endif // defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
966 // The device monitors are using |system_monitor_| as dependency, so delete
967 // them before |system_monitor_| goes away.
968 // On Mac and windows, the monitor needs to be destroyed on the same thread
969 // as they were created. On Linux, the monitor will be deleted when IO thread
970 // goes away.
971 #if defined(OS_WIN)
972 system_message_window_.reset();
973 #elif defined(OS_MACOSX)
974 device_monitor_mac_.reset();
975 #endif
976 #endif // !defined(OS_IOS)
978 // Must be size_t so we can subtract from it.
979 for (size_t thread_id = BrowserThread::ID_COUNT - 1;
980 thread_id >= (BrowserThread::UI + 1);
981 --thread_id) {
982 // Find the thread object we want to stop. Looping over all valid
983 // BrowserThread IDs and DCHECKing on a missing case in the switch
984 // statement helps avoid a mismatch between this code and the
985 // BrowserThread::ID enumeration.
987 // The destruction order is the reverse order of occurrence in the
988 // BrowserThread::ID list. The rationale for the order is as
989 // follows (need to be filled in a bit):
992 // - The IO thread is the only user of the CACHE thread.
994 // - The PROCESS_LAUNCHER thread must be stopped after IO in case
995 // the IO thread posted a task to terminate a process on the
996 // process launcher thread.
998 // - (Not sure why DB stops last.)
999 switch (thread_id) {
1000 case BrowserThread::DB: {
1001 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DBThread");
1002 ResetThread_DB(db_thread_.Pass());
1003 break;
1005 case BrowserThread::FILE: {
1006 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:FileThread");
1007 #if !defined(OS_IOS)
1008 // Clean up state that lives on or uses the file_thread_ before
1009 // it goes away.
1010 if (resource_dispatcher_host_)
1011 resource_dispatcher_host_.get()->save_file_manager()->Shutdown();
1012 #endif // !defined(OS_IOS)
1013 ResetThread_FILE(file_thread_.Pass());
1014 break;
1016 case BrowserThread::FILE_USER_BLOCKING: {
1017 TRACE_EVENT0("shutdown",
1018 "BrowserMainLoop::Subsystem:FileUserBlockingThread");
1019 ResetThread_FILE_USER_BLOCKING(file_user_blocking_thread_.Pass());
1020 break;
1022 case BrowserThread::PROCESS_LAUNCHER: {
1023 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:LauncherThread");
1024 ResetThread_PROCESS_LAUNCHER(process_launcher_thread_.Pass());
1025 break;
1027 case BrowserThread::CACHE: {
1028 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:CacheThread");
1029 ResetThread_CACHE(cache_thread_.Pass());
1030 break;
1032 case BrowserThread::IO: {
1033 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IOThread");
1034 ResetThread_IO(io_thread_.Pass());
1035 break;
1037 case BrowserThread::UI:
1038 case BrowserThread::ID_COUNT:
1039 default:
1040 NOTREACHED();
1041 break;
1045 #if !defined(OS_IOS)
1047 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IndexedDBThread");
1048 ResetThread_IndexedDb(indexed_db_thread_.Pass());
1050 #endif
1052 // Close the blocking I/O pool after the other threads. Other threads such
1053 // as the I/O thread may need to schedule work like closing files or flushing
1054 // data during shutdown, so the blocking pool needs to be available. There
1055 // may also be slow operations pending that will blcok shutdown, so closing
1056 // it here (which will block until required operations are complete) gives
1057 // more head start for those operations to finish.
1059 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:ThreadPool");
1060 BrowserThreadImpl::ShutdownThreadPool();
1063 #if !defined(OS_IOS)
1064 // Must happen after the IO thread is shutdown since this may be accessed from
1065 // it.
1067 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUChannelFactory");
1068 if (BrowserGpuChannelHostFactory::instance())
1069 BrowserGpuChannelHostFactory::Terminate();
1072 // Must happen after the I/O thread is shutdown since this class lives on the
1073 // I/O thread and isn't threadsafe.
1075 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GamepadService");
1076 GamepadService::GetInstance()->Terminate();
1079 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:SensorService");
1080 DeviceInertialSensorService::GetInstance()->Shutdown();
1083 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:BatteryStatusService");
1084 device::BatteryStatusService::GetInstance()->Shutdown();
1087 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DeleteDataSources");
1088 URLDataManager::DeleteDataSources();
1090 #endif // !defined(OS_IOS)
1092 if (parts_) {
1093 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:PostDestroyThreads");
1094 parts_->PostDestroyThreads();
1098 void BrowserMainLoop::StopStartupTracingTimer() {
1099 startup_trace_timer_.Stop();
1102 void BrowserMainLoop::InitializeMainThread() {
1103 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeMainThread");
1104 static const char kThreadName[] = "CrBrowserMain";
1105 base::PlatformThread::SetName(kThreadName);
1106 if (main_message_loop_)
1107 main_message_loop_->set_thread_name(kThreadName);
1109 // Register the main thread by instantiating it, but don't call any methods.
1110 main_thread_.reset(
1111 new BrowserThreadImpl(BrowserThread::UI, base::MessageLoop::current()));
1114 int BrowserMainLoop::BrowserThreadsStarted() {
1115 TRACE_EVENT0("startup", "BrowserMainLoop::BrowserThreadsStarted");
1117 #if !defined(OS_IOS)
1118 indexed_db_thread_.reset(new base::Thread("IndexedDB"));
1119 indexed_db_thread_->Start();
1120 #endif
1122 #if !defined(OS_IOS)
1123 HistogramSynchronizer::GetInstance();
1125 #if defined(OS_ANDROID)
1126 // Up the priority of the UI thread.
1127 base::PlatformThread::SetCurrentThreadPriority(base::ThreadPriority::DISPLAY);
1128 #endif
1130 bool always_uses_gpu = true;
1131 bool established_gpu_channel = false;
1132 #if defined(OS_ANDROID)
1133 // TODO(crbug.com/439322): This should be set to |true|.
1134 established_gpu_channel = false;
1135 BrowserGpuChannelHostFactory::Initialize(established_gpu_channel);
1136 #elif defined(USE_AURA) || defined(OS_MACOSX)
1137 established_gpu_channel = true;
1138 if (!GpuDataManagerImpl::GetInstance()->CanUseGpuBrowserCompositor() ||
1139 parsed_command_line_.HasSwitch(switches::kDisableGpuEarlyInit)) {
1140 established_gpu_channel = always_uses_gpu = false;
1142 BrowserGpuChannelHostFactory::Initialize(established_gpu_channel);
1143 ImageTransportFactory::Initialize();
1144 #if defined(USE_AURA)
1145 if (aura::Env::GetInstance()) {
1146 aura::Env::GetInstance()->set_context_factory(GetContextFactory());
1148 #endif // defined(USE_AURA)
1149 #endif // defined(OS_ANDROID)
1151 // Enable the GpuMemoryBuffer dump provider with IO thread affinity. Note that
1152 // unregistration happens on the IO thread (See
1153 // BrowserProcessSubThread::IOThreadPreCleanUp).
1154 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
1155 BrowserGpuMemoryBufferManager::current(), io_thread_->task_runner());
1158 TRACE_EVENT0("startup", "BrowserThreadsStarted::Subsystem:AudioMan");
1159 audio_manager_.reset(media::AudioManager::CreateWithHangTimer(
1160 MediaInternals::GetInstance(), io_thread_->task_runner()));
1164 TRACE_EVENT0("startup", "BrowserThreadsStarted::Subsystem:MidiManager");
1165 midi_manager_.reset(media::midi::MidiManager::Create());
1168 #if defined(OS_LINUX) && defined(USE_UDEV)
1169 device_monitor_linux_.reset(new DeviceMonitorLinux());
1170 #elif defined(OS_MACOSX)
1171 device_monitor_mac_.reset(new DeviceMonitorMac());
1172 #endif
1174 #if defined(OS_WIN)
1175 UMA_HISTOGRAM_BOOLEAN("Windows.Win32kRendererLockdown",
1176 IsWin32kRendererLockdownEnabled());
1177 #endif
1178 // RDH needs the IO thread to be created
1180 TRACE_EVENT0("startup",
1181 "BrowserMainLoop::BrowserThreadsStarted:InitResourceDispatcherHost");
1182 resource_dispatcher_host_.reset(new ResourceDispatcherHostImpl());
1185 // MediaStreamManager needs the IO thread to be created.
1187 TRACE_EVENT0("startup",
1188 "BrowserMainLoop::BrowserThreadsStarted:InitMediaStreamManager");
1189 media_stream_manager_.reset(new MediaStreamManager(audio_manager_.get()));
1193 TRACE_EVENT0("startup",
1194 "BrowserMainLoop::BrowserThreadsStarted:InitSpeechRecognition");
1195 speech_recognition_manager_.reset(new SpeechRecognitionManagerImpl(
1196 audio_manager_.get(), media_stream_manager_.get()));
1200 TRACE_EVENT0(
1201 "startup",
1202 "BrowserMainLoop::BrowserThreadsStarted::InitUserInputMonitor");
1203 user_input_monitor_ = media::UserInputMonitor::Create(
1204 io_thread_->task_runner(), main_thread_->task_runner());
1208 TRACE_EVENT0("startup",
1209 "BrowserMainLoop::BrowserThreadsStarted::TimeZoneMonitor");
1210 time_zone_monitor_ = TimeZoneMonitor::Create();
1213 // Alert the clipboard class to which threads are allowed to access the
1214 // clipboard:
1215 std::vector<base::PlatformThreadId> allowed_clipboard_threads;
1216 // The current thread is the UI thread.
1217 allowed_clipboard_threads.push_back(base::PlatformThread::CurrentId());
1218 #if defined(OS_WIN)
1219 // On Windows, clipboards are also used on the FILE or IO threads.
1220 allowed_clipboard_threads.push_back(file_thread_->GetThreadId());
1221 allowed_clipboard_threads.push_back(io_thread_->GetThreadId());
1222 #endif
1223 ui::Clipboard::SetAllowedThreads(allowed_clipboard_threads);
1225 // When running the GPU thread in-process, avoid optimistically starting it
1226 // since creating the GPU thread races against creation of the one-and-only
1227 // ChildProcess instance which is created by the renderer thread.
1228 if (GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL) &&
1229 !established_gpu_channel &&
1230 always_uses_gpu &&
1231 !UsingInProcessGpu()) {
1232 TRACE_EVENT_INSTANT0("gpu", "Post task to launch GPU process",
1233 TRACE_EVENT_SCOPE_THREAD);
1234 BrowserThread::PostTask(
1235 BrowserThread::IO, FROM_HERE,
1236 base::Bind(base::IgnoreResult(&GpuProcessHost::Get),
1237 GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED,
1238 CAUSE_FOR_GPU_LAUNCH_BROWSER_STARTUP));
1241 #if defined(OS_MACOSX)
1242 ThemeHelperMac::GetInstance();
1243 SystemHotkeyHelperMac::GetInstance()->DeferredLoadSystemHotkeys();
1244 if (ShouldEnableBootstrapSandbox()) {
1245 TRACE_EVENT0("startup",
1246 "BrowserMainLoop::BrowserThreadsStarted:BootstrapSandbox");
1247 CHECK(GetBootstrapSandbox());
1249 #endif // defined(OS_MACOSX)
1251 #endif // !defined(OS_IOS)
1253 mojo_shell_context_.reset(new MojoShellContext);
1255 return result_code_;
1258 bool BrowserMainLoop::UsingInProcessGpu() const {
1259 return parsed_command_line_.HasSwitch(switches::kSingleProcess) ||
1260 parsed_command_line_.HasSwitch(switches::kInProcessGPU);
1263 bool BrowserMainLoop::InitializeToolkit() {
1264 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeToolkit");
1265 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::InitializeToolkit");
1267 // TODO(evan): this function is rather subtle, due to the variety
1268 // of intersecting ifdefs we have. To keep it easy to follow, there
1269 // are no #else branches on any #ifs.
1270 // TODO(stevenjb): Move platform specific code into platform specific Parts
1271 // (Need to add InitializeToolkit stage to BrowserParts).
1272 // See also GTK setup in EarlyInitialization, above, and associated comments.
1274 #if defined(OS_WIN)
1275 // Init common control sex.
1276 INITCOMMONCONTROLSEX config;
1277 config.dwSize = sizeof(config);
1278 config.dwICC = ICC_WIN95_CLASSES;
1279 if (!InitCommonControlsEx(&config))
1280 PLOG(FATAL);
1281 #endif
1283 #if defined(USE_AURA)
1285 #if defined(USE_X11)
1286 if (!gfx::GetXDisplay())
1287 return false;
1288 #endif
1290 // Env creates the compositor. Aura widgets need the compositor to be created
1291 // before they can be initialized by the browser.
1292 aura::Env::CreateInstance(true);
1293 #endif // defined(USE_AURA)
1295 if (parts_)
1296 parts_->ToolkitInitialized();
1298 return true;
1301 void BrowserMainLoop::MainMessageLoopRun() {
1302 #if defined(OS_ANDROID)
1303 // Android's main message loop is the Java message loop.
1304 NOTREACHED();
1305 #else
1306 DCHECK(base::MessageLoopForUI::IsCurrent());
1307 if (parameters_.ui_task) {
1308 base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
1309 *parameters_.ui_task);
1312 base::RunLoop run_loop;
1313 run_loop.Run();
1314 #endif
1317 base::FilePath BrowserMainLoop::GetStartupTraceFileName(
1318 const base::CommandLine& command_line) const {
1319 base::FilePath trace_file = command_line.GetSwitchValuePath(
1320 switches::kTraceStartupFile);
1321 // trace_file = "none" means that startup events will show up for the next
1322 // begin/end tracing (via about:tracing or AutomationProxy::BeginTracing/
1323 // EndTracing, for example).
1324 if (trace_file == base::FilePath().AppendASCII("none"))
1325 return trace_file;
1327 if (trace_file.empty()) {
1328 #if defined(OS_ANDROID)
1329 TracingControllerAndroid::GenerateTracingFilePath(&trace_file);
1330 #else
1331 // Default to saving the startup trace into the current dir.
1332 trace_file = base::FilePath().AppendASCII("chrometrace.log");
1333 #endif
1336 return trace_file;
1339 void BrowserMainLoop::InitStartupTracing(
1340 const base::CommandLine& command_line) {
1341 DCHECK(is_tracing_startup_);
1343 startup_trace_file_ = GetStartupTraceFileName(parsed_command_line_);
1345 std::string delay_str = command_line.GetSwitchValueASCII(
1346 switches::kTraceStartupDuration);
1347 int delay_secs = 5;
1348 if (!delay_str.empty() && !base::StringToInt(delay_str, &delay_secs)) {
1349 DLOG(WARNING) << "Could not parse --" << switches::kTraceStartupDuration
1350 << "=" << delay_str << " defaulting to 5 (secs)";
1351 delay_secs = 5;
1354 startup_trace_timer_.Start(FROM_HERE,
1355 base::TimeDelta::FromSeconds(delay_secs),
1356 this,
1357 &BrowserMainLoop::EndStartupTracing);
1360 void BrowserMainLoop::EndStartupTracing() {
1361 DCHECK(is_tracing_startup_);
1363 is_tracing_startup_ = false;
1364 TracingController::GetInstance()->DisableRecording(
1365 TracingController::CreateFileSink(
1366 startup_trace_file_,
1367 base::Bind(OnStoppedStartupTracing, startup_trace_file_)));
1370 } // namespace content