CacheStorage: Remove unused interfaces from CacheStorageListener
[chromium-blink-merge.git] / content / browser / browser_main_loop.cc
blobf5b0f188e13e5a8b4964e96f7e5e2632aa25c3d0
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/system_monitor/system_monitor.h"
21 #include "base/thread_task_runner_handle.h"
22 #include "base/threading/thread_restrictions.h"
23 #include "base/timer/hi_res_timer_manager.h"
24 #include "base/trace_event/memory_dump_manager.h"
25 #include "base/trace_event/trace_event.h"
26 #include "content/browser/browser_thread_impl.h"
27 #include "content/browser/device_sensors/device_inertial_sensor_service.h"
28 #include "content/browser/download/save_file_manager.h"
29 #include "content/browser/gamepad/gamepad_service.h"
30 #include "content/browser/gpu/browser_gpu_channel_host_factory.h"
31 #include "content/browser/gpu/compositor_util.h"
32 #include "content/browser/gpu/gpu_data_manager_impl.h"
33 #include "content/browser/gpu/gpu_process_host.h"
34 #include "content/browser/gpu/gpu_process_host_ui_shim.h"
35 #include "content/browser/histogram_synchronizer.h"
36 #include "content/browser/loader/resource_dispatcher_host_impl.h"
37 #include "content/browser/media/media_internals.h"
38 #include "content/browser/net/browser_online_state_observer.h"
39 #include "content/browser/renderer_host/media/media_stream_manager.h"
40 #include "content/browser/speech/speech_recognition_manager_impl.h"
41 #include "content/browser/startup_task_runner.h"
42 #include "content/browser/time_zone_monitor.h"
43 #include "content/browser/webui/content_web_ui_controller_factory.h"
44 #include "content/browser/webui/url_data_manager.h"
45 #include "content/common/content_switches_internal.h"
46 #include "content/common/host_discardable_shared_memory_manager.h"
47 #include "content/public/browser/browser_main_parts.h"
48 #include "content/public/browser/browser_shutdown.h"
49 #include "content/public/browser/content_browser_client.h"
50 #include "content/public/browser/render_process_host.h"
51 #include "content/public/browser/tracing_controller.h"
52 #include "content/public/common/content_switches.h"
53 #include "content/public/common/main_function_params.h"
54 #include "content/public/common/result_codes.h"
55 #include "crypto/nss_util.h"
56 #include "device/battery/battery_status_service.h"
57 #include "media/audio/audio_manager.h"
58 #include "media/base/media.h"
59 #include "media/base/user_input_monitor.h"
60 #include "media/midi/midi_manager.h"
61 #include "net/base/network_change_notifier.h"
62 #include "net/socket/client_socket_factory.h"
63 #include "net/ssl/ssl_config_service.h"
64 #include "ui/base/clipboard/clipboard.h"
66 #if defined(USE_AURA) || (defined(OS_MACOSX) && !defined(OS_IOS))
67 #include "content/browser/compositor/image_transport_factory.h"
68 #endif
70 #if defined(USE_AURA)
71 #include "content/public/browser/context_factory.h"
72 #include "ui/aura/env.h"
73 #endif
75 #if !defined(OS_IOS)
76 #include "content/browser/renderer_host/render_process_host_impl.h"
77 #endif
79 #if defined(OS_ANDROID)
80 #include "base/android/jni_android.h"
81 #include "content/browser/android/browser_startup_controller.h"
82 #include "content/browser/android/browser_surface_texture_manager.h"
83 #include "content/browser/android/tracing_controller_android.h"
84 #include "content/browser/screen_orientation/screen_orientation_delegate_android.h"
85 #include "content/public/browser/screen_orientation_provider.h"
86 #include "ui/gl/gl_surface.h"
87 #endif
89 #if defined(OS_MACOSX) && !defined(OS_IOS)
90 #include "content/browser/bootstrap_sandbox_mac.h"
91 #include "content/browser/cocoa/system_hotkey_helper_mac.h"
92 #include "content/browser/compositor/browser_compositor_view_mac.h"
93 #include "content/browser/theme_helper_mac.h"
94 #endif
96 #if defined(OS_WIN)
97 #include <windows.h>
98 #include <commctrl.h>
99 #include <shellapi.h>
101 #include "content/browser/system_message_window_win.h"
102 #include "content/common/sandbox_win.h"
103 #include "net/base/winsock_init.h"
104 #include "ui/base/l10n/l10n_util_win.h"
105 #endif
107 #if defined(OS_CHROMEOS)
108 #include "base/chromeos/memory_pressure_monitor_chromeos.h"
109 #include "chromeos/chromeos_switches.h"
110 #endif
112 #if defined(USE_GLIB)
113 #include <glib-object.h>
114 #endif
116 #if defined(OS_LINUX) && defined(USE_UDEV)
117 #include "content/browser/device_monitor_udev.h"
118 #elif defined(OS_MACOSX) && !defined(OS_IOS)
119 #include "content/browser/device_monitor_mac.h"
120 #endif
122 #if defined(OS_POSIX) && !defined(OS_MACOSX)
123 #include "content/browser/renderer_host/render_sandbox_host_linux.h"
124 #include "content/browser/zygote_host/zygote_host_impl_linux.h"
125 #include "sandbox/linux/suid/client/setuid_sandbox_host.h"
126 #endif
128 #if defined(ENABLE_PLUGINS)
129 #include "content/browser/plugin_service_impl.h"
130 #endif
132 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
133 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
134 #endif
136 #if defined(USE_X11)
137 #include "ui/gfx/x/x11_connection.h"
138 #include "ui/gfx/x/x11_types.h"
139 #endif
141 // One of the linux specific headers defines this as a macro.
142 #ifdef DestroyAll
143 #undef DestroyAll
144 #endif
146 namespace content {
147 namespace {
149 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
150 void SetupSandbox(const base::CommandLine& parsed_command_line) {
151 TRACE_EVENT0("startup", "SetupSandbox");
152 base::FilePath sandbox_binary;
154 scoped_ptr<sandbox::SetuidSandboxHost> setuid_sandbox_host(
155 sandbox::SetuidSandboxHost::Create());
157 const bool want_setuid_sandbox =
158 !parsed_command_line.HasSwitch(switches::kNoSandbox) &&
159 !parsed_command_line.HasSwitch(switches::kDisableSetuidSandbox) &&
160 !setuid_sandbox_host->IsDisabledViaEnvironment();
162 static const char no_suid_error[] =
163 "Running without the SUID sandbox! See "
164 "https://code.google.com/p/chromium/wiki/LinuxSUIDSandboxDevelopment "
165 "for more information on developing with the sandbox on.";
166 if (want_setuid_sandbox) {
167 sandbox_binary = setuid_sandbox_host->GetSandboxBinaryPath();
168 if (sandbox_binary.empty()) {
169 // This needs to be fatal. Talk to security@chromium.org if you feel
170 // otherwise.
171 LOG(FATAL) << no_suid_error;
173 } else {
174 LOG(ERROR) << no_suid_error;
177 // Tickle the sandbox host and zygote host so they fork now.
178 RenderSandboxHostLinux::GetInstance()->Init();
179 ZygoteHostImpl::GetInstance()->Init(sandbox_binary.value());
181 #endif
183 #if defined(USE_GLIB)
184 static void GLibLogHandler(const gchar* log_domain,
185 GLogLevelFlags log_level,
186 const gchar* message,
187 gpointer userdata) {
188 if (!log_domain)
189 log_domain = "<unknown>";
190 if (!message)
191 message = "<no message>";
193 if (strstr(message, "Unable to retrieve the file info for")) {
194 LOG(ERROR) << "GTK File code error: " << message;
195 } else if (strstr(message, "Could not find the icon") &&
196 strstr(log_domain, "Gtk")) {
197 LOG(ERROR) << "GTK icon error: " << message;
198 } else if (strstr(message, "Theme file for default has no") ||
199 strstr(message, "Theme directory") ||
200 strstr(message, "theme pixmap") ||
201 strstr(message, "locate theme engine")) {
202 LOG(ERROR) << "GTK theme error: " << message;
203 } else if (strstr(message, "Unable to create Ubuntu Menu Proxy") &&
204 strstr(log_domain, "<unknown>")) {
205 LOG(ERROR) << "GTK menu proxy create failed";
206 } else if (strstr(message, "Out of memory") &&
207 strstr(log_domain, "<unknown>")) {
208 LOG(ERROR) << "DBus call timeout or out of memory: "
209 << "http://crosbug.com/15496";
210 } else if (strstr(message, "Could not connect: Connection refused") &&
211 strstr(log_domain, "<unknown>")) {
212 LOG(ERROR) << "DConf settings backend could not connect to session bus: "
213 << "http://crbug.com/179797";
214 } else if (strstr(message, "Attempting to store changes into") ||
215 strstr(message, "Attempting to set the permissions of")) {
216 LOG(ERROR) << message << " (http://bugs.chromium.org/161366)";
217 } else if (strstr(message, "drawable is not a native X11 window")) {
218 LOG(ERROR) << message << " (http://bugs.chromium.org/329991)";
219 } else {
220 LOG(DFATAL) << log_domain << ": " << message;
224 static void SetUpGLibLogHandler() {
225 // Register GLib-handled assertions to go through our logging system.
226 const char* kLogDomains[] = { NULL, "Gtk", "Gdk", "GLib", "GLib-GObject" };
227 for (size_t i = 0; i < arraysize(kLogDomains); i++) {
228 g_log_set_handler(kLogDomains[i],
229 static_cast<GLogLevelFlags>(G_LOG_FLAG_RECURSION |
230 G_LOG_FLAG_FATAL |
231 G_LOG_LEVEL_ERROR |
232 G_LOG_LEVEL_CRITICAL |
233 G_LOG_LEVEL_WARNING),
234 GLibLogHandler,
235 NULL);
238 #endif
240 void OnStoppedStartupTracing(const base::FilePath& trace_file) {
241 VLOG(0) << "Completed startup tracing to " << trace_file.value();
244 // Disable optimizations for this block of functions so the compiler doesn't
245 // merge them all together. This makes it possible to tell what thread was
246 // unresponsive by inspecting the callstack.
247 MSVC_DISABLE_OPTIMIZE()
248 MSVC_PUSH_DISABLE_WARNING(4748)
250 NOINLINE void ResetThread_DB(scoped_ptr<BrowserProcessSubThread> thread) {
251 volatile int inhibit_comdat = __LINE__;
252 ALLOW_UNUSED_LOCAL(inhibit_comdat);
253 thread.reset();
256 NOINLINE void ResetThread_FILE(scoped_ptr<BrowserProcessSubThread> thread) {
257 volatile int inhibit_comdat = __LINE__;
258 ALLOW_UNUSED_LOCAL(inhibit_comdat);
259 thread.reset();
262 NOINLINE void ResetThread_FILE_USER_BLOCKING(
263 scoped_ptr<BrowserProcessSubThread> thread) {
264 volatile int inhibit_comdat = __LINE__;
265 ALLOW_UNUSED_LOCAL(inhibit_comdat);
266 thread.reset();
269 NOINLINE void ResetThread_PROCESS_LAUNCHER(
270 scoped_ptr<BrowserProcessSubThread> thread) {
271 volatile int inhibit_comdat = __LINE__;
272 ALLOW_UNUSED_LOCAL(inhibit_comdat);
273 thread.reset();
276 NOINLINE void ResetThread_CACHE(scoped_ptr<BrowserProcessSubThread> thread) {
277 volatile int inhibit_comdat = __LINE__;
278 ALLOW_UNUSED_LOCAL(inhibit_comdat);
279 thread.reset();
282 NOINLINE void ResetThread_IO(scoped_ptr<BrowserProcessSubThread> thread) {
283 volatile int inhibit_comdat = __LINE__;
284 ALLOW_UNUSED_LOCAL(inhibit_comdat);
285 thread.reset();
288 #if !defined(OS_IOS)
289 NOINLINE void ResetThread_IndexedDb(scoped_ptr<base::Thread> thread) {
290 volatile int inhibit_comdat = __LINE__;
291 ALLOW_UNUSED_LOCAL(inhibit_comdat);
292 thread.reset();
294 #endif
296 MSVC_POP_WARNING()
297 MSVC_ENABLE_OPTIMIZE();
299 } // namespace
301 // The currently-running BrowserMainLoop. There can be one or zero.
302 BrowserMainLoop* g_current_browser_main_loop = NULL;
304 // This is just to be able to keep ShutdownThreadsAndCleanUp out of
305 // the public interface of BrowserMainLoop.
306 class BrowserShutdownImpl {
307 public:
308 static void ImmediateShutdownAndExitProcess() {
309 DCHECK(g_current_browser_main_loop);
310 g_current_browser_main_loop->ShutdownThreadsAndCleanUp();
312 #if defined(OS_WIN)
313 // At this point the message loop is still running yet we've shut everything
314 // down. If any messages are processed we'll likely crash. Exit now.
315 ExitProcess(RESULT_CODE_NORMAL_EXIT);
316 #elif defined(OS_POSIX) && !defined(OS_MACOSX)
317 _exit(RESULT_CODE_NORMAL_EXIT);
318 #else
319 NOTIMPLEMENTED();
320 #endif
324 void ImmediateShutdownAndExitProcess() {
325 BrowserShutdownImpl::ImmediateShutdownAndExitProcess();
328 // For measuring memory usage after each task. Behind a command line flag.
329 class BrowserMainLoop::MemoryObserver : public base::MessageLoop::TaskObserver {
330 public:
331 MemoryObserver() {}
332 ~MemoryObserver() override {}
334 void WillProcessTask(const base::PendingTask& pending_task) override {}
336 void DidProcessTask(const base::PendingTask& pending_task) override {
337 #if !defined(OS_IOS) // No ProcessMetrics on IOS.
338 scoped_ptr<base::ProcessMetrics> process_metrics(
339 base::ProcessMetrics::CreateProcessMetrics(
340 #if defined(OS_MACOSX)
341 base::GetCurrentProcessHandle(), NULL));
342 #else
343 base::GetCurrentProcessHandle()));
344 #endif
345 size_t private_bytes;
346 process_metrics->GetMemoryBytes(&private_bytes, NULL);
347 LOCAL_HISTOGRAM_MEMORY_KB("Memory.BrowserUsed", private_bytes >> 10);
348 #endif
350 private:
351 DISALLOW_COPY_AND_ASSIGN(MemoryObserver);
355 // BrowserMainLoop construction / destruction =============================
357 BrowserMainLoop* BrowserMainLoop::GetInstance() {
358 DCHECK_CURRENTLY_ON(BrowserThread::UI);
359 return g_current_browser_main_loop;
362 BrowserMainLoop::BrowserMainLoop(const MainFunctionParams& parameters)
363 : parameters_(parameters),
364 parsed_command_line_(parameters.command_line),
365 result_code_(RESULT_CODE_NORMAL_EXIT),
366 created_threads_(false),
367 // ContentMainRunner should have enabled tracing of the browser process
368 // when kTraceStartup is in the command line.
369 is_tracing_startup_(
370 parameters.command_line.HasSwitch(switches::kTraceStartup)) {
371 DCHECK(!g_current_browser_main_loop);
372 g_current_browser_main_loop = this;
375 BrowserMainLoop::~BrowserMainLoop() {
376 DCHECK_EQ(this, g_current_browser_main_loop);
377 #if !defined(OS_IOS)
378 ui::Clipboard::DestroyClipboardForCurrentThread();
379 #endif // !defined(OS_IOS)
380 g_current_browser_main_loop = NULL;
383 void BrowserMainLoop::Init() {
384 TRACE_EVENT0("startup", "BrowserMainLoop::Init");
385 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::Init");
387 parts_.reset(
388 GetContentClient()->browser()->CreateBrowserMainParts(parameters_));
391 // BrowserMainLoop stages ==================================================
393 void BrowserMainLoop::EarlyInitialization() {
394 TRACE_EVENT0("startup", "BrowserMainLoop::EarlyInitialization");
395 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::EarlyInitialization");
397 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
398 // No thread should be created before this call, as SetupSandbox()
399 // will end-up using fork().
400 SetupSandbox(parsed_command_line_);
401 #endif
403 #if defined(USE_X11)
404 if (UsingInProcessGpu()) {
405 if (!gfx::InitializeThreadedX11()) {
406 LOG(ERROR) << "Failed to put Xlib into threaded mode.";
409 #endif
411 // GLib's spawning of new processes is buggy, so it's important that at this
412 // point GLib does not need to start DBUS. Chrome should always start with
413 // DBUS_SESSION_BUS_ADDRESS properly set. See crbug.com/309093.
414 #if defined(USE_GLIB)
415 // g_type_init will be deprecated in 2.36. 2.35 is the development
416 // version for 2.36, hence do not call g_type_init starting 2.35.
417 // http://developer.gnome.org/gobject/unstable/gobject-Type-Information.html#g-type-init
418 #if !GLIB_CHECK_VERSION(2, 35, 0)
419 // GLib type system initialization. Needed at least for gconf,
420 // used in net/proxy/proxy_config_service_linux.cc. Most likely
421 // this is superfluous as gtk_init() ought to do this. It's
422 // definitely harmless, so retained as a reminder of this
423 // requirement for gconf.
424 g_type_init();
425 #endif
427 SetUpGLibLogHandler();
428 #endif
430 if (parts_)
431 parts_->PreEarlyInitialization();
433 #if defined(OS_MACOSX)
434 // We use quite a few file descriptors for our IPC, and the default limit on
435 // the Mac is low (256), so bump it up.
436 base::SetFdLimit(1024);
437 #endif
439 #if defined(OS_WIN)
440 net::EnsureWinsockInit();
441 #endif
443 #if !defined(USE_OPENSSL)
444 // We want to be sure to init NSPR on the main thread.
445 crypto::EnsureNSPRInit();
446 #endif // !defined(USE_OPENSSL)
448 #if !defined(OS_IOS)
449 if (parsed_command_line_.HasSwitch(switches::kRendererProcessLimit)) {
450 std::string limit_string = parsed_command_line_.GetSwitchValueASCII(
451 switches::kRendererProcessLimit);
452 size_t process_limit;
453 if (base::StringToSizeT(limit_string, &process_limit)) {
454 RenderProcessHost::SetMaxRendererProcessCount(process_limit);
457 #endif // !defined(OS_IOS)
459 if (parsed_command_line_.HasSwitch(switches::kEnableNativeGpuMemoryBuffers)) {
460 BrowserGpuChannelHostFactory::EnableGpuMemoryBufferFactoryUsage(
461 gfx::GpuMemoryBuffer::MAP);
464 #if defined(USE_OZONE)
465 BrowserGpuChannelHostFactory::EnableGpuMemoryBufferFactoryUsage(
466 gfx::GpuMemoryBuffer::SCANOUT);
467 #endif
469 base::DiscardableMemoryAllocator::SetInstance(
470 HostDiscardableSharedMemoryManager::current());
472 if (parts_)
473 parts_->PostEarlyInitialization();
476 void BrowserMainLoop::MainMessageLoopStart() {
477 TRACE_EVENT0("startup", "BrowserMainLoop::MainMessageLoopStart");
478 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::MainMessageLoopStart");
480 if (parts_) {
481 TRACE_EVENT0("startup",
482 "BrowserMainLoop::MainMessageLoopStart:PreMainMessageLoopStart");
483 parts_->PreMainMessageLoopStart();
486 #if defined(OS_WIN)
487 // If we're running tests (ui_task is non-null), then the ResourceBundle
488 // has already been initialized.
489 if (!parameters_.ui_task) {
490 // Override the configured locale with the user's preferred UI language.
491 l10n_util::OverrideLocaleWithUILanguageList();
493 #endif
495 // Create a MessageLoop if one does not already exist for the current thread.
496 if (!base::MessageLoop::current())
497 main_message_loop_.reset(new base::MessageLoopForUI);
499 InitializeMainThread();
502 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SystemMonitor");
503 system_monitor_.reset(new base::SystemMonitor);
506 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:PowerMonitor");
507 scoped_ptr<base::PowerMonitorSource> power_monitor_source(
508 new base::PowerMonitorDeviceSource());
509 power_monitor_.reset(new base::PowerMonitor(power_monitor_source.Pass()));
512 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:HighResTimerManager");
513 hi_res_timer_manager_.reset(new base::HighResolutionTimerManager);
516 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:NetworkChangeNotifier");
517 network_change_notifier_.reset(net::NetworkChangeNotifier::Create());
520 #if !defined(OS_IOS)
522 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MediaFeatures");
523 media::InitializeCPUSpecificMediaFeatures();
526 TRACE_EVENT0("startup",
527 "BrowserMainLoop::Subsystem:ContentWebUIController");
528 WebUIControllerFactory::RegisterFactory(
529 ContentWebUIControllerFactory::GetInstance());
533 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:OnlineStateObserver");
534 online_state_observer_.reset(new BrowserOnlineStateObserver);
538 system_stats_monitor_.reset(
539 new base::trace_event::TraceEventSystemStatsMonitor(
540 base::ThreadTaskRunnerHandle::Get()));
542 #endif // !defined(OS_IOS)
544 #if defined(OS_WIN)
545 system_message_window_.reset(new SystemMessageWindowWin);
546 #endif
548 if (parts_)
549 parts_->PostMainMessageLoopStart();
551 #if !defined(OS_IOS)
552 // Start tracing to a file if needed. Only do this after starting the main
553 // message loop to avoid calling MessagePumpForUI::ScheduleWork() before
554 // MessagePumpForUI::Start() as it will crash the browser.
555 if (is_tracing_startup_) {
556 TRACE_EVENT0("startup", "BrowserMainLoop::InitStartupTracing");
557 InitStartupTracing(parsed_command_line_);
559 #endif // !defined(OS_IOS)
561 #if defined(OS_ANDROID)
563 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SurfaceTextureManager");
564 SurfaceTextureManager::InitInstance(new BrowserSurfaceTextureManager);
567 if (!parsed_command_line_.HasSwitch(
568 switches::kDisableScreenOrientationLock)) {
569 TRACE_EVENT0("startup",
570 "BrowserMainLoop::Subsystem:ScreenOrientationProvider");
571 screen_orientation_delegate_.reset(
572 new ScreenOrientationDelegateAndroid());
573 ScreenOrientationProvider::SetDelegate(screen_orientation_delegate_.get());
575 #endif
577 if (parsed_command_line_.HasSwitch(switches::kMemoryMetrics)) {
578 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MemoryObserver");
579 memory_observer_.reset(new MemoryObserver());
580 base::MessageLoop::current()->AddTaskObserver(memory_observer_.get());
583 base::trace_event::MemoryDumpManager::GetInstance()->Initialize();
585 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
586 trace_memory_controller_.reset(new base::trace_event::TraceMemoryController(
587 base::MessageLoop::current()->message_loop_proxy(),
588 ::HeapProfilerWithPseudoStackStart, ::HeapProfilerStop,
589 ::GetHeapProfile));
590 #endif
593 int BrowserMainLoop::PreCreateThreads() {
594 if (parts_) {
595 TRACE_EVENT0("startup",
596 "BrowserMainLoop::CreateThreads:PreCreateThreads");
597 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::PreCreateThreads");
599 result_code_ = parts_->PreCreateThreads();
602 #if defined(OS_CHROMEOS)
603 if (chromeos::switches::MemoryPressureHandlingEnabled()) {
604 memory_pressure_monitor_.reset(new base::MemoryPressureMonitorChromeOS(
605 chromeos::switches::GetMemoryPressureThresholds()));
607 #endif
609 #if defined(ENABLE_PLUGINS)
610 // Prior to any processing happening on the io thread, we create the
611 // plugin service as it is predominantly used from the io thread,
612 // but must be created on the main thread. The service ctor is
613 // inexpensive and does not invoke the io_thread() accessor.
615 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads:PluginService");
616 PluginService::GetInstance()->Init();
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 #if !defined(OS_IOS) && (!defined(GOOGLE_CHROME_BUILD) || defined(OS_ANDROID))
640 // Single-process is an unsupported and not fully tested mode, so
641 // don't enable it for official Chrome builds (except on Android).
642 if (parsed_command_line_.HasSwitch(switches::kSingleProcess))
643 RenderProcessHost::SetRunRendererInProcess(true);
644 #endif
646 return result_code_;
649 void BrowserMainLoop::CreateStartupTasks() {
650 TRACE_EVENT0("startup", "BrowserMainLoop::CreateStartupTasks");
651 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::CreateStartupTasks");
653 // First time through, we really want to create all the tasks
654 if (!startup_task_runner_.get()) {
655 #if defined(OS_ANDROID)
656 startup_task_runner_ = make_scoped_ptr(new StartupTaskRunner(
657 base::Bind(&BrowserStartupComplete),
658 base::MessageLoop::current()->message_loop_proxy()));
659 #else
660 startup_task_runner_ = make_scoped_ptr(new StartupTaskRunner(
661 base::Callback<void(int)>(),
662 base::MessageLoop::current()->message_loop_proxy()));
663 #endif
664 StartupTask pre_create_threads =
665 base::Bind(&BrowserMainLoop::PreCreateThreads, base::Unretained(this));
666 startup_task_runner_->AddTask(pre_create_threads);
668 StartupTask create_threads =
669 base::Bind(&BrowserMainLoop::CreateThreads, base::Unretained(this));
670 startup_task_runner_->AddTask(create_threads);
672 StartupTask browser_thread_started = base::Bind(
673 &BrowserMainLoop::BrowserThreadsStarted, base::Unretained(this));
674 startup_task_runner_->AddTask(browser_thread_started);
676 StartupTask pre_main_message_loop_run = base::Bind(
677 &BrowserMainLoop::PreMainMessageLoopRun, base::Unretained(this));
678 startup_task_runner_->AddTask(pre_main_message_loop_run);
680 #if defined(OS_ANDROID)
681 if (BrowserMayStartAsynchronously()) {
682 startup_task_runner_->StartRunningTasksAsync();
684 #endif
686 #if defined(OS_ANDROID)
687 if (!BrowserMayStartAsynchronously()) {
688 // A second request for asynchronous startup can be ignored, so
689 // StartupRunningTasksAsync is only called first time through. If, however,
690 // this is a request for synchronous startup then it must override any
691 // previous call for async startup, so we call RunAllTasksNow()
692 // unconditionally.
693 startup_task_runner_->RunAllTasksNow();
695 #else
696 startup_task_runner_->RunAllTasksNow();
697 #endif
700 int BrowserMainLoop::CreateThreads() {
701 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads");
702 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::CreateThreads");
704 base::Thread::Options io_message_loop_options;
705 io_message_loop_options.message_loop_type = base::MessageLoop::TYPE_IO;
706 base::Thread::Options ui_message_loop_options;
707 ui_message_loop_options.message_loop_type = base::MessageLoop::TYPE_UI;
709 // Start threads in the order they occur in the BrowserThread::ID
710 // enumeration, except for BrowserThread::UI which is the main
711 // thread.
713 // Must be size_t so we can increment it.
714 for (size_t thread_id = BrowserThread::UI + 1;
715 thread_id < BrowserThread::ID_COUNT;
716 ++thread_id) {
717 scoped_ptr<BrowserProcessSubThread>* thread_to_start = NULL;
718 base::Thread::Options options;
720 switch (thread_id) {
721 case BrowserThread::DB:
722 TRACE_EVENT_BEGIN1("startup",
723 "BrowserMainLoop::CreateThreads:start",
724 "Thread", "BrowserThread::DB");
725 thread_to_start = &db_thread_;
726 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
727 break;
728 case BrowserThread::FILE_USER_BLOCKING:
729 TRACE_EVENT_BEGIN1("startup",
730 "BrowserMainLoop::CreateThreads:start",
731 "Thread", "BrowserThread::FILE_USER_BLOCKING");
732 thread_to_start = &file_user_blocking_thread_;
733 break;
734 case BrowserThread::FILE:
735 TRACE_EVENT_BEGIN1("startup",
736 "BrowserMainLoop::CreateThreads:start",
737 "Thread", "BrowserThread::FILE");
738 thread_to_start = &file_thread_;
739 #if defined(OS_WIN)
740 // On Windows, the FILE thread needs to be have a UI message loop
741 // which pumps messages in such a way that Google Update can
742 // communicate back to us.
743 options = ui_message_loop_options;
744 #else
745 options = io_message_loop_options;
746 #endif
747 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
748 break;
749 case BrowserThread::PROCESS_LAUNCHER:
750 TRACE_EVENT_BEGIN1("startup",
751 "BrowserMainLoop::CreateThreads:start",
752 "Thread", "BrowserThread::PROCESS_LAUNCHER");
753 thread_to_start = &process_launcher_thread_;
754 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
755 break;
756 case BrowserThread::CACHE:
757 TRACE_EVENT_BEGIN1("startup",
758 "BrowserMainLoop::CreateThreads:start",
759 "Thread", "BrowserThread::CACHE");
760 thread_to_start = &cache_thread_;
761 options = io_message_loop_options;
762 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
763 break;
764 case BrowserThread::IO:
765 TRACE_EVENT_BEGIN1("startup",
766 "BrowserMainLoop::CreateThreads:start",
767 "Thread", "BrowserThread::IO");
768 thread_to_start = &io_thread_;
769 options = io_message_loop_options;
770 break;
771 case BrowserThread::UI:
772 case BrowserThread::ID_COUNT:
773 default:
774 NOTREACHED();
775 break;
778 BrowserThread::ID id = static_cast<BrowserThread::ID>(thread_id);
780 if (thread_to_start) {
781 (*thread_to_start).reset(new BrowserProcessSubThread(id));
782 if (!(*thread_to_start)->StartWithOptions(options)) {
783 LOG(FATAL) << "Failed to start the browser thread: id == " << id;
785 } else {
786 NOTREACHED();
789 TRACE_EVENT_END0("startup", "BrowserMainLoop::CreateThreads:start");
791 created_threads_ = true;
792 return result_code_;
795 int BrowserMainLoop::PreMainMessageLoopRun() {
796 if (parts_) {
797 TRACE_EVENT0("startup",
798 "BrowserMainLoop::CreateThreads:PreMainMessageLoopRun");
799 TRACK_SCOPED_REGION(
800 "Startup", "BrowserMainLoop::PreMainMessageLoopRun");
802 parts_->PreMainMessageLoopRun();
805 // If the UI thread blocks, the whole UI is unresponsive.
806 // Do not allow disk IO from the UI thread.
807 base::ThreadRestrictions::SetIOAllowed(false);
808 base::ThreadRestrictions::DisallowWaiting();
809 return result_code_;
812 void BrowserMainLoop::RunMainMessageLoopParts() {
813 TRACE_EVENT_BEGIN_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
815 bool ran_main_loop = false;
816 if (parts_)
817 ran_main_loop = parts_->MainMessageLoopRun(&result_code_);
819 if (!ran_main_loop)
820 MainMessageLoopRun();
822 TRACE_EVENT_END_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
825 void BrowserMainLoop::ShutdownThreadsAndCleanUp() {
826 if (!created_threads_) {
827 // Called early, nothing to do
828 return;
830 TRACE_EVENT0("shutdown", "BrowserMainLoop::ShutdownThreadsAndCleanUp");
832 // Teardown may start in PostMainMessageLoopRun, and during teardown we
833 // need to be able to perform IO.
834 base::ThreadRestrictions::SetIOAllowed(true);
835 BrowserThread::PostTask(
836 BrowserThread::IO, FROM_HERE,
837 base::Bind(base::IgnoreResult(&base::ThreadRestrictions::SetIOAllowed),
838 true));
840 #if !defined(OS_IOS)
841 if (RenderProcessHost::run_renderer_in_process())
842 RenderProcessHostImpl::ShutDownInProcessRenderer();
843 #endif
845 if (parts_) {
846 TRACE_EVENT0("shutdown",
847 "BrowserMainLoop::Subsystem:PostMainMessageLoopRun");
848 parts_->PostMainMessageLoopRun();
851 trace_memory_controller_.reset();
852 system_stats_monitor_.reset();
854 #if !defined(OS_IOS)
855 // Destroying the GpuProcessHostUIShims on the UI thread posts a task to
856 // delete related objects on the GPU thread. This must be done before
857 // stopping the GPU thread. The GPU thread will close IPC channels to renderer
858 // processes so this has to happen before stopping the IO thread.
860 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUProcessHostShim");
861 GpuProcessHostUIShim::DestroyAll();
863 // Cancel pending requests and prevent new requests.
864 if (resource_dispatcher_host_) {
865 TRACE_EVENT0("shutdown",
866 "BrowserMainLoop::Subsystem:ResourceDispatcherHost");
867 resource_dispatcher_host_.get()->Shutdown();
870 #if defined(OS_CHROMEOS)
871 memory_pressure_monitor_.reset();
872 #endif
874 #if defined(OS_MACOSX)
875 BrowserCompositorMac::DisableRecyclingForShutdown();
876 #endif
878 #if defined(USE_AURA) || defined(OS_MACOSX)
880 TRACE_EVENT0("shutdown",
881 "BrowserMainLoop::Subsystem:ImageTransportFactory");
882 ImageTransportFactory::Terminate();
884 #endif
886 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
887 ZygoteHostImpl::GetInstance()->TearDownAfterLastChild();
888 #endif // defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
890 // The device monitors are using |system_monitor_| as dependency, so delete
891 // them before |system_monitor_| goes away.
892 // On Mac and windows, the monitor needs to be destroyed on the same thread
893 // as they were created. On Linux, the monitor will be deleted when IO thread
894 // goes away.
895 #if defined(OS_WIN)
896 system_message_window_.reset();
897 #elif defined(OS_MACOSX)
898 device_monitor_mac_.reset();
899 #endif
900 #endif // !defined(OS_IOS)
902 // Must be size_t so we can subtract from it.
903 for (size_t thread_id = BrowserThread::ID_COUNT - 1;
904 thread_id >= (BrowserThread::UI + 1);
905 --thread_id) {
906 // Find the thread object we want to stop. Looping over all valid
907 // BrowserThread IDs and DCHECKing on a missing case in the switch
908 // statement helps avoid a mismatch between this code and the
909 // BrowserThread::ID enumeration.
911 // The destruction order is the reverse order of occurrence in the
912 // BrowserThread::ID list. The rationale for the order is as
913 // follows (need to be filled in a bit):
916 // - The IO thread is the only user of the CACHE thread.
918 // - The PROCESS_LAUNCHER thread must be stopped after IO in case
919 // the IO thread posted a task to terminate a process on the
920 // process launcher thread.
922 // - (Not sure why DB stops last.)
923 switch (thread_id) {
924 case BrowserThread::DB: {
925 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DBThread");
926 ResetThread_DB(db_thread_.Pass());
927 break;
929 case BrowserThread::FILE: {
930 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:FileThread");
931 #if !defined(OS_IOS)
932 // Clean up state that lives on or uses the file_thread_ before
933 // it goes away.
934 if (resource_dispatcher_host_)
935 resource_dispatcher_host_.get()->save_file_manager()->Shutdown();
936 #endif // !defined(OS_IOS)
937 ResetThread_FILE(file_thread_.Pass());
938 break;
940 case BrowserThread::FILE_USER_BLOCKING: {
941 TRACE_EVENT0("shutdown",
942 "BrowserMainLoop::Subsystem:FileUserBlockingThread");
943 ResetThread_FILE_USER_BLOCKING(file_user_blocking_thread_.Pass());
944 break;
946 case BrowserThread::PROCESS_LAUNCHER: {
947 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:LauncherThread");
948 ResetThread_PROCESS_LAUNCHER(process_launcher_thread_.Pass());
949 break;
951 case BrowserThread::CACHE: {
952 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:CacheThread");
953 ResetThread_CACHE(cache_thread_.Pass());
954 break;
956 case BrowserThread::IO: {
957 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IOThread");
958 ResetThread_IO(io_thread_.Pass());
959 break;
961 case BrowserThread::UI:
962 case BrowserThread::ID_COUNT:
963 default:
964 NOTREACHED();
965 break;
969 #if !defined(OS_IOS)
971 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IndexedDBThread");
972 ResetThread_IndexedDb(indexed_db_thread_.Pass());
974 #endif
976 // Close the blocking I/O pool after the other threads. Other threads such
977 // as the I/O thread may need to schedule work like closing files or flushing
978 // data during shutdown, so the blocking pool needs to be available. There
979 // may also be slow operations pending that will blcok shutdown, so closing
980 // it here (which will block until required operations are complete) gives
981 // more head start for those operations to finish.
983 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:ThreadPool");
984 BrowserThreadImpl::ShutdownThreadPool();
987 #if !defined(OS_IOS)
988 // Must happen after the IO thread is shutdown since this may be accessed from
989 // it.
991 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUChannelFactory");
992 if (BrowserGpuChannelHostFactory::instance())
993 BrowserGpuChannelHostFactory::Terminate();
996 // Must happen after the I/O thread is shutdown since this class lives on the
997 // I/O thread and isn't threadsafe.
999 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GamepadService");
1000 GamepadService::GetInstance()->Terminate();
1003 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:SensorService");
1004 DeviceInertialSensorService::GetInstance()->Shutdown();
1007 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:BatteryStatusService");
1008 device::BatteryStatusService::GetInstance()->Shutdown();
1011 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DeleteDataSources");
1012 URLDataManager::DeleteDataSources();
1014 #endif // !defined(OS_IOS)
1016 if (parts_) {
1017 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:PostDestroyThreads");
1018 parts_->PostDestroyThreads();
1022 void BrowserMainLoop::StopStartupTracingTimer() {
1023 startup_trace_timer_.Stop();
1026 void BrowserMainLoop::InitializeMainThread() {
1027 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeMainThread");
1028 const char* kThreadName = "CrBrowserMain";
1029 base::PlatformThread::SetName(kThreadName);
1030 if (main_message_loop_)
1031 main_message_loop_->set_thread_name(kThreadName);
1033 // Register the main thread by instantiating it, but don't call any methods.
1034 main_thread_.reset(
1035 new BrowserThreadImpl(BrowserThread::UI, base::MessageLoop::current()));
1038 int BrowserMainLoop::BrowserThreadsStarted() {
1039 TRACE_EVENT0("startup", "BrowserMainLoop::BrowserThreadsStarted");
1041 #if !defined(OS_IOS)
1042 indexed_db_thread_.reset(new base::Thread("IndexedDB"));
1043 indexed_db_thread_->Start();
1044 #endif
1046 #if !defined(OS_IOS)
1047 HistogramSynchronizer::GetInstance();
1050 // GpuDataManager for in-process initialized in PreCreateThreads.
1051 bool initialize_gpu_data_manager = !UsingInProcessGpu();
1052 #if defined(OS_ANDROID)
1053 // Up the priority of anything that touches with display tasks
1054 // (this thread is UI thread, and io_thread_ is for IPCs).
1055 io_thread_->SetPriority(base::ThreadPriority::DISPLAY);
1056 base::PlatformThread::SetThreadPriority(base::PlatformThread::CurrentHandle(),
1057 base::ThreadPriority::DISPLAY);
1059 // On Android, GLSurface::InitializeOneOff() must be called before
1060 // initalizing the GpuDataManagerImpl as it uses the GL bindings.
1061 // TODO(sievers): Shouldn't need to init full bindings to determine GL
1062 // version/vendor strings. crbug.com/326295
1063 if (initialize_gpu_data_manager) {
1064 // Note InitializeOneOff is not safe either for in-process gpu after
1065 // creating threads, since it may race with the gpu thread.
1066 if (!gfx::GLSurface::InitializeOneOff()) {
1067 LOG(FATAL) << "GLSurface::InitializeOneOff failed";
1070 #endif
1072 if (initialize_gpu_data_manager)
1073 GpuDataManagerImpl::GetInstance()->Initialize();
1075 bool always_uses_gpu = true;
1076 bool established_gpu_channel = false;
1077 #if defined(USE_AURA) || defined(OS_MACOSX)
1078 established_gpu_channel = true;
1079 if (!GpuDataManagerImpl::GetInstance()->CanUseGpuBrowserCompositor() ||
1080 parsed_command_line_.HasSwitch(switches::kDisableGpuEarlyInit)) {
1081 established_gpu_channel = always_uses_gpu = false;
1083 BrowserGpuChannelHostFactory::Initialize(established_gpu_channel);
1084 ImageTransportFactory::Initialize();
1085 #if defined(USE_AURA)
1086 if (aura::Env::GetInstance()) {
1087 aura::Env::GetInstance()->set_context_factory(GetContextFactory());
1089 #endif
1090 #elif defined(OS_ANDROID)
1091 // TODO(crbug.com/439322): This should be set to |true|.
1092 established_gpu_channel = false;
1093 BrowserGpuChannelHostFactory::Initialize(established_gpu_channel);
1094 #endif
1097 TRACE_EVENT0("startup", "BrowserThreadsStarted::Subsystem:AudioMan");
1098 audio_manager_.reset(media::AudioManager::CreateWithHangTimer(
1099 MediaInternals::GetInstance(), io_thread_->task_runner()));
1103 TRACE_EVENT0("startup", "BrowserThreadsStarted::Subsystem:MidiManager");
1104 midi_manager_.reset(media::MidiManager::Create());
1107 #if defined(OS_LINUX) && defined(USE_UDEV)
1108 device_monitor_linux_.reset(new DeviceMonitorLinux());
1109 #elif defined(OS_MACOSX)
1110 device_monitor_mac_.reset(new DeviceMonitorMac());
1111 #endif
1113 #if defined(OS_WIN)
1114 UMA_HISTOGRAM_BOOLEAN("Windows.Win32kRendererLockdown",
1115 IsWin32kRendererLockdownEnabled());
1116 #endif
1117 // RDH needs the IO thread to be created
1119 TRACE_EVENT0("startup",
1120 "BrowserMainLoop::BrowserThreadsStarted:InitResourceDispatcherHost");
1121 resource_dispatcher_host_.reset(new ResourceDispatcherHostImpl());
1124 // MediaStreamManager needs the IO thread to be created.
1126 TRACE_EVENT0("startup",
1127 "BrowserMainLoop::BrowserThreadsStarted:InitMediaStreamManager");
1128 media_stream_manager_.reset(new MediaStreamManager(audio_manager_.get()));
1132 TRACE_EVENT0("startup",
1133 "BrowserMainLoop::BrowserThreadsStarted:InitSpeechRecognition");
1134 speech_recognition_manager_.reset(new SpeechRecognitionManagerImpl(
1135 audio_manager_.get(), media_stream_manager_.get()));
1139 TRACE_EVENT0(
1140 "startup",
1141 "BrowserMainLoop::BrowserThreadsStarted::InitUserInputMonitor");
1142 user_input_monitor_ = media::UserInputMonitor::Create(
1143 io_thread_->message_loop_proxy(), main_thread_->message_loop_proxy());
1147 TRACE_EVENT0("startup",
1148 "BrowserMainLoop::BrowserThreadsStarted::TimeZoneMonitor");
1149 time_zone_monitor_ = TimeZoneMonitor::Create();
1152 // Alert the clipboard class to which threads are allowed to access the
1153 // clipboard:
1154 std::vector<base::PlatformThreadId> allowed_clipboard_threads;
1155 // The current thread is the UI thread.
1156 allowed_clipboard_threads.push_back(base::PlatformThread::CurrentId());
1157 #if defined(OS_WIN)
1158 // On Windows, clipboards are also used on the File or IO threads.
1159 allowed_clipboard_threads.push_back(file_thread_->thread_id());
1160 allowed_clipboard_threads.push_back(io_thread_->thread_id());
1161 #endif
1162 ui::Clipboard::SetAllowedThreads(allowed_clipboard_threads);
1164 // When running the GPU thread in-process, avoid optimistically starting it
1165 // since creating the GPU thread races against creation of the one-and-only
1166 // ChildProcess instance which is created by the renderer thread.
1167 if (GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL) &&
1168 !established_gpu_channel &&
1169 always_uses_gpu &&
1170 !UsingInProcessGpu()) {
1171 TRACE_EVENT_INSTANT0("gpu", "Post task to launch GPU process",
1172 TRACE_EVENT_SCOPE_THREAD);
1173 BrowserThread::PostTask(
1174 BrowserThread::IO, FROM_HERE, base::Bind(
1175 base::IgnoreResult(&GpuProcessHost::Get),
1176 GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED,
1177 CAUSE_FOR_GPU_LAUNCH_BROWSER_STARTUP));
1180 #if defined(OS_MACOSX)
1181 ThemeHelperMac::GetInstance();
1182 SystemHotkeyHelperMac::GetInstance()->DeferredLoadSystemHotkeys();
1183 if (ShouldEnableBootstrapSandbox()) {
1184 TRACE_EVENT0("startup",
1185 "BrowserMainLoop::BrowserThreadsStarted:BootstrapSandbox");
1186 CHECK(GetBootstrapSandbox());
1188 #endif // defined(OS_MACOSX)
1190 #endif // !defined(OS_IOS)
1192 return result_code_;
1195 bool BrowserMainLoop::UsingInProcessGpu() const {
1196 return parsed_command_line_.HasSwitch(switches::kSingleProcess) ||
1197 parsed_command_line_.HasSwitch(switches::kInProcessGPU);
1200 bool BrowserMainLoop::InitializeToolkit() {
1201 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeToolkit");
1202 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::InitializeToolkit");
1204 // TODO(evan): this function is rather subtle, due to the variety
1205 // of intersecting ifdefs we have. To keep it easy to follow, there
1206 // are no #else branches on any #ifs.
1207 // TODO(stevenjb): Move platform specific code into platform specific Parts
1208 // (Need to add InitializeToolkit stage to BrowserParts).
1209 // See also GTK setup in EarlyInitialization, above, and associated comments.
1211 #if defined(OS_WIN)
1212 // Init common control sex.
1213 INITCOMMONCONTROLSEX config;
1214 config.dwSize = sizeof(config);
1215 config.dwICC = ICC_WIN95_CLASSES;
1216 if (!InitCommonControlsEx(&config))
1217 PLOG(FATAL);
1218 #endif
1220 #if defined(USE_AURA)
1222 #if defined(USE_X11)
1223 if (!gfx::GetXDisplay())
1224 return false;
1225 #endif
1227 // Env creates the compositor. Aura widgets need the compositor to be created
1228 // before they can be initialized by the browser.
1229 aura::Env::CreateInstance(true);
1230 #endif // defined(USE_AURA)
1232 if (parts_)
1233 parts_->ToolkitInitialized();
1235 return true;
1238 void BrowserMainLoop::MainMessageLoopRun() {
1239 #if defined(OS_ANDROID)
1240 // Android's main message loop is the Java message loop.
1241 NOTREACHED();
1242 #else
1243 DCHECK(base::MessageLoopForUI::IsCurrent());
1244 if (parameters_.ui_task)
1245 base::MessageLoopForUI::current()->PostTask(FROM_HERE,
1246 *parameters_.ui_task);
1248 base::RunLoop run_loop;
1249 run_loop.Run();
1250 #endif
1253 base::FilePath BrowserMainLoop::GetStartupTraceFileName(
1254 const base::CommandLine& command_line) const {
1255 base::FilePath trace_file = command_line.GetSwitchValuePath(
1256 switches::kTraceStartupFile);
1257 // trace_file = "none" means that startup events will show up for the next
1258 // begin/end tracing (via about:tracing or AutomationProxy::BeginTracing/
1259 // EndTracing, for example).
1260 if (trace_file == base::FilePath().AppendASCII("none"))
1261 return trace_file;
1263 if (trace_file.empty()) {
1264 #if defined(OS_ANDROID)
1265 TracingControllerAndroid::GenerateTracingFilePath(&trace_file);
1266 #else
1267 // Default to saving the startup trace into the current dir.
1268 trace_file = base::FilePath().AppendASCII("chrometrace.log");
1269 #endif
1272 return trace_file;
1275 void BrowserMainLoop::InitStartupTracing(
1276 const base::CommandLine& command_line) {
1277 DCHECK(is_tracing_startup_);
1279 startup_trace_file_ = GetStartupTraceFileName(parsed_command_line_);
1281 std::string delay_str = command_line.GetSwitchValueASCII(
1282 switches::kTraceStartupDuration);
1283 int delay_secs = 5;
1284 if (!delay_str.empty() && !base::StringToInt(delay_str, &delay_secs)) {
1285 DLOG(WARNING) << "Could not parse --" << switches::kTraceStartupDuration
1286 << "=" << delay_str << " defaulting to 5 (secs)";
1287 delay_secs = 5;
1290 startup_trace_timer_.Start(FROM_HERE,
1291 base::TimeDelta::FromSeconds(delay_secs),
1292 this,
1293 &BrowserMainLoop::EndStartupTracing);
1296 void BrowserMainLoop::EndStartupTracing() {
1297 is_tracing_startup_ = false;
1298 TracingController::GetInstance()->DisableRecording(
1299 TracingController::CreateFileSink(
1300 startup_trace_file_,
1301 base::Bind(OnStoppedStartupTracing, startup_trace_file_)));
1304 } // namespace content