Extract SIGPIPE ignoring code to a common place.
[chromium-blink-merge.git] / content / app / content_main_runner.cc
blobe35c8e485eb27a87a5317e5fcefa6ec878fd7117
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/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_util.h"
24 #include "base/stringprintf.h"
25 #include "base/string_number_conversions.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_switches.h"
43 #include "ui/base/ui_base_paths.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 <cstring>
63 #include <atlbase.h>
64 #include <atlapp.h>
65 #include <malloc.h>
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 extern int PluginMain(const content::MainFunctionParams&);
97 extern int PpapiPluginMain(const MainFunctionParams&);
98 extern int PpapiBrokerMain(const MainFunctionParams&);
99 extern int RendererMain(const content::MainFunctionParams&);
100 extern int UtilityMain(const MainFunctionParams&);
101 extern int WorkerMain(const MainFunctionParams&);
102 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
103 extern int ZygoteMain(const MainFunctionParams&,
104 ZygoteForkDelegate* forkdelegate);
105 #endif
106 } // namespace content
108 namespace {
109 #if defined(OS_WIN)
110 // In order to have Theme support, we need to connect to the theme service.
111 // This needs to be done before we lock down the process. Officially this
112 // can be done with OpenThemeData() but it fails unless you pass a valid
113 // window at least the first time. Interestingly, the very act of creating a
114 // window also sets the connection to the theme service.
115 void EnableThemeSupportOnAllWindowStations() {
116 HDESK desktop_handle = ::OpenInputDesktop(0, FALSE, READ_CONTROL);
117 if (desktop_handle) {
118 // This means we are running in an input desktop, which implies WinSta0.
119 ::CloseDesktop(desktop_handle);
120 return;
123 HWINSTA current_station = ::GetProcessWindowStation();
124 DCHECK(current_station);
126 HWINSTA winsta0 = ::OpenWindowStationA("WinSta0", FALSE, GENERIC_READ);
127 if (!winsta0 || !::SetProcessWindowStation(winsta0)) {
128 // Could not set the alternate window station. There is a possibility
129 // that the theme wont be correctly initialized.
130 NOTREACHED() << "Unable to switch to WinSta0, we: "<< ::GetLastError();
133 HWND window = ::CreateWindowExW(0, L"Static", L"", WS_POPUP | WS_DISABLED,
134 CW_USEDEFAULT, 0, 0, 0, HWND_MESSAGE, NULL,
135 ::GetModuleHandleA(NULL), NULL);
136 if (!window) {
137 DLOG(WARNING) << "failed to enable theme support";
138 } else {
139 ::DestroyWindow(window);
140 window = NULL;
143 // Revert the window station.
144 if (!::SetProcessWindowStation(current_station)) {
145 // We failed to switch back to the secure window station. This might
146 // confuse the process enough that we should kill it now.
147 LOG(FATAL) << "Failed to restore alternate window station";
150 if (!::CloseWindowStation(winsta0)) {
151 // We might be leaking a winsta0 handle. This is a security risk, but
152 // since we allow fail over to no desktop protection in low memory
153 // condition, this is not a big risk.
154 NOTREACHED();
157 #endif // defined(OS_WIN)
158 } // namespace
160 namespace content {
162 base::LazyInstance<ContentBrowserClient>
163 g_empty_content_browser_client = LAZY_INSTANCE_INITIALIZER;
164 #if !defined(OS_IOS)
165 base::LazyInstance<ContentPluginClient>
166 g_empty_content_plugin_client = LAZY_INSTANCE_INITIALIZER;
167 base::LazyInstance<ContentRendererClient>
168 g_empty_content_renderer_client = LAZY_INSTANCE_INITIALIZER;
169 base::LazyInstance<ContentUtilityClient>
170 g_empty_content_utility_client = LAZY_INSTANCE_INITIALIZER;
171 #endif // !OS_IOS
173 #if defined(OS_WIN)
175 static CAppModule _Module;
177 #elif defined(OS_MACOSX) && !defined(OS_IOS)
179 // Completes the Mach IPC handshake by sending this process' task port to the
180 // parent process. The parent is listening on the Mach port given by
181 // |GetMachPortName()|. The task port is used by the parent to get CPU/memory
182 // stats to display in the task manager.
183 void SendTaskPortToParentProcess() {
184 const mach_msg_timeout_t kTimeoutMs = 100;
185 const int32_t kMessageId = 0;
186 std::string mach_port_name = MachBroker::GetMachPortName();
188 base::MachSendMessage child_message(kMessageId);
189 if (!child_message.AddDescriptor(mach_task_self())) {
190 LOG(ERROR) << "child AddDescriptor(mach_task_self()) failed.";
191 return;
194 base::MachPortSender child_sender(mach_port_name.c_str());
195 kern_return_t err = child_sender.SendMessage(child_message, kTimeoutMs);
196 if (err != KERN_SUCCESS) {
197 LOG(ERROR) << StringPrintf("child SendMessage() failed: 0x%x %s", err,
198 mach_error_string(err));
202 #endif // defined(OS_WIN)
204 #if defined(OS_POSIX) && !defined(OS_IOS)
206 // Setup signal-handling state: resanitize most signals, ignore SIGPIPE.
207 void SetupSignalHandlers() {
208 // Sanitise our signal handling state. Signals that were ignored by our
209 // parent will also be ignored by us. We also inherit our parent's sigmask.
210 sigset_t empty_signal_set;
211 CHECK(0 == sigemptyset(&empty_signal_set));
212 CHECK(0 == sigprocmask(SIG_SETMASK, &empty_signal_set, NULL));
214 struct sigaction sigact;
215 memset(&sigact, 0, sizeof(sigact));
216 sigact.sa_handler = SIG_DFL;
217 static const int signals_to_reset[] =
218 {SIGHUP, SIGINT, SIGQUIT, SIGILL, SIGABRT, SIGFPE, SIGSEGV,
219 SIGALRM, SIGTERM, SIGCHLD, SIGBUS, SIGTRAP}; // SIGPIPE is set below.
220 for (unsigned i = 0; i < arraysize(signals_to_reset); i++) {
221 CHECK(0 == sigaction(signals_to_reset[i], &sigact, NULL));
224 // Always ignore SIGPIPE. We check the return value of write().
225 CHECK(base::IgnoreSigPipe());
228 #endif // OS_POSIX && !OS_IOS
230 void CommonSubprocessInit(const std::string& process_type) {
231 #if defined(OS_WIN)
232 // HACK: Let Windows know that we have started. This is needed to suppress
233 // the IDC_APPSTARTING cursor from being displayed for a prolonged period
234 // while a subprocess is starting.
235 PostThreadMessage(GetCurrentThreadId(), WM_NULL, 0, 0);
236 MSG msg;
237 PeekMessage(&msg, NULL, 0, 0, PM_REMOVE);
238 #endif
239 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
240 // Various things break when you're using a locale where the decimal
241 // separator isn't a period. See e.g. bugs 22782 and 39964. For
242 // all processes except the browser process (where we call system
243 // APIs that may rely on the correct locale for formatting numbers
244 // when presenting them to the user), reset the locale for numeric
245 // formatting.
246 // Note that this is not correct for plugin processes -- they can
247 // surface UI -- but it's likely they get this wrong too so why not.
248 setlocale(LC_NUMERIC, "C");
249 #endif
252 static base::ProcessId GetBrowserPid(const CommandLine& command_line) {
253 base::ProcessId browser_pid = base::GetCurrentProcId();
254 #if !defined(OS_IOS)
255 if (command_line.HasSwitch(switches::kProcessChannelID)) {
256 #if defined(OS_WIN) || defined(OS_MACOSX)
257 std::string channel_name =
258 command_line.GetSwitchValueASCII(switches::kProcessChannelID);
260 int browser_pid_int;
261 base::StringToInt(channel_name, &browser_pid_int);
262 browser_pid = static_cast<base::ProcessId>(browser_pid_int);
263 DCHECK_NE(browser_pid_int, 0);
264 #elif defined(OS_ANDROID)
265 // On Android, the browser process isn't the parent. A bunch
266 // of work will be required before callers of this routine will
267 // get what they want.
269 // Note: On Linux, base::GetParentProcessId() is defined in
270 // process_util_linux.cc. Note that *_linux.cc is excluded from
271 // Android builds but a special exception is made in base.gypi
272 // for a few files including process_util_linux.cc.
273 LOG(ERROR) << "GetBrowserPid() not implemented for Android().";
274 #elif defined(OS_POSIX)
275 // On linux, we're in a process forked from the zygote here; so we need the
276 // parent's parent process' id.
277 browser_pid =
278 base::GetParentProcessId(
279 base::GetParentProcessId(base::GetCurrentProcId()));
280 #endif
282 #endif // !OS_IOS
283 return browser_pid;
286 static void InitializeStatsTable(const CommandLine& command_line) {
287 // Initialize the Stats Counters table. With this initialized,
288 // the StatsViewer can be utilized to read counters outside of
289 // Chrome. These lines can be commented out to effectively turn
290 // counters 'off'. The table is created and exists for the life
291 // of the process. It is not cleaned up.
292 if (command_line.HasSwitch(switches::kEnableStatsTable)) {
293 // NOTIMPLEMENTED: we probably need to shut this down correctly to avoid
294 // leaking shared memory regions on posix platforms.
295 std::string statsfile =
296 base::StringPrintf("%s-%u", kStatsFilename,
297 static_cast<unsigned int>(GetBrowserPid(command_line)));
298 base::StatsTable* stats_table = new base::StatsTable(statsfile,
299 kStatsMaxThreads, kStatsMaxCounters);
300 base::StatsTable::set_current(stats_table);
304 class ContentClientInitializer {
305 public:
306 static void Set(const std::string& process_type,
307 ContentMainDelegate* delegate) {
308 ContentClient* content_client = GetContentClient();
309 if (process_type.empty()) {
310 if (delegate)
311 content_client->browser_ = delegate->CreateContentBrowserClient();
312 if (!content_client->browser_)
313 content_client->browser_ = &g_empty_content_browser_client.Get();
316 #if !defined(OS_IOS)
317 if (process_type == switches::kPluginProcess ||
318 process_type == switches::kPpapiPluginProcess) {
319 if (delegate)
320 content_client->plugin_ = delegate->CreateContentPluginClient();
321 if (!content_client->plugin_)
322 content_client->plugin_ = &g_empty_content_plugin_client.Get();
323 } else if (process_type == switches::kRendererProcess ||
324 CommandLine::ForCurrentProcess()->HasSwitch(
325 switches::kSingleProcess)) {
326 if (delegate)
327 content_client->renderer_ = delegate->CreateContentRendererClient();
328 if (!content_client->renderer_)
329 content_client->renderer_ = &g_empty_content_renderer_client.Get();
330 } else if (process_type == switches::kUtilityProcess) {
331 if (delegate)
332 content_client->utility_ = delegate->CreateContentUtilityClient();
333 if (!content_client->utility_)
334 content_client->utility_ = &g_empty_content_utility_client.Get();
336 #endif // !OS_IOS
340 // We dispatch to a process-type-specific FooMain() based on a command-line
341 // flag. This struct is used to build a table of (flag, main function) pairs.
342 struct MainFunction {
343 const char* name;
344 int (*function)(const MainFunctionParams&);
347 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
348 // On platforms that use the zygote, we have a special subset of
349 // subprocesses that are launched via the zygote. This function
350 // fills in some process-launching bits around ZygoteMain().
351 // Returns the exit code of the subprocess.
352 int RunZygote(const MainFunctionParams& main_function_params,
353 ContentMainDelegate* delegate) {
354 static const MainFunction kMainFunctions[] = {
355 { switches::kRendererProcess, RendererMain },
356 { switches::kWorkerProcess, WorkerMain },
357 { switches::kPpapiPluginProcess, PpapiPluginMain },
358 { switches::kUtilityProcess, UtilityMain },
361 scoped_ptr<ZygoteForkDelegate> zygote_fork_delegate;
362 if (delegate) {
363 zygote_fork_delegate.reset(delegate->ZygoteStarting());
364 // Each Renderer we spawn will re-attempt initialization of the media
365 // libraries, at which point failure will be detected and handled, so
366 // we do not need to cope with initialization failures here.
367 FilePath media_path;
368 if (PathService::Get(DIR_MEDIA_LIBS, &media_path))
369 media::InitializeMediaLibrary(media_path);
372 // This function call can return multiple times, once per fork().
373 if (!ZygoteMain(main_function_params, zygote_fork_delegate.get()))
374 return 1;
376 if (delegate) delegate->ZygoteForked();
378 // Zygote::HandleForkRequest may have reallocated the command
379 // line so update it here with the new version.
380 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
381 std::string process_type =
382 command_line.GetSwitchValueASCII(switches::kProcessType);
383 ContentClientInitializer::Set(process_type, delegate);
385 // If a custom user agent was passed on the command line, we need
386 // to (re)set it now, rather than using the default one the zygote
387 // initialized.
388 if (command_line.HasSwitch(switches::kUserAgent)) {
389 webkit_glue::SetUserAgent(
390 command_line.GetSwitchValueASCII(switches::kUserAgent), true);
393 // The StatsTable must be initialized in each process; we already
394 // initialized for the browser process, now we need to initialize
395 // within the new processes as well.
396 InitializeStatsTable(command_line);
398 MainFunctionParams main_params(command_line);
400 for (size_t i = 0; i < arraysize(kMainFunctions); ++i) {
401 if (process_type == kMainFunctions[i].name)
402 return kMainFunctions[i].function(main_params);
405 if (delegate)
406 return delegate->RunProcess(process_type, main_params);
408 NOTREACHED() << "Unknown zygote process type: " << process_type;
409 return 1;
411 #endif // defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
413 #if !defined(OS_IOS)
414 // Run the FooMain() for a given process type.
415 // If |process_type| is empty, runs BrowserMain().
416 // Returns the exit code for this process.
417 int RunNamedProcessTypeMain(
418 const std::string& process_type,
419 const MainFunctionParams& main_function_params,
420 ContentMainDelegate* delegate) {
421 static const MainFunction kMainFunctions[] = {
422 { "", BrowserMain },
423 { switches::kRendererProcess, RendererMain },
424 { switches::kPluginProcess, PluginMain },
425 { switches::kWorkerProcess, WorkerMain },
426 { switches::kPpapiPluginProcess, PpapiPluginMain },
427 { switches::kPpapiBrokerProcess, PpapiBrokerMain },
428 { switches::kUtilityProcess, UtilityMain },
429 { switches::kGpuProcess, GpuMain },
432 for (size_t i = 0; i < arraysize(kMainFunctions); ++i) {
433 if (process_type == kMainFunctions[i].name) {
434 if (delegate) {
435 int exit_code = delegate->RunProcess(process_type,
436 main_function_params);
437 #if defined(OS_ANDROID)
438 // In Android's browser process, the negative exit code doesn't mean the
439 // default behavior should be used as the UI message loop is managed by
440 // the Java and the browser process's default behavior is always
441 // overridden.
442 if (process_type.empty())
443 return exit_code;
444 #endif
445 if (exit_code >= 0)
446 return exit_code;
448 return kMainFunctions[i].function(main_function_params);
452 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
453 // Zygote startup is special -- see RunZygote comments above
454 // for why we don't use ZygoteMain directly.
455 if (process_type == switches::kZygoteProcess)
456 return RunZygote(main_function_params, delegate);
457 #endif
459 // If it's a process we don't know about, the embedder should know.
460 if (delegate)
461 return delegate->RunProcess(process_type, main_function_params);
463 NOTREACHED() << "Unknown process type: " << process_type;
464 return 1;
466 #endif // !OS_IOS
468 class ContentMainRunnerImpl : public ContentMainRunner {
469 public:
470 ContentMainRunnerImpl()
471 : is_initialized_(false),
472 is_shutdown_(false),
473 completed_basic_startup_(false),
474 delegate_(NULL) {
475 #if defined(OS_WIN)
476 memset(&sandbox_info_, 0, sizeof(sandbox_info_));
477 #endif
480 ~ContentMainRunnerImpl() {
481 if (is_initialized_ && !is_shutdown_)
482 Shutdown();
485 #if defined(USE_TCMALLOC)
486 static bool GetPropertyThunk(const char* name, size_t* value) {
487 return MallocExtension::instance()->GetNumericProperty(name, value);
490 static void GetStatsThunk(char* buffer, int buffer_length) {
491 MallocExtension::instance()->GetStats(buffer, buffer_length);
494 static void ReleaseFreeMemoryThunk() {
495 MallocExtension::instance()->ReleaseFreeMemory();
497 #endif
500 #if defined(OS_WIN)
501 virtual int Initialize(HINSTANCE instance,
502 sandbox::SandboxInterfaceInfo* sandbox_info,
503 ContentMainDelegate* delegate) OVERRIDE {
504 // argc/argv are ignored on Windows; see command_line.h for details.
505 int argc = 0;
506 char** argv = NULL;
508 RegisterInvalidParamHandler();
509 _Module.Init(NULL, static_cast<HINSTANCE>(instance));
511 sandbox_info_ = *sandbox_info;
512 #else // !OS_WIN
513 virtual int Initialize(int argc,
514 const char** argv,
515 ContentMainDelegate* delegate) OVERRIDE {
517 // NOTE(willchan): One might ask why these TCMalloc-related calls are done
518 // here rather than in process_util_linux.cc with the definition of
519 // EnableTerminationOnOutOfMemory(). That's because base shouldn't have a
520 // dependency on TCMalloc. Really, we ought to have our allocator shim code
521 // implement this EnableTerminationOnOutOfMemory() function. Whateverz.
522 // This works for now.
523 #if !defined(OS_MACOSX) && defined(USE_TCMALLOC)
525 #if defined(TYPE_PROFILING)
526 base::type_profiler::InterceptFunctions::SetFunctions(
527 base::type_profiler::NewInterceptForTCMalloc,
528 base::type_profiler::DeleteInterceptForTCMalloc);
529 #endif
531 // For tcmalloc, we need to tell it to behave like new.
532 tc_set_new_mode(1);
534 // On windows, we've already set these thunks up in _heap_init()
535 base::allocator::SetGetPropertyFunction(GetPropertyThunk);
536 base::allocator::SetGetStatsFunction(GetStatsThunk);
537 base::allocator::SetReleaseFreeMemoryFunction(ReleaseFreeMemoryThunk);
539 // Provide optional hook for monitoring allocation quantities on a
540 // per-thread basis. Only set the hook if the environment indicates this
541 // needs to be enabled.
542 const char* profiling = getenv(tracked_objects::kAlternateProfilerTime);
543 if (profiling &&
544 (atoi(profiling) == tracked_objects::TIME_SOURCE_TYPE_TCMALLOC)) {
545 tracked_objects::SetAlternateTimeSource(
546 MallocExtension::GetBytesAllocatedOnCurrentThread,
547 tracked_objects::TIME_SOURCE_TYPE_TCMALLOC);
549 #endif
551 // On Android,
552 // - setlocale() is not supported.
553 // - We do not override the signal handlers so that we can get
554 // stack trace when crashing.
555 // - The ipc_fd is passed through the Java service.
556 // Thus, these are all disabled.
557 #if !defined(OS_ANDROID) && !defined(OS_IOS)
558 // Set C library locale to make sure CommandLine can parse argument values
559 // in correct encoding.
560 setlocale(LC_ALL, "");
562 SetupSignalHandlers();
564 base::GlobalDescriptors* g_fds = base::GlobalDescriptors::GetInstance();
565 g_fds->Set(kPrimaryIPCChannel,
566 kPrimaryIPCChannel + base::GlobalDescriptors::kBaseDescriptor);
567 #endif // !OS_ANDROID && !OS_IOS
569 #if defined(OS_LINUX) || defined(OS_OPENBSD)
570 g_fds->Set(kCrashDumpSignal,
571 kCrashDumpSignal + base::GlobalDescriptors::kBaseDescriptor);
572 #endif
574 #endif // !OS_WIN
576 is_initialized_ = true;
577 delegate_ = delegate;
579 base::EnableTerminationOnHeapCorruption();
580 base::EnableTerminationOnOutOfMemory();
582 // The exit manager is in charge of calling the dtors of singleton objects.
583 // On Android, AtExitManager is set up when library is loaded.
584 // On iOS, it's set up in main(), which can't call directly through to here.
585 #if !defined(OS_ANDROID) && !defined(OS_IOS)
586 exit_manager_.reset(new base::AtExitManager);
587 #endif // !OS_ANDROID && !OS_IOS
589 #if defined(OS_MACOSX)
590 // We need this pool for all the objects created before we get to the
591 // event loop, but we don't want to leave them hanging around until the
592 // app quits. Each "main" needs to flush this pool right before it goes into
593 // its main event loop to get rid of the cruft.
594 autorelease_pool_.reset(new base::mac::ScopedNSAutoreleasePool());
595 #endif
597 // On Android, the command line is initialized when library is loaded.
598 #if !defined(OS_ANDROID)
599 CommandLine::Init(argc, argv);
600 #endif
602 int exit_code;
603 if (delegate && delegate->BasicStartupComplete(&exit_code))
604 return exit_code;
606 completed_basic_startup_ = true;
608 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
609 std::string process_type =
610 command_line.GetSwitchValueASCII(switches::kProcessType);
612 if (!GetContentClient())
613 SetContentClient(&empty_content_client_);
614 ContentClientInitializer::Set(process_type, delegate_);
616 #if defined(OS_WIN)
617 // Route stdio to parent console (if any) or create one.
618 if (command_line.HasSwitch(switches::kEnableLogging))
619 base::RouteStdioToConsole();
620 #endif
622 // Enable startup tracing asap to avoid early TRACE_EVENT calls being
623 // ignored.
624 if (command_line.HasSwitch(switches::kTraceStartup)) {
625 base::debug::TraceLog::GetInstance()->SetEnabled(
626 command_line.GetSwitchValueASCII(switches::kTraceStartup));
629 #if defined(OS_MACOSX) && !defined(OS_IOS)
630 // We need to allocate the IO Ports before the Sandbox is initialized or
631 // the first instance of SystemMonitor is created.
632 // It's important not to allocate the ports for processes which don't
633 // register with the system monitor - see crbug.com/88867.
634 if (process_type.empty() ||
635 process_type == switches::kPluginProcess ||
636 process_type == switches::kRendererProcess ||
637 process_type == switches::kUtilityProcess ||
638 process_type == switches::kWorkerProcess ||
639 (delegate &&
640 delegate->ProcessRegistersWithSystemProcess(process_type))) {
641 base::SystemMonitor::AllocateSystemIOPorts();
644 if (!process_type.empty() &&
645 (!delegate || delegate->ShouldSendMachPort(process_type))) {
646 SendTaskPortToParentProcess();
648 #elif defined(OS_WIN)
649 // This must be done early enough since some helper functions like
650 // IsTouchEnanbled, needed to load resources, may call into the theme dll.
651 EnableThemeSupportOnAllWindowStations();
652 #if defined(ENABLE_HIDPI)
653 ui::EnableHighDPISupport();
654 #endif
655 SetupCRT(command_line);
656 #endif
658 #if defined(OS_POSIX)
659 if (!process_type.empty()) {
660 // When you hit Ctrl-C in a terminal running the browser
661 // process, a SIGINT is delivered to the entire process group.
662 // When debugging the browser process via gdb, gdb catches the
663 // SIGINT for the browser process (and dumps you back to the gdb
664 // console) but doesn't for the child processes, killing them.
665 // The fix is to have child processes ignore SIGINT; they'll die
666 // on their own when the browser process goes away.
668 // Note that we *can't* rely on BeingDebugged to catch this case because
669 // we are the child process, which is not being debugged.
670 // TODO(evanm): move this to some shared subprocess-init function.
671 if (!base::debug::BeingDebugged())
672 signal(SIGINT, SIG_IGN);
674 #endif
676 #if defined(USE_NSS)
677 crypto::EarlySetupForNSSInit();
678 #endif
680 ui::RegisterPathProvider();
681 RegisterPathProvider();
682 RegisterContentSchemes(true);
684 CHECK(icu_util::Initialize());
686 InitializeStatsTable(command_line);
688 if (delegate)
689 delegate->PreSandboxStartup();
691 // Set any custom user agent passed on the command line now so the string
692 // doesn't change between calls to webkit_glue::GetUserAgent(), otherwise it
693 // defaults to the user agent set during SetContentClient().
694 if (command_line.HasSwitch(switches::kUserAgent)) {
695 webkit_glue::SetUserAgent(
696 command_line.GetSwitchValueASCII(switches::kUserAgent), true);
699 if (!process_type.empty())
700 CommonSubprocessInit(process_type);
702 #if defined(OS_WIN)
703 CHECK(InitializeSandbox(sandbox_info));
704 #elif defined(OS_MACOSX) && !defined(OS_IOS)
705 if (process_type == switches::kRendererProcess ||
706 process_type == switches::kPpapiPluginProcess ||
707 (delegate && delegate->DelaySandboxInitialization(process_type))) {
708 // On OS X the renderer sandbox needs to be initialized later in the
709 // startup sequence in RendererMainPlatformDelegate::EnableSandbox().
710 } else {
711 CHECK(InitializeSandbox());
713 #endif
715 if (delegate)
716 delegate->SandboxInitialized(process_type);
718 #if defined(OS_POSIX) && !defined(OS_IOS)
719 SetProcessTitleFromCommandLine(argv);
720 #endif
722 // Return -1 to indicate no early termination.
723 return -1;
726 virtual int Run() OVERRIDE {
727 DCHECK(is_initialized_);
728 DCHECK(!is_shutdown_);
729 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
730 std::string process_type =
731 command_line.GetSwitchValueASCII(switches::kProcessType);
733 MainFunctionParams main_params(command_line);
734 #if defined(OS_WIN)
735 main_params.sandbox_info = &sandbox_info_;
736 #elif defined(OS_MACOSX)
737 main_params.autorelease_pool = autorelease_pool_.get();
738 #endif
740 #if !defined(OS_IOS)
741 return RunNamedProcessTypeMain(process_type, main_params, delegate_);
742 #else
743 return 1;
744 #endif
747 virtual void Shutdown() OVERRIDE {
748 DCHECK(is_initialized_);
749 DCHECK(!is_shutdown_);
751 if (completed_basic_startup_ && delegate_) {
752 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
753 std::string process_type =
754 command_line.GetSwitchValueASCII(switches::kProcessType);
756 delegate_->ProcessExiting(process_type);
759 #if defined(OS_WIN)
760 #ifdef _CRTDBG_MAP_ALLOC
761 _CrtDumpMemoryLeaks();
762 #endif // _CRTDBG_MAP_ALLOC
764 _Module.Term();
765 #endif // OS_WIN
767 #if defined(OS_MACOSX)
768 autorelease_pool_.reset(NULL);
769 #endif
771 exit_manager_.reset(NULL);
773 delegate_ = NULL;
774 is_shutdown_ = true;
777 private:
778 // True if the runner has been initialized.
779 bool is_initialized_;
781 // True if the runner has been shut down.
782 bool is_shutdown_;
784 // True if basic startup was completed.
785 bool completed_basic_startup_;
787 // Used if the embedder doesn't set one.
788 ContentClient empty_content_client_;
790 // The delegate will outlive this object.
791 ContentMainDelegate* delegate_;
793 scoped_ptr<base::AtExitManager> exit_manager_;
794 #if defined(OS_WIN)
795 sandbox::SandboxInterfaceInfo sandbox_info_;
796 #elif defined(OS_MACOSX)
797 scoped_ptr<base::mac::ScopedNSAutoreleasePool> autorelease_pool_;
798 #endif
800 DISALLOW_COPY_AND_ASSIGN(ContentMainRunnerImpl);
803 // static
804 ContentMainRunner* ContentMainRunner::Create() {
805 return new ContentMainRunnerImpl();
808 } // namespace content