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/cocoa/system_hotkey_helper_mac.h"
90 #include "content/browser/theme_helper_mac.h"
98 #include "content/browser/system_message_window_win.h"
99 #include "content/common/sandbox_win.h"
100 #include "net/base/winsock_init.h"
101 #include "ui/base/l10n/l10n_util_win.h"
104 #if defined(USE_GLIB)
105 #include <glib-object.h>
108 #if defined(OS_LINUX) && defined(USE_UDEV)
109 #include "content/browser/device_monitor_udev.h"
110 #elif defined(OS_MACOSX) && !defined(OS_IOS)
111 #include "content/browser/device_monitor_mac.h"
114 #if defined(OS_POSIX) && !defined(OS_MACOSX)
115 #include "content/browser/renderer_host/render_sandbox_host_linux.h"
116 #include "content/browser/zygote_host/zygote_host_impl_linux.h"
117 #include "sandbox/linux/suid/client/setuid_sandbox_client.h"
120 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
121 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
125 #include "ui/gfx/x/x11_connection.h"
126 #include "ui/gfx/x/x11_types.h"
129 // One of the linux specific headers defines this as a macro.
137 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
138 void SetupSandbox(const base::CommandLine
& parsed_command_line
) {
139 TRACE_EVENT0("startup", "SetupSandbox");
140 base::FilePath sandbox_binary
;
142 scoped_ptr
<sandbox::SetuidSandboxClient
> setuid_sandbox_client(
143 sandbox::SetuidSandboxClient::Create());
145 const bool want_setuid_sandbox
=
146 !parsed_command_line
.HasSwitch(switches::kNoSandbox
) &&
147 !parsed_command_line
.HasSwitch(switches::kDisableSetuidSandbox
) &&
148 !setuid_sandbox_client
->IsDisabledViaEnvironment();
150 static const char no_suid_error
[] =
151 "Running without the SUID sandbox! See "
152 "https://code.google.com/p/chromium/wiki/LinuxSUIDSandboxDevelopment "
153 "for more information on developing with the sandbox on.";
154 if (want_setuid_sandbox
) {
155 sandbox_binary
= setuid_sandbox_client
->GetSandboxBinaryPath();
156 if (sandbox_binary
.empty()) {
157 // This needs to be fatal. Talk to security@chromium.org if you feel
159 LOG(FATAL
) << no_suid_error
;
162 LOG(ERROR
) << no_suid_error
;
165 // Tickle the sandbox host and zygote host so they fork now.
166 RenderSandboxHostLinux::GetInstance()->Init();
167 ZygoteHostImpl::GetInstance()->Init(sandbox_binary
.value());
171 #if defined(USE_GLIB)
172 static void GLibLogHandler(const gchar
* log_domain
,
173 GLogLevelFlags log_level
,
174 const gchar
* message
,
177 log_domain
= "<unknown>";
179 message
= "<no message>";
181 if (strstr(message
, "Unable to retrieve the file info for")) {
182 LOG(ERROR
) << "GTK File code error: " << message
;
183 } else if (strstr(message
, "Could not find the icon") &&
184 strstr(log_domain
, "Gtk")) {
185 LOG(ERROR
) << "GTK icon error: " << message
;
186 } else if (strstr(message
, "Theme file for default has no") ||
187 strstr(message
, "Theme directory") ||
188 strstr(message
, "theme pixmap") ||
189 strstr(message
, "locate theme engine")) {
190 LOG(ERROR
) << "GTK theme error: " << message
;
191 } else if (strstr(message
, "Unable to create Ubuntu Menu Proxy") &&
192 strstr(log_domain
, "<unknown>")) {
193 LOG(ERROR
) << "GTK menu proxy create failed";
194 } else if (strstr(message
, "Out of memory") &&
195 strstr(log_domain
, "<unknown>")) {
196 LOG(ERROR
) << "DBus call timeout or out of memory: "
197 << "http://crosbug.com/15496";
198 } else if (strstr(message
, "Could not connect: Connection refused") &&
199 strstr(log_domain
, "<unknown>")) {
200 LOG(ERROR
) << "DConf settings backend could not connect to session bus: "
201 << "http://crbug.com/179797";
202 } else if (strstr(message
, "Attempting to store changes into") ||
203 strstr(message
, "Attempting to set the permissions of")) {
204 LOG(ERROR
) << message
<< " (http://bugs.chromium.org/161366)";
205 } else if (strstr(message
, "drawable is not a native X11 window")) {
206 LOG(ERROR
) << message
<< " (http://bugs.chromium.org/329991)";
208 LOG(DFATAL
) << log_domain
<< ": " << message
;
212 static void SetUpGLibLogHandler() {
213 // Register GLib-handled assertions to go through our logging system.
214 const char* kLogDomains
[] = { NULL
, "Gtk", "Gdk", "GLib", "GLib-GObject" };
215 for (size_t i
= 0; i
< arraysize(kLogDomains
); i
++) {
216 g_log_set_handler(kLogDomains
[i
],
217 static_cast<GLogLevelFlags
>(G_LOG_FLAG_RECURSION
|
220 G_LOG_LEVEL_CRITICAL
|
221 G_LOG_LEVEL_WARNING
),
228 void OnStoppedStartupTracing(const base::FilePath
& trace_file
) {
229 VLOG(0) << "Completed startup tracing to " << trace_file
.value();
232 #if defined(USE_AURA)
233 bool ShouldInitializeBrowserGpuChannelAndTransportSurface() {
236 #elif defined(OS_MACOSX) && !defined(OS_IOS)
237 bool ShouldInitializeBrowserGpuChannelAndTransportSurface() {
238 return IsDelegatedRendererEnabled();
242 // Disable optimizations for this block of functions so the compiler doesn't
243 // merge them all together. This makes it possible to tell what thread was
244 // unresponsive by inspecting the callstack.
245 MSVC_DISABLE_OPTIMIZE()
246 MSVC_PUSH_DISABLE_WARNING(4748)
248 NOINLINE
void ResetThread_DB(scoped_ptr
<BrowserProcessSubThread
> thread
) {
252 NOINLINE
void ResetThread_FILE(scoped_ptr
<BrowserProcessSubThread
> thread
) {
256 NOINLINE
void ResetThread_FILE_USER_BLOCKING(
257 scoped_ptr
<BrowserProcessSubThread
> thread
) {
261 NOINLINE
void ResetThread_PROCESS_LAUNCHER(
262 scoped_ptr
<BrowserProcessSubThread
> thread
) {
266 NOINLINE
void ResetThread_CACHE(scoped_ptr
<BrowserProcessSubThread
> thread
) {
270 NOINLINE
void ResetThread_IO(scoped_ptr
<BrowserProcessSubThread
> thread
) {
275 NOINLINE
void ResetThread_IndexedDb(scoped_ptr
<base::Thread
> thread
) {
281 MSVC_ENABLE_OPTIMIZE();
285 // The currently-running BrowserMainLoop. There can be one or zero.
286 BrowserMainLoop
* g_current_browser_main_loop
= NULL
;
288 // This is just to be able to keep ShutdownThreadsAndCleanUp out of
289 // the public interface of BrowserMainLoop.
290 class BrowserShutdownImpl
{
292 static void ImmediateShutdownAndExitProcess() {
293 DCHECK(g_current_browser_main_loop
);
294 g_current_browser_main_loop
->ShutdownThreadsAndCleanUp();
297 // At this point the message loop is still running yet we've shut everything
298 // down. If any messages are processed we'll likely crash. Exit now.
299 ExitProcess(RESULT_CODE_NORMAL_EXIT
);
300 #elif defined(OS_POSIX) && !defined(OS_MACOSX)
301 _exit(RESULT_CODE_NORMAL_EXIT
);
308 void ImmediateShutdownAndExitProcess() {
309 BrowserShutdownImpl::ImmediateShutdownAndExitProcess();
312 // For measuring memory usage after each task. Behind a command line flag.
313 class BrowserMainLoop::MemoryObserver
: public base::MessageLoop::TaskObserver
{
316 virtual ~MemoryObserver() {}
318 virtual void WillProcessTask(const base::PendingTask
& pending_task
) OVERRIDE
{
321 virtual void DidProcessTask(const base::PendingTask
& pending_task
) OVERRIDE
{
322 #if !defined(OS_IOS) // No ProcessMetrics on IOS.
323 scoped_ptr
<base::ProcessMetrics
> process_metrics(
324 base::ProcessMetrics::CreateProcessMetrics(
325 #if defined(OS_MACOSX)
326 base::GetCurrentProcessHandle(), NULL
));
328 base::GetCurrentProcessHandle()));
330 size_t private_bytes
;
331 process_metrics
->GetMemoryBytes(&private_bytes
, NULL
);
332 HISTOGRAM_MEMORY_KB("Memory.BrowserUsed", private_bytes
>> 10);
336 DISALLOW_COPY_AND_ASSIGN(MemoryObserver
);
340 // BrowserMainLoop construction / destruction =============================
342 BrowserMainLoop
* BrowserMainLoop::GetInstance() {
343 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
344 return g_current_browser_main_loop
;
347 BrowserMainLoop::BrowserMainLoop(const MainFunctionParams
& parameters
)
348 : parameters_(parameters
),
349 parsed_command_line_(parameters
.command_line
),
350 result_code_(RESULT_CODE_NORMAL_EXIT
),
351 created_threads_(false),
352 // ContentMainRunner should have enabled tracing of the browser process
353 // when kTraceStartup is in the command line.
355 parameters
.command_line
.HasSwitch(switches::kTraceStartup
)) {
356 DCHECK(!g_current_browser_main_loop
);
357 g_current_browser_main_loop
= this;
360 BrowserMainLoop::~BrowserMainLoop() {
361 DCHECK_EQ(this, g_current_browser_main_loop
);
363 ui::Clipboard::DestroyClipboardForCurrentThread();
364 #endif // !defined(OS_IOS)
365 g_current_browser_main_loop
= NULL
;
368 void BrowserMainLoop::Init() {
369 TRACE_EVENT0("startup", "BrowserMainLoop::Init");
371 GetContentClient()->browser()->CreateBrowserMainParts(parameters_
));
374 // BrowserMainLoop stages ==================================================
376 void BrowserMainLoop::EarlyInitialization() {
377 TRACE_EVENT0("startup", "BrowserMainLoop::EarlyInitialization");
379 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
380 // No thread should be created before this call, as SetupSandbox()
381 // will end-up using fork().
382 SetupSandbox(parsed_command_line_
);
386 if (parsed_command_line_
.HasSwitch(switches::kSingleProcess
) ||
387 parsed_command_line_
.HasSwitch(switches::kInProcessGPU
)) {
388 if (!gfx::InitializeThreadedX11()) {
389 LOG(ERROR
) << "Failed to put Xlib into threaded mode.";
394 // GLib's spawning of new processes is buggy, so it's important that at this
395 // point GLib does not need to start DBUS. Chrome should always start with
396 // DBUS_SESSION_BUS_ADDRESS properly set. See crbug.com/309093.
397 #if defined(USE_GLIB)
398 // g_type_init will be deprecated in 2.36. 2.35 is the development
399 // version for 2.36, hence do not call g_type_init starting 2.35.
400 // http://developer.gnome.org/gobject/unstable/gobject-Type-Information.html#g-type-init
401 #if !GLIB_CHECK_VERSION(2, 35, 0)
402 // GLib type system initialization. Needed at least for gconf,
403 // used in net/proxy/proxy_config_service_linux.cc. Most likely
404 // this is superfluous as gtk_init() ought to do this. It's
405 // definitely harmless, so retained as a reminder of this
406 // requirement for gconf.
410 SetUpGLibLogHandler();
414 parts_
->PreEarlyInitialization();
416 #if defined(OS_MACOSX)
417 // We use quite a few file descriptors for our IPC, and the default limit on
418 // the Mac is low (256), so bump it up.
419 base::SetFdLimit(1024);
423 net::EnsureWinsockInit();
426 #if !defined(USE_OPENSSL)
427 // We want to be sure to init NSPR on the main thread.
428 crypto::EnsureNSPRInit();
429 #endif // !defined(USE_OPENSSL)
432 if (parsed_command_line_
.HasSwitch(switches::kRendererProcessLimit
)) {
433 std::string limit_string
= parsed_command_line_
.GetSwitchValueASCII(
434 switches::kRendererProcessLimit
);
435 size_t process_limit
;
436 if (base::StringToSizeT(limit_string
, &process_limit
)) {
437 RenderProcessHost::SetMaxRendererProcessCount(process_limit
);
440 #endif // !defined(OS_IOS)
443 parts_
->PostEarlyInitialization();
446 void BrowserMainLoop::MainMessageLoopStart() {
447 TRACE_EVENT0("startup", "BrowserMainLoop::MainMessageLoopStart");
449 TRACE_EVENT0("startup",
450 "BrowserMainLoop::MainMessageLoopStart:PreMainMessageLoopStart");
451 parts_
->PreMainMessageLoopStart();
455 // If we're running tests (ui_task is non-null), then the ResourceBundle
456 // has already been initialized.
457 if (!parameters_
.ui_task
) {
458 // Override the configured locale with the user's preferred UI language.
459 l10n_util::OverrideLocaleWithUILanguageList();
463 // Create a MessageLoop if one does not already exist for the current thread.
464 if (!base::MessageLoop::current())
465 main_message_loop_
.reset(new base::MessageLoopForUI
);
467 InitializeMainThread();
470 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SystemMonitor");
471 system_monitor_
.reset(new base::SystemMonitor
);
474 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:PowerMonitor");
475 scoped_ptr
<base::PowerMonitorSource
> power_monitor_source(
476 new base::PowerMonitorDeviceSource());
477 power_monitor_
.reset(new base::PowerMonitor(power_monitor_source
.Pass()));
480 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:HighResTimerManager");
481 hi_res_timer_manager_
.reset(new base::HighResolutionTimerManager
);
484 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:NetworkChangeNotifier");
485 network_change_notifier_
.reset(net::NetworkChangeNotifier::Create());
490 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MediaFeatures");
491 media::InitializeCPUSpecificMediaFeatures();
494 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:AudioMan");
495 audio_manager_
.reset(media::AudioManager::Create(
496 MediaInternals::GetInstance()));
499 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MidiManager");
500 midi_manager_
.reset(media::MidiManager::Create());
503 TRACE_EVENT0("startup",
504 "BrowserMainLoop::Subsystem:ContentWebUIController");
505 WebUIControllerFactory::RegisterFactory(
506 ContentWebUIControllerFactory::GetInstance());
510 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:AudioMirroringManager");
511 audio_mirroring_manager_
.reset(new AudioMirroringManager());
514 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:OnlineStateObserver");
515 online_state_observer_
.reset(new BrowserOnlineStateObserver
);
519 system_stats_monitor_
.reset(new base::debug::TraceEventSystemStatsMonitor(
520 base::ThreadTaskRunnerHandle::Get()));
522 #endif // !defined(OS_IOS)
525 system_message_window_
.reset(new SystemMessageWindowWin
);
529 parts_
->PostMainMessageLoopStart();
532 // Start tracing to a file if needed. Only do this after starting the main
533 // message loop to avoid calling MessagePumpForUI::ScheduleWork() before
534 // MessagePumpForUI::Start() as it will crash the browser.
535 if (is_tracing_startup_
) {
536 TRACE_EVENT0("startup", "BrowserMainLoop::InitStartupTracing");
537 InitStartupTracing(parsed_command_line_
);
539 #endif // !defined(OS_IOS)
541 #if defined(OS_ANDROID)
543 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SurfaceTexturePeer");
544 SurfaceTexturePeer::InitInstance(new SurfaceTexturePeerBrowserImpl());
548 if (parsed_command_line_
.HasSwitch(switches::kMemoryMetrics
)) {
549 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MemoryObserver");
550 memory_observer_
.reset(new MemoryObserver());
551 base::MessageLoop::current()->AddTaskObserver(memory_observer_
.get());
554 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
555 trace_memory_controller_
.reset(new base::debug::TraceMemoryController(
556 base::MessageLoop::current()->message_loop_proxy(),
557 ::HeapProfilerWithPseudoStackStart
,
563 int BrowserMainLoop::PreCreateThreads() {
565 TRACE_EVENT0("startup",
566 "BrowserMainLoop::CreateThreads:PreCreateThreads");
567 result_code_
= parts_
->PreCreateThreads();
570 #if defined(ENABLE_PLUGINS)
571 // Prior to any processing happening on the io thread, we create the
572 // plugin service as it is predominantly used from the io thread,
573 // but must be created on the main thread. The service ctor is
574 // inexpensive and does not invoke the io_thread() accessor.
576 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads:PluginService");
577 PluginService::GetInstance()->Init();
581 #if !defined(OS_IOS) && (!defined(GOOGLE_CHROME_BUILD) || defined(OS_ANDROID))
582 // Single-process is an unsupported and not fully tested mode, so
583 // don't enable it for official Chrome builds (except on Android).
584 if (parsed_command_line_
.HasSwitch(switches::kSingleProcess
))
585 RenderProcessHost::SetRunRendererInProcess(true);
590 void BrowserMainLoop::CreateStartupTasks() {
591 TRACE_EVENT0("startup", "BrowserMainLoop::CreateStartupTasks");
593 // First time through, we really want to create all the tasks
594 if (!startup_task_runner_
.get()) {
595 #if defined(OS_ANDROID)
596 startup_task_runner_
= make_scoped_ptr(new StartupTaskRunner(
597 base::Bind(&BrowserStartupComplete
),
598 base::MessageLoop::current()->message_loop_proxy()));
600 startup_task_runner_
= make_scoped_ptr(new StartupTaskRunner(
601 base::Callback
<void(int)>(),
602 base::MessageLoop::current()->message_loop_proxy()));
604 StartupTask pre_create_threads
=
605 base::Bind(&BrowserMainLoop::PreCreateThreads
, base::Unretained(this));
606 startup_task_runner_
->AddTask(pre_create_threads
);
608 StartupTask create_threads
=
609 base::Bind(&BrowserMainLoop::CreateThreads
, base::Unretained(this));
610 startup_task_runner_
->AddTask(create_threads
);
612 StartupTask browser_thread_started
= base::Bind(
613 &BrowserMainLoop::BrowserThreadsStarted
, base::Unretained(this));
614 startup_task_runner_
->AddTask(browser_thread_started
);
616 StartupTask pre_main_message_loop_run
= base::Bind(
617 &BrowserMainLoop::PreMainMessageLoopRun
, base::Unretained(this));
618 startup_task_runner_
->AddTask(pre_main_message_loop_run
);
620 #if defined(OS_ANDROID)
621 if (BrowserMayStartAsynchronously()) {
622 startup_task_runner_
->StartRunningTasksAsync();
626 #if defined(OS_ANDROID)
627 if (!BrowserMayStartAsynchronously()) {
628 // A second request for asynchronous startup can be ignored, so
629 // StartupRunningTasksAsync is only called first time through. If, however,
630 // this is a request for synchronous startup then it must override any
631 // previous call for async startup, so we call RunAllTasksNow()
633 startup_task_runner_
->RunAllTasksNow();
636 startup_task_runner_
->RunAllTasksNow();
640 int BrowserMainLoop::CreateThreads() {
641 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads");
643 base::Thread::Options io_message_loop_options
;
644 io_message_loop_options
.message_loop_type
= base::MessageLoop::TYPE_IO
;
645 base::Thread::Options ui_message_loop_options
;
646 ui_message_loop_options
.message_loop_type
= base::MessageLoop::TYPE_UI
;
648 // Start threads in the order they occur in the BrowserThread::ID
649 // enumeration, except for BrowserThread::UI which is the main
652 // Must be size_t so we can increment it.
653 for (size_t thread_id
= BrowserThread::UI
+ 1;
654 thread_id
< BrowserThread::ID_COUNT
;
656 scoped_ptr
<BrowserProcessSubThread
>* thread_to_start
= NULL
;
657 base::Thread::Options options
;
660 case BrowserThread::DB
:
661 TRACE_EVENT_BEGIN1("startup",
662 "BrowserMainLoop::CreateThreads:start",
663 "Thread", "BrowserThread::DB");
664 thread_to_start
= &db_thread_
;
665 options
.timer_slack
= base::TIMER_SLACK_MAXIMUM
;
667 case BrowserThread::FILE_USER_BLOCKING
:
668 TRACE_EVENT_BEGIN1("startup",
669 "BrowserMainLoop::CreateThreads:start",
670 "Thread", "BrowserThread::FILE_USER_BLOCKING");
671 thread_to_start
= &file_user_blocking_thread_
;
673 case BrowserThread::FILE:
674 TRACE_EVENT_BEGIN1("startup",
675 "BrowserMainLoop::CreateThreads:start",
676 "Thread", "BrowserThread::FILE");
677 thread_to_start
= &file_thread_
;
679 // On Windows, the FILE thread needs to be have a UI message loop
680 // which pumps messages in such a way that Google Update can
681 // communicate back to us.
682 options
= ui_message_loop_options
;
684 options
= io_message_loop_options
;
686 options
.timer_slack
= base::TIMER_SLACK_MAXIMUM
;
688 case BrowserThread::PROCESS_LAUNCHER
:
689 TRACE_EVENT_BEGIN1("startup",
690 "BrowserMainLoop::CreateThreads:start",
691 "Thread", "BrowserThread::PROCESS_LAUNCHER");
692 thread_to_start
= &process_launcher_thread_
;
693 options
.timer_slack
= base::TIMER_SLACK_MAXIMUM
;
695 case BrowserThread::CACHE
:
696 TRACE_EVENT_BEGIN1("startup",
697 "BrowserMainLoop::CreateThreads:start",
698 "Thread", "BrowserThread::CACHE");
699 thread_to_start
= &cache_thread_
;
700 options
= io_message_loop_options
;
701 options
.timer_slack
= base::TIMER_SLACK_MAXIMUM
;
703 case BrowserThread::IO
:
704 TRACE_EVENT_BEGIN1("startup",
705 "BrowserMainLoop::CreateThreads:start",
706 "Thread", "BrowserThread::IO");
707 thread_to_start
= &io_thread_
;
708 options
= io_message_loop_options
;
710 case BrowserThread::UI
:
711 case BrowserThread::ID_COUNT
:
717 BrowserThread::ID id
= static_cast<BrowserThread::ID
>(thread_id
);
719 if (thread_to_start
) {
720 (*thread_to_start
).reset(new BrowserProcessSubThread(id
));
721 (*thread_to_start
)->StartWithOptions(options
);
726 TRACE_EVENT_END0("startup", "BrowserMainLoop::CreateThreads:start");
728 created_threads_
= true;
732 int BrowserMainLoop::PreMainMessageLoopRun() {
734 TRACE_EVENT0("startup",
735 "BrowserMainLoop::CreateThreads:PreMainMessageLoopRun");
736 parts_
->PreMainMessageLoopRun();
739 // If the UI thread blocks, the whole UI is unresponsive.
740 // Do not allow disk IO from the UI thread.
741 base::ThreadRestrictions::SetIOAllowed(false);
742 base::ThreadRestrictions::DisallowWaiting();
746 void BrowserMainLoop::RunMainMessageLoopParts() {
747 TRACE_EVENT_BEGIN_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
749 bool ran_main_loop
= false;
751 ran_main_loop
= parts_
->MainMessageLoopRun(&result_code_
);
754 MainMessageLoopRun();
756 TRACE_EVENT_END_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
759 void BrowserMainLoop::ShutdownThreadsAndCleanUp() {
760 if (!created_threads_
) {
761 // Called early, nothing to do
764 TRACE_EVENT0("shutdown", "BrowserMainLoop::ShutdownThreadsAndCleanUp");
766 // Teardown may start in PostMainMessageLoopRun, and during teardown we
767 // need to be able to perform IO.
768 base::ThreadRestrictions::SetIOAllowed(true);
769 BrowserThread::PostTask(
770 BrowserThread::IO
, FROM_HERE
,
771 base::Bind(base::IgnoreResult(&base::ThreadRestrictions::SetIOAllowed
),
775 if (RenderProcessHost::run_renderer_in_process())
776 RenderProcessHostImpl::ShutDownInProcessRenderer();
780 TRACE_EVENT0("shutdown",
781 "BrowserMainLoop::Subsystem:PostMainMessageLoopRun");
782 parts_
->PostMainMessageLoopRun();
785 trace_memory_controller_
.reset();
786 system_stats_monitor_
.reset();
789 // Destroying the GpuProcessHostUIShims on the UI thread posts a task to
790 // delete related objects on the GPU thread. This must be done before
791 // stopping the GPU thread. The GPU thread will close IPC channels to renderer
792 // processes so this has to happen before stopping the IO thread.
794 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUProcessHostShim");
795 GpuProcessHostUIShim::DestroyAll();
797 // Cancel pending requests and prevent new requests.
798 if (resource_dispatcher_host_
) {
799 TRACE_EVENT0("shutdown",
800 "BrowserMainLoop::Subsystem:ResourceDispatcherHost");
801 resource_dispatcher_host_
.get()->Shutdown();
804 #if defined(USE_AURA) || defined(OS_MACOSX)
805 if (ShouldInitializeBrowserGpuChannelAndTransportSurface()) {
806 TRACE_EVENT0("shutdown",
807 "BrowserMainLoop::Subsystem:ImageTransportFactory");
808 ImageTransportFactory::Terminate();
812 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
813 ZygoteHostImpl::GetInstance()->TearDownAfterLastChild();
814 #endif // defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
816 // The device monitors are using |system_monitor_| as dependency, so delete
817 // them before |system_monitor_| goes away.
818 // On Mac and windows, the monitor needs to be destroyed on the same thread
819 // as they were created. On Linux, the monitor will be deleted when IO thread
822 system_message_window_
.reset();
823 #elif defined(OS_MACOSX)
824 device_monitor_mac_
.reset();
826 #endif // !defined(OS_IOS)
828 // Must be size_t so we can subtract from it.
829 for (size_t thread_id
= BrowserThread::ID_COUNT
- 1;
830 thread_id
>= (BrowserThread::UI
+ 1);
832 // Find the thread object we want to stop. Looping over all valid
833 // BrowserThread IDs and DCHECKing on a missing case in the switch
834 // statement helps avoid a mismatch between this code and the
835 // BrowserThread::ID enumeration.
837 // The destruction order is the reverse order of occurrence in the
838 // BrowserThread::ID list. The rationale for the order is as
839 // follows (need to be filled in a bit):
842 // - The IO thread is the only user of the CACHE thread.
844 // - The PROCESS_LAUNCHER thread must be stopped after IO in case
845 // the IO thread posted a task to terminate a process on the
846 // process launcher thread.
848 // - (Not sure why DB stops last.)
850 case BrowserThread::DB
: {
851 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DBThread");
852 ResetThread_DB(db_thread_
.Pass());
855 case BrowserThread::FILE: {
856 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:FileThread");
858 // Clean up state that lives on or uses the file_thread_ before
860 if (resource_dispatcher_host_
)
861 resource_dispatcher_host_
.get()->save_file_manager()->Shutdown();
862 #endif // !defined(OS_IOS)
863 ResetThread_FILE(file_thread_
.Pass());
866 case BrowserThread::FILE_USER_BLOCKING
: {
867 TRACE_EVENT0("shutdown",
868 "BrowserMainLoop::Subsystem:FileUserBlockingThread");
869 ResetThread_FILE_USER_BLOCKING(file_user_blocking_thread_
.Pass());
872 case BrowserThread::PROCESS_LAUNCHER
: {
873 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:LauncherThread");
874 ResetThread_PROCESS_LAUNCHER(process_launcher_thread_
.Pass());
877 case BrowserThread::CACHE
: {
878 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:CacheThread");
879 ResetThread_CACHE(cache_thread_
.Pass());
882 case BrowserThread::IO
: {
883 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IOThread");
884 ResetThread_IO(io_thread_
.Pass());
887 case BrowserThread::UI
:
888 case BrowserThread::ID_COUNT
:
897 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IndexedDBThread");
898 ResetThread_IndexedDb(indexed_db_thread_
.Pass());
902 // Close the blocking I/O pool after the other threads. Other threads such
903 // as the I/O thread may need to schedule work like closing files or flushing
904 // data during shutdown, so the blocking pool needs to be available. There
905 // may also be slow operations pending that will blcok shutdown, so closing
906 // it here (which will block until required operations are complete) gives
907 // more head start for those operations to finish.
909 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:ThreadPool");
910 BrowserThreadImpl::ShutdownThreadPool();
914 // Must happen after the IO thread is shutdown since this may be accessed from
917 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUChannelFactory");
918 if (BrowserGpuChannelHostFactory::instance())
919 BrowserGpuChannelHostFactory::Terminate();
922 // Must happen after the I/O thread is shutdown since this class lives on the
923 // I/O thread and isn't threadsafe.
925 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GamepadService");
926 GamepadService::GetInstance()->Terminate();
929 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:SensorService");
930 DeviceInertialSensorService::GetInstance()->Shutdown();
933 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:BatteryStatusService");
934 BatteryStatusService::GetInstance()->Shutdown();
937 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DeleteDataSources");
938 URLDataManager::DeleteDataSources();
940 #endif // !defined(OS_IOS)
943 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:PostDestroyThreads");
944 parts_
->PostDestroyThreads();
948 void BrowserMainLoop::StopStartupTracingTimer() {
949 startup_trace_timer_
.Stop();
952 void BrowserMainLoop::InitializeMainThread() {
953 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeMainThread");
954 const char* kThreadName
= "CrBrowserMain";
955 base::PlatformThread::SetName(kThreadName
);
956 if (main_message_loop_
)
957 main_message_loop_
->set_thread_name(kThreadName
);
959 // Register the main thread by instantiating it, but don't call any methods.
961 new BrowserThreadImpl(BrowserThread::UI
, base::MessageLoop::current()));
964 int BrowserMainLoop::BrowserThreadsStarted() {
965 TRACE_EVENT0("startup", "BrowserMainLoop::BrowserThreadsStarted");
968 indexed_db_thread_
.reset(new base::Thread("IndexedDB"));
969 indexed_db_thread_
->Start();
972 #if defined(OS_ANDROID)
973 // Up the priority of anything that touches with display tasks
974 // (this thread is UI thread, and io_thread_ is for IPCs).
975 io_thread_
->SetPriority(base::kThreadPriority_Display
);
976 base::PlatformThread::SetThreadPriority(
977 base::PlatformThread::CurrentHandle(),
978 base::kThreadPriority_Display
);
982 HistogramSynchronizer::GetInstance();
984 bool initialize_gpu_data_manager
= true;
985 #if defined(OS_ANDROID)
986 // On Android, GLSurface::InitializeOneOff() must be called before initalizing
987 // the GpuDataManagerImpl as it uses the GL bindings. crbug.com/326295
988 if (!gfx::GLSurface::InitializeOneOff()) {
989 LOG(ERROR
) << "GLSurface::InitializeOneOff failed";
990 initialize_gpu_data_manager
= false;
994 // Initialize the GpuDataManager before we set up the MessageLoops because
995 // otherwise we'll trigger the assertion about doing IO on the UI thread.
996 if (initialize_gpu_data_manager
)
997 GpuDataManagerImpl::GetInstance()->Initialize();
999 bool always_uses_gpu
= true;
1000 bool established_gpu_channel
= false;
1001 #if defined(USE_AURA) || defined(OS_MACOSX)
1002 if (ShouldInitializeBrowserGpuChannelAndTransportSurface()) {
1003 established_gpu_channel
= true;
1004 if (!GpuDataManagerImpl::GetInstance()->CanUseGpuBrowserCompositor()) {
1005 established_gpu_channel
= always_uses_gpu
= false;
1007 BrowserGpuChannelHostFactory::Initialize(established_gpu_channel
);
1008 ImageTransportFactory::Initialize();
1009 #if defined(USE_AURA)
1010 if (aura::Env::GetInstance()) {
1011 aura::Env::GetInstance()->set_context_factory(
1012 content::GetContextFactory());
1016 #elif defined(OS_ANDROID)
1017 established_gpu_channel
= true;
1018 BrowserGpuChannelHostFactory::Initialize(established_gpu_channel
);
1021 #if defined(OS_LINUX) && defined(USE_UDEV)
1022 device_monitor_linux_
.reset(new DeviceMonitorLinux());
1023 #elif defined(OS_MACOSX)
1024 device_monitor_mac_
.reset(new DeviceMonitorMac());
1027 // RDH needs the IO thread to be created
1029 TRACE_EVENT0("startup",
1030 "BrowserMainLoop::BrowserThreadsStarted:InitResourceDispatcherHost");
1031 resource_dispatcher_host_
.reset(new ResourceDispatcherHostImpl());
1034 // MediaStreamManager needs the IO thread to be created.
1036 TRACE_EVENT0("startup",
1037 "BrowserMainLoop::BrowserThreadsStarted:InitMediaStreamManager");
1038 media_stream_manager_
.reset(new MediaStreamManager(audio_manager_
.get()));
1042 TRACE_EVENT0("startup",
1043 "BrowserMainLoop::BrowserThreadsStarted:InitSpeechRecognition");
1044 speech_recognition_manager_
.reset(new SpeechRecognitionManagerImpl(
1045 audio_manager_
.get(), media_stream_manager_
.get()));
1051 "BrowserMainLoop::BrowserThreadsStarted::InitUserInputMonitor");
1052 user_input_monitor_
= media::UserInputMonitor::Create(
1053 io_thread_
->message_loop_proxy(), main_thread_
->message_loop_proxy());
1057 TRACE_EVENT0("startup",
1058 "BrowserMainLoop::BrowserThreadsStarted::TimeZoneMonitor");
1059 time_zone_monitor_
= TimeZoneMonitor::Create();
1062 // Alert the clipboard class to which threads are allowed to access the
1064 std::vector
<base::PlatformThreadId
> allowed_clipboard_threads
;
1065 // The current thread is the UI thread.
1066 allowed_clipboard_threads
.push_back(base::PlatformThread::CurrentId());
1068 // On Windows, clipboards are also used on the File or IO threads.
1069 allowed_clipboard_threads
.push_back(file_thread_
->thread_id());
1070 allowed_clipboard_threads
.push_back(io_thread_
->thread_id());
1072 ui::Clipboard::SetAllowedThreads(allowed_clipboard_threads
);
1074 // When running the GPU thread in-process, avoid optimistically starting it
1075 // since creating the GPU thread races against creation of the one-and-only
1076 // ChildProcess instance which is created by the renderer thread.
1077 if (GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL
) &&
1078 !established_gpu_channel
&&
1080 !parsed_command_line_
.HasSwitch(switches::kSingleProcess
) &&
1081 !parsed_command_line_
.HasSwitch(switches::kInProcessGPU
)) {
1082 TRACE_EVENT_INSTANT0("gpu", "Post task to launch GPU process",
1083 TRACE_EVENT_SCOPE_THREAD
);
1084 BrowserThread::PostTask(
1085 BrowserThread::IO
, FROM_HERE
, base::Bind(
1086 base::IgnoreResult(&GpuProcessHost::Get
),
1087 GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED
,
1088 CAUSE_FOR_GPU_LAUNCH_BROWSER_STARTUP
));
1091 #if defined(OS_MACOSX)
1092 ThemeHelperMac::GetInstance();
1093 SystemHotkeyHelperMac::GetInstance()->DeferredLoadSystemHotkeys();
1094 if (ShouldEnableBootstrapSandbox()) {
1095 TRACE_EVENT0("startup",
1096 "BrowserMainLoop::BrowserThreadsStarted:BootstrapSandbox");
1097 CHECK(GetBootstrapSandbox());
1099 #endif // defined(OS_MACOSX)
1101 #endif // !defined(OS_IOS)
1103 return result_code_
;
1106 bool BrowserMainLoop::InitializeToolkit() {
1107 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeToolkit");
1108 // TODO(evan): this function is rather subtle, due to the variety
1109 // of intersecting ifdefs we have. To keep it easy to follow, there
1110 // are no #else branches on any #ifs.
1111 // TODO(stevenjb): Move platform specific code into platform specific Parts
1112 // (Need to add InitializeToolkit stage to BrowserParts).
1113 // See also GTK setup in EarlyInitialization, above, and associated comments.
1116 // Init common control sex.
1117 INITCOMMONCONTROLSEX config
;
1118 config
.dwSize
= sizeof(config
);
1119 config
.dwICC
= ICC_WIN95_CLASSES
;
1120 if (!InitCommonControlsEx(&config
))
1124 #if defined(USE_AURA)
1126 #if defined(USE_X11)
1127 if (!gfx::GetXDisplay())
1131 // Env creates the compositor. Aura widgets need the compositor to be created
1132 // before they can be initialized by the browser.
1133 aura::Env::CreateInstance(true);
1134 #endif // defined(USE_AURA)
1137 parts_
->ToolkitInitialized();
1142 void BrowserMainLoop::MainMessageLoopRun() {
1143 #if defined(OS_ANDROID)
1144 // Android's main message loop is the Java message loop.
1147 DCHECK(base::MessageLoopForUI::IsCurrent());
1148 if (parameters_
.ui_task
)
1149 base::MessageLoopForUI::current()->PostTask(FROM_HERE
,
1150 *parameters_
.ui_task
);
1152 base::RunLoop run_loop
;
1157 base::FilePath
BrowserMainLoop::GetStartupTraceFileName(
1158 const base::CommandLine
& command_line
) const {
1159 base::FilePath trace_file
= command_line
.GetSwitchValuePath(
1160 switches::kTraceStartupFile
);
1161 // trace_file = "none" means that startup events will show up for the next
1162 // begin/end tracing (via about:tracing or AutomationProxy::BeginTracing/
1163 // EndTracing, for example).
1164 if (trace_file
== base::FilePath().AppendASCII("none"))
1167 if (trace_file
.empty()) {
1168 #if defined(OS_ANDROID)
1169 TracingControllerAndroid::GenerateTracingFilePath(&trace_file
);
1171 // Default to saving the startup trace into the current dir.
1172 trace_file
= base::FilePath().AppendASCII("chrometrace.log");
1179 void BrowserMainLoop::InitStartupTracing(
1180 const base::CommandLine
& command_line
) {
1181 DCHECK(is_tracing_startup_
);
1183 startup_trace_file_
= GetStartupTraceFileName(parsed_command_line_
);
1185 std::string delay_str
= command_line
.GetSwitchValueASCII(
1186 switches::kTraceStartupDuration
);
1188 if (!delay_str
.empty() && !base::StringToInt(delay_str
, &delay_secs
)) {
1189 DLOG(WARNING
) << "Could not parse --" << switches::kTraceStartupDuration
1190 << "=" << delay_str
<< " defaulting to 5 (secs)";
1194 startup_trace_timer_
.Start(FROM_HERE
,
1195 base::TimeDelta::FromSeconds(delay_secs
),
1197 &BrowserMainLoop::EndStartupTracing
);
1200 void BrowserMainLoop::EndStartupTracing() {
1201 is_tracing_startup_
= false;
1202 TracingController::GetInstance()->DisableRecording(
1203 startup_trace_file_
, base::Bind(&OnStoppedStartupTracing
));
1206 } // namespace content