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 "base/trace_event/trace_event_impl.h"
20 #include "build/build_config.h"
21 #include "chrome/browser/chrome_content_browser_client.h"
22 #include "chrome/browser/defaults.h"
23 #include "chrome/common/chrome_constants.h"
24 #include "chrome/common/chrome_content_client.h"
25 #include "chrome/common/chrome_paths.h"
26 #include "chrome/common/chrome_paths_internal.h"
27 #include "chrome/common/chrome_result_codes.h"
28 #include "chrome/common/chrome_switches.h"
29 #include "chrome/common/chrome_version_info.h"
30 #include "chrome/common/crash_keys.h"
31 #include "chrome/common/logging_chrome.h"
32 #include "chrome/common/profiling.h"
33 #include "chrome/common/switch_utils.h"
34 #include "chrome/common/trace_event_args_whitelist.h"
35 #include "chrome/common/url_constants.h"
36 #include "chrome/plugin/chrome_content_plugin_client.h"
37 #include "chrome/renderer/chrome_content_renderer_client.h"
38 #include "chrome/utility/chrome_content_utility_client.h"
39 #include "components/component_updater/component_updater_paths.h"
40 #include "components/content_settings/core/common/content_settings_pattern.h"
41 #include "components/startup_metric_utils/startup_metric_utils.h"
42 #include "content/public/common/content_client.h"
43 #include "content/public/common/content_paths.h"
44 #include "extensions/common/constants.h"
45 #include "ui/base/ui_base_switches.h"
51 #include "chrome/app/close_handle_hook_win.h"
52 #include "chrome/common/child_process_logging.h"
53 #include "chrome/common/v8_breakpad_support_win.h"
54 #include "sandbox/win/src/sandbox.h"
55 #include "ui/base/resource/resource_bundle_win.h"
58 #if defined(OS_MACOSX)
59 #include "base/mac/foundation_util.h"
60 #include "chrome/app/chrome_main_mac.h"
61 #include "chrome/browser/mac/relauncher.h"
62 #include "chrome/common/mac/cfbundle_blocker.h"
63 #include "chrome/common/mac/objc_zombie.h"
64 #include "components/crash/app/crashpad_mac.h"
65 #include "ui/base/l10n/l10n_util_mac.h"
71 #include "chrome/app/chrome_crash_reporter_client.h"
72 #include "components/crash/app/crash_reporter_client.h"
75 #if !defined(DISABLE_NACL) && defined(OS_LINUX)
76 #include "components/nacl/common/nacl_paths.h"
77 #include "components/nacl/zygote/nacl_fork_delegate_linux.h"
80 #if defined(OS_CHROMEOS)
81 #include "base/sys_info.h"
82 #include "chrome/browser/chromeos/boot_times_recorder.h"
83 #include "chromeos/chromeos_paths.h"
84 #include "chromeos/chromeos_switches.h"
87 #if defined(OS_ANDROID)
88 #include "chrome/browser/android/java_exception_reporter.h"
89 #include "chrome/common/descriptors_android.h"
91 // Diagnostics is only available on non-android platforms.
92 #include "chrome/browser/diagnostics/diagnostics_controller.h"
93 #include "chrome/browser/diagnostics/diagnostics_writer.h"
99 #include "ui/base/x/x11_util.h"
102 #if defined(OS_POSIX) && !defined(OS_MACOSX)
103 #include "components/crash/app/breakpad_linux.h"
106 #if defined(OS_LINUX)
107 #include "base/environment.h"
110 #if defined(OS_MACOSX) || defined(OS_WIN)
111 #include "chrome/browser/policy/policy_path_parser.h"
114 #if !defined(DISABLE_NACL)
115 #include "components/nacl/common/nacl_switches.h"
116 #include "components/nacl/renderer/plugin/ppapi_entrypoints.h"
119 #if defined(ENABLE_REMOTING)
120 #include "remoting/client/plugin/pepper_entrypoints.h"
123 #if defined(ENABLE_PLUGINS) && (defined(CHROME_MULTIPLE_DLL_CHILD) || \
124 !defined(CHROME_MULTIPLE_DLL_BROWSER))
128 #if !defined(CHROME_MULTIPLE_DLL_BROWSER)
129 #include "chrome/child/pdf_child_init.h"
131 base::LazyInstance
<ChromeContentRendererClient
>
132 g_chrome_content_renderer_client
= LAZY_INSTANCE_INITIALIZER
;
133 base::LazyInstance
<ChromeContentUtilityClient
>
134 g_chrome_content_utility_client
= LAZY_INSTANCE_INITIALIZER
;
135 base::LazyInstance
<chrome::ChromeContentPluginClient
>
136 g_chrome_content_plugin_client
= LAZY_INSTANCE_INITIALIZER
;
139 #if !defined(CHROME_MULTIPLE_DLL_CHILD)
140 base::LazyInstance
<chrome::ChromeContentBrowserClient
>
141 g_chrome_content_browser_client
= LAZY_INSTANCE_INITIALIZER
;
144 #if defined(OS_POSIX)
145 base::LazyInstance
<chrome::ChromeCrashReporterClient
>::Leaky
146 g_chrome_crash_client
= LAZY_INSTANCE_INITIALIZER
;
149 extern int NaClMain(const content::MainFunctionParams
&);
150 extern int ServiceProcessMain(const content::MainFunctionParams
&);
155 // Early versions of Chrome incorrectly registered a chromehtml: URL handler,
156 // which gives us nothing but trouble. Avoid launching chrome this way since
157 // some apps fail to properly escape arguments.
158 bool HasDeprecatedArguments(const std::wstring
& command_line
) {
159 const wchar_t kChromeHtml
[] = L
"chromehtml:";
160 std::wstring command_line_lower
= command_line
;
161 // We are only searching for ASCII characters so this is OK.
162 base::StringToLowerASCII(&command_line_lower
);
163 std::wstring::size_type pos
= command_line_lower
.find(kChromeHtml
);
164 return (pos
!= std::wstring::npos
);
167 // If we try to access a path that is not currently available, we want the call
168 // to fail rather than show an error dialog.
169 void SuppressWindowsErrorDialogs() {
170 UINT new_flags
= SEM_FAILCRITICALERRORS
|
171 SEM_NOOPENFILEERRORBOX
;
173 // Preserve existing error mode.
174 UINT existing_flags
= SetErrorMode(new_flags
);
175 SetErrorMode(existing_flags
| new_flags
);
178 bool IsSandboxedProcess() {
179 typedef bool (*IsSandboxedProcessFunc
)();
180 IsSandboxedProcessFunc is_sandboxed_process_func
=
181 reinterpret_cast<IsSandboxedProcessFunc
>(
182 GetProcAddress(GetModuleHandle(NULL
), "IsSandboxedProcess"));
183 return is_sandboxed_process_func
&& is_sandboxed_process_func();
186 #endif // defined(OS_WIN)
188 #if defined(OS_LINUX)
189 static void AdjustLinuxOOMScore(const std::string
& process_type
) {
190 // Browsers and zygotes should still be killable, but killed last.
191 const int kZygoteScore
= 0;
192 // The minimum amount to bump a score by. This is large enough that
193 // even if it's translated into the old values, it will still go up
195 const int kScoreBump
= 100;
196 // This is the lowest score that renderers and extensions start with
197 // in the OomPriorityManager.
198 const int kRendererScore
= chrome::kLowestRendererOomScore
;
199 // For "miscellaneous" things, we want them after renderers,
200 // but before plugins.
201 const int kMiscScore
= kRendererScore
- kScoreBump
;
202 // We want plugins to die after the renderers.
203 const int kPluginScore
= kMiscScore
- kScoreBump
;
206 DCHECK(kMiscScore
> 0);
207 DCHECK(kPluginScore
> 0);
209 if (process_type
== switches::kPluginProcess
||
210 process_type
== switches::kPpapiPluginProcess
) {
211 score
= kPluginScore
;
212 } else if (process_type
== switches::kPpapiBrokerProcess
) {
213 // The broker should be killed before the PPAPI plugin.
214 score
= kPluginScore
+ kScoreBump
;
215 } else if (process_type
== switches::kUtilityProcess
||
216 process_type
== switches::kGpuProcess
||
217 process_type
== switches::kServiceProcess
) {
220 } else if (process_type
== switches::kNaClLoaderProcess
||
221 process_type
== switches::kNaClLoaderNonSfiProcess
) {
222 score
= kPluginScore
;
224 } else if (process_type
== switches::kZygoteProcess
||
225 process_type
.empty()) {
226 // For zygotes and unlabeled process types, we want to still make
227 // them killable by the OOM killer.
228 score
= kZygoteScore
;
229 } else if (process_type
== switches::kRendererProcess
) {
230 LOG(WARNING
) << "process type 'renderer' "
231 << "should be created through the zygote.";
232 // When debugging, this process type can end up being run directly, but
233 // this isn't the typical path for assigning the OOM score for it. Still,
234 // we want to assign a score that is somewhat representative for debugging.
235 score
= kRendererScore
;
237 NOTREACHED() << "Unknown process type";
240 base::AdjustOOMScore(base::GetCurrentProcId(), score
);
242 #endif // defined(OS_LINUX)
244 // Returns true if this subprocess type needs the ResourceBundle initialized
245 // and resources loaded.
246 bool SubprocessNeedsResourceBundle(const std::string
& process_type
) {
248 #if defined(OS_WIN) || defined(OS_MACOSX)
249 // Windows needs resources for the default/null plugin.
250 // Mac needs them for the plugin process name.
251 process_type
== switches::kPluginProcess
||
253 #if defined(OS_POSIX) && !defined(OS_MACOSX)
254 // The zygote process opens the resources for the renderers.
255 process_type
== switches::kZygoteProcess
||
257 #if defined(OS_MACOSX)
258 // Mac needs them too for scrollbar related images and for sandbox
260 #if !defined(DISABLE_NACL)
261 process_type
== switches::kNaClLoaderProcess
||
263 process_type
== switches::kPpapiPluginProcess
||
264 process_type
== switches::kPpapiBrokerProcess
||
265 process_type
== switches::kGpuProcess
||
267 process_type
== switches::kRendererProcess
||
268 process_type
== switches::kUtilityProcess
;
271 #if defined(OS_POSIX)
272 // Check for --version and --product-version; return true if we encountered
273 // one of these switches and should exit now.
274 bool HandleVersionSwitches(const base::CommandLine
& command_line
) {
275 const chrome::VersionInfo version_info
;
277 #if !defined(OS_MACOSX)
278 if (command_line
.HasSwitch(switches::kProductVersion
)) {
279 printf("%s\n", version_info
.Version().c_str());
284 if (command_line
.HasSwitch(switches::kVersion
)) {
286 version_info
.Name().c_str(),
287 version_info
.Version().c_str(),
288 chrome::VersionInfo::GetVersionStringModifier().c_str());
295 #if !defined(OS_MACOSX) && !defined(OS_CHROMEOS)
296 // Show the man page if --help or -h is on the command line.
297 void HandleHelpSwitches(const base::CommandLine
& command_line
) {
298 if (command_line
.HasSwitch(switches::kHelp
) ||
299 command_line
.HasSwitch(switches::kHelpShort
)) {
300 base::FilePath
binary(command_line
.argv()[0]);
301 execlp("man", "man", binary
.BaseName().value().c_str(), NULL
);
302 PLOG(FATAL
) << "execlp failed";
307 #if !defined(OS_MACOSX) && !defined(OS_ANDROID)
308 void SIGTERMProfilingShutdown(int signal
) {
310 struct sigaction sigact
;
311 memset(&sigact
, 0, sizeof(sigact
));
312 sigact
.sa_handler
= SIG_DFL
;
313 CHECK(sigaction(SIGTERM
, &sigact
, NULL
) == 0);
317 void SetUpProfilingShutdownHandler() {
318 struct sigaction sigact
;
319 sigact
.sa_handler
= SIGTERMProfilingShutdown
;
320 sigact
.sa_flags
= SA_RESETHAND
;
321 sigemptyset(&sigact
.sa_mask
);
322 CHECK(sigaction(SIGTERM
, &sigact
, NULL
) == 0);
324 #endif // !defined(OS_MACOSX) && !defined(OS_ANDROID)
328 struct MainFunction
{
330 int (*function
)(const content::MainFunctionParams
&);
333 // Initializes the user data dir. Must be called before InitializeLocalState().
334 void InitializeUserDataDir() {
335 base::CommandLine
* command_line
= base::CommandLine::ForCurrentProcess();
336 base::FilePath user_data_dir
=
337 command_line
->GetSwitchValuePath(switches::kUserDataDir
);
338 std::string process_type
=
339 command_line
->GetSwitchValueASCII(switches::kProcessType
);
341 #if defined(OS_LINUX)
342 // On Linux, Chrome does not support running multiple copies under different
343 // DISPLAYs, so the profile directory can be specified in the environment to
344 // support the virtual desktop use-case.
345 if (user_data_dir
.empty()) {
346 std::string user_data_dir_string
;
347 scoped_ptr
<base::Environment
> environment(base::Environment::Create());
348 if (environment
->GetVar("CHROME_USER_DATA_DIR", &user_data_dir_string
) &&
349 base::IsStringUTF8(user_data_dir_string
)) {
350 user_data_dir
= base::FilePath::FromUTF8Unsafe(user_data_dir_string
);
354 #if defined(OS_MACOSX) || defined(OS_WIN)
355 policy::path_parser::CheckUserDataDirPolicy(&user_data_dir
);
358 // On Windows, trailing separators leave Chrome in a bad state.
359 // See crbug.com/464616.
360 if (user_data_dir
.EndsWithSeparator())
361 user_data_dir
= user_data_dir
.StripTrailingSeparators();
363 const bool specified_directory_was_invalid
= !user_data_dir
.empty() &&
364 !PathService::OverrideAndCreateIfNeeded(chrome::DIR_USER_DATA
,
365 user_data_dir
, false, true);
366 // Save inaccessible or invalid paths so the user may be prompted later.
367 if (specified_directory_was_invalid
)
368 chrome::SetInvalidSpecifiedUserDataDir(user_data_dir
);
370 // Warn and fail early if the process fails to get a user data directory.
371 if (!PathService::Get(chrome::DIR_USER_DATA
, &user_data_dir
)) {
372 // If an invalid command-line or policy override was specified, the user
373 // will be given an error with that value. Otherwise, use the directory
374 // returned by PathService (or the fallback default directory) in the error.
375 if (!specified_directory_was_invalid
) {
376 // PathService::Get() returns false and yields an empty path if it fails
377 // to create DIR_USER_DATA. Retrieve the default value manually to display
378 // a more meaningful error to the user in that case.
379 if (user_data_dir
.empty())
380 chrome::GetDefaultUserDataDirectory(&user_data_dir
);
381 chrome::SetInvalidSpecifiedUserDataDir(user_data_dir
);
384 // The browser process (which is identified by an empty |process_type|) will
385 // handle the error later; other processes that need the dir crash here.
386 CHECK(process_type
.empty()) << "Unable to get the user data directory "
387 << "for process type: " << process_type
;
390 // Append the fallback user data directory to the commandline. Otherwise,
391 // child or service processes will attempt to use the invalid directory.
392 if (specified_directory_was_invalid
)
393 command_line
->AppendSwitchPath(switches::kUserDataDir
, user_data_dir
);
398 ChromeMainDelegate::ChromeMainDelegate() {
399 #if defined(OS_ANDROID)
400 // On Android the main entry point time is the time when the Java code starts.
401 // This happens before the shared library containing this code is even loaded.
402 // The Java startup code has recorded that time, but the C++ code can't fetch it
403 // from the Java side until it has initialized the JNI. See
404 // ChromeMainDelegateAndroid.
406 startup_metric_utils::RecordMainEntryPointTime();
410 ChromeMainDelegate::~ChromeMainDelegate() {
413 bool ChromeMainDelegate::BasicStartupComplete(int* exit_code
) {
414 #if defined(OS_CHROMEOS)
415 chromeos::BootTimesRecorder::Get()->SaveChromeMainStats();
418 const base::CommandLine
& command_line
=
419 *base::CommandLine::ForCurrentProcess();
423 // Browser should not be sandboxed.
424 const bool is_browser
= !command_line
.HasSwitch(switches::kProcessType
);
425 if (is_browser
&& IsSandboxedProcess()) {
426 *exit_code
= chrome::RESULT_CODE_INVALID_SANDBOX_STATE
;
431 #if defined(OS_MACOSX)
432 // Give the browser process a longer treadmill, since crashes
433 // there have more impact.
434 const bool is_browser
= !command_line
.HasSwitch(switches::kProcessType
);
435 ObjcEvilDoers::ZombieEnable(true, is_browser
? 10000 : 1000);
437 SetUpBundleOverrides();
438 chrome::common::mac::EnableCFBundleBlocker();
441 Profiling::ProcessStarted();
443 base::trace_event::TraceLog::GetInstance()->SetArgumentFilterPredicate(
444 base::Bind(&IsTraceEventArgsWhitelisted
));
447 v8_breakpad_support::SetUp();
450 #if defined(OS_POSIX)
451 if (HandleVersionSwitches(command_line
)) {
453 return true; // Got a --version switch; exit with a success error code.
455 #if !defined(OS_MACOSX) && !defined(OS_CHROMEOS)
456 // This will directly exit if the user asked for help.
457 HandleHelpSwitches(command_line
);
462 // Must do this before any other usage of command line!
463 if (HasDeprecatedArguments(command_line
.GetCommandLineString())) {
468 InstallCloseHandleHooks();
471 chrome::RegisterPathProvider();
472 #if defined(OS_CHROMEOS)
473 chromeos::RegisterPathProvider();
475 #if !defined(DISABLE_NACL) && defined(OS_LINUX)
476 nacl::RegisterPathProvider();
479 ContentSettingsPattern::SetNonWildcardDomainNonPortScheme(
480 extensions::kExtensionScheme
);
482 // No support for ANDROID yet as DiagnosticsController needs wchar support.
483 // TODO(gspencer): That's not true anymore, or at least there are no w-string
484 // references anymore. Not sure if that means this can be enabled on Android or
485 // not though. As there is no easily accessible command line on Android, I'm
486 // not sure this is a big deal.
487 #if !defined(OS_ANDROID) && !defined(CHROME_MULTIPLE_DLL_CHILD)
488 // If we are in diagnostics mode this is the end of the line: after the
489 // diagnostics are run the process will invariably exit.
490 if (command_line
.HasSwitch(switches::kDiagnostics
)) {
491 diagnostics::DiagnosticsWriter::FormatType format
=
492 diagnostics::DiagnosticsWriter::HUMAN
;
493 if (command_line
.HasSwitch(switches::kDiagnosticsFormat
)) {
494 std::string format_str
=
495 command_line
.GetSwitchValueASCII(switches::kDiagnosticsFormat
);
496 if (format_str
== "machine") {
497 format
= diagnostics::DiagnosticsWriter::MACHINE
;
498 } else if (format_str
== "log") {
499 format
= diagnostics::DiagnosticsWriter::LOG
;
501 DCHECK_EQ("human", format_str
);
505 diagnostics::DiagnosticsWriter
writer(format
);
506 *exit_code
= diagnostics::DiagnosticsController::GetInstance()->Run(
507 command_line
, &writer
);
508 diagnostics::DiagnosticsController::GetInstance()->ClearResults();
513 #if defined(OS_CHROMEOS)
514 // Initialize primary user homedir (in multi-profile session) as it may be
515 // passed as a command line switch.
516 base::FilePath homedir
;
517 if (command_line
.HasSwitch(chromeos::switches::kHomedir
)) {
518 homedir
= base::FilePath(
519 command_line
.GetSwitchValueASCII(chromeos::switches::kHomedir
));
520 PathService::OverrideAndCreateIfNeeded(
521 base::DIR_HOME
, homedir
, true, false);
524 // If we are recovering from a crash on ChromeOS, then we will do some
525 // recovery using the diagnostics module, and then continue on. We fake up a
526 // command line to tell it that we want it to recover, and to preserve the
527 // original command line.
528 if (command_line
.HasSwitch(chromeos::switches::kLoginUser
) ||
529 command_line
.HasSwitch(switches::kDiagnosticsRecovery
)) {
530 // The statistics subsystem needs get initialized soon enough for the
531 // statistics to be collected. It's safe to call this more than once.
532 base::StatisticsRecorder::Initialize();
534 base::CommandLine
interim_command_line(command_line
.GetProgram());
535 const char* const kSwitchNames
[] = {switches::kUserDataDir
, };
536 interim_command_line
.CopySwitchesFrom(
537 command_line
, kSwitchNames
, arraysize(kSwitchNames
));
538 interim_command_line
.AppendSwitch(switches::kDiagnostics
);
539 interim_command_line
.AppendSwitch(switches::kDiagnosticsRecovery
);
541 diagnostics::DiagnosticsWriter::FormatType format
=
542 diagnostics::DiagnosticsWriter::LOG
;
543 if (command_line
.HasSwitch(switches::kDiagnosticsFormat
)) {
544 std::string format_str
=
545 command_line
.GetSwitchValueASCII(switches::kDiagnosticsFormat
);
546 if (format_str
== "machine") {
547 format
= diagnostics::DiagnosticsWriter::MACHINE
;
548 } else if (format_str
== "human") {
549 format
= diagnostics::DiagnosticsWriter::HUMAN
;
551 DCHECK_EQ("log", format_str
);
555 diagnostics::DiagnosticsWriter
writer(format
);
556 int diagnostics_exit_code
=
557 diagnostics::DiagnosticsController::GetInstance()->Run(command_line
,
559 if (diagnostics_exit_code
) {
560 // Diagnostics has failed somehow, so we exit.
561 *exit_code
= diagnostics_exit_code
;
565 // Now we run the actual recovery tasks.
566 int recovery_exit_code
=
567 diagnostics::DiagnosticsController::GetInstance()->RunRecovery(
568 command_line
, &writer
);
570 if (recovery_exit_code
) {
571 // Recovery has failed somehow, so we exit.
572 *exit_code
= recovery_exit_code
;
575 } else { // Not running diagnostics or recovery.
576 diagnostics::DiagnosticsController::GetInstance()->RecordRegularStartup();
580 content::SetContentClient(&chrome_content_client_
);
585 #if defined(OS_MACOSX)
586 void ChromeMainDelegate::InitMacCrashReporter(
587 const base::CommandLine
& command_line
,
588 const std::string
& process_type
) {
589 // TODO(mark): Right now, InitializeCrashpad() needs to be called after
590 // CommandLine::Init() and chrome::RegisterPathProvider(). Ideally, Crashpad
591 // initialization could occur sooner, preferably even before the framework
592 // dylib is even loaded, to catch potential early crashes.
593 crash_reporter::InitializeCrashpad(process_type
);
595 const bool browser_process
= process_type
.empty();
596 if (!browser_process
) {
597 std::string metrics_client_id
=
598 command_line
.GetSwitchValueASCII(switches::kMetricsClientID
);
599 crash_keys::SetMetricsClientIdFromGUID(metrics_client_id
);
602 // Mac Chrome is packaged with a main app bundle and a helper app bundle.
603 // The main app bundle should only be used for the browser process, so it
604 // should never see a --type switch (switches::kProcessType). Likewise,
605 // the helper should always have a --type switch.
607 // This check is done this late so there is already a call to
608 // base::mac::IsBackgroundOnlyProcess(), so there is no change in
609 // startup/initialization order.
611 // The helper's Info.plist marks it as a background only app.
612 if (base::mac::IsBackgroundOnlyProcess()) {
613 CHECK(command_line
.HasSwitch(switches::kProcessType
) &&
614 !process_type
.empty())
615 << "Helper application requires --type.";
617 // In addition, some helper flavors only work with certain process types.
618 base::FilePath executable
;
619 if (PathService::Get(base::FILE_EXE
, &executable
) &&
620 executable
.value().size() >= 3) {
621 std::string last_three
=
622 executable
.value().substr(executable
.value().size() - 3);
624 if (last_three
== " EH") {
625 CHECK(process_type
== switches::kPluginProcess
||
626 process_type
== switches::kUtilityProcess
)
627 << "Executable-heap process requires --type="
628 << switches::kPluginProcess
<< " or "
629 << switches::kUtilityProcess
<< ", saw " << process_type
;
630 } else if (last_three
== " NP") {
631 #if !defined(DISABLE_NACL)
632 CHECK_EQ(switches::kNaClLoaderProcess
, process_type
)
633 << "Non-PIE process requires --type="
634 << switches::kNaClLoaderProcess
<< ", saw " << process_type
;
637 #if defined(DISABLE_NACL)
638 CHECK(process_type
!= switches::kPluginProcess
)
639 << "Non-executable-heap PIE process is intolerant of --type="
640 << switches::kPluginProcess
;
642 CHECK(process_type
!= switches::kPluginProcess
&&
643 process_type
!= switches::kNaClLoaderProcess
)
644 << "Non-executable-heap PIE process is intolerant of --type="
645 << switches::kPluginProcess
<< " and "
646 << switches::kNaClLoaderProcess
<< ", saw " << process_type
;
651 CHECK(!command_line
.HasSwitch(switches::kProcessType
) &&
652 process_type
.empty())
653 << "Main application forbids --type, saw " << process_type
;
656 #endif // defined(OS_MACOSX)
658 void ChromeMainDelegate::PreSandboxStartup() {
659 const base::CommandLine
& command_line
=
660 *base::CommandLine::ForCurrentProcess();
661 std::string process_type
=
662 command_line
.GetSwitchValueASCII(switches::kProcessType
);
664 #if defined(OS_POSIX)
665 crash_reporter::SetCrashReporterClient(g_chrome_crash_client
.Pointer());
668 #if defined(OS_MACOSX)
669 // On the Mac, the child executable lives at a predefined location within
670 // the app bundle's versioned directory.
671 PathService::Override(content::CHILD_PROCESS_EXE
,
672 chrome::GetVersionedDirectory().
673 Append(chrome::kHelperProcessExecutablePath
));
675 InitMacCrashReporter(command_line
, process_type
);
679 child_process_logging::Init();
681 #if defined(ARCH_CPU_ARM_FAMILY) && (defined(OS_ANDROID) || defined(OS_LINUX))
682 // Create an instance of the CPU class to parse /proc/cpuinfo and cache
687 // Initialize the user data dir for any process type that needs it.
688 if (chrome::ProcessNeedsProfileDir(process_type
))
689 InitializeUserDataDir();
691 // Register component_updater PathProvider after DIR_USER_DATA overidden by
692 // command line flags. Maybe move the chrome PathProvider down here also?
693 component_updater::RegisterPathProvider(chrome::DIR_USER_DATA
);
695 // Enable Message Loop related state asap.
696 if (command_line
.HasSwitch(switches::kMessageLoopHistogrammer
))
697 base::MessageLoop::EnableHistogrammer(true);
699 #if !defined(OS_ANDROID)
700 // Android does InitLogging when library is loaded. Skip here.
701 logging::OldFileDeletionState file_state
=
702 logging::APPEND_TO_OLD_LOG_FILE
;
703 if (process_type
.empty()) {
704 file_state
= logging::DELETE_OLD_LOG_FILE
;
706 logging::InitChromeLogging(command_line
, file_state
);
710 // TODO(zturner): Throbber icons are still stored in chrome.dll, this can be
711 // killed once those are merged into resources.pak. See
712 // GlassBrowserFrameView::InitThrobberIcons() and http://crbug.com/368327.
713 ui::SetResourcesDataDLL(_AtlBaseModule
.GetResourceInstance());
716 if (SubprocessNeedsResourceBundle(process_type
)) {
717 // Initialize ResourceBundle which handles files loaded from external
718 // sources. The language should have been passed in to us from the
719 // browser process as a command line flag.
720 #if defined(DISABLE_NACL)
721 DCHECK(command_line
.HasSwitch(switches::kLang
) ||
722 process_type
== switches::kZygoteProcess
||
723 process_type
== switches::kGpuProcess
||
724 process_type
== switches::kPpapiBrokerProcess
||
725 process_type
== switches::kPpapiPluginProcess
);
727 DCHECK(command_line
.HasSwitch(switches::kLang
) ||
728 process_type
== switches::kZygoteProcess
||
729 process_type
== switches::kGpuProcess
||
730 process_type
== switches::kNaClLoaderProcess
||
731 process_type
== switches::kPpapiBrokerProcess
||
732 process_type
== switches::kPpapiPluginProcess
);
735 // TODO(markusheintz): The command line flag --lang is actually processed
736 // by the CommandLinePrefStore, and made available through the PrefService
737 // via the preference prefs::kApplicationLocale. The browser process uses
738 // the --lang flag to pass the value of the PrefService in here. Maybe
739 // this value could be passed in a different way.
740 const std::string locale
=
741 command_line
.GetSwitchValueASCII(switches::kLang
);
742 #if defined(OS_ANDROID)
743 // The renderer sandbox prevents us from accessing our .pak files directly.
744 // Therefore file descriptors to the .pak files that we need are passed in
745 // at process creation time.
746 auto global_descriptors
= base::GlobalDescriptors::GetInstance();
747 int pak_fd
= global_descriptors
->Get(kAndroidLocalePakDescriptor
);
748 base::MemoryMappedFile::Region pak_region
=
749 global_descriptors
->GetRegion(kAndroidLocalePakDescriptor
);
750 ResourceBundle::InitSharedInstanceWithPakFileRegion(base::File(pak_fd
),
753 int extra_pak_keys
[] = {
754 kAndroidChrome100PercentPakDescriptor
,
755 kAndroidUIResourcesPakDescriptor
,
757 for (size_t i
= 0; i
< arraysize(extra_pak_keys
); ++i
) {
758 pak_fd
= global_descriptors
->Get(extra_pak_keys
[i
]);
759 pak_region
= global_descriptors
->GetRegion(extra_pak_keys
[i
]);
760 ResourceBundle::GetSharedInstance().AddDataPackFromFileRegion(
761 base::File(pak_fd
), pak_region
, ui::SCALE_FACTOR_100P
);
764 base::i18n::SetICUDefaultLocale(locale
);
765 const std::string loaded_locale
= locale
;
767 const std::string loaded_locale
=
768 ui::ResourceBundle::InitSharedInstanceWithLocale(
769 locale
, NULL
, ui::ResourceBundle::LOAD_COMMON_RESOURCES
);
771 base::FilePath resources_pack_path
;
772 PathService::Get(chrome::FILE_RESOURCES_PACK
, &resources_pack_path
);
773 ResourceBundle::GetSharedInstance().AddDataPackFromPath(
774 resources_pack_path
, ui::SCALE_FACTOR_NONE
);
776 CHECK(!loaded_locale
.empty()) << "Locale could not be found for " <<
780 #if !defined(CHROME_MULTIPLE_DLL_BROWSER)
781 if (process_type
== switches::kUtilityProcess
||
782 process_type
== switches::kZygoteProcess
) {
783 ChromeContentUtilityClient::PreSandboxStartup();
786 chrome::InitializePDF();
789 #if defined(OS_POSIX) && !defined(OS_MACOSX)
790 // Zygote needs to call InitCrashReporter() in RunZygote().
791 if (process_type
!= switches::kZygoteProcess
) {
792 #if defined(OS_ANDROID)
793 if (process_type
.empty()) {
794 breakpad::InitCrashReporter(process_type
);
795 chrome::android::InitJavaExceptionReporter();
797 breakpad::InitNonBrowserCrashReporterForAndroid(process_type
);
799 #else // !defined(OS_ANDROID)
800 breakpad::InitCrashReporter(process_type
);
801 #endif // defined(OS_ANDROID)
803 #endif // defined(OS_POSIX) && !defined(OS_MACOSX)
805 // After all the platform Breakpads have been initialized, store the command
806 // line for crash reporting.
807 crash_keys::SetSwitchesFromCommandLine(&command_line
);
810 void ChromeMainDelegate::SandboxInitialized(const std::string
& process_type
) {
811 // Note: If you are adding a new process type below, be sure to adjust the
812 // AdjustLinuxOOMScore function too.
813 #if defined(OS_LINUX)
814 AdjustLinuxOOMScore(process_type
);
817 SuppressWindowsErrorDialogs();
820 #if defined(CHROME_MULTIPLE_DLL_CHILD) || !defined(CHROME_MULTIPLE_DLL_BROWSER)
821 #if defined(ENABLE_REMOTING)
822 ChromeContentClient::SetRemotingEntryFunctions(
823 remoting::PPP_GetInterface
,
824 remoting::PPP_InitializeModule
,
825 remoting::PPP_ShutdownModule
);
827 #if !defined(DISABLE_NACL)
828 ChromeContentClient::SetNaClEntryFunctions(
829 nacl_plugin::PPP_GetInterface
,
830 nacl_plugin::PPP_InitializeModule
,
831 nacl_plugin::PPP_ShutdownModule
);
833 #if defined(ENABLE_PLUGINS)
834 ChromeContentClient::SetPDFEntryFunctions(
835 chrome_pdf::PPP_GetInterface
,
836 chrome_pdf::PPP_InitializeModule
,
837 chrome_pdf::PPP_ShutdownModule
);
842 int ChromeMainDelegate::RunProcess(
843 const std::string
& process_type
,
844 const content::MainFunctionParams
& main_function_params
) {
845 // ANDROID doesn't support "service", so no ServiceProcessMain, and arraysize
846 // doesn't support empty array. So we comment out the block for Android.
847 #if !defined(OS_ANDROID)
848 static const MainFunction kMainFunctions
[] = {
849 #if defined(ENABLE_PRINT_PREVIEW) && !defined(CHROME_MULTIPLE_DLL_CHILD)
850 { switches::kServiceProcess
, ServiceProcessMain
},
853 #if defined(OS_MACOSX)
854 { switches::kRelauncherProcess
,
855 mac_relauncher::internal::RelauncherMain
},
858 // This entry is not needed on Linux, where the NaCl loader
859 // process is launched via nacl_helper instead.
860 #if !defined(DISABLE_NACL) && !defined(CHROME_MULTIPLE_DLL_BROWSER) && \
862 { switches::kNaClLoaderProcess
, NaClMain
},
864 { "<invalid>", NULL
}, // To avoid constant array of size 0
865 // when DISABLE_NACL and CHROME_MULTIPLE_DLL_CHILD
866 #endif // DISABLE_NACL
869 for (size_t i
= 0; i
< arraysize(kMainFunctions
); ++i
) {
870 if (process_type
== kMainFunctions
[i
].name
)
871 return kMainFunctions
[i
].function(main_function_params
);
878 void ChromeMainDelegate::ProcessExiting(const std::string
& process_type
) {
879 if (SubprocessNeedsResourceBundle(process_type
))
880 ResourceBundle::CleanupSharedInstance();
881 #if !defined(OS_ANDROID)
882 logging::CleanupChromeLogging();
884 // Android doesn't use InitChromeLogging, so we close the log file manually.
885 logging::CloseLogFile();
886 #endif // !defined(OS_ANDROID)
889 RemoveCloseHandleHooks();
893 #if defined(OS_MACOSX)
894 bool ChromeMainDelegate::ProcessRegistersWithSystemProcess(
895 const std::string
& process_type
) {
896 #if defined(DISABLE_NACL)
899 return process_type
== switches::kNaClLoaderProcess
;
903 bool ChromeMainDelegate::ShouldSendMachPort(const std::string
& process_type
) {
904 return process_type
!= switches::kRelauncherProcess
&&
905 process_type
!= switches::kServiceProcess
;
908 bool ChromeMainDelegate::DelaySandboxInitialization(
909 const std::string
& process_type
) {
910 #if !defined(DISABLE_NACL)
911 // NaClLoader does this in NaClMainPlatformDelegate::EnableSandbox().
912 // No sandbox needed for relauncher.
913 if (process_type
== switches::kNaClLoaderProcess
)
916 return process_type
== switches::kRelauncherProcess
;
918 #elif defined(OS_POSIX) && !defined(OS_ANDROID)
919 void ChromeMainDelegate::ZygoteStarting(
920 ScopedVector
<content::ZygoteForkDelegate
>* delegates
) {
921 #if !defined(DISABLE_NACL)
922 nacl::AddNaClZygoteForkDelegates(delegates
);
926 void ChromeMainDelegate::ZygoteForked() {
927 Profiling::ProcessStarted();
928 if (Profiling::BeingProfiled()) {
929 base::debug::RestartProfilingAfterFork();
930 SetUpProfilingShutdownHandler();
933 // Needs to be called after we have chrome::DIR_USER_DATA. BrowserMain sets
934 // this up for the browser process in a different manner.
935 const base::CommandLine
* command_line
=
936 base::CommandLine::ForCurrentProcess();
937 std::string process_type
=
938 command_line
->GetSwitchValueASCII(switches::kProcessType
);
939 breakpad::InitCrashReporter(process_type
);
941 // Reset the command line for the newly spawned process.
942 crash_keys::SetSwitchesFromCommandLine(command_line
);
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();
982 bool ChromeMainDelegate::ShouldEnableProfilerRecording() {
983 switch (chrome::VersionInfo::GetChannel()) {
984 case chrome::VersionInfo::CHANNEL_UNKNOWN
:
985 case chrome::VersionInfo::CHANNEL_CANARY
:
987 case chrome::VersionInfo::CHANNEL_DEV
:
988 case chrome::VersionInfo::CHANNEL_BETA
:
989 case chrome::VersionInfo::CHANNEL_STABLE
:
991 // Don't enable instrumentation.