Remove Chromium plumbing for fixed-position-creates-stacking-context
[chromium-blink-merge.git] / content / app / content_main_runner.cc
blob24a528929e5acd2c7bfaa4ade8cca1bc32ebb621
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/debug/trace_event.h"
14 #include "base/files/file_path.h"
15 #include "base/i18n/icu_util.h"
16 #include "base/lazy_instance.h"
17 #include "base/logging.h"
18 #include "base/memory/scoped_ptr.h"
19 #include "base/memory/scoped_vector.h"
20 #include "base/metrics/stats_table.h"
21 #include "base/path_service.h"
22 #include "base/process/launch.h"
23 #include "base/process/memory.h"
24 #include "base/process/process_handle.h"
25 #include "base/profiler/alternate_timer.h"
26 #include "base/strings/string_number_conversions.h"
27 #include "base/strings/string_util.h"
28 #include "base/strings/stringprintf.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"
52 #include "ui/gfx/win/dpi.h"
54 #if defined(USE_TCMALLOC)
55 #include "third_party/tcmalloc/chromium/src/gperftools/malloc_extension.h"
56 #if defined(TYPE_PROFILING)
57 #include "base/allocator/type_profiler.h"
58 #include "base/allocator/type_profiler_tcmalloc.h"
59 #endif
60 #endif
62 #if !defined(OS_IOS)
63 #include "content/app/mojo/mojo_init.h"
64 #include "content/browser/gpu/gpu_process_host.h"
65 #include "content/browser/renderer_host/render_process_host_impl.h"
66 #include "content/browser/utility_process_host_impl.h"
67 #include "content/public/plugin/content_plugin_client.h"
68 #include "content/public/renderer/content_renderer_client.h"
69 #include "content/public/utility/content_utility_client.h"
70 #endif
72 #if defined(OS_WIN)
73 #include <atlbase.h>
74 #include <atlapp.h>
75 #include <malloc.h>
76 #include <cstring>
77 #elif defined(OS_MACOSX)
78 #include "base/mac/scoped_nsautorelease_pool.h"
79 #if !defined(OS_IOS)
80 #include "base/power_monitor/power_monitor_device_source.h"
81 #include "content/browser/mach_broker_mac.h"
82 #include "content/common/sandbox_init_mac.h"
83 #endif // !OS_IOS
84 #endif // OS_WIN
86 #if defined(OS_POSIX)
87 #include <signal.h>
89 #include "base/posix/global_descriptors.h"
90 #include "content/public/common/content_descriptors.h"
92 #if !defined(OS_MACOSX)
93 #include "content/public/common/zygote_fork_delegate_linux.h"
94 #endif
95 #if !defined(OS_MACOSX) && !defined(OS_ANDROID)
96 #include "content/zygote/zygote_main.h"
97 #endif
99 #endif // OS_POSIX
101 #if !defined(OS_MACOSX) && defined(USE_TCMALLOC)
102 extern "C" {
103 int tc_set_new_mode(int mode);
105 #endif
107 namespace content {
108 extern int GpuMain(const content::MainFunctionParams&);
109 #if defined(ENABLE_PLUGINS)
110 #if !defined(OS_LINUX)
111 extern int PluginMain(const content::MainFunctionParams&);
112 #endif
113 extern int PpapiPluginMain(const MainFunctionParams&);
114 extern int PpapiBrokerMain(const MainFunctionParams&);
115 #endif
116 extern int RendererMain(const content::MainFunctionParams&);
117 extern int UtilityMain(const MainFunctionParams&);
118 extern int WorkerMain(const MainFunctionParams&);
119 } // namespace content
121 namespace content {
123 base::LazyInstance<ContentBrowserClient>
124 g_empty_content_browser_client = LAZY_INSTANCE_INITIALIZER;
125 #if !defined(OS_IOS) && !defined(CHROME_MULTIPLE_DLL_BROWSER)
126 base::LazyInstance<ContentPluginClient>
127 g_empty_content_plugin_client = LAZY_INSTANCE_INITIALIZER;
128 base::LazyInstance<ContentRendererClient>
129 g_empty_content_renderer_client = LAZY_INSTANCE_INITIALIZER;
130 base::LazyInstance<ContentUtilityClient>
131 g_empty_content_utility_client = LAZY_INSTANCE_INITIALIZER;
132 #endif // !OS_IOS && !CHROME_MULTIPLE_DLL_BROWSER
134 #if defined(OS_WIN)
136 static CAppModule _Module;
138 #endif // defined(OS_WIN)
140 #if defined(OS_POSIX) && !defined(OS_IOS)
142 // Setup signal-handling state: resanitize most signals, ignore SIGPIPE.
143 void SetupSignalHandlers() {
144 // Sanitise our signal handling state. Signals that were ignored by our
145 // parent will also be ignored by us. We also inherit our parent's sigmask.
146 sigset_t empty_signal_set;
147 CHECK(0 == sigemptyset(&empty_signal_set));
148 CHECK(0 == sigprocmask(SIG_SETMASK, &empty_signal_set, NULL));
150 struct sigaction sigact;
151 memset(&sigact, 0, sizeof(sigact));
152 sigact.sa_handler = SIG_DFL;
153 static const int signals_to_reset[] =
154 {SIGHUP, SIGINT, SIGQUIT, SIGILL, SIGABRT, SIGFPE, SIGSEGV,
155 SIGALRM, SIGTERM, SIGCHLD, SIGBUS, SIGTRAP}; // SIGPIPE is set below.
156 for (unsigned i = 0; i < arraysize(signals_to_reset); i++) {
157 CHECK(0 == sigaction(signals_to_reset[i], &sigact, NULL));
160 // Always ignore SIGPIPE. We check the return value of write().
161 CHECK(signal(SIGPIPE, SIG_IGN) != SIG_ERR);
164 #endif // OS_POSIX && !OS_IOS
166 void CommonSubprocessInit(const std::string& process_type) {
167 #if defined(OS_WIN)
168 // HACK: Let Windows know that we have started. This is needed to suppress
169 // the IDC_APPSTARTING cursor from being displayed for a prolonged period
170 // while a subprocess is starting.
171 PostThreadMessage(GetCurrentThreadId(), WM_NULL, 0, 0);
172 MSG msg;
173 PeekMessage(&msg, NULL, 0, 0, PM_REMOVE);
174 #endif
175 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
176 // Various things break when you're using a locale where the decimal
177 // separator isn't a period. See e.g. bugs 22782 and 39964. For
178 // all processes except the browser process (where we call system
179 // APIs that may rely on the correct locale for formatting numbers
180 // when presenting them to the user), reset the locale for numeric
181 // formatting.
182 // Note that this is not correct for plugin processes -- they can
183 // surface UI -- but it's likely they get this wrong too so why not.
184 setlocale(LC_NUMERIC, "C");
185 #endif
188 // Only needed on Windows for creating stats tables.
189 #if defined(OS_WIN)
190 static base::ProcessId GetBrowserPid(const CommandLine& command_line) {
191 base::ProcessId browser_pid = base::GetCurrentProcId();
192 if (command_line.HasSwitch(switches::kProcessChannelID)) {
193 std::string channel_name =
194 command_line.GetSwitchValueASCII(switches::kProcessChannelID);
196 int browser_pid_int;
197 base::StringToInt(channel_name, &browser_pid_int);
198 browser_pid = static_cast<base::ProcessId>(browser_pid_int);
199 DCHECK_NE(browser_pid_int, 0);
201 return browser_pid;
203 #endif
205 static void InitializeStatsTable(const CommandLine& command_line) {
206 // Initialize the Stats Counters table. With this initialized,
207 // the StatsViewer can be utilized to read counters outside of
208 // Chrome. These lines can be commented out to effectively turn
209 // counters 'off'. The table is created and exists for the life
210 // of the process. It is not cleaned up.
211 if (command_line.HasSwitch(switches::kEnableStatsTable)) {
212 // NOTIMPLEMENTED: we probably need to shut this down correctly to avoid
213 // leaking shared memory regions on posix platforms.
214 #if defined(OS_POSIX)
215 // Stats table is in the global file descriptors table on Posix.
216 base::GlobalDescriptors* global_descriptors =
217 base::GlobalDescriptors::GetInstance();
218 base::FileDescriptor table_ident;
219 if (global_descriptors->MaybeGet(kStatsTableSharedMemFd) != -1) {
220 // Open the shared memory file descriptor passed by the browser process.
221 table_ident = base::FileDescriptor(
222 global_descriptors->Get(kStatsTableSharedMemFd), false);
224 #elif defined(OS_WIN)
225 // Stats table is in a named segment on Windows. Use the PID to make this
226 // unique on the system.
227 std::string table_ident =
228 base::StringPrintf("%s-%u", kStatsFilename,
229 static_cast<unsigned int>(GetBrowserPid(command_line)));
230 #endif
231 base::StatsTable* stats_table =
232 new base::StatsTable(table_ident, kStatsMaxThreads, kStatsMaxCounters);
233 base::StatsTable::set_current(stats_table);
237 class ContentClientInitializer {
238 public:
239 static void Set(const std::string& process_type,
240 ContentMainDelegate* delegate) {
241 ContentClient* content_client = GetContentClient();
242 if (process_type.empty()) {
243 if (delegate)
244 content_client->browser_ = delegate->CreateContentBrowserClient();
245 if (!content_client->browser_)
246 content_client->browser_ = &g_empty_content_browser_client.Get();
249 #if !defined(OS_IOS) && !defined(CHROME_MULTIPLE_DLL_BROWSER)
250 if (process_type == switches::kPluginProcess ||
251 process_type == switches::kPpapiPluginProcess) {
252 if (delegate)
253 content_client->plugin_ = delegate->CreateContentPluginClient();
254 if (!content_client->plugin_)
255 content_client->plugin_ = &g_empty_content_plugin_client.Get();
256 // Single process not supported in split dll mode.
257 } else if (process_type == switches::kRendererProcess ||
258 CommandLine::ForCurrentProcess()->HasSwitch(
259 switches::kSingleProcess)) {
260 if (delegate)
261 content_client->renderer_ = delegate->CreateContentRendererClient();
262 if (!content_client->renderer_)
263 content_client->renderer_ = &g_empty_content_renderer_client.Get();
266 if (process_type == switches::kUtilityProcess ||
267 CommandLine::ForCurrentProcess()->HasSwitch(
268 switches::kSingleProcess)) {
269 if (delegate)
270 content_client->utility_ = delegate->CreateContentUtilityClient();
271 // TODO(scottmg): http://crbug.com/237249 Should be in _child.
272 if (!content_client->utility_)
273 content_client->utility_ = &g_empty_content_utility_client.Get();
275 #endif // !OS_IOS && !CHROME_MULTIPLE_DLL_BROWSER
279 // We dispatch to a process-type-specific FooMain() based on a command-line
280 // flag. This struct is used to build a table of (flag, main function) pairs.
281 struct MainFunction {
282 const char* name;
283 int (*function)(const MainFunctionParams&);
286 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
287 // On platforms that use the zygote, we have a special subset of
288 // subprocesses that are launched via the zygote. This function
289 // fills in some process-launching bits around ZygoteMain().
290 // Returns the exit code of the subprocess.
291 int RunZygote(const MainFunctionParams& main_function_params,
292 ContentMainDelegate* delegate) {
293 static const MainFunction kMainFunctions[] = {
294 { switches::kRendererProcess, RendererMain },
295 { switches::kWorkerProcess, WorkerMain },
296 #if defined(ENABLE_PLUGINS)
297 { switches::kPpapiPluginProcess, PpapiPluginMain },
298 #endif
299 { switches::kUtilityProcess, UtilityMain },
302 ScopedVector<ZygoteForkDelegate> zygote_fork_delegates;
303 if (delegate) {
304 delegate->ZygoteStarting(&zygote_fork_delegates);
305 // Each Renderer we spawn will re-attempt initialization of the media
306 // libraries, at which point failure will be detected and handled, so
307 // we do not need to cope with initialization failures here.
308 base::FilePath media_path;
309 if (PathService::Get(DIR_MEDIA_LIBS, &media_path))
310 media::InitializeMediaLibrary(media_path);
313 // This function call can return multiple times, once per fork().
314 if (!ZygoteMain(main_function_params, zygote_fork_delegates.Pass()))
315 return 1;
317 if (delegate) delegate->ZygoteForked();
319 // Zygote::HandleForkRequest may have reallocated the command
320 // line so update it here with the new version.
321 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
322 std::string process_type =
323 command_line.GetSwitchValueASCII(switches::kProcessType);
324 ContentClientInitializer::Set(process_type, delegate);
326 // The StatsTable must be initialized in each process; we already
327 // initialized for the browser process, now we need to initialize
328 // within the new processes as well.
329 InitializeStatsTable(command_line);
331 MainFunctionParams main_params(command_line);
333 for (size_t i = 0; i < arraysize(kMainFunctions); ++i) {
334 if (process_type == kMainFunctions[i].name)
335 return kMainFunctions[i].function(main_params);
338 if (delegate)
339 return delegate->RunProcess(process_type, main_params);
341 NOTREACHED() << "Unknown zygote process type: " << process_type;
342 return 1;
344 #endif // defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
346 #if !defined(OS_IOS)
347 static void RegisterMainThreadFactories() {
348 #if !defined(CHROME_MULTIPLE_DLL_BROWSER)
349 UtilityProcessHostImpl::RegisterUtilityMainThreadFactory(
350 CreateInProcessUtilityThread);
351 RenderProcessHostImpl::RegisterRendererMainThreadFactory(
352 CreateInProcessRendererThread);
353 GpuProcessHost::RegisterGpuMainThreadFactory(
354 CreateInProcessGpuThread);
355 #else
356 CommandLine& command_line = *CommandLine::ForCurrentProcess();
357 if (command_line.HasSwitch(switches::kSingleProcess)) {
358 LOG(FATAL) <<
359 "--single-process is not supported in chrome multiple dll browser.";
361 if (command_line.HasSwitch(switches::kInProcessGPU)) {
362 LOG(FATAL) <<
363 "--in-process-gpu is not supported in chrome multiple dll browser.";
365 #endif
368 // Run the FooMain() for a given process type.
369 // If |process_type| is empty, runs BrowserMain().
370 // Returns the exit code for this process.
371 int RunNamedProcessTypeMain(
372 const std::string& process_type,
373 const MainFunctionParams& main_function_params,
374 ContentMainDelegate* delegate) {
375 static const MainFunction kMainFunctions[] = {
376 #if !defined(CHROME_MULTIPLE_DLL_CHILD)
377 { "", BrowserMain },
378 #endif
379 #if !defined(CHROME_MULTIPLE_DLL_BROWSER)
380 #if defined(ENABLE_PLUGINS)
381 #if !defined(OS_LINUX)
382 { switches::kPluginProcess, PluginMain },
383 #endif
384 { switches::kWorkerProcess, WorkerMain },
385 { switches::kPpapiPluginProcess, PpapiPluginMain },
386 { switches::kPpapiBrokerProcess, PpapiBrokerMain },
387 #endif // ENABLE_PLUGINS
388 { switches::kUtilityProcess, UtilityMain },
389 { switches::kRendererProcess, RendererMain },
390 { switches::kGpuProcess, GpuMain },
391 #endif // !CHROME_MULTIPLE_DLL_BROWSER
394 RegisterMainThreadFactories();
396 for (size_t i = 0; i < arraysize(kMainFunctions); ++i) {
397 if (process_type == kMainFunctions[i].name) {
398 if (delegate) {
399 int exit_code = delegate->RunProcess(process_type,
400 main_function_params);
401 #if defined(OS_ANDROID)
402 // In Android's browser process, the negative exit code doesn't mean the
403 // default behavior should be used as the UI message loop is managed by
404 // the Java and the browser process's default behavior is always
405 // overridden.
406 if (process_type.empty())
407 return exit_code;
408 #endif
409 if (exit_code >= 0)
410 return exit_code;
412 return kMainFunctions[i].function(main_function_params);
416 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
417 // Zygote startup is special -- see RunZygote comments above
418 // for why we don't use ZygoteMain directly.
419 if (process_type == switches::kZygoteProcess)
420 return RunZygote(main_function_params, delegate);
421 #endif
423 // If it's a process we don't know about, the embedder should know.
424 if (delegate)
425 return delegate->RunProcess(process_type, main_function_params);
427 NOTREACHED() << "Unknown process type: " << process_type;
428 return 1;
430 #endif // !OS_IOS
432 class ContentMainRunnerImpl : public ContentMainRunner {
433 public:
434 ContentMainRunnerImpl()
435 : is_initialized_(false),
436 is_shutdown_(false),
437 completed_basic_startup_(false),
438 delegate_(NULL),
439 ui_task_(NULL) {
440 #if defined(OS_WIN)
441 memset(&sandbox_info_, 0, sizeof(sandbox_info_));
442 #endif
445 virtual ~ContentMainRunnerImpl() {
446 if (is_initialized_ && !is_shutdown_)
447 Shutdown();
450 #if defined(USE_TCMALLOC)
451 static bool GetAllocatorWasteSizeThunk(size_t* size) {
452 size_t heap_size, allocated_bytes, unmapped_bytes;
453 MallocExtension* ext = MallocExtension::instance();
454 if (ext->GetNumericProperty("generic.heap_size", &heap_size) &&
455 ext->GetNumericProperty("generic.current_allocated_bytes",
456 &allocated_bytes) &&
457 ext->GetNumericProperty("tcmalloc.pageheap_unmapped_bytes",
458 &unmapped_bytes)) {
459 *size = heap_size - allocated_bytes - unmapped_bytes;
460 return true;
462 DCHECK(false);
463 return false;
466 static void GetStatsThunk(char* buffer, int buffer_length) {
467 MallocExtension::instance()->GetStats(buffer, buffer_length);
470 static void ReleaseFreeMemoryThunk() {
471 MallocExtension::instance()->ReleaseFreeMemory();
473 #endif
475 virtual int Initialize(const ContentMainParams& params) OVERRIDE {
476 ui_task_ = params.ui_task;
478 #if defined(OS_WIN)
479 RegisterInvalidParamHandler();
480 _Module.Init(NULL, static_cast<HINSTANCE>(params.instance));
482 sandbox_info_ = *params.sandbox_info;
483 #else // !OS_WIN
485 #if defined(OS_ANDROID)
486 // See note at the initialization of ExitManager, below; basically,
487 // only Android builds have the ctor/dtor handlers set up to use
488 // TRACE_EVENT right away.
489 TRACE_EVENT0("startup", "ContentMainRunnerImpl::Initialize");
490 #endif // OS_ANDROID
492 // NOTE(willchan): One might ask why these TCMalloc-related calls are done
493 // here rather than in process_util_linux.cc with the definition of
494 // EnableTerminationOnOutOfMemory(). That's because base shouldn't have a
495 // dependency on TCMalloc. Really, we ought to have our allocator shim code
496 // implement this EnableTerminationOnOutOfMemory() function. Whateverz.
497 // This works for now.
498 #if !defined(OS_MACOSX) && defined(USE_TCMALLOC)
500 #if defined(TYPE_PROFILING)
501 base::type_profiler::InterceptFunctions::SetFunctions(
502 base::type_profiler::NewInterceptForTCMalloc,
503 base::type_profiler::DeleteInterceptForTCMalloc);
504 #endif
506 // For tcmalloc, we need to tell it to behave like new.
507 tc_set_new_mode(1);
509 // On windows, we've already set these thunks up in _heap_init()
510 base::allocator::SetGetAllocatorWasteSizeFunction(
511 GetAllocatorWasteSizeThunk);
512 base::allocator::SetGetStatsFunction(GetStatsThunk);
513 base::allocator::SetReleaseFreeMemoryFunction(ReleaseFreeMemoryThunk);
515 // Provide optional hook for monitoring allocation quantities on a
516 // per-thread basis. Only set the hook if the environment indicates this
517 // needs to be enabled.
518 const char* profiling = getenv(tracked_objects::kAlternateProfilerTime);
519 if (profiling &&
520 (atoi(profiling) == tracked_objects::TIME_SOURCE_TYPE_TCMALLOC)) {
521 tracked_objects::SetAlternateTimeSource(
522 MallocExtension::GetBytesAllocatedOnCurrentThread,
523 tracked_objects::TIME_SOURCE_TYPE_TCMALLOC);
525 #endif // !OS_MACOSX && USE_TCMALLOC
527 // On Android,
528 // - setlocale() is not supported.
529 // - We do not override the signal handlers so that we can get
530 // stack trace when crashing.
531 // - The ipc_fd is passed through the Java service.
532 // Thus, these are all disabled.
533 #if !defined(OS_ANDROID) && !defined(OS_IOS)
534 // Set C library locale to make sure CommandLine can parse argument values
535 // in correct encoding.
536 setlocale(LC_ALL, "");
538 SetupSignalHandlers();
540 base::GlobalDescriptors* g_fds = base::GlobalDescriptors::GetInstance();
541 g_fds->Set(kPrimaryIPCChannel,
542 kPrimaryIPCChannel + base::GlobalDescriptors::kBaseDescriptor);
543 #endif // !OS_ANDROID && !OS_IOS
545 #if defined(OS_LINUX) || defined(OS_OPENBSD)
546 g_fds->Set(kCrashDumpSignal,
547 kCrashDumpSignal + base::GlobalDescriptors::kBaseDescriptor);
548 #endif
550 #endif // !OS_WIN
552 is_initialized_ = true;
553 delegate_ = params.delegate;
555 base::EnableTerminationOnHeapCorruption();
556 base::EnableTerminationOnOutOfMemory();
558 // The exit manager is in charge of calling the dtors of singleton objects.
559 // On Android, AtExitManager is set up when library is loaded.
560 // On iOS, it's set up in main(), which can't call directly through to here.
561 // A consequence of this is that you can't use the ctor/dtor-based
562 // TRACE_EVENT methods on Linux or iOS builds till after we set this up.
563 #if !defined(OS_ANDROID) && !defined(OS_IOS)
564 if (!ui_task_) {
565 // When running browser tests, don't create a second AtExitManager as that
566 // interfers with shutdown when objects created before ContentMain is
567 // called are destructed when it returns.
568 exit_manager_.reset(new base::AtExitManager);
570 #endif // !OS_ANDROID && !OS_IOS
572 #if defined(OS_MACOSX)
573 // We need this pool for all the objects created before we get to the
574 // event loop, but we don't want to leave them hanging around until the
575 // app quits. Each "main" needs to flush this pool right before it goes into
576 // its main event loop to get rid of the cruft.
577 autorelease_pool_.reset(new base::mac::ScopedNSAutoreleasePool());
578 #endif
580 // On Android, the command line is initialized when library is loaded and
581 // we have already started our TRACE_EVENT0.
582 #if !defined(OS_ANDROID)
583 // argc/argv are ignored on Windows and Android; see command_line.h for
584 // details.
585 int argc = 0;
586 const char** argv = NULL;
588 #if !defined(OS_WIN)
589 argc = params.argc;
590 argv = params.argv;
591 #endif
593 CommandLine::Init(argc, argv);
595 #if !defined(OS_IOS)
596 SetProcessTitleFromCommandLine(argv);
597 #endif
598 #endif // !OS_ANDROID
600 int exit_code;
601 if (delegate_ && delegate_->BasicStartupComplete(&exit_code))
602 return exit_code;
604 completed_basic_startup_ = true;
606 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
607 std::string process_type =
608 command_line.GetSwitchValueASCII(switches::kProcessType);
610 #if !defined(OS_IOS)
611 // Initialize mojo here so that services can be registered.
612 InitializeMojo();
613 #endif
615 if (!GetContentClient())
616 SetContentClient(&empty_content_client_);
617 ContentClientInitializer::Set(process_type, delegate_);
619 #if defined(OS_WIN)
620 // Route stdio to parent console (if any) or create one.
621 if (command_line.HasSwitch(switches::kEnableLogging))
622 base::RouteStdioToConsole();
623 #endif
625 // Enable startup tracing asap to avoid early TRACE_EVENT calls being
626 // ignored.
627 if (command_line.HasSwitch(switches::kTraceStartup)) {
628 base::debug::CategoryFilter category_filter(
629 command_line.GetSwitchValueASCII(switches::kTraceStartup));
630 base::debug::TraceLog::GetInstance()->SetEnabled(
631 category_filter,
632 base::debug::TraceLog::RECORDING_MODE,
633 base::debug::TraceLog::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 if (command_line.HasSwitch(switches::kEnableHighResolutionTime))
659 base::TimeTicks::SetNowIsHighResNowIfSupported();
661 SetupCRT(command_line);
662 #endif
664 #if defined(OS_POSIX)
665 if (!process_type.empty()) {
666 // When you hit Ctrl-C in a terminal running the browser
667 // process, a SIGINT is delivered to the entire process group.
668 // When debugging the browser process via gdb, gdb catches the
669 // SIGINT for the browser process (and dumps you back to the gdb
670 // console) but doesn't for the child processes, killing them.
671 // The fix is to have child processes ignore SIGINT; they'll die
672 // on their own when the browser process goes away.
674 // Note that we *can't* rely on BeingDebugged to catch this case because
675 // we are the child process, which is not being debugged.
676 // TODO(evanm): move this to some shared subprocess-init function.
677 if (!base::debug::BeingDebugged())
678 signal(SIGINT, SIG_IGN);
680 #endif
682 #if defined(USE_NSS)
683 crypto::EarlySetupForNSSInit();
684 #endif
686 ui::RegisterPathProvider();
687 RegisterPathProvider();
688 RegisterContentSchemes(true);
690 CHECK(base::i18n::InitializeICU());
692 InitializeStatsTable(command_line);
694 if (delegate_)
695 delegate_->PreSandboxStartup();
697 if (!process_type.empty())
698 CommonSubprocessInit(process_type);
700 #if defined(OS_WIN)
701 CHECK(InitializeSandbox(params.sandbox_info));
702 #elif defined(OS_MACOSX) && !defined(OS_IOS)
703 if (process_type == switches::kRendererProcess ||
704 process_type == switches::kPpapiPluginProcess ||
705 (delegate_ && delegate_->DelaySandboxInitialization(process_type))) {
706 // On OS X the renderer sandbox needs to be initialized later in the
707 // startup sequence in RendererMainPlatformDelegate::EnableSandbox().
708 } else {
709 CHECK(InitializeSandbox());
711 #endif
713 if (delegate_)
714 delegate_->SandboxInitialized(process_type);
716 // Return -1 to indicate no early termination.
717 return -1;
720 virtual int Run() OVERRIDE {
721 DCHECK(is_initialized_);
722 DCHECK(!is_shutdown_);
723 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
724 std::string process_type =
725 command_line.GetSwitchValueASCII(switches::kProcessType);
727 MainFunctionParams main_params(command_line);
728 main_params.ui_task = ui_task_;
729 #if defined(OS_WIN)
730 main_params.sandbox_info = &sandbox_info_;
731 #elif defined(OS_MACOSX)
732 main_params.autorelease_pool = autorelease_pool_.get();
733 #endif
735 #if !defined(OS_IOS)
736 return RunNamedProcessTypeMain(process_type, main_params, delegate_);
737 #else
738 return 1;
739 #endif
742 virtual void Shutdown() OVERRIDE {
743 DCHECK(is_initialized_);
744 DCHECK(!is_shutdown_);
746 if (completed_basic_startup_ && delegate_) {
747 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
748 std::string process_type =
749 command_line.GetSwitchValueASCII(switches::kProcessType);
751 delegate_->ProcessExiting(process_type);
754 #if !defined(OS_IOS)
755 ShutdownMojo();
756 #endif
758 #if defined(OS_WIN)
759 #ifdef _CRTDBG_MAP_ALLOC
760 _CrtDumpMemoryLeaks();
761 #endif // _CRTDBG_MAP_ALLOC
763 _Module.Term();
764 #endif // OS_WIN
766 #if defined(OS_MACOSX)
767 autorelease_pool_.reset(NULL);
768 #endif
770 exit_manager_.reset(NULL);
772 delegate_ = NULL;
773 is_shutdown_ = true;
776 private:
777 // True if the runner has been initialized.
778 bool is_initialized_;
780 // True if the runner has been shut down.
781 bool is_shutdown_;
783 // True if basic startup was completed.
784 bool completed_basic_startup_;
786 // Used if the embedder doesn't set one.
787 ContentClient empty_content_client_;
789 // The delegate will outlive this object.
790 ContentMainDelegate* delegate_;
792 scoped_ptr<base::AtExitManager> exit_manager_;
793 #if defined(OS_WIN)
794 sandbox::SandboxInterfaceInfo sandbox_info_;
795 #elif defined(OS_MACOSX)
796 scoped_ptr<base::mac::ScopedNSAutoreleasePool> autorelease_pool_;
797 #endif
799 base::Closure* ui_task_;
801 DISALLOW_COPY_AND_ASSIGN(ContentMainRunnerImpl);
804 // static
805 ContentMainRunner* ContentMainRunner::Create() {
806 return new ContentMainRunnerImpl();
809 } // namespace content