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 "content/browser/browser_main.h"
31 #include "content/common/set_process_title.h"
32 #include "content/common/url_schemes.h"
33 #include "content/gpu/in_process_gpu_thread.h"
34 #include "content/public/app/content_main.h"
35 #include "content/public/app/content_main_delegate.h"
36 #include "content/public/app/startup_helper_win.h"
37 #include "content/public/browser/content_browser_client.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_descriptors.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"
54 #ifdef V8_USE_EXTERNAL_STARTUP_DATA
55 #include "gin/v8_initializer.h"
58 #if defined(USE_TCMALLOC)
59 #include "third_party/tcmalloc/chromium/src/gperftools/malloc_extension.h"
60 #if defined(TYPE_PROFILING)
61 #include "base/allocator/type_profiler.h"
62 #include "base/allocator/type_profiler_tcmalloc.h"
67 #include "content/app/mojo/mojo_init.h"
68 #include "content/browser/gpu/gpu_process_host.h"
69 #include "content/browser/renderer_host/render_process_host_impl.h"
70 #include "content/browser/utility_process_host_impl.h"
71 #include "content/public/plugin/content_plugin_client.h"
72 #include "content/public/renderer/content_renderer_client.h"
73 #include "content/public/utility/content_utility_client.h"
80 #include "base/strings/string_number_conversions.h"
81 #include "base/trace_event/trace_event_etw_export_win.h"
82 #include "ui/base/win/atl_module.h"
83 #include "ui/gfx/win/dpi.h"
84 #elif defined(OS_MACOSX)
85 #include "base/mac/scoped_nsautorelease_pool.h"
87 #include "base/power_monitor/power_monitor_device_source.h"
88 #include "content/app/mac/mac_init.h"
89 #include "content/browser/mach_broker_mac.h"
90 #include "content/common/sandbox_init_mac.h"
97 #include "base/posix/global_descriptors.h"
98 #include "content/public/common/content_descriptors.h"
100 #if !defined(OS_MACOSX)
101 #include "content/public/common/content_descriptors.h"
102 #include "content/public/common/zygote_fork_delegate_linux.h"
104 #if !defined(OS_MACOSX) && !defined(OS_ANDROID)
105 #include "content/zygote/zygote_main.h"
110 #if !defined(OS_MACOSX) && defined(USE_TCMALLOC)
112 int tc_set_new_mode(int mode
);
117 extern int GpuMain(const content::MainFunctionParams
&);
118 #if defined(ENABLE_PLUGINS)
119 #if !defined(OS_LINUX)
120 extern int PluginMain(const content::MainFunctionParams
&);
122 extern int PpapiPluginMain(const MainFunctionParams
&);
123 extern int PpapiBrokerMain(const MainFunctionParams
&);
125 extern int RendererMain(const content::MainFunctionParams
&);
126 extern int UtilityMain(const MainFunctionParams
&);
127 } // namespace content
131 #if !defined(CHROME_MULTIPLE_DLL_CHILD)
132 base::LazyInstance
<ContentBrowserClient
>
133 g_empty_content_browser_client
= LAZY_INSTANCE_INITIALIZER
;
134 #endif // !CHROME_MULTIPLE_DLL_CHILD
136 #if !defined(OS_IOS) && !defined(CHROME_MULTIPLE_DLL_BROWSER)
137 base::LazyInstance
<ContentPluginClient
>
138 g_empty_content_plugin_client
= LAZY_INSTANCE_INITIALIZER
;
139 base::LazyInstance
<ContentRendererClient
>
140 g_empty_content_renderer_client
= LAZY_INSTANCE_INITIALIZER
;
141 base::LazyInstance
<ContentUtilityClient
>
142 g_empty_content_utility_client
= LAZY_INSTANCE_INITIALIZER
;
143 #endif // !OS_IOS && !CHROME_MULTIPLE_DLL_BROWSER
147 #endif // defined(OS_WIN)
149 #if defined(OS_POSIX) && !defined(OS_IOS)
151 // Setup signal-handling state: resanitize most signals, ignore SIGPIPE.
152 void SetupSignalHandlers() {
153 // Sanitise our signal handling state. Signals that were ignored by our
154 // parent will also be ignored by us. We also inherit our parent's sigmask.
155 sigset_t empty_signal_set
;
156 CHECK(0 == sigemptyset(&empty_signal_set
));
157 CHECK(0 == sigprocmask(SIG_SETMASK
, &empty_signal_set
, NULL
));
159 struct sigaction sigact
;
160 memset(&sigact
, 0, sizeof(sigact
));
161 sigact
.sa_handler
= SIG_DFL
;
162 static const int signals_to_reset
[] =
163 {SIGHUP
, SIGINT
, SIGQUIT
, SIGILL
, SIGABRT
, SIGFPE
, SIGSEGV
,
164 SIGALRM
, SIGTERM
, SIGCHLD
, SIGBUS
, SIGTRAP
}; // SIGPIPE is set below.
165 for (unsigned i
= 0; i
< arraysize(signals_to_reset
); i
++) {
166 CHECK(0 == sigaction(signals_to_reset
[i
], &sigact
, NULL
));
169 // Always ignore SIGPIPE. We check the return value of write().
170 CHECK(signal(SIGPIPE
, SIG_IGN
) != SIG_ERR
);
173 #endif // OS_POSIX && !OS_IOS
175 void CommonSubprocessInit(const std::string
& process_type
) {
177 // HACK: Let Windows know that we have started. This is needed to suppress
178 // the IDC_APPSTARTING cursor from being displayed for a prolonged period
179 // while a subprocess is starting.
180 PostThreadMessage(GetCurrentThreadId(), WM_NULL
, 0, 0);
182 PeekMessage(&msg
, NULL
, 0, 0, PM_REMOVE
);
184 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
185 // Various things break when you're using a locale where the decimal
186 // separator isn't a period. See e.g. bugs 22782 and 39964. For
187 // all processes except the browser process (where we call system
188 // APIs that may rely on the correct locale for formatting numbers
189 // when presenting them to the user), reset the locale for numeric
191 // Note that this is not correct for plugin processes -- they can
192 // surface UI -- but it's likely they get this wrong too so why not.
193 setlocale(LC_NUMERIC
, "C");
197 // Only needed on Windows for creating stats tables.
199 static base::ProcessId
GetBrowserPid(const base::CommandLine
& command_line
) {
200 base::ProcessId browser_pid
= base::GetCurrentProcId();
201 if (command_line
.HasSwitch(switches::kProcessChannelID
)) {
202 std::string channel_name
=
203 command_line
.GetSwitchValueASCII(switches::kProcessChannelID
);
206 base::StringToInt(channel_name
, &browser_pid_int
);
207 browser_pid
= static_cast<base::ProcessId
>(browser_pid_int
);
208 DCHECK_NE(browser_pid_int
, 0);
214 class ContentClientInitializer
{
216 static void Set(const std::string
& process_type
,
217 ContentMainDelegate
* delegate
) {
218 ContentClient
* content_client
= GetContentClient();
219 #if !defined(CHROME_MULTIPLE_DLL_CHILD)
220 if (process_type
.empty()) {
222 content_client
->browser_
= delegate
->CreateContentBrowserClient();
223 if (!content_client
->browser_
)
224 content_client
->browser_
= &g_empty_content_browser_client
.Get();
226 #endif // !CHROME_MULTIPLE_DLL_CHILD
228 #if !defined(OS_IOS) && !defined(CHROME_MULTIPLE_DLL_BROWSER)
229 if (process_type
== switches::kPluginProcess
||
230 process_type
== switches::kPpapiPluginProcess
) {
232 content_client
->plugin_
= delegate
->CreateContentPluginClient();
233 if (!content_client
->plugin_
)
234 content_client
->plugin_
= &g_empty_content_plugin_client
.Get();
235 // Single process not supported in split dll mode.
236 } else if (process_type
== switches::kRendererProcess
||
237 base::CommandLine::ForCurrentProcess()->HasSwitch(
238 switches::kSingleProcess
)) {
240 content_client
->renderer_
= delegate
->CreateContentRendererClient();
241 if (!content_client
->renderer_
)
242 content_client
->renderer_
= &g_empty_content_renderer_client
.Get();
245 if (process_type
== switches::kUtilityProcess
||
246 base::CommandLine::ForCurrentProcess()->HasSwitch(
247 switches::kSingleProcess
)) {
249 content_client
->utility_
= delegate
->CreateContentUtilityClient();
250 // TODO(scottmg): http://crbug.com/237249 Should be in _child.
251 if (!content_client
->utility_
)
252 content_client
->utility_
= &g_empty_content_utility_client
.Get();
254 #endif // !OS_IOS && !CHROME_MULTIPLE_DLL_BROWSER
258 // We dispatch to a process-type-specific FooMain() based on a command-line
259 // flag. This struct is used to build a table of (flag, main function) pairs.
260 struct MainFunction
{
262 int (*function
)(const MainFunctionParams
&);
265 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
266 // On platforms that use the zygote, we have a special subset of
267 // subprocesses that are launched via the zygote. This function
268 // fills in some process-launching bits around ZygoteMain().
269 // Returns the exit code of the subprocess.
270 int RunZygote(const MainFunctionParams
& main_function_params
,
271 ContentMainDelegate
* delegate
) {
272 static const MainFunction kMainFunctions
[] = {
273 { switches::kRendererProcess
, RendererMain
},
274 #if defined(ENABLE_PLUGINS)
275 { switches::kPpapiPluginProcess
, PpapiPluginMain
},
277 { switches::kUtilityProcess
, UtilityMain
},
280 ScopedVector
<ZygoteForkDelegate
> zygote_fork_delegates
;
282 delegate
->ZygoteStarting(&zygote_fork_delegates
);
283 // Each Renderer we spawn will re-attempt initialization of the media
284 // libraries, at which point failure will be detected and handled, so
285 // we do not need to cope with initialization failures here.
286 base::FilePath media_path
;
287 if (PathService::Get(DIR_MEDIA_LIBS
, &media_path
))
288 media::InitializeMediaLibrary(media_path
);
291 // This function call can return multiple times, once per fork().
292 if (!ZygoteMain(main_function_params
, zygote_fork_delegates
.Pass()))
295 if (delegate
) delegate
->ZygoteForked();
297 // Zygote::HandleForkRequest may have reallocated the command
298 // line so update it here with the new version.
299 const base::CommandLine
& command_line
=
300 *base::CommandLine::ForCurrentProcess();
301 std::string process_type
=
302 command_line
.GetSwitchValueASCII(switches::kProcessType
);
303 ContentClientInitializer::Set(process_type
, delegate
);
305 MainFunctionParams
main_params(command_line
);
306 main_params
.zygote_child
= true;
308 for (size_t i
= 0; i
< arraysize(kMainFunctions
); ++i
) {
309 if (process_type
== kMainFunctions
[i
].name
)
310 return kMainFunctions
[i
].function(main_params
);
314 return delegate
->RunProcess(process_type
, main_params
);
316 NOTREACHED() << "Unknown zygote process type: " << process_type
;
319 #endif // defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
322 static void RegisterMainThreadFactories() {
323 #if !defined(CHROME_MULTIPLE_DLL_BROWSER) && !defined(CHROME_MULTIPLE_DLL_CHILD)
324 UtilityProcessHostImpl::RegisterUtilityMainThreadFactory(
325 CreateInProcessUtilityThread
);
326 RenderProcessHostImpl::RegisterRendererMainThreadFactory(
327 CreateInProcessRendererThread
);
328 GpuProcessHost::RegisterGpuMainThreadFactory(
329 CreateInProcessGpuThread
);
331 base::CommandLine
& command_line
= *base::CommandLine::ForCurrentProcess();
332 if (command_line
.HasSwitch(switches::kSingleProcess
)) {
334 "--single-process is not supported in chrome multiple dll browser.";
336 if (command_line
.HasSwitch(switches::kInProcessGPU
)) {
338 "--in-process-gpu is not supported in chrome multiple dll browser.";
340 #endif // !CHROME_MULTIPLE_DLL_BROWSER && !CHROME_MULTIPLE_DLL_CHILD
343 // Run the FooMain() for a given process type.
344 // If |process_type| is empty, runs BrowserMain().
345 // Returns the exit code for this process.
346 int RunNamedProcessTypeMain(
347 const std::string
& process_type
,
348 const MainFunctionParams
& main_function_params
,
349 ContentMainDelegate
* delegate
) {
350 static const MainFunction kMainFunctions
[] = {
351 #if !defined(CHROME_MULTIPLE_DLL_CHILD)
354 #if !defined(CHROME_MULTIPLE_DLL_BROWSER)
355 #if defined(ENABLE_PLUGINS)
356 #if !defined(OS_LINUX)
357 { switches::kPluginProcess
, PluginMain
},
359 { switches::kPpapiPluginProcess
, PpapiPluginMain
},
360 { switches::kPpapiBrokerProcess
, PpapiBrokerMain
},
361 #endif // ENABLE_PLUGINS
362 { switches::kUtilityProcess
, UtilityMain
},
363 { switches::kRendererProcess
, RendererMain
},
364 { switches::kGpuProcess
, GpuMain
},
365 #endif // !CHROME_MULTIPLE_DLL_BROWSER
368 RegisterMainThreadFactories();
370 for (size_t i
= 0; i
< arraysize(kMainFunctions
); ++i
) {
371 if (process_type
== kMainFunctions
[i
].name
) {
373 int exit_code
= delegate
->RunProcess(process_type
,
374 main_function_params
);
375 #if defined(OS_ANDROID)
376 // In Android's browser process, the negative exit code doesn't mean the
377 // default behavior should be used as the UI message loop is managed by
378 // the Java and the browser process's default behavior is always
380 if (process_type
.empty())
386 return kMainFunctions
[i
].function(main_function_params
);
390 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
391 // Zygote startup is special -- see RunZygote comments above
392 // for why we don't use ZygoteMain directly.
393 if (process_type
== switches::kZygoteProcess
)
394 return RunZygote(main_function_params
, delegate
);
397 // If it's a process we don't know about, the embedder should know.
399 return delegate
->RunProcess(process_type
, main_function_params
);
401 NOTREACHED() << "Unknown process type: " << process_type
;
406 class ContentMainRunnerImpl
: public ContentMainRunner
{
408 ContentMainRunnerImpl()
409 : is_initialized_(false),
411 completed_basic_startup_(false),
415 memset(&sandbox_info_
, 0, sizeof(sandbox_info_
));
419 ~ContentMainRunnerImpl() override
{
420 if (is_initialized_
&& !is_shutdown_
)
424 #if defined(USE_TCMALLOC)
425 static bool GetAllocatorWasteSizeThunk(size_t* size
) {
426 size_t heap_size
, allocated_bytes
, unmapped_bytes
;
427 MallocExtension
* ext
= MallocExtension::instance();
428 if (ext
->GetNumericProperty("generic.heap_size", &heap_size
) &&
429 ext
->GetNumericProperty("generic.current_allocated_bytes",
431 ext
->GetNumericProperty("tcmalloc.pageheap_unmapped_bytes",
433 *size
= heap_size
- allocated_bytes
- unmapped_bytes
;
440 static void GetStatsThunk(char* buffer
, int buffer_length
) {
441 MallocExtension::instance()->GetStats(buffer
, buffer_length
);
444 static void ReleaseFreeMemoryThunk() {
445 MallocExtension::instance()->ReleaseFreeMemory();
449 int Initialize(const ContentMainParams
& params
) override
{
450 ui_task_
= params
.ui_task
;
452 base::EnableTerminationOnOutOfMemory();
454 RegisterInvalidParamHandler();
455 ui::win::CreateATLModuleIfNeeded();
457 sandbox_info_
= *params
.sandbox_info
;
460 #if defined(OS_ANDROID)
461 // See note at the initialization of ExitManager, below; basically,
462 // only Android builds have the ctor/dtor handlers set up to use
463 // TRACE_EVENT right away.
464 TRACE_EVENT0("startup", "ContentMainRunnerImpl::Initialize");
467 // NOTE(willchan): One might ask why these TCMalloc-related calls are done
468 // here rather than in process_util_linux.cc with the definition of
469 // EnableTerminationOnOutOfMemory(). That's because base shouldn't have a
470 // dependency on TCMalloc. Really, we ought to have our allocator shim code
471 // implement this EnableTerminationOnOutOfMemory() function. Whateverz.
472 // This works for now.
473 #if !defined(OS_MACOSX) && defined(USE_TCMALLOC)
475 #if defined(TYPE_PROFILING)
476 base::type_profiler::InterceptFunctions::SetFunctions(
477 base::type_profiler::NewInterceptForTCMalloc
,
478 base::type_profiler::DeleteInterceptForTCMalloc
);
481 // For tcmalloc, we need to tell it to behave like new.
484 // On windows, we've already set these thunks up in _heap_init()
485 base::allocator::SetGetAllocatorWasteSizeFunction(
486 GetAllocatorWasteSizeThunk
);
487 base::allocator::SetGetStatsFunction(GetStatsThunk
);
488 base::allocator::SetReleaseFreeMemoryFunction(ReleaseFreeMemoryThunk
);
490 // Provide optional hook for monitoring allocation quantities on a
491 // per-thread basis. Only set the hook if the environment indicates this
492 // needs to be enabled.
493 const char* profiling
= getenv(tracked_objects::kAlternateProfilerTime
);
495 (atoi(profiling
) == tracked_objects::TIME_SOURCE_TYPE_TCMALLOC
)) {
496 tracked_objects::SetAlternateTimeSource(
497 MallocExtension::GetBytesAllocatedOnCurrentThread
,
498 tracked_objects::TIME_SOURCE_TYPE_TCMALLOC
);
500 #endif // !OS_MACOSX && USE_TCMALLOC
503 base::GlobalDescriptors
* g_fds
= base::GlobalDescriptors::GetInstance();
507 // - setlocale() is not supported.
508 // - We do not override the signal handlers so that we can get
509 // stack trace when crashing.
510 // - The ipc_fd is passed through the Java service.
511 // Thus, these are all disabled.
512 #if !defined(OS_ANDROID) && !defined(OS_IOS)
513 // Set C library locale to make sure CommandLine can parse argument values
514 // in correct encoding.
515 setlocale(LC_ALL
, "");
517 SetupSignalHandlers();
518 g_fds
->Set(kPrimaryIPCChannel
,
519 kPrimaryIPCChannel
+ base::GlobalDescriptors::kBaseDescriptor
);
520 #endif // !OS_ANDROID && !OS_IOS
522 #if defined(OS_LINUX) || defined(OS_OPENBSD)
523 g_fds
->Set(kCrashDumpSignal
,
524 kCrashDumpSignal
+ base::GlobalDescriptors::kBaseDescriptor
);
525 #endif // OS_LINUX || OS_OPENBSD
530 is_initialized_
= true;
531 delegate_
= params
.delegate
;
533 // The exit manager is in charge of calling the dtors of singleton objects.
534 // On Android, AtExitManager is set up when library is loaded.
535 // On iOS, it's set up in main(), which can't call directly through to here.
536 // A consequence of this is that you can't use the ctor/dtor-based
537 // TRACE_EVENT methods on Linux or iOS builds till after we set this up.
538 #if !defined(OS_ANDROID) && !defined(OS_IOS)
540 // When running browser tests, don't create a second AtExitManager as that
541 // interfers with shutdown when objects created before ContentMain is
542 // called are destructed when it returns.
543 exit_manager_
.reset(new base::AtExitManager
);
545 #endif // !OS_ANDROID && !OS_IOS
547 // Don't create this loop on iOS, since the outer loop is already handled
548 // and a loop that's destroyed in shutdown interleaves badly with the event
550 #if defined(OS_MACOSX) && !defined(OS_IOS)
551 // We need this pool for all the objects created before we get to the
552 // event loop, but we don't want to leave them hanging around until the
553 // app quits. Each "main" needs to flush this pool right before it goes into
554 // its main event loop to get rid of the cruft.
555 autorelease_pool_
.reset(new base::mac::ScopedNSAutoreleasePool());
559 // On Android, the command line is initialized when library is loaded and
560 // we have already started our TRACE_EVENT0.
561 #if !defined(OS_ANDROID)
562 // argc/argv are ignored on Windows and Android; see command_line.h for
565 const char** argv
= NULL
;
572 base::CommandLine::Init(argc
, argv
);
574 base::EnableTerminationOnHeapCorruption();
576 // TODO(yiyaoliu, vadimt): Remove this once crbug.com/453640 is fixed.
577 // Enable profiler recording right after command line is initialized so that
578 // browser startup can be instrumented.
579 if (delegate_
&& delegate_
->ShouldEnableProfilerRecording())
580 tracked_objects::ScopedTracker::Enable();
583 SetProcessTitleFromCommandLine(argv
);
585 #endif // !OS_ANDROID
588 if (delegate_
&& delegate_
->BasicStartupComplete(&exit_code
))
591 completed_basic_startup_
= true;
593 const base::CommandLine
& command_line
=
594 *base::CommandLine::ForCurrentProcess();
595 std::string process_type
=
596 command_line
.GetSwitchValueASCII(switches::kProcessType
);
599 // Initialize mojo here so that services can be registered.
604 bool init_device_scale_factor
= true;
605 if (command_line
.HasSwitch(switches::kDeviceScaleFactor
)) {
606 std::string scale_factor_string
= command_line
.GetSwitchValueASCII(
607 switches::kDeviceScaleFactor
);
608 double scale_factor
= 0;
609 if (base::StringToDouble(scale_factor_string
, &scale_factor
)) {
610 init_device_scale_factor
= false;
611 gfx::InitDeviceScaleFactor(scale_factor
);
614 if (init_device_scale_factor
)
615 gfx::InitDeviceScaleFactor(gfx::GetDPIScale());
618 if (!GetContentClient())
619 SetContentClient(&empty_content_client_
);
620 ContentClientInitializer::Set(process_type
, delegate_
);
623 // Route stdio to parent console (if any) or create one.
624 if (command_line
.HasSwitch(switches::kEnableLogging
))
625 base::RouteStdioToConsole();
628 // Enable startup tracing asap to avoid early TRACE_EVENT calls being
630 if (command_line
.HasSwitch(switches::kTraceStartup
)) {
631 base::trace_event::CategoryFilter
category_filter(
632 command_line
.GetSwitchValueASCII(switches::kTraceStartup
));
633 base::trace_event::TraceLog::GetInstance()->SetEnabled(
635 base::trace_event::TraceLog::RECORDING_MODE
,
636 base::trace_event::TraceOptions(
637 base::trace_event::RECORD_UNTIL_FULL
));
640 // Enable exporting of events to ETW if requested on the command line.
641 if (command_line
.HasSwitch(switches::kTraceExportEventsToETW
))
642 base::trace_event::TraceEventETWExport::EnableETWExport();
645 #if !defined(OS_ANDROID)
646 // Android tracing started at the beginning of the method.
647 // Other OSes have to wait till we get here in order for all the memory
648 // management setup to be completed.
649 TRACE_EVENT0("startup", "ContentMainRunnerImpl::Initialize");
650 #endif // !OS_ANDROID
652 #if defined(OS_MACOSX) && !defined(OS_IOS)
653 // We need to allocate the IO Ports before the Sandbox is initialized or
654 // the first instance of PowerMonitor is created.
655 // It's important not to allocate the ports for processes which don't
656 // register with the power monitor - see crbug.com/88867.
657 if (process_type
.empty() ||
659 delegate_
->ProcessRegistersWithSystemProcess(process_type
))) {
660 base::PowerMonitorDeviceSource::AllocateSystemIOPorts();
663 if (!process_type
.empty() &&
664 (!delegate_
|| delegate_
->ShouldSendMachPort(process_type
))) {
665 MachBroker::ChildSendTaskPortToParent();
667 #elif defined(OS_WIN)
668 SetupCRT(command_line
);
671 #if defined(OS_POSIX)
672 if (!process_type
.empty()) {
673 // When you hit Ctrl-C in a terminal running the browser
674 // process, a SIGINT is delivered to the entire process group.
675 // When debugging the browser process via gdb, gdb catches the
676 // SIGINT for the browser process (and dumps you back to the gdb
677 // console) but doesn't for the child processes, killing them.
678 // The fix is to have child processes ignore SIGINT; they'll die
679 // on their own when the browser process goes away.
681 // Note that we *can't* rely on BeingDebugged to catch this case because
682 // we are the child process, which is not being debugged.
683 // TODO(evanm): move this to some shared subprocess-init function.
684 if (!base::debug::BeingDebugged())
685 signal(SIGINT
, SIG_IGN
);
689 #if defined(USE_NSS_CERTS)
690 crypto::EarlySetupForNSSInit();
693 ui::RegisterPathProvider();
694 RegisterPathProvider();
695 RegisterContentSchemes(true);
697 #if defined(OS_ANDROID)
698 int icudata_fd
= g_fds
->MaybeGet(kAndroidICUDataDescriptor
);
699 if (icudata_fd
!= -1) {
700 auto icudata_region
= g_fds
->GetRegion(kAndroidICUDataDescriptor
);
701 CHECK(base::i18n::InitializeICUWithFileDescriptor(icudata_fd
,
704 CHECK(base::i18n::InitializeICU());
707 CHECK(base::i18n::InitializeICU());
710 base::StatisticsRecorder::Initialize();
712 #if defined(V8_USE_EXTERNAL_STARTUP_DATA)
713 #if defined(OS_POSIX) && !defined(OS_MACOSX)
714 #if !defined(OS_ANDROID)
715 // kV8NativesDataDescriptor and kV8SnapshotDataDescriptor could be shared
716 // with child processes via file descriptors. On Android they are set in
717 // ChildProcessService::InternalInitChildProcess, otherwise set them here.
718 if (command_line
.HasSwitch(switches::kV8NativesPassedByFD
)) {
720 kV8NativesDataDescriptor
,
721 kV8NativesDataDescriptor
+ base::GlobalDescriptors::kBaseDescriptor
);
723 if (command_line
.HasSwitch(switches::kV8SnapshotPassedByFD
)) {
725 kV8SnapshotDataDescriptor
,
726 kV8SnapshotDataDescriptor
+ base::GlobalDescriptors::kBaseDescriptor
);
728 #endif // !OS_ANDROID
729 int v8_natives_fd
= g_fds
->MaybeGet(kV8NativesDataDescriptor
);
730 int v8_snapshot_fd
= g_fds
->MaybeGet(kV8SnapshotDataDescriptor
);
731 if (v8_natives_fd
!= -1 && v8_snapshot_fd
!= -1) {
732 auto v8_natives_region
= g_fds
->GetRegion(kV8NativesDataDescriptor
);
733 auto v8_snapshot_region
= g_fds
->GetRegion(kV8SnapshotDataDescriptor
);
734 CHECK(gin::V8Initializer::LoadV8SnapshotFromFD(
735 v8_natives_fd
, v8_natives_region
.offset
, v8_natives_region
.size
,
736 v8_snapshot_fd
, v8_snapshot_region
.offset
, v8_snapshot_region
.size
));
738 CHECK(gin::V8Initializer::LoadV8Snapshot());
741 CHECK(gin::V8Initializer::LoadV8Snapshot());
742 #endif // OS_POSIX && !OS_MACOSX
743 #endif // V8_USE_EXTERNAL_STARTUP_DATA
746 delegate_
->PreSandboxStartup();
748 if (!process_type
.empty())
749 CommonSubprocessInit(process_type
);
752 CHECK(InitializeSandbox(params
.sandbox_info
));
753 #elif defined(OS_MACOSX) && !defined(OS_IOS)
754 if (process_type
== switches::kRendererProcess
||
755 process_type
== switches::kPpapiPluginProcess
||
756 (delegate_
&& delegate_
->DelaySandboxInitialization(process_type
))) {
757 // On OS X the renderer sandbox needs to be initialized later in the
758 // startup sequence in RendererMainPlatformDelegate::EnableSandbox().
760 CHECK(InitializeSandbox());
765 delegate_
->SandboxInitialized(process_type
);
767 // Return -1 to indicate no early termination.
772 DCHECK(is_initialized_
);
773 DCHECK(!is_shutdown_
);
774 const base::CommandLine
& command_line
=
775 *base::CommandLine::ForCurrentProcess();
776 std::string process_type
=
777 command_line
.GetSwitchValueASCII(switches::kProcessType
);
779 MainFunctionParams
main_params(command_line
);
780 main_params
.ui_task
= ui_task_
;
782 main_params
.sandbox_info
= &sandbox_info_
;
783 #elif defined(OS_MACOSX)
784 main_params
.autorelease_pool
= autorelease_pool_
.get();
788 return RunNamedProcessTypeMain(process_type
, main_params
, delegate_
);
794 void Shutdown() override
{
795 DCHECK(is_initialized_
);
796 DCHECK(!is_shutdown_
);
798 if (completed_basic_startup_
&& delegate_
) {
799 const base::CommandLine
& command_line
=
800 *base::CommandLine::ForCurrentProcess();
801 std::string process_type
=
802 command_line
.GetSwitchValueASCII(switches::kProcessType
);
804 delegate_
->ProcessExiting(process_type
);
808 #ifdef _CRTDBG_MAP_ALLOC
809 _CrtDumpMemoryLeaks();
810 #endif // _CRTDBG_MAP_ALLOC
813 #if defined(OS_MACOSX) && !defined(OS_IOS)
814 autorelease_pool_
.reset(NULL
);
817 exit_manager_
.reset(NULL
);
824 // True if the runner has been initialized.
825 bool is_initialized_
;
827 // True if the runner has been shut down.
830 // True if basic startup was completed.
831 bool completed_basic_startup_
;
833 // Used if the embedder doesn't set one.
834 ContentClient empty_content_client_
;
836 // The delegate will outlive this object.
837 ContentMainDelegate
* delegate_
;
839 scoped_ptr
<base::AtExitManager
> exit_manager_
;
841 sandbox::SandboxInterfaceInfo sandbox_info_
;
842 #elif defined(OS_MACOSX)
843 scoped_ptr
<base::mac::ScopedNSAutoreleasePool
> autorelease_pool_
;
846 base::Closure
* ui_task_
;
848 DISALLOW_COPY_AND_ASSIGN(ContentMainRunnerImpl
);
852 ContentMainRunner
* ContentMainRunner::Create() {
853 return new ContentMainRunnerImpl();
856 } // namespace content