Revert of Update V8 to version 4.4.24. (patchset #1 id:1 of https://codereview.chromi...
[chromium-blink-merge.git] / content / browser / browser_main_loop.cc
blobd485389c44e98099fb7e177ef3e3794a691cdf19
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/common/host_discardable_shared_memory_manager.h"
45 #include "content/public/browser/browser_main_parts.h"
46 #include "content/public/browser/browser_shutdown.h"
47 #include "content/public/browser/content_browser_client.h"
48 #include "content/public/browser/render_process_host.h"
49 #include "content/public/browser/tracing_controller.h"
50 #include "content/public/common/content_switches.h"
51 #include "content/public/common/main_function_params.h"
52 #include "content/public/common/result_codes.h"
53 #include "crypto/nss_util.h"
54 #include "device/battery/battery_status_service.h"
55 #include "media/audio/audio_manager.h"
56 #include "media/base/media.h"
57 #include "media/base/user_input_monitor.h"
58 #include "media/midi/midi_manager.h"
59 #include "net/base/network_change_notifier.h"
60 #include "net/socket/client_socket_factory.h"
61 #include "net/ssl/ssl_config_service.h"
62 #include "ui/base/clipboard/clipboard.h"
64 #if defined(USE_AURA) || (defined(OS_MACOSX) && !defined(OS_IOS))
65 #include "content/browser/compositor/image_transport_factory.h"
66 #endif
68 #if defined(USE_AURA)
69 #include "content/public/browser/context_factory.h"
70 #include "ui/aura/env.h"
71 #endif
73 #if !defined(OS_IOS)
74 #include "content/browser/renderer_host/render_process_host_impl.h"
75 #endif
77 #if defined(OS_ANDROID)
78 #include "base/android/jni_android.h"
79 #include "content/browser/android/browser_startup_controller.h"
80 #include "content/browser/android/browser_surface_texture_manager.h"
81 #include "content/browser/android/tracing_controller_android.h"
82 #include "content/browser/screen_orientation/screen_orientation_delegate_android.h"
83 #include "content/public/browser/screen_orientation_provider.h"
84 #include "ui/gl/gl_surface.h"
85 #endif
87 #if defined(OS_MACOSX) && !defined(OS_IOS)
88 #include "content/browser/bootstrap_sandbox_mac.h"
89 #include "content/browser/cocoa/system_hotkey_helper_mac.h"
90 #include "content/browser/compositor/browser_compositor_view_mac.h"
91 #include "content/browser/theme_helper_mac.h"
92 #endif
94 #if defined(OS_WIN)
95 #include <windows.h>
96 #include <commctrl.h>
97 #include <shellapi.h>
99 #include "content/browser/system_message_window_win.h"
100 #include "content/common/sandbox_win.h"
101 #include "net/base/winsock_init.h"
102 #include "ui/base/l10n/l10n_util_win.h"
103 #endif
105 #if defined(OS_CHROMEOS)
106 #include "base/chromeos/memory_pressure_monitor_chromeos.h"
107 #include "chromeos/chromeos_switches.h"
108 #endif
110 #if defined(USE_GLIB)
111 #include <glib-object.h>
112 #endif
114 #if defined(OS_LINUX) && defined(USE_UDEV)
115 #include "content/browser/device_monitor_udev.h"
116 #elif defined(OS_MACOSX) && !defined(OS_IOS)
117 #include "content/browser/device_monitor_mac.h"
118 #endif
120 #if defined(OS_POSIX) && !defined(OS_MACOSX)
121 #include "content/browser/renderer_host/render_sandbox_host_linux.h"
122 #include "content/browser/zygote_host/zygote_host_impl_linux.h"
123 #include "sandbox/linux/suid/client/setuid_sandbox_host.h"
124 #endif
126 #if defined(ENABLE_PLUGINS)
127 #include "content/browser/plugin_service_impl.h"
128 #endif
130 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
131 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
132 #endif
134 #if defined(USE_X11)
135 #include "ui/gfx/x/x11_connection.h"
136 #include "ui/gfx/x/x11_types.h"
137 #endif
139 // One of the linux specific headers defines this as a macro.
140 #ifdef DestroyAll
141 #undef DestroyAll
142 #endif
144 namespace content {
145 namespace {
147 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
148 void SetupSandbox(const base::CommandLine& parsed_command_line) {
149 TRACE_EVENT0("startup", "SetupSandbox");
150 base::FilePath sandbox_binary;
152 scoped_ptr<sandbox::SetuidSandboxHost> setuid_sandbox_host(
153 sandbox::SetuidSandboxHost::Create());
155 const bool want_setuid_sandbox =
156 !parsed_command_line.HasSwitch(switches::kNoSandbox) &&
157 !parsed_command_line.HasSwitch(switches::kDisableSetuidSandbox) &&
158 !setuid_sandbox_host->IsDisabledViaEnvironment();
160 static const char no_suid_error[] =
161 "Running without the SUID sandbox! See "
162 "https://code.google.com/p/chromium/wiki/LinuxSUIDSandboxDevelopment "
163 "for more information on developing with the sandbox on.";
164 if (want_setuid_sandbox) {
165 sandbox_binary = setuid_sandbox_host->GetSandboxBinaryPath();
166 if (sandbox_binary.empty()) {
167 // This needs to be fatal. Talk to security@chromium.org if you feel
168 // otherwise.
169 LOG(FATAL) << no_suid_error;
171 } else {
172 LOG(ERROR) << no_suid_error;
175 // Tickle the sandbox host and zygote host so they fork now.
176 RenderSandboxHostLinux::GetInstance()->Init();
177 ZygoteHostImpl::GetInstance()->Init(sandbox_binary.value());
179 #endif
181 #if defined(USE_GLIB)
182 static void GLibLogHandler(const gchar* log_domain,
183 GLogLevelFlags log_level,
184 const gchar* message,
185 gpointer userdata) {
186 if (!log_domain)
187 log_domain = "<unknown>";
188 if (!message)
189 message = "<no message>";
191 if (strstr(message, "Unable to retrieve the file info for")) {
192 LOG(ERROR) << "GTK File code error: " << message;
193 } else if (strstr(message, "Could not find the icon") &&
194 strstr(log_domain, "Gtk")) {
195 LOG(ERROR) << "GTK icon error: " << message;
196 } else if (strstr(message, "Theme file for default has no") ||
197 strstr(message, "Theme directory") ||
198 strstr(message, "theme pixmap") ||
199 strstr(message, "locate theme engine")) {
200 LOG(ERROR) << "GTK theme error: " << message;
201 } else if (strstr(message, "Unable to create Ubuntu Menu Proxy") &&
202 strstr(log_domain, "<unknown>")) {
203 LOG(ERROR) << "GTK menu proxy create failed";
204 } else if (strstr(message, "Out of memory") &&
205 strstr(log_domain, "<unknown>")) {
206 LOG(ERROR) << "DBus call timeout or out of memory: "
207 << "http://crosbug.com/15496";
208 } else if (strstr(message, "Could not connect: Connection refused") &&
209 strstr(log_domain, "<unknown>")) {
210 LOG(ERROR) << "DConf settings backend could not connect to session bus: "
211 << "http://crbug.com/179797";
212 } else if (strstr(message, "Attempting to store changes into") ||
213 strstr(message, "Attempting to set the permissions of")) {
214 LOG(ERROR) << message << " (http://bugs.chromium.org/161366)";
215 } else if (strstr(message, "drawable is not a native X11 window")) {
216 LOG(ERROR) << message << " (http://bugs.chromium.org/329991)";
217 } else {
218 LOG(DFATAL) << log_domain << ": " << message;
222 static void SetUpGLibLogHandler() {
223 // Register GLib-handled assertions to go through our logging system.
224 const char* kLogDomains[] = { NULL, "Gtk", "Gdk", "GLib", "GLib-GObject" };
225 for (size_t i = 0; i < arraysize(kLogDomains); i++) {
226 g_log_set_handler(kLogDomains[i],
227 static_cast<GLogLevelFlags>(G_LOG_FLAG_RECURSION |
228 G_LOG_FLAG_FATAL |
229 G_LOG_LEVEL_ERROR |
230 G_LOG_LEVEL_CRITICAL |
231 G_LOG_LEVEL_WARNING),
232 GLibLogHandler,
233 NULL);
236 #endif
238 void OnStoppedStartupTracing(const base::FilePath& trace_file) {
239 VLOG(0) << "Completed startup tracing to " << trace_file.value();
242 // Disable optimizations for this block of functions so the compiler doesn't
243 // merge them all together. This makes it possible to tell what thread was
244 // unresponsive by inspecting the callstack.
245 MSVC_DISABLE_OPTIMIZE()
246 MSVC_PUSH_DISABLE_WARNING(4748)
248 NOINLINE void ResetThread_DB(scoped_ptr<BrowserProcessSubThread> thread) {
249 volatile int inhibit_comdat = __LINE__;
250 ALLOW_UNUSED_LOCAL(inhibit_comdat);
251 thread.reset();
254 NOINLINE void ResetThread_FILE(scoped_ptr<BrowserProcessSubThread> thread) {
255 volatile int inhibit_comdat = __LINE__;
256 ALLOW_UNUSED_LOCAL(inhibit_comdat);
257 thread.reset();
260 NOINLINE void ResetThread_FILE_USER_BLOCKING(
261 scoped_ptr<BrowserProcessSubThread> thread) {
262 volatile int inhibit_comdat = __LINE__;
263 ALLOW_UNUSED_LOCAL(inhibit_comdat);
264 thread.reset();
267 NOINLINE void ResetThread_PROCESS_LAUNCHER(
268 scoped_ptr<BrowserProcessSubThread> thread) {
269 volatile int inhibit_comdat = __LINE__;
270 ALLOW_UNUSED_LOCAL(inhibit_comdat);
271 thread.reset();
274 NOINLINE void ResetThread_CACHE(scoped_ptr<BrowserProcessSubThread> thread) {
275 volatile int inhibit_comdat = __LINE__;
276 ALLOW_UNUSED_LOCAL(inhibit_comdat);
277 thread.reset();
280 NOINLINE void ResetThread_IO(scoped_ptr<BrowserProcessSubThread> thread) {
281 volatile int inhibit_comdat = __LINE__;
282 ALLOW_UNUSED_LOCAL(inhibit_comdat);
283 thread.reset();
286 #if !defined(OS_IOS)
287 NOINLINE void ResetThread_IndexedDb(scoped_ptr<base::Thread> thread) {
288 volatile int inhibit_comdat = __LINE__;
289 ALLOW_UNUSED_LOCAL(inhibit_comdat);
290 thread.reset();
292 #endif
294 MSVC_POP_WARNING()
295 MSVC_ENABLE_OPTIMIZE();
297 } // namespace
299 // The currently-running BrowserMainLoop. There can be one or zero.
300 BrowserMainLoop* g_current_browser_main_loop = NULL;
302 // This is just to be able to keep ShutdownThreadsAndCleanUp out of
303 // the public interface of BrowserMainLoop.
304 class BrowserShutdownImpl {
305 public:
306 static void ImmediateShutdownAndExitProcess() {
307 DCHECK(g_current_browser_main_loop);
308 g_current_browser_main_loop->ShutdownThreadsAndCleanUp();
310 #if defined(OS_WIN)
311 // At this point the message loop is still running yet we've shut everything
312 // down. If any messages are processed we'll likely crash. Exit now.
313 ExitProcess(RESULT_CODE_NORMAL_EXIT);
314 #elif defined(OS_POSIX) && !defined(OS_MACOSX)
315 _exit(RESULT_CODE_NORMAL_EXIT);
316 #else
317 NOTIMPLEMENTED();
318 #endif
322 void ImmediateShutdownAndExitProcess() {
323 BrowserShutdownImpl::ImmediateShutdownAndExitProcess();
326 // For measuring memory usage after each task. Behind a command line flag.
327 class BrowserMainLoop::MemoryObserver : public base::MessageLoop::TaskObserver {
328 public:
329 MemoryObserver() {}
330 ~MemoryObserver() override {}
332 void WillProcessTask(const base::PendingTask& pending_task) override {}
334 void DidProcessTask(const base::PendingTask& pending_task) override {
335 #if !defined(OS_IOS) // No ProcessMetrics on IOS.
336 scoped_ptr<base::ProcessMetrics> process_metrics(
337 base::ProcessMetrics::CreateProcessMetrics(
338 #if defined(OS_MACOSX)
339 base::GetCurrentProcessHandle(), NULL));
340 #else
341 base::GetCurrentProcessHandle()));
342 #endif
343 size_t private_bytes;
344 process_metrics->GetMemoryBytes(&private_bytes, NULL);
345 LOCAL_HISTOGRAM_MEMORY_KB("Memory.BrowserUsed", private_bytes >> 10);
346 #endif
348 private:
349 DISALLOW_COPY_AND_ASSIGN(MemoryObserver);
353 // BrowserMainLoop construction / destruction =============================
355 BrowserMainLoop* BrowserMainLoop::GetInstance() {
356 DCHECK_CURRENTLY_ON(BrowserThread::UI);
357 return g_current_browser_main_loop;
360 BrowserMainLoop::BrowserMainLoop(const MainFunctionParams& parameters)
361 : parameters_(parameters),
362 parsed_command_line_(parameters.command_line),
363 result_code_(RESULT_CODE_NORMAL_EXIT),
364 created_threads_(false),
365 // ContentMainRunner should have enabled tracing of the browser process
366 // when kTraceStartup is in the command line.
367 is_tracing_startup_(
368 parameters.command_line.HasSwitch(switches::kTraceStartup)) {
369 DCHECK(!g_current_browser_main_loop);
370 g_current_browser_main_loop = this;
373 BrowserMainLoop::~BrowserMainLoop() {
374 DCHECK_EQ(this, g_current_browser_main_loop);
375 #if !defined(OS_IOS)
376 ui::Clipboard::DestroyClipboardForCurrentThread();
377 #endif // !defined(OS_IOS)
378 g_current_browser_main_loop = NULL;
381 void BrowserMainLoop::Init() {
382 TRACE_EVENT0("startup", "BrowserMainLoop::Init");
383 parts_.reset(
384 GetContentClient()->browser()->CreateBrowserMainParts(parameters_));
387 // BrowserMainLoop stages ==================================================
389 void BrowserMainLoop::EarlyInitialization() {
390 TRACE_EVENT0("startup", "BrowserMainLoop::EarlyInitialization");
392 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
393 // No thread should be created before this call, as SetupSandbox()
394 // will end-up using fork().
395 SetupSandbox(parsed_command_line_);
396 #endif
398 #if defined(USE_X11)
399 if (UsingInProcessGpu()) {
400 if (!gfx::InitializeThreadedX11()) {
401 LOG(ERROR) << "Failed to put Xlib into threaded mode.";
404 #endif
406 // GLib's spawning of new processes is buggy, so it's important that at this
407 // point GLib does not need to start DBUS. Chrome should always start with
408 // DBUS_SESSION_BUS_ADDRESS properly set. See crbug.com/309093.
409 #if defined(USE_GLIB)
410 // g_type_init will be deprecated in 2.36. 2.35 is the development
411 // version for 2.36, hence do not call g_type_init starting 2.35.
412 // http://developer.gnome.org/gobject/unstable/gobject-Type-Information.html#g-type-init
413 #if !GLIB_CHECK_VERSION(2, 35, 0)
414 // GLib type system initialization. Needed at least for gconf,
415 // used in net/proxy/proxy_config_service_linux.cc. Most likely
416 // this is superfluous as gtk_init() ought to do this. It's
417 // definitely harmless, so retained as a reminder of this
418 // requirement for gconf.
419 g_type_init();
420 #endif
422 SetUpGLibLogHandler();
423 #endif
425 if (parts_)
426 parts_->PreEarlyInitialization();
428 #if defined(OS_MACOSX)
429 // We use quite a few file descriptors for our IPC, and the default limit on
430 // the Mac is low (256), so bump it up.
431 base::SetFdLimit(1024);
432 #endif
434 #if defined(OS_WIN)
435 net::EnsureWinsockInit();
436 #endif
438 #if !defined(USE_OPENSSL)
439 // We want to be sure to init NSPR on the main thread.
440 crypto::EnsureNSPRInit();
441 #endif // !defined(USE_OPENSSL)
443 #if !defined(OS_IOS)
444 if (parsed_command_line_.HasSwitch(switches::kRendererProcessLimit)) {
445 std::string limit_string = parsed_command_line_.GetSwitchValueASCII(
446 switches::kRendererProcessLimit);
447 size_t process_limit;
448 if (base::StringToSizeT(limit_string, &process_limit)) {
449 RenderProcessHost::SetMaxRendererProcessCount(process_limit);
452 #endif // !defined(OS_IOS)
454 if (parsed_command_line_.HasSwitch(switches::kEnableNativeGpuMemoryBuffers)) {
455 BrowserGpuChannelHostFactory::EnableGpuMemoryBufferFactoryUsage(
456 gfx::GpuMemoryBuffer::MAP);
459 #if defined(USE_OZONE)
460 BrowserGpuChannelHostFactory::EnableGpuMemoryBufferFactoryUsage(
461 gfx::GpuMemoryBuffer::SCANOUT);
462 #endif
464 base::DiscardableMemoryAllocator::SetInstance(
465 HostDiscardableSharedMemoryManager::current());
467 if (parts_)
468 parts_->PostEarlyInitialization();
471 void BrowserMainLoop::MainMessageLoopStart() {
472 TRACE_EVENT0("startup", "BrowserMainLoop::MainMessageLoopStart");
473 if (parts_) {
474 TRACE_EVENT0("startup",
475 "BrowserMainLoop::MainMessageLoopStart:PreMainMessageLoopStart");
476 parts_->PreMainMessageLoopStart();
479 #if defined(OS_WIN)
480 // If we're running tests (ui_task is non-null), then the ResourceBundle
481 // has already been initialized.
482 if (!parameters_.ui_task) {
483 // Override the configured locale with the user's preferred UI language.
484 l10n_util::OverrideLocaleWithUILanguageList();
486 #endif
488 // Create a MessageLoop if one does not already exist for the current thread.
489 if (!base::MessageLoop::current())
490 main_message_loop_.reset(new base::MessageLoopForUI);
492 InitializeMainThread();
495 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SystemMonitor");
496 system_monitor_.reset(new base::SystemMonitor);
499 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:PowerMonitor");
500 scoped_ptr<base::PowerMonitorSource> power_monitor_source(
501 new base::PowerMonitorDeviceSource());
502 power_monitor_.reset(new base::PowerMonitor(power_monitor_source.Pass()));
505 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:HighResTimerManager");
506 hi_res_timer_manager_.reset(new base::HighResolutionTimerManager);
509 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:NetworkChangeNotifier");
510 network_change_notifier_.reset(net::NetworkChangeNotifier::Create());
513 #if !defined(OS_IOS)
515 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MediaFeatures");
516 media::InitializeCPUSpecificMediaFeatures();
519 TRACE_EVENT0("startup",
520 "BrowserMainLoop::Subsystem:ContentWebUIController");
521 WebUIControllerFactory::RegisterFactory(
522 ContentWebUIControllerFactory::GetInstance());
526 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:OnlineStateObserver");
527 online_state_observer_.reset(new BrowserOnlineStateObserver);
531 system_stats_monitor_.reset(
532 new base::trace_event::TraceEventSystemStatsMonitor(
533 base::ThreadTaskRunnerHandle::Get()));
535 #endif // !defined(OS_IOS)
537 #if defined(OS_WIN)
538 system_message_window_.reset(new SystemMessageWindowWin);
539 #endif
541 if (parts_)
542 parts_->PostMainMessageLoopStart();
544 #if !defined(OS_IOS)
545 // Start tracing to a file if needed. Only do this after starting the main
546 // message loop to avoid calling MessagePumpForUI::ScheduleWork() before
547 // MessagePumpForUI::Start() as it will crash the browser.
548 if (is_tracing_startup_) {
549 TRACE_EVENT0("startup", "BrowserMainLoop::InitStartupTracing");
550 InitStartupTracing(parsed_command_line_);
552 #endif // !defined(OS_IOS)
554 #if defined(OS_ANDROID)
556 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SurfaceTextureManager");
557 SurfaceTextureManager::InitInstance(new BrowserSurfaceTextureManager);
560 if (!parsed_command_line_.HasSwitch(
561 switches::kDisableScreenOrientationLock)) {
562 TRACE_EVENT0("startup",
563 "BrowserMainLoop::Subsystem:ScreenOrientationProvider");
564 screen_orientation_delegate_.reset(
565 new ScreenOrientationDelegateAndroid());
566 ScreenOrientationProvider::SetDelegate(screen_orientation_delegate_.get());
568 #endif
570 if (parsed_command_line_.HasSwitch(switches::kMemoryMetrics)) {
571 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MemoryObserver");
572 memory_observer_.reset(new MemoryObserver());
573 base::MessageLoop::current()->AddTaskObserver(memory_observer_.get());
576 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
577 trace_memory_controller_.reset(new base::trace_event::TraceMemoryController(
578 base::MessageLoop::current()->message_loop_proxy(),
579 ::HeapProfilerWithPseudoStackStart, ::HeapProfilerStop,
580 ::GetHeapProfile));
581 #endif
584 int BrowserMainLoop::PreCreateThreads() {
585 if (parts_) {
586 TRACE_EVENT0("startup",
587 "BrowserMainLoop::CreateThreads:PreCreateThreads");
588 result_code_ = parts_->PreCreateThreads();
591 #if defined(OS_CHROMEOS)
592 if (chromeos::switches::MemoryPressureHandlingEnabled()) {
593 memory_pressure_monitor_.reset(new base::MemoryPressureMonitorChromeOS(
594 chromeos::switches::GetMemoryPressureThresholds()));
596 #endif
598 #if defined(ENABLE_PLUGINS)
599 // Prior to any processing happening on the io thread, we create the
600 // plugin service as it is predominantly used from the io thread,
601 // but must be created on the main thread. The service ctor is
602 // inexpensive and does not invoke the io_thread() accessor.
604 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads:PluginService");
605 PluginService::GetInstance()->Init();
607 #endif
609 // Need to initialize in-process GpuDataManager before creating threads.
610 // It's unsafe to append the gpu command line switches to the global
611 // CommandLine::ForCurrentProcess object after threads are created.
612 if (UsingInProcessGpu()) {
613 bool initialize_gpu_data_manager = true;
614 #if defined(OS_ANDROID)
615 if (!gfx::GLSurface::InitializeOneOff()) {
616 // Single-process Android WebView supports no gpu.
617 LOG(ERROR) << "GLSurface::InitializeOneOff failed";
618 initialize_gpu_data_manager = false;
620 #endif
622 // Initialize the GpuDataManager before we set up the MessageLoops because
623 // otherwise we'll trigger the assertion about doing IO on the UI thread.
624 if (initialize_gpu_data_manager)
625 GpuDataManagerImpl::GetInstance()->Initialize();
628 #if !defined(OS_IOS) && (!defined(GOOGLE_CHROME_BUILD) || defined(OS_ANDROID))
629 // Single-process is an unsupported and not fully tested mode, so
630 // don't enable it for official Chrome builds (except on Android).
631 if (parsed_command_line_.HasSwitch(switches::kSingleProcess))
632 RenderProcessHost::SetRunRendererInProcess(true);
633 #endif
635 return result_code_;
638 void BrowserMainLoop::CreateStartupTasks() {
639 TRACE_EVENT0("startup", "BrowserMainLoop::CreateStartupTasks");
641 // First time through, we really want to create all the tasks
642 if (!startup_task_runner_.get()) {
643 #if defined(OS_ANDROID)
644 startup_task_runner_ = make_scoped_ptr(new StartupTaskRunner(
645 base::Bind(&BrowserStartupComplete),
646 base::MessageLoop::current()->message_loop_proxy()));
647 #else
648 startup_task_runner_ = make_scoped_ptr(new StartupTaskRunner(
649 base::Callback<void(int)>(),
650 base::MessageLoop::current()->message_loop_proxy()));
651 #endif
652 StartupTask pre_create_threads =
653 base::Bind(&BrowserMainLoop::PreCreateThreads, base::Unretained(this));
654 startup_task_runner_->AddTask(pre_create_threads);
656 StartupTask create_threads =
657 base::Bind(&BrowserMainLoop::CreateThreads, base::Unretained(this));
658 startup_task_runner_->AddTask(create_threads);
660 StartupTask browser_thread_started = base::Bind(
661 &BrowserMainLoop::BrowserThreadsStarted, base::Unretained(this));
662 startup_task_runner_->AddTask(browser_thread_started);
664 StartupTask pre_main_message_loop_run = base::Bind(
665 &BrowserMainLoop::PreMainMessageLoopRun, base::Unretained(this));
666 startup_task_runner_->AddTask(pre_main_message_loop_run);
668 #if defined(OS_ANDROID)
669 if (BrowserMayStartAsynchronously()) {
670 startup_task_runner_->StartRunningTasksAsync();
672 #endif
674 #if defined(OS_ANDROID)
675 if (!BrowserMayStartAsynchronously()) {
676 // A second request for asynchronous startup can be ignored, so
677 // StartupRunningTasksAsync is only called first time through. If, however,
678 // this is a request for synchronous startup then it must override any
679 // previous call for async startup, so we call RunAllTasksNow()
680 // unconditionally.
681 startup_task_runner_->RunAllTasksNow();
683 #else
684 startup_task_runner_->RunAllTasksNow();
685 #endif
688 int BrowserMainLoop::CreateThreads() {
689 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads");
691 base::Thread::Options io_message_loop_options;
692 io_message_loop_options.message_loop_type = base::MessageLoop::TYPE_IO;
693 base::Thread::Options ui_message_loop_options;
694 ui_message_loop_options.message_loop_type = base::MessageLoop::TYPE_UI;
696 // Start threads in the order they occur in the BrowserThread::ID
697 // enumeration, except for BrowserThread::UI which is the main
698 // thread.
700 // Must be size_t so we can increment it.
701 for (size_t thread_id = BrowserThread::UI + 1;
702 thread_id < BrowserThread::ID_COUNT;
703 ++thread_id) {
704 scoped_ptr<BrowserProcessSubThread>* thread_to_start = NULL;
705 base::Thread::Options options;
707 switch (thread_id) {
708 case BrowserThread::DB:
709 TRACE_EVENT_BEGIN1("startup",
710 "BrowserMainLoop::CreateThreads:start",
711 "Thread", "BrowserThread::DB");
712 thread_to_start = &db_thread_;
713 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
714 break;
715 case BrowserThread::FILE_USER_BLOCKING:
716 TRACE_EVENT_BEGIN1("startup",
717 "BrowserMainLoop::CreateThreads:start",
718 "Thread", "BrowserThread::FILE_USER_BLOCKING");
719 thread_to_start = &file_user_blocking_thread_;
720 break;
721 case BrowserThread::FILE:
722 TRACE_EVENT_BEGIN1("startup",
723 "BrowserMainLoop::CreateThreads:start",
724 "Thread", "BrowserThread::FILE");
725 thread_to_start = &file_thread_;
726 #if defined(OS_WIN)
727 // On Windows, the FILE thread needs to be have a UI message loop
728 // which pumps messages in such a way that Google Update can
729 // communicate back to us.
730 options = ui_message_loop_options;
731 #else
732 options = io_message_loop_options;
733 #endif
734 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
735 break;
736 case BrowserThread::PROCESS_LAUNCHER:
737 TRACE_EVENT_BEGIN1("startup",
738 "BrowserMainLoop::CreateThreads:start",
739 "Thread", "BrowserThread::PROCESS_LAUNCHER");
740 thread_to_start = &process_launcher_thread_;
741 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
742 break;
743 case BrowserThread::CACHE:
744 TRACE_EVENT_BEGIN1("startup",
745 "BrowserMainLoop::CreateThreads:start",
746 "Thread", "BrowserThread::CACHE");
747 thread_to_start = &cache_thread_;
748 options = io_message_loop_options;
749 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
750 break;
751 case BrowserThread::IO:
752 TRACE_EVENT_BEGIN1("startup",
753 "BrowserMainLoop::CreateThreads:start",
754 "Thread", "BrowserThread::IO");
755 thread_to_start = &io_thread_;
756 options = io_message_loop_options;
757 break;
758 case BrowserThread::UI:
759 case BrowserThread::ID_COUNT:
760 default:
761 NOTREACHED();
762 break;
765 BrowserThread::ID id = static_cast<BrowserThread::ID>(thread_id);
767 if (thread_to_start) {
768 (*thread_to_start).reset(new BrowserProcessSubThread(id));
769 if (!(*thread_to_start)->StartWithOptions(options)) {
770 LOG(FATAL) << "Failed to start the browser thread: id == " << id;
772 } else {
773 NOTREACHED();
776 TRACE_EVENT_END0("startup", "BrowserMainLoop::CreateThreads:start");
778 created_threads_ = true;
779 return result_code_;
782 int BrowserMainLoop::PreMainMessageLoopRun() {
783 if (parts_) {
784 TRACE_EVENT0("startup",
785 "BrowserMainLoop::CreateThreads:PreMainMessageLoopRun");
786 parts_->PreMainMessageLoopRun();
789 // If the UI thread blocks, the whole UI is unresponsive.
790 // Do not allow disk IO from the UI thread.
791 base::ThreadRestrictions::SetIOAllowed(false);
792 base::ThreadRestrictions::DisallowWaiting();
793 return result_code_;
796 void BrowserMainLoop::RunMainMessageLoopParts() {
797 TRACE_EVENT_BEGIN_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
799 bool ran_main_loop = false;
800 if (parts_)
801 ran_main_loop = parts_->MainMessageLoopRun(&result_code_);
803 if (!ran_main_loop)
804 MainMessageLoopRun();
806 TRACE_EVENT_END_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
809 void BrowserMainLoop::ShutdownThreadsAndCleanUp() {
810 if (!created_threads_) {
811 // Called early, nothing to do
812 return;
814 TRACE_EVENT0("shutdown", "BrowserMainLoop::ShutdownThreadsAndCleanUp");
816 // Teardown may start in PostMainMessageLoopRun, and during teardown we
817 // need to be able to perform IO.
818 base::ThreadRestrictions::SetIOAllowed(true);
819 BrowserThread::PostTask(
820 BrowserThread::IO, FROM_HERE,
821 base::Bind(base::IgnoreResult(&base::ThreadRestrictions::SetIOAllowed),
822 true));
824 #if !defined(OS_IOS)
825 if (RenderProcessHost::run_renderer_in_process())
826 RenderProcessHostImpl::ShutDownInProcessRenderer();
827 #endif
829 if (parts_) {
830 TRACE_EVENT0("shutdown",
831 "BrowserMainLoop::Subsystem:PostMainMessageLoopRun");
832 parts_->PostMainMessageLoopRun();
835 trace_memory_controller_.reset();
836 system_stats_monitor_.reset();
838 #if !defined(OS_IOS)
839 // Destroying the GpuProcessHostUIShims on the UI thread posts a task to
840 // delete related objects on the GPU thread. This must be done before
841 // stopping the GPU thread. The GPU thread will close IPC channels to renderer
842 // processes so this has to happen before stopping the IO thread.
844 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUProcessHostShim");
845 GpuProcessHostUIShim::DestroyAll();
847 // Cancel pending requests and prevent new requests.
848 if (resource_dispatcher_host_) {
849 TRACE_EVENT0("shutdown",
850 "BrowserMainLoop::Subsystem:ResourceDispatcherHost");
851 resource_dispatcher_host_.get()->Shutdown();
854 #if defined(OS_CHROMEOS)
855 memory_pressure_monitor_.reset();
856 #endif
858 #if defined(OS_MACOSX)
859 BrowserCompositorMac::DisableRecyclingForShutdown();
860 #endif
862 #if defined(USE_AURA) || defined(OS_MACOSX)
864 TRACE_EVENT0("shutdown",
865 "BrowserMainLoop::Subsystem:ImageTransportFactory");
866 ImageTransportFactory::Terminate();
868 #endif
870 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
871 ZygoteHostImpl::GetInstance()->TearDownAfterLastChild();
872 #endif // defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
874 // The device monitors are using |system_monitor_| as dependency, so delete
875 // them before |system_monitor_| goes away.
876 // On Mac and windows, the monitor needs to be destroyed on the same thread
877 // as they were created. On Linux, the monitor will be deleted when IO thread
878 // goes away.
879 #if defined(OS_WIN)
880 system_message_window_.reset();
881 #elif defined(OS_MACOSX)
882 device_monitor_mac_.reset();
883 #endif
884 #endif // !defined(OS_IOS)
886 // Must be size_t so we can subtract from it.
887 for (size_t thread_id = BrowserThread::ID_COUNT - 1;
888 thread_id >= (BrowserThread::UI + 1);
889 --thread_id) {
890 // Find the thread object we want to stop. Looping over all valid
891 // BrowserThread IDs and DCHECKing on a missing case in the switch
892 // statement helps avoid a mismatch between this code and the
893 // BrowserThread::ID enumeration.
895 // The destruction order is the reverse order of occurrence in the
896 // BrowserThread::ID list. The rationale for the order is as
897 // follows (need to be filled in a bit):
900 // - The IO thread is the only user of the CACHE thread.
902 // - The PROCESS_LAUNCHER thread must be stopped after IO in case
903 // the IO thread posted a task to terminate a process on the
904 // process launcher thread.
906 // - (Not sure why DB stops last.)
907 switch (thread_id) {
908 case BrowserThread::DB: {
909 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DBThread");
910 ResetThread_DB(db_thread_.Pass());
911 break;
913 case BrowserThread::FILE: {
914 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:FileThread");
915 #if !defined(OS_IOS)
916 // Clean up state that lives on or uses the file_thread_ before
917 // it goes away.
918 if (resource_dispatcher_host_)
919 resource_dispatcher_host_.get()->save_file_manager()->Shutdown();
920 #endif // !defined(OS_IOS)
921 ResetThread_FILE(file_thread_.Pass());
922 break;
924 case BrowserThread::FILE_USER_BLOCKING: {
925 TRACE_EVENT0("shutdown",
926 "BrowserMainLoop::Subsystem:FileUserBlockingThread");
927 ResetThread_FILE_USER_BLOCKING(file_user_blocking_thread_.Pass());
928 break;
930 case BrowserThread::PROCESS_LAUNCHER: {
931 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:LauncherThread");
932 ResetThread_PROCESS_LAUNCHER(process_launcher_thread_.Pass());
933 break;
935 case BrowserThread::CACHE: {
936 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:CacheThread");
937 ResetThread_CACHE(cache_thread_.Pass());
938 break;
940 case BrowserThread::IO: {
941 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IOThread");
942 ResetThread_IO(io_thread_.Pass());
943 break;
945 case BrowserThread::UI:
946 case BrowserThread::ID_COUNT:
947 default:
948 NOTREACHED();
949 break;
953 #if !defined(OS_IOS)
955 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IndexedDBThread");
956 ResetThread_IndexedDb(indexed_db_thread_.Pass());
958 #endif
960 // Close the blocking I/O pool after the other threads. Other threads such
961 // as the I/O thread may need to schedule work like closing files or flushing
962 // data during shutdown, so the blocking pool needs to be available. There
963 // may also be slow operations pending that will blcok shutdown, so closing
964 // it here (which will block until required operations are complete) gives
965 // more head start for those operations to finish.
967 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:ThreadPool");
968 BrowserThreadImpl::ShutdownThreadPool();
971 #if !defined(OS_IOS)
972 // Must happen after the IO thread is shutdown since this may be accessed from
973 // it.
975 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUChannelFactory");
976 if (BrowserGpuChannelHostFactory::instance())
977 BrowserGpuChannelHostFactory::Terminate();
980 // Must happen after the I/O thread is shutdown since this class lives on the
981 // I/O thread and isn't threadsafe.
983 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GamepadService");
984 GamepadService::GetInstance()->Terminate();
987 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:SensorService");
988 DeviceInertialSensorService::GetInstance()->Shutdown();
991 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:BatteryStatusService");
992 device::BatteryStatusService::GetInstance()->Shutdown();
995 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DeleteDataSources");
996 URLDataManager::DeleteDataSources();
998 #endif // !defined(OS_IOS)
1000 if (parts_) {
1001 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:PostDestroyThreads");
1002 parts_->PostDestroyThreads();
1006 void BrowserMainLoop::StopStartupTracingTimer() {
1007 startup_trace_timer_.Stop();
1010 void BrowserMainLoop::InitializeMainThread() {
1011 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeMainThread");
1012 const char* kThreadName = "CrBrowserMain";
1013 base::PlatformThread::SetName(kThreadName);
1014 if (main_message_loop_)
1015 main_message_loop_->set_thread_name(kThreadName);
1017 // Register the main thread by instantiating it, but don't call any methods.
1018 main_thread_.reset(
1019 new BrowserThreadImpl(BrowserThread::UI, base::MessageLoop::current()));
1022 int BrowserMainLoop::BrowserThreadsStarted() {
1023 TRACE_EVENT0("startup", "BrowserMainLoop::BrowserThreadsStarted");
1025 #if !defined(OS_IOS)
1026 indexed_db_thread_.reset(new base::Thread("IndexedDB"));
1027 indexed_db_thread_->Start();
1028 #endif
1030 #if !defined(OS_IOS)
1031 HistogramSynchronizer::GetInstance();
1034 // GpuDataManager for in-process initialized in PreCreateThreads.
1035 bool initialize_gpu_data_manager = !UsingInProcessGpu();
1036 #if defined(OS_ANDROID)
1037 // Up the priority of anything that touches with display tasks
1038 // (this thread is UI thread, and io_thread_ is for IPCs).
1039 io_thread_->SetPriority(base::ThreadPriority::DISPLAY);
1040 base::PlatformThread::SetThreadPriority(base::PlatformThread::CurrentHandle(),
1041 base::ThreadPriority::DISPLAY);
1043 // On Android, GLSurface::InitializeOneOff() must be called before
1044 // initalizing the GpuDataManagerImpl as it uses the GL bindings.
1045 // TODO(sievers): Shouldn't need to init full bindings to determine GL
1046 // version/vendor strings. crbug.com/326295
1047 if (initialize_gpu_data_manager) {
1048 // Note InitializeOneOff is not safe either for in-process gpu after
1049 // creating threads, since it may race with the gpu thread.
1050 if (!gfx::GLSurface::InitializeOneOff()) {
1051 LOG(FATAL) << "GLSurface::InitializeOneOff failed";
1054 #endif
1056 if (initialize_gpu_data_manager)
1057 GpuDataManagerImpl::GetInstance()->Initialize();
1059 bool always_uses_gpu = true;
1060 bool established_gpu_channel = false;
1061 #if defined(USE_AURA) || defined(OS_MACOSX)
1062 established_gpu_channel = true;
1063 if (!GpuDataManagerImpl::GetInstance()->CanUseGpuBrowserCompositor() ||
1064 parsed_command_line_.HasSwitch(switches::kDisableGpuEarlyInit)) {
1065 established_gpu_channel = always_uses_gpu = false;
1067 BrowserGpuChannelHostFactory::Initialize(established_gpu_channel);
1068 ImageTransportFactory::Initialize();
1069 #if defined(USE_AURA)
1070 if (aura::Env::GetInstance()) {
1071 aura::Env::GetInstance()->set_context_factory(GetContextFactory());
1073 #endif
1074 #elif defined(OS_ANDROID)
1075 // TODO(crbug.com/439322): This should be set to |true|.
1076 established_gpu_channel = false;
1077 BrowserGpuChannelHostFactory::Initialize(established_gpu_channel);
1078 #endif
1081 TRACE_EVENT0("startup", "BrowserThreadsStarted::Subsystem:AudioMan");
1082 audio_manager_.reset(media::AudioManager::CreateWithHangTimer(
1083 MediaInternals::GetInstance(), io_thread_->task_runner()));
1087 TRACE_EVENT0("startup", "BrowserThreadsStarted::Subsystem:MidiManager");
1088 midi_manager_.reset(media::MidiManager::Create());
1091 #if defined(OS_LINUX) && defined(USE_UDEV)
1092 device_monitor_linux_.reset(new DeviceMonitorLinux());
1093 #elif defined(OS_MACOSX)
1094 device_monitor_mac_.reset(new DeviceMonitorMac());
1095 #endif
1097 #if defined(OS_WIN)
1098 UMA_HISTOGRAM_BOOLEAN("Windows.Win32kRendererLockdown",
1099 IsWin32kRendererLockdownEnabled());
1100 #endif
1101 // RDH needs the IO thread to be created
1103 TRACE_EVENT0("startup",
1104 "BrowserMainLoop::BrowserThreadsStarted:InitResourceDispatcherHost");
1105 resource_dispatcher_host_.reset(new ResourceDispatcherHostImpl());
1108 // MediaStreamManager needs the IO thread to be created.
1110 TRACE_EVENT0("startup",
1111 "BrowserMainLoop::BrowserThreadsStarted:InitMediaStreamManager");
1112 media_stream_manager_.reset(new MediaStreamManager(audio_manager_.get()));
1116 TRACE_EVENT0("startup",
1117 "BrowserMainLoop::BrowserThreadsStarted:InitSpeechRecognition");
1118 speech_recognition_manager_.reset(new SpeechRecognitionManagerImpl(
1119 audio_manager_.get(), media_stream_manager_.get()));
1123 TRACE_EVENT0(
1124 "startup",
1125 "BrowserMainLoop::BrowserThreadsStarted::InitUserInputMonitor");
1126 user_input_monitor_ = media::UserInputMonitor::Create(
1127 io_thread_->message_loop_proxy(), main_thread_->message_loop_proxy());
1131 TRACE_EVENT0("startup",
1132 "BrowserMainLoop::BrowserThreadsStarted::TimeZoneMonitor");
1133 time_zone_monitor_ = TimeZoneMonitor::Create();
1136 // Alert the clipboard class to which threads are allowed to access the
1137 // clipboard:
1138 std::vector<base::PlatformThreadId> allowed_clipboard_threads;
1139 // The current thread is the UI thread.
1140 allowed_clipboard_threads.push_back(base::PlatformThread::CurrentId());
1141 #if defined(OS_WIN)
1142 // On Windows, clipboards are also used on the File or IO threads.
1143 allowed_clipboard_threads.push_back(file_thread_->thread_id());
1144 allowed_clipboard_threads.push_back(io_thread_->thread_id());
1145 #endif
1146 ui::Clipboard::SetAllowedThreads(allowed_clipboard_threads);
1148 // When running the GPU thread in-process, avoid optimistically starting it
1149 // since creating the GPU thread races against creation of the one-and-only
1150 // ChildProcess instance which is created by the renderer thread.
1151 if (GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL) &&
1152 !established_gpu_channel &&
1153 always_uses_gpu &&
1154 !UsingInProcessGpu()) {
1155 TRACE_EVENT_INSTANT0("gpu", "Post task to launch GPU process",
1156 TRACE_EVENT_SCOPE_THREAD);
1157 BrowserThread::PostTask(
1158 BrowserThread::IO, FROM_HERE, base::Bind(
1159 base::IgnoreResult(&GpuProcessHost::Get),
1160 GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED,
1161 CAUSE_FOR_GPU_LAUNCH_BROWSER_STARTUP));
1164 #if defined(OS_MACOSX)
1165 ThemeHelperMac::GetInstance();
1166 SystemHotkeyHelperMac::GetInstance()->DeferredLoadSystemHotkeys();
1167 if (ShouldEnableBootstrapSandbox()) {
1168 TRACE_EVENT0("startup",
1169 "BrowserMainLoop::BrowserThreadsStarted:BootstrapSandbox");
1170 CHECK(GetBootstrapSandbox());
1172 #endif // defined(OS_MACOSX)
1174 #endif // !defined(OS_IOS)
1176 return result_code_;
1179 bool BrowserMainLoop::UsingInProcessGpu() const {
1180 return parsed_command_line_.HasSwitch(switches::kSingleProcess) ||
1181 parsed_command_line_.HasSwitch(switches::kInProcessGPU);
1184 bool BrowserMainLoop::InitializeToolkit() {
1185 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeToolkit");
1186 // TODO(evan): this function is rather subtle, due to the variety
1187 // of intersecting ifdefs we have. To keep it easy to follow, there
1188 // are no #else branches on any #ifs.
1189 // TODO(stevenjb): Move platform specific code into platform specific Parts
1190 // (Need to add InitializeToolkit stage to BrowserParts).
1191 // See also GTK setup in EarlyInitialization, above, and associated comments.
1193 #if defined(OS_WIN)
1194 // Init common control sex.
1195 INITCOMMONCONTROLSEX config;
1196 config.dwSize = sizeof(config);
1197 config.dwICC = ICC_WIN95_CLASSES;
1198 if (!InitCommonControlsEx(&config))
1199 PLOG(FATAL);
1200 #endif
1202 #if defined(USE_AURA)
1204 #if defined(USE_X11)
1205 if (!gfx::GetXDisplay())
1206 return false;
1207 #endif
1209 // Env creates the compositor. Aura widgets need the compositor to be created
1210 // before they can be initialized by the browser.
1211 aura::Env::CreateInstance(true);
1212 #endif // defined(USE_AURA)
1214 if (parts_)
1215 parts_->ToolkitInitialized();
1217 return true;
1220 void BrowserMainLoop::MainMessageLoopRun() {
1221 #if defined(OS_ANDROID)
1222 // Android's main message loop is the Java message loop.
1223 NOTREACHED();
1224 #else
1225 DCHECK(base::MessageLoopForUI::IsCurrent());
1226 if (parameters_.ui_task)
1227 base::MessageLoopForUI::current()->PostTask(FROM_HERE,
1228 *parameters_.ui_task);
1230 base::RunLoop run_loop;
1231 run_loop.Run();
1232 #endif
1235 base::FilePath BrowserMainLoop::GetStartupTraceFileName(
1236 const base::CommandLine& command_line) const {
1237 base::FilePath trace_file = command_line.GetSwitchValuePath(
1238 switches::kTraceStartupFile);
1239 // trace_file = "none" means that startup events will show up for the next
1240 // begin/end tracing (via about:tracing or AutomationProxy::BeginTracing/
1241 // EndTracing, for example).
1242 if (trace_file == base::FilePath().AppendASCII("none"))
1243 return trace_file;
1245 if (trace_file.empty()) {
1246 #if defined(OS_ANDROID)
1247 TracingControllerAndroid::GenerateTracingFilePath(&trace_file);
1248 #else
1249 // Default to saving the startup trace into the current dir.
1250 trace_file = base::FilePath().AppendASCII("chrometrace.log");
1251 #endif
1254 return trace_file;
1257 void BrowserMainLoop::InitStartupTracing(
1258 const base::CommandLine& command_line) {
1259 DCHECK(is_tracing_startup_);
1261 startup_trace_file_ = GetStartupTraceFileName(parsed_command_line_);
1263 std::string delay_str = command_line.GetSwitchValueASCII(
1264 switches::kTraceStartupDuration);
1265 int delay_secs = 5;
1266 if (!delay_str.empty() && !base::StringToInt(delay_str, &delay_secs)) {
1267 DLOG(WARNING) << "Could not parse --" << switches::kTraceStartupDuration
1268 << "=" << delay_str << " defaulting to 5 (secs)";
1269 delay_secs = 5;
1272 startup_trace_timer_.Start(FROM_HERE,
1273 base::TimeDelta::FromSeconds(delay_secs),
1274 this,
1275 &BrowserMainLoop::EndStartupTracing);
1278 void BrowserMainLoop::EndStartupTracing() {
1279 is_tracing_startup_ = false;
1280 TracingController::GetInstance()->DisableRecording(
1281 TracingController::CreateFileSink(
1282 startup_trace_file_,
1283 base::Bind(OnStoppedStartupTracing, startup_trace_file_)));
1286 } // namespace content