diff options
26 files changed, 887 insertions, 567 deletions
diff --git a/chrome/app/chrome_main.cc b/chrome/app/chrome_main.cc index 93ff2e6..425932e 100644 --- a/chrome/app/chrome_main.cc +++ b/chrome/app/chrome_main.cc @@ -1,10 +1,10 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/app/chrome_main_delegate.h" -#include "content/app/content_main.h" +#include "content/public/app/content_main.h" #if defined(OS_WIN) #define DLLEXPORT __declspec(dllexport) diff --git a/chrome/app/chrome_main_delegate.cc b/chrome/app/chrome_main_delegate.cc index ceabdb8..a742401 100644 --- a/chrome/app/chrome_main_delegate.cc +++ b/chrome/app/chrome_main_delegate.cc @@ -29,9 +29,7 @@ #include "chrome/plugin/chrome_content_plugin_client.h" #include "chrome/renderer/chrome_content_renderer_client.h" #include "chrome/utility/chrome_content_utility_client.h" -#include "content/app/content_main.h" #include "content/common/content_counters.h" -#include "content/public/app/content_main_delegate.h" #include "content/public/browser/render_process_host.h" #include "content/public/common/content_client.h" #include "content/public/common/content_paths.h" @@ -699,8 +697,7 @@ int ChromeMainDelegate::RunProcess( return kMainFunctions[i].function(main_function_params); } - NOTREACHED() << "Unknown process type: " << process_type; - return 1; + return -1; } void ChromeMainDelegate::ProcessExiting(const std::string& process_type) { diff --git a/chrome/browser/chrome_browser_main.cc b/chrome/browser/chrome_browser_main.cc index ded5461..fa261e0 100644 --- a/chrome/browser/chrome_browser_main.cc +++ b/chrome/browser/chrome_browser_main.cc @@ -1109,6 +1109,10 @@ void ChromeBrowserMainParts::PreMainMessageLoopStart() { chrome_extra_parts_[i]->PreMainMessageLoopStart(); } +MessageLoop* ChromeBrowserMainParts::GetMainMessageLoop() { + return NULL; +} + void ChromeBrowserMainParts::PostMainMessageLoopStart() { for (size_t i = 0; i < chrome_extra_parts_.size(); ++i) chrome_extra_parts_[i]->PostMainMessageLoopStart(); diff --git a/chrome/browser/chrome_browser_main.h b/chrome/browser/chrome_browser_main.h index 435dadc..018be20 100644 --- a/chrome/browser/chrome_browser_main.h +++ b/chrome/browser/chrome_browser_main.h @@ -63,6 +63,7 @@ class ChromeBrowserMainParts : public content::BrowserMainParts { virtual void PostEarlyInitialization() OVERRIDE; virtual void ToolkitInitialized() OVERRIDE; virtual void PreMainMessageLoopStart() OVERRIDE; + virtual MessageLoop* GetMainMessageLoop() OVERRIDE; virtual void PostMainMessageLoopStart() OVERRIDE; virtual int PreCreateThreads() OVERRIDE; virtual void PreMainMessageLoopRun() OVERRIDE; diff --git a/chrome/test/base/chrome_test_launcher.cc b/chrome/test/base/chrome_test_launcher.cc index 8e6fab4..21aa802 100644 --- a/chrome/test/base/chrome_test_launcher.cc +++ b/chrome/test/base/chrome_test_launcher.cc @@ -1,4 +1,4 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. @@ -11,7 +11,7 @@ #include "chrome/common/chrome_switches.h" #include "chrome/common/chrome_constants.h" #include "chrome/test/base/chrome_test_suite.h" -#include "content/app/content_main.h" +#include "content/public/app/content_main.h" #if defined(OS_MACOSX) #include "chrome/browser/chrome_browser_application_mac.h" diff --git a/chrome_frame/test/net/fake_external_tab.cc b/chrome_frame/test/net/fake_external_tab.cc index d81a2a2..5a7a0af 100644 --- a/chrome_frame/test/net/fake_external_tab.cc +++ b/chrome_frame/test/net/fake_external_tab.cc @@ -49,7 +49,7 @@ #include "chrome_frame/test/simulate_input.h" #include "chrome_frame/test/win_event_receiver.h" #include "chrome_frame/utils.h" -#include "content/app/content_main.h" +#include "content/public/app/content_main.h" #include "content/public/app/startup_helper_win.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/notification_service.h" @@ -613,6 +613,10 @@ void CFUrlRequestUnittestRunner::PreEarlyInitialization() { FilterDisabledTests(); } +MessageLoop* CFUrlRequestUnittestRunner::GetMainMessageLoop() { + return NULL; +} + int CFUrlRequestUnittestRunner::PreCreateThreads() { fake_chrome_.reset(new FakeExternalTab()); fake_chrome_->Initialize(); diff --git a/chrome_frame/test/net/fake_external_tab.h b/chrome_frame/test/net/fake_external_tab.h index 0ed4f78..d7e726c7 100644 --- a/chrome_frame/test/net/fake_external_tab.h +++ b/chrome_frame/test/net/fake_external_tab.h @@ -102,6 +102,7 @@ class CFUrlRequestUnittestRunner virtual void PreEarlyInitialization() OVERRIDE; virtual void PostEarlyInitialization() OVERRIDE {} virtual void PreMainMessageLoopStart() OVERRIDE {} + virtual MessageLoop* GetMainMessageLoop() OVERRIDE; virtual void PostMainMessageLoopStart() OVERRIDE {} virtual void ToolkitInitialized() OVERRIDE {} virtual int PreCreateThreads() OVERRIDE; diff --git a/content/app/content_main.cc b/content/app/content_main.cc index 6b1ccf3..c82d790 100644 --- a/content/app/content_main.cc +++ b/content/app/content_main.cc @@ -2,284 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "content/app/content_main.h" +#include "content/public/app/content_main.h" -#include "base/at_exit.h" -#include "base/command_line.h" -#include "base/debug/debugger.h" -#include "base/debug/trace_event.h" -#include "base/i18n/icu_util.h" -#include "base/logging.h" #include "base/memory/scoped_ptr.h" -#include "base/metrics/stats_table.h" -#include "base/process_util.h" -#include "base/stringprintf.h" -#include "base/string_number_conversions.h" -#include "content/browser/browser_main.h" -#include "content/common/set_process_title.h" -#include "content/public/app/content_main_delegate.h" -#include "content/public/app/startup_helper_win.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 "crypto/nss_util.h" -#include "ipc/ipc_switches.h" -#include "ui/base/ui_base_switches.h" -#include "ui/base/ui_base_paths.h" -#include "webkit/glue/webkit_glue.h" - -#if defined(OS_WIN) -#include <atlbase.h> -#include <atlapp.h> -#include <malloc.h> -#elif defined(OS_MACOSX) -#include "base/mac/scoped_nsautorelease_pool.h" -#include "base/mach_ipc_mac.h" -#include "base/system_monitor/system_monitor.h" -#include "content/browser/mach_broker_mac.h" -#include "content/common/sandbox_init_mac.h" -#endif // OS_WIN - -#if defined(OS_POSIX) -#include <signal.h> - -#include "base/global_descriptors_posix.h" -#include "content/common/chrome_descriptors.h" - -#if !defined(OS_MACOSX) -#include "content/public/common/zygote_fork_delegate_linux.h" -#endif - -#endif // OS_POSIX - -#if !defined(OS_MACOSX) && defined(USE_TCMALLOC) -extern "C" { -int tc_set_new_mode(int mode); -} -#endif - -extern int GpuMain(const content::MainFunctionParams&); -extern int PluginMain(const content::MainFunctionParams&); -extern int PpapiPluginMain(const content::MainFunctionParams&); -extern int PpapiBrokerMain(const content::MainFunctionParams&); -extern int RendererMain(const content::MainFunctionParams&); -extern int WorkerMain(const content::MainFunctionParams&); -extern int UtilityMain(const content::MainFunctionParams&); -#if defined(OS_POSIX) && !defined(OS_MACOSX) -extern int ZygoteMain(const content::MainFunctionParams&, - content::ZygoteForkDelegate* forkdelegate); -#endif - -namespace { - -#if defined(OS_WIN) - -static CAppModule _Module; - -#elif defined(OS_MACOSX) - -// Completes the Mach IPC handshake by sending this process' task port to the -// parent process. The parent is listening on the Mach port given by -// |GetMachPortName()|. The task port is used by the parent to get CPU/memory -// stats to display in the task manager. -void SendTaskPortToParentProcess() { - const mach_msg_timeout_t kTimeoutMs = 100; - const int32_t kMessageId = 0; - std::string mach_port_name = MachBroker::GetMachPortName(); - - base::MachSendMessage child_message(kMessageId); - if (!child_message.AddDescriptor(mach_task_self())) { - LOG(ERROR) << "child AddDescriptor(mach_task_self()) failed."; - return; - } - - base::MachPortSender child_sender(mach_port_name.c_str()); - kern_return_t err = child_sender.SendMessage(child_message, kTimeoutMs); - if (err != KERN_SUCCESS) { - LOG(ERROR) << StringPrintf("child SendMessage() failed: 0x%x %s", err, - mach_error_string(err)); - } -} - -#endif // defined(OS_WIN) - -#if defined(OS_POSIX) - -// Setup signal-handling state: resanitize most signals, ignore SIGPIPE. -void SetupSignalHandlers() { - // Sanitise our signal handling state. Signals that were ignored by our - // parent will also be ignored by us. We also inherit our parent's sigmask. - 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}; // SIGPIPE is set below. - for (unsigned i = 0; i < arraysize(signals_to_reset); i++) { - CHECK(0 == sigaction(signals_to_reset[i], &sigact, NULL)); - } - - // Always ignore SIGPIPE. We check the return value of write(). - CHECK(signal(SIGPIPE, SIG_IGN) != SIG_ERR); -} - -#endif // OS_POSIX - -void CommonSubprocessInit(const std::string& process_type) { -#if defined(OS_WIN) - // HACK: Let Windows know that we have started. This is needed to suppress - // the IDC_APPSTARTING cursor from being displayed for a prolonged period - // while a subprocess is starting. - 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) - // Various things break when you're using a locale where the decimal - // separator isn't a period. See e.g. bugs 22782 and 39964. For - // all processes except the browser process (where we call system - // APIs that may rely on the correct locale for formatting numbers - // when presenting them to the user), reset the locale for numeric - // formatting. - // Note that this is not correct for plugin processes -- they can - // surface UI -- but it's likely they get this wrong too so why not. - setlocale(LC_NUMERIC, "C"); -#endif -} - -void InitializeStatsTable(base::ProcessId browser_pid, - const CommandLine& command_line) { - // Initialize the Stats Counters table. With this initialized, - // the StatsViewer can be utilized to read counters outside of - // Chrome. These lines can be commented out to effectively turn - // counters 'off'. The table is created and exists for the life - // of the process. It is not cleaned up. - if (command_line.HasSwitch(switches::kEnableStatsTable)) { - // NOTIMPLEMENTED: we probably need to shut this down correctly to avoid - // leaking shared memory regions on posix platforms. - std::string statsfile = - base::StringPrintf("%s-%u", - content::kStatsFilename, - static_cast<unsigned int>(browser_pid)); - base::StatsTable* stats_table = new base::StatsTable(statsfile, - content::kStatsMaxThreads, content::kStatsMaxCounters); - base::StatsTable::set_current(stats_table); - } -} - -// We dispatch to a process-type-specific FooMain() based on a command-line -// flag. This struct is used to build a table of (flag, main function) pairs. -struct MainFunction { - const char* name; - int (*function)(const content::MainFunctionParams&); -}; - -#if defined(OS_POSIX) && !defined(OS_MACOSX) -// On platforms that use the zygote, we have a special subset of -// subprocesses that are launched via the zygote. This function -// fills in some process-launching bits around ZygoteMain(). -// Returns the exit code of the subprocess. -int RunZygote(const content::MainFunctionParams& main_function_params, - content::ContentMainDelegate* delegate) { - static const MainFunction kMainFunctions[] = { - { switches::kRendererProcess, RendererMain }, - { switches::kWorkerProcess, WorkerMain }, - { switches::kPpapiPluginProcess, PpapiPluginMain }, - { switches::kUtilityProcess, UtilityMain }, - }; - - scoped_ptr<content::ZygoteForkDelegate> zygote_fork_delegate; - if (delegate) zygote_fork_delegate.reset(delegate->ZygoteStarting()); - - // This function call can return multiple times, once per fork(). - if (!ZygoteMain(main_function_params, zygote_fork_delegate.get())) - return 1; - - if (delegate) delegate->ZygoteForked(); - - // Zygote::HandleForkRequest may have reallocated the command - // line so update it here with the new version. - const CommandLine& command_line = *CommandLine::ForCurrentProcess(); - - // If a custom user agent was passed on the command line, we need - // to (re)set it now, rather than using the default one the zygote - // initialized. - bool custom = false; - std::string ua = content::GetContentClient()->GetUserAgent(&custom); - if (custom) webkit_glue::SetUserAgent(ua, custom); - - // The StatsTable must be initialized in each process; we already - // initialized for the browser process, now we need to initialize - // within the new processes as well. - pid_t browser_pid = base::GetParentProcessId( - base::GetParentProcessId(base::GetCurrentProcId())); - InitializeStatsTable(browser_pid, command_line); - - content::MainFunctionParams main_params(command_line); - - // Get the new process type from the new command line. - std::string process_type = - command_line.GetSwitchValueASCII(switches::kProcessType); - - 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 // defined(OS_POSIX) && !defined(OS_MACOSX) - -// Run the FooMain() for a given process type. -// If |process_type| is empty, runs BrowserMain(). -// Returns the exit code for this process. -int RunNamedProcessTypeMain( - const std::string& process_type, - const content::MainFunctionParams& main_function_params, - content::ContentMainDelegate* delegate) { - static const MainFunction kMainFunctions[] = { - { "", BrowserMain }, - { switches::kRendererProcess, RendererMain }, - { switches::kPluginProcess, PluginMain }, - { switches::kWorkerProcess, WorkerMain }, - { switches::kPpapiPluginProcess, PpapiPluginMain }, - { switches::kPpapiBrokerProcess, PpapiBrokerMain }, - { switches::kUtilityProcess, UtilityMain }, - { switches::kGpuProcess, GpuMain }, - }; - - for (size_t i = 0; i < arraysize(kMainFunctions); ++i) { - if (process_type == kMainFunctions[i].name) - return kMainFunctions[i].function(main_function_params); - } - -#if defined(OS_POSIX) && !defined(OS_MACOSX) - // Zygote startup is special -- see RunZygote comments above - // for why we don't use ZygoteMain directly. - if (process_type == switches::kZygoteProcess) - return RunZygote(main_function_params, delegate); -#endif - - // If it's a process we don't know about, the embedder should know. - if (delegate) - return delegate->RunProcess(process_type, main_function_params); - - NOTREACHED() << "Unknown process type: " << process_type; - return 1; -} - -} // namespace +#include "content/public/app/content_main_runner.h" namespace content { @@ -287,184 +13,28 @@ namespace content { int ContentMain(HINSTANCE instance, sandbox::SandboxInterfaceInfo* sandbox_info, ContentMainDelegate* delegate) { - // argc/argv are ignored on Windows; see command_line.h for details. - int argc = 0; - char** argv = NULL; - - content::RegisterInvalidParamHandler(); - _Module.Init(NULL, static_cast<HINSTANCE>(instance)); #else int ContentMain(int argc, const char** argv, ContentMainDelegate* delegate) { - // NOTE(willchan): One might ask why this call is done here rather than in - // process_util_linux.cc with the definition of - // EnableTerminationOnOutOfMemory(). That's because base shouldn't have a - // dependency on TCMalloc. Really, we ought to have our allocator shim code - // implement this EnableTerminationOnOutOfMemory() function. Whateverz. This - // works for now. -#if !defined(OS_MACOSX) && defined(USE_TCMALLOC) - // For tcmalloc, we need to tell it to behave like new. - tc_set_new_mode(1); -#endif - -#if !defined(OS_ANDROID) - // Set C library locale to make sure CommandLine can parse argument values - // in correct encoding. - setlocale(LC_ALL, ""); -#endif - - SetupSignalHandlers(); - - base::GlobalDescriptors* g_fds = base::GlobalDescriptors::GetInstance(); - g_fds->Set(kPrimaryIPCChannel, - kPrimaryIPCChannel + base::GlobalDescriptors::kBaseDescriptor); -#if defined(OS_LINUX) || defined(OS_OPENBSD) - g_fds->Set(kCrashDumpSignal, - kCrashDumpSignal + base::GlobalDescriptors::kBaseDescriptor); -#endif - #endif // OS_WIN - base::EnableTerminationOnHeapCorruption(); - base::EnableTerminationOnOutOfMemory(); - - // The exit manager is in charge of calling the dtors of singleton objects. - base::AtExitManager exit_manager; - -#if defined(OS_MACOSX) - // We need this pool for all the objects created before we get to the - // event loop, but we don't want to leave them hanging around until the - // app quits. Each "main" needs to flush this pool right before it goes into - // its main event loop to get rid of the cruft. - base::mac::ScopedNSAutoreleasePool autorelease_pool; -#endif - - CommandLine::Init(argc, argv); + scoped_ptr<ContentMainRunner> main_runner(ContentMainRunner::Create()); int exit_code; - if (delegate && delegate->BasicStartupComplete(&exit_code)) - return exit_code; - - const CommandLine& command_line = *CommandLine::ForCurrentProcess(); - std::string process_type = - command_line.GetSwitchValueASCII(switches::kProcessType); - - // Enable startup tracing asap to avoid early TRACE_EVENT calls being ignored. - if (command_line.HasSwitch(switches::kTraceStartup)) { - base::debug::TraceLog::GetInstance()->SetEnabled( - command_line.GetSwitchValueASCII(switches::kTraceStartup)); - } - -#if defined(OS_MACOSX) - // We need to allocate the IO Ports before the Sandbox is initialized or - // the first instance of SystemMonitor is created. - // It's important not to allocate the ports for processes which don't register - // with the system monitor - see crbug.com/88867. - if (process_type.empty() || - process_type == switches::kPluginProcess || - process_type == switches::kRendererProcess || - process_type == switches::kUtilityProcess || - process_type == switches::kWorkerProcess || - (delegate && delegate->ProcessRegistersWithSystemProcess(process_type))) { - base::SystemMonitor::AllocateSystemIOPorts(); - } - - if (!process_type.empty() && - (!delegate || delegate->ShouldSendMachPort(process_type))) { - SendTaskPortToParentProcess(); - } -#elif defined(OS_WIN) - content::SetupCRT(command_line); -#endif - -#if defined(OS_POSIX) - if (!process_type.empty()) { - // When you hit Ctrl-C in a terminal running the browser - // process, a SIGINT is delivered to the entire process group. - // When debugging the browser process via gdb, gdb catches the - // SIGINT for the browser process (and dumps you back to the gdb - // console) but doesn't for the child processes, killing them. - // The fix is to have child processes ignore SIGINT; they'll die - // on their own when the browser process goes away. - // - // Note that we *can't* rely on BeingDebugged to catch this case because we - // are the child process, which is not being debugged. - // TODO(evanm): move this to some shared subprocess-init function. - if (!base::debug::BeingDebugged()) - signal(SIGINT, SIG_IGN); - } -#endif - -#if defined(USE_NSS) - crypto::EarlySetupForNSSInit(); -#endif - - ui::RegisterPathProvider(); - content::RegisterPathProvider(); - - CHECK(icu_util::Initialize()); - - base::ProcessId browser_pid = base::GetCurrentProcId(); - 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_POSIX) - // On linux, we're in the zygote here; so we need the parent process' id. - browser_pid = base::GetParentProcessId(base::GetCurrentProcId()); -#endif - } - - InitializeStatsTable(browser_pid, command_line); - - if (delegate) delegate->PreSandboxStartup(); - - if (!process_type.empty()) - CommonSubprocessInit(process_type); #if defined(OS_WIN) - CHECK(content::InitializeSandbox(sandbox_info)); -#elif defined(OS_MACOSX) - if (process_type == switches::kRendererProcess || - process_type == switches::kPpapiPluginProcess || - (delegate && delegate->DelaySandboxInitialization(process_type))) { - // On OS X the renderer sandbox needs to be initialized later in the startup - // sequence in RendererMainPlatformDelegate::EnableSandbox(). - } else { - CHECK(content::InitializeSandbox()); - } -#endif - - if (delegate) delegate->SandboxInitialized(process_type); - -#if defined(OS_POSIX) - SetProcessTitleFromCommandLine(argv); -#endif - - content::MainFunctionParams main_params(command_line); -#if defined(OS_WIN) - main_params.sandbox_info = sandbox_info; -#elif defined(OS_MACOSX) - main_params.autorelease_pool = &autorelease_pool; -#endif - - exit_code = RunNamedProcessTypeMain(process_type, main_params, delegate); + exit_code = main_runner->Initialize(instance, sandbox_info, delegate); +#else + exit_code = main_runner->Initialize(argc, argv, delegate); +#endif // OS_WIN - if (delegate) delegate->ProcessExiting(process_type); + if (exit_code >= 0) + return exit_code; -#if defined(OS_WIN) -#ifdef _CRTDBG_MAP_ALLOC - _CrtDumpMemoryLeaks(); -#endif // _CRTDBG_MAP_ALLOC + exit_code = main_runner->Run(); - _Module.Term(); -#endif // OS_WIN + main_runner->Shutdown(); return exit_code; } diff --git a/content/app/content_main_runner.cc b/content/app/content_main_runner.cc new file mode 100644 index 0000000..cd329bd --- /dev/null +++ b/content/app/content_main_runner.cc @@ -0,0 +1,557 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "content/public/app/content_main_runner.h" + +#include "base/at_exit.h" +#include "base/command_line.h" +#include "base/debug/debugger.h" +#include "base/debug/trace_event.h" +#include "base/i18n/icu_util.h" +#include "base/logging.h" +#include "base/memory/scoped_ptr.h" +#include "base/metrics/stats_table.h" +#include "base/process_util.h" +#include "base/stringprintf.h" +#include "base/string_number_conversions.h" +#include "content/browser/browser_main.h" +#include "content/common/set_process_title.h" +#include "content/public/app/content_main_delegate.h" +#include "content/public/app/startup_helper_win.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 "crypto/nss_util.h" +#include "ipc/ipc_switches.h" +#include "sandbox/src/sandbox_types.h" +#include "ui/base/ui_base_switches.h" +#include "ui/base/ui_base_paths.h" +#include "webkit/glue/webkit_glue.h" + +#if defined(OS_WIN) +#include <atlbase.h> +#include <atlapp.h> +#include <malloc.h> +#elif defined(OS_MACOSX) +#include "base/mac/scoped_nsautorelease_pool.h" +#include "base/mach_ipc_mac.h" +#include "base/system_monitor/system_monitor.h" +#include "content/browser/mach_broker_mac.h" +#include "content/common/sandbox_init_mac.h" +#endif // OS_WIN + +#if defined(OS_POSIX) +#include <signal.h> + +#include "base/global_descriptors_posix.h" +#include "content/common/chrome_descriptors.h" + +#if !defined(OS_MACOSX) +#include "content/public/common/zygote_fork_delegate_linux.h" +#endif + +#endif // OS_POSIX + +#if !defined(OS_MACOSX) && defined(USE_TCMALLOC) +extern "C" { +int tc_set_new_mode(int mode); +} +#endif + +extern int GpuMain(const content::MainFunctionParams&); +extern int PluginMain(const content::MainFunctionParams&); +extern int PpapiPluginMain(const content::MainFunctionParams&); +extern int PpapiBrokerMain(const content::MainFunctionParams&); +extern int RendererMain(const content::MainFunctionParams&); +extern int WorkerMain(const content::MainFunctionParams&); +extern int UtilityMain(const content::MainFunctionParams&); +#if defined(OS_POSIX) && !defined(OS_MACOSX) +extern int ZygoteMain(const content::MainFunctionParams&, + content::ZygoteForkDelegate* forkdelegate); +#endif + +namespace { + +#if defined(OS_WIN) + +static CAppModule _Module; + +#elif defined(OS_MACOSX) + +// Completes the Mach IPC handshake by sending this process' task port to the +// parent process. The parent is listening on the Mach port given by +// |GetMachPortName()|. The task port is used by the parent to get CPU/memory +// stats to display in the task manager. +void SendTaskPortToParentProcess() { + const mach_msg_timeout_t kTimeoutMs = 100; + const int32_t kMessageId = 0; + std::string mach_port_name = MachBroker::GetMachPortName(); + + base::MachSendMessage child_message(kMessageId); + if (!child_message.AddDescriptor(mach_task_self())) { + LOG(ERROR) << "child AddDescriptor(mach_task_self()) failed."; + return; + } + + base::MachPortSender child_sender(mach_port_name.c_str()); + kern_return_t err = child_sender.SendMessage(child_message, kTimeoutMs); + if (err != KERN_SUCCESS) { + LOG(ERROR) << StringPrintf("child SendMessage() failed: 0x%x %s", err, + mach_error_string(err)); + } +} + +#endif // defined(OS_WIN) + +#if defined(OS_POSIX) + +// Setup signal-handling state: resanitize most signals, ignore SIGPIPE. +void SetupSignalHandlers() { + // Sanitise our signal handling state. Signals that were ignored by our + // parent will also be ignored by us. We also inherit our parent's sigmask. + 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}; // SIGPIPE is set below. + for (unsigned i = 0; i < arraysize(signals_to_reset); i++) { + CHECK(0 == sigaction(signals_to_reset[i], &sigact, NULL)); + } + + // Always ignore SIGPIPE. We check the return value of write(). + CHECK(signal(SIGPIPE, SIG_IGN) != SIG_ERR); +} + +#endif // OS_POSIX + +void CommonSubprocessInit(const std::string& process_type) { +#if defined(OS_WIN) + // HACK: Let Windows know that we have started. This is needed to suppress + // the IDC_APPSTARTING cursor from being displayed for a prolonged period + // while a subprocess is starting. + 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) + // Various things break when you're using a locale where the decimal + // separator isn't a period. See e.g. bugs 22782 and 39964. For + // all processes except the browser process (where we call system + // APIs that may rely on the correct locale for formatting numbers + // when presenting them to the user), reset the locale for numeric + // formatting. + // Note that this is not correct for plugin processes -- they can + // surface UI -- but it's likely they get this wrong too so why not. + setlocale(LC_NUMERIC, "C"); +#endif +} + +void InitializeStatsTable(base::ProcessId browser_pid, + const CommandLine& command_line) { + // Initialize the Stats Counters table. With this initialized, + // the StatsViewer can be utilized to read counters outside of + // Chrome. These lines can be commented out to effectively turn + // counters 'off'. The table is created and exists for the life + // of the process. It is not cleaned up. + if (command_line.HasSwitch(switches::kEnableStatsTable)) { + // NOTIMPLEMENTED: we probably need to shut this down correctly to avoid + // leaking shared memory regions on posix platforms. + std::string statsfile = + base::StringPrintf("%s-%u", + content::kStatsFilename, + static_cast<unsigned int>(browser_pid)); + base::StatsTable* stats_table = new base::StatsTable(statsfile, + content::kStatsMaxThreads, content::kStatsMaxCounters); + base::StatsTable::set_current(stats_table); + } +} + +// We dispatch to a process-type-specific FooMain() based on a command-line +// flag. This struct is used to build a table of (flag, main function) pairs. +struct MainFunction { + const char* name; + int (*function)(const content::MainFunctionParams&); +}; + +#if defined(OS_POSIX) && !defined(OS_MACOSX) +// On platforms that use the zygote, we have a special subset of +// subprocesses that are launched via the zygote. This function +// fills in some process-launching bits around ZygoteMain(). +// Returns the exit code of the subprocess. +int RunZygote(const content::MainFunctionParams& main_function_params, + content::ContentMainDelegate* delegate) { + static const MainFunction kMainFunctions[] = { + { switches::kRendererProcess, RendererMain }, + { switches::kWorkerProcess, WorkerMain }, + { switches::kPpapiPluginProcess, PpapiPluginMain }, + { switches::kUtilityProcess, UtilityMain }, + }; + + scoped_ptr<content::ZygoteForkDelegate> zygote_fork_delegate; + if (delegate) zygote_fork_delegate.reset(delegate->ZygoteStarting()); + + // This function call can return multiple times, once per fork(). + if (!ZygoteMain(main_function_params, zygote_fork_delegate.get())) + return 1; + + if (delegate) delegate->ZygoteForked(); + + // Zygote::HandleForkRequest may have reallocated the command + // line so update it here with the new version. + const CommandLine& command_line = *CommandLine::ForCurrentProcess(); + + // If a custom user agent was passed on the command line, we need + // to (re)set it now, rather than using the default one the zygote + // initialized. + bool custom = false; + std::string ua = content::GetContentClient()->GetUserAgent(&custom); + if (custom) webkit_glue::SetUserAgent(ua, custom); + + // The StatsTable must be initialized in each process; we already + // initialized for the browser process, now we need to initialize + // within the new processes as well. + pid_t browser_pid = base::GetParentProcessId( + base::GetParentProcessId(base::GetCurrentProcId())); + InitializeStatsTable(browser_pid, command_line); + + content::MainFunctionParams main_params(command_line); + + // Get the new process type from the new command line. + std::string process_type = + command_line.GetSwitchValueASCII(switches::kProcessType); + + 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 // defined(OS_POSIX) && !defined(OS_MACOSX) + +// Run the FooMain() for a given process type. +// If |process_type| is empty, runs BrowserMain(). +// Returns the exit code for this process. +int RunNamedProcessTypeMain( + const std::string& process_type, + const content::MainFunctionParams& main_function_params, + content::ContentMainDelegate* delegate) { + static const MainFunction kMainFunctions[] = { + { "", BrowserMain }, + { switches::kRendererProcess, RendererMain }, + { switches::kPluginProcess, PluginMain }, + { switches::kWorkerProcess, WorkerMain }, + { switches::kPpapiPluginProcess, PpapiPluginMain }, + { switches::kPpapiBrokerProcess, PpapiBrokerMain }, + { switches::kUtilityProcess, UtilityMain }, + { switches::kGpuProcess, GpuMain }, + }; + + 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 (exit_code >= 0) + return exit_code; + } + return kMainFunctions[i].function(main_function_params); + } + } + +#if defined(OS_POSIX) && !defined(OS_MACOSX) + // Zygote startup is special -- see RunZygote comments above + // for why we don't use ZygoteMain directly. + if (process_type == switches::kZygoteProcess) + return RunZygote(main_function_params, delegate); +#endif + + // If it's a process we don't know about, the embedder should know. + if (delegate) + return delegate->RunProcess(process_type, main_function_params); + + NOTREACHED() << "Unknown process type: " << process_type; + return 1; +} + +class ContentMainRunnerImpl : public content::ContentMainRunner { + public: + ContentMainRunnerImpl() + : is_initialized_(false), + is_shutdown_(false) { + } + + ~ContentMainRunnerImpl() { + if (is_initialized_ && !is_shutdown_) + Shutdown(); + } + +#if defined(OS_WIN) + virtual int Initialize(HINSTANCE instance, + sandbox::SandboxInterfaceInfo* sandbox_info, + content::ContentMainDelegate* delegate) OVERRIDE { + // argc/argv are ignored on Windows; see command_line.h for details. + int argc = 0; + char** argv = NULL; + + content::RegisterInvalidParamHandler(); + _Module.Init(NULL, static_cast<HINSTANCE>(instance)); + + if (sandbox_info) + sandbox_info_ = *sandbox_info; + else + memset(&sandbox_info_, 0, sizeof(sandbox_info_)); + +#else // !OS_WIN + virtual int Initialize(int argc, + const char** argv, + content::ContentMainDelegate* delegate) OVERRIDE { + // NOTE(willchan): One might ask why this call is done here rather than in + // process_util_linux.cc with the definition of + // EnableTerminationOnOutOfMemory(). That's because base shouldn't have a + // dependency on TCMalloc. Really, we ought to have our allocator shim code + // implement this EnableTerminationOnOutOfMemory() function. Whateverz. + // This works for now. +#if !defined(OS_MACOSX) && defined(USE_TCMALLOC) + // For tcmalloc, we need to tell it to behave like new. + tc_set_new_mode(1); +#endif + +#if !defined(OS_ANDROID) + // Set C library locale to make sure CommandLine can parse argument values + // in correct encoding. + setlocale(LC_ALL, ""); +#endif + + SetupSignalHandlers(); + + base::GlobalDescriptors* g_fds = base::GlobalDescriptors::GetInstance(); + g_fds->Set(kPrimaryIPCChannel, + kPrimaryIPCChannel + base::GlobalDescriptors::kBaseDescriptor); +#if defined(OS_LINUX) || defined(OS_OPENBSD) + g_fds->Set(kCrashDumpSignal, + kCrashDumpSignal + base::GlobalDescriptors::kBaseDescriptor); +#endif + +#endif // !OS_WIN + + is_initialized_ = true; + delegate_ = delegate; + + base::EnableTerminationOnHeapCorruption(); + base::EnableTerminationOnOutOfMemory(); + + // The exit manager is in charge of calling the dtors of singleton objects. + exit_manager_.reset(new base::AtExitManager); + +#if defined(OS_MACOSX) + // We need this pool for all the objects created before we get to the + // event loop, but we don't want to leave them hanging around until the + // app quits. Each "main" needs to flush this pool right before it goes into + // its main event loop to get rid of the cruft. + autorelease_pool_.reset(new base::mac::ScopedNSAutoreleasePool()); +#endif + + CommandLine::Init(argc, argv); + + int exit_code; + if (delegate && delegate->BasicStartupComplete(&exit_code)) + return exit_code; + + const CommandLine& command_line = *CommandLine::ForCurrentProcess(); + std::string process_type = + command_line.GetSwitchValueASCII(switches::kProcessType); + + // Enable startup tracing asap to avoid early TRACE_EVENT calls being + // ignored. + if (command_line.HasSwitch(switches::kTraceStartup)) { + base::debug::TraceLog::GetInstance()->SetEnabled( + command_line.GetSwitchValueASCII(switches::kTraceStartup)); + } + +#if defined(OS_MACOSX) + // We need to allocate the IO Ports before the Sandbox is initialized or + // the first instance of SystemMonitor is created. + // It's important not to allocate the ports for processes which don't + // register with the system monitor - see crbug.com/88867. + if (process_type.empty() || + process_type == switches::kPluginProcess || + process_type == switches::kRendererProcess || + process_type == switches::kUtilityProcess || + process_type == switches::kWorkerProcess || + (delegate && + delegate->ProcessRegistersWithSystemProcess(process_type))) { + base::SystemMonitor::AllocateSystemIOPorts(); + } + + if (!process_type.empty() && + (!delegate || delegate->ShouldSendMachPort(process_type))) { + SendTaskPortToParentProcess(); + } +#elif defined(OS_WIN) + content::SetupCRT(command_line); +#endif + +#if defined(OS_POSIX) + if (!process_type.empty()) { + // When you hit Ctrl-C in a terminal running the browser + // process, a SIGINT is delivered to the entire process group. + // When debugging the browser process via gdb, gdb catches the + // SIGINT for the browser process (and dumps you back to the gdb + // console) but doesn't for the child processes, killing them. + // The fix is to have child processes ignore SIGINT; they'll die + // on their own when the browser process goes away. + // + // Note that we *can't* rely on BeingDebugged to catch this case because + // we are the child process, which is not being debugged. + // TODO(evanm): move this to some shared subprocess-init function. + if (!base::debug::BeingDebugged()) + signal(SIGINT, SIG_IGN); + } +#endif + +#if defined(USE_NSS) + crypto::EarlySetupForNSSInit(); +#endif + + ui::RegisterPathProvider(); + content::RegisterPathProvider(); + + CHECK(icu_util::Initialize()); + + base::ProcessId browser_pid = base::GetCurrentProcId(); + 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_POSIX) + // On linux, we're in the zygote here; so we need the parent process' id. + browser_pid = base::GetParentProcessId(base::GetCurrentProcId()); +#endif + } + + InitializeStatsTable(browser_pid, command_line); + + if (delegate) + delegate->PreSandboxStartup(); + + if (!process_type.empty()) + CommonSubprocessInit(process_type); + +#if defined(OS_WIN) + CHECK(content::InitializeSandbox(sandbox_info)); +#elif defined(OS_MACOSX) + if (process_type == switches::kRendererProcess || + process_type == switches::kPpapiPluginProcess || + (delegate && delegate->DelaySandboxInitialization(process_type))) { + // On OS X the renderer sandbox needs to be initialized later in the + // startup sequence in RendererMainPlatformDelegate::EnableSandbox(). + } else { + CHECK(content::InitializeSandbox()); + } +#endif + + if (delegate) + delegate->SandboxInitialized(process_type); + +#if defined(OS_POSIX) + SetProcessTitleFromCommandLine(argv); +#endif + + // Return -1 to indicate no early termination. + 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); + + content::MainFunctionParams main_params(command_line); +#if defined(OS_WIN) + main_params.sandbox_info = &sandbox_info_; +#elif defined(OS_MACOSX) + main_params.autorelease_pool = autorelease_pool_.get(); +#endif + + return RunNamedProcessTypeMain(process_type, main_params, delegate_); + } + + virtual void Shutdown() OVERRIDE { + DCHECK(is_initialized_); + DCHECK(!is_shutdown_); + const CommandLine& command_line = *CommandLine::ForCurrentProcess(); + std::string process_type = + command_line.GetSwitchValueASCII(switches::kProcessType); + + if (delegate_) + delegate_->ProcessExiting(process_type); + +#if defined(OS_WIN) +#ifdef _CRTDBG_MAP_ALLOC + _CrtDumpMemoryLeaks(); +#endif // _CRTDBG_MAP_ALLOC + + _Module.Term(); +#endif // OS_WIN + +#if defined(OS_MACOSX) + autorelease_pool_.reset(NULL); +#endif + + exit_manager_.reset(NULL); + + delegate_ = NULL; + is_shutdown_ = true; + } + + protected: + // True if the runner has been initialized. + bool is_initialized_; + + // True if the runner has been shut down. + bool is_shutdown_; + + // The delegate will outlive this object. + content::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 + + DISALLOW_COPY_AND_ASSIGN(ContentMainRunnerImpl); +}; + +} // namespace + +namespace content { + +// static +ContentMainRunner* ContentMainRunner::Create() { + return new ContentMainRunnerImpl(); +} + +} // namespace content diff --git a/content/browser/browser_main.cc b/content/browser/browser_main.cc index 0efd4ae..99f8247 100644 --- a/content/browser/browser_main.cc +++ b/content/browser/browser_main.cc @@ -1,105 +1,28 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/browser_main.h" -#include "base/allocator/allocator_shim.h" -#include "base/base_switches.h" -#include "base/command_line.h" #include "base/debug/trace_event.h" -#include "base/logging.h" -#include "base/metrics/histogram.h" -#include "content/browser/browser_main_loop.h" -#include "content/browser/notification_service_impl.h" -#include "content/common/child_process.h" -#include "content/public/common/content_switches.h" -#include "content/public/common/main_function_params.h" - -#if defined(OS_WIN) -#include "base/win/scoped_com_initializer.h" -#endif - -namespace { - -bool g_exited_main_message_loop = false; - -} // namespace - -namespace content { - -bool ExitedMainMessageLoop() { - return g_exited_main_message_loop; -} - -} // namespace content +#include "content/public/browser/browser_main_runner.h" // Main routine for running as the Browser process. int BrowserMain(const content::MainFunctionParams& parameters) { TRACE_EVENT_BEGIN_ETW("BrowserMain", 0, ""); - // ChildProcess:: is a misnomer unless you consider context. Use - // of --wait-for-debugger only makes sense when Chrome itself is a - // child process (e.g. when launched by PyAuto). - if (parameters.command_line.HasSwitch(switches::kWaitForDebugger)) - ChildProcess::WaitForDebugger("Browser"); - - NotificationServiceImpl main_notification_service; - - scoped_ptr<content::BrowserMainLoop> main_loop( - new content::BrowserMainLoop(parameters)); - - main_loop->Init(); - - main_loop->EarlyInitialization(); - - // Must happen before we try to use a message loop or display any UI. - main_loop->InitializeToolkit(); - - main_loop->MainMessageLoopStart(); - - // WARNING: If we get a WM_ENDSESSION, objects created on the stack here - // are NOT deleted. If you need something to run during WM_ENDSESSION add it - // to browser_shutdown::Shutdown or BrowserProcess::EndSession. - - // !!!!!!!!!! READ ME !!!!!!!!!! - // I (viettrungluu) am in the process of refactoring |BrowserMain()|. If you - // need to add something above this comment, read the documentation in - // browser_main.h. If you need to add something below, please do the - // following: - // - Figure out where you should add your code. Do NOT just pick a random - // location "which works". - // - Document the dependencies apart from compile-time-checkable ones. What - // must happen before your new code is executed? Does your new code need to - // run before something else? Are there performance reasons for executing - // your code at that point? - // - If you need to create a (persistent) object, heap allocate it and keep a - // |scoped_ptr| to it rather than allocating it on the stack. Otherwise - // I'll have to convert your code when I refactor. - // - Unless your new code is just a couple of lines, factor it out into a - // function with a well-defined purpose. Do NOT just add it inline in - // |BrowserMain()|. - // Thanks! - - // TODO(viettrungluu): put the remainder into BrowserMainParts - -#if defined(OS_WIN) -#if !defined(NO_TCMALLOC) - // When linking shared libraries, NO_TCMALLOC is defined, and dynamic - // allocator selection is not supported. - - // Make this call before going multithreaded, or spawning any subprocesses. - base::allocator::SetupSubprocessAllocator(); -#endif + scoped_ptr<content::BrowserMainRunner> main_runner_( + content::BrowserMainRunner::Create()); - base::win::ScopedCOMInitializer com_initializer; -#endif // OS_WIN + int exit_code = main_runner_->Initialize(parameters); + if (exit_code >= 0) + return exit_code; - base::StatisticsRecorder statistics; + exit_code = main_runner_->Run(); - main_loop->RunMainMessageLoopParts(&g_exited_main_message_loop); + main_runner_->Shutdown(); TRACE_EVENT_END_ETW("BrowserMain", 0, 0); - return main_loop->GetResultCode(); + return exit_code; } diff --git a/content/browser/browser_main_loop.cc b/content/browser/browser_main_loop.cc index 00b2a87..c953db0 100644 --- a/content/browser/browser_main_loop.cc +++ b/content/browser/browser_main_loop.cc @@ -291,7 +291,9 @@ void BrowserMainLoop::MainMessageLoopStart() { // Must first NULL pointer or we hit a DCHECK that the newly constructed // message loop is the current one. main_message_loop_.reset(); - main_message_loop_.reset(new MessageLoop(MessageLoop::TYPE_UI)); + main_message_loop_.reset(parts_->GetMainMessageLoop()); + if (!main_message_loop_.get()) + main_message_loop_.reset(new MessageLoop(MessageLoop::TYPE_UI)); InitializeMainThread(); @@ -318,8 +320,7 @@ void BrowserMainLoop::MainMessageLoopStart() { parts_->PostMainMessageLoopStart(); } -void BrowserMainLoop::RunMainMessageLoopParts( - bool* completed_main_message_loop) { +void BrowserMainLoop::CreateThreads() { if (parts_.get()) result_code_ = parts_->PreCreateThreads(); @@ -403,10 +404,13 @@ void BrowserMainLoop::RunMainMessageLoopParts( if (parts_.get()) parts_->PreMainMessageLoopRun(); - TRACE_EVENT_BEGIN_ETW("BrowserMain:MESSAGE_LOOP", 0, ""); // If the UI thread blocks, the whole UI is unresponsive. // Do not allow disk IO from the UI thread. base::ThreadRestrictions::SetIOAllowed(false); +} + +void BrowserMainLoop::RunMainMessageLoopParts() { + TRACE_EVENT_BEGIN_ETW("BrowserMain:MESSAGE_LOOP", 0, ""); bool ran_main_loop = false; if (parts_.get()) @@ -416,11 +420,6 @@ void BrowserMainLoop::RunMainMessageLoopParts( MainMessageLoopRun(); TRACE_EVENT_END_ETW("BrowserMain:MESSAGE_LOOP", 0, ""); - - if (completed_main_message_loop) - *completed_main_message_loop = true; - - ShutdownThreadsAndCleanUp(); } void BrowserMainLoop::ShutdownThreadsAndCleanUp() { diff --git a/content/browser/browser_main_loop.h b/content/browser/browser_main_loop.h index c0c3a45..d6f351d 100644 --- a/content/browser/browser_main_loop.h +++ b/content/browser/browser_main_loop.h @@ -44,24 +44,30 @@ class BrowserMainLoop { void EarlyInitialization(); void InitializeToolkit(); void MainMessageLoopStart(); - void RunMainMessageLoopParts(bool* completed_main_message_loop); - void MainMessageLoopRun(); - int GetResultCode() const { return result_code_; } + // Create all secondary threads. + void CreateThreads(); - private: - // For ShutdownThreadsAndCleanUp. - friend class BrowserShutdownImpl; + // Perform the default message loop run logic. + void RunMainMessageLoopParts(); // Performs the shutdown sequence, starting with PostMainMessageLoopRun // through stopping threads to PostDestroyThreads. void ShutdownThreadsAndCleanUp(); + int GetResultCode() const { return result_code_; } + + private: + // For ShutdownThreadsAndCleanUp. + friend class BrowserShutdownImpl; + void InitializeMainThread(); // Called right after the browser threads have been started. void BrowserThreadsStarted(); + void MainMessageLoopRun(); + // Members initialized on construction --------------------------------------- const content::MainFunctionParams& parameters_; const CommandLine& parsed_command_line_; diff --git a/content/browser/browser_main_runner.cc b/content/browser/browser_main_runner.cc new file mode 100644 index 0000000..23bfb8d --- /dev/null +++ b/content/browser/browser_main_runner.cc @@ -0,0 +1,148 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "content/public/browser/browser_main_runner.h" + +#include "base/allocator/allocator_shim.h" +#include "base/base_switches.h" +#include "base/command_line.h" +#include "base/debug/trace_event.h" +#include "base/logging.h" +#include "base/metrics/histogram.h" +#include "content/browser/browser_main_loop.h" +#include "content/browser/notification_service_impl.h" +#include "content/common/child_process.h" +#include "content/public/common/content_switches.h" +#include "content/public/common/main_function_params.h" + +#if defined(OS_WIN) +#include "base/win/scoped_com_initializer.h" +#endif + +bool g_exited_main_message_loop = false; + +namespace { + +class BrowserMainRunnerImpl : public content::BrowserMainRunner { + public: + BrowserMainRunnerImpl() + : is_initialized_(false), + is_shutdown_(false), + created_threads_(false) { + } + + ~BrowserMainRunnerImpl() { + if (is_initialized_ && !is_shutdown_) + Shutdown(); + } + + virtual int Initialize(const content::MainFunctionParams& parameters) + OVERRIDE { + is_initialized_ = true; + + // ChildProcess:: is a misnomer unless you consider context. Use + // of --wait-for-debugger only makes sense when Chrome itself is a + // child process (e.g. when launched by PyAuto). + if (parameters.command_line.HasSwitch(switches::kWaitForDebugger)) + ChildProcess::WaitForDebugger("Browser"); + + notification_service_.reset(new NotificationServiceImpl); + + main_loop_.reset(new content::BrowserMainLoop(parameters)); + + main_loop_->Init(); + + main_loop_->EarlyInitialization(); + + // Must happen before we try to use a message loop or display any UI. + main_loop_->InitializeToolkit(); + + main_loop_->MainMessageLoopStart(); + + // WARNING: If we get a WM_ENDSESSION, objects created on the stack here + // are NOT deleted. If you need something to run during WM_ENDSESSION add it + // to browser_shutdown::Shutdown or BrowserProcess::EndSession. + +#if defined(OS_WIN) +#if !defined(NO_TCMALLOC) + // When linking shared libraries, NO_TCMALLOC is defined, and dynamic + // allocator selection is not supported. + + // Make this call before going multithreaded, or spawning any subprocesses. + base::allocator::SetupSubprocessAllocator(); +#endif + + com_initializer_.reset(new base::win::ScopedCOMInitializer); +#endif // OS_WIN + + statistics_.reset(new base::StatisticsRecorder); + + main_loop_->CreateThreads(); + int result_code = main_loop_->GetResultCode(); + if (result_code > 0) + return result_code; + created_threads_ = true; + + // Return -1 to indicate no early termination. + return -1; + } + + virtual int Run() OVERRIDE { + DCHECK(is_initialized_); + DCHECK(!is_shutdown_); + main_loop_->RunMainMessageLoopParts(); + return main_loop_->GetResultCode(); + } + + virtual void Shutdown() OVERRIDE { + DCHECK(is_initialized_); + DCHECK(!is_shutdown_); + g_exited_main_message_loop = true; + + if (created_threads_) + main_loop_->ShutdownThreadsAndCleanUp(); + + statistics_.reset(NULL); + +#if defined(OS_WIN) + com_initializer_.reset(NULL); +#endif + + main_loop_.reset(NULL); + + notification_service_.reset(NULL); + + is_shutdown_ = true; + } + + protected: + // True if the runner has been initialized. + bool is_initialized_; + + // True if the runner has been shut down. + bool is_shutdown_; + + // True if the non-UI threads were created. + bool created_threads_; + + scoped_ptr<NotificationServiceImpl> notification_service_; + scoped_ptr<content::BrowserMainLoop> main_loop_; +#if defined(OS_WIN) + scoped_ptr<base::win::ScopedCOMInitializer> com_initializer_; +#endif + scoped_ptr<base::StatisticsRecorder> statistics_; + + DISALLOW_COPY_AND_ASSIGN(BrowserMainRunnerImpl); +}; + +} // namespace + +namespace content { + +// static +BrowserMainRunner* BrowserMainRunner::Create() { + return new BrowserMainRunnerImpl(); +} + +} // namespace content diff --git a/content/browser/renderer_host/render_process_host_impl.cc b/content/browser/renderer_host/render_process_host_impl.cc index 952ffb3..ce2d699 100644 --- a/content/browser/renderer_host/render_process_host_impl.cc +++ b/content/browser/renderer_host/render_process_host_impl.cc @@ -120,6 +120,8 @@ using content::ChildProcessHostImpl; using content::UserMetricsAction; using content::WebUIControllerFactory; +extern bool g_exited_main_message_loop; + // This class creates the IO thread for the renderer when running in // single-process mode. It's not used in multi-process mode. class RendererMainThread : public base::Thread { @@ -314,7 +316,7 @@ RenderProcessHostImpl::RenderProcessHostImpl( base::PLATFORM_FILE_CREATE | base::PLATFORM_FILE_CREATE_ALWAYS | base::PLATFORM_FILE_WRITE); - CHECK(!content::ExitedMainMessageLoop()); + CHECK(!g_exited_main_message_loop); RegisterHost(GetID(), this); g_all_hosts.Get().set_check_on_null_data(true); // Initialize |child_process_activity_time_| to a reasonable value. diff --git a/content/content_app.gypi b/content/content_app.gypi index baa5207..ad1cc83 100644 --- a/content/content_app.gypi +++ b/content/content_app.gypi @@ -1,4 +1,4 @@ -# Copyright (c) 2011 The Chromium Authors. All rights reserved. +# Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. @@ -14,9 +14,11 @@ ], 'sources': [ 'app/content_main.cc', - 'app/content_main.h', + 'app/content_main_runner.cc', 'app/startup_helper_win.cc', + 'public/app/content_main.h', 'public/app/content_main_delegate.h', + 'public/app/content_main_runner.h', 'public/app/startup_helper_win.h', ], 'conditions': [ diff --git a/content/content_browser.gypi b/content/content_browser.gypi index 6e43dcb..3c8af69 100644 --- a/content/content_browser.gypi +++ b/content/content_browser.gypi @@ -34,6 +34,7 @@ 'public/browser/browser_child_process_host_iterator.h', 'public/browser/browser_context.h', 'public/browser/browser_main_parts.h', + 'public/browser/browser_main_runner.h', 'public/browser/browser_message_filter.cc', 'public/browser/browser_message_filter.h', 'public/browser/browser_shutdown.h', @@ -148,6 +149,7 @@ 'browser/browser_main.h', 'browser/browser_main_loop.cc', 'browser/browser_main_loop.h', + 'browser/browser_main_runner.cc', 'browser/browser_process_sub_thread.cc', 'browser/browser_process_sub_thread.h', 'browser/browser_thread_impl.cc', diff --git a/content/app/content_main.h b/content/public/app/content_main.h index c35b589..6c58a8a 100644 --- a/content/app/content_main.h +++ b/content/public/app/content_main.h @@ -1,9 +1,9 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CONTENT_APP_CONTENT_MAIN_H_ -#define CONTENT_APP_CONTENT_MAIN_H_ +#ifndef CONTENT_PUBLIC_APP_CONTENT_MAIN_H_ +#define CONTENT_PUBLIC_APP_CONTENT_MAIN_H_ #pragma once #include "build/build_config.h" @@ -40,4 +40,4 @@ CONTENT_EXPORT int ContentMain(int argc, } // namespace content -#endif // CONTENT_APP_CONTENT_MAIN_H_ +#endif // CONTENT_PUBLIC_APP_CONTENT_MAIN_H_ diff --git a/content/public/app/content_main_delegate.h b/content/public/app/content_main_delegate.h index 6fd40b0..c7c6bd6 100644 --- a/content/public/app/content_main_delegate.h +++ b/content/public/app/content_main_delegate.h @@ -1,4 +1,4 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. @@ -34,7 +34,7 @@ class ContentMainDelegate { // has been initialized. virtual void SandboxInitialized(const std::string& process_type) = 0; - // Asks the embedder to start a process that content doesn't know about. + // Asks the embedder to start a process. Return -1 for the default behavior. virtual int RunProcess( const std::string& process_type, const content::MainFunctionParams& main_function_params) = 0; diff --git a/content/public/app/content_main_runner.h b/content/public/app/content_main_runner.h new file mode 100644 index 0000000..af9d05f --- /dev/null +++ b/content/public/app/content_main_runner.h @@ -0,0 +1,57 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CONTENT_PUBLIC_APP_CONTENT_MAIN_RUNNER_H_ +#define CONTENT_PUBLIC_APP_CONTENT_MAIN_RUNNER_H_ +#pragma once + +#include <string> + +#include "build/build_config.h" + +#if defined(OS_WIN) +#include <windows.h> +#endif + +namespace sandbox { +struct SandboxInterfaceInfo; +} + +namespace content { + +class ContentMainDelegate; + +// This class is responsible for content initialization, running and shutdown. +class ContentMainRunner { + public: + virtual ~ContentMainRunner() {} + + // Create a new ContentMainRunner object. + static ContentMainRunner* Create(); + + // Initialize all necessary content state. +#if defined(OS_WIN) + // The |sandbox_info| and |delegate| objects must outlive this class. + // |sandbox_info| should be initialized using InitializeSandboxInfo from + // content_main_win.h. + virtual int Initialize(HINSTANCE instance, + sandbox::SandboxInterfaceInfo* sandbox_info, + ContentMainDelegate* delegate) = 0; +#else + // The |delegate| object must outlive this class. + virtual int Initialize(int argc, + const char** argv, + ContentMainDelegate* delegate) = 0; +#endif + + // Perform the default run logic. + virtual int Run() = 0; + + // Shut down the content state. + virtual void Shutdown() = 0; +}; + +} // namespace content + +#endif // CONTENT_PUBLIC_APP_CONTENT_MAIN_RUNNER_H_ diff --git a/content/public/browser/browser_main_parts.h b/content/public/browser/browser_main_parts.h index 5bfadda..cbccdfb 100644 --- a/content/public/browser/browser_main_parts.h +++ b/content/public/browser/browser_main_parts.h @@ -10,6 +10,8 @@ #include "content/common/content_export.h" #include "content/public/browser/browser_thread.h" +class MessageLoop; + namespace content { // This class contains different "stages" to be executed by |BrowserMain()|, @@ -60,6 +62,10 @@ class CONTENT_EXPORT BrowserMainParts { virtual void PreMainMessageLoopStart() = 0; + // Return the main message loop object or NULL to use the default message + // loop object. + virtual MessageLoop* GetMainMessageLoop() = 0; + virtual void PostMainMessageLoopStart() = 0; // Allows an embedder to do any extra toolkit initialization. diff --git a/content/public/browser/browser_main_runner.h b/content/public/browser/browser_main_runner.h new file mode 100644 index 0000000..97fbf42 --- /dev/null +++ b/content/public/browser/browser_main_runner.h @@ -0,0 +1,37 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CONTENT_PUBLIC_BROWSER_BROWSER_MAIN_RUNNER_H_ +#define CONTENT_PUBLIC_BROWSER_BROWSER_MAIN_RUNNER_H_ +#pragma once + +#include "base/basictypes.h" +#include "content/common/content_export.h" + +namespace content { + +struct MainFunctionParams; + +// This class is responsible for browser initialization, running and shutdown. +class BrowserMainRunner { + public: + virtual ~BrowserMainRunner() {} + + // Create a new BrowserMainRunner object. + static BrowserMainRunner* Create(); + + // Initialize all necessary browser state. The |parameters| values will be + // copied. + virtual int Initialize(const content::MainFunctionParams& parameters) = 0; + + // Perform the default run logic. + virtual int Run() = 0; + + // Shut down the browser state. + virtual void Shutdown() = 0; +}; + +} // namespace content + +#endif // CONTENT_PUBLIC_BROWSER_BROWSER_MAIN_RUNNER_H_ diff --git a/content/shell/shell_browser_main.cc b/content/shell/shell_browser_main.cc index bdea106..7f7b30d 100644 --- a/content/shell/shell_browser_main.cc +++ b/content/shell/shell_browser_main.cc @@ -46,6 +46,10 @@ ShellBrowserMainParts::ShellBrowserMainParts( ShellBrowserMainParts::~ShellBrowserMainParts() { } +MessageLoop* ShellBrowserMainParts::GetMainMessageLoop() { + return NULL; +} + int ShellBrowserMainParts::PreCreateThreads() { return 0; } diff --git a/content/shell/shell_browser_main.h b/content/shell/shell_browser_main.h index 373b37e..4e836d8 100644 --- a/content/shell/shell_browser_main.h +++ b/content/shell/shell_browser_main.h @@ -32,8 +32,9 @@ class ShellBrowserMainParts : public BrowserMainParts { virtual void PreEarlyInitialization() OVERRIDE {} virtual void PostEarlyInitialization() OVERRIDE {} virtual void PreMainMessageLoopStart() OVERRIDE {} - virtual void ToolkitInitialized() OVERRIDE {} + virtual MessageLoop* GetMainMessageLoop() OVERRIDE; virtual void PostMainMessageLoopStart() OVERRIDE {} + virtual void ToolkitInitialized() OVERRIDE {} virtual int PreCreateThreads() OVERRIDE; virtual void PreMainMessageLoopRun() OVERRIDE; virtual bool MainMessageLoopRun(int* result_code) OVERRIDE; diff --git a/content/shell/shell_main.cc b/content/shell/shell_main.cc index b998aed..8c4892f 100644 --- a/content/shell/shell_main.cc +++ b/content/shell/shell_main.cc @@ -1,8 +1,8 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "content/app/content_main.h" +#include "content/public/app/content_main.h" #include "content/shell/shell_main_delegate.h" #include "sandbox/src/sandbox_types.h" diff --git a/content/shell/shell_main_delegate.cc b/content/shell/shell_main_delegate.cc index f914e8d..0a3977b 100644 --- a/content/shell/shell_main_delegate.cc +++ b/content/shell/shell_main_delegate.cc @@ -43,7 +43,6 @@ void ShellMainDelegate::SandboxInitialized(const std::string& process_type) { int ShellMainDelegate::RunProcess( const std::string& process_type, const content::MainFunctionParams& main_function_params) { - NOTREACHED(); return -1; } diff --git a/content/test/content_test_launcher.cc b/content/test/content_test_launcher.cc index f2cd5a3..b646f3e 100644 --- a/content/test/content_test_launcher.cc +++ b/content/test/content_test_launcher.cc @@ -1,4 +1,4 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. @@ -10,7 +10,7 @@ #include "base/path_service.h" #include "base/scoped_temp_dir.h" #include "base/test/test_suite.h" -#include "content/app/content_main.h" +#include "content/public/app/content_main.h" #include "content/public/common/content_switches.h" #include "content/shell/shell_main_delegate.h" |