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();
350 command_line
->AppendSwitchPath(switches::kUserDataDir
, user_data_dir
);
353 const bool specified_directory_was_invalid
= !user_data_dir
.empty() &&
354 !PathService::OverrideAndCreateIfNeeded(chrome::DIR_USER_DATA
,
355 user_data_dir
, false, true);
356 // Save inaccessible or invalid paths so the user may be prompted later.
357 if (specified_directory_was_invalid
)
358 chrome::SetInvalidSpecifiedUserDataDir(user_data_dir
);
360 // Warn and fail early if the process fails to get a user data directory.
361 if (!PathService::Get(chrome::DIR_USER_DATA
, &user_data_dir
)) {
362 // If an invalid command-line or policy override was specified, the user
363 // will be given an error with that value. Otherwise, use the directory
364 // returned by PathService (or the fallback default directory) in the error.
365 if (!specified_directory_was_invalid
) {
366 // PathService::Get() returns false and yields an empty path if it fails
367 // to create DIR_USER_DATA. Retrieve the default value manually to display
368 // a more meaningful error to the user in that case.
369 if (user_data_dir
.empty())
370 chrome::GetDefaultUserDataDirectory(&user_data_dir
);
371 chrome::SetInvalidSpecifiedUserDataDir(user_data_dir
);
374 // The browser process (which is identified by an empty |process_type|) will
375 // handle the error later; other processes that need the dir crash here.
376 CHECK(process_type
.empty()) << "Unable to get the user data directory "
377 << "for process type: " << process_type
;
380 // Append the fallback user data directory to the commandline. Otherwise,
381 // child or service processes will attempt to use the invalid directory.
382 if (specified_directory_was_invalid
)
383 command_line
->AppendSwitchPath(switches::kUserDataDir
, user_data_dir
);
388 ChromeMainDelegate::ChromeMainDelegate() {
389 #if defined(OS_ANDROID)
390 // On Android the main entry point time is the time when the Java code starts.
391 // This happens before the shared library containing this code is even loaded.
392 // The Java startup code has recorded that time, but the C++ code can't fetch it
393 // from the Java side until it has initialized the JNI. See
394 // ChromeMainDelegateAndroid.
396 startup_metric_utils::RecordMainEntryPointTime();
400 ChromeMainDelegate::~ChromeMainDelegate() {
403 bool ChromeMainDelegate::BasicStartupComplete(int* exit_code
) {
404 #if defined(OS_CHROMEOS)
405 chromeos::BootTimesRecorder::Get()->SaveChromeMainStats();
408 const base::CommandLine
& command_line
=
409 *base::CommandLine::ForCurrentProcess();
411 #if defined(OS_MACOSX)
412 // Give the browser process a longer treadmill, since crashes
413 // there have more impact.
414 const bool is_browser
= !command_line
.HasSwitch(switches::kProcessType
);
415 ObjcEvilDoers::ZombieEnable(true, is_browser
? 10000 : 1000);
417 SetUpBundleOverrides();
418 chrome::common::mac::EnableCFBundleBlocker();
421 Profiling::ProcessStarted();
424 v8_breakpad_support::SetUp();
427 #if defined(OS_POSIX)
428 if (HandleVersionSwitches(command_line
)) {
430 return true; // Got a --version switch; exit with a success error code.
432 #if !defined(OS_MACOSX) && !defined(OS_CHROMEOS)
433 // This will directly exit if the user asked for help.
434 HandleHelpSwitches(command_line
);
439 // Must do this before any other usage of command line!
440 if (HasDeprecatedArguments(command_line
.GetCommandLineString())) {
445 InstallCloseHandleHooks();
448 chrome::RegisterPathProvider();
449 #if defined(OS_CHROMEOS)
450 chromeos::RegisterPathProvider();
452 #if !defined(DISABLE_NACL) && defined(OS_LINUX)
453 nacl::RegisterPathProvider();
456 ContentSettingsPattern::SetNonWildcardDomainNonPortScheme(
457 extensions::kExtensionScheme
);
459 // No support for ANDROID yet as DiagnosticsController needs wchar support.
460 // TODO(gspencer): That's not true anymore, or at least there are no w-string
461 // references anymore. Not sure if that means this can be enabled on Android or
462 // not though. As there is no easily accessible command line on Android, I'm
463 // not sure this is a big deal.
464 #if !defined(OS_ANDROID) && !defined(CHROME_MULTIPLE_DLL_CHILD)
465 // If we are in diagnostics mode this is the end of the line: after the
466 // diagnostics are run the process will invariably exit.
467 if (command_line
.HasSwitch(switches::kDiagnostics
)) {
468 diagnostics::DiagnosticsWriter::FormatType format
=
469 diagnostics::DiagnosticsWriter::HUMAN
;
470 if (command_line
.HasSwitch(switches::kDiagnosticsFormat
)) {
471 std::string format_str
=
472 command_line
.GetSwitchValueASCII(switches::kDiagnosticsFormat
);
473 if (format_str
== "machine") {
474 format
= diagnostics::DiagnosticsWriter::MACHINE
;
475 } else if (format_str
== "log") {
476 format
= diagnostics::DiagnosticsWriter::LOG
;
478 DCHECK_EQ("human", format_str
);
482 diagnostics::DiagnosticsWriter
writer(format
);
483 *exit_code
= diagnostics::DiagnosticsController::GetInstance()->Run(
484 command_line
, &writer
);
485 diagnostics::DiagnosticsController::GetInstance()->ClearResults();
490 #if defined(OS_CHROMEOS)
491 // Initialize primary user homedir (in multi-profile session) as it may be
492 // passed as a command line switch.
493 base::FilePath homedir
;
494 if (command_line
.HasSwitch(chromeos::switches::kHomedir
)) {
495 homedir
= base::FilePath(
496 command_line
.GetSwitchValueASCII(chromeos::switches::kHomedir
));
497 PathService::OverrideAndCreateIfNeeded(
498 base::DIR_HOME
, homedir
, true, false);
501 // If we are recovering from a crash on ChromeOS, then we will do some
502 // recovery using the diagnostics module, and then continue on. We fake up a
503 // command line to tell it that we want it to recover, and to preserve the
504 // original command line.
505 if (command_line
.HasSwitch(chromeos::switches::kLoginUser
) ||
506 command_line
.HasSwitch(switches::kDiagnosticsRecovery
)) {
507 // The statistics subsystem needs get initialized soon enough for the
508 // statistics to be collected. It's safe to call this more than once.
509 base::StatisticsRecorder::Initialize();
511 base::CommandLine
interim_command_line(command_line
.GetProgram());
512 const char* const kSwitchNames
[] = {switches::kUserDataDir
, };
513 interim_command_line
.CopySwitchesFrom(
514 command_line
, kSwitchNames
, arraysize(kSwitchNames
));
515 interim_command_line
.AppendSwitch(switches::kDiagnostics
);
516 interim_command_line
.AppendSwitch(switches::kDiagnosticsRecovery
);
518 diagnostics::DiagnosticsWriter::FormatType format
=
519 diagnostics::DiagnosticsWriter::LOG
;
520 if (command_line
.HasSwitch(switches::kDiagnosticsFormat
)) {
521 std::string format_str
=
522 command_line
.GetSwitchValueASCII(switches::kDiagnosticsFormat
);
523 if (format_str
== "machine") {
524 format
= diagnostics::DiagnosticsWriter::MACHINE
;
525 } else if (format_str
== "human") {
526 format
= diagnostics::DiagnosticsWriter::HUMAN
;
528 DCHECK_EQ("log", format_str
);
532 diagnostics::DiagnosticsWriter
writer(format
);
533 int diagnostics_exit_code
=
534 diagnostics::DiagnosticsController::GetInstance()->Run(command_line
,
536 if (diagnostics_exit_code
) {
537 // Diagnostics has failed somehow, so we exit.
538 *exit_code
= diagnostics_exit_code
;
542 // Now we run the actual recovery tasks.
543 int recovery_exit_code
=
544 diagnostics::DiagnosticsController::GetInstance()->RunRecovery(
545 command_line
, &writer
);
547 if (recovery_exit_code
) {
548 // Recovery has failed somehow, so we exit.
549 *exit_code
= recovery_exit_code
;
552 } else { // Not running diagnostics or recovery.
553 diagnostics::DiagnosticsController::GetInstance()->RecordRegularStartup();
557 content::SetContentClient(&chrome_content_client_
);
562 #if defined(OS_MACOSX)
563 void ChromeMainDelegate::InitMacCrashReporter(
564 const base::CommandLine
& command_line
,
565 const std::string
& process_type
) {
566 // TODO(mark): Right now, InitializeCrashpad() needs to be called after
567 // CommandLine::Init() and chrome::RegisterPathProvider(). Ideally, Crashpad
568 // initialization could occur sooner, preferably even before the framework
569 // dylib is even loaded, to catch potential early crashes.
570 crash_reporter::InitializeCrashpad(process_type
);
572 const bool browser_process
= process_type
.empty();
573 if (!browser_process
) {
574 std::string metrics_client_id
=
575 command_line
.GetSwitchValueASCII(switches::kMetricsClientID
);
576 crash_keys::SetMetricsClientIdFromGUID(metrics_client_id
);
579 // Mac Chrome is packaged with a main app bundle and a helper app bundle.
580 // The main app bundle should only be used for the browser process, so it
581 // should never see a --type switch (switches::kProcessType). Likewise,
582 // the helper should always have a --type switch.
584 // This check is done this late so there is already a call to
585 // base::mac::IsBackgroundOnlyProcess(), so there is no change in
586 // startup/initialization order.
588 // The helper's Info.plist marks it as a background only app.
589 if (base::mac::IsBackgroundOnlyProcess()) {
590 CHECK(command_line
.HasSwitch(switches::kProcessType
) &&
591 !process_type
.empty())
592 << "Helper application requires --type.";
594 // In addition, some helper flavors only work with certain process types.
595 base::FilePath executable
;
596 if (PathService::Get(base::FILE_EXE
, &executable
) &&
597 executable
.value().size() >= 3) {
598 std::string last_three
=
599 executable
.value().substr(executable
.value().size() - 3);
601 if (last_three
== " EH") {
602 CHECK(process_type
== switches::kPluginProcess
||
603 process_type
== switches::kUtilityProcess
)
604 << "Executable-heap process requires --type="
605 << switches::kPluginProcess
<< " or "
606 << switches::kUtilityProcess
<< ", saw " << process_type
;
607 } else if (last_three
== " NP") {
608 #if !defined(DISABLE_NACL)
609 CHECK_EQ(switches::kNaClLoaderProcess
, process_type
)
610 << "Non-PIE process requires --type="
611 << switches::kNaClLoaderProcess
<< ", saw " << process_type
;
614 #if defined(DISABLE_NACL)
615 CHECK(process_type
!= switches::kPluginProcess
)
616 << "Non-executable-heap PIE process is intolerant of --type="
617 << switches::kPluginProcess
;
619 CHECK(process_type
!= switches::kPluginProcess
&&
620 process_type
!= switches::kNaClLoaderProcess
)
621 << "Non-executable-heap PIE process is intolerant of --type="
622 << switches::kPluginProcess
<< " and "
623 << switches::kNaClLoaderProcess
<< ", saw " << process_type
;
628 CHECK(!command_line
.HasSwitch(switches::kProcessType
) &&
629 process_type
.empty())
630 << "Main application forbids --type, saw " << process_type
;
633 #endif // defined(OS_MACOSX)
635 void ChromeMainDelegate::PreSandboxStartup() {
636 const base::CommandLine
& command_line
=
637 *base::CommandLine::ForCurrentProcess();
638 std::string process_type
=
639 command_line
.GetSwitchValueASCII(switches::kProcessType
);
641 #if defined(OS_POSIX)
642 crash_reporter::SetCrashReporterClient(g_chrome_crash_client
.Pointer());
645 #if defined(OS_MACOSX)
646 // On the Mac, the child executable lives at a predefined location within
647 // the app bundle's versioned directory.
648 PathService::Override(content::CHILD_PROCESS_EXE
,
649 chrome::GetVersionedDirectory().
650 Append(chrome::kHelperProcessExecutablePath
));
652 InitMacCrashReporter(command_line
, process_type
);
656 child_process_logging::Init();
658 #if defined(ARCH_CPU_ARM_FAMILY) && (defined(OS_ANDROID) || defined(OS_LINUX))
659 // Create an instance of the CPU class to parse /proc/cpuinfo and cache
664 // Initialize the user data dir for any process type that needs it.
665 if (chrome::ProcessNeedsProfileDir(process_type
))
666 InitializeUserDataDir();
668 // Register component_updater PathProvider after DIR_USER_DATA overidden by
669 // command line flags. Maybe move the chrome PathProvider down here also?
670 component_updater::RegisterPathProvider(chrome::DIR_USER_DATA
);
672 // Enable Message Loop related state asap.
673 if (command_line
.HasSwitch(switches::kMessageLoopHistogrammer
))
674 base::MessageLoop::EnableHistogrammer(true);
676 #if !defined(OS_ANDROID)
677 // Android does InitLogging when library is loaded. Skip here.
678 logging::OldFileDeletionState file_state
=
679 logging::APPEND_TO_OLD_LOG_FILE
;
680 if (process_type
.empty()) {
681 file_state
= logging::DELETE_OLD_LOG_FILE
;
683 logging::InitChromeLogging(command_line
, file_state
);
687 // TODO(zturner): Throbber icons are still stored in chrome.dll, this can be
688 // killed once those are merged into resources.pak. See
689 // GlassBrowserFrameView::InitThrobberIcons() and http://crbug.com/368327.
690 ui::SetResourcesDataDLL(_AtlBaseModule
.GetResourceInstance());
693 if (SubprocessNeedsResourceBundle(process_type
)) {
694 // Initialize ResourceBundle which handles files loaded from external
695 // sources. The language should have been passed in to us from the
696 // browser process as a command line flag.
697 #if defined(DISABLE_NACL)
698 DCHECK(command_line
.HasSwitch(switches::kLang
) ||
699 process_type
== switches::kZygoteProcess
||
700 process_type
== switches::kGpuProcess
||
701 process_type
== switches::kPpapiBrokerProcess
||
702 process_type
== switches::kPpapiPluginProcess
);
704 DCHECK(command_line
.HasSwitch(switches::kLang
) ||
705 process_type
== switches::kZygoteProcess
||
706 process_type
== switches::kGpuProcess
||
707 process_type
== switches::kNaClLoaderProcess
||
708 process_type
== switches::kPpapiBrokerProcess
||
709 process_type
== switches::kPpapiPluginProcess
);
712 // TODO(markusheintz): The command line flag --lang is actually processed
713 // by the CommandLinePrefStore, and made available through the PrefService
714 // via the preference prefs::kApplicationLocale. The browser process uses
715 // the --lang flag to pass the value of the PrefService in here. Maybe
716 // this value could be passed in a different way.
717 const std::string locale
=
718 command_line
.GetSwitchValueASCII(switches::kLang
);
719 #if defined(OS_ANDROID)
720 // The renderer sandbox prevents us from accessing our .pak files directly.
721 // Therefore file descriptors to the .pak files that we need are passed in
722 // at process creation time.
723 int locale_pak_fd
= base::GlobalDescriptors::GetInstance()->MaybeGet(
724 kAndroidLocalePakDescriptor
);
725 CHECK(locale_pak_fd
!= -1);
726 ResourceBundle::InitSharedInstanceWithPakFileRegion(
727 base::File(locale_pak_fd
), base::MemoryMappedFile::Region::kWholeFile
);
729 int extra_pak_keys
[] = {
730 kAndroidChrome100PercentPakDescriptor
,
731 kAndroidUIResourcesPakDescriptor
,
733 for (size_t i
= 0; i
< arraysize(extra_pak_keys
); ++i
) {
735 base::GlobalDescriptors::GetInstance()->MaybeGet(extra_pak_keys
[i
]);
737 ResourceBundle::GetSharedInstance().AddDataPackFromFile(
738 base::File(pak_fd
), ui::SCALE_FACTOR_100P
);
741 base::i18n::SetICUDefaultLocale(locale
);
742 const std::string loaded_locale
= locale
;
744 const std::string loaded_locale
=
745 ui::ResourceBundle::InitSharedInstanceWithLocale(
746 locale
, NULL
, ui::ResourceBundle::LOAD_COMMON_RESOURCES
);
748 base::FilePath resources_pack_path
;
749 PathService::Get(chrome::FILE_RESOURCES_PACK
, &resources_pack_path
);
750 ResourceBundle::GetSharedInstance().AddDataPackFromPath(
751 resources_pack_path
, ui::SCALE_FACTOR_NONE
);
753 CHECK(!loaded_locale
.empty()) << "Locale could not be found for " <<
757 #if !defined(CHROME_MULTIPLE_DLL_BROWSER)
758 if (process_type
== switches::kUtilityProcess
||
759 process_type
== switches::kZygoteProcess
) {
760 ChromeContentUtilityClient::PreSandboxStartup();
763 chrome::InitializePDF();
766 #if defined(OS_POSIX) && !defined(OS_MACOSX)
767 // Zygote needs to call InitCrashReporter() in RunZygote().
768 if (process_type
!= switches::kZygoteProcess
) {
769 #if defined(OS_ANDROID)
770 if (process_type
.empty())
771 breakpad::InitCrashReporter(process_type
);
773 breakpad::InitNonBrowserCrashReporterForAndroid(process_type
);
774 #else // !defined(OS_ANDROID)
775 breakpad::InitCrashReporter(process_type
);
776 #endif // defined(OS_ANDROID)
778 #endif // defined(OS_POSIX) && !defined(OS_MACOSX)
780 // After all the platform Breakpads have been initialized, store the command
781 // line for crash reporting.
782 crash_keys::SetSwitchesFromCommandLine(&command_line
);
785 void ChromeMainDelegate::SandboxInitialized(const std::string
& process_type
) {
786 // Note: If you are adding a new process type below, be sure to adjust the
787 // AdjustLinuxOOMScore function too.
788 #if defined(OS_LINUX)
789 AdjustLinuxOOMScore(process_type
);
792 SuppressWindowsErrorDialogs();
795 #if defined(CHROME_MULTIPLE_DLL_CHILD) || !defined(CHROME_MULTIPLE_DLL_BROWSER)
796 #if defined(ENABLE_REMOTING)
797 ChromeContentClient::SetRemotingEntryFunctions(
798 remoting::PPP_GetInterface
,
799 remoting::PPP_InitializeModule
,
800 remoting::PPP_ShutdownModule
);
802 #if !defined(DISABLE_NACL)
803 ChromeContentClient::SetNaClEntryFunctions(
804 nacl_plugin::PPP_GetInterface
,
805 nacl_plugin::PPP_InitializeModule
,
806 nacl_plugin::PPP_ShutdownModule
);
808 #if defined(ENABLE_PLUGINS)
809 ChromeContentClient::SetPDFEntryFunctions(
810 chrome_pdf::PPP_GetInterface
,
811 chrome_pdf::PPP_InitializeModule
,
812 chrome_pdf::PPP_ShutdownModule
);
817 int ChromeMainDelegate::RunProcess(
818 const std::string
& process_type
,
819 const content::MainFunctionParams
& main_function_params
) {
820 // ANDROID doesn't support "service", so no ServiceProcessMain, and arraysize
821 // doesn't support empty array. So we comment out the block for Android.
822 #if !defined(OS_ANDROID)
823 static const MainFunction kMainFunctions
[] = {
824 #if defined(ENABLE_PRINT_PREVIEW) && !defined(CHROME_MULTIPLE_DLL_CHILD)
825 { switches::kServiceProcess
, ServiceProcessMain
},
828 #if defined(OS_MACOSX)
829 { switches::kRelauncherProcess
,
830 mac_relauncher::internal::RelauncherMain
},
833 // This entry is not needed on Linux, where the NaCl loader
834 // process is launched via nacl_helper instead.
835 #if !defined(DISABLE_NACL) && !defined(CHROME_MULTIPLE_DLL_BROWSER) && \
837 { switches::kNaClLoaderProcess
, NaClMain
},
839 { "<invalid>", NULL
}, // To avoid constant array of size 0
840 // when DISABLE_NACL and CHROME_MULTIPLE_DLL_CHILD
841 #endif // DISABLE_NACL
844 for (size_t i
= 0; i
< arraysize(kMainFunctions
); ++i
) {
845 if (process_type
== kMainFunctions
[i
].name
)
846 return kMainFunctions
[i
].function(main_function_params
);
853 void ChromeMainDelegate::ProcessExiting(const std::string
& process_type
) {
854 if (SubprocessNeedsResourceBundle(process_type
))
855 ResourceBundle::CleanupSharedInstance();
856 #if !defined(OS_ANDROID)
857 logging::CleanupChromeLogging();
859 // Android doesn't use InitChromeLogging, so we close the log file manually.
860 logging::CloseLogFile();
861 #endif // !defined(OS_ANDROID)
864 RemoveCloseHandleHooks();
868 #if defined(OS_MACOSX)
869 bool ChromeMainDelegate::ProcessRegistersWithSystemProcess(
870 const std::string
& process_type
) {
871 #if defined(DISABLE_NACL)
874 return process_type
== switches::kNaClLoaderProcess
;
878 bool ChromeMainDelegate::ShouldSendMachPort(const std::string
& process_type
) {
879 return process_type
!= switches::kRelauncherProcess
&&
880 process_type
!= switches::kServiceProcess
;
883 bool ChromeMainDelegate::DelaySandboxInitialization(
884 const std::string
& process_type
) {
885 #if !defined(DISABLE_NACL)
886 // NaClLoader does this in NaClMainPlatformDelegate::EnableSandbox().
887 // No sandbox needed for relauncher.
888 if (process_type
== switches::kNaClLoaderProcess
)
891 return process_type
== switches::kRelauncherProcess
;
893 #elif defined(OS_POSIX) && !defined(OS_ANDROID)
894 void ChromeMainDelegate::ZygoteStarting(
895 ScopedVector
<content::ZygoteForkDelegate
>* delegates
) {
896 #if !defined(DISABLE_NACL)
897 nacl::AddNaClZygoteForkDelegates(delegates
);
901 void ChromeMainDelegate::ZygoteForked() {
902 Profiling::ProcessStarted();
903 if (Profiling::BeingProfiled()) {
904 base::debug::RestartProfilingAfterFork();
905 SetUpProfilingShutdownHandler();
908 // Needs to be called after we have chrome::DIR_USER_DATA. BrowserMain sets
909 // this up for the browser process in a different manner.
910 const base::CommandLine
* command_line
=
911 base::CommandLine::ForCurrentProcess();
912 std::string process_type
=
913 command_line
->GetSwitchValueASCII(switches::kProcessType
);
914 breakpad::InitCrashReporter(process_type
);
916 // Reset the command line for the newly spawned process.
917 crash_keys::SetSwitchesFromCommandLine(command_line
);
922 content::ContentBrowserClient
*
923 ChromeMainDelegate::CreateContentBrowserClient() {
924 #if defined(CHROME_MULTIPLE_DLL_CHILD)
927 return g_chrome_content_browser_client
.Pointer();
931 content::ContentPluginClient
* ChromeMainDelegate::CreateContentPluginClient() {
932 #if defined(CHROME_MULTIPLE_DLL_BROWSER)
935 return g_chrome_content_plugin_client
.Pointer();
939 content::ContentRendererClient
*
940 ChromeMainDelegate::CreateContentRendererClient() {
941 #if defined(CHROME_MULTIPLE_DLL_BROWSER)
944 return g_chrome_content_renderer_client
.Pointer();
948 content::ContentUtilityClient
*
949 ChromeMainDelegate::CreateContentUtilityClient() {
950 #if defined(CHROME_MULTIPLE_DLL_BROWSER)
953 return g_chrome_content_utility_client
.Pointer();
957 bool ChromeMainDelegate::ShouldEnableProfilerRecording() {
958 switch (chrome::VersionInfo::GetChannel()) {
959 case chrome::VersionInfo::CHANNEL_UNKNOWN
:
960 case chrome::VersionInfo::CHANNEL_CANARY
:
962 case chrome::VersionInfo::CHANNEL_DEV
:
963 case chrome::VersionInfo::CHANNEL_BETA
:
964 case chrome::VersionInfo::CHANNEL_STABLE
:
966 // Don't enable instrumentation.