- add sources.
[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_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/net/browser_online_state_observer.h"
38 #include "content/browser/plugin_service_impl.h"
39 #include "content/browser/renderer_host/media/audio_mirroring_manager.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/tracing/trace_controller_impl.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/common/content_switches.h"
51 #include "content/public/common/main_function_params.h"
52 #include "content/public/common/result_codes.h"
53 #include "crypto/nss_util.h"
54 #include "media/audio/audio_manager.h"
55 #include "media/base/media.h"
56 #include "media/base/user_input_monitor.h"
57 #include "media/midi/midi_manager.h"
58 #include "net/base/network_change_notifier.h"
59 #include "net/socket/client_socket_factory.h"
60 #include "net/ssl/ssl_config_service.h"
61 #include "ui/base/clipboard/clipboard.h"
62
63 #if defined(USE_AURA)
64 #include "content/browser/aura/image_transport_factory.h"
65 #endif
66
67 #if defined(OS_ANDROID)
68 #include "base/android/jni_android.h"
69 #include "content/browser/android/browser_startup_controller.h"
70 #include "content/browser/android/surface_texture_peer_browser_impl.h"
71 #endif
72
73 #if defined(OS_WIN)
74 #include <windows.h>
75 #include <commctrl.h>
76 #include <shellapi.h>
77
78 #include "base/win/text_services_message_filter.h"
79 #include "content/browser/system_message_window_win.h"
80 #include "content/common/sandbox_win.h"
81 #include "net/base/winsock_init.h"
82 #include "ui/base/l10n/l10n_util_win.h"
83 #endif
84
85 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
86 #include <glib-object.h>
87 #endif
88
89 #if defined(OS_LINUX)
90 #include "content/browser/device_monitor_linux.h"
91 #elif defined(OS_MACOSX) && !defined(OS_IOS)
92 #include "content/browser/device_monitor_mac.h"
93 #endif
94
95 #if defined(TOOLKIT_GTK)
96 #include "ui/gfx/gtk_util.h"
97 #endif
98
99 #if defined(OS_POSIX) && !defined(OS_MACOSX)
100 #include <sys/stat.h>
101
102 #include "content/browser/renderer_host/render_sandbox_host_linux.h"
103 #include "content/browser/zygote_host/zygote_host_impl_linux.h"
104 #endif
105
106 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
107 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
108 #endif
109
110 #if defined(USE_X11)
111 #include <X11/Xlib.h>
112 #endif
113
114 // One of the linux specific headers defines this as a macro.
115 #ifdef DestroyAll
116 #undef DestroyAll
117 #endif
118
119 namespace content {
120 namespace {
121
122 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
123 void SetupSandbox(const CommandLine& parsed_command_line) {
124   TRACE_EVENT0("startup", "SetupSandbox");
125   // TODO(evanm): move this into SandboxWrapper; I'm just trying to move this
126   // code en masse out of chrome_main for now.
127   base::FilePath sandbox_binary;
128   bool env_chrome_devel_sandbox_set = false;
129   struct stat st;
130
131   const bool want_setuid_sandbox =
132       !parsed_command_line.HasSwitch(switches::kNoSandbox) &&
133       !parsed_command_line.HasSwitch(switches::kDisableSetuidSandbox);
134
135   if (want_setuid_sandbox) {
136     base::FilePath exe_dir;
137     if (PathService::Get(base::DIR_EXE, &exe_dir)) {
138       base::FilePath sandbox_candidate = exe_dir.AppendASCII("chrome-sandbox");
139       if (base::PathExists(sandbox_candidate))
140         sandbox_binary = sandbox_candidate;
141     }
142
143     // In user-managed builds, including development builds, an environment
144     // variable is required to enable the sandbox. See
145     // http://code.google.com/p/chromium/wiki/LinuxSUIDSandboxDevelopment
146     if (sandbox_binary.empty() &&
147         stat(base::kProcSelfExe, &st) == 0 && st.st_uid == getuid()) {
148       const char* devel_sandbox_path = getenv("CHROME_DEVEL_SANDBOX");
149       if (devel_sandbox_path) {
150         env_chrome_devel_sandbox_set = true;
151         sandbox_binary = base::FilePath(devel_sandbox_path);
152       }
153     }
154
155     static const char no_suid_error[] = "Running without the SUID sandbox! See "
156         "https://code.google.com/p/chromium/wiki/LinuxSUIDSandboxDevelopment "
157         "for more information on developing with the sandbox on.";
158     if (sandbox_binary.empty()) {
159       if (!env_chrome_devel_sandbox_set) {
160         // This needs to be fatal. Talk to security@chromium.org if you feel
161         // otherwise.
162         LOG(FATAL) << no_suid_error;
163       }
164
165       // TODO(jln): an empty CHROME_DEVEL_SANDBOX environment variable (as
166       // opposed to a non existing one) is not fatal yet. This is needed
167       // because of existing bots and scripts. Fix it (crbug.com/245376).
168       LOG(ERROR) << no_suid_error;
169     }
170   }
171
172   // Tickle the sandbox host and zygote host so they fork now.
173   RenderSandboxHostLinux::GetInstance()->Init(sandbox_binary.value());
174   ZygoteHostImpl::GetInstance()->Init(sandbox_binary.value());
175 }
176 #endif
177
178 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
179 static void GLibLogHandler(const gchar* log_domain,
180                            GLogLevelFlags log_level,
181                            const gchar* message,
182                            gpointer userdata) {
183   if (!log_domain)
184     log_domain = "<unknown>";
185   if (!message)
186     message = "<no message>";
187
188   if (strstr(message, "Loading IM context type") ||
189       strstr(message, "wrong ELF class: ELFCLASS64")) {
190     // http://crbug.com/9643
191     // Until we have a real 64-bit build or all of these 32-bit package issues
192     // are sorted out, don't fatal on ELF 32/64-bit mismatch warnings and don't
193     // spam the user with more than one of them.
194     static bool alerted = false;
195     if (!alerted) {
196       LOG(ERROR) << "Bug 9643: " << log_domain << ": " << message;
197       alerted = true;
198     }
199   } else if (strstr(message, "Unable to retrieve the file info for")) {
200     LOG(ERROR) << "GTK File code error: " << message;
201   } else if (strstr(message, "Could not find the icon") &&
202              strstr(log_domain, "Gtk")) {
203     LOG(ERROR) << "GTK icon error: " << message;
204   } else if (strstr(message, "Theme file for default has no") ||
205              strstr(message, "Theme directory") ||
206              strstr(message, "theme pixmap") ||
207              strstr(message, "locate theme engine")) {
208     LOG(ERROR) << "GTK theme error: " << message;
209   } else if (strstr(message, "Unable to create Ubuntu Menu Proxy") &&
210              strstr(log_domain, "<unknown>")) {
211     LOG(ERROR) << "GTK menu proxy create failed";
212   } else if (strstr(message, "gtk_drag_dest_leave: assertion")) {
213     LOG(ERROR) << "Drag destination deleted: http://crbug.com/18557";
214   } else if (strstr(message, "Out of memory") &&
215              strstr(log_domain, "<unknown>")) {
216     LOG(ERROR) << "DBus call timeout or out of memory: "
217                << "http://crosbug.com/15496";
218   } else if (strstr(message, "Could not connect: Connection refused") &&
219              strstr(log_domain, "<unknown>")) {
220     LOG(ERROR) << "DConf settings backend could not connect to session bus: "
221                << "http://crbug.com/179797";
222   } else if (strstr(message, "XDG_RUNTIME_DIR variable not set")) {
223     LOG(ERROR) << message << " (http://bugs.chromium.org/97293)";
224   } else if (strstr(message, "Attempting to store changes into") ||
225              strstr(message, "Attempting to set the permissions of")) {
226     LOG(ERROR) << message << " (http://bugs.chromium.org/161366)";
227   } else {
228     LOG(DFATAL) << log_domain << ": " << message;
229   }
230 }
231
232 static void SetUpGLibLogHandler() {
233   // Register GLib-handled assertions to go through our logging system.
234   const char* kLogDomains[] = { NULL, "Gtk", "Gdk", "GLib", "GLib-GObject" };
235   for (size_t i = 0; i < arraysize(kLogDomains); i++) {
236     g_log_set_handler(kLogDomains[i],
237                       static_cast<GLogLevelFlags>(G_LOG_FLAG_RECURSION |
238                                                   G_LOG_FLAG_FATAL |
239                                                   G_LOG_LEVEL_ERROR |
240                                                   G_LOG_LEVEL_CRITICAL |
241                                                   G_LOG_LEVEL_WARNING),
242                       GLibLogHandler,
243                       NULL);
244   }
245 }
246 #endif
247
248 }  // namespace
249
250 // The currently-running BrowserMainLoop.  There can be one or zero.
251 BrowserMainLoop* g_current_browser_main_loop = NULL;
252
253 // This is just to be able to keep ShutdownThreadsAndCleanUp out of
254 // the public interface of BrowserMainLoop.
255 class BrowserShutdownImpl {
256  public:
257   static void ImmediateShutdownAndExitProcess() {
258     DCHECK(g_current_browser_main_loop);
259     g_current_browser_main_loop->ShutdownThreadsAndCleanUp();
260
261 #if defined(OS_WIN)
262     // At this point the message loop is still running yet we've shut everything
263     // down. If any messages are processed we'll likely crash. Exit now.
264     ExitProcess(RESULT_CODE_NORMAL_EXIT);
265 #elif defined(OS_POSIX) && !defined(OS_MACOSX)
266     _exit(RESULT_CODE_NORMAL_EXIT);
267 #else
268     NOTIMPLEMENTED();
269 #endif
270   }
271 };
272
273 void ImmediateShutdownAndExitProcess() {
274   BrowserShutdownImpl::ImmediateShutdownAndExitProcess();
275 }
276
277 // For measuring memory usage after each task. Behind a command line flag.
278 class BrowserMainLoop::MemoryObserver : public base::MessageLoop::TaskObserver {
279  public:
280   MemoryObserver() {}
281   virtual ~MemoryObserver() {}
282
283   virtual void WillProcessTask(const base::PendingTask& pending_task) OVERRIDE {
284   }
285
286   virtual void DidProcessTask(const base::PendingTask& pending_task) OVERRIDE {
287 #if !defined(OS_IOS)  // No ProcessMetrics on IOS.
288     scoped_ptr<base::ProcessMetrics> process_metrics(
289         base::ProcessMetrics::CreateProcessMetrics(
290 #if defined(OS_MACOSX)
291             base::GetCurrentProcessHandle(), NULL));
292 #else
293             base::GetCurrentProcessHandle()));
294 #endif
295     size_t private_bytes;
296     process_metrics->GetMemoryBytes(&private_bytes, NULL);
297     HISTOGRAM_MEMORY_KB("Memory.BrowserUsed", private_bytes >> 10);
298 #endif
299   }
300  private:
301   DISALLOW_COPY_AND_ASSIGN(MemoryObserver);
302 };
303
304
305 // BrowserMainLoop construction / destruction =============================
306
307 BrowserMainLoop* BrowserMainLoop::GetInstance() {
308   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
309   return g_current_browser_main_loop;
310 }
311
312 BrowserMainLoop::BrowserMainLoop(const MainFunctionParams& parameters)
313     : parameters_(parameters),
314       parsed_command_line_(parameters.command_line),
315       result_code_(RESULT_CODE_NORMAL_EXIT),
316       created_threads_(false) {
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 #if defined(USE_X11)
340   if (parsed_command_line_.HasSwitch(switches::kSingleProcess) ||
341       parsed_command_line_.HasSwitch(switches::kInProcessGPU)) {
342     if (!XInitThreads()) {
343       LOG(ERROR) << "Failed to put Xlib into threaded mode.";
344     }
345   }
346 #endif
347
348   // Due to bugs in GLib we need to initialize GLib/GTK before we start threads;
349   // see crbug.com/309093. Sandbox setup spawns sub-processes and a thread
350   // running waitpid().
351 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
352   // g_type_init will be deprecated in 2.36. 2.35 is the development
353   // version for 2.36, hence do not call g_type_init starting 2.35.
354   // http://developer.gnome.org/gobject/unstable/gobject-Type-Information.html#g-type-init
355 #if !GLIB_CHECK_VERSION(2, 35, 0)
356   // GLib type system initialization. Needed at least for gconf,
357   // used in net/proxy/proxy_config_service_linux.cc. Most likely
358   // this is superfluous as gtk_init() ought to do this. It's
359   // definitely harmless, so retained as a reminder of this
360   // requirement for gconf.
361   g_type_init();
362 #endif
363
364 #if !defined(USE_AURA)
365   gfx::GtkInitFromCommandLine(parsed_command_line_);
366 #endif
367
368   SetUpGLibLogHandler();
369 #endif
370
371   if (parts_)
372     parts_->PreEarlyInitialization();
373
374 #if defined(OS_WIN)
375   net::EnsureWinsockInit();
376 #endif
377
378 #if !defined(USE_OPENSSL)
379   // We want to be sure to init NSPR on the main thread.
380   crypto::EnsureNSPRInit();
381 #endif  // !defined(USE_OPENSSL)
382
383 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
384   SetupSandbox(parsed_command_line_);
385 #endif
386
387   if (parsed_command_line_.HasSwitch(switches::kEnableSSLCachedInfo))
388     net::SSLConfigService::EnableCachedInfo();
389
390 #if !defined(OS_IOS)
391   if (parsed_command_line_.HasSwitch(switches::kRendererProcessLimit)) {
392     std::string limit_string = parsed_command_line_.GetSwitchValueASCII(
393         switches::kRendererProcessLimit);
394     size_t process_limit;
395     if (base::StringToSizeT(limit_string, &process_limit)) {
396       RenderProcessHost::SetMaxRendererProcessCount(process_limit);
397     }
398   }
399 #endif  // !defined(OS_IOS)
400
401   if (parts_)
402     parts_->PostEarlyInitialization();
403 }
404
405 void BrowserMainLoop::MainMessageLoopStart() {
406   TRACE_EVENT0("startup", "BrowserMainLoop::MainMessageLoopStart")
407   if (parts_) {
408     TRACE_EVENT0("startup",
409         "BrowserMainLoop::MainMessageLoopStart:PreMainMessageLoopStart");
410     parts_->PreMainMessageLoopStart();
411   }
412
413 #if defined(OS_WIN)
414   // If we're running tests (ui_task is non-null), then the ResourceBundle
415   // has already been initialized.
416   if (!parameters_.ui_task) {
417     // Override the configured locale with the user's preferred UI language.
418     l10n_util::OverrideLocaleWithUILanguageList();
419   }
420 #endif
421
422   // Create a MessageLoop if one does not already exist for the current thread.
423   if (!base::MessageLoop::current())
424     main_message_loop_.reset(new base::MessageLoop(base::MessageLoop::TYPE_UI));
425
426   InitializeMainThread();
427
428   {
429     TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SystemMonitor")
430     system_monitor_.reset(new base::SystemMonitor);
431   }
432   {
433     TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:PowerMonitor")
434     scoped_ptr<base::PowerMonitorSource> power_monitor_source(
435       new base::PowerMonitorDeviceSource());
436     power_monitor_.reset(new base::PowerMonitor(power_monitor_source.Pass()));
437   }
438   {
439     TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:HighResTimerManager")
440     hi_res_timer_manager_.reset(new base::HighResolutionTimerManager);
441   }
442   {
443     TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:NetworkChangeNotifier")
444     network_change_notifier_.reset(net::NetworkChangeNotifier::Create());
445   }
446
447 #if !defined(OS_IOS)
448   {
449     TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MediaFeatures")
450     media::InitializeCPUSpecificMediaFeatures();
451   }
452   {
453     TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:AudioMan")
454     audio_manager_.reset(media::AudioManager::Create());
455   }
456   {
457     TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MIDIManager")
458     midi_manager_.reset(media::MIDIManager::Create());
459   }
460   {
461     TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:ContentWebUIController")
462     WebUIControllerFactory::RegisterFactory(
463         ContentWebUIControllerFactory::GetInstance());
464   }
465
466   {
467     TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:AudioMirroringManager")
468     audio_mirroring_manager_.reset(new AudioMirroringManager());
469   }
470
471   // Start tracing to a file if needed.
472   if (base::debug::TraceLog::GetInstance()->IsEnabled()) {
473     TRACE_EVENT0("startup", "BrowserMainLoop::InitStartupTracing")
474     TraceControllerImpl::GetInstance()->InitStartupTracing(
475         parsed_command_line_);
476   }
477
478   {
479     TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:OnlineStateObserver")
480     online_state_observer_.reset(new BrowserOnlineStateObserver);
481   }
482
483   {
484     system_stats_monitor_.reset(new base::debug::TraceEventSystemStatsMonitor(
485         base::ThreadTaskRunnerHandle::Get()));
486   }
487 #endif  // !defined(OS_IOS)
488
489 #if defined(OS_WIN)
490   system_message_window_.reset(new SystemMessageWindowWin);
491
492   if (base::win::IsTSFAwareRequired()) {
493     // Create a TSF message filter for the message loop. MessageLoop takes
494     // ownership of the filter.
495     scoped_ptr<base::win::TextServicesMessageFilter> tsf_message_filter(
496       new base::win::TextServicesMessageFilter);
497     if (tsf_message_filter->Init()) {
498       base::MessageLoopForUI::current()->SetMessageFilter(
499         tsf_message_filter.PassAs<base::MessageLoopForUI::MessageFilter>());
500     }
501   }
502 #endif
503
504   if (parts_)
505     parts_->PostMainMessageLoopStart();
506
507 #if defined(OS_ANDROID)
508   {
509     TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SurfaceTexturePeer")
510     SurfaceTexturePeer::InitInstance(new SurfaceTexturePeerBrowserImpl());
511   }
512 #endif
513
514   if (parsed_command_line_.HasSwitch(switches::kMemoryMetrics)) {
515     TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MemoryObserver")
516     memory_observer_.reset(new MemoryObserver());
517     base::MessageLoop::current()->AddTaskObserver(memory_observer_.get());
518   }
519
520 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
521   trace_memory_controller_.reset(new base::debug::TraceMemoryController(
522       base::MessageLoop::current()->message_loop_proxy(),
523       ::HeapProfilerWithPseudoStackStart,
524       ::HeapProfilerStop,
525       ::GetHeapProfile));
526 #endif
527 }
528
529 int BrowserMainLoop::PreCreateThreads() {
530
531   if (parts_) {
532     TRACE_EVENT0("startup",
533         "BrowserMainLoop::CreateThreads:PreCreateThreads");
534     result_code_ = parts_->PreCreateThreads();
535   }
536
537 #if defined(ENABLE_PLUGINS)
538   // Prior to any processing happening on the io thread, we create the
539   // plugin service as it is predominantly used from the io thread,
540   // but must be created on the main thread. The service ctor is
541   // inexpensive and does not invoke the io_thread() accessor.
542   {
543     TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads:PluginService")
544     PluginService::GetInstance()->Init();
545   }
546 #endif
547
548 #if !defined(OS_IOS) && (!defined(GOOGLE_CHROME_BUILD) || defined(OS_ANDROID))
549   // Single-process is an unsupported and not fully tested mode, so
550   // don't enable it for official Chrome builds (except on Android).
551   if (parsed_command_line_.HasSwitch(switches::kSingleProcess))
552     RenderProcessHost::SetRunRendererInProcess(true);
553 #endif
554   return result_code_;
555 }
556
557 void BrowserMainLoop::CreateStartupTasks() {
558   TRACE_EVENT0("startup", "BrowserMainLoop::CreateStartupTasks");
559
560   // First time through, we really want to create all the tasks
561   if (!startup_task_runner_.get()) {
562 #if defined(OS_ANDROID)
563     startup_task_runner_ = make_scoped_ptr(new StartupTaskRunner(
564         base::Bind(&BrowserStartupComplete),
565         base::MessageLoop::current()->message_loop_proxy()));
566 #else
567     startup_task_runner_ = make_scoped_ptr(new StartupTaskRunner(
568         base::Callback<void(int)>(),
569         base::MessageLoop::current()->message_loop_proxy()));
570 #endif
571     StartupTask pre_create_threads =
572         base::Bind(&BrowserMainLoop::PreCreateThreads, base::Unretained(this));
573     startup_task_runner_->AddTask(pre_create_threads);
574
575     StartupTask create_threads =
576         base::Bind(&BrowserMainLoop::CreateThreads, base::Unretained(this));
577     startup_task_runner_->AddTask(create_threads);
578
579     StartupTask browser_thread_started = base::Bind(
580         &BrowserMainLoop::BrowserThreadsStarted, base::Unretained(this));
581     startup_task_runner_->AddTask(browser_thread_started);
582
583     StartupTask pre_main_message_loop_run = base::Bind(
584         &BrowserMainLoop::PreMainMessageLoopRun, base::Unretained(this));
585     startup_task_runner_->AddTask(pre_main_message_loop_run);
586
587 #if defined(OS_ANDROID)
588     if (BrowserMayStartAsynchronously()) {
589       startup_task_runner_->StartRunningTasksAsync();
590     }
591 #endif
592   }
593 #if defined(OS_ANDROID)
594   if (!BrowserMayStartAsynchronously()) {
595     // A second request for asynchronous startup can be ignored, so
596     // StartupRunningTasksAsync is only called first time through. If, however,
597     // this is a request for synchronous startup then it must override any
598     // previous call for async startup, so we call RunAllTasksNow()
599     // unconditionally.
600     startup_task_runner_->RunAllTasksNow();
601   }
602 #else
603   startup_task_runner_->RunAllTasksNow();
604 #endif
605 }
606
607 int BrowserMainLoop::CreateThreads() {
608   TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads");
609
610   base::Thread::Options default_options;
611   base::Thread::Options io_message_loop_options;
612   io_message_loop_options.message_loop_type = base::MessageLoop::TYPE_IO;
613   base::Thread::Options ui_message_loop_options;
614   ui_message_loop_options.message_loop_type = base::MessageLoop::TYPE_UI;
615
616   // Start threads in the order they occur in the BrowserThread::ID
617   // enumeration, except for BrowserThread::UI which is the main
618   // thread.
619   //
620   // Must be size_t so we can increment it.
621   for (size_t thread_id = BrowserThread::UI + 1;
622        thread_id < BrowserThread::ID_COUNT;
623        ++thread_id) {
624     scoped_ptr<BrowserProcessSubThread>* thread_to_start = NULL;
625     base::Thread::Options* options = &default_options;
626
627     switch (thread_id) {
628       case BrowserThread::DB:
629         TRACE_EVENT_BEGIN1("startup",
630             "BrowserMainLoop::CreateThreads:start",
631             "Thread", "BrowserThread::DB");
632         thread_to_start = &db_thread_;
633         break;
634       case BrowserThread::FILE_USER_BLOCKING:
635         TRACE_EVENT_BEGIN1("startup",
636             "BrowserMainLoop::CreateThreads:start",
637             "Thread", "BrowserThread::FILE_USER_BLOCKING");
638         thread_to_start = &file_user_blocking_thread_;
639         break;
640       case BrowserThread::FILE:
641         TRACE_EVENT_BEGIN1("startup",
642             "BrowserMainLoop::CreateThreads:start",
643             "Thread", "BrowserThread::FILE");
644         thread_to_start = &file_thread_;
645 #if defined(OS_WIN)
646         // On Windows, the FILE thread needs to be have a UI message loop
647         // which pumps messages in such a way that Google Update can
648         // communicate back to us.
649         options = &ui_message_loop_options;
650 #else
651         options = &io_message_loop_options;
652 #endif
653         break;
654       case BrowserThread::PROCESS_LAUNCHER:
655         TRACE_EVENT_BEGIN1("startup",
656             "BrowserMainLoop::CreateThreads:start",
657             "Thread", "BrowserThread::PROCESS_LAUNCHER");
658         thread_to_start = &process_launcher_thread_;
659         break;
660       case BrowserThread::CACHE:
661         TRACE_EVENT_BEGIN1("startup",
662             "BrowserMainLoop::CreateThreads:start",
663             "Thread", "BrowserThread::CACHE");
664         thread_to_start = &cache_thread_;
665         options = &io_message_loop_options;
666         break;
667       case BrowserThread::IO:
668         TRACE_EVENT_BEGIN1("startup",
669             "BrowserMainLoop::CreateThreads:start",
670             "Thread", "BrowserThread::IO");
671         thread_to_start = &io_thread_;
672         options = &io_message_loop_options;
673         break;
674       case BrowserThread::UI:
675       case BrowserThread::ID_COUNT:
676       default:
677         NOTREACHED();
678         break;
679     }
680
681     BrowserThread::ID id = static_cast<BrowserThread::ID>(thread_id);
682
683     if (thread_to_start) {
684       (*thread_to_start).reset(new BrowserProcessSubThread(id));
685       (*thread_to_start)->StartWithOptions(*options);
686     } else {
687       NOTREACHED();
688     }
689
690     TRACE_EVENT_END0("startup", "BrowserMainLoop::CreateThreads:start");
691
692   }
693   created_threads_ = true;
694   return result_code_;
695 }
696
697 int BrowserMainLoop::PreMainMessageLoopRun() {
698   if (parts_) {
699     TRACE_EVENT0("startup",
700         "BrowserMainLoop::CreateThreads:PreMainMessageLoopRun");
701     parts_->PreMainMessageLoopRun();
702   }
703
704   // If the UI thread blocks, the whole UI is unresponsive.
705   // Do not allow disk IO from the UI thread.
706   base::ThreadRestrictions::SetIOAllowed(false);
707   base::ThreadRestrictions::DisallowWaiting();
708   return result_code_;
709 }
710
711 void BrowserMainLoop::RunMainMessageLoopParts() {
712   TRACE_EVENT_BEGIN_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
713
714   bool ran_main_loop = false;
715   if (parts_)
716     ran_main_loop = parts_->MainMessageLoopRun(&result_code_);
717
718   if (!ran_main_loop)
719     MainMessageLoopRun();
720
721   TRACE_EVENT_END_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
722 }
723
724 void BrowserMainLoop::ShutdownThreadsAndCleanUp() {
725   if (!created_threads_) {
726     // Called early, nothing to do
727     return;
728   }
729   TRACE_EVENT0("shutdown", "BrowserMainLoop::ShutdownThreadsAndCleanUp")
730
731   // Teardown may start in PostMainMessageLoopRun, and during teardown we
732   // need to be able to perform IO.
733   base::ThreadRestrictions::SetIOAllowed(true);
734   BrowserThread::PostTask(
735       BrowserThread::IO, FROM_HERE,
736       base::Bind(base::IgnoreResult(&base::ThreadRestrictions::SetIOAllowed),
737                  true));
738
739   if (RenderProcessHost::run_renderer_in_process() &&
740       !RenderProcessHost::AllHostsIterator().IsAtEnd()) {
741     delete RenderProcessHost::AllHostsIterator().GetCurrentValue();
742   }
743
744   if (parts_) {
745     TRACE_EVENT0("shutdown",
746                  "BrowserMainLoop::Subsystem:PostMainMessageLoopRun");
747     parts_->PostMainMessageLoopRun();
748   }
749
750   trace_memory_controller_.reset();
751   system_stats_monitor_.reset();
752
753 #if !defined(OS_IOS)
754   // Destroying the GpuProcessHostUIShims on the UI thread posts a task to
755   // delete related objects on the GPU thread. This must be done before
756   // stopping the GPU thread. The GPU thread will close IPC channels to renderer
757   // processes so this has to happen before stopping the IO thread.
758   {
759     TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUProcessHostShim");
760     GpuProcessHostUIShim::DestroyAll();
761   }
762   // Cancel pending requests and prevent new requests.
763   if (resource_dispatcher_host_) {
764     TRACE_EVENT0("shutdown",
765                  "BrowserMainLoop::Subsystem:ResourceDispatcherHost");
766     resource_dispatcher_host_.get()->Shutdown();
767   }
768
769 #if defined(USE_AURA)
770   {
771     TRACE_EVENT0("shutdown",
772                  "BrowserMainLoop::Subsystem:ImageTransportFactory");
773     ImageTransportFactory::Terminate();
774   }
775 #endif
776
777   // The device monitors are using |system_monitor_| as dependency, so delete
778   // them before |system_monitor_| goes away.
779   // On Mac and windows, the monitor needs to be destroyed on the same thread
780   // as they were created. On Linux, the monitor will be deleted when IO thread
781   // goes away.
782 #if defined(OS_WIN)
783   system_message_window_.reset();
784 #elif defined(OS_MACOSX)
785   device_monitor_mac_.reset();
786 #endif
787 #endif  // !defined(OS_IOS)
788
789   // Must be size_t so we can subtract from it.
790   for (size_t thread_id = BrowserThread::ID_COUNT - 1;
791        thread_id >= (BrowserThread::UI + 1);
792        --thread_id) {
793     // Find the thread object we want to stop. Looping over all valid
794     // BrowserThread IDs and DCHECKing on a missing case in the switch
795     // statement helps avoid a mismatch between this code and the
796     // BrowserThread::ID enumeration.
797     //
798     // The destruction order is the reverse order of occurrence in the
799     // BrowserThread::ID list. The rationale for the order is as
800     // follows (need to be filled in a bit):
801     //
802     //
803     // - The IO thread is the only user of the CACHE thread.
804     //
805     // - The PROCESS_LAUNCHER thread must be stopped after IO in case
806     //   the IO thread posted a task to terminate a process on the
807     //   process launcher thread.
808     //
809     // - (Not sure why DB stops last.)
810     switch (thread_id) {
811       case BrowserThread::DB: {
812           TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DBThread");
813           db_thread_.reset();
814         }
815         break;
816       case BrowserThread::FILE_USER_BLOCKING: {
817           TRACE_EVENT0("shutdown",
818                        "BrowserMainLoop::Subsystem:FileUserBlockingThread");
819           file_user_blocking_thread_.reset();
820         }
821         break;
822       case BrowserThread::FILE: {
823           TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:FileThread");
824 #if !defined(OS_IOS)
825           // Clean up state that lives on or uses the file_thread_ before
826           // it goes away.
827           if (resource_dispatcher_host_)
828             resource_dispatcher_host_.get()->save_file_manager()->Shutdown();
829 #endif  // !defined(OS_IOS)
830           file_thread_.reset();
831         }
832         break;
833       case BrowserThread::PROCESS_LAUNCHER: {
834           TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:LauncherThread");
835           process_launcher_thread_.reset();
836         }
837         break;
838       case BrowserThread::CACHE: {
839           TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:CacheThread");
840           cache_thread_.reset();
841         }
842         break;
843       case BrowserThread::IO: {
844           TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IOThread");
845           io_thread_.reset();
846         }
847         break;
848       case BrowserThread::UI:
849       case BrowserThread::ID_COUNT:
850       default:
851         NOTREACHED();
852         break;
853     }
854   }
855
856 #if !defined(OS_IOS)
857   {
858     TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IndexedDBThread");
859     indexed_db_thread_.reset();
860   }
861 #endif
862
863   // Close the blocking I/O pool after the other threads. Other threads such
864   // as the I/O thread may need to schedule work like closing files or flushing
865   // data during shutdown, so the blocking pool needs to be available. There
866   // may also be slow operations pending that will blcok shutdown, so closing
867   // it here (which will block until required operations are complete) gives
868   // more head start for those operations to finish.
869   {
870     TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:ThreadPool");
871     BrowserThreadImpl::ShutdownThreadPool();
872   }
873
874 #if !defined(OS_IOS)
875   // Must happen after the IO thread is shutdown since this may be accessed from
876   // it.
877   {
878     TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUChannelFactory");
879     if (BrowserGpuChannelHostFactory::instance())
880       BrowserGpuChannelHostFactory::Terminate();
881   }
882
883   // Must happen after the I/O thread is shutdown since this class lives on the
884   // I/O thread and isn't threadsafe.
885   {
886     TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GamepadService");
887     GamepadService::GetInstance()->Terminate();
888   }
889   {
890     TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:SensorService");
891     DeviceInertialSensorService::GetInstance()->Shutdown();
892   }
893   {
894     TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DeleteDataSources");
895     URLDataManager::DeleteDataSources();
896   }
897 #endif  // !defined(OS_IOS)
898
899   if (parts_) {
900     TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:PostDestroyThreads");
901     parts_->PostDestroyThreads();
902   }
903 }
904
905 void BrowserMainLoop::InitializeMainThread() {
906   TRACE_EVENT0("startup", "BrowserMainLoop::InitializeMainThread")
907   const char* kThreadName = "CrBrowserMain";
908   base::PlatformThread::SetName(kThreadName);
909   if (main_message_loop_)
910     main_message_loop_->set_thread_name(kThreadName);
911
912   // Register the main thread by instantiating it, but don't call any methods.
913   main_thread_.reset(
914       new BrowserThreadImpl(BrowserThread::UI, base::MessageLoop::current()));
915 }
916
917 int BrowserMainLoop::BrowserThreadsStarted() {
918   TRACE_EVENT0("startup", "BrowserMainLoop::BrowserThreadsStarted")
919
920 #if !defined(OS_IOS)
921   indexed_db_thread_.reset(new base::Thread("IndexedDB"));
922   indexed_db_thread_->Start();
923 #endif
924
925 #if defined(OS_ANDROID)
926   // Up the priority of anything that touches with display tasks
927   // (this thread is UI thread, and io_thread_ is for IPCs).
928   io_thread_->SetPriority(base::kThreadPriority_Display);
929   base::PlatformThread::SetThreadPriority(
930       base::PlatformThread::CurrentHandle(),
931       base::kThreadPriority_Display);
932 #endif
933
934 #if !defined(OS_IOS)
935   HistogramSynchronizer::GetInstance();
936
937   // Initialize the GpuDataManager before we set up the MessageLoops because
938   // otherwise we'll trigger the assertion about doing IO on the UI thread.
939   GpuDataManagerImpl::GetInstance()->Initialize();
940
941   bool always_uses_gpu = IsForceCompositingModeEnabled();
942   bool established_gpu_channel = false;
943 #if defined(USE_AURA) || defined(OS_ANDROID)
944   established_gpu_channel =
945       !parsed_command_line_.HasSwitch(switches::kDisableGpuProcessPrelaunch) ||
946       parsed_command_line_.HasSwitch(switches::kSingleProcess) ||
947       parsed_command_line_.HasSwitch(switches::kInProcessGPU);
948 #if defined(USE_AURA)
949   if (!GpuDataManagerImpl::GetInstance()->CanUseGpuBrowserCompositor()) {
950     established_gpu_channel = always_uses_gpu = false;
951   }
952   BrowserGpuChannelHostFactory::Initialize(established_gpu_channel);
953   ImageTransportFactory::Initialize();
954 #elif defined(OS_ANDROID)
955   BrowserGpuChannelHostFactory::Initialize(established_gpu_channel);
956 #endif
957 #endif
958
959 #if defined(OS_LINUX)
960   device_monitor_linux_.reset(new DeviceMonitorLinux());
961 #elif defined(OS_MACOSX)
962   device_monitor_mac_.reset(new DeviceMonitorMac());
963 #endif
964
965   // RDH needs the IO thread to be created
966   {
967     TRACE_EVENT0("startup",
968       "BrowserMainLoop::BrowserThreadsStarted:InitResourceDispatcherHost");
969     resource_dispatcher_host_.reset(new ResourceDispatcherHostImpl());
970   }
971
972   // MediaStreamManager needs the IO thread to be created.
973   {
974     TRACE_EVENT0("startup",
975       "BrowserMainLoop::BrowserThreadsStarted:InitMediaStreamManager");
976     media_stream_manager_.reset(new MediaStreamManager(audio_manager_.get()));
977   }
978
979   {
980     TRACE_EVENT0("startup",
981       "BrowserMainLoop::BrowserThreadsStarted:InitSpeechRecognition");
982     speech_recognition_manager_.reset(new SpeechRecognitionManagerImpl(
983         audio_manager_.get(), media_stream_manager_.get()));
984   }
985
986   {
987     TRACE_EVENT0(
988         "startup",
989         "BrowserMainLoop::BrowserThreadsStarted::InitUserInputMonitor");
990     user_input_monitor_ = media::UserInputMonitor::Create(
991         io_thread_->message_loop_proxy(), main_thread_->message_loop_proxy());
992   }
993
994   // Alert the clipboard class to which threads are allowed to access the
995   // clipboard:
996   std::vector<base::PlatformThreadId> allowed_clipboard_threads;
997   // The current thread is the UI thread.
998   allowed_clipboard_threads.push_back(base::PlatformThread::CurrentId());
999 #if defined(OS_WIN)
1000   // On Windows, clipboards are also used on the File or IO threads.
1001   allowed_clipboard_threads.push_back(file_thread_->thread_id());
1002   allowed_clipboard_threads.push_back(io_thread_->thread_id());
1003 #endif
1004   ui::Clipboard::SetAllowedThreads(allowed_clipboard_threads);
1005
1006   // When running the GPU thread in-process, avoid optimistically starting it
1007   // since creating the GPU thread races against creation of the one-and-only
1008   // ChildProcess instance which is created by the renderer thread.
1009   if (GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL) &&
1010       !established_gpu_channel &&
1011       always_uses_gpu &&
1012       !parsed_command_line_.HasSwitch(switches::kDisableGpuProcessPrelaunch) &&
1013       !parsed_command_line_.HasSwitch(switches::kSingleProcess) &&
1014       !parsed_command_line_.HasSwitch(switches::kInProcessGPU)) {
1015     TRACE_EVENT_INSTANT0("gpu", "Post task to launch GPU process",
1016                          TRACE_EVENT_SCOPE_THREAD);
1017     BrowserThread::PostTask(
1018         BrowserThread::IO, FROM_HERE, base::Bind(
1019             base::IgnoreResult(&GpuProcessHost::Get),
1020             GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED,
1021             CAUSE_FOR_GPU_LAUNCH_BROWSER_STARTUP));
1022   }
1023 #endif  // !defined(OS_IOS)
1024   return result_code_;
1025 }
1026
1027 void BrowserMainLoop::InitializeToolkit() {
1028   TRACE_EVENT0("startup", "BrowserMainLoop::InitializeToolkit")
1029   // TODO(evan): this function is rather subtle, due to the variety
1030   // of intersecting ifdefs we have.  To keep it easy to follow, there
1031   // are no #else branches on any #ifs.
1032   // TODO(stevenjb): Move platform specific code into platform specific Parts
1033   // (Need to add InitializeToolkit stage to BrowserParts).
1034   // See also GTK setup in EarlyInitialization, above, and associated comments.
1035
1036 #if defined(TOOLKIT_GTK)
1037   // It is important for this to happen before the first run dialog, as it
1038   // styles the dialog as well.
1039   gfx::InitRCStyles();
1040 #endif
1041
1042 #if defined(OS_WIN)
1043   // Init common control sex.
1044   INITCOMMONCONTROLSEX config;
1045   config.dwSize = sizeof(config);
1046   config.dwICC = ICC_WIN95_CLASSES;
1047   if (!InitCommonControlsEx(&config))
1048     LOG_GETLASTERROR(FATAL);
1049 #endif
1050
1051   if (parts_)
1052     parts_->ToolkitInitialized();
1053 }
1054
1055 void BrowserMainLoop::MainMessageLoopRun() {
1056 #if defined(OS_ANDROID)
1057   // Android's main message loop is the Java message loop.
1058   NOTREACHED();
1059 #else
1060   DCHECK_EQ(base::MessageLoop::TYPE_UI, base::MessageLoop::current()->type());
1061   if (parameters_.ui_task)
1062     base::MessageLoopForUI::current()->PostTask(FROM_HERE,
1063                                                 *parameters_.ui_task);
1064
1065   base::RunLoop run_loop;
1066   run_loop.Run();
1067 #endif
1068 }
1069
1070 }  // namespace content