1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/browser/browser_main_loop.h"
8 #include "base/command_line.h"
9 #include "base/location.h"
10 #include "base/logging.h"
11 #include "base/memory/memory_pressure_monitor.h"
12 #include "base/metrics/field_trial.h"
13 #include "base/metrics/histogram.h"
14 #include "base/pending_task.h"
15 #include "base/power_monitor/power_monitor.h"
16 #include "base/power_monitor/power_monitor_device_source.h"
17 #include "base/process/process_metrics.h"
18 #include "base/profiler/scoped_profile.h"
19 #include "base/run_loop.h"
20 #include "base/single_thread_task_runner.h"
21 #include "base/strings/string_number_conversions.h"
22 #include "base/strings/string_split.h"
23 #include "base/system_monitor/system_monitor.h"
24 #include "base/thread_task_runner_handle.h"
25 #include "base/threading/thread_restrictions.h"
26 #include "base/timer/hi_res_timer_manager.h"
27 #include "base/trace_event/memory_dump_manager.h"
28 #include "base/trace_event/trace_event.h"
29 #include "content/browser/browser_thread_impl.h"
30 #include "content/browser/device_sensors/device_inertial_sensor_service.h"
31 #include "content/browser/dom_storage/dom_storage_area.h"
32 #include "content/browser/download/save_file_manager.h"
33 #include "content/browser/gamepad/gamepad_service.h"
34 #include "content/browser/gpu/browser_gpu_channel_host_factory.h"
35 #include "content/browser/gpu/browser_gpu_memory_buffer_manager.h"
36 #include "content/browser/gpu/compositor_util.h"
37 #include "content/browser/gpu/gpu_data_manager_impl.h"
38 #include "content/browser/gpu/gpu_process_host.h"
39 #include "content/browser/gpu/gpu_process_host_ui_shim.h"
40 #include "content/browser/histogram_synchronizer.h"
41 #include "content/browser/loader/resource_dispatcher_host_impl.h"
42 #include "content/browser/media/media_internals.h"
43 #include "content/browser/mojo/mojo_shell_context.h"
44 #include "content/browser/net/browser_online_state_observer.h"
45 #include "content/browser/renderer_host/media/media_stream_manager.h"
46 #include "content/browser/speech/speech_recognition_manager_impl.h"
47 #include "content/browser/startup_task_runner.h"
48 #include "content/browser/time_zone_monitor.h"
49 #include "content/browser/webui/content_web_ui_controller_factory.h"
50 #include "content/browser/webui/url_data_manager.h"
51 #include "content/common/content_switches_internal.h"
52 #include "content/common/host_discardable_shared_memory_manager.h"
53 #include "content/common/host_shared_bitmap_manager.h"
54 #include "content/public/browser/browser_main_parts.h"
55 #include "content/public/browser/content_browser_client.h"
56 #include "content/public/browser/render_process_host.h"
57 #include "content/public/browser/tracing_controller.h"
58 #include "content/public/common/content_switches.h"
59 #include "content/public/common/main_function_params.h"
60 #include "content/public/common/result_codes.h"
61 #include "crypto/nss_util.h"
62 #include "device/battery/battery_status_service.h"
63 #include "media/audio/audio_manager.h"
64 #include "media/base/media.h"
65 #include "media/base/user_input_monitor.h"
66 #include "media/midi/midi_manager.h"
67 #include "net/base/network_change_notifier.h"
68 #include "net/socket/client_socket_factory.h"
69 #include "net/ssl/ssl_config_service.h"
70 #include "ui/base/clipboard/clipboard.h"
72 #if defined(USE_AURA) || (defined(OS_MACOSX) && !defined(OS_IOS))
73 #include "content/browser/compositor/image_transport_factory.h"
77 #include "content/public/browser/context_factory.h"
78 #include "ui/aura/env.h"
82 #include "content/browser/renderer_host/render_process_host_impl.h"
85 #if defined(OS_ANDROID)
86 #include "base/android/jni_android.h"
87 #include "content/browser/android/browser_startup_controller.h"
88 #include "content/browser/android/browser_surface_texture_manager.h"
89 #include "content/browser/android/in_process_surface_texture_manager.h"
90 #include "content/browser/android/tracing_controller_android.h"
91 #include "content/browser/screen_orientation/screen_orientation_delegate_android.h"
92 #include "content/public/browser/screen_orientation_provider.h"
93 #include "ui/gl/gl_surface.h"
96 #if defined(OS_MACOSX)
97 #include "media/base/mac/avfoundation_glue.h"
100 #if defined(OS_MACOSX) && !defined(OS_IOS)
101 #include "base/memory/memory_pressure_monitor_mac.h"
102 #include "content/browser/bootstrap_sandbox_mac.h"
103 #include "content/browser/browser_io_surface_manager_mac.h"
104 #include "content/browser/cocoa/system_hotkey_helper_mac.h"
105 #include "content/browser/compositor/browser_compositor_view_mac.h"
106 #include "content/browser/in_process_io_surface_manager_mac.h"
107 #include "content/browser/theme_helper_mac.h"
112 #include <commctrl.h>
113 #include <shellapi.h>
115 #include "base/memory/memory_pressure_monitor_win.h"
116 #include "content/browser/system_message_window_win.h"
117 #include "content/common/sandbox_win.h"
118 #include "net/base/winsock_init.h"
119 #include "ui/base/l10n/l10n_util_win.h"
122 #if defined(OS_CHROMEOS)
123 #include "base/memory/memory_pressure_monitor_chromeos.h"
124 #include "chromeos/chromeos_switches.h"
127 #if defined(USE_GLIB)
128 #include <glib-object.h>
131 #if defined(OS_LINUX) && defined(USE_UDEV)
132 #include "content/browser/device_monitor_udev.h"
133 #elif defined(OS_MACOSX) && !defined(OS_IOS)
134 #include "content/browser/device_monitor_mac.h"
137 #if defined(OS_POSIX) && !defined(OS_MACOSX)
138 #include "content/browser/renderer_host/render_sandbox_host_linux.h"
139 #include "content/browser/zygote_host/zygote_host_impl_linux.h"
140 #include "sandbox/linux/suid/client/setuid_sandbox_host.h"
143 #if defined(ENABLE_PLUGINS)
144 #include "content/browser/plugin_service_impl.h"
147 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
148 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
152 #include "ui/gfx/x/x11_connection.h"
153 #include "ui/gfx/x/x11_types.h"
156 // One of the linux specific headers defines this as a macro.
164 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
165 void SetupSandbox(const base::CommandLine
& parsed_command_line
) {
166 TRACE_EVENT0("startup", "SetupSandbox");
167 base::FilePath sandbox_binary
;
169 scoped_ptr
<sandbox::SetuidSandboxHost
> setuid_sandbox_host(
170 sandbox::SetuidSandboxHost::Create());
172 const bool want_setuid_sandbox
=
173 !parsed_command_line
.HasSwitch(switches::kNoSandbox
) &&
174 !parsed_command_line
.HasSwitch(switches::kDisableSetuidSandbox
) &&
175 !setuid_sandbox_host
->IsDisabledViaEnvironment();
177 static const char no_suid_error
[] =
178 "Running without the SUID sandbox! See "
179 "https://code.google.com/p/chromium/wiki/LinuxSUIDSandboxDevelopment "
180 "for more information on developing with the sandbox on.";
181 if (want_setuid_sandbox
) {
182 sandbox_binary
= setuid_sandbox_host
->GetSandboxBinaryPath();
183 if (sandbox_binary
.empty()) {
184 // This needs to be fatal. Talk to security@chromium.org if you feel
186 LOG(FATAL
) << no_suid_error
;
189 LOG(ERROR
) << no_suid_error
;
192 // Tickle the sandbox host and zygote host so they fork now.
193 RenderSandboxHostLinux::GetInstance()->Init();
194 ZygoteHostImpl::GetInstance()->Init(sandbox_binary
.value());
198 #if defined(USE_GLIB)
199 static void GLibLogHandler(const gchar
* log_domain
,
200 GLogLevelFlags log_level
,
201 const gchar
* message
,
204 log_domain
= "<unknown>";
206 message
= "<no message>";
208 if (strstr(message
, "Unable to retrieve the file info for")) {
209 LOG(ERROR
) << "GTK File code error: " << message
;
210 } else if (strstr(message
, "Could not find the icon") &&
211 strstr(log_domain
, "Gtk")) {
212 LOG(ERROR
) << "GTK icon error: " << message
;
213 } else if (strstr(message
, "Theme file for default has no") ||
214 strstr(message
, "Theme directory") ||
215 strstr(message
, "theme pixmap") ||
216 strstr(message
, "locate theme engine")) {
217 LOG(ERROR
) << "GTK theme error: " << message
;
218 } else if (strstr(message
, "Unable to create Ubuntu Menu Proxy") &&
219 strstr(log_domain
, "<unknown>")) {
220 LOG(ERROR
) << "GTK menu proxy create failed";
221 } else if (strstr(message
, "Out of memory") &&
222 strstr(log_domain
, "<unknown>")) {
223 LOG(ERROR
) << "DBus call timeout or out of memory: "
224 << "http://crosbug.com/15496";
225 } else if (strstr(message
, "Could not connect: Connection refused") &&
226 strstr(log_domain
, "<unknown>")) {
227 LOG(ERROR
) << "DConf settings backend could not connect to session bus: "
228 << "http://crbug.com/179797";
229 } else if (strstr(message
, "Attempting to store changes into") ||
230 strstr(message
, "Attempting to set the permissions of")) {
231 LOG(ERROR
) << message
<< " (http://bugs.chromium.org/161366)";
232 } else if (strstr(message
, "drawable is not a native X11 window")) {
233 LOG(ERROR
) << message
<< " (http://bugs.chromium.org/329991)";
234 } else if (strstr(message
, "Cannot do system-bus activation with no user")) {
235 LOG(ERROR
) << message
<< " (http://crbug.com/431005)";
237 LOG(DFATAL
) << log_domain
<< ": " << message
;
241 static void SetUpGLibLogHandler() {
242 // Register GLib-handled assertions to go through our logging system.
243 const char* kLogDomains
[] = { NULL
, "Gtk", "Gdk", "GLib", "GLib-GObject" };
244 for (size_t i
= 0; i
< arraysize(kLogDomains
); i
++) {
245 g_log_set_handler(kLogDomains
[i
],
246 static_cast<GLogLevelFlags
>(G_LOG_FLAG_RECURSION
|
249 G_LOG_LEVEL_CRITICAL
|
250 G_LOG_LEVEL_WARNING
),
257 void OnStoppedStartupTracing(const base::FilePath
& trace_file
) {
258 VLOG(0) << "Completed startup tracing to " << trace_file
.value();
261 // Disable optimizations for this block of functions so the compiler doesn't
262 // merge them all together. This makes it possible to tell what thread was
263 // unresponsive by inspecting the callstack.
264 MSVC_DISABLE_OPTIMIZE()
265 MSVC_PUSH_DISABLE_WARNING(4748)
267 NOINLINE
void ResetThread_DB(scoped_ptr
<BrowserProcessSubThread
> thread
) {
268 volatile int inhibit_comdat
= __LINE__
;
269 ALLOW_UNUSED_LOCAL(inhibit_comdat
);
273 NOINLINE
void ResetThread_FILE(scoped_ptr
<BrowserProcessSubThread
> thread
) {
274 volatile int inhibit_comdat
= __LINE__
;
275 ALLOW_UNUSED_LOCAL(inhibit_comdat
);
279 NOINLINE
void ResetThread_FILE_USER_BLOCKING(
280 scoped_ptr
<BrowserProcessSubThread
> thread
) {
281 volatile int inhibit_comdat
= __LINE__
;
282 ALLOW_UNUSED_LOCAL(inhibit_comdat
);
286 NOINLINE
void ResetThread_PROCESS_LAUNCHER(
287 scoped_ptr
<BrowserProcessSubThread
> thread
) {
288 volatile int inhibit_comdat
= __LINE__
;
289 ALLOW_UNUSED_LOCAL(inhibit_comdat
);
293 NOINLINE
void ResetThread_CACHE(scoped_ptr
<BrowserProcessSubThread
> thread
) {
294 volatile int inhibit_comdat
= __LINE__
;
295 ALLOW_UNUSED_LOCAL(inhibit_comdat
);
299 NOINLINE
void ResetThread_IO(scoped_ptr
<BrowserProcessSubThread
> thread
) {
300 volatile int inhibit_comdat
= __LINE__
;
301 ALLOW_UNUSED_LOCAL(inhibit_comdat
);
306 NOINLINE
void ResetThread_IndexedDb(scoped_ptr
<base::Thread
> thread
) {
307 volatile int inhibit_comdat
= __LINE__
;
308 ALLOW_UNUSED_LOCAL(inhibit_comdat
);
314 MSVC_ENABLE_OPTIMIZE();
317 // Creates a memory pressure monitor using automatic thresholds, or those
318 // specified on the command-line. Ownership is passed to the caller.
319 base::win::MemoryPressureMonitor
* CreateWinMemoryPressureMonitor(
320 const base::CommandLine
& parsed_command_line
) {
321 std::vector
<std::string
> thresholds
;
323 parsed_command_line
.GetSwitchValueASCII(
324 switches::kMemoryPressureThresholdsMb
),
328 int moderate_threshold_mb
= 0;
329 int critical_threshold_mb
= 0;
330 if (thresholds
.size() == 2 &&
331 base::StringToInt(thresholds
[0], &moderate_threshold_mb
) &&
332 base::StringToInt(thresholds
[1], &critical_threshold_mb
) &&
333 moderate_threshold_mb
>= critical_threshold_mb
&&
334 critical_threshold_mb
>= 0) {
335 return new base::win::MemoryPressureMonitor(moderate_threshold_mb
,
336 critical_threshold_mb
);
339 // In absence of valid switches use the automatic defaults.
340 return new base::win::MemoryPressureMonitor();
342 #endif // defined(OS_WIN)
346 // The currently-running BrowserMainLoop. There can be one or zero.
347 BrowserMainLoop
* g_current_browser_main_loop
= NULL
;
349 // For measuring memory usage after each task. Behind a command line flag.
350 class BrowserMainLoop::MemoryObserver
: public base::MessageLoop::TaskObserver
{
353 ~MemoryObserver() override
{}
355 void WillProcessTask(const base::PendingTask
& pending_task
) override
{}
357 void DidProcessTask(const base::PendingTask
& pending_task
) override
{
358 #if !defined(OS_IOS) // No ProcessMetrics on IOS.
359 scoped_ptr
<base::ProcessMetrics
> process_metrics(
360 base::ProcessMetrics::CreateProcessMetrics(
361 #if defined(OS_MACOSX)
362 base::GetCurrentProcessHandle(), NULL
));
364 base::GetCurrentProcessHandle()));
366 size_t private_bytes
;
367 process_metrics
->GetMemoryBytes(&private_bytes
, NULL
);
368 LOCAL_HISTOGRAM_MEMORY_KB("Memory.BrowserUsed", private_bytes
>> 10);
372 DISALLOW_COPY_AND_ASSIGN(MemoryObserver
);
376 // BrowserMainLoop construction / destruction =============================
378 BrowserMainLoop
* BrowserMainLoop::GetInstance() {
379 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
380 return g_current_browser_main_loop
;
383 BrowserMainLoop::BrowserMainLoop(const MainFunctionParams
& parameters
)
384 : parameters_(parameters
),
385 parsed_command_line_(parameters
.command_line
),
386 result_code_(RESULT_CODE_NORMAL_EXIT
),
387 created_threads_(false),
388 // ContentMainRunner should have enabled tracing of the browser process
389 // when kTraceStartup is in the command line.
391 parameters
.command_line
.HasSwitch(switches::kTraceStartup
)) {
392 DCHECK(!g_current_browser_main_loop
);
393 g_current_browser_main_loop
= this;
396 BrowserMainLoop::~BrowserMainLoop() {
397 DCHECK_EQ(this, g_current_browser_main_loop
);
399 ui::Clipboard::DestroyClipboardForCurrentThread();
400 #endif // !defined(OS_IOS)
401 g_current_browser_main_loop
= NULL
;
404 void BrowserMainLoop::Init() {
405 TRACE_EVENT0("startup", "BrowserMainLoop::Init");
406 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::Init");
409 GetContentClient()->browser()->CreateBrowserMainParts(parameters_
));
412 // BrowserMainLoop stages ==================================================
414 void BrowserMainLoop::EarlyInitialization() {
415 TRACE_EVENT0("startup", "BrowserMainLoop::EarlyInitialization");
416 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::EarlyInitialization");
418 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
419 // No thread should be created before this call, as SetupSandbox()
420 // will end-up using fork().
421 SetupSandbox(parsed_command_line_
);
425 if (UsingInProcessGpu()) {
426 if (!gfx::InitializeThreadedX11()) {
427 LOG(ERROR
) << "Failed to put Xlib into threaded mode.";
432 // GLib's spawning of new processes is buggy, so it's important that at this
433 // point GLib does not need to start DBUS. Chrome should always start with
434 // DBUS_SESSION_BUS_ADDRESS properly set. See crbug.com/309093.
435 #if defined(USE_GLIB)
436 // g_type_init will be deprecated in 2.36. 2.35 is the development
437 // version for 2.36, hence do not call g_type_init starting 2.35.
438 // http://developer.gnome.org/gobject/unstable/gobject-Type-Information.html#g-type-init
439 #if !GLIB_CHECK_VERSION(2, 35, 0)
440 // GLib type system initialization. Needed at least for gconf,
441 // used in net/proxy/proxy_config_service_linux.cc. Most likely
442 // this is superfluous as gtk_init() ought to do this. It's
443 // definitely harmless, so retained as a reminder of this
444 // requirement for gconf.
448 SetUpGLibLogHandler();
452 parts_
->PreEarlyInitialization();
454 #if defined(OS_MACOSX)
455 // We use quite a few file descriptors for our IPC, and the default limit on
456 // the Mac is low (256), so bump it up.
457 base::SetFdLimit(1024);
461 net::EnsureWinsockInit();
464 #if !defined(USE_OPENSSL)
465 // We want to be sure to init NSPR on the main thread.
466 crypto::EnsureNSPRInit();
467 #endif // !defined(USE_OPENSSL)
470 if (parsed_command_line_
.HasSwitch(switches::kRendererProcessLimit
)) {
471 std::string limit_string
= parsed_command_line_
.GetSwitchValueASCII(
472 switches::kRendererProcessLimit
);
473 size_t process_limit
;
474 if (base::StringToSizeT(limit_string
, &process_limit
)) {
475 RenderProcessHost::SetMaxRendererProcessCount(process_limit
);
478 #endif // !defined(OS_IOS)
480 // TODO(boliu): kSingleProcess check is a temporary workaround for
481 // in-process Android WebView. crbug.com/503724 tracks proper fix.
482 if (!parsed_command_line_
.HasSwitch(switches::kSingleProcess
)) {
483 base::DiscardableMemoryAllocator::SetInstance(
484 HostDiscardableSharedMemoryManager::current());
488 parts_
->PostEarlyInitialization();
491 void BrowserMainLoop::PreMainMessageLoopStart() {
493 TRACE_EVENT0("startup",
494 "BrowserMainLoop::MainMessageLoopStart:PreMainMessageLoopStart");
495 parts_
->PreMainMessageLoopStart();
499 // If we're running tests (ui_task is non-null), then the ResourceBundle
500 // has already been initialized.
501 if (!parameters_
.ui_task
) {
502 // Override the configured locale with the user's preferred UI language.
503 l10n_util::OverrideLocaleWithUILanguageList();
508 void BrowserMainLoop::MainMessageLoopStart() {
509 // DO NOT add more code here. Use PreMainMessageLoopStart() above or
510 // PostMainMessageLoopStart() below.
512 TRACE_EVENT0("startup", "BrowserMainLoop::MainMessageLoopStart");
513 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::MainMessageLoopStart");
515 // Create a MessageLoop if one does not already exist for the current thread.
516 if (!base::MessageLoop::current())
517 main_message_loop_
.reset(new base::MessageLoopForUI
);
519 InitializeMainThread();
522 void BrowserMainLoop::PostMainMessageLoopStart() {
524 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SystemMonitor");
525 system_monitor_
.reset(new base::SystemMonitor
);
528 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:PowerMonitor");
529 scoped_ptr
<base::PowerMonitorSource
> power_monitor_source(
530 new base::PowerMonitorDeviceSource());
531 power_monitor_
.reset(new base::PowerMonitor(power_monitor_source
.Pass()));
534 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:HighResTimerManager");
535 hi_res_timer_manager_
.reset(new base::HighResolutionTimerManager
);
538 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:NetworkChangeNotifier");
539 network_change_notifier_
.reset(net::NetworkChangeNotifier::Create());
544 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MediaFeatures");
545 media::InitializeMediaLibrary();
548 TRACE_EVENT0("startup",
549 "BrowserMainLoop::Subsystem:ContentWebUIController");
550 WebUIControllerFactory::RegisterFactory(
551 ContentWebUIControllerFactory::GetInstance());
555 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:OnlineStateObserver");
556 online_state_observer_
.reset(new BrowserOnlineStateObserver
);
560 system_stats_monitor_
.reset(
561 new base::trace_event::TraceEventSystemStatsMonitor(
562 base::ThreadTaskRunnerHandle::Get()));
564 #endif // !defined(OS_IOS)
567 system_message_window_
.reset(new SystemMessageWindowWin
);
571 parts_
->PostMainMessageLoopStart();
574 // Start tracing to a file if needed. Only do this after starting the main
575 // message loop to avoid calling MessagePumpForUI::ScheduleWork() before
576 // MessagePumpForUI::Start() as it will crash the browser.
577 if (is_tracing_startup_
) {
578 TRACE_EVENT0("startup", "BrowserMainLoop::InitStartupTracing");
579 InitStartupTracing(parsed_command_line_
);
581 #endif // !defined(OS_IOS)
583 #if defined(OS_ANDROID)
585 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SurfaceTextureManager");
586 if (parsed_command_line_
.HasSwitch(switches::kSingleProcess
)) {
587 SurfaceTextureManager::SetInstance(
588 InProcessSurfaceTextureManager::GetInstance());
590 SurfaceTextureManager::SetInstance(
591 BrowserSurfaceTextureManager::GetInstance());
595 if (!parsed_command_line_
.HasSwitch(
596 switches::kDisableScreenOrientationLock
)) {
597 TRACE_EVENT0("startup",
598 "BrowserMainLoop::Subsystem:ScreenOrientationProvider");
599 screen_orientation_delegate_
.reset(
600 new ScreenOrientationDelegateAndroid());
601 ScreenOrientationProvider::SetDelegate(screen_orientation_delegate_
.get());
605 #if defined(OS_MACOSX) && !defined(OS_IOS)
607 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:IOSurfaceManager");
608 if (parsed_command_line_
.HasSwitch(switches::kSingleProcess
)) {
609 IOSurfaceManager::SetInstance(InProcessIOSurfaceManager::GetInstance());
611 IOSurfaceManager::SetInstance(BrowserIOSurfaceManager::GetInstance());
616 if (parsed_command_line_
.HasSwitch(switches::kMemoryMetrics
)) {
617 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MemoryObserver");
618 memory_observer_
.reset(new MemoryObserver());
619 base::MessageLoop::current()->AddTaskObserver(memory_observer_
.get());
622 if (parsed_command_line_
.HasSwitch(
623 switches::kEnableAggressiveDOMStorageFlushing
)) {
624 TRACE_EVENT0("startup",
625 "BrowserMainLoop::Subsystem:EnableAggressiveCommitDelay");
626 DOMStorageArea::EnableAggressiveCommitDelay();
629 base::trace_event::MemoryDumpManager::GetInstance()->Initialize();
631 // Enable the dump providers.
632 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
633 HostSharedBitmapManager::current());
635 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
636 trace_memory_controller_
.reset(new base::trace_event::TraceMemoryController(
637 base::MessageLoop::current()->task_runner(),
638 ::HeapProfilerWithPseudoStackStart
, ::HeapProfilerStop
,
643 int BrowserMainLoop::PreCreateThreads() {
644 // Need to initialize in-process GpuDataManager before creating threads.
645 // It's unsafe to append the gpu command line switches to the global
646 // CommandLine::ForCurrentProcess object after threads are created.
647 // Also need to initialize before BrowserMainParts::PreCreateThreads, so
648 // BrowserMainParts has a hook to set GpuDataManager strings before
649 // starting Gpu process.
650 GpuDataManagerImpl::GetInstance()->Initialize();
653 TRACE_EVENT0("startup",
654 "BrowserMainLoop::CreateThreads:PreCreateThreads");
655 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::PreCreateThreads");
657 result_code_
= parts_
->PreCreateThreads();
660 // TODO(chrisha): Abstract away this construction mess to a helper function,
661 // once MemoryPressureMonitor is made a concrete class.
662 #if defined(OS_CHROMEOS)
663 if (chromeos::switches::MemoryPressureHandlingEnabled()) {
664 memory_pressure_monitor_
.reset(new base::chromeos::MemoryPressureMonitor(
665 chromeos::switches::GetMemoryPressureThresholds()));
667 #elif defined(OS_MACOSX) && !defined(OS_IOS)
668 memory_pressure_monitor_
.reset(new base::mac::MemoryPressureMonitor());
669 #elif defined(OS_WIN)
670 memory_pressure_monitor_
.reset(CreateWinMemoryPressureMonitor(
671 parsed_command_line_
));
674 #if defined(ENABLE_PLUGINS)
675 // Prior to any processing happening on the io thread, we create the
676 // plugin service as it is predominantly used from the io thread,
677 // but must be created on the main thread. The service ctor is
678 // inexpensive and does not invoke the io_thread() accessor.
680 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads:PluginService");
681 PluginService::GetInstance()->Init();
685 #if defined(OS_MACOSX)
687 // Initialize AVFoundation if supported, for audio and video.
688 TRACE_EVENT0("startup",
689 "BrowserMainLoop::CreateThreads:InitializeAVFoundation");
690 AVFoundationGlue::InitializeAVFoundation();
694 #if !defined(OS_IOS) && (!defined(GOOGLE_CHROME_BUILD) || defined(OS_ANDROID))
695 // Single-process is an unsupported and not fully tested mode, so
696 // don't enable it for official Chrome builds (except on Android).
697 if (parsed_command_line_
.HasSwitch(switches::kSingleProcess
))
698 RenderProcessHost::SetRunRendererInProcess(true);
704 void BrowserMainLoop::CreateStartupTasks() {
705 TRACE_EVENT0("startup", "BrowserMainLoop::CreateStartupTasks");
706 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::CreateStartupTasks");
708 // First time through, we really want to create all the tasks
709 if (!startup_task_runner_
.get()) {
710 #if defined(OS_ANDROID)
711 startup_task_runner_
= make_scoped_ptr(
712 new StartupTaskRunner(base::Bind(&BrowserStartupComplete
),
713 base::ThreadTaskRunnerHandle::Get()));
715 startup_task_runner_
= make_scoped_ptr(
716 new StartupTaskRunner(base::Callback
<void(int)>(),
717 base::ThreadTaskRunnerHandle::Get()));
719 StartupTask pre_create_threads
=
720 base::Bind(&BrowserMainLoop::PreCreateThreads
, base::Unretained(this));
721 startup_task_runner_
->AddTask(pre_create_threads
);
723 StartupTask create_threads
=
724 base::Bind(&BrowserMainLoop::CreateThreads
, base::Unretained(this));
725 startup_task_runner_
->AddTask(create_threads
);
727 StartupTask browser_thread_started
= base::Bind(
728 &BrowserMainLoop::BrowserThreadsStarted
, base::Unretained(this));
729 startup_task_runner_
->AddTask(browser_thread_started
);
731 StartupTask pre_main_message_loop_run
= base::Bind(
732 &BrowserMainLoop::PreMainMessageLoopRun
, base::Unretained(this));
733 startup_task_runner_
->AddTask(pre_main_message_loop_run
);
735 #if defined(OS_ANDROID)
736 if (BrowserMayStartAsynchronously()) {
737 startup_task_runner_
->StartRunningTasksAsync();
741 #if defined(OS_ANDROID)
742 if (!BrowserMayStartAsynchronously()) {
743 // A second request for asynchronous startup can be ignored, so
744 // StartupRunningTasksAsync is only called first time through. If, however,
745 // this is a request for synchronous startup then it must override any
746 // previous call for async startup, so we call RunAllTasksNow()
748 startup_task_runner_
->RunAllTasksNow();
751 startup_task_runner_
->RunAllTasksNow();
755 int BrowserMainLoop::CreateThreads() {
756 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads");
757 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::CreateThreads");
759 base::Thread::Options io_message_loop_options
;
760 io_message_loop_options
.message_loop_type
= base::MessageLoop::TYPE_IO
;
761 base::Thread::Options ui_message_loop_options
;
762 ui_message_loop_options
.message_loop_type
= base::MessageLoop::TYPE_UI
;
764 // Start threads in the order they occur in the BrowserThread::ID
765 // enumeration, except for BrowserThread::UI which is the main
768 // Must be size_t so we can increment it.
769 for (size_t thread_id
= BrowserThread::UI
+ 1;
770 thread_id
< BrowserThread::ID_COUNT
;
772 scoped_ptr
<BrowserProcessSubThread
>* thread_to_start
= NULL
;
773 base::Thread::Options options
;
776 case BrowserThread::DB
:
777 TRACE_EVENT_BEGIN1("startup",
778 "BrowserMainLoop::CreateThreads:start",
779 "Thread", "BrowserThread::DB");
780 thread_to_start
= &db_thread_
;
781 options
.timer_slack
= base::TIMER_SLACK_MAXIMUM
;
783 case BrowserThread::FILE_USER_BLOCKING
:
784 TRACE_EVENT_BEGIN1("startup",
785 "BrowserMainLoop::CreateThreads:start",
786 "Thread", "BrowserThread::FILE_USER_BLOCKING");
787 thread_to_start
= &file_user_blocking_thread_
;
789 case BrowserThread::FILE:
790 TRACE_EVENT_BEGIN1("startup",
791 "BrowserMainLoop::CreateThreads:start",
792 "Thread", "BrowserThread::FILE");
793 thread_to_start
= &file_thread_
;
795 // On Windows, the FILE thread needs to be have a UI message loop
796 // which pumps messages in such a way that Google Update can
797 // communicate back to us.
798 options
= ui_message_loop_options
;
800 options
= io_message_loop_options
;
802 options
.timer_slack
= base::TIMER_SLACK_MAXIMUM
;
804 case BrowserThread::PROCESS_LAUNCHER
:
805 TRACE_EVENT_BEGIN1("startup",
806 "BrowserMainLoop::CreateThreads:start",
807 "Thread", "BrowserThread::PROCESS_LAUNCHER");
808 thread_to_start
= &process_launcher_thread_
;
809 options
.timer_slack
= base::TIMER_SLACK_MAXIMUM
;
811 case BrowserThread::CACHE
:
812 TRACE_EVENT_BEGIN1("startup",
813 "BrowserMainLoop::CreateThreads:start",
814 "Thread", "BrowserThread::CACHE");
815 thread_to_start
= &cache_thread_
;
816 options
= io_message_loop_options
;
817 options
.timer_slack
= base::TIMER_SLACK_MAXIMUM
;
819 case BrowserThread::IO
:
820 TRACE_EVENT_BEGIN1("startup",
821 "BrowserMainLoop::CreateThreads:start",
822 "Thread", "BrowserThread::IO");
823 thread_to_start
= &io_thread_
;
824 options
= io_message_loop_options
;
825 #if defined(OS_ANDROID)
826 // Up the priority of the |io_thread_| as some of its IPCs relate to
828 options
.priority
= base::ThreadPriority::DISPLAY
;
831 case BrowserThread::UI
:
832 case BrowserThread::ID_COUNT
:
838 BrowserThread::ID id
= static_cast<BrowserThread::ID
>(thread_id
);
840 if (thread_to_start
) {
841 (*thread_to_start
).reset(new BrowserProcessSubThread(id
));
842 if (!(*thread_to_start
)->StartWithOptions(options
)) {
843 LOG(FATAL
) << "Failed to start the browser thread: id == " << id
;
849 TRACE_EVENT_END0("startup", "BrowserMainLoop::CreateThreads:start");
851 created_threads_
= true;
855 int BrowserMainLoop::PreMainMessageLoopRun() {
857 TRACE_EVENT0("startup",
858 "BrowserMainLoop::CreateThreads:PreMainMessageLoopRun");
860 "Startup", "BrowserMainLoop::PreMainMessageLoopRun");
862 parts_
->PreMainMessageLoopRun();
865 // If the UI thread blocks, the whole UI is unresponsive.
866 // Do not allow disk IO from the UI thread.
867 base::ThreadRestrictions::SetIOAllowed(false);
868 base::ThreadRestrictions::DisallowWaiting();
872 void BrowserMainLoop::RunMainMessageLoopParts() {
873 TRACE_EVENT_BEGIN_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
875 bool ran_main_loop
= false;
877 ran_main_loop
= parts_
->MainMessageLoopRun(&result_code_
);
880 MainMessageLoopRun();
882 TRACE_EVENT_END_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
885 void BrowserMainLoop::ShutdownThreadsAndCleanUp() {
886 if (!created_threads_
) {
887 // Called early, nothing to do
890 TRACE_EVENT0("shutdown", "BrowserMainLoop::ShutdownThreadsAndCleanUp");
892 // Teardown may start in PostMainMessageLoopRun, and during teardown we
893 // need to be able to perform IO.
894 base::ThreadRestrictions::SetIOAllowed(true);
895 BrowserThread::PostTask(
896 BrowserThread::IO
, FROM_HERE
,
897 base::Bind(base::IgnoreResult(&base::ThreadRestrictions::SetIOAllowed
),
900 mojo_shell_context_
.reset();
903 if (RenderProcessHost::run_renderer_in_process())
904 RenderProcessHostImpl::ShutDownInProcessRenderer();
908 TRACE_EVENT0("shutdown",
909 "BrowserMainLoop::Subsystem:PostMainMessageLoopRun");
910 parts_
->PostMainMessageLoopRun();
913 trace_memory_controller_
.reset();
914 system_stats_monitor_
.reset();
917 // Destroying the GpuProcessHostUIShims on the UI thread posts a task to
918 // delete related objects on the GPU thread. This must be done before
919 // stopping the GPU thread. The GPU thread will close IPC channels to renderer
920 // processes so this has to happen before stopping the IO thread.
922 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUProcessHostShim");
923 GpuProcessHostUIShim::DestroyAll();
925 // Cancel pending requests and prevent new requests.
926 if (resource_dispatcher_host_
) {
927 TRACE_EVENT0("shutdown",
928 "BrowserMainLoop::Subsystem:ResourceDispatcherHost");
929 resource_dispatcher_host_
.get()->Shutdown();
932 memory_pressure_monitor_
.reset();
934 #if defined(OS_MACOSX)
935 BrowserCompositorMac::DisableRecyclingForShutdown();
938 #if defined(USE_AURA) || defined(OS_MACOSX)
940 TRACE_EVENT0("shutdown",
941 "BrowserMainLoop::Subsystem:ImageTransportFactory");
942 ImageTransportFactory::Terminate();
946 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
947 ZygoteHostImpl::GetInstance()->TearDownAfterLastChild();
948 #endif // defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
950 // The device monitors are using |system_monitor_| as dependency, so delete
951 // them before |system_monitor_| goes away.
952 // On Mac and windows, the monitor needs to be destroyed on the same thread
953 // as they were created. On Linux, the monitor will be deleted when IO thread
956 system_message_window_
.reset();
957 #elif defined(OS_MACOSX)
958 device_monitor_mac_
.reset();
960 #endif // !defined(OS_IOS)
962 // Must be size_t so we can subtract from it.
963 for (size_t thread_id
= BrowserThread::ID_COUNT
- 1;
964 thread_id
>= (BrowserThread::UI
+ 1);
966 // Find the thread object we want to stop. Looping over all valid
967 // BrowserThread IDs and DCHECKing on a missing case in the switch
968 // statement helps avoid a mismatch between this code and the
969 // BrowserThread::ID enumeration.
971 // The destruction order is the reverse order of occurrence in the
972 // BrowserThread::ID list. The rationale for the order is as
973 // follows (need to be filled in a bit):
976 // - The IO thread is the only user of the CACHE thread.
978 // - The PROCESS_LAUNCHER thread must be stopped after IO in case
979 // the IO thread posted a task to terminate a process on the
980 // process launcher thread.
982 // - (Not sure why DB stops last.)
984 case BrowserThread::DB
: {
985 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DBThread");
986 ResetThread_DB(db_thread_
.Pass());
989 case BrowserThread::FILE: {
990 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:FileThread");
992 // Clean up state that lives on or uses the file_thread_ before
994 if (resource_dispatcher_host_
)
995 resource_dispatcher_host_
.get()->save_file_manager()->Shutdown();
996 #endif // !defined(OS_IOS)
997 ResetThread_FILE(file_thread_
.Pass());
1000 case BrowserThread::FILE_USER_BLOCKING
: {
1001 TRACE_EVENT0("shutdown",
1002 "BrowserMainLoop::Subsystem:FileUserBlockingThread");
1003 ResetThread_FILE_USER_BLOCKING(file_user_blocking_thread_
.Pass());
1006 case BrowserThread::PROCESS_LAUNCHER
: {
1007 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:LauncherThread");
1008 ResetThread_PROCESS_LAUNCHER(process_launcher_thread_
.Pass());
1011 case BrowserThread::CACHE
: {
1012 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:CacheThread");
1013 ResetThread_CACHE(cache_thread_
.Pass());
1016 case BrowserThread::IO
: {
1017 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IOThread");
1018 ResetThread_IO(io_thread_
.Pass());
1021 case BrowserThread::UI
:
1022 case BrowserThread::ID_COUNT
:
1029 #if !defined(OS_IOS)
1031 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IndexedDBThread");
1032 ResetThread_IndexedDb(indexed_db_thread_
.Pass());
1036 // Close the blocking I/O pool after the other threads. Other threads such
1037 // as the I/O thread may need to schedule work like closing files or flushing
1038 // data during shutdown, so the blocking pool needs to be available. There
1039 // may also be slow operations pending that will blcok shutdown, so closing
1040 // it here (which will block until required operations are complete) gives
1041 // more head start for those operations to finish.
1043 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:ThreadPool");
1044 BrowserThreadImpl::ShutdownThreadPool();
1047 #if !defined(OS_IOS)
1048 // Must happen after the IO thread is shutdown since this may be accessed from
1051 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUChannelFactory");
1052 if (BrowserGpuChannelHostFactory::instance())
1053 BrowserGpuChannelHostFactory::Terminate();
1056 // Must happen after the I/O thread is shutdown since this class lives on the
1057 // I/O thread and isn't threadsafe.
1059 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GamepadService");
1060 GamepadService::GetInstance()->Terminate();
1063 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:SensorService");
1064 DeviceInertialSensorService::GetInstance()->Shutdown();
1067 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:BatteryStatusService");
1068 device::BatteryStatusService::GetInstance()->Shutdown();
1071 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DeleteDataSources");
1072 URLDataManager::DeleteDataSources();
1074 #endif // !defined(OS_IOS)
1077 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:PostDestroyThreads");
1078 parts_
->PostDestroyThreads();
1082 void BrowserMainLoop::StopStartupTracingTimer() {
1083 startup_trace_timer_
.Stop();
1086 void BrowserMainLoop::InitializeMainThread() {
1087 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeMainThread");
1088 static const char kThreadName
[] = "CrBrowserMain";
1089 base::PlatformThread::SetName(kThreadName
);
1090 if (main_message_loop_
)
1091 main_message_loop_
->set_thread_name(kThreadName
);
1093 // Register the main thread by instantiating it, but don't call any methods.
1095 new BrowserThreadImpl(BrowserThread::UI
, base::MessageLoop::current()));
1098 int BrowserMainLoop::BrowserThreadsStarted() {
1099 TRACE_EVENT0("startup", "BrowserMainLoop::BrowserThreadsStarted");
1101 #if !defined(OS_IOS)
1102 indexed_db_thread_
.reset(new base::Thread("IndexedDB"));
1103 indexed_db_thread_
->Start();
1106 #if !defined(OS_IOS)
1107 HistogramSynchronizer::GetInstance();
1109 #if defined(OS_ANDROID)
1110 // Up the priority of the UI thread.
1111 base::PlatformThread::SetCurrentThreadPriority(base::ThreadPriority::DISPLAY
);
1114 bool always_uses_gpu
= true;
1115 bool established_gpu_channel
= false;
1116 #if defined(OS_ANDROID)
1117 // TODO(crbug.com/439322): This should be set to |true|.
1118 established_gpu_channel
= false;
1119 BrowserGpuChannelHostFactory::Initialize(established_gpu_channel
);
1120 #elif defined(USE_AURA) || defined(OS_MACOSX)
1121 established_gpu_channel
= true;
1122 if (!GpuDataManagerImpl::GetInstance()->CanUseGpuBrowserCompositor() ||
1123 parsed_command_line_
.HasSwitch(switches::kDisableGpuEarlyInit
)) {
1124 established_gpu_channel
= always_uses_gpu
= false;
1126 BrowserGpuChannelHostFactory::Initialize(established_gpu_channel
);
1127 ImageTransportFactory::Initialize();
1128 #if defined(USE_AURA)
1129 if (aura::Env::GetInstance()) {
1130 aura::Env::GetInstance()->set_context_factory(GetContextFactory());
1132 #endif // defined(USE_AURA)
1133 #endif // defined(OS_ANDROID)
1135 // Enable the GpuMemoryBuffer dump provider with IO thread affinity. Note that
1136 // unregistration happens on the IO thread (See
1137 // BrowserProcessSubThread::IOThreadPreCleanUp).
1138 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
1139 BrowserGpuMemoryBufferManager::current(), io_thread_
->task_runner());
1142 TRACE_EVENT0("startup", "BrowserThreadsStarted::Subsystem:AudioMan");
1143 audio_manager_
.reset(media::AudioManager::CreateWithHangTimer(
1144 MediaInternals::GetInstance(), io_thread_
->task_runner()));
1148 TRACE_EVENT0("startup", "BrowserThreadsStarted::Subsystem:MidiManager");
1149 midi_manager_
.reset(media::midi::MidiManager::Create());
1152 #if defined(OS_LINUX) && defined(USE_UDEV)
1153 device_monitor_linux_
.reset(new DeviceMonitorLinux());
1154 #elif defined(OS_MACOSX)
1155 device_monitor_mac_
.reset(new DeviceMonitorMac());
1159 UMA_HISTOGRAM_BOOLEAN("Windows.Win32kRendererLockdown",
1160 IsWin32kRendererLockdownEnabled());
1162 // RDH needs the IO thread to be created
1164 TRACE_EVENT0("startup",
1165 "BrowserMainLoop::BrowserThreadsStarted:InitResourceDispatcherHost");
1166 resource_dispatcher_host_
.reset(new ResourceDispatcherHostImpl());
1169 // MediaStreamManager needs the IO thread to be created.
1171 TRACE_EVENT0("startup",
1172 "BrowserMainLoop::BrowserThreadsStarted:InitMediaStreamManager");
1173 media_stream_manager_
.reset(new MediaStreamManager(audio_manager_
.get()));
1177 TRACE_EVENT0("startup",
1178 "BrowserMainLoop::BrowserThreadsStarted:InitSpeechRecognition");
1179 speech_recognition_manager_
.reset(new SpeechRecognitionManagerImpl(
1180 audio_manager_
.get(), media_stream_manager_
.get()));
1186 "BrowserMainLoop::BrowserThreadsStarted::InitUserInputMonitor");
1187 user_input_monitor_
= media::UserInputMonitor::Create(
1188 io_thread_
->task_runner(), main_thread_
->task_runner());
1192 TRACE_EVENT0("startup",
1193 "BrowserMainLoop::BrowserThreadsStarted::TimeZoneMonitor");
1194 time_zone_monitor_
= TimeZoneMonitor::Create();
1197 // Alert the clipboard class to which threads are allowed to access the
1199 std::vector
<base::PlatformThreadId
> allowed_clipboard_threads
;
1200 // The current thread is the UI thread.
1201 allowed_clipboard_threads
.push_back(base::PlatformThread::CurrentId());
1203 // On Windows, clipboards are also used on the FILE or IO threads.
1204 allowed_clipboard_threads
.push_back(file_thread_
->thread_id());
1205 allowed_clipboard_threads
.push_back(io_thread_
->thread_id());
1207 ui::Clipboard::SetAllowedThreads(allowed_clipboard_threads
);
1209 // When running the GPU thread in-process, avoid optimistically starting it
1210 // since creating the GPU thread races against creation of the one-and-only
1211 // ChildProcess instance which is created by the renderer thread.
1212 if (GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL
) &&
1213 !established_gpu_channel
&&
1215 !UsingInProcessGpu()) {
1216 TRACE_EVENT_INSTANT0("gpu", "Post task to launch GPU process",
1217 TRACE_EVENT_SCOPE_THREAD
);
1218 BrowserThread::PostTask(
1219 BrowserThread::IO
, FROM_HERE
,
1220 base::Bind(base::IgnoreResult(&GpuProcessHost::Get
),
1221 GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED
,
1222 CAUSE_FOR_GPU_LAUNCH_BROWSER_STARTUP
));
1225 #if defined(OS_MACOSX)
1226 ThemeHelperMac::GetInstance();
1227 SystemHotkeyHelperMac::GetInstance()->DeferredLoadSystemHotkeys();
1228 if (ShouldEnableBootstrapSandbox()) {
1229 TRACE_EVENT0("startup",
1230 "BrowserMainLoop::BrowserThreadsStarted:BootstrapSandbox");
1231 CHECK(GetBootstrapSandbox());
1233 #endif // defined(OS_MACOSX)
1235 #endif // !defined(OS_IOS)
1237 mojo_shell_context_
.reset(new MojoShellContext
);
1239 return result_code_
;
1242 bool BrowserMainLoop::UsingInProcessGpu() const {
1243 return parsed_command_line_
.HasSwitch(switches::kSingleProcess
) ||
1244 parsed_command_line_
.HasSwitch(switches::kInProcessGPU
);
1247 bool BrowserMainLoop::InitializeToolkit() {
1248 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeToolkit");
1249 TRACK_SCOPED_REGION("Startup", "BrowserMainLoop::InitializeToolkit");
1251 // TODO(evan): this function is rather subtle, due to the variety
1252 // of intersecting ifdefs we have. To keep it easy to follow, there
1253 // are no #else branches on any #ifs.
1254 // TODO(stevenjb): Move platform specific code into platform specific Parts
1255 // (Need to add InitializeToolkit stage to BrowserParts).
1256 // See also GTK setup in EarlyInitialization, above, and associated comments.
1259 // Init common control sex.
1260 INITCOMMONCONTROLSEX config
;
1261 config
.dwSize
= sizeof(config
);
1262 config
.dwICC
= ICC_WIN95_CLASSES
;
1263 if (!InitCommonControlsEx(&config
))
1267 #if defined(USE_AURA)
1269 #if defined(USE_X11)
1270 if (!gfx::GetXDisplay())
1274 // Env creates the compositor. Aura widgets need the compositor to be created
1275 // before they can be initialized by the browser.
1276 aura::Env::CreateInstance(true);
1277 #endif // defined(USE_AURA)
1280 parts_
->ToolkitInitialized();
1285 void BrowserMainLoop::MainMessageLoopRun() {
1286 #if defined(OS_ANDROID)
1287 // Android's main message loop is the Java message loop.
1290 DCHECK(base::MessageLoopForUI::IsCurrent());
1291 if (parameters_
.ui_task
) {
1292 base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE
,
1293 *parameters_
.ui_task
);
1296 base::RunLoop run_loop
;
1301 base::FilePath
BrowserMainLoop::GetStartupTraceFileName(
1302 const base::CommandLine
& command_line
) const {
1303 base::FilePath trace_file
= command_line
.GetSwitchValuePath(
1304 switches::kTraceStartupFile
);
1305 // trace_file = "none" means that startup events will show up for the next
1306 // begin/end tracing (via about:tracing or AutomationProxy::BeginTracing/
1307 // EndTracing, for example).
1308 if (trace_file
== base::FilePath().AppendASCII("none"))
1311 if (trace_file
.empty()) {
1312 #if defined(OS_ANDROID)
1313 TracingControllerAndroid::GenerateTracingFilePath(&trace_file
);
1315 // Default to saving the startup trace into the current dir.
1316 trace_file
= base::FilePath().AppendASCII("chrometrace.log");
1323 void BrowserMainLoop::InitStartupTracing(
1324 const base::CommandLine
& command_line
) {
1325 DCHECK(is_tracing_startup_
);
1327 startup_trace_file_
= GetStartupTraceFileName(parsed_command_line_
);
1329 std::string delay_str
= command_line
.GetSwitchValueASCII(
1330 switches::kTraceStartupDuration
);
1332 if (!delay_str
.empty() && !base::StringToInt(delay_str
, &delay_secs
)) {
1333 DLOG(WARNING
) << "Could not parse --" << switches::kTraceStartupDuration
1334 << "=" << delay_str
<< " defaulting to 5 (secs)";
1338 startup_trace_timer_
.Start(FROM_HERE
,
1339 base::TimeDelta::FromSeconds(delay_secs
),
1341 &BrowserMainLoop::EndStartupTracing
);
1344 void BrowserMainLoop::EndStartupTracing() {
1345 DCHECK(is_tracing_startup_
);
1347 is_tracing_startup_
= false;
1348 TracingController::GetInstance()->DisableRecording(
1349 TracingController::CreateFileSink(
1350 startup_trace_file_
,
1351 base::Bind(OnStoppedStartupTracing
, startup_trace_file_
)));
1354 } // namespace content