[blink-in-js] Migrate resources required for blink-in-js to grd - part 2
[chromium-blink-merge.git] / content / browser / browser_main_loop.cc
blob2a34b24ef02542b39966e2ccab814cafb4a13b00
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/files/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/renderer_host/media/media_stream_manager.h"
41 #include "content/browser/speech/speech_recognition_manager_impl.h"
42 #include "content/browser/startup_task_runner.h"
43 #include "content/browser/time_zone_monitor.h"
44 #include "content/browser/webui/content_web_ui_controller_factory.h"
45 #include "content/browser/webui/url_data_manager.h"
46 #include "content/public/browser/browser_main_parts.h"
47 #include "content/public/browser/browser_shutdown.h"
48 #include "content/public/browser/content_browser_client.h"
49 #include "content/public/browser/render_process_host.h"
50 #include "content/public/browser/tracing_controller.h"
51 #include "content/public/common/content_switches.h"
52 #include "content/public/common/main_function_params.h"
53 #include "content/public/common/result_codes.h"
54 #include "crypto/nss_util.h"
55 #include "media/audio/audio_manager.h"
56 #include "media/base/media.h"
57 #include "media/base/user_input_monitor.h"
58 #include "media/midi/midi_manager.h"
59 #include "net/base/network_change_notifier.h"
60 #include "net/socket/client_socket_factory.h"
61 #include "net/ssl/ssl_config_service.h"
62 #include "ui/base/clipboard/clipboard.h"
64 #if defined(USE_AURA) || (defined(OS_MACOSX) && !defined(OS_IOS))
65 #include "content/browser/compositor/image_transport_factory.h"
66 #endif
68 #if defined(USE_AURA)
69 #include "content/public/browser/context_factory.h"
70 #include "ui/aura/env.h"
71 #endif
73 #if !defined(OS_IOS)
74 #include "content/browser/renderer_host/render_process_host_impl.h"
75 #endif
77 #if defined(OS_ANDROID)
78 #include "base/android/jni_android.h"
79 #include "content/browser/android/browser_startup_controller.h"
80 #include "content/browser/android/surface_texture_peer_browser_impl.h"
81 #include "content/browser/android/tracing_controller_android.h"
82 #include "ui/gl/gl_surface.h"
83 #endif
85 #if defined(OS_MACOSX) && !defined(OS_IOS)
86 #include "content/browser/bootstrap_sandbox_mac.h"
87 #include "content/browser/cocoa/system_hotkey_helper_mac.h"
88 #include "content/browser/theme_helper_mac.h"
89 #endif
91 #if defined(OS_WIN)
92 #include <windows.h>
93 #include <commctrl.h>
94 #include <shellapi.h>
96 #include "content/browser/system_message_window_win.h"
97 #include "content/common/sandbox_win.h"
98 #include "net/base/winsock_init.h"
99 #include "ui/base/l10n/l10n_util_win.h"
100 #endif
102 #if defined(USE_GLIB)
103 #include <glib-object.h>
104 #endif
106 #if defined(OS_LINUX) && defined(USE_UDEV)
107 #include "content/browser/device_monitor_udev.h"
108 #elif defined(OS_MACOSX) && !defined(OS_IOS)
109 #include "content/browser/device_monitor_mac.h"
110 #endif
112 #if defined(OS_POSIX) && !defined(OS_MACOSX)
113 #include "content/browser/renderer_host/render_sandbox_host_linux.h"
114 #include "content/browser/zygote_host/zygote_host_impl_linux.h"
115 #include "sandbox/linux/suid/client/setuid_sandbox_client.h"
116 #endif
118 #if defined(ENABLE_PLUGINS)
119 #include "content/browser/plugin_service_impl.h"
120 #endif
122 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
123 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
124 #endif
126 #if defined(USE_X11)
127 #include "ui/gfx/x/x11_connection.h"
128 #include "ui/gfx/x/x11_types.h"
129 #endif
131 // One of the linux specific headers defines this as a macro.
132 #ifdef DestroyAll
133 #undef DestroyAll
134 #endif
136 namespace content {
137 namespace {
139 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
140 void SetupSandbox(const base::CommandLine& parsed_command_line) {
141 TRACE_EVENT0("startup", "SetupSandbox");
142 base::FilePath sandbox_binary;
144 scoped_ptr<sandbox::SetuidSandboxClient> setuid_sandbox_client(
145 sandbox::SetuidSandboxClient::Create());
147 const bool want_setuid_sandbox =
148 !parsed_command_line.HasSwitch(switches::kNoSandbox) &&
149 !parsed_command_line.HasSwitch(switches::kDisableSetuidSandbox) &&
150 !setuid_sandbox_client->IsDisabledViaEnvironment();
152 static const char no_suid_error[] =
153 "Running without the SUID sandbox! See "
154 "https://code.google.com/p/chromium/wiki/LinuxSUIDSandboxDevelopment "
155 "for more information on developing with the sandbox on.";
156 if (want_setuid_sandbox) {
157 sandbox_binary = setuid_sandbox_client->GetSandboxBinaryPath();
158 if (sandbox_binary.empty()) {
159 // This needs to be fatal. Talk to security@chromium.org if you feel
160 // otherwise.
161 LOG(FATAL) << no_suid_error;
163 } else {
164 LOG(ERROR) << no_suid_error;
167 // Tickle the sandbox host and zygote host so they fork now.
168 RenderSandboxHostLinux::GetInstance()->Init();
169 ZygoteHostImpl::GetInstance()->Init(sandbox_binary.value());
171 #endif
173 #if defined(USE_GLIB)
174 static void GLibLogHandler(const gchar* log_domain,
175 GLogLevelFlags log_level,
176 const gchar* message,
177 gpointer userdata) {
178 if (!log_domain)
179 log_domain = "<unknown>";
180 if (!message)
181 message = "<no message>";
183 if (strstr(message, "Unable to retrieve the file info for")) {
184 LOG(ERROR) << "GTK File code error: " << message;
185 } else if (strstr(message, "Could not find the icon") &&
186 strstr(log_domain, "Gtk")) {
187 LOG(ERROR) << "GTK icon error: " << message;
188 } else if (strstr(message, "Theme file for default has no") ||
189 strstr(message, "Theme directory") ||
190 strstr(message, "theme pixmap") ||
191 strstr(message, "locate theme engine")) {
192 LOG(ERROR) << "GTK theme error: " << message;
193 } else if (strstr(message, "Unable to create Ubuntu Menu Proxy") &&
194 strstr(log_domain, "<unknown>")) {
195 LOG(ERROR) << "GTK menu proxy create failed";
196 } else if (strstr(message, "Out of memory") &&
197 strstr(log_domain, "<unknown>")) {
198 LOG(ERROR) << "DBus call timeout or out of memory: "
199 << "http://crosbug.com/15496";
200 } else if (strstr(message, "Could not connect: Connection refused") &&
201 strstr(log_domain, "<unknown>")) {
202 LOG(ERROR) << "DConf settings backend could not connect to session bus: "
203 << "http://crbug.com/179797";
204 } else if (strstr(message, "Attempting to store changes into") ||
205 strstr(message, "Attempting to set the permissions of")) {
206 LOG(ERROR) << message << " (http://bugs.chromium.org/161366)";
207 } else if (strstr(message, "drawable is not a native X11 window")) {
208 LOG(ERROR) << message << " (http://bugs.chromium.org/329991)";
209 } else {
210 LOG(DFATAL) << log_domain << ": " << message;
214 static void SetUpGLibLogHandler() {
215 // Register GLib-handled assertions to go through our logging system.
216 const char* kLogDomains[] = { NULL, "Gtk", "Gdk", "GLib", "GLib-GObject" };
217 for (size_t i = 0; i < arraysize(kLogDomains); i++) {
218 g_log_set_handler(kLogDomains[i],
219 static_cast<GLogLevelFlags>(G_LOG_FLAG_RECURSION |
220 G_LOG_FLAG_FATAL |
221 G_LOG_LEVEL_ERROR |
222 G_LOG_LEVEL_CRITICAL |
223 G_LOG_LEVEL_WARNING),
224 GLibLogHandler,
225 NULL);
228 #endif
230 void OnStoppedStartupTracing(const base::FilePath& trace_file) {
231 VLOG(0) << "Completed startup tracing to " << trace_file.value();
234 #if defined(USE_AURA)
235 bool ShouldInitializeBrowserGpuChannelAndTransportSurface() {
236 return true;
238 #elif defined(OS_MACOSX) && !defined(OS_IOS)
239 bool ShouldInitializeBrowserGpuChannelAndTransportSurface() {
240 return IsDelegatedRendererEnabled();
242 #endif
244 // Disable optimizations for this block of functions so the compiler doesn't
245 // merge them all together. This makes it possible to tell what thread was
246 // unresponsive by inspecting the callstack.
247 MSVC_DISABLE_OPTIMIZE()
248 MSVC_PUSH_DISABLE_WARNING(4748)
250 NOINLINE void ResetThread_DB(scoped_ptr<BrowserProcessSubThread> thread) {
251 thread.reset();
254 NOINLINE void ResetThread_FILE(scoped_ptr<BrowserProcessSubThread> thread) {
255 thread.reset();
258 NOINLINE void ResetThread_FILE_USER_BLOCKING(
259 scoped_ptr<BrowserProcessSubThread> thread) {
260 thread.reset();
263 NOINLINE void ResetThread_PROCESS_LAUNCHER(
264 scoped_ptr<BrowserProcessSubThread> thread) {
265 thread.reset();
268 NOINLINE void ResetThread_CACHE(scoped_ptr<BrowserProcessSubThread> thread) {
269 thread.reset();
272 NOINLINE void ResetThread_IO(scoped_ptr<BrowserProcessSubThread> thread) {
273 thread.reset();
276 #if !defined(OS_IOS)
277 NOINLINE void ResetThread_IndexedDb(scoped_ptr<base::Thread> thread) {
278 thread.reset();
280 #endif
282 MSVC_POP_WARNING()
283 MSVC_ENABLE_OPTIMIZE();
285 } // namespace
287 // The currently-running BrowserMainLoop. There can be one or zero.
288 BrowserMainLoop* g_current_browser_main_loop = NULL;
290 // This is just to be able to keep ShutdownThreadsAndCleanUp out of
291 // the public interface of BrowserMainLoop.
292 class BrowserShutdownImpl {
293 public:
294 static void ImmediateShutdownAndExitProcess() {
295 DCHECK(g_current_browser_main_loop);
296 g_current_browser_main_loop->ShutdownThreadsAndCleanUp();
298 #if defined(OS_WIN)
299 // At this point the message loop is still running yet we've shut everything
300 // down. If any messages are processed we'll likely crash. Exit now.
301 ExitProcess(RESULT_CODE_NORMAL_EXIT);
302 #elif defined(OS_POSIX) && !defined(OS_MACOSX)
303 _exit(RESULT_CODE_NORMAL_EXIT);
304 #else
305 NOTIMPLEMENTED();
306 #endif
310 void ImmediateShutdownAndExitProcess() {
311 BrowserShutdownImpl::ImmediateShutdownAndExitProcess();
314 // For measuring memory usage after each task. Behind a command line flag.
315 class BrowserMainLoop::MemoryObserver : public base::MessageLoop::TaskObserver {
316 public:
317 MemoryObserver() {}
318 virtual ~MemoryObserver() {}
320 virtual void WillProcessTask(const base::PendingTask& pending_task) OVERRIDE {
323 virtual void DidProcessTask(const base::PendingTask& pending_task) OVERRIDE {
324 #if !defined(OS_IOS) // No ProcessMetrics on IOS.
325 scoped_ptr<base::ProcessMetrics> process_metrics(
326 base::ProcessMetrics::CreateProcessMetrics(
327 #if defined(OS_MACOSX)
328 base::GetCurrentProcessHandle(), NULL));
329 #else
330 base::GetCurrentProcessHandle()));
331 #endif
332 size_t private_bytes;
333 process_metrics->GetMemoryBytes(&private_bytes, NULL);
334 LOCAL_HISTOGRAM_MEMORY_KB("Memory.BrowserUsed", private_bytes >> 10);
335 #endif
337 private:
338 DISALLOW_COPY_AND_ASSIGN(MemoryObserver);
342 // BrowserMainLoop construction / destruction =============================
344 BrowserMainLoop* BrowserMainLoop::GetInstance() {
345 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
346 return g_current_browser_main_loop;
349 BrowserMainLoop::BrowserMainLoop(const MainFunctionParams& parameters)
350 : parameters_(parameters),
351 parsed_command_line_(parameters.command_line),
352 result_code_(RESULT_CODE_NORMAL_EXIT),
353 created_threads_(false),
354 // ContentMainRunner should have enabled tracing of the browser process
355 // when kTraceStartup is in the command line.
356 is_tracing_startup_(
357 parameters.command_line.HasSwitch(switches::kTraceStartup)) {
358 DCHECK(!g_current_browser_main_loop);
359 g_current_browser_main_loop = this;
362 BrowserMainLoop::~BrowserMainLoop() {
363 DCHECK_EQ(this, g_current_browser_main_loop);
364 #if !defined(OS_IOS)
365 ui::Clipboard::DestroyClipboardForCurrentThread();
366 #endif // !defined(OS_IOS)
367 g_current_browser_main_loop = NULL;
370 void BrowserMainLoop::Init() {
371 TRACE_EVENT0("startup", "BrowserMainLoop::Init");
372 parts_.reset(
373 GetContentClient()->browser()->CreateBrowserMainParts(parameters_));
376 // BrowserMainLoop stages ==================================================
378 void BrowserMainLoop::EarlyInitialization() {
379 TRACE_EVENT0("startup", "BrowserMainLoop::EarlyInitialization");
381 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
382 // No thread should be created before this call, as SetupSandbox()
383 // will end-up using fork().
384 SetupSandbox(parsed_command_line_);
385 #endif
387 #if defined(USE_X11)
388 if (parsed_command_line_.HasSwitch(switches::kSingleProcess) ||
389 parsed_command_line_.HasSwitch(switches::kInProcessGPU)) {
390 if (!gfx::InitializeThreadedX11()) {
391 LOG(ERROR) << "Failed to put Xlib into threaded mode.";
394 #endif
396 // GLib's spawning of new processes is buggy, so it's important that at this
397 // point GLib does not need to start DBUS. Chrome should always start with
398 // DBUS_SESSION_BUS_ADDRESS properly set. See crbug.com/309093.
399 #if defined(USE_GLIB)
400 // g_type_init will be deprecated in 2.36. 2.35 is the development
401 // version for 2.36, hence do not call g_type_init starting 2.35.
402 // http://developer.gnome.org/gobject/unstable/gobject-Type-Information.html#g-type-init
403 #if !GLIB_CHECK_VERSION(2, 35, 0)
404 // GLib type system initialization. Needed at least for gconf,
405 // used in net/proxy/proxy_config_service_linux.cc. Most likely
406 // this is superfluous as gtk_init() ought to do this. It's
407 // definitely harmless, so retained as a reminder of this
408 // requirement for gconf.
409 g_type_init();
410 #endif
412 SetUpGLibLogHandler();
413 #endif
415 if (parts_)
416 parts_->PreEarlyInitialization();
418 #if defined(OS_MACOSX)
419 // We use quite a few file descriptors for our IPC, and the default limit on
420 // the Mac is low (256), so bump it up.
421 base::SetFdLimit(1024);
422 #endif
424 #if defined(OS_WIN)
425 net::EnsureWinsockInit();
426 #endif
428 #if !defined(USE_OPENSSL)
429 // We want to be sure to init NSPR on the main thread.
430 crypto::EnsureNSPRInit();
431 #endif // !defined(USE_OPENSSL)
433 #if !defined(OS_IOS)
434 if (parsed_command_line_.HasSwitch(switches::kRendererProcessLimit)) {
435 std::string limit_string = parsed_command_line_.GetSwitchValueASCII(
436 switches::kRendererProcessLimit);
437 size_t process_limit;
438 if (base::StringToSizeT(limit_string, &process_limit)) {
439 RenderProcessHost::SetMaxRendererProcessCount(process_limit);
442 #endif // !defined(OS_IOS)
444 if (parts_)
445 parts_->PostEarlyInitialization();
448 void BrowserMainLoop::MainMessageLoopStart() {
449 TRACE_EVENT0("startup", "BrowserMainLoop::MainMessageLoopStart");
450 if (parts_) {
451 TRACE_EVENT0("startup",
452 "BrowserMainLoop::MainMessageLoopStart:PreMainMessageLoopStart");
453 parts_->PreMainMessageLoopStart();
456 #if defined(OS_WIN)
457 // If we're running tests (ui_task is non-null), then the ResourceBundle
458 // has already been initialized.
459 if (!parameters_.ui_task) {
460 // Override the configured locale with the user's preferred UI language.
461 l10n_util::OverrideLocaleWithUILanguageList();
463 #endif
465 // Create a MessageLoop if one does not already exist for the current thread.
466 if (!base::MessageLoop::current())
467 main_message_loop_.reset(new base::MessageLoopForUI);
469 InitializeMainThread();
472 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SystemMonitor");
473 system_monitor_.reset(new base::SystemMonitor);
476 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:PowerMonitor");
477 scoped_ptr<base::PowerMonitorSource> power_monitor_source(
478 new base::PowerMonitorDeviceSource());
479 power_monitor_.reset(new base::PowerMonitor(power_monitor_source.Pass()));
482 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:HighResTimerManager");
483 hi_res_timer_manager_.reset(new base::HighResolutionTimerManager);
486 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:NetworkChangeNotifier");
487 network_change_notifier_.reset(net::NetworkChangeNotifier::Create());
490 #if !defined(OS_IOS)
492 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MediaFeatures");
493 media::InitializeCPUSpecificMediaFeatures();
496 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:AudioMan");
497 audio_manager_.reset(media::AudioManager::Create(
498 MediaInternals::GetInstance()));
501 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MidiManager");
502 midi_manager_.reset(media::MidiManager::Create());
505 TRACE_EVENT0("startup",
506 "BrowserMainLoop::Subsystem:ContentWebUIController");
507 WebUIControllerFactory::RegisterFactory(
508 ContentWebUIControllerFactory::GetInstance());
512 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:OnlineStateObserver");
513 online_state_observer_.reset(new BrowserOnlineStateObserver);
517 system_stats_monitor_.reset(new base::debug::TraceEventSystemStatsMonitor(
518 base::ThreadTaskRunnerHandle::Get()));
520 #endif // !defined(OS_IOS)
522 #if defined(OS_WIN)
523 system_message_window_.reset(new SystemMessageWindowWin);
524 #endif
526 if (parts_)
527 parts_->PostMainMessageLoopStart();
529 #if !defined(OS_IOS)
530 // Start tracing to a file if needed. Only do this after starting the main
531 // message loop to avoid calling MessagePumpForUI::ScheduleWork() before
532 // MessagePumpForUI::Start() as it will crash the browser.
533 if (is_tracing_startup_) {
534 TRACE_EVENT0("startup", "BrowserMainLoop::InitStartupTracing");
535 InitStartupTracing(parsed_command_line_);
537 #endif // !defined(OS_IOS)
539 #if defined(OS_ANDROID)
541 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SurfaceTexturePeer");
542 SurfaceTexturePeer::InitInstance(new SurfaceTexturePeerBrowserImpl());
544 #endif
546 if (parsed_command_line_.HasSwitch(switches::kMemoryMetrics)) {
547 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MemoryObserver");
548 memory_observer_.reset(new MemoryObserver());
549 base::MessageLoop::current()->AddTaskObserver(memory_observer_.get());
552 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
553 trace_memory_controller_.reset(new base::debug::TraceMemoryController(
554 base::MessageLoop::current()->message_loop_proxy(),
555 ::HeapProfilerWithPseudoStackStart,
556 ::HeapProfilerStop,
557 ::GetHeapProfile));
558 #endif
561 int BrowserMainLoop::PreCreateThreads() {
562 if (parts_) {
563 TRACE_EVENT0("startup",
564 "BrowserMainLoop::CreateThreads:PreCreateThreads");
565 result_code_ = parts_->PreCreateThreads();
568 #if defined(ENABLE_PLUGINS)
569 // Prior to any processing happening on the io thread, we create the
570 // plugin service as it is predominantly used from the io thread,
571 // but must be created on the main thread. The service ctor is
572 // inexpensive and does not invoke the io_thread() accessor.
574 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads:PluginService");
575 PluginService::GetInstance()->Init();
577 #endif
579 #if !defined(OS_IOS) && (!defined(GOOGLE_CHROME_BUILD) || defined(OS_ANDROID))
580 // Single-process is an unsupported and not fully tested mode, so
581 // don't enable it for official Chrome builds (except on Android).
582 if (parsed_command_line_.HasSwitch(switches::kSingleProcess))
583 RenderProcessHost::SetRunRendererInProcess(true);
584 #endif
585 return result_code_;
588 void BrowserMainLoop::CreateStartupTasks() {
589 TRACE_EVENT0("startup", "BrowserMainLoop::CreateStartupTasks");
591 // First time through, we really want to create all the tasks
592 if (!startup_task_runner_.get()) {
593 #if defined(OS_ANDROID)
594 startup_task_runner_ = make_scoped_ptr(new StartupTaskRunner(
595 base::Bind(&BrowserStartupComplete),
596 base::MessageLoop::current()->message_loop_proxy()));
597 #else
598 startup_task_runner_ = make_scoped_ptr(new StartupTaskRunner(
599 base::Callback<void(int)>(),
600 base::MessageLoop::current()->message_loop_proxy()));
601 #endif
602 StartupTask pre_create_threads =
603 base::Bind(&BrowserMainLoop::PreCreateThreads, base::Unretained(this));
604 startup_task_runner_->AddTask(pre_create_threads);
606 StartupTask create_threads =
607 base::Bind(&BrowserMainLoop::CreateThreads, base::Unretained(this));
608 startup_task_runner_->AddTask(create_threads);
610 StartupTask browser_thread_started = base::Bind(
611 &BrowserMainLoop::BrowserThreadsStarted, base::Unretained(this));
612 startup_task_runner_->AddTask(browser_thread_started);
614 StartupTask pre_main_message_loop_run = base::Bind(
615 &BrowserMainLoop::PreMainMessageLoopRun, base::Unretained(this));
616 startup_task_runner_->AddTask(pre_main_message_loop_run);
618 #if defined(OS_ANDROID)
619 if (BrowserMayStartAsynchronously()) {
620 startup_task_runner_->StartRunningTasksAsync();
622 #endif
624 #if defined(OS_ANDROID)
625 if (!BrowserMayStartAsynchronously()) {
626 // A second request for asynchronous startup can be ignored, so
627 // StartupRunningTasksAsync is only called first time through. If, however,
628 // this is a request for synchronous startup then it must override any
629 // previous call for async startup, so we call RunAllTasksNow()
630 // unconditionally.
631 startup_task_runner_->RunAllTasksNow();
633 #else
634 startup_task_runner_->RunAllTasksNow();
635 #endif
638 int BrowserMainLoop::CreateThreads() {
639 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads");
641 base::Thread::Options io_message_loop_options;
642 io_message_loop_options.message_loop_type = base::MessageLoop::TYPE_IO;
643 base::Thread::Options ui_message_loop_options;
644 ui_message_loop_options.message_loop_type = base::MessageLoop::TYPE_UI;
646 // Start threads in the order they occur in the BrowserThread::ID
647 // enumeration, except for BrowserThread::UI which is the main
648 // thread.
650 // Must be size_t so we can increment it.
651 for (size_t thread_id = BrowserThread::UI + 1;
652 thread_id < BrowserThread::ID_COUNT;
653 ++thread_id) {
654 scoped_ptr<BrowserProcessSubThread>* thread_to_start = NULL;
655 base::Thread::Options options;
657 switch (thread_id) {
658 case BrowserThread::DB:
659 TRACE_EVENT_BEGIN1("startup",
660 "BrowserMainLoop::CreateThreads:start",
661 "Thread", "BrowserThread::DB");
662 thread_to_start = &db_thread_;
663 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
664 break;
665 case BrowserThread::FILE_USER_BLOCKING:
666 TRACE_EVENT_BEGIN1("startup",
667 "BrowserMainLoop::CreateThreads:start",
668 "Thread", "BrowserThread::FILE_USER_BLOCKING");
669 thread_to_start = &file_user_blocking_thread_;
670 break;
671 case BrowserThread::FILE:
672 TRACE_EVENT_BEGIN1("startup",
673 "BrowserMainLoop::CreateThreads:start",
674 "Thread", "BrowserThread::FILE");
675 thread_to_start = &file_thread_;
676 #if defined(OS_WIN)
677 // On Windows, the FILE thread needs to be have a UI message loop
678 // which pumps messages in such a way that Google Update can
679 // communicate back to us.
680 options = ui_message_loop_options;
681 #else
682 options = io_message_loop_options;
683 #endif
684 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
685 break;
686 case BrowserThread::PROCESS_LAUNCHER:
687 TRACE_EVENT_BEGIN1("startup",
688 "BrowserMainLoop::CreateThreads:start",
689 "Thread", "BrowserThread::PROCESS_LAUNCHER");
690 thread_to_start = &process_launcher_thread_;
691 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
692 break;
693 case BrowserThread::CACHE:
694 TRACE_EVENT_BEGIN1("startup",
695 "BrowserMainLoop::CreateThreads:start",
696 "Thread", "BrowserThread::CACHE");
697 thread_to_start = &cache_thread_;
698 options = io_message_loop_options;
699 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
700 break;
701 case BrowserThread::IO:
702 TRACE_EVENT_BEGIN1("startup",
703 "BrowserMainLoop::CreateThreads:start",
704 "Thread", "BrowserThread::IO");
705 thread_to_start = &io_thread_;
706 options = io_message_loop_options;
707 break;
708 case BrowserThread::UI:
709 case BrowserThread::ID_COUNT:
710 default:
711 NOTREACHED();
712 break;
715 BrowserThread::ID id = static_cast<BrowserThread::ID>(thread_id);
717 if (thread_to_start) {
718 (*thread_to_start).reset(new BrowserProcessSubThread(id));
719 (*thread_to_start)->StartWithOptions(options);
720 } else {
721 NOTREACHED();
724 TRACE_EVENT_END0("startup", "BrowserMainLoop::CreateThreads:start");
726 created_threads_ = true;
727 return result_code_;
730 int BrowserMainLoop::PreMainMessageLoopRun() {
731 if (parts_) {
732 TRACE_EVENT0("startup",
733 "BrowserMainLoop::CreateThreads:PreMainMessageLoopRun");
734 parts_->PreMainMessageLoopRun();
737 // If the UI thread blocks, the whole UI is unresponsive.
738 // Do not allow disk IO from the UI thread.
739 base::ThreadRestrictions::SetIOAllowed(false);
740 base::ThreadRestrictions::DisallowWaiting();
741 return result_code_;
744 void BrowserMainLoop::RunMainMessageLoopParts() {
745 TRACE_EVENT_BEGIN_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
747 bool ran_main_loop = false;
748 if (parts_)
749 ran_main_loop = parts_->MainMessageLoopRun(&result_code_);
751 if (!ran_main_loop)
752 MainMessageLoopRun();
754 TRACE_EVENT_END_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
757 void BrowserMainLoop::ShutdownThreadsAndCleanUp() {
758 if (!created_threads_) {
759 // Called early, nothing to do
760 return;
762 TRACE_EVENT0("shutdown", "BrowserMainLoop::ShutdownThreadsAndCleanUp");
764 // Teardown may start in PostMainMessageLoopRun, and during teardown we
765 // need to be able to perform IO.
766 base::ThreadRestrictions::SetIOAllowed(true);
767 BrowserThread::PostTask(
768 BrowserThread::IO, FROM_HERE,
769 base::Bind(base::IgnoreResult(&base::ThreadRestrictions::SetIOAllowed),
770 true));
772 #if !defined(OS_IOS)
773 if (RenderProcessHost::run_renderer_in_process())
774 RenderProcessHostImpl::ShutDownInProcessRenderer();
775 #endif
777 if (parts_) {
778 TRACE_EVENT0("shutdown",
779 "BrowserMainLoop::Subsystem:PostMainMessageLoopRun");
780 parts_->PostMainMessageLoopRun();
783 trace_memory_controller_.reset();
784 system_stats_monitor_.reset();
786 #if !defined(OS_IOS)
787 // Destroying the GpuProcessHostUIShims on the UI thread posts a task to
788 // delete related objects on the GPU thread. This must be done before
789 // stopping the GPU thread. The GPU thread will close IPC channels to renderer
790 // processes so this has to happen before stopping the IO thread.
792 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUProcessHostShim");
793 GpuProcessHostUIShim::DestroyAll();
795 // Cancel pending requests and prevent new requests.
796 if (resource_dispatcher_host_) {
797 TRACE_EVENT0("shutdown",
798 "BrowserMainLoop::Subsystem:ResourceDispatcherHost");
799 resource_dispatcher_host_.get()->Shutdown();
802 #if defined(USE_AURA) || defined(OS_MACOSX)
803 if (ShouldInitializeBrowserGpuChannelAndTransportSurface()) {
804 TRACE_EVENT0("shutdown",
805 "BrowserMainLoop::Subsystem:ImageTransportFactory");
806 ImageTransportFactory::Terminate();
808 #endif
810 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
811 ZygoteHostImpl::GetInstance()->TearDownAfterLastChild();
812 #endif // defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
814 // The device monitors are using |system_monitor_| as dependency, so delete
815 // them before |system_monitor_| goes away.
816 // On Mac and windows, the monitor needs to be destroyed on the same thread
817 // as they were created. On Linux, the monitor will be deleted when IO thread
818 // goes away.
819 #if defined(OS_WIN)
820 system_message_window_.reset();
821 #elif defined(OS_MACOSX)
822 device_monitor_mac_.reset();
823 #endif
824 #endif // !defined(OS_IOS)
826 // Must be size_t so we can subtract from it.
827 for (size_t thread_id = BrowserThread::ID_COUNT - 1;
828 thread_id >= (BrowserThread::UI + 1);
829 --thread_id) {
830 // Find the thread object we want to stop. Looping over all valid
831 // BrowserThread IDs and DCHECKing on a missing case in the switch
832 // statement helps avoid a mismatch between this code and the
833 // BrowserThread::ID enumeration.
835 // The destruction order is the reverse order of occurrence in the
836 // BrowserThread::ID list. The rationale for the order is as
837 // follows (need to be filled in a bit):
840 // - The IO thread is the only user of the CACHE thread.
842 // - The PROCESS_LAUNCHER thread must be stopped after IO in case
843 // the IO thread posted a task to terminate a process on the
844 // process launcher thread.
846 // - (Not sure why DB stops last.)
847 switch (thread_id) {
848 case BrowserThread::DB: {
849 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DBThread");
850 ResetThread_DB(db_thread_.Pass());
851 break;
853 case BrowserThread::FILE: {
854 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:FileThread");
855 #if !defined(OS_IOS)
856 // Clean up state that lives on or uses the file_thread_ before
857 // it goes away.
858 if (resource_dispatcher_host_)
859 resource_dispatcher_host_.get()->save_file_manager()->Shutdown();
860 #endif // !defined(OS_IOS)
861 ResetThread_FILE(file_thread_.Pass());
862 break;
864 case BrowserThread::FILE_USER_BLOCKING: {
865 TRACE_EVENT0("shutdown",
866 "BrowserMainLoop::Subsystem:FileUserBlockingThread");
867 ResetThread_FILE_USER_BLOCKING(file_user_blocking_thread_.Pass());
868 break;
870 case BrowserThread::PROCESS_LAUNCHER: {
871 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:LauncherThread");
872 ResetThread_PROCESS_LAUNCHER(process_launcher_thread_.Pass());
873 break;
875 case BrowserThread::CACHE: {
876 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:CacheThread");
877 ResetThread_CACHE(cache_thread_.Pass());
878 break;
880 case BrowserThread::IO: {
881 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IOThread");
882 ResetThread_IO(io_thread_.Pass());
883 break;
885 case BrowserThread::UI:
886 case BrowserThread::ID_COUNT:
887 default:
888 NOTREACHED();
889 break;
893 #if !defined(OS_IOS)
895 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IndexedDBThread");
896 ResetThread_IndexedDb(indexed_db_thread_.Pass());
898 #endif
900 // Close the blocking I/O pool after the other threads. Other threads such
901 // as the I/O thread may need to schedule work like closing files or flushing
902 // data during shutdown, so the blocking pool needs to be available. There
903 // may also be slow operations pending that will blcok shutdown, so closing
904 // it here (which will block until required operations are complete) gives
905 // more head start for those operations to finish.
907 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:ThreadPool");
908 BrowserThreadImpl::ShutdownThreadPool();
911 #if !defined(OS_IOS)
912 // Must happen after the IO thread is shutdown since this may be accessed from
913 // it.
915 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUChannelFactory");
916 if (BrowserGpuChannelHostFactory::instance())
917 BrowserGpuChannelHostFactory::Terminate();
920 // Must happen after the I/O thread is shutdown since this class lives on the
921 // I/O thread and isn't threadsafe.
923 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GamepadService");
924 GamepadService::GetInstance()->Terminate();
927 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:SensorService");
928 DeviceInertialSensorService::GetInstance()->Shutdown();
931 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:BatteryStatusService");
932 BatteryStatusService::GetInstance()->Shutdown();
935 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DeleteDataSources");
936 URLDataManager::DeleteDataSources();
938 #endif // !defined(OS_IOS)
940 if (parts_) {
941 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:PostDestroyThreads");
942 parts_->PostDestroyThreads();
946 void BrowserMainLoop::StopStartupTracingTimer() {
947 startup_trace_timer_.Stop();
950 void BrowserMainLoop::InitializeMainThread() {
951 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeMainThread");
952 const char* kThreadName = "CrBrowserMain";
953 base::PlatformThread::SetName(kThreadName);
954 if (main_message_loop_)
955 main_message_loop_->set_thread_name(kThreadName);
957 // Register the main thread by instantiating it, but don't call any methods.
958 main_thread_.reset(
959 new BrowserThreadImpl(BrowserThread::UI, base::MessageLoop::current()));
962 int BrowserMainLoop::BrowserThreadsStarted() {
963 TRACE_EVENT0("startup", "BrowserMainLoop::BrowserThreadsStarted");
965 #if !defined(OS_IOS)
966 indexed_db_thread_.reset(new base::Thread("IndexedDB"));
967 indexed_db_thread_->Start();
968 #endif
970 #if defined(OS_ANDROID)
971 // Up the priority of anything that touches with display tasks
972 // (this thread is UI thread, and io_thread_ is for IPCs).
973 io_thread_->SetPriority(base::kThreadPriority_Display);
974 base::PlatformThread::SetThreadPriority(
975 base::PlatformThread::CurrentHandle(),
976 base::kThreadPriority_Display);
977 #endif
979 #if !defined(OS_IOS)
980 HistogramSynchronizer::GetInstance();
982 bool initialize_gpu_data_manager = true;
983 #if defined(OS_ANDROID)
984 // On Android, GLSurface::InitializeOneOff() must be called before initalizing
985 // the GpuDataManagerImpl as it uses the GL bindings. crbug.com/326295
986 if (!gfx::GLSurface::InitializeOneOff()) {
987 LOG(ERROR) << "GLSurface::InitializeOneOff failed";
988 initialize_gpu_data_manager = false;
990 #endif
992 // Initialize the GpuDataManager before we set up the MessageLoops because
993 // otherwise we'll trigger the assertion about doing IO on the UI thread.
994 if (initialize_gpu_data_manager)
995 GpuDataManagerImpl::GetInstance()->Initialize();
997 bool always_uses_gpu = true;
998 bool established_gpu_channel = false;
999 #if defined(USE_AURA) || defined(OS_MACOSX)
1000 if (ShouldInitializeBrowserGpuChannelAndTransportSurface()) {
1001 established_gpu_channel = true;
1002 if (!GpuDataManagerImpl::GetInstance()->CanUseGpuBrowserCompositor()) {
1003 established_gpu_channel = always_uses_gpu = false;
1005 BrowserGpuChannelHostFactory::Initialize(established_gpu_channel);
1006 ImageTransportFactory::Initialize();
1007 #if defined(USE_AURA)
1008 if (aura::Env::GetInstance()) {
1009 aura::Env::GetInstance()->set_context_factory(GetContextFactory());
1011 #endif
1013 #elif defined(OS_ANDROID)
1014 established_gpu_channel = true;
1015 BrowserGpuChannelHostFactory::Initialize(established_gpu_channel);
1016 #endif
1018 #if defined(OS_LINUX) && defined(USE_UDEV)
1019 device_monitor_linux_.reset(new DeviceMonitorLinux());
1020 #elif defined(OS_MACOSX)
1021 device_monitor_mac_.reset(new DeviceMonitorMac());
1022 #endif
1024 // RDH needs the IO thread to be created
1026 TRACE_EVENT0("startup",
1027 "BrowserMainLoop::BrowserThreadsStarted:InitResourceDispatcherHost");
1028 resource_dispatcher_host_.reset(new ResourceDispatcherHostImpl());
1031 // MediaStreamManager needs the IO thread to be created.
1033 TRACE_EVENT0("startup",
1034 "BrowserMainLoop::BrowserThreadsStarted:InitMediaStreamManager");
1035 media_stream_manager_.reset(new MediaStreamManager(audio_manager_.get()));
1039 TRACE_EVENT0("startup",
1040 "BrowserMainLoop::BrowserThreadsStarted:InitSpeechRecognition");
1041 speech_recognition_manager_.reset(new SpeechRecognitionManagerImpl(
1042 audio_manager_.get(), media_stream_manager_.get()));
1046 TRACE_EVENT0(
1047 "startup",
1048 "BrowserMainLoop::BrowserThreadsStarted::InitUserInputMonitor");
1049 user_input_monitor_ = media::UserInputMonitor::Create(
1050 io_thread_->message_loop_proxy(), main_thread_->message_loop_proxy());
1054 TRACE_EVENT0("startup",
1055 "BrowserMainLoop::BrowserThreadsStarted::TimeZoneMonitor");
1056 time_zone_monitor_ = TimeZoneMonitor::Create();
1059 // Alert the clipboard class to which threads are allowed to access the
1060 // clipboard:
1061 std::vector<base::PlatformThreadId> allowed_clipboard_threads;
1062 // The current thread is the UI thread.
1063 allowed_clipboard_threads.push_back(base::PlatformThread::CurrentId());
1064 #if defined(OS_WIN)
1065 // On Windows, clipboards are also used on the File or IO threads.
1066 allowed_clipboard_threads.push_back(file_thread_->thread_id());
1067 allowed_clipboard_threads.push_back(io_thread_->thread_id());
1068 #endif
1069 ui::Clipboard::SetAllowedThreads(allowed_clipboard_threads);
1071 // When running the GPU thread in-process, avoid optimistically starting it
1072 // since creating the GPU thread races against creation of the one-and-only
1073 // ChildProcess instance which is created by the renderer thread.
1074 if (GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL) &&
1075 !established_gpu_channel &&
1076 always_uses_gpu &&
1077 !parsed_command_line_.HasSwitch(switches::kSingleProcess) &&
1078 !parsed_command_line_.HasSwitch(switches::kInProcessGPU)) {
1079 TRACE_EVENT_INSTANT0("gpu", "Post task to launch GPU process",
1080 TRACE_EVENT_SCOPE_THREAD);
1081 BrowserThread::PostTask(
1082 BrowserThread::IO, FROM_HERE, base::Bind(
1083 base::IgnoreResult(&GpuProcessHost::Get),
1084 GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED,
1085 CAUSE_FOR_GPU_LAUNCH_BROWSER_STARTUP));
1088 #if defined(OS_MACOSX)
1089 ThemeHelperMac::GetInstance();
1090 SystemHotkeyHelperMac::GetInstance()->DeferredLoadSystemHotkeys();
1091 if (ShouldEnableBootstrapSandbox()) {
1092 TRACE_EVENT0("startup",
1093 "BrowserMainLoop::BrowserThreadsStarted:BootstrapSandbox");
1094 CHECK(GetBootstrapSandbox());
1096 #endif // defined(OS_MACOSX)
1098 #endif // !defined(OS_IOS)
1100 return result_code_;
1103 bool BrowserMainLoop::InitializeToolkit() {
1104 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeToolkit");
1105 // TODO(evan): this function is rather subtle, due to the variety
1106 // of intersecting ifdefs we have. To keep it easy to follow, there
1107 // are no #else branches on any #ifs.
1108 // TODO(stevenjb): Move platform specific code into platform specific Parts
1109 // (Need to add InitializeToolkit stage to BrowserParts).
1110 // See also GTK setup in EarlyInitialization, above, and associated comments.
1112 #if defined(OS_WIN)
1113 // Init common control sex.
1114 INITCOMMONCONTROLSEX config;
1115 config.dwSize = sizeof(config);
1116 config.dwICC = ICC_WIN95_CLASSES;
1117 if (!InitCommonControlsEx(&config))
1118 PLOG(FATAL);
1119 #endif
1121 #if defined(USE_AURA)
1123 #if defined(USE_X11)
1124 if (!gfx::GetXDisplay())
1125 return false;
1126 #endif
1128 // Env creates the compositor. Aura widgets need the compositor to be created
1129 // before they can be initialized by the browser.
1130 aura::Env::CreateInstance(true);
1131 #endif // defined(USE_AURA)
1133 if (parts_)
1134 parts_->ToolkitInitialized();
1136 return true;
1139 void BrowserMainLoop::MainMessageLoopRun() {
1140 #if defined(OS_ANDROID)
1141 // Android's main message loop is the Java message loop.
1142 NOTREACHED();
1143 #else
1144 DCHECK(base::MessageLoopForUI::IsCurrent());
1145 if (parameters_.ui_task)
1146 base::MessageLoopForUI::current()->PostTask(FROM_HERE,
1147 *parameters_.ui_task);
1149 base::RunLoop run_loop;
1150 run_loop.Run();
1151 #endif
1154 base::FilePath BrowserMainLoop::GetStartupTraceFileName(
1155 const base::CommandLine& command_line) const {
1156 base::FilePath trace_file = command_line.GetSwitchValuePath(
1157 switches::kTraceStartupFile);
1158 // trace_file = "none" means that startup events will show up for the next
1159 // begin/end tracing (via about:tracing or AutomationProxy::BeginTracing/
1160 // EndTracing, for example).
1161 if (trace_file == base::FilePath().AppendASCII("none"))
1162 return trace_file;
1164 if (trace_file.empty()) {
1165 #if defined(OS_ANDROID)
1166 TracingControllerAndroid::GenerateTracingFilePath(&trace_file);
1167 #else
1168 // Default to saving the startup trace into the current dir.
1169 trace_file = base::FilePath().AppendASCII("chrometrace.log");
1170 #endif
1173 return trace_file;
1176 void BrowserMainLoop::InitStartupTracing(
1177 const base::CommandLine& command_line) {
1178 DCHECK(is_tracing_startup_);
1180 startup_trace_file_ = GetStartupTraceFileName(parsed_command_line_);
1182 std::string delay_str = command_line.GetSwitchValueASCII(
1183 switches::kTraceStartupDuration);
1184 int delay_secs = 5;
1185 if (!delay_str.empty() && !base::StringToInt(delay_str, &delay_secs)) {
1186 DLOG(WARNING) << "Could not parse --" << switches::kTraceStartupDuration
1187 << "=" << delay_str << " defaulting to 5 (secs)";
1188 delay_secs = 5;
1191 startup_trace_timer_.Start(FROM_HERE,
1192 base::TimeDelta::FromSeconds(delay_secs),
1193 this,
1194 &BrowserMainLoop::EndStartupTracing);
1197 void BrowserMainLoop::EndStartupTracing() {
1198 is_tracing_startup_ = false;
1199 TracingController::GetInstance()->DisableRecording(
1200 startup_trace_file_, base::Bind(&OnStoppedStartupTracing));
1203 } // namespace content