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/debug/trace_event.h"
10 #include "base/file_util.h"
11 #include "base/logging.h"
12 #include "base/message_loop/message_loop.h"
13 #include "base/metrics/field_trial.h"
14 #include "base/metrics/histogram.h"
15 #include "base/path_service.h"
16 #include "base/pending_task.h"
17 #include "base/power_monitor/power_monitor.h"
18 #include "base/power_monitor/power_monitor_device_source.h"
19 #include "base/process/process_metrics.h"
20 #include "base/run_loop.h"
21 #include "base/strings/string_number_conversions.h"
22 #include "base/system_monitor/system_monitor.h"
23 #include "base/thread_task_runner_handle.h"
24 #include "base/threading/thread_restrictions.h"
25 #include "base/timer/hi_res_timer_manager.h"
26 #include "content/browser/battery_status/battery_status_service.h"
27 #include "content/browser/browser_thread_impl.h"
28 #include "content/browser/device_sensors/device_inertial_sensor_service.h"
29 #include "content/browser/download/save_file_manager.h"
30 #include "content/browser/gamepad/gamepad_service.h"
31 #include "content/browser/gpu/browser_gpu_channel_host_factory.h"
32 #include "content/browser/gpu/compositor_util.h"
33 #include "content/browser/gpu/gpu_data_manager_impl.h"
34 #include "content/browser/gpu/gpu_process_host.h"
35 #include "content/browser/gpu/gpu_process_host_ui_shim.h"
36 #include "content/browser/histogram_synchronizer.h"
37 #include "content/browser/loader/resource_dispatcher_host_impl.h"
38 #include "content/browser/media/capture/audio_mirroring_manager.h"
39 #include "content/browser/media/media_internals.h"
40 #include "content/browser/net/browser_online_state_observer.h"
41 #include "content/browser/plugin_service_impl.h"
42 #include "content/browser/renderer_host/media/media_stream_manager.h"
43 #include "content/browser/speech/speech_recognition_manager_impl.h"
44 #include "content/browser/startup_task_runner.h"
45 #include "content/browser/time_zone_monitor.h"
46 #include "content/browser/webui/content_web_ui_controller_factory.h"
47 #include "content/browser/webui/url_data_manager.h"
48 #include "content/public/browser/browser_main_parts.h"
49 #include "content/public/browser/browser_shutdown.h"
50 #include "content/public/browser/content_browser_client.h"
51 #include "content/public/browser/render_process_host.h"
52 #include "content/public/browser/tracing_controller.h"
53 #include "content/public/common/content_switches.h"
54 #include "content/public/common/main_function_params.h"
55 #include "content/public/common/result_codes.h"
56 #include "crypto/nss_util.h"
57 #include "media/audio/audio_manager.h"
58 #include "media/base/media.h"
59 #include "media/base/user_input_monitor.h"
60 #include "media/midi/midi_manager.h"
61 #include "net/base/network_change_notifier.h"
62 #include "net/socket/client_socket_factory.h"
63 #include "net/ssl/ssl_config_service.h"
64 #include "ui/base/clipboard/clipboard.h"
66 #if defined(USE_AURA) || (defined(OS_MACOSX) && !defined(OS_IOS))
67 #include "content/browser/compositor/image_transport_factory.h"
71 #include "content/public/browser/context_factory.h"
72 #include "ui/aura/env.h"
76 #include "content/browser/renderer_host/render_process_host_impl.h"
79 #if defined(OS_ANDROID)
80 #include "base/android/jni_android.h"
81 #include "content/browser/android/browser_startup_controller.h"
82 #include "content/browser/android/surface_texture_peer_browser_impl.h"
83 #include "content/browser/android/tracing_controller_android.h"
84 #include "ui/gl/gl_surface.h"
87 #if defined(OS_MACOSX) && !defined(OS_IOS)
88 #include "content/browser/bootstrap_sandbox_mac.h"
89 #include "content/browser/theme_helper_mac.h"
97 #include "content/browser/system_message_window_win.h"
98 #include "content/common/sandbox_win.h"
99 #include "net/base/winsock_init.h"
100 #include "ui/base/l10n/l10n_util_win.h"
103 #if defined(USE_GLIB)
104 #include <glib-object.h>
107 #if defined(OS_LINUX) && defined(USE_UDEV)
108 #include "content/browser/device_monitor_udev.h"
109 #elif defined(OS_MACOSX) && !defined(OS_IOS)
110 #include "content/browser/device_monitor_mac.h"
113 #if defined(OS_POSIX) && !defined(OS_MACOSX)
114 #include "content/browser/renderer_host/render_sandbox_host_linux.h"
115 #include "content/browser/zygote_host/zygote_host_impl_linux.h"
116 #include "sandbox/linux/suid/client/setuid_sandbox_client.h"
119 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
120 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
124 #include "ui/gfx/x/x11_connection.h"
125 #include "ui/gfx/x/x11_types.h"
128 // One of the linux specific headers defines this as a macro.
136 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
137 void SetupSandbox(const CommandLine
& parsed_command_line
) {
138 TRACE_EVENT0("startup", "SetupSandbox");
139 base::FilePath sandbox_binary
;
141 scoped_ptr
<sandbox::SetuidSandboxClient
> setuid_sandbox_client(
142 sandbox::SetuidSandboxClient::Create());
144 const bool want_setuid_sandbox
=
145 !parsed_command_line
.HasSwitch(switches::kNoSandbox
) &&
146 !parsed_command_line
.HasSwitch(switches::kDisableSetuidSandbox
) &&
147 !setuid_sandbox_client
->IsDisabledViaEnvironment();
149 static const char no_suid_error
[] =
150 "Running without the SUID sandbox! See "
151 "https://code.google.com/p/chromium/wiki/LinuxSUIDSandboxDevelopment "
152 "for more information on developing with the sandbox on.";
153 if (want_setuid_sandbox
) {
154 sandbox_binary
= setuid_sandbox_client
->GetSandboxBinaryPath();
155 if (sandbox_binary
.empty()) {
156 // This needs to be fatal. Talk to security@chromium.org if you feel
158 LOG(FATAL
) << no_suid_error
;
161 LOG(ERROR
) << no_suid_error
;
164 // Tickle the sandbox host and zygote host so they fork now.
165 RenderSandboxHostLinux::GetInstance()->Init();
166 ZygoteHostImpl::GetInstance()->Init(sandbox_binary
.value());
170 #if defined(USE_GLIB)
171 static void GLibLogHandler(const gchar
* log_domain
,
172 GLogLevelFlags log_level
,
173 const gchar
* message
,
176 log_domain
= "<unknown>";
178 message
= "<no message>";
180 if (strstr(message
, "Unable to retrieve the file info for")) {
181 LOG(ERROR
) << "GTK File code error: " << message
;
182 } else if (strstr(message
, "Could not find the icon") &&
183 strstr(log_domain
, "Gtk")) {
184 LOG(ERROR
) << "GTK icon error: " << message
;
185 } else if (strstr(message
, "Theme file for default has no") ||
186 strstr(message
, "Theme directory") ||
187 strstr(message
, "theme pixmap") ||
188 strstr(message
, "locate theme engine")) {
189 LOG(ERROR
) << "GTK theme error: " << message
;
190 } else if (strstr(message
, "Unable to create Ubuntu Menu Proxy") &&
191 strstr(log_domain
, "<unknown>")) {
192 LOG(ERROR
) << "GTK menu proxy create failed";
193 } else if (strstr(message
, "Out of memory") &&
194 strstr(log_domain
, "<unknown>")) {
195 LOG(ERROR
) << "DBus call timeout or out of memory: "
196 << "http://crosbug.com/15496";
197 } else if (strstr(message
, "Could not connect: Connection refused") &&
198 strstr(log_domain
, "<unknown>")) {
199 LOG(ERROR
) << "DConf settings backend could not connect to session bus: "
200 << "http://crbug.com/179797";
201 } else if (strstr(message
, "Attempting to store changes into") ||
202 strstr(message
, "Attempting to set the permissions of")) {
203 LOG(ERROR
) << message
<< " (http://bugs.chromium.org/161366)";
204 } else if (strstr(message
, "drawable is not a native X11 window")) {
205 LOG(ERROR
) << message
<< " (http://bugs.chromium.org/329991)";
207 LOG(DFATAL
) << log_domain
<< ": " << message
;
211 static void SetUpGLibLogHandler() {
212 // Register GLib-handled assertions to go through our logging system.
213 const char* kLogDomains
[] = { NULL
, "Gtk", "Gdk", "GLib", "GLib-GObject" };
214 for (size_t i
= 0; i
< arraysize(kLogDomains
); i
++) {
215 g_log_set_handler(kLogDomains
[i
],
216 static_cast<GLogLevelFlags
>(G_LOG_FLAG_RECURSION
|
219 G_LOG_LEVEL_CRITICAL
|
220 G_LOG_LEVEL_WARNING
),
227 void OnStoppedStartupTracing(const base::FilePath
& trace_file
) {
228 VLOG(0) << "Completed startup tracing to " << trace_file
.value();
231 #if defined(USE_AURA)
232 bool ShouldInitializeBrowserGpuChannelAndTransportSurface() {
235 #elif defined(OS_MACOSX) && !defined(OS_IOS)
236 bool ShouldInitializeBrowserGpuChannelAndTransportSurface() {
237 return IsDelegatedRendererEnabled();
243 // The currently-running BrowserMainLoop. There can be one or zero.
244 BrowserMainLoop
* g_current_browser_main_loop
= NULL
;
246 // This is just to be able to keep ShutdownThreadsAndCleanUp out of
247 // the public interface of BrowserMainLoop.
248 class BrowserShutdownImpl
{
250 static void ImmediateShutdownAndExitProcess() {
251 DCHECK(g_current_browser_main_loop
);
252 g_current_browser_main_loop
->ShutdownThreadsAndCleanUp();
255 // At this point the message loop is still running yet we've shut everything
256 // down. If any messages are processed we'll likely crash. Exit now.
257 ExitProcess(RESULT_CODE_NORMAL_EXIT
);
258 #elif defined(OS_POSIX) && !defined(OS_MACOSX)
259 _exit(RESULT_CODE_NORMAL_EXIT
);
266 void ImmediateShutdownAndExitProcess() {
267 BrowserShutdownImpl::ImmediateShutdownAndExitProcess();
270 // For measuring memory usage after each task. Behind a command line flag.
271 class BrowserMainLoop::MemoryObserver
: public base::MessageLoop::TaskObserver
{
274 virtual ~MemoryObserver() {}
276 virtual void WillProcessTask(const base::PendingTask
& pending_task
) OVERRIDE
{
279 virtual void DidProcessTask(const base::PendingTask
& pending_task
) OVERRIDE
{
280 #if !defined(OS_IOS) // No ProcessMetrics on IOS.
281 scoped_ptr
<base::ProcessMetrics
> process_metrics(
282 base::ProcessMetrics::CreateProcessMetrics(
283 #if defined(OS_MACOSX)
284 base::GetCurrentProcessHandle(), NULL
));
286 base::GetCurrentProcessHandle()));
288 size_t private_bytes
;
289 process_metrics
->GetMemoryBytes(&private_bytes
, NULL
);
290 HISTOGRAM_MEMORY_KB("Memory.BrowserUsed", private_bytes
>> 10);
294 DISALLOW_COPY_AND_ASSIGN(MemoryObserver
);
298 // BrowserMainLoop construction / destruction =============================
300 BrowserMainLoop
* BrowserMainLoop::GetInstance() {
301 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
302 return g_current_browser_main_loop
;
305 BrowserMainLoop::BrowserMainLoop(const MainFunctionParams
& parameters
)
306 : parameters_(parameters
),
307 parsed_command_line_(parameters
.command_line
),
308 result_code_(RESULT_CODE_NORMAL_EXIT
),
309 created_threads_(false),
310 // ContentMainRunner should have enabled tracing of the browser process
311 // when kTraceStartup is in the command line.
313 parameters
.command_line
.HasSwitch(switches::kTraceStartup
)) {
314 DCHECK(!g_current_browser_main_loop
);
315 g_current_browser_main_loop
= this;
318 BrowserMainLoop::~BrowserMainLoop() {
319 DCHECK_EQ(this, g_current_browser_main_loop
);
321 ui::Clipboard::DestroyClipboardForCurrentThread();
322 #endif // !defined(OS_IOS)
323 g_current_browser_main_loop
= NULL
;
326 void BrowserMainLoop::Init() {
327 TRACE_EVENT0("startup", "BrowserMainLoop::Init");
329 GetContentClient()->browser()->CreateBrowserMainParts(parameters_
));
332 // BrowserMainLoop stages ==================================================
334 void BrowserMainLoop::EarlyInitialization() {
335 TRACE_EVENT0("startup", "BrowserMainLoop::EarlyInitialization");
337 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
338 // No thread should be created before this call, as SetupSandbox()
339 // will end-up using fork().
340 SetupSandbox(parsed_command_line_
);
344 if (parsed_command_line_
.HasSwitch(switches::kSingleProcess
) ||
345 parsed_command_line_
.HasSwitch(switches::kInProcessGPU
)) {
346 if (!gfx::InitializeThreadedX11()) {
347 LOG(ERROR
) << "Failed to put Xlib into threaded mode.";
352 // GLib's spawning of new processes is buggy, so it's important that at this
353 // point GLib does not need to start DBUS. Chrome should always start with
354 // DBUS_SESSION_BUS_ADDRESS properly set. See crbug.com/309093.
355 #if defined(USE_GLIB)
356 // g_type_init will be deprecated in 2.36. 2.35 is the development
357 // version for 2.36, hence do not call g_type_init starting 2.35.
358 // http://developer.gnome.org/gobject/unstable/gobject-Type-Information.html#g-type-init
359 #if !GLIB_CHECK_VERSION(2, 35, 0)
360 // GLib type system initialization. Needed at least for gconf,
361 // used in net/proxy/proxy_config_service_linux.cc. Most likely
362 // this is superfluous as gtk_init() ought to do this. It's
363 // definitely harmless, so retained as a reminder of this
364 // requirement for gconf.
368 SetUpGLibLogHandler();
372 parts_
->PreEarlyInitialization();
374 #if defined(OS_MACOSX)
375 // We use quite a few file descriptors for our IPC, and the default limit on
376 // the Mac is low (256), so bump it up.
377 base::SetFdLimit(1024);
381 net::EnsureWinsockInit();
384 #if !defined(USE_OPENSSL)
385 // We want to be sure to init NSPR on the main thread.
386 crypto::EnsureNSPRInit();
387 #endif // !defined(USE_OPENSSL)
390 if (parsed_command_line_
.HasSwitch(switches::kRendererProcessLimit
)) {
391 std::string limit_string
= parsed_command_line_
.GetSwitchValueASCII(
392 switches::kRendererProcessLimit
);
393 size_t process_limit
;
394 if (base::StringToSizeT(limit_string
, &process_limit
)) {
395 RenderProcessHost::SetMaxRendererProcessCount(process_limit
);
398 #endif // !defined(OS_IOS)
401 parts_
->PostEarlyInitialization();
404 void BrowserMainLoop::MainMessageLoopStart() {
405 TRACE_EVENT0("startup", "BrowserMainLoop::MainMessageLoopStart");
407 TRACE_EVENT0("startup",
408 "BrowserMainLoop::MainMessageLoopStart:PreMainMessageLoopStart");
409 parts_
->PreMainMessageLoopStart();
413 // If we're running tests (ui_task is non-null), then the ResourceBundle
414 // has already been initialized.
415 if (!parameters_
.ui_task
) {
416 // Override the configured locale with the user's preferred UI language.
417 l10n_util::OverrideLocaleWithUILanguageList();
421 // Create a MessageLoop if one does not already exist for the current thread.
422 if (!base::MessageLoop::current())
423 main_message_loop_
.reset(new base::MessageLoopForUI
);
425 InitializeMainThread();
428 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SystemMonitor");
429 system_monitor_
.reset(new base::SystemMonitor
);
432 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:PowerMonitor");
433 scoped_ptr
<base::PowerMonitorSource
> power_monitor_source(
434 new base::PowerMonitorDeviceSource());
435 power_monitor_
.reset(new base::PowerMonitor(power_monitor_source
.Pass()));
438 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:HighResTimerManager");
439 hi_res_timer_manager_
.reset(new base::HighResolutionTimerManager
);
442 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:NetworkChangeNotifier");
443 network_change_notifier_
.reset(net::NetworkChangeNotifier::Create());
448 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MediaFeatures");
449 media::InitializeCPUSpecificMediaFeatures();
452 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:AudioMan");
453 audio_manager_
.reset(media::AudioManager::Create(
454 MediaInternals::GetInstance()));
457 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MidiManager");
458 midi_manager_
.reset(media::MidiManager::Create());
461 TRACE_EVENT0("startup",
462 "BrowserMainLoop::Subsystem:ContentWebUIController");
463 WebUIControllerFactory::RegisterFactory(
464 ContentWebUIControllerFactory::GetInstance());
468 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:AudioMirroringManager");
469 audio_mirroring_manager_
.reset(new AudioMirroringManager());
472 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:OnlineStateObserver");
473 online_state_observer_
.reset(new BrowserOnlineStateObserver
);
477 system_stats_monitor_
.reset(new base::debug::TraceEventSystemStatsMonitor(
478 base::ThreadTaskRunnerHandle::Get()));
480 #endif // !defined(OS_IOS)
483 system_message_window_
.reset(new SystemMessageWindowWin
);
487 parts_
->PostMainMessageLoopStart();
490 // Start tracing to a file if needed. Only do this after starting the main
491 // message loop to avoid calling MessagePumpForUI::ScheduleWork() before
492 // MessagePumpForUI::Start() as it will crash the browser.
493 if (is_tracing_startup_
) {
494 TRACE_EVENT0("startup", "BrowserMainLoop::InitStartupTracing");
495 InitStartupTracing(parsed_command_line_
);
497 #endif // !defined(OS_IOS)
499 #if defined(OS_ANDROID)
501 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SurfaceTexturePeer");
502 SurfaceTexturePeer::InitInstance(new SurfaceTexturePeerBrowserImpl());
506 if (parsed_command_line_
.HasSwitch(switches::kMemoryMetrics
)) {
507 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MemoryObserver");
508 memory_observer_
.reset(new MemoryObserver());
509 base::MessageLoop::current()->AddTaskObserver(memory_observer_
.get());
512 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
513 trace_memory_controller_
.reset(new base::debug::TraceMemoryController(
514 base::MessageLoop::current()->message_loop_proxy(),
515 ::HeapProfilerWithPseudoStackStart
,
521 int BrowserMainLoop::PreCreateThreads() {
523 TRACE_EVENT0("startup",
524 "BrowserMainLoop::CreateThreads:PreCreateThreads");
525 result_code_
= parts_
->PreCreateThreads();
528 #if defined(ENABLE_PLUGINS)
529 // Prior to any processing happening on the io thread, we create the
530 // plugin service as it is predominantly used from the io thread,
531 // but must be created on the main thread. The service ctor is
532 // inexpensive and does not invoke the io_thread() accessor.
534 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads:PluginService");
535 PluginService::GetInstance()->Init();
539 #if !defined(OS_IOS) && (!defined(GOOGLE_CHROME_BUILD) || defined(OS_ANDROID))
540 // Single-process is an unsupported and not fully tested mode, so
541 // don't enable it for official Chrome builds (except on Android).
542 if (parsed_command_line_
.HasSwitch(switches::kSingleProcess
))
543 RenderProcessHost::SetRunRendererInProcess(true);
548 void BrowserMainLoop::CreateStartupTasks() {
549 TRACE_EVENT0("startup", "BrowserMainLoop::CreateStartupTasks");
551 // First time through, we really want to create all the tasks
552 if (!startup_task_runner_
.get()) {
553 #if defined(OS_ANDROID)
554 startup_task_runner_
= make_scoped_ptr(new StartupTaskRunner(
555 base::Bind(&BrowserStartupComplete
),
556 base::MessageLoop::current()->message_loop_proxy()));
558 startup_task_runner_
= make_scoped_ptr(new StartupTaskRunner(
559 base::Callback
<void(int)>(),
560 base::MessageLoop::current()->message_loop_proxy()));
562 StartupTask pre_create_threads
=
563 base::Bind(&BrowserMainLoop::PreCreateThreads
, base::Unretained(this));
564 startup_task_runner_
->AddTask(pre_create_threads
);
566 StartupTask create_threads
=
567 base::Bind(&BrowserMainLoop::CreateThreads
, base::Unretained(this));
568 startup_task_runner_
->AddTask(create_threads
);
570 StartupTask browser_thread_started
= base::Bind(
571 &BrowserMainLoop::BrowserThreadsStarted
, base::Unretained(this));
572 startup_task_runner_
->AddTask(browser_thread_started
);
574 StartupTask pre_main_message_loop_run
= base::Bind(
575 &BrowserMainLoop::PreMainMessageLoopRun
, base::Unretained(this));
576 startup_task_runner_
->AddTask(pre_main_message_loop_run
);
578 #if defined(OS_ANDROID)
579 if (BrowserMayStartAsynchronously()) {
580 startup_task_runner_
->StartRunningTasksAsync();
584 #if defined(OS_ANDROID)
585 if (!BrowserMayStartAsynchronously()) {
586 // A second request for asynchronous startup can be ignored, so
587 // StartupRunningTasksAsync is only called first time through. If, however,
588 // this is a request for synchronous startup then it must override any
589 // previous call for async startup, so we call RunAllTasksNow()
591 startup_task_runner_
->RunAllTasksNow();
594 startup_task_runner_
->RunAllTasksNow();
598 int BrowserMainLoop::CreateThreads() {
599 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads");
601 base::Thread::Options io_message_loop_options
;
602 io_message_loop_options
.message_loop_type
= base::MessageLoop::TYPE_IO
;
603 base::Thread::Options ui_message_loop_options
;
604 ui_message_loop_options
.message_loop_type
= base::MessageLoop::TYPE_UI
;
606 // Start threads in the order they occur in the BrowserThread::ID
607 // enumeration, except for BrowserThread::UI which is the main
610 // Must be size_t so we can increment it.
611 for (size_t thread_id
= BrowserThread::UI
+ 1;
612 thread_id
< BrowserThread::ID_COUNT
;
614 scoped_ptr
<BrowserProcessSubThread
>* thread_to_start
= NULL
;
615 base::Thread::Options options
;
618 case BrowserThread::DB
:
619 TRACE_EVENT_BEGIN1("startup",
620 "BrowserMainLoop::CreateThreads:start",
621 "Thread", "BrowserThread::DB");
622 thread_to_start
= &db_thread_
;
623 options
.timer_slack
= base::TIMER_SLACK_MAXIMUM
;
625 case BrowserThread::FILE_USER_BLOCKING
:
626 TRACE_EVENT_BEGIN1("startup",
627 "BrowserMainLoop::CreateThreads:start",
628 "Thread", "BrowserThread::FILE_USER_BLOCKING");
629 thread_to_start
= &file_user_blocking_thread_
;
631 case BrowserThread::FILE:
632 TRACE_EVENT_BEGIN1("startup",
633 "BrowserMainLoop::CreateThreads:start",
634 "Thread", "BrowserThread::FILE");
635 thread_to_start
= &file_thread_
;
637 // On Windows, the FILE thread needs to be have a UI message loop
638 // which pumps messages in such a way that Google Update can
639 // communicate back to us.
640 options
= ui_message_loop_options
;
642 options
= io_message_loop_options
;
644 options
.timer_slack
= base::TIMER_SLACK_MAXIMUM
;
646 case BrowserThread::PROCESS_LAUNCHER
:
647 TRACE_EVENT_BEGIN1("startup",
648 "BrowserMainLoop::CreateThreads:start",
649 "Thread", "BrowserThread::PROCESS_LAUNCHER");
650 thread_to_start
= &process_launcher_thread_
;
651 options
.timer_slack
= base::TIMER_SLACK_MAXIMUM
;
653 case BrowserThread::CACHE
:
654 TRACE_EVENT_BEGIN1("startup",
655 "BrowserMainLoop::CreateThreads:start",
656 "Thread", "BrowserThread::CACHE");
657 thread_to_start
= &cache_thread_
;
658 options
= io_message_loop_options
;
659 options
.timer_slack
= base::TIMER_SLACK_MAXIMUM
;
661 case BrowserThread::IO
:
662 TRACE_EVENT_BEGIN1("startup",
663 "BrowserMainLoop::CreateThreads:start",
664 "Thread", "BrowserThread::IO");
665 thread_to_start
= &io_thread_
;
666 options
= io_message_loop_options
;
668 case BrowserThread::UI
:
669 case BrowserThread::ID_COUNT
:
675 BrowserThread::ID id
= static_cast<BrowserThread::ID
>(thread_id
);
677 if (thread_to_start
) {
678 (*thread_to_start
).reset(new BrowserProcessSubThread(id
));
679 (*thread_to_start
)->StartWithOptions(options
);
684 TRACE_EVENT_END0("startup", "BrowserMainLoop::CreateThreads:start");
686 created_threads_
= true;
690 int BrowserMainLoop::PreMainMessageLoopRun() {
692 TRACE_EVENT0("startup",
693 "BrowserMainLoop::CreateThreads:PreMainMessageLoopRun");
694 parts_
->PreMainMessageLoopRun();
697 // If the UI thread blocks, the whole UI is unresponsive.
698 // Do not allow disk IO from the UI thread.
699 base::ThreadRestrictions::SetIOAllowed(false);
700 base::ThreadRestrictions::DisallowWaiting();
704 void BrowserMainLoop::RunMainMessageLoopParts() {
705 TRACE_EVENT_BEGIN_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
707 bool ran_main_loop
= false;
709 ran_main_loop
= parts_
->MainMessageLoopRun(&result_code_
);
712 MainMessageLoopRun();
714 TRACE_EVENT_END_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
717 void BrowserMainLoop::ShutdownThreadsAndCleanUp() {
718 if (!created_threads_
) {
719 // Called early, nothing to do
722 TRACE_EVENT0("shutdown", "BrowserMainLoop::ShutdownThreadsAndCleanUp");
724 // Teardown may start in PostMainMessageLoopRun, and during teardown we
725 // need to be able to perform IO.
726 base::ThreadRestrictions::SetIOAllowed(true);
727 BrowserThread::PostTask(
728 BrowserThread::IO
, FROM_HERE
,
729 base::Bind(base::IgnoreResult(&base::ThreadRestrictions::SetIOAllowed
),
733 if (RenderProcessHost::run_renderer_in_process())
734 RenderProcessHostImpl::ShutDownInProcessRenderer();
738 TRACE_EVENT0("shutdown",
739 "BrowserMainLoop::Subsystem:PostMainMessageLoopRun");
740 parts_
->PostMainMessageLoopRun();
743 trace_memory_controller_
.reset();
744 system_stats_monitor_
.reset();
747 // Destroying the GpuProcessHostUIShims on the UI thread posts a task to
748 // delete related objects on the GPU thread. This must be done before
749 // stopping the GPU thread. The GPU thread will close IPC channels to renderer
750 // processes so this has to happen before stopping the IO thread.
752 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUProcessHostShim");
753 GpuProcessHostUIShim::DestroyAll();
755 // Cancel pending requests and prevent new requests.
756 if (resource_dispatcher_host_
) {
757 TRACE_EVENT0("shutdown",
758 "BrowserMainLoop::Subsystem:ResourceDispatcherHost");
759 resource_dispatcher_host_
.get()->Shutdown();
762 #if defined(USE_AURA) || defined(OS_MACOSX)
763 if (ShouldInitializeBrowserGpuChannelAndTransportSurface()) {
764 TRACE_EVENT0("shutdown",
765 "BrowserMainLoop::Subsystem:ImageTransportFactory");
766 ImageTransportFactory::Terminate();
770 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
771 ZygoteHostImpl::GetInstance()->TearDownAfterLastChild();
772 #endif // defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
774 // The device monitors are using |system_monitor_| as dependency, so delete
775 // them before |system_monitor_| goes away.
776 // On Mac and windows, the monitor needs to be destroyed on the same thread
777 // as they were created. On Linux, the monitor will be deleted when IO thread
780 system_message_window_
.reset();
781 #elif defined(OS_MACOSX)
782 device_monitor_mac_
.reset();
784 #endif // !defined(OS_IOS)
786 // Must be size_t so we can subtract from it.
787 for (size_t thread_id
= BrowserThread::ID_COUNT
- 1;
788 thread_id
>= (BrowserThread::UI
+ 1);
790 // Find the thread object we want to stop. Looping over all valid
791 // BrowserThread IDs and DCHECKing on a missing case in the switch
792 // statement helps avoid a mismatch between this code and the
793 // BrowserThread::ID enumeration.
795 // The destruction order is the reverse order of occurrence in the
796 // BrowserThread::ID list. The rationale for the order is as
797 // follows (need to be filled in a bit):
800 // - The IO thread is the only user of the CACHE thread.
802 // - The PROCESS_LAUNCHER thread must be stopped after IO in case
803 // the IO thread posted a task to terminate a process on the
804 // process launcher thread.
806 // - (Not sure why DB stops last.)
808 case BrowserThread::DB
: {
809 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DBThread");
813 case BrowserThread::FILE_USER_BLOCKING
: {
814 TRACE_EVENT0("shutdown",
815 "BrowserMainLoop::Subsystem:FileUserBlockingThread");
816 file_user_blocking_thread_
.reset();
819 case BrowserThread::FILE: {
820 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:FileThread");
822 // Clean up state that lives on or uses the file_thread_ before
824 if (resource_dispatcher_host_
)
825 resource_dispatcher_host_
.get()->save_file_manager()->Shutdown();
826 #endif // !defined(OS_IOS)
827 file_thread_
.reset();
830 case BrowserThread::PROCESS_LAUNCHER
: {
831 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:LauncherThread");
832 process_launcher_thread_
.reset();
835 case BrowserThread::CACHE
: {
836 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:CacheThread");
837 cache_thread_
.reset();
840 case BrowserThread::IO
: {
841 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IOThread");
845 case BrowserThread::UI
:
846 case BrowserThread::ID_COUNT
:
855 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IndexedDBThread");
856 indexed_db_thread_
.reset();
860 // Close the blocking I/O pool after the other threads. Other threads such
861 // as the I/O thread may need to schedule work like closing files or flushing
862 // data during shutdown, so the blocking pool needs to be available. There
863 // may also be slow operations pending that will blcok shutdown, so closing
864 // it here (which will block until required operations are complete) gives
865 // more head start for those operations to finish.
867 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:ThreadPool");
868 BrowserThreadImpl::ShutdownThreadPool();
872 // Must happen after the IO thread is shutdown since this may be accessed from
875 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUChannelFactory");
876 if (BrowserGpuChannelHostFactory::instance())
877 BrowserGpuChannelHostFactory::Terminate();
880 // Must happen after the I/O thread is shutdown since this class lives on the
881 // I/O thread and isn't threadsafe.
883 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GamepadService");
884 GamepadService::GetInstance()->Terminate();
887 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:SensorService");
888 DeviceInertialSensorService::GetInstance()->Shutdown();
891 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:BatteryStatusService");
892 BatteryStatusService::GetInstance()->Shutdown();
895 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DeleteDataSources");
896 URLDataManager::DeleteDataSources();
898 #endif // !defined(OS_IOS)
901 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:PostDestroyThreads");
902 parts_
->PostDestroyThreads();
906 void BrowserMainLoop::StopStartupTracingTimer() {
907 startup_trace_timer_
.Stop();
910 void BrowserMainLoop::InitializeMainThread() {
911 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeMainThread");
912 const char* kThreadName
= "CrBrowserMain";
913 base::PlatformThread::SetName(kThreadName
);
914 if (main_message_loop_
)
915 main_message_loop_
->set_thread_name(kThreadName
);
917 // Register the main thread by instantiating it, but don't call any methods.
919 new BrowserThreadImpl(BrowserThread::UI
, base::MessageLoop::current()));
922 int BrowserMainLoop::BrowserThreadsStarted() {
923 TRACE_EVENT0("startup", "BrowserMainLoop::BrowserThreadsStarted");
926 indexed_db_thread_
.reset(new base::Thread("IndexedDB"));
927 indexed_db_thread_
->Start();
930 #if defined(OS_ANDROID)
931 // Up the priority of anything that touches with display tasks
932 // (this thread is UI thread, and io_thread_ is for IPCs).
933 io_thread_
->SetPriority(base::kThreadPriority_Display
);
934 base::PlatformThread::SetThreadPriority(
935 base::PlatformThread::CurrentHandle(),
936 base::kThreadPriority_Display
);
940 HistogramSynchronizer::GetInstance();
942 bool initialize_gpu_data_manager
= true;
943 #if defined(OS_ANDROID)
944 // On Android, GLSurface::InitializeOneOff() must be called before initalizing
945 // the GpuDataManagerImpl as it uses the GL bindings. crbug.com/326295
946 if (!gfx::GLSurface::InitializeOneOff()) {
947 LOG(ERROR
) << "GLSurface::InitializeOneOff failed";
948 initialize_gpu_data_manager
= false;
952 // Initialize the GpuDataManager before we set up the MessageLoops because
953 // otherwise we'll trigger the assertion about doing IO on the UI thread.
954 if (initialize_gpu_data_manager
)
955 GpuDataManagerImpl::GetInstance()->Initialize();
957 bool always_uses_gpu
= true;
958 bool established_gpu_channel
= false;
959 #if defined(USE_AURA) || defined(OS_MACOSX)
960 if (ShouldInitializeBrowserGpuChannelAndTransportSurface()) {
961 established_gpu_channel
= true;
962 if (!GpuDataManagerImpl::GetInstance()->CanUseGpuBrowserCompositor()) {
963 established_gpu_channel
= always_uses_gpu
= false;
965 BrowserGpuChannelHostFactory::Initialize(established_gpu_channel
);
966 ImageTransportFactory::Initialize();
967 #if defined(USE_AURA)
968 if (aura::Env::GetInstance()) {
969 aura::Env::GetInstance()->set_context_factory(
970 content::GetContextFactory());
974 #elif defined(OS_ANDROID)
975 established_gpu_channel
= true;
976 BrowserGpuChannelHostFactory::Initialize(established_gpu_channel
);
979 #if defined(OS_LINUX) && defined(USE_UDEV)
980 device_monitor_linux_
.reset(new DeviceMonitorLinux());
981 #elif defined(OS_MACOSX)
982 device_monitor_mac_
.reset(new DeviceMonitorMac());
985 // RDH needs the IO thread to be created
987 TRACE_EVENT0("startup",
988 "BrowserMainLoop::BrowserThreadsStarted:InitResourceDispatcherHost");
989 resource_dispatcher_host_
.reset(new ResourceDispatcherHostImpl());
992 // MediaStreamManager needs the IO thread to be created.
994 TRACE_EVENT0("startup",
995 "BrowserMainLoop::BrowserThreadsStarted:InitMediaStreamManager");
996 media_stream_manager_
.reset(new MediaStreamManager(audio_manager_
.get()));
1000 TRACE_EVENT0("startup",
1001 "BrowserMainLoop::BrowserThreadsStarted:InitSpeechRecognition");
1002 speech_recognition_manager_
.reset(new SpeechRecognitionManagerImpl(
1003 audio_manager_
.get(), media_stream_manager_
.get()));
1009 "BrowserMainLoop::BrowserThreadsStarted::InitUserInputMonitor");
1010 user_input_monitor_
= media::UserInputMonitor::Create(
1011 io_thread_
->message_loop_proxy(), main_thread_
->message_loop_proxy());
1015 TRACE_EVENT0("startup",
1016 "BrowserMainLoop::BrowserThreadsStarted::TimeZoneMonitor");
1017 time_zone_monitor_
= TimeZoneMonitor::Create();
1020 // Alert the clipboard class to which threads are allowed to access the
1022 std::vector
<base::PlatformThreadId
> allowed_clipboard_threads
;
1023 // The current thread is the UI thread.
1024 allowed_clipboard_threads
.push_back(base::PlatformThread::CurrentId());
1026 // On Windows, clipboards are also used on the File or IO threads.
1027 allowed_clipboard_threads
.push_back(file_thread_
->thread_id());
1028 allowed_clipboard_threads
.push_back(io_thread_
->thread_id());
1030 ui::Clipboard::SetAllowedThreads(allowed_clipboard_threads
);
1032 // When running the GPU thread in-process, avoid optimistically starting it
1033 // since creating the GPU thread races against creation of the one-and-only
1034 // ChildProcess instance which is created by the renderer thread.
1035 if (GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL
) &&
1036 !established_gpu_channel
&&
1038 !parsed_command_line_
.HasSwitch(switches::kSingleProcess
) &&
1039 !parsed_command_line_
.HasSwitch(switches::kInProcessGPU
)) {
1040 TRACE_EVENT_INSTANT0("gpu", "Post task to launch GPU process",
1041 TRACE_EVENT_SCOPE_THREAD
);
1042 BrowserThread::PostTask(
1043 BrowserThread::IO
, FROM_HERE
, base::Bind(
1044 base::IgnoreResult(&GpuProcessHost::Get
),
1045 GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED
,
1046 CAUSE_FOR_GPU_LAUNCH_BROWSER_STARTUP
));
1049 #if defined(OS_MACOSX)
1050 ThemeHelperMac::GetInstance();
1051 if (ShouldEnableBootstrapSandbox()) {
1052 TRACE_EVENT0("startup",
1053 "BrowserMainLoop::BrowserThreadsStarted:BootstrapSandbox");
1054 CHECK(GetBootstrapSandbox());
1056 #endif // defined(OS_MACOSX)
1058 #endif // !defined(OS_IOS)
1060 return result_code_
;
1063 bool BrowserMainLoop::InitializeToolkit() {
1064 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeToolkit");
1065 // TODO(evan): this function is rather subtle, due to the variety
1066 // of intersecting ifdefs we have. To keep it easy to follow, there
1067 // are no #else branches on any #ifs.
1068 // TODO(stevenjb): Move platform specific code into platform specific Parts
1069 // (Need to add InitializeToolkit stage to BrowserParts).
1070 // See also GTK setup in EarlyInitialization, above, and associated comments.
1073 // Init common control sex.
1074 INITCOMMONCONTROLSEX config
;
1075 config
.dwSize
= sizeof(config
);
1076 config
.dwICC
= ICC_WIN95_CLASSES
;
1077 if (!InitCommonControlsEx(&config
))
1081 #if defined(USE_AURA)
1083 #if defined(USE_X11)
1084 if (!gfx::GetXDisplay())
1088 // Env creates the compositor. Aura widgets need the compositor to be created
1089 // before they can be initialized by the browser.
1090 aura::Env::CreateInstance(true);
1091 #endif // defined(USE_AURA)
1094 parts_
->ToolkitInitialized();
1099 void BrowserMainLoop::MainMessageLoopRun() {
1100 #if defined(OS_ANDROID)
1101 // Android's main message loop is the Java message loop.
1104 DCHECK(base::MessageLoopForUI::IsCurrent());
1105 if (parameters_
.ui_task
)
1106 base::MessageLoopForUI::current()->PostTask(FROM_HERE
,
1107 *parameters_
.ui_task
);
1109 base::RunLoop run_loop
;
1114 base::FilePath
BrowserMainLoop::GetStartupTraceFileName(
1115 const base::CommandLine
& command_line
) const {
1116 base::FilePath trace_file
= command_line
.GetSwitchValuePath(
1117 switches::kTraceStartupFile
);
1118 // trace_file = "none" means that startup events will show up for the next
1119 // begin/end tracing (via about:tracing or AutomationProxy::BeginTracing/
1120 // EndTracing, for example).
1121 if (trace_file
== base::FilePath().AppendASCII("none"))
1124 if (trace_file
.empty()) {
1125 #if defined(OS_ANDROID)
1126 TracingControllerAndroid::GenerateTracingFilePath(&trace_file
);
1128 // Default to saving the startup trace into the current dir.
1129 trace_file
= base::FilePath().AppendASCII("chrometrace.log");
1136 void BrowserMainLoop::InitStartupTracing(const CommandLine
& command_line
) {
1137 DCHECK(is_tracing_startup_
);
1139 startup_trace_file_
= GetStartupTraceFileName(parsed_command_line_
);
1141 std::string delay_str
= command_line
.GetSwitchValueASCII(
1142 switches::kTraceStartupDuration
);
1144 if (!delay_str
.empty() && !base::StringToInt(delay_str
, &delay_secs
)) {
1145 DLOG(WARNING
) << "Could not parse --" << switches::kTraceStartupDuration
1146 << "=" << delay_str
<< " defaulting to 5 (secs)";
1150 startup_trace_timer_
.Start(FROM_HERE
,
1151 base::TimeDelta::FromSeconds(delay_secs
),
1153 &BrowserMainLoop::EndStartupTracing
);
1156 void BrowserMainLoop::EndStartupTracing() {
1157 is_tracing_startup_
= false;
1158 TracingController::GetInstance()->DisableRecording(
1159 startup_trace_file_
, base::Bind(&OnStoppedStartupTracing
));
1162 } // namespace content