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/process/process_info.h"
19 #include "base/strings/string_util.h"
20 #include "base/time/time.h"
21 #include "base/trace_event/trace_event_impl.h"
22 #include "build/build_config.h"
23 #include "chrome/browser/chrome_content_browser_client.h"
24 #include "chrome/browser/defaults.h"
25 #include "chrome/common/channel_info.h"
26 #include "chrome/common/chrome_constants.h"
27 #include "chrome/common/chrome_content_client.h"
28 #include "chrome/common/chrome_paths.h"
29 #include "chrome/common/chrome_paths_internal.h"
30 #include "chrome/common/chrome_result_codes.h"
31 #include "chrome/common/chrome_switches.h"
32 #include "chrome/common/crash_keys.h"
33 #include "chrome/common/logging_chrome.h"
34 #include "chrome/common/profiling.h"
35 #include "chrome/common/switch_utils.h"
36 #include "chrome/common/trace_event_args_whitelist.h"
37 #include "chrome/common/url_constants.h"
38 #include "chrome/plugin/chrome_content_plugin_client.h"
39 #include "chrome/renderer/chrome_content_renderer_client.h"
40 #include "chrome/utility/chrome_content_utility_client.h"
41 #include "components/component_updater/component_updater_paths.h"
42 #include "components/content_settings/core/common/content_settings_pattern.h"
43 #include "components/startup_metric_utils/startup_metric_utils.h"
44 #include "components/version_info/version_info.h"
45 #include "content/public/common/content_client.h"
46 #include "content/public/common/content_paths.h"
47 #include "extensions/common/constants.h"
48 #include "ui/base/ui_base_switches.h"
54 #include "chrome/app/close_handle_hook_win.h"
55 #include "chrome/common/child_process_logging.h"
56 #include "chrome/common/v8_breakpad_support_win.h"
57 #include "sandbox/win/src/sandbox.h"
58 #include "ui/base/resource/resource_bundle_win.h"
61 #if defined(OS_MACOSX)
62 #include "base/mac/foundation_util.h"
63 #include "chrome/app/chrome_main_mac.h"
64 #include "chrome/browser/mac/relauncher.h"
65 #include "chrome/common/mac/cfbundle_blocker.h"
66 #include "chrome/common/mac/objc_zombie.h"
67 #include "components/crash/content/app/crashpad_mac.h"
68 #include "ui/base/l10n/l10n_util_mac.h"
74 #include "chrome/app/chrome_crash_reporter_client.h"
75 #include "components/crash/content/app/crash_reporter_client.h"
78 #if !defined(DISABLE_NACL) && defined(OS_LINUX)
79 #include "components/nacl/common/nacl_paths.h"
80 #include "components/nacl/zygote/nacl_fork_delegate_linux.h"
83 #if defined(OS_CHROMEOS)
84 #include "base/sys_info.h"
85 #include "chrome/browser/chromeos/boot_times_recorder.h"
86 #include "chromeos/chromeos_paths.h"
87 #include "chromeos/chromeos_switches.h"
90 #if defined(OS_ANDROID)
91 #include "chrome/browser/android/java_exception_reporter.h"
92 #include "chrome/common/descriptors_android.h"
94 // Diagnostics is only available on non-android platforms.
95 #include "chrome/browser/diagnostics/diagnostics_controller.h"
96 #include "chrome/browser/diagnostics/diagnostics_writer.h"
102 #include "ui/base/x/x11_util.h"
105 #if defined(OS_POSIX) && !defined(OS_MACOSX)
106 #include "components/crash/content/app/breakpad_linux.h"
109 #if defined(OS_LINUX)
110 #include "base/environment.h"
113 #if defined(OS_MACOSX) || defined(OS_WIN)
114 #include "chrome/browser/policy/policy_path_parser.h"
117 #if !defined(DISABLE_NACL)
118 #include "components/nacl/common/nacl_switches.h"
119 #include "components/nacl/renderer/plugin/ppapi_entrypoints.h"
122 #if defined(ENABLE_PLUGINS) && (defined(CHROME_MULTIPLE_DLL_CHILD) || \
123 !defined(CHROME_MULTIPLE_DLL_BROWSER))
127 #if !defined(CHROME_MULTIPLE_DLL_BROWSER)
128 #include "chrome/child/pdf_child_init.h"
130 base::LazyInstance
<ChromeContentRendererClient
>
131 g_chrome_content_renderer_client
= LAZY_INSTANCE_INITIALIZER
;
132 base::LazyInstance
<ChromeContentUtilityClient
>
133 g_chrome_content_utility_client
= LAZY_INSTANCE_INITIALIZER
;
134 base::LazyInstance
<ChromeContentPluginClient
>
135 g_chrome_content_plugin_client
= LAZY_INSTANCE_INITIALIZER
;
138 #if !defined(CHROME_MULTIPLE_DLL_CHILD)
139 base::LazyInstance
<ChromeContentBrowserClient
> g_chrome_content_browser_client
=
140 LAZY_INSTANCE_INITIALIZER
;
143 #if defined(OS_POSIX)
144 base::LazyInstance
<ChromeCrashReporterClient
>::Leaky g_chrome_crash_client
=
145 LAZY_INSTANCE_INITIALIZER
;
148 extern int NaClMain(const content::MainFunctionParams
&);
149 extern int ServiceProcessMain(const content::MainFunctionParams
&);
154 // Early versions of Chrome incorrectly registered a chromehtml: URL handler,
155 // which gives us nothing but trouble. Avoid launching chrome this way since
156 // some apps fail to properly escape arguments.
157 bool HasDeprecatedArguments(const base::string16
& command_line
) {
158 const wchar_t kChromeHtml
[] = L
"chromehtml:";
159 base::string16 command_line_lower
= base::ToLowerASCII(command_line
);
160 // We are only searching for ASCII characters so this is OK.
161 return (command_line_lower
.find(kChromeHtml
) != base::string16::npos
);
164 // If we try to access a path that is not currently available, we want the call
165 // to fail rather than show an error dialog.
166 void SuppressWindowsErrorDialogs() {
167 UINT new_flags
= SEM_FAILCRITICALERRORS
|
168 SEM_NOOPENFILEERRORBOX
;
170 // Preserve existing error mode.
171 UINT existing_flags
= SetErrorMode(new_flags
);
172 SetErrorMode(existing_flags
| new_flags
);
175 bool IsSandboxedProcess() {
176 typedef bool (*IsSandboxedProcessFunc
)();
177 IsSandboxedProcessFunc is_sandboxed_process_func
=
178 reinterpret_cast<IsSandboxedProcessFunc
>(
179 GetProcAddress(GetModuleHandle(NULL
), "IsSandboxedProcess"));
180 return is_sandboxed_process_func
&& is_sandboxed_process_func();
183 #endif // defined(OS_WIN)
185 #if defined(OS_LINUX)
186 static void AdjustLinuxOOMScore(const std::string
& process_type
) {
187 // Browsers and zygotes should still be killable, but killed last.
188 const int kZygoteScore
= 0;
189 // The minimum amount to bump a score by. This is large enough that
190 // even if it's translated into the old values, it will still go up
192 const int kScoreBump
= 100;
193 // This is the lowest score that renderers and extensions start with
194 // in the OomPriorityManager.
195 const int kRendererScore
= chrome::kLowestRendererOomScore
;
196 // For "miscellaneous" things, we want them after renderers,
197 // but before plugins.
198 const int kMiscScore
= kRendererScore
- kScoreBump
;
199 // We want plugins to die after the renderers.
200 const int kPluginScore
= kMiscScore
- kScoreBump
;
203 DCHECK(kMiscScore
> 0);
204 DCHECK(kPluginScore
> 0);
206 if (process_type
== switches::kPluginProcess
||
207 process_type
== switches::kPpapiPluginProcess
) {
208 score
= kPluginScore
;
209 } else if (process_type
== switches::kPpapiBrokerProcess
) {
210 // The broker should be killed before the PPAPI plugin.
211 score
= kPluginScore
+ kScoreBump
;
212 } else if (process_type
== switches::kUtilityProcess
||
213 process_type
== switches::kGpuProcess
||
214 process_type
== switches::kServiceProcess
) {
217 } else if (process_type
== switches::kNaClLoaderProcess
||
218 process_type
== switches::kNaClLoaderNonSfiProcess
) {
219 score
= kPluginScore
;
221 } else if (process_type
== switches::kZygoteProcess
||
222 process_type
.empty()) {
223 // For zygotes and unlabeled process types, we want to still make
224 // them killable by the OOM killer.
225 score
= kZygoteScore
;
226 } else if (process_type
== switches::kRendererProcess
) {
227 LOG(WARNING
) << "process type 'renderer' "
228 << "should be created through the zygote.";
229 // When debugging, this process type can end up being run directly, but
230 // this isn't the typical path for assigning the OOM score for it. Still,
231 // we want to assign a score that is somewhat representative for debugging.
232 score
= kRendererScore
;
234 NOTREACHED() << "Unknown process type";
237 base::AdjustOOMScore(base::GetCurrentProcId(), score
);
239 #endif // defined(OS_LINUX)
241 // Returns true if this subprocess type needs the ResourceBundle initialized
242 // and resources loaded.
243 bool SubprocessNeedsResourceBundle(const std::string
& process_type
) {
245 #if defined(OS_WIN) || defined(OS_MACOSX)
246 // Windows needs resources for the default/null plugin.
247 // Mac needs them for the plugin process name.
248 process_type
== switches::kPluginProcess
||
250 #if defined(OS_POSIX) && !defined(OS_MACOSX)
251 // The zygote process opens the resources for the renderers.
252 process_type
== switches::kZygoteProcess
||
254 #if defined(OS_MACOSX)
255 // Mac needs them too for scrollbar related images and for sandbox
257 #if !defined(DISABLE_NACL)
258 process_type
== switches::kNaClLoaderProcess
||
260 process_type
== switches::kPpapiPluginProcess
||
261 process_type
== switches::kPpapiBrokerProcess
||
262 process_type
== switches::kGpuProcess
||
264 process_type
== switches::kRendererProcess
||
265 process_type
== switches::kUtilityProcess
;
268 #if defined(OS_POSIX)
269 // Check for --version and --product-version; return true if we encountered
270 // one of these switches and should exit now.
271 bool HandleVersionSwitches(const base::CommandLine
& command_line
) {
272 #if !defined(OS_MACOSX)
273 if (command_line
.HasSwitch(switches::kProductVersion
)) {
274 printf("%s\n", version_info::GetVersionNumber().c_str());
279 if (command_line
.HasSwitch(switches::kVersion
)) {
281 version_info::GetProductName().c_str(),
282 version_info::GetVersionNumber().c_str(),
283 chrome::GetChannelString().c_str());
290 #if !defined(OS_MACOSX) && !defined(OS_CHROMEOS)
291 // Show the man page if --help or -h is on the command line.
292 void HandleHelpSwitches(const base::CommandLine
& command_line
) {
293 if (command_line
.HasSwitch(switches::kHelp
) ||
294 command_line
.HasSwitch(switches::kHelpShort
)) {
295 base::FilePath
binary(command_line
.argv()[0]);
296 execlp("man", "man", binary
.BaseName().value().c_str(), NULL
);
297 PLOG(FATAL
) << "execlp failed";
302 #if !defined(OS_MACOSX) && !defined(OS_ANDROID)
303 void SIGTERMProfilingShutdown(int signal
) {
305 struct sigaction sigact
;
306 memset(&sigact
, 0, sizeof(sigact
));
307 sigact
.sa_handler
= SIG_DFL
;
308 CHECK(sigaction(SIGTERM
, &sigact
, NULL
) == 0);
312 void SetUpProfilingShutdownHandler() {
313 struct sigaction sigact
;
314 sigact
.sa_handler
= SIGTERMProfilingShutdown
;
315 sigact
.sa_flags
= SA_RESETHAND
;
316 sigemptyset(&sigact
.sa_mask
);
317 CHECK(sigaction(SIGTERM
, &sigact
, NULL
) == 0);
319 #endif // !defined(OS_MACOSX) && !defined(OS_ANDROID)
323 struct MainFunction
{
325 int (*function
)(const content::MainFunctionParams
&);
328 // Initializes the user data dir. Must be called before InitializeLocalState().
329 void InitializeUserDataDir() {
330 base::CommandLine
* command_line
= base::CommandLine::ForCurrentProcess();
331 base::FilePath user_data_dir
=
332 command_line
->GetSwitchValuePath(switches::kUserDataDir
);
333 std::string process_type
=
334 command_line
->GetSwitchValueASCII(switches::kProcessType
);
336 #if defined(OS_LINUX)
337 // On Linux, Chrome does not support running multiple copies under different
338 // DISPLAYs, so the profile directory can be specified in the environment to
339 // support the virtual desktop use-case.
340 if (user_data_dir
.empty()) {
341 std::string user_data_dir_string
;
342 scoped_ptr
<base::Environment
> environment(base::Environment::Create());
343 if (environment
->GetVar("CHROME_USER_DATA_DIR", &user_data_dir_string
) &&
344 base::IsStringUTF8(user_data_dir_string
)) {
345 user_data_dir
= base::FilePath::FromUTF8Unsafe(user_data_dir_string
);
349 #if defined(OS_MACOSX) || defined(OS_WIN)
350 policy::path_parser::CheckUserDataDirPolicy(&user_data_dir
);
353 // On Windows, trailing separators leave Chrome in a bad state.
354 // See crbug.com/464616.
355 if (user_data_dir
.EndsWithSeparator())
356 user_data_dir
= user_data_dir
.StripTrailingSeparators();
358 const bool specified_directory_was_invalid
= !user_data_dir
.empty() &&
359 !PathService::OverrideAndCreateIfNeeded(chrome::DIR_USER_DATA
,
360 user_data_dir
, false, true);
361 // Save inaccessible or invalid paths so the user may be prompted later.
362 if (specified_directory_was_invalid
)
363 chrome::SetInvalidSpecifiedUserDataDir(user_data_dir
);
365 // Warn and fail early if the process fails to get a user data directory.
366 if (!PathService::Get(chrome::DIR_USER_DATA
, &user_data_dir
)) {
367 // If an invalid command-line or policy override was specified, the user
368 // will be given an error with that value. Otherwise, use the directory
369 // returned by PathService (or the fallback default directory) in the error.
370 if (!specified_directory_was_invalid
) {
371 // PathService::Get() returns false and yields an empty path if it fails
372 // to create DIR_USER_DATA. Retrieve the default value manually to display
373 // a more meaningful error to the user in that case.
374 if (user_data_dir
.empty())
375 chrome::GetDefaultUserDataDirectory(&user_data_dir
);
376 chrome::SetInvalidSpecifiedUserDataDir(user_data_dir
);
379 // The browser process (which is identified by an empty |process_type|) will
380 // handle the error later; other processes that need the dir crash here.
381 CHECK(process_type
.empty()) << "Unable to get the user data directory "
382 << "for process type: " << process_type
;
385 // Append the fallback user data directory to the commandline. Otherwise,
386 // child or service processes will attempt to use the invalid directory.
387 if (specified_directory_was_invalid
)
388 command_line
->AppendSwitchPath(switches::kUserDataDir
, user_data_dir
);
391 #if !defined(OS_ANDROID)
392 void InitLogging(const std::string
& process_type
) {
393 logging::OldFileDeletionState file_state
=
394 logging::APPEND_TO_OLD_LOG_FILE
;
395 if (process_type
.empty()) {
396 file_state
= logging::DELETE_OLD_LOG_FILE
;
398 const base::CommandLine
& command_line
=
399 *base::CommandLine::ForCurrentProcess();
400 logging::InitChromeLogging(command_line
, file_state
);
406 ChromeMainDelegate::ChromeMainDelegate() {
407 #if defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
408 // Record the startup process creation time on supported platforms.
409 startup_metric_utils::RecordStartupProcessCreationTime(
410 base::CurrentProcessInfo::CreationTime());
413 // On Android the main entry point time is the time when the Java code starts.
414 // This happens before the shared library containing this code is even loaded.
415 // The Java startup code has recorded that time, but the C++ code can't fetch it
416 // from the Java side until it has initialized the JNI. See
417 // ChromeMainDelegateAndroid.
418 #if !defined(OS_ANDROID)
419 startup_metric_utils::RecordMainEntryPointTime(base::Time::Now());
423 ChromeMainDelegate::~ChromeMainDelegate() {
426 bool ChromeMainDelegate::BasicStartupComplete(int* exit_code
) {
427 #if defined(OS_CHROMEOS)
428 chromeos::BootTimesRecorder::Get()->SaveChromeMainStats();
431 const base::CommandLine
& command_line
=
432 *base::CommandLine::ForCurrentProcess();
436 // Browser should not be sandboxed.
437 const bool is_browser
= !command_line
.HasSwitch(switches::kProcessType
);
438 if (is_browser
&& IsSandboxedProcess()) {
439 *exit_code
= chrome::RESULT_CODE_INVALID_SANDBOX_STATE
;
444 #if defined(OS_MACOSX)
445 // Give the browser process a longer treadmill, since crashes
446 // there have more impact.
447 const bool is_browser
= !command_line
.HasSwitch(switches::kProcessType
);
448 ObjcEvilDoers::ZombieEnable(true, is_browser
? 10000 : 1000);
450 SetUpBundleOverrides();
451 chrome::common::mac::EnableCFBundleBlocker();
454 Profiling::ProcessStarted();
456 base::trace_event::TraceLog::GetInstance()->SetArgumentFilterPredicate(
457 base::Bind(&IsTraceEventArgsWhitelisted
));
460 v8_breakpad_support::SetUp();
463 #if defined(OS_POSIX)
464 if (HandleVersionSwitches(command_line
)) {
466 return true; // Got a --version switch; exit with a success error code.
468 #if !defined(OS_MACOSX) && !defined(OS_CHROMEOS)
469 // This will directly exit if the user asked for help.
470 HandleHelpSwitches(command_line
);
475 // Must do this before any other usage of command line!
476 if (HasDeprecatedArguments(command_line
.GetCommandLineString())) {
481 InstallHandleHooks();
484 chrome::RegisterPathProvider();
485 #if defined(OS_CHROMEOS)
486 chromeos::RegisterPathProvider();
488 #if !defined(DISABLE_NACL) && defined(OS_LINUX)
489 nacl::RegisterPathProvider();
492 ContentSettingsPattern::SetNonWildcardDomainNonPortScheme(
493 extensions::kExtensionScheme
);
495 // No support for ANDROID yet as DiagnosticsController needs wchar support.
496 // TODO(gspencer): That's not true anymore, or at least there are no w-string
497 // references anymore. Not sure if that means this can be enabled on Android or
498 // not though. As there is no easily accessible command line on Android, I'm
499 // not sure this is a big deal.
500 #if !defined(OS_ANDROID) && !defined(CHROME_MULTIPLE_DLL_CHILD)
501 // If we are in diagnostics mode this is the end of the line: after the
502 // diagnostics are run the process will invariably exit.
503 if (command_line
.HasSwitch(switches::kDiagnostics
)) {
504 diagnostics::DiagnosticsWriter::FormatType format
=
505 diagnostics::DiagnosticsWriter::HUMAN
;
506 if (command_line
.HasSwitch(switches::kDiagnosticsFormat
)) {
507 std::string format_str
=
508 command_line
.GetSwitchValueASCII(switches::kDiagnosticsFormat
);
509 if (format_str
== "machine") {
510 format
= diagnostics::DiagnosticsWriter::MACHINE
;
511 } else if (format_str
== "log") {
512 format
= diagnostics::DiagnosticsWriter::LOG
;
514 DCHECK_EQ("human", format_str
);
518 diagnostics::DiagnosticsWriter
writer(format
);
519 *exit_code
= diagnostics::DiagnosticsController::GetInstance()->Run(
520 command_line
, &writer
);
521 diagnostics::DiagnosticsController::GetInstance()->ClearResults();
526 #if defined(OS_CHROMEOS)
527 // Initialize primary user homedir (in multi-profile session) as it may be
528 // passed as a command line switch.
529 base::FilePath homedir
;
530 if (command_line
.HasSwitch(chromeos::switches::kHomedir
)) {
531 homedir
= base::FilePath(
532 command_line
.GetSwitchValueASCII(chromeos::switches::kHomedir
));
533 PathService::OverrideAndCreateIfNeeded(
534 base::DIR_HOME
, homedir
, true, false);
537 // If we are recovering from a crash on ChromeOS, then we will do some
538 // recovery using the diagnostics module, and then continue on. We fake up a
539 // command line to tell it that we want it to recover, and to preserve the
540 // original command line.
541 if (command_line
.HasSwitch(chromeos::switches::kLoginUser
) ||
542 command_line
.HasSwitch(switches::kDiagnosticsRecovery
)) {
543 // The statistics subsystem needs get initialized soon enough for the
544 // statistics to be collected. It's safe to call this more than once.
545 base::StatisticsRecorder::Initialize();
547 base::CommandLine
interim_command_line(command_line
.GetProgram());
548 const char* const kSwitchNames
[] = {switches::kUserDataDir
, };
549 interim_command_line
.CopySwitchesFrom(
550 command_line
, kSwitchNames
, arraysize(kSwitchNames
));
551 interim_command_line
.AppendSwitch(switches::kDiagnostics
);
552 interim_command_line
.AppendSwitch(switches::kDiagnosticsRecovery
);
554 diagnostics::DiagnosticsWriter::FormatType format
=
555 diagnostics::DiagnosticsWriter::LOG
;
556 if (command_line
.HasSwitch(switches::kDiagnosticsFormat
)) {
557 std::string format_str
=
558 command_line
.GetSwitchValueASCII(switches::kDiagnosticsFormat
);
559 if (format_str
== "machine") {
560 format
= diagnostics::DiagnosticsWriter::MACHINE
;
561 } else if (format_str
== "human") {
562 format
= diagnostics::DiagnosticsWriter::HUMAN
;
564 DCHECK_EQ("log", format_str
);
568 diagnostics::DiagnosticsWriter
writer(format
);
569 int diagnostics_exit_code
=
570 diagnostics::DiagnosticsController::GetInstance()->Run(command_line
,
572 if (diagnostics_exit_code
) {
573 // Diagnostics has failed somehow, so we exit.
574 *exit_code
= diagnostics_exit_code
;
578 // Now we run the actual recovery tasks.
579 int recovery_exit_code
=
580 diagnostics::DiagnosticsController::GetInstance()->RunRecovery(
581 command_line
, &writer
);
583 if (recovery_exit_code
) {
584 // Recovery has failed somehow, so we exit.
585 *exit_code
= recovery_exit_code
;
588 } else { // Not running diagnostics or recovery.
589 diagnostics::DiagnosticsController::GetInstance()->RecordRegularStartup();
593 content::SetContentClient(&chrome_content_client_
);
598 #if defined(OS_MACOSX)
599 void ChromeMainDelegate::InitMacCrashReporter(
600 const base::CommandLine
& command_line
,
601 const std::string
& process_type
) {
602 // TODO(mark): Right now, InitializeCrashpad() needs to be called after
603 // CommandLine::Init() and chrome::RegisterPathProvider(). Ideally, Crashpad
604 // initialization could occur sooner, preferably even before the framework
605 // dylib is even loaded, to catch potential early crashes.
606 crash_reporter::InitializeCrashpad(process_type
);
608 const bool browser_process
= process_type
.empty();
609 if (!browser_process
) {
610 std::string metrics_client_id
=
611 command_line
.GetSwitchValueASCII(switches::kMetricsClientID
);
612 crash_keys::SetMetricsClientIdFromGUID(metrics_client_id
);
615 // Mac Chrome is packaged with a main app bundle and a helper app bundle.
616 // The main app bundle should only be used for the browser process, so it
617 // should never see a --type switch (switches::kProcessType). Likewise,
618 // the helper should always have a --type switch.
620 // This check is done this late so there is already a call to
621 // base::mac::IsBackgroundOnlyProcess(), so there is no change in
622 // startup/initialization order.
624 // The helper's Info.plist marks it as a background only app.
625 if (base::mac::IsBackgroundOnlyProcess()) {
626 CHECK(command_line
.HasSwitch(switches::kProcessType
) &&
627 !process_type
.empty())
628 << "Helper application requires --type.";
630 CHECK(!command_line
.HasSwitch(switches::kProcessType
) &&
631 process_type
.empty())
632 << "Main application forbids --type, saw " << process_type
;
635 #endif // defined(OS_MACOSX)
637 void ChromeMainDelegate::PreSandboxStartup() {
638 const base::CommandLine
& command_line
=
639 *base::CommandLine::ForCurrentProcess();
640 std::string process_type
=
641 command_line
.GetSwitchValueASCII(switches::kProcessType
);
643 #if defined(OS_POSIX)
644 crash_reporter::SetCrashReporterClient(g_chrome_crash_client
.Pointer());
647 #if defined(OS_MACOSX)
648 // On the Mac, the child executable lives at a predefined location within
649 // the app bundle's versioned directory.
650 PathService::Override(content::CHILD_PROCESS_EXE
,
651 chrome::GetVersionedDirectory().
652 Append(chrome::kHelperProcessExecutablePath
));
654 InitMacCrashReporter(command_line
, process_type
);
658 child_process_logging::Init();
660 #if defined(ARCH_CPU_ARM_FAMILY) && (defined(OS_ANDROID) || defined(OS_LINUX))
661 // Create an instance of the CPU class to parse /proc/cpuinfo and cache
666 // Initialize the user data dir for any process type that needs it.
667 if (chrome::ProcessNeedsProfileDir(process_type
))
668 InitializeUserDataDir();
670 // Register component_updater PathProvider after DIR_USER_DATA overidden by
671 // command line flags. Maybe move the chrome PathProvider down here also?
672 component_updater::RegisterPathProvider(chrome::DIR_USER_DATA
);
674 // Enable Message Loop related state asap.
675 if (command_line
.HasSwitch(switches::kMessageLoopHistogrammer
))
676 base::MessageLoop::EnableHistogrammer(true);
678 #if !defined(OS_ANDROID) && !defined(OS_WIN)
679 // Android does InitLogging when library is loaded. Skip here.
680 // For windows we call InitLogging when the sandbox is initialized.
681 InitLogging(process_type
);
685 // TODO(zturner): Throbber icons are still stored in chrome.dll, this can be
686 // killed once those are merged into resources.pak. See
687 // GlassBrowserFrameView::InitThrobberIcons() and http://crbug.com/368327.
688 ui::SetResourcesDataDLL(_AtlBaseModule
.GetResourceInstance());
691 if (SubprocessNeedsResourceBundle(process_type
)) {
692 // Initialize ResourceBundle which handles files loaded from external
693 // sources. The language should have been passed in to us from the
694 // browser process as a command line flag.
695 #if defined(DISABLE_NACL)
696 DCHECK(command_line
.HasSwitch(switches::kLang
) ||
697 process_type
== switches::kZygoteProcess
||
698 process_type
== switches::kGpuProcess
||
699 process_type
== switches::kPpapiBrokerProcess
||
700 process_type
== switches::kPpapiPluginProcess
);
702 DCHECK(command_line
.HasSwitch(switches::kLang
) ||
703 process_type
== switches::kZygoteProcess
||
704 process_type
== switches::kGpuProcess
||
705 process_type
== switches::kNaClLoaderProcess
||
706 process_type
== switches::kPpapiBrokerProcess
||
707 process_type
== switches::kPpapiPluginProcess
);
710 // TODO(markusheintz): The command line flag --lang is actually processed
711 // by the CommandLinePrefStore, and made available through the PrefService
712 // via the preference prefs::kApplicationLocale. The browser process uses
713 // the --lang flag to pass the value of the PrefService in here. Maybe
714 // this value could be passed in a different way.
715 const std::string locale
=
716 command_line
.GetSwitchValueASCII(switches::kLang
);
717 #if defined(OS_ANDROID)
718 // The renderer sandbox prevents us from accessing our .pak files directly.
719 // Therefore file descriptors to the .pak files that we need are passed in
720 // at process creation time.
721 auto global_descriptors
= base::GlobalDescriptors::GetInstance();
722 int pak_fd
= global_descriptors
->Get(kAndroidLocalePakDescriptor
);
723 base::MemoryMappedFile::Region pak_region
=
724 global_descriptors
->GetRegion(kAndroidLocalePakDescriptor
);
725 ResourceBundle::InitSharedInstanceWithPakFileRegion(base::File(pak_fd
),
728 int extra_pak_keys
[] = {
729 kAndroidChrome100PercentPakDescriptor
,
730 kAndroidUIResourcesPakDescriptor
,
732 for (size_t i
= 0; i
< arraysize(extra_pak_keys
); ++i
) {
733 pak_fd
= global_descriptors
->Get(extra_pak_keys
[i
]);
734 pak_region
= global_descriptors
->GetRegion(extra_pak_keys
[i
]);
735 ResourceBundle::GetSharedInstance().AddDataPackFromFileRegion(
736 base::File(pak_fd
), pak_region
, ui::SCALE_FACTOR_100P
);
739 base::i18n::SetICUDefaultLocale(locale
);
740 const std::string loaded_locale
= locale
;
742 const std::string loaded_locale
=
743 ui::ResourceBundle::InitSharedInstanceWithLocale(
744 locale
, NULL
, ui::ResourceBundle::LOAD_COMMON_RESOURCES
);
746 base::FilePath resources_pack_path
;
747 PathService::Get(chrome::FILE_RESOURCES_PACK
, &resources_pack_path
);
748 ResourceBundle::GetSharedInstance().AddDataPackFromPath(
749 resources_pack_path
, ui::SCALE_FACTOR_NONE
);
751 CHECK(!loaded_locale
.empty()) << "Locale could not be found for " <<
755 #if !defined(CHROME_MULTIPLE_DLL_BROWSER)
756 if (process_type
== switches::kUtilityProcess
||
757 process_type
== switches::kZygoteProcess
) {
758 ChromeContentUtilityClient::PreSandboxStartup();
761 chrome::InitializePDF();
764 #if defined(OS_POSIX) && !defined(OS_MACOSX)
765 // Zygote needs to call InitCrashReporter() in RunZygote().
766 if (process_type
!= switches::kZygoteProcess
) {
767 #if defined(OS_ANDROID)
768 if (process_type
.empty()) {
769 breakpad::InitCrashReporter(process_type
);
770 chrome::android::InitJavaExceptionReporter();
772 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 InitLogging(process_type
);
793 SuppressWindowsErrorDialogs();
796 #if defined(CHROME_MULTIPLE_DLL_CHILD) || !defined(CHROME_MULTIPLE_DLL_BROWSER)
797 #if !defined(DISABLE_NACL)
798 ChromeContentClient::SetNaClEntryFunctions(
799 nacl_plugin::PPP_GetInterface
,
800 nacl_plugin::PPP_InitializeModule
,
801 nacl_plugin::PPP_ShutdownModule
);
803 #if defined(ENABLE_PLUGINS) && defined(ENABLE_PDF)
804 ChromeContentClient::SetPDFEntryFunctions(
805 chrome_pdf::PPP_GetInterface
,
806 chrome_pdf::PPP_InitializeModule
,
807 chrome_pdf::PPP_ShutdownModule
);
812 int ChromeMainDelegate::RunProcess(
813 const std::string
& process_type
,
814 const content::MainFunctionParams
& main_function_params
) {
815 // ANDROID doesn't support "service", so no ServiceProcessMain, and arraysize
816 // doesn't support empty array. So we comment out the block for Android.
817 #if !defined(OS_ANDROID)
818 static const MainFunction kMainFunctions
[] = {
819 #if defined(ENABLE_PRINT_PREVIEW) && !defined(CHROME_MULTIPLE_DLL_CHILD)
820 { switches::kServiceProcess
, ServiceProcessMain
},
823 #if defined(OS_MACOSX)
824 { switches::kRelauncherProcess
,
825 mac_relauncher::internal::RelauncherMain
},
828 // This entry is not needed on Linux, where the NaCl loader
829 // process is launched via nacl_helper instead.
830 #if !defined(DISABLE_NACL) && !defined(CHROME_MULTIPLE_DLL_BROWSER) && \
832 { switches::kNaClLoaderProcess
, NaClMain
},
834 { "<invalid>", NULL
}, // To avoid constant array of size 0
835 // when DISABLE_NACL and CHROME_MULTIPLE_DLL_CHILD
836 #endif // DISABLE_NACL
839 for (size_t i
= 0; i
< arraysize(kMainFunctions
); ++i
) {
840 if (process_type
== kMainFunctions
[i
].name
)
841 return kMainFunctions
[i
].function(main_function_params
);
848 void ChromeMainDelegate::ProcessExiting(const std::string
& process_type
) {
849 if (SubprocessNeedsResourceBundle(process_type
))
850 ResourceBundle::CleanupSharedInstance();
851 #if !defined(OS_ANDROID)
852 logging::CleanupChromeLogging();
854 // Android doesn't use InitChromeLogging, so we close the log file manually.
855 logging::CloseLogFile();
856 #endif // !defined(OS_ANDROID)
863 #if defined(OS_MACOSX)
864 bool ChromeMainDelegate::ProcessRegistersWithSystemProcess(
865 const std::string
& process_type
) {
866 #if defined(DISABLE_NACL)
869 return process_type
== switches::kNaClLoaderProcess
;
873 bool ChromeMainDelegate::ShouldSendMachPort(const std::string
& process_type
) {
874 return process_type
!= switches::kRelauncherProcess
&&
875 process_type
!= switches::kServiceProcess
;
878 bool ChromeMainDelegate::DelaySandboxInitialization(
879 const std::string
& process_type
) {
880 #if !defined(DISABLE_NACL)
881 // NaClLoader does this in NaClMainPlatformDelegate::EnableSandbox().
882 // No sandbox needed for relauncher.
883 if (process_type
== switches::kNaClLoaderProcess
)
886 return process_type
== switches::kRelauncherProcess
;
888 #elif defined(OS_POSIX) && !defined(OS_ANDROID)
889 void ChromeMainDelegate::ZygoteStarting(
890 ScopedVector
<content::ZygoteForkDelegate
>* delegates
) {
891 #if !defined(DISABLE_NACL)
892 nacl::AddNaClZygoteForkDelegates(delegates
);
896 void ChromeMainDelegate::ZygoteForked() {
897 Profiling::ProcessStarted();
898 if (Profiling::BeingProfiled()) {
899 base::debug::RestartProfilingAfterFork();
900 SetUpProfilingShutdownHandler();
903 // Needs to be called after we have chrome::DIR_USER_DATA. BrowserMain sets
904 // this up for the browser process in a different manner.
905 const base::CommandLine
* command_line
=
906 base::CommandLine::ForCurrentProcess();
907 std::string process_type
=
908 command_line
->GetSwitchValueASCII(switches::kProcessType
);
909 breakpad::InitCrashReporter(process_type
);
911 // Reset the command line for the newly spawned process.
912 crash_keys::SetSwitchesFromCommandLine(command_line
);
917 content::ContentBrowserClient
*
918 ChromeMainDelegate::CreateContentBrowserClient() {
919 #if defined(CHROME_MULTIPLE_DLL_CHILD)
922 return g_chrome_content_browser_client
.Pointer();
926 content::ContentPluginClient
* ChromeMainDelegate::CreateContentPluginClient() {
927 #if defined(CHROME_MULTIPLE_DLL_BROWSER)
930 return g_chrome_content_plugin_client
.Pointer();
934 content::ContentRendererClient
*
935 ChromeMainDelegate::CreateContentRendererClient() {
936 #if defined(CHROME_MULTIPLE_DLL_BROWSER)
939 return g_chrome_content_renderer_client
.Pointer();
943 content::ContentUtilityClient
*
944 ChromeMainDelegate::CreateContentUtilityClient() {
945 #if defined(CHROME_MULTIPLE_DLL_BROWSER)
948 return g_chrome_content_utility_client
.Pointer();
952 bool ChromeMainDelegate::ShouldEnableProfilerRecording() {
953 switch (chrome::GetChannel()) {
954 case version_info::Channel::UNKNOWN
:
955 case version_info::Channel::CANARY
:
957 case version_info::Channel::DEV
:
958 case version_info::Channel::BETA
:
959 case version_info::Channel::STABLE
:
961 // Don't enable instrumentation.