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_result_codes.h"
27 #include "chrome/common/chrome_switches.h"
28 #include "chrome/common/chrome_version_info.h"
29 #include "chrome/common/crash_keys.h"
30 #include "chrome/common/logging_chrome.h"
31 #include "chrome/common/profiling.h"
32 #include "chrome/common/switch_utils.h"
33 #include "chrome/common/url_constants.h"
34 #include "chrome/plugin/chrome_content_plugin_client.h"
35 #include "chrome/renderer/chrome_content_renderer_client.h"
36 #include "chrome/utility/chrome_content_utility_client.h"
37 #include "components/component_updater/component_updater_paths.h"
38 #include "components/content_settings/core/common/content_settings_pattern.h"
39 #include "components/startup_metric_utils/startup_metric_utils.h"
40 #include "content/public/common/content_client.h"
41 #include "content/public/common/content_paths.h"
42 #include "extensions/common/constants.h"
43 #include "ui/base/ui_base_switches.h"
49 #include "chrome/app/close_handle_hook_win.h"
50 #include "chrome/common/child_process_logging.h"
51 #include "chrome/common/v8_breakpad_support_win.h"
52 #include "sandbox/win/src/sandbox.h"
53 #include "ui/base/resource/resource_bundle_win.h"
56 #if defined(OS_MACOSX)
57 #include "base/mac/foundation_util.h"
58 #include "chrome/app/chrome_main_mac.h"
59 #include "chrome/browser/mac/relauncher.h"
60 #include "chrome/common/mac/cfbundle_blocker.h"
61 #include "chrome/common/mac/objc_zombie.h"
62 #include "components/crash/app/crashpad_mac.h"
63 #include "ui/base/l10n/l10n_util_mac.h"
69 #include "chrome/app/chrome_crash_reporter_client.h"
70 #include "components/crash/app/crash_reporter_client.h"
73 #if !defined(DISABLE_NACL) && defined(OS_LINUX)
74 #include "components/nacl/common/nacl_paths.h"
75 #include "components/nacl/zygote/nacl_fork_delegate_linux.h"
78 #if defined(OS_CHROMEOS)
79 #include "base/sys_info.h"
80 #include "chrome/browser/chromeos/boot_times_recorder.h"
81 #include "chromeos/chromeos_paths.h"
82 #include "chromeos/chromeos_switches.h"
85 #if defined(OS_ANDROID)
86 #include "chrome/browser/android/java_exception_reporter.h"
87 #include "chrome/common/descriptors_android.h"
89 // Diagnostics is only available on non-android platforms.
90 #include "chrome/browser/diagnostics/diagnostics_controller.h"
91 #include "chrome/browser/diagnostics/diagnostics_writer.h"
97 #include "ui/base/x/x11_util.h"
100 #if defined(OS_POSIX) && !defined(OS_MACOSX)
101 #include "components/crash/app/breakpad_linux.h"
104 #if defined(OS_LINUX)
105 #include "base/environment.h"
108 #if defined(OS_MACOSX) || defined(OS_WIN)
109 #include "chrome/browser/policy/policy_path_parser.h"
112 #if !defined(DISABLE_NACL)
113 #include "components/nacl/common/nacl_switches.h"
114 #include "components/nacl/renderer/plugin/ppapi_entrypoints.h"
117 #if defined(ENABLE_REMOTING)
118 #include "remoting/client/plugin/pepper_entrypoints.h"
121 #if defined(ENABLE_PLUGINS) && (defined(CHROME_MULTIPLE_DLL_CHILD) || \
122 !defined(CHROME_MULTIPLE_DLL_BROWSER))
126 #if !defined(CHROME_MULTIPLE_DLL_BROWSER)
127 #include "chrome/child/pdf_child_init.h"
129 base::LazyInstance
<ChromeContentRendererClient
>
130 g_chrome_content_renderer_client
= LAZY_INSTANCE_INITIALIZER
;
131 base::LazyInstance
<ChromeContentUtilityClient
>
132 g_chrome_content_utility_client
= LAZY_INSTANCE_INITIALIZER
;
133 base::LazyInstance
<chrome::ChromeContentPluginClient
>
134 g_chrome_content_plugin_client
= LAZY_INSTANCE_INITIALIZER
;
137 #if !defined(CHROME_MULTIPLE_DLL_CHILD)
138 base::LazyInstance
<chrome::ChromeContentBrowserClient
>
139 g_chrome_content_browser_client
= LAZY_INSTANCE_INITIALIZER
;
142 #if defined(OS_POSIX)
143 base::LazyInstance
<chrome::ChromeCrashReporterClient
>::Leaky
144 g_chrome_crash_client
= LAZY_INSTANCE_INITIALIZER
;
147 extern int NaClMain(const content::MainFunctionParams
&);
148 extern int ServiceProcessMain(const content::MainFunctionParams
&);
153 // Early versions of Chrome incorrectly registered a chromehtml: URL handler,
154 // which gives us nothing but trouble. Avoid launching chrome this way since
155 // some apps fail to properly escape arguments.
156 bool HasDeprecatedArguments(const std::wstring
& command_line
) {
157 const wchar_t kChromeHtml
[] = L
"chromehtml:";
158 std::wstring command_line_lower
= command_line
;
159 // We are only searching for ASCII characters so this is OK.
160 base::StringToLowerASCII(&command_line_lower
);
161 std::wstring::size_type pos
= command_line_lower
.find(kChromeHtml
);
162 return (pos
!= std::wstring::npos
);
165 // If we try to access a path that is not currently available, we want the call
166 // to fail rather than show an error dialog.
167 void SuppressWindowsErrorDialogs() {
168 UINT new_flags
= SEM_FAILCRITICALERRORS
|
169 SEM_NOOPENFILEERRORBOX
;
171 // Preserve existing error mode.
172 UINT existing_flags
= SetErrorMode(new_flags
);
173 SetErrorMode(existing_flags
| new_flags
);
176 bool IsSandboxedProcess() {
177 typedef bool (*IsSandboxedProcessFunc
)();
178 IsSandboxedProcessFunc is_sandboxed_process_func
=
179 reinterpret_cast<IsSandboxedProcessFunc
>(
180 GetProcAddress(GetModuleHandle(NULL
), "IsSandboxedProcess"));
181 return is_sandboxed_process_func
&& is_sandboxed_process_func();
184 #endif // defined(OS_WIN)
186 #if defined(OS_LINUX)
187 static void AdjustLinuxOOMScore(const std::string
& process_type
) {
188 // Browsers and zygotes should still be killable, but killed last.
189 const int kZygoteScore
= 0;
190 // The minimum amount to bump a score by. This is large enough that
191 // even if it's translated into the old values, it will still go up
193 const int kScoreBump
= 100;
194 // This is the lowest score that renderers and extensions start with
195 // in the OomPriorityManager.
196 const int kRendererScore
= chrome::kLowestRendererOomScore
;
197 // For "miscellaneous" things, we want them after renderers,
198 // but before plugins.
199 const int kMiscScore
= kRendererScore
- kScoreBump
;
200 // We want plugins to die after the renderers.
201 const int kPluginScore
= kMiscScore
- kScoreBump
;
204 DCHECK(kMiscScore
> 0);
205 DCHECK(kPluginScore
> 0);
207 if (process_type
== switches::kPluginProcess
||
208 process_type
== switches::kPpapiPluginProcess
) {
209 score
= kPluginScore
;
210 } else if (process_type
== switches::kPpapiBrokerProcess
) {
211 // The broker should be killed before the PPAPI plugin.
212 score
= kPluginScore
+ kScoreBump
;
213 } else if (process_type
== switches::kUtilityProcess
||
214 process_type
== switches::kGpuProcess
||
215 process_type
== switches::kServiceProcess
) {
218 } else if (process_type
== switches::kNaClLoaderProcess
||
219 process_type
== switches::kNaClLoaderNonSfiProcess
) {
220 score
= kPluginScore
;
222 } else if (process_type
== switches::kZygoteProcess
||
223 process_type
.empty()) {
224 // For zygotes and unlabeled process types, we want to still make
225 // them killable by the OOM killer.
226 score
= kZygoteScore
;
227 } else if (process_type
== switches::kRendererProcess
) {
228 LOG(WARNING
) << "process type 'renderer' "
229 << "should be created through the zygote.";
230 // When debugging, this process type can end up being run directly, but
231 // this isn't the typical path for assigning the OOM score for it. Still,
232 // we want to assign a score that is somewhat representative for debugging.
233 score
= kRendererScore
;
235 NOTREACHED() << "Unknown process type";
238 base::AdjustOOMScore(base::GetCurrentProcId(), score
);
240 #endif // defined(OS_LINUX)
242 // Returns true if this subprocess type needs the ResourceBundle initialized
243 // and resources loaded.
244 bool SubprocessNeedsResourceBundle(const std::string
& process_type
) {
246 #if defined(OS_WIN) || defined(OS_MACOSX)
247 // Windows needs resources for the default/null plugin.
248 // Mac needs them for the plugin process name.
249 process_type
== switches::kPluginProcess
||
251 #if defined(OS_POSIX) && !defined(OS_MACOSX)
252 // The zygote process opens the resources for the renderers.
253 process_type
== switches::kZygoteProcess
||
255 #if defined(OS_MACOSX)
256 // Mac needs them too for scrollbar related images and for sandbox
258 #if !defined(DISABLE_NACL)
259 process_type
== switches::kNaClLoaderProcess
||
261 process_type
== switches::kPpapiPluginProcess
||
262 process_type
== switches::kPpapiBrokerProcess
||
263 process_type
== switches::kGpuProcess
||
265 process_type
== switches::kRendererProcess
||
266 process_type
== switches::kUtilityProcess
;
269 #if defined(OS_POSIX)
270 // Check for --version and --product-version; return true if we encountered
271 // one of these switches and should exit now.
272 bool HandleVersionSwitches(const base::CommandLine
& command_line
) {
273 const chrome::VersionInfo version_info
;
275 #if !defined(OS_MACOSX)
276 if (command_line
.HasSwitch(switches::kProductVersion
)) {
277 printf("%s\n", version_info
.Version().c_str());
282 if (command_line
.HasSwitch(switches::kVersion
)) {
284 version_info
.Name().c_str(),
285 version_info
.Version().c_str(),
286 chrome::VersionInfo::GetVersionStringModifier().c_str());
293 #if !defined(OS_MACOSX) && !defined(OS_CHROMEOS)
294 // Show the man page if --help or -h is on the command line.
295 void HandleHelpSwitches(const base::CommandLine
& command_line
) {
296 if (command_line
.HasSwitch(switches::kHelp
) ||
297 command_line
.HasSwitch(switches::kHelpShort
)) {
298 base::FilePath
binary(command_line
.argv()[0]);
299 execlp("man", "man", binary
.BaseName().value().c_str(), NULL
);
300 PLOG(FATAL
) << "execlp failed";
305 #if !defined(OS_MACOSX) && !defined(OS_ANDROID)
306 void SIGTERMProfilingShutdown(int signal
) {
308 struct sigaction sigact
;
309 memset(&sigact
, 0, sizeof(sigact
));
310 sigact
.sa_handler
= SIG_DFL
;
311 CHECK(sigaction(SIGTERM
, &sigact
, NULL
) == 0);
315 void SetUpProfilingShutdownHandler() {
316 struct sigaction sigact
;
317 sigact
.sa_handler
= SIGTERMProfilingShutdown
;
318 sigact
.sa_flags
= SA_RESETHAND
;
319 sigemptyset(&sigact
.sa_mask
);
320 CHECK(sigaction(SIGTERM
, &sigact
, NULL
) == 0);
322 #endif // !defined(OS_MACOSX) && !defined(OS_ANDROID)
326 struct MainFunction
{
328 int (*function
)(const content::MainFunctionParams
&);
331 // Initializes the user data dir. Must be called before InitializeLocalState().
332 void InitializeUserDataDir() {
333 base::CommandLine
* command_line
= base::CommandLine::ForCurrentProcess();
334 base::FilePath user_data_dir
=
335 command_line
->GetSwitchValuePath(switches::kUserDataDir
);
336 std::string process_type
=
337 command_line
->GetSwitchValueASCII(switches::kProcessType
);
339 #if defined(OS_LINUX)
340 // On Linux, Chrome does not support running multiple copies under different
341 // DISPLAYs, so the profile directory can be specified in the environment to
342 // support the virtual desktop use-case.
343 if (user_data_dir
.empty()) {
344 std::string user_data_dir_string
;
345 scoped_ptr
<base::Environment
> environment(base::Environment::Create());
346 if (environment
->GetVar("CHROME_USER_DATA_DIR", &user_data_dir_string
) &&
347 base::IsStringUTF8(user_data_dir_string
)) {
348 user_data_dir
= base::FilePath::FromUTF8Unsafe(user_data_dir_string
);
352 #if defined(OS_MACOSX) || defined(OS_WIN)
353 policy::path_parser::CheckUserDataDirPolicy(&user_data_dir
);
356 // On Windows, trailing separators leave Chrome in a bad state.
357 // See crbug.com/464616.
358 if (user_data_dir
.EndsWithSeparator())
359 user_data_dir
= user_data_dir
.StripTrailingSeparators();
361 const bool specified_directory_was_invalid
= !user_data_dir
.empty() &&
362 !PathService::OverrideAndCreateIfNeeded(chrome::DIR_USER_DATA
,
363 user_data_dir
, false, true);
364 // Save inaccessible or invalid paths so the user may be prompted later.
365 if (specified_directory_was_invalid
)
366 chrome::SetInvalidSpecifiedUserDataDir(user_data_dir
);
368 // Warn and fail early if the process fails to get a user data directory.
369 if (!PathService::Get(chrome::DIR_USER_DATA
, &user_data_dir
)) {
370 // If an invalid command-line or policy override was specified, the user
371 // will be given an error with that value. Otherwise, use the directory
372 // returned by PathService (or the fallback default directory) in the error.
373 if (!specified_directory_was_invalid
) {
374 // PathService::Get() returns false and yields an empty path if it fails
375 // to create DIR_USER_DATA. Retrieve the default value manually to display
376 // a more meaningful error to the user in that case.
377 if (user_data_dir
.empty())
378 chrome::GetDefaultUserDataDirectory(&user_data_dir
);
379 chrome::SetInvalidSpecifiedUserDataDir(user_data_dir
);
382 // The browser process (which is identified by an empty |process_type|) will
383 // handle the error later; other processes that need the dir crash here.
384 CHECK(process_type
.empty()) << "Unable to get the user data directory "
385 << "for process type: " << process_type
;
388 // Append the fallback user data directory to the commandline. Otherwise,
389 // child or service processes will attempt to use the invalid directory.
390 if (specified_directory_was_invalid
)
391 command_line
->AppendSwitchPath(switches::kUserDataDir
, user_data_dir
);
396 ChromeMainDelegate::ChromeMainDelegate() {
397 #if defined(OS_ANDROID)
398 // On Android the main entry point time is the time when the Java code starts.
399 // This happens before the shared library containing this code is even loaded.
400 // The Java startup code has recorded that time, but the C++ code can't fetch it
401 // from the Java side until it has initialized the JNI. See
402 // ChromeMainDelegateAndroid.
404 startup_metric_utils::RecordMainEntryPointTime();
408 ChromeMainDelegate::~ChromeMainDelegate() {
411 bool ChromeMainDelegate::BasicStartupComplete(int* exit_code
) {
412 #if defined(OS_CHROMEOS)
413 chromeos::BootTimesRecorder::Get()->SaveChromeMainStats();
416 const base::CommandLine
& command_line
=
417 *base::CommandLine::ForCurrentProcess();
421 // Browser should not be sandboxed.
422 const bool is_browser
= !command_line
.HasSwitch(switches::kProcessType
);
423 if (is_browser
&& IsSandboxedProcess()) {
424 *exit_code
= chrome::RESULT_CODE_INVALID_SANDBOX_STATE
;
429 #if defined(OS_MACOSX)
430 // Give the browser process a longer treadmill, since crashes
431 // there have more impact.
432 const bool is_browser
= !command_line
.HasSwitch(switches::kProcessType
);
433 ObjcEvilDoers::ZombieEnable(true, is_browser
? 10000 : 1000);
435 SetUpBundleOverrides();
436 chrome::common::mac::EnableCFBundleBlocker();
439 Profiling::ProcessStarted();
442 v8_breakpad_support::SetUp();
445 #if defined(OS_POSIX)
446 if (HandleVersionSwitches(command_line
)) {
448 return true; // Got a --version switch; exit with a success error code.
450 #if !defined(OS_MACOSX) && !defined(OS_CHROMEOS)
451 // This will directly exit if the user asked for help.
452 HandleHelpSwitches(command_line
);
457 // Must do this before any other usage of command line!
458 if (HasDeprecatedArguments(command_line
.GetCommandLineString())) {
463 InstallCloseHandleHooks();
466 chrome::RegisterPathProvider();
467 #if defined(OS_CHROMEOS)
468 chromeos::RegisterPathProvider();
470 #if !defined(DISABLE_NACL) && defined(OS_LINUX)
471 nacl::RegisterPathProvider();
474 ContentSettingsPattern::SetNonWildcardDomainNonPortScheme(
475 extensions::kExtensionScheme
);
477 // No support for ANDROID yet as DiagnosticsController needs wchar support.
478 // TODO(gspencer): That's not true anymore, or at least there are no w-string
479 // references anymore. Not sure if that means this can be enabled on Android or
480 // not though. As there is no easily accessible command line on Android, I'm
481 // not sure this is a big deal.
482 #if !defined(OS_ANDROID) && !defined(CHROME_MULTIPLE_DLL_CHILD)
483 // If we are in diagnostics mode this is the end of the line: after the
484 // diagnostics are run the process will invariably exit.
485 if (command_line
.HasSwitch(switches::kDiagnostics
)) {
486 diagnostics::DiagnosticsWriter::FormatType format
=
487 diagnostics::DiagnosticsWriter::HUMAN
;
488 if (command_line
.HasSwitch(switches::kDiagnosticsFormat
)) {
489 std::string format_str
=
490 command_line
.GetSwitchValueASCII(switches::kDiagnosticsFormat
);
491 if (format_str
== "machine") {
492 format
= diagnostics::DiagnosticsWriter::MACHINE
;
493 } else if (format_str
== "log") {
494 format
= diagnostics::DiagnosticsWriter::LOG
;
496 DCHECK_EQ("human", format_str
);
500 diagnostics::DiagnosticsWriter
writer(format
);
501 *exit_code
= diagnostics::DiagnosticsController::GetInstance()->Run(
502 command_line
, &writer
);
503 diagnostics::DiagnosticsController::GetInstance()->ClearResults();
508 #if defined(OS_CHROMEOS)
509 // Initialize primary user homedir (in multi-profile session) as it may be
510 // passed as a command line switch.
511 base::FilePath homedir
;
512 if (command_line
.HasSwitch(chromeos::switches::kHomedir
)) {
513 homedir
= base::FilePath(
514 command_line
.GetSwitchValueASCII(chromeos::switches::kHomedir
));
515 PathService::OverrideAndCreateIfNeeded(
516 base::DIR_HOME
, homedir
, true, false);
519 // If we are recovering from a crash on ChromeOS, then we will do some
520 // recovery using the diagnostics module, and then continue on. We fake up a
521 // command line to tell it that we want it to recover, and to preserve the
522 // original command line.
523 if (command_line
.HasSwitch(chromeos::switches::kLoginUser
) ||
524 command_line
.HasSwitch(switches::kDiagnosticsRecovery
)) {
525 // The statistics subsystem needs get initialized soon enough for the
526 // statistics to be collected. It's safe to call this more than once.
527 base::StatisticsRecorder::Initialize();
529 base::CommandLine
interim_command_line(command_line
.GetProgram());
530 const char* const kSwitchNames
[] = {switches::kUserDataDir
, };
531 interim_command_line
.CopySwitchesFrom(
532 command_line
, kSwitchNames
, arraysize(kSwitchNames
));
533 interim_command_line
.AppendSwitch(switches::kDiagnostics
);
534 interim_command_line
.AppendSwitch(switches::kDiagnosticsRecovery
);
536 diagnostics::DiagnosticsWriter::FormatType format
=
537 diagnostics::DiagnosticsWriter::LOG
;
538 if (command_line
.HasSwitch(switches::kDiagnosticsFormat
)) {
539 std::string format_str
=
540 command_line
.GetSwitchValueASCII(switches::kDiagnosticsFormat
);
541 if (format_str
== "machine") {
542 format
= diagnostics::DiagnosticsWriter::MACHINE
;
543 } else if (format_str
== "human") {
544 format
= diagnostics::DiagnosticsWriter::HUMAN
;
546 DCHECK_EQ("log", format_str
);
550 diagnostics::DiagnosticsWriter
writer(format
);
551 int diagnostics_exit_code
=
552 diagnostics::DiagnosticsController::GetInstance()->Run(command_line
,
554 if (diagnostics_exit_code
) {
555 // Diagnostics has failed somehow, so we exit.
556 *exit_code
= diagnostics_exit_code
;
560 // Now we run the actual recovery tasks.
561 int recovery_exit_code
=
562 diagnostics::DiagnosticsController::GetInstance()->RunRecovery(
563 command_line
, &writer
);
565 if (recovery_exit_code
) {
566 // Recovery has failed somehow, so we exit.
567 *exit_code
= recovery_exit_code
;
570 } else { // Not running diagnostics or recovery.
571 diagnostics::DiagnosticsController::GetInstance()->RecordRegularStartup();
575 content::SetContentClient(&chrome_content_client_
);
580 #if defined(OS_MACOSX)
581 void ChromeMainDelegate::InitMacCrashReporter(
582 const base::CommandLine
& command_line
,
583 const std::string
& process_type
) {
584 // TODO(mark): Right now, InitializeCrashpad() needs to be called after
585 // CommandLine::Init() and chrome::RegisterPathProvider(). Ideally, Crashpad
586 // initialization could occur sooner, preferably even before the framework
587 // dylib is even loaded, to catch potential early crashes.
588 crash_reporter::InitializeCrashpad(process_type
);
590 const bool browser_process
= process_type
.empty();
591 if (!browser_process
) {
592 std::string metrics_client_id
=
593 command_line
.GetSwitchValueASCII(switches::kMetricsClientID
);
594 crash_keys::SetMetricsClientIdFromGUID(metrics_client_id
);
597 // Mac Chrome is packaged with a main app bundle and a helper app bundle.
598 // The main app bundle should only be used for the browser process, so it
599 // should never see a --type switch (switches::kProcessType). Likewise,
600 // the helper should always have a --type switch.
602 // This check is done this late so there is already a call to
603 // base::mac::IsBackgroundOnlyProcess(), so there is no change in
604 // startup/initialization order.
606 // The helper's Info.plist marks it as a background only app.
607 if (base::mac::IsBackgroundOnlyProcess()) {
608 CHECK(command_line
.HasSwitch(switches::kProcessType
) &&
609 !process_type
.empty())
610 << "Helper application requires --type.";
612 // In addition, some helper flavors only work with certain process types.
613 base::FilePath executable
;
614 if (PathService::Get(base::FILE_EXE
, &executable
) &&
615 executable
.value().size() >= 3) {
616 std::string last_three
=
617 executable
.value().substr(executable
.value().size() - 3);
619 if (last_three
== " EH") {
620 CHECK(process_type
== switches::kPluginProcess
||
621 process_type
== switches::kUtilityProcess
)
622 << "Executable-heap process requires --type="
623 << switches::kPluginProcess
<< " or "
624 << switches::kUtilityProcess
<< ", saw " << process_type
;
625 } else if (last_three
== " NP") {
626 #if !defined(DISABLE_NACL)
627 CHECK_EQ(switches::kNaClLoaderProcess
, process_type
)
628 << "Non-PIE process requires --type="
629 << switches::kNaClLoaderProcess
<< ", saw " << process_type
;
632 #if defined(DISABLE_NACL)
633 CHECK(process_type
!= switches::kPluginProcess
)
634 << "Non-executable-heap PIE process is intolerant of --type="
635 << switches::kPluginProcess
;
637 CHECK(process_type
!= switches::kPluginProcess
&&
638 process_type
!= switches::kNaClLoaderProcess
)
639 << "Non-executable-heap PIE process is intolerant of --type="
640 << switches::kPluginProcess
<< " and "
641 << switches::kNaClLoaderProcess
<< ", saw " << process_type
;
646 CHECK(!command_line
.HasSwitch(switches::kProcessType
) &&
647 process_type
.empty())
648 << "Main application forbids --type, saw " << process_type
;
651 #endif // defined(OS_MACOSX)
653 void ChromeMainDelegate::PreSandboxStartup() {
654 const base::CommandLine
& command_line
=
655 *base::CommandLine::ForCurrentProcess();
656 std::string process_type
=
657 command_line
.GetSwitchValueASCII(switches::kProcessType
);
659 #if defined(OS_POSIX)
660 crash_reporter::SetCrashReporterClient(g_chrome_crash_client
.Pointer());
663 #if defined(OS_MACOSX)
664 // On the Mac, the child executable lives at a predefined location within
665 // the app bundle's versioned directory.
666 PathService::Override(content::CHILD_PROCESS_EXE
,
667 chrome::GetVersionedDirectory().
668 Append(chrome::kHelperProcessExecutablePath
));
670 InitMacCrashReporter(command_line
, process_type
);
674 child_process_logging::Init();
676 #if defined(ARCH_CPU_ARM_FAMILY) && (defined(OS_ANDROID) || defined(OS_LINUX))
677 // Create an instance of the CPU class to parse /proc/cpuinfo and cache
682 // Initialize the user data dir for any process type that needs it.
683 if (chrome::ProcessNeedsProfileDir(process_type
))
684 InitializeUserDataDir();
686 // Register component_updater PathProvider after DIR_USER_DATA overidden by
687 // command line flags. Maybe move the chrome PathProvider down here also?
688 component_updater::RegisterPathProvider(chrome::DIR_USER_DATA
);
690 // Enable Message Loop related state asap.
691 if (command_line
.HasSwitch(switches::kMessageLoopHistogrammer
))
692 base::MessageLoop::EnableHistogrammer(true);
694 #if !defined(OS_ANDROID)
695 // Android does InitLogging when library is loaded. Skip here.
696 logging::OldFileDeletionState file_state
=
697 logging::APPEND_TO_OLD_LOG_FILE
;
698 if (process_type
.empty()) {
699 file_state
= logging::DELETE_OLD_LOG_FILE
;
701 logging::InitChromeLogging(command_line
, file_state
);
705 // TODO(zturner): Throbber icons are still stored in chrome.dll, this can be
706 // killed once those are merged into resources.pak. See
707 // GlassBrowserFrameView::InitThrobberIcons() and http://crbug.com/368327.
708 ui::SetResourcesDataDLL(_AtlBaseModule
.GetResourceInstance());
711 if (SubprocessNeedsResourceBundle(process_type
)) {
712 // Initialize ResourceBundle which handles files loaded from external
713 // sources. The language should have been passed in to us from the
714 // browser process as a command line flag.
715 #if defined(DISABLE_NACL)
716 DCHECK(command_line
.HasSwitch(switches::kLang
) ||
717 process_type
== switches::kZygoteProcess
||
718 process_type
== switches::kGpuProcess
||
719 process_type
== switches::kPpapiBrokerProcess
||
720 process_type
== switches::kPpapiPluginProcess
);
722 DCHECK(command_line
.HasSwitch(switches::kLang
) ||
723 process_type
== switches::kZygoteProcess
||
724 process_type
== switches::kGpuProcess
||
725 process_type
== switches::kNaClLoaderProcess
||
726 process_type
== switches::kPpapiBrokerProcess
||
727 process_type
== switches::kPpapiPluginProcess
);
730 // TODO(markusheintz): The command line flag --lang is actually processed
731 // by the CommandLinePrefStore, and made available through the PrefService
732 // via the preference prefs::kApplicationLocale. The browser process uses
733 // the --lang flag to pass the value of the PrefService in here. Maybe
734 // this value could be passed in a different way.
735 const std::string locale
=
736 command_line
.GetSwitchValueASCII(switches::kLang
);
737 #if defined(OS_ANDROID)
738 // The renderer sandbox prevents us from accessing our .pak files directly.
739 // Therefore file descriptors to the .pak files that we need are passed in
740 // at process creation time.
741 int locale_pak_fd
= base::GlobalDescriptors::GetInstance()->MaybeGet(
742 kAndroidLocalePakDescriptor
);
743 CHECK(locale_pak_fd
!= -1);
744 ResourceBundle::InitSharedInstanceWithPakFileRegion(
745 base::File(locale_pak_fd
), base::MemoryMappedFile::Region::kWholeFile
);
747 int extra_pak_keys
[] = {
748 kAndroidChrome100PercentPakDescriptor
,
749 kAndroidUIResourcesPakDescriptor
,
751 for (size_t i
= 0; i
< arraysize(extra_pak_keys
); ++i
) {
753 base::GlobalDescriptors::GetInstance()->MaybeGet(extra_pak_keys
[i
]);
755 ResourceBundle::GetSharedInstance().AddDataPackFromFile(
756 base::File(pak_fd
), ui::SCALE_FACTOR_100P
);
759 base::i18n::SetICUDefaultLocale(locale
);
760 const std::string loaded_locale
= locale
;
762 const std::string loaded_locale
=
763 ui::ResourceBundle::InitSharedInstanceWithLocale(
764 locale
, NULL
, ui::ResourceBundle::LOAD_COMMON_RESOURCES
);
766 base::FilePath resources_pack_path
;
767 PathService::Get(chrome::FILE_RESOURCES_PACK
, &resources_pack_path
);
768 ResourceBundle::GetSharedInstance().AddDataPackFromPath(
769 resources_pack_path
, ui::SCALE_FACTOR_NONE
);
771 CHECK(!loaded_locale
.empty()) << "Locale could not be found for " <<
775 #if !defined(CHROME_MULTIPLE_DLL_BROWSER)
776 if (process_type
== switches::kUtilityProcess
||
777 process_type
== switches::kZygoteProcess
) {
778 ChromeContentUtilityClient::PreSandboxStartup();
781 chrome::InitializePDF();
784 #if defined(OS_POSIX) && !defined(OS_MACOSX)
785 // Zygote needs to call InitCrashReporter() in RunZygote().
786 if (process_type
!= switches::kZygoteProcess
) {
787 #if defined(OS_ANDROID)
788 if (process_type
.empty()) {
789 breakpad::InitCrashReporter(process_type
);
790 chrome::android::InitJavaExceptionReporter();
792 breakpad::InitNonBrowserCrashReporterForAndroid(process_type
);
794 #else // !defined(OS_ANDROID)
795 breakpad::InitCrashReporter(process_type
);
796 #endif // defined(OS_ANDROID)
798 #endif // defined(OS_POSIX) && !defined(OS_MACOSX)
800 // After all the platform Breakpads have been initialized, store the command
801 // line for crash reporting.
802 crash_keys::SetSwitchesFromCommandLine(&command_line
);
805 void ChromeMainDelegate::SandboxInitialized(const std::string
& process_type
) {
806 // Note: If you are adding a new process type below, be sure to adjust the
807 // AdjustLinuxOOMScore function too.
808 #if defined(OS_LINUX)
809 AdjustLinuxOOMScore(process_type
);
812 SuppressWindowsErrorDialogs();
815 #if defined(CHROME_MULTIPLE_DLL_CHILD) || !defined(CHROME_MULTIPLE_DLL_BROWSER)
816 #if defined(ENABLE_REMOTING)
817 ChromeContentClient::SetRemotingEntryFunctions(
818 remoting::PPP_GetInterface
,
819 remoting::PPP_InitializeModule
,
820 remoting::PPP_ShutdownModule
);
822 #if !defined(DISABLE_NACL)
823 ChromeContentClient::SetNaClEntryFunctions(
824 nacl_plugin::PPP_GetInterface
,
825 nacl_plugin::PPP_InitializeModule
,
826 nacl_plugin::PPP_ShutdownModule
);
828 #if defined(ENABLE_PLUGINS)
829 ChromeContentClient::SetPDFEntryFunctions(
830 chrome_pdf::PPP_GetInterface
,
831 chrome_pdf::PPP_InitializeModule
,
832 chrome_pdf::PPP_ShutdownModule
);
837 int ChromeMainDelegate::RunProcess(
838 const std::string
& process_type
,
839 const content::MainFunctionParams
& main_function_params
) {
840 // ANDROID doesn't support "service", so no ServiceProcessMain, and arraysize
841 // doesn't support empty array. So we comment out the block for Android.
842 #if !defined(OS_ANDROID)
843 static const MainFunction kMainFunctions
[] = {
844 #if defined(ENABLE_PRINT_PREVIEW) && !defined(CHROME_MULTIPLE_DLL_CHILD)
845 { switches::kServiceProcess
, ServiceProcessMain
},
848 #if defined(OS_MACOSX)
849 { switches::kRelauncherProcess
,
850 mac_relauncher::internal::RelauncherMain
},
853 // This entry is not needed on Linux, where the NaCl loader
854 // process is launched via nacl_helper instead.
855 #if !defined(DISABLE_NACL) && !defined(CHROME_MULTIPLE_DLL_BROWSER) && \
857 { switches::kNaClLoaderProcess
, NaClMain
},
859 { "<invalid>", NULL
}, // To avoid constant array of size 0
860 // when DISABLE_NACL and CHROME_MULTIPLE_DLL_CHILD
861 #endif // DISABLE_NACL
864 for (size_t i
= 0; i
< arraysize(kMainFunctions
); ++i
) {
865 if (process_type
== kMainFunctions
[i
].name
)
866 return kMainFunctions
[i
].function(main_function_params
);
873 void ChromeMainDelegate::ProcessExiting(const std::string
& process_type
) {
874 if (SubprocessNeedsResourceBundle(process_type
))
875 ResourceBundle::CleanupSharedInstance();
876 #if !defined(OS_ANDROID)
877 logging::CleanupChromeLogging();
879 // Android doesn't use InitChromeLogging, so we close the log file manually.
880 logging::CloseLogFile();
881 #endif // !defined(OS_ANDROID)
884 RemoveCloseHandleHooks();
888 #if defined(OS_MACOSX)
889 bool ChromeMainDelegate::ProcessRegistersWithSystemProcess(
890 const std::string
& process_type
) {
891 #if defined(DISABLE_NACL)
894 return process_type
== switches::kNaClLoaderProcess
;
898 bool ChromeMainDelegate::ShouldSendMachPort(const std::string
& process_type
) {
899 return process_type
!= switches::kRelauncherProcess
&&
900 process_type
!= switches::kServiceProcess
;
903 bool ChromeMainDelegate::DelaySandboxInitialization(
904 const std::string
& process_type
) {
905 #if !defined(DISABLE_NACL)
906 // NaClLoader does this in NaClMainPlatformDelegate::EnableSandbox().
907 // No sandbox needed for relauncher.
908 if (process_type
== switches::kNaClLoaderProcess
)
911 return process_type
== switches::kRelauncherProcess
;
913 #elif defined(OS_POSIX) && !defined(OS_ANDROID)
914 void ChromeMainDelegate::ZygoteStarting(
915 ScopedVector
<content::ZygoteForkDelegate
>* delegates
) {
916 #if !defined(DISABLE_NACL)
917 nacl::AddNaClZygoteForkDelegates(delegates
);
921 void ChromeMainDelegate::ZygoteForked() {
922 Profiling::ProcessStarted();
923 if (Profiling::BeingProfiled()) {
924 base::debug::RestartProfilingAfterFork();
925 SetUpProfilingShutdownHandler();
928 // Needs to be called after we have chrome::DIR_USER_DATA. BrowserMain sets
929 // this up for the browser process in a different manner.
930 const base::CommandLine
* command_line
=
931 base::CommandLine::ForCurrentProcess();
932 std::string process_type
=
933 command_line
->GetSwitchValueASCII(switches::kProcessType
);
934 breakpad::InitCrashReporter(process_type
);
936 // Reset the command line for the newly spawned process.
937 crash_keys::SetSwitchesFromCommandLine(command_line
);
942 content::ContentBrowserClient
*
943 ChromeMainDelegate::CreateContentBrowserClient() {
944 #if defined(CHROME_MULTIPLE_DLL_CHILD)
947 return g_chrome_content_browser_client
.Pointer();
951 content::ContentPluginClient
* ChromeMainDelegate::CreateContentPluginClient() {
952 #if defined(CHROME_MULTIPLE_DLL_BROWSER)
955 return g_chrome_content_plugin_client
.Pointer();
959 content::ContentRendererClient
*
960 ChromeMainDelegate::CreateContentRendererClient() {
961 #if defined(CHROME_MULTIPLE_DLL_BROWSER)
964 return g_chrome_content_renderer_client
.Pointer();
968 content::ContentUtilityClient
*
969 ChromeMainDelegate::CreateContentUtilityClient() {
970 #if defined(CHROME_MULTIPLE_DLL_BROWSER)
973 return g_chrome_content_utility_client
.Pointer();
977 bool ChromeMainDelegate::ShouldEnableProfilerRecording() {
978 switch (chrome::VersionInfo::GetChannel()) {
979 case chrome::VersionInfo::CHANNEL_UNKNOWN
:
980 case chrome::VersionInfo::CHANNEL_CANARY
:
982 case chrome::VersionInfo::CHANNEL_DEV
:
983 case chrome::VersionInfo::CHANNEL_BETA
:
984 case chrome::VersionInfo::CHANNEL_STABLE
:
986 // Don't enable instrumentation.