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/threading/thread_restrictions.h"
24 #include "base/timer/hi_res_timer_manager.h"
25 #include "content/browser/browser_thread_impl.h"
26 #include "content/browser/device_orientation/device_inertial_sensor_service.h"
27 #include "content/browser/download/save_file_manager.h"
28 #include "content/browser/gamepad/gamepad_service.h"
29 #include "content/browser/gpu/browser_gpu_channel_host_factory.h"
30 #include "content/browser/gpu/compositor_util.h"
31 #include "content/browser/gpu/gpu_data_manager_impl.h"
32 #include "content/browser/gpu/gpu_process_host.h"
33 #include "content/browser/gpu/gpu_process_host_ui_shim.h"
34 #include "content/browser/histogram_synchronizer.h"
35 #include "content/browser/loader/resource_dispatcher_host_impl.h"
36 #include "content/browser/net/browser_online_state_observer.h"
37 #include "content/browser/plugin_service_impl.h"
38 #include "content/browser/renderer_host/media/audio_mirroring_manager.h"
39 #include "content/browser/renderer_host/media/media_stream_manager.h"
40 #include "content/browser/speech/speech_recognition_manager_impl.h"
41 #include "content/browser/startup_task_runner.h"
42 #include "content/browser/tracing/trace_controller_impl.h"
43 #include "content/browser/webui/content_web_ui_controller_factory.h"
44 #include "content/browser/webui/url_data_manager.h"
45 #include "content/public/browser/browser_main_parts.h"
46 #include "content/public/browser/browser_shutdown.h"
47 #include "content/public/browser/content_browser_client.h"
48 #include "content/public/browser/render_process_host.h"
49 #include "content/public/common/content_switches.h"
50 #include "content/public/common/main_function_params.h"
51 #include "content/public/common/result_codes.h"
52 #include "crypto/nss_util.h"
53 #include "media/audio/audio_manager.h"
54 #include "media/base/media.h"
55 #include "media/base/user_input_monitor.h"
56 #include "media/midi/midi_manager.h"
57 #include "net/base/network_change_notifier.h"
58 #include "net/socket/client_socket_factory.h"
59 #include "net/ssl/ssl_config_service.h"
60 #include "ui/base/clipboard/clipboard.h"
63 #include "content/browser/aura/image_transport_factory.h"
66 #if defined(OS_ANDROID)
67 #include "base/android/jni_android.h"
68 #include "content/browser/android/browser_startup_controller.h"
69 #include "content/browser/android/surface_texture_peer_browser_impl.h"
77 #include "base/win/text_services_message_filter.h"
78 #include "content/browser/system_message_window_win.h"
79 #include "content/common/sandbox_win.h"
80 #include "net/base/winsock_init.h"
81 #include "ui/base/l10n/l10n_util_win.h"
84 #if defined(OS_LINUX) || defined(OS_OPENBSD)
85 #include <glib-object.h>
89 #include "content/browser/device_monitor_linux.h"
90 #elif defined(OS_MACOSX) && !defined(OS_IOS)
91 #include "content/browser/device_monitor_mac.h"
94 #if defined(TOOLKIT_GTK)
95 #include "ui/gfx/gtk_util.h"
98 #if defined(OS_POSIX) && !defined(OS_MACOSX)
101 #include "content/browser/renderer_host/render_sandbox_host_linux.h"
102 #include "content/browser/zygote_host/zygote_host_impl_linux.h"
105 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
106 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
110 #include <X11/Xlib.h>
113 // One of the linux specific headers defines this as a macro.
121 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
122 void SetupSandbox(const CommandLine
& parsed_command_line
) {
123 TRACE_EVENT0("startup", "SetupSandbox");
124 // TODO(evanm): move this into SandboxWrapper; I'm just trying to move this
125 // code en masse out of chrome_main for now.
126 base::FilePath sandbox_binary
;
127 bool env_chrome_devel_sandbox_set
= false;
130 const bool want_setuid_sandbox
=
131 !parsed_command_line
.HasSwitch(switches::kNoSandbox
) &&
132 !parsed_command_line
.HasSwitch(switches::kDisableSetuidSandbox
);
134 if (want_setuid_sandbox
) {
135 base::FilePath exe_dir
;
136 if (PathService::Get(base::DIR_EXE
, &exe_dir
)) {
137 base::FilePath sandbox_candidate
= exe_dir
.AppendASCII("chrome-sandbox");
138 if (base::PathExists(sandbox_candidate
))
139 sandbox_binary
= sandbox_candidate
;
142 // In user-managed builds, including development builds, an environment
143 // variable is required to enable the sandbox. See
144 // http://code.google.com/p/chromium/wiki/LinuxSUIDSandboxDevelopment
145 if (sandbox_binary
.empty() &&
146 stat(base::kProcSelfExe
, &st
) == 0 && st
.st_uid
== getuid()) {
147 const char* devel_sandbox_path
= getenv("CHROME_DEVEL_SANDBOX");
148 if (devel_sandbox_path
) {
149 env_chrome_devel_sandbox_set
= true;
150 sandbox_binary
= base::FilePath(devel_sandbox_path
);
154 static const char no_suid_error
[] = "Running without the SUID sandbox! See "
155 "https://code.google.com/p/chromium/wiki/LinuxSUIDSandboxDevelopment "
156 "for more information on developing with the sandbox on.";
157 if (sandbox_binary
.empty()) {
158 if (!env_chrome_devel_sandbox_set
) {
159 // This needs to be fatal. Talk to security@chromium.org if you feel
161 LOG(FATAL
) << no_suid_error
;
164 // TODO(jln): an empty CHROME_DEVEL_SANDBOX environment variable (as
165 // opposed to a non existing one) is not fatal yet. This is needed
166 // because of existing bots and scripts. Fix it (crbug.com/245376).
167 LOG(ERROR
) << no_suid_error
;
171 // Tickle the sandbox host and zygote host so they fork now.
172 RenderSandboxHostLinux::GetInstance()->Init(sandbox_binary
.value());
173 ZygoteHostImpl::GetInstance()->Init(sandbox_binary
.value());
177 #if defined(OS_LINUX) || defined(OS_OPENBSD)
178 static void GLibLogHandler(const gchar
* log_domain
,
179 GLogLevelFlags log_level
,
180 const gchar
* message
,
183 log_domain
= "<unknown>";
185 message
= "<no message>";
187 if (strstr(message
, "Loading IM context type") ||
188 strstr(message
, "wrong ELF class: ELFCLASS64")) {
189 // http://crbug.com/9643
190 // Until we have a real 64-bit build or all of these 32-bit package issues
191 // are sorted out, don't fatal on ELF 32/64-bit mismatch warnings and don't
192 // spam the user with more than one of them.
193 static bool alerted
= false;
195 LOG(ERROR
) << "Bug 9643: " << log_domain
<< ": " << message
;
198 } else if (strstr(message
, "Unable to retrieve the file info for")) {
199 LOG(ERROR
) << "GTK File code error: " << message
;
200 } else if (strstr(message
, "Could not find the icon") &&
201 strstr(log_domain
, "Gtk")) {
202 LOG(ERROR
) << "GTK icon error: " << message
;
203 } else if (strstr(message
, "Theme file for default has no") ||
204 strstr(message
, "Theme directory") ||
205 strstr(message
, "theme pixmap") ||
206 strstr(message
, "locate theme engine")) {
207 LOG(ERROR
) << "GTK theme error: " << message
;
208 } else if (strstr(message
, "Unable to create Ubuntu Menu Proxy") &&
209 strstr(log_domain
, "<unknown>")) {
210 LOG(ERROR
) << "GTK menu proxy create failed";
211 } else if (strstr(message
, "gtk_drag_dest_leave: assertion")) {
212 LOG(ERROR
) << "Drag destination deleted: http://crbug.com/18557";
213 } else if (strstr(message
, "Out of memory") &&
214 strstr(log_domain
, "<unknown>")) {
215 LOG(ERROR
) << "DBus call timeout or out of memory: "
216 << "http://crosbug.com/15496";
217 } else if (strstr(message
, "Could not connect: Connection refused") &&
218 strstr(log_domain
, "<unknown>")) {
219 LOG(ERROR
) << "DConf settings backend could not connect to session bus: "
220 << "http://crbug.com/179797";
221 } else if (strstr(message
, "XDG_RUNTIME_DIR variable not set")) {
222 LOG(ERROR
) << message
<< " (http://bugs.chromium.org/97293)";
223 } else if (strstr(message
, "Attempting to store changes into") ||
224 strstr(message
, "Attempting to set the permissions of")) {
225 LOG(ERROR
) << message
<< " (http://bugs.chromium.org/161366)";
227 LOG(DFATAL
) << log_domain
<< ": " << message
;
231 static void SetUpGLibLogHandler() {
232 // Register GLib-handled assertions to go through our logging system.
233 const char* kLogDomains
[] = { NULL
, "Gtk", "Gdk", "GLib", "GLib-GObject" };
234 for (size_t i
= 0; i
< arraysize(kLogDomains
); i
++) {
235 g_log_set_handler(kLogDomains
[i
],
236 static_cast<GLogLevelFlags
>(G_LOG_FLAG_RECURSION
|
239 G_LOG_LEVEL_CRITICAL
|
240 G_LOG_LEVEL_WARNING
),
249 // The currently-running BrowserMainLoop. There can be one or zero.
250 BrowserMainLoop
* g_current_browser_main_loop
= NULL
;
252 // This is just to be able to keep ShutdownThreadsAndCleanUp out of
253 // the public interface of BrowserMainLoop.
254 class BrowserShutdownImpl
{
256 static void ImmediateShutdownAndExitProcess() {
257 DCHECK(g_current_browser_main_loop
);
258 g_current_browser_main_loop
->ShutdownThreadsAndCleanUp();
261 // At this point the message loop is still running yet we've shut everything
262 // down. If any messages are processed we'll likely crash. Exit now.
263 ExitProcess(RESULT_CODE_NORMAL_EXIT
);
264 #elif defined(OS_POSIX) && !defined(OS_MACOSX)
265 _exit(RESULT_CODE_NORMAL_EXIT
);
272 void ImmediateShutdownAndExitProcess() {
273 BrowserShutdownImpl::ImmediateShutdownAndExitProcess();
276 // For measuring memory usage after each task. Behind a command line flag.
277 class BrowserMainLoop::MemoryObserver
: public base::MessageLoop::TaskObserver
{
280 virtual ~MemoryObserver() {}
282 virtual void WillProcessTask(const base::PendingTask
& pending_task
) OVERRIDE
{
285 virtual void DidProcessTask(const base::PendingTask
& pending_task
) OVERRIDE
{
286 #if !defined(OS_IOS) // No ProcessMetrics on IOS.
287 scoped_ptr
<base::ProcessMetrics
> process_metrics(
288 base::ProcessMetrics::CreateProcessMetrics(
289 #if defined(OS_MACOSX)
290 base::GetCurrentProcessHandle(), NULL
));
292 base::GetCurrentProcessHandle()));
294 size_t private_bytes
;
295 process_metrics
->GetMemoryBytes(&private_bytes
, NULL
);
296 HISTOGRAM_MEMORY_KB("Memory.BrowserUsed", private_bytes
>> 10);
300 DISALLOW_COPY_AND_ASSIGN(MemoryObserver
);
304 // BrowserMainLoop construction / destruction =============================
306 BrowserMainLoop
* BrowserMainLoop::GetInstance() {
307 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
308 return g_current_browser_main_loop
;
311 BrowserMainLoop::BrowserMainLoop(const MainFunctionParams
& parameters
)
312 : parameters_(parameters
),
313 parsed_command_line_(parameters
.command_line
),
314 result_code_(RESULT_CODE_NORMAL_EXIT
),
315 created_threads_(false) {
316 DCHECK(!g_current_browser_main_loop
);
317 g_current_browser_main_loop
= this;
320 BrowserMainLoop::~BrowserMainLoop() {
321 DCHECK_EQ(this, g_current_browser_main_loop
);
323 ui::Clipboard::DestroyClipboardForCurrentThread();
324 #endif // !defined(OS_IOS)
325 g_current_browser_main_loop
= NULL
;
328 void BrowserMainLoop::Init() {
329 TRACE_EVENT0("startup", "BrowserMainLoop::Init")
331 GetContentClient()->browser()->CreateBrowserMainParts(parameters_
));
334 // BrowserMainLoop stages ==================================================
336 void BrowserMainLoop::EarlyInitialization() {
337 TRACE_EVENT0("startup", "BrowserMainLoop::EarlyInitialization");
339 if (parsed_command_line_
.HasSwitch(switches::kSingleProcess
) ||
340 parsed_command_line_
.HasSwitch(switches::kInProcessGPU
)) {
341 if (!XInitThreads()) {
342 LOG(ERROR
) << "Failed to put Xlib into threaded mode.";
348 parts_
->PreEarlyInitialization();
351 net::EnsureWinsockInit();
354 #if !defined(USE_OPENSSL)
355 // We want to be sure to init NSPR on the main thread.
356 crypto::EnsureNSPRInit();
357 #endif // !defined(USE_OPENSSL)
359 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
360 SetupSandbox(parsed_command_line_
);
363 if (parsed_command_line_
.HasSwitch(switches::kEnableSSLCachedInfo
))
364 net::SSLConfigService::EnableCachedInfo();
367 if (parsed_command_line_
.HasSwitch(switches::kRendererProcessLimit
)) {
368 std::string limit_string
= parsed_command_line_
.GetSwitchValueASCII(
369 switches::kRendererProcessLimit
);
370 size_t process_limit
;
371 if (base::StringToSizeT(limit_string
, &process_limit
)) {
372 RenderProcessHost::SetMaxRendererProcessCount(process_limit
);
375 #endif // !defined(OS_IOS)
378 parts_
->PostEarlyInitialization();
381 void BrowserMainLoop::MainMessageLoopStart() {
382 TRACE_EVENT0("startup", "BrowserMainLoop::MainMessageLoopStart")
384 TRACE_EVENT0("startup",
385 "BrowserMainLoop::MainMessageLoopStart:PreMainMessageLoopStart");
386 parts_
->PreMainMessageLoopStart();
390 // If we're running tests (ui_task is non-null), then the ResourceBundle
391 // has already been initialized.
392 if (!parameters_
.ui_task
) {
393 // Override the configured locale with the user's preferred UI language.
394 l10n_util::OverrideLocaleWithUILanguageList();
398 // Create a MessageLoop if one does not already exist for the current thread.
399 if (!base::MessageLoop::current())
400 main_message_loop_
.reset(new base::MessageLoop(base::MessageLoop::TYPE_UI
));
402 InitializeMainThread();
405 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SystemMonitor")
406 system_monitor_
.reset(new base::SystemMonitor
);
409 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:PowerMonitor")
410 scoped_ptr
<base::PowerMonitorSource
> power_monitor_source(
411 new base::PowerMonitorDeviceSource());
412 power_monitor_
.reset(new base::PowerMonitor(power_monitor_source
.Pass()));
415 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:HighResTimerManager")
416 hi_res_timer_manager_
.reset(new base::HighResolutionTimerManager
);
419 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:NetworkChangeNotifier")
420 network_change_notifier_
.reset(net::NetworkChangeNotifier::Create());
424 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MediaFeatures")
425 media::InitializeCPUSpecificMediaFeatures();
428 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:AudioMan")
429 audio_manager_
.reset(media::AudioManager::Create());
432 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MIDIManager")
433 midi_manager_
.reset(media::MIDIManager::Create());
438 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:ContentWebUIController")
439 WebUIControllerFactory::RegisterFactory(
440 ContentWebUIControllerFactory::GetInstance());
444 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:AudioMirroringManager")
445 audio_mirroring_manager_
.reset(new AudioMirroringManager());
448 // Start tracing to a file if needed.
449 if (base::debug::TraceLog::GetInstance()->IsEnabled()) {
450 TRACE_EVENT0("startup", "BrowserMainLoop::InitStartupTracing")
451 TraceControllerImpl::GetInstance()->InitStartupTracing(
452 parsed_command_line_
);
456 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:OnlineStateObserver")
457 online_state_observer_
.reset(new BrowserOnlineStateObserver
);
459 #endif // !defined(OS_IOS)
462 system_message_window_
.reset(new SystemMessageWindowWin
);
464 if (base::win::IsTSFAwareRequired()) {
465 // Create a TSF message filter for the message loop. MessageLoop takes
466 // ownership of the filter.
467 scoped_ptr
<base::win::TextServicesMessageFilter
> tsf_message_filter(
468 new base::win::TextServicesMessageFilter
);
469 if (tsf_message_filter
->Init()) {
470 base::MessageLoopForUI::current()->SetMessageFilter(
471 tsf_message_filter
.PassAs
<base::MessageLoopForUI::MessageFilter
>());
477 parts_
->PostMainMessageLoopStart();
479 #if defined(OS_ANDROID)
481 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SurfaceTexturePeer")
482 SurfaceTexturePeer::InitInstance(new SurfaceTexturePeerBrowserImpl());
486 if (parsed_command_line_
.HasSwitch(switches::kMemoryMetrics
)) {
487 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MemoryObserver")
488 memory_observer_
.reset(new MemoryObserver());
489 base::MessageLoop::current()->AddTaskObserver(memory_observer_
.get());
492 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
493 trace_memory_controller_
.reset(new base::debug::TraceMemoryController(
494 base::MessageLoop::current()->message_loop_proxy(),
495 ::HeapProfilerWithPseudoStackStart
,
501 int BrowserMainLoop::PreCreateThreads() {
504 TRACE_EVENT0("startup",
505 "BrowserMainLoop::CreateThreads:PreCreateThreads");
506 result_code_
= parts_
->PreCreateThreads();
509 #if defined(ENABLE_PLUGINS)
510 // Prior to any processing happening on the io thread, we create the
511 // plugin service as it is predominantly used from the io thread,
512 // but must be created on the main thread. The service ctor is
513 // inexpensive and does not invoke the io_thread() accessor.
515 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads:PluginService")
516 PluginService::GetInstance()->Init();
520 #if !defined(OS_IOS) && (!defined(GOOGLE_CHROME_BUILD) || defined(OS_ANDROID))
521 // Single-process is an unsupported and not fully tested mode, so
522 // don't enable it for official Chrome builds (except on Android).
523 if (parsed_command_line_
.HasSwitch(switches::kSingleProcess
))
524 RenderProcessHost::SetRunRendererInProcess(true);
529 void BrowserMainLoop::CreateStartupTasks() {
530 TRACE_EVENT0("startup", "BrowserMainLoop::CreateStartupTasks");
532 // First time through, we really want to create all the tasks
533 if (!startup_task_runner_
.get()) {
534 #if defined(OS_ANDROID)
535 startup_task_runner_
= make_scoped_ptr(new StartupTaskRunner(
536 base::Bind(&BrowserStartupComplete
),
537 base::MessageLoop::current()->message_loop_proxy()));
539 startup_task_runner_
= make_scoped_ptr(new StartupTaskRunner(
540 base::Callback
<void(int)>(),
541 base::MessageLoop::current()->message_loop_proxy()));
543 StartupTask pre_create_threads
=
544 base::Bind(&BrowserMainLoop::PreCreateThreads
, base::Unretained(this));
545 startup_task_runner_
->AddTask(pre_create_threads
);
547 StartupTask create_threads
=
548 base::Bind(&BrowserMainLoop::CreateThreads
, base::Unretained(this));
549 startup_task_runner_
->AddTask(create_threads
);
551 StartupTask browser_thread_started
= base::Bind(
552 &BrowserMainLoop::BrowserThreadsStarted
, base::Unretained(this));
553 startup_task_runner_
->AddTask(browser_thread_started
);
555 StartupTask pre_main_message_loop_run
= base::Bind(
556 &BrowserMainLoop::PreMainMessageLoopRun
, base::Unretained(this));
557 startup_task_runner_
->AddTask(pre_main_message_loop_run
);
559 #if defined(OS_ANDROID)
560 if (BrowserMayStartAsynchronously()) {
561 startup_task_runner_
->StartRunningTasksAsync();
565 #if defined(OS_ANDROID)
566 if (!BrowserMayStartAsynchronously()) {
567 // A second request for asynchronous startup can be ignored, so
568 // StartupRunningTasksAsync is only called first time through. If, however,
569 // this is a request for synchronous startup then it must override any
570 // previous call for async startup, so we call RunAllTasksNow()
572 startup_task_runner_
->RunAllTasksNow();
575 startup_task_runner_
->RunAllTasksNow();
579 int BrowserMainLoop::CreateThreads() {
580 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads");
582 base::Thread::Options default_options
;
583 base::Thread::Options io_message_loop_options
;
584 io_message_loop_options
.message_loop_type
= base::MessageLoop::TYPE_IO
;
585 base::Thread::Options ui_message_loop_options
;
586 ui_message_loop_options
.message_loop_type
= base::MessageLoop::TYPE_UI
;
588 // Start threads in the order they occur in the BrowserThread::ID
589 // enumeration, except for BrowserThread::UI which is the main
592 // Must be size_t so we can increment it.
593 for (size_t thread_id
= BrowserThread::UI
+ 1;
594 thread_id
< BrowserThread::ID_COUNT
;
596 scoped_ptr
<BrowserProcessSubThread
>* thread_to_start
= NULL
;
597 base::Thread::Options
* options
= &default_options
;
600 case BrowserThread::DB
:
601 TRACE_EVENT_BEGIN1("startup",
602 "BrowserMainLoop::CreateThreads:start",
603 "Thread", "BrowserThread::DB");
604 thread_to_start
= &db_thread_
;
606 case BrowserThread::FILE_USER_BLOCKING
:
607 TRACE_EVENT_BEGIN1("startup",
608 "BrowserMainLoop::CreateThreads:start",
609 "Thread", "BrowserThread::FILE_USER_BLOCKING");
610 thread_to_start
= &file_user_blocking_thread_
;
612 case BrowserThread::FILE:
613 TRACE_EVENT_BEGIN1("startup",
614 "BrowserMainLoop::CreateThreads:start",
615 "Thread", "BrowserThread::FILE");
616 thread_to_start
= &file_thread_
;
618 // On Windows, the FILE thread needs to be have a UI message loop
619 // which pumps messages in such a way that Google Update can
620 // communicate back to us.
621 options
= &ui_message_loop_options
;
623 options
= &io_message_loop_options
;
626 case BrowserThread::PROCESS_LAUNCHER
:
627 TRACE_EVENT_BEGIN1("startup",
628 "BrowserMainLoop::CreateThreads:start",
629 "Thread", "BrowserThread::PROCESS_LAUNCHER");
630 thread_to_start
= &process_launcher_thread_
;
632 case BrowserThread::CACHE
:
633 TRACE_EVENT_BEGIN1("startup",
634 "BrowserMainLoop::CreateThreads:start",
635 "Thread", "BrowserThread::CACHE");
636 thread_to_start
= &cache_thread_
;
637 options
= &io_message_loop_options
;
639 case BrowserThread::IO
:
640 TRACE_EVENT_BEGIN1("startup",
641 "BrowserMainLoop::CreateThreads:start",
642 "Thread", "BrowserThread::IO");
643 thread_to_start
= &io_thread_
;
644 options
= &io_message_loop_options
;
646 case BrowserThread::UI
:
647 case BrowserThread::ID_COUNT
:
653 BrowserThread::ID id
= static_cast<BrowserThread::ID
>(thread_id
);
655 if (thread_to_start
) {
656 (*thread_to_start
).reset(new BrowserProcessSubThread(id
));
657 (*thread_to_start
)->StartWithOptions(*options
);
662 TRACE_EVENT_END0("startup", "BrowserMainLoop::CreateThreads:start");
665 created_threads_
= true;
669 int BrowserMainLoop::PreMainMessageLoopRun() {
671 TRACE_EVENT0("startup",
672 "BrowserMainLoop::CreateThreads:PreMainMessageLoopRun");
673 parts_
->PreMainMessageLoopRun();
676 // If the UI thread blocks, the whole UI is unresponsive.
677 // Do not allow disk IO from the UI thread.
678 base::ThreadRestrictions::SetIOAllowed(false);
679 base::ThreadRestrictions::DisallowWaiting();
683 void BrowserMainLoop::RunMainMessageLoopParts() {
684 TRACE_EVENT_BEGIN_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
686 bool ran_main_loop
= false;
688 ran_main_loop
= parts_
->MainMessageLoopRun(&result_code_
);
691 MainMessageLoopRun();
693 TRACE_EVENT_END_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
696 void BrowserMainLoop::ShutdownThreadsAndCleanUp() {
698 if (!created_threads_
) {
699 // Called early, nothing to do
702 // Teardown may start in PostMainMessageLoopRun, and during teardown we
703 // need to be able to perform IO.
704 base::ThreadRestrictions::SetIOAllowed(true);
705 BrowserThread::PostTask(
706 BrowserThread::IO
, FROM_HERE
,
707 base::Bind(base::IgnoreResult(&base::ThreadRestrictions::SetIOAllowed
),
711 parts_
->PostMainMessageLoopRun();
713 trace_memory_controller_
.reset();
716 // Destroying the GpuProcessHostUIShims on the UI thread posts a task to
717 // delete related objects on the GPU thread. This must be done before
718 // stopping the GPU thread. The GPU thread will close IPC channels to renderer
719 // processes so this has to happen before stopping the IO thread.
720 GpuProcessHostUIShim::DestroyAll();
722 // Cancel pending requests and prevent new requests.
723 if (resource_dispatcher_host_
)
724 resource_dispatcher_host_
.get()->Shutdown();
726 #if defined(USE_AURA)
727 ImageTransportFactory::Terminate();
730 // The device monitors are using |system_monitor_| as dependency, so delete
731 // them before |system_monitor_| goes away.
732 // On Mac and windows, the monitor needs to be destroyed on the same thread
733 // as they were created. On Linux, the monitor will be deleted when IO thread
736 system_message_window_
.reset();
737 #elif defined(OS_MACOSX)
738 device_monitor_mac_
.reset();
740 #endif // !defined(OS_IOS)
742 // Must be size_t so we can subtract from it.
743 for (size_t thread_id
= BrowserThread::ID_COUNT
- 1;
744 thread_id
>= (BrowserThread::UI
+ 1);
746 // Find the thread object we want to stop. Looping over all valid
747 // BrowserThread IDs and DCHECKing on a missing case in the switch
748 // statement helps avoid a mismatch between this code and the
749 // BrowserThread::ID enumeration.
751 // The destruction order is the reverse order of occurrence in the
752 // BrowserThread::ID list. The rationale for the order is as
753 // follows (need to be filled in a bit):
756 // - The IO thread is the only user of the CACHE thread.
758 // - The PROCESS_LAUNCHER thread must be stopped after IO in case
759 // the IO thread posted a task to terminate a process on the
760 // process launcher thread.
762 // - (Not sure why DB stops last.)
764 case BrowserThread::DB
:
767 case BrowserThread::FILE_USER_BLOCKING
:
768 file_user_blocking_thread_
.reset();
770 case BrowserThread::FILE:
772 // Clean up state that lives on or uses the file_thread_ before
774 if (resource_dispatcher_host_
)
775 resource_dispatcher_host_
.get()->save_file_manager()->Shutdown();
776 #endif // !defined(OS_IOS)
777 file_thread_
.reset();
779 case BrowserThread::PROCESS_LAUNCHER
:
780 process_launcher_thread_
.reset();
782 case BrowserThread::CACHE
:
783 cache_thread_
.reset();
785 case BrowserThread::IO
:
788 case BrowserThread::UI
:
789 case BrowserThread::ID_COUNT
:
797 indexed_db_thread_
.reset();
800 // Close the blocking I/O pool after the other threads. Other threads such
801 // as the I/O thread may need to schedule work like closing files or flushing
802 // data during shutdown, so the blocking pool needs to be available. There
803 // may also be slow operations pending that will blcok shutdown, so closing
804 // it here (which will block until required operations are complete) gives
805 // more head start for those operations to finish.
806 BrowserThreadImpl::ShutdownThreadPool();
809 // Must happen after the IO thread is shutdown since this may be accessed from
811 BrowserGpuChannelHostFactory::Terminate();
813 // Must happen after the I/O thread is shutdown since this class lives on the
814 // I/O thread and isn't threadsafe.
815 GamepadService::GetInstance()->Terminate();
816 DeviceInertialSensorService::GetInstance()->Shutdown();
818 URLDataManager::DeleteDataSources();
819 #endif // !defined(OS_IOS)
822 parts_
->PostDestroyThreads();
825 void BrowserMainLoop::InitializeMainThread() {
826 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeMainThread")
827 const char* kThreadName
= "CrBrowserMain";
828 base::PlatformThread::SetName(kThreadName
);
829 if (main_message_loop_
)
830 main_message_loop_
->set_thread_name(kThreadName
);
832 // Register the main thread by instantiating it, but don't call any methods.
834 new BrowserThreadImpl(BrowserThread::UI
, base::MessageLoop::current()));
837 int BrowserMainLoop::BrowserThreadsStarted() {
838 TRACE_EVENT0("startup", "BrowserMainLoop::BrowserThreadsStarted")
841 indexed_db_thread_
.reset(new base::Thread("IndexedDB"));
842 indexed_db_thread_
->Start();
845 #if defined(OS_ANDROID)
846 // Up the priority of anything that touches with display tasks
847 // (this thread is UI thread, and io_thread_ is for IPCs).
848 io_thread_
->SetPriority(base::kThreadPriority_Display
);
849 base::PlatformThread::SetThreadPriority(
850 base::PlatformThread::CurrentHandle(),
851 base::kThreadPriority_Display
);
855 HistogramSynchronizer::GetInstance();
857 BrowserGpuChannelHostFactory::Initialize();
858 #if defined(USE_AURA)
859 ImageTransportFactory::Initialize();
862 #if defined(OS_LINUX)
863 device_monitor_linux_
.reset(new DeviceMonitorLinux());
864 #elif defined(OS_MACOSX)
865 device_monitor_mac_
.reset(new DeviceMonitorMac());
868 // RDH needs the IO thread to be created
870 TRACE_EVENT0("startup",
871 "BrowserMainLoop::BrowserThreadsStarted:InitResourceDispatcherHost");
872 resource_dispatcher_host_
.reset(new ResourceDispatcherHostImpl());
875 // MediaStreamManager needs the IO thread to be created.
877 TRACE_EVENT0("startup",
878 "BrowserMainLoop::BrowserThreadsStarted:InitMediaStreamManager");
879 media_stream_manager_
.reset(new MediaStreamManager(audio_manager_
.get()));
882 // Initialize the GpuDataManager before we set up the MessageLoops because
883 // otherwise we'll trigger the assertion about doing IO on the UI thread.
884 GpuDataManagerImpl::GetInstance()->Initialize();
887 TRACE_EVENT0("startup",
888 "BrowserMainLoop::BrowserThreadsStarted:InitSpeechRecognition");
889 speech_recognition_manager_
.reset(new SpeechRecognitionManagerImpl(
890 audio_manager_
.get(), media_stream_manager_
.get()));
896 "BrowserMainLoop::BrowserThreadsStarted::InitUserInputMonitor");
897 user_input_monitor_
= media::UserInputMonitor::Create(
898 io_thread_
->message_loop_proxy(), main_thread_
->message_loop_proxy());
901 // Alert the clipboard class to which threads are allowed to access the
903 std::vector
<base::PlatformThreadId
> allowed_clipboard_threads
;
904 // The current thread is the UI thread.
905 allowed_clipboard_threads
.push_back(base::PlatformThread::CurrentId());
907 // On Windows, clipboards are also used on the File or IO threads.
908 allowed_clipboard_threads
.push_back(file_thread_
->thread_id());
909 allowed_clipboard_threads
.push_back(io_thread_
->thread_id());
911 ui::Clipboard::SetAllowedThreads(allowed_clipboard_threads
);
913 // When running the GPU thread in-process, avoid optimistically starting it
914 // since creating the GPU thread races against creation of the one-and-only
915 // ChildProcess instance which is created by the renderer thread.
916 bool always_uses_gpu
= IsForceCompositingModeEnabled();
917 #if defined(USE_AURA)
918 if (!GpuDataManagerImpl::GetInstance()->CanUseGpuBrowserCompositor())
919 always_uses_gpu
= false;
921 if (GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL
) &&
923 !parsed_command_line_
.HasSwitch(switches::kDisableGpuProcessPrelaunch
) &&
924 !parsed_command_line_
.HasSwitch(switches::kSingleProcess
) &&
925 !parsed_command_line_
.HasSwitch(switches::kInProcessGPU
)) {
926 TRACE_EVENT_INSTANT0("gpu", "Post task to launch GPU process",
927 TRACE_EVENT_SCOPE_THREAD
);
928 BrowserThread::PostTask(
929 BrowserThread::IO
, FROM_HERE
, base::Bind(
930 base::IgnoreResult(&GpuProcessHost::Get
),
931 GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED
,
932 CAUSE_FOR_GPU_LAUNCH_BROWSER_STARTUP
));
934 #endif // !defined(OS_IOS)
938 void BrowserMainLoop::InitializeToolkit() {
939 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeToolkit")
940 // TODO(evan): this function is rather subtle, due to the variety
941 // of intersecting ifdefs we have. To keep it easy to follow, there
942 // are no #else branches on any #ifs.
943 // TODO(stevenjb): Move platform specific code into platform specific Parts
944 // (Need to add InitializeToolkit stage to BrowserParts).
945 #if defined(OS_LINUX) || defined(OS_OPENBSD)
946 // g_type_init will be deprecated in 2.36. 2.35 is the development
947 // version for 2.36, hence do not call g_type_init starting 2.35.
948 // http://developer.gnome.org/gobject/unstable/gobject-Type-Information.html#g-type-init
949 #if !GLIB_CHECK_VERSION(2, 35, 0)
950 // Glib type system initialization. Needed at least for gconf,
951 // used in net/proxy/proxy_config_service_linux.cc. Most likely
952 // this is superfluous as gtk_init() ought to do this. It's
953 // definitely harmless, so retained as a reminder of this
954 // requirement for gconf.
958 #if !defined(USE_AURA)
959 gfx::GtkInitFromCommandLine(parsed_command_line_
);
962 SetUpGLibLogHandler();
965 #if defined(TOOLKIT_GTK)
966 // It is important for this to happen before the first run dialog, as it
967 // styles the dialog as well.
972 // Init common control sex.
973 INITCOMMONCONTROLSEX config
;
974 config
.dwSize
= sizeof(config
);
975 config
.dwICC
= ICC_WIN95_CLASSES
;
976 if (!InitCommonControlsEx(&config
))
977 LOG_GETLASTERROR(FATAL
);
981 parts_
->ToolkitInitialized();
984 void BrowserMainLoop::MainMessageLoopRun() {
985 #if defined(OS_ANDROID)
986 // Android's main message loop is the Java message loop.
989 DCHECK_EQ(base::MessageLoop::TYPE_UI
, base::MessageLoop::current()->type());
990 if (parameters_
.ui_task
)
991 base::MessageLoopForUI::current()->PostTask(FROM_HERE
,
992 *parameters_
.ui_task
);
994 base::RunLoop run_loop
;
999 } // namespace content