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"
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"
80 #include "content/public/browser/context_factory.h"
81 #include "ui/aura/env.h"
85 #include "content/browser/renderer_host/render_process_host_impl.h"
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"
99 #if defined(OS_MACOSX)
100 #include "media/base/mac/avfoundation_glue.h"
103 #if defined(OS_MACOSX) && !defined(OS_IOS)
104 #include "base/memory/memory_pressure_monitor_mac.h"
105 #include "content/browser/bootstrap_sandbox_manager_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"
113 #if defined(USE_OZONE)
114 #include "ui/ozone/public/client_native_pixmap_factory.h"
115 #include "ui/ozone/public/ozone_platform.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"
130 #if defined(OS_CHROMEOS)
131 #include "base/memory/memory_pressure_monitor_chromeos.h"
132 #include "chromeos/chromeos_switches.h"
135 #if defined(USE_GLIB)
136 #include <glib-object.h>
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"
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"
151 #if defined(ENABLE_PLUGINS)
152 #include "content/browser/plugin_service_impl.h"
155 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
156 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
160 #include "ui/gfx/x/x11_connection.h"
161 #include "ui/gfx/x/x11_types.h"
164 // One of the linux specific headers defines this as a macro.
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
194 LOG(FATAL
) << no_suid_error
;
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());
206 #if defined(USE_GLIB)
207 static void GLibLogHandler(const gchar
* log_domain
,
208 GLogLevelFlags log_level
,
209 const gchar
* message
,
212 log_domain
= "<unknown>";
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
;
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
|
259 G_LOG_LEVEL_CRITICAL
|
260 G_LOG_LEVEL_WARNING
),
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
);
283 NOINLINE
void ResetThread_FILE(scoped_ptr
<BrowserProcessSubThread
> thread
) {
284 volatile int inhibit_comdat
= __LINE__
;
285 ALLOW_UNUSED_LOCAL(inhibit_comdat
);
289 NOINLINE
void ResetThread_FILE_USER_BLOCKING(
290 scoped_ptr
<BrowserProcessSubThread
> thread
) {
291 volatile int inhibit_comdat
= __LINE__
;
292 ALLOW_UNUSED_LOCAL(inhibit_comdat
);
296 NOINLINE
void ResetThread_PROCESS_LAUNCHER(
297 scoped_ptr
<BrowserProcessSubThread
> thread
) {
298 volatile int inhibit_comdat
= __LINE__
;
299 ALLOW_UNUSED_LOCAL(inhibit_comdat
);
303 NOINLINE
void ResetThread_CACHE(scoped_ptr
<BrowserProcessSubThread
> thread
) {
304 volatile int inhibit_comdat
= __LINE__
;
305 ALLOW_UNUSED_LOCAL(inhibit_comdat
);
309 NOINLINE
void ResetThread_IO(scoped_ptr
<BrowserProcessSubThread
> thread
) {
310 volatile int inhibit_comdat
= __LINE__
;
311 ALLOW_UNUSED_LOCAL(inhibit_comdat
);
316 NOINLINE
void ResetThread_IndexedDb(scoped_ptr
<base::Thread
> thread
) {
317 volatile int inhibit_comdat
= __LINE__
;
318 ALLOW_UNUSED_LOCAL(inhibit_comdat
);
324 MSVC_ENABLE_OPTIMIZE();
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)
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
{
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
));
372 base::GetCurrentProcessHandle()));
374 size_t private_bytes
;
375 process_metrics
->GetMemoryBytes(&private_bytes
, NULL
);
376 LOCAL_HISTOGRAM_MEMORY_KB("Memory.BrowserUsed", private_bytes
>> 10);
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
);
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");
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_
);
435 if (UsingInProcessGpu()) {
436 if (!gfx::InitializeThreadedX11()) {
437 LOG(ERROR
) << "Failed to put Xlib into threaded mode.";
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.
458 SetUpGLibLogHandler();
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);
471 net::EnsureWinsockInit();
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();
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());
498 parts_
->PostEarlyInitialization();
501 void BrowserMainLoop::PreMainMessageLoopStart() {
503 TRACE_EVENT0("startup",
504 "BrowserMainLoop::MainMessageLoopStart:PreMainMessageLoopStart");
505 parts_
->PreMainMessageLoopStart();
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();
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());
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)
577 system_message_window_
.reset(new SystemMessageWindowWin
);
581 parts_
->PostMainMessageLoopStart();
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());
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());
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());
621 IOSurfaceManager::SetInstance(BrowserIOSurfaceManager::GetInstance());
625 if (BootstrapSandboxManager::ShouldEnable()) {
626 TRACE_EVENT0("startup",
627 "BrowserMainLoop::Subsystem:BootstrapSandbox");
628 CHECK(BootstrapSandboxManager::GetInstance());
632 #if defined(USE_OZONE)
633 client_native_pixmap_factory_
= ui::ClientNativePixmapFactory::Create();
634 ui::ClientNativePixmapFactory::SetInstance(
635 client_native_pixmap_factory_
.get());
636 ui::ClientNativePixmapFactory::GetInstance()->Initialize(
637 ui::OzonePlatform::GetInstance()->OpenClientNativePixmapDevice());
640 if (parsed_command_line_
.HasSwitch(switches::kMemoryMetrics
)) {
641 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MemoryObserver");
642 memory_observer_
.reset(new MemoryObserver());
643 base::MessageLoop::current()->AddTaskObserver(memory_observer_
.get());
646 if (parsed_command_line_
.HasSwitch(
647 switches::kEnableAggressiveDOMStorageFlushing
)) {
648 TRACE_EVENT0("startup",
649 "BrowserMainLoop::Subsystem:EnableAggressiveCommitDelay");
650 DOMStorageArea::EnableAggressiveCommitDelay();
653 // Enable memory-infra dump providers.
654 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
655 HostSharedBitmapManager::current());
656 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
657 skia::SkiaMemoryDumpProvider::GetInstance());
659 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
660 trace_memory_controller_
.reset(new base::trace_event::TraceMemoryController(
661 base::MessageLoop::current()->task_runner(),
662 ::HeapProfilerWithPseudoStackStart
, ::HeapProfilerStop
,
667 int BrowserMainLoop::PreCreateThreads() {
669 TRACE_EVENT0("startup",
670 "BrowserMainLoop::CreateThreads:PreCreateThreads");
671 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::PreCreateThreads");
673 result_code_
= parts_
->PreCreateThreads();
676 // TODO(chrisha): Abstract away this construction mess to a helper function,
677 // once MemoryPressureMonitor is made a concrete class.
678 #if defined(OS_CHROMEOS)
679 if (chromeos::switches::MemoryPressureHandlingEnabled()) {
680 memory_pressure_monitor_
.reset(new base::chromeos::MemoryPressureMonitor(
681 chromeos::switches::GetMemoryPressureThresholds()));
683 #elif defined(OS_MACOSX) && !defined(OS_IOS)
684 memory_pressure_monitor_
.reset(new base::mac::MemoryPressureMonitor());
685 #elif defined(OS_WIN)
686 memory_pressure_monitor_
.reset(CreateWinMemoryPressureMonitor(
687 parsed_command_line_
));
690 #if defined(ENABLE_PLUGINS)
691 // Prior to any processing happening on the io thread, we create the
692 // plugin service as it is predominantly used from the io thread,
693 // but must be created on the main thread. The service ctor is
694 // inexpensive and does not invoke the io_thread() accessor.
696 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads:PluginService");
697 PluginService::GetInstance()->Init();
701 #if defined(OS_MACOSX)
703 // Initialize AVFoundation if supported, for audio and video.
704 TRACE_EVENT0("startup",
705 "BrowserMainLoop::CreateThreads:InitializeAVFoundation");
706 AVFoundationGlue::InitializeAVFoundation();
710 // 1) Need to initialize in-process GpuDataManager before creating threads.
711 // It's unsafe to append the gpu command line switches to the global
712 // CommandLine::ForCurrentProcess object after threads are created.
713 // 2) Must be after parts_->PreCreateThreads to pick up chrome://flags.
714 GpuDataManagerImpl::GetInstance()->Initialize();
716 #if !defined(OS_IOS) && (!defined(GOOGLE_CHROME_BUILD) || defined(OS_ANDROID))
717 // Single-process is an unsupported and not fully tested mode, so
718 // don't enable it for official Chrome builds (except on Android).
719 if (parsed_command_line_
.HasSwitch(switches::kSingleProcess
))
720 RenderProcessHost::SetRunRendererInProcess(true);
726 void BrowserMainLoop::CreateStartupTasks() {
727 TRACE_EVENT0("startup", "BrowserMainLoop::CreateStartupTasks");
728 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::CreateStartupTasks");
730 // First time through, we really want to create all the tasks
731 if (!startup_task_runner_
.get()) {
732 #if defined(OS_ANDROID)
733 startup_task_runner_
= make_scoped_ptr(
734 new StartupTaskRunner(base::Bind(&BrowserStartupComplete
),
735 base::ThreadTaskRunnerHandle::Get()));
737 startup_task_runner_
= make_scoped_ptr(
738 new StartupTaskRunner(base::Callback
<void(int)>(),
739 base::ThreadTaskRunnerHandle::Get()));
741 StartupTask pre_create_threads
=
742 base::Bind(&BrowserMainLoop::PreCreateThreads
, base::Unretained(this));
743 startup_task_runner_
->AddTask(pre_create_threads
);
745 StartupTask create_threads
=
746 base::Bind(&BrowserMainLoop::CreateThreads
, base::Unretained(this));
747 startup_task_runner_
->AddTask(create_threads
);
749 StartupTask browser_thread_started
= base::Bind(
750 &BrowserMainLoop::BrowserThreadsStarted
, base::Unretained(this));
751 startup_task_runner_
->AddTask(browser_thread_started
);
753 StartupTask pre_main_message_loop_run
= base::Bind(
754 &BrowserMainLoop::PreMainMessageLoopRun
, base::Unretained(this));
755 startup_task_runner_
->AddTask(pre_main_message_loop_run
);
757 #if defined(OS_ANDROID)
758 if (BrowserMayStartAsynchronously()) {
759 startup_task_runner_
->StartRunningTasksAsync();
763 #if defined(OS_ANDROID)
764 if (!BrowserMayStartAsynchronously()) {
765 // A second request for asynchronous startup can be ignored, so
766 // StartupRunningTasksAsync is only called first time through. If, however,
767 // this is a request for synchronous startup then it must override any
768 // previous call for async startup, so we call RunAllTasksNow()
770 startup_task_runner_
->RunAllTasksNow();
773 startup_task_runner_
->RunAllTasksNow();
777 int BrowserMainLoop::CreateThreads() {
778 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads");
779 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::CreateThreads");
781 base::Thread::Options io_message_loop_options
;
782 io_message_loop_options
.message_loop_type
= base::MessageLoop::TYPE_IO
;
783 base::Thread::Options ui_message_loop_options
;
784 ui_message_loop_options
.message_loop_type
= base::MessageLoop::TYPE_UI
;
786 // Start threads in the order they occur in the BrowserThread::ID
787 // enumeration, except for BrowserThread::UI which is the main
790 // Must be size_t so we can increment it.
791 for (size_t thread_id
= BrowserThread::UI
+ 1;
792 thread_id
< BrowserThread::ID_COUNT
;
794 scoped_ptr
<BrowserProcessSubThread
>* thread_to_start
= NULL
;
795 base::Thread::Options options
;
798 case BrowserThread::DB
:
799 TRACE_EVENT_BEGIN1("startup",
800 "BrowserMainLoop::CreateThreads:start",
801 "Thread", "BrowserThread::DB");
802 thread_to_start
= &db_thread_
;
803 options
.timer_slack
= base::TIMER_SLACK_MAXIMUM
;
805 case BrowserThread::FILE_USER_BLOCKING
:
806 TRACE_EVENT_BEGIN1("startup",
807 "BrowserMainLoop::CreateThreads:start",
808 "Thread", "BrowserThread::FILE_USER_BLOCKING");
809 thread_to_start
= &file_user_blocking_thread_
;
811 case BrowserThread::FILE:
812 TRACE_EVENT_BEGIN1("startup",
813 "BrowserMainLoop::CreateThreads:start",
814 "Thread", "BrowserThread::FILE");
815 thread_to_start
= &file_thread_
;
817 // On Windows, the FILE thread needs to be have a UI message loop
818 // which pumps messages in such a way that Google Update can
819 // communicate back to us.
820 options
= ui_message_loop_options
;
822 options
= io_message_loop_options
;
824 options
.timer_slack
= base::TIMER_SLACK_MAXIMUM
;
826 case BrowserThread::PROCESS_LAUNCHER
:
827 TRACE_EVENT_BEGIN1("startup",
828 "BrowserMainLoop::CreateThreads:start",
829 "Thread", "BrowserThread::PROCESS_LAUNCHER");
830 thread_to_start
= &process_launcher_thread_
;
831 options
.timer_slack
= base::TIMER_SLACK_MAXIMUM
;
833 case BrowserThread::CACHE
:
834 TRACE_EVENT_BEGIN1("startup",
835 "BrowserMainLoop::CreateThreads:start",
836 "Thread", "BrowserThread::CACHE");
837 thread_to_start
= &cache_thread_
;
838 options
= io_message_loop_options
;
839 options
.timer_slack
= base::TIMER_SLACK_MAXIMUM
;
841 case BrowserThread::IO
:
842 TRACE_EVENT_BEGIN1("startup",
843 "BrowserMainLoop::CreateThreads:start",
844 "Thread", "BrowserThread::IO");
845 thread_to_start
= &io_thread_
;
846 options
= io_message_loop_options
;
847 #if defined(OS_ANDROID)
848 // Up the priority of the |io_thread_| as some of its IPCs relate to
850 options
.priority
= base::ThreadPriority::DISPLAY
;
853 case BrowserThread::UI
:
854 case BrowserThread::ID_COUNT
:
860 BrowserThread::ID id
= static_cast<BrowserThread::ID
>(thread_id
);
862 if (thread_to_start
) {
863 (*thread_to_start
).reset(new BrowserProcessSubThread(id
));
864 if (!(*thread_to_start
)->StartWithOptions(options
)) {
865 LOG(FATAL
) << "Failed to start the browser thread: id == " << id
;
871 TRACE_EVENT_END0("startup", "BrowserMainLoop::CreateThreads:start");
873 created_threads_
= true;
877 int BrowserMainLoop::PreMainMessageLoopRun() {
879 TRACE_EVENT0("startup",
880 "BrowserMainLoop::CreateThreads:PreMainMessageLoopRun");
882 "Startup", "BrowserMainLoop::PreMainMessageLoopRun");
884 parts_
->PreMainMessageLoopRun();
887 // If the UI thread blocks, the whole UI is unresponsive.
888 // Do not allow disk IO from the UI thread.
889 base::ThreadRestrictions::SetIOAllowed(false);
890 base::ThreadRestrictions::DisallowWaiting();
894 void BrowserMainLoop::RunMainMessageLoopParts() {
895 TRACE_EVENT_BEGIN_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
897 bool ran_main_loop
= false;
899 ran_main_loop
= parts_
->MainMessageLoopRun(&result_code_
);
902 MainMessageLoopRun();
904 TRACE_EVENT_END_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
907 void BrowserMainLoop::ShutdownThreadsAndCleanUp() {
908 if (!created_threads_
) {
909 // Called early, nothing to do
912 TRACE_EVENT0("shutdown", "BrowserMainLoop::ShutdownThreadsAndCleanUp");
914 // Teardown may start in PostMainMessageLoopRun, and during teardown we
915 // need to be able to perform IO.
916 base::ThreadRestrictions::SetIOAllowed(true);
917 BrowserThread::PostTask(
918 BrowserThread::IO
, FROM_HERE
,
919 base::Bind(base::IgnoreResult(&base::ThreadRestrictions::SetIOAllowed
),
922 mojo_shell_context_
.reset();
925 if (RenderProcessHost::run_renderer_in_process())
926 RenderProcessHostImpl::ShutDownInProcessRenderer();
930 TRACE_EVENT0("shutdown",
931 "BrowserMainLoop::Subsystem:PostMainMessageLoopRun");
932 parts_
->PostMainMessageLoopRun();
935 #if defined(USE_AURA)
936 aura::Env::DeleteInstance();
939 trace_memory_controller_
.reset();
940 system_stats_monitor_
.reset();
943 // Destroying the GpuProcessHostUIShims on the UI thread posts a task to
944 // delete related objects on the GPU thread. This must be done before
945 // stopping the GPU thread. The GPU thread will close IPC channels to renderer
946 // processes so this has to happen before stopping the IO thread.
948 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUProcessHostShim");
949 GpuProcessHostUIShim::DestroyAll();
951 // Cancel pending requests and prevent new requests.
952 if (resource_dispatcher_host_
) {
953 TRACE_EVENT0("shutdown",
954 "BrowserMainLoop::Subsystem:ResourceDispatcherHost");
955 resource_dispatcher_host_
.get()->Shutdown();
958 memory_pressure_monitor_
.reset();
960 #if defined(OS_MACOSX)
961 BrowserCompositorMac::DisableRecyclingForShutdown();
964 #if defined(USE_AURA) || defined(OS_MACOSX)
966 TRACE_EVENT0("shutdown",
967 "BrowserMainLoop::Subsystem:ImageTransportFactory");
968 ImageTransportFactory::Terminate();
972 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
973 ZygoteHostImpl::GetInstance()->TearDownAfterLastChild();
974 #endif // defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
976 // The device monitors are using |system_monitor_| as dependency, so delete
977 // them before |system_monitor_| goes away.
978 // On Mac and windows, the monitor needs to be destroyed on the same thread
979 // as they were created. On Linux, the monitor will be deleted when IO thread
982 system_message_window_
.reset();
983 #elif defined(OS_MACOSX)
984 device_monitor_mac_
.reset();
986 #endif // !defined(OS_IOS)
988 // Must be size_t so we can subtract from it.
989 for (size_t thread_id
= BrowserThread::ID_COUNT
- 1;
990 thread_id
>= (BrowserThread::UI
+ 1);
992 // Find the thread object we want to stop. Looping over all valid
993 // BrowserThread IDs and DCHECKing on a missing case in the switch
994 // statement helps avoid a mismatch between this code and the
995 // BrowserThread::ID enumeration.
997 // The destruction order is the reverse order of occurrence in the
998 // BrowserThread::ID list. The rationale for the order is as
999 // follows (need to be filled in a bit):
1002 // - The IO thread is the only user of the CACHE thread.
1004 // - The PROCESS_LAUNCHER thread must be stopped after IO in case
1005 // the IO thread posted a task to terminate a process on the
1006 // process launcher thread.
1008 // - (Not sure why DB stops last.)
1009 switch (thread_id
) {
1010 case BrowserThread::DB
: {
1011 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DBThread");
1012 ResetThread_DB(db_thread_
.Pass());
1015 case BrowserThread::FILE: {
1016 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:FileThread");
1017 #if !defined(OS_IOS)
1018 // Clean up state that lives on or uses the file_thread_ before
1020 if (resource_dispatcher_host_
)
1021 resource_dispatcher_host_
.get()->save_file_manager()->Shutdown();
1022 #endif // !defined(OS_IOS)
1023 ResetThread_FILE(file_thread_
.Pass());
1026 case BrowserThread::FILE_USER_BLOCKING
: {
1027 TRACE_EVENT0("shutdown",
1028 "BrowserMainLoop::Subsystem:FileUserBlockingThread");
1029 ResetThread_FILE_USER_BLOCKING(file_user_blocking_thread_
.Pass());
1032 case BrowserThread::PROCESS_LAUNCHER
: {
1033 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:LauncherThread");
1034 ResetThread_PROCESS_LAUNCHER(process_launcher_thread_
.Pass());
1037 case BrowserThread::CACHE
: {
1038 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:CacheThread");
1039 ResetThread_CACHE(cache_thread_
.Pass());
1042 case BrowserThread::IO
: {
1043 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IOThread");
1044 ResetThread_IO(io_thread_
.Pass());
1047 case BrowserThread::UI
:
1048 case BrowserThread::ID_COUNT
:
1055 #if !defined(OS_IOS)
1057 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IndexedDBThread");
1058 ResetThread_IndexedDb(indexed_db_thread_
.Pass());
1062 // Close the blocking I/O pool after the other threads. Other threads such
1063 // as the I/O thread may need to schedule work like closing files or flushing
1064 // data during shutdown, so the blocking pool needs to be available. There
1065 // may also be slow operations pending that will blcok shutdown, so closing
1066 // it here (which will block until required operations are complete) gives
1067 // more head start for those operations to finish.
1069 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:ThreadPool");
1070 BrowserThreadImpl::ShutdownThreadPool();
1073 #if !defined(OS_IOS)
1074 // Must happen after the IO thread is shutdown since this may be accessed from
1077 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUChannelFactory");
1078 if (BrowserGpuChannelHostFactory::instance())
1079 BrowserGpuChannelHostFactory::Terminate();
1082 // Must happen after the I/O thread is shutdown since this class lives on the
1083 // I/O thread and isn't threadsafe.
1085 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GamepadService");
1086 GamepadService::GetInstance()->Terminate();
1089 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:SensorService");
1090 DeviceInertialSensorService::GetInstance()->Shutdown();
1092 #if !defined(OS_ANDROID)
1094 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:BatteryStatusService");
1095 device::BatteryStatusService::GetInstance()->Shutdown();
1099 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DeleteDataSources");
1100 URLDataManager::DeleteDataSources();
1102 #endif // !defined(OS_IOS)
1105 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:PostDestroyThreads");
1106 parts_
->PostDestroyThreads();
1110 void BrowserMainLoop::StopStartupTracingTimer() {
1111 startup_trace_timer_
.Stop();
1114 void BrowserMainLoop::InitializeMainThread() {
1115 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeMainThread");
1116 static const char kThreadName
[] = "CrBrowserMain";
1117 base::PlatformThread::SetName(kThreadName
);
1118 if (main_message_loop_
)
1119 main_message_loop_
->set_thread_name(kThreadName
);
1121 // Register the main thread by instantiating it, but don't call any methods.
1123 new BrowserThreadImpl(BrowserThread::UI
, base::MessageLoop::current()));
1126 int BrowserMainLoop::BrowserThreadsStarted() {
1127 TRACE_EVENT0("startup", "BrowserMainLoop::BrowserThreadsStarted");
1129 #if !defined(OS_IOS)
1130 indexed_db_thread_
.reset(new base::Thread("IndexedDB"));
1131 indexed_db_thread_
->Start();
1134 #if !defined(OS_IOS)
1135 HistogramSynchronizer::GetInstance();
1137 #if defined(OS_ANDROID)
1138 // Up the priority of the UI thread.
1139 base::PlatformThread::SetCurrentThreadPriority(base::ThreadPriority::DISPLAY
);
1142 bool always_uses_gpu
= true;
1143 bool established_gpu_channel
= false;
1144 #if defined(OS_ANDROID)
1145 // TODO(crbug.com/439322): This should be set to |true|.
1146 established_gpu_channel
= false;
1147 BrowserGpuChannelHostFactory::Initialize(established_gpu_channel
);
1148 #elif defined(USE_AURA) || defined(OS_MACOSX)
1149 established_gpu_channel
= true;
1150 if (!GpuDataManagerImpl::GetInstance()->CanUseGpuBrowserCompositor() ||
1151 parsed_command_line_
.HasSwitch(switches::kDisableGpuEarlyInit
)) {
1152 established_gpu_channel
= always_uses_gpu
= false;
1154 BrowserGpuChannelHostFactory::Initialize(established_gpu_channel
);
1155 ImageTransportFactory::Initialize();
1156 #if defined(USE_AURA)
1157 if (aura::Env::GetInstance()) {
1158 aura::Env::GetInstance()->set_context_factory(GetContextFactory());
1160 #endif // defined(USE_AURA)
1161 #endif // defined(OS_ANDROID)
1163 // Enable the GpuMemoryBuffer dump provider with IO thread affinity. Note that
1164 // unregistration happens on the IO thread (See
1165 // BrowserProcessSubThread::IOThreadPreCleanUp).
1166 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
1167 BrowserGpuMemoryBufferManager::current(), io_thread_
->task_runner());
1170 TRACE_EVENT0("startup", "BrowserThreadsStarted::Subsystem:AudioMan");
1171 audio_manager_
.reset(media::AudioManager::CreateWithHangTimer(
1172 MediaInternals::GetInstance(), io_thread_
->task_runner()));
1176 TRACE_EVENT0("startup", "BrowserThreadsStarted::Subsystem:MidiManager");
1177 midi_manager_
.reset(media::midi::MidiManager::Create());
1180 #if defined(OS_LINUX) && defined(USE_UDEV)
1181 device_monitor_linux_
.reset(new DeviceMonitorLinux());
1182 #elif defined(OS_MACOSX)
1183 device_monitor_mac_
.reset(new DeviceMonitorMac());
1187 UMA_HISTOGRAM_BOOLEAN("Windows.Win32kRendererLockdown",
1188 IsWin32kRendererLockdownEnabled());
1190 // RDH needs the IO thread to be created
1192 TRACE_EVENT0("startup",
1193 "BrowserMainLoop::BrowserThreadsStarted:InitResourceDispatcherHost");
1194 resource_dispatcher_host_
.reset(new ResourceDispatcherHostImpl());
1197 // MediaStreamManager needs the IO thread to be created.
1199 TRACE_EVENT0("startup",
1200 "BrowserMainLoop::BrowserThreadsStarted:InitMediaStreamManager");
1201 media_stream_manager_
.reset(new MediaStreamManager(audio_manager_
.get()));
1205 TRACE_EVENT0("startup",
1206 "BrowserMainLoop::BrowserThreadsStarted:InitSpeechRecognition");
1207 speech_recognition_manager_
.reset(new SpeechRecognitionManagerImpl(
1208 audio_manager_
.get(), media_stream_manager_
.get()));
1214 "BrowserMainLoop::BrowserThreadsStarted::InitUserInputMonitor");
1215 user_input_monitor_
= media::UserInputMonitor::Create(
1216 io_thread_
->task_runner(), main_thread_
->task_runner());
1220 TRACE_EVENT0("startup",
1221 "BrowserMainLoop::BrowserThreadsStarted::TimeZoneMonitor");
1222 time_zone_monitor_
= TimeZoneMonitor::Create();
1225 // Alert the clipboard class to which threads are allowed to access the
1227 std::vector
<base::PlatformThreadId
> allowed_clipboard_threads
;
1228 // The current thread is the UI thread.
1229 allowed_clipboard_threads
.push_back(base::PlatformThread::CurrentId());
1231 // On Windows, clipboards are also used on the FILE or IO threads.
1232 allowed_clipboard_threads
.push_back(file_thread_
->GetThreadId());
1233 allowed_clipboard_threads
.push_back(io_thread_
->GetThreadId());
1235 ui::Clipboard::SetAllowedThreads(allowed_clipboard_threads
);
1237 // When running the GPU thread in-process, avoid optimistically starting it
1238 // since creating the GPU thread races against creation of the one-and-only
1239 // ChildProcess instance which is created by the renderer thread.
1240 if (GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL
) &&
1241 !established_gpu_channel
&&
1243 !UsingInProcessGpu()) {
1244 TRACE_EVENT_INSTANT0("gpu", "Post task to launch GPU process",
1245 TRACE_EVENT_SCOPE_THREAD
);
1246 BrowserThread::PostTask(
1247 BrowserThread::IO
, FROM_HERE
,
1248 base::Bind(base::IgnoreResult(&GpuProcessHost::Get
),
1249 GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED
,
1250 CAUSE_FOR_GPU_LAUNCH_BROWSER_STARTUP
));
1253 #if defined(OS_MACOSX)
1254 ThemeHelperMac::GetInstance();
1255 SystemHotkeyHelperMac::GetInstance()->DeferredLoadSystemHotkeys();
1256 #endif // defined(OS_MACOSX)
1258 #endif // !defined(OS_IOS)
1260 mojo_shell_context_
.reset(new MojoShellContext
);
1262 return result_code_
;
1265 bool BrowserMainLoop::UsingInProcessGpu() const {
1266 return parsed_command_line_
.HasSwitch(switches::kSingleProcess
) ||
1267 parsed_command_line_
.HasSwitch(switches::kInProcessGPU
);
1270 bool BrowserMainLoop::InitializeToolkit() {
1271 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeToolkit");
1272 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::InitializeToolkit");
1274 // TODO(evan): this function is rather subtle, due to the variety
1275 // of intersecting ifdefs we have. To keep it easy to follow, there
1276 // are no #else branches on any #ifs.
1277 // TODO(stevenjb): Move platform specific code into platform specific Parts
1278 // (Need to add InitializeToolkit stage to BrowserParts).
1279 // See also GTK setup in EarlyInitialization, above, and associated comments.
1282 // Init common control sex.
1283 INITCOMMONCONTROLSEX config
;
1284 config
.dwSize
= sizeof(config
);
1285 config
.dwICC
= ICC_WIN95_CLASSES
;
1286 if (!InitCommonControlsEx(&config
))
1290 #if defined(USE_AURA)
1292 #if defined(USE_X11)
1293 if (!gfx::GetXDisplay())
1297 // Env creates the compositor. Aura widgets need the compositor to be created
1298 // before they can be initialized by the browser.
1299 aura::Env::CreateInstance(true);
1300 #endif // defined(USE_AURA)
1303 parts_
->ToolkitInitialized();
1308 void BrowserMainLoop::MainMessageLoopRun() {
1309 #if defined(OS_ANDROID)
1310 // Android's main message loop is the Java message loop.
1313 DCHECK(base::MessageLoopForUI::IsCurrent());
1314 if (parameters_
.ui_task
) {
1315 base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE
,
1316 *parameters_
.ui_task
);
1319 base::RunLoop run_loop
;
1324 base::FilePath
BrowserMainLoop::GetStartupTraceFileName(
1325 const base::CommandLine
& command_line
) const {
1326 base::FilePath trace_file
;
1327 if (command_line
.HasSwitch(switches::kTraceStartup
)) {
1328 trace_file
= command_line
.GetSwitchValuePath(
1329 switches::kTraceStartupFile
);
1330 // trace_file = "none" means that startup events will show up for the next
1331 // begin/end tracing (via about:tracing or AutomationProxy::BeginTracing/
1332 // EndTracing, for example).
1333 if (trace_file
== base::FilePath().AppendASCII("none"))
1336 if (trace_file
.empty()) {
1337 #if defined(OS_ANDROID)
1338 TracingControllerAndroid::GenerateTracingFilePath(&trace_file
);
1340 // Default to saving the startup trace into the current dir.
1341 trace_file
= base::FilePath().AppendASCII("chrometrace.log");
1345 #if defined(OS_ANDROID)
1346 TracingControllerAndroid::GenerateTracingFilePath(&trace_file
);
1348 trace_file
= tracing::TraceConfigFile::GetInstance()->GetResultFile();
1355 void BrowserMainLoop::InitStartupTracingForDuration(
1356 const base::CommandLine
& command_line
) {
1357 DCHECK(is_tracing_startup_for_duration_
);
1359 // Initialize the tracing controller, required for memory tracing.
1360 TracingController::GetInstance();
1362 startup_trace_file_
= GetStartupTraceFileName(parsed_command_line_
);
1365 if (command_line
.HasSwitch(switches::kTraceStartup
)) {
1366 std::string delay_str
= command_line
.GetSwitchValueASCII(
1367 switches::kTraceStartupDuration
);
1368 if (!delay_str
.empty() && !base::StringToInt(delay_str
, &delay_secs
)) {
1369 DLOG(WARNING
) << "Could not parse --" << switches::kTraceStartupDuration
1370 << "=" << delay_str
<< " defaulting to 5 (secs)";
1374 delay_secs
= tracing::TraceConfigFile::GetInstance()->GetStartupDuration();
1377 startup_trace_timer_
.Start(FROM_HERE
,
1378 base::TimeDelta::FromSeconds(delay_secs
),
1380 &BrowserMainLoop::EndStartupTracing
);
1383 void BrowserMainLoop::EndStartupTracing() {
1384 DCHECK(is_tracing_startup_for_duration_
);
1386 is_tracing_startup_for_duration_
= false;
1387 TracingController::GetInstance()->DisableRecording(
1388 TracingController::CreateFileSink(
1389 startup_trace_file_
,
1390 base::Bind(OnStoppedStartupTracing
, startup_trace_file_
)));
1393 } // namespace content