1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/browser/browser_main_loop.h"
8 #include "base/command_line.h"
9 #include "base/location.h"
10 #include "base/logging.h"
11 #include "base/memory/memory_pressure_monitor.h"
12 #include "base/metrics/field_trial.h"
13 #include "base/metrics/histogram.h"
14 #include "base/pending_task.h"
15 #include "base/power_monitor/power_monitor.h"
16 #include "base/power_monitor/power_monitor_device_source.h"
17 #include "base/process/process_metrics.h"
18 #include "base/profiler/scoped_profile.h"
19 #include "base/run_loop.h"
20 #include "base/single_thread_task_runner.h"
21 #include "base/strings/string_number_conversions.h"
22 #include "base/strings/string_split.h"
23 #include "base/system_monitor/system_monitor.h"
24 #include "base/thread_task_runner_handle.h"
25 #include "base/threading/thread_restrictions.h"
26 #include "base/timer/hi_res_timer_manager.h"
27 #include "base/trace_event/memory_dump_manager.h"
28 #include "base/trace_event/trace_event.h"
29 #include "components/tracing/trace_config_file.h"
30 #include "components/tracing/tracing_switches.h"
31 #include "content/browser/browser_thread_impl.h"
32 #include "content/browser/device_sensors/device_inertial_sensor_service.h"
33 #include "content/browser/dom_storage/dom_storage_area.h"
34 #include "content/browser/download/save_file_manager.h"
35 #include "content/browser/gamepad/gamepad_service.h"
36 #include "content/browser/gpu/browser_gpu_channel_host_factory.h"
37 #include "content/browser/gpu/browser_gpu_memory_buffer_manager.h"
38 #include "content/browser/gpu/compositor_util.h"
39 #include "content/browser/gpu/gpu_data_manager_impl.h"
40 #include "content/browser/gpu/gpu_process_host.h"
41 #include "content/browser/gpu/gpu_process_host_ui_shim.h"
42 #include "content/browser/histogram_synchronizer.h"
43 #include "content/browser/loader/resource_dispatcher_host_impl.h"
44 #include "content/browser/media/media_internals.h"
45 #include "content/browser/mojo/mojo_shell_context.h"
46 #include "content/browser/net/browser_online_state_observer.h"
47 #include "content/browser/renderer_host/media/media_stream_manager.h"
48 #include "content/browser/speech/speech_recognition_manager_impl.h"
49 #include "content/browser/startup_task_runner.h"
50 #include "content/browser/time_zone_monitor.h"
51 #include "content/browser/webui/content_web_ui_controller_factory.h"
52 #include "content/browser/webui/url_data_manager.h"
53 #include "content/common/content_switches_internal.h"
54 #include "content/common/host_discardable_shared_memory_manager.h"
55 #include "content/common/host_shared_bitmap_manager.h"
56 #include "content/public/browser/browser_main_parts.h"
57 #include "content/public/browser/content_browser_client.h"
58 #include "content/public/browser/render_process_host.h"
59 #include "content/public/browser/tracing_controller.h"
60 #include "content/public/common/content_switches.h"
61 #include "content/public/common/main_function_params.h"
62 #include "content/public/common/result_codes.h"
63 #include "crypto/nss_util.h"
64 #include "device/battery/battery_status_service.h"
65 #include "media/audio/audio_manager.h"
66 #include "media/base/media.h"
67 #include "media/base/user_input_monitor.h"
68 #include "media/midi/midi_manager.h"
69 #include "net/base/network_change_notifier.h"
70 #include "net/socket/client_socket_factory.h"
71 #include "net/ssl/ssl_config_service.h"
72 #include "skia/ext/skia_memory_dump_provider.h"
73 #include "ui/base/clipboard/clipboard.h"
75 #if defined(USE_AURA) || (defined(OS_MACOSX) && !defined(OS_IOS))
76 #include "content/browser/compositor/image_transport_factory.h"
80 #include "content/public/browser/context_factory.h"
81 #include "ui/aura/env.h"
85 #include "content/browser/renderer_host/render_process_host_impl.h"
88 #if defined(OS_ANDROID)
89 #include "base/android/jni_android.h"
90 #include "content/browser/android/browser_startup_controller.h"
91 #include "content/browser/android/browser_surface_texture_manager.h"
92 #include "content/browser/android/in_process_surface_texture_manager.h"
93 #include "content/browser/android/tracing_controller_android.h"
94 #include "content/browser/screen_orientation/screen_orientation_delegate_android.h"
95 #include "content/public/browser/screen_orientation_provider.h"
96 #include "ui/gl/gl_surface.h"
99 #if defined(OS_MACOSX)
100 #include "media/base/mac/avfoundation_glue.h"
103 #if defined(OS_MACOSX) && !defined(OS_IOS)
104 #include "base/memory/memory_pressure_monitor_mac.h"
105 #include "content/browser/bootstrap_sandbox_mac.h"
106 #include "content/browser/browser_io_surface_manager_mac.h"
107 #include "content/browser/cocoa/system_hotkey_helper_mac.h"
108 #include "content/browser/compositor/browser_compositor_view_mac.h"
109 #include "content/browser/in_process_io_surface_manager_mac.h"
110 #include "content/browser/theme_helper_mac.h"
113 #if defined(USE_OZONE)
114 #include "ui/ozone/public/client_native_pixmap_factory.h"
115 #include "ui/ozone/public/ozone_platform.h"
120 #include <commctrl.h>
121 #include <shellapi.h>
123 #include "base/memory/memory_pressure_monitor_win.h"
124 #include "content/browser/system_message_window_win.h"
125 #include "content/common/sandbox_win.h"
126 #include "net/base/winsock_init.h"
127 #include "ui/base/l10n/l10n_util_win.h"
130 #if defined(OS_CHROMEOS)
131 #include "base/memory/memory_pressure_monitor_chromeos.h"
132 #include "chromeos/chromeos_switches.h"
135 #if defined(USE_GLIB)
136 #include <glib-object.h>
139 #if defined(OS_LINUX) && defined(USE_UDEV)
140 #include "content/browser/device_monitor_udev.h"
141 #elif defined(OS_MACOSX) && !defined(OS_IOS)
142 #include "content/browser/device_monitor_mac.h"
145 #if defined(OS_POSIX) && !defined(OS_MACOSX)
146 #include "content/browser/renderer_host/render_sandbox_host_linux.h"
147 #include "content/browser/zygote_host/zygote_host_impl_linux.h"
148 #include "sandbox/linux/suid/client/setuid_sandbox_host.h"
151 #if defined(ENABLE_PLUGINS)
152 #include "content/browser/plugin_service_impl.h"
155 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
156 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
160 #include "ui/gfx/x/x11_connection.h"
161 #include "ui/gfx/x/x11_types.h"
164 // One of the linux specific headers defines this as a macro.
172 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
173 void SetupSandbox(const base::CommandLine
& parsed_command_line
) {
174 TRACE_EVENT0("startup", "SetupSandbox");
175 base::FilePath sandbox_binary
;
177 scoped_ptr
<sandbox::SetuidSandboxHost
> setuid_sandbox_host(
178 sandbox::SetuidSandboxHost::Create());
180 const bool want_setuid_sandbox
=
181 !parsed_command_line
.HasSwitch(switches::kNoSandbox
) &&
182 !parsed_command_line
.HasSwitch(switches::kDisableSetuidSandbox
) &&
183 !setuid_sandbox_host
->IsDisabledViaEnvironment();
185 static const char no_suid_error
[] =
186 "Running without the SUID sandbox! See "
187 "https://code.google.com/p/chromium/wiki/LinuxSUIDSandboxDevelopment "
188 "for more information on developing with the sandbox on.";
189 if (want_setuid_sandbox
) {
190 sandbox_binary
= setuid_sandbox_host
->GetSandboxBinaryPath();
191 if (sandbox_binary
.empty()) {
192 // This needs to be fatal. Talk to security@chromium.org if you feel
194 LOG(FATAL
) << no_suid_error
;
197 LOG(ERROR
) << no_suid_error
;
200 // Tickle the sandbox host and zygote host so they fork now.
201 RenderSandboxHostLinux::GetInstance()->Init();
202 ZygoteHostImpl::GetInstance()->Init(sandbox_binary
.value());
206 #if defined(USE_GLIB)
207 static void GLibLogHandler(const gchar
* log_domain
,
208 GLogLevelFlags log_level
,
209 const gchar
* message
,
212 log_domain
= "<unknown>";
214 message
= "<no message>";
216 if (strstr(message
, "Unable to retrieve the file info for")) {
217 LOG(ERROR
) << "GTK File code error: " << message
;
218 } else if (strstr(message
, "Could not find the icon") &&
219 strstr(log_domain
, "Gtk")) {
220 LOG(ERROR
) << "GTK icon error: " << message
;
221 } else if (strstr(message
, "Theme file for default has no") ||
222 strstr(message
, "Theme directory") ||
223 strstr(message
, "theme pixmap") ||
224 strstr(message
, "locate theme engine")) {
225 LOG(ERROR
) << "GTK theme error: " << message
;
226 } else if (strstr(message
, "Unable to create Ubuntu Menu Proxy") &&
227 strstr(log_domain
, "<unknown>")) {
228 LOG(ERROR
) << "GTK menu proxy create failed";
229 } else if (strstr(message
, "Out of memory") &&
230 strstr(log_domain
, "<unknown>")) {
231 LOG(ERROR
) << "DBus call timeout or out of memory: "
232 << "http://crosbug.com/15496";
233 } else if (strstr(message
, "Could not connect: Connection refused") &&
234 strstr(log_domain
, "<unknown>")) {
235 LOG(ERROR
) << "DConf settings backend could not connect to session bus: "
236 << "http://crbug.com/179797";
237 } else if (strstr(message
, "Attempting to store changes into") ||
238 strstr(message
, "Attempting to set the permissions of")) {
239 LOG(ERROR
) << message
<< " (http://bugs.chromium.org/161366)";
240 } else if (strstr(message
, "drawable is not a native X11 window")) {
241 LOG(ERROR
) << message
<< " (http://bugs.chromium.org/329991)";
242 } else if (strstr(message
, "Cannot do system-bus activation with no user")) {
243 LOG(ERROR
) << message
<< " (http://crbug.com/431005)";
245 LOG(DFATAL
) << log_domain
<< ": " << message
;
249 static void SetUpGLibLogHandler() {
250 // Register GLib-handled assertions to go through our logging system.
251 const char* kLogDomains
[] = { NULL
, "Gtk", "Gdk", "GLib", "GLib-GObject" };
252 for (size_t i
= 0; i
< arraysize(kLogDomains
); i
++) {
253 g_log_set_handler(kLogDomains
[i
],
254 static_cast<GLogLevelFlags
>(G_LOG_FLAG_RECURSION
|
257 G_LOG_LEVEL_CRITICAL
|
258 G_LOG_LEVEL_WARNING
),
265 void OnStoppedStartupTracing(const base::FilePath
& trace_file
) {
266 VLOG(0) << "Completed startup tracing to " << trace_file
.value();
269 // Disable optimizations for this block of functions so the compiler doesn't
270 // merge them all together. This makes it possible to tell what thread was
271 // unresponsive by inspecting the callstack.
272 MSVC_DISABLE_OPTIMIZE()
273 MSVC_PUSH_DISABLE_WARNING(4748)
275 NOINLINE
void ResetThread_DB(scoped_ptr
<BrowserProcessSubThread
> thread
) {
276 volatile int inhibit_comdat
= __LINE__
;
277 ALLOW_UNUSED_LOCAL(inhibit_comdat
);
281 NOINLINE
void ResetThread_FILE(scoped_ptr
<BrowserProcessSubThread
> thread
) {
282 volatile int inhibit_comdat
= __LINE__
;
283 ALLOW_UNUSED_LOCAL(inhibit_comdat
);
287 NOINLINE
void ResetThread_FILE_USER_BLOCKING(
288 scoped_ptr
<BrowserProcessSubThread
> thread
) {
289 volatile int inhibit_comdat
= __LINE__
;
290 ALLOW_UNUSED_LOCAL(inhibit_comdat
);
294 NOINLINE
void ResetThread_PROCESS_LAUNCHER(
295 scoped_ptr
<BrowserProcessSubThread
> thread
) {
296 volatile int inhibit_comdat
= __LINE__
;
297 ALLOW_UNUSED_LOCAL(inhibit_comdat
);
301 NOINLINE
void ResetThread_CACHE(scoped_ptr
<BrowserProcessSubThread
> thread
) {
302 volatile int inhibit_comdat
= __LINE__
;
303 ALLOW_UNUSED_LOCAL(inhibit_comdat
);
307 NOINLINE
void ResetThread_IO(scoped_ptr
<BrowserProcessSubThread
> thread
) {
308 volatile int inhibit_comdat
= __LINE__
;
309 ALLOW_UNUSED_LOCAL(inhibit_comdat
);
314 NOINLINE
void ResetThread_IndexedDb(scoped_ptr
<base::Thread
> thread
) {
315 volatile int inhibit_comdat
= __LINE__
;
316 ALLOW_UNUSED_LOCAL(inhibit_comdat
);
322 MSVC_ENABLE_OPTIMIZE();
325 // Creates a memory pressure monitor using automatic thresholds, or those
326 // specified on the command-line. Ownership is passed to the caller.
327 base::win::MemoryPressureMonitor
* CreateWinMemoryPressureMonitor(
328 const base::CommandLine
& parsed_command_line
) {
329 std::vector
<std::string
> thresholds
= base::SplitString(
330 parsed_command_line
.GetSwitchValueASCII(
331 switches::kMemoryPressureThresholdsMb
),
332 ",", base::TRIM_WHITESPACE
, base::SPLIT_WANT_ALL
);
334 int moderate_threshold_mb
= 0;
335 int critical_threshold_mb
= 0;
336 if (thresholds
.size() == 2 &&
337 base::StringToInt(thresholds
[0], &moderate_threshold_mb
) &&
338 base::StringToInt(thresholds
[1], &critical_threshold_mb
) &&
339 moderate_threshold_mb
>= critical_threshold_mb
&&
340 critical_threshold_mb
>= 0) {
341 return new base::win::MemoryPressureMonitor(moderate_threshold_mb
,
342 critical_threshold_mb
);
345 // In absence of valid switches use the automatic defaults.
346 return new base::win::MemoryPressureMonitor();
348 #endif // defined(OS_WIN)
352 // The currently-running BrowserMainLoop. There can be one or zero.
353 BrowserMainLoop
* g_current_browser_main_loop
= NULL
;
355 // For measuring memory usage after each task. Behind a command line flag.
356 class BrowserMainLoop::MemoryObserver
: public base::MessageLoop::TaskObserver
{
359 ~MemoryObserver() override
{}
361 void WillProcessTask(const base::PendingTask
& pending_task
) override
{}
363 void DidProcessTask(const base::PendingTask
& pending_task
) override
{
364 #if !defined(OS_IOS) // No ProcessMetrics on IOS.
365 scoped_ptr
<base::ProcessMetrics
> process_metrics(
366 base::ProcessMetrics::CreateProcessMetrics(
367 #if defined(OS_MACOSX)
368 base::GetCurrentProcessHandle(), NULL
));
370 base::GetCurrentProcessHandle()));
372 size_t private_bytes
;
373 process_metrics
->GetMemoryBytes(&private_bytes
, NULL
);
374 LOCAL_HISTOGRAM_MEMORY_KB("Memory.BrowserUsed", private_bytes
>> 10);
378 DISALLOW_COPY_AND_ASSIGN(MemoryObserver
);
382 // BrowserMainLoop construction / destruction =============================
384 BrowserMainLoop
* BrowserMainLoop::GetInstance() {
385 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
386 return g_current_browser_main_loop
;
389 BrowserMainLoop::BrowserMainLoop(const MainFunctionParams
& parameters
)
390 : parameters_(parameters
),
391 parsed_command_line_(parameters
.command_line
),
392 result_code_(RESULT_CODE_NORMAL_EXIT
),
393 created_threads_(false),
394 // ContentMainRunner should have enabled tracing of the browser process
395 // when kTraceStartup or kTraceConfigFile is in the command line.
396 is_tracing_startup_for_duration_(
397 parameters
.command_line
.HasSwitch(switches::kTraceStartup
) ||
398 (tracing::TraceConfigFile::GetInstance()->IsEnabled() &&
399 tracing::TraceConfigFile::GetInstance()->GetStartupDuration() > 0)) {
400 DCHECK(!g_current_browser_main_loop
);
401 g_current_browser_main_loop
= this;
404 BrowserMainLoop::~BrowserMainLoop() {
405 DCHECK_EQ(this, g_current_browser_main_loop
);
407 ui::Clipboard::DestroyClipboardForCurrentThread();
408 #endif // !defined(OS_IOS)
409 g_current_browser_main_loop
= NULL
;
412 void BrowserMainLoop::Init() {
413 TRACE_EVENT0("startup", "BrowserMainLoop::Init");
414 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::Init");
417 GetContentClient()->browser()->CreateBrowserMainParts(parameters_
));
420 // BrowserMainLoop stages ==================================================
422 void BrowserMainLoop::EarlyInitialization() {
423 TRACE_EVENT0("startup", "BrowserMainLoop::EarlyInitialization");
424 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::EarlyInitialization");
426 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
427 // No thread should be created before this call, as SetupSandbox()
428 // will end-up using fork().
429 SetupSandbox(parsed_command_line_
);
433 if (UsingInProcessGpu()) {
434 if (!gfx::InitializeThreadedX11()) {
435 LOG(ERROR
) << "Failed to put Xlib into threaded mode.";
440 // GLib's spawning of new processes is buggy, so it's important that at this
441 // point GLib does not need to start DBUS. Chrome should always start with
442 // DBUS_SESSION_BUS_ADDRESS properly set. See crbug.com/309093.
443 #if defined(USE_GLIB)
444 // g_type_init will be deprecated in 2.36. 2.35 is the development
445 // version for 2.36, hence do not call g_type_init starting 2.35.
446 // http://developer.gnome.org/gobject/unstable/gobject-Type-Information.html#g-type-init
447 #if !GLIB_CHECK_VERSION(2, 35, 0)
448 // GLib type system initialization. Needed at least for gconf,
449 // used in net/proxy/proxy_config_service_linux.cc. Most likely
450 // this is superfluous as gtk_init() ought to do this. It's
451 // definitely harmless, so retained as a reminder of this
452 // requirement for gconf.
456 SetUpGLibLogHandler();
460 parts_
->PreEarlyInitialization();
462 #if defined(OS_MACOSX)
463 // We use quite a few file descriptors for our IPC, and the default limit on
464 // the Mac is low (256), so bump it up.
465 base::SetFdLimit(1024);
469 net::EnsureWinsockInit();
472 #if !defined(USE_OPENSSL)
473 // We want to be sure to init NSPR on the main thread.
474 crypto::EnsureNSPRInit();
475 #endif // !defined(USE_OPENSSL)
478 if (parsed_command_line_
.HasSwitch(switches::kRendererProcessLimit
)) {
479 std::string limit_string
= parsed_command_line_
.GetSwitchValueASCII(
480 switches::kRendererProcessLimit
);
481 size_t process_limit
;
482 if (base::StringToSizeT(limit_string
, &process_limit
)) {
483 RenderProcessHost::SetMaxRendererProcessCount(process_limit
);
486 #endif // !defined(OS_IOS)
488 // TODO(boliu): kSingleProcess check is a temporary workaround for
489 // in-process Android WebView. crbug.com/503724 tracks proper fix.
490 if (!parsed_command_line_
.HasSwitch(switches::kSingleProcess
)) {
491 base::DiscardableMemoryAllocator::SetInstance(
492 HostDiscardableSharedMemoryManager::current());
496 parts_
->PostEarlyInitialization();
499 void BrowserMainLoop::PreMainMessageLoopStart() {
501 TRACE_EVENT0("startup",
502 "BrowserMainLoop::MainMessageLoopStart:PreMainMessageLoopStart");
503 parts_
->PreMainMessageLoopStart();
507 // If we're running tests (ui_task is non-null), then the ResourceBundle
508 // has already been initialized.
509 if (!parameters_
.ui_task
) {
510 // Override the configured locale with the user's preferred UI language.
511 l10n_util::OverrideLocaleWithUILanguageList();
516 void BrowserMainLoop::MainMessageLoopStart() {
517 // DO NOT add more code here. Use PreMainMessageLoopStart() above or
518 // PostMainMessageLoopStart() below.
520 TRACE_EVENT0("startup", "BrowserMainLoop::MainMessageLoopStart");
521 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::MainMessageLoopStart");
523 // Create a MessageLoop if one does not already exist for the current thread.
524 if (!base::MessageLoop::current())
525 main_message_loop_
.reset(new base::MessageLoopForUI
);
527 InitializeMainThread();
530 void BrowserMainLoop::PostMainMessageLoopStart() {
532 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SystemMonitor");
533 system_monitor_
.reset(new base::SystemMonitor
);
536 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:PowerMonitor");
537 scoped_ptr
<base::PowerMonitorSource
> power_monitor_source(
538 new base::PowerMonitorDeviceSource());
539 power_monitor_
.reset(new base::PowerMonitor(power_monitor_source
.Pass()));
542 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:HighResTimerManager");
543 hi_res_timer_manager_
.reset(new base::HighResolutionTimerManager
);
546 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:NetworkChangeNotifier");
547 network_change_notifier_
.reset(net::NetworkChangeNotifier::Create());
552 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MediaFeatures");
553 media::InitializeMediaLibrary();
556 TRACE_EVENT0("startup",
557 "BrowserMainLoop::Subsystem:ContentWebUIController");
558 WebUIControllerFactory::RegisterFactory(
559 ContentWebUIControllerFactory::GetInstance());
563 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:OnlineStateObserver");
564 online_state_observer_
.reset(new BrowserOnlineStateObserver
);
568 system_stats_monitor_
.reset(
569 new base::trace_event::TraceEventSystemStatsMonitor(
570 base::ThreadTaskRunnerHandle::Get()));
572 #endif // !defined(OS_IOS)
575 system_message_window_
.reset(new SystemMessageWindowWin
);
579 parts_
->PostMainMessageLoopStart();
582 // Start tracing to a file if needed. Only do this after starting the main
583 // message loop to avoid calling MessagePumpForUI::ScheduleWork() before
584 // MessagePumpForUI::Start() as it will crash the browser.
585 if (is_tracing_startup_for_duration_
) {
586 TRACE_EVENT0("startup", "BrowserMainLoop::InitStartupTracingForDuration");
587 InitStartupTracingForDuration(parsed_command_line_
);
589 #endif // !defined(OS_IOS)
591 #if defined(OS_ANDROID)
593 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SurfaceTextureManager");
594 if (parsed_command_line_
.HasSwitch(switches::kSingleProcess
)) {
595 SurfaceTextureManager::SetInstance(
596 InProcessSurfaceTextureManager::GetInstance());
598 SurfaceTextureManager::SetInstance(
599 BrowserSurfaceTextureManager::GetInstance());
603 if (!parsed_command_line_
.HasSwitch(
604 switches::kDisableScreenOrientationLock
)) {
605 TRACE_EVENT0("startup",
606 "BrowserMainLoop::Subsystem:ScreenOrientationProvider");
607 screen_orientation_delegate_
.reset(
608 new ScreenOrientationDelegateAndroid());
609 ScreenOrientationProvider::SetDelegate(screen_orientation_delegate_
.get());
613 #if defined(OS_MACOSX) && !defined(OS_IOS)
615 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:IOSurfaceManager");
616 if (parsed_command_line_
.HasSwitch(switches::kSingleProcess
)) {
617 IOSurfaceManager::SetInstance(InProcessIOSurfaceManager::GetInstance());
619 IOSurfaceManager::SetInstance(BrowserIOSurfaceManager::GetInstance());
624 #if defined(USE_OZONE)
625 client_native_pixmap_factory_
= ui::ClientNativePixmapFactory::Create();
626 ui::ClientNativePixmapFactory::SetInstance(
627 client_native_pixmap_factory_
.get());
628 ui::ClientNativePixmapFactory::GetInstance()->Initialize(
629 ui::OzonePlatform::GetInstance()->OpenClientNativePixmapDevice());
632 if (parsed_command_line_
.HasSwitch(switches::kMemoryMetrics
)) {
633 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MemoryObserver");
634 memory_observer_
.reset(new MemoryObserver());
635 base::MessageLoop::current()->AddTaskObserver(memory_observer_
.get());
638 if (parsed_command_line_
.HasSwitch(
639 switches::kEnableAggressiveDOMStorageFlushing
)) {
640 TRACE_EVENT0("startup",
641 "BrowserMainLoop::Subsystem:EnableAggressiveCommitDelay");
642 DOMStorageArea::EnableAggressiveCommitDelay();
645 base::trace_event::MemoryDumpManager::GetInstance()->Initialize();
647 // Enable the dump providers.
648 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
649 HostSharedBitmapManager::current());
650 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
651 skia::SkiaMemoryDumpProvider::GetInstance());
653 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
654 trace_memory_controller_
.reset(new base::trace_event::TraceMemoryController(
655 base::MessageLoop::current()->task_runner(),
656 ::HeapProfilerWithPseudoStackStart
, ::HeapProfilerStop
,
661 int BrowserMainLoop::PreCreateThreads() {
662 // Need to initialize in-process GpuDataManager before creating threads.
663 // It's unsafe to append the gpu command line switches to the global
664 // CommandLine::ForCurrentProcess object after threads are created.
665 // Also need to initialize before BrowserMainParts::PreCreateThreads, so
666 // BrowserMainParts has a hook to set GpuDataManager strings before
667 // starting Gpu process.
668 GpuDataManagerImpl::GetInstance()->Initialize();
671 TRACE_EVENT0("startup",
672 "BrowserMainLoop::CreateThreads:PreCreateThreads");
673 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::PreCreateThreads");
675 result_code_
= parts_
->PreCreateThreads();
678 // TODO(chrisha): Abstract away this construction mess to a helper function,
679 // once MemoryPressureMonitor is made a concrete class.
680 #if defined(OS_CHROMEOS)
681 if (chromeos::switches::MemoryPressureHandlingEnabled()) {
682 memory_pressure_monitor_
.reset(new base::chromeos::MemoryPressureMonitor(
683 chromeos::switches::GetMemoryPressureThresholds()));
685 #elif defined(OS_MACOSX) && !defined(OS_IOS)
686 memory_pressure_monitor_
.reset(new base::mac::MemoryPressureMonitor());
687 #elif defined(OS_WIN)
688 memory_pressure_monitor_
.reset(CreateWinMemoryPressureMonitor(
689 parsed_command_line_
));
692 #if defined(ENABLE_PLUGINS)
693 // Prior to any processing happening on the io thread, we create the
694 // plugin service as it is predominantly used from the io thread,
695 // but must be created on the main thread. The service ctor is
696 // inexpensive and does not invoke the io_thread() accessor.
698 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads:PluginService");
699 PluginService::GetInstance()->Init();
703 #if defined(OS_MACOSX)
705 // Initialize AVFoundation if supported, for audio and video.
706 TRACE_EVENT0("startup",
707 "BrowserMainLoop::CreateThreads:InitializeAVFoundation");
708 AVFoundationGlue::InitializeAVFoundation();
712 #if !defined(OS_IOS) && (!defined(GOOGLE_CHROME_BUILD) || defined(OS_ANDROID))
713 // Single-process is an unsupported and not fully tested mode, so
714 // don't enable it for official Chrome builds (except on Android).
715 if (parsed_command_line_
.HasSwitch(switches::kSingleProcess
))
716 RenderProcessHost::SetRunRendererInProcess(true);
722 void BrowserMainLoop::CreateStartupTasks() {
723 TRACE_EVENT0("startup", "BrowserMainLoop::CreateStartupTasks");
724 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::CreateStartupTasks");
726 // First time through, we really want to create all the tasks
727 if (!startup_task_runner_
.get()) {
728 #if defined(OS_ANDROID)
729 startup_task_runner_
= make_scoped_ptr(
730 new StartupTaskRunner(base::Bind(&BrowserStartupComplete
),
731 base::ThreadTaskRunnerHandle::Get()));
733 startup_task_runner_
= make_scoped_ptr(
734 new StartupTaskRunner(base::Callback
<void(int)>(),
735 base::ThreadTaskRunnerHandle::Get()));
737 StartupTask pre_create_threads
=
738 base::Bind(&BrowserMainLoop::PreCreateThreads
, base::Unretained(this));
739 startup_task_runner_
->AddTask(pre_create_threads
);
741 StartupTask create_threads
=
742 base::Bind(&BrowserMainLoop::CreateThreads
, base::Unretained(this));
743 startup_task_runner_
->AddTask(create_threads
);
745 StartupTask browser_thread_started
= base::Bind(
746 &BrowserMainLoop::BrowserThreadsStarted
, base::Unretained(this));
747 startup_task_runner_
->AddTask(browser_thread_started
);
749 StartupTask pre_main_message_loop_run
= base::Bind(
750 &BrowserMainLoop::PreMainMessageLoopRun
, base::Unretained(this));
751 startup_task_runner_
->AddTask(pre_main_message_loop_run
);
753 #if defined(OS_ANDROID)
754 if (BrowserMayStartAsynchronously()) {
755 startup_task_runner_
->StartRunningTasksAsync();
759 #if defined(OS_ANDROID)
760 if (!BrowserMayStartAsynchronously()) {
761 // A second request for asynchronous startup can be ignored, so
762 // StartupRunningTasksAsync is only called first time through. If, however,
763 // this is a request for synchronous startup then it must override any
764 // previous call for async startup, so we call RunAllTasksNow()
766 startup_task_runner_
->RunAllTasksNow();
769 startup_task_runner_
->RunAllTasksNow();
773 int BrowserMainLoop::CreateThreads() {
774 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads");
775 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::CreateThreads");
777 base::Thread::Options io_message_loop_options
;
778 io_message_loop_options
.message_loop_type
= base::MessageLoop::TYPE_IO
;
779 base::Thread::Options ui_message_loop_options
;
780 ui_message_loop_options
.message_loop_type
= base::MessageLoop::TYPE_UI
;
782 // Start threads in the order they occur in the BrowserThread::ID
783 // enumeration, except for BrowserThread::UI which is the main
786 // Must be size_t so we can increment it.
787 for (size_t thread_id
= BrowserThread::UI
+ 1;
788 thread_id
< BrowserThread::ID_COUNT
;
790 scoped_ptr
<BrowserProcessSubThread
>* thread_to_start
= NULL
;
791 base::Thread::Options options
;
794 case BrowserThread::DB
:
795 TRACE_EVENT_BEGIN1("startup",
796 "BrowserMainLoop::CreateThreads:start",
797 "Thread", "BrowserThread::DB");
798 thread_to_start
= &db_thread_
;
799 options
.timer_slack
= base::TIMER_SLACK_MAXIMUM
;
801 case BrowserThread::FILE_USER_BLOCKING
:
802 TRACE_EVENT_BEGIN1("startup",
803 "BrowserMainLoop::CreateThreads:start",
804 "Thread", "BrowserThread::FILE_USER_BLOCKING");
805 thread_to_start
= &file_user_blocking_thread_
;
807 case BrowserThread::FILE:
808 TRACE_EVENT_BEGIN1("startup",
809 "BrowserMainLoop::CreateThreads:start",
810 "Thread", "BrowserThread::FILE");
811 thread_to_start
= &file_thread_
;
813 // On Windows, the FILE thread needs to be have a UI message loop
814 // which pumps messages in such a way that Google Update can
815 // communicate back to us.
816 options
= ui_message_loop_options
;
818 options
= io_message_loop_options
;
820 options
.timer_slack
= base::TIMER_SLACK_MAXIMUM
;
822 case BrowserThread::PROCESS_LAUNCHER
:
823 TRACE_EVENT_BEGIN1("startup",
824 "BrowserMainLoop::CreateThreads:start",
825 "Thread", "BrowserThread::PROCESS_LAUNCHER");
826 thread_to_start
= &process_launcher_thread_
;
827 options
.timer_slack
= base::TIMER_SLACK_MAXIMUM
;
829 case BrowserThread::CACHE
:
830 TRACE_EVENT_BEGIN1("startup",
831 "BrowserMainLoop::CreateThreads:start",
832 "Thread", "BrowserThread::CACHE");
833 thread_to_start
= &cache_thread_
;
834 options
= io_message_loop_options
;
835 options
.timer_slack
= base::TIMER_SLACK_MAXIMUM
;
837 case BrowserThread::IO
:
838 TRACE_EVENT_BEGIN1("startup",
839 "BrowserMainLoop::CreateThreads:start",
840 "Thread", "BrowserThread::IO");
841 thread_to_start
= &io_thread_
;
842 options
= io_message_loop_options
;
843 #if defined(OS_ANDROID)
844 // Up the priority of the |io_thread_| as some of its IPCs relate to
846 options
.priority
= base::ThreadPriority::DISPLAY
;
849 case BrowserThread::UI
:
850 case BrowserThread::ID_COUNT
:
856 BrowserThread::ID id
= static_cast<BrowserThread::ID
>(thread_id
);
858 if (thread_to_start
) {
859 (*thread_to_start
).reset(new BrowserProcessSubThread(id
));
860 if (!(*thread_to_start
)->StartWithOptions(options
)) {
861 LOG(FATAL
) << "Failed to start the browser thread: id == " << id
;
867 TRACE_EVENT_END0("startup", "BrowserMainLoop::CreateThreads:start");
869 created_threads_
= true;
873 int BrowserMainLoop::PreMainMessageLoopRun() {
875 TRACE_EVENT0("startup",
876 "BrowserMainLoop::CreateThreads:PreMainMessageLoopRun");
878 "Startup", "BrowserMainLoop::PreMainMessageLoopRun");
880 parts_
->PreMainMessageLoopRun();
883 // If the UI thread blocks, the whole UI is unresponsive.
884 // Do not allow disk IO from the UI thread.
885 base::ThreadRestrictions::SetIOAllowed(false);
886 base::ThreadRestrictions::DisallowWaiting();
890 void BrowserMainLoop::RunMainMessageLoopParts() {
891 TRACE_EVENT_BEGIN_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
893 bool ran_main_loop
= false;
895 ran_main_loop
= parts_
->MainMessageLoopRun(&result_code_
);
898 MainMessageLoopRun();
900 TRACE_EVENT_END_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
903 void BrowserMainLoop::ShutdownThreadsAndCleanUp() {
904 if (!created_threads_
) {
905 // Called early, nothing to do
908 TRACE_EVENT0("shutdown", "BrowserMainLoop::ShutdownThreadsAndCleanUp");
910 // Teardown may start in PostMainMessageLoopRun, and during teardown we
911 // need to be able to perform IO.
912 base::ThreadRestrictions::SetIOAllowed(true);
913 BrowserThread::PostTask(
914 BrowserThread::IO
, FROM_HERE
,
915 base::Bind(base::IgnoreResult(&base::ThreadRestrictions::SetIOAllowed
),
918 mojo_shell_context_
.reset();
921 if (RenderProcessHost::run_renderer_in_process())
922 RenderProcessHostImpl::ShutDownInProcessRenderer();
926 TRACE_EVENT0("shutdown",
927 "BrowserMainLoop::Subsystem:PostMainMessageLoopRun");
928 parts_
->PostMainMessageLoopRun();
931 #if defined(USE_AURA)
932 aura::Env::DeleteInstance();
935 trace_memory_controller_
.reset();
936 system_stats_monitor_
.reset();
939 // Destroying the GpuProcessHostUIShims on the UI thread posts a task to
940 // delete related objects on the GPU thread. This must be done before
941 // stopping the GPU thread. The GPU thread will close IPC channels to renderer
942 // processes so this has to happen before stopping the IO thread.
944 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUProcessHostShim");
945 GpuProcessHostUIShim::DestroyAll();
947 // Cancel pending requests and prevent new requests.
948 if (resource_dispatcher_host_
) {
949 TRACE_EVENT0("shutdown",
950 "BrowserMainLoop::Subsystem:ResourceDispatcherHost");
951 resource_dispatcher_host_
.get()->Shutdown();
954 memory_pressure_monitor_
.reset();
956 #if defined(OS_MACOSX)
957 BrowserCompositorMac::DisableRecyclingForShutdown();
960 #if defined(USE_AURA) || defined(OS_MACOSX)
962 TRACE_EVENT0("shutdown",
963 "BrowserMainLoop::Subsystem:ImageTransportFactory");
964 ImageTransportFactory::Terminate();
968 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
969 ZygoteHostImpl::GetInstance()->TearDownAfterLastChild();
970 #endif // defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
972 // The device monitors are using |system_monitor_| as dependency, so delete
973 // them before |system_monitor_| goes away.
974 // On Mac and windows, the monitor needs to be destroyed on the same thread
975 // as they were created. On Linux, the monitor will be deleted when IO thread
978 system_message_window_
.reset();
979 #elif defined(OS_MACOSX)
980 device_monitor_mac_
.reset();
982 #endif // !defined(OS_IOS)
984 // Must be size_t so we can subtract from it.
985 for (size_t thread_id
= BrowserThread::ID_COUNT
- 1;
986 thread_id
>= (BrowserThread::UI
+ 1);
988 // Find the thread object we want to stop. Looping over all valid
989 // BrowserThread IDs and DCHECKing on a missing case in the switch
990 // statement helps avoid a mismatch between this code and the
991 // BrowserThread::ID enumeration.
993 // The destruction order is the reverse order of occurrence in the
994 // BrowserThread::ID list. The rationale for the order is as
995 // follows (need to be filled in a bit):
998 // - The IO thread is the only user of the CACHE thread.
1000 // - The PROCESS_LAUNCHER thread must be stopped after IO in case
1001 // the IO thread posted a task to terminate a process on the
1002 // process launcher thread.
1004 // - (Not sure why DB stops last.)
1005 switch (thread_id
) {
1006 case BrowserThread::DB
: {
1007 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DBThread");
1008 ResetThread_DB(db_thread_
.Pass());
1011 case BrowserThread::FILE: {
1012 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:FileThread");
1013 #if !defined(OS_IOS)
1014 // Clean up state that lives on or uses the file_thread_ before
1016 if (resource_dispatcher_host_
)
1017 resource_dispatcher_host_
.get()->save_file_manager()->Shutdown();
1018 #endif // !defined(OS_IOS)
1019 ResetThread_FILE(file_thread_
.Pass());
1022 case BrowserThread::FILE_USER_BLOCKING
: {
1023 TRACE_EVENT0("shutdown",
1024 "BrowserMainLoop::Subsystem:FileUserBlockingThread");
1025 ResetThread_FILE_USER_BLOCKING(file_user_blocking_thread_
.Pass());
1028 case BrowserThread::PROCESS_LAUNCHER
: {
1029 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:LauncherThread");
1030 ResetThread_PROCESS_LAUNCHER(process_launcher_thread_
.Pass());
1033 case BrowserThread::CACHE
: {
1034 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:CacheThread");
1035 ResetThread_CACHE(cache_thread_
.Pass());
1038 case BrowserThread::IO
: {
1039 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IOThread");
1040 ResetThread_IO(io_thread_
.Pass());
1043 case BrowserThread::UI
:
1044 case BrowserThread::ID_COUNT
:
1051 #if !defined(OS_IOS)
1053 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IndexedDBThread");
1054 ResetThread_IndexedDb(indexed_db_thread_
.Pass());
1058 // Close the blocking I/O pool after the other threads. Other threads such
1059 // as the I/O thread may need to schedule work like closing files or flushing
1060 // data during shutdown, so the blocking pool needs to be available. There
1061 // may also be slow operations pending that will blcok shutdown, so closing
1062 // it here (which will block until required operations are complete) gives
1063 // more head start for those operations to finish.
1065 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:ThreadPool");
1066 BrowserThreadImpl::ShutdownThreadPool();
1069 #if !defined(OS_IOS)
1070 // Must happen after the IO thread is shutdown since this may be accessed from
1073 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUChannelFactory");
1074 if (BrowserGpuChannelHostFactory::instance())
1075 BrowserGpuChannelHostFactory::Terminate();
1078 // Must happen after the I/O thread is shutdown since this class lives on the
1079 // I/O thread and isn't threadsafe.
1081 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GamepadService");
1082 GamepadService::GetInstance()->Terminate();
1085 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:SensorService");
1086 DeviceInertialSensorService::GetInstance()->Shutdown();
1088 #if !defined(OS_ANDROID)
1090 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:BatteryStatusService");
1091 device::BatteryStatusService::GetInstance()->Shutdown();
1095 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DeleteDataSources");
1096 URLDataManager::DeleteDataSources();
1098 #endif // !defined(OS_IOS)
1101 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:PostDestroyThreads");
1102 parts_
->PostDestroyThreads();
1106 void BrowserMainLoop::StopStartupTracingTimer() {
1107 startup_trace_timer_
.Stop();
1110 void BrowserMainLoop::InitializeMainThread() {
1111 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeMainThread");
1112 static const char kThreadName
[] = "CrBrowserMain";
1113 base::PlatformThread::SetName(kThreadName
);
1114 if (main_message_loop_
)
1115 main_message_loop_
->set_thread_name(kThreadName
);
1117 // Register the main thread by instantiating it, but don't call any methods.
1119 new BrowserThreadImpl(BrowserThread::UI
, base::MessageLoop::current()));
1122 int BrowserMainLoop::BrowserThreadsStarted() {
1123 TRACE_EVENT0("startup", "BrowserMainLoop::BrowserThreadsStarted");
1125 #if !defined(OS_IOS)
1126 indexed_db_thread_
.reset(new base::Thread("IndexedDB"));
1127 indexed_db_thread_
->Start();
1130 #if !defined(OS_IOS)
1131 HistogramSynchronizer::GetInstance();
1133 #if defined(OS_ANDROID)
1134 // Up the priority of the UI thread.
1135 base::PlatformThread::SetCurrentThreadPriority(base::ThreadPriority::DISPLAY
);
1138 bool always_uses_gpu
= true;
1139 bool established_gpu_channel
= false;
1140 #if defined(OS_ANDROID)
1141 // TODO(crbug.com/439322): This should be set to |true|.
1142 established_gpu_channel
= false;
1143 BrowserGpuChannelHostFactory::Initialize(established_gpu_channel
);
1144 #elif defined(USE_AURA) || defined(OS_MACOSX)
1145 established_gpu_channel
= true;
1146 if (!GpuDataManagerImpl::GetInstance()->CanUseGpuBrowserCompositor() ||
1147 parsed_command_line_
.HasSwitch(switches::kDisableGpuEarlyInit
)) {
1148 established_gpu_channel
= always_uses_gpu
= false;
1150 BrowserGpuChannelHostFactory::Initialize(established_gpu_channel
);
1151 ImageTransportFactory::Initialize();
1152 #if defined(USE_AURA)
1153 if (aura::Env::GetInstance()) {
1154 aura::Env::GetInstance()->set_context_factory(GetContextFactory());
1156 #endif // defined(USE_AURA)
1157 #endif // defined(OS_ANDROID)
1159 // Enable the GpuMemoryBuffer dump provider with IO thread affinity. Note that
1160 // unregistration happens on the IO thread (See
1161 // BrowserProcessSubThread::IOThreadPreCleanUp).
1162 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
1163 BrowserGpuMemoryBufferManager::current(), io_thread_
->task_runner());
1166 TRACE_EVENT0("startup", "BrowserThreadsStarted::Subsystem:AudioMan");
1167 audio_manager_
.reset(media::AudioManager::CreateWithHangTimer(
1168 MediaInternals::GetInstance(), io_thread_
->task_runner()));
1172 TRACE_EVENT0("startup", "BrowserThreadsStarted::Subsystem:MidiManager");
1173 midi_manager_
.reset(media::midi::MidiManager::Create());
1176 #if defined(OS_LINUX) && defined(USE_UDEV)
1177 device_monitor_linux_
.reset(new DeviceMonitorLinux());
1178 #elif defined(OS_MACOSX)
1179 device_monitor_mac_
.reset(new DeviceMonitorMac());
1183 UMA_HISTOGRAM_BOOLEAN("Windows.Win32kRendererLockdown",
1184 IsWin32kRendererLockdownEnabled());
1186 // RDH needs the IO thread to be created
1188 TRACE_EVENT0("startup",
1189 "BrowserMainLoop::BrowserThreadsStarted:InitResourceDispatcherHost");
1190 resource_dispatcher_host_
.reset(new ResourceDispatcherHostImpl());
1193 // MediaStreamManager needs the IO thread to be created.
1195 TRACE_EVENT0("startup",
1196 "BrowserMainLoop::BrowserThreadsStarted:InitMediaStreamManager");
1197 media_stream_manager_
.reset(new MediaStreamManager(audio_manager_
.get()));
1201 TRACE_EVENT0("startup",
1202 "BrowserMainLoop::BrowserThreadsStarted:InitSpeechRecognition");
1203 speech_recognition_manager_
.reset(new SpeechRecognitionManagerImpl(
1204 audio_manager_
.get(), media_stream_manager_
.get()));
1210 "BrowserMainLoop::BrowserThreadsStarted::InitUserInputMonitor");
1211 user_input_monitor_
= media::UserInputMonitor::Create(
1212 io_thread_
->task_runner(), main_thread_
->task_runner());
1216 TRACE_EVENT0("startup",
1217 "BrowserMainLoop::BrowserThreadsStarted::TimeZoneMonitor");
1218 time_zone_monitor_
= TimeZoneMonitor::Create();
1221 // Alert the clipboard class to which threads are allowed to access the
1223 std::vector
<base::PlatformThreadId
> allowed_clipboard_threads
;
1224 // The current thread is the UI thread.
1225 allowed_clipboard_threads
.push_back(base::PlatformThread::CurrentId());
1227 // On Windows, clipboards are also used on the FILE or IO threads.
1228 allowed_clipboard_threads
.push_back(file_thread_
->GetThreadId());
1229 allowed_clipboard_threads
.push_back(io_thread_
->GetThreadId());
1231 ui::Clipboard::SetAllowedThreads(allowed_clipboard_threads
);
1233 // When running the GPU thread in-process, avoid optimistically starting it
1234 // since creating the GPU thread races against creation of the one-and-only
1235 // ChildProcess instance which is created by the renderer thread.
1236 if (GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL
) &&
1237 !established_gpu_channel
&&
1239 !UsingInProcessGpu()) {
1240 TRACE_EVENT_INSTANT0("gpu", "Post task to launch GPU process",
1241 TRACE_EVENT_SCOPE_THREAD
);
1242 BrowserThread::PostTask(
1243 BrowserThread::IO
, FROM_HERE
,
1244 base::Bind(base::IgnoreResult(&GpuProcessHost::Get
),
1245 GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED
,
1246 CAUSE_FOR_GPU_LAUNCH_BROWSER_STARTUP
));
1249 #if defined(OS_MACOSX)
1250 ThemeHelperMac::GetInstance();
1251 SystemHotkeyHelperMac::GetInstance()->DeferredLoadSystemHotkeys();
1252 if (ShouldEnableBootstrapSandbox()) {
1253 TRACE_EVENT0("startup",
1254 "BrowserMainLoop::BrowserThreadsStarted:BootstrapSandbox");
1255 CHECK(GetBootstrapSandbox());
1257 #endif // defined(OS_MACOSX)
1259 #endif // !defined(OS_IOS)
1261 mojo_shell_context_
.reset(new MojoShellContext
);
1263 return result_code_
;
1266 bool BrowserMainLoop::UsingInProcessGpu() const {
1267 return parsed_command_line_
.HasSwitch(switches::kSingleProcess
) ||
1268 parsed_command_line_
.HasSwitch(switches::kInProcessGPU
);
1271 bool BrowserMainLoop::InitializeToolkit() {
1272 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeToolkit");
1273 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::InitializeToolkit");
1275 // TODO(evan): this function is rather subtle, due to the variety
1276 // of intersecting ifdefs we have. To keep it easy to follow, there
1277 // are no #else branches on any #ifs.
1278 // TODO(stevenjb): Move platform specific code into platform specific Parts
1279 // (Need to add InitializeToolkit stage to BrowserParts).
1280 // See also GTK setup in EarlyInitialization, above, and associated comments.
1283 // Init common control sex.
1284 INITCOMMONCONTROLSEX config
;
1285 config
.dwSize
= sizeof(config
);
1286 config
.dwICC
= ICC_WIN95_CLASSES
;
1287 if (!InitCommonControlsEx(&config
))
1291 #if defined(USE_AURA)
1293 #if defined(USE_X11)
1294 if (!gfx::GetXDisplay())
1298 // Env creates the compositor. Aura widgets need the compositor to be created
1299 // before they can be initialized by the browser.
1300 aura::Env::CreateInstance(true);
1301 #endif // defined(USE_AURA)
1304 parts_
->ToolkitInitialized();
1309 void BrowserMainLoop::MainMessageLoopRun() {
1310 #if defined(OS_ANDROID)
1311 // Android's main message loop is the Java message loop.
1314 DCHECK(base::MessageLoopForUI::IsCurrent());
1315 if (parameters_
.ui_task
) {
1316 base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE
,
1317 *parameters_
.ui_task
);
1320 base::RunLoop run_loop
;
1325 base::FilePath
BrowserMainLoop::GetStartupTraceFileName(
1326 const base::CommandLine
& command_line
) const {
1327 base::FilePath trace_file
;
1328 if (command_line
.HasSwitch(switches::kTraceStartup
)) {
1329 trace_file
= command_line
.GetSwitchValuePath(
1330 switches::kTraceStartupFile
);
1331 // trace_file = "none" means that startup events will show up for the next
1332 // begin/end tracing (via about:tracing or AutomationProxy::BeginTracing/
1333 // EndTracing, for example).
1334 if (trace_file
== base::FilePath().AppendASCII("none"))
1337 if (trace_file
.empty()) {
1338 #if defined(OS_ANDROID)
1339 TracingControllerAndroid::GenerateTracingFilePath(&trace_file
);
1341 // Default to saving the startup trace into the current dir.
1342 trace_file
= base::FilePath().AppendASCII("chrometrace.log");
1346 #if defined(OS_ANDROID)
1347 TracingControllerAndroid::GenerateTracingFilePath(&trace_file
);
1349 trace_file
= tracing::TraceConfigFile::GetInstance()->GetResultFile();
1356 void BrowserMainLoop::InitStartupTracingForDuration(
1357 const base::CommandLine
& command_line
) {
1358 DCHECK(is_tracing_startup_for_duration_
);
1360 startup_trace_file_
= GetStartupTraceFileName(parsed_command_line_
);
1363 if (command_line
.HasSwitch(switches::kTraceStartup
)) {
1364 std::string delay_str
= command_line
.GetSwitchValueASCII(
1365 switches::kTraceStartupDuration
);
1366 if (!delay_str
.empty() && !base::StringToInt(delay_str
, &delay_secs
)) {
1367 DLOG(WARNING
) << "Could not parse --" << switches::kTraceStartupDuration
1368 << "=" << delay_str
<< " defaulting to 5 (secs)";
1372 delay_secs
= tracing::TraceConfigFile::GetInstance()->GetStartupDuration();
1375 startup_trace_timer_
.Start(FROM_HERE
,
1376 base::TimeDelta::FromSeconds(delay_secs
),
1378 &BrowserMainLoop::EndStartupTracing
);
1381 void BrowserMainLoop::EndStartupTracing() {
1382 DCHECK(is_tracing_startup_for_duration_
);
1384 is_tracing_startup_for_duration_
= false;
1385 TracingController::GetInstance()->DisableRecording(
1386 TracingController::CreateFileSink(
1387 startup_trace_file_
,
1388 base::Bind(OnStoppedStartupTracing
, startup_trace_file_
)));
1391 } // namespace content