Revert 187797 "Added tests for page launcher extensions in the a..."
[chromium-blink-merge.git] / content / app / content_main_runner.cc
blobe0a5a991135ad4ce938248ebd1fed466c87ad75d
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_util.h"
22 #include "base/profiler/alternate_timer.h"
23 #include "base/string_number_conversions.h"
24 #include "base/string_util.h"
25 #include "base/stringprintf.h"
26 #include "content/browser/browser_main.h"
27 #include "content/common/set_process_title.h"
28 #include "content/common/url_schemes.h"
29 #include "content/public/app/content_main_delegate.h"
30 #include "content/public/app/startup_helper_win.h"
31 #include "content/public/browser/content_browser_client.h"
32 #include "content/public/common/content_client.h"
33 #include "content/public/common/content_constants.h"
34 #include "content/public/common/content_paths.h"
35 #include "content/public/common/content_switches.h"
36 #include "content/public/common/main_function_params.h"
37 #include "content/public/common/sandbox_init.h"
38 #include "crypto/nss_util.h"
39 #include "ipc/ipc_switches.h"
40 #include "media/base/media.h"
41 #include "sandbox/win/src/sandbox_types.h"
42 #include "ui/base/ui_base_paths.h"
43 #include "ui/base/ui_base_switches.h"
44 #include "ui/base/win/dpi.h"
45 #include "webkit/user_agent/user_agent.h"
47 #if defined(USE_TCMALLOC)
48 #include "third_party/tcmalloc/chromium/src/gperftools/malloc_extension.h"
49 #if defined(TYPE_PROFILING)
50 #include "base/allocator/type_profiler.h"
51 #include "base/allocator/type_profiler_tcmalloc.h"
52 #endif
53 #endif
55 #if !defined(OS_IOS)
56 #include "content/public/plugin/content_plugin_client.h"
57 #include "content/public/renderer/content_renderer_client.h"
58 #include "content/public/utility/content_utility_client.h"
59 #endif
61 #if defined(OS_WIN)
62 #include <atlbase.h>
63 #include <atlapp.h>
64 #include <malloc.h>
65 #include <cstring>
66 #elif defined(OS_MACOSX)
67 #include "base/mac/scoped_nsautorelease_pool.h"
68 #if !defined(OS_IOS)
69 #include "base/mach_ipc_mac.h"
70 #include "base/system_monitor/system_monitor.h"
71 #include "content/browser/mach_broker_mac.h"
72 #include "content/common/sandbox_init_mac.h"
73 #endif // !OS_IOS
74 #endif // OS_WIN
76 #if defined(OS_POSIX)
77 #include <signal.h>
79 #include "base/posix/global_descriptors.h"
80 #include "content/public/common/content_descriptors.h"
82 #if !defined(OS_MACOSX)
83 #include "content/public/common/zygote_fork_delegate_linux.h"
84 #endif
86 #endif // OS_POSIX
88 #if !defined(OS_MACOSX) && defined(USE_TCMALLOC)
89 extern "C" {
90 int tc_set_new_mode(int mode);
92 #endif
94 namespace content {
95 extern int GpuMain(const content::MainFunctionParams&);
96 #if defined(ENABLE_PLUGINS)
97 extern int PluginMain(const content::MainFunctionParams&);
98 extern int PpapiPluginMain(const MainFunctionParams&);
99 extern int PpapiBrokerMain(const MainFunctionParams&);
100 #endif
101 extern int RendererMain(const content::MainFunctionParams&);
102 extern int UtilityMain(const MainFunctionParams&);
103 extern int WorkerMain(const MainFunctionParams&);
104 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
105 extern int ZygoteMain(const MainFunctionParams&,
106 ZygoteForkDelegate* forkdelegate);
107 #endif
108 } // namespace content
110 namespace {
111 #if defined(OS_WIN)
112 // In order to have Theme support, we need to connect to the theme service.
113 // This needs to be done before we lock down the process. Officially this
114 // can be done with OpenThemeData() but it fails unless you pass a valid
115 // window at least the first time. Interestingly, the very act of creating a
116 // window also sets the connection to the theme service.
117 void EnableThemeSupportOnAllWindowStations() {
118 HDESK desktop_handle = ::OpenInputDesktop(0, FALSE, READ_CONTROL);
119 if (desktop_handle) {
120 // This means we are running in an input desktop, which implies WinSta0.
121 ::CloseDesktop(desktop_handle);
122 return;
125 HWINSTA current_station = ::GetProcessWindowStation();
126 DCHECK(current_station);
128 HWINSTA winsta0 = ::OpenWindowStationA("WinSta0", FALSE, GENERIC_READ);
129 if (!winsta0 || !::SetProcessWindowStation(winsta0)) {
130 // Could not set the alternate window station. There is a possibility
131 // that the theme wont be correctly initialized.
132 NOTREACHED() << "Unable to switch to WinSta0, we: "<< ::GetLastError();
135 HWND window = ::CreateWindowExW(0, L"Static", L"", WS_POPUP | WS_DISABLED,
136 CW_USEDEFAULT, 0, 0, 0, HWND_MESSAGE, NULL,
137 ::GetModuleHandleA(NULL), NULL);
138 if (!window) {
139 DLOG(WARNING) << "failed to enable theme support";
140 } else {
141 ::DestroyWindow(window);
142 window = NULL;
145 // Revert the window station.
146 if (!::SetProcessWindowStation(current_station)) {
147 // We failed to switch back to the secure window station. This might
148 // confuse the process enough that we should kill it now.
149 LOG(FATAL) << "Failed to restore alternate window station";
152 if (!::CloseWindowStation(winsta0)) {
153 // We might be leaking a winsta0 handle. This is a security risk, but
154 // since we allow fail over to no desktop protection in low memory
155 // condition, this is not a big risk.
156 NOTREACHED();
159 #endif // defined(OS_WIN)
160 } // namespace
162 namespace content {
164 base::LazyInstance<ContentBrowserClient>
165 g_empty_content_browser_client = LAZY_INSTANCE_INITIALIZER;
166 #if !defined(OS_IOS)
167 base::LazyInstance<ContentPluginClient>
168 g_empty_content_plugin_client = LAZY_INSTANCE_INITIALIZER;
169 base::LazyInstance<ContentRendererClient>
170 g_empty_content_renderer_client = LAZY_INSTANCE_INITIALIZER;
171 base::LazyInstance<ContentUtilityClient>
172 g_empty_content_utility_client = LAZY_INSTANCE_INITIALIZER;
173 #endif // !OS_IOS
175 #if defined(OS_WIN)
177 static CAppModule _Module;
179 #elif defined(OS_MACOSX) && !defined(OS_IOS)
181 // Completes the Mach IPC handshake by sending this process' task port to the
182 // parent process. The parent is listening on the Mach port given by
183 // |GetMachPortName()|. The task port is used by the parent to get CPU/memory
184 // stats to display in the task manager.
185 void SendTaskPortToParentProcess() {
186 const mach_msg_timeout_t kTimeoutMs = 100;
187 const int32_t kMessageId = 0;
188 std::string mach_port_name = MachBroker::GetMachPortName();
190 base::MachSendMessage child_message(kMessageId);
191 if (!child_message.AddDescriptor(mach_task_self())) {
192 LOG(ERROR) << "child AddDescriptor(mach_task_self()) failed.";
193 return;
196 base::MachPortSender child_sender(mach_port_name.c_str());
197 kern_return_t err = child_sender.SendMessage(child_message, kTimeoutMs);
198 if (err != KERN_SUCCESS) {
199 LOG(ERROR) << StringPrintf("child SendMessage() failed: 0x%x %s", err,
200 mach_error_string(err));
204 #endif // defined(OS_WIN)
206 #if defined(OS_POSIX) && !defined(OS_IOS)
208 // Setup signal-handling state: resanitize most signals, ignore SIGPIPE.
209 void SetupSignalHandlers() {
210 // Sanitise our signal handling state. Signals that were ignored by our
211 // parent will also be ignored by us. We also inherit our parent's sigmask.
212 sigset_t empty_signal_set;
213 CHECK(0 == sigemptyset(&empty_signal_set));
214 CHECK(0 == sigprocmask(SIG_SETMASK, &empty_signal_set, NULL));
216 struct sigaction sigact;
217 memset(&sigact, 0, sizeof(sigact));
218 sigact.sa_handler = SIG_DFL;
219 static const int signals_to_reset[] =
220 {SIGHUP, SIGINT, SIGQUIT, SIGILL, SIGABRT, SIGFPE, SIGSEGV,
221 SIGALRM, SIGTERM, SIGCHLD, SIGBUS, SIGTRAP}; // SIGPIPE is set below.
222 for (unsigned i = 0; i < arraysize(signals_to_reset); i++) {
223 CHECK(0 == sigaction(signals_to_reset[i], &sigact, NULL));
226 // Always ignore SIGPIPE. We check the return value of write().
227 CHECK(signal(SIGPIPE, SIG_IGN) != SIG_ERR);
230 #endif // OS_POSIX && !OS_IOS
232 void CommonSubprocessInit(const std::string& process_type) {
233 #if defined(OS_WIN)
234 // HACK: Let Windows know that we have started. This is needed to suppress
235 // the IDC_APPSTARTING cursor from being displayed for a prolonged period
236 // while a subprocess is starting.
237 PostThreadMessage(GetCurrentThreadId(), WM_NULL, 0, 0);
238 MSG msg;
239 PeekMessage(&msg, NULL, 0, 0, PM_REMOVE);
240 #endif
241 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
242 // Various things break when you're using a locale where the decimal
243 // separator isn't a period. See e.g. bugs 22782 and 39964. For
244 // all processes except the browser process (where we call system
245 // APIs that may rely on the correct locale for formatting numbers
246 // when presenting them to the user), reset the locale for numeric
247 // formatting.
248 // Note that this is not correct for plugin processes -- they can
249 // surface UI -- but it's likely they get this wrong too so why not.
250 setlocale(LC_NUMERIC, "C");
251 #endif
254 static base::ProcessId GetBrowserPid(const CommandLine& command_line) {
255 base::ProcessId browser_pid = base::GetCurrentProcId();
256 #if !defined(OS_IOS)
257 if (command_line.HasSwitch(switches::kProcessChannelID)) {
258 #if defined(OS_WIN) || defined(OS_MACOSX)
259 std::string channel_name =
260 command_line.GetSwitchValueASCII(switches::kProcessChannelID);
262 int browser_pid_int;
263 base::StringToInt(channel_name, &browser_pid_int);
264 browser_pid = static_cast<base::ProcessId>(browser_pid_int);
265 DCHECK_NE(browser_pid_int, 0);
266 #elif defined(OS_ANDROID)
267 // On Android, the browser process isn't the parent. A bunch
268 // of work will be required before callers of this routine will
269 // get what they want.
271 // Note: On Linux, base::GetParentProcessId() is defined in
272 // process_util_linux.cc. Note that *_linux.cc is excluded from
273 // Android builds but a special exception is made in base.gypi
274 // for a few files including process_util_linux.cc.
275 LOG(ERROR) << "GetBrowserPid() not implemented for Android().";
276 #elif defined(OS_POSIX)
277 // On linux, we're in a process forked from the zygote here; so we need the
278 // parent's parent process' id.
279 browser_pid =
280 base::GetParentProcessId(
281 base::GetParentProcessId(base::GetCurrentProcId()));
282 #endif
284 #endif // !OS_IOS
285 return browser_pid;
288 static void InitializeStatsTable(const CommandLine& command_line) {
289 // Initialize the Stats Counters table. With this initialized,
290 // the StatsViewer can be utilized to read counters outside of
291 // Chrome. These lines can be commented out to effectively turn
292 // counters 'off'. The table is created and exists for the life
293 // of the process. It is not cleaned up.
294 if (command_line.HasSwitch(switches::kEnableStatsTable)) {
295 // NOTIMPLEMENTED: we probably need to shut this down correctly to avoid
296 // leaking shared memory regions on posix platforms.
297 std::string statsfile =
298 base::StringPrintf("%s-%u", kStatsFilename,
299 static_cast<unsigned int>(GetBrowserPid(command_line)));
300 base::StatsTable* stats_table = new base::StatsTable(statsfile,
301 kStatsMaxThreads, kStatsMaxCounters);
302 base::StatsTable::set_current(stats_table);
306 class ContentClientInitializer {
307 public:
308 static void Set(const std::string& process_type,
309 ContentMainDelegate* delegate) {
310 ContentClient* content_client = GetContentClient();
311 if (process_type.empty()) {
312 if (delegate)
313 content_client->browser_ = delegate->CreateContentBrowserClient();
314 if (!content_client->browser_)
315 content_client->browser_ = &g_empty_content_browser_client.Get();
318 #if !defined(OS_IOS)
319 if (process_type == switches::kPluginProcess ||
320 process_type == switches::kPpapiPluginProcess) {
321 if (delegate)
322 content_client->plugin_ = delegate->CreateContentPluginClient();
323 if (!content_client->plugin_)
324 content_client->plugin_ = &g_empty_content_plugin_client.Get();
325 } else if (process_type == switches::kRendererProcess ||
326 CommandLine::ForCurrentProcess()->HasSwitch(
327 switches::kSingleProcess)) {
328 if (delegate)
329 content_client->renderer_ = delegate->CreateContentRendererClient();
330 if (!content_client->renderer_)
331 content_client->renderer_ = &g_empty_content_renderer_client.Get();
332 } else if (process_type == switches::kUtilityProcess) {
333 if (delegate)
334 content_client->utility_ = delegate->CreateContentUtilityClient();
335 if (!content_client->utility_)
336 content_client->utility_ = &g_empty_content_utility_client.Get();
338 #endif // !OS_IOS
342 // We dispatch to a process-type-specific FooMain() based on a command-line
343 // flag. This struct is used to build a table of (flag, main function) pairs.
344 struct MainFunction {
345 const char* name;
346 int (*function)(const MainFunctionParams&);
349 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
350 // On platforms that use the zygote, we have a special subset of
351 // subprocesses that are launched via the zygote. This function
352 // fills in some process-launching bits around ZygoteMain().
353 // Returns the exit code of the subprocess.
354 int RunZygote(const MainFunctionParams& main_function_params,
355 ContentMainDelegate* delegate) {
356 static const MainFunction kMainFunctions[] = {
357 { switches::kRendererProcess, RendererMain },
358 { switches::kWorkerProcess, WorkerMain },
359 #if defined(ENABLE_PLUGINS)
360 { switches::kPpapiPluginProcess, PpapiPluginMain },
361 #endif
362 { switches::kUtilityProcess, UtilityMain },
365 scoped_ptr<ZygoteForkDelegate> zygote_fork_delegate;
366 if (delegate) {
367 zygote_fork_delegate.reset(delegate->ZygoteStarting());
368 // Each Renderer we spawn will re-attempt initialization of the media
369 // libraries, at which point failure will be detected and handled, so
370 // we do not need to cope with initialization failures here.
371 base::FilePath media_path;
372 if (PathService::Get(DIR_MEDIA_LIBS, &media_path))
373 media::InitializeMediaLibrary(media_path);
376 // This function call can return multiple times, once per fork().
377 if (!ZygoteMain(main_function_params, zygote_fork_delegate.get()))
378 return 1;
380 if (delegate) delegate->ZygoteForked();
382 // Zygote::HandleForkRequest may have reallocated the command
383 // line so update it here with the new version.
384 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
385 std::string process_type =
386 command_line.GetSwitchValueASCII(switches::kProcessType);
387 ContentClientInitializer::Set(process_type, delegate);
389 // If a custom user agent was passed on the command line, we need
390 // to (re)set it now, rather than using the default one the zygote
391 // initialized.
392 if (command_line.HasSwitch(switches::kUserAgent)) {
393 webkit_glue::SetUserAgent(
394 command_line.GetSwitchValueASCII(switches::kUserAgent), true);
397 // The StatsTable must be initialized in each process; we already
398 // initialized for the browser process, now we need to initialize
399 // within the new processes as well.
400 InitializeStatsTable(command_line);
402 MainFunctionParams main_params(command_line);
404 for (size_t i = 0; i < arraysize(kMainFunctions); ++i) {
405 if (process_type == kMainFunctions[i].name)
406 return kMainFunctions[i].function(main_params);
409 if (delegate)
410 return delegate->RunProcess(process_type, main_params);
412 NOTREACHED() << "Unknown zygote process type: " << process_type;
413 return 1;
415 #endif // defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
417 #if !defined(OS_IOS)
418 // Run the FooMain() for a given process type.
419 // If |process_type| is empty, runs BrowserMain().
420 // Returns the exit code for this process.
421 int RunNamedProcessTypeMain(
422 const std::string& process_type,
423 const MainFunctionParams& main_function_params,
424 ContentMainDelegate* delegate) {
425 static const MainFunction kMainFunctions[] = {
426 { "", BrowserMain },
427 { switches::kRendererProcess, RendererMain },
428 #if defined(ENABLE_PLUGINS)
429 { switches::kPluginProcess, PluginMain },
430 { switches::kWorkerProcess, WorkerMain },
431 { switches::kPpapiPluginProcess, PpapiPluginMain },
432 { switches::kPpapiBrokerProcess, PpapiBrokerMain },
433 #endif
434 { switches::kUtilityProcess, UtilityMain },
435 { switches::kGpuProcess, GpuMain },
438 for (size_t i = 0; i < arraysize(kMainFunctions); ++i) {
439 if (process_type == kMainFunctions[i].name) {
440 if (delegate) {
441 int exit_code = delegate->RunProcess(process_type,
442 main_function_params);
443 #if defined(OS_ANDROID)
444 // In Android's browser process, the negative exit code doesn't mean the
445 // default behavior should be used as the UI message loop is managed by
446 // the Java and the browser process's default behavior is always
447 // overridden.
448 if (process_type.empty())
449 return exit_code;
450 #endif
451 if (exit_code >= 0)
452 return exit_code;
454 return kMainFunctions[i].function(main_function_params);
458 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
459 // Zygote startup is special -- see RunZygote comments above
460 // for why we don't use ZygoteMain directly.
461 if (process_type == switches::kZygoteProcess)
462 return RunZygote(main_function_params, delegate);
463 #endif
465 // If it's a process we don't know about, the embedder should know.
466 if (delegate)
467 return delegate->RunProcess(process_type, main_function_params);
469 NOTREACHED() << "Unknown process type: " << process_type;
470 return 1;
472 #endif // !OS_IOS
474 class ContentMainRunnerImpl : public ContentMainRunner {
475 public:
476 ContentMainRunnerImpl()
477 : is_initialized_(false),
478 is_shutdown_(false),
479 completed_basic_startup_(false),
480 delegate_(NULL) {
481 #if defined(OS_WIN)
482 memset(&sandbox_info_, 0, sizeof(sandbox_info_));
483 #endif
486 virtual ~ContentMainRunnerImpl() {
487 if (is_initialized_ && !is_shutdown_)
488 Shutdown();
491 #if defined(USE_TCMALLOC)
492 static bool GetAllocatorWasteSizeThunk(size_t* size) {
493 size_t heap_size, allocated_bytes, unmapped_bytes;
494 MallocExtension* ext = MallocExtension::instance();
495 if (ext->GetNumericProperty("generic.heap_size", &heap_size) &&
496 ext->GetNumericProperty("generic.current_allocated_bytes",
497 &allocated_bytes) &&
498 ext->GetNumericProperty("tcmalloc.pageheap_unmapped_bytes",
499 &unmapped_bytes)) {
500 *size = heap_size - allocated_bytes - unmapped_bytes;
501 return true;
503 DCHECK(false);
504 return false;
507 static void GetStatsThunk(char* buffer, int buffer_length) {
508 MallocExtension::instance()->GetStats(buffer, buffer_length);
511 static void ReleaseFreeMemoryThunk() {
512 MallocExtension::instance()->ReleaseFreeMemory();
514 #endif
516 #if defined(OS_WIN)
517 virtual int Initialize(HINSTANCE instance,
518 sandbox::SandboxInterfaceInfo* sandbox_info,
519 ContentMainDelegate* delegate) OVERRIDE {
520 // argc/argv are ignored on Windows; see command_line.h for details.
521 int argc = 0;
522 char** argv = NULL;
524 RegisterInvalidParamHandler();
525 _Module.Init(NULL, static_cast<HINSTANCE>(instance));
527 sandbox_info_ = *sandbox_info;
528 #else // !OS_WIN
529 virtual int Initialize(int argc,
530 const char** argv,
531 ContentMainDelegate* delegate) OVERRIDE {
533 // NOTE(willchan): One might ask why these TCMalloc-related calls are done
534 // here rather than in process_util_linux.cc with the definition of
535 // EnableTerminationOnOutOfMemory(). That's because base shouldn't have a
536 // dependency on TCMalloc. Really, we ought to have our allocator shim code
537 // implement this EnableTerminationOnOutOfMemory() function. Whateverz.
538 // This works for now.
539 #if !defined(OS_MACOSX) && defined(USE_TCMALLOC)
541 #if defined(TYPE_PROFILING)
542 base::type_profiler::InterceptFunctions::SetFunctions(
543 base::type_profiler::NewInterceptForTCMalloc,
544 base::type_profiler::DeleteInterceptForTCMalloc);
545 #endif
547 // For tcmalloc, we need to tell it to behave like new.
548 tc_set_new_mode(1);
550 // On windows, we've already set these thunks up in _heap_init()
551 base::allocator::SetGetAllocatorWasteSizeFunction(
552 GetAllocatorWasteSizeThunk);
553 base::allocator::SetGetStatsFunction(GetStatsThunk);
554 base::allocator::SetReleaseFreeMemoryFunction(ReleaseFreeMemoryThunk);
556 // Provide optional hook for monitoring allocation quantities on a
557 // per-thread basis. Only set the hook if the environment indicates this
558 // needs to be enabled.
559 const char* profiling = getenv(tracked_objects::kAlternateProfilerTime);
560 if (profiling &&
561 (atoi(profiling) == tracked_objects::TIME_SOURCE_TYPE_TCMALLOC)) {
562 tracked_objects::SetAlternateTimeSource(
563 MallocExtension::GetBytesAllocatedOnCurrentThread,
564 tracked_objects::TIME_SOURCE_TYPE_TCMALLOC);
566 #endif
568 // On Android,
569 // - setlocale() is not supported.
570 // - We do not override the signal handlers so that we can get
571 // stack trace when crashing.
572 // - The ipc_fd is passed through the Java service.
573 // Thus, these are all disabled.
574 #if !defined(OS_ANDROID) && !defined(OS_IOS)
575 // Set C library locale to make sure CommandLine can parse argument values
576 // in correct encoding.
577 setlocale(LC_ALL, "");
579 SetupSignalHandlers();
581 base::GlobalDescriptors* g_fds = base::GlobalDescriptors::GetInstance();
582 g_fds->Set(kPrimaryIPCChannel,
583 kPrimaryIPCChannel + base::GlobalDescriptors::kBaseDescriptor);
584 #endif // !OS_ANDROID && !OS_IOS
586 #if defined(OS_LINUX) || defined(OS_OPENBSD)
587 g_fds->Set(kCrashDumpSignal,
588 kCrashDumpSignal + base::GlobalDescriptors::kBaseDescriptor);
589 #endif
591 #endif // !OS_WIN
593 is_initialized_ = true;
594 delegate_ = delegate;
596 base::EnableTerminationOnHeapCorruption();
597 base::EnableTerminationOnOutOfMemory();
599 // The exit manager is in charge of calling the dtors of singleton objects.
600 // On Android, AtExitManager is set up when library is loaded.
601 // On iOS, it's set up in main(), which can't call directly through to here.
602 #if !defined(OS_ANDROID) && !defined(OS_IOS)
603 exit_manager_.reset(new base::AtExitManager);
604 #endif // !OS_ANDROID && !OS_IOS
606 #if defined(OS_MACOSX)
607 // We need this pool for all the objects created before we get to the
608 // event loop, but we don't want to leave them hanging around until the
609 // app quits. Each "main" needs to flush this pool right before it goes into
610 // its main event loop to get rid of the cruft.
611 autorelease_pool_.reset(new base::mac::ScopedNSAutoreleasePool());
612 #endif
614 // On Android, the command line is initialized when library is loaded.
615 #if !defined(OS_ANDROID)
616 CommandLine::Init(argc, argv);
617 #endif
619 int exit_code;
620 if (delegate && delegate->BasicStartupComplete(&exit_code))
621 return exit_code;
623 completed_basic_startup_ = true;
625 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
626 std::string process_type =
627 command_line.GetSwitchValueASCII(switches::kProcessType);
629 if (!GetContentClient())
630 SetContentClient(&empty_content_client_);
631 ContentClientInitializer::Set(process_type, delegate_);
633 #if defined(OS_WIN)
634 // Route stdio to parent console (if any) or create one.
635 if (command_line.HasSwitch(switches::kEnableLogging))
636 base::RouteStdioToConsole();
637 #endif
639 // Enable startup tracing asap to avoid early TRACE_EVENT calls being
640 // ignored.
641 if (command_line.HasSwitch(switches::kTraceStartup)) {
642 base::debug::TraceLog::GetInstance()->SetEnabled(
643 command_line.GetSwitchValueASCII(switches::kTraceStartup),
644 base::debug::TraceLog::RECORD_UNTIL_FULL);
647 #if defined(OS_MACOSX) && !defined(OS_IOS)
648 // We need to allocate the IO Ports before the Sandbox is initialized or
649 // the first instance of SystemMonitor is created.
650 // It's important not to allocate the ports for processes which don't
651 // register with the system monitor - see crbug.com/88867.
652 if (process_type.empty() ||
653 process_type == switches::kPluginProcess ||
654 process_type == switches::kRendererProcess ||
655 process_type == switches::kUtilityProcess ||
656 process_type == switches::kWorkerProcess ||
657 (delegate &&
658 delegate->ProcessRegistersWithSystemProcess(process_type))) {
659 base::SystemMonitor::AllocateSystemIOPorts();
662 if (!process_type.empty() &&
663 (!delegate || delegate->ShouldSendMachPort(process_type))) {
664 SendTaskPortToParentProcess();
666 #elif defined(OS_WIN)
667 // This must be done early enough since some helper functions like
668 // IsTouchEnabled, needed to load resources, may call into the theme dll.
669 EnableThemeSupportOnAllWindowStations();
670 #if defined(ENABLE_HIDPI)
671 ui::EnableHighDPISupport();
672 #endif
673 SetupCRT(command_line);
674 #endif
676 #if defined(OS_POSIX)
677 if (!process_type.empty()) {
678 // When you hit Ctrl-C in a terminal running the browser
679 // process, a SIGINT is delivered to the entire process group.
680 // When debugging the browser process via gdb, gdb catches the
681 // SIGINT for the browser process (and dumps you back to the gdb
682 // console) but doesn't for the child processes, killing them.
683 // The fix is to have child processes ignore SIGINT; they'll die
684 // on their own when the browser process goes away.
686 // Note that we *can't* rely on BeingDebugged to catch this case because
687 // we are the child process, which is not being debugged.
688 // TODO(evanm): move this to some shared subprocess-init function.
689 if (!base::debug::BeingDebugged())
690 signal(SIGINT, SIG_IGN);
692 #endif
694 #if defined(USE_NSS)
695 crypto::EarlySetupForNSSInit();
696 #endif
698 ui::RegisterPathProvider();
699 RegisterPathProvider();
700 RegisterContentSchemes(true);
702 CHECK(icu_util::Initialize());
704 InitializeStatsTable(command_line);
706 if (delegate)
707 delegate->PreSandboxStartup();
709 // Set any custom user agent passed on the command line now so the string
710 // doesn't change between calls to webkit_glue::GetUserAgent(), otherwise it
711 // defaults to the user agent set during SetContentClient().
712 if (command_line.HasSwitch(switches::kUserAgent)) {
713 webkit_glue::SetUserAgent(
714 command_line.GetSwitchValueASCII(switches::kUserAgent), true);
717 if (!process_type.empty())
718 CommonSubprocessInit(process_type);
720 #if defined(OS_WIN)
721 CHECK(InitializeSandbox(sandbox_info));
722 #elif defined(OS_MACOSX) && !defined(OS_IOS)
723 if (process_type == switches::kRendererProcess ||
724 process_type == switches::kPpapiPluginProcess ||
725 (delegate && delegate->DelaySandboxInitialization(process_type))) {
726 // On OS X the renderer sandbox needs to be initialized later in the
727 // startup sequence in RendererMainPlatformDelegate::EnableSandbox().
728 } else {
729 CHECK(InitializeSandbox());
731 #endif
733 if (delegate)
734 delegate->SandboxInitialized(process_type);
736 #if defined(OS_POSIX) && !defined(OS_IOS)
737 SetProcessTitleFromCommandLine(argv);
738 #endif
740 // Return -1 to indicate no early termination.
741 return -1;
744 virtual int Run() OVERRIDE {
745 DCHECK(is_initialized_);
746 DCHECK(!is_shutdown_);
747 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
748 std::string process_type =
749 command_line.GetSwitchValueASCII(switches::kProcessType);
751 MainFunctionParams main_params(command_line);
752 #if defined(OS_WIN)
753 main_params.sandbox_info = &sandbox_info_;
754 #elif defined(OS_MACOSX)
755 main_params.autorelease_pool = autorelease_pool_.get();
756 #endif
758 #if !defined(OS_IOS)
759 return RunNamedProcessTypeMain(process_type, main_params, delegate_);
760 #else
761 return 1;
762 #endif
765 virtual void Shutdown() OVERRIDE {
766 DCHECK(is_initialized_);
767 DCHECK(!is_shutdown_);
769 if (completed_basic_startup_ && delegate_) {
770 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
771 std::string process_type =
772 command_line.GetSwitchValueASCII(switches::kProcessType);
774 delegate_->ProcessExiting(process_type);
777 #if defined(OS_WIN)
778 #ifdef _CRTDBG_MAP_ALLOC
779 _CrtDumpMemoryLeaks();
780 #endif // _CRTDBG_MAP_ALLOC
782 _Module.Term();
783 #endif // OS_WIN
785 #if defined(OS_MACOSX)
786 autorelease_pool_.reset(NULL);
787 #endif
789 exit_manager_.reset(NULL);
791 delegate_ = NULL;
792 is_shutdown_ = true;
795 private:
796 // True if the runner has been initialized.
797 bool is_initialized_;
799 // True if the runner has been shut down.
800 bool is_shutdown_;
802 // True if basic startup was completed.
803 bool completed_basic_startup_;
805 // Used if the embedder doesn't set one.
806 ContentClient empty_content_client_;
808 // The delegate will outlive this object.
809 ContentMainDelegate* delegate_;
811 scoped_ptr<base::AtExitManager> exit_manager_;
812 #if defined(OS_WIN)
813 sandbox::SandboxInterfaceInfo sandbox_info_;
814 #elif defined(OS_MACOSX)
815 scoped_ptr<base::mac::ScopedNSAutoreleasePool> autorelease_pool_;
816 #endif
818 DISALLOW_COPY_AND_ASSIGN(ContentMainRunnerImpl);
821 // static
822 ContentMainRunner* ContentMainRunner::Create() {
823 return new ContentMainRunnerImpl();
826 } // namespace content