localStorage: Aggressively flush to disk for Android WebView.
[chromium-blink-merge.git] / content / browser / browser_main_loop.cc
bloba7178dbb2bc5061138458029550860e730499d01
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/logging.h"
10 #include "base/message_loop/message_loop.h"
11 #include "base/metrics/field_trial.h"
12 #include "base/metrics/histogram.h"
13 #include "base/pending_task.h"
14 #include "base/power_monitor/power_monitor.h"
15 #include "base/power_monitor/power_monitor_device_source.h"
16 #include "base/process/process_metrics.h"
17 #include "base/profiler/scoped_profile.h"
18 #include "base/run_loop.h"
19 #include "base/strings/string_number_conversions.h"
20 #include "base/strings/string_split.h"
21 #include "base/system_monitor/system_monitor.h"
22 #include "base/thread_task_runner_handle.h"
23 #include "base/threading/thread_restrictions.h"
24 #include "base/timer/hi_res_timer_manager.h"
25 #include "base/trace_event/memory_dump_manager.h"
26 #include "base/trace_event/trace_event.h"
27 #include "content/browser/browser_thread_impl.h"
28 #include "content/browser/device_sensors/device_inertial_sensor_service.h"
29 #include "content/browser/dom_storage/dom_storage_area.h"
30 #include "content/browser/download/save_file_manager.h"
31 #include "content/browser/gamepad/gamepad_service.h"
32 #include "content/browser/gpu/browser_gpu_channel_host_factory.h"
33 #include "content/browser/gpu/browser_gpu_memory_buffer_manager.h"
34 #include "content/browser/gpu/compositor_util.h"
35 #include "content/browser/gpu/gpu_data_manager_impl.h"
36 #include "content/browser/gpu/gpu_process_host.h"
37 #include "content/browser/gpu/gpu_process_host_ui_shim.h"
38 #include "content/browser/histogram_synchronizer.h"
39 #include "content/browser/loader/resource_dispatcher_host_impl.h"
40 #include "content/browser/media/media_internals.h"
41 #include "content/browser/net/browser_online_state_observer.h"
42 #include "content/browser/renderer_host/media/media_stream_manager.h"
43 #include "content/browser/speech/speech_recognition_manager_impl.h"
44 #include "content/browser/startup_task_runner.h"
45 #include "content/browser/time_zone_monitor.h"
46 #include "content/browser/webui/content_web_ui_controller_factory.h"
47 #include "content/browser/webui/url_data_manager.h"
48 #include "content/common/content_switches_internal.h"
49 #include "content/common/host_discardable_shared_memory_manager.h"
50 #include "content/common/host_shared_bitmap_manager.h"
51 #include "content/public/browser/browser_main_parts.h"
52 #include "content/public/browser/browser_shutdown.h"
53 #include "content/public/browser/content_browser_client.h"
54 #include "content/public/browser/render_process_host.h"
55 #include "content/public/browser/tracing_controller.h"
56 #include "content/public/common/content_switches.h"
57 #include "content/public/common/main_function_params.h"
58 #include "content/public/common/result_codes.h"
59 #include "crypto/nss_util.h"
60 #include "device/battery/battery_status_service.h"
61 #include "media/audio/audio_manager.h"
62 #include "media/base/media.h"
63 #include "media/base/user_input_monitor.h"
64 #include "media/midi/midi_manager.h"
65 #include "net/base/network_change_notifier.h"
66 #include "net/socket/client_socket_factory.h"
67 #include "net/ssl/ssl_config_service.h"
68 #include "ui/base/clipboard/clipboard.h"
70 #if defined(USE_AURA) || (defined(OS_MACOSX) && !defined(OS_IOS))
71 #include "content/browser/compositor/image_transport_factory.h"
72 #endif
74 #if defined(USE_AURA)
75 #include "content/public/browser/context_factory.h"
76 #include "ui/aura/env.h"
77 #endif
79 #if !defined(OS_IOS)
80 #include "content/browser/renderer_host/render_process_host_impl.h"
81 #endif
83 #if defined(OS_ANDROID)
84 #include "base/android/jni_android.h"
85 #include "content/browser/android/browser_startup_controller.h"
86 #include "content/browser/android/browser_surface_texture_manager.h"
87 #include "content/browser/android/tracing_controller_android.h"
88 #include "content/browser/screen_orientation/screen_orientation_delegate_android.h"
89 #include "content/public/browser/screen_orientation_provider.h"
90 #include "ui/gl/gl_surface.h"
91 #endif
93 #if defined(OS_MACOSX) && !defined(OS_IOS)
94 #include "base/mac/memory_pressure_monitor_mac.h"
95 #include "content/browser/bootstrap_sandbox_mac.h"
96 #include "content/browser/cocoa/system_hotkey_helper_mac.h"
97 #include "content/browser/compositor/browser_compositor_view_mac.h"
98 #include "content/browser/theme_helper_mac.h"
99 #endif
101 #if defined(OS_WIN)
102 #include <windows.h>
103 #include <commctrl.h>
104 #include <shellapi.h>
106 #include "base/win/memory_pressure_monitor.h"
107 #include "content/browser/system_message_window_win.h"
108 #include "content/common/sandbox_win.h"
109 #include "net/base/winsock_init.h"
110 #include "ui/base/l10n/l10n_util_win.h"
111 #endif
113 #if defined(OS_CHROMEOS)
114 #include "base/chromeos/memory_pressure_monitor_chromeos.h"
115 #include "chromeos/chromeos_switches.h"
116 #endif
118 #if defined(USE_GLIB)
119 #include <glib-object.h>
120 #endif
122 #if defined(OS_LINUX) && defined(USE_UDEV)
123 #include "content/browser/device_monitor_udev.h"
124 #elif defined(OS_MACOSX) && !defined(OS_IOS)
125 #include "content/browser/device_monitor_mac.h"
126 #endif
128 #if defined(OS_POSIX) && !defined(OS_MACOSX)
129 #include "content/browser/renderer_host/render_sandbox_host_linux.h"
130 #include "content/browser/zygote_host/zygote_host_impl_linux.h"
131 #include "sandbox/linux/suid/client/setuid_sandbox_host.h"
132 #endif
134 #if defined(ENABLE_PLUGINS)
135 #include "content/browser/plugin_service_impl.h"
136 #endif
138 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
139 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
140 #endif
142 #if defined(USE_X11)
143 #include "ui/gfx/x/x11_connection.h"
144 #include "ui/gfx/x/x11_types.h"
145 #endif
147 // One of the linux specific headers defines this as a macro.
148 #ifdef DestroyAll
149 #undef DestroyAll
150 #endif
152 namespace content {
153 namespace {
155 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
156 void SetupSandbox(const base::CommandLine& parsed_command_line) {
157 TRACE_EVENT0("startup", "SetupSandbox");
158 base::FilePath sandbox_binary;
160 scoped_ptr<sandbox::SetuidSandboxHost> setuid_sandbox_host(
161 sandbox::SetuidSandboxHost::Create());
163 const bool want_setuid_sandbox =
164 !parsed_command_line.HasSwitch(switches::kNoSandbox) &&
165 !parsed_command_line.HasSwitch(switches::kDisableSetuidSandbox) &&
166 !setuid_sandbox_host->IsDisabledViaEnvironment();
168 static const char no_suid_error[] =
169 "Running without the SUID sandbox! See "
170 "https://code.google.com/p/chromium/wiki/LinuxSUIDSandboxDevelopment "
171 "for more information on developing with the sandbox on.";
172 if (want_setuid_sandbox) {
173 sandbox_binary = setuid_sandbox_host->GetSandboxBinaryPath();
174 if (sandbox_binary.empty()) {
175 // This needs to be fatal. Talk to security@chromium.org if you feel
176 // otherwise.
177 LOG(FATAL) << no_suid_error;
179 } else {
180 LOG(ERROR) << no_suid_error;
183 // Tickle the sandbox host and zygote host so they fork now.
184 RenderSandboxHostLinux::GetInstance()->Init();
185 ZygoteHostImpl::GetInstance()->Init(sandbox_binary.value());
187 #endif
189 #if defined(USE_GLIB)
190 static void GLibLogHandler(const gchar* log_domain,
191 GLogLevelFlags log_level,
192 const gchar* message,
193 gpointer userdata) {
194 if (!log_domain)
195 log_domain = "<unknown>";
196 if (!message)
197 message = "<no message>";
199 if (strstr(message, "Unable to retrieve the file info for")) {
200 LOG(ERROR) << "GTK File code error: " << message;
201 } else if (strstr(message, "Could not find the icon") &&
202 strstr(log_domain, "Gtk")) {
203 LOG(ERROR) << "GTK icon error: " << message;
204 } else if (strstr(message, "Theme file for default has no") ||
205 strstr(message, "Theme directory") ||
206 strstr(message, "theme pixmap") ||
207 strstr(message, "locate theme engine")) {
208 LOG(ERROR) << "GTK theme error: " << message;
209 } else if (strstr(message, "Unable to create Ubuntu Menu Proxy") &&
210 strstr(log_domain, "<unknown>")) {
211 LOG(ERROR) << "GTK menu proxy create failed";
212 } else if (strstr(message, "Out of memory") &&
213 strstr(log_domain, "<unknown>")) {
214 LOG(ERROR) << "DBus call timeout or out of memory: "
215 << "http://crosbug.com/15496";
216 } else if (strstr(message, "Could not connect: Connection refused") &&
217 strstr(log_domain, "<unknown>")) {
218 LOG(ERROR) << "DConf settings backend could not connect to session bus: "
219 << "http://crbug.com/179797";
220 } else if (strstr(message, "Attempting to store changes into") ||
221 strstr(message, "Attempting to set the permissions of")) {
222 LOG(ERROR) << message << " (http://bugs.chromium.org/161366)";
223 } else if (strstr(message, "drawable is not a native X11 window")) {
224 LOG(ERROR) << message << " (http://bugs.chromium.org/329991)";
225 } else {
226 LOG(DFATAL) << log_domain << ": " << message;
230 static void SetUpGLibLogHandler() {
231 // Register GLib-handled assertions to go through our logging system.
232 const char* kLogDomains[] = { NULL, "Gtk", "Gdk", "GLib", "GLib-GObject" };
233 for (size_t i = 0; i < arraysize(kLogDomains); i++) {
234 g_log_set_handler(kLogDomains[i],
235 static_cast<GLogLevelFlags>(G_LOG_FLAG_RECURSION |
236 G_LOG_FLAG_FATAL |
237 G_LOG_LEVEL_ERROR |
238 G_LOG_LEVEL_CRITICAL |
239 G_LOG_LEVEL_WARNING),
240 GLibLogHandler,
241 NULL);
244 #endif
246 void OnStoppedStartupTracing(const base::FilePath& trace_file) {
247 VLOG(0) << "Completed startup tracing to " << trace_file.value();
250 // Disable optimizations for this block of functions so the compiler doesn't
251 // merge them all together. This makes it possible to tell what thread was
252 // unresponsive by inspecting the callstack.
253 MSVC_DISABLE_OPTIMIZE()
254 MSVC_PUSH_DISABLE_WARNING(4748)
256 NOINLINE void ResetThread_DB(scoped_ptr<BrowserProcessSubThread> thread) {
257 volatile int inhibit_comdat = __LINE__;
258 ALLOW_UNUSED_LOCAL(inhibit_comdat);
259 thread.reset();
262 NOINLINE void ResetThread_FILE(scoped_ptr<BrowserProcessSubThread> thread) {
263 volatile int inhibit_comdat = __LINE__;
264 ALLOW_UNUSED_LOCAL(inhibit_comdat);
265 thread.reset();
268 NOINLINE void ResetThread_FILE_USER_BLOCKING(
269 scoped_ptr<BrowserProcessSubThread> thread) {
270 volatile int inhibit_comdat = __LINE__;
271 ALLOW_UNUSED_LOCAL(inhibit_comdat);
272 thread.reset();
275 NOINLINE void ResetThread_PROCESS_LAUNCHER(
276 scoped_ptr<BrowserProcessSubThread> thread) {
277 volatile int inhibit_comdat = __LINE__;
278 ALLOW_UNUSED_LOCAL(inhibit_comdat);
279 thread.reset();
282 NOINLINE void ResetThread_CACHE(scoped_ptr<BrowserProcessSubThread> thread) {
283 volatile int inhibit_comdat = __LINE__;
284 ALLOW_UNUSED_LOCAL(inhibit_comdat);
285 thread.reset();
288 NOINLINE void ResetThread_IO(scoped_ptr<BrowserProcessSubThread> thread) {
289 volatile int inhibit_comdat = __LINE__;
290 ALLOW_UNUSED_LOCAL(inhibit_comdat);
291 thread.reset();
294 #if !defined(OS_IOS)
295 NOINLINE void ResetThread_IndexedDb(scoped_ptr<base::Thread> thread) {
296 volatile int inhibit_comdat = __LINE__;
297 ALLOW_UNUSED_LOCAL(inhibit_comdat);
298 thread.reset();
300 #endif
302 MSVC_POP_WARNING()
303 MSVC_ENABLE_OPTIMIZE();
305 #if defined(OS_WIN)
306 // Creates a memory pressure monitor using automatic thresholds, or those
307 // specified on the command-line. Ownership is passed to the caller.
308 base::win::MemoryPressureMonitor* CreateWinMemoryPressureMonitor(
309 const base::CommandLine& parsed_command_line) {
310 std::vector<std::string> thresholds;
311 base::SplitString(
312 parsed_command_line.GetSwitchValueASCII(
313 switches::kMemoryPressureThresholdsMb),
314 ',',
315 &thresholds);
317 int moderate_threshold_mb = 0;
318 int critical_threshold_mb = 0;
319 if (thresholds.size() == 2 &&
320 base::StringToInt(thresholds[0], &moderate_threshold_mb) &&
321 base::StringToInt(thresholds[1], &critical_threshold_mb) &&
322 moderate_threshold_mb >= critical_threshold_mb &&
323 critical_threshold_mb >= 0) {
324 return new base::win::MemoryPressureMonitor(moderate_threshold_mb,
325 critical_threshold_mb);
328 // In absence of valid switches use the automatic defaults.
329 return new base::win::MemoryPressureMonitor();
331 #endif // defined(OS_WIN)
333 } // namespace
335 // The currently-running BrowserMainLoop. There can be one or zero.
336 BrowserMainLoop* g_current_browser_main_loop = NULL;
338 // This is just to be able to keep ShutdownThreadsAndCleanUp out of
339 // the public interface of BrowserMainLoop.
340 class BrowserShutdownImpl {
341 public:
342 static void ImmediateShutdownAndExitProcess() {
343 DCHECK(g_current_browser_main_loop);
344 g_current_browser_main_loop->ShutdownThreadsAndCleanUp();
346 #if defined(OS_WIN)
347 // At this point the message loop is still running yet we've shut everything
348 // down. If any messages are processed we'll likely crash. Exit now.
349 ExitProcess(RESULT_CODE_NORMAL_EXIT);
350 #elif defined(OS_POSIX) && !defined(OS_MACOSX)
351 _exit(RESULT_CODE_NORMAL_EXIT);
352 #else
353 NOTIMPLEMENTED();
354 #endif
358 void ImmediateShutdownAndExitProcess() {
359 BrowserShutdownImpl::ImmediateShutdownAndExitProcess();
362 // For measuring memory usage after each task. Behind a command line flag.
363 class BrowserMainLoop::MemoryObserver : public base::MessageLoop::TaskObserver {
364 public:
365 MemoryObserver() {}
366 ~MemoryObserver() override {}
368 void WillProcessTask(const base::PendingTask& pending_task) override {}
370 void DidProcessTask(const base::PendingTask& pending_task) override {
371 #if !defined(OS_IOS) // No ProcessMetrics on IOS.
372 scoped_ptr<base::ProcessMetrics> process_metrics(
373 base::ProcessMetrics::CreateProcessMetrics(
374 #if defined(OS_MACOSX)
375 base::GetCurrentProcessHandle(), NULL));
376 #else
377 base::GetCurrentProcessHandle()));
378 #endif
379 size_t private_bytes;
380 process_metrics->GetMemoryBytes(&private_bytes, NULL);
381 LOCAL_HISTOGRAM_MEMORY_KB("Memory.BrowserUsed", private_bytes >> 10);
382 #endif
384 private:
385 DISALLOW_COPY_AND_ASSIGN(MemoryObserver);
389 // BrowserMainLoop construction / destruction =============================
391 BrowserMainLoop* BrowserMainLoop::GetInstance() {
392 DCHECK_CURRENTLY_ON(BrowserThread::UI);
393 return g_current_browser_main_loop;
396 BrowserMainLoop::BrowserMainLoop(const MainFunctionParams& parameters)
397 : parameters_(parameters),
398 parsed_command_line_(parameters.command_line),
399 result_code_(RESULT_CODE_NORMAL_EXIT),
400 created_threads_(false),
401 // ContentMainRunner should have enabled tracing of the browser process
402 // when kTraceStartup is in the command line.
403 is_tracing_startup_(
404 parameters.command_line.HasSwitch(switches::kTraceStartup)) {
405 DCHECK(!g_current_browser_main_loop);
406 g_current_browser_main_loop = this;
409 BrowserMainLoop::~BrowserMainLoop() {
410 DCHECK_EQ(this, g_current_browser_main_loop);
411 #if !defined(OS_IOS)
412 ui::Clipboard::DestroyClipboardForCurrentThread();
413 #endif // !defined(OS_IOS)
414 g_current_browser_main_loop = NULL;
417 void BrowserMainLoop::Init() {
418 TRACE_EVENT0("startup", "BrowserMainLoop::Init");
419 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::Init");
421 parts_.reset(
422 GetContentClient()->browser()->CreateBrowserMainParts(parameters_));
425 // BrowserMainLoop stages ==================================================
427 void BrowserMainLoop::EarlyInitialization() {
428 TRACE_EVENT0("startup", "BrowserMainLoop::EarlyInitialization");
429 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::EarlyInitialization");
431 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
432 // No thread should be created before this call, as SetupSandbox()
433 // will end-up using fork().
434 SetupSandbox(parsed_command_line_);
435 #endif
437 #if defined(USE_X11)
438 if (UsingInProcessGpu()) {
439 if (!gfx::InitializeThreadedX11()) {
440 LOG(ERROR) << "Failed to put Xlib into threaded mode.";
443 #endif
445 // GLib's spawning of new processes is buggy, so it's important that at this
446 // point GLib does not need to start DBUS. Chrome should always start with
447 // DBUS_SESSION_BUS_ADDRESS properly set. See crbug.com/309093.
448 #if defined(USE_GLIB)
449 // g_type_init will be deprecated in 2.36. 2.35 is the development
450 // version for 2.36, hence do not call g_type_init starting 2.35.
451 // http://developer.gnome.org/gobject/unstable/gobject-Type-Information.html#g-type-init
452 #if !GLIB_CHECK_VERSION(2, 35, 0)
453 // GLib type system initialization. Needed at least for gconf,
454 // used in net/proxy/proxy_config_service_linux.cc. Most likely
455 // this is superfluous as gtk_init() ought to do this. It's
456 // definitely harmless, so retained as a reminder of this
457 // requirement for gconf.
458 g_type_init();
459 #endif
461 SetUpGLibLogHandler();
462 #endif
464 if (parts_)
465 parts_->PreEarlyInitialization();
467 #if defined(OS_MACOSX)
468 // We use quite a few file descriptors for our IPC, and the default limit on
469 // the Mac is low (256), so bump it up.
470 base::SetFdLimit(1024);
471 #endif
473 #if defined(OS_WIN)
474 net::EnsureWinsockInit();
475 #endif
477 #if !defined(USE_OPENSSL)
478 // We want to be sure to init NSPR on the main thread.
479 crypto::EnsureNSPRInit();
480 #endif // !defined(USE_OPENSSL)
482 #if !defined(OS_IOS)
483 if (parsed_command_line_.HasSwitch(switches::kRendererProcessLimit)) {
484 std::string limit_string = parsed_command_line_.GetSwitchValueASCII(
485 switches::kRendererProcessLimit);
486 size_t process_limit;
487 if (base::StringToSizeT(limit_string, &process_limit)) {
488 RenderProcessHost::SetMaxRendererProcessCount(process_limit);
491 #endif // !defined(OS_IOS)
493 if (parsed_command_line_.HasSwitch(switches::kEnableNativeGpuMemoryBuffers)) {
494 BrowserGpuChannelHostFactory::EnableGpuMemoryBufferFactoryUsage(
495 gfx::GpuMemoryBuffer::MAP);
498 #if defined(USE_OZONE)
499 BrowserGpuChannelHostFactory::EnableGpuMemoryBufferFactoryUsage(
500 gfx::GpuMemoryBuffer::SCANOUT);
501 #endif
503 base::DiscardableMemoryAllocator::SetInstance(
504 HostDiscardableSharedMemoryManager::current());
506 if (parts_)
507 parts_->PostEarlyInitialization();
510 void BrowserMainLoop::MainMessageLoopStart() {
511 TRACE_EVENT0("startup", "BrowserMainLoop::MainMessageLoopStart");
512 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::MainMessageLoopStart");
514 if (parts_) {
515 TRACE_EVENT0("startup",
516 "BrowserMainLoop::MainMessageLoopStart:PreMainMessageLoopStart");
517 parts_->PreMainMessageLoopStart();
520 #if defined(OS_WIN)
521 // If we're running tests (ui_task is non-null), then the ResourceBundle
522 // has already been initialized.
523 if (!parameters_.ui_task) {
524 // Override the configured locale with the user's preferred UI language.
525 l10n_util::OverrideLocaleWithUILanguageList();
527 #endif
529 // Create a MessageLoop if one does not already exist for the current thread.
530 if (!base::MessageLoop::current())
531 main_message_loop_.reset(new base::MessageLoopForUI);
533 InitializeMainThread();
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::InitializeCPUSpecificMediaFeatures();
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_) {
590 TRACE_EVENT0("startup", "BrowserMainLoop::InitStartupTracing");
591 InitStartupTracing(parsed_command_line_);
593 #endif // !defined(OS_IOS)
595 #if defined(OS_ANDROID)
597 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SurfaceTextureManager");
598 SurfaceTextureManager::InitInstance(new BrowserSurfaceTextureManager);
601 if (!parsed_command_line_.HasSwitch(
602 switches::kDisableScreenOrientationLock)) {
603 TRACE_EVENT0("startup",
604 "BrowserMainLoop::Subsystem:ScreenOrientationProvider");
605 screen_orientation_delegate_.reset(
606 new ScreenOrientationDelegateAndroid());
607 ScreenOrientationProvider::SetDelegate(screen_orientation_delegate_.get());
609 #endif
611 if (parsed_command_line_.HasSwitch(switches::kMemoryMetrics)) {
612 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MemoryObserver");
613 memory_observer_.reset(new MemoryObserver());
614 base::MessageLoop::current()->AddTaskObserver(memory_observer_.get());
617 if (parsed_command_line_.HasSwitch(
618 switches::kEnableAggressiveDOMStorageFlushing)) {
619 TRACE_EVENT0("startup",
620 "BrowserMainLoop::Subsystem:EnableAggressiveCommitDelay");
621 DOMStorageArea::EnableAggressiveCommitDelay();
624 base::trace_event::MemoryDumpManager::GetInstance()->Initialize();
626 // Enable the dump providers.
627 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
628 HostSharedBitmapManager::current());
630 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
631 trace_memory_controller_.reset(new base::trace_event::TraceMemoryController(
632 base::MessageLoop::current()->message_loop_proxy(),
633 ::HeapProfilerWithPseudoStackStart, ::HeapProfilerStop,
634 ::GetHeapProfile));
635 #endif
638 int BrowserMainLoop::PreCreateThreads() {
639 if (parts_) {
640 TRACE_EVENT0("startup",
641 "BrowserMainLoop::CreateThreads:PreCreateThreads");
642 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::PreCreateThreads");
644 result_code_ = parts_->PreCreateThreads();
647 #if defined(OS_CHROMEOS)
648 if (chromeos::switches::MemoryPressureHandlingEnabled()) {
649 memory_pressure_monitor_.reset(new base::MemoryPressureMonitorChromeOS(
650 chromeos::switches::GetMemoryPressureThresholds()));
652 #elif defined(OS_MACOSX) && !defined(OS_IOS)
653 memory_pressure_monitor_.reset(new base::MemoryPressureMonitorMac());
654 #elif defined(OS_WIN)
655 memory_pressure_monitor_.reset(CreateWinMemoryPressureMonitor(
656 parsed_command_line_));
657 #endif
659 #if defined(ENABLE_PLUGINS)
660 // Prior to any processing happening on the io thread, we create the
661 // plugin service as it is predominantly used from the io thread,
662 // but must be created on the main thread. The service ctor is
663 // inexpensive and does not invoke the io_thread() accessor.
665 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads:PluginService");
666 PluginService::GetInstance()->Init();
668 #endif
670 // Need to initialize in-process GpuDataManager before creating threads.
671 // It's unsafe to append the gpu command line switches to the global
672 // CommandLine::ForCurrentProcess object after threads are created.
673 if (UsingInProcessGpu()) {
674 bool initialize_gpu_data_manager = true;
675 #if defined(OS_ANDROID)
676 if (!gfx::GLSurface::InitializeOneOff()) {
677 // Single-process Android WebView supports no gpu.
678 LOG(ERROR) << "GLSurface::InitializeOneOff failed";
679 initialize_gpu_data_manager = false;
681 #endif
683 // Initialize the GpuDataManager before we set up the MessageLoops because
684 // otherwise we'll trigger the assertion about doing IO on the UI thread.
685 if (initialize_gpu_data_manager)
686 GpuDataManagerImpl::GetInstance()->Initialize();
689 #if !defined(OS_IOS) && (!defined(GOOGLE_CHROME_BUILD) || defined(OS_ANDROID))
690 // Single-process is an unsupported and not fully tested mode, so
691 // don't enable it for official Chrome builds (except on Android).
692 if (parsed_command_line_.HasSwitch(switches::kSingleProcess))
693 RenderProcessHost::SetRunRendererInProcess(true);
694 #endif
696 return result_code_;
699 void BrowserMainLoop::CreateStartupTasks() {
700 TRACE_EVENT0("startup", "BrowserMainLoop::CreateStartupTasks");
701 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::CreateStartupTasks");
703 // First time through, we really want to create all the tasks
704 if (!startup_task_runner_.get()) {
705 #if defined(OS_ANDROID)
706 startup_task_runner_ = make_scoped_ptr(new StartupTaskRunner(
707 base::Bind(&BrowserStartupComplete),
708 base::MessageLoop::current()->message_loop_proxy()));
709 #else
710 startup_task_runner_ = make_scoped_ptr(new StartupTaskRunner(
711 base::Callback<void(int)>(),
712 base::MessageLoop::current()->message_loop_proxy()));
713 #endif
714 StartupTask pre_create_threads =
715 base::Bind(&BrowserMainLoop::PreCreateThreads, base::Unretained(this));
716 startup_task_runner_->AddTask(pre_create_threads);
718 StartupTask create_threads =
719 base::Bind(&BrowserMainLoop::CreateThreads, base::Unretained(this));
720 startup_task_runner_->AddTask(create_threads);
722 StartupTask browser_thread_started = base::Bind(
723 &BrowserMainLoop::BrowserThreadsStarted, base::Unretained(this));
724 startup_task_runner_->AddTask(browser_thread_started);
726 StartupTask pre_main_message_loop_run = base::Bind(
727 &BrowserMainLoop::PreMainMessageLoopRun, base::Unretained(this));
728 startup_task_runner_->AddTask(pre_main_message_loop_run);
730 #if defined(OS_ANDROID)
731 if (BrowserMayStartAsynchronously()) {
732 startup_task_runner_->StartRunningTasksAsync();
734 #endif
736 #if defined(OS_ANDROID)
737 if (!BrowserMayStartAsynchronously()) {
738 // A second request for asynchronous startup can be ignored, so
739 // StartupRunningTasksAsync is only called first time through. If, however,
740 // this is a request for synchronous startup then it must override any
741 // previous call for async startup, so we call RunAllTasksNow()
742 // unconditionally.
743 startup_task_runner_->RunAllTasksNow();
745 #else
746 startup_task_runner_->RunAllTasksNow();
747 #endif
750 int BrowserMainLoop::CreateThreads() {
751 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads");
752 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::CreateThreads");
754 base::Thread::Options io_message_loop_options;
755 io_message_loop_options.message_loop_type = base::MessageLoop::TYPE_IO;
756 base::Thread::Options ui_message_loop_options;
757 ui_message_loop_options.message_loop_type = base::MessageLoop::TYPE_UI;
759 // Start threads in the order they occur in the BrowserThread::ID
760 // enumeration, except for BrowserThread::UI which is the main
761 // thread.
763 // Must be size_t so we can increment it.
764 for (size_t thread_id = BrowserThread::UI + 1;
765 thread_id < BrowserThread::ID_COUNT;
766 ++thread_id) {
767 scoped_ptr<BrowserProcessSubThread>* thread_to_start = NULL;
768 base::Thread::Options options;
770 switch (thread_id) {
771 case BrowserThread::DB:
772 TRACE_EVENT_BEGIN1("startup",
773 "BrowserMainLoop::CreateThreads:start",
774 "Thread", "BrowserThread::DB");
775 thread_to_start = &db_thread_;
776 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
777 break;
778 case BrowserThread::FILE_USER_BLOCKING:
779 TRACE_EVENT_BEGIN1("startup",
780 "BrowserMainLoop::CreateThreads:start",
781 "Thread", "BrowserThread::FILE_USER_BLOCKING");
782 thread_to_start = &file_user_blocking_thread_;
783 break;
784 case BrowserThread::FILE:
785 TRACE_EVENT_BEGIN1("startup",
786 "BrowserMainLoop::CreateThreads:start",
787 "Thread", "BrowserThread::FILE");
788 thread_to_start = &file_thread_;
789 #if defined(OS_WIN)
790 // On Windows, the FILE thread needs to be have a UI message loop
791 // which pumps messages in such a way that Google Update can
792 // communicate back to us.
793 options = ui_message_loop_options;
794 #else
795 options = io_message_loop_options;
796 #endif
797 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
798 break;
799 case BrowserThread::PROCESS_LAUNCHER:
800 TRACE_EVENT_BEGIN1("startup",
801 "BrowserMainLoop::CreateThreads:start",
802 "Thread", "BrowserThread::PROCESS_LAUNCHER");
803 thread_to_start = &process_launcher_thread_;
804 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
805 break;
806 case BrowserThread::CACHE:
807 TRACE_EVENT_BEGIN1("startup",
808 "BrowserMainLoop::CreateThreads:start",
809 "Thread", "BrowserThread::CACHE");
810 thread_to_start = &cache_thread_;
811 options = io_message_loop_options;
812 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
813 break;
814 case BrowserThread::IO:
815 TRACE_EVENT_BEGIN1("startup",
816 "BrowserMainLoop::CreateThreads:start",
817 "Thread", "BrowserThread::IO");
818 thread_to_start = &io_thread_;
819 options = io_message_loop_options;
820 break;
821 case BrowserThread::UI:
822 case BrowserThread::ID_COUNT:
823 default:
824 NOTREACHED();
825 break;
828 BrowserThread::ID id = static_cast<BrowserThread::ID>(thread_id);
830 if (thread_to_start) {
831 (*thread_to_start).reset(new BrowserProcessSubThread(id));
832 if (!(*thread_to_start)->StartWithOptions(options)) {
833 LOG(FATAL) << "Failed to start the browser thread: id == " << id;
835 } else {
836 NOTREACHED();
839 TRACE_EVENT_END0("startup", "BrowserMainLoop::CreateThreads:start");
841 created_threads_ = true;
842 return result_code_;
845 int BrowserMainLoop::PreMainMessageLoopRun() {
846 if (parts_) {
847 TRACE_EVENT0("startup",
848 "BrowserMainLoop::CreateThreads:PreMainMessageLoopRun");
849 TRACK_SCOPED_REGION(
850 "Startup", "BrowserMainLoop::PreMainMessageLoopRun");
852 parts_->PreMainMessageLoopRun();
855 // If the UI thread blocks, the whole UI is unresponsive.
856 // Do not allow disk IO from the UI thread.
857 base::ThreadRestrictions::SetIOAllowed(false);
858 base::ThreadRestrictions::DisallowWaiting();
859 return result_code_;
862 void BrowserMainLoop::RunMainMessageLoopParts() {
863 TRACE_EVENT_BEGIN_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
865 bool ran_main_loop = false;
866 if (parts_)
867 ran_main_loop = parts_->MainMessageLoopRun(&result_code_);
869 if (!ran_main_loop)
870 MainMessageLoopRun();
872 TRACE_EVENT_END_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
875 void BrowserMainLoop::ShutdownThreadsAndCleanUp() {
876 if (!created_threads_) {
877 // Called early, nothing to do
878 return;
880 TRACE_EVENT0("shutdown", "BrowserMainLoop::ShutdownThreadsAndCleanUp");
882 // Teardown may start in PostMainMessageLoopRun, and during teardown we
883 // need to be able to perform IO.
884 base::ThreadRestrictions::SetIOAllowed(true);
885 BrowserThread::PostTask(
886 BrowserThread::IO, FROM_HERE,
887 base::Bind(base::IgnoreResult(&base::ThreadRestrictions::SetIOAllowed),
888 true));
890 #if !defined(OS_IOS)
891 if (RenderProcessHost::run_renderer_in_process())
892 RenderProcessHostImpl::ShutDownInProcessRenderer();
893 #endif
895 if (parts_) {
896 TRACE_EVENT0("shutdown",
897 "BrowserMainLoop::Subsystem:PostMainMessageLoopRun");
898 parts_->PostMainMessageLoopRun();
901 trace_memory_controller_.reset();
902 system_stats_monitor_.reset();
904 #if !defined(OS_IOS)
905 // Destroying the GpuProcessHostUIShims on the UI thread posts a task to
906 // delete related objects on the GPU thread. This must be done before
907 // stopping the GPU thread. The GPU thread will close IPC channels to renderer
908 // processes so this has to happen before stopping the IO thread.
910 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUProcessHostShim");
911 GpuProcessHostUIShim::DestroyAll();
913 // Cancel pending requests and prevent new requests.
914 if (resource_dispatcher_host_) {
915 TRACE_EVENT0("shutdown",
916 "BrowserMainLoop::Subsystem:ResourceDispatcherHost");
917 resource_dispatcher_host_.get()->Shutdown();
920 #if defined(OS_CHROMEOS) || defined(OS_MACOSX)
921 memory_pressure_monitor_.reset();
922 #endif
924 #if defined(OS_MACOSX)
925 BrowserCompositorMac::DisableRecyclingForShutdown();
926 #endif
928 #if defined(USE_AURA) || defined(OS_MACOSX)
930 TRACE_EVENT0("shutdown",
931 "BrowserMainLoop::Subsystem:ImageTransportFactory");
932 ImageTransportFactory::Terminate();
934 #endif
936 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
937 ZygoteHostImpl::GetInstance()->TearDownAfterLastChild();
938 #endif // defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
940 // The device monitors are using |system_monitor_| as dependency, so delete
941 // them before |system_monitor_| goes away.
942 // On Mac and windows, the monitor needs to be destroyed on the same thread
943 // as they were created. On Linux, the monitor will be deleted when IO thread
944 // goes away.
945 #if defined(OS_WIN)
946 system_message_window_.reset();
947 #elif defined(OS_MACOSX)
948 device_monitor_mac_.reset();
949 #endif
950 #endif // !defined(OS_IOS)
952 // Must be size_t so we can subtract from it.
953 for (size_t thread_id = BrowserThread::ID_COUNT - 1;
954 thread_id >= (BrowserThread::UI + 1);
955 --thread_id) {
956 // Find the thread object we want to stop. Looping over all valid
957 // BrowserThread IDs and DCHECKing on a missing case in the switch
958 // statement helps avoid a mismatch between this code and the
959 // BrowserThread::ID enumeration.
961 // The destruction order is the reverse order of occurrence in the
962 // BrowserThread::ID list. The rationale for the order is as
963 // follows (need to be filled in a bit):
966 // - The IO thread is the only user of the CACHE thread.
968 // - The PROCESS_LAUNCHER thread must be stopped after IO in case
969 // the IO thread posted a task to terminate a process on the
970 // process launcher thread.
972 // - (Not sure why DB stops last.)
973 switch (thread_id) {
974 case BrowserThread::DB: {
975 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DBThread");
976 ResetThread_DB(db_thread_.Pass());
977 break;
979 case BrowserThread::FILE: {
980 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:FileThread");
981 #if !defined(OS_IOS)
982 // Clean up state that lives on or uses the file_thread_ before
983 // it goes away.
984 if (resource_dispatcher_host_)
985 resource_dispatcher_host_.get()->save_file_manager()->Shutdown();
986 #endif // !defined(OS_IOS)
987 ResetThread_FILE(file_thread_.Pass());
988 break;
990 case BrowserThread::FILE_USER_BLOCKING: {
991 TRACE_EVENT0("shutdown",
992 "BrowserMainLoop::Subsystem:FileUserBlockingThread");
993 ResetThread_FILE_USER_BLOCKING(file_user_blocking_thread_.Pass());
994 break;
996 case BrowserThread::PROCESS_LAUNCHER: {
997 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:LauncherThread");
998 ResetThread_PROCESS_LAUNCHER(process_launcher_thread_.Pass());
999 break;
1001 case BrowserThread::CACHE: {
1002 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:CacheThread");
1003 ResetThread_CACHE(cache_thread_.Pass());
1004 break;
1006 case BrowserThread::IO: {
1007 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IOThread");
1008 ResetThread_IO(io_thread_.Pass());
1009 break;
1011 case BrowserThread::UI:
1012 case BrowserThread::ID_COUNT:
1013 default:
1014 NOTREACHED();
1015 break;
1019 #if !defined(OS_IOS)
1021 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IndexedDBThread");
1022 ResetThread_IndexedDb(indexed_db_thread_.Pass());
1024 #endif
1026 // Close the blocking I/O pool after the other threads. Other threads such
1027 // as the I/O thread may need to schedule work like closing files or flushing
1028 // data during shutdown, so the blocking pool needs to be available. There
1029 // may also be slow operations pending that will blcok shutdown, so closing
1030 // it here (which will block until required operations are complete) gives
1031 // more head start for those operations to finish.
1033 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:ThreadPool");
1034 BrowserThreadImpl::ShutdownThreadPool();
1037 #if !defined(OS_IOS)
1038 // Must happen after the IO thread is shutdown since this may be accessed from
1039 // it.
1041 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUChannelFactory");
1042 if (BrowserGpuChannelHostFactory::instance())
1043 BrowserGpuChannelHostFactory::Terminate();
1046 // Must happen after the I/O thread is shutdown since this class lives on the
1047 // I/O thread and isn't threadsafe.
1049 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GamepadService");
1050 GamepadService::GetInstance()->Terminate();
1053 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:SensorService");
1054 DeviceInertialSensorService::GetInstance()->Shutdown();
1057 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:BatteryStatusService");
1058 device::BatteryStatusService::GetInstance()->Shutdown();
1061 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DeleteDataSources");
1062 URLDataManager::DeleteDataSources();
1064 #endif // !defined(OS_IOS)
1066 if (parts_) {
1067 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:PostDestroyThreads");
1068 parts_->PostDestroyThreads();
1072 void BrowserMainLoop::StopStartupTracingTimer() {
1073 startup_trace_timer_.Stop();
1076 void BrowserMainLoop::InitializeMainThread() {
1077 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeMainThread");
1078 const char* kThreadName = "CrBrowserMain";
1079 base::PlatformThread::SetName(kThreadName);
1080 if (main_message_loop_)
1081 main_message_loop_->set_thread_name(kThreadName);
1083 // Register the main thread by instantiating it, but don't call any methods.
1084 main_thread_.reset(
1085 new BrowserThreadImpl(BrowserThread::UI, base::MessageLoop::current()));
1088 int BrowserMainLoop::BrowserThreadsStarted() {
1089 TRACE_EVENT0("startup", "BrowserMainLoop::BrowserThreadsStarted");
1091 #if !defined(OS_IOS)
1092 indexed_db_thread_.reset(new base::Thread("IndexedDB"));
1093 indexed_db_thread_->Start();
1094 #endif
1096 #if !defined(OS_IOS)
1097 HistogramSynchronizer::GetInstance();
1100 // GpuDataManager for in-process initialized in PreCreateThreads.
1101 bool initialize_gpu_data_manager = !UsingInProcessGpu();
1102 #if defined(OS_ANDROID)
1103 // Up the priority of anything that touches with display tasks
1104 // (this thread is UI thread, and io_thread_ is for IPCs).
1105 io_thread_->SetPriority(base::ThreadPriority::DISPLAY);
1106 base::PlatformThread::SetThreadPriority(base::PlatformThread::CurrentHandle(),
1107 base::ThreadPriority::DISPLAY);
1109 // On Android, GLSurface::InitializeOneOff() must be called before
1110 // initalizing the GpuDataManagerImpl as it uses the GL bindings.
1111 // TODO(sievers): Shouldn't need to init full bindings to determine GL
1112 // version/vendor strings. crbug.com/326295
1113 if (initialize_gpu_data_manager) {
1114 // Note InitializeOneOff is not safe either for in-process gpu after
1115 // creating threads, since it may race with the gpu thread.
1116 if (!gfx::GLSurface::InitializeOneOff()) {
1117 LOG(FATAL) << "GLSurface::InitializeOneOff failed";
1120 #endif
1122 if (initialize_gpu_data_manager)
1123 GpuDataManagerImpl::GetInstance()->Initialize();
1125 bool always_uses_gpu = true;
1126 bool established_gpu_channel = false;
1127 #if defined(USE_AURA) || defined(OS_MACOSX)
1128 established_gpu_channel = true;
1129 if (!GpuDataManagerImpl::GetInstance()->CanUseGpuBrowserCompositor() ||
1130 parsed_command_line_.HasSwitch(switches::kDisableGpuEarlyInit)) {
1131 established_gpu_channel = always_uses_gpu = false;
1133 BrowserGpuChannelHostFactory::Initialize(established_gpu_channel);
1134 ImageTransportFactory::Initialize();
1135 #if defined(USE_AURA)
1136 if (aura::Env::GetInstance()) {
1137 aura::Env::GetInstance()->set_context_factory(GetContextFactory());
1139 #endif
1140 #elif defined(OS_ANDROID)
1141 // TODO(crbug.com/439322): This should be set to |true|.
1142 established_gpu_channel = false;
1143 BrowserGpuChannelHostFactory::Initialize(established_gpu_channel);
1144 #endif
1146 // Enable the GpuMemoryBuffer dump provider with IO thread affinity. Note that
1147 // unregistration happens on the IO thread (See
1148 // BrowserProcessSubThread::IOThreadPreCleanUp).
1149 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
1150 BrowserGpuMemoryBufferManager::current(), io_thread_->task_runner());
1153 TRACE_EVENT0("startup", "BrowserThreadsStarted::Subsystem:AudioMan");
1154 audio_manager_.reset(media::AudioManager::CreateWithHangTimer(
1155 MediaInternals::GetInstance(), io_thread_->task_runner()));
1159 TRACE_EVENT0("startup", "BrowserThreadsStarted::Subsystem:MidiManager");
1160 midi_manager_.reset(media::midi::MidiManager::Create());
1163 #if defined(OS_LINUX) && defined(USE_UDEV)
1164 device_monitor_linux_.reset(new DeviceMonitorLinux());
1165 #elif defined(OS_MACOSX)
1166 device_monitor_mac_.reset(new DeviceMonitorMac());
1167 #endif
1169 #if defined(OS_WIN)
1170 UMA_HISTOGRAM_BOOLEAN("Windows.Win32kRendererLockdown",
1171 IsWin32kRendererLockdownEnabled());
1172 #endif
1173 // RDH needs the IO thread to be created
1175 TRACE_EVENT0("startup",
1176 "BrowserMainLoop::BrowserThreadsStarted:InitResourceDispatcherHost");
1177 resource_dispatcher_host_.reset(new ResourceDispatcherHostImpl());
1180 // MediaStreamManager needs the IO thread to be created.
1182 TRACE_EVENT0("startup",
1183 "BrowserMainLoop::BrowserThreadsStarted:InitMediaStreamManager");
1184 media_stream_manager_.reset(new MediaStreamManager(audio_manager_.get()));
1188 TRACE_EVENT0("startup",
1189 "BrowserMainLoop::BrowserThreadsStarted:InitSpeechRecognition");
1190 speech_recognition_manager_.reset(new SpeechRecognitionManagerImpl(
1191 audio_manager_.get(), media_stream_manager_.get()));
1195 TRACE_EVENT0(
1196 "startup",
1197 "BrowserMainLoop::BrowserThreadsStarted::InitUserInputMonitor");
1198 user_input_monitor_ = media::UserInputMonitor::Create(
1199 io_thread_->message_loop_proxy(), main_thread_->message_loop_proxy());
1203 TRACE_EVENT0("startup",
1204 "BrowserMainLoop::BrowserThreadsStarted::TimeZoneMonitor");
1205 time_zone_monitor_ = TimeZoneMonitor::Create();
1208 // Alert the clipboard class to which threads are allowed to access the
1209 // clipboard:
1210 std::vector<base::PlatformThreadId> allowed_clipboard_threads;
1211 // The current thread is the UI thread.
1212 allowed_clipboard_threads.push_back(base::PlatformThread::CurrentId());
1213 #if defined(OS_WIN)
1214 // On Windows, clipboards are also used on the File or IO threads.
1215 allowed_clipboard_threads.push_back(file_thread_->thread_id());
1216 allowed_clipboard_threads.push_back(io_thread_->thread_id());
1217 #endif
1218 ui::Clipboard::SetAllowedThreads(allowed_clipboard_threads);
1220 // When running the GPU thread in-process, avoid optimistically starting it
1221 // since creating the GPU thread races against creation of the one-and-only
1222 // ChildProcess instance which is created by the renderer thread.
1223 if (GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL) &&
1224 !established_gpu_channel &&
1225 always_uses_gpu &&
1226 !UsingInProcessGpu()) {
1227 TRACE_EVENT_INSTANT0("gpu", "Post task to launch GPU process",
1228 TRACE_EVENT_SCOPE_THREAD);
1229 BrowserThread::PostTask(
1230 BrowserThread::IO, FROM_HERE, base::Bind(
1231 base::IgnoreResult(&GpuProcessHost::Get),
1232 GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED,
1233 CAUSE_FOR_GPU_LAUNCH_BROWSER_STARTUP));
1236 #if defined(OS_MACOSX)
1237 ThemeHelperMac::GetInstance();
1238 SystemHotkeyHelperMac::GetInstance()->DeferredLoadSystemHotkeys();
1239 if (ShouldEnableBootstrapSandbox()) {
1240 TRACE_EVENT0("startup",
1241 "BrowserMainLoop::BrowserThreadsStarted:BootstrapSandbox");
1242 CHECK(GetBootstrapSandbox());
1244 #endif // defined(OS_MACOSX)
1246 #endif // !defined(OS_IOS)
1248 return result_code_;
1251 bool BrowserMainLoop::UsingInProcessGpu() const {
1252 return parsed_command_line_.HasSwitch(switches::kSingleProcess) ||
1253 parsed_command_line_.HasSwitch(switches::kInProcessGPU);
1256 bool BrowserMainLoop::InitializeToolkit() {
1257 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeToolkit");
1258 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::InitializeToolkit");
1260 // TODO(evan): this function is rather subtle, due to the variety
1261 // of intersecting ifdefs we have. To keep it easy to follow, there
1262 // are no #else branches on any #ifs.
1263 // TODO(stevenjb): Move platform specific code into platform specific Parts
1264 // (Need to add InitializeToolkit stage to BrowserParts).
1265 // See also GTK setup in EarlyInitialization, above, and associated comments.
1267 #if defined(OS_WIN)
1268 // Init common control sex.
1269 INITCOMMONCONTROLSEX config;
1270 config.dwSize = sizeof(config);
1271 config.dwICC = ICC_WIN95_CLASSES;
1272 if (!InitCommonControlsEx(&config))
1273 PLOG(FATAL);
1274 #endif
1276 #if defined(USE_AURA)
1278 #if defined(USE_X11)
1279 if (!gfx::GetXDisplay())
1280 return false;
1281 #endif
1283 // Env creates the compositor. Aura widgets need the compositor to be created
1284 // before they can be initialized by the browser.
1285 aura::Env::CreateInstance(true);
1286 #endif // defined(USE_AURA)
1288 if (parts_)
1289 parts_->ToolkitInitialized();
1291 return true;
1294 void BrowserMainLoop::MainMessageLoopRun() {
1295 #if defined(OS_ANDROID)
1296 // Android's main message loop is the Java message loop.
1297 NOTREACHED();
1298 #else
1299 DCHECK(base::MessageLoopForUI::IsCurrent());
1300 if (parameters_.ui_task)
1301 base::MessageLoopForUI::current()->PostTask(FROM_HERE,
1302 *parameters_.ui_task);
1304 base::RunLoop run_loop;
1305 run_loop.Run();
1306 #endif
1309 base::FilePath BrowserMainLoop::GetStartupTraceFileName(
1310 const base::CommandLine& command_line) const {
1311 base::FilePath trace_file = command_line.GetSwitchValuePath(
1312 switches::kTraceStartupFile);
1313 // trace_file = "none" means that startup events will show up for the next
1314 // begin/end tracing (via about:tracing or AutomationProxy::BeginTracing/
1315 // EndTracing, for example).
1316 if (trace_file == base::FilePath().AppendASCII("none"))
1317 return trace_file;
1319 if (trace_file.empty()) {
1320 #if defined(OS_ANDROID)
1321 TracingControllerAndroid::GenerateTracingFilePath(&trace_file);
1322 #else
1323 // Default to saving the startup trace into the current dir.
1324 trace_file = base::FilePath().AppendASCII("chrometrace.log");
1325 #endif
1328 return trace_file;
1331 void BrowserMainLoop::InitStartupTracing(
1332 const base::CommandLine& command_line) {
1333 DCHECK(is_tracing_startup_);
1335 startup_trace_file_ = GetStartupTraceFileName(parsed_command_line_);
1337 std::string delay_str = command_line.GetSwitchValueASCII(
1338 switches::kTraceStartupDuration);
1339 int delay_secs = 5;
1340 if (!delay_str.empty() && !base::StringToInt(delay_str, &delay_secs)) {
1341 DLOG(WARNING) << "Could not parse --" << switches::kTraceStartupDuration
1342 << "=" << delay_str << " defaulting to 5 (secs)";
1343 delay_secs = 5;
1346 startup_trace_timer_.Start(FROM_HERE,
1347 base::TimeDelta::FromSeconds(delay_secs),
1348 this,
1349 &BrowserMainLoop::EndStartupTracing);
1352 void BrowserMainLoop::EndStartupTracing() {
1353 is_tracing_startup_ = false;
1354 TracingController::GetInstance()->DisableRecording(
1355 TracingController::CreateFileSink(
1356 startup_trace_file_,
1357 base::Bind(OnStoppedStartupTracing, startup_trace_file_)));
1360 } // namespace content