Unregister from GCM when the only GCM app is removed
[chromium-blink-merge.git] / chrome / app / chrome_main_delegate.cc
blob7af7949ead06eeb06b06ace9aea700fe572e5ec1
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/foundation_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_recorder.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 #include "components/nacl/renderer/plugin/ppapi_entrypoints.h"
116 #endif
118 #if defined(ENABLE_REMOTING)
119 #include "remoting/client/plugin/pepper_entrypoints.h"
120 #endif
122 #if defined(ENABLE_PLUGINS) && (defined(CHROME_MULTIPLE_DLL_CHILD) || \
123 !defined(CHROME_MULTIPLE_DLL_BROWSER))
124 #include "pdf/pdf.h"
125 #endif
127 #if !defined(CHROME_MULTIPLE_DLL_BROWSER)
128 #include "chrome/child/pdf_child_init.h"
130 base::LazyInstance<ChromeContentRendererClient>
131 g_chrome_content_renderer_client = LAZY_INSTANCE_INITIALIZER;
132 base::LazyInstance<ChromeContentUtilityClient>
133 g_chrome_content_utility_client = LAZY_INSTANCE_INITIALIZER;
134 base::LazyInstance<chrome::ChromeContentPluginClient>
135 g_chrome_content_plugin_client = LAZY_INSTANCE_INITIALIZER;
136 #endif
138 #if !defined(CHROME_MULTIPLE_DLL_CHILD)
139 base::LazyInstance<chrome::ChromeContentBrowserClient>
140 g_chrome_content_browser_client = LAZY_INSTANCE_INITIALIZER;
141 #endif
143 #if defined(OS_POSIX)
144 base::LazyInstance<chrome::ChromeCrashReporterClient>::Leaky
145 g_chrome_crash_client = LAZY_INSTANCE_INITIALIZER;
146 #endif
148 extern int NaClMain(const content::MainFunctionParams&);
149 extern int ServiceProcessMain(const content::MainFunctionParams&);
151 namespace {
153 #if defined(OS_WIN)
154 // Early versions of Chrome incorrectly registered a chromehtml: URL handler,
155 // which gives us nothing but trouble. Avoid launching chrome this way since
156 // some apps fail to properly escape arguments.
157 bool HasDeprecatedArguments(const std::wstring& command_line) {
158 const wchar_t kChromeHtml[] = L"chromehtml:";
159 std::wstring command_line_lower = command_line;
160 // We are only searching for ASCII characters so this is OK.
161 base::StringToLowerASCII(&command_line_lower);
162 std::wstring::size_type pos = command_line_lower.find(kChromeHtml);
163 return (pos != std::wstring::npos);
166 // If we try to access a path that is not currently available, we want the call
167 // to fail rather than show an error dialog.
168 void SuppressWindowsErrorDialogs() {
169 UINT new_flags = SEM_FAILCRITICALERRORS |
170 SEM_NOOPENFILEERRORBOX;
172 // Preserve existing error mode.
173 UINT existing_flags = SetErrorMode(new_flags);
174 SetErrorMode(existing_flags | new_flags);
177 #endif // defined(OS_WIN)
179 #if defined(OS_LINUX)
180 static void AdjustLinuxOOMScore(const std::string& process_type) {
181 // Browsers and zygotes should still be killable, but killed last.
182 const int kZygoteScore = 0;
183 // The minimum amount to bump a score by. This is large enough that
184 // even if it's translated into the old values, it will still go up
185 // by at least one.
186 const int kScoreBump = 100;
187 // This is the lowest score that renderers and extensions start with
188 // in the OomPriorityManager.
189 const int kRendererScore = chrome::kLowestRendererOomScore;
190 // For "miscellaneous" things, we want them after renderers,
191 // but before plugins.
192 const int kMiscScore = kRendererScore - kScoreBump;
193 // We want plugins to die after the renderers.
194 const int kPluginScore = kMiscScore - kScoreBump;
195 int score = -1;
197 DCHECK(kMiscScore > 0);
198 DCHECK(kPluginScore > 0);
200 if (process_type == switches::kPluginProcess ||
201 process_type == switches::kPpapiPluginProcess) {
202 score = kPluginScore;
203 } else if (process_type == switches::kPpapiBrokerProcess) {
204 // The broker should be killed before the PPAPI plugin.
205 score = kPluginScore + kScoreBump;
206 } else if (process_type == switches::kUtilityProcess ||
207 process_type == switches::kGpuProcess ||
208 process_type == switches::kServiceProcess) {
209 score = kMiscScore;
210 #ifndef DISABLE_NACL
211 } else if (process_type == switches::kNaClLoaderProcess ||
212 process_type == switches::kNaClLoaderNonSfiProcess) {
213 score = kPluginScore;
214 #endif
215 } else if (process_type == switches::kZygoteProcess ||
216 process_type.empty()) {
217 // For zygotes and unlabeled process types, we want to still make
218 // them killable by the OOM killer.
219 score = kZygoteScore;
220 } else if (process_type == switches::kRendererProcess) {
221 LOG(WARNING) << "process type 'renderer' "
222 << "should be created through the zygote.";
223 // When debugging, this process type can end up being run directly, but
224 // this isn't the typical path for assigning the OOM score for it. Still,
225 // we want to assign a score that is somewhat representative for debugging.
226 score = kRendererScore;
227 } else {
228 NOTREACHED() << "Unknown process type";
230 if (score > -1)
231 base::AdjustOOMScore(base::GetCurrentProcId(), score);
233 #endif // defined(OS_LINUX)
235 // Returns true if this subprocess type needs the ResourceBundle initialized
236 // and resources loaded.
237 bool SubprocessNeedsResourceBundle(const std::string& process_type) {
238 return
239 #if defined(OS_WIN) || defined(OS_MACOSX)
240 // Windows needs resources for the default/null plugin.
241 // Mac needs them for the plugin process name.
242 process_type == switches::kPluginProcess ||
243 #endif
244 #if defined(OS_POSIX) && !defined(OS_MACOSX)
245 // The zygote process opens the resources for the renderers.
246 process_type == switches::kZygoteProcess ||
247 #endif
248 #if defined(OS_MACOSX)
249 // Mac needs them too for scrollbar related images and for sandbox
250 // profiles.
251 #if !defined(DISABLE_NACL)
252 process_type == switches::kNaClLoaderProcess ||
253 #endif
254 process_type == switches::kPpapiPluginProcess ||
255 process_type == switches::kPpapiBrokerProcess ||
256 process_type == switches::kGpuProcess ||
257 #endif
258 process_type == switches::kRendererProcess ||
259 process_type == switches::kUtilityProcess;
262 #if defined(OS_POSIX)
263 // Check for --version and --product-version; return true if we encountered
264 // one of these switches and should exit now.
265 bool HandleVersionSwitches(const base::CommandLine& command_line) {
266 const chrome::VersionInfo version_info;
268 #if !defined(OS_MACOSX)
269 if (command_line.HasSwitch(switches::kProductVersion)) {
270 printf("%s\n", version_info.Version().c_str());
271 return true;
273 #endif
275 if (command_line.HasSwitch(switches::kVersion)) {
276 printf("%s %s %s\n",
277 version_info.Name().c_str(),
278 version_info.Version().c_str(),
279 chrome::VersionInfo::GetVersionStringModifier().c_str());
280 return true;
283 return false;
286 #if !defined(OS_MACOSX) && !defined(OS_CHROMEOS)
287 // Show the man page if --help or -h is on the command line.
288 void HandleHelpSwitches(const base::CommandLine& command_line) {
289 if (command_line.HasSwitch(switches::kHelp) ||
290 command_line.HasSwitch(switches::kHelpShort)) {
291 base::FilePath binary(command_line.argv()[0]);
292 execlp("man", "man", binary.BaseName().value().c_str(), NULL);
293 PLOG(FATAL) << "execlp failed";
296 #endif
298 #if !defined(OS_MACOSX) && !defined(OS_ANDROID)
299 void SIGTERMProfilingShutdown(int signal) {
300 Profiling::Stop();
301 struct sigaction sigact;
302 memset(&sigact, 0, sizeof(sigact));
303 sigact.sa_handler = SIG_DFL;
304 CHECK(sigaction(SIGTERM, &sigact, NULL) == 0);
305 raise(signal);
308 void SetUpProfilingShutdownHandler() {
309 struct sigaction sigact;
310 sigact.sa_handler = SIGTERMProfilingShutdown;
311 sigact.sa_flags = SA_RESETHAND;
312 sigemptyset(&sigact.sa_mask);
313 CHECK(sigaction(SIGTERM, &sigact, NULL) == 0);
315 #endif // !defined(OS_MACOSX) && !defined(OS_ANDROID)
317 #endif // OS_POSIX
319 struct MainFunction {
320 const char* name;
321 int (*function)(const content::MainFunctionParams&);
324 // Initializes the user data dir. Must be called before InitializeLocalState().
325 void InitializeUserDataDir() {
326 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
327 base::FilePath user_data_dir =
328 command_line->GetSwitchValuePath(switches::kUserDataDir);
329 std::string process_type =
330 command_line->GetSwitchValueASCII(switches::kProcessType);
332 #if defined(OS_LINUX)
333 // On Linux, Chrome does not support running multiple copies under different
334 // DISPLAYs, so the profile directory can be specified in the environment to
335 // support the virtual desktop use-case.
336 if (user_data_dir.empty()) {
337 std::string user_data_dir_string;
338 scoped_ptr<base::Environment> environment(base::Environment::Create());
339 if (environment->GetVar("CHROME_USER_DATA_DIR", &user_data_dir_string) &&
340 base::IsStringUTF8(user_data_dir_string)) {
341 user_data_dir = base::FilePath::FromUTF8Unsafe(user_data_dir_string);
344 #endif
345 #if defined(OS_MACOSX) || defined(OS_WIN)
346 policy::path_parser::CheckUserDataDirPolicy(&user_data_dir);
347 #endif
349 const bool specified_directory_was_invalid = !user_data_dir.empty() &&
350 !PathService::OverrideAndCreateIfNeeded(chrome::DIR_USER_DATA,
351 user_data_dir, false, true);
352 // Save inaccessible or invalid paths so the user may be prompted later.
353 if (specified_directory_was_invalid)
354 chrome::SetInvalidSpecifiedUserDataDir(user_data_dir);
356 // Warn and fail early if the process fails to get a user data directory.
357 if (!PathService::Get(chrome::DIR_USER_DATA, &user_data_dir)) {
358 // If an invalid command-line or policy override was specified, the user
359 // will be given an error with that value. Otherwise, use the directory
360 // returned by PathService (or the fallback default directory) in the error.
361 if (!specified_directory_was_invalid) {
362 // PathService::Get() returns false and yields an empty path if it fails
363 // to create DIR_USER_DATA. Retrieve the default value manually to display
364 // a more meaningful error to the user in that case.
365 if (user_data_dir.empty())
366 chrome::GetDefaultUserDataDirectory(&user_data_dir);
367 chrome::SetInvalidSpecifiedUserDataDir(user_data_dir);
370 // The browser process (which is identified by an empty |process_type|) will
371 // handle the error later; other processes that need the dir crash here.
372 CHECK(process_type.empty()) << "Unable to get the user data directory "
373 << "for process type: " << process_type;
376 // Append the fallback user data directory to the commandline. Otherwise,
377 // child or service processes will attempt to use the invalid directory.
378 if (specified_directory_was_invalid)
379 command_line->AppendSwitchPath(switches::kUserDataDir, user_data_dir);
382 } // namespace
384 ChromeMainDelegate::ChromeMainDelegate() {
385 #if defined(OS_ANDROID)
386 // On Android the main entry point time is the time when the Java code starts.
387 // This happens before the shared library containing this code is even loaded.
388 // The Java startup code has recorded that time, but the C++ code can't fetch it
389 // from the Java side until it has initialized the JNI. See
390 // ChromeMainDelegateAndroid.
391 #else
392 startup_metric_utils::RecordMainEntryPointTime();
393 #endif
396 ChromeMainDelegate::~ChromeMainDelegate() {
399 bool ChromeMainDelegate::BasicStartupComplete(int* exit_code) {
400 #if defined(OS_CHROMEOS)
401 chromeos::BootTimesRecorder::Get()->SaveChromeMainStats();
402 #endif
404 const base::CommandLine& command_line =
405 *base::CommandLine::ForCurrentProcess();
407 #if defined(OS_MACOSX)
408 // Give the browser process a longer treadmill, since crashes
409 // there have more impact.
410 const bool is_browser = !command_line.HasSwitch(switches::kProcessType);
411 ObjcEvilDoers::ZombieEnable(true, is_browser ? 10000 : 1000);
413 SetUpBundleOverrides();
414 chrome::common::mac::EnableCFBundleBlocker();
415 #endif
417 Profiling::ProcessStarted();
419 #if defined(OS_WIN)
420 v8_breakpad_support::SetUp();
421 #endif
423 #if defined(OS_POSIX)
424 if (HandleVersionSwitches(command_line)) {
425 *exit_code = 0;
426 return true; // Got a --version switch; exit with a success error code.
428 #if !defined(OS_MACOSX) && !defined(OS_CHROMEOS)
429 // This will directly exit if the user asked for help.
430 HandleHelpSwitches(command_line);
431 #endif
432 #endif // OS_POSIX
434 #if defined(OS_WIN)
435 // Must do this before any other usage of command line!
436 if (HasDeprecatedArguments(command_line.GetCommandLineString())) {
437 *exit_code = 1;
438 return true;
441 InstallCloseHandleHooks();
442 #endif
444 chrome::RegisterPathProvider();
445 #if defined(OS_CHROMEOS)
446 chromeos::RegisterPathProvider();
447 #endif
448 #if !defined(DISABLE_NACL) && defined(OS_LINUX)
449 nacl::RegisterPathProvider();
450 #endif
452 ContentSettingsPattern::SetNonWildcardDomainNonPortScheme(
453 extensions::kExtensionScheme);
455 // No support for ANDROID yet as DiagnosticsController needs wchar support.
456 // TODO(gspencer): That's not true anymore, or at least there are no w-string
457 // references anymore. Not sure if that means this can be enabled on Android or
458 // not though. As there is no easily accessible command line on Android, I'm
459 // not sure this is a big deal.
460 #if !defined(OS_ANDROID) && !defined(CHROME_MULTIPLE_DLL_CHILD)
461 // If we are in diagnostics mode this is the end of the line: after the
462 // diagnostics are run the process will invariably exit.
463 if (command_line.HasSwitch(switches::kDiagnostics)) {
464 diagnostics::DiagnosticsWriter::FormatType format =
465 diagnostics::DiagnosticsWriter::HUMAN;
466 if (command_line.HasSwitch(switches::kDiagnosticsFormat)) {
467 std::string format_str =
468 command_line.GetSwitchValueASCII(switches::kDiagnosticsFormat);
469 if (format_str == "machine") {
470 format = diagnostics::DiagnosticsWriter::MACHINE;
471 } else if (format_str == "log") {
472 format = diagnostics::DiagnosticsWriter::LOG;
473 } else {
474 DCHECK_EQ("human", format_str);
478 diagnostics::DiagnosticsWriter writer(format);
479 *exit_code = diagnostics::DiagnosticsController::GetInstance()->Run(
480 command_line, &writer);
481 diagnostics::DiagnosticsController::GetInstance()->ClearResults();
482 return true;
484 #endif
486 #if defined(OS_CHROMEOS)
487 // Initialize primary user homedir (in multi-profile session) as it may be
488 // passed as a command line switch.
489 base::FilePath homedir;
490 if (command_line.HasSwitch(chromeos::switches::kHomedir)) {
491 homedir = base::FilePath(
492 command_line.GetSwitchValueASCII(chromeos::switches::kHomedir));
493 PathService::OverrideAndCreateIfNeeded(
494 base::DIR_HOME, homedir, true, false);
497 // If we are recovering from a crash on ChromeOS, then we will do some
498 // recovery using the diagnostics module, and then continue on. We fake up a
499 // command line to tell it that we want it to recover, and to preserve the
500 // original command line.
501 if (command_line.HasSwitch(chromeos::switches::kLoginUser) ||
502 command_line.HasSwitch(switches::kDiagnosticsRecovery)) {
503 // The statistics subsystem needs get initialized soon enough for the
504 // statistics to be collected. It's safe to call this more than once.
505 base::StatisticsRecorder::Initialize();
507 base::CommandLine interim_command_line(command_line.GetProgram());
508 const char* const kSwitchNames[] = {switches::kUserDataDir, };
509 interim_command_line.CopySwitchesFrom(
510 command_line, kSwitchNames, arraysize(kSwitchNames));
511 interim_command_line.AppendSwitch(switches::kDiagnostics);
512 interim_command_line.AppendSwitch(switches::kDiagnosticsRecovery);
514 diagnostics::DiagnosticsWriter::FormatType format =
515 diagnostics::DiagnosticsWriter::LOG;
516 if (command_line.HasSwitch(switches::kDiagnosticsFormat)) {
517 std::string format_str =
518 command_line.GetSwitchValueASCII(switches::kDiagnosticsFormat);
519 if (format_str == "machine") {
520 format = diagnostics::DiagnosticsWriter::MACHINE;
521 } else if (format_str == "human") {
522 format = diagnostics::DiagnosticsWriter::HUMAN;
523 } else {
524 DCHECK_EQ("log", format_str);
528 diagnostics::DiagnosticsWriter writer(format);
529 int diagnostics_exit_code =
530 diagnostics::DiagnosticsController::GetInstance()->Run(command_line,
531 &writer);
532 if (diagnostics_exit_code) {
533 // Diagnostics has failed somehow, so we exit.
534 *exit_code = diagnostics_exit_code;
535 return true;
538 // Now we run the actual recovery tasks.
539 int recovery_exit_code =
540 diagnostics::DiagnosticsController::GetInstance()->RunRecovery(
541 command_line, &writer);
543 if (recovery_exit_code) {
544 // Recovery has failed somehow, so we exit.
545 *exit_code = recovery_exit_code;
546 return true;
548 } else { // Not running diagnostics or recovery.
549 diagnostics::DiagnosticsController::GetInstance()->RecordRegularStartup();
551 #endif
553 content::SetContentClient(&chrome_content_client_);
555 return false;
558 #if defined(OS_MACOSX)
559 void ChromeMainDelegate::InitMacCrashReporter(
560 const base::CommandLine& command_line,
561 const std::string& process_type) {
562 // TODO(mark): Right now, InitCrashReporter() needs to be called after
563 // CommandLine::Init() and chrome::RegisterPathProvider(). Ideally,
564 // Breakpad initialization could occur sooner, preferably even before the
565 // framework dylib is even loaded, to catch potential early crashes.
566 breakpad::InitCrashReporter(process_type);
568 #if defined(NDEBUG)
569 bool is_debug_build = false;
570 #else
571 bool is_debug_build = true;
572 #endif
574 // Details on when we enable Apple's Crash reporter.
576 // Motivation:
577 // In debug mode it takes Apple's crash reporter eons to generate a crash
578 // dump.
580 // What we do:
581 // * We only pass crashes for foreground processes to Apple's Crash
582 // reporter. At the time of this writing, that means just the Browser
583 // process.
584 // * If Breakpad is enabled, it will pass browser crashes to Crash Reporter
585 // itself.
586 // * If Breakpad is disabled, we only turn on Crash Reporter for the
587 // Browser process in release mode.
588 if (!command_line.HasSwitch(switches::kDisableBreakpad)) {
589 bool disable_apple_crash_reporter = is_debug_build ||
590 base::mac::IsBackgroundOnlyProcess();
591 if (!breakpad::IsCrashReporterEnabled() && disable_apple_crash_reporter) {
592 base::mac::DisableOSCrashDumps();
596 // Mac Chrome is packaged with a main app bundle and a helper app bundle.
597 // The main app bundle should only be used for the browser process, so it
598 // should never see a --type switch (switches::kProcessType). Likewise,
599 // the helper should always have a --type switch.
601 // This check is done this late so there is already a call to
602 // base::mac::IsBackgroundOnlyProcess(), so there is no change in
603 // startup/initialization order.
605 // The helper's Info.plist marks it as a background only app.
606 if (base::mac::IsBackgroundOnlyProcess()) {
607 CHECK(command_line.HasSwitch(switches::kProcessType) &&
608 !process_type.empty())
609 << "Helper application requires --type.";
611 // In addition, some helper flavors only work with certain process types.
612 base::FilePath executable;
613 if (PathService::Get(base::FILE_EXE, &executable) &&
614 executable.value().size() >= 3) {
615 std::string last_three =
616 executable.value().substr(executable.value().size() - 3);
618 if (last_three == " EH") {
619 CHECK(process_type == switches::kPluginProcess ||
620 process_type == switches::kUtilityProcess)
621 << "Executable-heap process requires --type="
622 << switches::kPluginProcess << " or "
623 << switches::kUtilityProcess << ", saw " << process_type;
624 } else if (last_three == " NP") {
625 #if !defined(DISABLE_NACL)
626 CHECK_EQ(switches::kNaClLoaderProcess, process_type)
627 << "Non-PIE process requires --type="
628 << switches::kNaClLoaderProcess << ", saw " << process_type;
629 #endif
630 } else {
631 #if defined(DISABLE_NACL)
632 CHECK(process_type != switches::kPluginProcess)
633 << "Non-executable-heap PIE process is intolerant of --type="
634 << switches::kPluginProcess;
635 #else
636 CHECK(process_type != switches::kPluginProcess &&
637 process_type != switches::kNaClLoaderProcess)
638 << "Non-executable-heap PIE process is intolerant of --type="
639 << switches::kPluginProcess << " and "
640 << switches::kNaClLoaderProcess << ", saw " << process_type;
641 #endif
644 } else {
645 CHECK(!command_line.HasSwitch(switches::kProcessType) &&
646 process_type.empty())
647 << "Main application forbids --type, saw " << process_type;
650 if (breakpad::IsCrashReporterEnabled())
651 breakpad::InitCrashProcessInfo(process_type);
653 #endif // defined(OS_MACOSX)
655 void ChromeMainDelegate::PreSandboxStartup() {
656 const base::CommandLine& command_line =
657 *base::CommandLine::ForCurrentProcess();
658 std::string process_type =
659 command_line.GetSwitchValueASCII(switches::kProcessType);
661 #if defined(OS_POSIX)
662 crash_reporter::SetCrashReporterClient(g_chrome_crash_client.Pointer());
663 #endif
665 #if defined(OS_MACOSX)
666 // On the Mac, the child executable lives at a predefined location within
667 // the app bundle's versioned directory.
668 PathService::Override(content::CHILD_PROCESS_EXE,
669 chrome::GetVersionedDirectory().
670 Append(chrome::kHelperProcessExecutablePath));
672 InitMacCrashReporter(command_line, process_type);
673 #endif
675 #if defined(OS_WIN)
676 child_process_logging::Init();
677 #endif
678 #if defined(ARCH_CPU_ARM_FAMILY) && (defined(OS_ANDROID) || defined(OS_LINUX))
679 // Create an instance of the CPU class to parse /proc/cpuinfo and cache
680 // cpu_brand info.
681 base::CPU cpu_info;
682 #endif
684 // Initialize the user data dir for any process type that needs it.
685 if (chrome::ProcessNeedsProfileDir(process_type))
686 InitializeUserDataDir();
688 // Register component_updater PathProvider after DIR_USER_DATA overidden by
689 // command line flags. Maybe move the chrome PathProvider down here also?
690 component_updater::RegisterPathProvider(chrome::DIR_USER_DATA);
692 stats_counter_timer_.reset(new base::StatsCounterTimer("Chrome.Init"));
693 startup_timer_.reset(new base::StatsScope<base::StatsCounterTimer>
694 (*stats_counter_timer_));
696 // Enable Message Loop related state asap.
697 if (command_line.HasSwitch(switches::kMessageLoopHistogrammer))
698 base::MessageLoop::EnableHistogrammer(true);
700 #if !defined(OS_ANDROID)
701 // Android does InitLogging when library is loaded. Skip here.
702 logging::OldFileDeletionState file_state =
703 logging::APPEND_TO_OLD_LOG_FILE;
704 if (process_type.empty()) {
705 file_state = logging::DELETE_OLD_LOG_FILE;
707 logging::InitChromeLogging(command_line, file_state);
708 #endif
710 #if defined(OS_WIN)
711 // TODO(zturner): Throbber icons are still stored in chrome.dll, this can be
712 // killed once those are merged into resources.pak. See
713 // GlassBrowserFrameView::InitThrobberIcons() and http://crbug.com/368327.
714 ui::SetResourcesDataDLL(_AtlBaseModule.GetResourceInstance());
715 #endif
717 if (SubprocessNeedsResourceBundle(process_type)) {
718 // Initialize ResourceBundle which handles files loaded from external
719 // sources. The language should have been passed in to us from the
720 // browser process as a command line flag.
721 #if defined(DISABLE_NACL)
722 DCHECK(command_line.HasSwitch(switches::kLang) ||
723 process_type == switches::kZygoteProcess ||
724 process_type == switches::kGpuProcess ||
725 process_type == switches::kPpapiBrokerProcess ||
726 process_type == switches::kPpapiPluginProcess);
727 #else
728 DCHECK(command_line.HasSwitch(switches::kLang) ||
729 process_type == switches::kZygoteProcess ||
730 process_type == switches::kGpuProcess ||
731 process_type == switches::kNaClLoaderProcess ||
732 process_type == switches::kPpapiBrokerProcess ||
733 process_type == switches::kPpapiPluginProcess);
734 #endif
736 // TODO(markusheintz): The command line flag --lang is actually processed
737 // by the CommandLinePrefStore, and made available through the PrefService
738 // via the preference prefs::kApplicationLocale. The browser process uses
739 // the --lang flag to pass the value of the PrefService in here. Maybe
740 // this value could be passed in a different way.
741 const std::string locale =
742 command_line.GetSwitchValueASCII(switches::kLang);
743 #if defined(OS_ANDROID)
744 // The renderer sandbox prevents us from accessing our .pak files directly.
745 // Therefore file descriptors to the .pak files that we need are passed in
746 // at process creation time.
747 int locale_pak_fd = base::GlobalDescriptors::GetInstance()->MaybeGet(
748 kAndroidLocalePakDescriptor);
749 CHECK(locale_pak_fd != -1);
750 ResourceBundle::InitSharedInstanceWithPakFileRegion(
751 base::File(locale_pak_fd), base::MemoryMappedFile::Region::kWholeFile);
753 int extra_pak_keys[] = {
754 kAndroidChrome100PercentPakDescriptor,
755 kAndroidUIResourcesPakDescriptor,
757 for (size_t i = 0; i < arraysize(extra_pak_keys); ++i) {
758 int pak_fd =
759 base::GlobalDescriptors::GetInstance()->MaybeGet(extra_pak_keys[i]);
760 CHECK(pak_fd != -1);
761 ResourceBundle::GetSharedInstance().AddDataPackFromFile(
762 base::File(pak_fd), ui::SCALE_FACTOR_100P);
765 base::i18n::SetICUDefaultLocale(locale);
766 const std::string loaded_locale = locale;
767 #else
768 const std::string loaded_locale =
769 ui::ResourceBundle::InitSharedInstanceWithLocale(
770 locale, NULL, ui::ResourceBundle::LOAD_COMMON_RESOURCES);
772 base::FilePath resources_pack_path;
773 PathService::Get(chrome::FILE_RESOURCES_PACK, &resources_pack_path);
774 ResourceBundle::GetSharedInstance().AddDataPackFromPath(
775 resources_pack_path, ui::SCALE_FACTOR_NONE);
776 #endif
777 CHECK(!loaded_locale.empty()) << "Locale could not be found for " <<
778 locale;
781 #if !defined(CHROME_MULTIPLE_DLL_BROWSER)
782 if (process_type == switches::kUtilityProcess ||
783 process_type == switches::kZygoteProcess) {
784 ChromeContentUtilityClient::PreSandboxStartup();
787 chrome::InitializePDF();
788 #endif
790 #if defined(OS_POSIX) && !defined(OS_MACOSX)
791 // Zygote needs to call InitCrashReporter() in RunZygote().
792 if (process_type != switches::kZygoteProcess) {
793 #if defined(OS_ANDROID)
794 if (process_type.empty())
795 breakpad::InitCrashReporter(process_type);
796 else
797 breakpad::InitNonBrowserCrashReporterForAndroid(process_type);
798 #else // !defined(OS_ANDROID)
799 breakpad::InitCrashReporter(process_type);
800 #endif // defined(OS_ANDROID)
802 #endif // defined(OS_POSIX) && !defined(OS_MACOSX)
804 // After all the platform Breakpads have been initialized, store the command
805 // line for crash reporting.
806 crash_keys::SetSwitchesFromCommandLine(&command_line);
809 void ChromeMainDelegate::SandboxInitialized(const std::string& process_type) {
810 startup_timer_->Stop(); // End of Startup Time Measurement.
812 // Note: If you are adding a new process type below, be sure to adjust the
813 // AdjustLinuxOOMScore function too.
814 #if defined(OS_LINUX)
815 AdjustLinuxOOMScore(process_type);
816 #endif
817 #if defined(OS_WIN)
818 SuppressWindowsErrorDialogs();
819 #endif
821 #if defined(CHROME_MULTIPLE_DLL_CHILD) || !defined(CHROME_MULTIPLE_DLL_BROWSER)
822 #if defined(ENABLE_REMOTING)
823 ChromeContentClient::SetRemotingEntryFunctions(
824 remoting::PPP_GetInterface,
825 remoting::PPP_InitializeModule,
826 remoting::PPP_ShutdownModule);
827 #endif
828 #if !defined(DISABLE_NACL)
829 ChromeContentClient::SetNaClEntryFunctions(
830 nacl_plugin::PPP_GetInterface,
831 nacl_plugin::PPP_InitializeModule,
832 nacl_plugin::PPP_ShutdownModule);
833 #endif
834 #if defined(ENABLE_PLUGINS)
835 ChromeContentClient::SetPDFEntryFunctions(
836 chrome_pdf::PPP_GetInterface,
837 chrome_pdf::PPP_InitializeModule,
838 chrome_pdf::PPP_ShutdownModule);
839 #endif
840 #endif
843 int ChromeMainDelegate::RunProcess(
844 const std::string& process_type,
845 const content::MainFunctionParams& main_function_params) {
846 // ANDROID doesn't support "service", so no ServiceProcessMain, and arraysize
847 // doesn't support empty array. So we comment out the block for Android.
848 #if !defined(OS_ANDROID)
849 static const MainFunction kMainFunctions[] = {
850 #if defined(ENABLE_PRINT_PREVIEW) && !defined(CHROME_MULTIPLE_DLL_CHILD)
851 { switches::kServiceProcess, ServiceProcessMain },
852 #endif
854 #if defined(OS_MACOSX)
855 { switches::kRelauncherProcess,
856 mac_relauncher::internal::RelauncherMain },
857 #endif
859 // This entry is not needed on Linux, where the NaCl loader
860 // process is launched via nacl_helper instead.
861 #if !defined(DISABLE_NACL) && !defined(CHROME_MULTIPLE_DLL_BROWSER) && \
862 !defined(OS_LINUX)
863 { switches::kNaClLoaderProcess, NaClMain },
864 #else
865 { "<invalid>", NULL }, // To avoid constant array of size 0
866 // when DISABLE_NACL and CHROME_MULTIPLE_DLL_CHILD
867 #endif // DISABLE_NACL
870 for (size_t i = 0; i < arraysize(kMainFunctions); ++i) {
871 if (process_type == kMainFunctions[i].name)
872 return kMainFunctions[i].function(main_function_params);
874 #endif
876 return -1;
879 void ChromeMainDelegate::ProcessExiting(const std::string& process_type) {
880 if (SubprocessNeedsResourceBundle(process_type))
881 ResourceBundle::CleanupSharedInstance();
882 #if !defined(OS_ANDROID)
883 logging::CleanupChromeLogging();
884 #else
885 // Android doesn't use InitChromeLogging, so we close the log file manually.
886 logging::CloseLogFile();
887 #endif // !defined(OS_ANDROID)
889 #if defined(OS_WIN)
890 RemoveCloseHandleHooks();
891 #endif
894 #if defined(OS_MACOSX)
895 bool ChromeMainDelegate::ProcessRegistersWithSystemProcess(
896 const std::string& process_type) {
897 #if defined(DISABLE_NACL)
898 return false;
899 #else
900 return process_type == switches::kNaClLoaderProcess;
901 #endif
904 bool ChromeMainDelegate::ShouldSendMachPort(const std::string& process_type) {
905 return process_type != switches::kRelauncherProcess &&
906 process_type != switches::kServiceProcess;
909 bool ChromeMainDelegate::DelaySandboxInitialization(
910 const std::string& process_type) {
911 #if !defined(DISABLE_NACL)
912 // NaClLoader does this in NaClMainPlatformDelegate::EnableSandbox().
913 // No sandbox needed for relauncher.
914 if (process_type == switches::kNaClLoaderProcess)
915 return true;
916 #endif
917 return process_type == switches::kRelauncherProcess;
919 #elif defined(OS_POSIX) && !defined(OS_ANDROID)
920 void ChromeMainDelegate::ZygoteStarting(
921 ScopedVector<content::ZygoteForkDelegate>* delegates) {
922 #if !defined(DISABLE_NACL)
923 nacl::AddNaClZygoteForkDelegates(delegates);
924 #endif
927 void ChromeMainDelegate::ZygoteForked() {
928 Profiling::ProcessStarted();
929 if (Profiling::BeingProfiled()) {
930 base::debug::RestartProfilingAfterFork();
931 SetUpProfilingShutdownHandler();
934 // Needs to be called after we have chrome::DIR_USER_DATA. BrowserMain sets
935 // this up for the browser process in a different manner.
936 const base::CommandLine* command_line =
937 base::CommandLine::ForCurrentProcess();
938 std::string process_type =
939 command_line->GetSwitchValueASCII(switches::kProcessType);
940 breakpad::InitCrashReporter(process_type);
942 // Reset the command line for the newly spawned process.
943 crash_keys::SetSwitchesFromCommandLine(command_line);
946 #endif // OS_MACOSX
948 #if defined(OS_WIN)
949 bool ChromeMainDelegate::ShouldEnableTerminationOnHeapCorruption() {
950 return !ShouldExperimentallyDisableTerminateOnHeapCorruption();
952 #endif // OS_WIN
954 content::ContentBrowserClient*
955 ChromeMainDelegate::CreateContentBrowserClient() {
956 #if defined(CHROME_MULTIPLE_DLL_CHILD)
957 return NULL;
958 #else
959 return g_chrome_content_browser_client.Pointer();
960 #endif
963 content::ContentPluginClient* ChromeMainDelegate::CreateContentPluginClient() {
964 #if defined(CHROME_MULTIPLE_DLL_BROWSER)
965 return NULL;
966 #else
967 return g_chrome_content_plugin_client.Pointer();
968 #endif
971 content::ContentRendererClient*
972 ChromeMainDelegate::CreateContentRendererClient() {
973 #if defined(CHROME_MULTIPLE_DLL_BROWSER)
974 return NULL;
975 #else
976 return g_chrome_content_renderer_client.Pointer();
977 #endif
980 content::ContentUtilityClient*
981 ChromeMainDelegate::CreateContentUtilityClient() {
982 #if defined(CHROME_MULTIPLE_DLL_BROWSER)
983 return NULL;
984 #else
985 return g_chrome_content_utility_client.Pointer();
986 #endif