#include "content/browser/browser_main_loop.h"
#include "base/bind.h"
#include "base/command_line.h"
#include "base/debug/trace_event.h"
#include "base/hi_res_timer_manager.h"
#include "base/logging.h"
#include "base/message_loop.h"
#include "base/metrics/field_trial.h"
#include "base/metrics/histogram.h"
#include "base/run_loop.h"
#include "base/string_number_conversions.h"
#include "base/threading/thread_restrictions.h"
#include "content/browser/browser_thread_impl.h"
#include "content/browser/download/download_file_manager.h"
#include "content/browser/download/save_file_manager.h"
#include "content/browser/gamepad/gamepad_service.h"
#include "content/browser/gpu/browser_gpu_channel_host_factory.h"
#include "content/browser/gpu/gpu_data_manager_impl.h"
#include "content/browser/gpu/gpu_process_host.h"
#include "content/browser/gpu/gpu_process_host_ui_shim.h"
#include "content/browser/histogram_synchronizer.h"
#include "content/browser/in_process_webkit/webkit_thread.h"
#include "content/browser/net/browser_online_state_observer.h"
#include "content/browser/plugin_service_impl.h"
#include "content/browser/renderer_host/media/media_stream_manager.h"
#include "content/browser/renderer_host/resource_dispatcher_host_impl.h"
#include "content/browser/speech/speech_recognition_manager_impl.h"
#include "content/browser/trace_controller_impl.h"
#include "content/public/browser/browser_main_parts.h"
#include "content/public/browser/browser_shutdown.h"
#include "content/public/browser/content_browser_client.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/main_function_params.h"
#include "content/public/common/result_codes.h"
#include "crypto/nss_util.h"
#include "media/audio/audio_manager.h"
#include "net/base/network_change_notifier.h"
#include "net/base/ssl_config_service.h"
#include "net/socket/client_socket_factory.h"
#include "net/socket/tcp_client_socket.h"
#include "ui/base/clipboard/clipboard.h"
#if defined(USE_AURA)
#include "content/browser/renderer_host/image_transport_factory.h"
#endif
#if defined(OS_WIN)
#include <windows.h>
#include <commctrl.h>
#include <shellapi.h>
#include "content/browser/system_message_window_win.h"
#include "content/common/sandbox_policy.h"
#include "ui/base/l10n/l10n_util_win.h"
#include "net/base/winsock_init.h"
#endif
#if defined(OS_LINUX) || defined(OS_OPENBSD)
#include <glib-object.h>
#endif
#if defined(OS_LINUX)
#include "content/browser/device_monitor_linux.h"
#elif defined(OS_MACOSX)
#include "content/browser/device_monitor_mac.h"
#endif
#if defined(OS_CHROMEOS)
#include <dbus/dbus-glib.h>
#endif
#if defined(TOOLKIT_GTK)
#include "ui/gfx/gtk_util.h"
#endif
#if defined(OS_POSIX) && !defined(OS_MACOSX)
#include <sys/stat.h>
#include "base/process_util.h"
#include "content/browser/renderer_host/render_sandbox_host_linux.h"
#include "content/browser/zygote_host/zygote_host_impl_linux.h"
#endif
#if defined(USE_X11)
#include <X11/Xlib.h>
#endif
#ifdef DestroyAll
#undef DestroyAll
#endif
using content::TraceControllerImpl;
namespace {
#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
void SetupSandbox(const CommandLine& parsed_command_line) {
const char* sandbox_binary = NULL;
struct stat st;
if (stat(base::kProcSelfExe, &st) == 0 && st.st_uid == getuid())
sandbox_binary = getenv("CHROME_DEVEL_SANDBOX");
#if defined(LINUX_SANDBOX_PATH)
if (!sandbox_binary)
sandbox_binary = LINUX_SANDBOX_PATH;
#endif
std::string sandbox_cmd;
if (sandbox_binary && !parsed_command_line.HasSwitch(switches::kNoSandbox))
sandbox_cmd = sandbox_binary;
RenderSandboxHostLinux::GetInstance()->Init(sandbox_cmd);
ZygoteHostImpl::GetInstance()->Init(sandbox_cmd);
}
#endif
#if defined(OS_LINUX) || defined(OS_OPENBSD)
static void GLibLogHandler(const gchar* log_domain,
GLogLevelFlags log_level,
const gchar* message,
gpointer userdata) {
if (!log_domain)
log_domain = "<unknown>";
if (!message)
message = "<no message>";
if (strstr(message, "Loading IM context type") ||
strstr(message, "wrong ELF class: ELFCLASS64")) {
static bool alerted = false;
if (!alerted) {
LOG(ERROR) << "Bug 9643: " << log_domain << ": " << message;
alerted = true;
}
} else if (strstr(message, "Unable to retrieve the file info for")) {
LOG(ERROR) << "GTK File code error: " << message;
} else if (strstr(message, "Theme file for default has no") ||
strstr(message, "Theme directory") ||
strstr(message, "theme pixmap") ||
strstr(message, "locate theme engine")) {
LOG(ERROR) << "GTK theme error: " << message;
} else if (strstr(message, "Unable to create Ubuntu Menu Proxy") &&
strstr(log_domain, "<unknown>")) {
LOG(ERROR) << "GTK menu proxy create failed";
} else if (strstr(message, "gtk_drag_dest_leave: assertion")) {
LOG(ERROR) << "Drag destination deleted: http://crbug.com/18557";
} else if (strstr(message, "Out of memory") &&
strstr(log_domain, "<unknown>")) {
LOG(ERROR) << "DBus call timeout or out of memory: "
<< "http://crosbug.com/15496";
} else if (strstr(message, "XDG_RUNTIME_DIR variable not set")) {
LOG(ERROR) << message << " (http://bugs.chromium.org/97293)";
} else {
LOG(DFATAL) << log_domain << ": " << message;
}
}
static void SetUpGLibLogHandler() {
const char* kLogDomains[] = { NULL, "Gtk", "Gdk", "GLib", "GLib-GObject" };
for (size_t i = 0; i < arraysize(kLogDomains); i++) {
g_log_set_handler(kLogDomains[i],
static_cast<GLogLevelFlags>(G_LOG_FLAG_RECURSION |
G_LOG_FLAG_FATAL |
G_LOG_LEVEL_ERROR |
G_LOG_LEVEL_CRITICAL |
G_LOG_LEVEL_WARNING),
GLibLogHandler,
NULL);
}
}
#endif
}
namespace content {
BrowserMainLoop* g_current_browser_main_loop = NULL;
class BrowserShutdownImpl {
public:
static void ImmediateShutdownAndExitProcess() {
DCHECK(g_current_browser_main_loop);
g_current_browser_main_loop->ShutdownThreadsAndCleanUp();
#if defined(OS_WIN)
ExitProcess(content::RESULT_CODE_NORMAL_EXIT);
#elif defined(OS_POSIX) && !defined(OS_MACOSX)
_exit(content::RESULT_CODE_NORMAL_EXIT);
#else
NOTIMPLEMENTED();
#endif
}
};
void ImmediateShutdownAndExitProcess() {
BrowserShutdownImpl::ImmediateShutdownAndExitProcess();
}
media::AudioManager* BrowserMainLoop::GetAudioManager() {
return g_current_browser_main_loop->audio_manager_.get();
}
media_stream::MediaStreamManager* BrowserMainLoop::GetMediaStreamManager() {
return g_current_browser_main_loop->media_stream_manager_.get();
}
BrowserMainLoop::BrowserMainLoop(const content::MainFunctionParams& parameters)
: parameters_(parameters),
parsed_command_line_(parameters.command_line),
result_code_(content::RESULT_CODE_NORMAL_EXIT) {
DCHECK(!g_current_browser_main_loop);
g_current_browser_main_loop = this;
}
BrowserMainLoop::~BrowserMainLoop() {
DCHECK_EQ(this, g_current_browser_main_loop);
ui::Clipboard::DestroyClipboardForCurrentThread();
g_current_browser_main_loop = NULL;
}
void BrowserMainLoop::Init() {
parts_.reset(
GetContentClient()->browser()->CreateBrowserMainParts(parameters_));
}
void BrowserMainLoop::EarlyInitialization() {
#if defined(USE_X11)
if (parsed_command_line_.HasSwitch(switches::kSingleProcess) ||
parsed_command_line_.HasSwitch(switches::kInProcessGPU)) {
if (!XInitThreads()) {
LOG(ERROR) << "Failed to put Xlib into threaded mode.";
}
}
#endif
if (parts_.get())
parts_->PreEarlyInitialization();
#if defined(OS_WIN)
net::EnsureWinsockInit();
#endif
#if !defined(USE_OPENSSL)
bool init_nspr = false;
#if defined(OS_WIN) || defined(OS_MACOSX)
if (parsed_command_line_.HasSwitch(switches::kUseSystemSSL)) {
net::ClientSocketFactory::UseSystemSSL();
} else {
init_nspr = true;
}
UMA_HISTOGRAM_BOOLEAN("Chrome.CommandLineUseSystemSSL", !init_nspr);
#elif defined(USE_NSS)
init_nspr = true;
#endif
if (init_nspr) {
crypto::EnsureNSPRInit();
}
#endif
#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
SetupSandbox(parsed_command_line_);
#endif
if (parsed_command_line_.HasSwitch(switches::kEnableSSLCachedInfo))
net::SSLConfigService::EnableCachedInfo();
if (parsed_command_line_.HasSwitch(switches::kEnableTcpFastOpen))
net::set_tcp_fastopen_enabled(true);
#if !defined(OS_IOS)
if (parsed_command_line_.HasSwitch(switches::kRendererProcessLimit)) {
std::string limit_string = parsed_command_line_.GetSwitchValueASCII(
switches::kRendererProcessLimit);
size_t process_limit;
if (base::StringToSizeT(limit_string, &process_limit)) {
content::RenderProcessHost::SetMaxRendererProcessCount(process_limit);
}
}
#endif
if (parts_.get())
parts_->PostEarlyInitialization();
}
void BrowserMainLoop::MainMessageLoopStart() {
if (parts_.get())
parts_->PreMainMessageLoopStart();
#if defined(OS_WIN)
if (!parameters_.ui_task) {
l10n_util::OverrideLocaleWithUILanguageList();
}
#endif
if (!MessageLoop::current())
main_message_loop_.reset(new MessageLoop(MessageLoop::TYPE_UI));
InitializeMainThread();
system_monitor_.reset(new base::SystemMonitor);
hi_res_timer_manager_.reset(new HighResolutionTimerManager);
network_change_notifier_.reset(net::NetworkChangeNotifier::Create());
audio_manager_.reset(media::AudioManager::Create());
#if !defined(OS_IOS)
if (base::debug::TraceLog::GetInstance()->IsEnabled()) {
TraceControllerImpl::GetInstance()->InitStartupTracing(
parsed_command_line_);
}
online_state_observer_.reset(new BrowserOnlineStateObserver);
media_stream_manager_.reset(
new media_stream::MediaStreamManager(audio_manager_.get()));
PluginService::GetInstance()->Init();
#endif
#if defined(OS_WIN)
system_message_window_.reset(new SystemMessageWindowWin);
#endif
if (parts_.get())
parts_->PostMainMessageLoopStart();
}
void BrowserMainLoop::CreateThreads() {
if (parts_.get())
result_code_ = parts_->PreCreateThreads();
if (result_code_ > 0)
return;
base::Thread::Options default_options;
base::Thread::Options io_message_loop_options;
io_message_loop_options.message_loop_type = MessageLoop::TYPE_IO;
base::Thread::Options ui_message_loop_options;
ui_message_loop_options.message_loop_type = MessageLoop::TYPE_UI;
for (size_t thread_id = BrowserThread::UI + 1;
thread_id < BrowserThread::ID_COUNT;
++thread_id) {
scoped_ptr<BrowserProcessSubThread>* thread_to_start = NULL;
base::Thread::Options* options = &default_options;
switch (thread_id) {
case BrowserThread::DB:
thread_to_start = &db_thread_;
break;
case BrowserThread::WEBKIT_DEPRECATED:
break;
case BrowserThread::FILE_USER_BLOCKING:
thread_to_start = &file_user_blocking_thread_;
break;
case BrowserThread::FILE:
thread_to_start = &file_thread_;
#if defined(OS_WIN)
options = &ui_message_loop_options;
#else
options = &io_message_loop_options;
#endif
break;
case BrowserThread::PROCESS_LAUNCHER:
thread_to_start = &process_launcher_thread_;
break;
case BrowserThread::CACHE:
thread_to_start = &cache_thread_;
options = &io_message_loop_options;
break;
case BrowserThread::IO:
thread_to_start = &io_thread_;
options = &io_message_loop_options;
break;
case BrowserThread::UI:
case BrowserThread::ID_COUNT:
default:
NOTREACHED();
break;
}
BrowserThread::ID id = static_cast<BrowserThread::ID>(thread_id);
if (thread_id == BrowserThread::WEBKIT_DEPRECATED) {
#if !defined(OS_IOS)
webkit_thread_.reset(new WebKitThread);
webkit_thread_->Initialize();
#endif
} else if (thread_to_start) {
(*thread_to_start).reset(new BrowserProcessSubThread(id));
(*thread_to_start)->StartWithOptions(*options);
} else {
NOTREACHED();
}
}
BrowserThreadsStarted();
if (parts_.get())
parts_->PreMainMessageLoopRun();
#if !defined(OS_IOS)
if (GpuDataManagerImpl::GetInstance()->GpuAccessAllowed() &&
!parsed_command_line_.HasSwitch(switches::kDisableGpuProcessPrelaunch) &&
!parsed_command_line_.HasSwitch(switches::kSingleProcess) &&
!parsed_command_line_.HasSwitch(switches::kInProcessGPU)) {
TRACE_EVENT_INSTANT0("gpu", "Post task to launch GPU process");
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE, base::Bind(
base::IgnoreResult(&GpuProcessHost::Get),
GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED,
content::CAUSE_FOR_GPU_LAUNCH_BROWSER_STARTUP));
}
#endif
base::ThreadRestrictions::SetIOAllowed(false);
base::ThreadRestrictions::DisallowWaiting();
}
void BrowserMainLoop::RunMainMessageLoopParts() {
TRACE_EVENT_BEGIN_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
bool ran_main_loop = false;
if (parts_.get())
ran_main_loop = parts_->MainMessageLoopRun(&result_code_);
if (!ran_main_loop)
MainMessageLoopRun();
TRACE_EVENT_END_ETW("BrowserMain:MESSAGE_LOOP", 0, "");
}
void BrowserMainLoop::ShutdownThreadsAndCleanUp() {
base::ThreadRestrictions::SetIOAllowed(true);
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::Bind(base::IgnoreResult(&base::ThreadRestrictions::SetIOAllowed),
true));
if (parts_.get())
parts_->PostMainMessageLoopRun();
#if !defined(OS_IOS)
GpuProcessHostUIShim::DestroyAll();
if (resource_dispatcher_host_.get())
resource_dispatcher_host_.get()->Shutdown();
#if defined(USE_AURA)
ImageTransportFactory::Terminate();
#endif
BrowserGpuChannelHostFactory::Terminate();
#if defined(OS_WIN)
system_message_window_.reset();
#elif defined(OS_MACOSX)
device_monitor_mac_.reset();
#endif
#endif
for (size_t thread_id = BrowserThread::ID_COUNT - 1;
thread_id >= (BrowserThread::UI + 1);
--thread_id) {
scoped_ptr<BrowserProcessSubThread>* thread_to_stop = NULL;
switch (thread_id) {
case BrowserThread::DB:
thread_to_stop = &db_thread_;
break;
case BrowserThread::WEBKIT_DEPRECATED:
resource_dispatcher_host_.reset();
break;
case BrowserThread::FILE_USER_BLOCKING:
thread_to_stop = &file_user_blocking_thread_;
break;
case BrowserThread::FILE:
thread_to_stop = &file_thread_;
#if !defined(OS_IOS)
if (resource_dispatcher_host_.get()) {
resource_dispatcher_host_.get()->download_file_manager()->Shutdown();
resource_dispatcher_host_.get()->save_file_manager()->Shutdown();
}
#endif
break;
case BrowserThread::PROCESS_LAUNCHER:
thread_to_stop = &process_launcher_thread_;
break;
case BrowserThread::CACHE:
thread_to_stop = &cache_thread_;
break;
case BrowserThread::IO:
thread_to_stop = &io_thread_;
break;
case BrowserThread::UI:
case BrowserThread::ID_COUNT:
default:
NOTREACHED();
break;
}
BrowserThread::ID id = static_cast<BrowserThread::ID>(thread_id);
if (id == BrowserThread::WEBKIT_DEPRECATED) {
#if !defined(OS_IOS)
webkit_thread_.reset();
#endif
} else if (thread_to_stop) {
thread_to_stop->reset();
} else {
NOTREACHED();
}
}
BrowserThreadImpl::ShutdownThreadPool();
GamepadService::GetInstance()->Terminate();
if (parts_.get())
parts_->PostDestroyThreads();
}
void BrowserMainLoop::InitializeMainThread() {
const char* kThreadName = "CrBrowserMain";
base::PlatformThread::SetName(kThreadName);
if (main_message_loop_.get())
main_message_loop_->set_thread_name(kThreadName);
main_thread_.reset(new BrowserThreadImpl(BrowserThread::UI,
MessageLoop::current()));
}
void BrowserMainLoop::BrowserThreadsStarted() {
#if !defined(OS_IOS)
HistogramSynchronizer::GetInstance();
content::BrowserGpuChannelHostFactory::Initialize();
#if defined(USE_AURA)
ImageTransportFactory::Initialize();
#endif
#if defined(OS_LINUX)
device_monitor_linux_.reset(new DeviceMonitorLinux());
#elif defined(OS_MACOSX)
device_monitor_mac_.reset(new DeviceMonitorMac());
#endif
resource_dispatcher_host_.reset(new ResourceDispatcherHostImpl());
GpuDataManagerImpl::GetInstance()->Initialize();
#endif
#if defined(ENABLE_INPUT_SPEECH)
speech_recognition_manager_.reset(new speech::SpeechRecognitionManagerImpl());
#endif
std::vector<base::PlatformThreadId> allowed_clipboard_threads;
allowed_clipboard_threads.push_back(base::PlatformThread::CurrentId());
#if defined(OS_WIN)
allowed_clipboard_threads.push_back(file_thread_->thread_id());
allowed_clipboard_threads.push_back(io_thread_->thread_id());
#endif
ui::Clipboard::SetAllowedThreads(allowed_clipboard_threads);
}
void BrowserMainLoop::InitializeToolkit() {
#if defined(OS_LINUX) || defined(OS_OPENBSD)
g_type_init();
#if !defined(USE_AURA)
gfx::GtkInitFromCommandLine(parsed_command_line_);
#endif
SetUpGLibLogHandler();
#endif
#if defined(TOOLKIT_GTK)
gfx::InitRCStyles();
#endif
#if defined(OS_WIN)
INITCOMMONCONTROLSEX config;
config.dwSize = sizeof(config);
config.dwICC = ICC_WIN95_CLASSES;
if (!InitCommonControlsEx(&config))
LOG_GETLASTERROR(FATAL);
#endif
if (parts_.get())
parts_->ToolkitInitialized();
}
void BrowserMainLoop::MainMessageLoopRun() {
#if defined(OS_ANDROID)
NOTREACHED();
#else
DCHECK_EQ(MessageLoop::TYPE_UI, MessageLoop::current()->type());
if (parameters_.ui_task)
MessageLoopForUI::current()->PostTask(FROM_HERE, *parameters_.ui_task);
base::RunLoop run_loop;
run_loop.Run();
#endif
}
}