Change DtmfSenderHandler to handle events on the signaling thread.
[chromium-blink-merge.git] / chrome / app / chrome_main_delegate.cc
blob118ac5d1f74bd9772469d4b2a1ef67ad2c72b034
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 "chrome/app/chrome_main_delegate.h"
7 #include "base/base_paths.h"
8 #include "base/command_line.h"
9 #include "base/cpu.h"
10 #include "base/files/file_path.h"
11 #include "base/i18n/rtl.h"
12 #include "base/lazy_instance.h"
13 #include "base/message_loop/message_loop.h"
14 #include "base/metrics/statistics_recorder.h"
15 #include "base/metrics/stats_counters.h"
16 #include "base/path_service.h"
17 #include "base/process/memory.h"
18 #include "base/process/process_handle.h"
19 #include "base/strings/string_util.h"
20 #include "build/build_config.h"
21 #include "chrome/browser/chrome_content_browser_client.h"
22 #include "chrome/browser/defaults.h"
23 #include "chrome/common/chrome_constants.h"
24 #include "chrome/common/chrome_content_client.h"
25 #include "chrome/common/chrome_paths.h"
26 #include "chrome/common/chrome_paths_internal.h"
27 #include "chrome/common/chrome_switches.h"
28 #include "chrome/common/chrome_version_info.h"
29 #include "chrome/common/crash_keys.h"
30 #include "chrome/common/logging_chrome.h"
31 #include "chrome/common/profiling.h"
32 #include "chrome/common/switch_utils.h"
33 #include "chrome/common/url_constants.h"
34 #include "chrome/plugin/chrome_content_plugin_client.h"
35 #include "chrome/renderer/chrome_content_renderer_client.h"
36 #include "chrome/utility/chrome_content_utility_client.h"
37 #include "components/component_updater/component_updater_paths.h"
38 #include "components/content_settings/core/common/content_settings_pattern.h"
39 #include "components/startup_metric_utils/startup_metric_utils.h"
40 #include "content/public/common/content_client.h"
41 #include "content/public/common/content_paths.h"
42 #include "extensions/common/constants.h"
43 #include "ui/base/ui_base_switches.h"
45 #if defined(OS_WIN)
46 #include <atlbase.h>
47 #include <malloc.h>
48 #include <algorithm>
49 #include "chrome/app/close_handle_hook_win.h"
50 #include "chrome/common/child_process_logging.h"
51 #include "chrome/common/terminate_on_heap_corruption_experiment_win.h"
52 #include "chrome/common/v8_breakpad_support_win.h"
53 #include "sandbox/win/src/sandbox.h"
54 #include "ui/base/resource/resource_bundle_win.h"
55 #endif
57 #if defined(OS_MACOSX)
58 #include "base/mac/mac_util.h"
59 #include "base/mac/os_crash_dumps.h"
60 #include "chrome/app/chrome_main_mac.h"
61 #include "chrome/browser/mac/relauncher.h"
62 #include "chrome/common/mac/cfbundle_blocker.h"
63 #include "chrome/common/mac/objc_zombie.h"
64 #include "components/crash/app/breakpad_mac.h"
65 #include "ui/base/l10n/l10n_util_mac.h"
66 #endif
68 #if defined(OS_POSIX)
69 #include <locale.h>
70 #include <signal.h>
71 #include "chrome/app/chrome_crash_reporter_client.h"
72 #include "components/crash/app/crash_reporter_client.h"
73 #endif
75 #if !defined(DISABLE_NACL) && defined(OS_LINUX)
76 #include "components/nacl/common/nacl_paths.h"
77 #include "components/nacl/zygote/nacl_fork_delegate_linux.h"
78 #endif
80 #if defined(OS_CHROMEOS)
81 #include "base/sys_info.h"
82 #include "chrome/browser/chromeos/boot_times_loader.h"
83 #include "chromeos/chromeos_paths.h"
84 #include "chromeos/chromeos_switches.h"
85 #endif
87 #if defined(OS_ANDROID)
88 #include "chrome/common/descriptors_android.h"
89 #else
90 // Diagnostics is only available on non-android platforms.
91 #include "chrome/browser/diagnostics/diagnostics_controller.h"
92 #include "chrome/browser/diagnostics/diagnostics_writer.h"
93 #endif
95 #if defined(USE_X11)
96 #include <stdlib.h>
97 #include <string.h>
98 #include "ui/base/x/x11_util.h"
99 #endif
101 #if defined(OS_POSIX) && !defined(OS_MACOSX)
102 #include "components/crash/app/breakpad_linux.h"
103 #endif
105 #if defined(OS_LINUX)
106 #include "base/environment.h"
107 #endif
109 #if defined(OS_MACOSX) || defined(OS_WIN)
110 #include "chrome/browser/policy/policy_path_parser.h"
111 #endif
113 #if !defined(DISABLE_NACL)
114 #include "components/nacl/common/nacl_switches.h"
115 #endif
117 #if !defined(CHROME_MULTIPLE_DLL_CHILD)
118 base::LazyInstance<chrome::ChromeContentBrowserClient>
119 g_chrome_content_browser_client = LAZY_INSTANCE_INITIALIZER;
120 #endif
122 #if !defined(CHROME_MULTIPLE_DLL_BROWSER)
123 base::LazyInstance<ChromeContentRendererClient>
124 g_chrome_content_renderer_client = LAZY_INSTANCE_INITIALIZER;
125 base::LazyInstance<ChromeContentUtilityClient>
126 g_chrome_content_utility_client = LAZY_INSTANCE_INITIALIZER;
127 base::LazyInstance<chrome::ChromeContentPluginClient>
128 g_chrome_content_plugin_client = LAZY_INSTANCE_INITIALIZER;
129 #endif
131 #if defined(OS_POSIX)
132 base::LazyInstance<chrome::ChromeCrashReporterClient>::Leaky
133 g_chrome_crash_client = LAZY_INSTANCE_INITIALIZER;
134 #endif
136 extern int NaClMain(const content::MainFunctionParams&);
137 extern int ServiceProcessMain(const content::MainFunctionParams&);
139 namespace {
141 #if defined(OS_WIN)
142 // Early versions of Chrome incorrectly registered a chromehtml: URL handler,
143 // which gives us nothing but trouble. Avoid launching chrome this way since
144 // some apps fail to properly escape arguments.
145 bool HasDeprecatedArguments(const std::wstring& command_line) {
146 const wchar_t kChromeHtml[] = L"chromehtml:";
147 std::wstring command_line_lower = command_line;
148 // We are only searching for ASCII characters so this is OK.
149 base::StringToLowerASCII(&command_line_lower);
150 std::wstring::size_type pos = command_line_lower.find(kChromeHtml);
151 return (pos != std::wstring::npos);
154 // If we try to access a path that is not currently available, we want the call
155 // to fail rather than show an error dialog.
156 void SuppressWindowsErrorDialogs() {
157 UINT new_flags = SEM_FAILCRITICALERRORS |
158 SEM_NOOPENFILEERRORBOX;
160 // Preserve existing error mode.
161 UINT existing_flags = SetErrorMode(new_flags);
162 SetErrorMode(existing_flags | new_flags);
165 #endif // defined(OS_WIN)
167 #if defined(OS_LINUX)
168 static void AdjustLinuxOOMScore(const std::string& process_type) {
169 // Browsers and zygotes should still be killable, but killed last.
170 const int kZygoteScore = 0;
171 // The minimum amount to bump a score by. This is large enough that
172 // even if it's translated into the old values, it will still go up
173 // by at least one.
174 const int kScoreBump = 100;
175 // This is the lowest score that renderers and extensions start with
176 // in the OomPriorityManager.
177 const int kRendererScore = chrome::kLowestRendererOomScore;
178 // For "miscellaneous" things, we want them after renderers,
179 // but before plugins.
180 const int kMiscScore = kRendererScore - kScoreBump;
181 // We want plugins to die after the renderers.
182 const int kPluginScore = kMiscScore - kScoreBump;
183 int score = -1;
185 DCHECK(kMiscScore > 0);
186 DCHECK(kPluginScore > 0);
188 if (process_type == switches::kPluginProcess ||
189 process_type == switches::kPpapiPluginProcess) {
190 score = kPluginScore;
191 } else if (process_type == switches::kPpapiBrokerProcess) {
192 // The broker should be killed before the PPAPI plugin.
193 score = kPluginScore + kScoreBump;
194 } else if (process_type == switches::kUtilityProcess ||
195 process_type == switches::kGpuProcess ||
196 process_type == switches::kServiceProcess) {
197 score = kMiscScore;
198 #ifndef DISABLE_NACL
199 } else if (process_type == switches::kNaClLoaderProcess ||
200 process_type == switches::kNaClLoaderNonSfiProcess) {
201 score = kPluginScore;
202 #endif
203 } else if (process_type == switches::kZygoteProcess ||
204 process_type.empty()) {
205 // For zygotes and unlabeled process types, we want to still make
206 // them killable by the OOM killer.
207 score = kZygoteScore;
208 } else if (process_type == switches::kRendererProcess) {
209 LOG(WARNING) << "process type 'renderer' "
210 << "should be created through the zygote.";
211 // When debugging, this process type can end up being run directly, but
212 // this isn't the typical path for assigning the OOM score for it. Still,
213 // we want to assign a score that is somewhat representative for debugging.
214 score = kRendererScore;
215 } else {
216 NOTREACHED() << "Unknown process type";
218 if (score > -1)
219 base::AdjustOOMScore(base::GetCurrentProcId(), score);
221 #endif // defined(OS_LINUX)
223 // Returns true if this subprocess type needs the ResourceBundle initialized
224 // and resources loaded.
225 bool SubprocessNeedsResourceBundle(const std::string& process_type) {
226 return
227 #if defined(OS_WIN) || defined(OS_MACOSX)
228 // Windows needs resources for the default/null plugin.
229 // Mac needs them for the plugin process name.
230 process_type == switches::kPluginProcess ||
231 #endif
232 #if defined(OS_POSIX) && !defined(OS_MACOSX)
233 // The zygote process opens the resources for the renderers.
234 process_type == switches::kZygoteProcess ||
235 #endif
236 #if defined(OS_MACOSX)
237 // Mac needs them too for scrollbar related images and for sandbox
238 // profiles.
239 #if !defined(DISABLE_NACL)
240 process_type == switches::kNaClLoaderProcess ||
241 #endif
242 process_type == switches::kPpapiPluginProcess ||
243 process_type == switches::kPpapiBrokerProcess ||
244 process_type == switches::kGpuProcess ||
245 #endif
246 process_type == switches::kRendererProcess ||
247 process_type == switches::kUtilityProcess;
250 #if defined(OS_POSIX)
251 // Check for --version and --product-version; return true if we encountered
252 // one of these switches and should exit now.
253 bool HandleVersionSwitches(const CommandLine& command_line) {
254 const chrome::VersionInfo version_info;
256 #if !defined(OS_MACOSX)
257 if (command_line.HasSwitch(switches::kProductVersion)) {
258 printf("%s\n", version_info.Version().c_str());
259 return true;
261 #endif
263 if (command_line.HasSwitch(switches::kVersion)) {
264 printf("%s %s %s\n",
265 version_info.Name().c_str(),
266 version_info.Version().c_str(),
267 chrome::VersionInfo::GetVersionStringModifier().c_str());
268 return true;
271 return false;
274 #if !defined(OS_MACOSX) && !defined(OS_CHROMEOS)
275 // Show the man page if --help or -h is on the command line.
276 void HandleHelpSwitches(const CommandLine& command_line) {
277 if (command_line.HasSwitch(switches::kHelp) ||
278 command_line.HasSwitch(switches::kHelpShort)) {
279 base::FilePath binary(command_line.argv()[0]);
280 execlp("man", "man", binary.BaseName().value().c_str(), NULL);
281 PLOG(FATAL) << "execlp failed";
284 #endif
286 #if !defined(OS_MACOSX) && !defined(OS_ANDROID)
287 void SIGTERMProfilingShutdown(int signal) {
288 Profiling::Stop();
289 struct sigaction sigact;
290 memset(&sigact, 0, sizeof(sigact));
291 sigact.sa_handler = SIG_DFL;
292 CHECK(sigaction(SIGTERM, &sigact, NULL) == 0);
293 raise(signal);
296 void SetUpProfilingShutdownHandler() {
297 struct sigaction sigact;
298 sigact.sa_handler = SIGTERMProfilingShutdown;
299 sigact.sa_flags = SA_RESETHAND;
300 sigemptyset(&sigact.sa_mask);
301 CHECK(sigaction(SIGTERM, &sigact, NULL) == 0);
303 #endif // !defined(OS_MACOSX) && !defined(OS_ANDROID)
305 #endif // OS_POSIX
307 struct MainFunction {
308 const char* name;
309 int (*function)(const content::MainFunctionParams&);
312 // Initializes the user data dir. Must be called before InitializeLocalState().
313 void InitializeUserDataDir() {
314 CommandLine* command_line = CommandLine::ForCurrentProcess();
315 base::FilePath user_data_dir =
316 command_line->GetSwitchValuePath(switches::kUserDataDir);
317 std::string process_type =
318 command_line->GetSwitchValueASCII(switches::kProcessType);
320 #if defined(OS_LINUX)
321 // On Linux, Chrome does not support running multiple copies under different
322 // DISPLAYs, so the profile directory can be specified in the environment to
323 // support the virtual desktop use-case.
324 if (user_data_dir.empty()) {
325 std::string user_data_dir_string;
326 scoped_ptr<base::Environment> environment(base::Environment::Create());
327 if (environment->GetVar("CHROME_USER_DATA_DIR", &user_data_dir_string) &&
328 base::IsStringUTF8(user_data_dir_string)) {
329 user_data_dir = base::FilePath::FromUTF8Unsafe(user_data_dir_string);
332 #endif
333 #if defined(OS_MACOSX) || defined(OS_WIN)
334 policy::path_parser::CheckUserDataDirPolicy(&user_data_dir);
335 #endif
337 const bool specified_directory_was_invalid = !user_data_dir.empty() &&
338 !PathService::OverrideAndCreateIfNeeded(chrome::DIR_USER_DATA,
339 user_data_dir, false, true);
340 // Save inaccessible or invalid paths so the user may be prompted later.
341 if (specified_directory_was_invalid)
342 chrome::SetInvalidSpecifiedUserDataDir(user_data_dir);
344 // Warn and fail early if the process fails to get a user data directory.
345 if (!PathService::Get(chrome::DIR_USER_DATA, &user_data_dir)) {
346 // If an invalid command-line or policy override was specified, the user
347 // will be given an error with that value. Otherwise, use the directory
348 // returned by PathService (or the fallback default directory) in the error.
349 if (!specified_directory_was_invalid) {
350 // PathService::Get() returns false and yields an empty path if it fails
351 // to create DIR_USER_DATA. Retrieve the default value manually to display
352 // a more meaningful error to the user in that case.
353 if (user_data_dir.empty())
354 chrome::GetDefaultUserDataDirectory(&user_data_dir);
355 chrome::SetInvalidSpecifiedUserDataDir(user_data_dir);
358 // The browser process (which is identified by an empty |process_type|) will
359 // handle the error later; other processes that need the dir crash here.
360 CHECK(process_type.empty()) << "Unable to get the user data directory "
361 << "for process type: " << process_type;
364 // Append the fallback user data directory to the commandline. Otherwise,
365 // child or service processes will attempt to use the invalid directory.
366 if (specified_directory_was_invalid)
367 command_line->AppendSwitchPath(switches::kUserDataDir, user_data_dir);
370 } // namespace
372 ChromeMainDelegate::ChromeMainDelegate() {
373 #if defined(OS_ANDROID)
374 // On Android the main entry point time is the time when the Java code starts.
375 // This happens before the shared library containing this code is even loaded.
376 // The Java startup code has recorded that time, but the C++ code can't fetch it
377 // from the Java side until it has initialized the JNI. See
378 // ChromeMainDelegateAndroid.
379 #else
380 startup_metric_utils::RecordMainEntryPointTime();
381 #endif
384 ChromeMainDelegate::~ChromeMainDelegate() {
387 bool ChromeMainDelegate::BasicStartupComplete(int* exit_code) {
388 #if defined(OS_CHROMEOS)
389 chromeos::BootTimesLoader::Get()->SaveChromeMainStats();
390 #endif
392 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
394 #if defined(OS_MACOSX)
395 // Give the browser process a longer treadmill, since crashes
396 // there have more impact.
397 const bool is_browser = !command_line.HasSwitch(switches::kProcessType);
398 ObjcEvilDoers::ZombieEnable(true, is_browser ? 10000 : 1000);
400 SetUpBundleOverrides();
401 chrome::common::mac::EnableCFBundleBlocker();
402 #endif
404 Profiling::ProcessStarted();
406 #if defined(OS_WIN)
407 v8_breakpad_support::SetUp();
408 #endif
410 #if defined(OS_POSIX)
411 if (HandleVersionSwitches(command_line)) {
412 *exit_code = 0;
413 return true; // Got a --version switch; exit with a success error code.
415 #if !defined(OS_MACOSX) && !defined(OS_CHROMEOS)
416 // This will directly exit if the user asked for help.
417 HandleHelpSwitches(command_line);
418 #endif
419 #endif // OS_POSIX
421 #if defined(OS_WIN)
422 // Must do this before any other usage of command line!
423 if (HasDeprecatedArguments(command_line.GetCommandLineString())) {
424 *exit_code = 1;
425 return true;
428 InstallCloseHandleHooks();
429 #endif
431 chrome::RegisterPathProvider();
432 #if defined(OS_CHROMEOS)
433 chromeos::RegisterPathProvider();
434 #endif
435 #if !defined(DISABLE_NACL) && defined(OS_LINUX)
436 nacl::RegisterPathProvider();
437 #endif
439 ContentSettingsPattern::SetNonWildcardDomainNonPortScheme(
440 extensions::kExtensionScheme);
442 // No support for ANDROID yet as DiagnosticsController needs wchar support.
443 // TODO(gspencer): That's not true anymore, or at least there are no w-string
444 // references anymore. Not sure if that means this can be enabled on Android or
445 // not though. As there is no easily accessible command line on Android, I'm
446 // not sure this is a big deal.
447 #if !defined(OS_ANDROID) && !defined(CHROME_MULTIPLE_DLL_CHILD)
448 // If we are in diagnostics mode this is the end of the line: after the
449 // diagnostics are run the process will invariably exit.
450 if (command_line.HasSwitch(switches::kDiagnostics)) {
451 diagnostics::DiagnosticsWriter::FormatType format =
452 diagnostics::DiagnosticsWriter::HUMAN;
453 if (command_line.HasSwitch(switches::kDiagnosticsFormat)) {
454 std::string format_str =
455 command_line.GetSwitchValueASCII(switches::kDiagnosticsFormat);
456 if (format_str == "machine") {
457 format = diagnostics::DiagnosticsWriter::MACHINE;
458 } else if (format_str == "log") {
459 format = diagnostics::DiagnosticsWriter::LOG;
460 } else {
461 DCHECK_EQ("human", format_str);
465 diagnostics::DiagnosticsWriter writer(format);
466 *exit_code = diagnostics::DiagnosticsController::GetInstance()->Run(
467 command_line, &writer);
468 diagnostics::DiagnosticsController::GetInstance()->ClearResults();
469 return true;
471 #endif
473 #if defined(OS_CHROMEOS)
474 // Initialize primary user homedir (in multi-profile session) as it may be
475 // passed as a command line switch.
476 base::FilePath homedir;
477 if (command_line.HasSwitch(chromeos::switches::kHomedir)) {
478 homedir = base::FilePath(
479 command_line.GetSwitchValueASCII(chromeos::switches::kHomedir));
480 PathService::OverrideAndCreateIfNeeded(
481 base::DIR_HOME, homedir, true, false);
484 // If we are recovering from a crash on ChromeOS, then we will do some
485 // recovery using the diagnostics module, and then continue on. We fake up a
486 // command line to tell it that we want it to recover, and to preserve the
487 // original command line.
488 if (command_line.HasSwitch(chromeos::switches::kLoginUser) ||
489 command_line.HasSwitch(switches::kDiagnosticsRecovery)) {
490 // The statistics subsystem needs get initialized soon enough for the
491 // statistics to be collected. It's safe to call this more than once.
492 base::StatisticsRecorder::Initialize();
494 CommandLine interim_command_line(command_line.GetProgram());
495 const char* const kSwitchNames[] = {switches::kUserDataDir, };
496 interim_command_line.CopySwitchesFrom(
497 command_line, kSwitchNames, arraysize(kSwitchNames));
498 interim_command_line.AppendSwitch(switches::kDiagnostics);
499 interim_command_line.AppendSwitch(switches::kDiagnosticsRecovery);
501 diagnostics::DiagnosticsWriter::FormatType format =
502 diagnostics::DiagnosticsWriter::LOG;
503 if (command_line.HasSwitch(switches::kDiagnosticsFormat)) {
504 std::string format_str =
505 command_line.GetSwitchValueASCII(switches::kDiagnosticsFormat);
506 if (format_str == "machine") {
507 format = diagnostics::DiagnosticsWriter::MACHINE;
508 } else if (format_str == "human") {
509 format = diagnostics::DiagnosticsWriter::HUMAN;
510 } else {
511 DCHECK_EQ("log", format_str);
515 diagnostics::DiagnosticsWriter writer(format);
516 int diagnostics_exit_code =
517 diagnostics::DiagnosticsController::GetInstance()->Run(command_line,
518 &writer);
519 if (diagnostics_exit_code) {
520 // Diagnostics has failed somehow, so we exit.
521 *exit_code = diagnostics_exit_code;
522 return true;
525 // Now we run the actual recovery tasks.
526 int recovery_exit_code =
527 diagnostics::DiagnosticsController::GetInstance()->RunRecovery(
528 command_line, &writer);
530 if (recovery_exit_code) {
531 // Recovery has failed somehow, so we exit.
532 *exit_code = recovery_exit_code;
533 return true;
535 } else { // Not running diagnostics or recovery.
536 diagnostics::DiagnosticsController::GetInstance()->RecordRegularStartup();
538 #endif
540 content::SetContentClient(&chrome_content_client_);
542 return false;
545 #if defined(OS_MACOSX)
546 void ChromeMainDelegate::InitMacCrashReporter(
547 const base::CommandLine& command_line,
548 const std::string& process_type) {
549 // TODO(mark): Right now, InitCrashReporter() needs to be called after
550 // CommandLine::Init() and chrome::RegisterPathProvider(). Ideally,
551 // Breakpad initialization could occur sooner, preferably even before the
552 // framework dylib is even loaded, to catch potential early crashes.
553 breakpad::InitCrashReporter(process_type);
555 #if defined(NDEBUG)
556 bool is_debug_build = false;
557 #else
558 bool is_debug_build = true;
559 #endif
561 // Details on when we enable Apple's Crash reporter.
563 // Motivation:
564 // In debug mode it takes Apple's crash reporter eons to generate a crash
565 // dump.
567 // What we do:
568 // * We only pass crashes for foreground processes to Apple's Crash
569 // reporter. At the time of this writing, that means just the Browser
570 // process.
571 // * If Breakpad is enabled, it will pass browser crashes to Crash Reporter
572 // itself.
573 // * If Breakpad is disabled, we only turn on Crash Reporter for the
574 // Browser process in release mode.
575 if (!command_line.HasSwitch(switches::kDisableBreakpad)) {
576 bool disable_apple_crash_reporter = is_debug_build ||
577 base::mac::IsBackgroundOnlyProcess();
578 if (!breakpad::IsCrashReporterEnabled() && disable_apple_crash_reporter) {
579 base::mac::DisableOSCrashDumps();
583 // Mac Chrome is packaged with a main app bundle and a helper app bundle.
584 // The main app bundle should only be used for the browser process, so it
585 // should never see a --type switch (switches::kProcessType). Likewise,
586 // the helper should always have a --type switch.
588 // This check is done this late so there is already a call to
589 // base::mac::IsBackgroundOnlyProcess(), so there is no change in
590 // startup/initialization order.
592 // The helper's Info.plist marks it as a background only app.
593 if (base::mac::IsBackgroundOnlyProcess()) {
594 CHECK(command_line.HasSwitch(switches::kProcessType) &&
595 !process_type.empty())
596 << "Helper application requires --type.";
598 // In addition, some helper flavors only work with certain process types.
599 base::FilePath executable;
600 if (PathService::Get(base::FILE_EXE, &executable) &&
601 executable.value().size() >= 3) {
602 std::string last_three =
603 executable.value().substr(executable.value().size() - 3);
605 if (last_three == " EH") {
606 CHECK(process_type == switches::kPluginProcess ||
607 process_type == switches::kUtilityProcess)
608 << "Executable-heap process requires --type="
609 << switches::kPluginProcess << " or "
610 << switches::kUtilityProcess << ", saw " << process_type;
611 } else if (last_three == " NP") {
612 #if !defined(DISABLE_NACL)
613 CHECK_EQ(switches::kNaClLoaderProcess, process_type)
614 << "Non-PIE process requires --type="
615 << switches::kNaClLoaderProcess << ", saw " << process_type;
616 #endif
617 } else {
618 #if defined(DISABLE_NACL)
619 CHECK(process_type != switches::kPluginProcess)
620 << "Non-executable-heap PIE process is intolerant of --type="
621 << switches::kPluginProcess;
622 #else
623 CHECK(process_type != switches::kPluginProcess &&
624 process_type != switches::kNaClLoaderProcess)
625 << "Non-executable-heap PIE process is intolerant of --type="
626 << switches::kPluginProcess << " and "
627 << switches::kNaClLoaderProcess << ", saw " << process_type;
628 #endif
631 } else {
632 CHECK(!command_line.HasSwitch(switches::kProcessType) &&
633 process_type.empty())
634 << "Main application forbids --type, saw " << process_type;
637 if (breakpad::IsCrashReporterEnabled())
638 breakpad::InitCrashProcessInfo(process_type);
640 #endif // defined(OS_MACOSX)
642 void ChromeMainDelegate::PreSandboxStartup() {
643 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
644 std::string process_type =
645 command_line.GetSwitchValueASCII(switches::kProcessType);
647 #if defined(OS_POSIX)
648 crash_reporter::SetCrashReporterClient(g_chrome_crash_client.Pointer());
649 #endif
651 #if defined(OS_MACOSX)
652 // On the Mac, the child executable lives at a predefined location within
653 // the app bundle's versioned directory.
654 PathService::Override(content::CHILD_PROCESS_EXE,
655 chrome::GetVersionedDirectory().
656 Append(chrome::kHelperProcessExecutablePath));
658 InitMacCrashReporter(command_line, process_type);
659 #endif
661 #if defined(OS_WIN)
662 child_process_logging::Init();
663 #endif
664 #if defined(ARCH_CPU_ARM_FAMILY) && (defined(OS_ANDROID) || defined(OS_LINUX))
665 // Create an instance of the CPU class to parse /proc/cpuinfo and cache
666 // cpu_brand info.
667 base::CPU cpu_info;
668 #endif
670 // Initialize the user data dir for any process type that needs it.
671 if (chrome::ProcessNeedsProfileDir(process_type))
672 InitializeUserDataDir();
674 // Register component_updater PathProvider after DIR_USER_DATA overidden by
675 // command line flags. Maybe move the chrome PathProvider down here also?
676 component_updater::RegisterPathProvider(chrome::DIR_USER_DATA);
678 stats_counter_timer_.reset(new base::StatsCounterTimer("Chrome.Init"));
679 startup_timer_.reset(new base::StatsScope<base::StatsCounterTimer>
680 (*stats_counter_timer_));
682 // Enable Message Loop related state asap.
683 if (command_line.HasSwitch(switches::kMessageLoopHistogrammer))
684 base::MessageLoop::EnableHistogrammer(true);
686 #if !defined(OS_ANDROID)
687 // Android does InitLogging when library is loaded. Skip here.
688 logging::OldFileDeletionState file_state =
689 logging::APPEND_TO_OLD_LOG_FILE;
690 if (process_type.empty()) {
691 file_state = logging::DELETE_OLD_LOG_FILE;
693 logging::InitChromeLogging(command_line, file_state);
694 #endif
696 #if defined(OS_WIN)
697 // TODO(zturner): Throbber icons are still stored in chrome.dll, this can be
698 // killed once those are merged into resources.pak. See
699 // GlassBrowserFrameView::InitThrobberIcons() and http://crbug.com/368327.
700 ui::SetResourcesDataDLL(_AtlBaseModule.GetResourceInstance());
701 #endif
703 if (SubprocessNeedsResourceBundle(process_type)) {
704 // Initialize ResourceBundle which handles files loaded from external
705 // sources. The language should have been passed in to us from the
706 // browser process as a command line flag.
707 #if defined(DISABLE_NACL)
708 DCHECK(command_line.HasSwitch(switches::kLang) ||
709 process_type == switches::kZygoteProcess ||
710 process_type == switches::kGpuProcess ||
711 process_type == switches::kPpapiBrokerProcess ||
712 process_type == switches::kPpapiPluginProcess);
713 #else
714 DCHECK(command_line.HasSwitch(switches::kLang) ||
715 process_type == switches::kZygoteProcess ||
716 process_type == switches::kGpuProcess ||
717 process_type == switches::kNaClLoaderProcess ||
718 process_type == switches::kPpapiBrokerProcess ||
719 process_type == switches::kPpapiPluginProcess);
720 #endif
722 // TODO(markusheintz): The command line flag --lang is actually processed
723 // by the CommandLinePrefStore, and made available through the PrefService
724 // via the preference prefs::kApplicationLocale. The browser process uses
725 // the --lang flag to pass the value of the PrefService in here. Maybe
726 // this value could be passed in a different way.
727 const std::string locale =
728 command_line.GetSwitchValueASCII(switches::kLang);
729 #if defined(OS_ANDROID)
730 // The renderer sandbox prevents us from accessing our .pak files directly.
731 // Therefore file descriptors to the .pak files that we need are passed in
732 // at process creation time.
733 int locale_pak_fd = base::GlobalDescriptors::GetInstance()->MaybeGet(
734 kAndroidLocalePakDescriptor);
735 CHECK(locale_pak_fd != -1);
736 ResourceBundle::InitSharedInstanceWithPakFileRegion(
737 base::File(locale_pak_fd), base::MemoryMappedFile::Region::kWholeFile);
739 int extra_pak_keys[] = {
740 kAndroidChrome100PercentPakDescriptor,
741 kAndroidUIResourcesPakDescriptor,
743 for (size_t i = 0; i < arraysize(extra_pak_keys); ++i) {
744 int pak_fd =
745 base::GlobalDescriptors::GetInstance()->MaybeGet(extra_pak_keys[i]);
746 CHECK(pak_fd != -1);
747 ResourceBundle::GetSharedInstance().AddDataPackFromFile(
748 base::File(pak_fd), ui::SCALE_FACTOR_100P);
751 base::i18n::SetICUDefaultLocale(locale);
752 const std::string loaded_locale = locale;
753 #else
754 const std::string loaded_locale =
755 ui::ResourceBundle::InitSharedInstanceWithLocale(
756 locale, NULL, ui::ResourceBundle::LOAD_COMMON_RESOURCES);
758 base::FilePath resources_pack_path;
759 PathService::Get(chrome::FILE_RESOURCES_PACK, &resources_pack_path);
760 ResourceBundle::GetSharedInstance().AddDataPackFromPath(
761 resources_pack_path, ui::SCALE_FACTOR_NONE);
762 #endif
763 CHECK(!loaded_locale.empty()) << "Locale could not be found for " <<
764 locale;
766 #if !defined(CHROME_MULTIPLE_DLL_BROWSER)
767 if (process_type == switches::kUtilityProcess ||
768 process_type == switches::kZygoteProcess) {
769 ChromeContentUtilityClient::PreSandboxStartup();
771 #endif
774 #if defined(OS_POSIX) && !defined(OS_MACOSX)
775 // Zygote needs to call InitCrashReporter() in RunZygote().
776 if (process_type != switches::kZygoteProcess) {
777 #if defined(OS_ANDROID)
778 if (process_type.empty())
779 breakpad::InitCrashReporter(process_type);
780 else
781 breakpad::InitNonBrowserCrashReporterForAndroid(process_type);
782 #else // !defined(OS_ANDROID)
783 breakpad::InitCrashReporter(process_type);
784 #endif // defined(OS_ANDROID)
786 #endif // defined(OS_POSIX) && !defined(OS_MACOSX)
788 // After all the platform Breakpads have been initialized, store the command
789 // line for crash reporting.
790 crash_keys::SetSwitchesFromCommandLine(&command_line);
793 void ChromeMainDelegate::SandboxInitialized(const std::string& process_type) {
794 startup_timer_->Stop(); // End of Startup Time Measurement.
796 // Note: If you are adding a new process type below, be sure to adjust the
797 // AdjustLinuxOOMScore function too.
798 #if defined(OS_LINUX)
799 AdjustLinuxOOMScore(process_type);
800 #endif
801 #if defined(OS_WIN)
802 SuppressWindowsErrorDialogs();
803 #endif
806 int ChromeMainDelegate::RunProcess(
807 const std::string& process_type,
808 const content::MainFunctionParams& main_function_params) {
809 // ANDROID doesn't support "service", so no ServiceProcessMain, and arraysize
810 // doesn't support empty array. So we comment out the block for Android.
811 #if !defined(OS_ANDROID)
812 static const MainFunction kMainFunctions[] = {
813 #if defined(ENABLE_FULL_PRINTING) && !defined(CHROME_MULTIPLE_DLL_CHILD)
814 { switches::kServiceProcess, ServiceProcessMain },
815 #endif
817 #if defined(OS_MACOSX)
818 { switches::kRelauncherProcess,
819 mac_relauncher::internal::RelauncherMain },
820 #endif
822 // This entry is not needed on Linux, where the NaCl loader
823 // process is launched via nacl_helper instead.
824 #if !defined(DISABLE_NACL) && !defined(CHROME_MULTIPLE_DLL_BROWSER) && \
825 !defined(OS_LINUX)
826 { switches::kNaClLoaderProcess, NaClMain },
827 #else
828 { "<invalid>", NULL }, // To avoid constant array of size 0
829 // when DISABLE_NACL and CHROME_MULTIPLE_DLL_CHILD
830 #endif // DISABLE_NACL
833 for (size_t i = 0; i < arraysize(kMainFunctions); ++i) {
834 if (process_type == kMainFunctions[i].name)
835 return kMainFunctions[i].function(main_function_params);
837 #endif
839 return -1;
842 void ChromeMainDelegate::ProcessExiting(const std::string& process_type) {
843 if (SubprocessNeedsResourceBundle(process_type))
844 ResourceBundle::CleanupSharedInstance();
845 #if !defined(OS_ANDROID)
846 logging::CleanupChromeLogging();
847 #else
848 // Android doesn't use InitChromeLogging, so we close the log file manually.
849 logging::CloseLogFile();
850 #endif // !defined(OS_ANDROID)
852 #if defined(OS_WIN)
853 RemoveCloseHandleHooks();
854 #endif
857 #if defined(OS_MACOSX)
858 bool ChromeMainDelegate::ProcessRegistersWithSystemProcess(
859 const std::string& process_type) {
860 #if defined(DISABLE_NACL)
861 return false;
862 #else
863 return process_type == switches::kNaClLoaderProcess;
864 #endif
867 bool ChromeMainDelegate::ShouldSendMachPort(const std::string& process_type) {
868 return process_type != switches::kRelauncherProcess &&
869 process_type != switches::kServiceProcess;
872 bool ChromeMainDelegate::DelaySandboxInitialization(
873 const std::string& process_type) {
874 #if !defined(DISABLE_NACL)
875 // NaClLoader does this in NaClMainPlatformDelegate::EnableSandbox().
876 // No sandbox needed for relauncher.
877 if (process_type == switches::kNaClLoaderProcess)
878 return true;
879 #endif
880 return process_type == switches::kRelauncherProcess;
882 #elif defined(OS_POSIX) && !defined(OS_ANDROID)
883 void ChromeMainDelegate::ZygoteStarting(
884 ScopedVector<content::ZygoteForkDelegate>* delegates) {
885 #if !defined(DISABLE_NACL)
886 nacl::AddNaClZygoteForkDelegates(delegates);
887 #endif
890 void ChromeMainDelegate::ZygoteForked() {
891 Profiling::ProcessStarted();
892 if (Profiling::BeingProfiled()) {
893 base::debug::RestartProfilingAfterFork();
894 SetUpProfilingShutdownHandler();
897 // Needs to be called after we have chrome::DIR_USER_DATA. BrowserMain sets
898 // this up for the browser process in a different manner.
899 const CommandLine* command_line = CommandLine::ForCurrentProcess();
900 std::string process_type =
901 command_line->GetSwitchValueASCII(switches::kProcessType);
902 breakpad::InitCrashReporter(process_type);
904 // Reset the command line for the newly spawned process.
905 crash_keys::SetSwitchesFromCommandLine(command_line);
908 #endif // OS_MACOSX
910 #if defined(OS_WIN)
911 bool ChromeMainDelegate::ShouldEnableTerminationOnHeapCorruption() {
912 return !ShouldExperimentallyDisableTerminateOnHeapCorruption();
914 #endif // OS_WIN
916 content::ContentBrowserClient*
917 ChromeMainDelegate::CreateContentBrowserClient() {
918 #if defined(CHROME_MULTIPLE_DLL_CHILD)
919 return NULL;
920 #else
921 return g_chrome_content_browser_client.Pointer();
922 #endif
925 content::ContentPluginClient* ChromeMainDelegate::CreateContentPluginClient() {
926 #if defined(CHROME_MULTIPLE_DLL_BROWSER)
927 return NULL;
928 #else
929 return g_chrome_content_plugin_client.Pointer();
930 #endif
933 content::ContentRendererClient*
934 ChromeMainDelegate::CreateContentRendererClient() {
935 #if defined(CHROME_MULTIPLE_DLL_BROWSER)
936 return NULL;
937 #else
938 return g_chrome_content_renderer_client.Pointer();
939 #endif
942 content::ContentUtilityClient*
943 ChromeMainDelegate::CreateContentUtilityClient() {
944 #if defined(CHROME_MULTIPLE_DLL_BROWSER)
945 return NULL;
946 #else
947 return g_chrome_content_utility_client.Pointer();
948 #endif