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/media_internals.h"
39 #include "content/browser/net/browser_online_state_observer.h"
40 #include "content/browser/plugin_service_impl.h"
41 #include "content/browser/renderer_host/media/media_stream_manager.h"
42 #include "content/browser/speech/speech_recognition_manager_impl.h"
43 #include "content/browser/startup_task_runner.h"
44 #include "content/browser/time_zone_monitor.h"
45 #include "content/browser/webui/content_web_ui_controller_factory.h"
46 #include "content/browser/webui/url_data_manager.h"
47 #include "content/public/browser/browser_main_parts.h"
48 #include "content/public/browser/browser_shutdown.h"
49 #include "content/public/browser/content_browser_client.h"
50 #include "content/public/browser/render_process_host.h"
51 #include "content/public/browser/tracing_controller.h"
52 #include "content/public/common/content_switches.h"
53 #include "content/public/common/main_function_params.h"
54 #include "content/public/common/result_codes.h"
55 #include "crypto/nss_util.h"
56 #include "media/audio/audio_manager.h"
57 #include "media/base/media.h"
58 #include "media/base/user_input_monitor.h"
59 #include "media/midi/midi_manager.h"
60 #include "net/base/network_change_notifier.h"
61 #include "net/socket/client_socket_factory.h"
62 #include "net/ssl/ssl_config_service.h"
63 #include "ui/base/clipboard/clipboard.h"
65 #if defined(USE_AURA) || (defined(OS_MACOSX) && !defined(OS_IOS))
66 #include "content/browser/compositor/image_transport_factory.h"
70 #include "content/public/browser/context_factory.h"
71 #include "ui/aura/env.h"
75 #include "content/browser/renderer_host/render_process_host_impl.h"
78 #if defined(OS_ANDROID)
79 #include "base/android/jni_android.h"
80 #include "content/browser/android/browser_startup_controller.h"
81 #include "content/browser/android/surface_texture_peer_browser_impl.h"
82 #include "content/browser/android/tracing_controller_android.h"
83 #include "ui/gl/gl_surface.h"
86 #if defined(OS_MACOSX) && !defined(OS_IOS)
87 #include "content/browser/bootstrap_sandbox_mac.h"
88 #include "content/browser/cocoa/system_hotkey_helper_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 base::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();
241 // Disable optimizations for this block of functions so the compiler doesn't
242 // merge them all together. This makes it possible to tell what thread was
243 // unresponsive by inspecting the callstack.
244 MSVC_DISABLE_OPTIMIZE()
245 MSVC_PUSH_DISABLE_WARNING(4748)
247 NOINLINE
void ResetThread_DB(scoped_ptr
<BrowserProcessSubThread
> thread
) {
251 NOINLINE
void ResetThread_FILE(scoped_ptr
<BrowserProcessSubThread
> thread
) {
255 NOINLINE
void ResetThread_FILE_USER_BLOCKING(
256 scoped_ptr
<BrowserProcessSubThread
> thread
) {
260 NOINLINE
void ResetThread_PROCESS_LAUNCHER(
261 scoped_ptr
<BrowserProcessSubThread
> thread
) {
265 NOINLINE
void ResetThread_CACHE(scoped_ptr
<BrowserProcessSubThread
> thread
) {
269 NOINLINE
void ResetThread_IO(scoped_ptr
<BrowserProcessSubThread
> thread
) {
274 NOINLINE
void ResetThread_IndexedDb(scoped_ptr
<base::Thread
> thread
) {
280 MSVC_ENABLE_OPTIMIZE();
284 // The currently-running BrowserMainLoop. There can be one or zero.
285 BrowserMainLoop
* g_current_browser_main_loop
= NULL
;
287 // This is just to be able to keep ShutdownThreadsAndCleanUp out of
288 // the public interface of BrowserMainLoop.
289 class BrowserShutdownImpl
{
291 static void ImmediateShutdownAndExitProcess() {
292 DCHECK(g_current_browser_main_loop
);
293 g_current_browser_main_loop
->ShutdownThreadsAndCleanUp();
296 // At this point the message loop is still running yet we've shut everything
297 // down. If any messages are processed we'll likely crash. Exit now.
298 ExitProcess(RESULT_CODE_NORMAL_EXIT
);
299 #elif defined(OS_POSIX) && !defined(OS_MACOSX)
300 _exit(RESULT_CODE_NORMAL_EXIT
);
307 void ImmediateShutdownAndExitProcess() {
308 BrowserShutdownImpl::ImmediateShutdownAndExitProcess();
311 // For measuring memory usage after each task. Behind a command line flag.
312 class BrowserMainLoop::MemoryObserver
: public base::MessageLoop::TaskObserver
{
315 virtual ~MemoryObserver() {}
317 virtual void WillProcessTask(const base::PendingTask
& pending_task
) OVERRIDE
{
320 virtual void DidProcessTask(const base::PendingTask
& pending_task
) OVERRIDE
{
321 #if !defined(OS_IOS) // No ProcessMetrics on IOS.
322 scoped_ptr
<base::ProcessMetrics
> process_metrics(
323 base::ProcessMetrics::CreateProcessMetrics(
324 #if defined(OS_MACOSX)
325 base::GetCurrentProcessHandle(), NULL
));
327 base::GetCurrentProcessHandle()));
329 size_t private_bytes
;
330 process_metrics
->GetMemoryBytes(&private_bytes
, NULL
);
331 LOCAL_HISTOGRAM_MEMORY_KB("Memory.BrowserUsed", private_bytes
>> 10);
335 DISALLOW_COPY_AND_ASSIGN(MemoryObserver
);
339 // BrowserMainLoop construction / destruction =============================
341 BrowserMainLoop
* BrowserMainLoop::GetInstance() {
342 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
343 return g_current_browser_main_loop
;
346 BrowserMainLoop::BrowserMainLoop(const MainFunctionParams
& parameters
)
347 : parameters_(parameters
),
348 parsed_command_line_(parameters
.command_line
),
349 result_code_(RESULT_CODE_NORMAL_EXIT
),
350 created_threads_(false),
351 // ContentMainRunner should have enabled tracing of the browser process
352 // when kTraceStartup is in the command line.
354 parameters
.command_line
.HasSwitch(switches::kTraceStartup
)) {
355 DCHECK(!g_current_browser_main_loop
);
356 g_current_browser_main_loop
= this;
359 BrowserMainLoop::~BrowserMainLoop() {
360 DCHECK_EQ(this, g_current_browser_main_loop
);
362 ui::Clipboard::DestroyClipboardForCurrentThread();
363 #endif // !defined(OS_IOS)
364 g_current_browser_main_loop
= NULL
;
367 void BrowserMainLoop::Init() {
368 TRACE_EVENT0("startup", "BrowserMainLoop::Init");
370 GetContentClient()->browser()->CreateBrowserMainParts(parameters_
));
373 // BrowserMainLoop stages ==================================================
375 void BrowserMainLoop::EarlyInitialization() {
376 TRACE_EVENT0("startup", "BrowserMainLoop::EarlyInitialization");
378 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
379 // No thread should be created before this call, as SetupSandbox()
380 // will end-up using fork().
381 SetupSandbox(parsed_command_line_
);
385 if (parsed_command_line_
.HasSwitch(switches::kSingleProcess
) ||
386 parsed_command_line_
.HasSwitch(switches::kInProcessGPU
)) {
387 if (!gfx::InitializeThreadedX11()) {
388 LOG(ERROR
) << "Failed to put Xlib into threaded mode.";
393 // GLib's spawning of new processes is buggy, so it's important that at this
394 // point GLib does not need to start DBUS. Chrome should always start with
395 // DBUS_SESSION_BUS_ADDRESS properly set. See crbug.com/309093.
396 #if defined(USE_GLIB)
397 // g_type_init will be deprecated in 2.36. 2.35 is the development
398 // version for 2.36, hence do not call g_type_init starting 2.35.
399 // http://developer.gnome.org/gobject/unstable/gobject-Type-Information.html#g-type-init
400 #if !GLIB_CHECK_VERSION(2, 35, 0)
401 // GLib type system initialization. Needed at least for gconf,
402 // used in net/proxy/proxy_config_service_linux.cc. Most likely
403 // this is superfluous as gtk_init() ought to do this. It's
404 // definitely harmless, so retained as a reminder of this
405 // requirement for gconf.
409 SetUpGLibLogHandler();
413 parts_
->PreEarlyInitialization();
415 #if defined(OS_MACOSX)
416 // We use quite a few file descriptors for our IPC, and the default limit on
417 // the Mac is low (256), so bump it up.
418 base::SetFdLimit(1024);
422 net::EnsureWinsockInit();
425 #if !defined(USE_OPENSSL)
426 // We want to be sure to init NSPR on the main thread.
427 crypto::EnsureNSPRInit();
428 #endif // !defined(USE_OPENSSL)
431 if (parsed_command_line_
.HasSwitch(switches::kRendererProcessLimit
)) {
432 std::string limit_string
= parsed_command_line_
.GetSwitchValueASCII(
433 switches::kRendererProcessLimit
);
434 size_t process_limit
;
435 if (base::StringToSizeT(limit_string
, &process_limit
)) {
436 RenderProcessHost::SetMaxRendererProcessCount(process_limit
);
439 #endif // !defined(OS_IOS)
442 parts_
->PostEarlyInitialization();
445 void BrowserMainLoop::MainMessageLoopStart() {
446 TRACE_EVENT0("startup", "BrowserMainLoop::MainMessageLoopStart");
448 TRACE_EVENT0("startup",
449 "BrowserMainLoop::MainMessageLoopStart:PreMainMessageLoopStart");
450 parts_
->PreMainMessageLoopStart();
454 // If we're running tests (ui_task is non-null), then the ResourceBundle
455 // has already been initialized.
456 if (!parameters_
.ui_task
) {
457 // Override the configured locale with the user's preferred UI language.
458 l10n_util::OverrideLocaleWithUILanguageList();
462 // Create a MessageLoop if one does not already exist for the current thread.
463 if (!base::MessageLoop::current())
464 main_message_loop_
.reset(new base::MessageLoopForUI
);
466 InitializeMainThread();
469 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SystemMonitor");
470 system_monitor_
.reset(new base::SystemMonitor
);
473 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:PowerMonitor");
474 scoped_ptr
<base::PowerMonitorSource
> power_monitor_source(
475 new base::PowerMonitorDeviceSource());
476 power_monitor_
.reset(new base::PowerMonitor(power_monitor_source
.Pass()));
479 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:HighResTimerManager");
480 hi_res_timer_manager_
.reset(new base::HighResolutionTimerManager
);
483 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:NetworkChangeNotifier");
484 network_change_notifier_
.reset(net::NetworkChangeNotifier::Create());
489 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MediaFeatures");
490 media::InitializeCPUSpecificMediaFeatures();
493 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:AudioMan");
494 audio_manager_
.reset(media::AudioManager::Create(
495 MediaInternals::GetInstance()));
498 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MidiManager");
499 midi_manager_
.reset(media::MidiManager::Create());
502 TRACE_EVENT0("startup",
503 "BrowserMainLoop::Subsystem:ContentWebUIController");
504 WebUIControllerFactory::RegisterFactory(
505 ContentWebUIControllerFactory::GetInstance());
509 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:OnlineStateObserver");
510 online_state_observer_
.reset(new BrowserOnlineStateObserver
);
514 system_stats_monitor_
.reset(new base::debug::TraceEventSystemStatsMonitor(
515 base::ThreadTaskRunnerHandle::Get()));
517 #endif // !defined(OS_IOS)
520 system_message_window_
.reset(new SystemMessageWindowWin
);
524 parts_
->PostMainMessageLoopStart();
527 // Start tracing to a file if needed. Only do this after starting the main
528 // message loop to avoid calling MessagePumpForUI::ScheduleWork() before
529 // MessagePumpForUI::Start() as it will crash the browser.
530 if (is_tracing_startup_
) {
531 TRACE_EVENT0("startup", "BrowserMainLoop::InitStartupTracing");
532 InitStartupTracing(parsed_command_line_
);
534 #endif // !defined(OS_IOS)
536 #if defined(OS_ANDROID)
538 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SurfaceTexturePeer");
539 SurfaceTexturePeer::InitInstance(new SurfaceTexturePeerBrowserImpl());
543 if (parsed_command_line_
.HasSwitch(switches::kMemoryMetrics
)) {
544 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MemoryObserver");
545 memory_observer_
.reset(new MemoryObserver());
546 base::MessageLoop::current()->AddTaskObserver(memory_observer_
.get());
549 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
550 trace_memory_controller_
.reset(new base::debug::TraceMemoryController(
551 base::MessageLoop::current()->message_loop_proxy(),
552 ::HeapProfilerWithPseudoStackStart
,
558 int BrowserMainLoop::PreCreateThreads() {
560 TRACE_EVENT0("startup",
561 "BrowserMainLoop::CreateThreads:PreCreateThreads");
562 result_code_
= parts_
->PreCreateThreads();
565 #if defined(ENABLE_PLUGINS)
566 // Prior to any processing happening on the io thread, we create the
567 // plugin service as it is predominantly used from the io thread,
568 // but must be created on the main thread. The service ctor is
569 // inexpensive and does not invoke the io_thread() accessor.
571 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads:PluginService");
572 PluginService::GetInstance()->Init();
576 #if !defined(OS_IOS) && (!defined(GOOGLE_CHROME_BUILD) || defined(OS_ANDROID))
577 // Single-process is an unsupported and not fully tested mode, so
578 // don't enable it for official Chrome builds (except on Android).
579 if (parsed_command_line_
.HasSwitch(switches::kSingleProcess
))
580 RenderProcessHost::SetRunRendererInProcess(true);
585 void BrowserMainLoop::CreateStartupTasks() {
586 TRACE_EVENT0("startup", "BrowserMainLoop::CreateStartupTasks");
588 // First time through, we really want to create all the tasks
589 if (!startup_task_runner_
.get()) {
590 #if defined(OS_ANDROID)
591 startup_task_runner_
= make_scoped_ptr(new StartupTaskRunner(
592 base::Bind(&BrowserStartupComplete
),
593 base::MessageLoop::current()->message_loop_proxy()));
595 startup_task_runner_
= make_scoped_ptr(new StartupTaskRunner(
596 base::Callback
<void(int)>(),
597 base::MessageLoop::current()->message_loop_proxy()));
599 StartupTask pre_create_threads
=
600 base::Bind(&BrowserMainLoop::PreCreateThreads
, base::Unretained(this));
601 startup_task_runner_
->AddTask(pre_create_threads
);
603 StartupTask create_threads
=
604 base::Bind(&BrowserMainLoop::CreateThreads
, base::Unretained(this));
605 startup_task_runner_
->AddTask(create_threads
);
607 StartupTask browser_thread_started
= base::Bind(
608 &BrowserMainLoop::BrowserThreadsStarted
, base::Unretained(this));
609 startup_task_runner_
->AddTask(browser_thread_started
);
611 StartupTask pre_main_message_loop_run
= base::Bind(
612 &BrowserMainLoop::PreMainMessageLoopRun
, base::Unretained(this));
613 startup_task_runner_
->AddTask(pre_main_message_loop_run
);
615 #if defined(OS_ANDROID)
616 if (BrowserMayStartAsynchronously()) {
617 startup_task_runner_
->StartRunningTasksAsync();
621 #if defined(OS_ANDROID)
622 if (!BrowserMayStartAsynchronously()) {
623 // A second request for asynchronous startup can be ignored, so
624 // StartupRunningTasksAsync is only called first time through. If, however,
625 // this is a request for synchronous startup then it must override any
626 // previous call for async startup, so we call RunAllTasksNow()
628 startup_task_runner_
->RunAllTasksNow();
631 startup_task_runner_
->RunAllTasksNow();
635 int BrowserMainLoop::CreateThreads() {
636 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads");
638 base::Thread::Options io_message_loop_options
;
639 io_message_loop_options
.message_loop_type
= base::MessageLoop::TYPE_IO
;
640 base::Thread::Options ui_message_loop_options
;
641 ui_message_loop_options
.message_loop_type
= base::MessageLoop::TYPE_UI
;
643 // Start threads in the order they occur in the BrowserThread::ID
644 // enumeration, except for BrowserThread::UI which is the main
647 // Must be size_t so we can increment it.
648 for (size_t thread_id
= BrowserThread::UI
+ 1;
649 thread_id
< BrowserThread::ID_COUNT
;
651 scoped_ptr
<BrowserProcessSubThread
>* thread_to_start
= NULL
;
652 base::Thread::Options options
;
655 case BrowserThread::DB
:
656 TRACE_EVENT_BEGIN1("startup",
657 "BrowserMainLoop::CreateThreads:start",
658 "Thread", "BrowserThread::DB");
659 thread_to_start
= &db_thread_
;
660 options
.timer_slack
= base::TIMER_SLACK_MAXIMUM
;
662 case BrowserThread::FILE_USER_BLOCKING
:
663 TRACE_EVENT_BEGIN1("startup",
664 "BrowserMainLoop::CreateThreads:start",
665 "Thread", "BrowserThread::FILE_USER_BLOCKING");
666 thread_to_start
= &file_user_blocking_thread_
;
668 case BrowserThread::FILE:
669 TRACE_EVENT_BEGIN1("startup",
670 "BrowserMainLoop::CreateThreads:start",
671 "Thread", "BrowserThread::FILE");
672 thread_to_start
= &file_thread_
;
674 // On Windows, the FILE thread needs to be have a UI message loop
675 // which pumps messages in such a way that Google Update can
676 // communicate back to us.
677 options
= ui_message_loop_options
;
679 options
= io_message_loop_options
;
681 options
.timer_slack
= base::TIMER_SLACK_MAXIMUM
;
683 case BrowserThread::PROCESS_LAUNCHER
:
684 TRACE_EVENT_BEGIN1("startup",
685 "BrowserMainLoop::CreateThreads:start",
686 "Thread", "BrowserThread::PROCESS_LAUNCHER");
687 thread_to_start
= &process_launcher_thread_
;
688 options
.timer_slack
= base::TIMER_SLACK_MAXIMUM
;
690 case BrowserThread::CACHE
:
691 TRACE_EVENT_BEGIN1("startup",
692 "BrowserMainLoop::CreateThreads:start",
693 "Thread", "BrowserThread::CACHE");
694 thread_to_start
= &cache_thread_
;
695 options
= io_message_loop_options
;
696 options
.timer_slack
= base::TIMER_SLACK_MAXIMUM
;
698 case BrowserThread::IO
:
699 TRACE_EVENT_BEGIN1("startup",
700 "BrowserMainLoop::CreateThreads:start",
701 "Thread", "BrowserThread::IO");
702 thread_to_start
= &io_thread_
;
703 options
= io_message_loop_options
;
705 case BrowserThread::UI
:
706 case BrowserThread::ID_COUNT
:
712 BrowserThread::ID id
= static_cast<BrowserThread::ID
>(thread_id
);
714 if (thread_to_start
) {
715 (*thread_to_start
).reset(new BrowserProcessSubThread(id
));
716 (*thread_to_start
)->StartWithOptions(options
);
721 TRACE_EVENT_END0("startup", "BrowserMainLoop::CreateThreads:start");
723 created_threads_
= true;
727 int BrowserMainLoop::PreMainMessageLoopRun() {
729 TRACE_EVENT0("startup",
730 "BrowserMainLoop::CreateThreads:PreMainMessageLoopRun");
731 parts_
->PreMainMessageLoopRun();
734 // If the UI thread blocks, the whole UI is unresponsive.
735 // Do not allow disk IO from the UI thread.
736 base::ThreadRestrictions::SetIOAllowed(false);
737 base::ThreadRestrictions::DisallowWaiting();
741 void BrowserMainLoop::RunMainMessageLoopParts() {
742 TRACE_EVENT_BEGIN_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
744 bool ran_main_loop
= false;
746 ran_main_loop
= parts_
->MainMessageLoopRun(&result_code_
);
749 MainMessageLoopRun();
751 TRACE_EVENT_END_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
754 void BrowserMainLoop::ShutdownThreadsAndCleanUp() {
755 if (!created_threads_
) {
756 // Called early, nothing to do
759 TRACE_EVENT0("shutdown", "BrowserMainLoop::ShutdownThreadsAndCleanUp");
761 // Teardown may start in PostMainMessageLoopRun, and during teardown we
762 // need to be able to perform IO.
763 base::ThreadRestrictions::SetIOAllowed(true);
764 BrowserThread::PostTask(
765 BrowserThread::IO
, FROM_HERE
,
766 base::Bind(base::IgnoreResult(&base::ThreadRestrictions::SetIOAllowed
),
770 if (RenderProcessHost::run_renderer_in_process())
771 RenderProcessHostImpl::ShutDownInProcessRenderer();
775 TRACE_EVENT0("shutdown",
776 "BrowserMainLoop::Subsystem:PostMainMessageLoopRun");
777 parts_
->PostMainMessageLoopRun();
780 trace_memory_controller_
.reset();
781 system_stats_monitor_
.reset();
784 // Destroying the GpuProcessHostUIShims on the UI thread posts a task to
785 // delete related objects on the GPU thread. This must be done before
786 // stopping the GPU thread. The GPU thread will close IPC channels to renderer
787 // processes so this has to happen before stopping the IO thread.
789 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUProcessHostShim");
790 GpuProcessHostUIShim::DestroyAll();
792 // Cancel pending requests and prevent new requests.
793 if (resource_dispatcher_host_
) {
794 TRACE_EVENT0("shutdown",
795 "BrowserMainLoop::Subsystem:ResourceDispatcherHost");
796 resource_dispatcher_host_
.get()->Shutdown();
799 #if defined(USE_AURA) || defined(OS_MACOSX)
800 if (ShouldInitializeBrowserGpuChannelAndTransportSurface()) {
801 TRACE_EVENT0("shutdown",
802 "BrowserMainLoop::Subsystem:ImageTransportFactory");
803 ImageTransportFactory::Terminate();
807 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
808 ZygoteHostImpl::GetInstance()->TearDownAfterLastChild();
809 #endif // defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
811 // The device monitors are using |system_monitor_| as dependency, so delete
812 // them before |system_monitor_| goes away.
813 // On Mac and windows, the monitor needs to be destroyed on the same thread
814 // as they were created. On Linux, the monitor will be deleted when IO thread
817 system_message_window_
.reset();
818 #elif defined(OS_MACOSX)
819 device_monitor_mac_
.reset();
821 #endif // !defined(OS_IOS)
823 // Must be size_t so we can subtract from it.
824 for (size_t thread_id
= BrowserThread::ID_COUNT
- 1;
825 thread_id
>= (BrowserThread::UI
+ 1);
827 // Find the thread object we want to stop. Looping over all valid
828 // BrowserThread IDs and DCHECKing on a missing case in the switch
829 // statement helps avoid a mismatch between this code and the
830 // BrowserThread::ID enumeration.
832 // The destruction order is the reverse order of occurrence in the
833 // BrowserThread::ID list. The rationale for the order is as
834 // follows (need to be filled in a bit):
837 // - The IO thread is the only user of the CACHE thread.
839 // - The PROCESS_LAUNCHER thread must be stopped after IO in case
840 // the IO thread posted a task to terminate a process on the
841 // process launcher thread.
843 // - (Not sure why DB stops last.)
845 case BrowserThread::DB
: {
846 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DBThread");
847 ResetThread_DB(db_thread_
.Pass());
850 case BrowserThread::FILE: {
851 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:FileThread");
853 // Clean up state that lives on or uses the file_thread_ before
855 if (resource_dispatcher_host_
)
856 resource_dispatcher_host_
.get()->save_file_manager()->Shutdown();
857 #endif // !defined(OS_IOS)
858 ResetThread_FILE(file_thread_
.Pass());
861 case BrowserThread::FILE_USER_BLOCKING
: {
862 TRACE_EVENT0("shutdown",
863 "BrowserMainLoop::Subsystem:FileUserBlockingThread");
864 ResetThread_FILE_USER_BLOCKING(file_user_blocking_thread_
.Pass());
867 case BrowserThread::PROCESS_LAUNCHER
: {
868 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:LauncherThread");
869 ResetThread_PROCESS_LAUNCHER(process_launcher_thread_
.Pass());
872 case BrowserThread::CACHE
: {
873 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:CacheThread");
874 ResetThread_CACHE(cache_thread_
.Pass());
877 case BrowserThread::IO
: {
878 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IOThread");
879 ResetThread_IO(io_thread_
.Pass());
882 case BrowserThread::UI
:
883 case BrowserThread::ID_COUNT
:
892 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IndexedDBThread");
893 ResetThread_IndexedDb(indexed_db_thread_
.Pass());
897 // Close the blocking I/O pool after the other threads. Other threads such
898 // as the I/O thread may need to schedule work like closing files or flushing
899 // data during shutdown, so the blocking pool needs to be available. There
900 // may also be slow operations pending that will blcok shutdown, so closing
901 // it here (which will block until required operations are complete) gives
902 // more head start for those operations to finish.
904 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:ThreadPool");
905 BrowserThreadImpl::ShutdownThreadPool();
909 // Must happen after the IO thread is shutdown since this may be accessed from
912 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUChannelFactory");
913 if (BrowserGpuChannelHostFactory::instance())
914 BrowserGpuChannelHostFactory::Terminate();
917 // Must happen after the I/O thread is shutdown since this class lives on the
918 // I/O thread and isn't threadsafe.
920 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GamepadService");
921 GamepadService::GetInstance()->Terminate();
924 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:SensorService");
925 DeviceInertialSensorService::GetInstance()->Shutdown();
928 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:BatteryStatusService");
929 BatteryStatusService::GetInstance()->Shutdown();
932 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DeleteDataSources");
933 URLDataManager::DeleteDataSources();
935 #endif // !defined(OS_IOS)
938 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:PostDestroyThreads");
939 parts_
->PostDestroyThreads();
943 void BrowserMainLoop::StopStartupTracingTimer() {
944 startup_trace_timer_
.Stop();
947 void BrowserMainLoop::InitializeMainThread() {
948 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeMainThread");
949 const char* kThreadName
= "CrBrowserMain";
950 base::PlatformThread::SetName(kThreadName
);
951 if (main_message_loop_
)
952 main_message_loop_
->set_thread_name(kThreadName
);
954 // Register the main thread by instantiating it, but don't call any methods.
956 new BrowserThreadImpl(BrowserThread::UI
, base::MessageLoop::current()));
959 int BrowserMainLoop::BrowserThreadsStarted() {
960 TRACE_EVENT0("startup", "BrowserMainLoop::BrowserThreadsStarted");
963 indexed_db_thread_
.reset(new base::Thread("IndexedDB"));
964 indexed_db_thread_
->Start();
967 #if defined(OS_ANDROID)
968 // Up the priority of anything that touches with display tasks
969 // (this thread is UI thread, and io_thread_ is for IPCs).
970 io_thread_
->SetPriority(base::kThreadPriority_Display
);
971 base::PlatformThread::SetThreadPriority(
972 base::PlatformThread::CurrentHandle(),
973 base::kThreadPriority_Display
);
977 HistogramSynchronizer::GetInstance();
979 bool initialize_gpu_data_manager
= true;
980 #if defined(OS_ANDROID)
981 // On Android, GLSurface::InitializeOneOff() must be called before initalizing
982 // the GpuDataManagerImpl as it uses the GL bindings. crbug.com/326295
983 if (!gfx::GLSurface::InitializeOneOff()) {
984 LOG(ERROR
) << "GLSurface::InitializeOneOff failed";
985 initialize_gpu_data_manager
= false;
989 // Initialize the GpuDataManager before we set up the MessageLoops because
990 // otherwise we'll trigger the assertion about doing IO on the UI thread.
991 if (initialize_gpu_data_manager
)
992 GpuDataManagerImpl::GetInstance()->Initialize();
994 bool always_uses_gpu
= true;
995 bool established_gpu_channel
= false;
996 #if defined(USE_AURA) || defined(OS_MACOSX)
997 if (ShouldInitializeBrowserGpuChannelAndTransportSurface()) {
998 established_gpu_channel
= true;
999 if (!GpuDataManagerImpl::GetInstance()->CanUseGpuBrowserCompositor()) {
1000 established_gpu_channel
= always_uses_gpu
= false;
1002 BrowserGpuChannelHostFactory::Initialize(established_gpu_channel
);
1003 ImageTransportFactory::Initialize();
1004 #if defined(USE_AURA)
1005 if (aura::Env::GetInstance()) {
1006 aura::Env::GetInstance()->set_context_factory(
1007 content::GetContextFactory());
1011 #elif defined(OS_ANDROID)
1012 established_gpu_channel
= true;
1013 BrowserGpuChannelHostFactory::Initialize(established_gpu_channel
);
1016 #if defined(OS_LINUX) && defined(USE_UDEV)
1017 device_monitor_linux_
.reset(new DeviceMonitorLinux());
1018 #elif defined(OS_MACOSX)
1019 device_monitor_mac_
.reset(new DeviceMonitorMac());
1022 // RDH needs the IO thread to be created
1024 TRACE_EVENT0("startup",
1025 "BrowserMainLoop::BrowserThreadsStarted:InitResourceDispatcherHost");
1026 resource_dispatcher_host_
.reset(new ResourceDispatcherHostImpl());
1029 // MediaStreamManager needs the IO thread to be created.
1031 TRACE_EVENT0("startup",
1032 "BrowserMainLoop::BrowserThreadsStarted:InitMediaStreamManager");
1033 media_stream_manager_
.reset(new MediaStreamManager(audio_manager_
.get()));
1037 TRACE_EVENT0("startup",
1038 "BrowserMainLoop::BrowserThreadsStarted:InitSpeechRecognition");
1039 speech_recognition_manager_
.reset(new SpeechRecognitionManagerImpl(
1040 audio_manager_
.get(), media_stream_manager_
.get()));
1046 "BrowserMainLoop::BrowserThreadsStarted::InitUserInputMonitor");
1047 user_input_monitor_
= media::UserInputMonitor::Create(
1048 io_thread_
->message_loop_proxy(), main_thread_
->message_loop_proxy());
1052 TRACE_EVENT0("startup",
1053 "BrowserMainLoop::BrowserThreadsStarted::TimeZoneMonitor");
1054 time_zone_monitor_
= TimeZoneMonitor::Create();
1057 // Alert the clipboard class to which threads are allowed to access the
1059 std::vector
<base::PlatformThreadId
> allowed_clipboard_threads
;
1060 // The current thread is the UI thread.
1061 allowed_clipboard_threads
.push_back(base::PlatformThread::CurrentId());
1063 // On Windows, clipboards are also used on the File or IO threads.
1064 allowed_clipboard_threads
.push_back(file_thread_
->thread_id());
1065 allowed_clipboard_threads
.push_back(io_thread_
->thread_id());
1067 ui::Clipboard::SetAllowedThreads(allowed_clipboard_threads
);
1069 // When running the GPU thread in-process, avoid optimistically starting it
1070 // since creating the GPU thread races against creation of the one-and-only
1071 // ChildProcess instance which is created by the renderer thread.
1072 if (GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL
) &&
1073 !established_gpu_channel
&&
1075 !parsed_command_line_
.HasSwitch(switches::kSingleProcess
) &&
1076 !parsed_command_line_
.HasSwitch(switches::kInProcessGPU
)) {
1077 TRACE_EVENT_INSTANT0("gpu", "Post task to launch GPU process",
1078 TRACE_EVENT_SCOPE_THREAD
);
1079 BrowserThread::PostTask(
1080 BrowserThread::IO
, FROM_HERE
, base::Bind(
1081 base::IgnoreResult(&GpuProcessHost::Get
),
1082 GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED
,
1083 CAUSE_FOR_GPU_LAUNCH_BROWSER_STARTUP
));
1086 #if defined(OS_MACOSX)
1087 ThemeHelperMac::GetInstance();
1088 SystemHotkeyHelperMac::GetInstance()->DeferredLoadSystemHotkeys();
1089 if (ShouldEnableBootstrapSandbox()) {
1090 TRACE_EVENT0("startup",
1091 "BrowserMainLoop::BrowserThreadsStarted:BootstrapSandbox");
1092 CHECK(GetBootstrapSandbox());
1094 #endif // defined(OS_MACOSX)
1096 #endif // !defined(OS_IOS)
1098 return result_code_
;
1101 bool BrowserMainLoop::InitializeToolkit() {
1102 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeToolkit");
1103 // TODO(evan): this function is rather subtle, due to the variety
1104 // of intersecting ifdefs we have. To keep it easy to follow, there
1105 // are no #else branches on any #ifs.
1106 // TODO(stevenjb): Move platform specific code into platform specific Parts
1107 // (Need to add InitializeToolkit stage to BrowserParts).
1108 // See also GTK setup in EarlyInitialization, above, and associated comments.
1111 // Init common control sex.
1112 INITCOMMONCONTROLSEX config
;
1113 config
.dwSize
= sizeof(config
);
1114 config
.dwICC
= ICC_WIN95_CLASSES
;
1115 if (!InitCommonControlsEx(&config
))
1119 #if defined(USE_AURA)
1121 #if defined(USE_X11)
1122 if (!gfx::GetXDisplay())
1126 // Env creates the compositor. Aura widgets need the compositor to be created
1127 // before they can be initialized by the browser.
1128 aura::Env::CreateInstance(true);
1129 #endif // defined(USE_AURA)
1132 parts_
->ToolkitInitialized();
1137 void BrowserMainLoop::MainMessageLoopRun() {
1138 #if defined(OS_ANDROID)
1139 // Android's main message loop is the Java message loop.
1142 DCHECK(base::MessageLoopForUI::IsCurrent());
1143 if (parameters_
.ui_task
)
1144 base::MessageLoopForUI::current()->PostTask(FROM_HERE
,
1145 *parameters_
.ui_task
);
1147 base::RunLoop run_loop
;
1152 base::FilePath
BrowserMainLoop::GetStartupTraceFileName(
1153 const base::CommandLine
& command_line
) const {
1154 base::FilePath trace_file
= command_line
.GetSwitchValuePath(
1155 switches::kTraceStartupFile
);
1156 // trace_file = "none" means that startup events will show up for the next
1157 // begin/end tracing (via about:tracing or AutomationProxy::BeginTracing/
1158 // EndTracing, for example).
1159 if (trace_file
== base::FilePath().AppendASCII("none"))
1162 if (trace_file
.empty()) {
1163 #if defined(OS_ANDROID)
1164 TracingControllerAndroid::GenerateTracingFilePath(&trace_file
);
1166 // Default to saving the startup trace into the current dir.
1167 trace_file
= base::FilePath().AppendASCII("chrometrace.log");
1174 void BrowserMainLoop::InitStartupTracing(
1175 const base::CommandLine
& command_line
) {
1176 DCHECK(is_tracing_startup_
);
1178 startup_trace_file_
= GetStartupTraceFileName(parsed_command_line_
);
1180 std::string delay_str
= command_line
.GetSwitchValueASCII(
1181 switches::kTraceStartupDuration
);
1183 if (!delay_str
.empty() && !base::StringToInt(delay_str
, &delay_secs
)) {
1184 DLOG(WARNING
) << "Could not parse --" << switches::kTraceStartupDuration
1185 << "=" << delay_str
<< " defaulting to 5 (secs)";
1189 startup_trace_timer_
.Start(FROM_HERE
,
1190 base::TimeDelta::FromSeconds(delay_secs
),
1192 &BrowserMainLoop::EndStartupTracing
);
1195 void BrowserMainLoop::EndStartupTracing() {
1196 is_tracing_startup_
= false;
1197 TracingController::GetInstance()->DisableRecording(
1198 startup_trace_file_
, base::Bind(&OnStoppedStartupTracing
));
1201 } // namespace content