Delete chrome.mediaGalleriesPrivate because the functionality unique to it has since...
[chromium-blink-merge.git] / content / browser / browser_main_loop.cc
blob64e3446bcce54b75ed116e3820d246929c916dcc
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/browser/browser_main_loop.h"
7 #include "base/bind.h"
8 #include "base/command_line.h"
9 #include "base/debug/trace_event.h"
10 #include "base/logging.h"
11 #include "base/message_loop/message_loop.h"
12 #include "base/metrics/field_trial.h"
13 #include "base/metrics/histogram.h"
14 #include "base/pending_task.h"
15 #include "base/power_monitor/power_monitor.h"
16 #include "base/power_monitor/power_monitor_device_source.h"
17 #include "base/process/process_metrics.h"
18 #include "base/run_loop.h"
19 #include "base/strings/string_number_conversions.h"
20 #include "base/system_monitor/system_monitor.h"
21 #include "base/thread_task_runner_handle.h"
22 #include "base/threading/thread_restrictions.h"
23 #include "base/timer/hi_res_timer_manager.h"
24 #include "content/browser/browser_thread_impl.h"
25 #include "content/browser/device_sensors/device_inertial_sensor_service.h"
26 #include "content/browser/download/save_file_manager.h"
27 #include "content/browser/gamepad/gamepad_service.h"
28 #include "content/browser/gpu/browser_gpu_channel_host_factory.h"
29 #include "content/browser/gpu/compositor_util.h"
30 #include "content/browser/gpu/gpu_data_manager_impl.h"
31 #include "content/browser/gpu/gpu_process_host.h"
32 #include "content/browser/gpu/gpu_process_host_ui_shim.h"
33 #include "content/browser/histogram_synchronizer.h"
34 #include "content/browser/loader/resource_dispatcher_host_impl.h"
35 #include "content/browser/media/media_internals.h"
36 #include "content/browser/net/browser_online_state_observer.h"
37 #include "content/browser/renderer_host/media/media_stream_manager.h"
38 #include "content/browser/speech/speech_recognition_manager_impl.h"
39 #include "content/browser/startup_task_runner.h"
40 #include "content/browser/time_zone_monitor.h"
41 #include "content/browser/webui/content_web_ui_controller_factory.h"
42 #include "content/browser/webui/url_data_manager.h"
43 #include "content/public/browser/browser_main_parts.h"
44 #include "content/public/browser/browser_shutdown.h"
45 #include "content/public/browser/content_browser_client.h"
46 #include "content/public/browser/render_process_host.h"
47 #include "content/public/browser/tracing_controller.h"
48 #include "content/public/common/content_switches.h"
49 #include "content/public/common/main_function_params.h"
50 #include "content/public/common/result_codes.h"
51 #include "crypto/nss_util.h"
52 #include "device/battery/battery_status_service.h"
53 #include "media/audio/audio_manager.h"
54 #include "media/base/media.h"
55 #include "media/base/user_input_monitor.h"
56 #include "media/midi/midi_manager.h"
57 #include "net/base/network_change_notifier.h"
58 #include "net/socket/client_socket_factory.h"
59 #include "net/ssl/ssl_config_service.h"
60 #include "ui/base/clipboard/clipboard.h"
62 #if defined(USE_AURA) || (defined(OS_MACOSX) && !defined(OS_IOS))
63 #include "content/browser/compositor/image_transport_factory.h"
64 #endif
66 #if defined(USE_AURA)
67 #include "content/public/browser/context_factory.h"
68 #include "ui/aura/env.h"
69 #endif
71 #if !defined(OS_IOS)
72 #include "content/browser/renderer_host/render_process_host_impl.h"
73 #endif
75 #if defined(OS_ANDROID)
76 #include "base/android/jni_android.h"
77 #include "content/browser/android/browser_startup_controller.h"
78 #include "content/browser/android/browser_surface_texture_manager.h"
79 #include "content/browser/android/tracing_controller_android.h"
80 #include "content/browser/screen_orientation/screen_orientation_delegate_android.h"
81 #include "content/public/browser/screen_orientation_provider.h"
82 #include "ui/gl/gl_surface.h"
83 #endif
85 #if defined(OS_MACOSX) && !defined(OS_IOS)
86 #include "content/browser/bootstrap_sandbox_mac.h"
87 #include "content/browser/cocoa/system_hotkey_helper_mac.h"
88 #include "content/browser/compositor/browser_compositor_view_mac.h"
89 #include "content/browser/theme_helper_mac.h"
90 #endif
92 #if defined(OS_WIN)
93 #include <windows.h>
94 #include <commctrl.h>
95 #include <shellapi.h>
97 #include "content/browser/system_message_window_win.h"
98 #include "content/common/sandbox_win.h"
99 #include "net/base/winsock_init.h"
100 #include "ui/base/l10n/l10n_util_win.h"
101 #endif
103 #if defined(OS_CHROMEOS)
104 #include "base/chromeos/memory_pressure_observer_chromeos.h"
105 #include "chromeos/chromeos_switches.h"
106 #endif
108 #if defined(USE_GLIB)
109 #include <glib-object.h>
110 #endif
112 #if defined(OS_LINUX) && defined(USE_UDEV)
113 #include "content/browser/device_monitor_udev.h"
114 #elif defined(OS_MACOSX) && !defined(OS_IOS)
115 #include "content/browser/device_monitor_mac.h"
116 #endif
118 #if defined(OS_POSIX) && !defined(OS_MACOSX)
119 #include "content/browser/renderer_host/render_sandbox_host_linux.h"
120 #include "content/browser/zygote_host/zygote_host_impl_linux.h"
121 #include "sandbox/linux/suid/client/setuid_sandbox_client.h"
122 #endif
124 #if defined(ENABLE_PLUGINS)
125 #include "content/browser/plugin_service_impl.h"
126 #endif
128 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
129 #include "third_party/tcmalloc/chromium/src/gperftools/heap-profiler.h"
130 #endif
132 #if defined(USE_X11)
133 #include "ui/gfx/x/x11_connection.h"
134 #include "ui/gfx/x/x11_types.h"
135 #endif
137 // One of the linux specific headers defines this as a macro.
138 #ifdef DestroyAll
139 #undef DestroyAll
140 #endif
142 namespace content {
143 namespace {
145 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
146 void SetupSandbox(const base::CommandLine& parsed_command_line) {
147 TRACE_EVENT0("startup", "SetupSandbox");
148 base::FilePath sandbox_binary;
150 scoped_ptr<sandbox::SetuidSandboxClient> setuid_sandbox_client(
151 sandbox::SetuidSandboxClient::Create());
153 const bool want_setuid_sandbox =
154 !parsed_command_line.HasSwitch(switches::kNoSandbox) &&
155 !parsed_command_line.HasSwitch(switches::kDisableSetuidSandbox) &&
156 !setuid_sandbox_client->IsDisabledViaEnvironment();
158 static const char no_suid_error[] =
159 "Running without the SUID sandbox! See "
160 "https://code.google.com/p/chromium/wiki/LinuxSUIDSandboxDevelopment "
161 "for more information on developing with the sandbox on.";
162 if (want_setuid_sandbox) {
163 sandbox_binary = setuid_sandbox_client->GetSandboxBinaryPath();
164 if (sandbox_binary.empty()) {
165 // This needs to be fatal. Talk to security@chromium.org if you feel
166 // otherwise.
167 LOG(FATAL) << no_suid_error;
169 } else {
170 LOG(ERROR) << no_suid_error;
173 // Tickle the sandbox host and zygote host so they fork now.
174 RenderSandboxHostLinux::GetInstance()->Init();
175 ZygoteHostImpl::GetInstance()->Init(sandbox_binary.value());
177 #endif
179 #if defined(USE_GLIB)
180 static void GLibLogHandler(const gchar* log_domain,
181 GLogLevelFlags log_level,
182 const gchar* message,
183 gpointer userdata) {
184 if (!log_domain)
185 log_domain = "<unknown>";
186 if (!message)
187 message = "<no message>";
189 if (strstr(message, "Unable to retrieve the file info for")) {
190 LOG(ERROR) << "GTK File code error: " << message;
191 } else if (strstr(message, "Could not find the icon") &&
192 strstr(log_domain, "Gtk")) {
193 LOG(ERROR) << "GTK icon error: " << message;
194 } else if (strstr(message, "Theme file for default has no") ||
195 strstr(message, "Theme directory") ||
196 strstr(message, "theme pixmap") ||
197 strstr(message, "locate theme engine")) {
198 LOG(ERROR) << "GTK theme error: " << message;
199 } else if (strstr(message, "Unable to create Ubuntu Menu Proxy") &&
200 strstr(log_domain, "<unknown>")) {
201 LOG(ERROR) << "GTK menu proxy create failed";
202 } else if (strstr(message, "Out of memory") &&
203 strstr(log_domain, "<unknown>")) {
204 LOG(ERROR) << "DBus call timeout or out of memory: "
205 << "http://crosbug.com/15496";
206 } else if (strstr(message, "Could not connect: Connection refused") &&
207 strstr(log_domain, "<unknown>")) {
208 LOG(ERROR) << "DConf settings backend could not connect to session bus: "
209 << "http://crbug.com/179797";
210 } else if (strstr(message, "Attempting to store changes into") ||
211 strstr(message, "Attempting to set the permissions of")) {
212 LOG(ERROR) << message << " (http://bugs.chromium.org/161366)";
213 } else if (strstr(message, "drawable is not a native X11 window")) {
214 LOG(ERROR) << message << " (http://bugs.chromium.org/329991)";
215 } else {
216 LOG(DFATAL) << log_domain << ": " << message;
220 static void SetUpGLibLogHandler() {
221 // Register GLib-handled assertions to go through our logging system.
222 const char* kLogDomains[] = { NULL, "Gtk", "Gdk", "GLib", "GLib-GObject" };
223 for (size_t i = 0; i < arraysize(kLogDomains); i++) {
224 g_log_set_handler(kLogDomains[i],
225 static_cast<GLogLevelFlags>(G_LOG_FLAG_RECURSION |
226 G_LOG_FLAG_FATAL |
227 G_LOG_LEVEL_ERROR |
228 G_LOG_LEVEL_CRITICAL |
229 G_LOG_LEVEL_WARNING),
230 GLibLogHandler,
231 NULL);
234 #endif
236 void OnStoppedStartupTracing(const base::FilePath& trace_file) {
237 VLOG(0) << "Completed startup tracing to " << trace_file.value();
240 // Disable optimizations for this block of functions so the compiler doesn't
241 // merge them all together. This makes it possible to tell what thread was
242 // unresponsive by inspecting the callstack.
243 MSVC_DISABLE_OPTIMIZE()
244 MSVC_PUSH_DISABLE_WARNING(4748)
246 NOINLINE void ResetThread_DB(scoped_ptr<BrowserProcessSubThread> thread) {
247 volatile int inhibit_comdat = __LINE__;
248 ALLOW_UNUSED_LOCAL(inhibit_comdat);
249 thread.reset();
252 NOINLINE void ResetThread_FILE(scoped_ptr<BrowserProcessSubThread> thread) {
253 volatile int inhibit_comdat = __LINE__;
254 ALLOW_UNUSED_LOCAL(inhibit_comdat);
255 thread.reset();
258 NOINLINE void ResetThread_FILE_USER_BLOCKING(
259 scoped_ptr<BrowserProcessSubThread> thread) {
260 volatile int inhibit_comdat = __LINE__;
261 ALLOW_UNUSED_LOCAL(inhibit_comdat);
262 thread.reset();
265 NOINLINE void ResetThread_PROCESS_LAUNCHER(
266 scoped_ptr<BrowserProcessSubThread> thread) {
267 volatile int inhibit_comdat = __LINE__;
268 ALLOW_UNUSED_LOCAL(inhibit_comdat);
269 thread.reset();
272 NOINLINE void ResetThread_CACHE(scoped_ptr<BrowserProcessSubThread> thread) {
273 volatile int inhibit_comdat = __LINE__;
274 ALLOW_UNUSED_LOCAL(inhibit_comdat);
275 thread.reset();
278 NOINLINE void ResetThread_IO(scoped_ptr<BrowserProcessSubThread> thread) {
279 volatile int inhibit_comdat = __LINE__;
280 ALLOW_UNUSED_LOCAL(inhibit_comdat);
281 thread.reset();
284 #if !defined(OS_IOS)
285 NOINLINE void ResetThread_IndexedDb(scoped_ptr<base::Thread> thread) {
286 volatile int inhibit_comdat = __LINE__;
287 ALLOW_UNUSED_LOCAL(inhibit_comdat);
288 thread.reset();
290 #endif
292 MSVC_POP_WARNING()
293 MSVC_ENABLE_OPTIMIZE();
295 } // namespace
297 // The currently-running BrowserMainLoop. There can be one or zero.
298 BrowserMainLoop* g_current_browser_main_loop = NULL;
300 // This is just to be able to keep ShutdownThreadsAndCleanUp out of
301 // the public interface of BrowserMainLoop.
302 class BrowserShutdownImpl {
303 public:
304 static void ImmediateShutdownAndExitProcess() {
305 DCHECK(g_current_browser_main_loop);
306 g_current_browser_main_loop->ShutdownThreadsAndCleanUp();
308 #if defined(OS_WIN)
309 // At this point the message loop is still running yet we've shut everything
310 // down. If any messages are processed we'll likely crash. Exit now.
311 ExitProcess(RESULT_CODE_NORMAL_EXIT);
312 #elif defined(OS_POSIX) && !defined(OS_MACOSX)
313 _exit(RESULT_CODE_NORMAL_EXIT);
314 #else
315 NOTIMPLEMENTED();
316 #endif
320 void ImmediateShutdownAndExitProcess() {
321 BrowserShutdownImpl::ImmediateShutdownAndExitProcess();
324 // For measuring memory usage after each task. Behind a command line flag.
325 class BrowserMainLoop::MemoryObserver : public base::MessageLoop::TaskObserver {
326 public:
327 MemoryObserver() {}
328 ~MemoryObserver() override {}
330 void WillProcessTask(const base::PendingTask& pending_task) override {}
332 void DidProcessTask(const base::PendingTask& pending_task) override {
333 #if !defined(OS_IOS) // No ProcessMetrics on IOS.
334 scoped_ptr<base::ProcessMetrics> process_metrics(
335 base::ProcessMetrics::CreateProcessMetrics(
336 #if defined(OS_MACOSX)
337 base::GetCurrentProcessHandle(), NULL));
338 #else
339 base::GetCurrentProcessHandle()));
340 #endif
341 size_t private_bytes;
342 process_metrics->GetMemoryBytes(&private_bytes, NULL);
343 LOCAL_HISTOGRAM_MEMORY_KB("Memory.BrowserUsed", private_bytes >> 10);
344 #endif
346 private:
347 DISALLOW_COPY_AND_ASSIGN(MemoryObserver);
351 // BrowserMainLoop construction / destruction =============================
353 BrowserMainLoop* BrowserMainLoop::GetInstance() {
354 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
355 return g_current_browser_main_loop;
358 BrowserMainLoop::BrowserMainLoop(const MainFunctionParams& parameters)
359 : parameters_(parameters),
360 parsed_command_line_(parameters.command_line),
361 result_code_(RESULT_CODE_NORMAL_EXIT),
362 created_threads_(false),
363 // ContentMainRunner should have enabled tracing of the browser process
364 // when kTraceStartup is in the command line.
365 is_tracing_startup_(
366 parameters.command_line.HasSwitch(switches::kTraceStartup)) {
367 DCHECK(!g_current_browser_main_loop);
368 g_current_browser_main_loop = this;
371 BrowserMainLoop::~BrowserMainLoop() {
372 DCHECK_EQ(this, g_current_browser_main_loop);
373 #if !defined(OS_IOS)
374 ui::Clipboard::DestroyClipboardForCurrentThread();
375 #endif // !defined(OS_IOS)
376 g_current_browser_main_loop = NULL;
379 void BrowserMainLoop::Init() {
380 TRACE_EVENT0("startup", "BrowserMainLoop::Init");
381 parts_.reset(
382 GetContentClient()->browser()->CreateBrowserMainParts(parameters_));
385 // BrowserMainLoop stages ==================================================
387 void BrowserMainLoop::EarlyInitialization() {
388 TRACE_EVENT0("startup", "BrowserMainLoop::EarlyInitialization");
390 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
391 // No thread should be created before this call, as SetupSandbox()
392 // will end-up using fork().
393 SetupSandbox(parsed_command_line_);
394 #endif
396 #if defined(USE_X11)
397 if (parsed_command_line_.HasSwitch(switches::kSingleProcess) ||
398 parsed_command_line_.HasSwitch(switches::kInProcessGPU)) {
399 if (!gfx::InitializeThreadedX11()) {
400 LOG(ERROR) << "Failed to put Xlib into threaded mode.";
403 #endif
405 // GLib's spawning of new processes is buggy, so it's important that at this
406 // point GLib does not need to start DBUS. Chrome should always start with
407 // DBUS_SESSION_BUS_ADDRESS properly set. See crbug.com/309093.
408 #if defined(USE_GLIB)
409 // g_type_init will be deprecated in 2.36. 2.35 is the development
410 // version for 2.36, hence do not call g_type_init starting 2.35.
411 // http://developer.gnome.org/gobject/unstable/gobject-Type-Information.html#g-type-init
412 #if !GLIB_CHECK_VERSION(2, 35, 0)
413 // GLib type system initialization. Needed at least for gconf,
414 // used in net/proxy/proxy_config_service_linux.cc. Most likely
415 // this is superfluous as gtk_init() ought to do this. It's
416 // definitely harmless, so retained as a reminder of this
417 // requirement for gconf.
418 g_type_init();
419 #endif
421 SetUpGLibLogHandler();
422 #endif
424 if (parts_)
425 parts_->PreEarlyInitialization();
427 #if defined(OS_MACOSX)
428 // We use quite a few file descriptors for our IPC, and the default limit on
429 // the Mac is low (256), so bump it up.
430 base::SetFdLimit(1024);
431 #endif
433 #if defined(OS_WIN)
434 net::EnsureWinsockInit();
435 #endif
437 #if !defined(USE_OPENSSL)
438 // We want to be sure to init NSPR on the main thread.
439 crypto::EnsureNSPRInit();
440 #endif // !defined(USE_OPENSSL)
442 #if !defined(OS_IOS)
443 if (parsed_command_line_.HasSwitch(switches::kRendererProcessLimit)) {
444 std::string limit_string = parsed_command_line_.GetSwitchValueASCII(
445 switches::kRendererProcessLimit);
446 size_t process_limit;
447 if (base::StringToSizeT(limit_string, &process_limit)) {
448 RenderProcessHost::SetMaxRendererProcessCount(process_limit);
451 #endif // !defined(OS_IOS)
453 if (parsed_command_line_.HasSwitch(switches::kEnableNativeGpuMemoryBuffers)) {
454 BrowserGpuChannelHostFactory::EnableGpuMemoryBufferFactoryUsage(
455 gfx::GpuMemoryBuffer::MAP);
458 #if defined(USE_OZONE)
459 BrowserGpuChannelHostFactory::EnableGpuMemoryBufferFactoryUsage(
460 gfx::GpuMemoryBuffer::SCANOUT);
461 #endif
463 if (parts_)
464 parts_->PostEarlyInitialization();
467 void BrowserMainLoop::MainMessageLoopStart() {
468 TRACE_EVENT0("startup", "BrowserMainLoop::MainMessageLoopStart");
469 if (parts_) {
470 TRACE_EVENT0("startup",
471 "BrowserMainLoop::MainMessageLoopStart:PreMainMessageLoopStart");
472 parts_->PreMainMessageLoopStart();
475 #if defined(OS_WIN)
476 // If we're running tests (ui_task is non-null), then the ResourceBundle
477 // has already been initialized.
478 if (!parameters_.ui_task) {
479 // Override the configured locale with the user's preferred UI language.
480 l10n_util::OverrideLocaleWithUILanguageList();
482 #endif
484 // Create a MessageLoop if one does not already exist for the current thread.
485 if (!base::MessageLoop::current())
486 main_message_loop_.reset(new base::MessageLoopForUI);
488 InitializeMainThread();
490 #if defined(OS_CHROMEOS)
491 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
492 chromeos::switches::kDisableMemoryPressureSystemChromeOS)) {
493 memory_pressure_observer_.reset(new base::MemoryPressureObserverChromeOS(
494 chromeos::switches::GetMemoryPressureThresholds()));
496 #endif
499 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SystemMonitor");
500 system_monitor_.reset(new base::SystemMonitor);
503 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:PowerMonitor");
504 scoped_ptr<base::PowerMonitorSource> power_monitor_source(
505 new base::PowerMonitorDeviceSource());
506 power_monitor_.reset(new base::PowerMonitor(power_monitor_source.Pass()));
509 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:HighResTimerManager");
510 hi_res_timer_manager_.reset(new base::HighResolutionTimerManager);
513 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:NetworkChangeNotifier");
514 network_change_notifier_.reset(net::NetworkChangeNotifier::Create());
517 #if !defined(OS_IOS)
519 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MediaFeatures");
520 media::InitializeCPUSpecificMediaFeatures();
523 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:AudioMan");
524 audio_manager_.reset(media::AudioManager::Create(
525 MediaInternals::GetInstance()));
528 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MidiManager");
529 midi_manager_.reset(media::MidiManager::Create());
532 TRACE_EVENT0("startup",
533 "BrowserMainLoop::Subsystem:ContentWebUIController");
534 WebUIControllerFactory::RegisterFactory(
535 ContentWebUIControllerFactory::GetInstance());
539 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:OnlineStateObserver");
540 online_state_observer_.reset(new BrowserOnlineStateObserver);
544 system_stats_monitor_.reset(new base::debug::TraceEventSystemStatsMonitor(
545 base::ThreadTaskRunnerHandle::Get()));
547 #endif // !defined(OS_IOS)
549 #if defined(OS_WIN)
550 system_message_window_.reset(new SystemMessageWindowWin);
551 #endif
553 if (parts_)
554 parts_->PostMainMessageLoopStart();
556 #if !defined(OS_IOS)
557 // Start tracing to a file if needed. Only do this after starting the main
558 // message loop to avoid calling MessagePumpForUI::ScheduleWork() before
559 // MessagePumpForUI::Start() as it will crash the browser.
560 if (is_tracing_startup_) {
561 TRACE_EVENT0("startup", "BrowserMainLoop::InitStartupTracing");
562 InitStartupTracing(parsed_command_line_);
564 #endif // !defined(OS_IOS)
566 #if defined(OS_ANDROID)
568 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:SurfaceTextureManager");
569 SurfaceTextureManager::InitInstance(new BrowserSurfaceTextureManager);
573 TRACE_EVENT0("startup",
574 "BrowserMainLoop::Subsystem:ScreenOrientationProvider");
575 screen_orientation_delegate_.reset(
576 new ScreenOrientationDelegateAndroid());
577 ScreenOrientationProvider::SetDelegate(screen_orientation_delegate_.get());
579 #endif
581 if (parsed_command_line_.HasSwitch(switches::kMemoryMetrics)) {
582 TRACE_EVENT0("startup", "BrowserMainLoop::Subsystem:MemoryObserver");
583 memory_observer_.reset(new MemoryObserver());
584 base::MessageLoop::current()->AddTaskObserver(memory_observer_.get());
587 #if defined(TCMALLOC_TRACE_MEMORY_SUPPORTED)
588 trace_memory_controller_.reset(new base::debug::TraceMemoryController(
589 base::MessageLoop::current()->message_loop_proxy(),
590 ::HeapProfilerWithPseudoStackStart,
591 ::HeapProfilerStop,
592 ::GetHeapProfile));
593 #endif
596 int BrowserMainLoop::PreCreateThreads() {
597 if (parts_) {
598 TRACE_EVENT0("startup",
599 "BrowserMainLoop::CreateThreads:PreCreateThreads");
600 result_code_ = parts_->PreCreateThreads();
603 #if defined(ENABLE_PLUGINS)
604 // Prior to any processing happening on the io thread, we create the
605 // plugin service as it is predominantly used from the io thread,
606 // but must be created on the main thread. The service ctor is
607 // inexpensive and does not invoke the io_thread() accessor.
609 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads:PluginService");
610 PluginService::GetInstance()->Init();
612 #endif
614 #if !defined(OS_IOS) && (!defined(GOOGLE_CHROME_BUILD) || defined(OS_ANDROID))
615 // Single-process is an unsupported and not fully tested mode, so
616 // don't enable it for official Chrome builds (except on Android).
617 if (parsed_command_line_.HasSwitch(switches::kSingleProcess))
618 RenderProcessHost::SetRunRendererInProcess(true);
619 #endif
620 return result_code_;
623 void BrowserMainLoop::CreateStartupTasks() {
624 TRACE_EVENT0("startup", "BrowserMainLoop::CreateStartupTasks");
626 // First time through, we really want to create all the tasks
627 if (!startup_task_runner_.get()) {
628 #if defined(OS_ANDROID)
629 startup_task_runner_ = make_scoped_ptr(new StartupTaskRunner(
630 base::Bind(&BrowserStartupComplete),
631 base::MessageLoop::current()->message_loop_proxy()));
632 #else
633 startup_task_runner_ = make_scoped_ptr(new StartupTaskRunner(
634 base::Callback<void(int)>(),
635 base::MessageLoop::current()->message_loop_proxy()));
636 #endif
637 StartupTask pre_create_threads =
638 base::Bind(&BrowserMainLoop::PreCreateThreads, base::Unretained(this));
639 startup_task_runner_->AddTask(pre_create_threads);
641 StartupTask create_threads =
642 base::Bind(&BrowserMainLoop::CreateThreads, base::Unretained(this));
643 startup_task_runner_->AddTask(create_threads);
645 StartupTask browser_thread_started = base::Bind(
646 &BrowserMainLoop::BrowserThreadsStarted, base::Unretained(this));
647 startup_task_runner_->AddTask(browser_thread_started);
649 StartupTask pre_main_message_loop_run = base::Bind(
650 &BrowserMainLoop::PreMainMessageLoopRun, base::Unretained(this));
651 startup_task_runner_->AddTask(pre_main_message_loop_run);
653 #if defined(OS_ANDROID)
654 if (BrowserMayStartAsynchronously()) {
655 startup_task_runner_->StartRunningTasksAsync();
657 #endif
659 #if defined(OS_ANDROID)
660 if (!BrowserMayStartAsynchronously()) {
661 // A second request for asynchronous startup can be ignored, so
662 // StartupRunningTasksAsync is only called first time through. If, however,
663 // this is a request for synchronous startup then it must override any
664 // previous call for async startup, so we call RunAllTasksNow()
665 // unconditionally.
666 startup_task_runner_->RunAllTasksNow();
668 #else
669 startup_task_runner_->RunAllTasksNow();
670 #endif
673 int BrowserMainLoop::CreateThreads() {
674 TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads");
676 base::Thread::Options io_message_loop_options;
677 io_message_loop_options.message_loop_type = base::MessageLoop::TYPE_IO;
678 base::Thread::Options ui_message_loop_options;
679 ui_message_loop_options.message_loop_type = base::MessageLoop::TYPE_UI;
681 // Start threads in the order they occur in the BrowserThread::ID
682 // enumeration, except for BrowserThread::UI which is the main
683 // thread.
685 // Must be size_t so we can increment it.
686 for (size_t thread_id = BrowserThread::UI + 1;
687 thread_id < BrowserThread::ID_COUNT;
688 ++thread_id) {
689 scoped_ptr<BrowserProcessSubThread>* thread_to_start = NULL;
690 base::Thread::Options options;
692 switch (thread_id) {
693 case BrowserThread::DB:
694 TRACE_EVENT_BEGIN1("startup",
695 "BrowserMainLoop::CreateThreads:start",
696 "Thread", "BrowserThread::DB");
697 thread_to_start = &db_thread_;
698 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
699 break;
700 case BrowserThread::FILE_USER_BLOCKING:
701 TRACE_EVENT_BEGIN1("startup",
702 "BrowserMainLoop::CreateThreads:start",
703 "Thread", "BrowserThread::FILE_USER_BLOCKING");
704 thread_to_start = &file_user_blocking_thread_;
705 break;
706 case BrowserThread::FILE:
707 TRACE_EVENT_BEGIN1("startup",
708 "BrowserMainLoop::CreateThreads:start",
709 "Thread", "BrowserThread::FILE");
710 thread_to_start = &file_thread_;
711 #if defined(OS_WIN)
712 // On Windows, the FILE thread needs to be have a UI message loop
713 // which pumps messages in such a way that Google Update can
714 // communicate back to us.
715 options = ui_message_loop_options;
716 #else
717 options = io_message_loop_options;
718 #endif
719 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
720 break;
721 case BrowserThread::PROCESS_LAUNCHER:
722 TRACE_EVENT_BEGIN1("startup",
723 "BrowserMainLoop::CreateThreads:start",
724 "Thread", "BrowserThread::PROCESS_LAUNCHER");
725 thread_to_start = &process_launcher_thread_;
726 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
727 break;
728 case BrowserThread::CACHE:
729 TRACE_EVENT_BEGIN1("startup",
730 "BrowserMainLoop::CreateThreads:start",
731 "Thread", "BrowserThread::CACHE");
732 thread_to_start = &cache_thread_;
733 options = io_message_loop_options;
734 options.timer_slack = base::TIMER_SLACK_MAXIMUM;
735 break;
736 case BrowserThread::IO:
737 TRACE_EVENT_BEGIN1("startup",
738 "BrowserMainLoop::CreateThreads:start",
739 "Thread", "BrowserThread::IO");
740 thread_to_start = &io_thread_;
741 options = io_message_loop_options;
742 break;
743 case BrowserThread::UI:
744 case BrowserThread::ID_COUNT:
745 default:
746 NOTREACHED();
747 break;
750 BrowserThread::ID id = static_cast<BrowserThread::ID>(thread_id);
752 if (thread_to_start) {
753 (*thread_to_start).reset(new BrowserProcessSubThread(id));
754 if (!(*thread_to_start)->StartWithOptions(options)) {
755 LOG(FATAL) << "Failed to start the browser thread: id == " << id;
757 } else {
758 NOTREACHED();
761 TRACE_EVENT_END0("startup", "BrowserMainLoop::CreateThreads:start");
763 created_threads_ = true;
764 return result_code_;
767 int BrowserMainLoop::PreMainMessageLoopRun() {
768 if (parts_) {
769 TRACE_EVENT0("startup",
770 "BrowserMainLoop::CreateThreads:PreMainMessageLoopRun");
771 parts_->PreMainMessageLoopRun();
774 // If the UI thread blocks, the whole UI is unresponsive.
775 // Do not allow disk IO from the UI thread.
776 base::ThreadRestrictions::SetIOAllowed(false);
777 base::ThreadRestrictions::DisallowWaiting();
778 return result_code_;
781 void BrowserMainLoop::RunMainMessageLoopParts() {
782 TRACE_EVENT_BEGIN_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
784 bool ran_main_loop = false;
785 if (parts_)
786 ran_main_loop = parts_->MainMessageLoopRun(&result_code_);
788 if (!ran_main_loop)
789 MainMessageLoopRun();
791 TRACE_EVENT_END_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
794 void BrowserMainLoop::ShutdownThreadsAndCleanUp() {
795 if (!created_threads_) {
796 // Called early, nothing to do
797 return;
799 TRACE_EVENT0("shutdown", "BrowserMainLoop::ShutdownThreadsAndCleanUp");
801 // Teardown may start in PostMainMessageLoopRun, and during teardown we
802 // need to be able to perform IO.
803 base::ThreadRestrictions::SetIOAllowed(true);
804 BrowserThread::PostTask(
805 BrowserThread::IO, FROM_HERE,
806 base::Bind(base::IgnoreResult(&base::ThreadRestrictions::SetIOAllowed),
807 true));
809 #if !defined(OS_IOS)
810 if (RenderProcessHost::run_renderer_in_process())
811 RenderProcessHostImpl::ShutDownInProcessRenderer();
812 #endif
814 if (parts_) {
815 TRACE_EVENT0("shutdown",
816 "BrowserMainLoop::Subsystem:PostMainMessageLoopRun");
817 parts_->PostMainMessageLoopRun();
820 trace_memory_controller_.reset();
821 system_stats_monitor_.reset();
823 #if !defined(OS_IOS)
824 // Destroying the GpuProcessHostUIShims on the UI thread posts a task to
825 // delete related objects on the GPU thread. This must be done before
826 // stopping the GPU thread. The GPU thread will close IPC channels to renderer
827 // processes so this has to happen before stopping the IO thread.
829 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUProcessHostShim");
830 GpuProcessHostUIShim::DestroyAll();
832 // Cancel pending requests and prevent new requests.
833 if (resource_dispatcher_host_) {
834 TRACE_EVENT0("shutdown",
835 "BrowserMainLoop::Subsystem:ResourceDispatcherHost");
836 resource_dispatcher_host_.get()->Shutdown();
839 #if defined(OS_CHROMEOS)
840 memory_pressure_observer_.reset();
841 #endif
843 #if defined(OS_MACOSX)
844 BrowserCompositorMac::DisableRecyclingForShutdown();
845 #endif
847 #if defined(USE_AURA) || defined(OS_MACOSX)
849 TRACE_EVENT0("shutdown",
850 "BrowserMainLoop::Subsystem:ImageTransportFactory");
851 ImageTransportFactory::Terminate();
853 #endif
855 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
856 ZygoteHostImpl::GetInstance()->TearDownAfterLastChild();
857 #endif // defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
859 // The device monitors are using |system_monitor_| as dependency, so delete
860 // them before |system_monitor_| goes away.
861 // On Mac and windows, the monitor needs to be destroyed on the same thread
862 // as they were created. On Linux, the monitor will be deleted when IO thread
863 // goes away.
864 #if defined(OS_WIN)
865 system_message_window_.reset();
866 #elif defined(OS_MACOSX)
867 device_monitor_mac_.reset();
868 #endif
869 #endif // !defined(OS_IOS)
871 // Must be size_t so we can subtract from it.
872 for (size_t thread_id = BrowserThread::ID_COUNT - 1;
873 thread_id >= (BrowserThread::UI + 1);
874 --thread_id) {
875 // Find the thread object we want to stop. Looping over all valid
876 // BrowserThread IDs and DCHECKing on a missing case in the switch
877 // statement helps avoid a mismatch between this code and the
878 // BrowserThread::ID enumeration.
880 // The destruction order is the reverse order of occurrence in the
881 // BrowserThread::ID list. The rationale for the order is as
882 // follows (need to be filled in a bit):
885 // - The IO thread is the only user of the CACHE thread.
887 // - The PROCESS_LAUNCHER thread must be stopped after IO in case
888 // the IO thread posted a task to terminate a process on the
889 // process launcher thread.
891 // - (Not sure why DB stops last.)
892 switch (thread_id) {
893 case BrowserThread::DB: {
894 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DBThread");
895 ResetThread_DB(db_thread_.Pass());
896 break;
898 case BrowserThread::FILE: {
899 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:FileThread");
900 #if !defined(OS_IOS)
901 // Clean up state that lives on or uses the file_thread_ before
902 // it goes away.
903 if (resource_dispatcher_host_)
904 resource_dispatcher_host_.get()->save_file_manager()->Shutdown();
905 #endif // !defined(OS_IOS)
906 ResetThread_FILE(file_thread_.Pass());
907 break;
909 case BrowserThread::FILE_USER_BLOCKING: {
910 TRACE_EVENT0("shutdown",
911 "BrowserMainLoop::Subsystem:FileUserBlockingThread");
912 ResetThread_FILE_USER_BLOCKING(file_user_blocking_thread_.Pass());
913 break;
915 case BrowserThread::PROCESS_LAUNCHER: {
916 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:LauncherThread");
917 ResetThread_PROCESS_LAUNCHER(process_launcher_thread_.Pass());
918 break;
920 case BrowserThread::CACHE: {
921 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:CacheThread");
922 ResetThread_CACHE(cache_thread_.Pass());
923 break;
925 case BrowserThread::IO: {
926 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IOThread");
927 ResetThread_IO(io_thread_.Pass());
928 break;
930 case BrowserThread::UI:
931 case BrowserThread::ID_COUNT:
932 default:
933 NOTREACHED();
934 break;
938 #if !defined(OS_IOS)
940 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:IndexedDBThread");
941 ResetThread_IndexedDb(indexed_db_thread_.Pass());
943 #endif
945 // Close the blocking I/O pool after the other threads. Other threads such
946 // as the I/O thread may need to schedule work like closing files or flushing
947 // data during shutdown, so the blocking pool needs to be available. There
948 // may also be slow operations pending that will blcok shutdown, so closing
949 // it here (which will block until required operations are complete) gives
950 // more head start for those operations to finish.
952 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:ThreadPool");
953 BrowserThreadImpl::ShutdownThreadPool();
956 #if !defined(OS_IOS)
957 // Must happen after the IO thread is shutdown since this may be accessed from
958 // it.
960 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GPUChannelFactory");
961 if (BrowserGpuChannelHostFactory::instance())
962 BrowserGpuChannelHostFactory::Terminate();
965 // Must happen after the I/O thread is shutdown since this class lives on the
966 // I/O thread and isn't threadsafe.
968 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:GamepadService");
969 GamepadService::GetInstance()->Terminate();
972 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:SensorService");
973 DeviceInertialSensorService::GetInstance()->Shutdown();
976 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:BatteryStatusService");
977 device::BatteryStatusService::GetInstance()->Shutdown();
980 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:DeleteDataSources");
981 URLDataManager::DeleteDataSources();
983 #endif // !defined(OS_IOS)
985 if (parts_) {
986 TRACE_EVENT0("shutdown", "BrowserMainLoop::Subsystem:PostDestroyThreads");
987 parts_->PostDestroyThreads();
991 void BrowserMainLoop::StopStartupTracingTimer() {
992 startup_trace_timer_.Stop();
995 void BrowserMainLoop::InitializeMainThread() {
996 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeMainThread");
997 const char* kThreadName = "CrBrowserMain";
998 base::PlatformThread::SetName(kThreadName);
999 if (main_message_loop_)
1000 main_message_loop_->set_thread_name(kThreadName);
1002 // Register the main thread by instantiating it, but don't call any methods.
1003 main_thread_.reset(
1004 new BrowserThreadImpl(BrowserThread::UI, base::MessageLoop::current()));
1007 int BrowserMainLoop::BrowserThreadsStarted() {
1008 TRACE_EVENT0("startup", "BrowserMainLoop::BrowserThreadsStarted");
1010 #if !defined(OS_IOS)
1011 indexed_db_thread_.reset(new base::Thread("IndexedDB"));
1012 indexed_db_thread_->Start();
1013 #endif
1015 #if defined(OS_ANDROID)
1016 // Up the priority of anything that touches with display tasks
1017 // (this thread is UI thread, and io_thread_ is for IPCs).
1018 io_thread_->SetPriority(base::kThreadPriority_Display);
1019 base::PlatformThread::SetThreadPriority(
1020 base::PlatformThread::CurrentHandle(),
1021 base::kThreadPriority_Display);
1022 #endif
1024 #if !defined(OS_IOS)
1025 HistogramSynchronizer::GetInstance();
1027 bool initialize_gpu_data_manager = true;
1028 #if defined(OS_ANDROID)
1029 // On Android, GLSurface::InitializeOneOff() must be called before initalizing
1030 // the GpuDataManagerImpl as it uses the GL bindings. crbug.com/326295
1031 if (!gfx::GLSurface::InitializeOneOff()) {
1032 LOG(ERROR) << "GLSurface::InitializeOneOff failed";
1033 initialize_gpu_data_manager = false;
1035 #endif
1037 // Initialize the GpuDataManager before we set up the MessageLoops because
1038 // otherwise we'll trigger the assertion about doing IO on the UI thread.
1039 if (initialize_gpu_data_manager)
1040 GpuDataManagerImpl::GetInstance()->Initialize();
1042 bool always_uses_gpu = true;
1043 bool established_gpu_channel = false;
1044 #if defined(USE_AURA) || defined(OS_MACOSX)
1045 established_gpu_channel = true;
1046 if (!GpuDataManagerImpl::GetInstance()->CanUseGpuBrowserCompositor()) {
1047 established_gpu_channel = always_uses_gpu = false;
1049 BrowserGpuChannelHostFactory::Initialize(established_gpu_channel);
1050 ImageTransportFactory::Initialize();
1051 #if defined(USE_AURA)
1052 if (aura::Env::GetInstance()) {
1053 aura::Env::GetInstance()->set_context_factory(GetContextFactory());
1055 #endif
1056 #elif defined(OS_ANDROID)
1057 // TODO(crbug.com/439322): This should be set to |true|.
1058 established_gpu_channel = false;
1059 BrowserGpuChannelHostFactory::Initialize(established_gpu_channel);
1060 #endif
1062 #if defined(OS_LINUX) && defined(USE_UDEV)
1063 device_monitor_linux_.reset(new DeviceMonitorLinux());
1064 #elif defined(OS_MACOSX)
1065 device_monitor_mac_.reset(new DeviceMonitorMac());
1066 #endif
1068 // RDH needs the IO thread to be created
1070 TRACE_EVENT0("startup",
1071 "BrowserMainLoop::BrowserThreadsStarted:InitResourceDispatcherHost");
1072 resource_dispatcher_host_.reset(new ResourceDispatcherHostImpl());
1075 // MediaStreamManager needs the IO thread to be created.
1077 TRACE_EVENT0("startup",
1078 "BrowserMainLoop::BrowserThreadsStarted:InitMediaStreamManager");
1079 media_stream_manager_.reset(new MediaStreamManager(audio_manager_.get()));
1083 TRACE_EVENT0("startup",
1084 "BrowserMainLoop::BrowserThreadsStarted:InitSpeechRecognition");
1085 speech_recognition_manager_.reset(new SpeechRecognitionManagerImpl(
1086 audio_manager_.get(), media_stream_manager_.get()));
1090 TRACE_EVENT0(
1091 "startup",
1092 "BrowserMainLoop::BrowserThreadsStarted::InitUserInputMonitor");
1093 user_input_monitor_ = media::UserInputMonitor::Create(
1094 io_thread_->message_loop_proxy(), main_thread_->message_loop_proxy());
1098 TRACE_EVENT0("startup",
1099 "BrowserMainLoop::BrowserThreadsStarted::TimeZoneMonitor");
1100 time_zone_monitor_ = TimeZoneMonitor::Create();
1103 // Alert the clipboard class to which threads are allowed to access the
1104 // clipboard:
1105 std::vector<base::PlatformThreadId> allowed_clipboard_threads;
1106 // The current thread is the UI thread.
1107 allowed_clipboard_threads.push_back(base::PlatformThread::CurrentId());
1108 #if defined(OS_WIN)
1109 // On Windows, clipboards are also used on the File or IO threads.
1110 allowed_clipboard_threads.push_back(file_thread_->thread_id());
1111 allowed_clipboard_threads.push_back(io_thread_->thread_id());
1112 #endif
1113 ui::Clipboard::SetAllowedThreads(allowed_clipboard_threads);
1115 // When running the GPU thread in-process, avoid optimistically starting it
1116 // since creating the GPU thread races against creation of the one-and-only
1117 // ChildProcess instance which is created by the renderer thread.
1118 if (GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL) &&
1119 !established_gpu_channel &&
1120 always_uses_gpu &&
1121 !parsed_command_line_.HasSwitch(switches::kSingleProcess) &&
1122 !parsed_command_line_.HasSwitch(switches::kInProcessGPU)) {
1123 TRACE_EVENT_INSTANT0("gpu", "Post task to launch GPU process",
1124 TRACE_EVENT_SCOPE_THREAD);
1125 BrowserThread::PostTask(
1126 BrowserThread::IO, FROM_HERE, base::Bind(
1127 base::IgnoreResult(&GpuProcessHost::Get),
1128 GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED,
1129 CAUSE_FOR_GPU_LAUNCH_BROWSER_STARTUP));
1132 #if defined(OS_MACOSX)
1133 ThemeHelperMac::GetInstance();
1134 SystemHotkeyHelperMac::GetInstance()->DeferredLoadSystemHotkeys();
1135 if (ShouldEnableBootstrapSandbox()) {
1136 TRACE_EVENT0("startup",
1137 "BrowserMainLoop::BrowserThreadsStarted:BootstrapSandbox");
1138 CHECK(GetBootstrapSandbox());
1140 #endif // defined(OS_MACOSX)
1142 #endif // !defined(OS_IOS)
1144 return result_code_;
1147 bool BrowserMainLoop::InitializeToolkit() {
1148 TRACE_EVENT0("startup", "BrowserMainLoop::InitializeToolkit");
1149 // TODO(evan): this function is rather subtle, due to the variety
1150 // of intersecting ifdefs we have. To keep it easy to follow, there
1151 // are no #else branches on any #ifs.
1152 // TODO(stevenjb): Move platform specific code into platform specific Parts
1153 // (Need to add InitializeToolkit stage to BrowserParts).
1154 // See also GTK setup in EarlyInitialization, above, and associated comments.
1156 #if defined(OS_WIN)
1157 // Init common control sex.
1158 INITCOMMONCONTROLSEX config;
1159 config.dwSize = sizeof(config);
1160 config.dwICC = ICC_WIN95_CLASSES;
1161 if (!InitCommonControlsEx(&config))
1162 PLOG(FATAL);
1163 #endif
1165 #if defined(USE_AURA)
1167 #if defined(USE_X11)
1168 if (!gfx::GetXDisplay())
1169 return false;
1170 #endif
1172 // Env creates the compositor. Aura widgets need the compositor to be created
1173 // before they can be initialized by the browser.
1174 aura::Env::CreateInstance(true);
1175 #endif // defined(USE_AURA)
1177 if (parts_)
1178 parts_->ToolkitInitialized();
1180 return true;
1183 void BrowserMainLoop::MainMessageLoopRun() {
1184 #if defined(OS_ANDROID)
1185 // Android's main message loop is the Java message loop.
1186 NOTREACHED();
1187 #else
1188 DCHECK(base::MessageLoopForUI::IsCurrent());
1189 if (parameters_.ui_task)
1190 base::MessageLoopForUI::current()->PostTask(FROM_HERE,
1191 *parameters_.ui_task);
1193 base::RunLoop run_loop;
1194 run_loop.Run();
1195 #endif
1198 base::FilePath BrowserMainLoop::GetStartupTraceFileName(
1199 const base::CommandLine& command_line) const {
1200 base::FilePath trace_file = command_line.GetSwitchValuePath(
1201 switches::kTraceStartupFile);
1202 // trace_file = "none" means that startup events will show up for the next
1203 // begin/end tracing (via about:tracing or AutomationProxy::BeginTracing/
1204 // EndTracing, for example).
1205 if (trace_file == base::FilePath().AppendASCII("none"))
1206 return trace_file;
1208 if (trace_file.empty()) {
1209 #if defined(OS_ANDROID)
1210 TracingControllerAndroid::GenerateTracingFilePath(&trace_file);
1211 #else
1212 // Default to saving the startup trace into the current dir.
1213 trace_file = base::FilePath().AppendASCII("chrometrace.log");
1214 #endif
1217 return trace_file;
1220 void BrowserMainLoop::InitStartupTracing(
1221 const base::CommandLine& command_line) {
1222 DCHECK(is_tracing_startup_);
1224 startup_trace_file_ = GetStartupTraceFileName(parsed_command_line_);
1226 std::string delay_str = command_line.GetSwitchValueASCII(
1227 switches::kTraceStartupDuration);
1228 int delay_secs = 5;
1229 if (!delay_str.empty() && !base::StringToInt(delay_str, &delay_secs)) {
1230 DLOG(WARNING) << "Could not parse --" << switches::kTraceStartupDuration
1231 << "=" << delay_str << " defaulting to 5 (secs)";
1232 delay_secs = 5;
1235 startup_trace_timer_.Start(FROM_HERE,
1236 base::TimeDelta::FromSeconds(delay_secs),
1237 this,
1238 &BrowserMainLoop::EndStartupTracing);
1241 void BrowserMainLoop::EndStartupTracing() {
1242 is_tracing_startup_ = false;
1243 TracingController::GetInstance()->DisableRecording(
1244 TracingController::CreateFileSink(
1245 startup_trace_file_,
1246 base::Bind(OnStoppedStartupTracing, startup_trace_file_)));
1249 } // namespace content