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