Only grant permissions to new extensions from sync if they have the expected version
[chromium-blink-merge.git] / content / browser / browser_main_loop.cc
blob1e39ed4aab0043d1af2633d45b648c7a28b741d9
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/location.h"
10 #include "base/logging.h"
11 #include "base/memory/memory_pressure_monitor.h"
12 #include "base/metrics/field_trial.h"
13 #include "base/metrics/histogram.h"
14 #include "base/pending_task.h"
15 #include "base/power_monitor/power_monitor.h"
16 #include "base/power_monitor/power_monitor_device_source.h"
17 #include "base/process/process_metrics.h"
18 #include "base/profiler/scoped_profile.h"
19 #include "base/run_loop.h"
20 #include "base/single_thread_task_runner.h"
21 #include "base/strings/string_number_conversions.h"
22 #include "base/strings/string_split.h"
23 #include "base/system_monitor/system_monitor.h"
24 #include "base/thread_task_runner_handle.h"
25 #include "base/threading/thread_restrictions.h"
26 #include "base/timer/hi_res_timer_manager.h"
27 #include "base/trace_event/memory_dump_manager.h"
28 #include "base/trace_event/trace_event.h"
29 #include "components/tracing/trace_config_file.h"
30 #include "components/tracing/tracing_switches.h"
31 #include "content/browser/browser_thread_impl.h"
32 #include "content/browser/device_sensors/device_inertial_sensor_service.h"
33 #include "content/browser/dom_storage/dom_storage_area.h"
34 #include "content/browser/download/save_file_manager.h"
35 #include "content/browser/gamepad/gamepad_service.h"
36 #include "content/browser/gpu/browser_gpu_channel_host_factory.h"
37 #include "content/browser/gpu/browser_gpu_memory_buffer_manager.h"
38 #include "content/browser/gpu/compositor_util.h"
39 #include "content/browser/gpu/gpu_data_manager_impl.h"
40 #include "content/browser/gpu/gpu_process_host.h"
41 #include "content/browser/gpu/gpu_process_host_ui_shim.h"
42 #include "content/browser/histogram_synchronizer.h"
43 #include "content/browser/loader/resource_dispatcher_host_impl.h"
44 #include "content/browser/media/media_internals.h"
45 #include "content/browser/mojo/mojo_shell_context.h"
46 #include "content/browser/net/browser_online_state_observer.h"
47 #include "content/browser/renderer_host/media/media_stream_manager.h"
48 #include "content/browser/speech/speech_recognition_manager_impl.h"
49 #include "content/browser/startup_task_runner.h"
50 #include "content/browser/time_zone_monitor.h"
51 #include "content/browser/webui/content_web_ui_controller_factory.h"
52 #include "content/browser/webui/url_data_manager.h"
53 #include "content/common/content_switches_internal.h"
54 #include "content/common/host_discardable_shared_memory_manager.h"
55 #include "content/common/host_shared_bitmap_manager.h"
56 #include "content/public/browser/browser_main_parts.h"
57 #include "content/public/browser/content_browser_client.h"
58 #include "content/public/browser/render_process_host.h"
59 #include "content/public/browser/tracing_controller.h"
60 #include "content/public/common/content_switches.h"
61 #include "content/public/common/main_function_params.h"
62 #include "content/public/common/result_codes.h"
63 #include "crypto/nss_util.h"
64 #include "device/battery/battery_status_service.h"
65 #include "media/audio/audio_manager.h"
66 #include "media/base/media.h"
67 #include "media/base/user_input_monitor.h"
68 #include "media/midi/midi_manager.h"
69 #include "net/base/network_change_notifier.h"
70 #include "net/socket/client_socket_factory.h"
71 #include "net/ssl/ssl_config_service.h"
72 #include "skia/ext/skia_memory_dump_provider.h"
73 #include "ui/base/clipboard/clipboard.h"
75 #if defined(USE_AURA) || (defined(OS_MACOSX) && !defined(OS_IOS))
76 #include "content/browser/compositor/image_transport_factory.h"
77 #endif
79 #if defined(USE_AURA)
80 #include "content/public/browser/context_factory.h"
81 #include "ui/aura/env.h"
82 #endif
84 #if !defined(OS_IOS)
85 #include "content/browser/renderer_host/render_process_host_impl.h"
86 #endif
88 #if defined(OS_ANDROID)
89 #include "base/android/jni_android.h"
90 #include "content/browser/android/browser_startup_controller.h"
91 #include "content/browser/android/browser_surface_texture_manager.h"
92 #include "content/browser/android/in_process_surface_texture_manager.h"
93 #include "content/browser/android/tracing_controller_android.h"
94 #include "content/browser/screen_orientation/screen_orientation_delegate_android.h"
95 #include "content/public/browser/screen_orientation_provider.h"
96 #include "ui/gl/gl_surface.h"
97 #endif
99 #if defined(OS_MACOSX)
100 #include "media/base/mac/avfoundation_glue.h"
101 #endif
103 #if defined(OS_MACOSX) && !defined(OS_IOS)
104 #include "base/memory/memory_pressure_monitor_mac.h"
105 #include "content/browser/bootstrap_sandbox_mac.h"
106 #include "content/browser/browser_io_surface_manager_mac.h"
107 #include "content/browser/cocoa/system_hotkey_helper_mac.h"
108 #include "content/browser/compositor/browser_compositor_view_mac.h"
109 #include "content/browser/in_process_io_surface_manager_mac.h"
110 #include "content/browser/theme_helper_mac.h"
111 #endif
113 #if defined(USE_OZONE)
114 #include "ui/ozone/public/client_native_pixmap_factory.h"
115 #include "ui/ozone/public/ozone_platform.h"
116 #endif
118 #if defined(OS_WIN)
119 #include <windows.h>
120 #include <commctrl.h>
121 #include <shellapi.h>
123 #include "base/memory/memory_pressure_monitor_win.h"
124 #include "content/browser/system_message_window_win.h"
125 #include "content/common/sandbox_win.h"
126 #include "net/base/winsock_init.h"
127 #include "ui/base/l10n/l10n_util_win.h"
128 #endif
130 #if defined(OS_CHROMEOS)
131 #include "base/memory/memory_pressure_monitor_chromeos.h"
132 #include "chromeos/chromeos_switches.h"
133 #endif
135 #if defined(USE_GLIB)
136 #include <glib-object.h>
137 #endif
139 #if defined(OS_LINUX) && defined(USE_UDEV)
140 #include "content/browser/device_monitor_udev.h"
141 #elif defined(OS_MACOSX) && !defined(OS_IOS)
142 #include "content/browser/device_monitor_mac.h"
143 #endif
145 #if defined(OS_POSIX) && !defined(OS_MACOSX)
146 #include "content/browser/renderer_host/render_sandbox_host_linux.h"
147 #include "content/browser/zygote_host/zygote_host_impl_linux.h"
148 #include "sandbox/linux/suid/client/setuid_sandbox_host.h"
149 #endif
151 #if defined(ENABLE_PLUGINS)
152 #include "content/browser/plugin_service_impl.h"
153 #endif
155 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
156 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
157 #endif
159 #if defined(USE_X11)
160 #include "ui/gfx/x/x11_connection.h"
161 #include "ui/gfx/x/x11_types.h"
162 #endif
164 // One of the linux specific headers defines this as a macro.
165 #ifdef DestroyAll
166 #undef DestroyAll
167 #endif
169 namespace content {
170 namespace {
172 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
173 void SetupSandbox(const base::CommandLine& parsed_command_line) {
174 TRACE_EVENT0("startup", "SetupSandbox");
175 base::FilePath sandbox_binary;
177 scoped_ptr<sandbox::SetuidSandboxHost> setuid_sandbox_host(
178 sandbox::SetuidSandboxHost::Create());
180 const bool want_setuid_sandbox =
181 !parsed_command_line.HasSwitch(switches::kNoSandbox) &&
182 !parsed_command_line.HasSwitch(switches::kDisableSetuidSandbox) &&
183 !setuid_sandbox_host->IsDisabledViaEnvironment();
185 static const char no_suid_error[] =
186 "Running without the SUID sandbox! See "
187 "https://code.google.com/p/chromium/wiki/LinuxSUIDSandboxDevelopment "
188 "for more information on developing with the sandbox on.";
189 if (want_setuid_sandbox) {
190 sandbox_binary = setuid_sandbox_host->GetSandboxBinaryPath();
191 if (sandbox_binary.empty()) {
192 // This needs to be fatal. Talk to security@chromium.org if you feel
193 // otherwise.
194 LOG(FATAL) << no_suid_error;
196 } else {
197 LOG(ERROR) << no_suid_error;
200 // Tickle the sandbox host and zygote host so they fork now.
201 RenderSandboxHostLinux::GetInstance()->Init();
202 ZygoteHostImpl::GetInstance()->Init(sandbox_binary.value());
204 #endif
206 #if defined(USE_GLIB)
207 static void GLibLogHandler(const gchar* log_domain,
208 GLogLevelFlags log_level,
209 const gchar* message,
210 gpointer userdata) {
211 if (!log_domain)
212 log_domain = "<unknown>";
213 if (!message)
214 message = "<no message>";
216 if (strstr(message, "Unable to retrieve the file info for")) {
217 LOG(ERROR) << "GTK File code error: " << message;
218 } else if (strstr(message, "Could not find the icon") &&
219 strstr(log_domain, "Gtk")) {
220 LOG(ERROR) << "GTK icon error: " << message;
221 } else if (strstr(message, "Theme file for default has no") ||
222 strstr(message, "Theme directory") ||
223 strstr(message, "theme pixmap") ||
224 strstr(message, "locate theme engine")) {
225 LOG(ERROR) << "GTK theme error: " << message;
226 } else if (strstr(message, "Unable to create Ubuntu Menu Proxy") &&
227 strstr(log_domain, "<unknown>")) {
228 LOG(ERROR) << "GTK menu proxy create failed";
229 } else if (strstr(message, "Out of memory") &&
230 strstr(log_domain, "<unknown>")) {
231 LOG(ERROR) << "DBus call timeout or out of memory: "
232 << "http://crosbug.com/15496";
233 } else if (strstr(message, "Could not connect: Connection refused") &&
234 strstr(log_domain, "<unknown>")) {
235 LOG(ERROR) << "DConf settings backend could not connect to session bus: "
236 << "http://crbug.com/179797";
237 } else if (strstr(message, "Attempting to store changes into") ||
238 strstr(message, "Attempting to set the permissions of")) {
239 LOG(ERROR) << message << " (http://bugs.chromium.org/161366)";
240 } else if (strstr(message, "drawable is not a native X11 window")) {
241 LOG(ERROR) << message << " (http://bugs.chromium.org/329991)";
242 } else if (strstr(message, "Cannot do system-bus activation with no user")) {
243 LOG(ERROR) << message << " (http://crbug.com/431005)";
244 } else if (strstr(message, "deprecated")) {
245 LOG(ERROR) << message;
246 } else {
247 LOG(DFATAL) << log_domain << ": " << message;
251 static void SetUpGLibLogHandler() {
252 // Register GLib-handled assertions to go through our logging system.
253 const char* kLogDomains[] = { NULL, "Gtk", "Gdk", "GLib", "GLib-GObject" };
254 for (size_t i = 0; i < arraysize(kLogDomains); i++) {
255 g_log_set_handler(kLogDomains[i],
256 static_cast<GLogLevelFlags>(G_LOG_FLAG_RECURSION |
257 G_LOG_FLAG_FATAL |
258 G_LOG_LEVEL_ERROR |
259 G_LOG_LEVEL_CRITICAL |
260 G_LOG_LEVEL_WARNING),
261 GLibLogHandler,
262 NULL);
265 #endif
267 void OnStoppedStartupTracing(const base::FilePath& trace_file) {
268 VLOG(0) << "Completed startup tracing to " << trace_file.value();
271 // Disable optimizations for this block of functions so the compiler doesn't
272 // merge them all together. This makes it possible to tell what thread was
273 // unresponsive by inspecting the callstack.
274 MSVC_DISABLE_OPTIMIZE()
275 MSVC_PUSH_DISABLE_WARNING(4748)
277 NOINLINE void ResetThread_DB(scoped_ptr<BrowserProcessSubThread> thread) {
278 volatile int inhibit_comdat = __LINE__;
279 ALLOW_UNUSED_LOCAL(inhibit_comdat);
280 thread.reset();
283 NOINLINE void ResetThread_FILE(scoped_ptr<BrowserProcessSubThread> thread) {
284 volatile int inhibit_comdat = __LINE__;
285 ALLOW_UNUSED_LOCAL(inhibit_comdat);
286 thread.reset();
289 NOINLINE void ResetThread_FILE_USER_BLOCKING(
290 scoped_ptr<BrowserProcessSubThread> thread) {
291 volatile int inhibit_comdat = __LINE__;
292 ALLOW_UNUSED_LOCAL(inhibit_comdat);
293 thread.reset();
296 NOINLINE void ResetThread_PROCESS_LAUNCHER(
297 scoped_ptr<BrowserProcessSubThread> thread) {
298 volatile int inhibit_comdat = __LINE__;
299 ALLOW_UNUSED_LOCAL(inhibit_comdat);
300 thread.reset();
303 NOINLINE void ResetThread_CACHE(scoped_ptr<BrowserProcessSubThread> thread) {
304 volatile int inhibit_comdat = __LINE__;
305 ALLOW_UNUSED_LOCAL(inhibit_comdat);
306 thread.reset();
309 NOINLINE void ResetThread_IO(scoped_ptr<BrowserProcessSubThread> thread) {
310 volatile int inhibit_comdat = __LINE__;
311 ALLOW_UNUSED_LOCAL(inhibit_comdat);
312 thread.reset();
315 #if !defined(OS_IOS)
316 NOINLINE void ResetThread_IndexedDb(scoped_ptr<base::Thread> thread) {
317 volatile int inhibit_comdat = __LINE__;
318 ALLOW_UNUSED_LOCAL(inhibit_comdat);
319 thread.reset();
321 #endif
323 MSVC_POP_WARNING()
324 MSVC_ENABLE_OPTIMIZE();
326 #if defined(OS_WIN)
327 // Creates a memory pressure monitor using automatic thresholds, or those
328 // specified on the command-line. Ownership is passed to the caller.
329 base::win::MemoryPressureMonitor* CreateWinMemoryPressureMonitor(
330 const base::CommandLine& parsed_command_line) {
331 std::vector<std::string> thresholds = base::SplitString(
332 parsed_command_line.GetSwitchValueASCII(
333 switches::kMemoryPressureThresholdsMb),
334 ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
336 int moderate_threshold_mb = 0;
337 int critical_threshold_mb = 0;
338 if (thresholds.size() == 2 &&
339 base::StringToInt(thresholds[0], &moderate_threshold_mb) &&
340 base::StringToInt(thresholds[1], &critical_threshold_mb) &&
341 moderate_threshold_mb >= critical_threshold_mb &&
342 critical_threshold_mb >= 0) {
343 return new base::win::MemoryPressureMonitor(moderate_threshold_mb,
344 critical_threshold_mb);
347 // In absence of valid switches use the automatic defaults.
348 return new base::win::MemoryPressureMonitor();
350 #endif // defined(OS_WIN)
352 } // namespace
354 // The currently-running BrowserMainLoop. There can be one or zero.
355 BrowserMainLoop* g_current_browser_main_loop = NULL;
357 // For measuring memory usage after each task. Behind a command line flag.
358 class BrowserMainLoop::MemoryObserver : public base::MessageLoop::TaskObserver {
359 public:
360 MemoryObserver() {}
361 ~MemoryObserver() override {}
363 void WillProcessTask(const base::PendingTask& pending_task) override {}
365 void DidProcessTask(const base::PendingTask& pending_task) override {
366 #if !defined(OS_IOS) // No ProcessMetrics on IOS.
367 scoped_ptr<base::ProcessMetrics> process_metrics(
368 base::ProcessMetrics::CreateProcessMetrics(
369 #if defined(OS_MACOSX)
370 base::GetCurrentProcessHandle(), NULL));
371 #else
372 base::GetCurrentProcessHandle()));
373 #endif
374 size_t private_bytes;
375 process_metrics->GetMemoryBytes(&private_bytes, NULL);
376 LOCAL_HISTOGRAM_MEMORY_KB("Memory.BrowserUsed", private_bytes >> 10);
377 #endif
379 private:
380 DISALLOW_COPY_AND_ASSIGN(MemoryObserver);
384 // BrowserMainLoop construction / destruction =============================
386 BrowserMainLoop* BrowserMainLoop::GetInstance() {
387 DCHECK_CURRENTLY_ON(BrowserThread::UI);
388 return g_current_browser_main_loop;
391 BrowserMainLoop::BrowserMainLoop(const MainFunctionParams& parameters)
392 : parameters_(parameters),
393 parsed_command_line_(parameters.command_line),
394 result_code_(RESULT_CODE_NORMAL_EXIT),
395 created_threads_(false),
396 // ContentMainRunner should have enabled tracing of the browser process
397 // when kTraceStartup or kTraceConfigFile is in the command line.
398 is_tracing_startup_for_duration_(
399 parameters.command_line.HasSwitch(switches::kTraceStartup) ||
400 (tracing::TraceConfigFile::GetInstance()->IsEnabled() &&
401 tracing::TraceConfigFile::GetInstance()->GetStartupDuration() > 0)) {
402 DCHECK(!g_current_browser_main_loop);
403 g_current_browser_main_loop = this;
406 BrowserMainLoop::~BrowserMainLoop() {
407 DCHECK_EQ(this, g_current_browser_main_loop);
408 #if !defined(OS_IOS)
409 ui::Clipboard::DestroyClipboardForCurrentThread();
410 #endif // !defined(OS_IOS)
411 g_current_browser_main_loop = NULL;
414 void BrowserMainLoop::Init() {
415 TRACE_EVENT0("startup", "BrowserMainLoop::Init");
416 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::Init");
418 parts_.reset(
419 GetContentClient()->browser()->CreateBrowserMainParts(parameters_));
422 // BrowserMainLoop stages ==================================================
424 void BrowserMainLoop::EarlyInitialization() {
425 TRACE_EVENT0("startup", "BrowserMainLoop::EarlyInitialization");
426 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::EarlyInitialization");
428 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
429 // No thread should be created before this call, as SetupSandbox()
430 // will end-up using fork().
431 SetupSandbox(parsed_command_line_);
432 #endif
434 #if defined(USE_X11)
435 if (UsingInProcessGpu()) {
436 if (!gfx::InitializeThreadedX11()) {
437 LOG(ERROR) << "Failed to put Xlib into threaded mode.";
440 #endif
442 // GLib's spawning of new processes is buggy, so it's important that at this
443 // point GLib does not need to start DBUS. Chrome should always start with
444 // DBUS_SESSION_BUS_ADDRESS properly set. See crbug.com/309093.
445 #if defined(USE_GLIB)
446 // g_type_init will be deprecated in 2.36. 2.35 is the development
447 // version for 2.36, hence do not call g_type_init starting 2.35.
448 // http://developer.gnome.org/gobject/unstable/gobject-Type-Information.html#g-type-init
449 #if !GLIB_CHECK_VERSION(2, 35, 0)
450 // GLib type system initialization. Needed at least for gconf,
451 // used in net/proxy/proxy_config_service_linux.cc. Most likely
452 // this is superfluous as gtk_init() ought to do this. It's
453 // definitely harmless, so retained as a reminder of this
454 // requirement for gconf.
455 g_type_init();
456 #endif
458 SetUpGLibLogHandler();
459 #endif
461 if (parts_)
462 parts_->PreEarlyInitialization();
464 #if defined(OS_MACOSX)
465 // We use quite a few file descriptors for our IPC, and the default limit on
466 // the Mac is low (256), so bump it up.
467 base::SetFdLimit(1024);
468 #endif
470 #if defined(OS_WIN)
471 net::EnsureWinsockInit();
472 #endif
474 #if defined(USE_NSS_CERTS) || !defined(USE_OPENSSL)
475 // We want to be sure to init NSPR on the main thread.
476 crypto::EnsureNSPRInit();
477 #endif
479 #if !defined(OS_IOS)
480 if (parsed_command_line_.HasSwitch(switches::kRendererProcessLimit)) {
481 std::string limit_string = parsed_command_line_.GetSwitchValueASCII(
482 switches::kRendererProcessLimit);
483 size_t process_limit;
484 if (base::StringToSizeT(limit_string, &process_limit)) {
485 RenderProcessHost::SetMaxRendererProcessCount(process_limit);
488 #endif // !defined(OS_IOS)
490 // TODO(boliu): kSingleProcess check is a temporary workaround for
491 // in-process Android WebView. crbug.com/503724 tracks proper fix.
492 if (!parsed_command_line_.HasSwitch(switches::kSingleProcess)) {
493 base::DiscardableMemoryAllocator::SetInstance(
494 HostDiscardableSharedMemoryManager::current());
497 if (parts_)
498 parts_->PostEarlyInitialization();
501 void BrowserMainLoop::PreMainMessageLoopStart() {
502 if (parts_) {
503 TRACE_EVENT0("startup",
504 "BrowserMainLoop::MainMessageLoopStart:PreMainMessageLoopStart");
505 parts_->PreMainMessageLoopStart();
508 #if defined(OS_WIN)
509 // If we're running tests (ui_task is non-null), then the ResourceBundle
510 // has already been initialized.
511 if (!parameters_.ui_task) {
512 // Override the configured locale with the user's preferred UI language.
513 l10n_util::OverrideLocaleWithUILanguageList();
515 #endif
518 void BrowserMainLoop::MainMessageLoopStart() {
519 // DO NOT add more code here. Use PreMainMessageLoopStart() above or
520 // PostMainMessageLoopStart() below.
522 TRACE_EVENT0("startup", "BrowserMainLoop::MainMessageLoopStart");
523 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::MainMessageLoopStart");
525 // Create a MessageLoop if one does not already exist for the current thread.
526 if (!base::MessageLoop::current())
527 main_message_loop_.reset(new base::MessageLoopForUI);
529 InitializeMainThread();
532 void BrowserMainLoop::PostMainMessageLoopStart() {
534 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SystemMonitor");
535 system_monitor_.reset(new base::SystemMonitor);
538 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:PowerMonitor");
539 scoped_ptr<base::PowerMonitorSource> power_monitor_source(
540 new base::PowerMonitorDeviceSource());
541 power_monitor_.reset(new base::PowerMonitor(power_monitor_source.Pass()));
544 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:HighResTimerManager");
545 hi_res_timer_manager_.reset(new base::HighResolutionTimerManager);
548 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:NetworkChangeNotifier");
549 network_change_notifier_.reset(net::NetworkChangeNotifier::Create());
552 #if !defined(OS_IOS)
554 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MediaFeatures");
555 media::InitializeMediaLibrary();
558 TRACE_EVENT0("startup",
559 "BrowserMainLoop::Subsystem:ContentWebUIController");
560 WebUIControllerFactory::RegisterFactory(
561 ContentWebUIControllerFactory::GetInstance());
565 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:OnlineStateObserver");
566 online_state_observer_.reset(new BrowserOnlineStateObserver);
570 system_stats_monitor_.reset(
571 new base::trace_event::TraceEventSystemStatsMonitor(
572 base::ThreadTaskRunnerHandle::Get()));
574 #endif // !defined(OS_IOS)
576 #if defined(OS_WIN)
577 system_message_window_.reset(new SystemMessageWindowWin);
578 #endif
580 if (parts_)
581 parts_->PostMainMessageLoopStart();
583 #if !defined(OS_IOS)
584 // Start tracing to a file if needed. Only do this after starting the main
585 // message loop to avoid calling MessagePumpForUI::ScheduleWork() before
586 // MessagePumpForUI::Start() as it will crash the browser.
587 if (is_tracing_startup_for_duration_) {
588 TRACE_EVENT0("startup", "BrowserMainLoop::InitStartupTracingForDuration");
589 InitStartupTracingForDuration(parsed_command_line_);
591 #endif // !defined(OS_IOS)
593 #if defined(OS_ANDROID)
595 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SurfaceTextureManager");
596 if (parsed_command_line_.HasSwitch(switches::kSingleProcess)) {
597 SurfaceTextureManager::SetInstance(
598 InProcessSurfaceTextureManager::GetInstance());
599 } else {
600 SurfaceTextureManager::SetInstance(
601 BrowserSurfaceTextureManager::GetInstance());
605 if (!parsed_command_line_.HasSwitch(
606 switches::kDisableScreenOrientationLock)) {
607 TRACE_EVENT0("startup",
608 "BrowserMainLoop::Subsystem:ScreenOrientationProvider");
609 screen_orientation_delegate_.reset(
610 new ScreenOrientationDelegateAndroid());
611 ScreenOrientationProvider::SetDelegate(screen_orientation_delegate_.get());
613 #endif
615 #if defined(OS_MACOSX) && !defined(OS_IOS)
617 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:IOSurfaceManager");
618 if (parsed_command_line_.HasSwitch(switches::kSingleProcess)) {
619 IOSurfaceManager::SetInstance(InProcessIOSurfaceManager::GetInstance());
620 } else {
621 IOSurfaceManager::SetInstance(BrowserIOSurfaceManager::GetInstance());
624 #endif
626 #if defined(USE_OZONE)
627 client_native_pixmap_factory_ = ui::ClientNativePixmapFactory::Create();
628 ui::ClientNativePixmapFactory::SetInstance(
629 client_native_pixmap_factory_.get());
630 ui::ClientNativePixmapFactory::GetInstance()->Initialize(
631 ui::OzonePlatform::GetInstance()->OpenClientNativePixmapDevice());
632 #endif
634 if (parsed_command_line_.HasSwitch(switches::kMemoryMetrics)) {
635 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MemoryObserver");
636 memory_observer_.reset(new MemoryObserver());
637 base::MessageLoop::current()->AddTaskObserver(memory_observer_.get());
640 if (parsed_command_line_.HasSwitch(
641 switches::kEnableAggressiveDOMStorageFlushing)) {
642 TRACE_EVENT0("startup",
643 "BrowserMainLoop::Subsystem:EnableAggressiveCommitDelay");
644 DOMStorageArea::EnableAggressiveCommitDelay();
647 // Enable memory-infra dump providers.
648 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
649 HostSharedBitmapManager::current());
650 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
651 skia::SkiaMemoryDumpProvider::GetInstance());
653 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
654 trace_memory_controller_.reset(new base::trace_event::TraceMemoryController(
655 base::MessageLoop::current()->task_runner(),
656 ::HeapProfilerWithPseudoStackStart, ::HeapProfilerStop,
657 ::GetHeapProfile));
658 #endif
661 int BrowserMainLoop::PreCreateThreads() {
662 if (parts_) {
663 TRACE_EVENT0("startup",
664 "BrowserMainLoop::CreateThreads:PreCreateThreads");
665 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::PreCreateThreads");
667 result_code_ = parts_->PreCreateThreads();
670 // TODO(chrisha): Abstract away this construction mess to a helper function,
671 // once MemoryPressureMonitor is made a concrete class.
672 #if defined(OS_CHROMEOS)
673 if (chromeos::switches::MemoryPressureHandlingEnabled()) {
674 memory_pressure_monitor_.reset(new base::chromeos::MemoryPressureMonitor(
675 chromeos::switches::GetMemoryPressureThresholds()));
677 #elif defined(OS_MACOSX) && !defined(OS_IOS)
678 memory_pressure_monitor_.reset(new base::mac::MemoryPressureMonitor());
679 #elif defined(OS_WIN)
680 memory_pressure_monitor_.reset(CreateWinMemoryPressureMonitor(
681 parsed_command_line_));
682 #endif
684 #if defined(ENABLE_PLUGINS)
685 // Prior to any processing happening on the io thread, we create the
686 // plugin service as it is predominantly used from the io thread,
687 // but must be created on the main thread. The service ctor is
688 // inexpensive and does not invoke the io_thread() accessor.
690 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads:PluginService");
691 PluginService::GetInstance()->Init();
693 #endif
695 #if defined(OS_MACOSX)
697 // Initialize AVFoundation if supported, for audio and video.
698 TRACE_EVENT0("startup",
699 "BrowserMainLoop::CreateThreads:InitializeAVFoundation");
700 AVFoundationGlue::InitializeAVFoundation();
702 #endif
704 // 1) Need to initialize in-process GpuDataManager before creating threads.
705 // It's unsafe to append the gpu command line switches to the global
706 // CommandLine::ForCurrentProcess object after threads are created.
707 // 2) Must be after parts_->PreCreateThreads to pick up chrome://flags.
708 GpuDataManagerImpl::GetInstance()->Initialize();
710 #if !defined(OS_IOS) && (!defined(GOOGLE_CHROME_BUILD) || defined(OS_ANDROID))
711 // Single-process is an unsupported and not fully tested mode, so
712 // don't enable it for official Chrome builds (except on Android).
713 if (parsed_command_line_.HasSwitch(switches::kSingleProcess))
714 RenderProcessHost::SetRunRendererInProcess(true);
715 #endif
717 return result_code_;
720 void BrowserMainLoop::CreateStartupTasks() {
721 TRACE_EVENT0("startup", "BrowserMainLoop::CreateStartupTasks");
722 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::CreateStartupTasks");
724 // First time through, we really want to create all the tasks
725 if (!startup_task_runner_.get()) {
726 #if defined(OS_ANDROID)
727 startup_task_runner_ = make_scoped_ptr(
728 new StartupTaskRunner(base::Bind(&BrowserStartupComplete),
729 base::ThreadTaskRunnerHandle::Get()));
730 #else
731 startup_task_runner_ = make_scoped_ptr(
732 new StartupTaskRunner(base::Callback<void(int)>(),
733 base::ThreadTaskRunnerHandle::Get()));
734 #endif
735 StartupTask pre_create_threads =
736 base::Bind(&BrowserMainLoop::PreCreateThreads, base::Unretained(this));
737 startup_task_runner_->AddTask(pre_create_threads);
739 StartupTask create_threads =
740 base::Bind(&BrowserMainLoop::CreateThreads, base::Unretained(this));
741 startup_task_runner_->AddTask(create_threads);
743 StartupTask browser_thread_started = base::Bind(
744 &BrowserMainLoop::BrowserThreadsStarted, base::Unretained(this));
745 startup_task_runner_->AddTask(browser_thread_started);
747 StartupTask pre_main_message_loop_run = base::Bind(
748 &BrowserMainLoop::PreMainMessageLoopRun, base::Unretained(this));
749 startup_task_runner_->AddTask(pre_main_message_loop_run);
751 #if defined(OS_ANDROID)
752 if (BrowserMayStartAsynchronously()) {
753 startup_task_runner_->StartRunningTasksAsync();
755 #endif
757 #if defined(OS_ANDROID)
758 if (!BrowserMayStartAsynchronously()) {
759 // A second request for asynchronous startup can be ignored, so
760 // StartupRunningTasksAsync is only called first time through. If, however,
761 // this is a request for synchronous startup then it must override any
762 // previous call for async startup, so we call RunAllTasksNow()
763 // unconditionally.
764 startup_task_runner_->RunAllTasksNow();
766 #else
767 startup_task_runner_->RunAllTasksNow();
768 #endif
771 int BrowserMainLoop::CreateThreads() {
772 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads");
773 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::CreateThreads");
775 base::Thread::Options io_message_loop_options;
776 io_message_loop_options.message_loop_type = base::MessageLoop::TYPE_IO;
777 base::Thread::Options ui_message_loop_options;
778 ui_message_loop_options.message_loop_type = base::MessageLoop::TYPE_UI;
780 // Start threads in the order they occur in the BrowserThread::ID
781 // enumeration, except for BrowserThread::UI which is the main
782 // thread.
784 // Must be size_t so we can increment it.
785 for (size_t thread_id = BrowserThread::UI + 1;
786 thread_id < BrowserThread::ID_COUNT;
787 ++thread_id) {
788 scoped_ptr<BrowserProcessSubThread>* thread_to_start = NULL;
789 base::Thread::Options options;
791 switch (thread_id) {
792 case BrowserThread::DB:
793 TRACE_EVENT_BEGIN1("startup",
794 "BrowserMainLoop::CreateThreads:start",
795 "Thread", "BrowserThread::DB");
796 thread_to_start = &db_thread_;
797 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
798 break;
799 case BrowserThread::FILE_USER_BLOCKING:
800 TRACE_EVENT_BEGIN1("startup",
801 "BrowserMainLoop::CreateThreads:start",
802 "Thread", "BrowserThread::FILE_USER_BLOCKING");
803 thread_to_start = &file_user_blocking_thread_;
804 break;
805 case BrowserThread::FILE:
806 TRACE_EVENT_BEGIN1("startup",
807 "BrowserMainLoop::CreateThreads:start",
808 "Thread", "BrowserThread::FILE");
809 thread_to_start = &file_thread_;
810 #if defined(OS_WIN)
811 // On Windows, the FILE thread needs to be have a UI message loop
812 // which pumps messages in such a way that Google Update can
813 // communicate back to us.
814 options = ui_message_loop_options;
815 #else
816 options = io_message_loop_options;
817 #endif
818 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
819 break;
820 case BrowserThread::PROCESS_LAUNCHER:
821 TRACE_EVENT_BEGIN1("startup",
822 "BrowserMainLoop::CreateThreads:start",
823 "Thread", "BrowserThread::PROCESS_LAUNCHER");
824 thread_to_start = &process_launcher_thread_;
825 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
826 break;
827 case BrowserThread::CACHE:
828 TRACE_EVENT_BEGIN1("startup",
829 "BrowserMainLoop::CreateThreads:start",
830 "Thread", "BrowserThread::CACHE");
831 thread_to_start = &cache_thread_;
832 options = io_message_loop_options;
833 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
834 break;
835 case BrowserThread::IO:
836 TRACE_EVENT_BEGIN1("startup",
837 "BrowserMainLoop::CreateThreads:start",
838 "Thread", "BrowserThread::IO");
839 thread_to_start = &io_thread_;
840 options = io_message_loop_options;
841 #if defined(OS_ANDROID)
842 // Up the priority of the |io_thread_| as some of its IPCs relate to
843 // display tasks.
844 options.priority = base::ThreadPriority::DISPLAY;
845 #endif
846 break;
847 case BrowserThread::UI:
848 case BrowserThread::ID_COUNT:
849 default:
850 NOTREACHED();
851 break;
854 BrowserThread::ID id = static_cast<BrowserThread::ID>(thread_id);
856 if (thread_to_start) {
857 (*thread_to_start).reset(new BrowserProcessSubThread(id));
858 if (!(*thread_to_start)->StartWithOptions(options)) {
859 LOG(FATAL) << "Failed to start the browser thread: id == " << id;
861 } else {
862 NOTREACHED();
865 TRACE_EVENT_END0("startup", "BrowserMainLoop::CreateThreads:start");
867 created_threads_ = true;
868 return result_code_;
871 int BrowserMainLoop::PreMainMessageLoopRun() {
872 if (parts_) {
873 TRACE_EVENT0("startup",
874 "BrowserMainLoop::CreateThreads:PreMainMessageLoopRun");
875 TRACK_SCOPED_REGION(
876 "Startup", "BrowserMainLoop::PreMainMessageLoopRun");
878 parts_->PreMainMessageLoopRun();
881 // If the UI thread blocks, the whole UI is unresponsive.
882 // Do not allow disk IO from the UI thread.
883 base::ThreadRestrictions::SetIOAllowed(false);
884 base::ThreadRestrictions::DisallowWaiting();
885 return result_code_;
888 void BrowserMainLoop::RunMainMessageLoopParts() {
889 TRACE_EVENT_BEGIN_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
891 bool ran_main_loop = false;
892 if (parts_)
893 ran_main_loop = parts_->MainMessageLoopRun(&result_code_);
895 if (!ran_main_loop)
896 MainMessageLoopRun();
898 TRACE_EVENT_END_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
901 void BrowserMainLoop::ShutdownThreadsAndCleanUp() {
902 if (!created_threads_) {
903 // Called early, nothing to do
904 return;
906 TRACE_EVENT0("shutdown", "BrowserMainLoop::ShutdownThreadsAndCleanUp");
908 // Teardown may start in PostMainMessageLoopRun, and during teardown we
909 // need to be able to perform IO.
910 base::ThreadRestrictions::SetIOAllowed(true);
911 BrowserThread::PostTask(
912 BrowserThread::IO, FROM_HERE,
913 base::Bind(base::IgnoreResult(&base::ThreadRestrictions::SetIOAllowed),
914 true));
916 mojo_shell_context_.reset();
918 #if !defined(OS_IOS)
919 if (RenderProcessHost::run_renderer_in_process())
920 RenderProcessHostImpl::ShutDownInProcessRenderer();
921 #endif
923 if (parts_) {
924 TRACE_EVENT0("shutdown",
925 "BrowserMainLoop::Subsystem:PostMainMessageLoopRun");
926 parts_->PostMainMessageLoopRun();
929 #if defined(USE_AURA)
930 aura::Env::DeleteInstance();
931 #endif
933 trace_memory_controller_.reset();
934 system_stats_monitor_.reset();
936 #if !defined(OS_IOS)
937 // Destroying the GpuProcessHostUIShims on the UI thread posts a task to
938 // delete related objects on the GPU thread. This must be done before
939 // stopping the GPU thread. The GPU thread will close IPC channels to renderer
940 // processes so this has to happen before stopping the IO thread.
942 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUProcessHostShim");
943 GpuProcessHostUIShim::DestroyAll();
945 // Cancel pending requests and prevent new requests.
946 if (resource_dispatcher_host_) {
947 TRACE_EVENT0("shutdown",
948 "BrowserMainLoop::Subsystem:ResourceDispatcherHost");
949 resource_dispatcher_host_.get()->Shutdown();
952 memory_pressure_monitor_.reset();
954 #if defined(OS_MACOSX)
955 BrowserCompositorMac::DisableRecyclingForShutdown();
956 #endif
958 #if defined(USE_AURA) || defined(OS_MACOSX)
960 TRACE_EVENT0("shutdown",
961 "BrowserMainLoop::Subsystem:ImageTransportFactory");
962 ImageTransportFactory::Terminate();
964 #endif
966 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
967 ZygoteHostImpl::GetInstance()->TearDownAfterLastChild();
968 #endif // defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
970 // The device monitors are using |system_monitor_| as dependency, so delete
971 // them before |system_monitor_| goes away.
972 // On Mac and windows, the monitor needs to be destroyed on the same thread
973 // as they were created. On Linux, the monitor will be deleted when IO thread
974 // goes away.
975 #if defined(OS_WIN)
976 system_message_window_.reset();
977 #elif defined(OS_MACOSX)
978 device_monitor_mac_.reset();
979 #endif
980 #endif // !defined(OS_IOS)
982 // Must be size_t so we can subtract from it.
983 for (size_t thread_id = BrowserThread::ID_COUNT - 1;
984 thread_id >= (BrowserThread::UI + 1);
985 --thread_id) {
986 // Find the thread object we want to stop. Looping over all valid
987 // BrowserThread IDs and DCHECKing on a missing case in the switch
988 // statement helps avoid a mismatch between this code and the
989 // BrowserThread::ID enumeration.
991 // The destruction order is the reverse order of occurrence in the
992 // BrowserThread::ID list. The rationale for the order is as
993 // follows (need to be filled in a bit):
996 // - The IO thread is the only user of the CACHE thread.
998 // - The PROCESS_LAUNCHER thread must be stopped after IO in case
999 // the IO thread posted a task to terminate a process on the
1000 // process launcher thread.
1002 // - (Not sure why DB stops last.)
1003 switch (thread_id) {
1004 case BrowserThread::DB: {
1005 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DBThread");
1006 ResetThread_DB(db_thread_.Pass());
1007 break;
1009 case BrowserThread::FILE: {
1010 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:FileThread");
1011 #if !defined(OS_IOS)
1012 // Clean up state that lives on or uses the file_thread_ before
1013 // it goes away.
1014 if (resource_dispatcher_host_)
1015 resource_dispatcher_host_.get()->save_file_manager()->Shutdown();
1016 #endif // !defined(OS_IOS)
1017 ResetThread_FILE(file_thread_.Pass());
1018 break;
1020 case BrowserThread::FILE_USER_BLOCKING: {
1021 TRACE_EVENT0("shutdown",
1022 "BrowserMainLoop::Subsystem:FileUserBlockingThread");
1023 ResetThread_FILE_USER_BLOCKING(file_user_blocking_thread_.Pass());
1024 break;
1026 case BrowserThread::PROCESS_LAUNCHER: {
1027 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:LauncherThread");
1028 ResetThread_PROCESS_LAUNCHER(process_launcher_thread_.Pass());
1029 break;
1031 case BrowserThread::CACHE: {
1032 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:CacheThread");
1033 ResetThread_CACHE(cache_thread_.Pass());
1034 break;
1036 case BrowserThread::IO: {
1037 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IOThread");
1038 ResetThread_IO(io_thread_.Pass());
1039 break;
1041 case BrowserThread::UI:
1042 case BrowserThread::ID_COUNT:
1043 default:
1044 NOTREACHED();
1045 break;
1049 #if !defined(OS_IOS)
1051 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IndexedDBThread");
1052 ResetThread_IndexedDb(indexed_db_thread_.Pass());
1054 #endif
1056 // Close the blocking I/O pool after the other threads. Other threads such
1057 // as the I/O thread may need to schedule work like closing files or flushing
1058 // data during shutdown, so the blocking pool needs to be available. There
1059 // may also be slow operations pending that will blcok shutdown, so closing
1060 // it here (which will block until required operations are complete) gives
1061 // more head start for those operations to finish.
1063 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:ThreadPool");
1064 BrowserThreadImpl::ShutdownThreadPool();
1067 #if !defined(OS_IOS)
1068 // Must happen after the IO thread is shutdown since this may be accessed from
1069 // it.
1071 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUChannelFactory");
1072 if (BrowserGpuChannelHostFactory::instance())
1073 BrowserGpuChannelHostFactory::Terminate();
1076 // Must happen after the I/O thread is shutdown since this class lives on the
1077 // I/O thread and isn't threadsafe.
1079 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GamepadService");
1080 GamepadService::GetInstance()->Terminate();
1083 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:SensorService");
1084 DeviceInertialSensorService::GetInstance()->Shutdown();
1086 #if !defined(OS_ANDROID)
1088 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:BatteryStatusService");
1089 device::BatteryStatusService::GetInstance()->Shutdown();
1091 #endif
1093 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DeleteDataSources");
1094 URLDataManager::DeleteDataSources();
1096 #endif // !defined(OS_IOS)
1098 if (parts_) {
1099 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:PostDestroyThreads");
1100 parts_->PostDestroyThreads();
1104 void BrowserMainLoop::StopStartupTracingTimer() {
1105 startup_trace_timer_.Stop();
1108 void BrowserMainLoop::InitializeMainThread() {
1109 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeMainThread");
1110 static const char kThreadName[] = "CrBrowserMain";
1111 base::PlatformThread::SetName(kThreadName);
1112 if (main_message_loop_)
1113 main_message_loop_->set_thread_name(kThreadName);
1115 // Register the main thread by instantiating it, but don't call any methods.
1116 main_thread_.reset(
1117 new BrowserThreadImpl(BrowserThread::UI, base::MessageLoop::current()));
1120 int BrowserMainLoop::BrowserThreadsStarted() {
1121 TRACE_EVENT0("startup", "BrowserMainLoop::BrowserThreadsStarted");
1123 #if !defined(OS_IOS)
1124 indexed_db_thread_.reset(new base::Thread("IndexedDB"));
1125 indexed_db_thread_->Start();
1126 #endif
1128 #if !defined(OS_IOS)
1129 HistogramSynchronizer::GetInstance();
1131 #if defined(OS_ANDROID)
1132 // Up the priority of the UI thread.
1133 base::PlatformThread::SetCurrentThreadPriority(base::ThreadPriority::DISPLAY);
1134 #endif
1136 bool always_uses_gpu = true;
1137 bool established_gpu_channel = false;
1138 #if defined(OS_ANDROID)
1139 // TODO(crbug.com/439322): This should be set to |true|.
1140 established_gpu_channel = false;
1141 BrowserGpuChannelHostFactory::Initialize(established_gpu_channel);
1142 #elif defined(USE_AURA) || defined(OS_MACOSX)
1143 established_gpu_channel = true;
1144 if (!GpuDataManagerImpl::GetInstance()->CanUseGpuBrowserCompositor() ||
1145 parsed_command_line_.HasSwitch(switches::kDisableGpuEarlyInit)) {
1146 established_gpu_channel = always_uses_gpu = false;
1148 BrowserGpuChannelHostFactory::Initialize(established_gpu_channel);
1149 ImageTransportFactory::Initialize();
1150 #if defined(USE_AURA)
1151 if (aura::Env::GetInstance()) {
1152 aura::Env::GetInstance()->set_context_factory(GetContextFactory());
1154 #endif // defined(USE_AURA)
1155 #endif // defined(OS_ANDROID)
1157 // Enable the GpuMemoryBuffer dump provider with IO thread affinity. Note that
1158 // unregistration happens on the IO thread (See
1159 // BrowserProcessSubThread::IOThreadPreCleanUp).
1160 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
1161 BrowserGpuMemoryBufferManager::current(), io_thread_->task_runner());
1164 TRACE_EVENT0("startup", "BrowserThreadsStarted::Subsystem:AudioMan");
1165 audio_manager_.reset(media::AudioManager::CreateWithHangTimer(
1166 MediaInternals::GetInstance(), io_thread_->task_runner()));
1170 TRACE_EVENT0("startup", "BrowserThreadsStarted::Subsystem:MidiManager");
1171 midi_manager_.reset(media::midi::MidiManager::Create());
1174 #if defined(OS_LINUX) && defined(USE_UDEV)
1175 device_monitor_linux_.reset(new DeviceMonitorLinux());
1176 #elif defined(OS_MACOSX)
1177 device_monitor_mac_.reset(new DeviceMonitorMac());
1178 #endif
1180 #if defined(OS_WIN)
1181 UMA_HISTOGRAM_BOOLEAN("Windows.Win32kRendererLockdown",
1182 IsWin32kRendererLockdownEnabled());
1183 #endif
1184 // RDH needs the IO thread to be created
1186 TRACE_EVENT0("startup",
1187 "BrowserMainLoop::BrowserThreadsStarted:InitResourceDispatcherHost");
1188 resource_dispatcher_host_.reset(new ResourceDispatcherHostImpl());
1191 // MediaStreamManager needs the IO thread to be created.
1193 TRACE_EVENT0("startup",
1194 "BrowserMainLoop::BrowserThreadsStarted:InitMediaStreamManager");
1195 media_stream_manager_.reset(new MediaStreamManager(audio_manager_.get()));
1199 TRACE_EVENT0("startup",
1200 "BrowserMainLoop::BrowserThreadsStarted:InitSpeechRecognition");
1201 speech_recognition_manager_.reset(new SpeechRecognitionManagerImpl(
1202 audio_manager_.get(), media_stream_manager_.get()));
1206 TRACE_EVENT0(
1207 "startup",
1208 "BrowserMainLoop::BrowserThreadsStarted::InitUserInputMonitor");
1209 user_input_monitor_ = media::UserInputMonitor::Create(
1210 io_thread_->task_runner(), main_thread_->task_runner());
1214 TRACE_EVENT0("startup",
1215 "BrowserMainLoop::BrowserThreadsStarted::TimeZoneMonitor");
1216 time_zone_monitor_ = TimeZoneMonitor::Create();
1219 // Alert the clipboard class to which threads are allowed to access the
1220 // clipboard:
1221 std::vector<base::PlatformThreadId> allowed_clipboard_threads;
1222 // The current thread is the UI thread.
1223 allowed_clipboard_threads.push_back(base::PlatformThread::CurrentId());
1224 #if defined(OS_WIN)
1225 // On Windows, clipboards are also used on the FILE or IO threads.
1226 allowed_clipboard_threads.push_back(file_thread_->GetThreadId());
1227 allowed_clipboard_threads.push_back(io_thread_->GetThreadId());
1228 #endif
1229 ui::Clipboard::SetAllowedThreads(allowed_clipboard_threads);
1231 // When running the GPU thread in-process, avoid optimistically starting it
1232 // since creating the GPU thread races against creation of the one-and-only
1233 // ChildProcess instance which is created by the renderer thread.
1234 if (GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL) &&
1235 !established_gpu_channel &&
1236 always_uses_gpu &&
1237 !UsingInProcessGpu()) {
1238 TRACE_EVENT_INSTANT0("gpu", "Post task to launch GPU process",
1239 TRACE_EVENT_SCOPE_THREAD);
1240 BrowserThread::PostTask(
1241 BrowserThread::IO, FROM_HERE,
1242 base::Bind(base::IgnoreResult(&GpuProcessHost::Get),
1243 GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED,
1244 CAUSE_FOR_GPU_LAUNCH_BROWSER_STARTUP));
1247 #if defined(OS_MACOSX)
1248 ThemeHelperMac::GetInstance();
1249 SystemHotkeyHelperMac::GetInstance()->DeferredLoadSystemHotkeys();
1250 if (ShouldEnableBootstrapSandbox()) {
1251 TRACE_EVENT0("startup",
1252 "BrowserMainLoop::BrowserThreadsStarted:BootstrapSandbox");
1253 CHECK(GetBootstrapSandbox());
1255 #endif // defined(OS_MACOSX)
1257 #endif // !defined(OS_IOS)
1259 mojo_shell_context_.reset(new MojoShellContext);
1261 return result_code_;
1264 bool BrowserMainLoop::UsingInProcessGpu() const {
1265 return parsed_command_line_.HasSwitch(switches::kSingleProcess) ||
1266 parsed_command_line_.HasSwitch(switches::kInProcessGPU);
1269 bool BrowserMainLoop::InitializeToolkit() {
1270 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeToolkit");
1271 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::InitializeToolkit");
1273 // TODO(evan): this function is rather subtle, due to the variety
1274 // of intersecting ifdefs we have. To keep it easy to follow, there
1275 // are no #else branches on any #ifs.
1276 // TODO(stevenjb): Move platform specific code into platform specific Parts
1277 // (Need to add InitializeToolkit stage to BrowserParts).
1278 // See also GTK setup in EarlyInitialization, above, and associated comments.
1280 #if defined(OS_WIN)
1281 // Init common control sex.
1282 INITCOMMONCONTROLSEX config;
1283 config.dwSize = sizeof(config);
1284 config.dwICC = ICC_WIN95_CLASSES;
1285 if (!InitCommonControlsEx(&config))
1286 PLOG(FATAL);
1287 #endif
1289 #if defined(USE_AURA)
1291 #if defined(USE_X11)
1292 if (!gfx::GetXDisplay())
1293 return false;
1294 #endif
1296 // Env creates the compositor. Aura widgets need the compositor to be created
1297 // before they can be initialized by the browser.
1298 aura::Env::CreateInstance(true);
1299 #endif // defined(USE_AURA)
1301 if (parts_)
1302 parts_->ToolkitInitialized();
1304 return true;
1307 void BrowserMainLoop::MainMessageLoopRun() {
1308 #if defined(OS_ANDROID)
1309 // Android's main message loop is the Java message loop.
1310 NOTREACHED();
1311 #else
1312 DCHECK(base::MessageLoopForUI::IsCurrent());
1313 if (parameters_.ui_task) {
1314 base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
1315 *parameters_.ui_task);
1318 base::RunLoop run_loop;
1319 run_loop.Run();
1320 #endif
1323 base::FilePath BrowserMainLoop::GetStartupTraceFileName(
1324 const base::CommandLine& command_line) const {
1325 base::FilePath trace_file;
1326 if (command_line.HasSwitch(switches::kTraceStartup)) {
1327 trace_file = command_line.GetSwitchValuePath(
1328 switches::kTraceStartupFile);
1329 // trace_file = "none" means that startup events will show up for the next
1330 // begin/end tracing (via about:tracing or AutomationProxy::BeginTracing/
1331 // EndTracing, for example).
1332 if (trace_file == base::FilePath().AppendASCII("none"))
1333 return trace_file;
1335 if (trace_file.empty()) {
1336 #if defined(OS_ANDROID)
1337 TracingControllerAndroid::GenerateTracingFilePath(&trace_file);
1338 #else
1339 // Default to saving the startup trace into the current dir.
1340 trace_file = base::FilePath().AppendASCII("chrometrace.log");
1341 #endif
1343 } else {
1344 #if defined(OS_ANDROID)
1345 TracingControllerAndroid::GenerateTracingFilePath(&trace_file);
1346 #else
1347 trace_file = tracing::TraceConfigFile::GetInstance()->GetResultFile();
1348 #endif
1351 return trace_file;
1354 void BrowserMainLoop::InitStartupTracingForDuration(
1355 const base::CommandLine& command_line) {
1356 DCHECK(is_tracing_startup_for_duration_);
1358 startup_trace_file_ = GetStartupTraceFileName(parsed_command_line_);
1360 int delay_secs = 5;
1361 if (command_line.HasSwitch(switches::kTraceStartup)) {
1362 std::string delay_str = command_line.GetSwitchValueASCII(
1363 switches::kTraceStartupDuration);
1364 if (!delay_str.empty() && !base::StringToInt(delay_str, &delay_secs)) {
1365 DLOG(WARNING) << "Could not parse --" << switches::kTraceStartupDuration
1366 << "=" << delay_str << " defaulting to 5 (secs)";
1367 delay_secs = 5;
1369 } else {
1370 delay_secs = tracing::TraceConfigFile::GetInstance()->GetStartupDuration();
1373 startup_trace_timer_.Start(FROM_HERE,
1374 base::TimeDelta::FromSeconds(delay_secs),
1375 this,
1376 &BrowserMainLoop::EndStartupTracing);
1379 void BrowserMainLoop::EndStartupTracing() {
1380 DCHECK(is_tracing_startup_for_duration_);
1382 is_tracing_startup_for_duration_ = false;
1383 TracingController::GetInstance()->DisableRecording(
1384 TracingController::CreateFileSink(
1385 startup_trace_file_,
1386 base::Bind(OnStoppedStartupTracing, startup_trace_file_)));
1389 } // namespace content