This source file includes following definitions.
- EnableThemeSupportOnAllWindowStations
- SetupSignalHandlers
- CommonSubprocessInit
- GetBrowserPid
- InitializeStatsTable
- Set
- RunZygote
- RegisterMainThreadFactories
- RunNamedProcessTypeMain
- ui_task_
- GetAllocatorWasteSizeThunk
- GetStatsThunk
- ReleaseFreeMemoryThunk
- Initialize
- Run
- Shutdown
- Create
#include "content/public/app/content_main_runner.h"
#include <stdlib.h>
#include "base/allocator/allocator_extension.h"
#include "base/at_exit.h"
#include "base/command_line.h"
#include "base/debug/debugger.h"
#include "base/debug/trace_event.h"
#include "base/files/file_path.h"
#include "base/i18n/icu_util.h"
#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/metrics/stats_table.h"
#include "base/path_service.h"
#include "base/process/launch.h"
#include "base/process/memory.h"
#include "base/process/process_handle.h"
#include "base/profiler/alternate_timer.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "content/browser/browser_main.h"
#include "content/browser/gpu/gpu_process_host.h"
#include "content/common/set_process_title.h"
#include "content/common/url_schemes.h"
#include "content/gpu/in_process_gpu_thread.h"
#include "content/public/app/content_main.h"
#include "content/public/app/content_main_delegate.h"
#include "content/public/app/startup_helper_win.h"
#include "content/public/browser/content_browser_client.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/utility_process_host.h"
#include "content/public/common/content_client.h"
#include "content/public/common/content_constants.h"
#include "content/public/common/content_paths.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/main_function_params.h"
#include "content/public/common/sandbox_init.h"
#include "content/renderer/in_process_renderer_thread.h"
#include "content/utility/in_process_utility_thread.h"
#include "crypto/nss_util.h"
#include "ipc/ipc_switches.h"
#include "media/base/media.h"
#include "sandbox/win/src/sandbox_types.h"
#include "ui/base/ui_base_paths.h"
#include "ui/base/ui_base_switches.h"
#include "ui/gfx/win/dpi.h"
#if defined(USE_TCMALLOC)
#include "third_party/tcmalloc/chromium/src/gperftools/malloc_extension.h"
#if defined(TYPE_PROFILING)
#include "base/allocator/type_profiler.h"
#include "base/allocator/type_profiler_tcmalloc.h"
#endif
#endif
#if !defined(OS_IOS)
#include "content/public/plugin/content_plugin_client.h"
#include "content/public/renderer/content_renderer_client.h"
#include "content/public/utility/content_utility_client.h"
#endif
#if defined(OS_WIN)
#include <atlbase.h>
#include <atlapp.h>
#include <malloc.h>
#include <cstring>
#elif defined(OS_MACOSX)
#include "base/mac/scoped_nsautorelease_pool.h"
#if !defined(OS_IOS)
#include "base/power_monitor/power_monitor_device_source.h"
#include "content/browser/mach_broker_mac.h"
#include "content/common/sandbox_init_mac.h"
#endif
#endif
#if defined(OS_POSIX)
#include <signal.h>
#include "base/posix/global_descriptors.h"
#include "content/public/common/content_descriptors.h"
#if !defined(OS_MACOSX)
#include "content/public/common/zygote_fork_delegate_linux.h"
#endif
#if !defined(OS_MACOSX) && !defined(OS_ANDROID)
#include "content/zygote/zygote_main.h"
#endif
#endif
#if !defined(OS_MACOSX) && defined(USE_TCMALLOC)
extern "C" {
int tc_set_new_mode(int mode);
}
#endif
#if defined(USE_MOJO)
#include "content/app/mojo/mojo_init.h"
#endif
namespace content {
extern int GpuMain(const content::MainFunctionParams&);
#if defined(ENABLE_PLUGINS)
extern int PluginMain(const content::MainFunctionParams&);
extern int PpapiPluginMain(const MainFunctionParams&);
extern int PpapiBrokerMain(const MainFunctionParams&);
#endif
extern int RendererMain(const content::MainFunctionParams&);
extern int UtilityMain(const MainFunctionParams&);
extern int WorkerMain(const MainFunctionParams&);
}
namespace {
#if defined(OS_WIN)
void EnableThemeSupportOnAllWindowStations() {
HDESK desktop_handle = ::OpenInputDesktop(0, FALSE, READ_CONTROL);
if (desktop_handle) {
::CloseDesktop(desktop_handle);
return;
}
HWINSTA current_station = ::GetProcessWindowStation();
DCHECK(current_station);
HWINSTA winsta0 = ::OpenWindowStationA("WinSta0", FALSE, GENERIC_READ);
if (!winsta0) {
DVLOG(0) << "Unable to open to WinSta0, we: "<< ::GetLastError();
return;
}
if (!::SetProcessWindowStation(winsta0)) {
NOTREACHED() << "Unable to switch to WinSta0, we: "<< ::GetLastError();
::CloseWindowStation(winsta0);
return;
}
HWND window = ::CreateWindowExW(0, L"Static", L"", WS_POPUP | WS_DISABLED,
CW_USEDEFAULT, 0, 0, 0, HWND_MESSAGE, NULL,
::GetModuleHandleA(NULL), NULL);
if (!window) {
DLOG(WARNING) << "failed to enable theme support";
} else {
::DestroyWindow(window);
window = NULL;
}
if (!::SetProcessWindowStation(current_station)) {
LOG(FATAL) << "Failed to restore alternate window station";
}
if (!::CloseWindowStation(winsta0)) {
NOTREACHED();
}
}
#endif
}
namespace content {
base::LazyInstance<ContentBrowserClient>
g_empty_content_browser_client = LAZY_INSTANCE_INITIALIZER;
#if !defined(OS_IOS) && !defined(CHROME_MULTIPLE_DLL_BROWSER)
base::LazyInstance<ContentPluginClient>
g_empty_content_plugin_client = LAZY_INSTANCE_INITIALIZER;
base::LazyInstance<ContentRendererClient>
g_empty_content_renderer_client = LAZY_INSTANCE_INITIALIZER;
base::LazyInstance<ContentUtilityClient>
g_empty_content_utility_client = LAZY_INSTANCE_INITIALIZER;
#endif
#if defined(OS_WIN)
static CAppModule _Module;
#endif
#if defined(OS_POSIX) && !defined(OS_IOS)
void SetupSignalHandlers() {
sigset_t empty_signal_set;
CHECK(0 == sigemptyset(&empty_signal_set));
CHECK(0 == sigprocmask(SIG_SETMASK, &empty_signal_set, NULL));
struct sigaction sigact;
memset(&sigact, 0, sizeof(sigact));
sigact.sa_handler = SIG_DFL;
static const int signals_to_reset[] =
{SIGHUP, SIGINT, SIGQUIT, SIGILL, SIGABRT, SIGFPE, SIGSEGV,
SIGALRM, SIGTERM, SIGCHLD, SIGBUS, SIGTRAP};
for (unsigned i = 0; i < arraysize(signals_to_reset); i++) {
CHECK(0 == sigaction(signals_to_reset[i], &sigact, NULL));
}
CHECK(signal(SIGPIPE, SIG_IGN) != SIG_ERR);
}
#endif
void CommonSubprocessInit(const std::string& process_type) {
#if defined(OS_WIN)
PostThreadMessage(GetCurrentThreadId(), WM_NULL, 0, 0);
MSG msg;
PeekMessage(&msg, NULL, 0, 0, PM_REMOVE);
#endif
#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
setlocale(LC_NUMERIC, "C");
#endif
}
static base::ProcessId GetBrowserPid(const CommandLine& command_line) {
base::ProcessId browser_pid = base::GetCurrentProcId();
#if !defined(OS_IOS)
if (command_line.HasSwitch(switches::kProcessChannelID)) {
#if defined(OS_WIN) || defined(OS_MACOSX)
std::string channel_name =
command_line.GetSwitchValueASCII(switches::kProcessChannelID);
int browser_pid_int;
base::StringToInt(channel_name, &browser_pid_int);
browser_pid = static_cast<base::ProcessId>(browser_pid_int);
DCHECK_NE(browser_pid_int, 0);
#elif defined(OS_ANDROID)
LOG(ERROR) << "GetBrowserPid() not implemented for Android().";
#elif defined(OS_POSIX)
browser_pid =
base::GetParentProcessId(
base::GetParentProcessId(base::GetCurrentProcId()));
#endif
}
#endif
return browser_pid;
}
static void InitializeStatsTable(const CommandLine& command_line) {
if (command_line.HasSwitch(switches::kEnableStatsTable)) {
std::string statsfile =
base::StringPrintf("%s-%u", kStatsFilename,
static_cast<unsigned int>(GetBrowserPid(command_line)));
base::StatsTable* stats_table = new base::StatsTable(statsfile,
kStatsMaxThreads, kStatsMaxCounters);
base::StatsTable::set_current(stats_table);
}
}
class ContentClientInitializer {
public:
static void Set(const std::string& process_type,
ContentMainDelegate* delegate) {
ContentClient* content_client = GetContentClient();
if (process_type.empty()) {
if (delegate)
content_client->browser_ = delegate->CreateContentBrowserClient();
if (!content_client->browser_)
content_client->browser_ = &g_empty_content_browser_client.Get();
}
#if !defined(OS_IOS) && !defined(CHROME_MULTIPLE_DLL_BROWSER)
if (process_type == switches::kPluginProcess ||
process_type == switches::kPpapiPluginProcess) {
if (delegate)
content_client->plugin_ = delegate->CreateContentPluginClient();
if (!content_client->plugin_)
content_client->plugin_ = &g_empty_content_plugin_client.Get();
} else if (process_type == switches::kRendererProcess ||
CommandLine::ForCurrentProcess()->HasSwitch(
switches::kSingleProcess)) {
if (delegate)
content_client->renderer_ = delegate->CreateContentRendererClient();
if (!content_client->renderer_)
content_client->renderer_ = &g_empty_content_renderer_client.Get();
}
if (process_type == switches::kUtilityProcess ||
CommandLine::ForCurrentProcess()->HasSwitch(
switches::kSingleProcess)) {
if (delegate)
content_client->utility_ = delegate->CreateContentUtilityClient();
if (!content_client->utility_)
content_client->utility_ = &g_empty_content_utility_client.Get();
}
#endif
}
};
struct MainFunction {
const char* name;
int (*function)(const MainFunctionParams&);
};
#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
int RunZygote(const MainFunctionParams& main_function_params,
ContentMainDelegate* delegate) {
static const MainFunction kMainFunctions[] = {
{ switches::kRendererProcess, RendererMain },
{ switches::kWorkerProcess, WorkerMain },
#if defined(ENABLE_PLUGINS)
{ switches::kPpapiPluginProcess, PpapiPluginMain },
#endif
{ switches::kUtilityProcess, UtilityMain },
};
scoped_ptr<ZygoteForkDelegate> zygote_fork_delegate;
if (delegate) {
zygote_fork_delegate.reset(delegate->ZygoteStarting());
base::FilePath media_path;
if (PathService::Get(DIR_MEDIA_LIBS, &media_path))
media::InitializeMediaLibrary(media_path);
}
if (!ZygoteMain(main_function_params, zygote_fork_delegate.get()))
return 1;
if (delegate) delegate->ZygoteForked();
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
std::string process_type =
command_line.GetSwitchValueASCII(switches::kProcessType);
ContentClientInitializer::Set(process_type, delegate);
InitializeStatsTable(command_line);
MainFunctionParams main_params(command_line);
for (size_t i = 0; i < arraysize(kMainFunctions); ++i) {
if (process_type == kMainFunctions[i].name)
return kMainFunctions[i].function(main_params);
}
if (delegate)
return delegate->RunProcess(process_type, main_params);
NOTREACHED() << "Unknown zygote process type: " << process_type;
return 1;
}
#endif
#if !defined(OS_IOS)
static void RegisterMainThreadFactories() {
#if !defined(CHROME_MULTIPLE_DLL_BROWSER)
UtilityProcessHost::RegisterUtilityMainThreadFactory(
CreateInProcessUtilityThread);
RenderProcessHost::RegisterRendererMainThreadFactory(
CreateInProcessRendererThread);
GpuProcessHost::RegisterGpuMainThreadFactory(
CreateInProcessGpuThread);
#else
CommandLine& command_line = *CommandLine::ForCurrentProcess();
if (command_line.HasSwitch(switches::kSingleProcess)) {
LOG(FATAL) <<
"--single-process is not supported in chrome multiple dll browser.";
}
if (command_line.HasSwitch(switches::kInProcessGPU)) {
LOG(FATAL) <<
"--in-process-gpu is not supported in chrome multiple dll browser.";
}
#endif
}
int RunNamedProcessTypeMain(
const std::string& process_type,
const MainFunctionParams& main_function_params,
ContentMainDelegate* delegate) {
static const MainFunction kMainFunctions[] = {
#if !defined(CHROME_MULTIPLE_DLL_CHILD)
{ "", BrowserMain },
#endif
#if !defined(CHROME_MULTIPLE_DLL_BROWSER)
#if defined(ENABLE_PLUGINS)
{ switches::kPluginProcess, PluginMain },
{ switches::kWorkerProcess, WorkerMain },
{ switches::kPpapiPluginProcess, PpapiPluginMain },
{ switches::kPpapiBrokerProcess, PpapiBrokerMain },
#endif
{ switches::kUtilityProcess, UtilityMain },
{ switches::kRendererProcess, RendererMain },
{ switches::kGpuProcess, GpuMain },
#endif
};
RegisterMainThreadFactories();
for (size_t i = 0; i < arraysize(kMainFunctions); ++i) {
if (process_type == kMainFunctions[i].name) {
if (delegate) {
int exit_code = delegate->RunProcess(process_type,
main_function_params);
#if defined(OS_ANDROID)
if (process_type.empty())
return exit_code;
#endif
if (exit_code >= 0)
return exit_code;
}
return kMainFunctions[i].function(main_function_params);
}
}
#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
if (process_type == switches::kZygoteProcess)
return RunZygote(main_function_params, delegate);
#endif
if (delegate)
return delegate->RunProcess(process_type, main_function_params);
NOTREACHED() << "Unknown process type: " << process_type;
return 1;
}
#endif
class ContentMainRunnerImpl : public ContentMainRunner {
public:
ContentMainRunnerImpl()
: is_initialized_(false),
is_shutdown_(false),
completed_basic_startup_(false),
delegate_(NULL),
ui_task_(NULL) {
#if defined(OS_WIN)
memset(&sandbox_info_, 0, sizeof(sandbox_info_));
#endif
}
virtual ~ContentMainRunnerImpl() {
if (is_initialized_ && !is_shutdown_)
Shutdown();
}
#if defined(USE_TCMALLOC)
static bool GetAllocatorWasteSizeThunk(size_t* size) {
size_t heap_size, allocated_bytes, unmapped_bytes;
MallocExtension* ext = MallocExtension::instance();
if (ext->GetNumericProperty("generic.heap_size", &heap_size) &&
ext->GetNumericProperty("generic.current_allocated_bytes",
&allocated_bytes) &&
ext->GetNumericProperty("tcmalloc.pageheap_unmapped_bytes",
&unmapped_bytes)) {
*size = heap_size - allocated_bytes - unmapped_bytes;
return true;
}
DCHECK(false);
return false;
}
static void GetStatsThunk(char* buffer, int buffer_length) {
MallocExtension::instance()->GetStats(buffer, buffer_length);
}
static void ReleaseFreeMemoryThunk() {
MallocExtension::instance()->ReleaseFreeMemory();
}
#endif
virtual int Initialize(const ContentMainParams& params) OVERRIDE {
ui_task_ = params.ui_task;
#if defined(OS_WIN)
RegisterInvalidParamHandler();
_Module.Init(NULL, static_cast<HINSTANCE>(params.instance));
sandbox_info_ = *params.sandbox_info;
#else
#if defined(OS_ANDROID)
TRACE_EVENT0("startup", "ContentMainRunnerImpl::Initialize");
#endif
#if !defined(OS_MACOSX) && defined(USE_TCMALLOC)
#if defined(TYPE_PROFILING)
base::type_profiler::InterceptFunctions::SetFunctions(
base::type_profiler::NewInterceptForTCMalloc,
base::type_profiler::DeleteInterceptForTCMalloc);
#endif
tc_set_new_mode(1);
base::allocator::SetGetAllocatorWasteSizeFunction(
GetAllocatorWasteSizeThunk);
base::allocator::SetGetStatsFunction(GetStatsThunk);
base::allocator::SetReleaseFreeMemoryFunction(ReleaseFreeMemoryThunk);
const char* profiling = getenv(tracked_objects::kAlternateProfilerTime);
if (profiling &&
(atoi(profiling) == tracked_objects::TIME_SOURCE_TYPE_TCMALLOC)) {
tracked_objects::SetAlternateTimeSource(
MallocExtension::GetBytesAllocatedOnCurrentThread,
tracked_objects::TIME_SOURCE_TYPE_TCMALLOC);
}
#endif
#if !defined(OS_ANDROID) && !defined(OS_IOS)
setlocale(LC_ALL, "");
SetupSignalHandlers();
base::GlobalDescriptors* g_fds = base::GlobalDescriptors::GetInstance();
g_fds->Set(kPrimaryIPCChannel,
kPrimaryIPCChannel + base::GlobalDescriptors::kBaseDescriptor);
#endif
#if defined(OS_LINUX) || defined(OS_OPENBSD)
g_fds->Set(kCrashDumpSignal,
kCrashDumpSignal + base::GlobalDescriptors::kBaseDescriptor);
#endif
#endif
is_initialized_ = true;
delegate_ = params.delegate;
base::EnableTerminationOnHeapCorruption();
base::EnableTerminationOnOutOfMemory();
#if !defined(OS_ANDROID) && !defined(OS_IOS)
if (!ui_task_) {
exit_manager_.reset(new base::AtExitManager);
}
#endif
#if defined(OS_MACOSX)
autorelease_pool_.reset(new base::mac::ScopedNSAutoreleasePool());
#endif
#if !defined(OS_ANDROID)
int argc = 0;
const char** argv = NULL;
#if !defined(OS_WIN)
argc = params.argc;
argv = params.argv;
#endif
CommandLine::Init(argc, argv);
#if !defined(OS_IOS)
SetProcessTitleFromCommandLine(argv);
#endif
#endif
int exit_code;
if (delegate_ && delegate_->BasicStartupComplete(&exit_code))
return exit_code;
completed_basic_startup_ = true;
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
std::string process_type =
command_line.GetSwitchValueASCII(switches::kProcessType);
#if defined(USE_MOJO)
InitializeMojo();
#endif
if (!GetContentClient())
SetContentClient(&empty_content_client_);
ContentClientInitializer::Set(process_type, delegate_);
#if defined(OS_WIN)
if (command_line.HasSwitch(switches::kEnableLogging))
base::RouteStdioToConsole();
#endif
if (command_line.HasSwitch(switches::kTraceStartup)) {
base::debug::CategoryFilter category_filter(
command_line.GetSwitchValueASCII(switches::kTraceStartup));
base::debug::TraceLog::GetInstance()->SetEnabled(
category_filter,
base::debug::TraceLog::RECORDING_MODE,
base::debug::TraceLog::RECORD_UNTIL_FULL);
}
#if !defined(OS_ANDROID)
TRACE_EVENT0("startup", "ContentMainRunnerImpl::Initialize");
#endif
#if defined(OS_MACOSX) && !defined(OS_IOS)
if (process_type.empty() ||
(delegate_ &&
delegate_->ProcessRegistersWithSystemProcess(process_type))) {
base::PowerMonitorDeviceSource::AllocateSystemIOPorts();
}
if (!process_type.empty() &&
(!delegate_ || delegate_->ShouldSendMachPort(process_type))) {
MachBroker::ChildSendTaskPortToParent();
}
#elif defined(OS_WIN)
if (command_line.HasSwitch(switches::kEnableHighResolutionTime))
base::TimeTicks::SetNowIsHighResNowIfSupported();
EnableThemeSupportOnAllWindowStations();
SetupCRT(command_line);
#endif
#if defined(OS_POSIX)
if (!process_type.empty()) {
if (!base::debug::BeingDebugged())
signal(SIGINT, SIG_IGN);
}
#endif
#if defined(USE_NSS)
crypto::EarlySetupForNSSInit();
#endif
ui::RegisterPathProvider();
RegisterPathProvider();
RegisterContentSchemes(true);
CHECK(base::i18n::InitializeICU());
InitializeStatsTable(command_line);
if (delegate_)
delegate_->PreSandboxStartup();
if (!process_type.empty())
CommonSubprocessInit(process_type);
#if defined(OS_WIN)
CHECK(InitializeSandbox(params.sandbox_info));
#elif defined(OS_MACOSX) && !defined(OS_IOS)
if (process_type == switches::kRendererProcess ||
process_type == switches::kPpapiPluginProcess ||
(delegate_ && delegate_->DelaySandboxInitialization(process_type))) {
} else {
CHECK(InitializeSandbox());
}
#endif
if (delegate_)
delegate_->SandboxInitialized(process_type);
return -1;
}
virtual int Run() OVERRIDE {
DCHECK(is_initialized_);
DCHECK(!is_shutdown_);
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
std::string process_type =
command_line.GetSwitchValueASCII(switches::kProcessType);
MainFunctionParams main_params(command_line);
main_params.ui_task = ui_task_;
#if defined(OS_WIN)
main_params.sandbox_info = &sandbox_info_;
#elif defined(OS_MACOSX)
main_params.autorelease_pool = autorelease_pool_.get();
#endif
#if !defined(OS_IOS)
return RunNamedProcessTypeMain(process_type, main_params, delegate_);
#else
return 1;
#endif
}
virtual void Shutdown() OVERRIDE {
DCHECK(is_initialized_);
DCHECK(!is_shutdown_);
if (completed_basic_startup_ && delegate_) {
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
std::string process_type =
command_line.GetSwitchValueASCII(switches::kProcessType);
delegate_->ProcessExiting(process_type);
}
#if defined(USE_MOJO)
ShutdownMojo();
#endif
#if defined(OS_WIN)
#ifdef _CRTDBG_MAP_ALLOC
_CrtDumpMemoryLeaks();
#endif
_Module.Term();
#endif
#if defined(OS_MACOSX)
autorelease_pool_.reset(NULL);
#endif
exit_manager_.reset(NULL);
delegate_ = NULL;
is_shutdown_ = true;
}
private:
bool is_initialized_;
bool is_shutdown_;
bool completed_basic_startup_;
ContentClient empty_content_client_;
ContentMainDelegate* delegate_;
scoped_ptr<base::AtExitManager> exit_manager_;
#if defined(OS_WIN)
sandbox::SandboxInterfaceInfo sandbox_info_;
#elif defined(OS_MACOSX)
scoped_ptr<base::mac::ScopedNSAutoreleasePool> autorelease_pool_;
#endif
base::Closure* ui_task_;
DISALLOW_COPY_AND_ASSIGN(ContentMainRunnerImpl);
};
ContentMainRunner* ContentMainRunner::Create() {
return new ContentMainRunnerImpl();
}
}