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"
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/path_service.h"
16 #include "base/process/memory.h"
17 #include "base/process/process_handle.h"
18 #include "base/strings/string_util.h"
19 #include "build/build_config.h"
20 #include "chrome/browser/chrome_content_browser_client.h"
21 #include "chrome/browser/defaults.h"
22 #include "chrome/common/chrome_constants.h"
23 #include "chrome/common/chrome_content_client.h"
24 #include "chrome/common/chrome_paths.h"
25 #include "chrome/common/chrome_paths_internal.h"
26 #include "chrome/common/chrome_switches.h"
27 #include "chrome/common/chrome_version_info.h"
28 #include "chrome/common/crash_keys.h"
29 #include "chrome/common/logging_chrome.h"
30 #include "chrome/common/profiling.h"
31 #include "chrome/common/switch_utils.h"
32 #include "chrome/common/url_constants.h"
33 #include "chrome/plugin/chrome_content_plugin_client.h"
34 #include "chrome/renderer/chrome_content_renderer_client.h"
35 #include "chrome/utility/chrome_content_utility_client.h"
36 #include "components/component_updater/component_updater_paths.h"
37 #include "components/content_settings/core/common/content_settings_pattern.h"
38 #include "components/startup_metric_utils/startup_metric_utils.h"
39 #include "content/public/common/content_client.h"
40 #include "content/public/common/content_paths.h"
41 #include "extensions/common/constants.h"
42 #include "ui/base/ui_base_switches.h"
48 #include "chrome/app/close_handle_hook_win.h"
49 #include "chrome/common/child_process_logging.h"
50 #include "chrome/common/terminate_on_heap_corruption_experiment_win.h"
51 #include "chrome/common/v8_breakpad_support_win.h"
52 #include "sandbox/win/src/sandbox.h"
53 #include "ui/base/resource/resource_bundle_win.h"
56 #if defined(OS_MACOSX)
57 #include "base/mac/foundation_util.h"
58 #include "base/mac/os_crash_dumps.h"
59 #include "chrome/app/chrome_main_mac.h"
60 #include "chrome/browser/mac/relauncher.h"
61 #include "chrome/common/mac/cfbundle_blocker.h"
62 #include "chrome/common/mac/objc_zombie.h"
63 #include "components/crash/app/breakpad_mac.h"
64 #include "ui/base/l10n/l10n_util_mac.h"
70 #include "chrome/app/chrome_crash_reporter_client.h"
71 #include "components/crash/app/crash_reporter_client.h"
74 #if !defined(DISABLE_NACL) && defined(OS_LINUX)
75 #include "components/nacl/common/nacl_paths.h"
76 #include "components/nacl/zygote/nacl_fork_delegate_linux.h"
79 #if defined(OS_CHROMEOS)
80 #include "base/sys_info.h"
81 #include "chrome/browser/chromeos/boot_times_recorder.h"
82 #include "chromeos/chromeos_paths.h"
83 #include "chromeos/chromeos_switches.h"
86 #if defined(OS_ANDROID)
87 #include "chrome/common/descriptors_android.h"
89 // Diagnostics is only available on non-android platforms.
90 #include "chrome/browser/diagnostics/diagnostics_controller.h"
91 #include "chrome/browser/diagnostics/diagnostics_writer.h"
97 #include "ui/base/x/x11_util.h"
100 #if defined(OS_POSIX) && !defined(OS_MACOSX)
101 #include "components/crash/app/breakpad_linux.h"
104 #if defined(OS_LINUX)
105 #include "base/environment.h"
108 #if defined(OS_MACOSX) || defined(OS_WIN)
109 #include "chrome/browser/policy/policy_path_parser.h"
112 #if !defined(DISABLE_NACL)
113 #include "components/nacl/common/nacl_switches.h"
114 #include "components/nacl/renderer/plugin/ppapi_entrypoints.h"
117 #if defined(ENABLE_REMOTING)
118 #include "remoting/client/plugin/pepper_entrypoints.h"
121 #if defined(ENABLE_PLUGINS) && (defined(CHROME_MULTIPLE_DLL_CHILD) || \
122 !defined(CHROME_MULTIPLE_DLL_BROWSER))
126 #if !defined(CHROME_MULTIPLE_DLL_BROWSER)
127 #include "chrome/child/pdf_child_init.h"
129 base::LazyInstance
<ChromeContentRendererClient
>
130 g_chrome_content_renderer_client
= LAZY_INSTANCE_INITIALIZER
;
131 base::LazyInstance
<ChromeContentUtilityClient
>
132 g_chrome_content_utility_client
= LAZY_INSTANCE_INITIALIZER
;
133 base::LazyInstance
<chrome::ChromeContentPluginClient
>
134 g_chrome_content_plugin_client
= LAZY_INSTANCE_INITIALIZER
;
137 #if !defined(CHROME_MULTIPLE_DLL_CHILD)
138 base::LazyInstance
<chrome::ChromeContentBrowserClient
>
139 g_chrome_content_browser_client
= LAZY_INSTANCE_INITIALIZER
;
142 #if defined(OS_POSIX)
143 base::LazyInstance
<chrome::ChromeCrashReporterClient
>::Leaky
144 g_chrome_crash_client
= LAZY_INSTANCE_INITIALIZER
;
147 extern int NaClMain(const content::MainFunctionParams
&);
148 extern int ServiceProcessMain(const content::MainFunctionParams
&);
153 // Early versions of Chrome incorrectly registered a chromehtml: URL handler,
154 // which gives us nothing but trouble. Avoid launching chrome this way since
155 // some apps fail to properly escape arguments.
156 bool HasDeprecatedArguments(const std::wstring
& command_line
) {
157 const wchar_t kChromeHtml
[] = L
"chromehtml:";
158 std::wstring command_line_lower
= command_line
;
159 // We are only searching for ASCII characters so this is OK.
160 base::StringToLowerASCII(&command_line_lower
);
161 std::wstring::size_type pos
= command_line_lower
.find(kChromeHtml
);
162 return (pos
!= std::wstring::npos
);
165 // If we try to access a path that is not currently available, we want the call
166 // to fail rather than show an error dialog.
167 void SuppressWindowsErrorDialogs() {
168 UINT new_flags
= SEM_FAILCRITICALERRORS
|
169 SEM_NOOPENFILEERRORBOX
;
171 // Preserve existing error mode.
172 UINT existing_flags
= SetErrorMode(new_flags
);
173 SetErrorMode(existing_flags
| new_flags
);
176 #endif // defined(OS_WIN)
178 #if defined(OS_LINUX)
179 static void AdjustLinuxOOMScore(const std::string
& process_type
) {
180 // Browsers and zygotes should still be killable, but killed last.
181 const int kZygoteScore
= 0;
182 // The minimum amount to bump a score by. This is large enough that
183 // even if it's translated into the old values, it will still go up
185 const int kScoreBump
= 100;
186 // This is the lowest score that renderers and extensions start with
187 // in the OomPriorityManager.
188 const int kRendererScore
= chrome::kLowestRendererOomScore
;
189 // For "miscellaneous" things, we want them after renderers,
190 // but before plugins.
191 const int kMiscScore
= kRendererScore
- kScoreBump
;
192 // We want plugins to die after the renderers.
193 const int kPluginScore
= kMiscScore
- kScoreBump
;
196 DCHECK(kMiscScore
> 0);
197 DCHECK(kPluginScore
> 0);
199 if (process_type
== switches::kPluginProcess
||
200 process_type
== switches::kPpapiPluginProcess
) {
201 score
= kPluginScore
;
202 } else if (process_type
== switches::kPpapiBrokerProcess
) {
203 // The broker should be killed before the PPAPI plugin.
204 score
= kPluginScore
+ kScoreBump
;
205 } else if (process_type
== switches::kUtilityProcess
||
206 process_type
== switches::kGpuProcess
||
207 process_type
== switches::kServiceProcess
) {
210 } else if (process_type
== switches::kNaClLoaderProcess
||
211 process_type
== switches::kNaClLoaderNonSfiProcess
) {
212 score
= kPluginScore
;
214 } else if (process_type
== switches::kZygoteProcess
||
215 process_type
.empty()) {
216 // For zygotes and unlabeled process types, we want to still make
217 // them killable by the OOM killer.
218 score
= kZygoteScore
;
219 } else if (process_type
== switches::kRendererProcess
) {
220 LOG(WARNING
) << "process type 'renderer' "
221 << "should be created through the zygote.";
222 // When debugging, this process type can end up being run directly, but
223 // this isn't the typical path for assigning the OOM score for it. Still,
224 // we want to assign a score that is somewhat representative for debugging.
225 score
= kRendererScore
;
227 NOTREACHED() << "Unknown process type";
230 base::AdjustOOMScore(base::GetCurrentProcId(), score
);
232 #endif // defined(OS_LINUX)
234 // Returns true if this subprocess type needs the ResourceBundle initialized
235 // and resources loaded.
236 bool SubprocessNeedsResourceBundle(const std::string
& process_type
) {
238 #if defined(OS_WIN) || defined(OS_MACOSX)
239 // Windows needs resources for the default/null plugin.
240 // Mac needs them for the plugin process name.
241 process_type
== switches::kPluginProcess
||
243 #if defined(OS_POSIX) && !defined(OS_MACOSX)
244 // The zygote process opens the resources for the renderers.
245 process_type
== switches::kZygoteProcess
||
247 #if defined(OS_MACOSX)
248 // Mac needs them too for scrollbar related images and for sandbox
250 #if !defined(DISABLE_NACL)
251 process_type
== switches::kNaClLoaderProcess
||
253 process_type
== switches::kPpapiPluginProcess
||
254 process_type
== switches::kPpapiBrokerProcess
||
255 process_type
== switches::kGpuProcess
||
257 process_type
== switches::kRendererProcess
||
258 process_type
== switches::kUtilityProcess
;
261 #if defined(OS_POSIX)
262 // Check for --version and --product-version; return true if we encountered
263 // one of these switches and should exit now.
264 bool HandleVersionSwitches(const base::CommandLine
& command_line
) {
265 const chrome::VersionInfo version_info
;
267 #if !defined(OS_MACOSX)
268 if (command_line
.HasSwitch(switches::kProductVersion
)) {
269 printf("%s\n", version_info
.Version().c_str());
274 if (command_line
.HasSwitch(switches::kVersion
)) {
276 version_info
.Name().c_str(),
277 version_info
.Version().c_str(),
278 chrome::VersionInfo::GetVersionStringModifier().c_str());
285 #if !defined(OS_MACOSX) && !defined(OS_CHROMEOS)
286 // Show the man page if --help or -h is on the command line.
287 void HandleHelpSwitches(const base::CommandLine
& command_line
) {
288 if (command_line
.HasSwitch(switches::kHelp
) ||
289 command_line
.HasSwitch(switches::kHelpShort
)) {
290 base::FilePath
binary(command_line
.argv()[0]);
291 execlp("man", "man", binary
.BaseName().value().c_str(), NULL
);
292 PLOG(FATAL
) << "execlp failed";
297 #if !defined(OS_MACOSX) && !defined(OS_ANDROID)
298 void SIGTERMProfilingShutdown(int signal
) {
300 struct sigaction sigact
;
301 memset(&sigact
, 0, sizeof(sigact
));
302 sigact
.sa_handler
= SIG_DFL
;
303 CHECK(sigaction(SIGTERM
, &sigact
, NULL
) == 0);
307 void SetUpProfilingShutdownHandler() {
308 struct sigaction sigact
;
309 sigact
.sa_handler
= SIGTERMProfilingShutdown
;
310 sigact
.sa_flags
= SA_RESETHAND
;
311 sigemptyset(&sigact
.sa_mask
);
312 CHECK(sigaction(SIGTERM
, &sigact
, NULL
) == 0);
314 #endif // !defined(OS_MACOSX) && !defined(OS_ANDROID)
318 struct MainFunction
{
320 int (*function
)(const content::MainFunctionParams
&);
323 // Initializes the user data dir. Must be called before InitializeLocalState().
324 void InitializeUserDataDir() {
325 base::CommandLine
* command_line
= base::CommandLine::ForCurrentProcess();
326 base::FilePath user_data_dir
=
327 command_line
->GetSwitchValuePath(switches::kUserDataDir
);
328 std::string process_type
=
329 command_line
->GetSwitchValueASCII(switches::kProcessType
);
331 #if defined(OS_LINUX)
332 // On Linux, Chrome does not support running multiple copies under different
333 // DISPLAYs, so the profile directory can be specified in the environment to
334 // support the virtual desktop use-case.
335 if (user_data_dir
.empty()) {
336 std::string user_data_dir_string
;
337 scoped_ptr
<base::Environment
> environment(base::Environment::Create());
338 if (environment
->GetVar("CHROME_USER_DATA_DIR", &user_data_dir_string
) &&
339 base::IsStringUTF8(user_data_dir_string
)) {
340 user_data_dir
= base::FilePath::FromUTF8Unsafe(user_data_dir_string
);
344 #if defined(OS_MACOSX) || defined(OS_WIN)
345 policy::path_parser::CheckUserDataDirPolicy(&user_data_dir
);
348 const bool specified_directory_was_invalid
= !user_data_dir
.empty() &&
349 !PathService::OverrideAndCreateIfNeeded(chrome::DIR_USER_DATA
,
350 user_data_dir
, false, true);
351 // Save inaccessible or invalid paths so the user may be prompted later.
352 if (specified_directory_was_invalid
)
353 chrome::SetInvalidSpecifiedUserDataDir(user_data_dir
);
355 // Warn and fail early if the process fails to get a user data directory.
356 if (!PathService::Get(chrome::DIR_USER_DATA
, &user_data_dir
)) {
357 // If an invalid command-line or policy override was specified, the user
358 // will be given an error with that value. Otherwise, use the directory
359 // returned by PathService (or the fallback default directory) in the error.
360 if (!specified_directory_was_invalid
) {
361 // PathService::Get() returns false and yields an empty path if it fails
362 // to create DIR_USER_DATA. Retrieve the default value manually to display
363 // a more meaningful error to the user in that case.
364 if (user_data_dir
.empty())
365 chrome::GetDefaultUserDataDirectory(&user_data_dir
);
366 chrome::SetInvalidSpecifiedUserDataDir(user_data_dir
);
369 // The browser process (which is identified by an empty |process_type|) will
370 // handle the error later; other processes that need the dir crash here.
371 CHECK(process_type
.empty()) << "Unable to get the user data directory "
372 << "for process type: " << process_type
;
375 // Append the fallback user data directory to the commandline. Otherwise,
376 // child or service processes will attempt to use the invalid directory.
377 if (specified_directory_was_invalid
)
378 command_line
->AppendSwitchPath(switches::kUserDataDir
, user_data_dir
);
383 ChromeMainDelegate::ChromeMainDelegate() {
384 #if defined(OS_ANDROID)
385 // On Android the main entry point time is the time when the Java code starts.
386 // This happens before the shared library containing this code is even loaded.
387 // The Java startup code has recorded that time, but the C++ code can't fetch it
388 // from the Java side until it has initialized the JNI. See
389 // ChromeMainDelegateAndroid.
391 startup_metric_utils::RecordMainEntryPointTime();
395 ChromeMainDelegate::~ChromeMainDelegate() {
398 bool ChromeMainDelegate::BasicStartupComplete(int* exit_code
) {
399 #if defined(OS_CHROMEOS)
400 chromeos::BootTimesRecorder::Get()->SaveChromeMainStats();
403 const base::CommandLine
& command_line
=
404 *base::CommandLine::ForCurrentProcess();
406 #if defined(OS_MACOSX)
407 // Give the browser process a longer treadmill, since crashes
408 // there have more impact.
409 const bool is_browser
= !command_line
.HasSwitch(switches::kProcessType
);
410 ObjcEvilDoers::ZombieEnable(true, is_browser
? 10000 : 1000);
412 SetUpBundleOverrides();
413 chrome::common::mac::EnableCFBundleBlocker();
416 Profiling::ProcessStarted();
419 v8_breakpad_support::SetUp();
422 #if defined(OS_POSIX)
423 if (HandleVersionSwitches(command_line
)) {
425 return true; // Got a --version switch; exit with a success error code.
427 #if !defined(OS_MACOSX) && !defined(OS_CHROMEOS)
428 // This will directly exit if the user asked for help.
429 HandleHelpSwitches(command_line
);
434 // Must do this before any other usage of command line!
435 if (HasDeprecatedArguments(command_line
.GetCommandLineString())) {
440 InstallCloseHandleHooks();
443 chrome::RegisterPathProvider();
444 #if defined(OS_CHROMEOS)
445 chromeos::RegisterPathProvider();
447 #if !defined(DISABLE_NACL) && defined(OS_LINUX)
448 nacl::RegisterPathProvider();
451 ContentSettingsPattern::SetNonWildcardDomainNonPortScheme(
452 extensions::kExtensionScheme
);
454 // No support for ANDROID yet as DiagnosticsController needs wchar support.
455 // TODO(gspencer): That's not true anymore, or at least there are no w-string
456 // references anymore. Not sure if that means this can be enabled on Android or
457 // not though. As there is no easily accessible command line on Android, I'm
458 // not sure this is a big deal.
459 #if !defined(OS_ANDROID) && !defined(CHROME_MULTIPLE_DLL_CHILD)
460 // If we are in diagnostics mode this is the end of the line: after the
461 // diagnostics are run the process will invariably exit.
462 if (command_line
.HasSwitch(switches::kDiagnostics
)) {
463 diagnostics::DiagnosticsWriter::FormatType format
=
464 diagnostics::DiagnosticsWriter::HUMAN
;
465 if (command_line
.HasSwitch(switches::kDiagnosticsFormat
)) {
466 std::string format_str
=
467 command_line
.GetSwitchValueASCII(switches::kDiagnosticsFormat
);
468 if (format_str
== "machine") {
469 format
= diagnostics::DiagnosticsWriter::MACHINE
;
470 } else if (format_str
== "log") {
471 format
= diagnostics::DiagnosticsWriter::LOG
;
473 DCHECK_EQ("human", format_str
);
477 diagnostics::DiagnosticsWriter
writer(format
);
478 *exit_code
= diagnostics::DiagnosticsController::GetInstance()->Run(
479 command_line
, &writer
);
480 diagnostics::DiagnosticsController::GetInstance()->ClearResults();
485 #if defined(OS_CHROMEOS)
486 // Initialize primary user homedir (in multi-profile session) as it may be
487 // passed as a command line switch.
488 base::FilePath homedir
;
489 if (command_line
.HasSwitch(chromeos::switches::kHomedir
)) {
490 homedir
= base::FilePath(
491 command_line
.GetSwitchValueASCII(chromeos::switches::kHomedir
));
492 PathService::OverrideAndCreateIfNeeded(
493 base::DIR_HOME
, homedir
, true, false);
496 // If we are recovering from a crash on ChromeOS, then we will do some
497 // recovery using the diagnostics module, and then continue on. We fake up a
498 // command line to tell it that we want it to recover, and to preserve the
499 // original command line.
500 if (command_line
.HasSwitch(chromeos::switches::kLoginUser
) ||
501 command_line
.HasSwitch(switches::kDiagnosticsRecovery
)) {
502 // The statistics subsystem needs get initialized soon enough for the
503 // statistics to be collected. It's safe to call this more than once.
504 base::StatisticsRecorder::Initialize();
506 base::CommandLine
interim_command_line(command_line
.GetProgram());
507 const char* const kSwitchNames
[] = {switches::kUserDataDir
, };
508 interim_command_line
.CopySwitchesFrom(
509 command_line
, kSwitchNames
, arraysize(kSwitchNames
));
510 interim_command_line
.AppendSwitch(switches::kDiagnostics
);
511 interim_command_line
.AppendSwitch(switches::kDiagnosticsRecovery
);
513 diagnostics::DiagnosticsWriter::FormatType format
=
514 diagnostics::DiagnosticsWriter::LOG
;
515 if (command_line
.HasSwitch(switches::kDiagnosticsFormat
)) {
516 std::string format_str
=
517 command_line
.GetSwitchValueASCII(switches::kDiagnosticsFormat
);
518 if (format_str
== "machine") {
519 format
= diagnostics::DiagnosticsWriter::MACHINE
;
520 } else if (format_str
== "human") {
521 format
= diagnostics::DiagnosticsWriter::HUMAN
;
523 DCHECK_EQ("log", format_str
);
527 diagnostics::DiagnosticsWriter
writer(format
);
528 int diagnostics_exit_code
=
529 diagnostics::DiagnosticsController::GetInstance()->Run(command_line
,
531 if (diagnostics_exit_code
) {
532 // Diagnostics has failed somehow, so we exit.
533 *exit_code
= diagnostics_exit_code
;
537 // Now we run the actual recovery tasks.
538 int recovery_exit_code
=
539 diagnostics::DiagnosticsController::GetInstance()->RunRecovery(
540 command_line
, &writer
);
542 if (recovery_exit_code
) {
543 // Recovery has failed somehow, so we exit.
544 *exit_code
= recovery_exit_code
;
547 } else { // Not running diagnostics or recovery.
548 diagnostics::DiagnosticsController::GetInstance()->RecordRegularStartup();
552 content::SetContentClient(&chrome_content_client_
);
557 #if defined(OS_MACOSX)
558 void ChromeMainDelegate::InitMacCrashReporter(
559 const base::CommandLine
& command_line
,
560 const std::string
& process_type
) {
561 // TODO(mark): Right now, InitCrashReporter() needs to be called after
562 // CommandLine::Init() and chrome::RegisterPathProvider(). Ideally,
563 // Breakpad initialization could occur sooner, preferably even before the
564 // framework dylib is even loaded, to catch potential early crashes.
565 breakpad::InitCrashReporter(process_type
);
568 bool is_debug_build
= false;
570 bool is_debug_build
= true;
573 // Details on when we enable Apple's Crash reporter.
576 // In debug mode it takes Apple's crash reporter eons to generate a crash
580 // * We only pass crashes for foreground processes to Apple's Crash
581 // reporter. At the time of this writing, that means just the Browser
583 // * If Breakpad is enabled, it will pass browser crashes to Crash Reporter
585 // * If Breakpad is disabled, we only turn on Crash Reporter for the
586 // Browser process in release mode.
587 if (!command_line
.HasSwitch(switches::kDisableBreakpad
)) {
588 bool disable_apple_crash_reporter
= is_debug_build
||
589 base::mac::IsBackgroundOnlyProcess();
590 if (!breakpad::IsCrashReporterEnabled() && disable_apple_crash_reporter
) {
591 base::mac::DisableOSCrashDumps();
595 // Mac Chrome is packaged with a main app bundle and a helper app bundle.
596 // The main app bundle should only be used for the browser process, so it
597 // should never see a --type switch (switches::kProcessType). Likewise,
598 // the helper should always have a --type switch.
600 // This check is done this late so there is already a call to
601 // base::mac::IsBackgroundOnlyProcess(), so there is no change in
602 // startup/initialization order.
604 // The helper's Info.plist marks it as a background only app.
605 if (base::mac::IsBackgroundOnlyProcess()) {
606 CHECK(command_line
.HasSwitch(switches::kProcessType
) &&
607 !process_type
.empty())
608 << "Helper application requires --type.";
610 // In addition, some helper flavors only work with certain process types.
611 base::FilePath executable
;
612 if (PathService::Get(base::FILE_EXE
, &executable
) &&
613 executable
.value().size() >= 3) {
614 std::string last_three
=
615 executable
.value().substr(executable
.value().size() - 3);
617 if (last_three
== " EH") {
618 CHECK(process_type
== switches::kPluginProcess
||
619 process_type
== switches::kUtilityProcess
)
620 << "Executable-heap process requires --type="
621 << switches::kPluginProcess
<< " or "
622 << switches::kUtilityProcess
<< ", saw " << process_type
;
623 } else if (last_three
== " NP") {
624 #if !defined(DISABLE_NACL)
625 CHECK_EQ(switches::kNaClLoaderProcess
, process_type
)
626 << "Non-PIE process requires --type="
627 << switches::kNaClLoaderProcess
<< ", saw " << process_type
;
630 #if defined(DISABLE_NACL)
631 CHECK(process_type
!= switches::kPluginProcess
)
632 << "Non-executable-heap PIE process is intolerant of --type="
633 << switches::kPluginProcess
;
635 CHECK(process_type
!= switches::kPluginProcess
&&
636 process_type
!= switches::kNaClLoaderProcess
)
637 << "Non-executable-heap PIE process is intolerant of --type="
638 << switches::kPluginProcess
<< " and "
639 << switches::kNaClLoaderProcess
<< ", saw " << process_type
;
644 CHECK(!command_line
.HasSwitch(switches::kProcessType
) &&
645 process_type
.empty())
646 << "Main application forbids --type, saw " << process_type
;
649 if (breakpad::IsCrashReporterEnabled())
650 breakpad::InitCrashProcessInfo(process_type
);
652 #endif // defined(OS_MACOSX)
654 void ChromeMainDelegate::PreSandboxStartup() {
655 const base::CommandLine
& command_line
=
656 *base::CommandLine::ForCurrentProcess();
657 std::string process_type
=
658 command_line
.GetSwitchValueASCII(switches::kProcessType
);
660 #if defined(OS_POSIX)
661 crash_reporter::SetCrashReporterClient(g_chrome_crash_client
.Pointer());
664 #if defined(OS_MACOSX)
665 // On the Mac, the child executable lives at a predefined location within
666 // the app bundle's versioned directory.
667 PathService::Override(content::CHILD_PROCESS_EXE
,
668 chrome::GetVersionedDirectory().
669 Append(chrome::kHelperProcessExecutablePath
));
671 InitMacCrashReporter(command_line
, process_type
);
675 child_process_logging::Init();
677 #if defined(ARCH_CPU_ARM_FAMILY) && (defined(OS_ANDROID) || defined(OS_LINUX))
678 // Create an instance of the CPU class to parse /proc/cpuinfo and cache
683 // Initialize the user data dir for any process type that needs it.
684 if (chrome::ProcessNeedsProfileDir(process_type
))
685 InitializeUserDataDir();
687 // Register component_updater PathProvider after DIR_USER_DATA overidden by
688 // command line flags. Maybe move the chrome PathProvider down here also?
689 component_updater::RegisterPathProvider(chrome::DIR_USER_DATA
);
691 // Enable Message Loop related state asap.
692 if (command_line
.HasSwitch(switches::kMessageLoopHistogrammer
))
693 base::MessageLoop::EnableHistogrammer(true);
695 #if !defined(OS_ANDROID)
696 // Android does InitLogging when library is loaded. Skip here.
697 logging::OldFileDeletionState file_state
=
698 logging::APPEND_TO_OLD_LOG_FILE
;
699 if (process_type
.empty()) {
700 file_state
= logging::DELETE_OLD_LOG_FILE
;
702 logging::InitChromeLogging(command_line
, file_state
);
706 // TODO(zturner): Throbber icons are still stored in chrome.dll, this can be
707 // killed once those are merged into resources.pak. See
708 // GlassBrowserFrameView::InitThrobberIcons() and http://crbug.com/368327.
709 ui::SetResourcesDataDLL(_AtlBaseModule
.GetResourceInstance());
712 if (SubprocessNeedsResourceBundle(process_type
)) {
713 // Initialize ResourceBundle which handles files loaded from external
714 // sources. The language should have been passed in to us from the
715 // browser process as a command line flag.
716 #if defined(DISABLE_NACL)
717 DCHECK(command_line
.HasSwitch(switches::kLang
) ||
718 process_type
== switches::kZygoteProcess
||
719 process_type
== switches::kGpuProcess
||
720 process_type
== switches::kPpapiBrokerProcess
||
721 process_type
== switches::kPpapiPluginProcess
);
723 DCHECK(command_line
.HasSwitch(switches::kLang
) ||
724 process_type
== switches::kZygoteProcess
||
725 process_type
== switches::kGpuProcess
||
726 process_type
== switches::kNaClLoaderProcess
||
727 process_type
== switches::kPpapiBrokerProcess
||
728 process_type
== switches::kPpapiPluginProcess
);
731 // TODO(markusheintz): The command line flag --lang is actually processed
732 // by the CommandLinePrefStore, and made available through the PrefService
733 // via the preference prefs::kApplicationLocale. The browser process uses
734 // the --lang flag to pass the value of the PrefService in here. Maybe
735 // this value could be passed in a different way.
736 const std::string locale
=
737 command_line
.GetSwitchValueASCII(switches::kLang
);
738 #if defined(OS_ANDROID)
739 // The renderer sandbox prevents us from accessing our .pak files directly.
740 // Therefore file descriptors to the .pak files that we need are passed in
741 // at process creation time.
742 int locale_pak_fd
= base::GlobalDescriptors::GetInstance()->MaybeGet(
743 kAndroidLocalePakDescriptor
);
744 CHECK(locale_pak_fd
!= -1);
745 ResourceBundle::InitSharedInstanceWithPakFileRegion(
746 base::File(locale_pak_fd
), base::MemoryMappedFile::Region::kWholeFile
);
748 int extra_pak_keys
[] = {
749 kAndroidChrome100PercentPakDescriptor
,
750 kAndroidUIResourcesPakDescriptor
,
752 for (size_t i
= 0; i
< arraysize(extra_pak_keys
); ++i
) {
754 base::GlobalDescriptors::GetInstance()->MaybeGet(extra_pak_keys
[i
]);
756 ResourceBundle::GetSharedInstance().AddDataPackFromFile(
757 base::File(pak_fd
), ui::SCALE_FACTOR_100P
);
760 base::i18n::SetICUDefaultLocale(locale
);
761 const std::string loaded_locale
= locale
;
763 const std::string loaded_locale
=
764 ui::ResourceBundle::InitSharedInstanceWithLocale(
765 locale
, NULL
, ui::ResourceBundle::LOAD_COMMON_RESOURCES
);
767 base::FilePath resources_pack_path
;
768 PathService::Get(chrome::FILE_RESOURCES_PACK
, &resources_pack_path
);
769 ResourceBundle::GetSharedInstance().AddDataPackFromPath(
770 resources_pack_path
, ui::SCALE_FACTOR_NONE
);
772 CHECK(!loaded_locale
.empty()) << "Locale could not be found for " <<
776 #if !defined(CHROME_MULTIPLE_DLL_BROWSER)
777 if (process_type
== switches::kUtilityProcess
||
778 process_type
== switches::kZygoteProcess
) {
779 ChromeContentUtilityClient::PreSandboxStartup();
782 chrome::InitializePDF();
785 #if defined(OS_POSIX) && !defined(OS_MACOSX)
786 // Zygote needs to call InitCrashReporter() in RunZygote().
787 if (process_type
!= switches::kZygoteProcess
) {
788 #if defined(OS_ANDROID)
789 if (process_type
.empty())
790 breakpad::InitCrashReporter(process_type
);
792 breakpad::InitNonBrowserCrashReporterForAndroid(process_type
);
793 #else // !defined(OS_ANDROID)
794 breakpad::InitCrashReporter(process_type
);
795 #endif // defined(OS_ANDROID)
797 #endif // defined(OS_POSIX) && !defined(OS_MACOSX)
799 // After all the platform Breakpads have been initialized, store the command
800 // line for crash reporting.
801 crash_keys::SetSwitchesFromCommandLine(&command_line
);
804 void ChromeMainDelegate::SandboxInitialized(const std::string
& process_type
) {
805 // Note: If you are adding a new process type below, be sure to adjust the
806 // AdjustLinuxOOMScore function too.
807 #if defined(OS_LINUX)
808 AdjustLinuxOOMScore(process_type
);
811 SuppressWindowsErrorDialogs();
814 #if defined(CHROME_MULTIPLE_DLL_CHILD) || !defined(CHROME_MULTIPLE_DLL_BROWSER)
815 #if defined(ENABLE_REMOTING)
816 ChromeContentClient::SetRemotingEntryFunctions(
817 remoting::PPP_GetInterface
,
818 remoting::PPP_InitializeModule
,
819 remoting::PPP_ShutdownModule
);
821 #if !defined(DISABLE_NACL)
822 ChromeContentClient::SetNaClEntryFunctions(
823 nacl_plugin::PPP_GetInterface
,
824 nacl_plugin::PPP_InitializeModule
,
825 nacl_plugin::PPP_ShutdownModule
);
827 #if defined(ENABLE_PLUGINS)
828 ChromeContentClient::SetPDFEntryFunctions(
829 chrome_pdf::PPP_GetInterface
,
830 chrome_pdf::PPP_InitializeModule
,
831 chrome_pdf::PPP_ShutdownModule
);
836 int ChromeMainDelegate::RunProcess(
837 const std::string
& process_type
,
838 const content::MainFunctionParams
& main_function_params
) {
839 // ANDROID doesn't support "service", so no ServiceProcessMain, and arraysize
840 // doesn't support empty array. So we comment out the block for Android.
841 #if !defined(OS_ANDROID)
842 static const MainFunction kMainFunctions
[] = {
843 #if defined(ENABLE_PRINT_PREVIEW) && !defined(CHROME_MULTIPLE_DLL_CHILD)
844 { switches::kServiceProcess
, ServiceProcessMain
},
847 #if defined(OS_MACOSX)
848 { switches::kRelauncherProcess
,
849 mac_relauncher::internal::RelauncherMain
},
852 // This entry is not needed on Linux, where the NaCl loader
853 // process is launched via nacl_helper instead.
854 #if !defined(DISABLE_NACL) && !defined(CHROME_MULTIPLE_DLL_BROWSER) && \
856 { switches::kNaClLoaderProcess
, NaClMain
},
858 { "<invalid>", NULL
}, // To avoid constant array of size 0
859 // when DISABLE_NACL and CHROME_MULTIPLE_DLL_CHILD
860 #endif // DISABLE_NACL
863 for (size_t i
= 0; i
< arraysize(kMainFunctions
); ++i
) {
864 if (process_type
== kMainFunctions
[i
].name
)
865 return kMainFunctions
[i
].function(main_function_params
);
872 void ChromeMainDelegate::ProcessExiting(const std::string
& process_type
) {
873 if (SubprocessNeedsResourceBundle(process_type
))
874 ResourceBundle::CleanupSharedInstance();
875 #if !defined(OS_ANDROID)
876 logging::CleanupChromeLogging();
878 // Android doesn't use InitChromeLogging, so we close the log file manually.
879 logging::CloseLogFile();
880 #endif // !defined(OS_ANDROID)
883 RemoveCloseHandleHooks();
887 #if defined(OS_MACOSX)
888 bool ChromeMainDelegate::ProcessRegistersWithSystemProcess(
889 const std::string
& process_type
) {
890 #if defined(DISABLE_NACL)
893 return process_type
== switches::kNaClLoaderProcess
;
897 bool ChromeMainDelegate::ShouldSendMachPort(const std::string
& process_type
) {
898 return process_type
!= switches::kRelauncherProcess
&&
899 process_type
!= switches::kServiceProcess
;
902 bool ChromeMainDelegate::DelaySandboxInitialization(
903 const std::string
& process_type
) {
904 #if !defined(DISABLE_NACL)
905 // NaClLoader does this in NaClMainPlatformDelegate::EnableSandbox().
906 // No sandbox needed for relauncher.
907 if (process_type
== switches::kNaClLoaderProcess
)
910 return process_type
== switches::kRelauncherProcess
;
912 #elif defined(OS_POSIX) && !defined(OS_ANDROID)
913 void ChromeMainDelegate::ZygoteStarting(
914 ScopedVector
<content::ZygoteForkDelegate
>* delegates
) {
915 #if !defined(DISABLE_NACL)
916 nacl::AddNaClZygoteForkDelegates(delegates
);
920 void ChromeMainDelegate::ZygoteForked() {
921 Profiling::ProcessStarted();
922 if (Profiling::BeingProfiled()) {
923 base::debug::RestartProfilingAfterFork();
924 SetUpProfilingShutdownHandler();
927 // Needs to be called after we have chrome::DIR_USER_DATA. BrowserMain sets
928 // this up for the browser process in a different manner.
929 const base::CommandLine
* command_line
=
930 base::CommandLine::ForCurrentProcess();
931 std::string process_type
=
932 command_line
->GetSwitchValueASCII(switches::kProcessType
);
933 breakpad::InitCrashReporter(process_type
);
935 // Reset the command line for the newly spawned process.
936 crash_keys::SetSwitchesFromCommandLine(command_line
);
942 bool ChromeMainDelegate::ShouldEnableTerminationOnHeapCorruption() {
943 return !ShouldExperimentallyDisableTerminateOnHeapCorruption();
947 content::ContentBrowserClient
*
948 ChromeMainDelegate::CreateContentBrowserClient() {
949 #if defined(CHROME_MULTIPLE_DLL_CHILD)
952 return g_chrome_content_browser_client
.Pointer();
956 content::ContentPluginClient
* ChromeMainDelegate::CreateContentPluginClient() {
957 #if defined(CHROME_MULTIPLE_DLL_BROWSER)
960 return g_chrome_content_plugin_client
.Pointer();
964 content::ContentRendererClient
*
965 ChromeMainDelegate::CreateContentRendererClient() {
966 #if defined(CHROME_MULTIPLE_DLL_BROWSER)
969 return g_chrome_content_renderer_client
.Pointer();
973 content::ContentUtilityClient
*
974 ChromeMainDelegate::CreateContentUtilityClient() {
975 #if defined(CHROME_MULTIPLE_DLL_BROWSER)
978 return g_chrome_content_utility_client
.Pointer();