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