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/stack_trace.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/memory/scoped_vector.h"
20 #include "base/metrics/statistics_recorder.h"
21 #include "base/path_service.h"
22 #include "base/process/launch.h"
23 #include "base/process/memory.h"
24 #include "base/process/process_handle.h"
25 #include "base/profiler/alternate_timer.h"
26 #include "base/profiler/scoped_tracker.h"
27 #include "base/strings/string_number_conversions.h"
28 #include "base/strings/string_util.h"
29 #include "base/strings/stringprintf.h"
30 #include "base/trace_event/trace_event.h"
31 #include "components/tracing/trace_config_file.h"
32 #include "components/tracing/tracing_switches.h"
33 #include "content/browser/browser_main.h"
34 #include "content/common/set_process_title.h"
35 #include "content/common/url_schemes.h"
36 #include "content/gpu/in_process_gpu_thread.h"
37 #include "content/public/app/content_main.h"
38 #include "content/public/app/content_main_delegate.h"
39 #include "content/public/app/startup_helper_win.h"
40 #include "content/public/browser/content_browser_client.h"
41 #include "content/public/common/content_client.h"
42 #include "content/public/common/content_constants.h"
43 #include "content/public/common/content_paths.h"
44 #include "content/public/common/content_switches.h"
45 #include "content/public/common/main_function_params.h"
46 #include "content/public/common/sandbox_init.h"
47 #include "content/renderer/in_process_renderer_thread.h"
48 #include "content/utility/in_process_utility_thread.h"
49 #include "crypto/nss_util.h"
50 #include "ipc/ipc_descriptors.h"
51 #include "ipc/ipc_switches.h"
52 #include "media/base/media.h"
53 #include "sandbox/win/src/sandbox_types.h"
54 #include "ui/base/ui_base_paths.h"
55 #include "ui/base/ui_base_switches.h"
57 #ifdef V8_USE_EXTERNAL_STARTUP_DATA
58 #include "gin/v8_initializer.h"
61 #if defined(USE_TCMALLOC)
62 #include "third_party/tcmalloc/chromium/src/gperftools/malloc_extension.h"
66 #include "content/app/mojo/mojo_init.h"
67 #include "content/browser/gpu/gpu_process_host.h"
68 #include "content/browser/renderer_host/render_process_host_impl.h"
69 #include "content/browser/utility_process_host_impl.h"
70 #include "content/public/plugin/content_plugin_client.h"
71 #include "content/public/renderer/content_renderer_client.h"
72 #include "content/public/utility/content_utility_client.h"
79 #include "base/strings/string_number_conversions.h"
80 #include "base/trace_event/trace_event_etw_export_win.h"
81 #include "ui/base/win/atl_module.h"
82 #include "ui/gfx/win/dpi.h"
83 #elif defined(OS_MACOSX)
84 #include "base/mac/scoped_nsautorelease_pool.h"
86 #include "base/power_monitor/power_monitor_device_source.h"
87 #include "content/app/mac/mac_init.h"
88 #include "content/browser/browser_io_surface_manager_mac.h"
89 #include "content/browser/mach_broker_mac.h"
90 #include "content/child/child_io_surface_manager_mac.h"
91 #include "content/common/sandbox_init_mac.h"
98 #include "base/posix/global_descriptors.h"
99 #include "content/public/common/content_descriptors.h"
101 #if !defined(OS_MACOSX)
102 #include "content/public/common/content_descriptors.h"
103 #include "content/public/common/zygote_fork_delegate_linux.h"
105 #if !defined(OS_MACOSX) && !defined(OS_ANDROID)
106 #include "content/zygote/zygote_main.h"
111 #if !defined(OS_MACOSX) && defined(USE_TCMALLOC)
113 int tc_set_new_mode(int mode
);
118 extern int GpuMain(const content::MainFunctionParams
&);
119 #if defined(ENABLE_PLUGINS)
120 #if !defined(OS_LINUX)
121 extern int PluginMain(const content::MainFunctionParams
&);
123 extern int PpapiPluginMain(const MainFunctionParams
&);
124 extern int PpapiBrokerMain(const MainFunctionParams
&);
126 extern int RendererMain(const content::MainFunctionParams
&);
127 extern int UtilityMain(const MainFunctionParams
&);
128 } // namespace content
132 #if !defined(CHROME_MULTIPLE_DLL_CHILD)
133 base::LazyInstance
<ContentBrowserClient
>
134 g_empty_content_browser_client
= LAZY_INSTANCE_INITIALIZER
;
135 #endif // !CHROME_MULTIPLE_DLL_CHILD
137 #if !defined(OS_IOS) && !defined(CHROME_MULTIPLE_DLL_BROWSER)
138 base::LazyInstance
<ContentPluginClient
>
139 g_empty_content_plugin_client
= LAZY_INSTANCE_INITIALIZER
;
140 base::LazyInstance
<ContentRendererClient
>
141 g_empty_content_renderer_client
= LAZY_INSTANCE_INITIALIZER
;
142 base::LazyInstance
<ContentUtilityClient
>
143 g_empty_content_utility_client
= LAZY_INSTANCE_INITIALIZER
;
144 #endif // !OS_IOS && !CHROME_MULTIPLE_DLL_BROWSER
148 #endif // defined(OS_WIN)
150 #if defined(OS_POSIX) && !defined(OS_IOS)
152 // Setup signal-handling state: resanitize most signals, ignore SIGPIPE.
153 void SetupSignalHandlers() {
154 // Sanitise our signal handling state. Signals that were ignored by our
155 // parent will also be ignored by us. We also inherit our parent's sigmask.
156 sigset_t empty_signal_set
;
157 CHECK(0 == sigemptyset(&empty_signal_set
));
158 CHECK(0 == sigprocmask(SIG_SETMASK
, &empty_signal_set
, NULL
));
160 struct sigaction sigact
;
161 memset(&sigact
, 0, sizeof(sigact
));
162 sigact
.sa_handler
= SIG_DFL
;
163 static const int signals_to_reset
[] =
164 {SIGHUP
, SIGINT
, SIGQUIT
, SIGILL
, SIGABRT
, SIGFPE
, SIGSEGV
,
165 SIGALRM
, SIGTERM
, SIGCHLD
, SIGBUS
, SIGTRAP
}; // SIGPIPE is set below.
166 for (unsigned i
= 0; i
< arraysize(signals_to_reset
); i
++) {
167 CHECK(0 == sigaction(signals_to_reset
[i
], &sigact
, NULL
));
170 // Always ignore SIGPIPE. We check the return value of write().
171 CHECK(signal(SIGPIPE
, SIG_IGN
) != SIG_ERR
);
174 #endif // OS_POSIX && !OS_IOS
176 void CommonSubprocessInit(const std::string
& process_type
) {
178 // HACK: Let Windows know that we have started. This is needed to suppress
179 // the IDC_APPSTARTING cursor from being displayed for a prolonged period
180 // while a subprocess is starting.
181 PostThreadMessage(GetCurrentThreadId(), WM_NULL
, 0, 0);
183 PeekMessage(&msg
, NULL
, 0, 0, PM_REMOVE
);
185 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
186 // Various things break when you're using a locale where the decimal
187 // separator isn't a period. See e.g. bugs 22782 and 39964. For
188 // all processes except the browser process (where we call system
189 // APIs that may rely on the correct locale for formatting numbers
190 // when presenting them to the user), reset the locale for numeric
192 // Note that this is not correct for plugin processes -- they can
193 // surface UI -- but it's likely they get this wrong too so why not.
194 setlocale(LC_NUMERIC
, "C");
197 #if !defined(OFFICIAL_BUILD)
198 // Print stack traces to stderr when crashes occur. This opens up security
199 // holes so it should never be enabled for official builds.
200 base::debug::EnableInProcessStackDumping();
202 base::RouteStdioToConsole(false);
203 LoadLibraryA("dbghelp.dll");
208 class ContentClientInitializer
{
210 static void Set(const std::string
& process_type
,
211 ContentMainDelegate
* delegate
) {
212 ContentClient
* content_client
= GetContentClient();
213 #if !defined(CHROME_MULTIPLE_DLL_CHILD)
214 if (process_type
.empty()) {
216 content_client
->browser_
= delegate
->CreateContentBrowserClient();
217 if (!content_client
->browser_
)
218 content_client
->browser_
= &g_empty_content_browser_client
.Get();
220 #endif // !CHROME_MULTIPLE_DLL_CHILD
222 #if !defined(OS_IOS) && !defined(CHROME_MULTIPLE_DLL_BROWSER)
223 if (process_type
== switches::kPluginProcess
||
224 process_type
== switches::kPpapiPluginProcess
) {
226 content_client
->plugin_
= delegate
->CreateContentPluginClient();
227 if (!content_client
->plugin_
)
228 content_client
->plugin_
= &g_empty_content_plugin_client
.Get();
229 // Single process not supported in split dll mode.
230 } else if (process_type
== switches::kRendererProcess
||
231 base::CommandLine::ForCurrentProcess()->HasSwitch(
232 switches::kSingleProcess
)) {
234 content_client
->renderer_
= delegate
->CreateContentRendererClient();
235 if (!content_client
->renderer_
)
236 content_client
->renderer_
= &g_empty_content_renderer_client
.Get();
239 if (process_type
== switches::kUtilityProcess
||
240 base::CommandLine::ForCurrentProcess()->HasSwitch(
241 switches::kSingleProcess
)) {
243 content_client
->utility_
= delegate
->CreateContentUtilityClient();
244 // TODO(scottmg): http://crbug.com/237249 Should be in _child.
245 if (!content_client
->utility_
)
246 content_client
->utility_
= &g_empty_content_utility_client
.Get();
248 #endif // !OS_IOS && !CHROME_MULTIPLE_DLL_BROWSER
252 // We dispatch to a process-type-specific FooMain() based on a command-line
253 // flag. This struct is used to build a table of (flag, main function) pairs.
254 struct MainFunction
{
256 int (*function
)(const MainFunctionParams
&);
259 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
260 // On platforms that use the zygote, we have a special subset of
261 // subprocesses that are launched via the zygote. This function
262 // fills in some process-launching bits around ZygoteMain().
263 // Returns the exit code of the subprocess.
264 int RunZygote(const MainFunctionParams
& main_function_params
,
265 ContentMainDelegate
* delegate
) {
266 static const MainFunction kMainFunctions
[] = {
267 { switches::kRendererProcess
, RendererMain
},
268 #if defined(ENABLE_PLUGINS)
269 { switches::kPpapiPluginProcess
, PpapiPluginMain
},
271 { switches::kUtilityProcess
, UtilityMain
},
274 ScopedVector
<ZygoteForkDelegate
> zygote_fork_delegates
;
276 delegate
->ZygoteStarting(&zygote_fork_delegates
);
277 media::InitializeMediaLibrary();
280 // This function call can return multiple times, once per fork().
281 if (!ZygoteMain(main_function_params
, zygote_fork_delegates
.Pass()))
284 if (delegate
) delegate
->ZygoteForked();
286 // Zygote::HandleForkRequest may have reallocated the command
287 // line so update it here with the new version.
288 const base::CommandLine
& command_line
=
289 *base::CommandLine::ForCurrentProcess();
290 std::string process_type
=
291 command_line
.GetSwitchValueASCII(switches::kProcessType
);
292 ContentClientInitializer::Set(process_type
, delegate
);
294 MainFunctionParams
main_params(command_line
);
295 main_params
.zygote_child
= true;
297 for (size_t i
= 0; i
< arraysize(kMainFunctions
); ++i
) {
298 if (process_type
== kMainFunctions
[i
].name
)
299 return kMainFunctions
[i
].function(main_params
);
303 return delegate
->RunProcess(process_type
, main_params
);
305 NOTREACHED() << "Unknown zygote process type: " << process_type
;
308 #endif // defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
311 static void RegisterMainThreadFactories() {
312 #if !defined(CHROME_MULTIPLE_DLL_BROWSER) && !defined(CHROME_MULTIPLE_DLL_CHILD)
313 UtilityProcessHostImpl::RegisterUtilityMainThreadFactory(
314 CreateInProcessUtilityThread
);
315 RenderProcessHostImpl::RegisterRendererMainThreadFactory(
316 CreateInProcessRendererThread
);
317 GpuProcessHost::RegisterGpuMainThreadFactory(
318 CreateInProcessGpuThread
);
320 base::CommandLine
& command_line
= *base::CommandLine::ForCurrentProcess();
321 if (command_line
.HasSwitch(switches::kSingleProcess
)) {
323 "--single-process is not supported in chrome multiple dll browser.";
325 if (command_line
.HasSwitch(switches::kInProcessGPU
)) {
327 "--in-process-gpu is not supported in chrome multiple dll browser.";
329 #endif // !CHROME_MULTIPLE_DLL_BROWSER && !CHROME_MULTIPLE_DLL_CHILD
332 // Run the FooMain() for a given process type.
333 // If |process_type| is empty, runs BrowserMain().
334 // Returns the exit code for this process.
335 int RunNamedProcessTypeMain(
336 const std::string
& process_type
,
337 const MainFunctionParams
& main_function_params
,
338 ContentMainDelegate
* delegate
) {
339 static const MainFunction kMainFunctions
[] = {
340 #if !defined(CHROME_MULTIPLE_DLL_CHILD)
343 #if !defined(CHROME_MULTIPLE_DLL_BROWSER)
344 #if defined(ENABLE_PLUGINS)
345 #if !defined(OS_LINUX)
346 { switches::kPluginProcess
, PluginMain
},
348 { switches::kPpapiPluginProcess
, PpapiPluginMain
},
349 { switches::kPpapiBrokerProcess
, PpapiBrokerMain
},
350 #endif // ENABLE_PLUGINS
351 { switches::kUtilityProcess
, UtilityMain
},
352 { switches::kRendererProcess
, RendererMain
},
353 { switches::kGpuProcess
, GpuMain
},
354 #endif // !CHROME_MULTIPLE_DLL_BROWSER
357 RegisterMainThreadFactories();
359 for (size_t i
= 0; i
< arraysize(kMainFunctions
); ++i
) {
360 if (process_type
== kMainFunctions
[i
].name
) {
362 int exit_code
= delegate
->RunProcess(process_type
,
363 main_function_params
);
364 #if defined(OS_ANDROID)
365 // In Android's browser process, the negative exit code doesn't mean the
366 // default behavior should be used as the UI message loop is managed by
367 // the Java and the browser process's default behavior is always
369 if (process_type
.empty())
375 return kMainFunctions
[i
].function(main_function_params
);
379 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
380 // Zygote startup is special -- see RunZygote comments above
381 // for why we don't use ZygoteMain directly.
382 if (process_type
== switches::kZygoteProcess
)
383 return RunZygote(main_function_params
, delegate
);
386 // If it's a process we don't know about, the embedder should know.
388 return delegate
->RunProcess(process_type
, main_function_params
);
390 NOTREACHED() << "Unknown process type: " << process_type
;
395 class ContentMainRunnerImpl
: public ContentMainRunner
{
397 ContentMainRunnerImpl()
398 : is_initialized_(false),
400 completed_basic_startup_(false),
404 memset(&sandbox_info_
, 0, sizeof(sandbox_info_
));
408 ~ContentMainRunnerImpl() override
{
409 if (is_initialized_
&& !is_shutdown_
)
413 #if defined(USE_TCMALLOC)
414 static bool GetAllocatorWasteSizeThunk(size_t* size
) {
415 size_t heap_size
, allocated_bytes
, unmapped_bytes
;
416 MallocExtension
* ext
= MallocExtension::instance();
417 if (ext
->GetNumericProperty("generic.heap_size", &heap_size
) &&
418 ext
->GetNumericProperty("generic.current_allocated_bytes",
420 ext
->GetNumericProperty("tcmalloc.pageheap_unmapped_bytes",
422 *size
= heap_size
- allocated_bytes
- unmapped_bytes
;
429 static void GetStatsThunk(char* buffer
, int buffer_length
) {
430 MallocExtension::instance()->GetStats(buffer
, buffer_length
);
433 static void ReleaseFreeMemoryThunk() {
434 MallocExtension::instance()->ReleaseFreeMemory();
438 int Initialize(const ContentMainParams
& params
) override
{
439 ui_task_
= params
.ui_task
;
441 base::EnableTerminationOnOutOfMemory();
443 RegisterInvalidParamHandler();
444 ui::win::CreateATLModuleIfNeeded();
446 sandbox_info_
= *params
.sandbox_info
;
449 #if defined(OS_ANDROID)
450 // See note at the initialization of ExitManager, below; basically,
451 // only Android builds have the ctor/dtor handlers set up to use
452 // TRACE_EVENT right away.
453 TRACE_EVENT0("startup", "ContentMainRunnerImpl::Initialize");
456 // NOTE(willchan): One might ask why these TCMalloc-related calls are done
457 // here rather than in process_util_linux.cc with the definition of
458 // EnableTerminationOnOutOfMemory(). That's because base shouldn't have a
459 // dependency on TCMalloc. Really, we ought to have our allocator shim code
460 // implement this EnableTerminationOnOutOfMemory() function. Whateverz.
461 // This works for now.
462 #if !defined(OS_MACOSX) && defined(USE_TCMALLOC)
463 // For tcmalloc, we need to tell it to behave like new.
466 // On windows, we've already set these thunks up in _heap_init()
467 base::allocator::SetGetAllocatorWasteSizeFunction(
468 GetAllocatorWasteSizeThunk
);
469 base::allocator::SetGetStatsFunction(GetStatsThunk
);
470 base::allocator::SetReleaseFreeMemoryFunction(ReleaseFreeMemoryThunk
);
472 // Provide optional hook for monitoring allocation quantities on a
473 // per-thread basis. Only set the hook if the environment indicates this
474 // needs to be enabled.
475 const char* profiling
= getenv(tracked_objects::kAlternateProfilerTime
);
477 (atoi(profiling
) == tracked_objects::TIME_SOURCE_TYPE_TCMALLOC
)) {
478 tracked_objects::SetAlternateTimeSource(
479 MallocExtension::GetBytesAllocatedOnCurrentThread
,
480 tracked_objects::TIME_SOURCE_TYPE_TCMALLOC
);
482 #endif // !OS_MACOSX && USE_TCMALLOC
485 base::GlobalDescriptors
* g_fds
= base::GlobalDescriptors::GetInstance();
489 // - setlocale() is not supported.
490 // - We do not override the signal handlers so that we can get
491 // stack trace when crashing.
492 // - The ipc_fd is passed through the Java service.
493 // Thus, these are all disabled.
494 #if !defined(OS_ANDROID) && !defined(OS_IOS)
495 // Set C library locale to make sure CommandLine can parse argument values
496 // in correct encoding.
497 setlocale(LC_ALL
, "");
499 SetupSignalHandlers();
500 g_fds
->Set(kPrimaryIPCChannel
,
501 kPrimaryIPCChannel
+ base::GlobalDescriptors::kBaseDescriptor
);
502 #endif // !OS_ANDROID && !OS_IOS
504 #if defined(OS_LINUX) || defined(OS_OPENBSD)
505 g_fds
->Set(kCrashDumpSignal
,
506 kCrashDumpSignal
+ base::GlobalDescriptors::kBaseDescriptor
);
507 #endif // OS_LINUX || OS_OPENBSD
512 is_initialized_
= true;
513 delegate_
= params
.delegate
;
515 // The exit manager is in charge of calling the dtors of singleton objects.
516 // On Android, AtExitManager is set up when library is loaded.
517 // On iOS, it's set up in main(), which can't call directly through to here.
518 // A consequence of this is that you can't use the ctor/dtor-based
519 // TRACE_EVENT methods on Linux or iOS builds till after we set this up.
520 #if !defined(OS_ANDROID) && !defined(OS_IOS)
522 // When running browser tests, don't create a second AtExitManager as that
523 // interfers with shutdown when objects created before ContentMain is
524 // called are destructed when it returns.
525 exit_manager_
.reset(new base::AtExitManager
);
527 #endif // !OS_ANDROID && !OS_IOS
529 // Don't create this loop on iOS, since the outer loop is already handled
530 // and a loop that's destroyed in shutdown interleaves badly with the event
532 #if defined(OS_MACOSX) && !defined(OS_IOS)
533 // We need this pool for all the objects created before we get to the
534 // event loop, but we don't want to leave them hanging around until the
535 // app quits. Each "main" needs to flush this pool right before it goes into
536 // its main event loop to get rid of the cruft.
537 autorelease_pool_
.reset(new base::mac::ScopedNSAutoreleasePool());
541 // On Android, the command line is initialized when library is loaded and
542 // we have already started our TRACE_EVENT0.
543 #if !defined(OS_ANDROID)
544 // argc/argv are ignored on Windows and Android; see command_line.h for
547 const char** argv
= NULL
;
554 base::CommandLine::Init(argc
, argv
);
556 base::EnableTerminationOnHeapCorruption();
558 // TODO(yiyaoliu, vadimt): Remove this once crbug.com/453640 is fixed.
559 // Enable profiler recording right after command line is initialized so that
560 // browser startup can be instrumented.
561 if (delegate_
&& delegate_
->ShouldEnableProfilerRecording())
562 tracked_objects::ScopedTracker::Enable();
565 SetProcessTitleFromCommandLine(argv
);
567 #endif // !OS_ANDROID
570 if (delegate_
&& delegate_
->BasicStartupComplete(&exit_code
))
573 completed_basic_startup_
= true;
575 const base::CommandLine
& command_line
=
576 *base::CommandLine::ForCurrentProcess();
577 std::string process_type
=
578 command_line
.GetSwitchValueASCII(switches::kProcessType
);
581 // Initialize mojo here so that services can be registered.
586 bool init_device_scale_factor
= true;
587 if (command_line
.HasSwitch(switches::kDeviceScaleFactor
)) {
588 std::string scale_factor_string
= command_line
.GetSwitchValueASCII(
589 switches::kDeviceScaleFactor
);
590 double scale_factor
= 0;
591 if (base::StringToDouble(scale_factor_string
, &scale_factor
)) {
592 init_device_scale_factor
= false;
593 gfx::InitDeviceScaleFactor(scale_factor
);
596 if (init_device_scale_factor
)
597 gfx::InitDeviceScaleFactor(gfx::GetDPIScale());
600 if (!GetContentClient())
601 SetContentClient(&empty_content_client_
);
602 ContentClientInitializer::Set(process_type
, delegate_
);
605 // Route stdio to parent console (if any) or create one.
606 if (command_line
.HasSwitch(switches::kEnableLogging
))
607 base::RouteStdioToConsole(true);
610 // Enable startup tracing asap to avoid early TRACE_EVENT calls being
612 if (command_line
.HasSwitch(switches::kTraceStartup
)) {
613 base::trace_event::TraceConfig
trace_config(
614 command_line
.GetSwitchValueASCII(switches::kTraceStartup
),
615 base::trace_event::RECORD_UNTIL_FULL
);
616 base::trace_event::TraceLog::GetInstance()->SetEnabled(
618 base::trace_event::TraceLog::RECORDING_MODE
);
619 } else if (process_type
!= switches::kZygoteProcess
&&
620 process_type
!= switches::kRendererProcess
) {
621 if (tracing::TraceConfigFile::GetInstance()->IsEnabled()) {
622 base::trace_event::TraceLog::GetInstance()->SetEnabled(
623 tracing::TraceConfigFile::GetInstance()->GetTraceConfig(),
624 base::trace_event::TraceLog::RECORDING_MODE
);
629 // Enable exporting of events to ETW if requested on the command line.
630 if (command_line
.HasSwitch(switches::kTraceExportEventsToETW
))
631 base::trace_event::TraceEventETWExport::EnableETWExport();
634 #if !defined(OS_ANDROID)
635 // Android tracing started at the beginning of the method.
636 // Other OSes have to wait till we get here in order for all the memory
637 // management setup to be completed.
638 TRACE_EVENT0("startup", "ContentMainRunnerImpl::Initialize");
639 #endif // !OS_ANDROID
641 #if defined(OS_MACOSX) && !defined(OS_IOS)
642 // We need to allocate the IO Ports before the Sandbox is initialized or
643 // the first instance of PowerMonitor is created.
644 // It's important not to allocate the ports for processes which don't
645 // register with the power monitor - see crbug.com/88867.
646 if (process_type
.empty() ||
648 delegate_
->ProcessRegistersWithSystemProcess(process_type
))) {
649 base::PowerMonitorDeviceSource::AllocateSystemIOPorts();
652 if (!process_type
.empty() &&
653 (!delegate_
|| delegate_
->ShouldSendMachPort(process_type
))) {
654 MachBroker::ChildSendTaskPortToParent();
657 if (!command_line
.HasSwitch(switches::kSingleProcess
) &&
658 !process_type
.empty() && (process_type
== switches::kRendererProcess
||
659 process_type
== switches::kGpuProcess
)) {
660 base::mac::ScopedMachSendRight service_port
=
661 BrowserIOSurfaceManager::LookupServicePort(getppid());
662 if (service_port
.is_valid()) {
663 ChildIOSurfaceManager::GetInstance()->set_service_port(
664 service_port
.release());
665 IOSurfaceManager::SetInstance(ChildIOSurfaceManager::GetInstance());
668 #elif defined(OS_WIN)
669 SetupCRT(command_line
);
672 #if defined(OS_POSIX)
673 if (!process_type
.empty()) {
674 // When you hit Ctrl-C in a terminal running the browser
675 // process, a SIGINT is delivered to the entire process group.
676 // When debugging the browser process via gdb, gdb catches the
677 // SIGINT for the browser process (and dumps you back to the gdb
678 // console) but doesn't for the child processes, killing them.
679 // The fix is to have child processes ignore SIGINT; they'll die
680 // on their own when the browser process goes away.
682 // Note that we *can't* rely on BeingDebugged to catch this case because
683 // we are the child process, which is not being debugged.
684 // TODO(evanm): move this to some shared subprocess-init function.
685 if (!base::debug::BeingDebugged())
686 signal(SIGINT
, SIG_IGN
);
690 #if defined(USE_NSS_CERTS)
691 crypto::EarlySetupForNSSInit();
694 ui::RegisterPathProvider();
695 RegisterPathProvider();
696 RegisterContentSchemes(true);
698 #if defined(OS_ANDROID)
699 int icudata_fd
= g_fds
->MaybeGet(kAndroidICUDataDescriptor
);
700 if (icudata_fd
!= -1) {
701 auto icudata_region
= g_fds
->GetRegion(kAndroidICUDataDescriptor
);
702 CHECK(base::i18n::InitializeICUWithFileDescriptor(icudata_fd
,
705 CHECK(base::i18n::InitializeICU());
708 CHECK(base::i18n::InitializeICU());
711 base::StatisticsRecorder::Initialize();
713 #if defined(V8_USE_EXTERNAL_STARTUP_DATA)
714 #if defined(OS_POSIX) && !defined(OS_MACOSX)
715 #if !defined(OS_ANDROID)
716 // kV8NativesDataDescriptor and kV8SnapshotDataDescriptor could be shared
717 // with child processes via file descriptors. On Android they are set in
718 // ChildProcessService::InternalInitChildProcess, otherwise set them here.
719 if (command_line
.HasSwitch(switches::kV8NativesPassedByFD
)) {
721 kV8NativesDataDescriptor
,
722 kV8NativesDataDescriptor
+ base::GlobalDescriptors::kBaseDescriptor
);
724 if (command_line
.HasSwitch(switches::kV8SnapshotPassedByFD
)) {
726 kV8SnapshotDataDescriptor
,
727 kV8SnapshotDataDescriptor
+ base::GlobalDescriptors::kBaseDescriptor
);
729 #endif // !OS_ANDROID
730 int v8_natives_fd
= g_fds
->MaybeGet(kV8NativesDataDescriptor
);
731 int v8_snapshot_fd
= g_fds
->MaybeGet(kV8SnapshotDataDescriptor
);
732 if (v8_snapshot_fd
!= -1) {
733 auto v8_snapshot_region
= g_fds
->GetRegion(kV8SnapshotDataDescriptor
);
734 gin::V8Initializer::LoadV8SnapshotFromFD(
735 v8_snapshot_fd
, v8_snapshot_region
.offset
, v8_snapshot_region
.size
);
737 gin::V8Initializer::LoadV8Snapshot();
739 if (v8_natives_fd
!= -1) {
740 auto v8_natives_region
= g_fds
->GetRegion(kV8NativesDataDescriptor
);
741 gin::V8Initializer::LoadV8NativesFromFD(
742 v8_natives_fd
, v8_natives_region
.offset
, v8_natives_region
.size
);
744 gin::V8Initializer::LoadV8Natives();
747 gin::V8Initializer::LoadV8Snapshot();
748 gin::V8Initializer::LoadV8Natives();
749 #endif // OS_POSIX && !OS_MACOSX
750 #endif // V8_USE_EXTERNAL_STARTUP_DATA
753 delegate_
->PreSandboxStartup();
755 if (!process_type
.empty())
756 CommonSubprocessInit(process_type
);
759 CHECK(InitializeSandbox(params
.sandbox_info
));
760 #elif defined(OS_MACOSX) && !defined(OS_IOS)
761 if (process_type
== switches::kRendererProcess
||
762 process_type
== switches::kPpapiPluginProcess
||
763 (delegate_
&& delegate_
->DelaySandboxInitialization(process_type
))) {
764 // On OS X the renderer sandbox needs to be initialized later in the
765 // startup sequence in RendererMainPlatformDelegate::EnableSandbox().
767 CHECK(InitializeSandbox());
772 delegate_
->SandboxInitialized(process_type
);
774 // Return -1 to indicate no early termination.
779 DCHECK(is_initialized_
);
780 DCHECK(!is_shutdown_
);
781 const base::CommandLine
& command_line
=
782 *base::CommandLine::ForCurrentProcess();
783 std::string process_type
=
784 command_line
.GetSwitchValueASCII(switches::kProcessType
);
786 MainFunctionParams
main_params(command_line
);
787 main_params
.ui_task
= ui_task_
;
789 main_params
.sandbox_info
= &sandbox_info_
;
790 #elif defined(OS_MACOSX)
791 main_params
.autorelease_pool
= autorelease_pool_
.get();
795 return RunNamedProcessTypeMain(process_type
, main_params
, delegate_
);
801 void Shutdown() override
{
802 DCHECK(is_initialized_
);
803 DCHECK(!is_shutdown_
);
805 if (completed_basic_startup_
&& delegate_
) {
806 const base::CommandLine
& command_line
=
807 *base::CommandLine::ForCurrentProcess();
808 std::string process_type
=
809 command_line
.GetSwitchValueASCII(switches::kProcessType
);
811 delegate_
->ProcessExiting(process_type
);
815 #ifdef _CRTDBG_MAP_ALLOC
816 _CrtDumpMemoryLeaks();
817 #endif // _CRTDBG_MAP_ALLOC
820 #if defined(OS_MACOSX) && !defined(OS_IOS)
821 autorelease_pool_
.reset(NULL
);
824 exit_manager_
.reset(NULL
);
831 // True if the runner has been initialized.
832 bool is_initialized_
;
834 // True if the runner has been shut down.
837 // True if basic startup was completed.
838 bool completed_basic_startup_
;
840 // Used if the embedder doesn't set one.
841 ContentClient empty_content_client_
;
843 // The delegate will outlive this object.
844 ContentMainDelegate
* delegate_
;
846 scoped_ptr
<base::AtExitManager
> exit_manager_
;
848 sandbox::SandboxInterfaceInfo sandbox_info_
;
849 #elif defined(OS_MACOSX)
850 scoped_ptr
<base::mac::ScopedNSAutoreleasePool
> autorelease_pool_
;
853 base::Closure
* ui_task_
;
855 DISALLOW_COPY_AND_ASSIGN(ContentMainRunnerImpl
);
859 ContentMainRunner
* ContentMainRunner::Create() {
860 return new ContentMainRunnerImpl();
863 } // namespace content