Re-subimission of https://codereview.chromium.org/1041213003/
[chromium-blink-merge.git] / content / app / content_main_runner.cc
blobf14c6ebff1d40ebe0b4bcc097a45968ce1e2416d
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"
7 #include <stdlib.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/path_service.h"
20 #include "base/process/launch.h"
21 #include "base/process/memory.h"
22 #include "base/process/process_handle.h"
23 #include "base/profiler/alternate_timer.h"
24 #include "base/profiler/scoped_tracker.h"
25 #include "base/strings/string_number_conversions.h"
26 #include "base/strings/string_util.h"
27 #include "base/strings/stringprintf.h"
28 #include "base/trace_event/trace_event.h"
29 #include "content/browser/browser_main.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/common/content_client.h"
38 #include "content/public/common/content_constants.h"
39 #include "content/public/common/content_paths.h"
40 #include "content/public/common/content_switches.h"
41 #include "content/public/common/main_function_params.h"
42 #include "content/public/common/sandbox_init.h"
43 #include "content/renderer/in_process_renderer_thread.h"
44 #include "content/utility/in_process_utility_thread.h"
45 #include "crypto/nss_util.h"
46 #include "ipc/ipc_descriptors.h"
47 #include "ipc/ipc_switches.h"
48 #include "media/base/media.h"
49 #include "sandbox/win/src/sandbox_types.h"
50 #include "ui/base/ui_base_paths.h"
51 #include "ui/base/ui_base_switches.h"
53 #ifdef V8_USE_EXTERNAL_STARTUP_DATA
54 #include "gin/v8_initializer.h"
55 #endif
57 #if defined(USE_TCMALLOC)
58 #include "third_party/tcmalloc/chromium/src/gperftools/malloc_extension.h"
59 #if defined(TYPE_PROFILING)
60 #include "base/allocator/type_profiler.h"
61 #include "base/allocator/type_profiler_tcmalloc.h"
62 #endif
63 #endif
65 #if !defined(OS_IOS)
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"
73 #endif
75 #if defined(OS_WIN)
76 #include <malloc.h>
77 #include <cstring>
79 #include "base/strings/string_number_conversions.h"
80 #include "ui/base/win/atl_module.h"
81 #include "ui/gfx/win/dpi.h"
82 #elif defined(OS_MACOSX)
83 #include "base/mac/scoped_nsautorelease_pool.h"
84 #if !defined(OS_IOS)
85 #include "base/power_monitor/power_monitor_device_source.h"
86 #include "content/browser/mach_broker_mac.h"
87 #include "content/common/sandbox_init_mac.h"
88 #endif // !OS_IOS
89 #endif // OS_WIN
91 #if defined(OS_POSIX)
92 #include <signal.h>
94 #include "base/posix/global_descriptors.h"
95 #include "content/public/common/content_descriptors.h"
97 #if !defined(OS_MACOSX)
98 #include "content/public/common/content_descriptors.h"
99 #include "content/public/common/zygote_fork_delegate_linux.h"
100 #endif
101 #if !defined(OS_MACOSX) && !defined(OS_ANDROID)
102 #include "content/zygote/zygote_main.h"
103 #endif
105 #endif // OS_POSIX
107 #if !defined(OS_MACOSX) && defined(USE_TCMALLOC)
108 extern "C" {
109 int tc_set_new_mode(int mode);
111 #endif
113 namespace content {
114 extern int GpuMain(const content::MainFunctionParams&);
115 #if defined(ENABLE_PLUGINS)
116 #if !defined(OS_LINUX)
117 extern int PluginMain(const content::MainFunctionParams&);
118 #endif
119 extern int PpapiPluginMain(const MainFunctionParams&);
120 extern int PpapiBrokerMain(const MainFunctionParams&);
121 #endif
122 extern int RendererMain(const content::MainFunctionParams&);
123 extern int UtilityMain(const MainFunctionParams&);
124 } // namespace content
126 namespace content {
128 #if !defined(CHROME_MULTIPLE_DLL_CHILD)
129 base::LazyInstance<ContentBrowserClient>
130 g_empty_content_browser_client = LAZY_INSTANCE_INITIALIZER;
131 #endif // !CHROME_MULTIPLE_DLL_CHILD
133 #if !defined(OS_IOS) && !defined(CHROME_MULTIPLE_DLL_BROWSER)
134 base::LazyInstance<ContentPluginClient>
135 g_empty_content_plugin_client = LAZY_INSTANCE_INITIALIZER;
136 base::LazyInstance<ContentRendererClient>
137 g_empty_content_renderer_client = LAZY_INSTANCE_INITIALIZER;
138 base::LazyInstance<ContentUtilityClient>
139 g_empty_content_utility_client = LAZY_INSTANCE_INITIALIZER;
140 #endif // !OS_IOS && !CHROME_MULTIPLE_DLL_BROWSER
142 #if defined(OS_WIN)
144 #endif // defined(OS_WIN)
146 #if defined(OS_POSIX) && !defined(OS_IOS)
148 // Setup signal-handling state: resanitize most signals, ignore SIGPIPE.
149 void SetupSignalHandlers() {
150 // Sanitise our signal handling state. Signals that were ignored by our
151 // parent will also be ignored by us. We also inherit our parent's sigmask.
152 sigset_t empty_signal_set;
153 CHECK(0 == sigemptyset(&empty_signal_set));
154 CHECK(0 == sigprocmask(SIG_SETMASK, &empty_signal_set, NULL));
156 struct sigaction sigact;
157 memset(&sigact, 0, sizeof(sigact));
158 sigact.sa_handler = SIG_DFL;
159 static const int signals_to_reset[] =
160 {SIGHUP, SIGINT, SIGQUIT, SIGILL, SIGABRT, SIGFPE, SIGSEGV,
161 SIGALRM, SIGTERM, SIGCHLD, SIGBUS, SIGTRAP}; // SIGPIPE is set below.
162 for (unsigned i = 0; i < arraysize(signals_to_reset); i++) {
163 CHECK(0 == sigaction(signals_to_reset[i], &sigact, NULL));
166 // Always ignore SIGPIPE. We check the return value of write().
167 CHECK(signal(SIGPIPE, SIG_IGN) != SIG_ERR);
170 #endif // OS_POSIX && !OS_IOS
172 void CommonSubprocessInit(const std::string& process_type) {
173 #if defined(OS_WIN)
174 // HACK: Let Windows know that we have started. This is needed to suppress
175 // the IDC_APPSTARTING cursor from being displayed for a prolonged period
176 // while a subprocess is starting.
177 PostThreadMessage(GetCurrentThreadId(), WM_NULL, 0, 0);
178 MSG msg;
179 PeekMessage(&msg, NULL, 0, 0, PM_REMOVE);
180 #endif
181 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
182 // Various things break when you're using a locale where the decimal
183 // separator isn't a period. See e.g. bugs 22782 and 39964. For
184 // all processes except the browser process (where we call system
185 // APIs that may rely on the correct locale for formatting numbers
186 // when presenting them to the user), reset the locale for numeric
187 // formatting.
188 // Note that this is not correct for plugin processes -- they can
189 // surface UI -- but it's likely they get this wrong too so why not.
190 setlocale(LC_NUMERIC, "C");
191 #endif
194 // Only needed on Windows for creating stats tables.
195 #if defined(OS_WIN)
196 static base::ProcessId GetBrowserPid(const base::CommandLine& command_line) {
197 base::ProcessId browser_pid = base::GetCurrentProcId();
198 if (command_line.HasSwitch(switches::kProcessChannelID)) {
199 std::string channel_name =
200 command_line.GetSwitchValueASCII(switches::kProcessChannelID);
202 int browser_pid_int;
203 base::StringToInt(channel_name, &browser_pid_int);
204 browser_pid = static_cast<base::ProcessId>(browser_pid_int);
205 DCHECK_NE(browser_pid_int, 0);
207 return browser_pid;
209 #endif
211 class ContentClientInitializer {
212 public:
213 static void Set(const std::string& process_type,
214 ContentMainDelegate* delegate) {
215 ContentClient* content_client = GetContentClient();
216 #if !defined(CHROME_MULTIPLE_DLL_CHILD)
217 if (process_type.empty()) {
218 if (delegate)
219 content_client->browser_ = delegate->CreateContentBrowserClient();
220 if (!content_client->browser_)
221 content_client->browser_ = &g_empty_content_browser_client.Get();
223 #endif // !CHROME_MULTIPLE_DLL_CHILD
225 #if !defined(OS_IOS) && !defined(CHROME_MULTIPLE_DLL_BROWSER)
226 if (process_type == switches::kPluginProcess ||
227 process_type == switches::kPpapiPluginProcess) {
228 if (delegate)
229 content_client->plugin_ = delegate->CreateContentPluginClient();
230 if (!content_client->plugin_)
231 content_client->plugin_ = &g_empty_content_plugin_client.Get();
232 // Single process not supported in split dll mode.
233 } else if (process_type == switches::kRendererProcess ||
234 base::CommandLine::ForCurrentProcess()->HasSwitch(
235 switches::kSingleProcess)) {
236 if (delegate)
237 content_client->renderer_ = delegate->CreateContentRendererClient();
238 if (!content_client->renderer_)
239 content_client->renderer_ = &g_empty_content_renderer_client.Get();
242 if (process_type == switches::kUtilityProcess ||
243 base::CommandLine::ForCurrentProcess()->HasSwitch(
244 switches::kSingleProcess)) {
245 if (delegate)
246 content_client->utility_ = delegate->CreateContentUtilityClient();
247 // TODO(scottmg): http://crbug.com/237249 Should be in _child.
248 if (!content_client->utility_)
249 content_client->utility_ = &g_empty_content_utility_client.Get();
251 #endif // !OS_IOS && !CHROME_MULTIPLE_DLL_BROWSER
255 // We dispatch to a process-type-specific FooMain() based on a command-line
256 // flag. This struct is used to build a table of (flag, main function) pairs.
257 struct MainFunction {
258 const char* name;
259 int (*function)(const MainFunctionParams&);
262 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
263 // On platforms that use the zygote, we have a special subset of
264 // subprocesses that are launched via the zygote. This function
265 // fills in some process-launching bits around ZygoteMain().
266 // Returns the exit code of the subprocess.
267 int RunZygote(const MainFunctionParams& main_function_params,
268 ContentMainDelegate* delegate) {
269 static const MainFunction kMainFunctions[] = {
270 { switches::kRendererProcess, RendererMain },
271 #if defined(ENABLE_PLUGINS)
272 { switches::kPpapiPluginProcess, PpapiPluginMain },
273 #endif
274 { switches::kUtilityProcess, UtilityMain },
277 ScopedVector<ZygoteForkDelegate> zygote_fork_delegates;
278 if (delegate) {
279 delegate->ZygoteStarting(&zygote_fork_delegates);
280 // Each Renderer we spawn will re-attempt initialization of the media
281 // libraries, at which point failure will be detected and handled, so
282 // we do not need to cope with initialization failures here.
283 base::FilePath media_path;
284 if (PathService::Get(DIR_MEDIA_LIBS, &media_path))
285 media::InitializeMediaLibrary(media_path);
288 // This function call can return multiple times, once per fork().
289 if (!ZygoteMain(main_function_params, zygote_fork_delegates.Pass()))
290 return 1;
292 if (delegate) delegate->ZygoteForked();
294 // Zygote::HandleForkRequest may have reallocated the command
295 // line so update it here with the new version.
296 const base::CommandLine& command_line =
297 *base::CommandLine::ForCurrentProcess();
298 std::string process_type =
299 command_line.GetSwitchValueASCII(switches::kProcessType);
300 ContentClientInitializer::Set(process_type, delegate);
302 MainFunctionParams main_params(command_line);
303 main_params.zygote_child = true;
305 for (size_t i = 0; i < arraysize(kMainFunctions); ++i) {
306 if (process_type == kMainFunctions[i].name)
307 return kMainFunctions[i].function(main_params);
310 if (delegate)
311 return delegate->RunProcess(process_type, main_params);
313 NOTREACHED() << "Unknown zygote process type: " << process_type;
314 return 1;
316 #endif // defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
318 #if !defined(OS_IOS)
319 static void RegisterMainThreadFactories() {
320 #if !defined(CHROME_MULTIPLE_DLL_BROWSER) && !defined(CHROME_MULTIPLE_DLL_CHILD)
321 UtilityProcessHostImpl::RegisterUtilityMainThreadFactory(
322 CreateInProcessUtilityThread);
323 RenderProcessHostImpl::RegisterRendererMainThreadFactory(
324 CreateInProcessRendererThread);
325 GpuProcessHost::RegisterGpuMainThreadFactory(
326 CreateInProcessGpuThread);
327 #else
328 base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess();
329 if (command_line.HasSwitch(switches::kSingleProcess)) {
330 LOG(FATAL) <<
331 "--single-process is not supported in chrome multiple dll browser.";
333 if (command_line.HasSwitch(switches::kInProcessGPU)) {
334 LOG(FATAL) <<
335 "--in-process-gpu is not supported in chrome multiple dll browser.";
337 #endif // !CHROME_MULTIPLE_DLL_BROWSER && !CHROME_MULTIPLE_DLL_CHILD
340 // Run the FooMain() for a given process type.
341 // If |process_type| is empty, runs BrowserMain().
342 // Returns the exit code for this process.
343 int RunNamedProcessTypeMain(
344 const std::string& process_type,
345 const MainFunctionParams& main_function_params,
346 ContentMainDelegate* delegate) {
347 static const MainFunction kMainFunctions[] = {
348 #if !defined(CHROME_MULTIPLE_DLL_CHILD)
349 { "", BrowserMain },
350 #endif
351 #if !defined(CHROME_MULTIPLE_DLL_BROWSER)
352 #if defined(ENABLE_PLUGINS)
353 #if !defined(OS_LINUX)
354 { switches::kPluginProcess, PluginMain },
355 #endif
356 { switches::kPpapiPluginProcess, PpapiPluginMain },
357 { switches::kPpapiBrokerProcess, PpapiBrokerMain },
358 #endif // ENABLE_PLUGINS
359 { switches::kUtilityProcess, UtilityMain },
360 { switches::kRendererProcess, RendererMain },
361 { switches::kGpuProcess, GpuMain },
362 #endif // !CHROME_MULTIPLE_DLL_BROWSER
365 RegisterMainThreadFactories();
367 for (size_t i = 0; i < arraysize(kMainFunctions); ++i) {
368 if (process_type == kMainFunctions[i].name) {
369 if (delegate) {
370 int exit_code = delegate->RunProcess(process_type,
371 main_function_params);
372 #if defined(OS_ANDROID)
373 // In Android's browser process, the negative exit code doesn't mean the
374 // default behavior should be used as the UI message loop is managed by
375 // the Java and the browser process's default behavior is always
376 // overridden.
377 if (process_type.empty())
378 return exit_code;
379 #endif
380 if (exit_code >= 0)
381 return exit_code;
383 return kMainFunctions[i].function(main_function_params);
387 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
388 // Zygote startup is special -- see RunZygote comments above
389 // for why we don't use ZygoteMain directly.
390 if (process_type == switches::kZygoteProcess)
391 return RunZygote(main_function_params, delegate);
392 #endif
394 // If it's a process we don't know about, the embedder should know.
395 if (delegate)
396 return delegate->RunProcess(process_type, main_function_params);
398 NOTREACHED() << "Unknown process type: " << process_type;
399 return 1;
401 #endif // !OS_IOS
403 class ContentMainRunnerImpl : public ContentMainRunner {
404 public:
405 ContentMainRunnerImpl()
406 : is_initialized_(false),
407 is_shutdown_(false),
408 completed_basic_startup_(false),
409 delegate_(NULL),
410 ui_task_(NULL) {
411 #if defined(OS_WIN)
412 memset(&sandbox_info_, 0, sizeof(sandbox_info_));
413 #endif
416 ~ContentMainRunnerImpl() override {
417 if (is_initialized_ && !is_shutdown_)
418 Shutdown();
421 #if defined(USE_TCMALLOC)
422 static bool GetAllocatorWasteSizeThunk(size_t* size) {
423 size_t heap_size, allocated_bytes, unmapped_bytes;
424 MallocExtension* ext = MallocExtension::instance();
425 if (ext->GetNumericProperty("generic.heap_size", &heap_size) &&
426 ext->GetNumericProperty("generic.current_allocated_bytes",
427 &allocated_bytes) &&
428 ext->GetNumericProperty("tcmalloc.pageheap_unmapped_bytes",
429 &unmapped_bytes)) {
430 *size = heap_size - allocated_bytes - unmapped_bytes;
431 return true;
433 DCHECK(false);
434 return false;
437 static void GetStatsThunk(char* buffer, int buffer_length) {
438 MallocExtension::instance()->GetStats(buffer, buffer_length);
441 static void ReleaseFreeMemoryThunk() {
442 MallocExtension::instance()->ReleaseFreeMemory();
444 #endif
446 int Initialize(const ContentMainParams& params) override {
447 ui_task_ = params.ui_task;
449 base::EnableTerminationOnOutOfMemory();
450 #if defined(OS_WIN)
451 RegisterInvalidParamHandler();
452 ui::win::CreateATLModuleIfNeeded();
454 sandbox_info_ = *params.sandbox_info;
455 #else // !OS_WIN
457 #if defined(OS_ANDROID)
458 // See note at the initialization of ExitManager, below; basically,
459 // only Android builds have the ctor/dtor handlers set up to use
460 // TRACE_EVENT right away.
461 TRACE_EVENT0("startup", "ContentMainRunnerImpl::Initialize");
462 #endif // OS_ANDROID
464 // NOTE(willchan): One might ask why these TCMalloc-related calls are done
465 // here rather than in process_util_linux.cc with the definition of
466 // EnableTerminationOnOutOfMemory(). That's because base shouldn't have a
467 // dependency on TCMalloc. Really, we ought to have our allocator shim code
468 // implement this EnableTerminationOnOutOfMemory() function. Whateverz.
469 // This works for now.
470 #if !defined(OS_MACOSX) && defined(USE_TCMALLOC)
472 #if defined(TYPE_PROFILING)
473 base::type_profiler::InterceptFunctions::SetFunctions(
474 base::type_profiler::NewInterceptForTCMalloc,
475 base::type_profiler::DeleteInterceptForTCMalloc);
476 #endif
478 // For tcmalloc, we need to tell it to behave like new.
479 tc_set_new_mode(1);
481 // On windows, we've already set these thunks up in _heap_init()
482 base::allocator::SetGetAllocatorWasteSizeFunction(
483 GetAllocatorWasteSizeThunk);
484 base::allocator::SetGetStatsFunction(GetStatsThunk);
485 base::allocator::SetReleaseFreeMemoryFunction(ReleaseFreeMemoryThunk);
487 // Provide optional hook for monitoring allocation quantities on a
488 // per-thread basis. Only set the hook if the environment indicates this
489 // needs to be enabled.
490 const char* profiling = getenv(tracked_objects::kAlternateProfilerTime);
491 if (profiling &&
492 (atoi(profiling) == tracked_objects::TIME_SOURCE_TYPE_TCMALLOC)) {
493 tracked_objects::SetAlternateTimeSource(
494 MallocExtension::GetBytesAllocatedOnCurrentThread,
495 tracked_objects::TIME_SOURCE_TYPE_TCMALLOC);
497 #endif // !OS_MACOSX && USE_TCMALLOC
499 #if !defined(OS_IOS)
500 base::GlobalDescriptors* g_fds = base::GlobalDescriptors::GetInstance();
501 #endif
503 // On Android,
504 // - setlocale() is not supported.
505 // - We do not override the signal handlers so that we can get
506 // stack trace when crashing.
507 // - The ipc_fd is passed through the Java service.
508 // Thus, these are all disabled.
509 #if !defined(OS_ANDROID) && !defined(OS_IOS)
510 // Set C library locale to make sure CommandLine can parse argument values
511 // in correct encoding.
512 setlocale(LC_ALL, "");
514 SetupSignalHandlers();
515 g_fds->Set(kPrimaryIPCChannel,
516 kPrimaryIPCChannel + base::GlobalDescriptors::kBaseDescriptor);
517 #endif // !OS_ANDROID && !OS_IOS
519 #if defined(OS_LINUX) || defined(OS_OPENBSD)
520 g_fds->Set(kCrashDumpSignal,
521 kCrashDumpSignal + base::GlobalDescriptors::kBaseDescriptor);
522 #endif // OS_LINUX || OS_OPENBSD
525 #endif // !OS_WIN
527 is_initialized_ = true;
528 delegate_ = params.delegate;
530 // The exit manager is in charge of calling the dtors of singleton objects.
531 // On Android, AtExitManager is set up when library is loaded.
532 // On iOS, it's set up in main(), which can't call directly through to here.
533 // A consequence of this is that you can't use the ctor/dtor-based
534 // TRACE_EVENT methods on Linux or iOS builds till after we set this up.
535 #if !defined(OS_ANDROID) && !defined(OS_IOS)
536 if (!ui_task_) {
537 // When running browser tests, don't create a second AtExitManager as that
538 // interfers with shutdown when objects created before ContentMain is
539 // called are destructed when it returns.
540 exit_manager_.reset(new base::AtExitManager);
542 #endif // !OS_ANDROID && !OS_IOS
544 // Don't create this loop on iOS, since the outer loop is already handled
545 // and a loop that's destroyed in shutdown interleaves badly with the event
546 // loop pool on iOS.
547 #if defined(OS_MACOSX) && !defined(OS_IOS)
548 // We need this pool for all the objects created before we get to the
549 // event loop, but we don't want to leave them hanging around until the
550 // app quits. Each "main" needs to flush this pool right before it goes into
551 // its main event loop to get rid of the cruft.
552 autorelease_pool_.reset(new base::mac::ScopedNSAutoreleasePool());
553 #endif
555 // On Android, the command line is initialized when library is loaded and
556 // we have already started our TRACE_EVENT0.
557 #if !defined(OS_ANDROID)
558 // argc/argv are ignored on Windows and Android; see command_line.h for
559 // details.
560 int argc = 0;
561 const char** argv = NULL;
563 #if !defined(OS_WIN)
564 argc = params.argc;
565 argv = params.argv;
566 #endif
568 base::CommandLine::Init(argc, argv);
570 base::EnableTerminationOnHeapCorruption();
572 // TODO(yiyaoliu, vadimt): Remove this once crbug.com/453640 is fixed.
573 // Enable profiler recording right after command line is initialized so that
574 // browser startup can be instrumented.
575 if (delegate_ && delegate_->ShouldEnableProfilerRecording())
576 tracked_objects::ScopedTracker::Enable();
578 #if !defined(OS_IOS)
579 SetProcessTitleFromCommandLine(argv);
580 #endif
581 #endif // !OS_ANDROID
583 int exit_code = 0;
584 if (delegate_ && delegate_->BasicStartupComplete(&exit_code))
585 return exit_code;
587 completed_basic_startup_ = true;
589 const base::CommandLine& command_line =
590 *base::CommandLine::ForCurrentProcess();
591 std::string process_type =
592 command_line.GetSwitchValueASCII(switches::kProcessType);
594 #if !defined(OS_IOS)
595 // Initialize mojo here so that services can be registered.
596 InitializeMojo();
597 #endif
599 #if defined(OS_WIN)
600 bool init_device_scale_factor = true;
601 if (command_line.HasSwitch(switches::kDeviceScaleFactor)) {
602 std::string scale_factor_string = command_line.GetSwitchValueASCII(
603 switches::kDeviceScaleFactor);
604 double scale_factor = 0;
605 if (base::StringToDouble(scale_factor_string, &scale_factor)) {
606 init_device_scale_factor = false;
607 gfx::InitDeviceScaleFactor(scale_factor);
610 if (init_device_scale_factor)
611 gfx::InitDeviceScaleFactor(gfx::GetDPIScale());
612 #endif
614 if (!GetContentClient())
615 SetContentClient(&empty_content_client_);
616 ContentClientInitializer::Set(process_type, delegate_);
618 #if defined(OS_WIN)
619 // Route stdio to parent console (if any) or create one.
620 if (command_line.HasSwitch(switches::kEnableLogging))
621 base::RouteStdioToConsole();
622 #endif
624 // Enable startup tracing asap to avoid early TRACE_EVENT calls being
625 // ignored.
626 if (command_line.HasSwitch(switches::kTraceStartup)) {
627 base::trace_event::CategoryFilter category_filter(
628 command_line.GetSwitchValueASCII(switches::kTraceStartup));
629 base::trace_event::TraceLog::GetInstance()->SetEnabled(
630 category_filter,
631 base::trace_event::TraceLog::RECORDING_MODE,
632 base::trace_event::TraceOptions(
633 base::trace_event::RECORD_UNTIL_FULL));
635 #if !defined(OS_ANDROID)
636 // Android tracing started at the beginning of the method.
637 // Other OSes have to wait till we get here in order for all the memory
638 // management setup to be completed.
639 TRACE_EVENT0("startup", "ContentMainRunnerImpl::Initialize");
640 #endif // !OS_ANDROID
642 #if defined(OS_MACOSX) && !defined(OS_IOS)
643 // We need to allocate the IO Ports before the Sandbox is initialized or
644 // the first instance of PowerMonitor is created.
645 // It's important not to allocate the ports for processes which don't
646 // register with the power monitor - see crbug.com/88867.
647 if (process_type.empty() ||
648 (delegate_ &&
649 delegate_->ProcessRegistersWithSystemProcess(process_type))) {
650 base::PowerMonitorDeviceSource::AllocateSystemIOPorts();
653 if (!process_type.empty() &&
654 (!delegate_ || delegate_->ShouldSendMachPort(process_type))) {
655 MachBroker::ChildSendTaskPortToParent();
657 #elif defined(OS_WIN)
658 SetupCRT(command_line);
659 #endif
661 #if defined(OS_POSIX)
662 if (!process_type.empty()) {
663 // When you hit Ctrl-C in a terminal running the browser
664 // process, a SIGINT is delivered to the entire process group.
665 // When debugging the browser process via gdb, gdb catches the
666 // SIGINT for the browser process (and dumps you back to the gdb
667 // console) but doesn't for the child processes, killing them.
668 // The fix is to have child processes ignore SIGINT; they'll die
669 // on their own when the browser process goes away.
671 // Note that we *can't* rely on BeingDebugged to catch this case because
672 // we are the child process, which is not being debugged.
673 // TODO(evanm): move this to some shared subprocess-init function.
674 if (!base::debug::BeingDebugged())
675 signal(SIGINT, SIG_IGN);
677 #endif
679 #if defined(USE_NSS)
680 crypto::EarlySetupForNSSInit();
681 #endif
683 ui::RegisterPathProvider();
684 RegisterPathProvider();
685 RegisterContentSchemes(true);
687 #if defined(OS_ANDROID)
688 int icudata_fd = g_fds->MaybeGet(kAndroidICUDataDescriptor);
689 if (icudata_fd != -1) {
690 auto icudata_region = g_fds->GetRegion(kAndroidICUDataDescriptor);
691 CHECK(base::i18n::InitializeICUWithFileDescriptor(icudata_fd,
692 icudata_region));
693 } else {
694 CHECK(base::i18n::InitializeICU());
696 #else
697 CHECK(base::i18n::InitializeICU());
698 #endif // OS_ANDROID
700 #if defined(V8_USE_EXTERNAL_STARTUP_DATA)
701 #if defined(OS_POSIX) && !defined(OS_MACOSX)
702 #if !defined(OS_ANDROID)
703 // kV8NativesDataDescriptor and kV8SnapshotDataDescriptor are shared with
704 // child processes. On Android they are set in
705 // ChildProcessService::InternalInitChildProcess, otherwise set them here.
706 if (!process_type.empty() && process_type != switches::kZygoteProcess
707 && process_type != "service") {
708 g_fds->Set(
709 kV8NativesDataDescriptor,
710 kV8NativesDataDescriptor + base::GlobalDescriptors::kBaseDescriptor);
711 g_fds->Set(
712 kV8SnapshotDataDescriptor,
713 kV8SnapshotDataDescriptor + base::GlobalDescriptors::kBaseDescriptor);
715 #endif // !OS_ANDROID
716 int v8_natives_fd = g_fds->MaybeGet(kV8NativesDataDescriptor);
717 int v8_snapshot_fd = g_fds->MaybeGet(kV8SnapshotDataDescriptor);
718 if (v8_natives_fd != -1 && v8_snapshot_fd != -1) {
719 auto v8_natives_region = g_fds->GetRegion(kV8NativesDataDescriptor);
720 auto v8_snapshot_region = g_fds->GetRegion(kV8SnapshotDataDescriptor);
721 CHECK(gin::V8Initializer::LoadV8SnapshotFromFD(
722 v8_natives_fd, v8_natives_region.offset, v8_natives_region.size,
723 v8_snapshot_fd, v8_snapshot_region.offset, v8_snapshot_region.size));
724 } else {
725 CHECK(gin::V8Initializer::LoadV8Snapshot());
727 #else
728 CHECK(gin::V8Initializer::LoadV8Snapshot());
729 #endif // OS_POSIX && !OS_MACOSX
730 #endif // V8_USE_EXTERNAL_STARTUP_DATA
732 if (delegate_)
733 delegate_->PreSandboxStartup();
735 if (!process_type.empty())
736 CommonSubprocessInit(process_type);
738 #if defined(OS_WIN)
739 CHECK(InitializeSandbox(params.sandbox_info));
740 #elif defined(OS_MACOSX) && !defined(OS_IOS)
741 if (process_type == switches::kRendererProcess ||
742 process_type == switches::kPpapiPluginProcess ||
743 (delegate_ && delegate_->DelaySandboxInitialization(process_type))) {
744 // On OS X the renderer sandbox needs to be initialized later in the
745 // startup sequence in RendererMainPlatformDelegate::EnableSandbox().
746 } else {
747 CHECK(InitializeSandbox());
749 #endif
751 if (delegate_)
752 delegate_->SandboxInitialized(process_type);
754 // Return -1 to indicate no early termination.
755 return -1;
758 int Run() override {
759 DCHECK(is_initialized_);
760 DCHECK(!is_shutdown_);
761 const base::CommandLine& command_line =
762 *base::CommandLine::ForCurrentProcess();
763 std::string process_type =
764 command_line.GetSwitchValueASCII(switches::kProcessType);
766 MainFunctionParams main_params(command_line);
767 main_params.ui_task = ui_task_;
768 #if defined(OS_WIN)
769 main_params.sandbox_info = &sandbox_info_;
770 #elif defined(OS_MACOSX)
771 main_params.autorelease_pool = autorelease_pool_.get();
772 #endif
774 #if !defined(OS_IOS)
775 return RunNamedProcessTypeMain(process_type, main_params, delegate_);
776 #else
777 return 1;
778 #endif
781 void Shutdown() override {
782 DCHECK(is_initialized_);
783 DCHECK(!is_shutdown_);
785 if (completed_basic_startup_ && delegate_) {
786 const base::CommandLine& command_line =
787 *base::CommandLine::ForCurrentProcess();
788 std::string process_type =
789 command_line.GetSwitchValueASCII(switches::kProcessType);
791 delegate_->ProcessExiting(process_type);
794 #if defined(OS_WIN)
795 #ifdef _CRTDBG_MAP_ALLOC
796 _CrtDumpMemoryLeaks();
797 #endif // _CRTDBG_MAP_ALLOC
798 #endif // OS_WIN
800 #if defined(OS_MACOSX) && !defined(OS_IOS)
801 autorelease_pool_.reset(NULL);
802 #endif
804 exit_manager_.reset(NULL);
806 delegate_ = NULL;
807 is_shutdown_ = true;
810 private:
811 // True if the runner has been initialized.
812 bool is_initialized_;
814 // True if the runner has been shut down.
815 bool is_shutdown_;
817 // True if basic startup was completed.
818 bool completed_basic_startup_;
820 // Used if the embedder doesn't set one.
821 ContentClient empty_content_client_;
823 // The delegate will outlive this object.
824 ContentMainDelegate* delegate_;
826 scoped_ptr<base::AtExitManager> exit_manager_;
827 #if defined(OS_WIN)
828 sandbox::SandboxInterfaceInfo sandbox_info_;
829 #elif defined(OS_MACOSX)
830 scoped_ptr<base::mac::ScopedNSAutoreleasePool> autorelease_pool_;
831 #endif
833 base::Closure* ui_task_;
835 DISALLOW_COPY_AND_ASSIGN(ContentMainRunnerImpl);
838 // static
839 ContentMainRunner* ContentMainRunner::Create() {
840 return new ContentMainRunnerImpl();
843 } // namespace content