Clean up check for dependency_info.
[chromium-blink-merge.git] / content / browser / browser_main_loop.cc
blob19346bdecf9e3975c31d5b868a0000ed8ae00ea1
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/trace_config_file.h"
30 #include "components/tracing/tracing_switches.h"
31 #include "content/browser/browser_thread_impl.h"
32 #include "content/browser/device_sensors/device_inertial_sensor_service.h"
33 #include "content/browser/dom_storage/dom_storage_area.h"
34 #include "content/browser/download/save_file_manager.h"
35 #include "content/browser/gamepad/gamepad_service.h"
36 #include "content/browser/gpu/browser_gpu_channel_host_factory.h"
37 #include "content/browser/gpu/browser_gpu_memory_buffer_manager.h"
38 #include "content/browser/gpu/compositor_util.h"
39 #include "content/browser/gpu/gpu_data_manager_impl.h"
40 #include "content/browser/gpu/gpu_process_host.h"
41 #include "content/browser/gpu/gpu_process_host_ui_shim.h"
42 #include "content/browser/histogram_synchronizer.h"
43 #include "content/browser/loader/resource_dispatcher_host_impl.h"
44 #include "content/browser/media/media_internals.h"
45 #include "content/browser/mojo/mojo_shell_context.h"
46 #include "content/browser/net/browser_online_state_observer.h"
47 #include "content/browser/renderer_host/media/media_stream_manager.h"
48 #include "content/browser/speech/speech_recognition_manager_impl.h"
49 #include "content/browser/startup_task_runner.h"
50 #include "content/browser/time_zone_monitor.h"
51 #include "content/browser/webui/content_web_ui_controller_factory.h"
52 #include "content/browser/webui/url_data_manager.h"
53 #include "content/common/content_switches_internal.h"
54 #include "content/common/host_discardable_shared_memory_manager.h"
55 #include "content/common/host_shared_bitmap_manager.h"
56 #include "content/common/resource_messages.h"
57 #include "content/public/browser/browser_main_parts.h"
58 #include "content/public/browser/content_browser_client.h"
59 #include "content/public/browser/render_process_host.h"
60 #include "content/public/browser/tracing_controller.h"
61 #include "content/public/common/content_switches.h"
62 #include "content/public/common/main_function_params.h"
63 #include "content/public/common/result_codes.h"
64 #include "crypto/nss_util.h"
65 #include "device/battery/battery_status_service.h"
66 #include "ipc/ipc_channel.h"
67 #include "media/audio/audio_manager.h"
68 #include "media/base/media.h"
69 #include "media/base/user_input_monitor.h"
70 #include "media/midi/midi_manager.h"
71 #include "net/base/network_change_notifier.h"
72 #include "net/socket/client_socket_factory.h"
73 #include "net/ssl/ssl_config_service.h"
74 #include "skia/ext/skia_memory_dump_provider.h"
75 #include "ui/base/clipboard/clipboard.h"
77 #if defined(USE_AURA) || (defined(OS_MACOSX) && !defined(OS_IOS))
78 #include "content/browser/compositor/image_transport_factory.h"
79 #endif
81 #if defined(USE_AURA)
82 #include "content/public/browser/context_factory.h"
83 #include "ui/aura/env.h"
84 #endif
86 #if !defined(OS_IOS)
87 #include "content/browser/renderer_host/render_process_host_impl.h"
88 #endif
90 #if defined(OS_ANDROID)
91 #include "base/android/jni_android.h"
92 #include "content/browser/android/browser_startup_controller.h"
93 #include "content/browser/android/browser_surface_texture_manager.h"
94 #include "content/browser/android/in_process_surface_texture_manager.h"
95 #include "content/browser/android/tracing_controller_android.h"
96 #include "content/browser/screen_orientation/screen_orientation_delegate_android.h"
97 #include "content/public/browser/screen_orientation_provider.h"
98 #include "ui/gl/gl_surface.h"
99 #endif
101 #if defined(OS_MACOSX)
102 #include "media/base/mac/avfoundation_glue.h"
103 #endif
105 #if defined(OS_MACOSX) && !defined(OS_IOS)
106 #include "base/memory/memory_pressure_monitor_mac.h"
107 #include "content/browser/bootstrap_sandbox_manager_mac.h"
108 #include "content/browser/browser_io_surface_manager_mac.h"
109 #include "content/browser/cocoa/system_hotkey_helper_mac.h"
110 #include "content/browser/compositor/browser_compositor_view_mac.h"
111 #include "content/browser/in_process_io_surface_manager_mac.h"
112 #include "content/browser/theme_helper_mac.h"
113 #endif
115 #if defined(USE_OZONE)
116 #include "ui/ozone/public/client_native_pixmap_factory.h"
117 #include "ui/ozone/public/ozone_platform.h"
118 #endif
120 #if defined(OS_WIN)
121 #include <windows.h>
122 #include <commctrl.h>
123 #include <shellapi.h>
125 #include "base/memory/memory_pressure_monitor_win.h"
126 #include "content/browser/system_message_window_win.h"
127 #include "content/common/sandbox_win.h"
128 #include "net/base/winsock_init.h"
129 #include "ui/base/l10n/l10n_util_win.h"
130 #endif
132 #if defined(OS_CHROMEOS)
133 #include "base/memory/memory_pressure_monitor_chromeos.h"
134 #include "chromeos/chromeos_switches.h"
135 #endif
137 #if defined(USE_GLIB)
138 #include <glib-object.h>
139 #endif
141 #if defined(OS_LINUX) && defined(USE_UDEV)
142 #include "content/browser/device_monitor_udev.h"
143 #elif defined(OS_MACOSX) && !defined(OS_IOS)
144 #include "content/browser/device_monitor_mac.h"
145 #endif
147 #if defined(OS_POSIX) && !defined(OS_MACOSX)
148 #include "content/browser/renderer_host/render_sandbox_host_linux.h"
149 #include "content/browser/zygote_host/zygote_host_impl_linux.h"
150 #include "sandbox/linux/suid/client/setuid_sandbox_host.h"
151 #endif
153 #if defined(ENABLE_PLUGINS)
154 #include "content/browser/plugin_service_impl.h"
155 #endif
157 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
158 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
159 #endif
161 #if defined(USE_X11)
162 #include "ui/gfx/x/x11_connection.h"
163 #include "ui/gfx/x/x11_types.h"
164 #endif
166 // One of the linux specific headers defines this as a macro.
167 #ifdef DestroyAll
168 #undef DestroyAll
169 #endif
171 namespace content {
172 namespace {
174 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
175 void SetupSandbox(const base::CommandLine& parsed_command_line) {
176 TRACE_EVENT0("startup", "SetupSandbox");
177 base::FilePath sandbox_binary;
179 scoped_ptr<sandbox::SetuidSandboxHost> setuid_sandbox_host(
180 sandbox::SetuidSandboxHost::Create());
182 const bool want_setuid_sandbox =
183 !parsed_command_line.HasSwitch(switches::kNoSandbox) &&
184 !parsed_command_line.HasSwitch(switches::kDisableSetuidSandbox) &&
185 !setuid_sandbox_host->IsDisabledViaEnvironment();
187 static const char no_suid_error[] =
188 "Running without the SUID sandbox! See "
189 "https://code.google.com/p/chromium/wiki/LinuxSUIDSandboxDevelopment "
190 "for more information on developing with the sandbox on.";
191 if (want_setuid_sandbox) {
192 sandbox_binary = setuid_sandbox_host->GetSandboxBinaryPath();
193 if (sandbox_binary.empty()) {
194 // This needs to be fatal. Talk to security@chromium.org if you feel
195 // otherwise.
196 LOG(FATAL) << no_suid_error;
198 } else {
199 LOG(ERROR) << no_suid_error;
202 // Tickle the sandbox host and zygote host so they fork now.
203 RenderSandboxHostLinux::GetInstance()->Init();
204 ZygoteHostImpl::GetInstance()->Init(sandbox_binary.value());
206 #endif
208 #if defined(USE_GLIB)
209 static void GLibLogHandler(const gchar* log_domain,
210 GLogLevelFlags log_level,
211 const gchar* message,
212 gpointer userdata) {
213 if (!log_domain)
214 log_domain = "<unknown>";
215 if (!message)
216 message = "<no message>";
218 if (strstr(message, "Unable to retrieve the file info for")) {
219 LOG(ERROR) << "GTK File code error: " << message;
220 } else if (strstr(message, "Could not find the icon") &&
221 strstr(log_domain, "Gtk")) {
222 LOG(ERROR) << "GTK icon error: " << message;
223 } else if (strstr(message, "Theme file for default has no") ||
224 strstr(message, "Theme directory") ||
225 strstr(message, "theme pixmap") ||
226 strstr(message, "locate theme engine")) {
227 LOG(ERROR) << "GTK theme error: " << message;
228 } else if (strstr(message, "Unable to create Ubuntu Menu Proxy") &&
229 strstr(log_domain, "<unknown>")) {
230 LOG(ERROR) << "GTK menu proxy create failed";
231 } else if (strstr(message, "Out of memory") &&
232 strstr(log_domain, "<unknown>")) {
233 LOG(ERROR) << "DBus call timeout or out of memory: "
234 << "http://crosbug.com/15496";
235 } else if (strstr(message, "Could not connect: Connection refused") &&
236 strstr(log_domain, "<unknown>")) {
237 LOG(ERROR) << "DConf settings backend could not connect to session bus: "
238 << "http://crbug.com/179797";
239 } else if (strstr(message, "Attempting to store changes into") ||
240 strstr(message, "Attempting to set the permissions of")) {
241 LOG(ERROR) << message << " (http://bugs.chromium.org/161366)";
242 } else if (strstr(message, "drawable is not a native X11 window")) {
243 LOG(ERROR) << message << " (http://bugs.chromium.org/329991)";
244 } else if (strstr(message, "Cannot do system-bus activation with no user")) {
245 LOG(ERROR) << message << " (http://crbug.com/431005)";
246 } else if (strstr(message, "deprecated")) {
247 LOG(ERROR) << message;
248 } else {
249 LOG(DFATAL) << log_domain << ": " << message;
253 static void SetUpGLibLogHandler() {
254 // Register GLib-handled assertions to go through our logging system.
255 const char* kLogDomains[] = { NULL, "Gtk", "Gdk", "GLib", "GLib-GObject" };
256 for (size_t i = 0; i < arraysize(kLogDomains); i++) {
257 g_log_set_handler(kLogDomains[i],
258 static_cast<GLogLevelFlags>(G_LOG_FLAG_RECURSION |
259 G_LOG_FLAG_FATAL |
260 G_LOG_LEVEL_ERROR |
261 G_LOG_LEVEL_CRITICAL |
262 G_LOG_LEVEL_WARNING),
263 GLibLogHandler,
264 NULL);
267 #endif
269 void OnStoppedStartupTracing(const base::FilePath& trace_file) {
270 VLOG(0) << "Completed startup tracing to " << trace_file.value();
273 // Disable optimizations for this block of functions so the compiler doesn't
274 // merge them all together. This makes it possible to tell what thread was
275 // unresponsive by inspecting the callstack.
276 MSVC_DISABLE_OPTIMIZE()
277 MSVC_PUSH_DISABLE_WARNING(4748)
279 NOINLINE void ResetThread_DB(scoped_ptr<BrowserProcessSubThread> thread) {
280 volatile int inhibit_comdat = __LINE__;
281 ALLOW_UNUSED_LOCAL(inhibit_comdat);
282 thread.reset();
285 NOINLINE void ResetThread_FILE(scoped_ptr<BrowserProcessSubThread> thread) {
286 volatile int inhibit_comdat = __LINE__;
287 ALLOW_UNUSED_LOCAL(inhibit_comdat);
288 thread.reset();
291 NOINLINE void ResetThread_FILE_USER_BLOCKING(
292 scoped_ptr<BrowserProcessSubThread> thread) {
293 volatile int inhibit_comdat = __LINE__;
294 ALLOW_UNUSED_LOCAL(inhibit_comdat);
295 thread.reset();
298 NOINLINE void ResetThread_PROCESS_LAUNCHER(
299 scoped_ptr<BrowserProcessSubThread> thread) {
300 volatile int inhibit_comdat = __LINE__;
301 ALLOW_UNUSED_LOCAL(inhibit_comdat);
302 thread.reset();
305 NOINLINE void ResetThread_CACHE(scoped_ptr<BrowserProcessSubThread> thread) {
306 volatile int inhibit_comdat = __LINE__;
307 ALLOW_UNUSED_LOCAL(inhibit_comdat);
308 thread.reset();
311 NOINLINE void ResetThread_IO(scoped_ptr<BrowserProcessSubThread> thread) {
312 volatile int inhibit_comdat = __LINE__;
313 ALLOW_UNUSED_LOCAL(inhibit_comdat);
314 thread.reset();
317 #if !defined(OS_IOS)
318 NOINLINE void ResetThread_IndexedDb(scoped_ptr<base::Thread> thread) {
319 volatile int inhibit_comdat = __LINE__;
320 ALLOW_UNUSED_LOCAL(inhibit_comdat);
321 thread.reset();
323 #endif
325 MSVC_POP_WARNING()
326 MSVC_ENABLE_OPTIMIZE();
328 #if defined(OS_WIN)
329 // Creates a memory pressure monitor using automatic thresholds, or those
330 // specified on the command-line. Ownership is passed to the caller.
331 base::win::MemoryPressureMonitor* CreateWinMemoryPressureMonitor(
332 const base::CommandLine& parsed_command_line) {
333 std::vector<std::string> thresholds = base::SplitString(
334 parsed_command_line.GetSwitchValueASCII(
335 switches::kMemoryPressureThresholdsMb),
336 ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
338 int moderate_threshold_mb = 0;
339 int critical_threshold_mb = 0;
340 if (thresholds.size() == 2 &&
341 base::StringToInt(thresholds[0], &moderate_threshold_mb) &&
342 base::StringToInt(thresholds[1], &critical_threshold_mb) &&
343 moderate_threshold_mb >= critical_threshold_mb &&
344 critical_threshold_mb >= 0) {
345 return new base::win::MemoryPressureMonitor(moderate_threshold_mb,
346 critical_threshold_mb);
349 // In absence of valid switches use the automatic defaults.
350 return new base::win::MemoryPressureMonitor();
352 #endif // defined(OS_WIN)
354 } // namespace
356 // The currently-running BrowserMainLoop. There can be one or zero.
357 BrowserMainLoop* g_current_browser_main_loop = NULL;
359 // For measuring memory usage after each task. Behind a command line flag.
360 class BrowserMainLoop::MemoryObserver : public base::MessageLoop::TaskObserver {
361 public:
362 MemoryObserver() {}
363 ~MemoryObserver() override {}
365 void WillProcessTask(const base::PendingTask& pending_task) override {}
367 void DidProcessTask(const base::PendingTask& pending_task) override {
368 #if !defined(OS_IOS) // No ProcessMetrics on IOS.
369 scoped_ptr<base::ProcessMetrics> process_metrics(
370 base::ProcessMetrics::CreateProcessMetrics(
371 #if defined(OS_MACOSX)
372 base::GetCurrentProcessHandle(), NULL));
373 #else
374 base::GetCurrentProcessHandle()));
375 #endif
376 size_t private_bytes;
377 process_metrics->GetMemoryBytes(&private_bytes, NULL);
378 LOCAL_HISTOGRAM_MEMORY_KB("Memory.BrowserUsed", private_bytes >> 10);
379 #endif
381 private:
382 DISALLOW_COPY_AND_ASSIGN(MemoryObserver);
386 // BrowserMainLoop construction / destruction =============================
388 BrowserMainLoop* BrowserMainLoop::GetInstance() {
389 DCHECK_CURRENTLY_ON(BrowserThread::UI);
390 return g_current_browser_main_loop;
393 BrowserMainLoop::BrowserMainLoop(const MainFunctionParams& parameters)
394 : parameters_(parameters),
395 parsed_command_line_(parameters.command_line),
396 result_code_(RESULT_CODE_NORMAL_EXIT),
397 created_threads_(false),
398 // ContentMainRunner should have enabled tracing of the browser process
399 // when kTraceStartup or kTraceConfigFile is in the command line.
400 is_tracing_startup_for_duration_(
401 parameters.command_line.HasSwitch(switches::kTraceStartup) ||
402 (tracing::TraceConfigFile::GetInstance()->IsEnabled() &&
403 tracing::TraceConfigFile::GetInstance()->GetStartupDuration() > 0)) {
404 DCHECK(!g_current_browser_main_loop);
405 g_current_browser_main_loop = this;
408 BrowserMainLoop::~BrowserMainLoop() {
409 DCHECK_EQ(this, g_current_browser_main_loop);
410 #if !defined(OS_IOS)
411 ui::Clipboard::DestroyClipboardForCurrentThread();
412 #endif // !defined(OS_IOS)
413 g_current_browser_main_loop = NULL;
416 void BrowserMainLoop::Init() {
417 TRACE_EVENT0("startup", "BrowserMainLoop::Init");
418 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::Init");
420 parts_.reset(
421 GetContentClient()->browser()->CreateBrowserMainParts(parameters_));
424 // BrowserMainLoop stages ==================================================
426 void BrowserMainLoop::EarlyInitialization() {
427 TRACE_EVENT0("startup", "BrowserMainLoop::EarlyInitialization");
428 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::EarlyInitialization");
430 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
431 // No thread should be created before this call, as SetupSandbox()
432 // will end-up using fork().
433 SetupSandbox(parsed_command_line_);
434 #endif
436 #if defined(USE_X11)
437 if (UsingInProcessGpu()) {
438 if (!gfx::InitializeThreadedX11()) {
439 LOG(ERROR) << "Failed to put Xlib into threaded mode.";
442 #endif
444 // GLib's spawning of new processes is buggy, so it's important that at this
445 // point GLib does not need to start DBUS. Chrome should always start with
446 // DBUS_SESSION_BUS_ADDRESS properly set. See crbug.com/309093.
447 #if defined(USE_GLIB)
448 // g_type_init will be deprecated in 2.36. 2.35 is the development
449 // version for 2.36, hence do not call g_type_init starting 2.35.
450 // http://developer.gnome.org/gobject/unstable/gobject-Type-Information.html#g-type-init
451 #if !GLIB_CHECK_VERSION(2, 35, 0)
452 // GLib type system initialization. Needed at least for gconf,
453 // used in net/proxy/proxy_config_service_linux.cc. Most likely
454 // this is superfluous as gtk_init() ought to do this. It's
455 // definitely harmless, so retained as a reminder of this
456 // requirement for gconf.
457 g_type_init();
458 #endif
460 SetUpGLibLogHandler();
461 #endif
463 if (parts_)
464 parts_->PreEarlyInitialization();
466 #if defined(OS_MACOSX)
467 // We use quite a few file descriptors for our IPC, and the default limit on
468 // the Mac is low (256), so bump it up.
469 base::SetFdLimit(1024);
470 #endif
472 #if defined(OS_WIN)
473 net::EnsureWinsockInit();
474 #endif
476 #if defined(USE_NSS_CERTS) || !defined(USE_OPENSSL)
477 // We want to be sure to init NSPR on the main thread.
478 crypto::EnsureNSPRInit();
479 #endif
481 #if !defined(OS_IOS)
482 if (parsed_command_line_.HasSwitch(switches::kRendererProcessLimit)) {
483 std::string limit_string = parsed_command_line_.GetSwitchValueASCII(
484 switches::kRendererProcessLimit);
485 size_t process_limit;
486 if (base::StringToSizeT(limit_string, &process_limit)) {
487 RenderProcessHost::SetMaxRendererProcessCount(process_limit);
490 #endif // !defined(OS_IOS)
492 // TODO(boliu): kSingleProcess check is a temporary workaround for
493 // in-process Android WebView. crbug.com/503724 tracks proper fix.
494 if (!parsed_command_line_.HasSwitch(switches::kSingleProcess)) {
495 base::DiscardableMemoryAllocator::SetInstance(
496 HostDiscardableSharedMemoryManager::current());
499 if (parts_)
500 parts_->PostEarlyInitialization();
503 void BrowserMainLoop::PreMainMessageLoopStart() {
504 if (parts_) {
505 TRACE_EVENT0("startup",
506 "BrowserMainLoop::MainMessageLoopStart:PreMainMessageLoopStart");
507 parts_->PreMainMessageLoopStart();
510 #if defined(OS_WIN)
511 // If we're running tests (ui_task is non-null), then the ResourceBundle
512 // has already been initialized.
513 if (!parameters_.ui_task) {
514 // Override the configured locale with the user's preferred UI language.
515 l10n_util::OverrideLocaleWithUILanguageList();
517 #endif
520 void BrowserMainLoop::MainMessageLoopStart() {
521 // DO NOT add more code here. Use PreMainMessageLoopStart() above or
522 // PostMainMessageLoopStart() below.
524 TRACE_EVENT0("startup", "BrowserMainLoop::MainMessageLoopStart");
525 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::MainMessageLoopStart");
527 // Create a MessageLoop if one does not already exist for the current thread.
528 if (!base::MessageLoop::current())
529 main_message_loop_.reset(new base::MessageLoopForUI);
531 InitializeMainThread();
534 void BrowserMainLoop::PostMainMessageLoopStart() {
536 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SystemMonitor");
537 system_monitor_.reset(new base::SystemMonitor);
540 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:PowerMonitor");
541 scoped_ptr<base::PowerMonitorSource> power_monitor_source(
542 new base::PowerMonitorDeviceSource());
543 power_monitor_.reset(new base::PowerMonitor(power_monitor_source.Pass()));
546 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:HighResTimerManager");
547 hi_res_timer_manager_.reset(new base::HighResolutionTimerManager);
550 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:NetworkChangeNotifier");
551 network_change_notifier_.reset(net::NetworkChangeNotifier::Create());
554 #if !defined(OS_IOS)
556 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MediaFeatures");
557 media::InitializeMediaLibrary();
560 TRACE_EVENT0("startup",
561 "BrowserMainLoop::Subsystem:ContentWebUIController");
562 WebUIControllerFactory::RegisterFactory(
563 ContentWebUIControllerFactory::GetInstance());
567 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:OnlineStateObserver");
568 online_state_observer_.reset(new BrowserOnlineStateObserver);
572 system_stats_monitor_.reset(
573 new base::trace_event::TraceEventSystemStatsMonitor(
574 base::ThreadTaskRunnerHandle::Get()));
576 #endif // !defined(OS_IOS)
578 #if defined(OS_WIN)
579 system_message_window_.reset(new SystemMessageWindowWin);
580 #endif
582 if (parts_)
583 parts_->PostMainMessageLoopStart();
585 #if !defined(OS_IOS)
586 // Start tracing to a file if needed. Only do this after starting the main
587 // message loop to avoid calling MessagePumpForUI::ScheduleWork() before
588 // MessagePumpForUI::Start() as it will crash the browser.
589 if (is_tracing_startup_for_duration_) {
590 TRACE_EVENT0("startup", "BrowserMainLoop::InitStartupTracingForDuration");
591 InitStartupTracingForDuration(parsed_command_line_);
593 #endif // !defined(OS_IOS)
595 #if defined(OS_ANDROID)
597 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SurfaceTextureManager");
598 if (parsed_command_line_.HasSwitch(switches::kSingleProcess)) {
599 SurfaceTextureManager::SetInstance(
600 InProcessSurfaceTextureManager::GetInstance());
601 } else {
602 SurfaceTextureManager::SetInstance(
603 BrowserSurfaceTextureManager::GetInstance());
607 if (!parsed_command_line_.HasSwitch(
608 switches::kDisableScreenOrientationLock)) {
609 TRACE_EVENT0("startup",
610 "BrowserMainLoop::Subsystem:ScreenOrientationProvider");
611 screen_orientation_delegate_.reset(
612 new ScreenOrientationDelegateAndroid());
613 ScreenOrientationProvider::SetDelegate(screen_orientation_delegate_.get());
615 #endif
617 #if defined(OS_MACOSX) && !defined(OS_IOS)
619 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:IOSurfaceManager");
620 if (parsed_command_line_.HasSwitch(switches::kSingleProcess)) {
621 IOSurfaceManager::SetInstance(InProcessIOSurfaceManager::GetInstance());
622 } else {
623 IOSurfaceManager::SetInstance(BrowserIOSurfaceManager::GetInstance());
627 if (BootstrapSandboxManager::ShouldEnable()) {
628 TRACE_EVENT0("startup",
629 "BrowserMainLoop::Subsystem:BootstrapSandbox");
630 CHECK(BootstrapSandboxManager::GetInstance());
632 #endif
634 #if defined(USE_OZONE)
635 client_native_pixmap_factory_ = ui::ClientNativePixmapFactory::Create();
636 ui::ClientNativePixmapFactory::SetInstance(
637 client_native_pixmap_factory_.get());
638 ui::ClientNativePixmapFactory::GetInstance()->Initialize(
639 ui::OzonePlatform::GetInstance()->OpenClientNativePixmapDevice());
640 #endif
642 if (parsed_command_line_.HasSwitch(switches::kMemoryMetrics)) {
643 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MemoryObserver");
644 memory_observer_.reset(new MemoryObserver());
645 base::MessageLoop::current()->AddTaskObserver(memory_observer_.get());
648 if (parsed_command_line_.HasSwitch(
649 switches::kEnableAggressiveDOMStorageFlushing)) {
650 TRACE_EVENT0("startup",
651 "BrowserMainLoop::Subsystem:EnableAggressiveCommitDelay");
652 DOMStorageArea::EnableAggressiveCommitDelay();
655 // Enable memory-infra dump providers.
656 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
657 HostSharedBitmapManager::current());
658 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
659 skia::SkiaMemoryDumpProvider::GetInstance());
661 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
662 trace_memory_controller_.reset(new base::trace_event::TraceMemoryController(
663 base::MessageLoop::current()->task_runner(),
664 ::HeapProfilerWithPseudoStackStart, ::HeapProfilerStop,
665 ::GetHeapProfile));
666 #endif
669 int BrowserMainLoop::PreCreateThreads() {
670 if (parts_) {
671 TRACE_EVENT0("startup",
672 "BrowserMainLoop::CreateThreads:PreCreateThreads");
673 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::PreCreateThreads");
675 result_code_ = parts_->PreCreateThreads();
678 // TODO(chrisha): Abstract away this construction mess to a helper function,
679 // once MemoryPressureMonitor is made a concrete class.
680 #if defined(OS_CHROMEOS)
681 if (chromeos::switches::MemoryPressureHandlingEnabled()) {
682 memory_pressure_monitor_.reset(new base::chromeos::MemoryPressureMonitor(
683 chromeos::switches::GetMemoryPressureThresholds()));
685 #elif defined(OS_MACOSX) && !defined(OS_IOS)
686 memory_pressure_monitor_.reset(new base::mac::MemoryPressureMonitor());
687 #elif defined(OS_WIN)
688 memory_pressure_monitor_.reset(CreateWinMemoryPressureMonitor(
689 parsed_command_line_));
690 #endif
692 #if defined(ENABLE_PLUGINS)
693 // Prior to any processing happening on the io thread, we create the
694 // plugin service as it is predominantly used from the io thread,
695 // but must be created on the main thread. The service ctor is
696 // inexpensive and does not invoke the io_thread() accessor.
698 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads:PluginService");
699 PluginService::GetInstance()->Init();
701 #endif
703 #if defined(OS_MACOSX)
705 // Initialize AVFoundation if supported, for audio and video.
706 TRACE_EVENT0("startup",
707 "BrowserMainLoop::CreateThreads:InitializeAVFoundation");
708 AVFoundationGlue::InitializeAVFoundation();
710 #endif
712 // 1) Need to initialize in-process GpuDataManager before creating threads.
713 // It's unsafe to append the gpu command line switches to the global
714 // CommandLine::ForCurrentProcess object after threads are created.
715 // 2) Must be after parts_->PreCreateThreads to pick up chrome://flags.
716 GpuDataManagerImpl::GetInstance()->Initialize();
718 #if !defined(OS_IOS) && (!defined(GOOGLE_CHROME_BUILD) || defined(OS_ANDROID))
719 // Single-process is an unsupported and not fully tested mode, so
720 // don't enable it for official Chrome builds (except on Android).
721 if (parsed_command_line_.HasSwitch(switches::kSingleProcess))
722 RenderProcessHost::SetRunRendererInProcess(true);
723 #endif
725 return result_code_;
728 void BrowserMainLoop::CreateStartupTasks() {
729 TRACE_EVENT0("startup", "BrowserMainLoop::CreateStartupTasks");
730 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::CreateStartupTasks");
732 // First time through, we really want to create all the tasks
733 if (!startup_task_runner_.get()) {
734 #if defined(OS_ANDROID)
735 startup_task_runner_ = make_scoped_ptr(
736 new StartupTaskRunner(base::Bind(&BrowserStartupComplete),
737 base::ThreadTaskRunnerHandle::Get()));
738 #else
739 startup_task_runner_ = make_scoped_ptr(
740 new StartupTaskRunner(base::Callback<void(int)>(),
741 base::ThreadTaskRunnerHandle::Get()));
742 #endif
743 StartupTask pre_create_threads =
744 base::Bind(&BrowserMainLoop::PreCreateThreads, base::Unretained(this));
745 startup_task_runner_->AddTask(pre_create_threads);
747 StartupTask create_threads =
748 base::Bind(&BrowserMainLoop::CreateThreads, base::Unretained(this));
749 startup_task_runner_->AddTask(create_threads);
751 StartupTask browser_thread_started = base::Bind(
752 &BrowserMainLoop::BrowserThreadsStarted, base::Unretained(this));
753 startup_task_runner_->AddTask(browser_thread_started);
755 StartupTask pre_main_message_loop_run = base::Bind(
756 &BrowserMainLoop::PreMainMessageLoopRun, base::Unretained(this));
757 startup_task_runner_->AddTask(pre_main_message_loop_run);
759 #if defined(OS_ANDROID)
760 if (BrowserMayStartAsynchronously()) {
761 startup_task_runner_->StartRunningTasksAsync();
763 #endif
765 #if defined(OS_ANDROID)
766 if (!BrowserMayStartAsynchronously()) {
767 // A second request for asynchronous startup can be ignored, so
768 // StartupRunningTasksAsync is only called first time through. If, however,
769 // this is a request for synchronous startup then it must override any
770 // previous call for async startup, so we call RunAllTasksNow()
771 // unconditionally.
772 startup_task_runner_->RunAllTasksNow();
774 #else
775 startup_task_runner_->RunAllTasksNow();
776 #endif
779 int BrowserMainLoop::CreateThreads() {
780 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads");
781 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::CreateThreads");
783 base::Thread::Options io_message_loop_options;
784 io_message_loop_options.message_loop_type = base::MessageLoop::TYPE_IO;
785 base::Thread::Options ui_message_loop_options;
786 ui_message_loop_options.message_loop_type = base::MessageLoop::TYPE_UI;
788 // Start threads in the order they occur in the BrowserThread::ID
789 // enumeration, except for BrowserThread::UI which is the main
790 // thread.
792 // Must be size_t so we can increment it.
793 for (size_t thread_id = BrowserThread::UI + 1;
794 thread_id < BrowserThread::ID_COUNT;
795 ++thread_id) {
796 scoped_ptr<BrowserProcessSubThread>* thread_to_start = NULL;
797 base::Thread::Options options;
799 switch (thread_id) {
800 case BrowserThread::DB:
801 TRACE_EVENT_BEGIN1("startup",
802 "BrowserMainLoop::CreateThreads:start",
803 "Thread", "BrowserThread::DB");
804 thread_to_start = &db_thread_;
805 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
806 break;
807 case BrowserThread::FILE_USER_BLOCKING:
808 TRACE_EVENT_BEGIN1("startup",
809 "BrowserMainLoop::CreateThreads:start",
810 "Thread", "BrowserThread::FILE_USER_BLOCKING");
811 thread_to_start = &file_user_blocking_thread_;
812 break;
813 case BrowserThread::FILE:
814 TRACE_EVENT_BEGIN1("startup",
815 "BrowserMainLoop::CreateThreads:start",
816 "Thread", "BrowserThread::FILE");
817 thread_to_start = &file_thread_;
818 #if defined(OS_WIN)
819 // On Windows, the FILE thread needs to be have a UI message loop
820 // which pumps messages in such a way that Google Update can
821 // communicate back to us.
822 options = ui_message_loop_options;
823 #else
824 options = io_message_loop_options;
825 #endif
826 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
827 break;
828 case BrowserThread::PROCESS_LAUNCHER:
829 TRACE_EVENT_BEGIN1("startup",
830 "BrowserMainLoop::CreateThreads:start",
831 "Thread", "BrowserThread::PROCESS_LAUNCHER");
832 thread_to_start = &process_launcher_thread_;
833 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
834 break;
835 case BrowserThread::CACHE:
836 TRACE_EVENT_BEGIN1("startup",
837 "BrowserMainLoop::CreateThreads:start",
838 "Thread", "BrowserThread::CACHE");
839 thread_to_start = &cache_thread_;
840 options = io_message_loop_options;
841 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
842 break;
843 case BrowserThread::IO:
844 TRACE_EVENT_BEGIN1("startup",
845 "BrowserMainLoop::CreateThreads:start",
846 "Thread", "BrowserThread::IO");
847 thread_to_start = &io_thread_;
848 options = io_message_loop_options;
849 #if defined(OS_ANDROID)
850 // Up the priority of the |io_thread_| as some of its IPCs relate to
851 // display tasks.
852 options.priority = base::ThreadPriority::DISPLAY;
853 #endif
854 break;
855 case BrowserThread::UI:
856 case BrowserThread::ID_COUNT:
857 default:
858 NOTREACHED();
859 break;
862 BrowserThread::ID id = static_cast<BrowserThread::ID>(thread_id);
864 if (thread_to_start) {
865 (*thread_to_start).reset(new BrowserProcessSubThread(id));
866 if (!(*thread_to_start)->StartWithOptions(options)) {
867 LOG(FATAL) << "Failed to start the browser thread: id == " << id;
869 } else {
870 NOTREACHED();
873 TRACE_EVENT_END0("startup", "BrowserMainLoop::CreateThreads:start");
875 created_threads_ = true;
876 return result_code_;
879 int BrowserMainLoop::PreMainMessageLoopRun() {
880 if (parts_) {
881 TRACE_EVENT0("startup",
882 "BrowserMainLoop::CreateThreads:PreMainMessageLoopRun");
883 TRACK_SCOPED_REGION(
884 "Startup", "BrowserMainLoop::PreMainMessageLoopRun");
886 parts_->PreMainMessageLoopRun();
889 // If the UI thread blocks, the whole UI is unresponsive.
890 // Do not allow disk IO from the UI thread.
891 base::ThreadRestrictions::SetIOAllowed(false);
892 base::ThreadRestrictions::DisallowWaiting();
893 return result_code_;
896 void BrowserMainLoop::RunMainMessageLoopParts() {
897 TRACE_EVENT_BEGIN_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
899 bool ran_main_loop = false;
900 if (parts_)
901 ran_main_loop = parts_->MainMessageLoopRun(&result_code_);
903 if (!ran_main_loop)
904 MainMessageLoopRun();
906 TRACE_EVENT_END_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
909 void BrowserMainLoop::ShutdownThreadsAndCleanUp() {
910 if (!created_threads_) {
911 // Called early, nothing to do
912 return;
914 TRACE_EVENT0("shutdown", "BrowserMainLoop::ShutdownThreadsAndCleanUp");
916 // Teardown may start in PostMainMessageLoopRun, and during teardown we
917 // need to be able to perform IO.
918 base::ThreadRestrictions::SetIOAllowed(true);
919 BrowserThread::PostTask(
920 BrowserThread::IO, FROM_HERE,
921 base::Bind(base::IgnoreResult(&base::ThreadRestrictions::SetIOAllowed),
922 true));
924 mojo_shell_context_.reset();
926 #if !defined(OS_IOS)
927 if (RenderProcessHost::run_renderer_in_process())
928 RenderProcessHostImpl::ShutDownInProcessRenderer();
929 #endif
931 if (parts_) {
932 TRACE_EVENT0("shutdown",
933 "BrowserMainLoop::Subsystem:PostMainMessageLoopRun");
934 parts_->PostMainMessageLoopRun();
937 #if defined(USE_AURA)
938 aura::Env::DeleteInstance();
939 #endif
941 trace_memory_controller_.reset();
942 system_stats_monitor_.reset();
944 #if !defined(OS_IOS)
945 // Destroying the GpuProcessHostUIShims on the UI thread posts a task to
946 // delete related objects on the GPU thread. This must be done before
947 // stopping the GPU thread. The GPU thread will close IPC channels to renderer
948 // processes so this has to happen before stopping the IO thread.
950 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUProcessHostShim");
951 GpuProcessHostUIShim::DestroyAll();
953 // Cancel pending requests and prevent new requests.
954 if (resource_dispatcher_host_) {
955 TRACE_EVENT0("shutdown",
956 "BrowserMainLoop::Subsystem:ResourceDispatcherHost");
957 resource_dispatcher_host_.get()->Shutdown();
960 memory_pressure_monitor_.reset();
962 #if defined(OS_MACOSX)
963 BrowserCompositorMac::DisableRecyclingForShutdown();
964 #endif
966 #if defined(USE_AURA) || defined(OS_MACOSX)
968 TRACE_EVENT0("shutdown",
969 "BrowserMainLoop::Subsystem:ImageTransportFactory");
970 ImageTransportFactory::Terminate();
972 #endif
974 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
975 ZygoteHostImpl::GetInstance()->TearDownAfterLastChild();
976 #endif // defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
978 // The device monitors are using |system_monitor_| as dependency, so delete
979 // them before |system_monitor_| goes away.
980 // On Mac and windows, the monitor needs to be destroyed on the same thread
981 // as they were created. On Linux, the monitor will be deleted when IO thread
982 // goes away.
983 #if defined(OS_WIN)
984 system_message_window_.reset();
985 #elif defined(OS_MACOSX)
986 device_monitor_mac_.reset();
987 #endif
988 #endif // !defined(OS_IOS)
990 // Must be size_t so we can subtract from it.
991 for (size_t thread_id = BrowserThread::ID_COUNT - 1;
992 thread_id >= (BrowserThread::UI + 1);
993 --thread_id) {
994 // Find the thread object we want to stop. Looping over all valid
995 // BrowserThread IDs and DCHECKing on a missing case in the switch
996 // statement helps avoid a mismatch between this code and the
997 // BrowserThread::ID enumeration.
999 // The destruction order is the reverse order of occurrence in the
1000 // BrowserThread::ID list. The rationale for the order is as
1001 // follows (need to be filled in a bit):
1004 // - The IO thread is the only user of the CACHE thread.
1006 // - The PROCESS_LAUNCHER thread must be stopped after IO in case
1007 // the IO thread posted a task to terminate a process on the
1008 // process launcher thread.
1010 // - (Not sure why DB stops last.)
1011 switch (thread_id) {
1012 case BrowserThread::DB: {
1013 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DBThread");
1014 ResetThread_DB(db_thread_.Pass());
1015 break;
1017 case BrowserThread::FILE: {
1018 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:FileThread");
1019 #if !defined(OS_IOS)
1020 // Clean up state that lives on or uses the file_thread_ before
1021 // it goes away.
1022 if (resource_dispatcher_host_)
1023 resource_dispatcher_host_.get()->save_file_manager()->Shutdown();
1024 #endif // !defined(OS_IOS)
1025 ResetThread_FILE(file_thread_.Pass());
1026 break;
1028 case BrowserThread::FILE_USER_BLOCKING: {
1029 TRACE_EVENT0("shutdown",
1030 "BrowserMainLoop::Subsystem:FileUserBlockingThread");
1031 ResetThread_FILE_USER_BLOCKING(file_user_blocking_thread_.Pass());
1032 break;
1034 case BrowserThread::PROCESS_LAUNCHER: {
1035 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:LauncherThread");
1036 ResetThread_PROCESS_LAUNCHER(process_launcher_thread_.Pass());
1037 break;
1039 case BrowserThread::CACHE: {
1040 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:CacheThread");
1041 ResetThread_CACHE(cache_thread_.Pass());
1042 break;
1044 case BrowserThread::IO: {
1045 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IOThread");
1046 ResetThread_IO(io_thread_.Pass());
1047 break;
1049 case BrowserThread::UI:
1050 case BrowserThread::ID_COUNT:
1051 default:
1052 NOTREACHED();
1053 break;
1057 #if !defined(OS_IOS)
1059 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IndexedDBThread");
1060 ResetThread_IndexedDb(indexed_db_thread_.Pass());
1062 #endif
1064 // Close the blocking I/O pool after the other threads. Other threads such
1065 // as the I/O thread may need to schedule work like closing files or flushing
1066 // data during shutdown, so the blocking pool needs to be available. There
1067 // may also be slow operations pending that will blcok shutdown, so closing
1068 // it here (which will block until required operations are complete) gives
1069 // more head start for those operations to finish.
1071 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:ThreadPool");
1072 BrowserThreadImpl::ShutdownThreadPool();
1075 #if !defined(OS_IOS)
1076 // Must happen after the IO thread is shutdown since this may be accessed from
1077 // it.
1079 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUChannelFactory");
1080 if (BrowserGpuChannelHostFactory::instance())
1081 BrowserGpuChannelHostFactory::Terminate();
1084 // Must happen after the I/O thread is shutdown since this class lives on the
1085 // I/O thread and isn't threadsafe.
1087 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GamepadService");
1088 GamepadService::GetInstance()->Terminate();
1091 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:SensorService");
1092 DeviceInertialSensorService::GetInstance()->Shutdown();
1094 #if !defined(OS_ANDROID)
1096 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:BatteryStatusService");
1097 device::BatteryStatusService::GetInstance()->Shutdown();
1099 #endif
1101 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DeleteDataSources");
1102 URLDataManager::DeleteDataSources();
1104 #endif // !defined(OS_IOS)
1106 if (parts_) {
1107 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:PostDestroyThreads");
1108 parts_->PostDestroyThreads();
1112 void BrowserMainLoop::StopStartupTracingTimer() {
1113 startup_trace_timer_.Stop();
1116 void BrowserMainLoop::InitializeMainThread() {
1117 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeMainThread");
1118 static const char kThreadName[] = "CrBrowserMain";
1119 base::PlatformThread::SetName(kThreadName);
1120 if (main_message_loop_)
1121 main_message_loop_->set_thread_name(kThreadName);
1123 // Register the main thread by instantiating it, but don't call any methods.
1124 main_thread_.reset(
1125 new BrowserThreadImpl(BrowserThread::UI, base::MessageLoop::current()));
1127 // TODO(erikchen): Temporary code to help track http://crbug.com/527588.
1128 IPC::Channel::SetMessageVerifier(
1129 &content::CheckContentsOfDataReceivedMessage);
1132 int BrowserMainLoop::BrowserThreadsStarted() {
1133 TRACE_EVENT0("startup", "BrowserMainLoop::BrowserThreadsStarted");
1135 #if !defined(OS_IOS)
1136 indexed_db_thread_.reset(new base::Thread("IndexedDB"));
1137 indexed_db_thread_->Start();
1138 #endif
1140 #if !defined(OS_IOS)
1141 HistogramSynchronizer::GetInstance();
1143 #if defined(OS_ANDROID)
1144 // Up the priority of the UI thread.
1145 base::PlatformThread::SetCurrentThreadPriority(base::ThreadPriority::DISPLAY);
1146 #endif
1148 bool always_uses_gpu = true;
1149 bool established_gpu_channel = false;
1150 #if defined(OS_ANDROID)
1151 // TODO(crbug.com/439322): This should be set to |true|.
1152 established_gpu_channel = false;
1153 BrowserGpuChannelHostFactory::Initialize(established_gpu_channel);
1154 #elif defined(USE_AURA) || defined(OS_MACOSX)
1155 established_gpu_channel = true;
1156 if (!GpuDataManagerImpl::GetInstance()->CanUseGpuBrowserCompositor() ||
1157 parsed_command_line_.HasSwitch(switches::kDisableGpuEarlyInit)) {
1158 established_gpu_channel = always_uses_gpu = false;
1160 BrowserGpuChannelHostFactory::Initialize(established_gpu_channel);
1161 ImageTransportFactory::Initialize();
1162 #if defined(USE_AURA)
1163 if (aura::Env::GetInstance()) {
1164 aura::Env::GetInstance()->set_context_factory(GetContextFactory());
1166 #endif // defined(USE_AURA)
1167 #endif // defined(OS_ANDROID)
1169 // Enable the GpuMemoryBuffer dump provider with IO thread affinity. Note that
1170 // unregistration happens on the IO thread (See
1171 // BrowserProcessSubThread::IOThreadPreCleanUp).
1172 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
1173 BrowserGpuMemoryBufferManager::current(), io_thread_->task_runner());
1176 TRACE_EVENT0("startup", "BrowserThreadsStarted::Subsystem:AudioMan");
1177 audio_manager_.reset(media::AudioManager::CreateWithHangTimer(
1178 MediaInternals::GetInstance(), io_thread_->task_runner()));
1182 TRACE_EVENT0("startup", "BrowserThreadsStarted::Subsystem:MidiManager");
1183 midi_manager_.reset(media::midi::MidiManager::Create());
1186 #if defined(OS_LINUX) && defined(USE_UDEV)
1187 device_monitor_linux_.reset(new DeviceMonitorLinux());
1188 #elif defined(OS_MACOSX)
1189 device_monitor_mac_.reset(new DeviceMonitorMac());
1190 #endif
1192 #if defined(OS_WIN)
1193 UMA_HISTOGRAM_BOOLEAN("Windows.Win32kRendererLockdown",
1194 IsWin32kRendererLockdownEnabled());
1195 #endif
1196 // RDH needs the IO thread to be created
1198 TRACE_EVENT0("startup",
1199 "BrowserMainLoop::BrowserThreadsStarted:InitResourceDispatcherHost");
1200 resource_dispatcher_host_.reset(new ResourceDispatcherHostImpl());
1203 // MediaStreamManager needs the IO thread to be created.
1205 TRACE_EVENT0("startup",
1206 "BrowserMainLoop::BrowserThreadsStarted:InitMediaStreamManager");
1207 media_stream_manager_.reset(new MediaStreamManager(audio_manager_.get()));
1211 TRACE_EVENT0("startup",
1212 "BrowserMainLoop::BrowserThreadsStarted:InitSpeechRecognition");
1213 speech_recognition_manager_.reset(new SpeechRecognitionManagerImpl(
1214 audio_manager_.get(), media_stream_manager_.get()));
1218 TRACE_EVENT0(
1219 "startup",
1220 "BrowserMainLoop::BrowserThreadsStarted::InitUserInputMonitor");
1221 user_input_monitor_ = media::UserInputMonitor::Create(
1222 io_thread_->task_runner(), main_thread_->task_runner());
1226 TRACE_EVENT0("startup",
1227 "BrowserMainLoop::BrowserThreadsStarted::TimeZoneMonitor");
1228 time_zone_monitor_ = TimeZoneMonitor::Create();
1231 // Alert the clipboard class to which threads are allowed to access the
1232 // clipboard:
1233 std::vector<base::PlatformThreadId> allowed_clipboard_threads;
1234 // The current thread is the UI thread.
1235 allowed_clipboard_threads.push_back(base::PlatformThread::CurrentId());
1236 #if defined(OS_WIN)
1237 // On Windows, clipboards are also used on the FILE or IO threads.
1238 allowed_clipboard_threads.push_back(file_thread_->GetThreadId());
1239 allowed_clipboard_threads.push_back(io_thread_->GetThreadId());
1240 #endif
1241 ui::Clipboard::SetAllowedThreads(allowed_clipboard_threads);
1243 // When running the GPU thread in-process, avoid optimistically starting it
1244 // since creating the GPU thread races against creation of the one-and-only
1245 // ChildProcess instance which is created by the renderer thread.
1246 if (GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL) &&
1247 !established_gpu_channel &&
1248 always_uses_gpu &&
1249 !UsingInProcessGpu()) {
1250 TRACE_EVENT_INSTANT0("gpu", "Post task to launch GPU process",
1251 TRACE_EVENT_SCOPE_THREAD);
1252 BrowserThread::PostTask(
1253 BrowserThread::IO, FROM_HERE,
1254 base::Bind(base::IgnoreResult(&GpuProcessHost::Get),
1255 GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED,
1256 CAUSE_FOR_GPU_LAUNCH_BROWSER_STARTUP));
1259 #if defined(OS_MACOSX)
1260 ThemeHelperMac::GetInstance();
1261 SystemHotkeyHelperMac::GetInstance()->DeferredLoadSystemHotkeys();
1262 #endif // defined(OS_MACOSX)
1264 #endif // !defined(OS_IOS)
1266 mojo_shell_context_.reset(new MojoShellContext);
1268 return result_code_;
1271 bool BrowserMainLoop::UsingInProcessGpu() const {
1272 return parsed_command_line_.HasSwitch(switches::kSingleProcess) ||
1273 parsed_command_line_.HasSwitch(switches::kInProcessGPU);
1276 bool BrowserMainLoop::InitializeToolkit() {
1277 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeToolkit");
1278 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::InitializeToolkit");
1280 // TODO(evan): this function is rather subtle, due to the variety
1281 // of intersecting ifdefs we have. To keep it easy to follow, there
1282 // are no #else branches on any #ifs.
1283 // TODO(stevenjb): Move platform specific code into platform specific Parts
1284 // (Need to add InitializeToolkit stage to BrowserParts).
1285 // See also GTK setup in EarlyInitialization, above, and associated comments.
1287 #if defined(OS_WIN)
1288 // Init common control sex.
1289 INITCOMMONCONTROLSEX config;
1290 config.dwSize = sizeof(config);
1291 config.dwICC = ICC_WIN95_CLASSES;
1292 if (!InitCommonControlsEx(&config))
1293 PLOG(FATAL);
1294 #endif
1296 #if defined(USE_AURA)
1298 #if defined(USE_X11)
1299 if (!gfx::GetXDisplay())
1300 return false;
1301 #endif
1303 // Env creates the compositor. Aura widgets need the compositor to be created
1304 // before they can be initialized by the browser.
1305 aura::Env::CreateInstance(true);
1306 #endif // defined(USE_AURA)
1308 if (parts_)
1309 parts_->ToolkitInitialized();
1311 return true;
1314 void BrowserMainLoop::MainMessageLoopRun() {
1315 #if defined(OS_ANDROID)
1316 // Android's main message loop is the Java message loop.
1317 NOTREACHED();
1318 #else
1319 DCHECK(base::MessageLoopForUI::IsCurrent());
1320 if (parameters_.ui_task) {
1321 base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
1322 *parameters_.ui_task);
1325 base::RunLoop run_loop;
1326 run_loop.Run();
1327 #endif
1330 base::FilePath BrowserMainLoop::GetStartupTraceFileName(
1331 const base::CommandLine& command_line) const {
1332 base::FilePath trace_file;
1333 if (command_line.HasSwitch(switches::kTraceStartup)) {
1334 trace_file = command_line.GetSwitchValuePath(
1335 switches::kTraceStartupFile);
1336 // trace_file = "none" means that startup events will show up for the next
1337 // begin/end tracing (via about:tracing or AutomationProxy::BeginTracing/
1338 // EndTracing, for example).
1339 if (trace_file == base::FilePath().AppendASCII("none"))
1340 return trace_file;
1342 if (trace_file.empty()) {
1343 #if defined(OS_ANDROID)
1344 TracingControllerAndroid::GenerateTracingFilePath(&trace_file);
1345 #else
1346 // Default to saving the startup trace into the current dir.
1347 trace_file = base::FilePath().AppendASCII("chrometrace.log");
1348 #endif
1350 } else {
1351 #if defined(OS_ANDROID)
1352 TracingControllerAndroid::GenerateTracingFilePath(&trace_file);
1353 #else
1354 trace_file = tracing::TraceConfigFile::GetInstance()->GetResultFile();
1355 #endif
1358 return trace_file;
1361 void BrowserMainLoop::InitStartupTracingForDuration(
1362 const base::CommandLine& command_line) {
1363 DCHECK(is_tracing_startup_for_duration_);
1365 // Initialize the tracing controller, required for memory tracing.
1366 TracingController::GetInstance();
1368 startup_trace_file_ = GetStartupTraceFileName(parsed_command_line_);
1370 int delay_secs = 5;
1371 if (command_line.HasSwitch(switches::kTraceStartup)) {
1372 std::string delay_str = command_line.GetSwitchValueASCII(
1373 switches::kTraceStartupDuration);
1374 if (!delay_str.empty() && !base::StringToInt(delay_str, &delay_secs)) {
1375 DLOG(WARNING) << "Could not parse --" << switches::kTraceStartupDuration
1376 << "=" << delay_str << " defaulting to 5 (secs)";
1377 delay_secs = 5;
1379 } else {
1380 delay_secs = tracing::TraceConfigFile::GetInstance()->GetStartupDuration();
1383 startup_trace_timer_.Start(FROM_HERE,
1384 base::TimeDelta::FromSeconds(delay_secs),
1385 this,
1386 &BrowserMainLoop::EndStartupTracing);
1389 void BrowserMainLoop::EndStartupTracing() {
1390 DCHECK(is_tracing_startup_for_duration_);
1392 is_tracing_startup_for_duration_ = false;
1393 TracingController::GetInstance()->DisableRecording(
1394 TracingController::CreateFileSink(
1395 startup_trace_file_,
1396 base::Bind(OnStoppedStartupTracing, startup_trace_file_)));
1399 } // namespace content