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/files/file_path.h"
14 #include "base/i18n/icu_util.h"
15 #include "base/lazy_instance.h"
16 #include "base/logging.h"
17 #include "base/memory/scoped_ptr.h"
18 #include "base/memory/scoped_vector.h"
19 #include "base/metrics/statistics_recorder.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/profiler/scoped_tracker.h"
26 #include "base/strings/string_number_conversions.h"
27 #include "base/strings/string_util.h"
28 #include "base/strings/stringprintf.h"
29 #include "base/trace_event/trace_event.h"
30 #include "components/tracing/startup_tracing.h"
31 #include "content/browser/browser_main.h"
32 #include "content/common/set_process_title.h"
33 #include "content/common/url_schemes.h"
34 #include "content/gpu/in_process_gpu_thread.h"
35 #include "content/public/app/content_main.h"
36 #include "content/public/app/content_main_delegate.h"
37 #include "content/public/app/startup_helper_win.h"
38 #include "content/public/browser/content_browser_client.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_descriptors.h"
49 #include "ipc/ipc_switches.h"
50 #include "media/base/media.h"
51 #include "sandbox/win/src/sandbox_types.h"
52 #include "ui/base/ui_base_paths.h"
53 #include "ui/base/ui_base_switches.h"
55 #ifdef V8_USE_EXTERNAL_STARTUP_DATA
56 #include "gin/v8_initializer.h"
59 #if defined(USE_TCMALLOC)
60 #include "third_party/tcmalloc/chromium/src/gperftools/malloc_extension.h"
61 #if defined(TYPE_PROFILING)
62 #include "base/allocator/type_profiler.h"
63 #include "base/allocator/type_profiler_tcmalloc.h"
68 #include "content/app/mojo/mojo_init.h"
69 #include "content/browser/gpu/gpu_process_host.h"
70 #include "content/browser/renderer_host/render_process_host_impl.h"
71 #include "content/browser/utility_process_host_impl.h"
72 #include "content/public/plugin/content_plugin_client.h"
73 #include "content/public/renderer/content_renderer_client.h"
74 #include "content/public/utility/content_utility_client.h"
81 #include "base/strings/string_number_conversions.h"
82 #include "base/trace_event/trace_event_etw_export_win.h"
83 #include "ui/base/win/atl_module.h"
84 #include "ui/gfx/win/dpi.h"
85 #elif defined(OS_MACOSX)
86 #include "base/mac/scoped_nsautorelease_pool.h"
88 #include "base/power_monitor/power_monitor_device_source.h"
89 #include "content/app/mac/mac_init.h"
90 #include "content/browser/browser_io_surface_manager_mac.h"
91 #include "content/browser/mach_broker_mac.h"
92 #include "content/child/child_io_surface_manager_mac.h"
93 #include "content/common/sandbox_init_mac.h"
100 #include "base/posix/global_descriptors.h"
101 #include "content/public/common/content_descriptors.h"
103 #if !defined(OS_MACOSX)
104 #include "content/public/common/content_descriptors.h"
105 #include "content/public/common/zygote_fork_delegate_linux.h"
107 #if !defined(OS_MACOSX) && !defined(OS_ANDROID)
108 #include "content/zygote/zygote_main.h"
113 #if !defined(OS_MACOSX) && defined(USE_TCMALLOC)
115 int tc_set_new_mode(int mode
);
120 extern int GpuMain(const content::MainFunctionParams
&);
121 #if defined(ENABLE_PLUGINS)
122 #if !defined(OS_LINUX)
123 extern int PluginMain(const content::MainFunctionParams
&);
125 extern int PpapiPluginMain(const MainFunctionParams
&);
126 extern int PpapiBrokerMain(const MainFunctionParams
&);
128 extern int RendererMain(const content::MainFunctionParams
&);
129 extern int UtilityMain(const MainFunctionParams
&);
130 } // namespace content
134 #if !defined(CHROME_MULTIPLE_DLL_CHILD)
135 base::LazyInstance
<ContentBrowserClient
>
136 g_empty_content_browser_client
= LAZY_INSTANCE_INITIALIZER
;
137 #endif // !CHROME_MULTIPLE_DLL_CHILD
139 #if !defined(OS_IOS) && !defined(CHROME_MULTIPLE_DLL_BROWSER)
140 base::LazyInstance
<ContentPluginClient
>
141 g_empty_content_plugin_client
= LAZY_INSTANCE_INITIALIZER
;
142 base::LazyInstance
<ContentRendererClient
>
143 g_empty_content_renderer_client
= LAZY_INSTANCE_INITIALIZER
;
144 base::LazyInstance
<ContentUtilityClient
>
145 g_empty_content_utility_client
= LAZY_INSTANCE_INITIALIZER
;
146 #endif // !OS_IOS && !CHROME_MULTIPLE_DLL_BROWSER
150 #endif // defined(OS_WIN)
152 #if defined(OS_POSIX) && !defined(OS_IOS)
154 // Setup signal-handling state: resanitize most signals, ignore SIGPIPE.
155 void SetupSignalHandlers() {
156 // Sanitise our signal handling state. Signals that were ignored by our
157 // parent will also be ignored by us. We also inherit our parent's sigmask.
158 sigset_t empty_signal_set
;
159 CHECK(0 == sigemptyset(&empty_signal_set
));
160 CHECK(0 == sigprocmask(SIG_SETMASK
, &empty_signal_set
, NULL
));
162 struct sigaction sigact
;
163 memset(&sigact
, 0, sizeof(sigact
));
164 sigact
.sa_handler
= SIG_DFL
;
165 static const int signals_to_reset
[] =
166 {SIGHUP
, SIGINT
, SIGQUIT
, SIGILL
, SIGABRT
, SIGFPE
, SIGSEGV
,
167 SIGALRM
, SIGTERM
, SIGCHLD
, SIGBUS
, SIGTRAP
}; // SIGPIPE is set below.
168 for (unsigned i
= 0; i
< arraysize(signals_to_reset
); i
++) {
169 CHECK(0 == sigaction(signals_to_reset
[i
], &sigact
, NULL
));
172 // Always ignore SIGPIPE. We check the return value of write().
173 CHECK(signal(SIGPIPE
, SIG_IGN
) != SIG_ERR
);
176 #endif // OS_POSIX && !OS_IOS
178 void CommonSubprocessInit(const std::string
& process_type
) {
180 // HACK: Let Windows know that we have started. This is needed to suppress
181 // the IDC_APPSTARTING cursor from being displayed for a prolonged period
182 // while a subprocess is starting.
183 PostThreadMessage(GetCurrentThreadId(), WM_NULL
, 0, 0);
185 PeekMessage(&msg
, NULL
, 0, 0, PM_REMOVE
);
187 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
188 // Various things break when you're using a locale where the decimal
189 // separator isn't a period. See e.g. bugs 22782 and 39964. For
190 // all processes except the browser process (where we call system
191 // APIs that may rely on the correct locale for formatting numbers
192 // when presenting them to the user), reset the locale for numeric
194 // Note that this is not correct for plugin processes -- they can
195 // surface UI -- but it's likely they get this wrong too so why not.
196 setlocale(LC_NUMERIC
, "C");
200 class ContentClientInitializer
{
202 static void Set(const std::string
& process_type
,
203 ContentMainDelegate
* delegate
) {
204 ContentClient
* content_client
= GetContentClient();
205 #if !defined(CHROME_MULTIPLE_DLL_CHILD)
206 if (process_type
.empty()) {
208 content_client
->browser_
= delegate
->CreateContentBrowserClient();
209 if (!content_client
->browser_
)
210 content_client
->browser_
= &g_empty_content_browser_client
.Get();
212 #endif // !CHROME_MULTIPLE_DLL_CHILD
214 #if !defined(OS_IOS) && !defined(CHROME_MULTIPLE_DLL_BROWSER)
215 if (process_type
== switches::kPluginProcess
||
216 process_type
== switches::kPpapiPluginProcess
) {
218 content_client
->plugin_
= delegate
->CreateContentPluginClient();
219 if (!content_client
->plugin_
)
220 content_client
->plugin_
= &g_empty_content_plugin_client
.Get();
221 // Single process not supported in split dll mode.
222 } else if (process_type
== switches::kRendererProcess
||
223 base::CommandLine::ForCurrentProcess()->HasSwitch(
224 switches::kSingleProcess
)) {
226 content_client
->renderer_
= delegate
->CreateContentRendererClient();
227 if (!content_client
->renderer_
)
228 content_client
->renderer_
= &g_empty_content_renderer_client
.Get();
231 if (process_type
== switches::kUtilityProcess
||
232 base::CommandLine::ForCurrentProcess()->HasSwitch(
233 switches::kSingleProcess
)) {
235 content_client
->utility_
= delegate
->CreateContentUtilityClient();
236 // TODO(scottmg): http://crbug.com/237249 Should be in _child.
237 if (!content_client
->utility_
)
238 content_client
->utility_
= &g_empty_content_utility_client
.Get();
240 #endif // !OS_IOS && !CHROME_MULTIPLE_DLL_BROWSER
244 // We dispatch to a process-type-specific FooMain() based on a command-line
245 // flag. This struct is used to build a table of (flag, main function) pairs.
246 struct MainFunction
{
248 int (*function
)(const MainFunctionParams
&);
251 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
252 // On platforms that use the zygote, we have a special subset of
253 // subprocesses that are launched via the zygote. This function
254 // fills in some process-launching bits around ZygoteMain().
255 // Returns the exit code of the subprocess.
256 int RunZygote(const MainFunctionParams
& main_function_params
,
257 ContentMainDelegate
* delegate
) {
258 static const MainFunction kMainFunctions
[] = {
259 { switches::kRendererProcess
, RendererMain
},
260 #if defined(ENABLE_PLUGINS)
261 { switches::kPpapiPluginProcess
, PpapiPluginMain
},
263 { switches::kUtilityProcess
, UtilityMain
},
266 ScopedVector
<ZygoteForkDelegate
> zygote_fork_delegates
;
268 delegate
->ZygoteStarting(&zygote_fork_delegates
);
269 media::InitializeMediaLibrary();
272 // This function call can return multiple times, once per fork().
273 if (!ZygoteMain(main_function_params
, zygote_fork_delegates
.Pass()))
276 if (delegate
) delegate
->ZygoteForked();
278 // Zygote::HandleForkRequest may have reallocated the command
279 // line so update it here with the new version.
280 const base::CommandLine
& command_line
=
281 *base::CommandLine::ForCurrentProcess();
282 std::string process_type
=
283 command_line
.GetSwitchValueASCII(switches::kProcessType
);
284 ContentClientInitializer::Set(process_type
, delegate
);
286 MainFunctionParams
main_params(command_line
);
287 main_params
.zygote_child
= true;
289 for (size_t i
= 0; i
< arraysize(kMainFunctions
); ++i
) {
290 if (process_type
== kMainFunctions
[i
].name
)
291 return kMainFunctions
[i
].function(main_params
);
295 return delegate
->RunProcess(process_type
, main_params
);
297 NOTREACHED() << "Unknown zygote process type: " << process_type
;
300 #endif // defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
303 static void RegisterMainThreadFactories() {
304 #if !defined(CHROME_MULTIPLE_DLL_BROWSER) && !defined(CHROME_MULTIPLE_DLL_CHILD)
305 UtilityProcessHostImpl::RegisterUtilityMainThreadFactory(
306 CreateInProcessUtilityThread
);
307 RenderProcessHostImpl::RegisterRendererMainThreadFactory(
308 CreateInProcessRendererThread
);
309 GpuProcessHost::RegisterGpuMainThreadFactory(
310 CreateInProcessGpuThread
);
312 base::CommandLine
& command_line
= *base::CommandLine::ForCurrentProcess();
313 if (command_line
.HasSwitch(switches::kSingleProcess
)) {
315 "--single-process is not supported in chrome multiple dll browser.";
317 if (command_line
.HasSwitch(switches::kInProcessGPU
)) {
319 "--in-process-gpu is not supported in chrome multiple dll browser.";
321 #endif // !CHROME_MULTIPLE_DLL_BROWSER && !CHROME_MULTIPLE_DLL_CHILD
324 // Run the FooMain() for a given process type.
325 // If |process_type| is empty, runs BrowserMain().
326 // Returns the exit code for this process.
327 int RunNamedProcessTypeMain(
328 const std::string
& process_type
,
329 const MainFunctionParams
& main_function_params
,
330 ContentMainDelegate
* delegate
) {
331 static const MainFunction kMainFunctions
[] = {
332 #if !defined(CHROME_MULTIPLE_DLL_CHILD)
335 #if !defined(CHROME_MULTIPLE_DLL_BROWSER)
336 #if defined(ENABLE_PLUGINS)
337 #if !defined(OS_LINUX)
338 { switches::kPluginProcess
, PluginMain
},
340 { switches::kPpapiPluginProcess
, PpapiPluginMain
},
341 { switches::kPpapiBrokerProcess
, PpapiBrokerMain
},
342 #endif // ENABLE_PLUGINS
343 { switches::kUtilityProcess
, UtilityMain
},
344 { switches::kRendererProcess
, RendererMain
},
345 { switches::kGpuProcess
, GpuMain
},
346 #endif // !CHROME_MULTIPLE_DLL_BROWSER
349 RegisterMainThreadFactories();
351 for (size_t i
= 0; i
< arraysize(kMainFunctions
); ++i
) {
352 if (process_type
== kMainFunctions
[i
].name
) {
354 int exit_code
= delegate
->RunProcess(process_type
,
355 main_function_params
);
356 #if defined(OS_ANDROID)
357 // In Android's browser process, the negative exit code doesn't mean the
358 // default behavior should be used as the UI message loop is managed by
359 // the Java and the browser process's default behavior is always
361 if (process_type
.empty())
367 return kMainFunctions
[i
].function(main_function_params
);
371 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
372 // Zygote startup is special -- see RunZygote comments above
373 // for why we don't use ZygoteMain directly.
374 if (process_type
== switches::kZygoteProcess
)
375 return RunZygote(main_function_params
, delegate
);
378 // If it's a process we don't know about, the embedder should know.
380 return delegate
->RunProcess(process_type
, main_function_params
);
382 NOTREACHED() << "Unknown process type: " << process_type
;
387 class ContentMainRunnerImpl
: public ContentMainRunner
{
389 ContentMainRunnerImpl()
390 : is_initialized_(false),
392 completed_basic_startup_(false),
396 memset(&sandbox_info_
, 0, sizeof(sandbox_info_
));
400 ~ContentMainRunnerImpl() override
{
401 if (is_initialized_
&& !is_shutdown_
)
405 #if defined(USE_TCMALLOC)
406 static bool GetAllocatorWasteSizeThunk(size_t* size
) {
407 size_t heap_size
, allocated_bytes
, unmapped_bytes
;
408 MallocExtension
* ext
= MallocExtension::instance();
409 if (ext
->GetNumericProperty("generic.heap_size", &heap_size
) &&
410 ext
->GetNumericProperty("generic.current_allocated_bytes",
412 ext
->GetNumericProperty("tcmalloc.pageheap_unmapped_bytes",
414 *size
= heap_size
- allocated_bytes
- unmapped_bytes
;
421 static void GetStatsThunk(char* buffer
, int buffer_length
) {
422 MallocExtension::instance()->GetStats(buffer
, buffer_length
);
425 static void ReleaseFreeMemoryThunk() {
426 MallocExtension::instance()->ReleaseFreeMemory();
430 int Initialize(const ContentMainParams
& params
) override
{
431 ui_task_
= params
.ui_task
;
433 base::EnableTerminationOnOutOfMemory();
435 RegisterInvalidParamHandler();
436 ui::win::CreateATLModuleIfNeeded();
438 sandbox_info_
= *params
.sandbox_info
;
441 #if defined(OS_ANDROID)
442 // See note at the initialization of ExitManager, below; basically,
443 // only Android builds have the ctor/dtor handlers set up to use
444 // TRACE_EVENT right away.
445 TRACE_EVENT0("startup", "ContentMainRunnerImpl::Initialize");
448 // NOTE(willchan): One might ask why these TCMalloc-related calls are done
449 // here rather than in process_util_linux.cc with the definition of
450 // EnableTerminationOnOutOfMemory(). That's because base shouldn't have a
451 // dependency on TCMalloc. Really, we ought to have our allocator shim code
452 // implement this EnableTerminationOnOutOfMemory() function. Whateverz.
453 // This works for now.
454 #if !defined(OS_MACOSX) && defined(USE_TCMALLOC)
456 #if defined(TYPE_PROFILING)
457 base::type_profiler::InterceptFunctions::SetFunctions(
458 base::type_profiler::NewInterceptForTCMalloc
,
459 base::type_profiler::DeleteInterceptForTCMalloc
);
462 // For tcmalloc, we need to tell it to behave like new.
465 // On windows, we've already set these thunks up in _heap_init()
466 base::allocator::SetGetAllocatorWasteSizeFunction(
467 GetAllocatorWasteSizeThunk
);
468 base::allocator::SetGetStatsFunction(GetStatsThunk
);
469 base::allocator::SetReleaseFreeMemoryFunction(ReleaseFreeMemoryThunk
);
471 // Provide optional hook for monitoring allocation quantities on a
472 // per-thread basis. Only set the hook if the environment indicates this
473 // needs to be enabled.
474 const char* profiling
= getenv(tracked_objects::kAlternateProfilerTime
);
476 (atoi(profiling
) == tracked_objects::TIME_SOURCE_TYPE_TCMALLOC
)) {
477 tracked_objects::SetAlternateTimeSource(
478 MallocExtension::GetBytesAllocatedOnCurrentThread
,
479 tracked_objects::TIME_SOURCE_TYPE_TCMALLOC
);
481 #endif // !OS_MACOSX && USE_TCMALLOC
484 base::GlobalDescriptors
* g_fds
= base::GlobalDescriptors::GetInstance();
488 // - setlocale() is not supported.
489 // - We do not override the signal handlers so that we can get
490 // stack trace when crashing.
491 // - The ipc_fd is passed through the Java service.
492 // Thus, these are all disabled.
493 #if !defined(OS_ANDROID) && !defined(OS_IOS)
494 // Set C library locale to make sure CommandLine can parse argument values
495 // in correct encoding.
496 setlocale(LC_ALL
, "");
498 SetupSignalHandlers();
499 g_fds
->Set(kPrimaryIPCChannel
,
500 kPrimaryIPCChannel
+ base::GlobalDescriptors::kBaseDescriptor
);
501 #endif // !OS_ANDROID && !OS_IOS
503 #if defined(OS_LINUX) || defined(OS_OPENBSD)
504 g_fds
->Set(kCrashDumpSignal
,
505 kCrashDumpSignal
+ base::GlobalDescriptors::kBaseDescriptor
);
506 #endif // OS_LINUX || OS_OPENBSD
511 is_initialized_
= true;
512 delegate_
= params
.delegate
;
514 // The exit manager is in charge of calling the dtors of singleton objects.
515 // On Android, AtExitManager is set up when library is loaded.
516 // On iOS, it's set up in main(), which can't call directly through to here.
517 // A consequence of this is that you can't use the ctor/dtor-based
518 // TRACE_EVENT methods on Linux or iOS builds till after we set this up.
519 #if !defined(OS_ANDROID) && !defined(OS_IOS)
521 // When running browser tests, don't create a second AtExitManager as that
522 // interfers with shutdown when objects created before ContentMain is
523 // called are destructed when it returns.
524 exit_manager_
.reset(new base::AtExitManager
);
526 #endif // !OS_ANDROID && !OS_IOS
528 // Don't create this loop on iOS, since the outer loop is already handled
529 // and a loop that's destroyed in shutdown interleaves badly with the event
531 #if defined(OS_MACOSX) && !defined(OS_IOS)
532 // We need this pool for all the objects created before we get to the
533 // event loop, but we don't want to leave them hanging around until the
534 // app quits. Each "main" needs to flush this pool right before it goes into
535 // its main event loop to get rid of the cruft.
536 autorelease_pool_
.reset(new base::mac::ScopedNSAutoreleasePool());
540 // On Android, the command line is initialized when library is loaded and
541 // we have already started our TRACE_EVENT0.
542 #if !defined(OS_ANDROID)
543 // argc/argv are ignored on Windows and Android; see command_line.h for
546 const char** argv
= NULL
;
553 base::CommandLine::Init(argc
, argv
);
555 base::EnableTerminationOnHeapCorruption();
557 // TODO(yiyaoliu, vadimt): Remove this once crbug.com/453640 is fixed.
558 // Enable profiler recording right after command line is initialized so that
559 // browser startup can be instrumented.
560 if (delegate_
&& delegate_
->ShouldEnableProfilerRecording())
561 tracked_objects::ScopedTracker::Enable();
564 SetProcessTitleFromCommandLine(argv
);
566 #endif // !OS_ANDROID
569 if (delegate_
&& delegate_
->BasicStartupComplete(&exit_code
))
572 completed_basic_startup_
= true;
574 const base::CommandLine
& command_line
=
575 *base::CommandLine::ForCurrentProcess();
576 std::string process_type
=
577 command_line
.GetSwitchValueASCII(switches::kProcessType
);
580 // Initialize mojo here so that services can be registered.
585 bool init_device_scale_factor
= true;
586 if (command_line
.HasSwitch(switches::kDeviceScaleFactor
)) {
587 std::string scale_factor_string
= command_line
.GetSwitchValueASCII(
588 switches::kDeviceScaleFactor
);
589 double scale_factor
= 0;
590 if (base::StringToDouble(scale_factor_string
, &scale_factor
)) {
591 init_device_scale_factor
= false;
592 gfx::InitDeviceScaleFactor(scale_factor
);
595 if (init_device_scale_factor
)
596 gfx::InitDeviceScaleFactor(gfx::GetDPIScale());
599 if (!GetContentClient())
600 SetContentClient(&empty_content_client_
);
601 ContentClientInitializer::Set(process_type
, delegate_
);
604 // Route stdio to parent console (if any) or create one.
605 if (command_line
.HasSwitch(switches::kEnableLogging
))
606 base::RouteStdioToConsole();
609 // Enable startup tracing asap to avoid early TRACE_EVENT calls being
611 if (command_line
.HasSwitch(switches::kTraceStartup
)) {
612 base::trace_event::TraceConfig
trace_config(
613 command_line
.GetSwitchValueASCII(switches::kTraceStartup
),
614 base::trace_event::RECORD_UNTIL_FULL
);
615 base::trace_event::TraceLog::GetInstance()->SetEnabled(
617 base::trace_event::TraceLog::RECORDING_MODE
);
618 } else if (process_type
!= switches::kZygoteProcess
&&
619 process_type
!= switches::kRendererProcess
) {
620 // There is no need to schedule stopping tracing in this case. Telemetry
621 // will stop tracing on demand later.
622 tracing::EnableStartupTracingIfConfigFileExists();
626 // Enable exporting of events to ETW if requested on the command line.
627 if (command_line
.HasSwitch(switches::kTraceExportEventsToETW
))
628 base::trace_event::TraceEventETWExport::EnableETWExport();
631 #if !defined(OS_ANDROID)
632 // Android tracing started at the beginning of the method.
633 // Other OSes have to wait till we get here in order for all the memory
634 // management setup to be completed.
635 TRACE_EVENT0("startup", "ContentMainRunnerImpl::Initialize");
636 #endif // !OS_ANDROID
638 #if defined(OS_MACOSX) && !defined(OS_IOS)
639 // We need to allocate the IO Ports before the Sandbox is initialized or
640 // the first instance of PowerMonitor is created.
641 // It's important not to allocate the ports for processes which don't
642 // register with the power monitor - see crbug.com/88867.
643 if (process_type
.empty() ||
645 delegate_
->ProcessRegistersWithSystemProcess(process_type
))) {
646 base::PowerMonitorDeviceSource::AllocateSystemIOPorts();
649 if (!process_type
.empty() &&
650 (!delegate_
|| delegate_
->ShouldSendMachPort(process_type
))) {
651 MachBroker::ChildSendTaskPortToParent();
654 if (!command_line
.HasSwitch(switches::kSingleProcess
) &&
655 !process_type
.empty() && (process_type
== switches::kRendererProcess
||
656 process_type
== switches::kGpuProcess
)) {
657 base::mac::ScopedMachSendRight service_port
=
658 BrowserIOSurfaceManager::LookupServicePort(getppid());
659 if (service_port
.is_valid()) {
660 ChildIOSurfaceManager::GetInstance()->set_service_port(
661 service_port
.release());
662 IOSurfaceManager::SetInstance(ChildIOSurfaceManager::GetInstance());
665 #elif defined(OS_WIN)
666 SetupCRT(command_line
);
669 #if defined(OS_POSIX)
670 if (!process_type
.empty()) {
671 // When you hit Ctrl-C in a terminal running the browser
672 // process, a SIGINT is delivered to the entire process group.
673 // When debugging the browser process via gdb, gdb catches the
674 // SIGINT for the browser process (and dumps you back to the gdb
675 // console) but doesn't for the child processes, killing them.
676 // The fix is to have child processes ignore SIGINT; they'll die
677 // on their own when the browser process goes away.
679 // Note that we *can't* rely on BeingDebugged to catch this case because
680 // we are the child process, which is not being debugged.
681 // TODO(evanm): move this to some shared subprocess-init function.
682 if (!base::debug::BeingDebugged())
683 signal(SIGINT
, SIG_IGN
);
687 #if defined(USE_NSS_CERTS)
688 crypto::EarlySetupForNSSInit();
691 ui::RegisterPathProvider();
692 RegisterPathProvider();
693 RegisterContentSchemes(true);
695 #if defined(OS_ANDROID)
696 int icudata_fd
= g_fds
->MaybeGet(kAndroidICUDataDescriptor
);
697 if (icudata_fd
!= -1) {
698 auto icudata_region
= g_fds
->GetRegion(kAndroidICUDataDescriptor
);
699 CHECK(base::i18n::InitializeICUWithFileDescriptor(icudata_fd
,
702 CHECK(base::i18n::InitializeICU());
705 CHECK(base::i18n::InitializeICU());
708 base::StatisticsRecorder::Initialize();
710 #if defined(V8_USE_EXTERNAL_STARTUP_DATA)
711 #if defined(OS_POSIX) && !defined(OS_MACOSX)
712 #if !defined(OS_ANDROID)
713 // kV8NativesDataDescriptor and kV8SnapshotDataDescriptor could be shared
714 // with child processes via file descriptors. On Android they are set in
715 // ChildProcessService::InternalInitChildProcess, otherwise set them here.
716 if (command_line
.HasSwitch(switches::kV8NativesPassedByFD
)) {
718 kV8NativesDataDescriptor
,
719 kV8NativesDataDescriptor
+ base::GlobalDescriptors::kBaseDescriptor
);
721 if (command_line
.HasSwitch(switches::kV8SnapshotPassedByFD
)) {
723 kV8SnapshotDataDescriptor
,
724 kV8SnapshotDataDescriptor
+ base::GlobalDescriptors::kBaseDescriptor
);
726 #endif // !OS_ANDROID
727 int v8_natives_fd
= g_fds
->MaybeGet(kV8NativesDataDescriptor
);
728 int v8_snapshot_fd
= g_fds
->MaybeGet(kV8SnapshotDataDescriptor
);
729 if (v8_snapshot_fd
!= -1) {
730 auto v8_snapshot_region
= g_fds
->GetRegion(kV8SnapshotDataDescriptor
);
731 gin::V8Initializer::LoadV8SnapshotFromFD(
732 v8_snapshot_fd
, v8_snapshot_region
.offset
, v8_snapshot_region
.size
);
734 gin::V8Initializer::LoadV8Snapshot();
736 if (v8_natives_fd
!= -1) {
737 auto v8_natives_region
= g_fds
->GetRegion(kV8NativesDataDescriptor
);
738 gin::V8Initializer::LoadV8NativesFromFD(
739 v8_natives_fd
, v8_natives_region
.offset
, v8_natives_region
.size
);
741 gin::V8Initializer::LoadV8Natives();
744 gin::V8Initializer::LoadV8Snapshot();
745 gin::V8Initializer::LoadV8Natives();
746 #endif // OS_POSIX && !OS_MACOSX
747 #endif // V8_USE_EXTERNAL_STARTUP_DATA
750 delegate_
->PreSandboxStartup();
752 if (!process_type
.empty())
753 CommonSubprocessInit(process_type
);
756 CHECK(InitializeSandbox(params
.sandbox_info
));
757 #elif defined(OS_MACOSX) && !defined(OS_IOS)
758 if (process_type
== switches::kRendererProcess
||
759 process_type
== switches::kPpapiPluginProcess
||
760 (delegate_
&& delegate_
->DelaySandboxInitialization(process_type
))) {
761 // On OS X the renderer sandbox needs to be initialized later in the
762 // startup sequence in RendererMainPlatformDelegate::EnableSandbox().
764 CHECK(InitializeSandbox());
769 delegate_
->SandboxInitialized(process_type
);
771 // Return -1 to indicate no early termination.
776 DCHECK(is_initialized_
);
777 DCHECK(!is_shutdown_
);
778 const base::CommandLine
& command_line
=
779 *base::CommandLine::ForCurrentProcess();
780 std::string process_type
=
781 command_line
.GetSwitchValueASCII(switches::kProcessType
);
783 MainFunctionParams
main_params(command_line
);
784 main_params
.ui_task
= ui_task_
;
786 main_params
.sandbox_info
= &sandbox_info_
;
787 #elif defined(OS_MACOSX)
788 main_params
.autorelease_pool
= autorelease_pool_
.get();
792 return RunNamedProcessTypeMain(process_type
, main_params
, delegate_
);
798 void Shutdown() override
{
799 DCHECK(is_initialized_
);
800 DCHECK(!is_shutdown_
);
802 if (completed_basic_startup_
&& delegate_
) {
803 const base::CommandLine
& command_line
=
804 *base::CommandLine::ForCurrentProcess();
805 std::string process_type
=
806 command_line
.GetSwitchValueASCII(switches::kProcessType
);
808 delegate_
->ProcessExiting(process_type
);
812 #ifdef _CRTDBG_MAP_ALLOC
813 _CrtDumpMemoryLeaks();
814 #endif // _CRTDBG_MAP_ALLOC
817 #if defined(OS_MACOSX) && !defined(OS_IOS)
818 autorelease_pool_
.reset(NULL
);
821 exit_manager_
.reset(NULL
);
828 // True if the runner has been initialized.
829 bool is_initialized_
;
831 // True if the runner has been shut down.
834 // True if basic startup was completed.
835 bool completed_basic_startup_
;
837 // Used if the embedder doesn't set one.
838 ContentClient empty_content_client_
;
840 // The delegate will outlive this object.
841 ContentMainDelegate
* delegate_
;
843 scoped_ptr
<base::AtExitManager
> exit_manager_
;
845 sandbox::SandboxInterfaceInfo sandbox_info_
;
846 #elif defined(OS_MACOSX)
847 scoped_ptr
<base::mac::ScopedNSAutoreleasePool
> autorelease_pool_
;
850 base::Closure
* ui_task_
;
852 DISALLOW_COPY_AND_ASSIGN(ContentMainRunnerImpl
);
856 ContentMainRunner
* ContentMainRunner::Create() {
857 return new ContentMainRunnerImpl();
860 } // namespace content