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