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 "skia/ext/skia_memory_dump_provider.h"
71 #include "ui/base/clipboard/clipboard.h"
73 #if defined(USE_AURA) || (defined(OS_MACOSX) && !defined(OS_IOS))
74 #include "content/browser/compositor/image_transport_factory.h"
78 #include "content/public/browser/context_factory.h"
79 #include "ui/aura/env.h"
83 #include "content/browser/renderer_host/render_process_host_impl.h"
86 #if defined(OS_ANDROID)
87 #include "base/android/jni_android.h"
88 #include "content/browser/android/browser_startup_controller.h"
89 #include "content/browser/android/browser_surface_texture_manager.h"
90 #include "content/browser/android/in_process_surface_texture_manager.h"
91 #include "content/browser/android/tracing_controller_android.h"
92 #include "content/browser/screen_orientation/screen_orientation_delegate_android.h"
93 #include "content/public/browser/screen_orientation_provider.h"
94 #include "ui/gl/gl_surface.h"
97 #if defined(OS_MACOSX)
98 #include "media/base/mac/avfoundation_glue.h"
101 #if defined(OS_MACOSX) && !defined(OS_IOS)
102 #include "base/memory/memory_pressure_monitor_mac.h"
103 #include "content/browser/bootstrap_sandbox_mac.h"
104 #include "content/browser/browser_io_surface_manager_mac.h"
105 #include "content/browser/cocoa/system_hotkey_helper_mac.h"
106 #include "content/browser/compositor/browser_compositor_view_mac.h"
107 #include "content/browser/in_process_io_surface_manager_mac.h"
108 #include "content/browser/theme_helper_mac.h"
111 #if defined(USE_OZONE)
112 #include "ui/ozone/public/client_native_pixmap_factory.h"
117 #include <commctrl.h>
118 #include <shellapi.h>
120 #include "base/memory/memory_pressure_monitor_win.h"
121 #include "content/browser/system_message_window_win.h"
122 #include "content/common/sandbox_win.h"
123 #include "net/base/winsock_init.h"
124 #include "ui/base/l10n/l10n_util_win.h"
127 #if defined(OS_CHROMEOS)
128 #include "base/memory/memory_pressure_monitor_chromeos.h"
129 #include "chromeos/chromeos_switches.h"
132 #if defined(USE_GLIB)
133 #include <glib-object.h>
136 #if defined(OS_LINUX) && defined(USE_UDEV)
137 #include "content/browser/device_monitor_udev.h"
138 #elif defined(OS_MACOSX) && !defined(OS_IOS)
139 #include "content/browser/device_monitor_mac.h"
142 #if defined(OS_POSIX) && !defined(OS_MACOSX)
143 #include "content/browser/renderer_host/render_sandbox_host_linux.h"
144 #include "content/browser/zygote_host/zygote_host_impl_linux.h"
145 #include "sandbox/linux/suid/client/setuid_sandbox_host.h"
148 #if defined(ENABLE_PLUGINS)
149 #include "content/browser/plugin_service_impl.h"
152 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
153 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
157 #include "ui/gfx/x/x11_connection.h"
158 #include "ui/gfx/x/x11_types.h"
161 // One of the linux specific headers defines this as a macro.
169 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
170 void SetupSandbox(const base::CommandLine
& parsed_command_line
) {
171 TRACE_EVENT0("startup", "SetupSandbox");
172 base::FilePath sandbox_binary
;
174 scoped_ptr
<sandbox::SetuidSandboxHost
> setuid_sandbox_host(
175 sandbox::SetuidSandboxHost::Create());
177 const bool want_setuid_sandbox
=
178 !parsed_command_line
.HasSwitch(switches::kNoSandbox
) &&
179 !parsed_command_line
.HasSwitch(switches::kDisableSetuidSandbox
) &&
180 !setuid_sandbox_host
->IsDisabledViaEnvironment();
182 static const char no_suid_error
[] =
183 "Running without the SUID sandbox! See "
184 "https://code.google.com/p/chromium/wiki/LinuxSUIDSandboxDevelopment "
185 "for more information on developing with the sandbox on.";
186 if (want_setuid_sandbox
) {
187 sandbox_binary
= setuid_sandbox_host
->GetSandboxBinaryPath();
188 if (sandbox_binary
.empty()) {
189 // This needs to be fatal. Talk to security@chromium.org if you feel
191 LOG(FATAL
) << no_suid_error
;
194 LOG(ERROR
) << no_suid_error
;
197 // Tickle the sandbox host and zygote host so they fork now.
198 RenderSandboxHostLinux::GetInstance()->Init();
199 ZygoteHostImpl::GetInstance()->Init(sandbox_binary
.value());
203 #if defined(USE_GLIB)
204 static void GLibLogHandler(const gchar
* log_domain
,
205 GLogLevelFlags log_level
,
206 const gchar
* message
,
209 log_domain
= "<unknown>";
211 message
= "<no message>";
213 if (strstr(message
, "Unable to retrieve the file info for")) {
214 LOG(ERROR
) << "GTK File code error: " << message
;
215 } else if (strstr(message
, "Could not find the icon") &&
216 strstr(log_domain
, "Gtk")) {
217 LOG(ERROR
) << "GTK icon error: " << message
;
218 } else if (strstr(message
, "Theme file for default has no") ||
219 strstr(message
, "Theme directory") ||
220 strstr(message
, "theme pixmap") ||
221 strstr(message
, "locate theme engine")) {
222 LOG(ERROR
) << "GTK theme error: " << message
;
223 } else if (strstr(message
, "Unable to create Ubuntu Menu Proxy") &&
224 strstr(log_domain
, "<unknown>")) {
225 LOG(ERROR
) << "GTK menu proxy create failed";
226 } else if (strstr(message
, "Out of memory") &&
227 strstr(log_domain
, "<unknown>")) {
228 LOG(ERROR
) << "DBus call timeout or out of memory: "
229 << "http://crosbug.com/15496";
230 } else if (strstr(message
, "Could not connect: Connection refused") &&
231 strstr(log_domain
, "<unknown>")) {
232 LOG(ERROR
) << "DConf settings backend could not connect to session bus: "
233 << "http://crbug.com/179797";
234 } else if (strstr(message
, "Attempting to store changes into") ||
235 strstr(message
, "Attempting to set the permissions of")) {
236 LOG(ERROR
) << message
<< " (http://bugs.chromium.org/161366)";
237 } else if (strstr(message
, "drawable is not a native X11 window")) {
238 LOG(ERROR
) << message
<< " (http://bugs.chromium.org/329991)";
239 } else if (strstr(message
, "Cannot do system-bus activation with no user")) {
240 LOG(ERROR
) << message
<< " (http://crbug.com/431005)";
242 LOG(DFATAL
) << log_domain
<< ": " << message
;
246 static void SetUpGLibLogHandler() {
247 // Register GLib-handled assertions to go through our logging system.
248 const char* kLogDomains
[] = { NULL
, "Gtk", "Gdk", "GLib", "GLib-GObject" };
249 for (size_t i
= 0; i
< arraysize(kLogDomains
); i
++) {
250 g_log_set_handler(kLogDomains
[i
],
251 static_cast<GLogLevelFlags
>(G_LOG_FLAG_RECURSION
|
254 G_LOG_LEVEL_CRITICAL
|
255 G_LOG_LEVEL_WARNING
),
262 void OnStoppedStartupTracing(const base::FilePath
& trace_file
) {
263 VLOG(0) << "Completed startup tracing to " << trace_file
.value();
266 // Disable optimizations for this block of functions so the compiler doesn't
267 // merge them all together. This makes it possible to tell what thread was
268 // unresponsive by inspecting the callstack.
269 MSVC_DISABLE_OPTIMIZE()
270 MSVC_PUSH_DISABLE_WARNING(4748)
272 NOINLINE
void ResetThread_DB(scoped_ptr
<BrowserProcessSubThread
> thread
) {
273 volatile int inhibit_comdat
= __LINE__
;
274 ALLOW_UNUSED_LOCAL(inhibit_comdat
);
278 NOINLINE
void ResetThread_FILE(scoped_ptr
<BrowserProcessSubThread
> thread
) {
279 volatile int inhibit_comdat
= __LINE__
;
280 ALLOW_UNUSED_LOCAL(inhibit_comdat
);
284 NOINLINE
void ResetThread_FILE_USER_BLOCKING(
285 scoped_ptr
<BrowserProcessSubThread
> thread
) {
286 volatile int inhibit_comdat
= __LINE__
;
287 ALLOW_UNUSED_LOCAL(inhibit_comdat
);
291 NOINLINE
void ResetThread_PROCESS_LAUNCHER(
292 scoped_ptr
<BrowserProcessSubThread
> thread
) {
293 volatile int inhibit_comdat
= __LINE__
;
294 ALLOW_UNUSED_LOCAL(inhibit_comdat
);
298 NOINLINE
void ResetThread_CACHE(scoped_ptr
<BrowserProcessSubThread
> thread
) {
299 volatile int inhibit_comdat
= __LINE__
;
300 ALLOW_UNUSED_LOCAL(inhibit_comdat
);
304 NOINLINE
void ResetThread_IO(scoped_ptr
<BrowserProcessSubThread
> thread
) {
305 volatile int inhibit_comdat
= __LINE__
;
306 ALLOW_UNUSED_LOCAL(inhibit_comdat
);
311 NOINLINE
void ResetThread_IndexedDb(scoped_ptr
<base::Thread
> thread
) {
312 volatile int inhibit_comdat
= __LINE__
;
313 ALLOW_UNUSED_LOCAL(inhibit_comdat
);
319 MSVC_ENABLE_OPTIMIZE();
322 // Creates a memory pressure monitor using automatic thresholds, or those
323 // specified on the command-line. Ownership is passed to the caller.
324 base::win::MemoryPressureMonitor
* CreateWinMemoryPressureMonitor(
325 const base::CommandLine
& parsed_command_line
) {
326 std::vector
<std::string
> thresholds
;
328 parsed_command_line
.GetSwitchValueASCII(
329 switches::kMemoryPressureThresholdsMb
),
333 int moderate_threshold_mb
= 0;
334 int critical_threshold_mb
= 0;
335 if (thresholds
.size() == 2 &&
336 base::StringToInt(thresholds
[0], &moderate_threshold_mb
) &&
337 base::StringToInt(thresholds
[1], &critical_threshold_mb
) &&
338 moderate_threshold_mb
>= critical_threshold_mb
&&
339 critical_threshold_mb
>= 0) {
340 return new base::win::MemoryPressureMonitor(moderate_threshold_mb
,
341 critical_threshold_mb
);
344 // In absence of valid switches use the automatic defaults.
345 return new base::win::MemoryPressureMonitor();
347 #endif // defined(OS_WIN)
351 // The currently-running BrowserMainLoop. There can be one or zero.
352 BrowserMainLoop
* g_current_browser_main_loop
= NULL
;
354 // For measuring memory usage after each task. Behind a command line flag.
355 class BrowserMainLoop::MemoryObserver
: public base::MessageLoop::TaskObserver
{
358 ~MemoryObserver() override
{}
360 void WillProcessTask(const base::PendingTask
& pending_task
) override
{}
362 void DidProcessTask(const base::PendingTask
& pending_task
) override
{
363 #if !defined(OS_IOS) // No ProcessMetrics on IOS.
364 scoped_ptr
<base::ProcessMetrics
> process_metrics(
365 base::ProcessMetrics::CreateProcessMetrics(
366 #if defined(OS_MACOSX)
367 base::GetCurrentProcessHandle(), NULL
));
369 base::GetCurrentProcessHandle()));
371 size_t private_bytes
;
372 process_metrics
->GetMemoryBytes(&private_bytes
, NULL
);
373 LOCAL_HISTOGRAM_MEMORY_KB("Memory.BrowserUsed", private_bytes
>> 10);
377 DISALLOW_COPY_AND_ASSIGN(MemoryObserver
);
381 // BrowserMainLoop construction / destruction =============================
383 BrowserMainLoop
* BrowserMainLoop::GetInstance() {
384 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
385 return g_current_browser_main_loop
;
388 BrowserMainLoop::BrowserMainLoop(const MainFunctionParams
& parameters
)
389 : parameters_(parameters
),
390 parsed_command_line_(parameters
.command_line
),
391 result_code_(RESULT_CODE_NORMAL_EXIT
),
392 created_threads_(false),
393 // ContentMainRunner should have enabled tracing of the browser process
394 // when kTraceStartup is in the command line.
396 parameters
.command_line
.HasSwitch(switches::kTraceStartup
)) {
397 DCHECK(!g_current_browser_main_loop
);
398 g_current_browser_main_loop
= this;
401 BrowserMainLoop::~BrowserMainLoop() {
402 DCHECK_EQ(this, g_current_browser_main_loop
);
404 ui::Clipboard::DestroyClipboardForCurrentThread();
405 #endif // !defined(OS_IOS)
406 g_current_browser_main_loop
= NULL
;
409 void BrowserMainLoop::Init() {
410 TRACE_EVENT0("startup", "BrowserMainLoop::Init");
411 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::Init");
414 GetContentClient()->browser()->CreateBrowserMainParts(parameters_
));
417 // BrowserMainLoop stages ==================================================
419 void BrowserMainLoop::EarlyInitialization() {
420 TRACE_EVENT0("startup", "BrowserMainLoop::EarlyInitialization");
421 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::EarlyInitialization");
423 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
424 // No thread should be created before this call, as SetupSandbox()
425 // will end-up using fork().
426 SetupSandbox(parsed_command_line_
);
430 if (UsingInProcessGpu()) {
431 if (!gfx::InitializeThreadedX11()) {
432 LOG(ERROR
) << "Failed to put Xlib into threaded mode.";
437 // GLib's spawning of new processes is buggy, so it's important that at this
438 // point GLib does not need to start DBUS. Chrome should always start with
439 // DBUS_SESSION_BUS_ADDRESS properly set. See crbug.com/309093.
440 #if defined(USE_GLIB)
441 // g_type_init will be deprecated in 2.36. 2.35 is the development
442 // version for 2.36, hence do not call g_type_init starting 2.35.
443 // http://developer.gnome.org/gobject/unstable/gobject-Type-Information.html#g-type-init
444 #if !GLIB_CHECK_VERSION(2, 35, 0)
445 // GLib type system initialization. Needed at least for gconf,
446 // used in net/proxy/proxy_config_service_linux.cc. Most likely
447 // this is superfluous as gtk_init() ought to do this. It's
448 // definitely harmless, so retained as a reminder of this
449 // requirement for gconf.
453 SetUpGLibLogHandler();
457 parts_
->PreEarlyInitialization();
459 #if defined(OS_MACOSX)
460 // We use quite a few file descriptors for our IPC, and the default limit on
461 // the Mac is low (256), so bump it up.
462 base::SetFdLimit(1024);
466 net::EnsureWinsockInit();
469 #if !defined(USE_OPENSSL)
470 // We want to be sure to init NSPR on the main thread.
471 crypto::EnsureNSPRInit();
472 #endif // !defined(USE_OPENSSL)
475 if (parsed_command_line_
.HasSwitch(switches::kRendererProcessLimit
)) {
476 std::string limit_string
= parsed_command_line_
.GetSwitchValueASCII(
477 switches::kRendererProcessLimit
);
478 size_t process_limit
;
479 if (base::StringToSizeT(limit_string
, &process_limit
)) {
480 RenderProcessHost::SetMaxRendererProcessCount(process_limit
);
483 #endif // !defined(OS_IOS)
485 // TODO(boliu): kSingleProcess check is a temporary workaround for
486 // in-process Android WebView. crbug.com/503724 tracks proper fix.
487 if (!parsed_command_line_
.HasSwitch(switches::kSingleProcess
)) {
488 base::DiscardableMemoryAllocator::SetInstance(
489 HostDiscardableSharedMemoryManager::current());
493 parts_
->PostEarlyInitialization();
496 void BrowserMainLoop::PreMainMessageLoopStart() {
498 TRACE_EVENT0("startup",
499 "BrowserMainLoop::MainMessageLoopStart:PreMainMessageLoopStart");
500 parts_
->PreMainMessageLoopStart();
504 // If we're running tests (ui_task is non-null), then the ResourceBundle
505 // has already been initialized.
506 if (!parameters_
.ui_task
) {
507 // Override the configured locale with the user's preferred UI language.
508 l10n_util::OverrideLocaleWithUILanguageList();
513 void BrowserMainLoop::MainMessageLoopStart() {
514 // DO NOT add more code here. Use PreMainMessageLoopStart() above or
515 // PostMainMessageLoopStart() below.
517 TRACE_EVENT0("startup", "BrowserMainLoop::MainMessageLoopStart");
518 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::MainMessageLoopStart");
520 // Create a MessageLoop if one does not already exist for the current thread.
521 if (!base::MessageLoop::current())
522 main_message_loop_
.reset(new base::MessageLoopForUI
);
524 InitializeMainThread();
527 void BrowserMainLoop::PostMainMessageLoopStart() {
529 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SystemMonitor");
530 system_monitor_
.reset(new base::SystemMonitor
);
533 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:PowerMonitor");
534 scoped_ptr
<base::PowerMonitorSource
> power_monitor_source(
535 new base::PowerMonitorDeviceSource());
536 power_monitor_
.reset(new base::PowerMonitor(power_monitor_source
.Pass()));
539 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:HighResTimerManager");
540 hi_res_timer_manager_
.reset(new base::HighResolutionTimerManager
);
543 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:NetworkChangeNotifier");
544 network_change_notifier_
.reset(net::NetworkChangeNotifier::Create());
549 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MediaFeatures");
550 media::InitializeMediaLibrary();
553 TRACE_EVENT0("startup",
554 "BrowserMainLoop::Subsystem:ContentWebUIController");
555 WebUIControllerFactory::RegisterFactory(
556 ContentWebUIControllerFactory::GetInstance());
560 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:OnlineStateObserver");
561 online_state_observer_
.reset(new BrowserOnlineStateObserver
);
565 system_stats_monitor_
.reset(
566 new base::trace_event::TraceEventSystemStatsMonitor(
567 base::ThreadTaskRunnerHandle::Get()));
569 #endif // !defined(OS_IOS)
572 system_message_window_
.reset(new SystemMessageWindowWin
);
576 parts_
->PostMainMessageLoopStart();
579 // Start tracing to a file if needed. Only do this after starting the main
580 // message loop to avoid calling MessagePumpForUI::ScheduleWork() before
581 // MessagePumpForUI::Start() as it will crash the browser.
582 if (is_tracing_startup_
) {
583 TRACE_EVENT0("startup", "BrowserMainLoop::InitStartupTracing");
584 InitStartupTracing(parsed_command_line_
);
586 #endif // !defined(OS_IOS)
588 #if defined(OS_ANDROID)
590 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SurfaceTextureManager");
591 if (parsed_command_line_
.HasSwitch(switches::kSingleProcess
)) {
592 SurfaceTextureManager::SetInstance(
593 InProcessSurfaceTextureManager::GetInstance());
595 SurfaceTextureManager::SetInstance(
596 BrowserSurfaceTextureManager::GetInstance());
600 if (!parsed_command_line_
.HasSwitch(
601 switches::kDisableScreenOrientationLock
)) {
602 TRACE_EVENT0("startup",
603 "BrowserMainLoop::Subsystem:ScreenOrientationProvider");
604 screen_orientation_delegate_
.reset(
605 new ScreenOrientationDelegateAndroid());
606 ScreenOrientationProvider::SetDelegate(screen_orientation_delegate_
.get());
610 #if defined(OS_MACOSX) && !defined(OS_IOS)
612 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:IOSurfaceManager");
613 if (parsed_command_line_
.HasSwitch(switches::kSingleProcess
)) {
614 IOSurfaceManager::SetInstance(InProcessIOSurfaceManager::GetInstance());
616 IOSurfaceManager::SetInstance(BrowserIOSurfaceManager::GetInstance());
621 #if defined(USE_OZONE)
622 client_native_pixmap_factory_
= ui::ClientNativePixmapFactory::Create();
623 ui::ClientNativePixmapFactory::SetInstance(
624 client_native_pixmap_factory_
.get());
627 if (parsed_command_line_
.HasSwitch(switches::kMemoryMetrics
)) {
628 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MemoryObserver");
629 memory_observer_
.reset(new MemoryObserver());
630 base::MessageLoop::current()->AddTaskObserver(memory_observer_
.get());
633 if (parsed_command_line_
.HasSwitch(
634 switches::kEnableAggressiveDOMStorageFlushing
)) {
635 TRACE_EVENT0("startup",
636 "BrowserMainLoop::Subsystem:EnableAggressiveCommitDelay");
637 DOMStorageArea::EnableAggressiveCommitDelay();
640 base::trace_event::MemoryDumpManager::GetInstance()->Initialize();
642 // Enable the dump providers.
643 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
644 HostSharedBitmapManager::current());
645 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
646 skia::SkiaMemoryDumpProvider::GetInstance());
648 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
649 trace_memory_controller_
.reset(new base::trace_event::TraceMemoryController(
650 base::MessageLoop::current()->task_runner(),
651 ::HeapProfilerWithPseudoStackStart
, ::HeapProfilerStop
,
656 int BrowserMainLoop::PreCreateThreads() {
657 // Need to initialize in-process GpuDataManager before creating threads.
658 // It's unsafe to append the gpu command line switches to the global
659 // CommandLine::ForCurrentProcess object after threads are created.
660 // Also need to initialize before BrowserMainParts::PreCreateThreads, so
661 // BrowserMainParts has a hook to set GpuDataManager strings before
662 // starting Gpu process.
663 GpuDataManagerImpl::GetInstance()->Initialize();
666 TRACE_EVENT0("startup",
667 "BrowserMainLoop::CreateThreads:PreCreateThreads");
668 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::PreCreateThreads");
670 result_code_
= parts_
->PreCreateThreads();
673 // TODO(chrisha): Abstract away this construction mess to a helper function,
674 // once MemoryPressureMonitor is made a concrete class.
675 #if defined(OS_CHROMEOS)
676 if (chromeos::switches::MemoryPressureHandlingEnabled()) {
677 memory_pressure_monitor_
.reset(new base::chromeos::MemoryPressureMonitor(
678 chromeos::switches::GetMemoryPressureThresholds()));
680 #elif defined(OS_MACOSX) && !defined(OS_IOS)
681 memory_pressure_monitor_
.reset(new base::mac::MemoryPressureMonitor());
682 #elif defined(OS_WIN)
683 memory_pressure_monitor_
.reset(CreateWinMemoryPressureMonitor(
684 parsed_command_line_
));
687 #if defined(ENABLE_PLUGINS)
688 // Prior to any processing happening on the io thread, we create the
689 // plugin service as it is predominantly used from the io thread,
690 // but must be created on the main thread. The service ctor is
691 // inexpensive and does not invoke the io_thread() accessor.
693 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads:PluginService");
694 PluginService::GetInstance()->Init();
698 #if defined(OS_MACOSX)
700 // Initialize AVFoundation if supported, for audio and video.
701 TRACE_EVENT0("startup",
702 "BrowserMainLoop::CreateThreads:InitializeAVFoundation");
703 AVFoundationGlue::InitializeAVFoundation();
707 #if !defined(OS_IOS) && (!defined(GOOGLE_CHROME_BUILD) || defined(OS_ANDROID))
708 // Single-process is an unsupported and not fully tested mode, so
709 // don't enable it for official Chrome builds (except on Android).
710 if (parsed_command_line_
.HasSwitch(switches::kSingleProcess
))
711 RenderProcessHost::SetRunRendererInProcess(true);
717 void BrowserMainLoop::CreateStartupTasks() {
718 TRACE_EVENT0("startup", "BrowserMainLoop::CreateStartupTasks");
719 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::CreateStartupTasks");
721 // First time through, we really want to create all the tasks
722 if (!startup_task_runner_
.get()) {
723 #if defined(OS_ANDROID)
724 startup_task_runner_
= make_scoped_ptr(
725 new StartupTaskRunner(base::Bind(&BrowserStartupComplete
),
726 base::ThreadTaskRunnerHandle::Get()));
728 startup_task_runner_
= make_scoped_ptr(
729 new StartupTaskRunner(base::Callback
<void(int)>(),
730 base::ThreadTaskRunnerHandle::Get()));
732 StartupTask pre_create_threads
=
733 base::Bind(&BrowserMainLoop::PreCreateThreads
, base::Unretained(this));
734 startup_task_runner_
->AddTask(pre_create_threads
);
736 StartupTask create_threads
=
737 base::Bind(&BrowserMainLoop::CreateThreads
, base::Unretained(this));
738 startup_task_runner_
->AddTask(create_threads
);
740 StartupTask browser_thread_started
= base::Bind(
741 &BrowserMainLoop::BrowserThreadsStarted
, base::Unretained(this));
742 startup_task_runner_
->AddTask(browser_thread_started
);
744 StartupTask pre_main_message_loop_run
= base::Bind(
745 &BrowserMainLoop::PreMainMessageLoopRun
, base::Unretained(this));
746 startup_task_runner_
->AddTask(pre_main_message_loop_run
);
748 #if defined(OS_ANDROID)
749 if (BrowserMayStartAsynchronously()) {
750 startup_task_runner_
->StartRunningTasksAsync();
754 #if defined(OS_ANDROID)
755 if (!BrowserMayStartAsynchronously()) {
756 // A second request for asynchronous startup can be ignored, so
757 // StartupRunningTasksAsync is only called first time through. If, however,
758 // this is a request for synchronous startup then it must override any
759 // previous call for async startup, so we call RunAllTasksNow()
761 startup_task_runner_
->RunAllTasksNow();
764 startup_task_runner_
->RunAllTasksNow();
768 int BrowserMainLoop::CreateThreads() {
769 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads");
770 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::CreateThreads");
772 base::Thread::Options io_message_loop_options
;
773 io_message_loop_options
.message_loop_type
= base::MessageLoop::TYPE_IO
;
774 base::Thread::Options ui_message_loop_options
;
775 ui_message_loop_options
.message_loop_type
= base::MessageLoop::TYPE_UI
;
777 // Start threads in the order they occur in the BrowserThread::ID
778 // enumeration, except for BrowserThread::UI which is the main
781 // Must be size_t so we can increment it.
782 for (size_t thread_id
= BrowserThread::UI
+ 1;
783 thread_id
< BrowserThread::ID_COUNT
;
785 scoped_ptr
<BrowserProcessSubThread
>* thread_to_start
= NULL
;
786 base::Thread::Options options
;
789 case BrowserThread::DB
:
790 TRACE_EVENT_BEGIN1("startup",
791 "BrowserMainLoop::CreateThreads:start",
792 "Thread", "BrowserThread::DB");
793 thread_to_start
= &db_thread_
;
794 options
.timer_slack
= base::TIMER_SLACK_MAXIMUM
;
796 case BrowserThread::FILE_USER_BLOCKING
:
797 TRACE_EVENT_BEGIN1("startup",
798 "BrowserMainLoop::CreateThreads:start",
799 "Thread", "BrowserThread::FILE_USER_BLOCKING");
800 thread_to_start
= &file_user_blocking_thread_
;
802 case BrowserThread::FILE:
803 TRACE_EVENT_BEGIN1("startup",
804 "BrowserMainLoop::CreateThreads:start",
805 "Thread", "BrowserThread::FILE");
806 thread_to_start
= &file_thread_
;
808 // On Windows, the FILE thread needs to be have a UI message loop
809 // which pumps messages in such a way that Google Update can
810 // communicate back to us.
811 options
= ui_message_loop_options
;
813 options
= io_message_loop_options
;
815 options
.timer_slack
= base::TIMER_SLACK_MAXIMUM
;
817 case BrowserThread::PROCESS_LAUNCHER
:
818 TRACE_EVENT_BEGIN1("startup",
819 "BrowserMainLoop::CreateThreads:start",
820 "Thread", "BrowserThread::PROCESS_LAUNCHER");
821 thread_to_start
= &process_launcher_thread_
;
822 options
.timer_slack
= base::TIMER_SLACK_MAXIMUM
;
824 case BrowserThread::CACHE
:
825 TRACE_EVENT_BEGIN1("startup",
826 "BrowserMainLoop::CreateThreads:start",
827 "Thread", "BrowserThread::CACHE");
828 thread_to_start
= &cache_thread_
;
829 options
= io_message_loop_options
;
830 options
.timer_slack
= base::TIMER_SLACK_MAXIMUM
;
832 case BrowserThread::IO
:
833 TRACE_EVENT_BEGIN1("startup",
834 "BrowserMainLoop::CreateThreads:start",
835 "Thread", "BrowserThread::IO");
836 thread_to_start
= &io_thread_
;
837 options
= io_message_loop_options
;
838 #if defined(OS_ANDROID)
839 // Up the priority of the |io_thread_| as some of its IPCs relate to
841 options
.priority
= base::ThreadPriority::DISPLAY
;
844 case BrowserThread::UI
:
845 case BrowserThread::ID_COUNT
:
851 BrowserThread::ID id
= static_cast<BrowserThread::ID
>(thread_id
);
853 if (thread_to_start
) {
854 (*thread_to_start
).reset(new BrowserProcessSubThread(id
));
855 if (!(*thread_to_start
)->StartWithOptions(options
)) {
856 LOG(FATAL
) << "Failed to start the browser thread: id == " << id
;
862 TRACE_EVENT_END0("startup", "BrowserMainLoop::CreateThreads:start");
864 created_threads_
= true;
868 int BrowserMainLoop::PreMainMessageLoopRun() {
870 TRACE_EVENT0("startup",
871 "BrowserMainLoop::CreateThreads:PreMainMessageLoopRun");
873 "Startup", "BrowserMainLoop::PreMainMessageLoopRun");
875 parts_
->PreMainMessageLoopRun();
878 // If the UI thread blocks, the whole UI is unresponsive.
879 // Do not allow disk IO from the UI thread.
880 base::ThreadRestrictions::SetIOAllowed(false);
881 base::ThreadRestrictions::DisallowWaiting();
885 void BrowserMainLoop::RunMainMessageLoopParts() {
886 TRACE_EVENT_BEGIN_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
888 bool ran_main_loop
= false;
890 ran_main_loop
= parts_
->MainMessageLoopRun(&result_code_
);
893 MainMessageLoopRun();
895 TRACE_EVENT_END_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
898 void BrowserMainLoop::ShutdownThreadsAndCleanUp() {
899 if (!created_threads_
) {
900 // Called early, nothing to do
903 TRACE_EVENT0("shutdown", "BrowserMainLoop::ShutdownThreadsAndCleanUp");
905 // Teardown may start in PostMainMessageLoopRun, and during teardown we
906 // need to be able to perform IO.
907 base::ThreadRestrictions::SetIOAllowed(true);
908 BrowserThread::PostTask(
909 BrowserThread::IO
, FROM_HERE
,
910 base::Bind(base::IgnoreResult(&base::ThreadRestrictions::SetIOAllowed
),
913 mojo_shell_context_
.reset();
916 if (RenderProcessHost::run_renderer_in_process())
917 RenderProcessHostImpl::ShutDownInProcessRenderer();
921 TRACE_EVENT0("shutdown",
922 "BrowserMainLoop::Subsystem:PostMainMessageLoopRun");
923 parts_
->PostMainMessageLoopRun();
926 #if defined(USE_AURA)
927 aura::Env::DeleteInstance();
930 trace_memory_controller_
.reset();
931 system_stats_monitor_
.reset();
934 // Destroying the GpuProcessHostUIShims on the UI thread posts a task to
935 // delete related objects on the GPU thread. This must be done before
936 // stopping the GPU thread. The GPU thread will close IPC channels to renderer
937 // processes so this has to happen before stopping the IO thread.
939 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUProcessHostShim");
940 GpuProcessHostUIShim::DestroyAll();
942 // Cancel pending requests and prevent new requests.
943 if (resource_dispatcher_host_
) {
944 TRACE_EVENT0("shutdown",
945 "BrowserMainLoop::Subsystem:ResourceDispatcherHost");
946 resource_dispatcher_host_
.get()->Shutdown();
949 memory_pressure_monitor_
.reset();
951 #if defined(OS_MACOSX)
952 BrowserCompositorMac::DisableRecyclingForShutdown();
955 #if defined(USE_AURA) || defined(OS_MACOSX)
957 TRACE_EVENT0("shutdown",
958 "BrowserMainLoop::Subsystem:ImageTransportFactory");
959 ImageTransportFactory::Terminate();
963 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
964 ZygoteHostImpl::GetInstance()->TearDownAfterLastChild();
965 #endif // defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
967 // The device monitors are using |system_monitor_| as dependency, so delete
968 // them before |system_monitor_| goes away.
969 // On Mac and windows, the monitor needs to be destroyed on the same thread
970 // as they were created. On Linux, the monitor will be deleted when IO thread
973 system_message_window_
.reset();
974 #elif defined(OS_MACOSX)
975 device_monitor_mac_
.reset();
977 #endif // !defined(OS_IOS)
979 // Must be size_t so we can subtract from it.
980 for (size_t thread_id
= BrowserThread::ID_COUNT
- 1;
981 thread_id
>= (BrowserThread::UI
+ 1);
983 // Find the thread object we want to stop. Looping over all valid
984 // BrowserThread IDs and DCHECKing on a missing case in the switch
985 // statement helps avoid a mismatch between this code and the
986 // BrowserThread::ID enumeration.
988 // The destruction order is the reverse order of occurrence in the
989 // BrowserThread::ID list. The rationale for the order is as
990 // follows (need to be filled in a bit):
993 // - The IO thread is the only user of the CACHE thread.
995 // - The PROCESS_LAUNCHER thread must be stopped after IO in case
996 // the IO thread posted a task to terminate a process on the
997 // process launcher thread.
999 // - (Not sure why DB stops last.)
1000 switch (thread_id
) {
1001 case BrowserThread::DB
: {
1002 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DBThread");
1003 ResetThread_DB(db_thread_
.Pass());
1006 case BrowserThread::FILE: {
1007 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:FileThread");
1008 #if !defined(OS_IOS)
1009 // Clean up state that lives on or uses the file_thread_ before
1011 if (resource_dispatcher_host_
)
1012 resource_dispatcher_host_
.get()->save_file_manager()->Shutdown();
1013 #endif // !defined(OS_IOS)
1014 ResetThread_FILE(file_thread_
.Pass());
1017 case BrowserThread::FILE_USER_BLOCKING
: {
1018 TRACE_EVENT0("shutdown",
1019 "BrowserMainLoop::Subsystem:FileUserBlockingThread");
1020 ResetThread_FILE_USER_BLOCKING(file_user_blocking_thread_
.Pass());
1023 case BrowserThread::PROCESS_LAUNCHER
: {
1024 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:LauncherThread");
1025 ResetThread_PROCESS_LAUNCHER(process_launcher_thread_
.Pass());
1028 case BrowserThread::CACHE
: {
1029 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:CacheThread");
1030 ResetThread_CACHE(cache_thread_
.Pass());
1033 case BrowserThread::IO
: {
1034 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IOThread");
1035 ResetThread_IO(io_thread_
.Pass());
1038 case BrowserThread::UI
:
1039 case BrowserThread::ID_COUNT
:
1046 #if !defined(OS_IOS)
1048 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IndexedDBThread");
1049 ResetThread_IndexedDb(indexed_db_thread_
.Pass());
1053 // Close the blocking I/O pool after the other threads. Other threads such
1054 // as the I/O thread may need to schedule work like closing files or flushing
1055 // data during shutdown, so the blocking pool needs to be available. There
1056 // may also be slow operations pending that will blcok shutdown, so closing
1057 // it here (which will block until required operations are complete) gives
1058 // more head start for those operations to finish.
1060 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:ThreadPool");
1061 BrowserThreadImpl::ShutdownThreadPool();
1064 #if !defined(OS_IOS)
1065 // Must happen after the IO thread is shutdown since this may be accessed from
1068 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUChannelFactory");
1069 if (BrowserGpuChannelHostFactory::instance())
1070 BrowserGpuChannelHostFactory::Terminate();
1073 // Must happen after the I/O thread is shutdown since this class lives on the
1074 // I/O thread and isn't threadsafe.
1076 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GamepadService");
1077 GamepadService::GetInstance()->Terminate();
1080 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:SensorService");
1081 DeviceInertialSensorService::GetInstance()->Shutdown();
1084 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:BatteryStatusService");
1085 device::BatteryStatusService::GetInstance()->Shutdown();
1088 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DeleteDataSources");
1089 URLDataManager::DeleteDataSources();
1091 #endif // !defined(OS_IOS)
1094 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:PostDestroyThreads");
1095 parts_
->PostDestroyThreads();
1099 void BrowserMainLoop::StopStartupTracingTimer() {
1100 startup_trace_timer_
.Stop();
1103 void BrowserMainLoop::InitializeMainThread() {
1104 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeMainThread");
1105 static const char kThreadName
[] = "CrBrowserMain";
1106 base::PlatformThread::SetName(kThreadName
);
1107 if (main_message_loop_
)
1108 main_message_loop_
->set_thread_name(kThreadName
);
1110 // Register the main thread by instantiating it, but don't call any methods.
1112 new BrowserThreadImpl(BrowserThread::UI
, base::MessageLoop::current()));
1115 int BrowserMainLoop::BrowserThreadsStarted() {
1116 TRACE_EVENT0("startup", "BrowserMainLoop::BrowserThreadsStarted");
1118 #if !defined(OS_IOS)
1119 indexed_db_thread_
.reset(new base::Thread("IndexedDB"));
1120 indexed_db_thread_
->Start();
1123 #if !defined(OS_IOS)
1124 HistogramSynchronizer::GetInstance();
1126 #if defined(OS_ANDROID)
1127 // Up the priority of the UI thread.
1128 base::PlatformThread::SetCurrentThreadPriority(base::ThreadPriority::DISPLAY
);
1131 bool always_uses_gpu
= true;
1132 bool established_gpu_channel
= false;
1133 #if defined(OS_ANDROID)
1134 // TODO(crbug.com/439322): This should be set to |true|.
1135 established_gpu_channel
= false;
1136 BrowserGpuChannelHostFactory::Initialize(established_gpu_channel
);
1137 #elif defined(USE_AURA) || defined(OS_MACOSX)
1138 established_gpu_channel
= true;
1139 if (!GpuDataManagerImpl::GetInstance()->CanUseGpuBrowserCompositor() ||
1140 parsed_command_line_
.HasSwitch(switches::kDisableGpuEarlyInit
)) {
1141 established_gpu_channel
= always_uses_gpu
= false;
1143 BrowserGpuChannelHostFactory::Initialize(established_gpu_channel
);
1144 ImageTransportFactory::Initialize();
1145 #if defined(USE_AURA)
1146 if (aura::Env::GetInstance()) {
1147 aura::Env::GetInstance()->set_context_factory(GetContextFactory());
1149 #endif // defined(USE_AURA)
1150 #endif // defined(OS_ANDROID)
1152 // Enable the GpuMemoryBuffer dump provider with IO thread affinity. Note that
1153 // unregistration happens on the IO thread (See
1154 // BrowserProcessSubThread::IOThreadPreCleanUp).
1155 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
1156 BrowserGpuMemoryBufferManager::current(), io_thread_
->task_runner());
1159 TRACE_EVENT0("startup", "BrowserThreadsStarted::Subsystem:AudioMan");
1160 audio_manager_
.reset(media::AudioManager::CreateWithHangTimer(
1161 MediaInternals::GetInstance(), io_thread_
->task_runner()));
1165 TRACE_EVENT0("startup", "BrowserThreadsStarted::Subsystem:MidiManager");
1166 midi_manager_
.reset(media::midi::MidiManager::Create());
1169 #if defined(OS_LINUX) && defined(USE_UDEV)
1170 device_monitor_linux_
.reset(new DeviceMonitorLinux());
1171 #elif defined(OS_MACOSX)
1172 device_monitor_mac_
.reset(new DeviceMonitorMac());
1176 UMA_HISTOGRAM_BOOLEAN("Windows.Win32kRendererLockdown",
1177 IsWin32kRendererLockdownEnabled());
1179 // RDH needs the IO thread to be created
1181 TRACE_EVENT0("startup",
1182 "BrowserMainLoop::BrowserThreadsStarted:InitResourceDispatcherHost");
1183 resource_dispatcher_host_
.reset(new ResourceDispatcherHostImpl());
1186 // MediaStreamManager needs the IO thread to be created.
1188 TRACE_EVENT0("startup",
1189 "BrowserMainLoop::BrowserThreadsStarted:InitMediaStreamManager");
1190 media_stream_manager_
.reset(new MediaStreamManager(audio_manager_
.get()));
1194 TRACE_EVENT0("startup",
1195 "BrowserMainLoop::BrowserThreadsStarted:InitSpeechRecognition");
1196 speech_recognition_manager_
.reset(new SpeechRecognitionManagerImpl(
1197 audio_manager_
.get(), media_stream_manager_
.get()));
1203 "BrowserMainLoop::BrowserThreadsStarted::InitUserInputMonitor");
1204 user_input_monitor_
= media::UserInputMonitor::Create(
1205 io_thread_
->task_runner(), main_thread_
->task_runner());
1209 TRACE_EVENT0("startup",
1210 "BrowserMainLoop::BrowserThreadsStarted::TimeZoneMonitor");
1211 time_zone_monitor_
= TimeZoneMonitor::Create();
1214 // Alert the clipboard class to which threads are allowed to access the
1216 std::vector
<base::PlatformThreadId
> allowed_clipboard_threads
;
1217 // The current thread is the UI thread.
1218 allowed_clipboard_threads
.push_back(base::PlatformThread::CurrentId());
1220 // On Windows, clipboards are also used on the FILE or IO threads.
1221 allowed_clipboard_threads
.push_back(file_thread_
->GetThreadId());
1222 allowed_clipboard_threads
.push_back(io_thread_
->GetThreadId());
1224 ui::Clipboard::SetAllowedThreads(allowed_clipboard_threads
);
1226 // When running the GPU thread in-process, avoid optimistically starting it
1227 // since creating the GPU thread races against creation of the one-and-only
1228 // ChildProcess instance which is created by the renderer thread.
1229 if (GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL
) &&
1230 !established_gpu_channel
&&
1232 !UsingInProcessGpu()) {
1233 TRACE_EVENT_INSTANT0("gpu", "Post task to launch GPU process",
1234 TRACE_EVENT_SCOPE_THREAD
);
1235 BrowserThread::PostTask(
1236 BrowserThread::IO
, FROM_HERE
,
1237 base::Bind(base::IgnoreResult(&GpuProcessHost::Get
),
1238 GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED
,
1239 CAUSE_FOR_GPU_LAUNCH_BROWSER_STARTUP
));
1242 #if defined(OS_MACOSX)
1243 ThemeHelperMac::GetInstance();
1244 SystemHotkeyHelperMac::GetInstance()->DeferredLoadSystemHotkeys();
1245 if (ShouldEnableBootstrapSandbox()) {
1246 TRACE_EVENT0("startup",
1247 "BrowserMainLoop::BrowserThreadsStarted:BootstrapSandbox");
1248 CHECK(GetBootstrapSandbox());
1250 #endif // defined(OS_MACOSX)
1252 #endif // !defined(OS_IOS)
1254 mojo_shell_context_
.reset(new MojoShellContext
);
1256 return result_code_
;
1259 bool BrowserMainLoop::UsingInProcessGpu() const {
1260 return parsed_command_line_
.HasSwitch(switches::kSingleProcess
) ||
1261 parsed_command_line_
.HasSwitch(switches::kInProcessGPU
);
1264 bool BrowserMainLoop::InitializeToolkit() {
1265 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeToolkit");
1266 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::InitializeToolkit");
1268 // TODO(evan): this function is rather subtle, due to the variety
1269 // of intersecting ifdefs we have. To keep it easy to follow, there
1270 // are no #else branches on any #ifs.
1271 // TODO(stevenjb): Move platform specific code into platform specific Parts
1272 // (Need to add InitializeToolkit stage to BrowserParts).
1273 // See also GTK setup in EarlyInitialization, above, and associated comments.
1276 // Init common control sex.
1277 INITCOMMONCONTROLSEX config
;
1278 config
.dwSize
= sizeof(config
);
1279 config
.dwICC
= ICC_WIN95_CLASSES
;
1280 if (!InitCommonControlsEx(&config
))
1284 #if defined(USE_AURA)
1286 #if defined(USE_X11)
1287 if (!gfx::GetXDisplay())
1291 // Env creates the compositor. Aura widgets need the compositor to be created
1292 // before they can be initialized by the browser.
1293 aura::Env::CreateInstance(true);
1294 #endif // defined(USE_AURA)
1297 parts_
->ToolkitInitialized();
1302 void BrowserMainLoop::MainMessageLoopRun() {
1303 #if defined(OS_ANDROID)
1304 // Android's main message loop is the Java message loop.
1307 DCHECK(base::MessageLoopForUI::IsCurrent());
1308 if (parameters_
.ui_task
) {
1309 base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE
,
1310 *parameters_
.ui_task
);
1313 base::RunLoop run_loop
;
1318 base::FilePath
BrowserMainLoop::GetStartupTraceFileName(
1319 const base::CommandLine
& command_line
) const {
1320 base::FilePath trace_file
= command_line
.GetSwitchValuePath(
1321 switches::kTraceStartupFile
);
1322 // trace_file = "none" means that startup events will show up for the next
1323 // begin/end tracing (via about:tracing or AutomationProxy::BeginTracing/
1324 // EndTracing, for example).
1325 if (trace_file
== base::FilePath().AppendASCII("none"))
1328 if (trace_file
.empty()) {
1329 #if defined(OS_ANDROID)
1330 TracingControllerAndroid::GenerateTracingFilePath(&trace_file
);
1332 // Default to saving the startup trace into the current dir.
1333 trace_file
= base::FilePath().AppendASCII("chrometrace.log");
1340 void BrowserMainLoop::InitStartupTracing(
1341 const base::CommandLine
& command_line
) {
1342 DCHECK(is_tracing_startup_
);
1344 startup_trace_file_
= GetStartupTraceFileName(parsed_command_line_
);
1346 std::string delay_str
= command_line
.GetSwitchValueASCII(
1347 switches::kTraceStartupDuration
);
1349 if (!delay_str
.empty() && !base::StringToInt(delay_str
, &delay_secs
)) {
1350 DLOG(WARNING
) << "Could not parse --" << switches::kTraceStartupDuration
1351 << "=" << delay_str
<< " defaulting to 5 (secs)";
1355 startup_trace_timer_
.Start(FROM_HERE
,
1356 base::TimeDelta::FromSeconds(delay_secs
),
1358 &BrowserMainLoop::EndStartupTracing
);
1361 void BrowserMainLoop::EndStartupTracing() {
1362 DCHECK(is_tracing_startup_
);
1364 is_tracing_startup_
= false;
1365 TracingController::GetInstance()->DisableRecording(
1366 TracingController::CreateFileSink(
1367 startup_trace_file_
,
1368 base::Bind(OnStoppedStartupTracing
, startup_trace_file_
)));
1371 } // namespace content