1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/browser/browser_main_loop.h"
8 #include "base/command_line.h"
9 #include "base/location.h"
10 #include "base/logging.h"
11 #include "base/memory/memory_pressure_monitor.h"
12 #include "base/metrics/field_trial.h"
13 #include "base/metrics/histogram.h"
14 #include "base/pending_task.h"
15 #include "base/power_monitor/power_monitor.h"
16 #include "base/power_monitor/power_monitor_device_source.h"
17 #include "base/process/process_metrics.h"
18 #include "base/profiler/scoped_profile.h"
19 #include "base/run_loop.h"
20 #include "base/single_thread_task_runner.h"
21 #include "base/strings/string_number_conversions.h"
22 #include "base/strings/string_split.h"
23 #include "base/system_monitor/system_monitor.h"
24 #include "base/thread_task_runner_handle.h"
25 #include "base/threading/thread_restrictions.h"
26 #include "base/timer/hi_res_timer_manager.h"
27 #include "base/trace_event/memory_dump_manager.h"
28 #include "base/trace_event/trace_event.h"
29 #include "components/tracing/tracing_switches.h"
30 #include "content/browser/browser_thread_impl.h"
31 #include "content/browser/device_sensors/device_inertial_sensor_service.h"
32 #include "content/browser/dom_storage/dom_storage_area.h"
33 #include "content/browser/download/save_file_manager.h"
34 #include "content/browser/gamepad/gamepad_service.h"
35 #include "content/browser/gpu/browser_gpu_channel_host_factory.h"
36 #include "content/browser/gpu/browser_gpu_memory_buffer_manager.h"
37 #include "content/browser/gpu/compositor_util.h"
38 #include "content/browser/gpu/gpu_data_manager_impl.h"
39 #include "content/browser/gpu/gpu_process_host.h"
40 #include "content/browser/gpu/gpu_process_host_ui_shim.h"
41 #include "content/browser/histogram_synchronizer.h"
42 #include "content/browser/loader/resource_dispatcher_host_impl.h"
43 #include "content/browser/media/media_internals.h"
44 #include "content/browser/mojo/mojo_shell_context.h"
45 #include "content/browser/net/browser_online_state_observer.h"
46 #include "content/browser/renderer_host/media/media_stream_manager.h"
47 #include "content/browser/speech/speech_recognition_manager_impl.h"
48 #include "content/browser/startup_task_runner.h"
49 #include "content/browser/time_zone_monitor.h"
50 #include "content/browser/webui/content_web_ui_controller_factory.h"
51 #include "content/browser/webui/url_data_manager.h"
52 #include "content/common/content_switches_internal.h"
53 #include "content/common/host_discardable_shared_memory_manager.h"
54 #include "content/common/host_shared_bitmap_manager.h"
55 #include "content/public/browser/browser_main_parts.h"
56 #include "content/public/browser/content_browser_client.h"
57 #include "content/public/browser/render_process_host.h"
58 #include "content/public/browser/tracing_controller.h"
59 #include "content/public/common/content_switches.h"
60 #include "content/public/common/main_function_params.h"
61 #include "content/public/common/result_codes.h"
62 #include "crypto/nss_util.h"
63 #include "device/battery/battery_status_service.h"
64 #include "media/audio/audio_manager.h"
65 #include "media/base/media.h"
66 #include "media/base/user_input_monitor.h"
67 #include "media/midi/midi_manager.h"
68 #include "net/base/network_change_notifier.h"
69 #include "net/socket/client_socket_factory.h"
70 #include "net/ssl/ssl_config_service.h"
71 #include "skia/ext/skia_memory_dump_provider.h"
72 #include "ui/base/clipboard/clipboard.h"
74 #if defined(USE_AURA) || (defined(OS_MACOSX) && !defined(OS_IOS))
75 #include "content/browser/compositor/image_transport_factory.h"
79 #include "content/public/browser/context_factory.h"
80 #include "ui/aura/env.h"
84 #include "content/browser/renderer_host/render_process_host_impl.h"
87 #if defined(OS_ANDROID)
88 #include "base/android/jni_android.h"
89 #include "content/browser/android/browser_startup_controller.h"
90 #include "content/browser/android/browser_surface_texture_manager.h"
91 #include "content/browser/android/in_process_surface_texture_manager.h"
92 #include "content/browser/android/tracing_controller_android.h"
93 #include "content/browser/screen_orientation/screen_orientation_delegate_android.h"
94 #include "content/public/browser/screen_orientation_provider.h"
95 #include "ui/gl/gl_surface.h"
98 #if defined(OS_MACOSX)
99 #include "media/base/mac/avfoundation_glue.h"
102 #if defined(OS_MACOSX) && !defined(OS_IOS)
103 #include "base/memory/memory_pressure_monitor_mac.h"
104 #include "content/browser/bootstrap_sandbox_mac.h"
105 #include "content/browser/browser_io_surface_manager_mac.h"
106 #include "content/browser/cocoa/system_hotkey_helper_mac.h"
107 #include "content/browser/compositor/browser_compositor_view_mac.h"
108 #include "content/browser/in_process_io_surface_manager_mac.h"
109 #include "content/browser/theme_helper_mac.h"
112 #if defined(USE_OZONE)
113 #include "ui/ozone/public/client_native_pixmap_factory.h"
118 #include <commctrl.h>
119 #include <shellapi.h>
121 #include "base/memory/memory_pressure_monitor_win.h"
122 #include "content/browser/system_message_window_win.h"
123 #include "content/common/sandbox_win.h"
124 #include "net/base/winsock_init.h"
125 #include "ui/base/l10n/l10n_util_win.h"
128 #if defined(OS_CHROMEOS)
129 #include "base/memory/memory_pressure_monitor_chromeos.h"
130 #include "chromeos/chromeos_switches.h"
133 #if defined(USE_GLIB)
134 #include <glib-object.h>
137 #if defined(OS_LINUX) && defined(USE_UDEV)
138 #include "content/browser/device_monitor_udev.h"
139 #elif defined(OS_MACOSX) && !defined(OS_IOS)
140 #include "content/browser/device_monitor_mac.h"
143 #if defined(OS_POSIX) && !defined(OS_MACOSX)
144 #include "content/browser/renderer_host/render_sandbox_host_linux.h"
145 #include "content/browser/zygote_host/zygote_host_impl_linux.h"
146 #include "sandbox/linux/suid/client/setuid_sandbox_host.h"
149 #if defined(ENABLE_PLUGINS)
150 #include "content/browser/plugin_service_impl.h"
153 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
154 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
158 #include "ui/gfx/x/x11_connection.h"
159 #include "ui/gfx/x/x11_types.h"
162 // One of the linux specific headers defines this as a macro.
170 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
171 void SetupSandbox(const base::CommandLine
& parsed_command_line
) {
172 TRACE_EVENT0("startup", "SetupSandbox");
173 base::FilePath sandbox_binary
;
175 scoped_ptr
<sandbox::SetuidSandboxHost
> setuid_sandbox_host(
176 sandbox::SetuidSandboxHost::Create());
178 const bool want_setuid_sandbox
=
179 !parsed_command_line
.HasSwitch(switches::kNoSandbox
) &&
180 !parsed_command_line
.HasSwitch(switches::kDisableSetuidSandbox
) &&
181 !setuid_sandbox_host
->IsDisabledViaEnvironment();
183 static const char no_suid_error
[] =
184 "Running without the SUID sandbox! See "
185 "https://code.google.com/p/chromium/wiki/LinuxSUIDSandboxDevelopment "
186 "for more information on developing with the sandbox on.";
187 if (want_setuid_sandbox
) {
188 sandbox_binary
= setuid_sandbox_host
->GetSandboxBinaryPath();
189 if (sandbox_binary
.empty()) {
190 // This needs to be fatal. Talk to security@chromium.org if you feel
192 LOG(FATAL
) << no_suid_error
;
195 LOG(ERROR
) << no_suid_error
;
198 // Tickle the sandbox host and zygote host so they fork now.
199 RenderSandboxHostLinux::GetInstance()->Init();
200 ZygoteHostImpl::GetInstance()->Init(sandbox_binary
.value());
204 #if defined(USE_GLIB)
205 static void GLibLogHandler(const gchar
* log_domain
,
206 GLogLevelFlags log_level
,
207 const gchar
* message
,
210 log_domain
= "<unknown>";
212 message
= "<no message>";
214 if (strstr(message
, "Unable to retrieve the file info for")) {
215 LOG(ERROR
) << "GTK File code error: " << message
;
216 } else if (strstr(message
, "Could not find the icon") &&
217 strstr(log_domain
, "Gtk")) {
218 LOG(ERROR
) << "GTK icon error: " << message
;
219 } else if (strstr(message
, "Theme file for default has no") ||
220 strstr(message
, "Theme directory") ||
221 strstr(message
, "theme pixmap") ||
222 strstr(message
, "locate theme engine")) {
223 LOG(ERROR
) << "GTK theme error: " << message
;
224 } else if (strstr(message
, "Unable to create Ubuntu Menu Proxy") &&
225 strstr(log_domain
, "<unknown>")) {
226 LOG(ERROR
) << "GTK menu proxy create failed";
227 } else if (strstr(message
, "Out of memory") &&
228 strstr(log_domain
, "<unknown>")) {
229 LOG(ERROR
) << "DBus call timeout or out of memory: "
230 << "http://crosbug.com/15496";
231 } else if (strstr(message
, "Could not connect: Connection refused") &&
232 strstr(log_domain
, "<unknown>")) {
233 LOG(ERROR
) << "DConf settings backend could not connect to session bus: "
234 << "http://crbug.com/179797";
235 } else if (strstr(message
, "Attempting to store changes into") ||
236 strstr(message
, "Attempting to set the permissions of")) {
237 LOG(ERROR
) << message
<< " (http://bugs.chromium.org/161366)";
238 } else if (strstr(message
, "drawable is not a native X11 window")) {
239 LOG(ERROR
) << message
<< " (http://bugs.chromium.org/329991)";
240 } else if (strstr(message
, "Cannot do system-bus activation with no user")) {
241 LOG(ERROR
) << message
<< " (http://crbug.com/431005)";
243 LOG(DFATAL
) << log_domain
<< ": " << message
;
247 static void SetUpGLibLogHandler() {
248 // Register GLib-handled assertions to go through our logging system.
249 const char* kLogDomains
[] = { NULL
, "Gtk", "Gdk", "GLib", "GLib-GObject" };
250 for (size_t i
= 0; i
< arraysize(kLogDomains
); i
++) {
251 g_log_set_handler(kLogDomains
[i
],
252 static_cast<GLogLevelFlags
>(G_LOG_FLAG_RECURSION
|
255 G_LOG_LEVEL_CRITICAL
|
256 G_LOG_LEVEL_WARNING
),
263 void OnStoppedStartupTracing(const base::FilePath
& trace_file
) {
264 VLOG(0) << "Completed startup tracing to " << trace_file
.value();
267 // Disable optimizations for this block of functions so the compiler doesn't
268 // merge them all together. This makes it possible to tell what thread was
269 // unresponsive by inspecting the callstack.
270 MSVC_DISABLE_OPTIMIZE()
271 MSVC_PUSH_DISABLE_WARNING(4748)
273 NOINLINE
void ResetThread_DB(scoped_ptr
<BrowserProcessSubThread
> thread
) {
274 volatile int inhibit_comdat
= __LINE__
;
275 ALLOW_UNUSED_LOCAL(inhibit_comdat
);
279 NOINLINE
void ResetThread_FILE(scoped_ptr
<BrowserProcessSubThread
> thread
) {
280 volatile int inhibit_comdat
= __LINE__
;
281 ALLOW_UNUSED_LOCAL(inhibit_comdat
);
285 NOINLINE
void ResetThread_FILE_USER_BLOCKING(
286 scoped_ptr
<BrowserProcessSubThread
> thread
) {
287 volatile int inhibit_comdat
= __LINE__
;
288 ALLOW_UNUSED_LOCAL(inhibit_comdat
);
292 NOINLINE
void ResetThread_PROCESS_LAUNCHER(
293 scoped_ptr
<BrowserProcessSubThread
> thread
) {
294 volatile int inhibit_comdat
= __LINE__
;
295 ALLOW_UNUSED_LOCAL(inhibit_comdat
);
299 NOINLINE
void ResetThread_CACHE(scoped_ptr
<BrowserProcessSubThread
> thread
) {
300 volatile int inhibit_comdat
= __LINE__
;
301 ALLOW_UNUSED_LOCAL(inhibit_comdat
);
305 NOINLINE
void ResetThread_IO(scoped_ptr
<BrowserProcessSubThread
> thread
) {
306 volatile int inhibit_comdat
= __LINE__
;
307 ALLOW_UNUSED_LOCAL(inhibit_comdat
);
312 NOINLINE
void ResetThread_IndexedDb(scoped_ptr
<base::Thread
> thread
) {
313 volatile int inhibit_comdat
= __LINE__
;
314 ALLOW_UNUSED_LOCAL(inhibit_comdat
);
320 MSVC_ENABLE_OPTIMIZE();
323 // Creates a memory pressure monitor using automatic thresholds, or those
324 // specified on the command-line. Ownership is passed to the caller.
325 base::win::MemoryPressureMonitor
* CreateWinMemoryPressureMonitor(
326 const base::CommandLine
& parsed_command_line
) {
327 std::vector
<std::string
> thresholds
= base::SplitString(
328 parsed_command_line
.GetSwitchValueASCII(
329 switches::kMemoryPressureThresholdsMb
),
330 ",", base::TRIM_WHITESPACE
, base::SPLIT_WANT_ALL
);
332 int moderate_threshold_mb
= 0;
333 int critical_threshold_mb
= 0;
334 if (thresholds
.size() == 2 &&
335 base::StringToInt(thresholds
[0], &moderate_threshold_mb
) &&
336 base::StringToInt(thresholds
[1], &critical_threshold_mb
) &&
337 moderate_threshold_mb
>= critical_threshold_mb
&&
338 critical_threshold_mb
>= 0) {
339 return new base::win::MemoryPressureMonitor(moderate_threshold_mb
,
340 critical_threshold_mb
);
343 // In absence of valid switches use the automatic defaults.
344 return new base::win::MemoryPressureMonitor();
346 #endif // defined(OS_WIN)
350 // The currently-running BrowserMainLoop. There can be one or zero.
351 BrowserMainLoop
* g_current_browser_main_loop
= NULL
;
353 // For measuring memory usage after each task. Behind a command line flag.
354 class BrowserMainLoop::MemoryObserver
: public base::MessageLoop::TaskObserver
{
357 ~MemoryObserver() override
{}
359 void WillProcessTask(const base::PendingTask
& pending_task
) override
{}
361 void DidProcessTask(const base::PendingTask
& pending_task
) override
{
362 #if !defined(OS_IOS) // No ProcessMetrics on IOS.
363 scoped_ptr
<base::ProcessMetrics
> process_metrics(
364 base::ProcessMetrics::CreateProcessMetrics(
365 #if defined(OS_MACOSX)
366 base::GetCurrentProcessHandle(), NULL
));
368 base::GetCurrentProcessHandle()));
370 size_t private_bytes
;
371 process_metrics
->GetMemoryBytes(&private_bytes
, NULL
);
372 LOCAL_HISTOGRAM_MEMORY_KB("Memory.BrowserUsed", private_bytes
>> 10);
376 DISALLOW_COPY_AND_ASSIGN(MemoryObserver
);
380 // BrowserMainLoop construction / destruction =============================
382 BrowserMainLoop
* BrowserMainLoop::GetInstance() {
383 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
384 return g_current_browser_main_loop
;
387 BrowserMainLoop::BrowserMainLoop(const MainFunctionParams
& parameters
)
388 : parameters_(parameters
),
389 parsed_command_line_(parameters
.command_line
),
390 result_code_(RESULT_CODE_NORMAL_EXIT
),
391 created_threads_(false),
392 // ContentMainRunner should have enabled tracing of the browser process
393 // when kTraceStartup is in the command line.
395 parameters
.command_line
.HasSwitch(switches::kTraceStartup
)) {
396 DCHECK(!g_current_browser_main_loop
);
397 g_current_browser_main_loop
= this;
400 BrowserMainLoop::~BrowserMainLoop() {
401 DCHECK_EQ(this, g_current_browser_main_loop
);
403 ui::Clipboard::DestroyClipboardForCurrentThread();
404 #endif // !defined(OS_IOS)
405 g_current_browser_main_loop
= NULL
;
408 void BrowserMainLoop::Init() {
409 TRACE_EVENT0("startup", "BrowserMainLoop::Init");
410 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::Init");
413 GetContentClient()->browser()->CreateBrowserMainParts(parameters_
));
416 // BrowserMainLoop stages ==================================================
418 void BrowserMainLoop::EarlyInitialization() {
419 TRACE_EVENT0("startup", "BrowserMainLoop::EarlyInitialization");
420 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::EarlyInitialization");
422 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
423 // No thread should be created before this call, as SetupSandbox()
424 // will end-up using fork().
425 SetupSandbox(parsed_command_line_
);
429 if (UsingInProcessGpu()) {
430 if (!gfx::InitializeThreadedX11()) {
431 LOG(ERROR
) << "Failed to put Xlib into threaded mode.";
436 // GLib's spawning of new processes is buggy, so it's important that at this
437 // point GLib does not need to start DBUS. Chrome should always start with
438 // DBUS_SESSION_BUS_ADDRESS properly set. See crbug.com/309093.
439 #if defined(USE_GLIB)
440 // g_type_init will be deprecated in 2.36. 2.35 is the development
441 // version for 2.36, hence do not call g_type_init starting 2.35.
442 // http://developer.gnome.org/gobject/unstable/gobject-Type-Information.html#g-type-init
443 #if !GLIB_CHECK_VERSION(2, 35, 0)
444 // GLib type system initialization. Needed at least for gconf,
445 // used in net/proxy/proxy_config_service_linux.cc. Most likely
446 // this is superfluous as gtk_init() ought to do this. It's
447 // definitely harmless, so retained as a reminder of this
448 // requirement for gconf.
452 SetUpGLibLogHandler();
456 parts_
->PreEarlyInitialization();
458 #if defined(OS_MACOSX)
459 // We use quite a few file descriptors for our IPC, and the default limit on
460 // the Mac is low (256), so bump it up.
461 base::SetFdLimit(1024);
465 net::EnsureWinsockInit();
468 #if !defined(USE_OPENSSL)
469 // We want to be sure to init NSPR on the main thread.
470 crypto::EnsureNSPRInit();
471 #endif // !defined(USE_OPENSSL)
474 if (parsed_command_line_
.HasSwitch(switches::kRendererProcessLimit
)) {
475 std::string limit_string
= parsed_command_line_
.GetSwitchValueASCII(
476 switches::kRendererProcessLimit
);
477 size_t process_limit
;
478 if (base::StringToSizeT(limit_string
, &process_limit
)) {
479 RenderProcessHost::SetMaxRendererProcessCount(process_limit
);
482 #endif // !defined(OS_IOS)
484 // TODO(boliu): kSingleProcess check is a temporary workaround for
485 // in-process Android WebView. crbug.com/503724 tracks proper fix.
486 if (!parsed_command_line_
.HasSwitch(switches::kSingleProcess
)) {
487 base::DiscardableMemoryAllocator::SetInstance(
488 HostDiscardableSharedMemoryManager::current());
492 parts_
->PostEarlyInitialization();
495 void BrowserMainLoop::PreMainMessageLoopStart() {
497 TRACE_EVENT0("startup",
498 "BrowserMainLoop::MainMessageLoopStart:PreMainMessageLoopStart");
499 parts_
->PreMainMessageLoopStart();
503 // If we're running tests (ui_task is non-null), then the ResourceBundle
504 // has already been initialized.
505 if (!parameters_
.ui_task
) {
506 // Override the configured locale with the user's preferred UI language.
507 l10n_util::OverrideLocaleWithUILanguageList();
512 void BrowserMainLoop::MainMessageLoopStart() {
513 // DO NOT add more code here. Use PreMainMessageLoopStart() above or
514 // PostMainMessageLoopStart() below.
516 TRACE_EVENT0("startup", "BrowserMainLoop::MainMessageLoopStart");
517 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::MainMessageLoopStart");
519 // Create a MessageLoop if one does not already exist for the current thread.
520 if (!base::MessageLoop::current())
521 main_message_loop_
.reset(new base::MessageLoopForUI
);
523 InitializeMainThread();
526 void BrowserMainLoop::PostMainMessageLoopStart() {
528 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SystemMonitor");
529 system_monitor_
.reset(new base::SystemMonitor
);
532 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:PowerMonitor");
533 scoped_ptr
<base::PowerMonitorSource
> power_monitor_source(
534 new base::PowerMonitorDeviceSource());
535 power_monitor_
.reset(new base::PowerMonitor(power_monitor_source
.Pass()));
538 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:HighResTimerManager");
539 hi_res_timer_manager_
.reset(new base::HighResolutionTimerManager
);
542 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:NetworkChangeNotifier");
543 network_change_notifier_
.reset(net::NetworkChangeNotifier::Create());
548 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MediaFeatures");
549 media::InitializeMediaLibrary();
552 TRACE_EVENT0("startup",
553 "BrowserMainLoop::Subsystem:ContentWebUIController");
554 WebUIControllerFactory::RegisterFactory(
555 ContentWebUIControllerFactory::GetInstance());
559 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:OnlineStateObserver");
560 online_state_observer_
.reset(new BrowserOnlineStateObserver
);
564 system_stats_monitor_
.reset(
565 new base::trace_event::TraceEventSystemStatsMonitor(
566 base::ThreadTaskRunnerHandle::Get()));
568 #endif // !defined(OS_IOS)
571 system_message_window_
.reset(new SystemMessageWindowWin
);
575 parts_
->PostMainMessageLoopStart();
578 // Start tracing to a file if needed. Only do this after starting the main
579 // message loop to avoid calling MessagePumpForUI::ScheduleWork() before
580 // MessagePumpForUI::Start() as it will crash the browser.
581 if (is_tracing_startup_
) {
582 TRACE_EVENT0("startup", "BrowserMainLoop::InitStartupTracing");
583 InitStartupTracing(parsed_command_line_
);
585 #endif // !defined(OS_IOS)
587 #if defined(OS_ANDROID)
589 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SurfaceTextureManager");
590 if (parsed_command_line_
.HasSwitch(switches::kSingleProcess
)) {
591 SurfaceTextureManager::SetInstance(
592 InProcessSurfaceTextureManager::GetInstance());
594 SurfaceTextureManager::SetInstance(
595 BrowserSurfaceTextureManager::GetInstance());
599 if (!parsed_command_line_
.HasSwitch(
600 switches::kDisableScreenOrientationLock
)) {
601 TRACE_EVENT0("startup",
602 "BrowserMainLoop::Subsystem:ScreenOrientationProvider");
603 screen_orientation_delegate_
.reset(
604 new ScreenOrientationDelegateAndroid());
605 ScreenOrientationProvider::SetDelegate(screen_orientation_delegate_
.get());
609 #if defined(OS_MACOSX) && !defined(OS_IOS)
611 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:IOSurfaceManager");
612 if (parsed_command_line_
.HasSwitch(switches::kSingleProcess
)) {
613 IOSurfaceManager::SetInstance(InProcessIOSurfaceManager::GetInstance());
615 IOSurfaceManager::SetInstance(BrowserIOSurfaceManager::GetInstance());
620 #if defined(USE_OZONE)
621 client_native_pixmap_factory_
= ui::ClientNativePixmapFactory::Create();
622 ui::ClientNativePixmapFactory::SetInstance(
623 client_native_pixmap_factory_
.get());
626 if (parsed_command_line_
.HasSwitch(switches::kMemoryMetrics
)) {
627 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MemoryObserver");
628 memory_observer_
.reset(new MemoryObserver());
629 base::MessageLoop::current()->AddTaskObserver(memory_observer_
.get());
632 if (parsed_command_line_
.HasSwitch(
633 switches::kEnableAggressiveDOMStorageFlushing
)) {
634 TRACE_EVENT0("startup",
635 "BrowserMainLoop::Subsystem:EnableAggressiveCommitDelay");
636 DOMStorageArea::EnableAggressiveCommitDelay();
639 base::trace_event::MemoryDumpManager::GetInstance()->Initialize();
641 // Enable the dump providers.
642 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
643 HostSharedBitmapManager::current());
644 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
645 skia::SkiaMemoryDumpProvider::GetInstance());
647 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
648 trace_memory_controller_
.reset(new base::trace_event::TraceMemoryController(
649 base::MessageLoop::current()->task_runner(),
650 ::HeapProfilerWithPseudoStackStart
, ::HeapProfilerStop
,
655 int BrowserMainLoop::PreCreateThreads() {
656 // Need to initialize in-process GpuDataManager before creating threads.
657 // It's unsafe to append the gpu command line switches to the global
658 // CommandLine::ForCurrentProcess object after threads are created.
659 // Also need to initialize before BrowserMainParts::PreCreateThreads, so
660 // BrowserMainParts has a hook to set GpuDataManager strings before
661 // starting Gpu process.
662 GpuDataManagerImpl::GetInstance()->Initialize();
665 TRACE_EVENT0("startup",
666 "BrowserMainLoop::CreateThreads:PreCreateThreads");
667 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::PreCreateThreads");
669 result_code_
= parts_
->PreCreateThreads();
672 // TODO(chrisha): Abstract away this construction mess to a helper function,
673 // once MemoryPressureMonitor is made a concrete class.
674 #if defined(OS_CHROMEOS)
675 if (chromeos::switches::MemoryPressureHandlingEnabled()) {
676 memory_pressure_monitor_
.reset(new base::chromeos::MemoryPressureMonitor(
677 chromeos::switches::GetMemoryPressureThresholds()));
679 #elif defined(OS_MACOSX) && !defined(OS_IOS)
680 memory_pressure_monitor_
.reset(new base::mac::MemoryPressureMonitor());
681 #elif defined(OS_WIN)
682 memory_pressure_monitor_
.reset(CreateWinMemoryPressureMonitor(
683 parsed_command_line_
));
686 #if defined(ENABLE_PLUGINS)
687 // Prior to any processing happening on the io thread, we create the
688 // plugin service as it is predominantly used from the io thread,
689 // but must be created on the main thread. The service ctor is
690 // inexpensive and does not invoke the io_thread() accessor.
692 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads:PluginService");
693 PluginService::GetInstance()->Init();
697 #if defined(OS_MACOSX)
699 // Initialize AVFoundation if supported, for audio and video.
700 TRACE_EVENT0("startup",
701 "BrowserMainLoop::CreateThreads:InitializeAVFoundation");
702 AVFoundationGlue::InitializeAVFoundation();
706 #if !defined(OS_IOS) && (!defined(GOOGLE_CHROME_BUILD) || defined(OS_ANDROID))
707 // Single-process is an unsupported and not fully tested mode, so
708 // don't enable it for official Chrome builds (except on Android).
709 if (parsed_command_line_
.HasSwitch(switches::kSingleProcess
))
710 RenderProcessHost::SetRunRendererInProcess(true);
716 void BrowserMainLoop::CreateStartupTasks() {
717 TRACE_EVENT0("startup", "BrowserMainLoop::CreateStartupTasks");
718 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::CreateStartupTasks");
720 // First time through, we really want to create all the tasks
721 if (!startup_task_runner_
.get()) {
722 #if defined(OS_ANDROID)
723 startup_task_runner_
= make_scoped_ptr(
724 new StartupTaskRunner(base::Bind(&BrowserStartupComplete
),
725 base::ThreadTaskRunnerHandle::Get()));
727 startup_task_runner_
= make_scoped_ptr(
728 new StartupTaskRunner(base::Callback
<void(int)>(),
729 base::ThreadTaskRunnerHandle::Get()));
731 StartupTask pre_create_threads
=
732 base::Bind(&BrowserMainLoop::PreCreateThreads
, base::Unretained(this));
733 startup_task_runner_
->AddTask(pre_create_threads
);
735 StartupTask create_threads
=
736 base::Bind(&BrowserMainLoop::CreateThreads
, base::Unretained(this));
737 startup_task_runner_
->AddTask(create_threads
);
739 StartupTask browser_thread_started
= base::Bind(
740 &BrowserMainLoop::BrowserThreadsStarted
, base::Unretained(this));
741 startup_task_runner_
->AddTask(browser_thread_started
);
743 StartupTask pre_main_message_loop_run
= base::Bind(
744 &BrowserMainLoop::PreMainMessageLoopRun
, base::Unretained(this));
745 startup_task_runner_
->AddTask(pre_main_message_loop_run
);
747 #if defined(OS_ANDROID)
748 if (BrowserMayStartAsynchronously()) {
749 startup_task_runner_
->StartRunningTasksAsync();
753 #if defined(OS_ANDROID)
754 if (!BrowserMayStartAsynchronously()) {
755 // A second request for asynchronous startup can be ignored, so
756 // StartupRunningTasksAsync is only called first time through. If, however,
757 // this is a request for synchronous startup then it must override any
758 // previous call for async startup, so we call RunAllTasksNow()
760 startup_task_runner_
->RunAllTasksNow();
763 startup_task_runner_
->RunAllTasksNow();
767 int BrowserMainLoop::CreateThreads() {
768 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads");
769 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::CreateThreads");
771 base::Thread::Options io_message_loop_options
;
772 io_message_loop_options
.message_loop_type
= base::MessageLoop::TYPE_IO
;
773 base::Thread::Options ui_message_loop_options
;
774 ui_message_loop_options
.message_loop_type
= base::MessageLoop::TYPE_UI
;
776 // Start threads in the order they occur in the BrowserThread::ID
777 // enumeration, except for BrowserThread::UI which is the main
780 // Must be size_t so we can increment it.
781 for (size_t thread_id
= BrowserThread::UI
+ 1;
782 thread_id
< BrowserThread::ID_COUNT
;
784 scoped_ptr
<BrowserProcessSubThread
>* thread_to_start
= NULL
;
785 base::Thread::Options options
;
788 case BrowserThread::DB
:
789 TRACE_EVENT_BEGIN1("startup",
790 "BrowserMainLoop::CreateThreads:start",
791 "Thread", "BrowserThread::DB");
792 thread_to_start
= &db_thread_
;
793 options
.timer_slack
= base::TIMER_SLACK_MAXIMUM
;
795 case BrowserThread::FILE_USER_BLOCKING
:
796 TRACE_EVENT_BEGIN1("startup",
797 "BrowserMainLoop::CreateThreads:start",
798 "Thread", "BrowserThread::FILE_USER_BLOCKING");
799 thread_to_start
= &file_user_blocking_thread_
;
801 case BrowserThread::FILE:
802 TRACE_EVENT_BEGIN1("startup",
803 "BrowserMainLoop::CreateThreads:start",
804 "Thread", "BrowserThread::FILE");
805 thread_to_start
= &file_thread_
;
807 // On Windows, the FILE thread needs to be have a UI message loop
808 // which pumps messages in such a way that Google Update can
809 // communicate back to us.
810 options
= ui_message_loop_options
;
812 options
= io_message_loop_options
;
814 options
.timer_slack
= base::TIMER_SLACK_MAXIMUM
;
816 case BrowserThread::PROCESS_LAUNCHER
:
817 TRACE_EVENT_BEGIN1("startup",
818 "BrowserMainLoop::CreateThreads:start",
819 "Thread", "BrowserThread::PROCESS_LAUNCHER");
820 thread_to_start
= &process_launcher_thread_
;
821 options
.timer_slack
= base::TIMER_SLACK_MAXIMUM
;
823 case BrowserThread::CACHE
:
824 TRACE_EVENT_BEGIN1("startup",
825 "BrowserMainLoop::CreateThreads:start",
826 "Thread", "BrowserThread::CACHE");
827 thread_to_start
= &cache_thread_
;
828 options
= io_message_loop_options
;
829 options
.timer_slack
= base::TIMER_SLACK_MAXIMUM
;
831 case BrowserThread::IO
:
832 TRACE_EVENT_BEGIN1("startup",
833 "BrowserMainLoop::CreateThreads:start",
834 "Thread", "BrowserThread::IO");
835 thread_to_start
= &io_thread_
;
836 options
= io_message_loop_options
;
837 #if defined(OS_ANDROID)
838 // Up the priority of the |io_thread_| as some of its IPCs relate to
840 options
.priority
= base::ThreadPriority::DISPLAY
;
843 case BrowserThread::UI
:
844 case BrowserThread::ID_COUNT
:
850 BrowserThread::ID id
= static_cast<BrowserThread::ID
>(thread_id
);
852 if (thread_to_start
) {
853 (*thread_to_start
).reset(new BrowserProcessSubThread(id
));
854 if (!(*thread_to_start
)->StartWithOptions(options
)) {
855 LOG(FATAL
) << "Failed to start the browser thread: id == " << id
;
861 TRACE_EVENT_END0("startup", "BrowserMainLoop::CreateThreads:start");
863 created_threads_
= true;
867 int BrowserMainLoop::PreMainMessageLoopRun() {
869 TRACE_EVENT0("startup",
870 "BrowserMainLoop::CreateThreads:PreMainMessageLoopRun");
872 "Startup", "BrowserMainLoop::PreMainMessageLoopRun");
874 parts_
->PreMainMessageLoopRun();
877 // If the UI thread blocks, the whole UI is unresponsive.
878 // Do not allow disk IO from the UI thread.
879 base::ThreadRestrictions::SetIOAllowed(false);
880 base::ThreadRestrictions::DisallowWaiting();
884 void BrowserMainLoop::RunMainMessageLoopParts() {
885 TRACE_EVENT_BEGIN_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
887 bool ran_main_loop
= false;
889 ran_main_loop
= parts_
->MainMessageLoopRun(&result_code_
);
892 MainMessageLoopRun();
894 TRACE_EVENT_END_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
897 void BrowserMainLoop::ShutdownThreadsAndCleanUp() {
898 if (!created_threads_
) {
899 // Called early, nothing to do
902 TRACE_EVENT0("shutdown", "BrowserMainLoop::ShutdownThreadsAndCleanUp");
904 // Teardown may start in PostMainMessageLoopRun, and during teardown we
905 // need to be able to perform IO.
906 base::ThreadRestrictions::SetIOAllowed(true);
907 BrowserThread::PostTask(
908 BrowserThread::IO
, FROM_HERE
,
909 base::Bind(base::IgnoreResult(&base::ThreadRestrictions::SetIOAllowed
),
912 mojo_shell_context_
.reset();
915 if (RenderProcessHost::run_renderer_in_process())
916 RenderProcessHostImpl::ShutDownInProcessRenderer();
920 TRACE_EVENT0("shutdown",
921 "BrowserMainLoop::Subsystem:PostMainMessageLoopRun");
922 parts_
->PostMainMessageLoopRun();
925 #if defined(USE_AURA)
926 aura::Env::DeleteInstance();
929 trace_memory_controller_
.reset();
930 system_stats_monitor_
.reset();
933 // Destroying the GpuProcessHostUIShims on the UI thread posts a task to
934 // delete related objects on the GPU thread. This must be done before
935 // stopping the GPU thread. The GPU thread will close IPC channels to renderer
936 // processes so this has to happen before stopping the IO thread.
938 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUProcessHostShim");
939 GpuProcessHostUIShim::DestroyAll();
941 // Cancel pending requests and prevent new requests.
942 if (resource_dispatcher_host_
) {
943 TRACE_EVENT0("shutdown",
944 "BrowserMainLoop::Subsystem:ResourceDispatcherHost");
945 resource_dispatcher_host_
.get()->Shutdown();
948 memory_pressure_monitor_
.reset();
950 #if defined(OS_MACOSX)
951 BrowserCompositorMac::DisableRecyclingForShutdown();
954 #if defined(USE_AURA) || defined(OS_MACOSX)
956 TRACE_EVENT0("shutdown",
957 "BrowserMainLoop::Subsystem:ImageTransportFactory");
958 ImageTransportFactory::Terminate();
962 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
963 ZygoteHostImpl::GetInstance()->TearDownAfterLastChild();
964 #endif // defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
966 // The device monitors are using |system_monitor_| as dependency, so delete
967 // them before |system_monitor_| goes away.
968 // On Mac and windows, the monitor needs to be destroyed on the same thread
969 // as they were created. On Linux, the monitor will be deleted when IO thread
972 system_message_window_
.reset();
973 #elif defined(OS_MACOSX)
974 device_monitor_mac_
.reset();
976 #endif // !defined(OS_IOS)
978 // Must be size_t so we can subtract from it.
979 for (size_t thread_id
= BrowserThread::ID_COUNT
- 1;
980 thread_id
>= (BrowserThread::UI
+ 1);
982 // Find the thread object we want to stop. Looping over all valid
983 // BrowserThread IDs and DCHECKing on a missing case in the switch
984 // statement helps avoid a mismatch between this code and the
985 // BrowserThread::ID enumeration.
987 // The destruction order is the reverse order of occurrence in the
988 // BrowserThread::ID list. The rationale for the order is as
989 // follows (need to be filled in a bit):
992 // - The IO thread is the only user of the CACHE thread.
994 // - The PROCESS_LAUNCHER thread must be stopped after IO in case
995 // the IO thread posted a task to terminate a process on the
996 // process launcher thread.
998 // - (Not sure why DB stops last.)
1000 case BrowserThread::DB
: {
1001 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DBThread");
1002 ResetThread_DB(db_thread_
.Pass());
1005 case BrowserThread::FILE: {
1006 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:FileThread");
1007 #if !defined(OS_IOS)
1008 // Clean up state that lives on or uses the file_thread_ before
1010 if (resource_dispatcher_host_
)
1011 resource_dispatcher_host_
.get()->save_file_manager()->Shutdown();
1012 #endif // !defined(OS_IOS)
1013 ResetThread_FILE(file_thread_
.Pass());
1016 case BrowserThread::FILE_USER_BLOCKING
: {
1017 TRACE_EVENT0("shutdown",
1018 "BrowserMainLoop::Subsystem:FileUserBlockingThread");
1019 ResetThread_FILE_USER_BLOCKING(file_user_blocking_thread_
.Pass());
1022 case BrowserThread::PROCESS_LAUNCHER
: {
1023 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:LauncherThread");
1024 ResetThread_PROCESS_LAUNCHER(process_launcher_thread_
.Pass());
1027 case BrowserThread::CACHE
: {
1028 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:CacheThread");
1029 ResetThread_CACHE(cache_thread_
.Pass());
1032 case BrowserThread::IO
: {
1033 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IOThread");
1034 ResetThread_IO(io_thread_
.Pass());
1037 case BrowserThread::UI
:
1038 case BrowserThread::ID_COUNT
:
1045 #if !defined(OS_IOS)
1047 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IndexedDBThread");
1048 ResetThread_IndexedDb(indexed_db_thread_
.Pass());
1052 // Close the blocking I/O pool after the other threads. Other threads such
1053 // as the I/O thread may need to schedule work like closing files or flushing
1054 // data during shutdown, so the blocking pool needs to be available. There
1055 // may also be slow operations pending that will blcok shutdown, so closing
1056 // it here (which will block until required operations are complete) gives
1057 // more head start for those operations to finish.
1059 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:ThreadPool");
1060 BrowserThreadImpl::ShutdownThreadPool();
1063 #if !defined(OS_IOS)
1064 // Must happen after the IO thread is shutdown since this may be accessed from
1067 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUChannelFactory");
1068 if (BrowserGpuChannelHostFactory::instance())
1069 BrowserGpuChannelHostFactory::Terminate();
1072 // Must happen after the I/O thread is shutdown since this class lives on the
1073 // I/O thread and isn't threadsafe.
1075 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GamepadService");
1076 GamepadService::GetInstance()->Terminate();
1079 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:SensorService");
1080 DeviceInertialSensorService::GetInstance()->Shutdown();
1083 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:BatteryStatusService");
1084 device::BatteryStatusService::GetInstance()->Shutdown();
1087 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DeleteDataSources");
1088 URLDataManager::DeleteDataSources();
1090 #endif // !defined(OS_IOS)
1093 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:PostDestroyThreads");
1094 parts_
->PostDestroyThreads();
1098 void BrowserMainLoop::StopStartupTracingTimer() {
1099 startup_trace_timer_
.Stop();
1102 void BrowserMainLoop::InitializeMainThread() {
1103 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeMainThread");
1104 static const char kThreadName
[] = "CrBrowserMain";
1105 base::PlatformThread::SetName(kThreadName
);
1106 if (main_message_loop_
)
1107 main_message_loop_
->set_thread_name(kThreadName
);
1109 // Register the main thread by instantiating it, but don't call any methods.
1111 new BrowserThreadImpl(BrowserThread::UI
, base::MessageLoop::current()));
1114 int BrowserMainLoop::BrowserThreadsStarted() {
1115 TRACE_EVENT0("startup", "BrowserMainLoop::BrowserThreadsStarted");
1117 #if !defined(OS_IOS)
1118 indexed_db_thread_
.reset(new base::Thread("IndexedDB"));
1119 indexed_db_thread_
->Start();
1122 #if !defined(OS_IOS)
1123 HistogramSynchronizer::GetInstance();
1125 #if defined(OS_ANDROID)
1126 // Up the priority of the UI thread.
1127 base::PlatformThread::SetCurrentThreadPriority(base::ThreadPriority::DISPLAY
);
1130 bool always_uses_gpu
= true;
1131 bool established_gpu_channel
= false;
1132 #if defined(OS_ANDROID)
1133 // TODO(crbug.com/439322): This should be set to |true|.
1134 established_gpu_channel
= false;
1135 BrowserGpuChannelHostFactory::Initialize(established_gpu_channel
);
1136 #elif defined(USE_AURA) || defined(OS_MACOSX)
1137 established_gpu_channel
= true;
1138 if (!GpuDataManagerImpl::GetInstance()->CanUseGpuBrowserCompositor() ||
1139 parsed_command_line_
.HasSwitch(switches::kDisableGpuEarlyInit
)) {
1140 established_gpu_channel
= always_uses_gpu
= false;
1142 BrowserGpuChannelHostFactory::Initialize(established_gpu_channel
);
1143 ImageTransportFactory::Initialize();
1144 #if defined(USE_AURA)
1145 if (aura::Env::GetInstance()) {
1146 aura::Env::GetInstance()->set_context_factory(GetContextFactory());
1148 #endif // defined(USE_AURA)
1149 #endif // defined(OS_ANDROID)
1151 // Enable the GpuMemoryBuffer dump provider with IO thread affinity. Note that
1152 // unregistration happens on the IO thread (See
1153 // BrowserProcessSubThread::IOThreadPreCleanUp).
1154 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
1155 BrowserGpuMemoryBufferManager::current(), io_thread_
->task_runner());
1158 TRACE_EVENT0("startup", "BrowserThreadsStarted::Subsystem:AudioMan");
1159 audio_manager_
.reset(media::AudioManager::CreateWithHangTimer(
1160 MediaInternals::GetInstance(), io_thread_
->task_runner()));
1164 TRACE_EVENT0("startup", "BrowserThreadsStarted::Subsystem:MidiManager");
1165 midi_manager_
.reset(media::midi::MidiManager::Create());
1168 #if defined(OS_LINUX) && defined(USE_UDEV)
1169 device_monitor_linux_
.reset(new DeviceMonitorLinux());
1170 #elif defined(OS_MACOSX)
1171 device_monitor_mac_
.reset(new DeviceMonitorMac());
1175 UMA_HISTOGRAM_BOOLEAN("Windows.Win32kRendererLockdown",
1176 IsWin32kRendererLockdownEnabled());
1178 // RDH needs the IO thread to be created
1180 TRACE_EVENT0("startup",
1181 "BrowserMainLoop::BrowserThreadsStarted:InitResourceDispatcherHost");
1182 resource_dispatcher_host_
.reset(new ResourceDispatcherHostImpl());
1185 // MediaStreamManager needs the IO thread to be created.
1187 TRACE_EVENT0("startup",
1188 "BrowserMainLoop::BrowserThreadsStarted:InitMediaStreamManager");
1189 media_stream_manager_
.reset(new MediaStreamManager(audio_manager_
.get()));
1193 TRACE_EVENT0("startup",
1194 "BrowserMainLoop::BrowserThreadsStarted:InitSpeechRecognition");
1195 speech_recognition_manager_
.reset(new SpeechRecognitionManagerImpl(
1196 audio_manager_
.get(), media_stream_manager_
.get()));
1202 "BrowserMainLoop::BrowserThreadsStarted::InitUserInputMonitor");
1203 user_input_monitor_
= media::UserInputMonitor::Create(
1204 io_thread_
->task_runner(), main_thread_
->task_runner());
1208 TRACE_EVENT0("startup",
1209 "BrowserMainLoop::BrowserThreadsStarted::TimeZoneMonitor");
1210 time_zone_monitor_
= TimeZoneMonitor::Create();
1213 // Alert the clipboard class to which threads are allowed to access the
1215 std::vector
<base::PlatformThreadId
> allowed_clipboard_threads
;
1216 // The current thread is the UI thread.
1217 allowed_clipboard_threads
.push_back(base::PlatformThread::CurrentId());
1219 // On Windows, clipboards are also used on the FILE or IO threads.
1220 allowed_clipboard_threads
.push_back(file_thread_
->GetThreadId());
1221 allowed_clipboard_threads
.push_back(io_thread_
->GetThreadId());
1223 ui::Clipboard::SetAllowedThreads(allowed_clipboard_threads
);
1225 // When running the GPU thread in-process, avoid optimistically starting it
1226 // since creating the GPU thread races against creation of the one-and-only
1227 // ChildProcess instance which is created by the renderer thread.
1228 if (GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL
) &&
1229 !established_gpu_channel
&&
1231 !UsingInProcessGpu()) {
1232 TRACE_EVENT_INSTANT0("gpu", "Post task to launch GPU process",
1233 TRACE_EVENT_SCOPE_THREAD
);
1234 BrowserThread::PostTask(
1235 BrowserThread::IO
, FROM_HERE
,
1236 base::Bind(base::IgnoreResult(&GpuProcessHost::Get
),
1237 GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED
,
1238 CAUSE_FOR_GPU_LAUNCH_BROWSER_STARTUP
));
1241 #if defined(OS_MACOSX)
1242 ThemeHelperMac::GetInstance();
1243 SystemHotkeyHelperMac::GetInstance()->DeferredLoadSystemHotkeys();
1244 if (ShouldEnableBootstrapSandbox()) {
1245 TRACE_EVENT0("startup",
1246 "BrowserMainLoop::BrowserThreadsStarted:BootstrapSandbox");
1247 CHECK(GetBootstrapSandbox());
1249 #endif // defined(OS_MACOSX)
1251 #endif // !defined(OS_IOS)
1253 mojo_shell_context_
.reset(new MojoShellContext
);
1255 return result_code_
;
1258 bool BrowserMainLoop::UsingInProcessGpu() const {
1259 return parsed_command_line_
.HasSwitch(switches::kSingleProcess
) ||
1260 parsed_command_line_
.HasSwitch(switches::kInProcessGPU
);
1263 bool BrowserMainLoop::InitializeToolkit() {
1264 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeToolkit");
1265 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::InitializeToolkit");
1267 // TODO(evan): this function is rather subtle, due to the variety
1268 // of intersecting ifdefs we have. To keep it easy to follow, there
1269 // are no #else branches on any #ifs.
1270 // TODO(stevenjb): Move platform specific code into platform specific Parts
1271 // (Need to add InitializeToolkit stage to BrowserParts).
1272 // See also GTK setup in EarlyInitialization, above, and associated comments.
1275 // Init common control sex.
1276 INITCOMMONCONTROLSEX config
;
1277 config
.dwSize
= sizeof(config
);
1278 config
.dwICC
= ICC_WIN95_CLASSES
;
1279 if (!InitCommonControlsEx(&config
))
1283 #if defined(USE_AURA)
1285 #if defined(USE_X11)
1286 if (!gfx::GetXDisplay())
1290 // Env creates the compositor. Aura widgets need the compositor to be created
1291 // before they can be initialized by the browser.
1292 aura::Env::CreateInstance(true);
1293 #endif // defined(USE_AURA)
1296 parts_
->ToolkitInitialized();
1301 void BrowserMainLoop::MainMessageLoopRun() {
1302 #if defined(OS_ANDROID)
1303 // Android's main message loop is the Java message loop.
1306 DCHECK(base::MessageLoopForUI::IsCurrent());
1307 if (parameters_
.ui_task
) {
1308 base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE
,
1309 *parameters_
.ui_task
);
1312 base::RunLoop run_loop
;
1317 base::FilePath
BrowserMainLoop::GetStartupTraceFileName(
1318 const base::CommandLine
& command_line
) const {
1319 base::FilePath trace_file
= command_line
.GetSwitchValuePath(
1320 switches::kTraceStartupFile
);
1321 // trace_file = "none" means that startup events will show up for the next
1322 // begin/end tracing (via about:tracing or AutomationProxy::BeginTracing/
1323 // EndTracing, for example).
1324 if (trace_file
== base::FilePath().AppendASCII("none"))
1327 if (trace_file
.empty()) {
1328 #if defined(OS_ANDROID)
1329 TracingControllerAndroid::GenerateTracingFilePath(&trace_file
);
1331 // Default to saving the startup trace into the current dir.
1332 trace_file
= base::FilePath().AppendASCII("chrometrace.log");
1339 void BrowserMainLoop::InitStartupTracing(
1340 const base::CommandLine
& command_line
) {
1341 DCHECK(is_tracing_startup_
);
1343 startup_trace_file_
= GetStartupTraceFileName(parsed_command_line_
);
1345 std::string delay_str
= command_line
.GetSwitchValueASCII(
1346 switches::kTraceStartupDuration
);
1348 if (!delay_str
.empty() && !base::StringToInt(delay_str
, &delay_secs
)) {
1349 DLOG(WARNING
) << "Could not parse --" << switches::kTraceStartupDuration
1350 << "=" << delay_str
<< " defaulting to 5 (secs)";
1354 startup_trace_timer_
.Start(FROM_HERE
,
1355 base::TimeDelta::FromSeconds(delay_secs
),
1357 &BrowserMainLoop::EndStartupTracing
);
1360 void BrowserMainLoop::EndStartupTracing() {
1361 DCHECK(is_tracing_startup_
);
1363 is_tracing_startup_
= false;
1364 TracingController::GetInstance()->DisableRecording(
1365 TracingController::CreateFileSink(
1366 startup_trace_file_
,
1367 base::Bind(OnStoppedStartupTracing
, startup_trace_file_
)));
1370 } // namespace content