Upstream version 6.35.121.0
[platform/framework/web/crosswalk.git] / src / content / app / content_main_runner.cc
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.
4
5 #include "content/public/app/content_main_runner.h"
6
7 #include <stdlib.h>
8
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/metrics/stats_table.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/strings/string_number_conversions.h"
26 #include "base/strings/string_util.h"
27 #include "base/strings/stringprintf.h"
28 #include "content/browser/browser_main.h"
29 #include "content/browser/gpu/gpu_process_host.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/browser/render_process_host.h"
38 #include "content/public/browser/utility_process_host.h"
39 #include "content/public/common/content_client.h"
40 #include "content/public/common/content_constants.h"
41 #include "content/public/common/content_paths.h"
42 #include "content/public/common/content_switches.h"
43 #include "content/public/common/main_function_params.h"
44 #include "content/public/common/sandbox_init.h"
45 #include "content/renderer/in_process_renderer_thread.h"
46 #include "content/utility/in_process_utility_thread.h"
47 #include "crypto/nss_util.h"
48 #include "ipc/ipc_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"
53 #include "ui/gfx/win/dpi.h"
54
55 #if defined(USE_TCMALLOC)
56 #include "third_party/tcmalloc/chromium/src/gperftools/malloc_extension.h"
57 #if defined(TYPE_PROFILING)
58 #include "base/allocator/type_profiler.h"
59 #include "base/allocator/type_profiler_tcmalloc.h"
60 #endif
61 #endif
62
63 #if !defined(OS_IOS)
64 #include "content/public/plugin/content_plugin_client.h"
65 #include "content/public/renderer/content_renderer_client.h"
66 #include "content/public/utility/content_utility_client.h"
67 #endif
68
69 #if defined(OS_WIN)
70 #include <atlbase.h>
71 #include <atlapp.h>
72 #include <malloc.h>
73 #include <cstring>
74 #elif defined(OS_MACOSX)
75 #include "base/mac/scoped_nsautorelease_pool.h"
76 #if !defined(OS_IOS)
77 #include "base/power_monitor/power_monitor_device_source.h"
78 #include "content/browser/mach_broker_mac.h"
79 #include "content/common/sandbox_init_mac.h"
80 #endif  // !OS_IOS
81 #endif  // OS_WIN
82
83 #if defined(OS_POSIX)
84 #include <signal.h>
85
86 #include "base/posix/global_descriptors.h"
87 #include "content/public/common/content_descriptors.h"
88
89 #if !defined(OS_MACOSX)
90 #include "content/public/common/zygote_fork_delegate_linux.h"
91 #endif
92 #if !defined(OS_MACOSX) && !defined(OS_ANDROID)
93 #include "content/zygote/zygote_main.h"
94 #endif
95
96 #endif  // OS_POSIX
97
98 #if !defined(OS_MACOSX) && defined(USE_TCMALLOC)
99 extern "C" {
100 int tc_set_new_mode(int mode);
101 }
102 #endif
103
104 #if defined(USE_MOJO)
105 #include "content/app/mojo/mojo_init.h"
106 #endif
107
108 namespace content {
109 extern int GpuMain(const content::MainFunctionParams&);
110 #if defined(ENABLE_PLUGINS)
111 extern int PluginMain(const content::MainFunctionParams&);
112 extern int PpapiPluginMain(const MainFunctionParams&);
113 extern int PpapiBrokerMain(const MainFunctionParams&);
114 #endif
115 extern int RendererMain(const content::MainFunctionParams&);
116 extern int UtilityMain(const MainFunctionParams&);
117 extern int WorkerMain(const MainFunctionParams&);
118 }  // namespace content
119
120 namespace {
121 #if defined(OS_WIN)
122 // In order to have Theme support, we need to connect to the theme service.
123 // This needs to be done before we lock down the process. Officially this
124 // can be done with OpenThemeData() but it fails unless you pass a valid
125 // window at least the first time. Interestingly, the very act of creating a
126 // window also sets the connection to the theme service.
127 void EnableThemeSupportOnAllWindowStations() {
128   HDESK desktop_handle = ::OpenInputDesktop(0, FALSE, READ_CONTROL);
129   if (desktop_handle) {
130     // This means we are running in an input desktop, which implies WinSta0.
131     ::CloseDesktop(desktop_handle);
132     return;
133   }
134
135   HWINSTA current_station = ::GetProcessWindowStation();
136   DCHECK(current_station);
137
138   HWINSTA winsta0 = ::OpenWindowStationA("WinSta0", FALSE, GENERIC_READ);
139   if (!winsta0) {
140     DVLOG(0) << "Unable to open to WinSta0, we: "<< ::GetLastError();
141     return;
142   }
143   if (!::SetProcessWindowStation(winsta0)) {
144     // Could not set the alternate window station. There is a possibility
145     // that the theme wont be correctly initialized.
146     NOTREACHED() << "Unable to switch to WinSta0, we: "<< ::GetLastError();
147     ::CloseWindowStation(winsta0);
148     return;
149   }
150
151   HWND window = ::CreateWindowExW(0, L"Static", L"", WS_POPUP | WS_DISABLED,
152                                   CW_USEDEFAULT, 0, 0, 0,  HWND_MESSAGE, NULL,
153                                   ::GetModuleHandleA(NULL), NULL);
154   if (!window) {
155     DLOG(WARNING) << "failed to enable theme support";
156   } else {
157     ::DestroyWindow(window);
158     window = NULL;
159   }
160
161   // Revert the window station.
162   if (!::SetProcessWindowStation(current_station)) {
163     // We failed to switch back to the secure window station. This might
164     // confuse the process enough that we should kill it now.
165     LOG(FATAL) << "Failed to restore alternate window station";
166   }
167
168   if (!::CloseWindowStation(winsta0)) {
169     // We might be leaking a winsta0 handle.  This is a security risk, but
170     // since we allow fail over to no desktop protection in low memory
171     // condition, this is not a big risk.
172     NOTREACHED();
173   }
174 }
175 #endif  // defined(OS_WIN)
176 }  // namespace
177
178 namespace content {
179
180 base::LazyInstance<ContentBrowserClient>
181     g_empty_content_browser_client = LAZY_INSTANCE_INITIALIZER;
182 #if !defined(OS_IOS) && !defined(CHROME_MULTIPLE_DLL_BROWSER)
183 base::LazyInstance<ContentPluginClient>
184     g_empty_content_plugin_client = LAZY_INSTANCE_INITIALIZER;
185 base::LazyInstance<ContentRendererClient>
186     g_empty_content_renderer_client = LAZY_INSTANCE_INITIALIZER;
187 base::LazyInstance<ContentUtilityClient>
188     g_empty_content_utility_client = LAZY_INSTANCE_INITIALIZER;
189 #endif  // !OS_IOS && !CHROME_MULTIPLE_DLL_BROWSER
190
191 #if defined(OS_WIN)
192
193 static CAppModule _Module;
194
195 #endif  // defined(OS_WIN)
196
197 #if defined(OS_POSIX) && !defined(OS_IOS)
198
199 // Setup signal-handling state: resanitize most signals, ignore SIGPIPE.
200 void SetupSignalHandlers() {
201   // Sanitise our signal handling state. Signals that were ignored by our
202   // parent will also be ignored by us. We also inherit our parent's sigmask.
203   sigset_t empty_signal_set;
204   CHECK(0 == sigemptyset(&empty_signal_set));
205   CHECK(0 == sigprocmask(SIG_SETMASK, &empty_signal_set, NULL));
206
207   struct sigaction sigact;
208   memset(&sigact, 0, sizeof(sigact));
209   sigact.sa_handler = SIG_DFL;
210   static const int signals_to_reset[] =
211       {SIGHUP, SIGINT, SIGQUIT, SIGILL, SIGABRT, SIGFPE, SIGSEGV,
212        SIGALRM, SIGTERM, SIGCHLD, SIGBUS, SIGTRAP};  // SIGPIPE is set below.
213   for (unsigned i = 0; i < arraysize(signals_to_reset); i++) {
214     CHECK(0 == sigaction(signals_to_reset[i], &sigact, NULL));
215   }
216
217   // Always ignore SIGPIPE.  We check the return value of write().
218   CHECK(signal(SIGPIPE, SIG_IGN) != SIG_ERR);
219 }
220
221 #endif  // OS_POSIX && !OS_IOS
222
223 void CommonSubprocessInit(const std::string& process_type) {
224 #if defined(OS_WIN)
225   // HACK: Let Windows know that we have started.  This is needed to suppress
226   // the IDC_APPSTARTING cursor from being displayed for a prolonged period
227   // while a subprocess is starting.
228   PostThreadMessage(GetCurrentThreadId(), WM_NULL, 0, 0);
229   MSG msg;
230   PeekMessage(&msg, NULL, 0, 0, PM_REMOVE);
231 #endif
232 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
233   // Various things break when you're using a locale where the decimal
234   // separator isn't a period.  See e.g. bugs 22782 and 39964.  For
235   // all processes except the browser process (where we call system
236   // APIs that may rely on the correct locale for formatting numbers
237   // when presenting them to the user), reset the locale for numeric
238   // formatting.
239   // Note that this is not correct for plugin processes -- they can
240   // surface UI -- but it's likely they get this wrong too so why not.
241   setlocale(LC_NUMERIC, "C");
242 #endif
243 }
244
245 static base::ProcessId GetBrowserPid(const CommandLine& command_line) {
246   base::ProcessId browser_pid = base::GetCurrentProcId();
247 #if !defined(OS_IOS)
248   if (command_line.HasSwitch(switches::kProcessChannelID)) {
249 #if defined(OS_WIN) || defined(OS_MACOSX)
250     std::string channel_name =
251         command_line.GetSwitchValueASCII(switches::kProcessChannelID);
252
253     int browser_pid_int;
254     base::StringToInt(channel_name, &browser_pid_int);
255     browser_pid = static_cast<base::ProcessId>(browser_pid_int);
256     DCHECK_NE(browser_pid_int, 0);
257 #elif defined(OS_ANDROID)
258     // On Android, the browser process isn't the parent. A bunch
259     // of work will be required before callers of this routine will
260     // get what they want.
261     //
262     // Note: On Linux, base::GetParentProcessId() is defined in
263     // process_util_linux.cc. Note that *_linux.cc is excluded from
264     // Android builds but a special exception is made in base.gypi
265     // for a few files including process_util_linux.cc.
266     LOG(ERROR) << "GetBrowserPid() not implemented for Android().";
267 #elif defined(OS_POSIX)
268     // On linux, we're in a process forked from the zygote here; so we need the
269     // parent's parent process' id.
270     browser_pid =
271         base::GetParentProcessId(
272             base::GetParentProcessId(base::GetCurrentProcId()));
273 #endif
274   }
275 #endif  // !OS_IOS
276   return browser_pid;
277 }
278
279 static void InitializeStatsTable(const CommandLine& command_line) {
280   // Initialize the Stats Counters table.  With this initialized,
281   // the StatsViewer can be utilized to read counters outside of
282   // Chrome.  These lines can be commented out to effectively turn
283   // counters 'off'.  The table is created and exists for the life
284   // of the process.  It is not cleaned up.
285   if (command_line.HasSwitch(switches::kEnableStatsTable)) {
286     // NOTIMPLEMENTED: we probably need to shut this down correctly to avoid
287     // leaking shared memory regions on posix platforms.
288     std::string statsfile =
289       base::StringPrintf("%s-%u", kStatsFilename,
290           static_cast<unsigned int>(GetBrowserPid(command_line)));
291     base::StatsTable* stats_table = new base::StatsTable(statsfile,
292         kStatsMaxThreads, kStatsMaxCounters);
293     base::StatsTable::set_current(stats_table);
294   }
295 }
296
297 class ContentClientInitializer {
298  public:
299   static void Set(const std::string& process_type,
300                   ContentMainDelegate* delegate) {
301     ContentClient* content_client = GetContentClient();
302     if (process_type.empty()) {
303       if (delegate)
304         content_client->browser_ = delegate->CreateContentBrowserClient();
305       if (!content_client->browser_)
306         content_client->browser_ = &g_empty_content_browser_client.Get();
307     }
308
309 #if !defined(OS_IOS) && !defined(CHROME_MULTIPLE_DLL_BROWSER)
310     if (process_type == switches::kPluginProcess ||
311         process_type == switches::kPpapiPluginProcess) {
312       if (delegate)
313         content_client->plugin_ = delegate->CreateContentPluginClient();
314       if (!content_client->plugin_)
315         content_client->plugin_ = &g_empty_content_plugin_client.Get();
316       // Single process not supported in split dll mode.
317     } else if (process_type == switches::kRendererProcess ||
318                CommandLine::ForCurrentProcess()->HasSwitch(
319                    switches::kSingleProcess)) {
320       if (delegate)
321         content_client->renderer_ = delegate->CreateContentRendererClient();
322       if (!content_client->renderer_)
323         content_client->renderer_ = &g_empty_content_renderer_client.Get();
324     }
325
326     if (process_type == switches::kUtilityProcess ||
327         CommandLine::ForCurrentProcess()->HasSwitch(
328             switches::kSingleProcess)) {
329       if (delegate)
330         content_client->utility_ = delegate->CreateContentUtilityClient();
331       // TODO(scottmg): http://crbug.com/237249 Should be in _child.
332       if (!content_client->utility_)
333         content_client->utility_ = &g_empty_content_utility_client.Get();
334     }
335 #endif  // !OS_IOS && !CHROME_MULTIPLE_DLL_BROWSER
336   }
337 };
338
339 // We dispatch to a process-type-specific FooMain() based on a command-line
340 // flag.  This struct is used to build a table of (flag, main function) pairs.
341 struct MainFunction {
342   const char* name;
343   int (*function)(const MainFunctionParams&);
344 };
345
346 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
347 // On platforms that use the zygote, we have a special subset of
348 // subprocesses that are launched via the zygote.  This function
349 // fills in some process-launching bits around ZygoteMain().
350 // Returns the exit code of the subprocess.
351 int RunZygote(const MainFunctionParams& main_function_params,
352               ContentMainDelegate* delegate) {
353   static const MainFunction kMainFunctions[] = {
354     { switches::kRendererProcess,    RendererMain },
355     { switches::kWorkerProcess,      WorkerMain },
356 #if defined(ENABLE_PLUGINS)
357     { switches::kPpapiPluginProcess, PpapiPluginMain },
358 #endif
359     { switches::kUtilityProcess,     UtilityMain },
360   };
361
362   scoped_ptr<ZygoteForkDelegate> zygote_fork_delegate;
363   if (delegate) {
364     zygote_fork_delegate.reset(delegate->ZygoteStarting());
365     // Each Renderer we spawn will re-attempt initialization of the media
366     // libraries, at which point failure will be detected and handled, so
367     // we do not need to cope with initialization failures here.
368     base::FilePath media_path;
369     if (PathService::Get(DIR_MEDIA_LIBS, &media_path))
370       media::InitializeMediaLibrary(media_path);
371   }
372
373   // This function call can return multiple times, once per fork().
374   if (!ZygoteMain(main_function_params, zygote_fork_delegate.get()))
375     return 1;
376
377   if (delegate) delegate->ZygoteForked();
378
379   // Zygote::HandleForkRequest may have reallocated the command
380   // line so update it here with the new version.
381   const CommandLine& command_line = *CommandLine::ForCurrentProcess();
382   std::string process_type =
383       command_line.GetSwitchValueASCII(switches::kProcessType);
384   ContentClientInitializer::Set(process_type, delegate);
385
386   // The StatsTable must be initialized in each process; we already
387   // initialized for the browser process, now we need to initialize
388   // within the new processes as well.
389   InitializeStatsTable(command_line);
390
391   MainFunctionParams main_params(command_line);
392
393   for (size_t i = 0; i < arraysize(kMainFunctions); ++i) {
394     if (process_type == kMainFunctions[i].name)
395       return kMainFunctions[i].function(main_params);
396   }
397
398   if (delegate)
399     return delegate->RunProcess(process_type, main_params);
400
401   NOTREACHED() << "Unknown zygote process type: " << process_type;
402   return 1;
403 }
404 #endif  // defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
405
406 #if !defined(OS_IOS)
407 static void RegisterMainThreadFactories() {
408 #if !defined(CHROME_MULTIPLE_DLL_BROWSER)
409   UtilityProcessHost::RegisterUtilityMainThreadFactory(
410       CreateInProcessUtilityThread);
411   RenderProcessHost::RegisterRendererMainThreadFactory(
412       CreateInProcessRendererThread);
413   GpuProcessHost::RegisterGpuMainThreadFactory(
414       CreateInProcessGpuThread);
415 #else
416   CommandLine& command_line = *CommandLine::ForCurrentProcess();
417   if (command_line.HasSwitch(switches::kSingleProcess)) {
418     LOG(FATAL) <<
419         "--single-process is not supported in chrome multiple dll browser.";
420   }
421   if (command_line.HasSwitch(switches::kInProcessGPU)) {
422     LOG(FATAL) <<
423         "--in-process-gpu is not supported in chrome multiple dll browser.";
424   }
425 #endif
426 }
427
428 // Run the FooMain() for a given process type.
429 // If |process_type| is empty, runs BrowserMain().
430 // Returns the exit code for this process.
431 int RunNamedProcessTypeMain(
432     const std::string& process_type,
433     const MainFunctionParams& main_function_params,
434     ContentMainDelegate* delegate) {
435   static const MainFunction kMainFunctions[] = {
436 #if !defined(CHROME_MULTIPLE_DLL_CHILD)
437     { "",                            BrowserMain },
438 #endif
439 #if !defined(CHROME_MULTIPLE_DLL_BROWSER)
440 #if defined(ENABLE_PLUGINS)
441     { switches::kPluginProcess,      PluginMain },
442     { switches::kWorkerProcess,      WorkerMain },
443     { switches::kPpapiPluginProcess, PpapiPluginMain },
444     { switches::kPpapiBrokerProcess, PpapiBrokerMain },
445 #endif  // ENABLE_PLUGINS
446     { switches::kUtilityProcess,     UtilityMain },
447     { switches::kRendererProcess,    RendererMain },
448     { switches::kGpuProcess,         GpuMain },
449 #endif  // !CHROME_MULTIPLE_DLL_BROWSER
450   };
451
452   RegisterMainThreadFactories();
453
454   for (size_t i = 0; i < arraysize(kMainFunctions); ++i) {
455     if (process_type == kMainFunctions[i].name) {
456       if (delegate) {
457         int exit_code = delegate->RunProcess(process_type,
458             main_function_params);
459 #if defined(OS_ANDROID)
460         // In Android's browser process, the negative exit code doesn't mean the
461         // default behavior should be used as the UI message loop is managed by
462         // the Java and the browser process's default behavior is always
463         // overridden.
464         if (process_type.empty())
465           return exit_code;
466 #endif
467         if (exit_code >= 0)
468           return exit_code;
469       }
470       return kMainFunctions[i].function(main_function_params);
471     }
472   }
473
474 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
475   // Zygote startup is special -- see RunZygote comments above
476   // for why we don't use ZygoteMain directly.
477   if (process_type == switches::kZygoteProcess)
478     return RunZygote(main_function_params, delegate);
479 #endif
480
481   // If it's a process we don't know about, the embedder should know.
482   if (delegate)
483     return delegate->RunProcess(process_type, main_function_params);
484
485   NOTREACHED() << "Unknown process type: " << process_type;
486   return 1;
487 }
488 #endif  // !OS_IOS
489
490 class ContentMainRunnerImpl : public ContentMainRunner {
491  public:
492   ContentMainRunnerImpl()
493       : is_initialized_(false),
494         is_shutdown_(false),
495         completed_basic_startup_(false),
496         delegate_(NULL),
497         ui_task_(NULL) {
498 #if defined(OS_WIN)
499     memset(&sandbox_info_, 0, sizeof(sandbox_info_));
500 #endif
501   }
502
503   virtual ~ContentMainRunnerImpl() {
504     if (is_initialized_ && !is_shutdown_)
505       Shutdown();
506   }
507
508 #if defined(USE_TCMALLOC)
509   static bool GetAllocatorWasteSizeThunk(size_t* size) {
510     size_t heap_size, allocated_bytes, unmapped_bytes;
511     MallocExtension* ext = MallocExtension::instance();
512     if (ext->GetNumericProperty("generic.heap_size", &heap_size) &&
513         ext->GetNumericProperty("generic.current_allocated_bytes",
514                                 &allocated_bytes) &&
515         ext->GetNumericProperty("tcmalloc.pageheap_unmapped_bytes",
516                                 &unmapped_bytes)) {
517       *size = heap_size - allocated_bytes - unmapped_bytes;
518       return true;
519     }
520     DCHECK(false);
521     return false;
522   }
523
524   static void GetStatsThunk(char* buffer, int buffer_length) {
525     MallocExtension::instance()->GetStats(buffer, buffer_length);
526   }
527
528   static void ReleaseFreeMemoryThunk() {
529     MallocExtension::instance()->ReleaseFreeMemory();
530   }
531 #endif
532
533   virtual int Initialize(const ContentMainParams& params) OVERRIDE {
534     ui_task_ = params.ui_task;
535
536 #if defined(OS_WIN)
537     RegisterInvalidParamHandler();
538     _Module.Init(NULL, static_cast<HINSTANCE>(params.instance));
539
540     sandbox_info_ = *params.sandbox_info;
541 #else  // !OS_WIN
542
543 #if defined(OS_ANDROID)
544     // See note at the initialization of ExitManager, below; basically,
545     // only Android builds have the ctor/dtor handlers set up to use
546     // TRACE_EVENT right away.
547     TRACE_EVENT0("startup", "ContentMainRunnerImpl::Initialize");
548 #endif  // OS_ANDROID
549
550     // NOTE(willchan): One might ask why these TCMalloc-related calls are done
551     // here rather than in process_util_linux.cc with the definition of
552     // EnableTerminationOnOutOfMemory().  That's because base shouldn't have a
553     // dependency on TCMalloc.  Really, we ought to have our allocator shim code
554     // implement this EnableTerminationOnOutOfMemory() function.  Whateverz.
555     // This works for now.
556 #if !defined(OS_MACOSX) && defined(USE_TCMALLOC)
557
558 #if defined(TYPE_PROFILING)
559     base::type_profiler::InterceptFunctions::SetFunctions(
560         base::type_profiler::NewInterceptForTCMalloc,
561         base::type_profiler::DeleteInterceptForTCMalloc);
562 #endif
563
564     // For tcmalloc, we need to tell it to behave like new.
565     tc_set_new_mode(1);
566
567     // On windows, we've already set these thunks up in _heap_init()
568     base::allocator::SetGetAllocatorWasteSizeFunction(
569         GetAllocatorWasteSizeThunk);
570     base::allocator::SetGetStatsFunction(GetStatsThunk);
571     base::allocator::SetReleaseFreeMemoryFunction(ReleaseFreeMemoryThunk);
572
573     // Provide optional hook for monitoring allocation quantities on a
574     // per-thread basis.  Only set the hook if the environment indicates this
575     // needs to be enabled.
576     const char* profiling = getenv(tracked_objects::kAlternateProfilerTime);
577     if (profiling &&
578         (atoi(profiling) == tracked_objects::TIME_SOURCE_TYPE_TCMALLOC)) {
579       tracked_objects::SetAlternateTimeSource(
580           MallocExtension::GetBytesAllocatedOnCurrentThread,
581           tracked_objects::TIME_SOURCE_TYPE_TCMALLOC);
582     }
583 #endif  // !OS_MACOSX && USE_TCMALLOC
584
585     // On Android,
586     // - setlocale() is not supported.
587     // - We do not override the signal handlers so that we can get
588     //   stack trace when crashing.
589     // - The ipc_fd is passed through the Java service.
590     // Thus, these are all disabled.
591 #if !defined(OS_ANDROID) && !defined(OS_IOS)
592     // Set C library locale to make sure CommandLine can parse argument values
593     // in correct encoding.
594     setlocale(LC_ALL, "");
595
596     SetupSignalHandlers();
597
598     base::GlobalDescriptors* g_fds = base::GlobalDescriptors::GetInstance();
599     g_fds->Set(kPrimaryIPCChannel,
600                kPrimaryIPCChannel + base::GlobalDescriptors::kBaseDescriptor);
601 #endif  // !OS_ANDROID && !OS_IOS
602
603 #if defined(OS_LINUX) || defined(OS_OPENBSD)
604     g_fds->Set(kCrashDumpSignal,
605                kCrashDumpSignal + base::GlobalDescriptors::kBaseDescriptor);
606 #endif
607
608 #endif  // !OS_WIN
609
610     is_initialized_ = true;
611     delegate_ = params.delegate;
612
613     base::EnableTerminationOnHeapCorruption();
614     base::EnableTerminationOnOutOfMemory();
615
616     // The exit manager is in charge of calling the dtors of singleton objects.
617     // On Android, AtExitManager is set up when library is loaded.
618     // On iOS, it's set up in main(), which can't call directly through to here.
619     // A consequence of this is that you can't use the ctor/dtor-based
620     // TRACE_EVENT methods on Linux or iOS builds till after we set this up.
621 #if !defined(OS_ANDROID) && !defined(OS_IOS)
622     if (!ui_task_) {
623       // When running browser tests, don't create a second AtExitManager as that
624       // interfers with shutdown when objects created before ContentMain is
625       // called are destructed when it returns.
626       exit_manager_.reset(new base::AtExitManager);
627     }
628 #endif  // !OS_ANDROID && !OS_IOS
629
630 #if defined(OS_MACOSX)
631     // We need this pool for all the objects created before we get to the
632     // event loop, but we don't want to leave them hanging around until the
633     // app quits. Each "main" needs to flush this pool right before it goes into
634     // its main event loop to get rid of the cruft.
635     autorelease_pool_.reset(new base::mac::ScopedNSAutoreleasePool());
636 #endif
637
638     // On Android, the command line is initialized when library is loaded and
639     // we have already started our TRACE_EVENT0.
640 #if !defined(OS_ANDROID)
641     // argc/argv are ignored on Windows and Android; see command_line.h for
642     // details.
643     int argc = 0;
644     const char** argv = NULL;
645
646 #if !defined(OS_WIN)
647     argc = params.argc;
648     argv = params.argv;
649 #endif
650
651     CommandLine::Init(argc, argv);
652
653 #if !defined(OS_IOS)
654     SetProcessTitleFromCommandLine(argv);
655 #endif
656 #endif // !OS_ANDROID
657
658     int exit_code;
659     if (delegate_ && delegate_->BasicStartupComplete(&exit_code))
660       return exit_code;
661
662     completed_basic_startup_ = true;
663
664     const CommandLine& command_line = *CommandLine::ForCurrentProcess();
665     std::string process_type =
666         command_line.GetSwitchValueASCII(switches::kProcessType);
667
668 #if defined(USE_MOJO)
669     // Initialize mojo here so that services can be registered.
670     InitializeMojo();
671 #endif
672
673     if (!GetContentClient())
674       SetContentClient(&empty_content_client_);
675     ContentClientInitializer::Set(process_type, delegate_);
676
677 #if defined(OS_WIN)
678     // Route stdio to parent console (if any) or create one.
679     if (command_line.HasSwitch(switches::kEnableLogging))
680       base::RouteStdioToConsole();
681 #endif
682
683     // Enable startup tracing asap to avoid early TRACE_EVENT calls being
684     // ignored.
685     if (command_line.HasSwitch(switches::kTraceStartup)) {
686       base::debug::CategoryFilter category_filter(
687           command_line.GetSwitchValueASCII(switches::kTraceStartup));
688       base::debug::TraceLog::GetInstance()->SetEnabled(
689           category_filter,
690           base::debug::TraceLog::RECORDING_MODE,
691           base::debug::TraceLog::RECORD_UNTIL_FULL);
692     }
693 #if !defined(OS_ANDROID)
694     // Android tracing started at the beginning of the method.
695     // Other OSes have to wait till we get here in order for all the memory
696     // management setup to be completed.
697     TRACE_EVENT0("startup", "ContentMainRunnerImpl::Initialize");
698 #endif // !OS_ANDROID
699
700 #if defined(OS_MACOSX) && !defined(OS_IOS)
701     // We need to allocate the IO Ports before the Sandbox is initialized or
702     // the first instance of PowerMonitor is created.
703     // It's important not to allocate the ports for processes which don't
704     // register with the power monitor - see crbug.com/88867.
705     if (process_type.empty() ||
706         (delegate_ &&
707          delegate_->ProcessRegistersWithSystemProcess(process_type))) {
708       base::PowerMonitorDeviceSource::AllocateSystemIOPorts();
709     }
710
711     if (!process_type.empty() &&
712         (!delegate_ || delegate_->ShouldSendMachPort(process_type))) {
713       MachBroker::ChildSendTaskPortToParent();
714     }
715 #elif defined(OS_WIN)
716     if (command_line.HasSwitch(switches::kEnableHighResolutionTime))
717       base::TimeTicks::SetNowIsHighResNowIfSupported();
718
719     // This must be done early enough since some helper functions like
720     // IsTouchEnabled, needed to load resources, may call into the theme dll.
721     EnableThemeSupportOnAllWindowStations();
722     SetupCRT(command_line);
723 #endif
724
725 #if defined(OS_POSIX)
726     if (!process_type.empty()) {
727       // When you hit Ctrl-C in a terminal running the browser
728       // process, a SIGINT is delivered to the entire process group.
729       // When debugging the browser process via gdb, gdb catches the
730       // SIGINT for the browser process (and dumps you back to the gdb
731       // console) but doesn't for the child processes, killing them.
732       // The fix is to have child processes ignore SIGINT; they'll die
733       // on their own when the browser process goes away.
734       //
735       // Note that we *can't* rely on BeingDebugged to catch this case because
736       // we are the child process, which is not being debugged.
737       // TODO(evanm): move this to some shared subprocess-init function.
738       if (!base::debug::BeingDebugged())
739         signal(SIGINT, SIG_IGN);
740     }
741 #endif
742
743 #if defined(USE_NSS)
744     crypto::EarlySetupForNSSInit();
745 #endif
746
747     ui::RegisterPathProvider();
748     RegisterPathProvider();
749     RegisterContentSchemes(true);
750
751     CHECK(base::i18n::InitializeICU());
752
753     InitializeStatsTable(command_line);
754
755     if (delegate_)
756       delegate_->PreSandboxStartup();
757
758     if (!process_type.empty())
759       CommonSubprocessInit(process_type);
760
761 #if defined(OS_WIN)
762     CHECK(InitializeSandbox(params.sandbox_info));
763 #elif defined(OS_MACOSX) && !defined(OS_IOS)
764     if (process_type == switches::kRendererProcess ||
765         process_type == switches::kPpapiPluginProcess ||
766         (delegate_ && delegate_->DelaySandboxInitialization(process_type))) {
767       // On OS X the renderer sandbox needs to be initialized later in the
768       // startup sequence in RendererMainPlatformDelegate::EnableSandbox().
769     } else {
770       CHECK(InitializeSandbox());
771     }
772 #endif
773
774     if (delegate_)
775       delegate_->SandboxInitialized(process_type);
776
777 #if defined(OS_TIZEN_MOBILE)
778     if (process_type.empty())
779       StoreArgvPointerAddress(argv);
780     else
781       SetProcessTitleFromCommandLine(argv);
782 #elif defined(OS_POSIX) && !defined(OS_IOS) && !defined(OS_ANDROID)
783     SetProcessTitleFromCommandLine(argv);
784 #endif
785
786     // Return -1 to indicate no early termination.
787     return -1;
788   }
789
790   virtual int Run() OVERRIDE {
791     DCHECK(is_initialized_);
792     DCHECK(!is_shutdown_);
793     const CommandLine& command_line = *CommandLine::ForCurrentProcess();
794     std::string process_type =
795           command_line.GetSwitchValueASCII(switches::kProcessType);
796
797     MainFunctionParams main_params(command_line);
798     main_params.ui_task = ui_task_;
799 #if defined(OS_WIN)
800     main_params.sandbox_info = &sandbox_info_;
801 #elif defined(OS_MACOSX)
802     main_params.autorelease_pool = autorelease_pool_.get();
803 #endif
804
805 #if !defined(OS_IOS)
806     return RunNamedProcessTypeMain(process_type, main_params, delegate_);
807 #else
808     return 1;
809 #endif
810   }
811
812   virtual void Shutdown() OVERRIDE {
813     DCHECK(is_initialized_);
814     DCHECK(!is_shutdown_);
815
816     if (completed_basic_startup_ && delegate_) {
817       const CommandLine& command_line = *CommandLine::ForCurrentProcess();
818       std::string process_type =
819           command_line.GetSwitchValueASCII(switches::kProcessType);
820
821       delegate_->ProcessExiting(process_type);
822     }
823
824 #if defined(OS_WIN)
825 #ifdef _CRTDBG_MAP_ALLOC
826     _CrtDumpMemoryLeaks();
827 #endif  // _CRTDBG_MAP_ALLOC
828
829     _Module.Term();
830 #endif  // OS_WIN
831
832 #if defined(OS_MACOSX)
833     autorelease_pool_.reset(NULL);
834 #endif
835
836     exit_manager_.reset(NULL);
837
838     delegate_ = NULL;
839     is_shutdown_ = true;
840   }
841
842  private:
843   // True if the runner has been initialized.
844   bool is_initialized_;
845
846   // True if the runner has been shut down.
847   bool is_shutdown_;
848
849   // True if basic startup was completed.
850   bool completed_basic_startup_;
851
852   // Used if the embedder doesn't set one.
853   ContentClient empty_content_client_;
854
855   // The delegate will outlive this object.
856   ContentMainDelegate* delegate_;
857
858   scoped_ptr<base::AtExitManager> exit_manager_;
859 #if defined(OS_WIN)
860   sandbox::SandboxInterfaceInfo sandbox_info_;
861 #elif defined(OS_MACOSX)
862   scoped_ptr<base::mac::ScopedNSAutoreleasePool> autorelease_pool_;
863 #endif
864
865   base::Closure* ui_task_;
866
867   DISALLOW_COPY_AND_ASSIGN(ContentMainRunnerImpl);
868 };
869
870 // static
871 ContentMainRunner* ContentMainRunner::Create() {
872   return new ContentMainRunnerImpl();
873 }
874
875 }  // namespace content