Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / content / browser / browser_main_loop.cc
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.
4
5 #include "content/browser/browser_main_loop.h"
6
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_sensors/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/speech/speech_recognition_manager_impl.h"
43 #include "content/browser/startup_task_runner.h"
44 #include "content/browser/time_zone_monitor.h"
45 #include "content/browser/webui/content_web_ui_controller_factory.h"
46 #include "content/browser/webui/url_data_manager.h"
47 #include "content/public/browser/browser_main_parts.h"
48 #include "content/public/browser/browser_shutdown.h"
49 #include "content/public/browser/content_browser_client.h"
50 #include "content/public/browser/render_process_host.h"
51 #include "content/public/browser/tracing_controller.h"
52 #include "content/public/common/content_switches.h"
53 #include "content/public/common/main_function_params.h"
54 #include "content/public/common/result_codes.h"
55 #include "crypto/nss_util.h"
56 #include "media/audio/audio_manager.h"
57 #include "media/base/media.h"
58 #include "media/base/user_input_monitor.h"
59 #include "media/midi/midi_manager.h"
60 #include "net/base/network_change_notifier.h"
61 #include "net/socket/client_socket_factory.h"
62 #include "net/ssl/ssl_config_service.h"
63 #include "ui/base/clipboard/clipboard.h"
64
65 #if defined(USE_AURA) || (defined(OS_MACOSX) && !defined(OS_IOS))
66 #include "content/browser/compositor/image_transport_factory.h"
67 #endif
68
69 #if defined(USE_AURA)
70 #include "ui/aura/env.h"
71 #endif
72
73 #if !defined(OS_IOS)
74 #include "content/browser/renderer_host/render_process_host_impl.h"
75 #endif
76
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
84
85 #if defined(OS_MACOSX) && !defined(OS_IOS)
86 #include "content/browser/theme_helper_mac.h"
87 #endif
88
89 #if defined(OS_WIN)
90 #include <windows.h>
91 #include <commctrl.h>
92 #include <shellapi.h>
93
94 #include "content/browser/system_message_window_win.h"
95 #include "content/common/sandbox_win.h"
96 #include "net/base/winsock_init.h"
97 #include "ui/base/l10n/l10n_util_win.h"
98 #endif
99
100 #if defined(USE_GLIB)
101 #include <glib-object.h>
102 #endif
103
104 #if defined(OS_LINUX) && defined(USE_UDEV)
105 #include "content/browser/device_monitor_udev.h"
106 #elif defined(OS_MACOSX) && !defined(OS_IOS)
107 #include "content/browser/device_monitor_mac.h"
108 #endif
109
110 #if defined(OS_POSIX) && !defined(OS_MACOSX)
111 #include "content/browser/renderer_host/render_sandbox_host_linux.h"
112 #include "content/browser/zygote_host/zygote_host_impl_linux.h"
113 #include "sandbox/linux/suid/client/setuid_sandbox_client.h"
114 #endif
115
116 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
117 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
118 #endif
119
120 #if defined(USE_X11)
121 #include "ui/gfx/x/x11_connection.h"
122 #include "ui/gfx/x/x11_types.h"
123 #endif
124
125 #if defined(USE_OZONE)
126 #include "ui/ozone/ozone_platform.h"
127 #include "ui/events/ozone/event_factory_ozone.h"
128 #include "ozone/content/ozone_channel_host_factory.h"
129 #endif
130
131 // One of the linux specific headers defines this as a macro.
132 #ifdef DestroyAll
133 #undef DestroyAll
134 #endif
135
136 namespace content {
137 namespace {
138
139 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
140 void SetupSandbox(const CommandLine& parsed_command_line) {
141   TRACE_EVENT0("startup", "SetupSandbox");
142   base::FilePath sandbox_binary;
143
144   scoped_ptr<sandbox::SetuidSandboxClient> setuid_sandbox_client(
145       sandbox::SetuidSandboxClient::Create());
146
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();
151
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;
162     }
163   } else {
164     LOG(ERROR) << no_suid_error;
165   }
166
167   // Tickle the sandbox host and zygote host so they fork now.
168   RenderSandboxHostLinux::GetInstance()->Init(sandbox_binary.value());
169   ZygoteHostImpl::GetInstance()->Init(sandbox_binary.value());
170 }
171 #endif
172
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>";
182
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;
211   }
212 }
213
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);
226   }
227 }
228 #endif
229
230 void OnStoppedStartupTracing(const base::FilePath& trace_file) {
231   VLOG(0) << "Completed startup tracing to " << trace_file.value();
232 }
233
234 #if defined(USE_AURA)
235 bool ShouldInitializeBrowserGpuChannelAndTransportSurface() {
236   return true;
237 }
238 #elif defined(OS_MACOSX) && !defined(OS_IOS)
239 bool ShouldInitializeBrowserGpuChannelAndTransportSurface() {
240   return IsDelegatedRendererEnabled();
241 }
242 #endif
243
244 }  // namespace
245
246 // The currently-running BrowserMainLoop.  There can be one or zero.
247 BrowserMainLoop* g_current_browser_main_loop = NULL;
248
249 // This is just to be able to keep ShutdownThreadsAndCleanUp out of
250 // the public interface of BrowserMainLoop.
251 class BrowserShutdownImpl {
252  public:
253   static void ImmediateShutdownAndExitProcess() {
254     DCHECK(g_current_browser_main_loop);
255     g_current_browser_main_loop->ShutdownThreadsAndCleanUp();
256
257 #if defined(OS_WIN)
258     // At this point the message loop is still running yet we've shut everything
259     // down. If any messages are processed we'll likely crash. Exit now.
260     ExitProcess(RESULT_CODE_NORMAL_EXIT);
261 #elif defined(OS_POSIX) && !defined(OS_MACOSX)
262     _exit(RESULT_CODE_NORMAL_EXIT);
263 #else
264     NOTIMPLEMENTED();
265 #endif
266   }
267 };
268
269 void ImmediateShutdownAndExitProcess() {
270   BrowserShutdownImpl::ImmediateShutdownAndExitProcess();
271 }
272
273 // For measuring memory usage after each task. Behind a command line flag.
274 class BrowserMainLoop::MemoryObserver : public base::MessageLoop::TaskObserver {
275  public:
276   MemoryObserver() {}
277   virtual ~MemoryObserver() {}
278
279   virtual void WillProcessTask(const base::PendingTask& pending_task) OVERRIDE {
280   }
281
282   virtual void DidProcessTask(const base::PendingTask& pending_task) OVERRIDE {
283 #if !defined(OS_IOS)  // No ProcessMetrics on IOS.
284     scoped_ptr<base::ProcessMetrics> process_metrics(
285         base::ProcessMetrics::CreateProcessMetrics(
286 #if defined(OS_MACOSX)
287             base::GetCurrentProcessHandle(), NULL));
288 #else
289             base::GetCurrentProcessHandle()));
290 #endif
291     size_t private_bytes;
292     process_metrics->GetMemoryBytes(&private_bytes, NULL);
293     HISTOGRAM_MEMORY_KB("Memory.BrowserUsed", private_bytes >> 10);
294 #endif
295   }
296  private:
297   DISALLOW_COPY_AND_ASSIGN(MemoryObserver);
298 };
299
300
301 // BrowserMainLoop construction / destruction =============================
302
303 BrowserMainLoop* BrowserMainLoop::GetInstance() {
304   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
305   return g_current_browser_main_loop;
306 }
307
308 BrowserMainLoop::BrowserMainLoop(const MainFunctionParams& parameters)
309     : parameters_(parameters),
310       parsed_command_line_(parameters.command_line),
311       result_code_(RESULT_CODE_NORMAL_EXIT),
312       created_threads_(false),
313       // ContentMainRunner should have enabled tracing of the browser process
314       // when kTraceStartup is in the command line.
315       is_tracing_startup_(
316           parameters.command_line.HasSwitch(switches::kTraceStartup)) {
317   DCHECK(!g_current_browser_main_loop);
318   g_current_browser_main_loop = this;
319 }
320
321 BrowserMainLoop::~BrowserMainLoop() {
322   DCHECK_EQ(this, g_current_browser_main_loop);
323 #if !defined(OS_IOS)
324   ui::Clipboard::DestroyClipboardForCurrentThread();
325 #endif  // !defined(OS_IOS)
326   g_current_browser_main_loop = NULL;
327 }
328
329 void BrowserMainLoop::Init() {
330   TRACE_EVENT0("startup", "BrowserMainLoop::Init");
331   parts_.reset(
332       GetContentClient()->browser()->CreateBrowserMainParts(parameters_));
333 }
334
335 // BrowserMainLoop stages ==================================================
336
337 void BrowserMainLoop::EarlyInitialization() {
338   TRACE_EVENT0("startup", "BrowserMainLoop::EarlyInitialization");
339
340 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
341   // No thread should be created before this call, as SetupSandbox()
342   // will end-up using fork().
343   SetupSandbox(parsed_command_line_);
344 #endif
345
346 #if defined(USE_X11)
347   if (parsed_command_line_.HasSwitch(switches::kSingleProcess) ||
348       parsed_command_line_.HasSwitch(switches::kInProcessGPU)) {
349     if (!gfx::InitializeThreadedX11()) {
350       LOG(ERROR) << "Failed to put Xlib into threaded mode.";
351     }
352   }
353 #endif
354
355   // GLib's spawning of new processes is buggy, so it's important that at this
356   // point GLib does not need to start DBUS. Chrome should always start with
357   // DBUS_SESSION_BUS_ADDRESS properly set. See crbug.com/309093.
358 #if defined(USE_GLIB)
359   // g_type_init will be deprecated in 2.36. 2.35 is the development
360   // version for 2.36, hence do not call g_type_init starting 2.35.
361   // http://developer.gnome.org/gobject/unstable/gobject-Type-Information.html#g-type-init
362 #if !GLIB_CHECK_VERSION(2, 35, 0)
363   // GLib type system initialization. Needed at least for gconf,
364   // used in net/proxy/proxy_config_service_linux.cc. Most likely
365   // this is superfluous as gtk_init() ought to do this. It's
366   // definitely harmless, so retained as a reminder of this
367   // requirement for gconf.
368   g_type_init();
369 #endif
370
371   SetUpGLibLogHandler();
372 #endif
373
374   if (parts_)
375     parts_->PreEarlyInitialization();
376
377 #if defined(OS_WIN)
378   net::EnsureWinsockInit();
379 #endif
380
381 #if !defined(USE_OPENSSL)
382   // We want to be sure to init NSPR on the main thread.
383   crypto::EnsureNSPRInit();
384 #endif  // !defined(USE_OPENSSL)
385
386 #if !defined(OS_IOS)
387   if (parsed_command_line_.HasSwitch(switches::kRendererProcessLimit)) {
388     std::string limit_string = parsed_command_line_.GetSwitchValueASCII(
389         switches::kRendererProcessLimit);
390     size_t process_limit;
391     if (base::StringToSizeT(limit_string, &process_limit)) {
392       RenderProcessHost::SetMaxRendererProcessCount(process_limit);
393     }
394   }
395 #endif  // !defined(OS_IOS)
396
397   if (parts_)
398     parts_->PostEarlyInitialization();
399 }
400
401 void BrowserMainLoop::MainMessageLoopStart() {
402   TRACE_EVENT0("startup", "BrowserMainLoop::MainMessageLoopStart");
403   if (parts_) {
404     TRACE_EVENT0("startup",
405         "BrowserMainLoop::MainMessageLoopStart:PreMainMessageLoopStart");
406     parts_->PreMainMessageLoopStart();
407   }
408
409 #if defined(OS_WIN)
410   // If we're running tests (ui_task is non-null), then the ResourceBundle
411   // has already been initialized.
412   if (!parameters_.ui_task) {
413     // Override the configured locale with the user's preferred UI language.
414     l10n_util::OverrideLocaleWithUILanguageList();
415   }
416 #endif
417
418   // Create a MessageLoop if one does not already exist for the current thread.
419   if (!base::MessageLoop::current())
420     main_message_loop_.reset(new base::MessageLoopForUI);
421
422   InitializeMainThread();
423
424   {
425     TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SystemMonitor");
426     system_monitor_.reset(new base::SystemMonitor);
427   }
428   {
429     TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:PowerMonitor");
430     scoped_ptr<base::PowerMonitorSource> power_monitor_source(
431       new base::PowerMonitorDeviceSource());
432     power_monitor_.reset(new base::PowerMonitor(power_monitor_source.Pass()));
433   }
434   {
435     TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:HighResTimerManager");
436     hi_res_timer_manager_.reset(new base::HighResolutionTimerManager);
437   }
438   {
439     TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:NetworkChangeNotifier");
440     network_change_notifier_.reset(net::NetworkChangeNotifier::Create());
441   }
442
443 #if !defined(OS_IOS)
444   {
445     TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MediaFeatures");
446     media::InitializeCPUSpecificMediaFeatures();
447   }
448   {
449     TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:AudioMan");
450     audio_manager_.reset(media::AudioManager::Create(
451         MediaInternals::GetInstance()));
452   }
453   {
454     TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MidiManager");
455     midi_manager_.reset(media::MidiManager::Create());
456   }
457   {
458     TRACE_EVENT0("startup",
459                  "BrowserMainLoop::Subsystem:ContentWebUIController");
460     WebUIControllerFactory::RegisterFactory(
461         ContentWebUIControllerFactory::GetInstance());
462   }
463
464   {
465     TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:AudioMirroringManager");
466     audio_mirroring_manager_.reset(new AudioMirroringManager());
467   }
468   {
469     TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:OnlineStateObserver");
470     online_state_observer_.reset(new BrowserOnlineStateObserver);
471   }
472
473   {
474     system_stats_monitor_.reset(new base::debug::TraceEventSystemStatsMonitor(
475         base::ThreadTaskRunnerHandle::Get()));
476   }
477 #endif  // !defined(OS_IOS)
478
479 #if defined(OS_WIN)
480   system_message_window_.reset(new SystemMessageWindowWin);
481 #endif
482
483   if (parts_)
484     parts_->PostMainMessageLoopStart();
485
486 #if !defined(OS_IOS)
487   // Start tracing to a file if needed. Only do this after starting the main
488   // message loop to avoid calling MessagePumpForUI::ScheduleWork() before
489   // MessagePumpForUI::Start() as it will crash the browser.
490   if (is_tracing_startup_) {
491     TRACE_EVENT0("startup", "BrowserMainLoop::InitStartupTracing");
492     InitStartupTracing(parsed_command_line_);
493   }
494 #endif  // !defined(OS_IOS)
495
496 #if defined(OS_ANDROID)
497   {
498     TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SurfaceTexturePeer");
499     SurfaceTexturePeer::InitInstance(new SurfaceTexturePeerBrowserImpl());
500   }
501 #endif
502
503   if (parsed_command_line_.HasSwitch(switches::kMemoryMetrics)) {
504     TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MemoryObserver");
505     memory_observer_.reset(new MemoryObserver());
506     base::MessageLoop::current()->AddTaskObserver(memory_observer_.get());
507   }
508
509 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
510   trace_memory_controller_.reset(new base::debug::TraceMemoryController(
511       base::MessageLoop::current()->message_loop_proxy(),
512       ::HeapProfilerWithPseudoStackStart,
513       ::HeapProfilerStop,
514       ::GetHeapProfile));
515 #endif
516 }
517
518 int BrowserMainLoop::PreCreateThreads() {
519
520   if (parts_) {
521     TRACE_EVENT0("startup",
522         "BrowserMainLoop::CreateThreads:PreCreateThreads");
523     result_code_ = parts_->PreCreateThreads();
524   }
525
526 #if defined(ENABLE_PLUGINS)
527   // Prior to any processing happening on the io thread, we create the
528   // plugin service as it is predominantly used from the io thread,
529   // but must be created on the main thread. The service ctor is
530   // inexpensive and does not invoke the io_thread() accessor.
531   {
532     TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads:PluginService");
533     PluginService::GetInstance()->Init();
534   }
535 #endif
536
537 #if !defined(OS_IOS) && (!defined(GOOGLE_CHROME_BUILD) || defined(OS_ANDROID))
538   // Single-process is an unsupported and not fully tested mode, so
539   // don't enable it for official Chrome builds (except on Android).
540   if (parsed_command_line_.HasSwitch(switches::kSingleProcess))
541     RenderProcessHost::SetRunRendererInProcess(true);
542 #endif
543   return result_code_;
544 }
545
546 void BrowserMainLoop::CreateStartupTasks() {
547   TRACE_EVENT0("startup", "BrowserMainLoop::CreateStartupTasks");
548
549   // First time through, we really want to create all the tasks
550   if (!startup_task_runner_.get()) {
551 #if defined(OS_ANDROID)
552     startup_task_runner_ = make_scoped_ptr(new StartupTaskRunner(
553         base::Bind(&BrowserStartupComplete),
554         base::MessageLoop::current()->message_loop_proxy()));
555 #else
556     startup_task_runner_ = make_scoped_ptr(new StartupTaskRunner(
557         base::Callback<void(int)>(),
558         base::MessageLoop::current()->message_loop_proxy()));
559 #endif
560     StartupTask pre_create_threads =
561         base::Bind(&BrowserMainLoop::PreCreateThreads, base::Unretained(this));
562     startup_task_runner_->AddTask(pre_create_threads);
563
564     StartupTask create_threads =
565         base::Bind(&BrowserMainLoop::CreateThreads, base::Unretained(this));
566     startup_task_runner_->AddTask(create_threads);
567
568     StartupTask browser_thread_started = base::Bind(
569         &BrowserMainLoop::BrowserThreadsStarted, base::Unretained(this));
570     startup_task_runner_->AddTask(browser_thread_started);
571
572     StartupTask pre_main_message_loop_run = base::Bind(
573         &BrowserMainLoop::PreMainMessageLoopRun, base::Unretained(this));
574     startup_task_runner_->AddTask(pre_main_message_loop_run);
575
576 #if defined(OS_ANDROID)
577     if (BrowserMayStartAsynchronously()) {
578       startup_task_runner_->StartRunningTasksAsync();
579     }
580 #endif
581   }
582 #if defined(OS_ANDROID)
583   if (!BrowserMayStartAsynchronously()) {
584     // A second request for asynchronous startup can be ignored, so
585     // StartupRunningTasksAsync is only called first time through. If, however,
586     // this is a request for synchronous startup then it must override any
587     // previous call for async startup, so we call RunAllTasksNow()
588     // unconditionally.
589     startup_task_runner_->RunAllTasksNow();
590   }
591 #else
592   startup_task_runner_->RunAllTasksNow();
593 #endif
594 }
595
596 int BrowserMainLoop::CreateThreads() {
597   TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads");
598
599   base::Thread::Options default_options;
600   base::Thread::Options io_message_loop_options;
601   io_message_loop_options.message_loop_type = base::MessageLoop::TYPE_IO;
602   base::Thread::Options ui_message_loop_options;
603   ui_message_loop_options.message_loop_type = base::MessageLoop::TYPE_UI;
604
605   // Start threads in the order they occur in the BrowserThread::ID
606   // enumeration, except for BrowserThread::UI which is the main
607   // thread.
608   //
609   // Must be size_t so we can increment it.
610   for (size_t thread_id = BrowserThread::UI + 1;
611        thread_id < BrowserThread::ID_COUNT;
612        ++thread_id) {
613     scoped_ptr<BrowserProcessSubThread>* thread_to_start = NULL;
614     base::Thread::Options* options = &default_options;
615
616     switch (thread_id) {
617       case BrowserThread::DB:
618         TRACE_EVENT_BEGIN1("startup",
619             "BrowserMainLoop::CreateThreads:start",
620             "Thread", "BrowserThread::DB");
621         thread_to_start = &db_thread_;
622         break;
623       case BrowserThread::FILE_USER_BLOCKING:
624         TRACE_EVENT_BEGIN1("startup",
625             "BrowserMainLoop::CreateThreads:start",
626             "Thread", "BrowserThread::FILE_USER_BLOCKING");
627         thread_to_start = &file_user_blocking_thread_;
628         break;
629       case BrowserThread::FILE:
630         TRACE_EVENT_BEGIN1("startup",
631             "BrowserMainLoop::CreateThreads:start",
632             "Thread", "BrowserThread::FILE");
633         thread_to_start = &file_thread_;
634 #if defined(OS_WIN)
635         // On Windows, the FILE thread needs to be have a UI message loop
636         // which pumps messages in such a way that Google Update can
637         // communicate back to us.
638         options = &ui_message_loop_options;
639 #else
640         options = &io_message_loop_options;
641 #endif
642         break;
643       case BrowserThread::PROCESS_LAUNCHER:
644         TRACE_EVENT_BEGIN1("startup",
645             "BrowserMainLoop::CreateThreads:start",
646             "Thread", "BrowserThread::PROCESS_LAUNCHER");
647         thread_to_start = &process_launcher_thread_;
648         break;
649       case BrowserThread::CACHE:
650         TRACE_EVENT_BEGIN1("startup",
651             "BrowserMainLoop::CreateThreads:start",
652             "Thread", "BrowserThread::CACHE");
653         thread_to_start = &cache_thread_;
654         options = &io_message_loop_options;
655         break;
656       case BrowserThread::IO:
657         TRACE_EVENT_BEGIN1("startup",
658             "BrowserMainLoop::CreateThreads:start",
659             "Thread", "BrowserThread::IO");
660         thread_to_start = &io_thread_;
661         options = &io_message_loop_options;
662         break;
663       case BrowserThread::UI:
664       case BrowserThread::ID_COUNT:
665       default:
666         NOTREACHED();
667         break;
668     }
669
670     BrowserThread::ID id = static_cast<BrowserThread::ID>(thread_id);
671
672     if (thread_to_start) {
673       (*thread_to_start).reset(new BrowserProcessSubThread(id));
674       (*thread_to_start)->StartWithOptions(*options);
675     } else {
676       NOTREACHED();
677     }
678
679     TRACE_EVENT_END0("startup", "BrowserMainLoop::CreateThreads:start");
680
681   }
682   created_threads_ = true;
683   return result_code_;
684 }
685
686 int BrowserMainLoop::PreMainMessageLoopRun() {
687   if (parts_) {
688     TRACE_EVENT0("startup",
689         "BrowserMainLoop::CreateThreads:PreMainMessageLoopRun");
690     parts_->PreMainMessageLoopRun();
691   }
692
693   // If the UI thread blocks, the whole UI is unresponsive.
694   // Do not allow disk IO from the UI thread.
695   base::ThreadRestrictions::SetIOAllowed(false);
696   base::ThreadRestrictions::DisallowWaiting();
697   return result_code_;
698 }
699
700 void BrowserMainLoop::RunMainMessageLoopParts() {
701   TRACE_EVENT_BEGIN_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
702
703   bool ran_main_loop = false;
704   if (parts_)
705     ran_main_loop = parts_->MainMessageLoopRun(&result_code_);
706
707   if (!ran_main_loop)
708     MainMessageLoopRun();
709
710   TRACE_EVENT_END_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
711 }
712
713 void BrowserMainLoop::ShutdownThreadsAndCleanUp() {
714   if (!created_threads_) {
715     // Called early, nothing to do
716     return;
717   }
718   TRACE_EVENT0("shutdown", "BrowserMainLoop::ShutdownThreadsAndCleanUp");
719
720   // Teardown may start in PostMainMessageLoopRun, and during teardown we
721   // need to be able to perform IO.
722   base::ThreadRestrictions::SetIOAllowed(true);
723   BrowserThread::PostTask(
724       BrowserThread::IO, FROM_HERE,
725       base::Bind(base::IgnoreResult(&base::ThreadRestrictions::SetIOAllowed),
726                  true));
727
728 #if !defined(OS_IOS)
729   if (RenderProcessHost::run_renderer_in_process())
730     RenderProcessHostImpl::ShutDownInProcessRenderer();
731 #endif
732
733   if (parts_) {
734     TRACE_EVENT0("shutdown",
735                  "BrowserMainLoop::Subsystem:PostMainMessageLoopRun");
736     parts_->PostMainMessageLoopRun();
737   }
738
739   trace_memory_controller_.reset();
740   system_stats_monitor_.reset();
741
742 #if !defined(OS_IOS)
743   // Destroying the GpuProcessHostUIShims on the UI thread posts a task to
744   // delete related objects on the GPU thread. This must be done before
745   // stopping the GPU thread. The GPU thread will close IPC channels to renderer
746   // processes so this has to happen before stopping the IO thread.
747   {
748     TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUProcessHostShim");
749     GpuProcessHostUIShim::DestroyAll();
750   }
751   // Cancel pending requests and prevent new requests.
752   if (resource_dispatcher_host_) {
753     TRACE_EVENT0("shutdown",
754                  "BrowserMainLoop::Subsystem:ResourceDispatcherHost");
755     resource_dispatcher_host_.get()->Shutdown();
756   }
757
758 #if defined(USE_AURA)
759   {
760     TRACE_EVENT0("shutdown",
761                  "BrowserMainLoop::Subsystem:ImageTransportFactory");
762     ImageTransportFactory::Terminate();
763   }
764 #endif
765
766 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
767   ZygoteHostImpl::GetInstance()->TearDownAfterLastChild();
768 #endif  // defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
769
770   // The device monitors are using |system_monitor_| as dependency, so delete
771   // them before |system_monitor_| goes away.
772   // On Mac and windows, the monitor needs to be destroyed on the same thread
773   // as they were created. On Linux, the monitor will be deleted when IO thread
774   // goes away.
775 #if defined(OS_WIN)
776   system_message_window_.reset();
777 #elif defined(OS_MACOSX)
778   device_monitor_mac_.reset();
779 #endif
780 #endif  // !defined(OS_IOS)
781
782   // Must be size_t so we can subtract from it.
783   for (size_t thread_id = BrowserThread::ID_COUNT - 1;
784        thread_id >= (BrowserThread::UI + 1);
785        --thread_id) {
786     // Find the thread object we want to stop. Looping over all valid
787     // BrowserThread IDs and DCHECKing on a missing case in the switch
788     // statement helps avoid a mismatch between this code and the
789     // BrowserThread::ID enumeration.
790     //
791     // The destruction order is the reverse order of occurrence in the
792     // BrowserThread::ID list. The rationale for the order is as
793     // follows (need to be filled in a bit):
794     //
795     //
796     // - The IO thread is the only user of the CACHE thread.
797     //
798     // - The PROCESS_LAUNCHER thread must be stopped after IO in case
799     //   the IO thread posted a task to terminate a process on the
800     //   process launcher thread.
801     //
802     // - (Not sure why DB stops last.)
803     switch (thread_id) {
804       case BrowserThread::DB: {
805           TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DBThread");
806           db_thread_.reset();
807         }
808         break;
809       case BrowserThread::FILE_USER_BLOCKING: {
810           TRACE_EVENT0("shutdown",
811                        "BrowserMainLoop::Subsystem:FileUserBlockingThread");
812           file_user_blocking_thread_.reset();
813         }
814         break;
815       case BrowserThread::FILE: {
816           TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:FileThread");
817 #if !defined(OS_IOS)
818           // Clean up state that lives on or uses the file_thread_ before
819           // it goes away.
820           if (resource_dispatcher_host_)
821             resource_dispatcher_host_.get()->save_file_manager()->Shutdown();
822 #endif  // !defined(OS_IOS)
823           file_thread_.reset();
824         }
825         break;
826       case BrowserThread::PROCESS_LAUNCHER: {
827           TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:LauncherThread");
828           process_launcher_thread_.reset();
829         }
830         break;
831       case BrowserThread::CACHE: {
832           TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:CacheThread");
833           cache_thread_.reset();
834         }
835         break;
836       case BrowserThread::IO: {
837           TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IOThread");
838           io_thread_.reset();
839         }
840         break;
841       case BrowserThread::UI:
842       case BrowserThread::ID_COUNT:
843       default:
844         NOTREACHED();
845         break;
846     }
847   }
848
849 #if !defined(OS_IOS)
850   {
851     TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IndexedDBThread");
852     indexed_db_thread_.reset();
853   }
854 #endif
855
856   // Close the blocking I/O pool after the other threads. Other threads such
857   // as the I/O thread may need to schedule work like closing files or flushing
858   // data during shutdown, so the blocking pool needs to be available. There
859   // may also be slow operations pending that will blcok shutdown, so closing
860   // it here (which will block until required operations are complete) gives
861   // more head start for those operations to finish.
862   {
863     TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:ThreadPool");
864     BrowserThreadImpl::ShutdownThreadPool();
865   }
866
867 #if !defined(OS_IOS)
868   // Must happen after the IO thread is shutdown since this may be accessed from
869   // it.
870   {
871     TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUChannelFactory");
872     if (BrowserGpuChannelHostFactory::instance())
873       BrowserGpuChannelHostFactory::Terminate();
874 #if defined(USE_OZONE)
875     if (OzoneChannelHostFactory::instance())
876       OzoneChannelHostFactory::Terminate();
877 #endif
878   }
879
880   // Must happen after the I/O thread is shutdown since this class lives on the
881   // I/O thread and isn't threadsafe.
882   {
883     TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GamepadService");
884     GamepadService::GetInstance()->Terminate();
885   }
886   {
887     TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:SensorService");
888     DeviceInertialSensorService::GetInstance()->Shutdown();
889   }
890   {
891     TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DeleteDataSources");
892     URLDataManager::DeleteDataSources();
893   }
894 #endif  // !defined(OS_IOS)
895
896   if (parts_) {
897     TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:PostDestroyThreads");
898     parts_->PostDestroyThreads();
899   }
900 }
901
902 void BrowserMainLoop::InitializeMainThread() {
903   TRACE_EVENT0("startup", "BrowserMainLoop::InitializeMainThread");
904   const char* kThreadName = "CrBrowserMain";
905   base::PlatformThread::SetName(kThreadName);
906   if (main_message_loop_)
907     main_message_loop_->set_thread_name(kThreadName);
908
909   // Register the main thread by instantiating it, but don't call any methods.
910   main_thread_.reset(
911       new BrowserThreadImpl(BrowserThread::UI, base::MessageLoop::current()));
912 }
913
914 int BrowserMainLoop::BrowserThreadsStarted() {
915   TRACE_EVENT0("startup", "BrowserMainLoop::BrowserThreadsStarted");
916
917 #if !defined(OS_IOS)
918   indexed_db_thread_.reset(new base::Thread("IndexedDB"));
919   indexed_db_thread_->Start();
920 #endif
921
922 #if defined(OS_ANDROID)
923   // Up the priority of anything that touches with display tasks
924   // (this thread is UI thread, and io_thread_ is for IPCs).
925   io_thread_->SetPriority(base::kThreadPriority_Display);
926   base::PlatformThread::SetThreadPriority(
927       base::PlatformThread::CurrentHandle(),
928       base::kThreadPriority_Display);
929 #endif
930
931 #if !defined(OS_IOS)
932   HistogramSynchronizer::GetInstance();
933
934 #if defined(OS_ANDROID)
935   // On Android, GLSurface::InitializeOneOff() must be called before initalizing
936   // the GpuDataManagerImpl as it uses the GL bindings. crbug.com/326295
937   if (!gfx::GLSurface::InitializeOneOff())
938     LOG(FATAL) << "GLSurface::InitializeOneOff failed";
939 #endif
940
941   // Initialize the GpuDataManager before we set up the MessageLoops because
942   // otherwise we'll trigger the assertion about doing IO on the UI thread.
943   GpuDataManagerImpl::GetInstance()->Initialize();
944
945   bool always_uses_gpu = true;
946   bool established_gpu_channel = false;
947 #if defined(USE_AURA) || defined(OS_MACOSX)
948   if (ShouldInitializeBrowserGpuChannelAndTransportSurface()) {
949     established_gpu_channel = true;
950     if (!GpuDataManagerImpl::GetInstance()->CanUseGpuBrowserCompositor()) {
951       established_gpu_channel = always_uses_gpu = false;
952     }
953     BrowserGpuChannelHostFactory::Initialize(established_gpu_channel);
954     ImageTransportFactory::Initialize();
955   }
956 #elif defined(OS_ANDROID)
957   established_gpu_channel = true;
958   BrowserGpuChannelHostFactory::Initialize(established_gpu_channel);
959 #endif
960
961 #if defined(OS_LINUX) && defined(USE_UDEV)
962   device_monitor_linux_.reset(new DeviceMonitorLinux());
963 #elif defined(OS_MACOSX)
964   device_monitor_mac_.reset(new DeviceMonitorMac());
965 #endif
966
967 #if defined(USE_OZONE)
968   ui::OzonePlatform::Initialize();
969   ui::EventFactoryOzone::GetInstance()->SetFileTaskRunner(
970       BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE));
971 #endif
972
973   // RDH needs the IO thread to be created
974   {
975     TRACE_EVENT0("startup",
976       "BrowserMainLoop::BrowserThreadsStarted:InitResourceDispatcherHost");
977     resource_dispatcher_host_.reset(new ResourceDispatcherHostImpl());
978   }
979
980   // MediaStreamManager needs the IO thread to be created.
981   {
982     TRACE_EVENT0("startup",
983       "BrowserMainLoop::BrowserThreadsStarted:InitMediaStreamManager");
984     media_stream_manager_.reset(new MediaStreamManager(audio_manager_.get()));
985   }
986
987   {
988     TRACE_EVENT0("startup",
989       "BrowserMainLoop::BrowserThreadsStarted:InitSpeechRecognition");
990     speech_recognition_manager_.reset(new SpeechRecognitionManagerImpl(
991         audio_manager_.get(), media_stream_manager_.get()));
992   }
993
994   {
995     TRACE_EVENT0(
996         "startup",
997         "BrowserMainLoop::BrowserThreadsStarted::InitUserInputMonitor");
998     user_input_monitor_ = media::UserInputMonitor::Create(
999         io_thread_->message_loop_proxy(), main_thread_->message_loop_proxy());
1000   }
1001
1002   {
1003     TRACE_EVENT0("startup",
1004                  "BrowserMainLoop::BrowserThreadsStarted::TimeZoneMonitor");
1005     time_zone_monitor_ = TimeZoneMonitor::Create();
1006   }
1007
1008   // Alert the clipboard class to which threads are allowed to access the
1009   // clipboard:
1010   std::vector<base::PlatformThreadId> allowed_clipboard_threads;
1011   // The current thread is the UI thread.
1012   allowed_clipboard_threads.push_back(base::PlatformThread::CurrentId());
1013 #if defined(OS_WIN)
1014   // On Windows, clipboards are also used on the File or IO threads.
1015   allowed_clipboard_threads.push_back(file_thread_->thread_id());
1016   allowed_clipboard_threads.push_back(io_thread_->thread_id());
1017 #endif
1018   ui::Clipboard::SetAllowedThreads(allowed_clipboard_threads);
1019
1020   // When running the GPU thread in-process, avoid optimistically starting it
1021   // since creating the GPU thread races against creation of the one-and-only
1022   // ChildProcess instance which is created by the renderer thread.
1023   if (GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL) &&
1024       !established_gpu_channel &&
1025       always_uses_gpu &&
1026       !parsed_command_line_.HasSwitch(switches::kSingleProcess) &&
1027       !parsed_command_line_.HasSwitch(switches::kInProcessGPU)) {
1028     TRACE_EVENT_INSTANT0("gpu", "Post task to launch GPU process",
1029                          TRACE_EVENT_SCOPE_THREAD);
1030     BrowserThread::PostTask(
1031         BrowserThread::IO, FROM_HERE, base::Bind(
1032             base::IgnoreResult(&GpuProcessHost::Get),
1033             GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED,
1034             CAUSE_FOR_GPU_LAUNCH_BROWSER_STARTUP));
1035   }
1036
1037 #if defined(OS_MACOSX)
1038   ThemeHelperMac::GetInstance();
1039 #endif
1040
1041 #if defined(USE_OZONE)
1042   bool using_gpu_process =
1043       established_gpu_channel &&
1044       !parsed_command_line_.HasSwitch(switches::kSingleProcess) &&
1045       !parsed_command_line_.HasSwitch(switches::kInProcessGPU);
1046   OzoneChannelHostFactory::Initialize(using_gpu_process);
1047 #endif
1048 #endif  // !defined(OS_IOS)
1049
1050   return result_code_;
1051 }
1052
1053 bool 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.
1061
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
1067
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
1076
1077 #if defined(USE_AURA)
1078
1079 #if defined(USE_X11)
1080   if (!gfx::GetXDisplay())
1081     return false;
1082 #endif
1083
1084   // Env creates the compositor. Aura widgets need the compositor to be created
1085   // before they can be initialized by the browser.
1086   aura::Env::CreateInstance(true);
1087 #endif  // defined(USE_AURA)
1088
1089   if (parts_)
1090     parts_->ToolkitInitialized();
1091
1092   return true;
1093 }
1094
1095 void BrowserMainLoop::MainMessageLoopRun() {
1096 #if defined(OS_ANDROID)
1097   // Android's main message loop is the Java message loop.
1098   NOTREACHED();
1099 #else
1100   DCHECK(base::MessageLoopForUI::IsCurrent());
1101   if (parameters_.ui_task)
1102     base::MessageLoopForUI::current()->PostTask(FROM_HERE,
1103                                                 *parameters_.ui_task);
1104
1105   base::RunLoop run_loop;
1106   run_loop.Run();
1107 #endif
1108 }
1109
1110 void BrowserMainLoop::InitStartupTracing(const CommandLine& command_line) {
1111   DCHECK(is_tracing_startup_);
1112
1113   base::FilePath trace_file = command_line.GetSwitchValuePath(
1114       switches::kTraceStartupFile);
1115   // trace_file = "none" means that startup events will show up for the next
1116   // begin/end tracing (via about:tracing or AutomationProxy::BeginTracing/
1117   // EndTracing, for example).
1118   if (trace_file == base::FilePath().AppendASCII("none"))
1119     return;
1120
1121   if (trace_file.empty()) {
1122 #if defined(OS_ANDROID)
1123     TracingControllerAndroid::GenerateTracingFilePath(&trace_file);
1124 #else
1125     // Default to saving the startup trace into the current dir.
1126     trace_file = base::FilePath().AppendASCII("chrometrace.log");
1127 #endif
1128   }
1129
1130   std::string delay_str = command_line.GetSwitchValueASCII(
1131       switches::kTraceStartupDuration);
1132   int delay_secs = 5;
1133   if (!delay_str.empty() && !base::StringToInt(delay_str, &delay_secs)) {
1134     DLOG(WARNING) << "Could not parse --" << switches::kTraceStartupDuration
1135         << "=" << delay_str << " defaulting to 5 (secs)";
1136     delay_secs = 5;
1137   }
1138
1139   BrowserThread::PostDelayedTask(
1140       BrowserThread::UI, FROM_HERE,
1141       base::Bind(&BrowserMainLoop::EndStartupTracing,
1142                  base::Unretained(this), trace_file),
1143       base::TimeDelta::FromSeconds(delay_secs));
1144 }
1145
1146 void BrowserMainLoop::EndStartupTracing(const base::FilePath& trace_file) {
1147   is_tracing_startup_ = false;
1148   TracingController::GetInstance()->DisableRecording(
1149       trace_file, base::Bind(&OnStoppedStartupTracing));
1150 }
1151
1152 }  // namespace content