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.h"
34 #include "content/public/app/content_main_delegate.h"
35 #include "content/public/app/startup_helper_win.h"
36 #include "content/public/browser/content_browser_client.h"
37 #include "content/public/browser/render_process_host.h"
38 #include "content/public/browser/utility_process_host.h"
39 #include "content/public/common/content_client.h"
40 #include "content/public/common/content_constants.h"
41 #include "content/public/common/content_paths.h"
42 #include "content/public/common/content_switches.h"
43 #include "content/public/common/main_function_params.h"
44 #include "content/public/common/sandbox_init.h"
45 #include "content/renderer/in_process_renderer_thread.h"
46 #include "content/utility/in_process_utility_thread.h"
47 #include "crypto/nss_util.h"
48 #include "ipc/ipc_switches.h"
49 #include "media/base/media.h"
50 #include "sandbox/win/src/sandbox_types.h"
51 #include "ui/base/ui_base_paths.h"
52 #include "ui/base/ui_base_switches.h"
53 #include "ui/gfx/win/dpi.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);
104 #if defined(USE_MOJO)
105 #include "content/app/mojo/mojo_init.h"
109 extern int GpuMain(const content::MainFunctionParams&);
110 #if defined(ENABLE_PLUGINS)
111 extern int PluginMain(const content::MainFunctionParams&);
112 extern int PpapiPluginMain(const MainFunctionParams&);
113 extern int PpapiBrokerMain(const MainFunctionParams&);
115 extern int RendererMain(const content::MainFunctionParams&);
116 extern int UtilityMain(const MainFunctionParams&);
117 extern int WorkerMain(const MainFunctionParams&);
118 } // namespace content
122 // In order to have Theme support, we need to connect to the theme service.
123 // This needs to be done before we lock down the process. Officially this
124 // can be done with OpenThemeData() but it fails unless you pass a valid
125 // window at least the first time. Interestingly, the very act of creating a
126 // window also sets the connection to the theme service.
127 void EnableThemeSupportOnAllWindowStations() {
128 HDESK desktop_handle = ::OpenInputDesktop(0, FALSE, READ_CONTROL);
129 if (desktop_handle) {
130 // This means we are running in an input desktop, which implies WinSta0.
131 ::CloseDesktop(desktop_handle);
135 HWINSTA current_station = ::GetProcessWindowStation();
136 DCHECK(current_station);
138 HWINSTA winsta0 = ::OpenWindowStationA("WinSta0", FALSE, GENERIC_READ);
140 DVLOG(0) << "Unable to open to WinSta0, we: "<< ::GetLastError();
143 if (!::SetProcessWindowStation(winsta0)) {
144 // Could not set the alternate window station. There is a possibility
145 // that the theme wont be correctly initialized.
146 NOTREACHED() << "Unable to switch to WinSta0, we: "<< ::GetLastError();
147 ::CloseWindowStation(winsta0);
151 HWND window = ::CreateWindowExW(0, L"Static", L"", WS_POPUP | WS_DISABLED,
152 CW_USEDEFAULT, 0, 0, 0, HWND_MESSAGE, NULL,
153 ::GetModuleHandleA(NULL), NULL);
155 DLOG(WARNING) << "failed to enable theme support";
157 ::DestroyWindow(window);
161 // Revert the window station.
162 if (!::SetProcessWindowStation(current_station)) {
163 // We failed to switch back to the secure window station. This might
164 // confuse the process enough that we should kill it now.
165 LOG(FATAL) << "Failed to restore alternate window station";
168 if (!::CloseWindowStation(winsta0)) {
169 // We might be leaking a winsta0 handle. This is a security risk, but
170 // since we allow fail over to no desktop protection in low memory
171 // condition, this is not a big risk.
175 #endif // defined(OS_WIN)
180 base::LazyInstance<ContentBrowserClient>
181 g_empty_content_browser_client = LAZY_INSTANCE_INITIALIZER;
182 #if !defined(OS_IOS) && !defined(CHROME_MULTIPLE_DLL_BROWSER)
183 base::LazyInstance<ContentPluginClient>
184 g_empty_content_plugin_client = LAZY_INSTANCE_INITIALIZER;
185 base::LazyInstance<ContentRendererClient>
186 g_empty_content_renderer_client = LAZY_INSTANCE_INITIALIZER;
187 base::LazyInstance<ContentUtilityClient>
188 g_empty_content_utility_client = LAZY_INSTANCE_INITIALIZER;
189 #endif // !OS_IOS && !CHROME_MULTIPLE_DLL_BROWSER
193 static CAppModule _Module;
195 #endif // defined(OS_WIN)
197 #if defined(OS_POSIX) && !defined(OS_IOS)
199 // Setup signal-handling state: resanitize most signals, ignore SIGPIPE.
200 void SetupSignalHandlers() {
201 // Sanitise our signal handling state. Signals that were ignored by our
202 // parent will also be ignored by us. We also inherit our parent's sigmask.
203 sigset_t empty_signal_set;
204 CHECK(0 == sigemptyset(&empty_signal_set));
205 CHECK(0 == sigprocmask(SIG_SETMASK, &empty_signal_set, NULL));
207 struct sigaction sigact;
208 memset(&sigact, 0, sizeof(sigact));
209 sigact.sa_handler = SIG_DFL;
210 static const int signals_to_reset[] =
211 {SIGHUP, SIGINT, SIGQUIT, SIGILL, SIGABRT, SIGFPE, SIGSEGV,
212 SIGALRM, SIGTERM, SIGCHLD, SIGBUS, SIGTRAP}; // SIGPIPE is set below.
213 for (unsigned i = 0; i < arraysize(signals_to_reset); i++) {
214 CHECK(0 == sigaction(signals_to_reset[i], &sigact, NULL));
217 // Always ignore SIGPIPE. We check the return value of write().
218 CHECK(signal(SIGPIPE, SIG_IGN) != SIG_ERR);
221 #endif // OS_POSIX && !OS_IOS
223 void CommonSubprocessInit(const std::string& process_type) {
225 // HACK: Let Windows know that we have started. This is needed to suppress
226 // the IDC_APPSTARTING cursor from being displayed for a prolonged period
227 // while a subprocess is starting.
228 PostThreadMessage(GetCurrentThreadId(), WM_NULL, 0, 0);
230 PeekMessage(&msg, NULL, 0, 0, PM_REMOVE);
232 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
233 // Various things break when you're using a locale where the decimal
234 // separator isn't a period. See e.g. bugs 22782 and 39964. For
235 // all processes except the browser process (where we call system
236 // APIs that may rely on the correct locale for formatting numbers
237 // when presenting them to the user), reset the locale for numeric
239 // Note that this is not correct for plugin processes -- they can
240 // surface UI -- but it's likely they get this wrong too so why not.
241 setlocale(LC_NUMERIC, "C");
245 static base::ProcessId GetBrowserPid(const CommandLine& command_line) {
246 base::ProcessId browser_pid = base::GetCurrentProcId();
248 if (command_line.HasSwitch(switches::kProcessChannelID)) {
249 #if defined(OS_WIN) || defined(OS_MACOSX)
250 std::string channel_name =
251 command_line.GetSwitchValueASCII(switches::kProcessChannelID);
254 base::StringToInt(channel_name, &browser_pid_int);
255 browser_pid = static_cast<base::ProcessId>(browser_pid_int);
256 DCHECK_NE(browser_pid_int, 0);
257 #elif defined(OS_ANDROID)
258 // On Android, the browser process isn't the parent. A bunch
259 // of work will be required before callers of this routine will
260 // get what they want.
262 // Note: On Linux, base::GetParentProcessId() is defined in
263 // process_util_linux.cc. Note that *_linux.cc is excluded from
264 // Android builds but a special exception is made in base.gypi
265 // for a few files including process_util_linux.cc.
266 LOG(ERROR) << "GetBrowserPid() not implemented for Android().";
267 #elif defined(OS_POSIX)
268 // On linux, we're in a process forked from the zygote here; so we need the
269 // parent's parent process' id.
271 base::GetParentProcessId(
272 base::GetParentProcessId(base::GetCurrentProcId()));
279 static void InitializeStatsTable(const CommandLine& command_line) {
280 // Initialize the Stats Counters table. With this initialized,
281 // the StatsViewer can be utilized to read counters outside of
282 // Chrome. These lines can be commented out to effectively turn
283 // counters 'off'. The table is created and exists for the life
284 // of the process. It is not cleaned up.
285 if (command_line.HasSwitch(switches::kEnableStatsTable)) {
286 // NOTIMPLEMENTED: we probably need to shut this down correctly to avoid
287 // leaking shared memory regions on posix platforms.
288 std::string statsfile =
289 base::StringPrintf("%s-%u", kStatsFilename,
290 static_cast<unsigned int>(GetBrowserPid(command_line)));
291 base::StatsTable* stats_table = new base::StatsTable(statsfile,
292 kStatsMaxThreads, kStatsMaxCounters);
293 base::StatsTable::set_current(stats_table);
297 class ContentClientInitializer {
299 static void Set(const std::string& process_type,
300 ContentMainDelegate* delegate) {
301 ContentClient* content_client = GetContentClient();
302 if (process_type.empty()) {
304 content_client->browser_ = delegate->CreateContentBrowserClient();
305 if (!content_client->browser_)
306 content_client->browser_ = &g_empty_content_browser_client.Get();
309 #if !defined(OS_IOS) && !defined(CHROME_MULTIPLE_DLL_BROWSER)
310 if (process_type == switches::kPluginProcess ||
311 process_type == switches::kPpapiPluginProcess) {
313 content_client->plugin_ = delegate->CreateContentPluginClient();
314 if (!content_client->plugin_)
315 content_client->plugin_ = &g_empty_content_plugin_client.Get();
316 // Single process not supported in split dll mode.
317 } else if (process_type == switches::kRendererProcess ||
318 CommandLine::ForCurrentProcess()->HasSwitch(
319 switches::kSingleProcess)) {
321 content_client->renderer_ = delegate->CreateContentRendererClient();
322 if (!content_client->renderer_)
323 content_client->renderer_ = &g_empty_content_renderer_client.Get();
326 if (process_type == switches::kUtilityProcess ||
327 CommandLine::ForCurrentProcess()->HasSwitch(
328 switches::kSingleProcess)) {
330 content_client->utility_ = delegate->CreateContentUtilityClient();
331 // TODO(scottmg): http://crbug.com/237249 Should be in _child.
332 if (!content_client->utility_)
333 content_client->utility_ = &g_empty_content_utility_client.Get();
335 #endif // !OS_IOS && !CHROME_MULTIPLE_DLL_BROWSER
339 // We dispatch to a process-type-specific FooMain() based on a command-line
340 // flag. This struct is used to build a table of (flag, main function) pairs.
341 struct MainFunction {
343 int (*function)(const MainFunctionParams&);
346 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
347 // On platforms that use the zygote, we have a special subset of
348 // subprocesses that are launched via the zygote. This function
349 // fills in some process-launching bits around ZygoteMain().
350 // Returns the exit code of the subprocess.
351 int RunZygote(const MainFunctionParams& main_function_params,
352 ContentMainDelegate* delegate) {
353 static const MainFunction kMainFunctions[] = {
354 { switches::kRendererProcess, RendererMain },
355 { switches::kWorkerProcess, WorkerMain },
356 #if defined(ENABLE_PLUGINS)
357 { switches::kPpapiPluginProcess, PpapiPluginMain },
359 { switches::kUtilityProcess, UtilityMain },
362 scoped_ptr<ZygoteForkDelegate> zygote_fork_delegate;
364 zygote_fork_delegate.reset(delegate->ZygoteStarting());
365 // Each Renderer we spawn will re-attempt initialization of the media
366 // libraries, at which point failure will be detected and handled, so
367 // we do not need to cope with initialization failures here.
368 base::FilePath media_path;
369 if (PathService::Get(DIR_MEDIA_LIBS, &media_path))
370 media::InitializeMediaLibrary(media_path);
373 // This function call can return multiple times, once per fork().
374 if (!ZygoteMain(main_function_params, zygote_fork_delegate.get()))
377 if (delegate) delegate->ZygoteForked();
379 // Zygote::HandleForkRequest may have reallocated the command
380 // line so update it here with the new version.
381 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
382 std::string process_type =
383 command_line.GetSwitchValueASCII(switches::kProcessType);
384 ContentClientInitializer::Set(process_type, delegate);
386 // The StatsTable must be initialized in each process; we already
387 // initialized for the browser process, now we need to initialize
388 // within the new processes as well.
389 InitializeStatsTable(command_line);
391 MainFunctionParams main_params(command_line);
393 for (size_t i = 0; i < arraysize(kMainFunctions); ++i) {
394 if (process_type == kMainFunctions[i].name)
395 return kMainFunctions[i].function(main_params);
399 return delegate->RunProcess(process_type, main_params);
401 NOTREACHED() << "Unknown zygote process type: " << process_type;
404 #endif // defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
407 static void RegisterMainThreadFactories() {
408 #if !defined(CHROME_MULTIPLE_DLL_BROWSER)
409 UtilityProcessHost::RegisterUtilityMainThreadFactory(
410 CreateInProcessUtilityThread);
411 RenderProcessHost::RegisterRendererMainThreadFactory(
412 CreateInProcessRendererThread);
413 GpuProcessHost::RegisterGpuMainThreadFactory(
414 CreateInProcessGpuThread);
416 CommandLine& command_line = *CommandLine::ForCurrentProcess();
417 if (command_line.HasSwitch(switches::kSingleProcess)) {
419 "--single-process is not supported in chrome multiple dll browser.";
421 if (command_line.HasSwitch(switches::kInProcessGPU)) {
423 "--in-process-gpu is not supported in chrome multiple dll browser.";
428 // Run the FooMain() for a given process type.
429 // If |process_type| is empty, runs BrowserMain().
430 // Returns the exit code for this process.
431 int RunNamedProcessTypeMain(
432 const std::string& process_type,
433 const MainFunctionParams& main_function_params,
434 ContentMainDelegate* delegate) {
435 static const MainFunction kMainFunctions[] = {
436 #if !defined(CHROME_MULTIPLE_DLL_CHILD)
439 #if !defined(CHROME_MULTIPLE_DLL_BROWSER)
440 #if defined(ENABLE_PLUGINS)
441 { switches::kPluginProcess, PluginMain },
442 { switches::kWorkerProcess, WorkerMain },
443 { switches::kPpapiPluginProcess, PpapiPluginMain },
444 { switches::kPpapiBrokerProcess, PpapiBrokerMain },
445 #endif // ENABLE_PLUGINS
446 { switches::kUtilityProcess, UtilityMain },
447 { switches::kRendererProcess, RendererMain },
448 { switches::kGpuProcess, GpuMain },
449 #endif // !CHROME_MULTIPLE_DLL_BROWSER
452 RegisterMainThreadFactories();
454 for (size_t i = 0; i < arraysize(kMainFunctions); ++i) {
455 if (process_type == kMainFunctions[i].name) {
457 int exit_code = delegate->RunProcess(process_type,
458 main_function_params);
459 #if defined(OS_ANDROID)
460 // In Android's browser process, the negative exit code doesn't mean the
461 // default behavior should be used as the UI message loop is managed by
462 // the Java and the browser process's default behavior is always
464 if (process_type.empty())
470 return kMainFunctions[i].function(main_function_params);
474 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
475 // Zygote startup is special -- see RunZygote comments above
476 // for why we don't use ZygoteMain directly.
477 if (process_type == switches::kZygoteProcess)
478 return RunZygote(main_function_params, delegate);
481 // If it's a process we don't know about, the embedder should know.
483 return delegate->RunProcess(process_type, main_function_params);
485 NOTREACHED() << "Unknown process type: " << process_type;
490 class ContentMainRunnerImpl : public ContentMainRunner {
492 ContentMainRunnerImpl()
493 : is_initialized_(false),
495 completed_basic_startup_(false),
499 memset(&sandbox_info_, 0, sizeof(sandbox_info_));
503 virtual ~ContentMainRunnerImpl() {
504 if (is_initialized_ && !is_shutdown_)
508 #if defined(USE_TCMALLOC)
509 static bool GetAllocatorWasteSizeThunk(size_t* size) {
510 size_t heap_size, allocated_bytes, unmapped_bytes;
511 MallocExtension* ext = MallocExtension::instance();
512 if (ext->GetNumericProperty("generic.heap_size", &heap_size) &&
513 ext->GetNumericProperty("generic.current_allocated_bytes",
515 ext->GetNumericProperty("tcmalloc.pageheap_unmapped_bytes",
517 *size = heap_size - allocated_bytes - unmapped_bytes;
524 static void GetStatsThunk(char* buffer, int buffer_length) {
525 MallocExtension::instance()->GetStats(buffer, buffer_length);
528 static void ReleaseFreeMemoryThunk() {
529 MallocExtension::instance()->ReleaseFreeMemory();
533 virtual int Initialize(const ContentMainParams& params) OVERRIDE {
534 ui_task_ = params.ui_task;
537 RegisterInvalidParamHandler();
538 _Module.Init(NULL, static_cast<HINSTANCE>(params.instance));
540 sandbox_info_ = *params.sandbox_info;
543 #if defined(OS_ANDROID)
544 // See note at the initialization of ExitManager, below; basically,
545 // only Android builds have the ctor/dtor handlers set up to use
546 // TRACE_EVENT right away.
547 TRACE_EVENT0("startup", "ContentMainRunnerImpl::Initialize");
550 // NOTE(willchan): One might ask why these TCMalloc-related calls are done
551 // here rather than in process_util_linux.cc with the definition of
552 // EnableTerminationOnOutOfMemory(). That's because base shouldn't have a
553 // dependency on TCMalloc. Really, we ought to have our allocator shim code
554 // implement this EnableTerminationOnOutOfMemory() function. Whateverz.
555 // This works for now.
556 #if !defined(OS_MACOSX) && defined(USE_TCMALLOC)
558 #if defined(TYPE_PROFILING)
559 base::type_profiler::InterceptFunctions::SetFunctions(
560 base::type_profiler::NewInterceptForTCMalloc,
561 base::type_profiler::DeleteInterceptForTCMalloc);
564 // For tcmalloc, we need to tell it to behave like new.
567 // On windows, we've already set these thunks up in _heap_init()
568 base::allocator::SetGetAllocatorWasteSizeFunction(
569 GetAllocatorWasteSizeThunk);
570 base::allocator::SetGetStatsFunction(GetStatsThunk);
571 base::allocator::SetReleaseFreeMemoryFunction(ReleaseFreeMemoryThunk);
573 // Provide optional hook for monitoring allocation quantities on a
574 // per-thread basis. Only set the hook if the environment indicates this
575 // needs to be enabled.
576 const char* profiling = getenv(tracked_objects::kAlternateProfilerTime);
578 (atoi(profiling) == tracked_objects::TIME_SOURCE_TYPE_TCMALLOC)) {
579 tracked_objects::SetAlternateTimeSource(
580 MallocExtension::GetBytesAllocatedOnCurrentThread,
581 tracked_objects::TIME_SOURCE_TYPE_TCMALLOC);
583 #endif // !OS_MACOSX && USE_TCMALLOC
586 // - setlocale() is not supported.
587 // - We do not override the signal handlers so that we can get
588 // stack trace when crashing.
589 // - The ipc_fd is passed through the Java service.
590 // Thus, these are all disabled.
591 #if !defined(OS_ANDROID) && !defined(OS_IOS)
592 // Set C library locale to make sure CommandLine can parse argument values
593 // in correct encoding.
594 setlocale(LC_ALL, "");
596 SetupSignalHandlers();
598 base::GlobalDescriptors* g_fds = base::GlobalDescriptors::GetInstance();
599 g_fds->Set(kPrimaryIPCChannel,
600 kPrimaryIPCChannel + base::GlobalDescriptors::kBaseDescriptor);
601 #endif // !OS_ANDROID && !OS_IOS
603 #if defined(OS_LINUX) || defined(OS_OPENBSD)
604 g_fds->Set(kCrashDumpSignal,
605 kCrashDumpSignal + base::GlobalDescriptors::kBaseDescriptor);
610 is_initialized_ = true;
611 delegate_ = params.delegate;
613 base::EnableTerminationOnHeapCorruption();
614 base::EnableTerminationOnOutOfMemory();
616 // The exit manager is in charge of calling the dtors of singleton objects.
617 // On Android, AtExitManager is set up when library is loaded.
618 // On iOS, it's set up in main(), which can't call directly through to here.
619 // A consequence of this is that you can't use the ctor/dtor-based
620 // TRACE_EVENT methods on Linux or iOS builds till after we set this up.
621 #if !defined(OS_ANDROID) && !defined(OS_IOS)
623 // When running browser tests, don't create a second AtExitManager as that
624 // interfers with shutdown when objects created before ContentMain is
625 // called are destructed when it returns.
626 exit_manager_.reset(new base::AtExitManager);
628 #endif // !OS_ANDROID && !OS_IOS
630 #if defined(OS_MACOSX)
631 // We need this pool for all the objects created before we get to the
632 // event loop, but we don't want to leave them hanging around until the
633 // app quits. Each "main" needs to flush this pool right before it goes into
634 // its main event loop to get rid of the cruft.
635 autorelease_pool_.reset(new base::mac::ScopedNSAutoreleasePool());
638 // On Android, the command line is initialized when library is loaded and
639 // we have already started our TRACE_EVENT0.
640 #if !defined(OS_ANDROID)
641 // argc/argv are ignored on Windows and Android; see command_line.h for
644 const char** argv = NULL;
651 CommandLine::Init(argc, argv);
654 SetProcessTitleFromCommandLine(argv);
656 #endif // !OS_ANDROID
659 if (delegate_ && delegate_->BasicStartupComplete(&exit_code))
662 completed_basic_startup_ = true;
664 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
665 std::string process_type =
666 command_line.GetSwitchValueASCII(switches::kProcessType);
668 #if defined(USE_MOJO)
669 // Initialize mojo here so that services can be registered.
673 if (!GetContentClient())
674 SetContentClient(&empty_content_client_);
675 ContentClientInitializer::Set(process_type, delegate_);
678 // Route stdio to parent console (if any) or create one.
679 if (command_line.HasSwitch(switches::kEnableLogging))
680 base::RouteStdioToConsole();
683 // Enable startup tracing asap to avoid early TRACE_EVENT calls being
685 if (command_line.HasSwitch(switches::kTraceStartup)) {
686 base::debug::CategoryFilter category_filter(
687 command_line.GetSwitchValueASCII(switches::kTraceStartup));
688 base::debug::TraceLog::GetInstance()->SetEnabled(
690 base::debug::TraceLog::RECORDING_MODE,
691 base::debug::TraceLog::RECORD_UNTIL_FULL);
693 #if !defined(OS_ANDROID)
694 // Android tracing started at the beginning of the method.
695 // Other OSes have to wait till we get here in order for all the memory
696 // management setup to be completed.
697 TRACE_EVENT0("startup", "ContentMainRunnerImpl::Initialize");
698 #endif // !OS_ANDROID
700 #if defined(OS_MACOSX) && !defined(OS_IOS)
701 // We need to allocate the IO Ports before the Sandbox is initialized or
702 // the first instance of PowerMonitor is created.
703 // It's important not to allocate the ports for processes which don't
704 // register with the power monitor - see crbug.com/88867.
705 if (process_type.empty() ||
707 delegate_->ProcessRegistersWithSystemProcess(process_type))) {
708 base::PowerMonitorDeviceSource::AllocateSystemIOPorts();
711 if (!process_type.empty() &&
712 (!delegate_ || delegate_->ShouldSendMachPort(process_type))) {
713 MachBroker::ChildSendTaskPortToParent();
715 #elif defined(OS_WIN)
716 if (command_line.HasSwitch(switches::kEnableHighResolutionTime))
717 base::TimeTicks::SetNowIsHighResNowIfSupported();
719 // This must be done early enough since some helper functions like
720 // IsTouchEnabled, needed to load resources, may call into the theme dll.
721 EnableThemeSupportOnAllWindowStations();
722 SetupCRT(command_line);
725 #if defined(OS_POSIX)
726 if (!process_type.empty()) {
727 // When you hit Ctrl-C in a terminal running the browser
728 // process, a SIGINT is delivered to the entire process group.
729 // When debugging the browser process via gdb, gdb catches the
730 // SIGINT for the browser process (and dumps you back to the gdb
731 // console) but doesn't for the child processes, killing them.
732 // The fix is to have child processes ignore SIGINT; they'll die
733 // on their own when the browser process goes away.
735 // Note that we *can't* rely on BeingDebugged to catch this case because
736 // we are the child process, which is not being debugged.
737 // TODO(evanm): move this to some shared subprocess-init function.
738 if (!base::debug::BeingDebugged())
739 signal(SIGINT, SIG_IGN);
744 crypto::EarlySetupForNSSInit();
747 ui::RegisterPathProvider();
748 RegisterPathProvider();
749 RegisterContentSchemes(true);
751 CHECK(base::i18n::InitializeICU());
753 InitializeStatsTable(command_line);
756 delegate_->PreSandboxStartup();
758 if (!process_type.empty())
759 CommonSubprocessInit(process_type);
762 CHECK(InitializeSandbox(params.sandbox_info));
763 #elif defined(OS_MACOSX) && !defined(OS_IOS)
764 if (process_type == switches::kRendererProcess ||
765 process_type == switches::kPpapiPluginProcess ||
766 (delegate_ && delegate_->DelaySandboxInitialization(process_type))) {
767 // On OS X the renderer sandbox needs to be initialized later in the
768 // startup sequence in RendererMainPlatformDelegate::EnableSandbox().
770 CHECK(InitializeSandbox());
775 delegate_->SandboxInitialized(process_type);
777 #if defined(OS_TIZEN_MOBILE)
778 if (process_type.empty())
779 StoreArgvPointerAddress(argv);
781 SetProcessTitleFromCommandLine(argv);
782 #elif defined(OS_POSIX) && !defined(OS_IOS) && !defined(OS_ANDROID)
783 SetProcessTitleFromCommandLine(argv);
786 // Return -1 to indicate no early termination.
790 virtual int Run() OVERRIDE {
791 DCHECK(is_initialized_);
792 DCHECK(!is_shutdown_);
793 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
794 std::string process_type =
795 command_line.GetSwitchValueASCII(switches::kProcessType);
797 MainFunctionParams main_params(command_line);
798 main_params.ui_task = ui_task_;
800 main_params.sandbox_info = &sandbox_info_;
801 #elif defined(OS_MACOSX)
802 main_params.autorelease_pool = autorelease_pool_.get();
806 return RunNamedProcessTypeMain(process_type, main_params, delegate_);
812 virtual void Shutdown() OVERRIDE {
813 DCHECK(is_initialized_);
814 DCHECK(!is_shutdown_);
816 if (completed_basic_startup_ && delegate_) {
817 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
818 std::string process_type =
819 command_line.GetSwitchValueASCII(switches::kProcessType);
821 delegate_->ProcessExiting(process_type);
825 #ifdef _CRTDBG_MAP_ALLOC
826 _CrtDumpMemoryLeaks();
827 #endif // _CRTDBG_MAP_ALLOC
832 #if defined(OS_MACOSX)
833 autorelease_pool_.reset(NULL);
836 exit_manager_.reset(NULL);
843 // True if the runner has been initialized.
844 bool is_initialized_;
846 // True if the runner has been shut down.
849 // True if basic startup was completed.
850 bool completed_basic_startup_;
852 // Used if the embedder doesn't set one.
853 ContentClient empty_content_client_;
855 // The delegate will outlive this object.
856 ContentMainDelegate* delegate_;
858 scoped_ptr<base::AtExitManager> exit_manager_;
860 sandbox::SandboxInterfaceInfo sandbox_info_;
861 #elif defined(OS_MACOSX)
862 scoped_ptr<base::mac::ScopedNSAutoreleasePool> autorelease_pool_;
865 base::Closure* ui_task_;
867 DISALLOW_COPY_AND_ASSIGN(ContentMainRunnerImpl);
871 ContentMainRunner* ContentMainRunner::Create() {
872 return new ContentMainRunnerImpl();
875 } // namespace content