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/v8_breakpad_support_win.h"
51 #include "sandbox/win/src/sandbox.h"
52 #include "ui/base/resource/resource_bundle_win.h"
55 #if defined(OS_MACOSX)
56 #include "base/mac/foundation_util.h"
57 #include "chrome/app/chrome_main_mac.h"
58 #include "chrome/browser/mac/relauncher.h"
59 #include "chrome/common/mac/cfbundle_blocker.h"
60 #include "chrome/common/mac/objc_zombie.h"
61 #include "components/crash/app/crashpad_mac.h"
62 #include "ui/base/l10n/l10n_util_mac.h"
68 #include "chrome/app/chrome_crash_reporter_client.h"
69 #include "components/crash/app/crash_reporter_client.h"
72 #if !defined(DISABLE_NACL) && defined(OS_LINUX)
73 #include "components/nacl/common/nacl_paths.h"
74 #include "components/nacl/zygote/nacl_fork_delegate_linux.h"
77 #if defined(OS_CHROMEOS)
78 #include "base/sys_info.h"
79 #include "chrome/browser/chromeos/boot_times_recorder.h"
80 #include "chromeos/chromeos_paths.h"
81 #include "chromeos/chromeos_switches.h"
84 #if defined(OS_ANDROID)
85 #include "chrome/common/descriptors_android.h"
87 // Diagnostics is only available on non-android platforms.
88 #include "chrome/browser/diagnostics/diagnostics_controller.h"
89 #include "chrome/browser/diagnostics/diagnostics_writer.h"
95 #include "ui/base/x/x11_util.h"
98 #if defined(OS_POSIX) && !defined(OS_MACOSX)
99 #include "components/crash/app/breakpad_linux.h"
102 #if defined(OS_LINUX)
103 #include "base/environment.h"
106 #if defined(OS_MACOSX) || defined(OS_WIN)
107 #include "chrome/browser/policy/policy_path_parser.h"
110 #if !defined(DISABLE_NACL)
111 #include "components/nacl/common/nacl_switches.h"
112 #include "components/nacl/renderer/plugin/ppapi_entrypoints.h"
115 #if defined(ENABLE_REMOTING)
116 #include "remoting/client/plugin/pepper_entrypoints.h"
119 #if defined(ENABLE_PLUGINS) && (defined(CHROME_MULTIPLE_DLL_CHILD) || \
120 !defined(CHROME_MULTIPLE_DLL_BROWSER))
124 #if !defined(CHROME_MULTIPLE_DLL_BROWSER)
125 #include "chrome/child/pdf_child_init.h"
127 base::LazyInstance
<ChromeContentRendererClient
>
128 g_chrome_content_renderer_client
= LAZY_INSTANCE_INITIALIZER
;
129 base::LazyInstance
<ChromeContentUtilityClient
>
130 g_chrome_content_utility_client
= LAZY_INSTANCE_INITIALIZER
;
131 base::LazyInstance
<chrome::ChromeContentPluginClient
>
132 g_chrome_content_plugin_client
= LAZY_INSTANCE_INITIALIZER
;
135 #if !defined(CHROME_MULTIPLE_DLL_CHILD)
136 base::LazyInstance
<chrome::ChromeContentBrowserClient
>
137 g_chrome_content_browser_client
= LAZY_INSTANCE_INITIALIZER
;
140 #if defined(OS_POSIX)
141 base::LazyInstance
<chrome::ChromeCrashReporterClient
>::Leaky
142 g_chrome_crash_client
= LAZY_INSTANCE_INITIALIZER
;
145 extern int NaClMain(const content::MainFunctionParams
&);
146 extern int ServiceProcessMain(const content::MainFunctionParams
&);
151 // Early versions of Chrome incorrectly registered a chromehtml: URL handler,
152 // which gives us nothing but trouble. Avoid launching chrome this way since
153 // some apps fail to properly escape arguments.
154 bool HasDeprecatedArguments(const std::wstring
& command_line
) {
155 const wchar_t kChromeHtml
[] = L
"chromehtml:";
156 std::wstring command_line_lower
= command_line
;
157 // We are only searching for ASCII characters so this is OK.
158 base::StringToLowerASCII(&command_line_lower
);
159 std::wstring::size_type pos
= command_line_lower
.find(kChromeHtml
);
160 return (pos
!= std::wstring::npos
);
163 // If we try to access a path that is not currently available, we want the call
164 // to fail rather than show an error dialog.
165 void SuppressWindowsErrorDialogs() {
166 UINT new_flags
= SEM_FAILCRITICALERRORS
|
167 SEM_NOOPENFILEERRORBOX
;
169 // Preserve existing error mode.
170 UINT existing_flags
= SetErrorMode(new_flags
);
171 SetErrorMode(existing_flags
| new_flags
);
174 #endif // defined(OS_WIN)
176 #if defined(OS_LINUX)
177 static void AdjustLinuxOOMScore(const std::string
& process_type
) {
178 // Browsers and zygotes should still be killable, but killed last.
179 const int kZygoteScore
= 0;
180 // The minimum amount to bump a score by. This is large enough that
181 // even if it's translated into the old values, it will still go up
183 const int kScoreBump
= 100;
184 // This is the lowest score that renderers and extensions start with
185 // in the OomPriorityManager.
186 const int kRendererScore
= chrome::kLowestRendererOomScore
;
187 // For "miscellaneous" things, we want them after renderers,
188 // but before plugins.
189 const int kMiscScore
= kRendererScore
- kScoreBump
;
190 // We want plugins to die after the renderers.
191 const int kPluginScore
= kMiscScore
- kScoreBump
;
194 DCHECK(kMiscScore
> 0);
195 DCHECK(kPluginScore
> 0);
197 if (process_type
== switches::kPluginProcess
||
198 process_type
== switches::kPpapiPluginProcess
) {
199 score
= kPluginScore
;
200 } else if (process_type
== switches::kPpapiBrokerProcess
) {
201 // The broker should be killed before the PPAPI plugin.
202 score
= kPluginScore
+ kScoreBump
;
203 } else if (process_type
== switches::kUtilityProcess
||
204 process_type
== switches::kGpuProcess
||
205 process_type
== switches::kServiceProcess
) {
208 } else if (process_type
== switches::kNaClLoaderProcess
||
209 process_type
== switches::kNaClLoaderNonSfiProcess
) {
210 score
= kPluginScore
;
212 } else if (process_type
== switches::kZygoteProcess
||
213 process_type
.empty()) {
214 // For zygotes and unlabeled process types, we want to still make
215 // them killable by the OOM killer.
216 score
= kZygoteScore
;
217 } else if (process_type
== switches::kRendererProcess
) {
218 LOG(WARNING
) << "process type 'renderer' "
219 << "should be created through the zygote.";
220 // When debugging, this process type can end up being run directly, but
221 // this isn't the typical path for assigning the OOM score for it. Still,
222 // we want to assign a score that is somewhat representative for debugging.
223 score
= kRendererScore
;
225 NOTREACHED() << "Unknown process type";
228 base::AdjustOOMScore(base::GetCurrentProcId(), score
);
230 #endif // defined(OS_LINUX)
232 // Returns true if this subprocess type needs the ResourceBundle initialized
233 // and resources loaded.
234 bool SubprocessNeedsResourceBundle(const std::string
& process_type
) {
236 #if defined(OS_WIN) || defined(OS_MACOSX)
237 // Windows needs resources for the default/null plugin.
238 // Mac needs them for the plugin process name.
239 process_type
== switches::kPluginProcess
||
241 #if defined(OS_POSIX) && !defined(OS_MACOSX)
242 // The zygote process opens the resources for the renderers.
243 process_type
== switches::kZygoteProcess
||
245 #if defined(OS_MACOSX)
246 // Mac needs them too for scrollbar related images and for sandbox
248 #if !defined(DISABLE_NACL)
249 process_type
== switches::kNaClLoaderProcess
||
251 process_type
== switches::kPpapiPluginProcess
||
252 process_type
== switches::kPpapiBrokerProcess
||
253 process_type
== switches::kGpuProcess
||
255 process_type
== switches::kRendererProcess
||
256 process_type
== switches::kUtilityProcess
;
259 #if defined(OS_POSIX)
260 // Check for --version and --product-version; return true if we encountered
261 // one of these switches and should exit now.
262 bool HandleVersionSwitches(const base::CommandLine
& command_line
) {
263 const chrome::VersionInfo version_info
;
265 #if !defined(OS_MACOSX)
266 if (command_line
.HasSwitch(switches::kProductVersion
)) {
267 printf("%s\n", version_info
.Version().c_str());
272 if (command_line
.HasSwitch(switches::kVersion
)) {
274 version_info
.Name().c_str(),
275 version_info
.Version().c_str(),
276 chrome::VersionInfo::GetVersionStringModifier().c_str());
283 #if !defined(OS_MACOSX) && !defined(OS_CHROMEOS)
284 // Show the man page if --help or -h is on the command line.
285 void HandleHelpSwitches(const base::CommandLine
& command_line
) {
286 if (command_line
.HasSwitch(switches::kHelp
) ||
287 command_line
.HasSwitch(switches::kHelpShort
)) {
288 base::FilePath
binary(command_line
.argv()[0]);
289 execlp("man", "man", binary
.BaseName().value().c_str(), NULL
);
290 PLOG(FATAL
) << "execlp failed";
295 #if !defined(OS_MACOSX) && !defined(OS_ANDROID)
296 void SIGTERMProfilingShutdown(int signal
) {
298 struct sigaction sigact
;
299 memset(&sigact
, 0, sizeof(sigact
));
300 sigact
.sa_handler
= SIG_DFL
;
301 CHECK(sigaction(SIGTERM
, &sigact
, NULL
) == 0);
305 void SetUpProfilingShutdownHandler() {
306 struct sigaction sigact
;
307 sigact
.sa_handler
= SIGTERMProfilingShutdown
;
308 sigact
.sa_flags
= SA_RESETHAND
;
309 sigemptyset(&sigact
.sa_mask
);
310 CHECK(sigaction(SIGTERM
, &sigact
, NULL
) == 0);
312 #endif // !defined(OS_MACOSX) && !defined(OS_ANDROID)
316 struct MainFunction
{
318 int (*function
)(const content::MainFunctionParams
&);
321 // Initializes the user data dir. Must be called before InitializeLocalState().
322 void InitializeUserDataDir() {
323 base::CommandLine
* command_line
= base::CommandLine::ForCurrentProcess();
324 base::FilePath user_data_dir
=
325 command_line
->GetSwitchValuePath(switches::kUserDataDir
);
326 std::string process_type
=
327 command_line
->GetSwitchValueASCII(switches::kProcessType
);
329 #if defined(OS_LINUX)
330 // On Linux, Chrome does not support running multiple copies under different
331 // DISPLAYs, so the profile directory can be specified in the environment to
332 // support the virtual desktop use-case.
333 if (user_data_dir
.empty()) {
334 std::string user_data_dir_string
;
335 scoped_ptr
<base::Environment
> environment(base::Environment::Create());
336 if (environment
->GetVar("CHROME_USER_DATA_DIR", &user_data_dir_string
) &&
337 base::IsStringUTF8(user_data_dir_string
)) {
338 user_data_dir
= base::FilePath::FromUTF8Unsafe(user_data_dir_string
);
342 #if defined(OS_MACOSX) || defined(OS_WIN)
343 policy::path_parser::CheckUserDataDirPolicy(&user_data_dir
);
346 // On Windows, trailing separators leave Chrome in a bad state.
347 // See crbug.com/464616.
348 if (user_data_dir
.EndsWithSeparator())
349 user_data_dir
= user_data_dir
.StripTrailingSeparators();
351 const bool specified_directory_was_invalid
= !user_data_dir
.empty() &&
352 !PathService::OverrideAndCreateIfNeeded(chrome::DIR_USER_DATA
,
353 user_data_dir
, false, true);
354 // Save inaccessible or invalid paths so the user may be prompted later.
355 if (specified_directory_was_invalid
)
356 chrome::SetInvalidSpecifiedUserDataDir(user_data_dir
);
358 // Warn and fail early if the process fails to get a user data directory.
359 if (!PathService::Get(chrome::DIR_USER_DATA
, &user_data_dir
)) {
360 // If an invalid command-line or policy override was specified, the user
361 // will be given an error with that value. Otherwise, use the directory
362 // returned by PathService (or the fallback default directory) in the error.
363 if (!specified_directory_was_invalid
) {
364 // PathService::Get() returns false and yields an empty path if it fails
365 // to create DIR_USER_DATA. Retrieve the default value manually to display
366 // a more meaningful error to the user in that case.
367 if (user_data_dir
.empty())
368 chrome::GetDefaultUserDataDirectory(&user_data_dir
);
369 chrome::SetInvalidSpecifiedUserDataDir(user_data_dir
);
372 // The browser process (which is identified by an empty |process_type|) will
373 // handle the error later; other processes that need the dir crash here.
374 CHECK(process_type
.empty()) << "Unable to get the user data directory "
375 << "for process type: " << process_type
;
378 // Append the fallback user data directory to the commandline. Otherwise,
379 // child or service processes will attempt to use the invalid directory.
380 if (specified_directory_was_invalid
)
381 command_line
->AppendSwitchPath(switches::kUserDataDir
, user_data_dir
);
386 ChromeMainDelegate::ChromeMainDelegate() {
387 #if defined(OS_ANDROID)
388 // On Android the main entry point time is the time when the Java code starts.
389 // This happens before the shared library containing this code is even loaded.
390 // The Java startup code has recorded that time, but the C++ code can't fetch it
391 // from the Java side until it has initialized the JNI. See
392 // ChromeMainDelegateAndroid.
394 startup_metric_utils::RecordMainEntryPointTime();
398 ChromeMainDelegate::~ChromeMainDelegate() {
401 bool ChromeMainDelegate::BasicStartupComplete(int* exit_code
) {
402 #if defined(OS_CHROMEOS)
403 chromeos::BootTimesRecorder::Get()->SaveChromeMainStats();
406 const base::CommandLine
& command_line
=
407 *base::CommandLine::ForCurrentProcess();
409 #if defined(OS_MACOSX)
410 // Give the browser process a longer treadmill, since crashes
411 // there have more impact.
412 const bool is_browser
= !command_line
.HasSwitch(switches::kProcessType
);
413 ObjcEvilDoers::ZombieEnable(true, is_browser
? 10000 : 1000);
415 SetUpBundleOverrides();
416 chrome::common::mac::EnableCFBundleBlocker();
419 Profiling::ProcessStarted();
422 v8_breakpad_support::SetUp();
425 #if defined(OS_POSIX)
426 if (HandleVersionSwitches(command_line
)) {
428 return true; // Got a --version switch; exit with a success error code.
430 #if !defined(OS_MACOSX) && !defined(OS_CHROMEOS)
431 // This will directly exit if the user asked for help.
432 HandleHelpSwitches(command_line
);
437 // Must do this before any other usage of command line!
438 if (HasDeprecatedArguments(command_line
.GetCommandLineString())) {
443 InstallCloseHandleHooks();
446 chrome::RegisterPathProvider();
447 #if defined(OS_CHROMEOS)
448 chromeos::RegisterPathProvider();
450 #if !defined(DISABLE_NACL) && defined(OS_LINUX)
451 nacl::RegisterPathProvider();
454 ContentSettingsPattern::SetNonWildcardDomainNonPortScheme(
455 extensions::kExtensionScheme
);
457 // No support for ANDROID yet as DiagnosticsController needs wchar support.
458 // TODO(gspencer): That's not true anymore, or at least there are no w-string
459 // references anymore. Not sure if that means this can be enabled on Android or
460 // not though. As there is no easily accessible command line on Android, I'm
461 // not sure this is a big deal.
462 #if !defined(OS_ANDROID) && !defined(CHROME_MULTIPLE_DLL_CHILD)
463 // If we are in diagnostics mode this is the end of the line: after the
464 // diagnostics are run the process will invariably exit.
465 if (command_line
.HasSwitch(switches::kDiagnostics
)) {
466 diagnostics::DiagnosticsWriter::FormatType format
=
467 diagnostics::DiagnosticsWriter::HUMAN
;
468 if (command_line
.HasSwitch(switches::kDiagnosticsFormat
)) {
469 std::string format_str
=
470 command_line
.GetSwitchValueASCII(switches::kDiagnosticsFormat
);
471 if (format_str
== "machine") {
472 format
= diagnostics::DiagnosticsWriter::MACHINE
;
473 } else if (format_str
== "log") {
474 format
= diagnostics::DiagnosticsWriter::LOG
;
476 DCHECK_EQ("human", format_str
);
480 diagnostics::DiagnosticsWriter
writer(format
);
481 *exit_code
= diagnostics::DiagnosticsController::GetInstance()->Run(
482 command_line
, &writer
);
483 diagnostics::DiagnosticsController::GetInstance()->ClearResults();
488 #if defined(OS_CHROMEOS)
489 // Initialize primary user homedir (in multi-profile session) as it may be
490 // passed as a command line switch.
491 base::FilePath homedir
;
492 if (command_line
.HasSwitch(chromeos::switches::kHomedir
)) {
493 homedir
= base::FilePath(
494 command_line
.GetSwitchValueASCII(chromeos::switches::kHomedir
));
495 PathService::OverrideAndCreateIfNeeded(
496 base::DIR_HOME
, homedir
, true, false);
499 // If we are recovering from a crash on ChromeOS, then we will do some
500 // recovery using the diagnostics module, and then continue on. We fake up a
501 // command line to tell it that we want it to recover, and to preserve the
502 // original command line.
503 if (command_line
.HasSwitch(chromeos::switches::kLoginUser
) ||
504 command_line
.HasSwitch(switches::kDiagnosticsRecovery
)) {
505 // The statistics subsystem needs get initialized soon enough for the
506 // statistics to be collected. It's safe to call this more than once.
507 base::StatisticsRecorder::Initialize();
509 base::CommandLine
interim_command_line(command_line
.GetProgram());
510 const char* const kSwitchNames
[] = {switches::kUserDataDir
, };
511 interim_command_line
.CopySwitchesFrom(
512 command_line
, kSwitchNames
, arraysize(kSwitchNames
));
513 interim_command_line
.AppendSwitch(switches::kDiagnostics
);
514 interim_command_line
.AppendSwitch(switches::kDiagnosticsRecovery
);
516 diagnostics::DiagnosticsWriter::FormatType format
=
517 diagnostics::DiagnosticsWriter::LOG
;
518 if (command_line
.HasSwitch(switches::kDiagnosticsFormat
)) {
519 std::string format_str
=
520 command_line
.GetSwitchValueASCII(switches::kDiagnosticsFormat
);
521 if (format_str
== "machine") {
522 format
= diagnostics::DiagnosticsWriter::MACHINE
;
523 } else if (format_str
== "human") {
524 format
= diagnostics::DiagnosticsWriter::HUMAN
;
526 DCHECK_EQ("log", format_str
);
530 diagnostics::DiagnosticsWriter
writer(format
);
531 int diagnostics_exit_code
=
532 diagnostics::DiagnosticsController::GetInstance()->Run(command_line
,
534 if (diagnostics_exit_code
) {
535 // Diagnostics has failed somehow, so we exit.
536 *exit_code
= diagnostics_exit_code
;
540 // Now we run the actual recovery tasks.
541 int recovery_exit_code
=
542 diagnostics::DiagnosticsController::GetInstance()->RunRecovery(
543 command_line
, &writer
);
545 if (recovery_exit_code
) {
546 // Recovery has failed somehow, so we exit.
547 *exit_code
= recovery_exit_code
;
550 } else { // Not running diagnostics or recovery.
551 diagnostics::DiagnosticsController::GetInstance()->RecordRegularStartup();
555 content::SetContentClient(&chrome_content_client_
);
560 #if defined(OS_MACOSX)
561 void ChromeMainDelegate::InitMacCrashReporter(
562 const base::CommandLine
& command_line
,
563 const std::string
& process_type
) {
564 // TODO(mark): Right now, InitializeCrashpad() needs to be called after
565 // CommandLine::Init() and chrome::RegisterPathProvider(). Ideally, Crashpad
566 // initialization could occur sooner, preferably even before the framework
567 // dylib is even loaded, to catch potential early crashes.
568 crash_reporter::InitializeCrashpad(process_type
);
570 const bool browser_process
= process_type
.empty();
571 if (!browser_process
) {
572 std::string metrics_client_id
=
573 command_line
.GetSwitchValueASCII(switches::kMetricsClientID
);
574 crash_keys::SetMetricsClientIdFromGUID(metrics_client_id
);
577 // Mac Chrome is packaged with a main app bundle and a helper app bundle.
578 // The main app bundle should only be used for the browser process, so it
579 // should never see a --type switch (switches::kProcessType). Likewise,
580 // the helper should always have a --type switch.
582 // This check is done this late so there is already a call to
583 // base::mac::IsBackgroundOnlyProcess(), so there is no change in
584 // startup/initialization order.
586 // The helper's Info.plist marks it as a background only app.
587 if (base::mac::IsBackgroundOnlyProcess()) {
588 CHECK(command_line
.HasSwitch(switches::kProcessType
) &&
589 !process_type
.empty())
590 << "Helper application requires --type.";
592 // In addition, some helper flavors only work with certain process types.
593 base::FilePath executable
;
594 if (PathService::Get(base::FILE_EXE
, &executable
) &&
595 executable
.value().size() >= 3) {
596 std::string last_three
=
597 executable
.value().substr(executable
.value().size() - 3);
599 if (last_three
== " EH") {
600 CHECK(process_type
== switches::kPluginProcess
||
601 process_type
== switches::kUtilityProcess
)
602 << "Executable-heap process requires --type="
603 << switches::kPluginProcess
<< " or "
604 << switches::kUtilityProcess
<< ", saw " << process_type
;
605 } else if (last_three
== " NP") {
606 #if !defined(DISABLE_NACL)
607 CHECK_EQ(switches::kNaClLoaderProcess
, process_type
)
608 << "Non-PIE process requires --type="
609 << switches::kNaClLoaderProcess
<< ", saw " << process_type
;
612 #if defined(DISABLE_NACL)
613 CHECK(process_type
!= switches::kPluginProcess
)
614 << "Non-executable-heap PIE process is intolerant of --type="
615 << switches::kPluginProcess
;
617 CHECK(process_type
!= switches::kPluginProcess
&&
618 process_type
!= switches::kNaClLoaderProcess
)
619 << "Non-executable-heap PIE process is intolerant of --type="
620 << switches::kPluginProcess
<< " and "
621 << switches::kNaClLoaderProcess
<< ", saw " << process_type
;
626 CHECK(!command_line
.HasSwitch(switches::kProcessType
) &&
627 process_type
.empty())
628 << "Main application forbids --type, saw " << process_type
;
631 #endif // defined(OS_MACOSX)
633 void ChromeMainDelegate::PreSandboxStartup() {
634 const base::CommandLine
& command_line
=
635 *base::CommandLine::ForCurrentProcess();
636 std::string process_type
=
637 command_line
.GetSwitchValueASCII(switches::kProcessType
);
639 #if defined(OS_POSIX)
640 crash_reporter::SetCrashReporterClient(g_chrome_crash_client
.Pointer());
643 #if defined(OS_MACOSX)
644 // On the Mac, the child executable lives at a predefined location within
645 // the app bundle's versioned directory.
646 PathService::Override(content::CHILD_PROCESS_EXE
,
647 chrome::GetVersionedDirectory().
648 Append(chrome::kHelperProcessExecutablePath
));
650 InitMacCrashReporter(command_line
, process_type
);
654 child_process_logging::Init();
656 #if defined(ARCH_CPU_ARM_FAMILY) && (defined(OS_ANDROID) || defined(OS_LINUX))
657 // Create an instance of the CPU class to parse /proc/cpuinfo and cache
662 // Initialize the user data dir for any process type that needs it.
663 if (chrome::ProcessNeedsProfileDir(process_type
))
664 InitializeUserDataDir();
666 // Register component_updater PathProvider after DIR_USER_DATA overidden by
667 // command line flags. Maybe move the chrome PathProvider down here also?
668 component_updater::RegisterPathProvider(chrome::DIR_USER_DATA
);
670 // Enable Message Loop related state asap.
671 if (command_line
.HasSwitch(switches::kMessageLoopHistogrammer
))
672 base::MessageLoop::EnableHistogrammer(true);
674 #if !defined(OS_ANDROID)
675 // Android does InitLogging when library is loaded. Skip here.
676 logging::OldFileDeletionState file_state
=
677 logging::APPEND_TO_OLD_LOG_FILE
;
678 if (process_type
.empty()) {
679 file_state
= logging::DELETE_OLD_LOG_FILE
;
681 logging::InitChromeLogging(command_line
, file_state
);
685 // TODO(zturner): Throbber icons are still stored in chrome.dll, this can be
686 // killed once those are merged into resources.pak. See
687 // GlassBrowserFrameView::InitThrobberIcons() and http://crbug.com/368327.
688 ui::SetResourcesDataDLL(_AtlBaseModule
.GetResourceInstance());
691 if (SubprocessNeedsResourceBundle(process_type
)) {
692 // Initialize ResourceBundle which handles files loaded from external
693 // sources. The language should have been passed in to us from the
694 // browser process as a command line flag.
695 #if defined(DISABLE_NACL)
696 DCHECK(command_line
.HasSwitch(switches::kLang
) ||
697 process_type
== switches::kZygoteProcess
||
698 process_type
== switches::kGpuProcess
||
699 process_type
== switches::kPpapiBrokerProcess
||
700 process_type
== switches::kPpapiPluginProcess
);
702 DCHECK(command_line
.HasSwitch(switches::kLang
) ||
703 process_type
== switches::kZygoteProcess
||
704 process_type
== switches::kGpuProcess
||
705 process_type
== switches::kNaClLoaderProcess
||
706 process_type
== switches::kPpapiBrokerProcess
||
707 process_type
== switches::kPpapiPluginProcess
);
710 // TODO(markusheintz): The command line flag --lang is actually processed
711 // by the CommandLinePrefStore, and made available through the PrefService
712 // via the preference prefs::kApplicationLocale. The browser process uses
713 // the --lang flag to pass the value of the PrefService in here. Maybe
714 // this value could be passed in a different way.
715 const std::string locale
=
716 command_line
.GetSwitchValueASCII(switches::kLang
);
717 #if defined(OS_ANDROID)
718 // The renderer sandbox prevents us from accessing our .pak files directly.
719 // Therefore file descriptors to the .pak files that we need are passed in
720 // at process creation time.
721 int locale_pak_fd
= base::GlobalDescriptors::GetInstance()->MaybeGet(
722 kAndroidLocalePakDescriptor
);
723 CHECK(locale_pak_fd
!= -1);
724 ResourceBundle::InitSharedInstanceWithPakFileRegion(
725 base::File(locale_pak_fd
), base::MemoryMappedFile::Region::kWholeFile
);
727 int extra_pak_keys
[] = {
728 kAndroidChrome100PercentPakDescriptor
,
729 kAndroidUIResourcesPakDescriptor
,
731 for (size_t i
= 0; i
< arraysize(extra_pak_keys
); ++i
) {
733 base::GlobalDescriptors::GetInstance()->MaybeGet(extra_pak_keys
[i
]);
735 ResourceBundle::GetSharedInstance().AddDataPackFromFile(
736 base::File(pak_fd
), ui::SCALE_FACTOR_100P
);
739 base::i18n::SetICUDefaultLocale(locale
);
740 const std::string loaded_locale
= locale
;
742 const std::string loaded_locale
=
743 ui::ResourceBundle::InitSharedInstanceWithLocale(
744 locale
, NULL
, ui::ResourceBundle::LOAD_COMMON_RESOURCES
);
746 base::FilePath resources_pack_path
;
747 PathService::Get(chrome::FILE_RESOURCES_PACK
, &resources_pack_path
);
748 ResourceBundle::GetSharedInstance().AddDataPackFromPath(
749 resources_pack_path
, ui::SCALE_FACTOR_NONE
);
751 CHECK(!loaded_locale
.empty()) << "Locale could not be found for " <<
755 #if !defined(CHROME_MULTIPLE_DLL_BROWSER)
756 if (process_type
== switches::kUtilityProcess
||
757 process_type
== switches::kZygoteProcess
) {
758 ChromeContentUtilityClient::PreSandboxStartup();
761 chrome::InitializePDF();
764 #if defined(OS_POSIX) && !defined(OS_MACOSX)
765 // Zygote needs to call InitCrashReporter() in RunZygote().
766 if (process_type
!= switches::kZygoteProcess
) {
767 #if defined(OS_ANDROID)
768 if (process_type
.empty())
769 breakpad::InitCrashReporter(process_type
);
771 breakpad::InitNonBrowserCrashReporterForAndroid(process_type
);
772 #else // !defined(OS_ANDROID)
773 breakpad::InitCrashReporter(process_type
);
774 #endif // defined(OS_ANDROID)
776 #endif // defined(OS_POSIX) && !defined(OS_MACOSX)
778 // After all the platform Breakpads have been initialized, store the command
779 // line for crash reporting.
780 crash_keys::SetSwitchesFromCommandLine(&command_line
);
783 void ChromeMainDelegate::SandboxInitialized(const std::string
& process_type
) {
784 // Note: If you are adding a new process type below, be sure to adjust the
785 // AdjustLinuxOOMScore function too.
786 #if defined(OS_LINUX)
787 AdjustLinuxOOMScore(process_type
);
790 SuppressWindowsErrorDialogs();
793 #if defined(CHROME_MULTIPLE_DLL_CHILD) || !defined(CHROME_MULTIPLE_DLL_BROWSER)
794 #if defined(ENABLE_REMOTING)
795 ChromeContentClient::SetRemotingEntryFunctions(
796 remoting::PPP_GetInterface
,
797 remoting::PPP_InitializeModule
,
798 remoting::PPP_ShutdownModule
);
800 #if !defined(DISABLE_NACL)
801 ChromeContentClient::SetNaClEntryFunctions(
802 nacl_plugin::PPP_GetInterface
,
803 nacl_plugin::PPP_InitializeModule
,
804 nacl_plugin::PPP_ShutdownModule
);
806 #if defined(ENABLE_PLUGINS)
807 ChromeContentClient::SetPDFEntryFunctions(
808 chrome_pdf::PPP_GetInterface
,
809 chrome_pdf::PPP_InitializeModule
,
810 chrome_pdf::PPP_ShutdownModule
);
815 int ChromeMainDelegate::RunProcess(
816 const std::string
& process_type
,
817 const content::MainFunctionParams
& main_function_params
) {
818 // ANDROID doesn't support "service", so no ServiceProcessMain, and arraysize
819 // doesn't support empty array. So we comment out the block for Android.
820 #if !defined(OS_ANDROID)
821 static const MainFunction kMainFunctions
[] = {
822 #if defined(ENABLE_PRINT_PREVIEW) && !defined(CHROME_MULTIPLE_DLL_CHILD)
823 { switches::kServiceProcess
, ServiceProcessMain
},
826 #if defined(OS_MACOSX)
827 { switches::kRelauncherProcess
,
828 mac_relauncher::internal::RelauncherMain
},
831 // This entry is not needed on Linux, where the NaCl loader
832 // process is launched via nacl_helper instead.
833 #if !defined(DISABLE_NACL) && !defined(CHROME_MULTIPLE_DLL_BROWSER) && \
835 { switches::kNaClLoaderProcess
, NaClMain
},
837 { "<invalid>", NULL
}, // To avoid constant array of size 0
838 // when DISABLE_NACL and CHROME_MULTIPLE_DLL_CHILD
839 #endif // DISABLE_NACL
842 for (size_t i
= 0; i
< arraysize(kMainFunctions
); ++i
) {
843 if (process_type
== kMainFunctions
[i
].name
)
844 return kMainFunctions
[i
].function(main_function_params
);
851 void ChromeMainDelegate::ProcessExiting(const std::string
& process_type
) {
852 if (SubprocessNeedsResourceBundle(process_type
))
853 ResourceBundle::CleanupSharedInstance();
854 #if !defined(OS_ANDROID)
855 logging::CleanupChromeLogging();
857 // Android doesn't use InitChromeLogging, so we close the log file manually.
858 logging::CloseLogFile();
859 #endif // !defined(OS_ANDROID)
862 RemoveCloseHandleHooks();
866 #if defined(OS_MACOSX)
867 bool ChromeMainDelegate::ProcessRegistersWithSystemProcess(
868 const std::string
& process_type
) {
869 #if defined(DISABLE_NACL)
872 return process_type
== switches::kNaClLoaderProcess
;
876 bool ChromeMainDelegate::ShouldSendMachPort(const std::string
& process_type
) {
877 return process_type
!= switches::kRelauncherProcess
&&
878 process_type
!= switches::kServiceProcess
;
881 bool ChromeMainDelegate::DelaySandboxInitialization(
882 const std::string
& process_type
) {
883 #if !defined(DISABLE_NACL)
884 // NaClLoader does this in NaClMainPlatformDelegate::EnableSandbox().
885 // No sandbox needed for relauncher.
886 if (process_type
== switches::kNaClLoaderProcess
)
889 return process_type
== switches::kRelauncherProcess
;
891 #elif defined(OS_POSIX) && !defined(OS_ANDROID)
892 void ChromeMainDelegate::ZygoteStarting(
893 ScopedVector
<content::ZygoteForkDelegate
>* delegates
) {
894 #if !defined(DISABLE_NACL)
895 nacl::AddNaClZygoteForkDelegates(delegates
);
899 void ChromeMainDelegate::ZygoteForked() {
900 Profiling::ProcessStarted();
901 if (Profiling::BeingProfiled()) {
902 base::debug::RestartProfilingAfterFork();
903 SetUpProfilingShutdownHandler();
906 // Needs to be called after we have chrome::DIR_USER_DATA. BrowserMain sets
907 // this up for the browser process in a different manner.
908 const base::CommandLine
* command_line
=
909 base::CommandLine::ForCurrentProcess();
910 std::string process_type
=
911 command_line
->GetSwitchValueASCII(switches::kProcessType
);
912 breakpad::InitCrashReporter(process_type
);
914 // Reset the command line for the newly spawned process.
915 crash_keys::SetSwitchesFromCommandLine(command_line
);
920 content::ContentBrowserClient
*
921 ChromeMainDelegate::CreateContentBrowserClient() {
922 #if defined(CHROME_MULTIPLE_DLL_CHILD)
925 return g_chrome_content_browser_client
.Pointer();
929 content::ContentPluginClient
* ChromeMainDelegate::CreateContentPluginClient() {
930 #if defined(CHROME_MULTIPLE_DLL_BROWSER)
933 return g_chrome_content_plugin_client
.Pointer();
937 content::ContentRendererClient
*
938 ChromeMainDelegate::CreateContentRendererClient() {
939 #if defined(CHROME_MULTIPLE_DLL_BROWSER)
942 return g_chrome_content_renderer_client
.Pointer();
946 content::ContentUtilityClient
*
947 ChromeMainDelegate::CreateContentUtilityClient() {
948 #if defined(CHROME_MULTIPLE_DLL_BROWSER)
951 return g_chrome_content_utility_client
.Pointer();
955 bool ChromeMainDelegate::ShouldEnableProfilerRecording() {
956 switch (chrome::VersionInfo::GetChannel()) {
957 case chrome::VersionInfo::CHANNEL_UNKNOWN
:
958 case chrome::VersionInfo::CHANNEL_CANARY
:
960 case chrome::VersionInfo::CHANNEL_DEV
:
961 case chrome::VersionInfo::CHANNEL_BETA
:
962 case chrome::VersionInfo::CHANNEL_STABLE
:
964 // Don't enable instrumentation.