1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/public/app/content_main_runner.h"
9 #include "base/allocator/allocator_extension.h"
10 #include "base/at_exit.h"
11 #include "base/command_line.h"
12 #include "base/debug/debugger.h"
13 #include "base/debug/trace_event.h"
14 #include "base/files/file_path.h"
15 #include "base/i18n/icu_util.h"
16 #include "base/lazy_instance.h"
17 #include "base/logging.h"
18 #include "base/memory/scoped_ptr.h"
19 #include "base/metrics/stats_table.h"
20 #include "base/path_service.h"
21 #include "base/process/launch.h"
22 #include "base/process/memory.h"
23 #include "base/process/process_handle.h"
24 #include "base/profiler/alternate_timer.h"
25 #include "base/strings/string_number_conversions.h"
26 #include "base/strings/string_util.h"
27 #include "base/strings/stringprintf.h"
28 #include "content/browser/browser_main.h"
29 #include "content/browser/gpu/gpu_process_host.h"
30 #include "content/common/set_process_title.h"
31 #include "content/common/url_schemes.h"
32 #include "content/gpu/in_process_gpu_thread.h"
33 #include "content/public/app/content_main_delegate.h"
34 #include "content/public/app/startup_helper_win.h"
35 #include "content/public/browser/content_browser_client.h"
36 #include "content/public/browser/render_process_host.h"
37 #include "content/public/browser/utility_process_host.h"
38 #include "content/public/common/content_client.h"
39 #include "content/public/common/content_constants.h"
40 #include "content/public/common/content_paths.h"
41 #include "content/public/common/content_switches.h"
42 #include "content/public/common/main_function_params.h"
43 #include "content/public/common/sandbox_init.h"
44 #include "content/renderer/in_process_renderer_thread.h"
45 #include "content/utility/in_process_utility_thread.h"
46 #include "crypto/nss_util.h"
47 #include "ipc/ipc_switches.h"
48 #include "media/base/media.h"
49 #include "sandbox/win/src/sandbox_types.h"
50 #include "ui/base/ui_base_paths.h"
51 #include "ui/base/ui_base_switches.h"
52 #include "ui/gfx/win/dpi.h"
53 #include "webkit/common/user_agent/user_agent.h"
55 #if defined(USE_TCMALLOC)
56 #include "third_party/tcmalloc/chromium/src/gperftools/malloc_extension.h"
57 #if defined(TYPE_PROFILING)
58 #include "base/allocator/type_profiler.h"
59 #include "base/allocator/type_profiler_tcmalloc.h"
64 #include "content/public/plugin/content_plugin_client.h"
65 #include "content/public/renderer/content_renderer_client.h"
66 #include "content/public/utility/content_utility_client.h"
74 #elif defined(OS_MACOSX)
75 #include "base/mac/scoped_nsautorelease_pool.h"
77 #include "base/power_monitor/power_monitor_device_source.h"
78 #include "content/browser/mach_broker_mac.h"
79 #include "content/common/sandbox_init_mac.h"
86 #include "base/posix/global_descriptors.h"
87 #include "content/public/common/content_descriptors.h"
89 #if !defined(OS_MACOSX)
90 #include "content/public/common/zygote_fork_delegate_linux.h"
92 #if !defined(OS_MACOSX) && !defined(OS_ANDROID)
93 #include "content/zygote/zygote_main.h"
98 #if !defined(OS_MACOSX) && defined(USE_TCMALLOC)
100 int tc_set_new_mode(int mode);
105 extern int GpuMain(const content::MainFunctionParams&);
106 #if defined(ENABLE_PLUGINS)
107 extern int PluginMain(const content::MainFunctionParams&);
108 extern int PpapiPluginMain(const MainFunctionParams&);
109 extern int PpapiBrokerMain(const MainFunctionParams&);
111 extern int RendererMain(const content::MainFunctionParams&);
112 extern int UtilityMain(const MainFunctionParams&);
113 extern int WorkerMain(const MainFunctionParams&);
114 } // namespace content
118 // In order to have Theme support, we need to connect to the theme service.
119 // This needs to be done before we lock down the process. Officially this
120 // can be done with OpenThemeData() but it fails unless you pass a valid
121 // window at least the first time. Interestingly, the very act of creating a
122 // window also sets the connection to the theme service.
123 void EnableThemeSupportOnAllWindowStations() {
124 HDESK desktop_handle = ::OpenInputDesktop(0, FALSE, READ_CONTROL);
125 if (desktop_handle) {
126 // This means we are running in an input desktop, which implies WinSta0.
127 ::CloseDesktop(desktop_handle);
131 HWINSTA current_station = ::GetProcessWindowStation();
132 DCHECK(current_station);
134 HWINSTA winsta0 = ::OpenWindowStationA("WinSta0", FALSE, GENERIC_READ);
136 DVLOG(0) << "Unable to open to WinSta0, we: "<< ::GetLastError();
139 if (!::SetProcessWindowStation(winsta0)) {
140 // Could not set the alternate window station. There is a possibility
141 // that the theme wont be correctly initialized.
142 NOTREACHED() << "Unable to switch to WinSta0, we: "<< ::GetLastError();
145 HWND window = ::CreateWindowExW(0, L"Static", L"", WS_POPUP | WS_DISABLED,
146 CW_USEDEFAULT, 0, 0, 0, HWND_MESSAGE, NULL,
147 ::GetModuleHandleA(NULL), NULL);
149 DLOG(WARNING) << "failed to enable theme support";
151 ::DestroyWindow(window);
155 // Revert the window station.
156 if (!::SetProcessWindowStation(current_station)) {
157 // We failed to switch back to the secure window station. This might
158 // confuse the process enough that we should kill it now.
159 LOG(FATAL) << "Failed to restore alternate window station";
162 if (!::CloseWindowStation(winsta0)) {
163 // We might be leaking a winsta0 handle. This is a security risk, but
164 // since we allow fail over to no desktop protection in low memory
165 // condition, this is not a big risk.
169 #endif // defined(OS_WIN)
174 base::LazyInstance<ContentBrowserClient>
175 g_empty_content_browser_client = LAZY_INSTANCE_INITIALIZER;
176 #if !defined(OS_IOS) && !defined(CHROME_MULTIPLE_DLL_BROWSER)
177 base::LazyInstance<ContentPluginClient>
178 g_empty_content_plugin_client = LAZY_INSTANCE_INITIALIZER;
179 base::LazyInstance<ContentRendererClient>
180 g_empty_content_renderer_client = LAZY_INSTANCE_INITIALIZER;
181 base::LazyInstance<ContentUtilityClient>
182 g_empty_content_utility_client = LAZY_INSTANCE_INITIALIZER;
183 #endif // !OS_IOS && !CHROME_MULTIPLE_DLL_BROWSER
187 static CAppModule _Module;
189 #endif // defined(OS_WIN)
191 #if defined(OS_POSIX) && !defined(OS_IOS)
193 // Setup signal-handling state: resanitize most signals, ignore SIGPIPE.
194 void SetupSignalHandlers() {
195 // Sanitise our signal handling state. Signals that were ignored by our
196 // parent will also be ignored by us. We also inherit our parent's sigmask.
197 sigset_t empty_signal_set;
198 CHECK(0 == sigemptyset(&empty_signal_set));
199 CHECK(0 == sigprocmask(SIG_SETMASK, &empty_signal_set, NULL));
201 struct sigaction sigact;
202 memset(&sigact, 0, sizeof(sigact));
203 sigact.sa_handler = SIG_DFL;
204 static const int signals_to_reset[] =
205 {SIGHUP, SIGINT, SIGQUIT, SIGILL, SIGABRT, SIGFPE, SIGSEGV,
206 SIGALRM, SIGTERM, SIGCHLD, SIGBUS, SIGTRAP}; // SIGPIPE is set below.
207 for (unsigned i = 0; i < arraysize(signals_to_reset); i++) {
208 CHECK(0 == sigaction(signals_to_reset[i], &sigact, NULL));
211 // Always ignore SIGPIPE. We check the return value of write().
212 CHECK(signal(SIGPIPE, SIG_IGN) != SIG_ERR);
215 #endif // OS_POSIX && !OS_IOS
217 void CommonSubprocessInit(const std::string& process_type) {
219 // HACK: Let Windows know that we have started. This is needed to suppress
220 // the IDC_APPSTARTING cursor from being displayed for a prolonged period
221 // while a subprocess is starting.
222 PostThreadMessage(GetCurrentThreadId(), WM_NULL, 0, 0);
224 PeekMessage(&msg, NULL, 0, 0, PM_REMOVE);
226 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
227 // Various things break when you're using a locale where the decimal
228 // separator isn't a period. See e.g. bugs 22782 and 39964. For
229 // all processes except the browser process (where we call system
230 // APIs that may rely on the correct locale for formatting numbers
231 // when presenting them to the user), reset the locale for numeric
233 // Note that this is not correct for plugin processes -- they can
234 // surface UI -- but it's likely they get this wrong too so why not.
235 setlocale(LC_NUMERIC, "C");
239 static base::ProcessId GetBrowserPid(const CommandLine& command_line) {
240 base::ProcessId browser_pid = base::GetCurrentProcId();
242 if (command_line.HasSwitch(switches::kProcessChannelID)) {
243 #if defined(OS_WIN) || defined(OS_MACOSX)
244 std::string channel_name =
245 command_line.GetSwitchValueASCII(switches::kProcessChannelID);
248 base::StringToInt(channel_name, &browser_pid_int);
249 browser_pid = static_cast<base::ProcessId>(browser_pid_int);
250 DCHECK_NE(browser_pid_int, 0);
251 #elif defined(OS_ANDROID)
252 // On Android, the browser process isn't the parent. A bunch
253 // of work will be required before callers of this routine will
254 // get what they want.
256 // Note: On Linux, base::GetParentProcessId() is defined in
257 // process_util_linux.cc. Note that *_linux.cc is excluded from
258 // Android builds but a special exception is made in base.gypi
259 // for a few files including process_util_linux.cc.
260 LOG(ERROR) << "GetBrowserPid() not implemented for Android().";
261 #elif defined(OS_POSIX)
262 // On linux, we're in a process forked from the zygote here; so we need the
263 // parent's parent process' id.
265 base::GetParentProcessId(
266 base::GetParentProcessId(base::GetCurrentProcId()));
273 static void InitializeStatsTable(const CommandLine& command_line) {
274 // Initialize the Stats Counters table. With this initialized,
275 // the StatsViewer can be utilized to read counters outside of
276 // Chrome. These lines can be commented out to effectively turn
277 // counters 'off'. The table is created and exists for the life
278 // of the process. It is not cleaned up.
279 if (command_line.HasSwitch(switches::kEnableStatsTable)) {
280 // NOTIMPLEMENTED: we probably need to shut this down correctly to avoid
281 // leaking shared memory regions on posix platforms.
282 std::string statsfile =
283 base::StringPrintf("%s-%u", kStatsFilename,
284 static_cast<unsigned int>(GetBrowserPid(command_line)));
285 base::StatsTable* stats_table = new base::StatsTable(statsfile,
286 kStatsMaxThreads, kStatsMaxCounters);
287 base::StatsTable::set_current(stats_table);
291 class ContentClientInitializer {
293 static void Set(const std::string& process_type,
294 ContentMainDelegate* delegate) {
295 ContentClient* content_client = GetContentClient();
296 if (process_type.empty()) {
298 content_client->browser_ = delegate->CreateContentBrowserClient();
299 if (!content_client->browser_)
300 content_client->browser_ = &g_empty_content_browser_client.Get();
303 #if !defined(OS_IOS) && !defined(CHROME_MULTIPLE_DLL_BROWSER)
304 if (process_type == switches::kPluginProcess ||
305 process_type == switches::kPpapiPluginProcess) {
307 content_client->plugin_ = delegate->CreateContentPluginClient();
308 if (!content_client->plugin_)
309 content_client->plugin_ = &g_empty_content_plugin_client.Get();
310 // Single process not supported in split dll mode.
311 } else if (process_type == switches::kRendererProcess ||
312 CommandLine::ForCurrentProcess()->HasSwitch(
313 switches::kSingleProcess)) {
315 content_client->renderer_ = delegate->CreateContentRendererClient();
316 if (!content_client->renderer_)
317 content_client->renderer_ = &g_empty_content_renderer_client.Get();
320 if (process_type == switches::kUtilityProcess ||
321 CommandLine::ForCurrentProcess()->HasSwitch(
322 switches::kSingleProcess)) {
324 content_client->utility_ = delegate->CreateContentUtilityClient();
325 // TODO(scottmg): http://crbug.com/237249 Should be in _child.
326 if (!content_client->utility_)
327 content_client->utility_ = &g_empty_content_utility_client.Get();
329 #endif // !OS_IOS && !CHROME_MULTIPLE_DLL_BROWSER
333 // We dispatch to a process-type-specific FooMain() based on a command-line
334 // flag. This struct is used to build a table of (flag, main function) pairs.
335 struct MainFunction {
337 int (*function)(const MainFunctionParams&);
340 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
341 // On platforms that use the zygote, we have a special subset of
342 // subprocesses that are launched via the zygote. This function
343 // fills in some process-launching bits around ZygoteMain().
344 // Returns the exit code of the subprocess.
345 int RunZygote(const MainFunctionParams& main_function_params,
346 ContentMainDelegate* delegate) {
347 static const MainFunction kMainFunctions[] = {
348 { switches::kRendererProcess, RendererMain },
349 { switches::kWorkerProcess, WorkerMain },
350 #if defined(ENABLE_PLUGINS)
351 { switches::kPpapiPluginProcess, PpapiPluginMain },
353 { switches::kUtilityProcess, UtilityMain },
356 scoped_ptr<ZygoteForkDelegate> zygote_fork_delegate;
358 zygote_fork_delegate.reset(delegate->ZygoteStarting());
359 // Each Renderer we spawn will re-attempt initialization of the media
360 // libraries, at which point failure will be detected and handled, so
361 // we do not need to cope with initialization failures here.
362 base::FilePath media_path;
363 if (PathService::Get(DIR_MEDIA_LIBS, &media_path))
364 media::InitializeMediaLibrary(media_path);
367 // This function call can return multiple times, once per fork().
368 if (!ZygoteMain(main_function_params, zygote_fork_delegate.get()))
371 if (delegate) delegate->ZygoteForked();
373 // Zygote::HandleForkRequest may have reallocated the command
374 // line so update it here with the new version.
375 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
376 std::string process_type =
377 command_line.GetSwitchValueASCII(switches::kProcessType);
378 ContentClientInitializer::Set(process_type, delegate);
380 // If a custom user agent was passed on the command line, we need
381 // to (re)set it now, rather than using the default one the zygote
383 if (command_line.HasSwitch(switches::kUserAgent)) {
384 webkit_glue::SetUserAgent(
385 command_line.GetSwitchValueASCII(switches::kUserAgent), true);
388 // The StatsTable must be initialized in each process; we already
389 // initialized for the browser process, now we need to initialize
390 // within the new processes as well.
391 InitializeStatsTable(command_line);
393 MainFunctionParams main_params(command_line);
395 for (size_t i = 0; i < arraysize(kMainFunctions); ++i) {
396 if (process_type == kMainFunctions[i].name)
397 return kMainFunctions[i].function(main_params);
401 return delegate->RunProcess(process_type, main_params);
403 NOTREACHED() << "Unknown zygote process type: " << process_type;
406 #endif // defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
409 static void RegisterMainThreadFactories() {
410 #if !defined(CHROME_MULTIPLE_DLL_BROWSER)
411 UtilityProcessHost::RegisterUtilityMainThreadFactory(
412 CreateInProcessUtilityThread);
413 RenderProcessHost::RegisterRendererMainThreadFactory(
414 CreateInProcessRendererThread);
415 GpuProcessHost::RegisterGpuMainThreadFactory(
416 CreateInProcessGpuThread);
418 CommandLine& command_line = *CommandLine::ForCurrentProcess();
419 if (command_line.HasSwitch(switches::kSingleProcess)) {
421 "--single-process is not supported in chrome multiple dll browser.";
423 if (command_line.HasSwitch(switches::kInProcessGPU)) {
425 "--in-process-gpu is not supported in chrome multiple dll browser.";
430 // Run the FooMain() for a given process type.
431 // If |process_type| is empty, runs BrowserMain().
432 // Returns the exit code for this process.
433 int RunNamedProcessTypeMain(
434 const std::string& process_type,
435 const MainFunctionParams& main_function_params,
436 ContentMainDelegate* delegate) {
437 static const MainFunction kMainFunctions[] = {
438 #if !defined(CHROME_MULTIPLE_DLL_CHILD)
441 #if !defined(CHROME_MULTIPLE_DLL_BROWSER)
442 #if defined(ENABLE_PLUGINS)
443 { switches::kPluginProcess, PluginMain },
444 { switches::kWorkerProcess, WorkerMain },
445 { switches::kPpapiPluginProcess, PpapiPluginMain },
446 { switches::kPpapiBrokerProcess, PpapiBrokerMain },
447 #endif // ENABLE_PLUGINS
448 { switches::kUtilityProcess, UtilityMain },
449 { switches::kRendererProcess, RendererMain },
450 { switches::kGpuProcess, GpuMain },
451 #endif // !CHROME_MULTIPLE_DLL_BROWSER
454 RegisterMainThreadFactories();
456 for (size_t i = 0; i < arraysize(kMainFunctions); ++i) {
457 if (process_type == kMainFunctions[i].name) {
459 int exit_code = delegate->RunProcess(process_type,
460 main_function_params);
461 #if defined(OS_ANDROID)
462 // In Android's browser process, the negative exit code doesn't mean the
463 // default behavior should be used as the UI message loop is managed by
464 // the Java and the browser process's default behavior is always
466 if (process_type.empty())
472 return kMainFunctions[i].function(main_function_params);
476 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
477 // Zygote startup is special -- see RunZygote comments above
478 // for why we don't use ZygoteMain directly.
479 if (process_type == switches::kZygoteProcess)
480 return RunZygote(main_function_params, delegate);
483 // If it's a process we don't know about, the embedder should know.
485 return delegate->RunProcess(process_type, main_function_params);
487 NOTREACHED() << "Unknown process type: " << process_type;
492 class ContentMainRunnerImpl : public ContentMainRunner {
494 ContentMainRunnerImpl()
495 : is_initialized_(false),
497 completed_basic_startup_(false),
500 memset(&sandbox_info_, 0, sizeof(sandbox_info_));
504 virtual ~ContentMainRunnerImpl() {
505 if (is_initialized_ && !is_shutdown_)
509 #if defined(USE_TCMALLOC)
510 static bool GetAllocatorWasteSizeThunk(size_t* size) {
511 size_t heap_size, allocated_bytes, unmapped_bytes;
512 MallocExtension* ext = MallocExtension::instance();
513 if (ext->GetNumericProperty("generic.heap_size", &heap_size) &&
514 ext->GetNumericProperty("generic.current_allocated_bytes",
516 ext->GetNumericProperty("tcmalloc.pageheap_unmapped_bytes",
518 *size = heap_size - allocated_bytes - unmapped_bytes;
525 static void GetStatsThunk(char* buffer, int buffer_length) {
526 MallocExtension::instance()->GetStats(buffer, buffer_length);
529 static void ReleaseFreeMemoryThunk() {
530 MallocExtension::instance()->ReleaseFreeMemory();
535 virtual int Initialize(HINSTANCE instance,
536 sandbox::SandboxInterfaceInfo* sandbox_info,
537 ContentMainDelegate* delegate) OVERRIDE {
538 // argc/argv are ignored on Windows; see command_line.h for details.
542 RegisterInvalidParamHandler();
543 _Module.Init(NULL, static_cast<HINSTANCE>(instance));
545 sandbox_info_ = *sandbox_info;
547 virtual int Initialize(int argc,
549 ContentMainDelegate* delegate) OVERRIDE {
551 #if defined(OS_ANDROID)
552 // See note at the initialization of ExitManager, below; basically,
553 // only Android builds have the ctor/dtor handlers set up to use
554 // TRACE_EVENT right away.
555 TRACE_EVENT0("startup", "ContentMainRunnerImpl::Initialize");
558 // NOTE(willchan): One might ask why these TCMalloc-related calls are done
559 // here rather than in process_util_linux.cc with the definition of
560 // EnableTerminationOnOutOfMemory(). That's because base shouldn't have a
561 // dependency on TCMalloc. Really, we ought to have our allocator shim code
562 // implement this EnableTerminationOnOutOfMemory() function. Whateverz.
563 // This works for now.
564 #if !defined(OS_MACOSX) && defined(USE_TCMALLOC)
566 #if defined(TYPE_PROFILING)
567 base::type_profiler::InterceptFunctions::SetFunctions(
568 base::type_profiler::NewInterceptForTCMalloc,
569 base::type_profiler::DeleteInterceptForTCMalloc);
572 // For tcmalloc, we need to tell it to behave like new.
575 // On windows, we've already set these thunks up in _heap_init()
576 base::allocator::SetGetAllocatorWasteSizeFunction(
577 GetAllocatorWasteSizeThunk);
578 base::allocator::SetGetStatsFunction(GetStatsThunk);
579 base::allocator::SetReleaseFreeMemoryFunction(ReleaseFreeMemoryThunk);
581 // Provide optional hook for monitoring allocation quantities on a
582 // per-thread basis. Only set the hook if the environment indicates this
583 // needs to be enabled.
584 const char* profiling = getenv(tracked_objects::kAlternateProfilerTime);
586 (atoi(profiling) == tracked_objects::TIME_SOURCE_TYPE_TCMALLOC)) {
587 tracked_objects::SetAlternateTimeSource(
588 MallocExtension::GetBytesAllocatedOnCurrentThread,
589 tracked_objects::TIME_SOURCE_TYPE_TCMALLOC);
594 // - setlocale() is not supported.
595 // - We do not override the signal handlers so that we can get
596 // stack trace when crashing.
597 // - The ipc_fd is passed through the Java service.
598 // Thus, these are all disabled.
599 #if !defined(OS_ANDROID) && !defined(OS_IOS)
600 // Set C library locale to make sure CommandLine can parse argument values
601 // in correct encoding.
602 setlocale(LC_ALL, "");
604 SetupSignalHandlers();
606 base::GlobalDescriptors* g_fds = base::GlobalDescriptors::GetInstance();
607 g_fds->Set(kPrimaryIPCChannel,
608 kPrimaryIPCChannel + base::GlobalDescriptors::kBaseDescriptor);
609 #endif // !OS_ANDROID && !OS_IOS
611 #if defined(OS_LINUX) || defined(OS_OPENBSD)
612 g_fds->Set(kCrashDumpSignal,
613 kCrashDumpSignal + base::GlobalDescriptors::kBaseDescriptor);
618 is_initialized_ = true;
619 delegate_ = delegate;
621 base::EnableTerminationOnHeapCorruption();
622 base::EnableTerminationOnOutOfMemory();
624 // The exit manager is in charge of calling the dtors of singleton objects.
625 // On Android, AtExitManager is set up when library is loaded.
626 // On iOS, it's set up in main(), which can't call directly through to here.
627 // A consequence of this is that you can't use the ctor/dtor-based
628 // TRACE_EVENT methods on Linux or iOS builds till after we set this up.
629 #if !defined(OS_ANDROID) && !defined(OS_IOS)
630 exit_manager_.reset(new base::AtExitManager);
631 #endif // !OS_ANDROID && !OS_IOS
633 #if defined(OS_MACOSX)
634 // We need this pool for all the objects created before we get to the
635 // event loop, but we don't want to leave them hanging around until the
636 // app quits. Each "main" needs to flush this pool right before it goes into
637 // its main event loop to get rid of the cruft.
638 autorelease_pool_.reset(new base::mac::ScopedNSAutoreleasePool());
641 // On Android, the command line is initialized when library is loaded and
642 // we have already started our TRACE_EVENT0.
643 #if !defined(OS_ANDROID)
644 CommandLine::Init(argc, argv);
645 #endif // !OS_ANDROID
648 if (delegate && delegate->BasicStartupComplete(&exit_code))
651 completed_basic_startup_ = true;
653 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
654 std::string process_type =
655 command_line.GetSwitchValueASCII(switches::kProcessType);
657 if (!GetContentClient())
658 SetContentClient(&empty_content_client_);
659 ContentClientInitializer::Set(process_type, delegate_);
662 // Route stdio to parent console (if any) or create one.
663 if (command_line.HasSwitch(switches::kEnableLogging))
664 base::RouteStdioToConsole();
667 // Enable startup tracing asap to avoid early TRACE_EVENT calls being
669 if (command_line.HasSwitch(switches::kTraceStartup)) {
670 base::debug::CategoryFilter category_filter(
671 command_line.GetSwitchValueASCII(switches::kTraceStartup));
672 base::debug::TraceLog::GetInstance()->SetEnabled(
674 base::debug::TraceLog::RECORDING_MODE,
675 base::debug::TraceLog::RECORD_UNTIL_FULL);
677 #if !defined(OS_ANDROID)
678 // Android tracing started at the beginning of the method.
679 // Other OSes have to wait till we get here in order for all the memory
680 // management setup to be completed.
681 TRACE_EVENT0("startup", "ContentMainRunnerImpl::Initialize");
682 #endif // !OS_ANDROID
684 #if defined(OS_MACOSX) && !defined(OS_IOS)
685 // We need to allocate the IO Ports before the Sandbox is initialized or
686 // the first instance of PowerMonitor is created.
687 // It's important not to allocate the ports for processes which don't
688 // register with the power monitor - see crbug.com/88867.
689 if (process_type.empty() ||
691 delegate->ProcessRegistersWithSystemProcess(process_type))) {
692 base::PowerMonitorDeviceSource::AllocateSystemIOPorts();
695 if (!process_type.empty() &&
696 (!delegate || delegate->ShouldSendMachPort(process_type))) {
697 MachBroker::ChildSendTaskPortToParent();
699 #elif defined(OS_WIN)
700 if (command_line.HasSwitch(switches::kEnableHighResolutionTime))
701 base::TimeTicks::SetNowIsHighResNowIfSupported();
703 // This must be done early enough since some helper functions like
704 // IsTouchEnabled, needed to load resources, may call into the theme dll.
705 EnableThemeSupportOnAllWindowStations();
706 SetupCRT(command_line);
709 #if defined(OS_POSIX)
710 if (!process_type.empty()) {
711 // When you hit Ctrl-C in a terminal running the browser
712 // process, a SIGINT is delivered to the entire process group.
713 // When debugging the browser process via gdb, gdb catches the
714 // SIGINT for the browser process (and dumps you back to the gdb
715 // console) but doesn't for the child processes, killing them.
716 // The fix is to have child processes ignore SIGINT; they'll die
717 // on their own when the browser process goes away.
719 // Note that we *can't* rely on BeingDebugged to catch this case because
720 // we are the child process, which is not being debugged.
721 // TODO(evanm): move this to some shared subprocess-init function.
722 if (!base::debug::BeingDebugged())
723 signal(SIGINT, SIG_IGN);
728 crypto::EarlySetupForNSSInit();
731 ui::RegisterPathProvider();
732 RegisterPathProvider();
733 RegisterContentSchemes(true);
735 CHECK(base::i18n::InitializeICU());
737 InitializeStatsTable(command_line);
740 delegate->PreSandboxStartup();
742 // Set any custom user agent passed on the command line now so the string
743 // doesn't change between calls to webkit_glue::GetUserAgent(), otherwise it
744 // defaults to the user agent set during SetContentClient().
745 if (command_line.HasSwitch(switches::kUserAgent)) {
746 webkit_glue::SetUserAgent(
747 command_line.GetSwitchValueASCII(switches::kUserAgent), true);
750 if (!process_type.empty())
751 CommonSubprocessInit(process_type);
754 CHECK(InitializeSandbox(sandbox_info));
755 #elif defined(OS_MACOSX) && !defined(OS_IOS)
756 if (process_type == switches::kRendererProcess ||
757 process_type == switches::kPpapiPluginProcess ||
758 (delegate && delegate->DelaySandboxInitialization(process_type))) {
759 // On OS X the renderer sandbox needs to be initialized later in the
760 // startup sequence in RendererMainPlatformDelegate::EnableSandbox().
762 CHECK(InitializeSandbox());
767 delegate->SandboxInitialized(process_type);
769 #if defined(OS_TIZEN_MOBILE)
770 if (process_type.empty())
771 StoreArgvPointerAddress(argv);
773 SetProcessTitleFromCommandLine(argv);
774 #elif defined(OS_POSIX) && !defined(OS_IOS)
775 SetProcessTitleFromCommandLine(argv);
778 // Return -1 to indicate no early termination.
782 virtual int Run() OVERRIDE {
783 DCHECK(is_initialized_);
784 DCHECK(!is_shutdown_);
785 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
786 std::string process_type =
787 command_line.GetSwitchValueASCII(switches::kProcessType);
789 MainFunctionParams main_params(command_line);
791 main_params.sandbox_info = &sandbox_info_;
792 #elif defined(OS_MACOSX)
793 main_params.autorelease_pool = autorelease_pool_.get();
797 return RunNamedProcessTypeMain(process_type, main_params, delegate_);
803 virtual void Shutdown() OVERRIDE {
804 DCHECK(is_initialized_);
805 DCHECK(!is_shutdown_);
807 if (completed_basic_startup_ && delegate_) {
808 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
809 std::string process_type =
810 command_line.GetSwitchValueASCII(switches::kProcessType);
812 delegate_->ProcessExiting(process_type);
816 #ifdef _CRTDBG_MAP_ALLOC
817 _CrtDumpMemoryLeaks();
818 #endif // _CRTDBG_MAP_ALLOC
823 #if defined(OS_MACOSX)
824 autorelease_pool_.reset(NULL);
827 exit_manager_.reset(NULL);
834 // True if the runner has been initialized.
835 bool is_initialized_;
837 // True if the runner has been shut down.
840 // True if basic startup was completed.
841 bool completed_basic_startup_;
843 // Used if the embedder doesn't set one.
844 ContentClient empty_content_client_;
846 // The delegate will outlive this object.
847 ContentMainDelegate* delegate_;
849 scoped_ptr<base::AtExitManager> exit_manager_;
851 sandbox::SandboxInterfaceInfo sandbox_info_;
852 #elif defined(OS_MACOSX)
853 scoped_ptr<base::mac::ScopedNSAutoreleasePool> autorelease_pool_;
856 DISALLOW_COPY_AND_ASSIGN(ContentMainRunnerImpl);
860 ContentMainRunner* ContentMainRunner::Create() {
861 return new ContentMainRunnerImpl();
864 } // namespace content