Remove PlatformFile from profile_browsertest
[chromium-blink-merge.git] / content / browser / browser_main_loop.cc
blobab045e4fadab4008f4545ea6fdd1aaaadb4dded4
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"
7 #include "base/bind.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/browser_thread_impl.h"
27 #include "content/browser/device_orientation/device_inertial_sensor_service.h"
28 #include "content/browser/download/save_file_manager.h"
29 #include "content/browser/gamepad/gamepad_service.h"
30 #include "content/browser/gpu/browser_gpu_channel_host_factory.h"
31 #include "content/browser/gpu/compositor_util.h"
32 #include "content/browser/gpu/gpu_data_manager_impl.h"
33 #include "content/browser/gpu/gpu_process_host.h"
34 #include "content/browser/gpu/gpu_process_host_ui_shim.h"
35 #include "content/browser/histogram_synchronizer.h"
36 #include "content/browser/loader/resource_dispatcher_host_impl.h"
37 #include "content/browser/media/capture/audio_mirroring_manager.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/renderer_host/render_process_host_impl.h"
43 #include "content/browser/speech/speech_recognition_manager_impl.h"
44 #include "content/browser/startup_task_runner.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)
66 #include "content/browser/compositor/image_transport_factory.h"
67 #endif
69 #if defined(OS_ANDROID)
70 #include "base/android/jni_android.h"
71 #include "content/browser/android/browser_startup_controller.h"
72 #include "content/browser/android/surface_texture_peer_browser_impl.h"
73 #include "ui/gl/gl_surface.h"
74 #endif
76 #if defined(OS_MACOSX) && !defined(OS_IOS)
77 #include "content/browser/theme_helper_mac.h"
78 #endif
80 #if defined(OS_WIN)
81 #include <windows.h>
82 #include <commctrl.h>
83 #include <shellapi.h>
85 #include "content/browser/system_message_window_win.h"
86 #include "content/common/sandbox_win.h"
87 #include "net/base/winsock_init.h"
88 #include "ui/base/l10n/l10n_util_win.h"
89 #endif
91 #if defined(USE_GLIB)
92 #include <glib-object.h>
93 #endif
95 #if defined(OS_LINUX) && defined(USE_UDEV)
96 #include "content/browser/device_monitor_udev.h"
97 #elif defined(OS_MACOSX) && !defined(OS_IOS)
98 #include "content/browser/device_monitor_mac.h"
99 #endif
101 #if defined(TOOLKIT_GTK)
102 #include "ui/gfx/gtk_util.h"
103 #endif
105 #if defined(OS_POSIX) && !defined(OS_MACOSX)
106 #include <sys/stat.h>
108 #include "content/browser/renderer_host/render_sandbox_host_linux.h"
109 #include "content/browser/zygote_host/zygote_host_impl_linux.h"
110 #endif
112 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
113 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
114 #endif
116 #if defined(USE_X11)
117 #include <X11/Xlib.h>
118 #endif
120 #if defined(USE_OZONE)
121 #include "ui/ozone/ozone_platform.h"
122 #endif
124 // One of the linux specific headers defines this as a macro.
125 #ifdef DestroyAll
126 #undef DestroyAll
127 #endif
129 namespace content {
130 namespace {
132 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
133 void SetupSandbox(const CommandLine& parsed_command_line) {
134 TRACE_EVENT0("startup", "SetupSandbox");
135 // TODO(evanm): move this into SandboxWrapper; I'm just trying to move this
136 // code en masse out of chrome_main for now.
137 base::FilePath sandbox_binary;
138 bool env_chrome_devel_sandbox_set = false;
139 struct stat st;
141 const bool want_setuid_sandbox =
142 !parsed_command_line.HasSwitch(switches::kNoSandbox) &&
143 !parsed_command_line.HasSwitch(switches::kDisableSetuidSandbox);
145 if (want_setuid_sandbox) {
146 base::FilePath exe_dir;
147 if (PathService::Get(base::DIR_EXE, &exe_dir)) {
148 base::FilePath sandbox_candidate = exe_dir.AppendASCII("chrome-sandbox");
149 if (base::PathExists(sandbox_candidate))
150 sandbox_binary = sandbox_candidate;
153 // In user-managed builds, including development builds, an environment
154 // variable is required to enable the sandbox. See
155 // http://code.google.com/p/chromium/wiki/LinuxSUIDSandboxDevelopment
156 if (sandbox_binary.empty() &&
157 stat(base::kProcSelfExe, &st) == 0 && st.st_uid == getuid()) {
158 const char* devel_sandbox_path = getenv("CHROME_DEVEL_SANDBOX");
159 if (devel_sandbox_path) {
160 env_chrome_devel_sandbox_set = true;
161 sandbox_binary = base::FilePath(devel_sandbox_path);
165 static const char no_suid_error[] = "Running without the SUID sandbox! See "
166 "https://code.google.com/p/chromium/wiki/LinuxSUIDSandboxDevelopment "
167 "for more information on developing with the sandbox on.";
168 if (sandbox_binary.empty()) {
169 if (!env_chrome_devel_sandbox_set) {
170 // This needs to be fatal. Talk to security@chromium.org if you feel
171 // otherwise.
172 LOG(FATAL) << no_suid_error;
175 // TODO(jln): an empty CHROME_DEVEL_SANDBOX environment variable (as
176 // opposed to a non existing one) is not fatal yet. This is needed
177 // because of existing bots and scripts. Fix it (crbug.com/245376).
178 LOG(ERROR) << no_suid_error;
182 // Tickle the sandbox host and zygote host so they fork now.
183 RenderSandboxHostLinux::GetInstance()->Init(sandbox_binary.value());
184 ZygoteHostImpl::GetInstance()->Init(sandbox_binary.value());
186 #endif
188 #if defined(USE_GLIB)
189 static void GLibLogHandler(const gchar* log_domain,
190 GLogLevelFlags log_level,
191 const gchar* message,
192 gpointer userdata) {
193 if (!log_domain)
194 log_domain = "<unknown>";
195 if (!message)
196 message = "<no message>";
198 if (strstr(message, "Loading IM context type") ||
199 strstr(message, "wrong ELF class: ELFCLASS64")) {
200 // http://crbug.com/9643
201 // Until we have a real 64-bit build or all of these 32-bit package issues
202 // are sorted out, don't fatal on ELF 32/64-bit mismatch warnings and don't
203 // spam the user with more than one of them.
204 static bool alerted = false;
205 if (!alerted) {
206 LOG(ERROR) << "Bug 9643: " << log_domain << ": " << message;
207 alerted = true;
209 } else if (strstr(message, "Unable to retrieve the file info for")) {
210 LOG(ERROR) << "GTK File code error: " << message;
211 } else if (strstr(message, "Could not find the icon") &&
212 strstr(log_domain, "Gtk")) {
213 LOG(ERROR) << "GTK icon error: " << message;
214 } else if (strstr(message, "Theme file for default has no") ||
215 strstr(message, "Theme directory") ||
216 strstr(message, "theme pixmap") ||
217 strstr(message, "locate theme engine")) {
218 LOG(ERROR) << "GTK theme error: " << message;
219 } else if (strstr(message, "Unable to create Ubuntu Menu Proxy") &&
220 strstr(log_domain, "<unknown>")) {
221 LOG(ERROR) << "GTK menu proxy create failed";
222 } else if (strstr(message, "gtk_drag_dest_leave: assertion")) {
223 LOG(ERROR) << "Drag destination deleted: http://crbug.com/18557";
224 } else if (strstr(message, "Out of memory") &&
225 strstr(log_domain, "<unknown>")) {
226 LOG(ERROR) << "DBus call timeout or out of memory: "
227 << "http://crosbug.com/15496";
228 } else if (strstr(message, "Could not connect: Connection refused") &&
229 strstr(log_domain, "<unknown>")) {
230 LOG(ERROR) << "DConf settings backend could not connect to session bus: "
231 << "http://crbug.com/179797";
232 } else if (strstr(message, "XDG_RUNTIME_DIR variable not set")) {
233 LOG(ERROR) << message << " (http://bugs.chromium.org/97293)";
234 } else if (strstr(message, "Attempting to store changes into") ||
235 strstr(message, "Attempting to set the permissions of")) {
236 LOG(ERROR) << message << " (http://bugs.chromium.org/161366)";
237 } else if (strstr(message, "drawable is not a native X11 window")) {
238 LOG(ERROR) << message << " (http://bugs.chromium.org/329991)";
239 } else {
240 LOG(DFATAL) << log_domain << ": " << message;
244 static void SetUpGLibLogHandler() {
245 // Register GLib-handled assertions to go through our logging system.
246 const char* kLogDomains[] = { NULL, "Gtk", "Gdk", "GLib", "GLib-GObject" };
247 for (size_t i = 0; i < arraysize(kLogDomains); i++) {
248 g_log_set_handler(kLogDomains[i],
249 static_cast<GLogLevelFlags>(G_LOG_FLAG_RECURSION |
250 G_LOG_FLAG_FATAL |
251 G_LOG_LEVEL_ERROR |
252 G_LOG_LEVEL_CRITICAL |
253 G_LOG_LEVEL_WARNING),
254 GLibLogHandler,
255 NULL);
258 #endif
260 } // namespace
262 // The currently-running BrowserMainLoop. There can be one or zero.
263 BrowserMainLoop* g_current_browser_main_loop = NULL;
265 // This is just to be able to keep ShutdownThreadsAndCleanUp out of
266 // the public interface of BrowserMainLoop.
267 class BrowserShutdownImpl {
268 public:
269 static void ImmediateShutdownAndExitProcess() {
270 DCHECK(g_current_browser_main_loop);
271 g_current_browser_main_loop->ShutdownThreadsAndCleanUp();
273 #if defined(OS_WIN)
274 // At this point the message loop is still running yet we've shut everything
275 // down. If any messages are processed we'll likely crash. Exit now.
276 ExitProcess(RESULT_CODE_NORMAL_EXIT);
277 #elif defined(OS_POSIX) && !defined(OS_MACOSX)
278 _exit(RESULT_CODE_NORMAL_EXIT);
279 #else
280 NOTIMPLEMENTED();
281 #endif
285 void ImmediateShutdownAndExitProcess() {
286 BrowserShutdownImpl::ImmediateShutdownAndExitProcess();
289 // For measuring memory usage after each task. Behind a command line flag.
290 class BrowserMainLoop::MemoryObserver : public base::MessageLoop::TaskObserver {
291 public:
292 MemoryObserver() {}
293 virtual ~MemoryObserver() {}
295 virtual void WillProcessTask(const base::PendingTask& pending_task) OVERRIDE {
298 virtual void DidProcessTask(const base::PendingTask& pending_task) OVERRIDE {
299 #if !defined(OS_IOS) // No ProcessMetrics on IOS.
300 scoped_ptr<base::ProcessMetrics> process_metrics(
301 base::ProcessMetrics::CreateProcessMetrics(
302 #if defined(OS_MACOSX)
303 base::GetCurrentProcessHandle(), NULL));
304 #else
305 base::GetCurrentProcessHandle()));
306 #endif
307 size_t private_bytes;
308 process_metrics->GetMemoryBytes(&private_bytes, NULL);
309 HISTOGRAM_MEMORY_KB("Memory.BrowserUsed", private_bytes >> 10);
310 #endif
312 private:
313 DISALLOW_COPY_AND_ASSIGN(MemoryObserver);
317 // BrowserMainLoop construction / destruction =============================
319 BrowserMainLoop* BrowserMainLoop::GetInstance() {
320 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
321 return g_current_browser_main_loop;
324 BrowserMainLoop::BrowserMainLoop(const MainFunctionParams& parameters)
325 : parameters_(parameters),
326 parsed_command_line_(parameters.command_line),
327 result_code_(RESULT_CODE_NORMAL_EXIT),
328 created_threads_(false),
329 // ContentMainRunner should have enabled tracing of the browser process
330 // when kTraceStartup is in the command line.
331 is_tracing_startup_(
332 parameters.command_line.HasSwitch(switches::kTraceStartup)) {
333 DCHECK(!g_current_browser_main_loop);
334 g_current_browser_main_loop = this;
337 BrowserMainLoop::~BrowserMainLoop() {
338 DCHECK_EQ(this, g_current_browser_main_loop);
339 #if !defined(OS_IOS)
340 ui::Clipboard::DestroyClipboardForCurrentThread();
341 #endif // !defined(OS_IOS)
342 g_current_browser_main_loop = NULL;
345 void BrowserMainLoop::Init() {
346 TRACE_EVENT0("startup", "BrowserMainLoop::Init")
347 parts_.reset(
348 GetContentClient()->browser()->CreateBrowserMainParts(parameters_));
351 // BrowserMainLoop stages ==================================================
353 void BrowserMainLoop::EarlyInitialization() {
354 TRACE_EVENT0("startup", "BrowserMainLoop::EarlyInitialization");
356 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
357 // No thread should be created before this call, as SetupSandbox()
358 // will end-up using fork().
359 SetupSandbox(parsed_command_line_);
360 #endif
362 #if defined(USE_X11)
363 if (parsed_command_line_.HasSwitch(switches::kSingleProcess) ||
364 parsed_command_line_.HasSwitch(switches::kInProcessGPU)) {
365 if (!XInitThreads()) {
366 LOG(ERROR) << "Failed to put Xlib into threaded mode.";
369 #endif
371 // GLib's spawning of new processes is buggy, so it's important that at this
372 // point GLib does not need to start DBUS. Chrome should always start with
373 // DBUS_SESSION_BUS_ADDRESS properly set. See crbug.com/309093.
374 #if defined(USE_GLIB)
375 // g_type_init will be deprecated in 2.36. 2.35 is the development
376 // version for 2.36, hence do not call g_type_init starting 2.35.
377 // http://developer.gnome.org/gobject/unstable/gobject-Type-Information.html#g-type-init
378 #if !GLIB_CHECK_VERSION(2, 35, 0)
379 // GLib type system initialization. Needed at least for gconf,
380 // used in net/proxy/proxy_config_service_linux.cc. Most likely
381 // this is superfluous as gtk_init() ought to do this. It's
382 // definitely harmless, so retained as a reminder of this
383 // requirement for gconf.
384 g_type_init();
385 #endif
387 #if !defined(USE_AURA)
388 gfx::GtkInitFromCommandLine(parsed_command_line_);
389 #endif
391 SetUpGLibLogHandler();
392 #endif
394 if (parts_)
395 parts_->PreEarlyInitialization();
397 #if defined(OS_WIN)
398 net::EnsureWinsockInit();
399 #endif
401 #if !defined(USE_OPENSSL)
402 // We want to be sure to init NSPR on the main thread.
403 crypto::EnsureNSPRInit();
404 #endif // !defined(USE_OPENSSL)
406 #if !defined(OS_IOS)
407 if (parsed_command_line_.HasSwitch(switches::kRendererProcessLimit)) {
408 std::string limit_string = parsed_command_line_.GetSwitchValueASCII(
409 switches::kRendererProcessLimit);
410 size_t process_limit;
411 if (base::StringToSizeT(limit_string, &process_limit)) {
412 RenderProcessHost::SetMaxRendererProcessCount(process_limit);
415 #endif // !defined(OS_IOS)
417 if (parts_)
418 parts_->PostEarlyInitialization();
421 void BrowserMainLoop::MainMessageLoopStart() {
422 TRACE_EVENT0("startup", "BrowserMainLoop::MainMessageLoopStart")
423 if (parts_) {
424 TRACE_EVENT0("startup",
425 "BrowserMainLoop::MainMessageLoopStart:PreMainMessageLoopStart");
426 parts_->PreMainMessageLoopStart();
429 #if defined(OS_WIN)
430 // If we're running tests (ui_task is non-null), then the ResourceBundle
431 // has already been initialized.
432 if (!parameters_.ui_task) {
433 // Override the configured locale with the user's preferred UI language.
434 l10n_util::OverrideLocaleWithUILanguageList();
436 #endif
438 // Create a MessageLoop if one does not already exist for the current thread.
439 if (!base::MessageLoop::current())
440 main_message_loop_.reset(new base::MessageLoopForUI);
442 InitializeMainThread();
445 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SystemMonitor")
446 system_monitor_.reset(new base::SystemMonitor);
449 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:PowerMonitor")
450 scoped_ptr<base::PowerMonitorSource> power_monitor_source(
451 new base::PowerMonitorDeviceSource());
452 power_monitor_.reset(new base::PowerMonitor(power_monitor_source.Pass()));
455 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:HighResTimerManager")
456 hi_res_timer_manager_.reset(new base::HighResolutionTimerManager);
459 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:NetworkChangeNotifier")
460 network_change_notifier_.reset(net::NetworkChangeNotifier::Create());
463 #if !defined(OS_IOS)
465 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MediaFeatures")
466 media::InitializeCPUSpecificMediaFeatures();
469 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:AudioMan")
470 audio_manager_.reset(media::AudioManager::Create(
471 MediaInternals::GetInstance()));
474 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MidiManager")
475 midi_manager_.reset(media::MidiManager::Create());
478 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:ContentWebUIController")
479 WebUIControllerFactory::RegisterFactory(
480 ContentWebUIControllerFactory::GetInstance());
484 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:AudioMirroringManager")
485 audio_mirroring_manager_.reset(new AudioMirroringManager());
488 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:OnlineStateObserver")
489 online_state_observer_.reset(new BrowserOnlineStateObserver);
493 system_stats_monitor_.reset(new base::debug::TraceEventSystemStatsMonitor(
494 base::ThreadTaskRunnerHandle::Get()));
496 #endif // !defined(OS_IOS)
498 #if defined(OS_WIN)
499 system_message_window_.reset(new SystemMessageWindowWin);
500 #endif
502 if (parts_)
503 parts_->PostMainMessageLoopStart();
505 #if !defined(OS_IOS)
506 // Start tracing to a file if needed. Only do this after starting the main
507 // message loop to avoid calling MessagePumpForUI::ScheduleWork() before
508 // MessagePumpForUI::Start() as it will crash the browser.
509 if (is_tracing_startup_) {
510 TRACE_EVENT0("startup", "BrowserMainLoop::InitStartupTracing")
511 InitStartupTracing(parsed_command_line_);
513 #endif // !defined(OS_IOS)
515 #if defined(OS_ANDROID)
517 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SurfaceTexturePeer")
518 SurfaceTexturePeer::InitInstance(new SurfaceTexturePeerBrowserImpl());
520 #endif
522 if (parsed_command_line_.HasSwitch(switches::kMemoryMetrics)) {
523 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MemoryObserver")
524 memory_observer_.reset(new MemoryObserver());
525 base::MessageLoop::current()->AddTaskObserver(memory_observer_.get());
528 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
529 trace_memory_controller_.reset(new base::debug::TraceMemoryController(
530 base::MessageLoop::current()->message_loop_proxy(),
531 ::HeapProfilerWithPseudoStackStart,
532 ::HeapProfilerStop,
533 ::GetHeapProfile));
534 #endif
537 int BrowserMainLoop::PreCreateThreads() {
539 if (parts_) {
540 TRACE_EVENT0("startup",
541 "BrowserMainLoop::CreateThreads:PreCreateThreads");
542 result_code_ = parts_->PreCreateThreads();
545 #if defined(ENABLE_PLUGINS)
546 // Prior to any processing happening on the io thread, we create the
547 // plugin service as it is predominantly used from the io thread,
548 // but must be created on the main thread. The service ctor is
549 // inexpensive and does not invoke the io_thread() accessor.
551 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads:PluginService")
552 PluginService::GetInstance()->Init();
554 #endif
556 #if !defined(OS_IOS) && (!defined(GOOGLE_CHROME_BUILD) || defined(OS_ANDROID))
557 // Single-process is an unsupported and not fully tested mode, so
558 // don't enable it for official Chrome builds (except on Android).
559 if (parsed_command_line_.HasSwitch(switches::kSingleProcess))
560 RenderProcessHost::SetRunRendererInProcess(true);
561 #endif
562 return result_code_;
565 void BrowserMainLoop::CreateStartupTasks() {
566 TRACE_EVENT0("startup", "BrowserMainLoop::CreateStartupTasks");
568 // First time through, we really want to create all the tasks
569 if (!startup_task_runner_.get()) {
570 #if defined(OS_ANDROID)
571 startup_task_runner_ = make_scoped_ptr(new StartupTaskRunner(
572 base::Bind(&BrowserStartupComplete),
573 base::MessageLoop::current()->message_loop_proxy()));
574 #else
575 startup_task_runner_ = make_scoped_ptr(new StartupTaskRunner(
576 base::Callback<void(int)>(),
577 base::MessageLoop::current()->message_loop_proxy()));
578 #endif
579 StartupTask pre_create_threads =
580 base::Bind(&BrowserMainLoop::PreCreateThreads, base::Unretained(this));
581 startup_task_runner_->AddTask(pre_create_threads);
583 StartupTask create_threads =
584 base::Bind(&BrowserMainLoop::CreateThreads, base::Unretained(this));
585 startup_task_runner_->AddTask(create_threads);
587 StartupTask browser_thread_started = base::Bind(
588 &BrowserMainLoop::BrowserThreadsStarted, base::Unretained(this));
589 startup_task_runner_->AddTask(browser_thread_started);
591 StartupTask pre_main_message_loop_run = base::Bind(
592 &BrowserMainLoop::PreMainMessageLoopRun, base::Unretained(this));
593 startup_task_runner_->AddTask(pre_main_message_loop_run);
595 #if defined(OS_ANDROID)
596 if (BrowserMayStartAsynchronously()) {
597 startup_task_runner_->StartRunningTasksAsync();
599 #endif
601 #if defined(OS_ANDROID)
602 if (!BrowserMayStartAsynchronously()) {
603 // A second request for asynchronous startup can be ignored, so
604 // StartupRunningTasksAsync is only called first time through. If, however,
605 // this is a request for synchronous startup then it must override any
606 // previous call for async startup, so we call RunAllTasksNow()
607 // unconditionally.
608 startup_task_runner_->RunAllTasksNow();
610 #else
611 startup_task_runner_->RunAllTasksNow();
612 #endif
615 int BrowserMainLoop::CreateThreads() {
616 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads");
618 base::Thread::Options default_options;
619 base::Thread::Options io_message_loop_options;
620 io_message_loop_options.message_loop_type = base::MessageLoop::TYPE_IO;
621 base::Thread::Options ui_message_loop_options;
622 ui_message_loop_options.message_loop_type = base::MessageLoop::TYPE_UI;
624 // Start threads in the order they occur in the BrowserThread::ID
625 // enumeration, except for BrowserThread::UI which is the main
626 // thread.
628 // Must be size_t so we can increment it.
629 for (size_t thread_id = BrowserThread::UI + 1;
630 thread_id < BrowserThread::ID_COUNT;
631 ++thread_id) {
632 scoped_ptr<BrowserProcessSubThread>* thread_to_start = NULL;
633 base::Thread::Options* options = &default_options;
635 switch (thread_id) {
636 case BrowserThread::DB:
637 TRACE_EVENT_BEGIN1("startup",
638 "BrowserMainLoop::CreateThreads:start",
639 "Thread", "BrowserThread::DB");
640 thread_to_start = &db_thread_;
641 break;
642 case BrowserThread::FILE_USER_BLOCKING:
643 TRACE_EVENT_BEGIN1("startup",
644 "BrowserMainLoop::CreateThreads:start",
645 "Thread", "BrowserThread::FILE_USER_BLOCKING");
646 thread_to_start = &file_user_blocking_thread_;
647 break;
648 case BrowserThread::FILE:
649 TRACE_EVENT_BEGIN1("startup",
650 "BrowserMainLoop::CreateThreads:start",
651 "Thread", "BrowserThread::FILE");
652 thread_to_start = &file_thread_;
653 #if defined(OS_WIN)
654 // On Windows, the FILE thread needs to be have a UI message loop
655 // which pumps messages in such a way that Google Update can
656 // communicate back to us.
657 options = &ui_message_loop_options;
658 #else
659 options = &io_message_loop_options;
660 #endif
661 break;
662 case BrowserThread::PROCESS_LAUNCHER:
663 TRACE_EVENT_BEGIN1("startup",
664 "BrowserMainLoop::CreateThreads:start",
665 "Thread", "BrowserThread::PROCESS_LAUNCHER");
666 thread_to_start = &process_launcher_thread_;
667 break;
668 case BrowserThread::CACHE:
669 TRACE_EVENT_BEGIN1("startup",
670 "BrowserMainLoop::CreateThreads:start",
671 "Thread", "BrowserThread::CACHE");
672 thread_to_start = &cache_thread_;
673 options = &io_message_loop_options;
674 break;
675 case BrowserThread::IO:
676 TRACE_EVENT_BEGIN1("startup",
677 "BrowserMainLoop::CreateThreads:start",
678 "Thread", "BrowserThread::IO");
679 thread_to_start = &io_thread_;
680 options = &io_message_loop_options;
681 break;
682 case BrowserThread::UI:
683 case BrowserThread::ID_COUNT:
684 default:
685 NOTREACHED();
686 break;
689 BrowserThread::ID id = static_cast<BrowserThread::ID>(thread_id);
691 if (thread_to_start) {
692 (*thread_to_start).reset(new BrowserProcessSubThread(id));
693 (*thread_to_start)->StartWithOptions(*options);
694 } else {
695 NOTREACHED();
698 TRACE_EVENT_END0("startup", "BrowserMainLoop::CreateThreads:start");
701 created_threads_ = true;
702 return result_code_;
705 int BrowserMainLoop::PreMainMessageLoopRun() {
706 if (parts_) {
707 TRACE_EVENT0("startup",
708 "BrowserMainLoop::CreateThreads:PreMainMessageLoopRun");
709 parts_->PreMainMessageLoopRun();
712 // If the UI thread blocks, the whole UI is unresponsive.
713 // Do not allow disk IO from the UI thread.
714 base::ThreadRestrictions::SetIOAllowed(false);
715 base::ThreadRestrictions::DisallowWaiting();
716 return result_code_;
719 void BrowserMainLoop::RunMainMessageLoopParts() {
720 TRACE_EVENT_BEGIN_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
722 bool ran_main_loop = false;
723 if (parts_)
724 ran_main_loop = parts_->MainMessageLoopRun(&result_code_);
726 if (!ran_main_loop)
727 MainMessageLoopRun();
729 TRACE_EVENT_END_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
732 void BrowserMainLoop::ShutdownThreadsAndCleanUp() {
733 if (!created_threads_) {
734 // Called early, nothing to do
735 return;
737 TRACE_EVENT0("shutdown", "BrowserMainLoop::ShutdownThreadsAndCleanUp")
739 // Teardown may start in PostMainMessageLoopRun, and during teardown we
740 // need to be able to perform IO.
741 base::ThreadRestrictions::SetIOAllowed(true);
742 BrowserThread::PostTask(
743 BrowserThread::IO, FROM_HERE,
744 base::Bind(base::IgnoreResult(&base::ThreadRestrictions::SetIOAllowed),
745 true));
747 if (RenderProcessHost::run_renderer_in_process())
748 RenderProcessHostImpl::ShutDownInProcessRenderer();
750 if (parts_) {
751 TRACE_EVENT0("shutdown",
752 "BrowserMainLoop::Subsystem:PostMainMessageLoopRun");
753 parts_->PostMainMessageLoopRun();
756 trace_memory_controller_.reset();
757 system_stats_monitor_.reset();
759 #if !defined(OS_IOS)
760 // Destroying the GpuProcessHostUIShims on the UI thread posts a task to
761 // delete related objects on the GPU thread. This must be done before
762 // stopping the GPU thread. The GPU thread will close IPC channels to renderer
763 // processes so this has to happen before stopping the IO thread.
765 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUProcessHostShim");
766 GpuProcessHostUIShim::DestroyAll();
768 // Cancel pending requests and prevent new requests.
769 if (resource_dispatcher_host_) {
770 TRACE_EVENT0("shutdown",
771 "BrowserMainLoop::Subsystem:ResourceDispatcherHost");
772 resource_dispatcher_host_.get()->Shutdown();
775 #if defined(USE_AURA)
777 TRACE_EVENT0("shutdown",
778 "BrowserMainLoop::Subsystem:ImageTransportFactory");
779 ImageTransportFactory::Terminate();
781 #endif
783 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
784 ZygoteHostImpl::GetInstance()->TearDownAfterLastChild();
785 #endif // defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
787 // The device monitors are using |system_monitor_| as dependency, so delete
788 // them before |system_monitor_| goes away.
789 // On Mac and windows, the monitor needs to be destroyed on the same thread
790 // as they were created. On Linux, the monitor will be deleted when IO thread
791 // goes away.
792 #if defined(OS_WIN)
793 system_message_window_.reset();
794 #elif defined(OS_MACOSX)
795 device_monitor_mac_.reset();
796 #endif
797 #endif // !defined(OS_IOS)
799 // Must be size_t so we can subtract from it.
800 for (size_t thread_id = BrowserThread::ID_COUNT - 1;
801 thread_id >= (BrowserThread::UI + 1);
802 --thread_id) {
803 // Find the thread object we want to stop. Looping over all valid
804 // BrowserThread IDs and DCHECKing on a missing case in the switch
805 // statement helps avoid a mismatch between this code and the
806 // BrowserThread::ID enumeration.
808 // The destruction order is the reverse order of occurrence in the
809 // BrowserThread::ID list. The rationale for the order is as
810 // follows (need to be filled in a bit):
813 // - The IO thread is the only user of the CACHE thread.
815 // - The PROCESS_LAUNCHER thread must be stopped after IO in case
816 // the IO thread posted a task to terminate a process on the
817 // process launcher thread.
819 // - (Not sure why DB stops last.)
820 switch (thread_id) {
821 case BrowserThread::DB: {
822 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DBThread");
823 db_thread_.reset();
825 break;
826 case BrowserThread::FILE_USER_BLOCKING: {
827 TRACE_EVENT0("shutdown",
828 "BrowserMainLoop::Subsystem:FileUserBlockingThread");
829 file_user_blocking_thread_.reset();
831 break;
832 case BrowserThread::FILE: {
833 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:FileThread");
834 #if !defined(OS_IOS)
835 // Clean up state that lives on or uses the file_thread_ before
836 // it goes away.
837 if (resource_dispatcher_host_)
838 resource_dispatcher_host_.get()->save_file_manager()->Shutdown();
839 #endif // !defined(OS_IOS)
840 file_thread_.reset();
842 break;
843 case BrowserThread::PROCESS_LAUNCHER: {
844 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:LauncherThread");
845 process_launcher_thread_.reset();
847 break;
848 case BrowserThread::CACHE: {
849 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:CacheThread");
850 cache_thread_.reset();
852 break;
853 case BrowserThread::IO: {
854 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IOThread");
855 io_thread_.reset();
857 break;
858 case BrowserThread::UI:
859 case BrowserThread::ID_COUNT:
860 default:
861 NOTREACHED();
862 break;
866 #if !defined(OS_IOS)
868 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IndexedDBThread");
869 indexed_db_thread_.reset();
871 #endif
873 // Close the blocking I/O pool after the other threads. Other threads such
874 // as the I/O thread may need to schedule work like closing files or flushing
875 // data during shutdown, so the blocking pool needs to be available. There
876 // may also be slow operations pending that will blcok shutdown, so closing
877 // it here (which will block until required operations are complete) gives
878 // more head start for those operations to finish.
880 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:ThreadPool");
881 BrowserThreadImpl::ShutdownThreadPool();
884 #if !defined(OS_IOS)
885 // Must happen after the IO thread is shutdown since this may be accessed from
886 // it.
888 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUChannelFactory");
889 if (BrowserGpuChannelHostFactory::instance())
890 BrowserGpuChannelHostFactory::Terminate();
893 // Must happen after the I/O thread is shutdown since this class lives on the
894 // I/O thread and isn't threadsafe.
896 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GamepadService");
897 GamepadService::GetInstance()->Terminate();
900 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:SensorService");
901 DeviceInertialSensorService::GetInstance()->Shutdown();
904 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DeleteDataSources");
905 URLDataManager::DeleteDataSources();
907 #endif // !defined(OS_IOS)
909 if (parts_) {
910 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:PostDestroyThreads");
911 parts_->PostDestroyThreads();
915 void BrowserMainLoop::InitializeMainThread() {
916 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeMainThread")
917 const char* kThreadName = "CrBrowserMain";
918 base::PlatformThread::SetName(kThreadName);
919 if (main_message_loop_)
920 main_message_loop_->set_thread_name(kThreadName);
922 // Register the main thread by instantiating it, but don't call any methods.
923 main_thread_.reset(
924 new BrowserThreadImpl(BrowserThread::UI, base::MessageLoop::current()));
927 int BrowserMainLoop::BrowserThreadsStarted() {
928 TRACE_EVENT0("startup", "BrowserMainLoop::BrowserThreadsStarted")
930 #if !defined(OS_IOS)
931 indexed_db_thread_.reset(new base::Thread("IndexedDB"));
932 indexed_db_thread_->Start();
933 #endif
935 #if defined(OS_ANDROID)
936 // Up the priority of anything that touches with display tasks
937 // (this thread is UI thread, and io_thread_ is for IPCs).
938 io_thread_->SetPriority(base::kThreadPriority_Display);
939 base::PlatformThread::SetThreadPriority(
940 base::PlatformThread::CurrentHandle(),
941 base::kThreadPriority_Display);
942 #endif
944 #if !defined(OS_IOS)
945 HistogramSynchronizer::GetInstance();
947 #if defined(OS_ANDROID)
948 // On Android, GLSurface::InitializeOneOff() must be called before initalizing
949 // the GpuDataManagerImpl as it uses the GL bindings. crbug.com/326295
950 if (!gfx::GLSurface::InitializeOneOff())
951 LOG(FATAL) << "GLSurface::InitializeOneOff failed";
952 #endif
954 // Initialize the GpuDataManager before we set up the MessageLoops because
955 // otherwise we'll trigger the assertion about doing IO on the UI thread.
956 GpuDataManagerImpl::GetInstance()->Initialize();
958 bool always_uses_gpu = IsForceCompositingModeEnabled();
959 bool established_gpu_channel = false;
960 #if defined(USE_AURA) || defined(OS_ANDROID)
961 established_gpu_channel =
962 parsed_command_line_.HasSwitch(switches::kSingleProcess) ||
963 parsed_command_line_.HasSwitch(switches::kInProcessGPU);
964 #if defined(USE_AURA)
965 if (!GpuDataManagerImpl::GetInstance()->CanUseGpuBrowserCompositor()) {
966 established_gpu_channel = always_uses_gpu = false;
968 BrowserGpuChannelHostFactory::Initialize(established_gpu_channel);
969 ImageTransportFactory::Initialize();
970 #elif defined(OS_ANDROID)
971 BrowserGpuChannelHostFactory::Initialize(established_gpu_channel);
972 #endif
973 #endif
975 #if defined(OS_LINUX) && defined(USE_UDEV)
976 device_monitor_linux_.reset(new DeviceMonitorLinux());
977 #elif defined(OS_MACOSX)
978 device_monitor_mac_.reset(new DeviceMonitorMac());
979 #endif
981 #if defined(USE_OZONE)
982 ui::OzonePlatform::Initialize();
983 ui::EventFactoryOzone::GetInstance()->SetFileTaskRunner(
984 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE));
985 #endif
987 // RDH needs the IO thread to be created
989 TRACE_EVENT0("startup",
990 "BrowserMainLoop::BrowserThreadsStarted:InitResourceDispatcherHost");
991 resource_dispatcher_host_.reset(new ResourceDispatcherHostImpl());
994 // MediaStreamManager needs the IO thread to be created.
996 TRACE_EVENT0("startup",
997 "BrowserMainLoop::BrowserThreadsStarted:InitMediaStreamManager");
998 media_stream_manager_.reset(new MediaStreamManager(audio_manager_.get()));
1002 TRACE_EVENT0("startup",
1003 "BrowserMainLoop::BrowserThreadsStarted:InitSpeechRecognition");
1004 speech_recognition_manager_.reset(new SpeechRecognitionManagerImpl(
1005 audio_manager_.get(), media_stream_manager_.get()));
1009 TRACE_EVENT0(
1010 "startup",
1011 "BrowserMainLoop::BrowserThreadsStarted::InitUserInputMonitor");
1012 user_input_monitor_ = media::UserInputMonitor::Create(
1013 io_thread_->message_loop_proxy(), main_thread_->message_loop_proxy());
1016 // Alert the clipboard class to which threads are allowed to access the
1017 // clipboard:
1018 std::vector<base::PlatformThreadId> allowed_clipboard_threads;
1019 // The current thread is the UI thread.
1020 allowed_clipboard_threads.push_back(base::PlatformThread::CurrentId());
1021 #if defined(OS_WIN)
1022 // On Windows, clipboards are also used on the File or IO threads.
1023 allowed_clipboard_threads.push_back(file_thread_->thread_id());
1024 allowed_clipboard_threads.push_back(io_thread_->thread_id());
1025 #endif
1026 ui::Clipboard::SetAllowedThreads(allowed_clipboard_threads);
1028 // When running the GPU thread in-process, avoid optimistically starting it
1029 // since creating the GPU thread races against creation of the one-and-only
1030 // ChildProcess instance which is created by the renderer thread.
1031 if (GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL) &&
1032 !established_gpu_channel &&
1033 always_uses_gpu &&
1034 !parsed_command_line_.HasSwitch(switches::kSingleProcess) &&
1035 !parsed_command_line_.HasSwitch(switches::kInProcessGPU)) {
1036 TRACE_EVENT_INSTANT0("gpu", "Post task to launch GPU process",
1037 TRACE_EVENT_SCOPE_THREAD);
1038 BrowserThread::PostTask(
1039 BrowserThread::IO, FROM_HERE, base::Bind(
1040 base::IgnoreResult(&GpuProcessHost::Get),
1041 GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED,
1042 CAUSE_FOR_GPU_LAUNCH_BROWSER_STARTUP));
1045 #if defined(OS_MACOSX)
1046 ThemeHelperMac::GetInstance();
1047 #endif
1048 #endif // !defined(OS_IOS)
1050 return result_code_;
1053 void BrowserMainLoop::InitializeToolkit() {
1054 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeToolkit")
1055 // TODO(evan): this function is rather subtle, due to the variety
1056 // of intersecting ifdefs we have. To keep it easy to follow, there
1057 // are no #else branches on any #ifs.
1058 // TODO(stevenjb): Move platform specific code into platform specific Parts
1059 // (Need to add InitializeToolkit stage to BrowserParts).
1060 // See also GTK setup in EarlyInitialization, above, and associated comments.
1062 #if defined(TOOLKIT_GTK)
1063 // It is important for this to happen before the first run dialog, as it
1064 // styles the dialog as well.
1065 gfx::InitRCStyles();
1066 #endif
1068 #if defined(OS_WIN)
1069 // Init common control sex.
1070 INITCOMMONCONTROLSEX config;
1071 config.dwSize = sizeof(config);
1072 config.dwICC = ICC_WIN95_CLASSES;
1073 if (!InitCommonControlsEx(&config))
1074 LOG_GETLASTERROR(FATAL);
1075 #endif
1077 if (parts_)
1078 parts_->ToolkitInitialized();
1081 void BrowserMainLoop::MainMessageLoopRun() {
1082 #if defined(OS_ANDROID)
1083 // Android's main message loop is the Java message loop.
1084 NOTREACHED();
1085 #else
1086 DCHECK(base::MessageLoopForUI::IsCurrent());
1087 if (parameters_.ui_task)
1088 base::MessageLoopForUI::current()->PostTask(FROM_HERE,
1089 *parameters_.ui_task);
1091 base::RunLoop run_loop;
1092 run_loop.Run();
1093 #endif
1096 void BrowserMainLoop::InitStartupTracing(const CommandLine& command_line) {
1097 DCHECK(is_tracing_startup_);
1099 base::FilePath trace_file = command_line.GetSwitchValuePath(
1100 switches::kTraceStartupFile);
1101 // trace_file = "none" means that startup events will show up for the next
1102 // begin/end tracing (via about:tracing or AutomationProxy::BeginTracing/
1103 // EndTracing, for example).
1104 if (trace_file == base::FilePath().AppendASCII("none"))
1105 return;
1107 if (trace_file.empty()) {
1108 // Default to saving the startup trace into the current dir.
1109 trace_file = base::FilePath().AppendASCII("chrometrace.log");
1112 std::string delay_str = command_line.GetSwitchValueASCII(
1113 switches::kTraceStartupDuration);
1114 int delay_secs = 5;
1115 if (!delay_str.empty() && !base::StringToInt(delay_str, &delay_secs)) {
1116 DLOG(WARNING) << "Could not parse --" << switches::kTraceStartupDuration
1117 << "=" << delay_str << " defaulting to 5 (secs)";
1118 delay_secs = 5;
1121 BrowserThread::PostDelayedTask(
1122 BrowserThread::UI, FROM_HERE,
1123 base::Bind(&BrowserMainLoop::EndStartupTracing,
1124 base::Unretained(this), trace_file),
1125 base::TimeDelta::FromSeconds(delay_secs));
1128 void BrowserMainLoop::EndStartupTracing(const base::FilePath& trace_file) {
1129 is_tracing_startup_ = false;
1130 TracingController::GetInstance()->DisableRecording(
1131 trace_file, TracingController::TracingFileResultCallback());
1134 } // namespace content