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