Roll src/third_party/WebKit 3a0ba1e:fcd7003 (svn 191141:191149)
[chromium-blink-merge.git] / content / browser / browser_main_loop.cc
blob2409bc78f8a26ef634559cd92a218278da491bca
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/run_loop.h"
18 #include "base/strings/string_number_conversions.h"
19 #include "base/system_monitor/system_monitor.h"
20 #include "base/thread_task_runner_handle.h"
21 #include "base/threading/thread_restrictions.h"
22 #include "base/timer/hi_res_timer_manager.h"
23 #include "base/trace_event/trace_event.h"
24 #include "content/browser/browser_thread_impl.h"
25 #include "content/browser/device_sensors/device_inertial_sensor_service.h"
26 #include "content/browser/download/save_file_manager.h"
27 #include "content/browser/gamepad/gamepad_service.h"
28 #include "content/browser/gpu/browser_gpu_channel_host_factory.h"
29 #include "content/browser/gpu/compositor_util.h"
30 #include "content/browser/gpu/gpu_data_manager_impl.h"
31 #include "content/browser/gpu/gpu_process_host.h"
32 #include "content/browser/gpu/gpu_process_host_ui_shim.h"
33 #include "content/browser/histogram_synchronizer.h"
34 #include "content/browser/loader/resource_dispatcher_host_impl.h"
35 #include "content/browser/media/media_internals.h"
36 #include "content/browser/net/browser_online_state_observer.h"
37 #include "content/browser/renderer_host/media/media_stream_manager.h"
38 #include "content/browser/speech/speech_recognition_manager_impl.h"
39 #include "content/browser/startup_task_runner.h"
40 #include "content/browser/time_zone_monitor.h"
41 #include "content/browser/webui/content_web_ui_controller_factory.h"
42 #include "content/browser/webui/url_data_manager.h"
43 #include "content/common/content_switches_internal.h"
44 #include "content/public/browser/browser_main_parts.h"
45 #include "content/public/browser/browser_shutdown.h"
46 #include "content/public/browser/content_browser_client.h"
47 #include "content/public/browser/render_process_host.h"
48 #include "content/public/browser/tracing_controller.h"
49 #include "content/public/common/content_switches.h"
50 #include "content/public/common/main_function_params.h"
51 #include "content/public/common/result_codes.h"
52 #include "crypto/nss_util.h"
53 #include "device/battery/battery_status_service.h"
54 #include "media/audio/audio_manager.h"
55 #include "media/base/media.h"
56 #include "media/base/user_input_monitor.h"
57 #include "media/midi/midi_manager.h"
58 #include "net/base/network_change_notifier.h"
59 #include "net/socket/client_socket_factory.h"
60 #include "net/ssl/ssl_config_service.h"
61 #include "ui/base/clipboard/clipboard.h"
63 #if defined(USE_AURA) || (defined(OS_MACOSX) && !defined(OS_IOS))
64 #include "content/browser/compositor/image_transport_factory.h"
65 #endif
67 #if defined(USE_AURA)
68 #include "content/public/browser/context_factory.h"
69 #include "ui/aura/env.h"
70 #endif
72 #if !defined(OS_IOS)
73 #include "content/browser/renderer_host/render_process_host_impl.h"
74 #endif
76 #if defined(OS_ANDROID)
77 #include "base/android/jni_android.h"
78 #include "content/browser/android/browser_startup_controller.h"
79 #include "content/browser/android/browser_surface_texture_manager.h"
80 #include "content/browser/android/tracing_controller_android.h"
81 #include "content/browser/screen_orientation/screen_orientation_delegate_android.h"
82 #include "content/public/browser/screen_orientation_provider.h"
83 #include "ui/gl/gl_surface.h"
84 #endif
86 #if defined(OS_MACOSX) && !defined(OS_IOS)
87 #include "content/browser/bootstrap_sandbox_mac.h"
88 #include "content/browser/cocoa/system_hotkey_helper_mac.h"
89 #include "content/browser/compositor/browser_compositor_view_mac.h"
90 #include "content/browser/theme_helper_mac.h"
91 #endif
93 #if defined(OS_WIN)
94 #include <windows.h>
95 #include <commctrl.h>
96 #include <shellapi.h>
98 #include "content/browser/system_message_window_win.h"
99 #include "content/common/sandbox_win.h"
100 #include "net/base/winsock_init.h"
101 #include "ui/base/l10n/l10n_util_win.h"
102 #endif
104 #if defined(OS_CHROMEOS)
105 #include "base/chromeos/memory_pressure_observer_chromeos.h"
106 #include "chromeos/chromeos_switches.h"
107 #endif
109 #if defined(USE_GLIB)
110 #include <glib-object.h>
111 #endif
113 #if defined(OS_LINUX) && defined(USE_UDEV)
114 #include "content/browser/device_monitor_udev.h"
115 #elif defined(OS_MACOSX) && !defined(OS_IOS)
116 #include "content/browser/device_monitor_mac.h"
117 #endif
119 #if defined(OS_POSIX) && !defined(OS_MACOSX)
120 #include "content/browser/renderer_host/render_sandbox_host_linux.h"
121 #include "content/browser/zygote_host/zygote_host_impl_linux.h"
122 #include "sandbox/linux/suid/client/setuid_sandbox_host.h"
123 #endif
125 #if defined(ENABLE_PLUGINS)
126 #include "content/browser/plugin_service_impl.h"
127 #endif
129 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
130 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
131 #endif
133 #if defined(USE_X11)
134 #include "ui/gfx/x/x11_connection.h"
135 #include "ui/gfx/x/x11_types.h"
136 #endif
138 // One of the linux specific headers defines this as a macro.
139 #ifdef DestroyAll
140 #undef DestroyAll
141 #endif
143 namespace content {
144 namespace {
146 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
147 void SetupSandbox(const base::CommandLine& parsed_command_line) {
148 TRACE_EVENT0("startup", "SetupSandbox");
149 base::FilePath sandbox_binary;
151 scoped_ptr<sandbox::SetuidSandboxHost> setuid_sandbox_host(
152 sandbox::SetuidSandboxHost::Create());
154 const bool want_setuid_sandbox =
155 !parsed_command_line.HasSwitch(switches::kNoSandbox) &&
156 !parsed_command_line.HasSwitch(switches::kDisableSetuidSandbox) &&
157 !setuid_sandbox_host->IsDisabledViaEnvironment();
159 static const char no_suid_error[] =
160 "Running without the SUID sandbox! See "
161 "https://code.google.com/p/chromium/wiki/LinuxSUIDSandboxDevelopment "
162 "for more information on developing with the sandbox on.";
163 if (want_setuid_sandbox) {
164 sandbox_binary = setuid_sandbox_host->GetSandboxBinaryPath();
165 if (sandbox_binary.empty()) {
166 // This needs to be fatal. Talk to security@chromium.org if you feel
167 // otherwise.
168 LOG(FATAL) << no_suid_error;
170 } else {
171 LOG(ERROR) << no_suid_error;
174 // Tickle the sandbox host and zygote host so they fork now.
175 RenderSandboxHostLinux::GetInstance()->Init();
176 ZygoteHostImpl::GetInstance()->Init(sandbox_binary.value());
178 #endif
180 #if defined(USE_GLIB)
181 static void GLibLogHandler(const gchar* log_domain,
182 GLogLevelFlags log_level,
183 const gchar* message,
184 gpointer userdata) {
185 if (!log_domain)
186 log_domain = "<unknown>";
187 if (!message)
188 message = "<no message>";
190 if (strstr(message, "Unable to retrieve the file info for")) {
191 LOG(ERROR) << "GTK File code error: " << message;
192 } else if (strstr(message, "Could not find the icon") &&
193 strstr(log_domain, "Gtk")) {
194 LOG(ERROR) << "GTK icon error: " << message;
195 } else if (strstr(message, "Theme file for default has no") ||
196 strstr(message, "Theme directory") ||
197 strstr(message, "theme pixmap") ||
198 strstr(message, "locate theme engine")) {
199 LOG(ERROR) << "GTK theme error: " << message;
200 } else if (strstr(message, "Unable to create Ubuntu Menu Proxy") &&
201 strstr(log_domain, "<unknown>")) {
202 LOG(ERROR) << "GTK menu proxy create failed";
203 } else if (strstr(message, "Out of memory") &&
204 strstr(log_domain, "<unknown>")) {
205 LOG(ERROR) << "DBus call timeout or out of memory: "
206 << "http://crosbug.com/15496";
207 } else if (strstr(message, "Could not connect: Connection refused") &&
208 strstr(log_domain, "<unknown>")) {
209 LOG(ERROR) << "DConf settings backend could not connect to session bus: "
210 << "http://crbug.com/179797";
211 } else if (strstr(message, "Attempting to store changes into") ||
212 strstr(message, "Attempting to set the permissions of")) {
213 LOG(ERROR) << message << " (http://bugs.chromium.org/161366)";
214 } else if (strstr(message, "drawable is not a native X11 window")) {
215 LOG(ERROR) << message << " (http://bugs.chromium.org/329991)";
216 } else {
217 LOG(DFATAL) << log_domain << ": " << message;
221 static void SetUpGLibLogHandler() {
222 // Register GLib-handled assertions to go through our logging system.
223 const char* kLogDomains[] = { NULL, "Gtk", "Gdk", "GLib", "GLib-GObject" };
224 for (size_t i = 0; i < arraysize(kLogDomains); i++) {
225 g_log_set_handler(kLogDomains[i],
226 static_cast<GLogLevelFlags>(G_LOG_FLAG_RECURSION |
227 G_LOG_FLAG_FATAL |
228 G_LOG_LEVEL_ERROR |
229 G_LOG_LEVEL_CRITICAL |
230 G_LOG_LEVEL_WARNING),
231 GLibLogHandler,
232 NULL);
235 #endif
237 void OnStoppedStartupTracing(const base::FilePath& trace_file) {
238 VLOG(0) << "Completed startup tracing to " << trace_file.value();
241 // Disable optimizations for this block of functions so the compiler doesn't
242 // merge them all together. This makes it possible to tell what thread was
243 // unresponsive by inspecting the callstack.
244 MSVC_DISABLE_OPTIMIZE()
245 MSVC_PUSH_DISABLE_WARNING(4748)
247 NOINLINE void ResetThread_DB(scoped_ptr<BrowserProcessSubThread> thread) {
248 volatile int inhibit_comdat = __LINE__;
249 ALLOW_UNUSED_LOCAL(inhibit_comdat);
250 thread.reset();
253 NOINLINE void ResetThread_FILE(scoped_ptr<BrowserProcessSubThread> thread) {
254 volatile int inhibit_comdat = __LINE__;
255 ALLOW_UNUSED_LOCAL(inhibit_comdat);
256 thread.reset();
259 NOINLINE void ResetThread_FILE_USER_BLOCKING(
260 scoped_ptr<BrowserProcessSubThread> thread) {
261 volatile int inhibit_comdat = __LINE__;
262 ALLOW_UNUSED_LOCAL(inhibit_comdat);
263 thread.reset();
266 NOINLINE void ResetThread_PROCESS_LAUNCHER(
267 scoped_ptr<BrowserProcessSubThread> thread) {
268 volatile int inhibit_comdat = __LINE__;
269 ALLOW_UNUSED_LOCAL(inhibit_comdat);
270 thread.reset();
273 NOINLINE void ResetThread_CACHE(scoped_ptr<BrowserProcessSubThread> thread) {
274 volatile int inhibit_comdat = __LINE__;
275 ALLOW_UNUSED_LOCAL(inhibit_comdat);
276 thread.reset();
279 NOINLINE void ResetThread_IO(scoped_ptr<BrowserProcessSubThread> thread) {
280 volatile int inhibit_comdat = __LINE__;
281 ALLOW_UNUSED_LOCAL(inhibit_comdat);
282 thread.reset();
285 #if !defined(OS_IOS)
286 NOINLINE void ResetThread_IndexedDb(scoped_ptr<base::Thread> thread) {
287 volatile int inhibit_comdat = __LINE__;
288 ALLOW_UNUSED_LOCAL(inhibit_comdat);
289 thread.reset();
291 #endif
293 MSVC_POP_WARNING()
294 MSVC_ENABLE_OPTIMIZE();
296 } // namespace
298 // The currently-running BrowserMainLoop. There can be one or zero.
299 BrowserMainLoop* g_current_browser_main_loop = NULL;
301 // This is just to be able to keep ShutdownThreadsAndCleanUp out of
302 // the public interface of BrowserMainLoop.
303 class BrowserShutdownImpl {
304 public:
305 static void ImmediateShutdownAndExitProcess() {
306 DCHECK(g_current_browser_main_loop);
307 g_current_browser_main_loop->ShutdownThreadsAndCleanUp();
309 #if defined(OS_WIN)
310 // At this point the message loop is still running yet we've shut everything
311 // down. If any messages are processed we'll likely crash. Exit now.
312 ExitProcess(RESULT_CODE_NORMAL_EXIT);
313 #elif defined(OS_POSIX) && !defined(OS_MACOSX)
314 _exit(RESULT_CODE_NORMAL_EXIT);
315 #else
316 NOTIMPLEMENTED();
317 #endif
321 void ImmediateShutdownAndExitProcess() {
322 BrowserShutdownImpl::ImmediateShutdownAndExitProcess();
325 // For measuring memory usage after each task. Behind a command line flag.
326 class BrowserMainLoop::MemoryObserver : public base::MessageLoop::TaskObserver {
327 public:
328 MemoryObserver() {}
329 ~MemoryObserver() override {}
331 void WillProcessTask(const base::PendingTask& pending_task) override {}
333 void DidProcessTask(const base::PendingTask& pending_task) override {
334 #if !defined(OS_IOS) // No ProcessMetrics on IOS.
335 scoped_ptr<base::ProcessMetrics> process_metrics(
336 base::ProcessMetrics::CreateProcessMetrics(
337 #if defined(OS_MACOSX)
338 base::GetCurrentProcessHandle(), NULL));
339 #else
340 base::GetCurrentProcessHandle()));
341 #endif
342 size_t private_bytes;
343 process_metrics->GetMemoryBytes(&private_bytes, NULL);
344 LOCAL_HISTOGRAM_MEMORY_KB("Memory.BrowserUsed", private_bytes >> 10);
345 #endif
347 private:
348 DISALLOW_COPY_AND_ASSIGN(MemoryObserver);
352 // BrowserMainLoop construction / destruction =============================
354 BrowserMainLoop* BrowserMainLoop::GetInstance() {
355 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
356 return g_current_browser_main_loop;
359 BrowserMainLoop::BrowserMainLoop(const MainFunctionParams& parameters)
360 : parameters_(parameters),
361 parsed_command_line_(parameters.command_line),
362 result_code_(RESULT_CODE_NORMAL_EXIT),
363 created_threads_(false),
364 // ContentMainRunner should have enabled tracing of the browser process
365 // when kTraceStartup is in the command line.
366 is_tracing_startup_(
367 parameters.command_line.HasSwitch(switches::kTraceStartup)) {
368 DCHECK(!g_current_browser_main_loop);
369 g_current_browser_main_loop = this;
372 BrowserMainLoop::~BrowserMainLoop() {
373 DCHECK_EQ(this, g_current_browser_main_loop);
374 #if !defined(OS_IOS)
375 ui::Clipboard::DestroyClipboardForCurrentThread();
376 #endif // !defined(OS_IOS)
377 g_current_browser_main_loop = NULL;
380 void BrowserMainLoop::Init() {
381 TRACE_EVENT0("startup", "BrowserMainLoop::Init");
382 parts_.reset(
383 GetContentClient()->browser()->CreateBrowserMainParts(parameters_));
386 // BrowserMainLoop stages ==================================================
388 void BrowserMainLoop::EarlyInitialization() {
389 TRACE_EVENT0("startup", "BrowserMainLoop::EarlyInitialization");
391 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
392 // No thread should be created before this call, as SetupSandbox()
393 // will end-up using fork().
394 SetupSandbox(parsed_command_line_);
395 #endif
397 #if defined(USE_X11)
398 if (UsingInProcessGpu()) {
399 if (!gfx::InitializeThreadedX11()) {
400 LOG(ERROR) << "Failed to put Xlib into threaded mode.";
403 #endif
405 // GLib's spawning of new processes is buggy, so it's important that at this
406 // point GLib does not need to start DBUS. Chrome should always start with
407 // DBUS_SESSION_BUS_ADDRESS properly set. See crbug.com/309093.
408 #if defined(USE_GLIB)
409 // g_type_init will be deprecated in 2.36. 2.35 is the development
410 // version for 2.36, hence do not call g_type_init starting 2.35.
411 // http://developer.gnome.org/gobject/unstable/gobject-Type-Information.html#g-type-init
412 #if !GLIB_CHECK_VERSION(2, 35, 0)
413 // GLib type system initialization. Needed at least for gconf,
414 // used in net/proxy/proxy_config_service_linux.cc. Most likely
415 // this is superfluous as gtk_init() ought to do this. It's
416 // definitely harmless, so retained as a reminder of this
417 // requirement for gconf.
418 g_type_init();
419 #endif
421 SetUpGLibLogHandler();
422 #endif
424 if (parts_)
425 parts_->PreEarlyInitialization();
427 #if defined(OS_MACOSX)
428 // We use quite a few file descriptors for our IPC, and the default limit on
429 // the Mac is low (256), so bump it up.
430 base::SetFdLimit(1024);
431 #endif
433 #if defined(OS_WIN)
434 net::EnsureWinsockInit();
435 #endif
437 #if !defined(USE_OPENSSL)
438 // We want to be sure to init NSPR on the main thread.
439 crypto::EnsureNSPRInit();
440 #endif // !defined(USE_OPENSSL)
442 #if !defined(OS_IOS)
443 if (parsed_command_line_.HasSwitch(switches::kRendererProcessLimit)) {
444 std::string limit_string = parsed_command_line_.GetSwitchValueASCII(
445 switches::kRendererProcessLimit);
446 size_t process_limit;
447 if (base::StringToSizeT(limit_string, &process_limit)) {
448 RenderProcessHost::SetMaxRendererProcessCount(process_limit);
451 #endif // !defined(OS_IOS)
453 if (parsed_command_line_.HasSwitch(switches::kEnableNativeGpuMemoryBuffers)) {
454 BrowserGpuChannelHostFactory::EnableGpuMemoryBufferFactoryUsage(
455 gfx::GpuMemoryBuffer::MAP);
458 #if defined(USE_OZONE)
459 BrowserGpuChannelHostFactory::EnableGpuMemoryBufferFactoryUsage(
460 gfx::GpuMemoryBuffer::SCANOUT);
461 #endif
463 if (parts_)
464 parts_->PostEarlyInitialization();
467 void BrowserMainLoop::MainMessageLoopStart() {
468 TRACE_EVENT0("startup", "BrowserMainLoop::MainMessageLoopStart");
469 if (parts_) {
470 TRACE_EVENT0("startup",
471 "BrowserMainLoop::MainMessageLoopStart:PreMainMessageLoopStart");
472 parts_->PreMainMessageLoopStart();
475 #if defined(OS_WIN)
476 // If we're running tests (ui_task is non-null), then the ResourceBundle
477 // has already been initialized.
478 if (!parameters_.ui_task) {
479 // Override the configured locale with the user's preferred UI language.
480 l10n_util::OverrideLocaleWithUILanguageList();
482 #endif
484 // Create a MessageLoop if one does not already exist for the current thread.
485 if (!base::MessageLoop::current())
486 main_message_loop_.reset(new base::MessageLoopForUI);
488 InitializeMainThread();
491 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SystemMonitor");
492 system_monitor_.reset(new base::SystemMonitor);
495 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:PowerMonitor");
496 scoped_ptr<base::PowerMonitorSource> power_monitor_source(
497 new base::PowerMonitorDeviceSource());
498 power_monitor_.reset(new base::PowerMonitor(power_monitor_source.Pass()));
501 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:HighResTimerManager");
502 hi_res_timer_manager_.reset(new base::HighResolutionTimerManager);
505 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:NetworkChangeNotifier");
506 network_change_notifier_.reset(net::NetworkChangeNotifier::Create());
509 #if !defined(OS_IOS)
511 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MediaFeatures");
512 media::InitializeCPUSpecificMediaFeatures();
515 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:AudioMan");
516 audio_manager_.reset(media::AudioManager::Create(
517 MediaInternals::GetInstance()));
520 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MidiManager");
521 midi_manager_.reset(media::MidiManager::Create());
524 TRACE_EVENT0("startup",
525 "BrowserMainLoop::Subsystem:ContentWebUIController");
526 WebUIControllerFactory::RegisterFactory(
527 ContentWebUIControllerFactory::GetInstance());
531 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:OnlineStateObserver");
532 online_state_observer_.reset(new BrowserOnlineStateObserver);
536 system_stats_monitor_.reset(
537 new base::trace_event::TraceEventSystemStatsMonitor(
538 base::ThreadTaskRunnerHandle::Get()));
540 #endif // !defined(OS_IOS)
542 #if defined(OS_WIN)
543 system_message_window_.reset(new SystemMessageWindowWin);
544 #endif
546 if (parts_)
547 parts_->PostMainMessageLoopStart();
549 #if !defined(OS_IOS)
550 // Start tracing to a file if needed. Only do this after starting the main
551 // message loop to avoid calling MessagePumpForUI::ScheduleWork() before
552 // MessagePumpForUI::Start() as it will crash the browser.
553 if (is_tracing_startup_) {
554 TRACE_EVENT0("startup", "BrowserMainLoop::InitStartupTracing");
555 InitStartupTracing(parsed_command_line_);
557 #endif // !defined(OS_IOS)
559 #if defined(OS_ANDROID)
561 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SurfaceTextureManager");
562 SurfaceTextureManager::InitInstance(new BrowserSurfaceTextureManager);
566 TRACE_EVENT0("startup",
567 "BrowserMainLoop::Subsystem:ScreenOrientationProvider");
568 screen_orientation_delegate_.reset(
569 new ScreenOrientationDelegateAndroid());
570 ScreenOrientationProvider::SetDelegate(screen_orientation_delegate_.get());
572 #endif
574 if (parsed_command_line_.HasSwitch(switches::kMemoryMetrics)) {
575 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MemoryObserver");
576 memory_observer_.reset(new MemoryObserver());
577 base::MessageLoop::current()->AddTaskObserver(memory_observer_.get());
580 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
581 trace_memory_controller_.reset(new base::trace_event::TraceMemoryController(
582 base::MessageLoop::current()->message_loop_proxy(),
583 ::HeapProfilerWithPseudoStackStart, ::HeapProfilerStop,
584 ::GetHeapProfile));
585 #endif
588 int BrowserMainLoop::PreCreateThreads() {
589 if (parts_) {
590 TRACE_EVENT0("startup",
591 "BrowserMainLoop::CreateThreads:PreCreateThreads");
592 result_code_ = parts_->PreCreateThreads();
595 #if defined(OS_CHROMEOS)
596 if (chromeos::switches::MemoryPressureHandlingEnabled()) {
597 memory_pressure_observer_.reset(new base::MemoryPressureObserverChromeOS(
598 chromeos::switches::GetMemoryPressureThresholds()));
600 #endif
602 #if defined(ENABLE_PLUGINS)
603 // Prior to any processing happening on the io thread, we create the
604 // plugin service as it is predominantly used from the io thread,
605 // but must be created on the main thread. The service ctor is
606 // inexpensive and does not invoke the io_thread() accessor.
608 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads:PluginService");
609 PluginService::GetInstance()->Init();
611 #endif
613 #if !defined(OS_IOS) && (!defined(GOOGLE_CHROME_BUILD) || defined(OS_ANDROID))
614 // Single-process is an unsupported and not fully tested mode, so
615 // don't enable it for official Chrome builds (except on Android).
616 if (parsed_command_line_.HasSwitch(switches::kSingleProcess))
617 RenderProcessHost::SetRunRendererInProcess(true);
618 #endif
620 // Need to initialize in-process GpuDataManager before creating threads.
621 // It's unsafe to append the gpu command line switches to the global
622 // CommandLine::ForCurrentProcess object after threads are created.
623 if (UsingInProcessGpu()) {
624 bool initialize_gpu_data_manager = true;
625 #if defined(OS_ANDROID)
626 if (!gfx::GLSurface::InitializeOneOff()) {
627 // Single-process Android WebView supports no gpu.
628 LOG(ERROR) << "GLSurface::InitializeOneOff failed";
629 initialize_gpu_data_manager = false;
631 #endif
633 // Initialize the GpuDataManager before we set up the MessageLoops because
634 // otherwise we'll trigger the assertion about doing IO on the UI thread.
635 if (initialize_gpu_data_manager)
636 GpuDataManagerImpl::GetInstance()->Initialize();
639 return result_code_;
642 void BrowserMainLoop::CreateStartupTasks() {
643 TRACE_EVENT0("startup", "BrowserMainLoop::CreateStartupTasks");
645 // First time through, we really want to create all the tasks
646 if (!startup_task_runner_.get()) {
647 #if defined(OS_ANDROID)
648 startup_task_runner_ = make_scoped_ptr(new StartupTaskRunner(
649 base::Bind(&BrowserStartupComplete),
650 base::MessageLoop::current()->message_loop_proxy()));
651 #else
652 startup_task_runner_ = make_scoped_ptr(new StartupTaskRunner(
653 base::Callback<void(int)>(),
654 base::MessageLoop::current()->message_loop_proxy()));
655 #endif
656 StartupTask pre_create_threads =
657 base::Bind(&BrowserMainLoop::PreCreateThreads, base::Unretained(this));
658 startup_task_runner_->AddTask(pre_create_threads);
660 StartupTask create_threads =
661 base::Bind(&BrowserMainLoop::CreateThreads, base::Unretained(this));
662 startup_task_runner_->AddTask(create_threads);
664 StartupTask browser_thread_started = base::Bind(
665 &BrowserMainLoop::BrowserThreadsStarted, base::Unretained(this));
666 startup_task_runner_->AddTask(browser_thread_started);
668 StartupTask pre_main_message_loop_run = base::Bind(
669 &BrowserMainLoop::PreMainMessageLoopRun, base::Unretained(this));
670 startup_task_runner_->AddTask(pre_main_message_loop_run);
672 #if defined(OS_ANDROID)
673 if (BrowserMayStartAsynchronously()) {
674 startup_task_runner_->StartRunningTasksAsync();
676 #endif
678 #if defined(OS_ANDROID)
679 if (!BrowserMayStartAsynchronously()) {
680 // A second request for asynchronous startup can be ignored, so
681 // StartupRunningTasksAsync is only called first time through. If, however,
682 // this is a request for synchronous startup then it must override any
683 // previous call for async startup, so we call RunAllTasksNow()
684 // unconditionally.
685 startup_task_runner_->RunAllTasksNow();
687 #else
688 startup_task_runner_->RunAllTasksNow();
689 #endif
692 int BrowserMainLoop::CreateThreads() {
693 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads");
695 base::Thread::Options io_message_loop_options;
696 io_message_loop_options.message_loop_type = base::MessageLoop::TYPE_IO;
697 base::Thread::Options ui_message_loop_options;
698 ui_message_loop_options.message_loop_type = base::MessageLoop::TYPE_UI;
700 // Start threads in the order they occur in the BrowserThread::ID
701 // enumeration, except for BrowserThread::UI which is the main
702 // thread.
704 // Must be size_t so we can increment it.
705 for (size_t thread_id = BrowserThread::UI + 1;
706 thread_id < BrowserThread::ID_COUNT;
707 ++thread_id) {
708 scoped_ptr<BrowserProcessSubThread>* thread_to_start = NULL;
709 base::Thread::Options options;
711 switch (thread_id) {
712 case BrowserThread::DB:
713 TRACE_EVENT_BEGIN1("startup",
714 "BrowserMainLoop::CreateThreads:start",
715 "Thread", "BrowserThread::DB");
716 thread_to_start = &db_thread_;
717 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
718 break;
719 case BrowserThread::FILE_USER_BLOCKING:
720 TRACE_EVENT_BEGIN1("startup",
721 "BrowserMainLoop::CreateThreads:start",
722 "Thread", "BrowserThread::FILE_USER_BLOCKING");
723 thread_to_start = &file_user_blocking_thread_;
724 break;
725 case BrowserThread::FILE:
726 TRACE_EVENT_BEGIN1("startup",
727 "BrowserMainLoop::CreateThreads:start",
728 "Thread", "BrowserThread::FILE");
729 thread_to_start = &file_thread_;
730 #if defined(OS_WIN)
731 // On Windows, the FILE thread needs to be have a UI message loop
732 // which pumps messages in such a way that Google Update can
733 // communicate back to us.
734 options = ui_message_loop_options;
735 #else
736 options = io_message_loop_options;
737 #endif
738 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
739 break;
740 case BrowserThread::PROCESS_LAUNCHER:
741 TRACE_EVENT_BEGIN1("startup",
742 "BrowserMainLoop::CreateThreads:start",
743 "Thread", "BrowserThread::PROCESS_LAUNCHER");
744 thread_to_start = &process_launcher_thread_;
745 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
746 break;
747 case BrowserThread::CACHE:
748 TRACE_EVENT_BEGIN1("startup",
749 "BrowserMainLoop::CreateThreads:start",
750 "Thread", "BrowserThread::CACHE");
751 thread_to_start = &cache_thread_;
752 options = io_message_loop_options;
753 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
754 break;
755 case BrowserThread::IO:
756 TRACE_EVENT_BEGIN1("startup",
757 "BrowserMainLoop::CreateThreads:start",
758 "Thread", "BrowserThread::IO");
759 thread_to_start = &io_thread_;
760 options = io_message_loop_options;
761 break;
762 case BrowserThread::UI:
763 case BrowserThread::ID_COUNT:
764 default:
765 NOTREACHED();
766 break;
769 BrowserThread::ID id = static_cast<BrowserThread::ID>(thread_id);
771 if (thread_to_start) {
772 (*thread_to_start).reset(new BrowserProcessSubThread(id));
773 if (!(*thread_to_start)->StartWithOptions(options)) {
774 LOG(FATAL) << "Failed to start the browser thread: id == " << id;
776 } else {
777 NOTREACHED();
780 TRACE_EVENT_END0("startup", "BrowserMainLoop::CreateThreads:start");
782 created_threads_ = true;
783 return result_code_;
786 int BrowserMainLoop::PreMainMessageLoopRun() {
787 if (parts_) {
788 TRACE_EVENT0("startup",
789 "BrowserMainLoop::CreateThreads:PreMainMessageLoopRun");
790 parts_->PreMainMessageLoopRun();
793 // If the UI thread blocks, the whole UI is unresponsive.
794 // Do not allow disk IO from the UI thread.
795 base::ThreadRestrictions::SetIOAllowed(false);
796 base::ThreadRestrictions::DisallowWaiting();
797 return result_code_;
800 void BrowserMainLoop::RunMainMessageLoopParts() {
801 TRACE_EVENT_BEGIN_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
803 bool ran_main_loop = false;
804 if (parts_)
805 ran_main_loop = parts_->MainMessageLoopRun(&result_code_);
807 if (!ran_main_loop)
808 MainMessageLoopRun();
810 TRACE_EVENT_END_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
813 void BrowserMainLoop::ShutdownThreadsAndCleanUp() {
814 if (!created_threads_) {
815 // Called early, nothing to do
816 return;
818 TRACE_EVENT0("shutdown", "BrowserMainLoop::ShutdownThreadsAndCleanUp");
820 // Teardown may start in PostMainMessageLoopRun, and during teardown we
821 // need to be able to perform IO.
822 base::ThreadRestrictions::SetIOAllowed(true);
823 BrowserThread::PostTask(
824 BrowserThread::IO, FROM_HERE,
825 base::Bind(base::IgnoreResult(&base::ThreadRestrictions::SetIOAllowed),
826 true));
828 #if !defined(OS_IOS)
829 if (RenderProcessHost::run_renderer_in_process())
830 RenderProcessHostImpl::ShutDownInProcessRenderer();
831 #endif
833 if (parts_) {
834 TRACE_EVENT0("shutdown",
835 "BrowserMainLoop::Subsystem:PostMainMessageLoopRun");
836 parts_->PostMainMessageLoopRun();
839 trace_memory_controller_.reset();
840 system_stats_monitor_.reset();
842 #if !defined(OS_IOS)
843 // Destroying the GpuProcessHostUIShims on the UI thread posts a task to
844 // delete related objects on the GPU thread. This must be done before
845 // stopping the GPU thread. The GPU thread will close IPC channels to renderer
846 // processes so this has to happen before stopping the IO thread.
848 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUProcessHostShim");
849 GpuProcessHostUIShim::DestroyAll();
851 // Cancel pending requests and prevent new requests.
852 if (resource_dispatcher_host_) {
853 TRACE_EVENT0("shutdown",
854 "BrowserMainLoop::Subsystem:ResourceDispatcherHost");
855 resource_dispatcher_host_.get()->Shutdown();
858 #if defined(OS_CHROMEOS)
859 memory_pressure_observer_.reset();
860 #endif
862 #if defined(OS_MACOSX)
863 BrowserCompositorMac::DisableRecyclingForShutdown();
864 #endif
866 #if defined(USE_AURA) || defined(OS_MACOSX)
868 TRACE_EVENT0("shutdown",
869 "BrowserMainLoop::Subsystem:ImageTransportFactory");
870 ImageTransportFactory::Terminate();
872 #endif
874 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
875 ZygoteHostImpl::GetInstance()->TearDownAfterLastChild();
876 #endif // defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
878 // The device monitors are using |system_monitor_| as dependency, so delete
879 // them before |system_monitor_| goes away.
880 // On Mac and windows, the monitor needs to be destroyed on the same thread
881 // as they were created. On Linux, the monitor will be deleted when IO thread
882 // goes away.
883 #if defined(OS_WIN)
884 system_message_window_.reset();
885 #elif defined(OS_MACOSX)
886 device_monitor_mac_.reset();
887 #endif
888 #endif // !defined(OS_IOS)
890 // Must be size_t so we can subtract from it.
891 for (size_t thread_id = BrowserThread::ID_COUNT - 1;
892 thread_id >= (BrowserThread::UI + 1);
893 --thread_id) {
894 // Find the thread object we want to stop. Looping over all valid
895 // BrowserThread IDs and DCHECKing on a missing case in the switch
896 // statement helps avoid a mismatch between this code and the
897 // BrowserThread::ID enumeration.
899 // The destruction order is the reverse order of occurrence in the
900 // BrowserThread::ID list. The rationale for the order is as
901 // follows (need to be filled in a bit):
904 // - The IO thread is the only user of the CACHE thread.
906 // - The PROCESS_LAUNCHER thread must be stopped after IO in case
907 // the IO thread posted a task to terminate a process on the
908 // process launcher thread.
910 // - (Not sure why DB stops last.)
911 switch (thread_id) {
912 case BrowserThread::DB: {
913 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DBThread");
914 ResetThread_DB(db_thread_.Pass());
915 break;
917 case BrowserThread::FILE: {
918 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:FileThread");
919 #if !defined(OS_IOS)
920 // Clean up state that lives on or uses the file_thread_ before
921 // it goes away.
922 if (resource_dispatcher_host_)
923 resource_dispatcher_host_.get()->save_file_manager()->Shutdown();
924 #endif // !defined(OS_IOS)
925 ResetThread_FILE(file_thread_.Pass());
926 break;
928 case BrowserThread::FILE_USER_BLOCKING: {
929 TRACE_EVENT0("shutdown",
930 "BrowserMainLoop::Subsystem:FileUserBlockingThread");
931 ResetThread_FILE_USER_BLOCKING(file_user_blocking_thread_.Pass());
932 break;
934 case BrowserThread::PROCESS_LAUNCHER: {
935 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:LauncherThread");
936 ResetThread_PROCESS_LAUNCHER(process_launcher_thread_.Pass());
937 break;
939 case BrowserThread::CACHE: {
940 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:CacheThread");
941 ResetThread_CACHE(cache_thread_.Pass());
942 break;
944 case BrowserThread::IO: {
945 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IOThread");
946 ResetThread_IO(io_thread_.Pass());
947 break;
949 case BrowserThread::UI:
950 case BrowserThread::ID_COUNT:
951 default:
952 NOTREACHED();
953 break;
957 #if !defined(OS_IOS)
959 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IndexedDBThread");
960 ResetThread_IndexedDb(indexed_db_thread_.Pass());
962 #endif
964 // Close the blocking I/O pool after the other threads. Other threads such
965 // as the I/O thread may need to schedule work like closing files or flushing
966 // data during shutdown, so the blocking pool needs to be available. There
967 // may also be slow operations pending that will blcok shutdown, so closing
968 // it here (which will block until required operations are complete) gives
969 // more head start for those operations to finish.
971 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:ThreadPool");
972 BrowserThreadImpl::ShutdownThreadPool();
975 #if !defined(OS_IOS)
976 // Must happen after the IO thread is shutdown since this may be accessed from
977 // it.
979 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUChannelFactory");
980 if (BrowserGpuChannelHostFactory::instance())
981 BrowserGpuChannelHostFactory::Terminate();
984 // Must happen after the I/O thread is shutdown since this class lives on the
985 // I/O thread and isn't threadsafe.
987 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GamepadService");
988 GamepadService::GetInstance()->Terminate();
991 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:SensorService");
992 DeviceInertialSensorService::GetInstance()->Shutdown();
995 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:BatteryStatusService");
996 device::BatteryStatusService::GetInstance()->Shutdown();
999 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DeleteDataSources");
1000 URLDataManager::DeleteDataSources();
1002 #endif // !defined(OS_IOS)
1004 if (parts_) {
1005 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:PostDestroyThreads");
1006 parts_->PostDestroyThreads();
1010 void BrowserMainLoop::StopStartupTracingTimer() {
1011 startup_trace_timer_.Stop();
1014 void BrowserMainLoop::InitializeMainThread() {
1015 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeMainThread");
1016 const char* kThreadName = "CrBrowserMain";
1017 base::PlatformThread::SetName(kThreadName);
1018 if (main_message_loop_)
1019 main_message_loop_->set_thread_name(kThreadName);
1021 // Register the main thread by instantiating it, but don't call any methods.
1022 main_thread_.reset(
1023 new BrowserThreadImpl(BrowserThread::UI, base::MessageLoop::current()));
1026 int BrowserMainLoop::BrowserThreadsStarted() {
1027 TRACE_EVENT0("startup", "BrowserMainLoop::BrowserThreadsStarted");
1029 #if !defined(OS_IOS)
1030 indexed_db_thread_.reset(new base::Thread("IndexedDB"));
1031 indexed_db_thread_->Start();
1032 #endif
1034 #if !defined(OS_IOS)
1035 HistogramSynchronizer::GetInstance();
1038 // GpuDataManager for in-process initialized in PreCreateThreads.
1039 bool initialize_gpu_data_manager = !UsingInProcessGpu();
1040 #if defined(OS_ANDROID)
1041 // Up the priority of anything that touches with display tasks
1042 // (this thread is UI thread, and io_thread_ is for IPCs).
1043 io_thread_->SetPriority(base::kThreadPriority_Display);
1044 base::PlatformThread::SetThreadPriority(
1045 base::PlatformThread::CurrentHandle(),
1046 base::kThreadPriority_Display);
1048 // On Android, GLSurface::InitializeOneOff() must be called before
1049 // initalizing the GpuDataManagerImpl as it uses the GL bindings.
1050 // TODO(sievers): Shouldn't need to init full bindings to determine GL
1051 // version/vendor strings. crbug.com/326295
1052 if (initialize_gpu_data_manager) {
1053 // Note InitializeOneOff is not safe either for in-process gpu after
1054 // creating threads, since it may race with the gpu thread.
1055 if (!gfx::GLSurface::InitializeOneOff()) {
1056 LOG(FATAL) << "GLSurface::InitializeOneOff failed";
1059 #endif
1061 if (initialize_gpu_data_manager)
1062 GpuDataManagerImpl::GetInstance()->Initialize();
1064 bool always_uses_gpu = true;
1065 bool established_gpu_channel = false;
1066 #if defined(USE_AURA) || defined(OS_MACOSX)
1067 established_gpu_channel = true;
1068 if (!GpuDataManagerImpl::GetInstance()->CanUseGpuBrowserCompositor()) {
1069 established_gpu_channel = always_uses_gpu = false;
1071 BrowserGpuChannelHostFactory::Initialize(established_gpu_channel);
1072 ImageTransportFactory::Initialize();
1073 #if defined(USE_AURA)
1074 if (aura::Env::GetInstance()) {
1075 aura::Env::GetInstance()->set_context_factory(GetContextFactory());
1077 #endif
1078 #elif defined(OS_ANDROID)
1079 // TODO(crbug.com/439322): This should be set to |true|.
1080 established_gpu_channel = false;
1081 BrowserGpuChannelHostFactory::Initialize(established_gpu_channel);
1082 #endif
1084 #if defined(OS_LINUX) && defined(USE_UDEV)
1085 device_monitor_linux_.reset(new DeviceMonitorLinux());
1086 #elif defined(OS_MACOSX)
1087 device_monitor_mac_.reset(new DeviceMonitorMac());
1088 #endif
1090 #if defined(OS_WIN)
1091 UMA_HISTOGRAM_BOOLEAN("Windows.Win32kRendererLockdown",
1092 IsWin32kRendererLockdownEnabled());
1093 #endif
1094 // RDH needs the IO thread to be created
1096 TRACE_EVENT0("startup",
1097 "BrowserMainLoop::BrowserThreadsStarted:InitResourceDispatcherHost");
1098 resource_dispatcher_host_.reset(new ResourceDispatcherHostImpl());
1101 // MediaStreamManager needs the IO thread to be created.
1103 TRACE_EVENT0("startup",
1104 "BrowserMainLoop::BrowserThreadsStarted:InitMediaStreamManager");
1105 media_stream_manager_.reset(new MediaStreamManager(audio_manager_.get()));
1109 TRACE_EVENT0("startup",
1110 "BrowserMainLoop::BrowserThreadsStarted:InitSpeechRecognition");
1111 speech_recognition_manager_.reset(new SpeechRecognitionManagerImpl(
1112 audio_manager_.get(), media_stream_manager_.get()));
1116 TRACE_EVENT0(
1117 "startup",
1118 "BrowserMainLoop::BrowserThreadsStarted::InitUserInputMonitor");
1119 user_input_monitor_ = media::UserInputMonitor::Create(
1120 io_thread_->message_loop_proxy(), main_thread_->message_loop_proxy());
1124 TRACE_EVENT0("startup",
1125 "BrowserMainLoop::BrowserThreadsStarted::TimeZoneMonitor");
1126 time_zone_monitor_ = TimeZoneMonitor::Create();
1129 // Alert the clipboard class to which threads are allowed to access the
1130 // clipboard:
1131 std::vector<base::PlatformThreadId> allowed_clipboard_threads;
1132 // The current thread is the UI thread.
1133 allowed_clipboard_threads.push_back(base::PlatformThread::CurrentId());
1134 #if defined(OS_WIN)
1135 // On Windows, clipboards are also used on the File or IO threads.
1136 allowed_clipboard_threads.push_back(file_thread_->thread_id());
1137 allowed_clipboard_threads.push_back(io_thread_->thread_id());
1138 #endif
1139 ui::Clipboard::SetAllowedThreads(allowed_clipboard_threads);
1141 // When running the GPU thread in-process, avoid optimistically starting it
1142 // since creating the GPU thread races against creation of the one-and-only
1143 // ChildProcess instance which is created by the renderer thread.
1144 if (GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL) &&
1145 !established_gpu_channel &&
1146 always_uses_gpu &&
1147 !UsingInProcessGpu()) {
1148 TRACE_EVENT_INSTANT0("gpu", "Post task to launch GPU process",
1149 TRACE_EVENT_SCOPE_THREAD);
1150 BrowserThread::PostTask(
1151 BrowserThread::IO, FROM_HERE, base::Bind(
1152 base::IgnoreResult(&GpuProcessHost::Get),
1153 GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED,
1154 CAUSE_FOR_GPU_LAUNCH_BROWSER_STARTUP));
1157 #if defined(OS_MACOSX)
1158 ThemeHelperMac::GetInstance();
1159 SystemHotkeyHelperMac::GetInstance()->DeferredLoadSystemHotkeys();
1160 if (ShouldEnableBootstrapSandbox()) {
1161 TRACE_EVENT0("startup",
1162 "BrowserMainLoop::BrowserThreadsStarted:BootstrapSandbox");
1163 CHECK(GetBootstrapSandbox());
1165 #endif // defined(OS_MACOSX)
1167 #endif // !defined(OS_IOS)
1169 return result_code_;
1172 bool BrowserMainLoop::UsingInProcessGpu() const {
1173 return parsed_command_line_.HasSwitch(switches::kSingleProcess) ||
1174 parsed_command_line_.HasSwitch(switches::kInProcessGPU);
1177 bool BrowserMainLoop::InitializeToolkit() {
1178 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeToolkit");
1179 // TODO(evan): this function is rather subtle, due to the variety
1180 // of intersecting ifdefs we have. To keep it easy to follow, there
1181 // are no #else branches on any #ifs.
1182 // TODO(stevenjb): Move platform specific code into platform specific Parts
1183 // (Need to add InitializeToolkit stage to BrowserParts).
1184 // See also GTK setup in EarlyInitialization, above, and associated comments.
1186 #if defined(OS_WIN)
1187 // Init common control sex.
1188 INITCOMMONCONTROLSEX config;
1189 config.dwSize = sizeof(config);
1190 config.dwICC = ICC_WIN95_CLASSES;
1191 if (!InitCommonControlsEx(&config))
1192 PLOG(FATAL);
1193 #endif
1195 #if defined(USE_AURA)
1197 #if defined(USE_X11)
1198 if (!gfx::GetXDisplay())
1199 return false;
1200 #endif
1202 // Env creates the compositor. Aura widgets need the compositor to be created
1203 // before they can be initialized by the browser.
1204 aura::Env::CreateInstance(true);
1205 #endif // defined(USE_AURA)
1207 if (parts_)
1208 parts_->ToolkitInitialized();
1210 return true;
1213 void BrowserMainLoop::MainMessageLoopRun() {
1214 #if defined(OS_ANDROID)
1215 // Android's main message loop is the Java message loop.
1216 NOTREACHED();
1217 #else
1218 DCHECK(base::MessageLoopForUI::IsCurrent());
1219 if (parameters_.ui_task)
1220 base::MessageLoopForUI::current()->PostTask(FROM_HERE,
1221 *parameters_.ui_task);
1223 base::RunLoop run_loop;
1224 run_loop.Run();
1225 #endif
1228 base::FilePath BrowserMainLoop::GetStartupTraceFileName(
1229 const base::CommandLine& command_line) const {
1230 base::FilePath trace_file = command_line.GetSwitchValuePath(
1231 switches::kTraceStartupFile);
1232 // trace_file = "none" means that startup events will show up for the next
1233 // begin/end tracing (via about:tracing or AutomationProxy::BeginTracing/
1234 // EndTracing, for example).
1235 if (trace_file == base::FilePath().AppendASCII("none"))
1236 return trace_file;
1238 if (trace_file.empty()) {
1239 #if defined(OS_ANDROID)
1240 TracingControllerAndroid::GenerateTracingFilePath(&trace_file);
1241 #else
1242 // Default to saving the startup trace into the current dir.
1243 trace_file = base::FilePath().AppendASCII("chrometrace.log");
1244 #endif
1247 return trace_file;
1250 void BrowserMainLoop::InitStartupTracing(
1251 const base::CommandLine& command_line) {
1252 DCHECK(is_tracing_startup_);
1254 startup_trace_file_ = GetStartupTraceFileName(parsed_command_line_);
1256 std::string delay_str = command_line.GetSwitchValueASCII(
1257 switches::kTraceStartupDuration);
1258 int delay_secs = 5;
1259 if (!delay_str.empty() && !base::StringToInt(delay_str, &delay_secs)) {
1260 DLOG(WARNING) << "Could not parse --" << switches::kTraceStartupDuration
1261 << "=" << delay_str << " defaulting to 5 (secs)";
1262 delay_secs = 5;
1265 startup_trace_timer_.Start(FROM_HERE,
1266 base::TimeDelta::FromSeconds(delay_secs),
1267 this,
1268 &BrowserMainLoop::EndStartupTracing);
1271 void BrowserMainLoop::EndStartupTracing() {
1272 is_tracing_startup_ = false;
1273 TracingController::GetInstance()->DisableRecording(
1274 TracingController::CreateFileSink(
1275 startup_trace_file_,
1276 base::Bind(OnStoppedStartupTracing, startup_trace_file_)));
1279 } // namespace content