Add long running gmail memory benchmark for background tab.
[chromium-blink-merge.git] / content / browser / browser_main_loop.cc
blob0e38b9ceae3e5dcd100b66964411ab3b9868b504
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(OS_WIN)
112 #include <windows.h>
113 #include <commctrl.h>
114 #include <shellapi.h>
116 #include "base/memory/memory_pressure_monitor_win.h"
117 #include "content/browser/system_message_window_win.h"
118 #include "content/common/sandbox_win.h"
119 #include "net/base/winsock_init.h"
120 #include "ui/base/l10n/l10n_util_win.h"
121 #endif
123 #if defined(OS_CHROMEOS)
124 #include "base/memory/memory_pressure_monitor_chromeos.h"
125 #include "chromeos/chromeos_switches.h"
126 #endif
128 #if defined(USE_GLIB)
129 #include <glib-object.h>
130 #endif
132 #if defined(OS_LINUX) && defined(USE_UDEV)
133 #include "content/browser/device_monitor_udev.h"
134 #elif defined(OS_MACOSX) && !defined(OS_IOS)
135 #include "content/browser/device_monitor_mac.h"
136 #endif
138 #if defined(OS_POSIX) && !defined(OS_MACOSX)
139 #include "content/browser/renderer_host/render_sandbox_host_linux.h"
140 #include "content/browser/zygote_host/zygote_host_impl_linux.h"
141 #include "sandbox/linux/suid/client/setuid_sandbox_host.h"
142 #endif
144 #if defined(ENABLE_PLUGINS)
145 #include "content/browser/plugin_service_impl.h"
146 #endif
148 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
149 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
150 #endif
152 #if defined(USE_X11)
153 #include "ui/gfx/x/x11_connection.h"
154 #include "ui/gfx/x/x11_types.h"
155 #endif
157 // One of the linux specific headers defines this as a macro.
158 #ifdef DestroyAll
159 #undef DestroyAll
160 #endif
162 namespace content {
163 namespace {
165 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
166 void SetupSandbox(const base::CommandLine& parsed_command_line) {
167 TRACE_EVENT0("startup", "SetupSandbox");
168 base::FilePath sandbox_binary;
170 scoped_ptr<sandbox::SetuidSandboxHost> setuid_sandbox_host(
171 sandbox::SetuidSandboxHost::Create());
173 const bool want_setuid_sandbox =
174 !parsed_command_line.HasSwitch(switches::kNoSandbox) &&
175 !parsed_command_line.HasSwitch(switches::kDisableSetuidSandbox) &&
176 !setuid_sandbox_host->IsDisabledViaEnvironment();
178 static const char no_suid_error[] =
179 "Running without the SUID sandbox! See "
180 "https://code.google.com/p/chromium/wiki/LinuxSUIDSandboxDevelopment "
181 "for more information on developing with the sandbox on.";
182 if (want_setuid_sandbox) {
183 sandbox_binary = setuid_sandbox_host->GetSandboxBinaryPath();
184 if (sandbox_binary.empty()) {
185 // This needs to be fatal. Talk to security@chromium.org if you feel
186 // otherwise.
187 LOG(FATAL) << no_suid_error;
189 } else {
190 LOG(ERROR) << no_suid_error;
193 // Tickle the sandbox host and zygote host so they fork now.
194 RenderSandboxHostLinux::GetInstance()->Init();
195 ZygoteHostImpl::GetInstance()->Init(sandbox_binary.value());
197 #endif
199 #if defined(USE_GLIB)
200 static void GLibLogHandler(const gchar* log_domain,
201 GLogLevelFlags log_level,
202 const gchar* message,
203 gpointer userdata) {
204 if (!log_domain)
205 log_domain = "<unknown>";
206 if (!message)
207 message = "<no message>";
209 if (strstr(message, "Unable to retrieve the file info for")) {
210 LOG(ERROR) << "GTK File code error: " << message;
211 } else if (strstr(message, "Could not find the icon") &&
212 strstr(log_domain, "Gtk")) {
213 LOG(ERROR) << "GTK icon error: " << message;
214 } else if (strstr(message, "Theme file for default has no") ||
215 strstr(message, "Theme directory") ||
216 strstr(message, "theme pixmap") ||
217 strstr(message, "locate theme engine")) {
218 LOG(ERROR) << "GTK theme error: " << message;
219 } else if (strstr(message, "Unable to create Ubuntu Menu Proxy") &&
220 strstr(log_domain, "<unknown>")) {
221 LOG(ERROR) << "GTK menu proxy create failed";
222 } else if (strstr(message, "Out of memory") &&
223 strstr(log_domain, "<unknown>")) {
224 LOG(ERROR) << "DBus call timeout or out of memory: "
225 << "http://crosbug.com/15496";
226 } else if (strstr(message, "Could not connect: Connection refused") &&
227 strstr(log_domain, "<unknown>")) {
228 LOG(ERROR) << "DConf settings backend could not connect to session bus: "
229 << "http://crbug.com/179797";
230 } else if (strstr(message, "Attempting to store changes into") ||
231 strstr(message, "Attempting to set the permissions of")) {
232 LOG(ERROR) << message << " (http://bugs.chromium.org/161366)";
233 } else if (strstr(message, "drawable is not a native X11 window")) {
234 LOG(ERROR) << message << " (http://bugs.chromium.org/329991)";
235 } else if (strstr(message, "Cannot do system-bus activation with no user")) {
236 LOG(ERROR) << message << " (http://crbug.com/431005)";
237 } else {
238 LOG(DFATAL) << log_domain << ": " << message;
242 static void SetUpGLibLogHandler() {
243 // Register GLib-handled assertions to go through our logging system.
244 const char* kLogDomains[] = { NULL, "Gtk", "Gdk", "GLib", "GLib-GObject" };
245 for (size_t i = 0; i < arraysize(kLogDomains); i++) {
246 g_log_set_handler(kLogDomains[i],
247 static_cast<GLogLevelFlags>(G_LOG_FLAG_RECURSION |
248 G_LOG_FLAG_FATAL |
249 G_LOG_LEVEL_ERROR |
250 G_LOG_LEVEL_CRITICAL |
251 G_LOG_LEVEL_WARNING),
252 GLibLogHandler,
253 NULL);
256 #endif
258 void OnStoppedStartupTracing(const base::FilePath& trace_file) {
259 VLOG(0) << "Completed startup tracing to " << trace_file.value();
262 // Disable optimizations for this block of functions so the compiler doesn't
263 // merge them all together. This makes it possible to tell what thread was
264 // unresponsive by inspecting the callstack.
265 MSVC_DISABLE_OPTIMIZE()
266 MSVC_PUSH_DISABLE_WARNING(4748)
268 NOINLINE void ResetThread_DB(scoped_ptr<BrowserProcessSubThread> thread) {
269 volatile int inhibit_comdat = __LINE__;
270 ALLOW_UNUSED_LOCAL(inhibit_comdat);
271 thread.reset();
274 NOINLINE void ResetThread_FILE(scoped_ptr<BrowserProcessSubThread> thread) {
275 volatile int inhibit_comdat = __LINE__;
276 ALLOW_UNUSED_LOCAL(inhibit_comdat);
277 thread.reset();
280 NOINLINE void ResetThread_FILE_USER_BLOCKING(
281 scoped_ptr<BrowserProcessSubThread> thread) {
282 volatile int inhibit_comdat = __LINE__;
283 ALLOW_UNUSED_LOCAL(inhibit_comdat);
284 thread.reset();
287 NOINLINE void ResetThread_PROCESS_LAUNCHER(
288 scoped_ptr<BrowserProcessSubThread> thread) {
289 volatile int inhibit_comdat = __LINE__;
290 ALLOW_UNUSED_LOCAL(inhibit_comdat);
291 thread.reset();
294 NOINLINE void ResetThread_CACHE(scoped_ptr<BrowserProcessSubThread> thread) {
295 volatile int inhibit_comdat = __LINE__;
296 ALLOW_UNUSED_LOCAL(inhibit_comdat);
297 thread.reset();
300 NOINLINE void ResetThread_IO(scoped_ptr<BrowserProcessSubThread> thread) {
301 volatile int inhibit_comdat = __LINE__;
302 ALLOW_UNUSED_LOCAL(inhibit_comdat);
303 thread.reset();
306 #if !defined(OS_IOS)
307 NOINLINE void ResetThread_IndexedDb(scoped_ptr<base::Thread> thread) {
308 volatile int inhibit_comdat = __LINE__;
309 ALLOW_UNUSED_LOCAL(inhibit_comdat);
310 thread.reset();
312 #endif
314 MSVC_POP_WARNING()
315 MSVC_ENABLE_OPTIMIZE();
317 #if defined(OS_WIN)
318 // Creates a memory pressure monitor using automatic thresholds, or those
319 // specified on the command-line. Ownership is passed to the caller.
320 base::win::MemoryPressureMonitor* CreateWinMemoryPressureMonitor(
321 const base::CommandLine& parsed_command_line) {
322 std::vector<std::string> thresholds;
323 base::SplitString(
324 parsed_command_line.GetSwitchValueASCII(
325 switches::kMemoryPressureThresholdsMb),
326 ',',
327 &thresholds);
329 int moderate_threshold_mb = 0;
330 int critical_threshold_mb = 0;
331 if (thresholds.size() == 2 &&
332 base::StringToInt(thresholds[0], &moderate_threshold_mb) &&
333 base::StringToInt(thresholds[1], &critical_threshold_mb) &&
334 moderate_threshold_mb >= critical_threshold_mb &&
335 critical_threshold_mb >= 0) {
336 return new base::win::MemoryPressureMonitor(moderate_threshold_mb,
337 critical_threshold_mb);
340 // In absence of valid switches use the automatic defaults.
341 return new base::win::MemoryPressureMonitor();
343 #endif // defined(OS_WIN)
345 } // namespace
347 // The currently-running BrowserMainLoop. There can be one or zero.
348 BrowserMainLoop* g_current_browser_main_loop = NULL;
350 // For measuring memory usage after each task. Behind a command line flag.
351 class BrowserMainLoop::MemoryObserver : public base::MessageLoop::TaskObserver {
352 public:
353 MemoryObserver() {}
354 ~MemoryObserver() override {}
356 void WillProcessTask(const base::PendingTask& pending_task) override {}
358 void DidProcessTask(const base::PendingTask& pending_task) override {
359 #if !defined(OS_IOS) // No ProcessMetrics on IOS.
360 scoped_ptr<base::ProcessMetrics> process_metrics(
361 base::ProcessMetrics::CreateProcessMetrics(
362 #if defined(OS_MACOSX)
363 base::GetCurrentProcessHandle(), NULL));
364 #else
365 base::GetCurrentProcessHandle()));
366 #endif
367 size_t private_bytes;
368 process_metrics->GetMemoryBytes(&private_bytes, NULL);
369 LOCAL_HISTOGRAM_MEMORY_KB("Memory.BrowserUsed", private_bytes >> 10);
370 #endif
372 private:
373 DISALLOW_COPY_AND_ASSIGN(MemoryObserver);
377 // BrowserMainLoop construction / destruction =============================
379 BrowserMainLoop* BrowserMainLoop::GetInstance() {
380 DCHECK_CURRENTLY_ON(BrowserThread::UI);
381 return g_current_browser_main_loop;
384 BrowserMainLoop::BrowserMainLoop(const MainFunctionParams& parameters)
385 : parameters_(parameters),
386 parsed_command_line_(parameters.command_line),
387 result_code_(RESULT_CODE_NORMAL_EXIT),
388 created_threads_(false),
389 // ContentMainRunner should have enabled tracing of the browser process
390 // when kTraceStartup is in the command line.
391 is_tracing_startup_(
392 parameters.command_line.HasSwitch(switches::kTraceStartup)) {
393 DCHECK(!g_current_browser_main_loop);
394 g_current_browser_main_loop = this;
397 BrowserMainLoop::~BrowserMainLoop() {
398 DCHECK_EQ(this, g_current_browser_main_loop);
399 #if !defined(OS_IOS)
400 ui::Clipboard::DestroyClipboardForCurrentThread();
401 #endif // !defined(OS_IOS)
402 g_current_browser_main_loop = NULL;
405 void BrowserMainLoop::Init() {
406 TRACE_EVENT0("startup", "BrowserMainLoop::Init");
407 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::Init");
409 parts_.reset(
410 GetContentClient()->browser()->CreateBrowserMainParts(parameters_));
413 // BrowserMainLoop stages ==================================================
415 void BrowserMainLoop::EarlyInitialization() {
416 TRACE_EVENT0("startup", "BrowserMainLoop::EarlyInitialization");
417 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::EarlyInitialization");
419 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
420 // No thread should be created before this call, as SetupSandbox()
421 // will end-up using fork().
422 SetupSandbox(parsed_command_line_);
423 #endif
425 #if defined(USE_X11)
426 if (UsingInProcessGpu()) {
427 if (!gfx::InitializeThreadedX11()) {
428 LOG(ERROR) << "Failed to put Xlib into threaded mode.";
431 #endif
433 // GLib's spawning of new processes is buggy, so it's important that at this
434 // point GLib does not need to start DBUS. Chrome should always start with
435 // DBUS_SESSION_BUS_ADDRESS properly set. See crbug.com/309093.
436 #if defined(USE_GLIB)
437 // g_type_init will be deprecated in 2.36. 2.35 is the development
438 // version for 2.36, hence do not call g_type_init starting 2.35.
439 // http://developer.gnome.org/gobject/unstable/gobject-Type-Information.html#g-type-init
440 #if !GLIB_CHECK_VERSION(2, 35, 0)
441 // GLib type system initialization. Needed at least for gconf,
442 // used in net/proxy/proxy_config_service_linux.cc. Most likely
443 // this is superfluous as gtk_init() ought to do this. It's
444 // definitely harmless, so retained as a reminder of this
445 // requirement for gconf.
446 g_type_init();
447 #endif
449 SetUpGLibLogHandler();
450 #endif
452 if (parts_)
453 parts_->PreEarlyInitialization();
455 #if defined(OS_MACOSX)
456 // We use quite a few file descriptors for our IPC, and the default limit on
457 // the Mac is low (256), so bump it up.
458 base::SetFdLimit(1024);
459 #endif
461 #if defined(OS_WIN)
462 net::EnsureWinsockInit();
463 #endif
465 #if !defined(USE_OPENSSL)
466 // We want to be sure to init NSPR on the main thread.
467 crypto::EnsureNSPRInit();
468 #endif // !defined(USE_OPENSSL)
470 #if !defined(OS_IOS)
471 if (parsed_command_line_.HasSwitch(switches::kRendererProcessLimit)) {
472 std::string limit_string = parsed_command_line_.GetSwitchValueASCII(
473 switches::kRendererProcessLimit);
474 size_t process_limit;
475 if (base::StringToSizeT(limit_string, &process_limit)) {
476 RenderProcessHost::SetMaxRendererProcessCount(process_limit);
479 #endif // !defined(OS_IOS)
481 // TODO(boliu): kSingleProcess check is a temporary workaround for
482 // in-process Android WebView. crbug.com/503724 tracks proper fix.
483 if (!parsed_command_line_.HasSwitch(switches::kSingleProcess)) {
484 base::DiscardableMemoryAllocator::SetInstance(
485 HostDiscardableSharedMemoryManager::current());
488 if (parts_)
489 parts_->PostEarlyInitialization();
492 void BrowserMainLoop::PreMainMessageLoopStart() {
493 if (parts_) {
494 TRACE_EVENT0("startup",
495 "BrowserMainLoop::MainMessageLoopStart:PreMainMessageLoopStart");
496 parts_->PreMainMessageLoopStart();
499 #if defined(OS_WIN)
500 // If we're running tests (ui_task is non-null), then the ResourceBundle
501 // has already been initialized.
502 if (!parameters_.ui_task) {
503 // Override the configured locale with the user's preferred UI language.
504 l10n_util::OverrideLocaleWithUILanguageList();
506 #endif
509 void BrowserMainLoop::MainMessageLoopStart() {
510 // DO NOT add more code here. Use PreMainMessageLoopStart() above or
511 // PostMainMessageLoopStart() below.
513 TRACE_EVENT0("startup", "BrowserMainLoop::MainMessageLoopStart");
514 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::MainMessageLoopStart");
516 // Create a MessageLoop if one does not already exist for the current thread.
517 if (!base::MessageLoop::current())
518 main_message_loop_.reset(new base::MessageLoopForUI);
520 InitializeMainThread();
523 void BrowserMainLoop::PostMainMessageLoopStart() {
525 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SystemMonitor");
526 system_monitor_.reset(new base::SystemMonitor);
529 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:PowerMonitor");
530 scoped_ptr<base::PowerMonitorSource> power_monitor_source(
531 new base::PowerMonitorDeviceSource());
532 power_monitor_.reset(new base::PowerMonitor(power_monitor_source.Pass()));
535 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:HighResTimerManager");
536 hi_res_timer_manager_.reset(new base::HighResolutionTimerManager);
539 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:NetworkChangeNotifier");
540 network_change_notifier_.reset(net::NetworkChangeNotifier::Create());
543 #if !defined(OS_IOS)
545 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MediaFeatures");
546 media::InitializeMediaLibrary();
549 TRACE_EVENT0("startup",
550 "BrowserMainLoop::Subsystem:ContentWebUIController");
551 WebUIControllerFactory::RegisterFactory(
552 ContentWebUIControllerFactory::GetInstance());
556 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:OnlineStateObserver");
557 online_state_observer_.reset(new BrowserOnlineStateObserver);
561 system_stats_monitor_.reset(
562 new base::trace_event::TraceEventSystemStatsMonitor(
563 base::ThreadTaskRunnerHandle::Get()));
565 #endif // !defined(OS_IOS)
567 #if defined(OS_WIN)
568 system_message_window_.reset(new SystemMessageWindowWin);
569 #endif
571 if (parts_)
572 parts_->PostMainMessageLoopStart();
574 #if !defined(OS_IOS)
575 // Start tracing to a file if needed. Only do this after starting the main
576 // message loop to avoid calling MessagePumpForUI::ScheduleWork() before
577 // MessagePumpForUI::Start() as it will crash the browser.
578 if (is_tracing_startup_) {
579 TRACE_EVENT0("startup", "BrowserMainLoop::InitStartupTracing");
580 InitStartupTracing(parsed_command_line_);
582 #endif // !defined(OS_IOS)
584 #if defined(OS_ANDROID)
586 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SurfaceTextureManager");
587 if (parsed_command_line_.HasSwitch(switches::kSingleProcess)) {
588 SurfaceTextureManager::SetInstance(
589 InProcessSurfaceTextureManager::GetInstance());
590 } else {
591 SurfaceTextureManager::SetInstance(
592 BrowserSurfaceTextureManager::GetInstance());
596 if (!parsed_command_line_.HasSwitch(
597 switches::kDisableScreenOrientationLock)) {
598 TRACE_EVENT0("startup",
599 "BrowserMainLoop::Subsystem:ScreenOrientationProvider");
600 screen_orientation_delegate_.reset(
601 new ScreenOrientationDelegateAndroid());
602 ScreenOrientationProvider::SetDelegate(screen_orientation_delegate_.get());
604 #endif
606 #if defined(OS_MACOSX) && !defined(OS_IOS)
608 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:IOSurfaceManager");
609 if (parsed_command_line_.HasSwitch(switches::kSingleProcess)) {
610 IOSurfaceManager::SetInstance(InProcessIOSurfaceManager::GetInstance());
611 } else {
612 IOSurfaceManager::SetInstance(BrowserIOSurfaceManager::GetInstance());
615 #endif
617 if (parsed_command_line_.HasSwitch(switches::kMemoryMetrics)) {
618 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MemoryObserver");
619 memory_observer_.reset(new MemoryObserver());
620 base::MessageLoop::current()->AddTaskObserver(memory_observer_.get());
623 if (parsed_command_line_.HasSwitch(
624 switches::kEnableAggressiveDOMStorageFlushing)) {
625 TRACE_EVENT0("startup",
626 "BrowserMainLoop::Subsystem:EnableAggressiveCommitDelay");
627 DOMStorageArea::EnableAggressiveCommitDelay();
630 base::trace_event::MemoryDumpManager::GetInstance()->Initialize();
632 // Enable the dump providers.
633 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
634 HostSharedBitmapManager::current());
635 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
636 skia::SkiaMemoryDumpProvider::GetInstance());
638 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
639 trace_memory_controller_.reset(new base::trace_event::TraceMemoryController(
640 base::MessageLoop::current()->task_runner(),
641 ::HeapProfilerWithPseudoStackStart, ::HeapProfilerStop,
642 ::GetHeapProfile));
643 #endif
646 int BrowserMainLoop::PreCreateThreads() {
647 // Need to initialize in-process GpuDataManager before creating threads.
648 // It's unsafe to append the gpu command line switches to the global
649 // CommandLine::ForCurrentProcess object after threads are created.
650 // Also need to initialize before BrowserMainParts::PreCreateThreads, so
651 // BrowserMainParts has a hook to set GpuDataManager strings before
652 // starting Gpu process.
653 GpuDataManagerImpl::GetInstance()->Initialize();
655 if (parts_) {
656 TRACE_EVENT0("startup",
657 "BrowserMainLoop::CreateThreads:PreCreateThreads");
658 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::PreCreateThreads");
660 result_code_ = parts_->PreCreateThreads();
663 // TODO(chrisha): Abstract away this construction mess to a helper function,
664 // once MemoryPressureMonitor is made a concrete class.
665 #if defined(OS_CHROMEOS)
666 if (chromeos::switches::MemoryPressureHandlingEnabled()) {
667 memory_pressure_monitor_.reset(new base::chromeos::MemoryPressureMonitor(
668 chromeos::switches::GetMemoryPressureThresholds()));
670 #elif defined(OS_MACOSX) && !defined(OS_IOS)
671 memory_pressure_monitor_.reset(new base::mac::MemoryPressureMonitor());
672 #elif defined(OS_WIN)
673 memory_pressure_monitor_.reset(CreateWinMemoryPressureMonitor(
674 parsed_command_line_));
675 #endif
677 #if defined(ENABLE_PLUGINS)
678 // Prior to any processing happening on the io thread, we create the
679 // plugin service as it is predominantly used from the io thread,
680 // but must be created on the main thread. The service ctor is
681 // inexpensive and does not invoke the io_thread() accessor.
683 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads:PluginService");
684 PluginService::GetInstance()->Init();
686 #endif
688 #if defined(OS_MACOSX)
690 // Initialize AVFoundation if supported, for audio and video.
691 TRACE_EVENT0("startup",
692 "BrowserMainLoop::CreateThreads:InitializeAVFoundation");
693 AVFoundationGlue::InitializeAVFoundation();
695 #endif
697 #if !defined(OS_IOS) && (!defined(GOOGLE_CHROME_BUILD) || defined(OS_ANDROID))
698 // Single-process is an unsupported and not fully tested mode, so
699 // don't enable it for official Chrome builds (except on Android).
700 if (parsed_command_line_.HasSwitch(switches::kSingleProcess))
701 RenderProcessHost::SetRunRendererInProcess(true);
702 #endif
704 return result_code_;
707 void BrowserMainLoop::CreateStartupTasks() {
708 TRACE_EVENT0("startup", "BrowserMainLoop::CreateStartupTasks");
709 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::CreateStartupTasks");
711 // First time through, we really want to create all the tasks
712 if (!startup_task_runner_.get()) {
713 #if defined(OS_ANDROID)
714 startup_task_runner_ = make_scoped_ptr(
715 new StartupTaskRunner(base::Bind(&BrowserStartupComplete),
716 base::ThreadTaskRunnerHandle::Get()));
717 #else
718 startup_task_runner_ = make_scoped_ptr(
719 new StartupTaskRunner(base::Callback<void(int)>(),
720 base::ThreadTaskRunnerHandle::Get()));
721 #endif
722 StartupTask pre_create_threads =
723 base::Bind(&BrowserMainLoop::PreCreateThreads, base::Unretained(this));
724 startup_task_runner_->AddTask(pre_create_threads);
726 StartupTask create_threads =
727 base::Bind(&BrowserMainLoop::CreateThreads, base::Unretained(this));
728 startup_task_runner_->AddTask(create_threads);
730 StartupTask browser_thread_started = base::Bind(
731 &BrowserMainLoop::BrowserThreadsStarted, base::Unretained(this));
732 startup_task_runner_->AddTask(browser_thread_started);
734 StartupTask pre_main_message_loop_run = base::Bind(
735 &BrowserMainLoop::PreMainMessageLoopRun, base::Unretained(this));
736 startup_task_runner_->AddTask(pre_main_message_loop_run);
738 #if defined(OS_ANDROID)
739 if (BrowserMayStartAsynchronously()) {
740 startup_task_runner_->StartRunningTasksAsync();
742 #endif
744 #if defined(OS_ANDROID)
745 if (!BrowserMayStartAsynchronously()) {
746 // A second request for asynchronous startup can be ignored, so
747 // StartupRunningTasksAsync is only called first time through. If, however,
748 // this is a request for synchronous startup then it must override any
749 // previous call for async startup, so we call RunAllTasksNow()
750 // unconditionally.
751 startup_task_runner_->RunAllTasksNow();
753 #else
754 startup_task_runner_->RunAllTasksNow();
755 #endif
758 int BrowserMainLoop::CreateThreads() {
759 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads");
760 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::CreateThreads");
762 base::Thread::Options io_message_loop_options;
763 io_message_loop_options.message_loop_type = base::MessageLoop::TYPE_IO;
764 base::Thread::Options ui_message_loop_options;
765 ui_message_loop_options.message_loop_type = base::MessageLoop::TYPE_UI;
767 // Start threads in the order they occur in the BrowserThread::ID
768 // enumeration, except for BrowserThread::UI which is the main
769 // thread.
771 // Must be size_t so we can increment it.
772 for (size_t thread_id = BrowserThread::UI + 1;
773 thread_id < BrowserThread::ID_COUNT;
774 ++thread_id) {
775 scoped_ptr<BrowserProcessSubThread>* thread_to_start = NULL;
776 base::Thread::Options options;
778 switch (thread_id) {
779 case BrowserThread::DB:
780 TRACE_EVENT_BEGIN1("startup",
781 "BrowserMainLoop::CreateThreads:start",
782 "Thread", "BrowserThread::DB");
783 thread_to_start = &db_thread_;
784 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
785 break;
786 case BrowserThread::FILE_USER_BLOCKING:
787 TRACE_EVENT_BEGIN1("startup",
788 "BrowserMainLoop::CreateThreads:start",
789 "Thread", "BrowserThread::FILE_USER_BLOCKING");
790 thread_to_start = &file_user_blocking_thread_;
791 break;
792 case BrowserThread::FILE:
793 TRACE_EVENT_BEGIN1("startup",
794 "BrowserMainLoop::CreateThreads:start",
795 "Thread", "BrowserThread::FILE");
796 thread_to_start = &file_thread_;
797 #if defined(OS_WIN)
798 // On Windows, the FILE thread needs to be have a UI message loop
799 // which pumps messages in such a way that Google Update can
800 // communicate back to us.
801 options = ui_message_loop_options;
802 #else
803 options = io_message_loop_options;
804 #endif
805 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
806 break;
807 case BrowserThread::PROCESS_LAUNCHER:
808 TRACE_EVENT_BEGIN1("startup",
809 "BrowserMainLoop::CreateThreads:start",
810 "Thread", "BrowserThread::PROCESS_LAUNCHER");
811 thread_to_start = &process_launcher_thread_;
812 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
813 break;
814 case BrowserThread::CACHE:
815 TRACE_EVENT_BEGIN1("startup",
816 "BrowserMainLoop::CreateThreads:start",
817 "Thread", "BrowserThread::CACHE");
818 thread_to_start = &cache_thread_;
819 options = io_message_loop_options;
820 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
821 break;
822 case BrowserThread::IO:
823 TRACE_EVENT_BEGIN1("startup",
824 "BrowserMainLoop::CreateThreads:start",
825 "Thread", "BrowserThread::IO");
826 thread_to_start = &io_thread_;
827 options = io_message_loop_options;
828 #if defined(OS_ANDROID)
829 // Up the priority of the |io_thread_| as some of its IPCs relate to
830 // display tasks.
831 options.priority = base::ThreadPriority::DISPLAY;
832 #endif
833 break;
834 case BrowserThread::UI:
835 case BrowserThread::ID_COUNT:
836 default:
837 NOTREACHED();
838 break;
841 BrowserThread::ID id = static_cast<BrowserThread::ID>(thread_id);
843 if (thread_to_start) {
844 (*thread_to_start).reset(new BrowserProcessSubThread(id));
845 if (!(*thread_to_start)->StartWithOptions(options)) {
846 LOG(FATAL) << "Failed to start the browser thread: id == " << id;
848 } else {
849 NOTREACHED();
852 TRACE_EVENT_END0("startup", "BrowserMainLoop::CreateThreads:start");
854 created_threads_ = true;
855 return result_code_;
858 int BrowserMainLoop::PreMainMessageLoopRun() {
859 if (parts_) {
860 TRACE_EVENT0("startup",
861 "BrowserMainLoop::CreateThreads:PreMainMessageLoopRun");
862 TRACK_SCOPED_REGION(
863 "Startup", "BrowserMainLoop::PreMainMessageLoopRun");
865 parts_->PreMainMessageLoopRun();
868 // If the UI thread blocks, the whole UI is unresponsive.
869 // Do not allow disk IO from the UI thread.
870 base::ThreadRestrictions::SetIOAllowed(false);
871 base::ThreadRestrictions::DisallowWaiting();
872 return result_code_;
875 void BrowserMainLoop::RunMainMessageLoopParts() {
876 TRACE_EVENT_BEGIN_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
878 bool ran_main_loop = false;
879 if (parts_)
880 ran_main_loop = parts_->MainMessageLoopRun(&result_code_);
882 if (!ran_main_loop)
883 MainMessageLoopRun();
885 TRACE_EVENT_END_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
888 void BrowserMainLoop::ShutdownThreadsAndCleanUp() {
889 if (!created_threads_) {
890 // Called early, nothing to do
891 return;
893 TRACE_EVENT0("shutdown", "BrowserMainLoop::ShutdownThreadsAndCleanUp");
895 // Teardown may start in PostMainMessageLoopRun, and during teardown we
896 // need to be able to perform IO.
897 base::ThreadRestrictions::SetIOAllowed(true);
898 BrowserThread::PostTask(
899 BrowserThread::IO, FROM_HERE,
900 base::Bind(base::IgnoreResult(&base::ThreadRestrictions::SetIOAllowed),
901 true));
903 mojo_shell_context_.reset();
905 #if !defined(OS_IOS)
906 if (RenderProcessHost::run_renderer_in_process())
907 RenderProcessHostImpl::ShutDownInProcessRenderer();
908 #endif
910 if (parts_) {
911 TRACE_EVENT0("shutdown",
912 "BrowserMainLoop::Subsystem:PostMainMessageLoopRun");
913 parts_->PostMainMessageLoopRun();
916 trace_memory_controller_.reset();
917 system_stats_monitor_.reset();
919 #if !defined(OS_IOS)
920 // Destroying the GpuProcessHostUIShims on the UI thread posts a task to
921 // delete related objects on the GPU thread. This must be done before
922 // stopping the GPU thread. The GPU thread will close IPC channels to renderer
923 // processes so this has to happen before stopping the IO thread.
925 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUProcessHostShim");
926 GpuProcessHostUIShim::DestroyAll();
928 // Cancel pending requests and prevent new requests.
929 if (resource_dispatcher_host_) {
930 TRACE_EVENT0("shutdown",
931 "BrowserMainLoop::Subsystem:ResourceDispatcherHost");
932 resource_dispatcher_host_.get()->Shutdown();
935 memory_pressure_monitor_.reset();
937 #if defined(OS_MACOSX)
938 BrowserCompositorMac::DisableRecyclingForShutdown();
939 #endif
941 #if defined(USE_AURA) || defined(OS_MACOSX)
943 TRACE_EVENT0("shutdown",
944 "BrowserMainLoop::Subsystem:ImageTransportFactory");
945 ImageTransportFactory::Terminate();
947 #endif
949 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
950 ZygoteHostImpl::GetInstance()->TearDownAfterLastChild();
951 #endif // defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
953 // The device monitors are using |system_monitor_| as dependency, so delete
954 // them before |system_monitor_| goes away.
955 // On Mac and windows, the monitor needs to be destroyed on the same thread
956 // as they were created. On Linux, the monitor will be deleted when IO thread
957 // goes away.
958 #if defined(OS_WIN)
959 system_message_window_.reset();
960 #elif defined(OS_MACOSX)
961 device_monitor_mac_.reset();
962 #endif
963 #endif // !defined(OS_IOS)
965 // Must be size_t so we can subtract from it.
966 for (size_t thread_id = BrowserThread::ID_COUNT - 1;
967 thread_id >= (BrowserThread::UI + 1);
968 --thread_id) {
969 // Find the thread object we want to stop. Looping over all valid
970 // BrowserThread IDs and DCHECKing on a missing case in the switch
971 // statement helps avoid a mismatch between this code and the
972 // BrowserThread::ID enumeration.
974 // The destruction order is the reverse order of occurrence in the
975 // BrowserThread::ID list. The rationale for the order is as
976 // follows (need to be filled in a bit):
979 // - The IO thread is the only user of the CACHE thread.
981 // - The PROCESS_LAUNCHER thread must be stopped after IO in case
982 // the IO thread posted a task to terminate a process on the
983 // process launcher thread.
985 // - (Not sure why DB stops last.)
986 switch (thread_id) {
987 case BrowserThread::DB: {
988 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DBThread");
989 ResetThread_DB(db_thread_.Pass());
990 break;
992 case BrowserThread::FILE: {
993 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:FileThread");
994 #if !defined(OS_IOS)
995 // Clean up state that lives on or uses the file_thread_ before
996 // it goes away.
997 if (resource_dispatcher_host_)
998 resource_dispatcher_host_.get()->save_file_manager()->Shutdown();
999 #endif // !defined(OS_IOS)
1000 ResetThread_FILE(file_thread_.Pass());
1001 break;
1003 case BrowserThread::FILE_USER_BLOCKING: {
1004 TRACE_EVENT0("shutdown",
1005 "BrowserMainLoop::Subsystem:FileUserBlockingThread");
1006 ResetThread_FILE_USER_BLOCKING(file_user_blocking_thread_.Pass());
1007 break;
1009 case BrowserThread::PROCESS_LAUNCHER: {
1010 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:LauncherThread");
1011 ResetThread_PROCESS_LAUNCHER(process_launcher_thread_.Pass());
1012 break;
1014 case BrowserThread::CACHE: {
1015 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:CacheThread");
1016 ResetThread_CACHE(cache_thread_.Pass());
1017 break;
1019 case BrowserThread::IO: {
1020 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IOThread");
1021 ResetThread_IO(io_thread_.Pass());
1022 break;
1024 case BrowserThread::UI:
1025 case BrowserThread::ID_COUNT:
1026 default:
1027 NOTREACHED();
1028 break;
1032 #if !defined(OS_IOS)
1034 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IndexedDBThread");
1035 ResetThread_IndexedDb(indexed_db_thread_.Pass());
1037 #endif
1039 // Close the blocking I/O pool after the other threads. Other threads such
1040 // as the I/O thread may need to schedule work like closing files or flushing
1041 // data during shutdown, so the blocking pool needs to be available. There
1042 // may also be slow operations pending that will blcok shutdown, so closing
1043 // it here (which will block until required operations are complete) gives
1044 // more head start for those operations to finish.
1046 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:ThreadPool");
1047 BrowserThreadImpl::ShutdownThreadPool();
1050 #if !defined(OS_IOS)
1051 // Must happen after the IO thread is shutdown since this may be accessed from
1052 // it.
1054 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUChannelFactory");
1055 if (BrowserGpuChannelHostFactory::instance())
1056 BrowserGpuChannelHostFactory::Terminate();
1059 // Must happen after the I/O thread is shutdown since this class lives on the
1060 // I/O thread and isn't threadsafe.
1062 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GamepadService");
1063 GamepadService::GetInstance()->Terminate();
1066 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:SensorService");
1067 DeviceInertialSensorService::GetInstance()->Shutdown();
1070 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:BatteryStatusService");
1071 device::BatteryStatusService::GetInstance()->Shutdown();
1074 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DeleteDataSources");
1075 URLDataManager::DeleteDataSources();
1077 #endif // !defined(OS_IOS)
1079 if (parts_) {
1080 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:PostDestroyThreads");
1081 parts_->PostDestroyThreads();
1085 void BrowserMainLoop::StopStartupTracingTimer() {
1086 startup_trace_timer_.Stop();
1089 void BrowserMainLoop::InitializeMainThread() {
1090 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeMainThread");
1091 static const char kThreadName[] = "CrBrowserMain";
1092 base::PlatformThread::SetName(kThreadName);
1093 if (main_message_loop_)
1094 main_message_loop_->set_thread_name(kThreadName);
1096 // Register the main thread by instantiating it, but don't call any methods.
1097 main_thread_.reset(
1098 new BrowserThreadImpl(BrowserThread::UI, base::MessageLoop::current()));
1101 int BrowserMainLoop::BrowserThreadsStarted() {
1102 TRACE_EVENT0("startup", "BrowserMainLoop::BrowserThreadsStarted");
1104 #if !defined(OS_IOS)
1105 indexed_db_thread_.reset(new base::Thread("IndexedDB"));
1106 indexed_db_thread_->Start();
1107 #endif
1109 #if !defined(OS_IOS)
1110 HistogramSynchronizer::GetInstance();
1112 #if defined(OS_ANDROID)
1113 // Up the priority of the UI thread.
1114 base::PlatformThread::SetCurrentThreadPriority(base::ThreadPriority::DISPLAY);
1115 #endif
1117 bool always_uses_gpu = true;
1118 bool established_gpu_channel = false;
1119 #if defined(OS_ANDROID)
1120 // TODO(crbug.com/439322): This should be set to |true|.
1121 established_gpu_channel = false;
1122 BrowserGpuChannelHostFactory::Initialize(established_gpu_channel);
1123 #elif defined(USE_AURA) || defined(OS_MACOSX)
1124 established_gpu_channel = true;
1125 if (!GpuDataManagerImpl::GetInstance()->CanUseGpuBrowserCompositor() ||
1126 parsed_command_line_.HasSwitch(switches::kDisableGpuEarlyInit)) {
1127 established_gpu_channel = always_uses_gpu = false;
1129 BrowserGpuChannelHostFactory::Initialize(established_gpu_channel);
1130 ImageTransportFactory::Initialize();
1131 #if defined(USE_AURA)
1132 if (aura::Env::GetInstance()) {
1133 aura::Env::GetInstance()->set_context_factory(GetContextFactory());
1135 #endif // defined(USE_AURA)
1136 #endif // defined(OS_ANDROID)
1138 // Enable the GpuMemoryBuffer dump provider with IO thread affinity. Note that
1139 // unregistration happens on the IO thread (See
1140 // BrowserProcessSubThread::IOThreadPreCleanUp).
1141 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
1142 BrowserGpuMemoryBufferManager::current(), io_thread_->task_runner());
1145 TRACE_EVENT0("startup", "BrowserThreadsStarted::Subsystem:AudioMan");
1146 audio_manager_.reset(media::AudioManager::CreateWithHangTimer(
1147 MediaInternals::GetInstance(), io_thread_->task_runner()));
1151 TRACE_EVENT0("startup", "BrowserThreadsStarted::Subsystem:MidiManager");
1152 midi_manager_.reset(media::midi::MidiManager::Create());
1155 #if defined(OS_LINUX) && defined(USE_UDEV)
1156 device_monitor_linux_.reset(new DeviceMonitorLinux());
1157 #elif defined(OS_MACOSX)
1158 device_monitor_mac_.reset(new DeviceMonitorMac());
1159 #endif
1161 #if defined(OS_WIN)
1162 UMA_HISTOGRAM_BOOLEAN("Windows.Win32kRendererLockdown",
1163 IsWin32kRendererLockdownEnabled());
1164 #endif
1165 // RDH needs the IO thread to be created
1167 TRACE_EVENT0("startup",
1168 "BrowserMainLoop::BrowserThreadsStarted:InitResourceDispatcherHost");
1169 resource_dispatcher_host_.reset(new ResourceDispatcherHostImpl());
1172 // MediaStreamManager needs the IO thread to be created.
1174 TRACE_EVENT0("startup",
1175 "BrowserMainLoop::BrowserThreadsStarted:InitMediaStreamManager");
1176 media_stream_manager_.reset(new MediaStreamManager(audio_manager_.get()));
1180 TRACE_EVENT0("startup",
1181 "BrowserMainLoop::BrowserThreadsStarted:InitSpeechRecognition");
1182 speech_recognition_manager_.reset(new SpeechRecognitionManagerImpl(
1183 audio_manager_.get(), media_stream_manager_.get()));
1187 TRACE_EVENT0(
1188 "startup",
1189 "BrowserMainLoop::BrowserThreadsStarted::InitUserInputMonitor");
1190 user_input_monitor_ = media::UserInputMonitor::Create(
1191 io_thread_->task_runner(), main_thread_->task_runner());
1195 TRACE_EVENT0("startup",
1196 "BrowserMainLoop::BrowserThreadsStarted::TimeZoneMonitor");
1197 time_zone_monitor_ = TimeZoneMonitor::Create();
1200 // Alert the clipboard class to which threads are allowed to access the
1201 // clipboard:
1202 std::vector<base::PlatformThreadId> allowed_clipboard_threads;
1203 // The current thread is the UI thread.
1204 allowed_clipboard_threads.push_back(base::PlatformThread::CurrentId());
1205 #if defined(OS_WIN)
1206 // On Windows, clipboards are also used on the FILE or IO threads.
1207 allowed_clipboard_threads.push_back(file_thread_->GetThreadId());
1208 allowed_clipboard_threads.push_back(io_thread_->GetThreadId());
1209 #endif
1210 ui::Clipboard::SetAllowedThreads(allowed_clipboard_threads);
1212 // When running the GPU thread in-process, avoid optimistically starting it
1213 // since creating the GPU thread races against creation of the one-and-only
1214 // ChildProcess instance which is created by the renderer thread.
1215 if (GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL) &&
1216 !established_gpu_channel &&
1217 always_uses_gpu &&
1218 !UsingInProcessGpu()) {
1219 TRACE_EVENT_INSTANT0("gpu", "Post task to launch GPU process",
1220 TRACE_EVENT_SCOPE_THREAD);
1221 BrowserThread::PostTask(
1222 BrowserThread::IO, FROM_HERE,
1223 base::Bind(base::IgnoreResult(&GpuProcessHost::Get),
1224 GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED,
1225 CAUSE_FOR_GPU_LAUNCH_BROWSER_STARTUP));
1228 #if defined(OS_MACOSX)
1229 ThemeHelperMac::GetInstance();
1230 SystemHotkeyHelperMac::GetInstance()->DeferredLoadSystemHotkeys();
1231 if (ShouldEnableBootstrapSandbox()) {
1232 TRACE_EVENT0("startup",
1233 "BrowserMainLoop::BrowserThreadsStarted:BootstrapSandbox");
1234 CHECK(GetBootstrapSandbox());
1236 #endif // defined(OS_MACOSX)
1238 #endif // !defined(OS_IOS)
1240 mojo_shell_context_.reset(new MojoShellContext);
1242 return result_code_;
1245 bool BrowserMainLoop::UsingInProcessGpu() const {
1246 return parsed_command_line_.HasSwitch(switches::kSingleProcess) ||
1247 parsed_command_line_.HasSwitch(switches::kInProcessGPU);
1250 bool BrowserMainLoop::InitializeToolkit() {
1251 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeToolkit");
1252 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::InitializeToolkit");
1254 // TODO(evan): this function is rather subtle, due to the variety
1255 // of intersecting ifdefs we have. To keep it easy to follow, there
1256 // are no #else branches on any #ifs.
1257 // TODO(stevenjb): Move platform specific code into platform specific Parts
1258 // (Need to add InitializeToolkit stage to BrowserParts).
1259 // See also GTK setup in EarlyInitialization, above, and associated comments.
1261 #if defined(OS_WIN)
1262 // Init common control sex.
1263 INITCOMMONCONTROLSEX config;
1264 config.dwSize = sizeof(config);
1265 config.dwICC = ICC_WIN95_CLASSES;
1266 if (!InitCommonControlsEx(&config))
1267 PLOG(FATAL);
1268 #endif
1270 #if defined(USE_AURA)
1272 #if defined(USE_X11)
1273 if (!gfx::GetXDisplay())
1274 return false;
1275 #endif
1277 // Env creates the compositor. Aura widgets need the compositor to be created
1278 // before they can be initialized by the browser.
1279 aura::Env::CreateInstance(true);
1280 #endif // defined(USE_AURA)
1282 if (parts_)
1283 parts_->ToolkitInitialized();
1285 return true;
1288 void BrowserMainLoop::MainMessageLoopRun() {
1289 #if defined(OS_ANDROID)
1290 // Android's main message loop is the Java message loop.
1291 NOTREACHED();
1292 #else
1293 DCHECK(base::MessageLoopForUI::IsCurrent());
1294 if (parameters_.ui_task) {
1295 base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
1296 *parameters_.ui_task);
1299 base::RunLoop run_loop;
1300 run_loop.Run();
1301 #endif
1304 base::FilePath BrowserMainLoop::GetStartupTraceFileName(
1305 const base::CommandLine& command_line) const {
1306 base::FilePath trace_file = command_line.GetSwitchValuePath(
1307 switches::kTraceStartupFile);
1308 // trace_file = "none" means that startup events will show up for the next
1309 // begin/end tracing (via about:tracing or AutomationProxy::BeginTracing/
1310 // EndTracing, for example).
1311 if (trace_file == base::FilePath().AppendASCII("none"))
1312 return trace_file;
1314 if (trace_file.empty()) {
1315 #if defined(OS_ANDROID)
1316 TracingControllerAndroid::GenerateTracingFilePath(&trace_file);
1317 #else
1318 // Default to saving the startup trace into the current dir.
1319 trace_file = base::FilePath().AppendASCII("chrometrace.log");
1320 #endif
1323 return trace_file;
1326 void BrowserMainLoop::InitStartupTracing(
1327 const base::CommandLine& command_line) {
1328 DCHECK(is_tracing_startup_);
1330 startup_trace_file_ = GetStartupTraceFileName(parsed_command_line_);
1332 std::string delay_str = command_line.GetSwitchValueASCII(
1333 switches::kTraceStartupDuration);
1334 int delay_secs = 5;
1335 if (!delay_str.empty() && !base::StringToInt(delay_str, &delay_secs)) {
1336 DLOG(WARNING) << "Could not parse --" << switches::kTraceStartupDuration
1337 << "=" << delay_str << " defaulting to 5 (secs)";
1338 delay_secs = 5;
1341 startup_trace_timer_.Start(FROM_HERE,
1342 base::TimeDelta::FromSeconds(delay_secs),
1343 this,
1344 &BrowserMainLoop::EndStartupTracing);
1347 void BrowserMainLoop::EndStartupTracing() {
1348 DCHECK(is_tracing_startup_);
1350 is_tracing_startup_ = false;
1351 TracingController::GetInstance()->DisableRecording(
1352 TracingController::CreateFileSink(
1353 startup_trace_file_,
1354 base::Bind(OnStoppedStartupTracing, startup_trace_file_)));
1357 } // namespace content