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 "content/browser/browser_thread_impl.h"
30 #include "content/browser/device_sensors/device_inertial_sensor_service.h"
31 #include "content/browser/dom_storage/dom_storage_area.h"
32 #include "content/browser/download/save_file_manager.h"
33 #include "content/browser/gamepad/gamepad_service.h"
34 #include "content/browser/gpu/browser_gpu_channel_host_factory.h"
35 #include "content/browser/gpu/browser_gpu_memory_buffer_manager.h"
36 #include "content/browser/gpu/compositor_util.h"
37 #include "content/browser/gpu/gpu_data_manager_impl.h"
38 #include "content/browser/gpu/gpu_process_host.h"
39 #include "content/browser/gpu/gpu_process_host_ui_shim.h"
40 #include "content/browser/histogram_synchronizer.h"
41 #include "content/browser/loader/resource_dispatcher_host_impl.h"
42 #include "content/browser/media/media_internals.h"
43 #include "content/browser/mojo/mojo_shell_context.h"
44 #include "content/browser/net/browser_online_state_observer.h"
45 #include "content/browser/renderer_host/media/media_stream_manager.h"
46 #include "content/browser/speech/speech_recognition_manager_impl.h"
47 #include "content/browser/startup_task_runner.h"
48 #include "content/browser/time_zone_monitor.h"
49 #include "content/browser/webui/content_web_ui_controller_factory.h"
50 #include "content/browser/webui/url_data_manager.h"
51 #include "content/common/content_switches_internal.h"
52 #include "content/common/host_discardable_shared_memory_manager.h"
53 #include "content/common/host_shared_bitmap_manager.h"
54 #include "content/public/browser/browser_main_parts.h"
55 #include "content/public/browser/content_browser_client.h"
56 #include "content/public/browser/render_process_host.h"
57 #include "content/public/browser/tracing_controller.h"
58 #include "content/public/common/content_switches.h"
59 #include "content/public/common/main_function_params.h"
60 #include "content/public/common/result_codes.h"
61 #include "crypto/nss_util.h"
62 #include "device/battery/battery_status_service.h"
63 #include "media/audio/audio_manager.h"
64 #include "media/base/media.h"
65 #include "media/base/user_input_monitor.h"
66 #include "media/midi/midi_manager.h"
67 #include "net/base/network_change_notifier.h"
68 #include "net/socket/client_socket_factory.h"
69 #include "net/ssl/ssl_config_service.h"
70 #include "ui/base/clipboard/clipboard.h"
72 #if defined(USE_AURA) || (defined(OS_MACOSX) && !defined(OS_IOS))
73 #include "content/browser/compositor/image_transport_factory.h"
77 #include "content/public/browser/context_factory.h"
78 #include "ui/aura/env.h"
82 #include "content/browser/renderer_host/render_process_host_impl.h"
85 #if defined(OS_ANDROID)
86 #include "base/android/jni_android.h"
87 #include "content/browser/android/browser_startup_controller.h"
88 #include "content/browser/android/browser_surface_texture_manager.h"
89 #include "content/browser/android/in_process_surface_texture_manager.h"
90 #include "content/browser/android/tracing_controller_android.h"
91 #include "content/browser/screen_orientation/screen_orientation_delegate_android.h"
92 #include "content/public/browser/screen_orientation_provider.h"
93 #include "ui/gl/gl_surface.h"
96 #if defined(OS_MACOSX)
97 #include "media/base/mac/avfoundation_glue.h"
100 #if defined(OS_MACOSX) && !defined(OS_IOS)
101 #include "base/memory/memory_pressure_monitor_mac.h"
102 #include "content/browser/bootstrap_sandbox_mac.h"
103 #include "content/browser/browser_io_surface_manager_mac.h"
104 #include "content/browser/cocoa/system_hotkey_helper_mac.h"
105 #include "content/browser/compositor/browser_compositor_view_mac.h"
106 #include "content/browser/in_process_io_surface_manager_mac.h"
107 #include "content/browser/theme_helper_mac.h"
112 #include <commctrl.h>
113 #include <shellapi.h>
115 #include "base/memory/memory_pressure_monitor_win.h"
116 #include "content/browser/system_message_window_win.h"
117 #include "content/common/sandbox_win.h"
118 #include "net/base/winsock_init.h"
119 #include "ui/base/l10n/l10n_util_win.h"
122 #if defined(OS_CHROMEOS)
123 #include "base/memory/memory_pressure_monitor_chromeos.h"
124 #include "chromeos/chromeos_switches.h"
127 #if defined(USE_GLIB)
128 #include <glib-object.h>
131 #if defined(OS_LINUX) && defined(USE_UDEV)
132 #include "content/browser/device_monitor_udev.h"
133 #elif defined(OS_MACOSX) && !defined(OS_IOS)
134 #include "content/browser/device_monitor_mac.h"
137 #if defined(OS_POSIX) && !defined(OS_MACOSX)
138 #include "content/browser/renderer_host/render_sandbox_host_linux.h"
139 #include "content/browser/zygote_host/zygote_host_impl_linux.h"
140 #include "sandbox/linux/suid/client/setuid_sandbox_host.h"
143 #if defined(ENABLE_PLUGINS)
144 #include "content/browser/plugin_service_impl.h"
147 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
148 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
152 #include "ui/gfx/x/x11_connection.h"
153 #include "ui/gfx/x/x11_types.h"
156 // One of the linux specific headers defines this as a macro.
164 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
165 void SetupSandbox(const base::CommandLine
& parsed_command_line
) {
166 TRACE_EVENT0("startup", "SetupSandbox");
167 base::FilePath sandbox_binary
;
169 scoped_ptr
<sandbox::SetuidSandboxHost
> setuid_sandbox_host(
170 sandbox::SetuidSandboxHost::Create());
172 const bool want_setuid_sandbox
=
173 !parsed_command_line
.HasSwitch(switches::kNoSandbox
) &&
174 !parsed_command_line
.HasSwitch(switches::kDisableSetuidSandbox
) &&
175 !setuid_sandbox_host
->IsDisabledViaEnvironment();
177 static const char no_suid_error
[] =
178 "Running without the SUID sandbox! See "
179 "https://code.google.com/p/chromium/wiki/LinuxSUIDSandboxDevelopment "
180 "for more information on developing with the sandbox on.";
181 if (want_setuid_sandbox
) {
182 sandbox_binary
= setuid_sandbox_host
->GetSandboxBinaryPath();
183 if (sandbox_binary
.empty()) {
184 // This needs to be fatal. Talk to security@chromium.org if you feel
186 LOG(FATAL
) << no_suid_error
;
189 LOG(ERROR
) << no_suid_error
;
192 // Tickle the sandbox host and zygote host so they fork now.
193 RenderSandboxHostLinux::GetInstance()->Init();
194 ZygoteHostImpl::GetInstance()->Init(sandbox_binary
.value());
198 #if defined(USE_GLIB)
199 static void GLibLogHandler(const gchar
* log_domain
,
200 GLogLevelFlags log_level
,
201 const gchar
* message
,
204 log_domain
= "<unknown>";
206 message
= "<no message>";
208 if (strstr(message
, "Unable to retrieve the file info for")) {
209 LOG(ERROR
) << "GTK File code error: " << message
;
210 } else if (strstr(message
, "Could not find the icon") &&
211 strstr(log_domain
, "Gtk")) {
212 LOG(ERROR
) << "GTK icon error: " << message
;
213 } else if (strstr(message
, "Theme file for default has no") ||
214 strstr(message
, "Theme directory") ||
215 strstr(message
, "theme pixmap") ||
216 strstr(message
, "locate theme engine")) {
217 LOG(ERROR
) << "GTK theme error: " << message
;
218 } else if (strstr(message
, "Unable to create Ubuntu Menu Proxy") &&
219 strstr(log_domain
, "<unknown>")) {
220 LOG(ERROR
) << "GTK menu proxy create failed";
221 } else if (strstr(message
, "Out of memory") &&
222 strstr(log_domain
, "<unknown>")) {
223 LOG(ERROR
) << "DBus call timeout or out of memory: "
224 << "http://crosbug.com/15496";
225 } else if (strstr(message
, "Could not connect: Connection refused") &&
226 strstr(log_domain
, "<unknown>")) {
227 LOG(ERROR
) << "DConf settings backend could not connect to session bus: "
228 << "http://crbug.com/179797";
229 } else if (strstr(message
, "Attempting to store changes into") ||
230 strstr(message
, "Attempting to set the permissions of")) {
231 LOG(ERROR
) << message
<< " (http://bugs.chromium.org/161366)";
232 } else if (strstr(message
, "drawable is not a native X11 window")) {
233 LOG(ERROR
) << message
<< " (http://bugs.chromium.org/329991)";
234 } else if (strstr(message
, "Cannot do system-bus activation with no user")) {
235 LOG(ERROR
) << message
<< " (http://crbug.com/431005)";
237 LOG(DFATAL
) << log_domain
<< ": " << message
;
241 static void SetUpGLibLogHandler() {
242 // Register GLib-handled assertions to go through our logging system.
243 const char* kLogDomains
[] = { NULL
, "Gtk", "Gdk", "GLib", "GLib-GObject" };
244 for (size_t i
= 0; i
< arraysize(kLogDomains
); i
++) {
245 g_log_set_handler(kLogDomains
[i
],
246 static_cast<GLogLevelFlags
>(G_LOG_FLAG_RECURSION
|
249 G_LOG_LEVEL_CRITICAL
|
250 G_LOG_LEVEL_WARNING
),
257 void OnStoppedStartupTracing(const base::FilePath
& trace_file
) {
258 VLOG(0) << "Completed startup tracing to " << trace_file
.value();
261 // Disable optimizations for this block of functions so the compiler doesn't
262 // merge them all together. This makes it possible to tell what thread was
263 // unresponsive by inspecting the callstack.
264 MSVC_DISABLE_OPTIMIZE()
265 MSVC_PUSH_DISABLE_WARNING(4748)
267 NOINLINE
void ResetThread_DB(scoped_ptr
<BrowserProcessSubThread
> thread
) {
268 volatile int inhibit_comdat
= __LINE__
;
269 ALLOW_UNUSED_LOCAL(inhibit_comdat
);
273 NOINLINE
void ResetThread_FILE(scoped_ptr
<BrowserProcessSubThread
> thread
) {
274 volatile int inhibit_comdat
= __LINE__
;
275 ALLOW_UNUSED_LOCAL(inhibit_comdat
);
279 NOINLINE
void ResetThread_FILE_USER_BLOCKING(
280 scoped_ptr
<BrowserProcessSubThread
> thread
) {
281 volatile int inhibit_comdat
= __LINE__
;
282 ALLOW_UNUSED_LOCAL(inhibit_comdat
);
286 NOINLINE
void ResetThread_PROCESS_LAUNCHER(
287 scoped_ptr
<BrowserProcessSubThread
> thread
) {
288 volatile int inhibit_comdat
= __LINE__
;
289 ALLOW_UNUSED_LOCAL(inhibit_comdat
);
293 NOINLINE
void ResetThread_CACHE(scoped_ptr
<BrowserProcessSubThread
> thread
) {
294 volatile int inhibit_comdat
= __LINE__
;
295 ALLOW_UNUSED_LOCAL(inhibit_comdat
);
299 NOINLINE
void ResetThread_IO(scoped_ptr
<BrowserProcessSubThread
> thread
) {
300 volatile int inhibit_comdat
= __LINE__
;
301 ALLOW_UNUSED_LOCAL(inhibit_comdat
);
306 NOINLINE
void ResetThread_IndexedDb(scoped_ptr
<base::Thread
> thread
) {
307 volatile int inhibit_comdat
= __LINE__
;
308 ALLOW_UNUSED_LOCAL(inhibit_comdat
);
314 MSVC_ENABLE_OPTIMIZE();
317 // Creates a memory pressure monitor using automatic thresholds, or those
318 // specified on the command-line. Ownership is passed to the caller.
319 base::win::MemoryPressureMonitor
* CreateWinMemoryPressureMonitor(
320 const base::CommandLine
& parsed_command_line
) {
321 std::vector
<std::string
> thresholds
;
323 parsed_command_line
.GetSwitchValueASCII(
324 switches::kMemoryPressureThresholdsMb
),
328 int moderate_threshold_mb
= 0;
329 int critical_threshold_mb
= 0;
330 if (thresholds
.size() == 2 &&
331 base::StringToInt(thresholds
[0], &moderate_threshold_mb
) &&
332 base::StringToInt(thresholds
[1], &critical_threshold_mb
) &&
333 moderate_threshold_mb
>= critical_threshold_mb
&&
334 critical_threshold_mb
>= 0) {
335 return new base::win::MemoryPressureMonitor(moderate_threshold_mb
,
336 critical_threshold_mb
);
339 // In absence of valid switches use the automatic defaults.
340 return new base::win::MemoryPressureMonitor();
342 #endif // defined(OS_WIN)
346 // The currently-running BrowserMainLoop. There can be one or zero.
347 BrowserMainLoop
* g_current_browser_main_loop
= NULL
;
349 // For measuring memory usage after each task. Behind a command line flag.
350 class BrowserMainLoop::MemoryObserver
: public base::MessageLoop::TaskObserver
{
353 ~MemoryObserver() override
{}
355 void WillProcessTask(const base::PendingTask
& pending_task
) override
{}
357 void DidProcessTask(const base::PendingTask
& pending_task
) override
{
358 #if !defined(OS_IOS) // No ProcessMetrics on IOS.
359 scoped_ptr
<base::ProcessMetrics
> process_metrics(
360 base::ProcessMetrics::CreateProcessMetrics(
361 #if defined(OS_MACOSX)
362 base::GetCurrentProcessHandle(), NULL
));
364 base::GetCurrentProcessHandle()));
366 size_t private_bytes
;
367 process_metrics
->GetMemoryBytes(&private_bytes
, NULL
);
368 LOCAL_HISTOGRAM_MEMORY_KB("Memory.BrowserUsed", private_bytes
>> 10);
372 DISALLOW_COPY_AND_ASSIGN(MemoryObserver
);
376 // BrowserMainLoop construction / destruction =============================
378 BrowserMainLoop
* BrowserMainLoop::GetInstance() {
379 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
380 return g_current_browser_main_loop
;
383 BrowserMainLoop::BrowserMainLoop(const MainFunctionParams
& parameters
)
384 : parameters_(parameters
),
385 parsed_command_line_(parameters
.command_line
),
386 result_code_(RESULT_CODE_NORMAL_EXIT
),
387 created_threads_(false),
388 // ContentMainRunner should have enabled tracing of the browser process
389 // when kTraceStartup is in the command line.
391 parameters
.command_line
.HasSwitch(switches::kTraceStartup
)) {
392 DCHECK(!g_current_browser_main_loop
);
393 g_current_browser_main_loop
= this;
396 BrowserMainLoop::~BrowserMainLoop() {
397 DCHECK_EQ(this, g_current_browser_main_loop
);
399 ui::Clipboard::DestroyClipboardForCurrentThread();
400 #endif // !defined(OS_IOS)
401 g_current_browser_main_loop
= NULL
;
404 void BrowserMainLoop::Init() {
405 TRACE_EVENT0("startup", "BrowserMainLoop::Init");
406 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::Init");
409 GetContentClient()->browser()->CreateBrowserMainParts(parameters_
));
412 // BrowserMainLoop stages ==================================================
414 void BrowserMainLoop::EarlyInitialization() {
415 TRACE_EVENT0("startup", "BrowserMainLoop::EarlyInitialization");
416 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::EarlyInitialization");
418 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
419 // No thread should be created before this call, as SetupSandbox()
420 // will end-up using fork().
421 SetupSandbox(parsed_command_line_
);
425 if (UsingInProcessGpu()) {
426 if (!gfx::InitializeThreadedX11()) {
427 LOG(ERROR
) << "Failed to put Xlib into threaded mode.";
432 // GLib's spawning of new processes is buggy, so it's important that at this
433 // point GLib does not need to start DBUS. Chrome should always start with
434 // DBUS_SESSION_BUS_ADDRESS properly set. See crbug.com/309093.
435 #if defined(USE_GLIB)
436 // g_type_init will be deprecated in 2.36. 2.35 is the development
437 // version for 2.36, hence do not call g_type_init starting 2.35.
438 // http://developer.gnome.org/gobject/unstable/gobject-Type-Information.html#g-type-init
439 #if !GLIB_CHECK_VERSION(2, 35, 0)
440 // GLib type system initialization. Needed at least for gconf,
441 // used in net/proxy/proxy_config_service_linux.cc. Most likely
442 // this is superfluous as gtk_init() ought to do this. It's
443 // definitely harmless, so retained as a reminder of this
444 // requirement for gconf.
448 SetUpGLibLogHandler();
452 parts_
->PreEarlyInitialization();
454 #if defined(OS_MACOSX)
455 // We use quite a few file descriptors for our IPC, and the default limit on
456 // the Mac is low (256), so bump it up.
457 base::SetFdLimit(1024);
461 net::EnsureWinsockInit();
464 #if !defined(USE_OPENSSL)
465 // We want to be sure to init NSPR on the main thread.
466 crypto::EnsureNSPRInit();
467 #endif // !defined(USE_OPENSSL)
470 if (parsed_command_line_
.HasSwitch(switches::kRendererProcessLimit
)) {
471 std::string limit_string
= parsed_command_line_
.GetSwitchValueASCII(
472 switches::kRendererProcessLimit
);
473 size_t process_limit
;
474 if (base::StringToSizeT(limit_string
, &process_limit
)) {
475 RenderProcessHost::SetMaxRendererProcessCount(process_limit
);
478 #endif // !defined(OS_IOS)
480 if (parsed_command_line_
.HasSwitch(switches::kEnableNativeGpuMemoryBuffers
)) {
481 BrowserGpuChannelHostFactory::EnableGpuMemoryBufferFactoryUsage(
482 gfx::GpuMemoryBuffer::MAP
);
483 BrowserGpuChannelHostFactory::EnableGpuMemoryBufferFactoryUsage(
484 gfx::GpuMemoryBuffer::PERSISTENT_MAP
);
487 #if defined(USE_OZONE)
488 BrowserGpuChannelHostFactory::EnableGpuMemoryBufferFactoryUsage(
489 gfx::GpuMemoryBuffer::SCANOUT
);
492 base::DiscardableMemoryAllocator::SetInstance(
493 HostDiscardableSharedMemoryManager::current());
496 parts_
->PostEarlyInitialization();
499 void BrowserMainLoop::PreMainMessageLoopStart() {
501 TRACE_EVENT0("startup",
502 "BrowserMainLoop::MainMessageLoopStart:PreMainMessageLoopStart");
503 parts_
->PreMainMessageLoopStart();
507 // If we're running tests (ui_task is non-null), then the ResourceBundle
508 // has already been initialized.
509 if (!parameters_
.ui_task
) {
510 // Override the configured locale with the user's preferred UI language.
511 l10n_util::OverrideLocaleWithUILanguageList();
516 void BrowserMainLoop::MainMessageLoopStart() {
517 // DO NOT add more code here. Use PreMainMessageLoopStart() above or
518 // PostMainMessageLoopStart() below.
520 TRACE_EVENT0("startup", "BrowserMainLoop::MainMessageLoopStart");
521 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::MainMessageLoopStart");
523 // Create a MessageLoop if one does not already exist for the current thread.
524 if (!base::MessageLoop::current())
525 main_message_loop_
.reset(new base::MessageLoopForUI
);
527 InitializeMainThread();
530 void BrowserMainLoop::PostMainMessageLoopStart() {
532 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SystemMonitor");
533 system_monitor_
.reset(new base::SystemMonitor
);
536 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:PowerMonitor");
537 scoped_ptr
<base::PowerMonitorSource
> power_monitor_source(
538 new base::PowerMonitorDeviceSource());
539 power_monitor_
.reset(new base::PowerMonitor(power_monitor_source
.Pass()));
542 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:HighResTimerManager");
543 hi_res_timer_manager_
.reset(new base::HighResolutionTimerManager
);
546 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:NetworkChangeNotifier");
547 network_change_notifier_
.reset(net::NetworkChangeNotifier::Create());
552 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MediaFeatures");
553 media::InitializeMediaLibrary();
556 TRACE_EVENT0("startup",
557 "BrowserMainLoop::Subsystem:ContentWebUIController");
558 WebUIControllerFactory::RegisterFactory(
559 ContentWebUIControllerFactory::GetInstance());
563 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:OnlineStateObserver");
564 online_state_observer_
.reset(new BrowserOnlineStateObserver
);
568 system_stats_monitor_
.reset(
569 new base::trace_event::TraceEventSystemStatsMonitor(
570 base::ThreadTaskRunnerHandle::Get()));
572 #endif // !defined(OS_IOS)
575 system_message_window_
.reset(new SystemMessageWindowWin
);
579 parts_
->PostMainMessageLoopStart();
582 // Start tracing to a file if needed. Only do this after starting the main
583 // message loop to avoid calling MessagePumpForUI::ScheduleWork() before
584 // MessagePumpForUI::Start() as it will crash the browser.
585 if (is_tracing_startup_
) {
586 TRACE_EVENT0("startup", "BrowserMainLoop::InitStartupTracing");
587 InitStartupTracing(parsed_command_line_
);
589 #endif // !defined(OS_IOS)
591 #if defined(OS_ANDROID)
593 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SurfaceTextureManager");
594 if (parsed_command_line_
.HasSwitch(switches::kSingleProcess
)) {
595 SurfaceTextureManager::SetInstance(
596 InProcessSurfaceTextureManager::GetInstance());
598 SurfaceTextureManager::SetInstance(
599 BrowserSurfaceTextureManager::GetInstance());
603 if (!parsed_command_line_
.HasSwitch(
604 switches::kDisableScreenOrientationLock
)) {
605 TRACE_EVENT0("startup",
606 "BrowserMainLoop::Subsystem:ScreenOrientationProvider");
607 screen_orientation_delegate_
.reset(
608 new ScreenOrientationDelegateAndroid());
609 ScreenOrientationProvider::SetDelegate(screen_orientation_delegate_
.get());
613 #if defined(OS_MACOSX) && !defined(OS_IOS)
615 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:IOSurfaceManager");
616 if (parsed_command_line_
.HasSwitch(switches::kSingleProcess
)) {
617 IOSurfaceManager::SetInstance(InProcessIOSurfaceManager::GetInstance());
619 IOSurfaceManager::SetInstance(BrowserIOSurfaceManager::GetInstance());
624 if (parsed_command_line_
.HasSwitch(switches::kMemoryMetrics
)) {
625 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MemoryObserver");
626 memory_observer_
.reset(new MemoryObserver());
627 base::MessageLoop::current()->AddTaskObserver(memory_observer_
.get());
630 if (parsed_command_line_
.HasSwitch(
631 switches::kEnableAggressiveDOMStorageFlushing
)) {
632 TRACE_EVENT0("startup",
633 "BrowserMainLoop::Subsystem:EnableAggressiveCommitDelay");
634 DOMStorageArea::EnableAggressiveCommitDelay();
637 base::trace_event::MemoryDumpManager::GetInstance()->Initialize();
639 // Enable the dump providers.
640 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
641 HostSharedBitmapManager::current());
643 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
644 trace_memory_controller_
.reset(new base::trace_event::TraceMemoryController(
645 base::MessageLoop::current()->task_runner(),
646 ::HeapProfilerWithPseudoStackStart
, ::HeapProfilerStop
,
651 int BrowserMainLoop::PreCreateThreads() {
653 TRACE_EVENT0("startup",
654 "BrowserMainLoop::CreateThreads:PreCreateThreads");
655 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::PreCreateThreads");
657 result_code_
= parts_
->PreCreateThreads();
660 // TODO(chrisha): Abstract away this construction mess to a helper function,
661 // once MemoryPressureMonitor is made a concrete class.
662 #if defined(OS_CHROMEOS)
663 if (chromeos::switches::MemoryPressureHandlingEnabled()) {
664 memory_pressure_monitor_
.reset(new base::chromeos::MemoryPressureMonitor(
665 chromeos::switches::GetMemoryPressureThresholds()));
667 #elif defined(OS_MACOSX) && !defined(OS_IOS)
668 memory_pressure_monitor_
.reset(new base::mac::MemoryPressureMonitor());
669 #elif defined(OS_WIN)
670 memory_pressure_monitor_
.reset(CreateWinMemoryPressureMonitor(
671 parsed_command_line_
));
674 #if defined(ENABLE_PLUGINS)
675 // Prior to any processing happening on the io thread, we create the
676 // plugin service as it is predominantly used from the io thread,
677 // but must be created on the main thread. The service ctor is
678 // inexpensive and does not invoke the io_thread() accessor.
680 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads:PluginService");
681 PluginService::GetInstance()->Init();
685 #if defined(OS_MACOSX)
687 // Initialize AVFoundation if supported, for audio and video.
688 TRACE_EVENT0("startup",
689 "BrowserMainLoop::CreateThreads:InitializeAVFoundation");
690 AVFoundationGlue::InitializeAVFoundation();
694 // Need to initialize in-process GpuDataManager before creating threads.
695 // It's unsafe to append the gpu command line switches to the global
696 // CommandLine::ForCurrentProcess object after threads are created.
697 if (UsingInProcessGpu()) {
698 bool initialize_gpu_data_manager
= true;
699 #if defined(OS_ANDROID)
700 if (!gfx::GLSurface::InitializeOneOff()) {
701 // Single-process Android WebView supports no gpu.
702 LOG(ERROR
) << "GLSurface::InitializeOneOff failed";
703 initialize_gpu_data_manager
= false;
707 // Initialize the GpuDataManager before we set up the MessageLoops because
708 // otherwise we'll trigger the assertion about doing IO on the UI thread.
709 if (initialize_gpu_data_manager
)
710 GpuDataManagerImpl::GetInstance()->Initialize();
713 #if !defined(OS_IOS) && (!defined(GOOGLE_CHROME_BUILD) || defined(OS_ANDROID))
714 // Single-process is an unsupported and not fully tested mode, so
715 // don't enable it for official Chrome builds (except on Android).
716 if (parsed_command_line_
.HasSwitch(switches::kSingleProcess
))
717 RenderProcessHost::SetRunRendererInProcess(true);
723 void BrowserMainLoop::CreateStartupTasks() {
724 TRACE_EVENT0("startup", "BrowserMainLoop::CreateStartupTasks");
725 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::CreateStartupTasks");
727 // First time through, we really want to create all the tasks
728 if (!startup_task_runner_
.get()) {
729 #if defined(OS_ANDROID)
730 startup_task_runner_
= make_scoped_ptr(
731 new StartupTaskRunner(base::Bind(&BrowserStartupComplete
),
732 base::ThreadTaskRunnerHandle::Get()));
734 startup_task_runner_
= make_scoped_ptr(
735 new StartupTaskRunner(base::Callback
<void(int)>(),
736 base::ThreadTaskRunnerHandle::Get()));
738 StartupTask pre_create_threads
=
739 base::Bind(&BrowserMainLoop::PreCreateThreads
, base::Unretained(this));
740 startup_task_runner_
->AddTask(pre_create_threads
);
742 StartupTask create_threads
=
743 base::Bind(&BrowserMainLoop::CreateThreads
, base::Unretained(this));
744 startup_task_runner_
->AddTask(create_threads
);
746 StartupTask browser_thread_started
= base::Bind(
747 &BrowserMainLoop::BrowserThreadsStarted
, base::Unretained(this));
748 startup_task_runner_
->AddTask(browser_thread_started
);
750 StartupTask pre_main_message_loop_run
= base::Bind(
751 &BrowserMainLoop::PreMainMessageLoopRun
, base::Unretained(this));
752 startup_task_runner_
->AddTask(pre_main_message_loop_run
);
754 #if defined(OS_ANDROID)
755 if (BrowserMayStartAsynchronously()) {
756 startup_task_runner_
->StartRunningTasksAsync();
760 #if defined(OS_ANDROID)
761 if (!BrowserMayStartAsynchronously()) {
762 // A second request for asynchronous startup can be ignored, so
763 // StartupRunningTasksAsync is only called first time through. If, however,
764 // this is a request for synchronous startup then it must override any
765 // previous call for async startup, so we call RunAllTasksNow()
767 startup_task_runner_
->RunAllTasksNow();
770 startup_task_runner_
->RunAllTasksNow();
774 int BrowserMainLoop::CreateThreads() {
775 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads");
776 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::CreateThreads");
778 base::Thread::Options io_message_loop_options
;
779 io_message_loop_options
.message_loop_type
= base::MessageLoop::TYPE_IO
;
780 base::Thread::Options ui_message_loop_options
;
781 ui_message_loop_options
.message_loop_type
= base::MessageLoop::TYPE_UI
;
783 // Start threads in the order they occur in the BrowserThread::ID
784 // enumeration, except for BrowserThread::UI which is the main
787 // Must be size_t so we can increment it.
788 for (size_t thread_id
= BrowserThread::UI
+ 1;
789 thread_id
< BrowserThread::ID_COUNT
;
791 scoped_ptr
<BrowserProcessSubThread
>* thread_to_start
= NULL
;
792 base::Thread::Options options
;
795 case BrowserThread::DB
:
796 TRACE_EVENT_BEGIN1("startup",
797 "BrowserMainLoop::CreateThreads:start",
798 "Thread", "BrowserThread::DB");
799 thread_to_start
= &db_thread_
;
800 options
.timer_slack
= base::TIMER_SLACK_MAXIMUM
;
802 case BrowserThread::FILE_USER_BLOCKING
:
803 TRACE_EVENT_BEGIN1("startup",
804 "BrowserMainLoop::CreateThreads:start",
805 "Thread", "BrowserThread::FILE_USER_BLOCKING");
806 thread_to_start
= &file_user_blocking_thread_
;
808 case BrowserThread::FILE:
809 TRACE_EVENT_BEGIN1("startup",
810 "BrowserMainLoop::CreateThreads:start",
811 "Thread", "BrowserThread::FILE");
812 thread_to_start
= &file_thread_
;
814 // On Windows, the FILE thread needs to be have a UI message loop
815 // which pumps messages in such a way that Google Update can
816 // communicate back to us.
817 options
= ui_message_loop_options
;
819 options
= io_message_loop_options
;
821 options
.timer_slack
= base::TIMER_SLACK_MAXIMUM
;
823 case BrowserThread::PROCESS_LAUNCHER
:
824 TRACE_EVENT_BEGIN1("startup",
825 "BrowserMainLoop::CreateThreads:start",
826 "Thread", "BrowserThread::PROCESS_LAUNCHER");
827 thread_to_start
= &process_launcher_thread_
;
828 options
.timer_slack
= base::TIMER_SLACK_MAXIMUM
;
830 case BrowserThread::CACHE
:
831 TRACE_EVENT_BEGIN1("startup",
832 "BrowserMainLoop::CreateThreads:start",
833 "Thread", "BrowserThread::CACHE");
834 thread_to_start
= &cache_thread_
;
835 options
= io_message_loop_options
;
836 options
.timer_slack
= base::TIMER_SLACK_MAXIMUM
;
838 case BrowserThread::IO
:
839 TRACE_EVENT_BEGIN1("startup",
840 "BrowserMainLoop::CreateThreads:start",
841 "Thread", "BrowserThread::IO");
842 thread_to_start
= &io_thread_
;
843 options
= io_message_loop_options
;
845 case BrowserThread::UI
:
846 case BrowserThread::ID_COUNT
:
852 BrowserThread::ID id
= static_cast<BrowserThread::ID
>(thread_id
);
854 if (thread_to_start
) {
855 (*thread_to_start
).reset(new BrowserProcessSubThread(id
));
856 if (!(*thread_to_start
)->StartWithOptions(options
)) {
857 LOG(FATAL
) << "Failed to start the browser thread: id == " << id
;
863 TRACE_EVENT_END0("startup", "BrowserMainLoop::CreateThreads:start");
865 created_threads_
= true;
869 int BrowserMainLoop::PreMainMessageLoopRun() {
871 TRACE_EVENT0("startup",
872 "BrowserMainLoop::CreateThreads:PreMainMessageLoopRun");
874 "Startup", "BrowserMainLoop::PreMainMessageLoopRun");
876 parts_
->PreMainMessageLoopRun();
879 // If the UI thread blocks, the whole UI is unresponsive.
880 // Do not allow disk IO from the UI thread.
881 base::ThreadRestrictions::SetIOAllowed(false);
882 base::ThreadRestrictions::DisallowWaiting();
886 void BrowserMainLoop::RunMainMessageLoopParts() {
887 TRACE_EVENT_BEGIN_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
889 bool ran_main_loop
= false;
891 ran_main_loop
= parts_
->MainMessageLoopRun(&result_code_
);
894 MainMessageLoopRun();
896 TRACE_EVENT_END_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
899 void BrowserMainLoop::ShutdownThreadsAndCleanUp() {
900 if (!created_threads_
) {
901 // Called early, nothing to do
904 TRACE_EVENT0("shutdown", "BrowserMainLoop::ShutdownThreadsAndCleanUp");
906 // Teardown may start in PostMainMessageLoopRun, and during teardown we
907 // need to be able to perform IO.
908 base::ThreadRestrictions::SetIOAllowed(true);
909 BrowserThread::PostTask(
910 BrowserThread::IO
, FROM_HERE
,
911 base::Bind(base::IgnoreResult(&base::ThreadRestrictions::SetIOAllowed
),
914 mojo_shell_context_
.reset();
917 if (RenderProcessHost::run_renderer_in_process())
918 RenderProcessHostImpl::ShutDownInProcessRenderer();
922 TRACE_EVENT0("shutdown",
923 "BrowserMainLoop::Subsystem:PostMainMessageLoopRun");
924 parts_
->PostMainMessageLoopRun();
927 trace_memory_controller_
.reset();
928 system_stats_monitor_
.reset();
931 // Destroying the GpuProcessHostUIShims on the UI thread posts a task to
932 // delete related objects on the GPU thread. This must be done before
933 // stopping the GPU thread. The GPU thread will close IPC channels to renderer
934 // processes so this has to happen before stopping the IO thread.
936 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUProcessHostShim");
937 GpuProcessHostUIShim::DestroyAll();
939 // Cancel pending requests and prevent new requests.
940 if (resource_dispatcher_host_
) {
941 TRACE_EVENT0("shutdown",
942 "BrowserMainLoop::Subsystem:ResourceDispatcherHost");
943 resource_dispatcher_host_
.get()->Shutdown();
946 memory_pressure_monitor_
.reset();
948 #if defined(OS_MACOSX)
949 BrowserCompositorMac::DisableRecyclingForShutdown();
952 #if defined(USE_AURA) || defined(OS_MACOSX)
954 TRACE_EVENT0("shutdown",
955 "BrowserMainLoop::Subsystem:ImageTransportFactory");
956 ImageTransportFactory::Terminate();
960 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
961 ZygoteHostImpl::GetInstance()->TearDownAfterLastChild();
962 #endif // defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
964 // The device monitors are using |system_monitor_| as dependency, so delete
965 // them before |system_monitor_| goes away.
966 // On Mac and windows, the monitor needs to be destroyed on the same thread
967 // as they were created. On Linux, the monitor will be deleted when IO thread
970 system_message_window_
.reset();
971 #elif defined(OS_MACOSX)
972 device_monitor_mac_
.reset();
974 #endif // !defined(OS_IOS)
976 // Must be size_t so we can subtract from it.
977 for (size_t thread_id
= BrowserThread::ID_COUNT
- 1;
978 thread_id
>= (BrowserThread::UI
+ 1);
980 // Find the thread object we want to stop. Looping over all valid
981 // BrowserThread IDs and DCHECKing on a missing case in the switch
982 // statement helps avoid a mismatch between this code and the
983 // BrowserThread::ID enumeration.
985 // The destruction order is the reverse order of occurrence in the
986 // BrowserThread::ID list. The rationale for the order is as
987 // follows (need to be filled in a bit):
990 // - The IO thread is the only user of the CACHE thread.
992 // - The PROCESS_LAUNCHER thread must be stopped after IO in case
993 // the IO thread posted a task to terminate a process on the
994 // process launcher thread.
996 // - (Not sure why DB stops last.)
998 case BrowserThread::DB
: {
999 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DBThread");
1000 ResetThread_DB(db_thread_
.Pass());
1003 case BrowserThread::FILE: {
1004 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:FileThread");
1005 #if !defined(OS_IOS)
1006 // Clean up state that lives on or uses the file_thread_ before
1008 if (resource_dispatcher_host_
)
1009 resource_dispatcher_host_
.get()->save_file_manager()->Shutdown();
1010 #endif // !defined(OS_IOS)
1011 ResetThread_FILE(file_thread_
.Pass());
1014 case BrowserThread::FILE_USER_BLOCKING
: {
1015 TRACE_EVENT0("shutdown",
1016 "BrowserMainLoop::Subsystem:FileUserBlockingThread");
1017 ResetThread_FILE_USER_BLOCKING(file_user_blocking_thread_
.Pass());
1020 case BrowserThread::PROCESS_LAUNCHER
: {
1021 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:LauncherThread");
1022 ResetThread_PROCESS_LAUNCHER(process_launcher_thread_
.Pass());
1025 case BrowserThread::CACHE
: {
1026 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:CacheThread");
1027 ResetThread_CACHE(cache_thread_
.Pass());
1030 case BrowserThread::IO
: {
1031 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IOThread");
1032 ResetThread_IO(io_thread_
.Pass());
1035 case BrowserThread::UI
:
1036 case BrowserThread::ID_COUNT
:
1043 #if !defined(OS_IOS)
1045 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IndexedDBThread");
1046 ResetThread_IndexedDb(indexed_db_thread_
.Pass());
1050 // Close the blocking I/O pool after the other threads. Other threads such
1051 // as the I/O thread may need to schedule work like closing files or flushing
1052 // data during shutdown, so the blocking pool needs to be available. There
1053 // may also be slow operations pending that will blcok shutdown, so closing
1054 // it here (which will block until required operations are complete) gives
1055 // more head start for those operations to finish.
1057 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:ThreadPool");
1058 BrowserThreadImpl::ShutdownThreadPool();
1061 #if !defined(OS_IOS)
1062 // Must happen after the IO thread is shutdown since this may be accessed from
1065 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUChannelFactory");
1066 if (BrowserGpuChannelHostFactory::instance())
1067 BrowserGpuChannelHostFactory::Terminate();
1070 // Must happen after the I/O thread is shutdown since this class lives on the
1071 // I/O thread and isn't threadsafe.
1073 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GamepadService");
1074 GamepadService::GetInstance()->Terminate();
1077 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:SensorService");
1078 DeviceInertialSensorService::GetInstance()->Shutdown();
1081 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:BatteryStatusService");
1082 device::BatteryStatusService::GetInstance()->Shutdown();
1085 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DeleteDataSources");
1086 URLDataManager::DeleteDataSources();
1088 #endif // !defined(OS_IOS)
1091 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:PostDestroyThreads");
1092 parts_
->PostDestroyThreads();
1096 void BrowserMainLoop::StopStartupTracingTimer() {
1097 startup_trace_timer_
.Stop();
1100 void BrowserMainLoop::InitializeMainThread() {
1101 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeMainThread");
1102 static const char kThreadName
[] = "CrBrowserMain";
1103 base::PlatformThread::SetName(kThreadName
);
1104 if (main_message_loop_
)
1105 main_message_loop_
->set_thread_name(kThreadName
);
1107 // Register the main thread by instantiating it, but don't call any methods.
1109 new BrowserThreadImpl(BrowserThread::UI
, base::MessageLoop::current()));
1112 int BrowserMainLoop::BrowserThreadsStarted() {
1113 TRACE_EVENT0("startup", "BrowserMainLoop::BrowserThreadsStarted");
1115 #if !defined(OS_IOS)
1116 indexed_db_thread_
.reset(new base::Thread("IndexedDB"));
1117 indexed_db_thread_
->Start();
1120 #if !defined(OS_IOS)
1121 HistogramSynchronizer::GetInstance();
1124 // GpuDataManager for in-process initialized in PreCreateThreads.
1125 bool initialize_gpu_data_manager
= !UsingInProcessGpu();
1126 #if defined(OS_ANDROID)
1127 // Up the priority of anything that touches with display tasks
1128 // (this thread is UI thread, and io_thread_ is for IPCs).
1129 io_thread_
->SetPriority(base::ThreadPriority::DISPLAY
);
1130 base::PlatformThread::SetThreadPriority(base::PlatformThread::CurrentHandle(),
1131 base::ThreadPriority::DISPLAY
);
1133 // On Android, GLSurface::InitializeOneOff() must be called before
1134 // initalizing the GpuDataManagerImpl as it uses the GL bindings.
1135 // TODO(sievers): Shouldn't need to init full bindings to determine GL
1136 // version/vendor strings. crbug.com/326295
1137 if (initialize_gpu_data_manager
) {
1138 // Note InitializeOneOff is not safe either for in-process gpu after
1139 // creating threads, since it may race with the gpu thread.
1140 if (!gfx::GLSurface::InitializeOneOff()) {
1141 LOG(FATAL
) << "GLSurface::InitializeOneOff failed";
1146 if (initialize_gpu_data_manager
)
1147 GpuDataManagerImpl::GetInstance()->Initialize();
1149 bool always_uses_gpu
= true;
1150 bool established_gpu_channel
= false;
1151 #if defined(OS_ANDROID)
1152 // TODO(crbug.com/439322): This should be set to |true|.
1153 established_gpu_channel
= false;
1154 BrowserGpuChannelHostFactory::Initialize(established_gpu_channel
);
1155 #elif defined(USE_AURA) || defined(OS_MACOSX)
1156 established_gpu_channel
= true;
1157 if (!GpuDataManagerImpl::GetInstance()->CanUseGpuBrowserCompositor() ||
1158 parsed_command_line_
.HasSwitch(switches::kDisableGpuEarlyInit
)) {
1159 established_gpu_channel
= always_uses_gpu
= false;
1161 BrowserGpuChannelHostFactory::Initialize(established_gpu_channel
);
1162 ImageTransportFactory::Initialize();
1163 #if defined(USE_AURA)
1164 if (aura::Env::GetInstance()) {
1165 aura::Env::GetInstance()->set_context_factory(GetContextFactory());
1167 #endif // defined(USE_AURA)
1168 #endif // defined(OS_ANDROID)
1170 // Enable the GpuMemoryBuffer dump provider with IO thread affinity. Note that
1171 // unregistration happens on the IO thread (See
1172 // BrowserProcessSubThread::IOThreadPreCleanUp).
1173 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
1174 BrowserGpuMemoryBufferManager::current(), io_thread_
->task_runner());
1177 TRACE_EVENT0("startup", "BrowserThreadsStarted::Subsystem:AudioMan");
1178 audio_manager_
.reset(media::AudioManager::CreateWithHangTimer(
1179 MediaInternals::GetInstance(), io_thread_
->task_runner()));
1183 TRACE_EVENT0("startup", "BrowserThreadsStarted::Subsystem:MidiManager");
1184 midi_manager_
.reset(media::midi::MidiManager::Create());
1187 #if defined(OS_LINUX) && defined(USE_UDEV)
1188 device_monitor_linux_
.reset(new DeviceMonitorLinux());
1189 #elif defined(OS_MACOSX)
1190 device_monitor_mac_
.reset(new DeviceMonitorMac());
1194 UMA_HISTOGRAM_BOOLEAN("Windows.Win32kRendererLockdown",
1195 IsWin32kRendererLockdownEnabled());
1197 // RDH needs the IO thread to be created
1199 TRACE_EVENT0("startup",
1200 "BrowserMainLoop::BrowserThreadsStarted:InitResourceDispatcherHost");
1201 resource_dispatcher_host_
.reset(new ResourceDispatcherHostImpl());
1204 // MediaStreamManager needs the IO thread to be created.
1206 TRACE_EVENT0("startup",
1207 "BrowserMainLoop::BrowserThreadsStarted:InitMediaStreamManager");
1208 media_stream_manager_
.reset(new MediaStreamManager(audio_manager_
.get()));
1212 TRACE_EVENT0("startup",
1213 "BrowserMainLoop::BrowserThreadsStarted:InitSpeechRecognition");
1214 speech_recognition_manager_
.reset(new SpeechRecognitionManagerImpl(
1215 audio_manager_
.get(), media_stream_manager_
.get()));
1221 "BrowserMainLoop::BrowserThreadsStarted::InitUserInputMonitor");
1222 user_input_monitor_
= media::UserInputMonitor::Create(
1223 io_thread_
->task_runner(), main_thread_
->task_runner());
1227 TRACE_EVENT0("startup",
1228 "BrowserMainLoop::BrowserThreadsStarted::TimeZoneMonitor");
1229 time_zone_monitor_
= TimeZoneMonitor::Create();
1232 // Alert the clipboard class to which threads are allowed to access the
1234 std::vector
<base::PlatformThreadId
> allowed_clipboard_threads
;
1235 // The current thread is the UI thread.
1236 allowed_clipboard_threads
.push_back(base::PlatformThread::CurrentId());
1238 // On Windows, clipboards are also used on the FILE or IO threads.
1239 allowed_clipboard_threads
.push_back(file_thread_
->thread_id());
1240 allowed_clipboard_threads
.push_back(io_thread_
->thread_id());
1242 ui::Clipboard::SetAllowedThreads(allowed_clipboard_threads
);
1244 // When running the GPU thread in-process, avoid optimistically starting it
1245 // since creating the GPU thread races against creation of the one-and-only
1246 // ChildProcess instance which is created by the renderer thread.
1247 if (GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL
) &&
1248 !established_gpu_channel
&&
1250 !UsingInProcessGpu()) {
1251 TRACE_EVENT_INSTANT0("gpu", "Post task to launch GPU process",
1252 TRACE_EVENT_SCOPE_THREAD
);
1253 BrowserThread::PostTask(
1254 BrowserThread::IO
, FROM_HERE
,
1255 base::Bind(base::IgnoreResult(&GpuProcessHost::Get
),
1256 GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED
,
1257 CAUSE_FOR_GPU_LAUNCH_BROWSER_STARTUP
));
1260 #if defined(OS_MACOSX)
1261 ThemeHelperMac::GetInstance();
1262 SystemHotkeyHelperMac::GetInstance()->DeferredLoadSystemHotkeys();
1263 if (ShouldEnableBootstrapSandbox()) {
1264 TRACE_EVENT0("startup",
1265 "BrowserMainLoop::BrowserThreadsStarted:BootstrapSandbox");
1266 CHECK(GetBootstrapSandbox());
1268 #endif // defined(OS_MACOSX)
1270 #endif // !defined(OS_IOS)
1272 mojo_shell_context_
.reset(new MojoShellContext
);
1274 return result_code_
;
1277 bool BrowserMainLoop::UsingInProcessGpu() const {
1278 return parsed_command_line_
.HasSwitch(switches::kSingleProcess
) ||
1279 parsed_command_line_
.HasSwitch(switches::kInProcessGPU
);
1282 bool BrowserMainLoop::InitializeToolkit() {
1283 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeToolkit");
1284 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::InitializeToolkit");
1286 // TODO(evan): this function is rather subtle, due to the variety
1287 // of intersecting ifdefs we have. To keep it easy to follow, there
1288 // are no #else branches on any #ifs.
1289 // TODO(stevenjb): Move platform specific code into platform specific Parts
1290 // (Need to add InitializeToolkit stage to BrowserParts).
1291 // See also GTK setup in EarlyInitialization, above, and associated comments.
1294 // Init common control sex.
1295 INITCOMMONCONTROLSEX config
;
1296 config
.dwSize
= sizeof(config
);
1297 config
.dwICC
= ICC_WIN95_CLASSES
;
1298 if (!InitCommonControlsEx(&config
))
1302 #if defined(USE_AURA)
1304 #if defined(USE_X11)
1305 if (!gfx::GetXDisplay())
1309 // Env creates the compositor. Aura widgets need the compositor to be created
1310 // before they can be initialized by the browser.
1311 aura::Env::CreateInstance(true);
1312 #endif // defined(USE_AURA)
1315 parts_
->ToolkitInitialized();
1320 void BrowserMainLoop::MainMessageLoopRun() {
1321 #if defined(OS_ANDROID)
1322 // Android's main message loop is the Java message loop.
1325 DCHECK(base::MessageLoopForUI::IsCurrent());
1326 if (parameters_
.ui_task
) {
1327 base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE
,
1328 *parameters_
.ui_task
);
1331 base::RunLoop run_loop
;
1336 base::FilePath
BrowserMainLoop::GetStartupTraceFileName(
1337 const base::CommandLine
& command_line
) const {
1338 base::FilePath trace_file
= command_line
.GetSwitchValuePath(
1339 switches::kTraceStartupFile
);
1340 // trace_file = "none" means that startup events will show up for the next
1341 // begin/end tracing (via about:tracing or AutomationProxy::BeginTracing/
1342 // EndTracing, for example).
1343 if (trace_file
== base::FilePath().AppendASCII("none"))
1346 if (trace_file
.empty()) {
1347 #if defined(OS_ANDROID)
1348 TracingControllerAndroid::GenerateTracingFilePath(&trace_file
);
1350 // Default to saving the startup trace into the current dir.
1351 trace_file
= base::FilePath().AppendASCII("chrometrace.log");
1358 void BrowserMainLoop::InitStartupTracing(
1359 const base::CommandLine
& command_line
) {
1360 DCHECK(is_tracing_startup_
);
1362 startup_trace_file_
= GetStartupTraceFileName(parsed_command_line_
);
1364 std::string delay_str
= command_line
.GetSwitchValueASCII(
1365 switches::kTraceStartupDuration
);
1367 if (!delay_str
.empty() && !base::StringToInt(delay_str
, &delay_secs
)) {
1368 DLOG(WARNING
) << "Could not parse --" << switches::kTraceStartupDuration
1369 << "=" << delay_str
<< " defaulting to 5 (secs)";
1373 startup_trace_timer_
.Start(FROM_HERE
,
1374 base::TimeDelta::FromSeconds(delay_secs
),
1376 &BrowserMainLoop::EndStartupTracing
);
1379 void BrowserMainLoop::EndStartupTracing() {
1380 DCHECK(is_tracing_startup_
);
1382 is_tracing_startup_
= false;
1383 TracingController::GetInstance()->DisableRecording(
1384 TracingController::CreateFileSink(
1385 startup_trace_file_
,
1386 base::Bind(OnStoppedStartupTracing
, startup_trace_file_
)));
1389 } // namespace content