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/metrics/stats_counters.h"
16 #include "base/path_service.h"
17 #include "base/process/memory.h"
18 #include "base/process/process_handle.h"
19 #include "base/strings/string_util.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_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/nacl/common/nacl_switches.h"
38 #include "components/startup_metric_utils/startup_metric_utils.h"
39 #include "content/public/common/content_client.h"
40 #include "content/public/common/content_paths.h"
41 #include "ui/base/ui_base_switches.h"
47 #include "base/strings/string_util.h"
48 #include "chrome/common/child_process_logging.h"
49 #include "sandbox/win/src/sandbox.h"
50 #include "tools/memory_watcher/memory_watcher.h"
51 #include "ui/base/resource/resource_bundle_win.h"
54 #if defined(OS_MACOSX)
55 #include "base/mac/mac_util.h"
56 #include "base/mac/os_crash_dumps.h"
57 #include "chrome/app/chrome_main_mac.h"
58 #include "chrome/browser/mac/relauncher.h"
59 #include "chrome/common/chrome_paths_internal.h"
60 #include "chrome/common/mac/cfbundle_blocker.h"
61 #include "chrome/common/mac/objc_zombie.h"
62 #include "components/breakpad/app/breakpad_mac.h"
63 #include "grit/chromium_strings.h"
64 #include "ui/base/l10n/l10n_util_mac.h"
70 #include "chrome/app/chrome_breakpad_client.h"
71 #include "components/breakpad/app/breakpad_client.h"
74 #if !defined(DISABLE_NACL) && defined(OS_LINUX)
75 #include "components/nacl/common/nacl_paths.h"
76 #include "components/nacl/zygote/nacl_fork_delegate_linux.h"
79 #if defined(OS_CHROMEOS)
80 #include "base/sys_info.h"
81 #include "chrome/browser/chromeos/boot_times_loader.h"
82 #include "chromeos/chromeos_paths.h"
83 #include "chromeos/chromeos_switches.h"
86 #if defined(OS_ANDROID)
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/breakpad/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(CHROME_MULTIPLE_DLL_CHILD)
113 base::LazyInstance
<chrome::ChromeContentBrowserClient
>
114 g_chrome_content_browser_client
= LAZY_INSTANCE_INITIALIZER
;
117 #if !defined(CHROME_MULTIPLE_DLL_BROWSER)
118 base::LazyInstance
<ChromeContentRendererClient
>
119 g_chrome_content_renderer_client
= LAZY_INSTANCE_INITIALIZER
;
120 base::LazyInstance
<chrome::ChromeContentUtilityClient
>
121 g_chrome_content_utility_client
= LAZY_INSTANCE_INITIALIZER
;
122 base::LazyInstance
<chrome::ChromeContentPluginClient
>
123 g_chrome_content_plugin_client
= LAZY_INSTANCE_INITIALIZER
;
126 #if defined(OS_POSIX)
127 base::LazyInstance
<chrome::ChromeBreakpadClient
>::Leaky
128 g_chrome_breakpad_client
= LAZY_INSTANCE_INITIALIZER
;
131 extern int NaClMain(const content::MainFunctionParams
&);
132 extern int ServiceProcessMain(const content::MainFunctionParams
&);
137 const wchar_t kProfilingDll
[] = L
"memory_watcher.dll";
139 // Load the memory profiling DLL. All it needs to be activated
140 // is to be loaded. Return true on success, false otherwise.
141 bool LoadMemoryProfiler() {
142 HMODULE prof_module
= LoadLibrary(kProfilingDll
);
143 return prof_module
!= NULL
;
146 // Early versions of Chrome incorrectly registered a chromehtml: URL handler,
147 // which gives us nothing but trouble. Avoid launching chrome this way since
148 // some apps fail to properly escape arguments.
149 bool HasDeprecatedArguments(const std::wstring
& command_line
) {
150 const wchar_t kChromeHtml
[] = L
"chromehtml:";
151 std::wstring command_line_lower
= command_line
;
152 // We are only searching for ASCII characters so this is OK.
153 StringToLowerASCII(&command_line_lower
);
154 std::wstring::size_type pos
= command_line_lower
.find(kChromeHtml
);
155 return (pos
!= std::wstring::npos
);
158 // If we try to access a path that is not currently available, we want the call
159 // to fail rather than show an error dialog.
160 void SuppressWindowsErrorDialogs() {
161 UINT new_flags
= SEM_FAILCRITICALERRORS
|
162 SEM_NOOPENFILEERRORBOX
;
164 // Preserve existing error mode.
165 UINT existing_flags
= SetErrorMode(new_flags
);
166 SetErrorMode(existing_flags
| new_flags
);
169 #endif // defined(OS_WIN)
171 #if defined(OS_LINUX)
172 static void AdjustLinuxOOMScore(const std::string
& process_type
) {
173 // Browsers and zygotes should still be killable, but killed last.
174 const int kZygoteScore
= 0;
175 // The minimum amount to bump a score by. This is large enough that
176 // even if it's translated into the old values, it will still go up
178 const int kScoreBump
= 100;
179 // This is the lowest score that renderers and extensions start with
180 // in the OomPriorityManager.
181 const int kRendererScore
= chrome::kLowestRendererOomScore
;
182 // For "miscellaneous" things, we want them after renderers,
183 // but before plugins.
184 const int kMiscScore
= kRendererScore
- kScoreBump
;
185 // We want plugins to die after the renderers.
186 const int kPluginScore
= kMiscScore
- kScoreBump
;
189 DCHECK(kMiscScore
> 0);
190 DCHECK(kPluginScore
> 0);
192 if (process_type
== switches::kPluginProcess
||
193 process_type
== switches::kPpapiPluginProcess
) {
194 score
= kPluginScore
;
195 } else if (process_type
== switches::kPpapiBrokerProcess
) {
196 // The broker should be killed before the PPAPI plugin.
197 score
= kPluginScore
+ kScoreBump
;
198 } else if (process_type
== switches::kUtilityProcess
||
199 process_type
== switches::kWorkerProcess
||
200 process_type
== switches::kGpuProcess
||
201 process_type
== switches::kServiceProcess
) {
204 } else if (process_type
== switches::kNaClLoaderProcess
||
205 process_type
== switches::kNaClLoaderNonSfiProcess
) {
206 score
= kPluginScore
;
208 } else if (process_type
== switches::kZygoteProcess
||
209 process_type
.empty()) {
210 // For zygotes and unlabeled process types, we want to still make
211 // them killable by the OOM killer.
212 score
= kZygoteScore
;
213 } else if (process_type
== switches::kRendererProcess
) {
214 LOG(WARNING
) << "process type 'renderer' "
215 << "should be created through the zygote.";
216 // When debugging, this process type can end up being run directly, but
217 // this isn't the typical path for assigning the OOM score for it. Still,
218 // we want to assign a score that is somewhat representative for debugging.
219 score
= kRendererScore
;
221 NOTREACHED() << "Unknown process type";
224 base::AdjustOOMScore(base::GetCurrentProcId(), score
);
226 #endif // defined(OS_LINUX)
228 // Enable the heap profiler if the appropriate command-line switch is
229 // present, bailing out of the app we can't.
230 void EnableHeapProfiler(const CommandLine
& command_line
) {
232 if (command_line
.HasSwitch(switches::kMemoryProfiling
))
233 if (!LoadMemoryProfiler())
238 // Returns true if this subprocess type needs the ResourceBundle initialized
239 // and resources loaded.
240 bool SubprocessNeedsResourceBundle(const std::string
& process_type
) {
242 #if defined(OS_WIN) || defined(OS_MACOSX)
243 // Windows needs resources for the default/null plugin.
244 // Mac needs them for the plugin process name.
245 process_type
== switches::kPluginProcess
||
246 // Needed for scrollbar related images.
247 process_type
== switches::kWorkerProcess
||
249 #if defined(OS_POSIX) && !defined(OS_MACOSX)
250 // The zygote process opens the resources for the renderers.
251 process_type
== switches::kZygoteProcess
||
253 #if defined(OS_MACOSX)
254 // Mac needs them too for scrollbar related images and for sandbox
256 process_type
== switches::kNaClLoaderProcess
||
257 process_type
== switches::kPpapiPluginProcess
||
258 process_type
== switches::kPpapiBrokerProcess
||
259 process_type
== switches::kGpuProcess
||
261 process_type
== switches::kRendererProcess
||
262 process_type
== switches::kUtilityProcess
;
265 #if defined(OS_POSIX)
266 // Check for --version and --product-version; return true if we encountered
267 // one of these switches and should exit now.
268 bool HandleVersionSwitches(const CommandLine
& command_line
) {
269 const chrome::VersionInfo version_info
;
271 #if !defined(OS_MACOSX)
272 if (command_line
.HasSwitch(switches::kProductVersion
)) {
273 printf("%s\n", version_info
.Version().c_str());
278 if (command_line
.HasSwitch(switches::kVersion
)) {
280 version_info
.Name().c_str(),
281 version_info
.Version().c_str(),
282 chrome::VersionInfo::GetVersionStringModifier().c_str());
289 #if !defined(OS_MACOSX) && !defined(OS_CHROMEOS)
290 // Show the man page if --help or -h is on the command line.
291 void HandleHelpSwitches(const CommandLine
& command_line
) {
292 if (command_line
.HasSwitch(switches::kHelp
) ||
293 command_line
.HasSwitch(switches::kHelpShort
)) {
294 base::FilePath
binary(command_line
.argv()[0]);
295 execlp("man", "man", binary
.BaseName().value().c_str(), NULL
);
296 PLOG(FATAL
) << "execlp failed";
301 #if !defined(OS_MACOSX) && !defined(OS_ANDROID)
302 void SIGTERMProfilingShutdown(int signal
) {
304 struct sigaction sigact
;
305 memset(&sigact
, 0, sizeof(sigact
));
306 sigact
.sa_handler
= SIG_DFL
;
307 CHECK(sigaction(SIGTERM
, &sigact
, NULL
) == 0);
311 void SetUpProfilingShutdownHandler() {
312 struct sigaction sigact
;
313 sigact
.sa_handler
= SIGTERMProfilingShutdown
;
314 sigact
.sa_flags
= SA_RESETHAND
;
315 sigemptyset(&sigact
.sa_mask
);
316 CHECK(sigaction(SIGTERM
, &sigact
, NULL
) == 0);
318 #endif // !defined(OS_MACOSX) && !defined(OS_ANDROID)
322 struct MainFunction
{
324 int (*function
)(const content::MainFunctionParams
&);
327 // Initializes the user data dir. Must be called before InitializeLocalState().
328 void InitializeUserDataDir() {
329 CommandLine
* command_line
= CommandLine::ForCurrentProcess();
330 base::FilePath user_data_dir
=
331 command_line
->GetSwitchValuePath(switches::kUserDataDir
);
332 std::string process_type
=
333 command_line
->GetSwitchValueASCII(switches::kProcessType
);
335 #if defined(OS_LINUX)
336 // On Linux, Chrome does not support running multiple copies under different
337 // DISPLAYs, so the profile directory can be specified in the environment to
338 // support the virtual desktop use-case.
339 if (user_data_dir
.empty()) {
340 std::string user_data_dir_string
;
341 scoped_ptr
<base::Environment
> environment(base::Environment::Create());
342 if (environment
->GetVar("CHROME_USER_DATA_DIR", &user_data_dir_string
) &&
343 base::IsStringUTF8(user_data_dir_string
)) {
344 user_data_dir
= base::FilePath::FromUTF8Unsafe(user_data_dir_string
);
348 #if defined(OS_MACOSX) || defined(OS_WIN)
349 policy::path_parser::CheckUserDataDirPolicy(&user_data_dir
);
352 const bool specified_directory_was_invalid
= !user_data_dir
.empty() &&
353 !PathService::OverrideAndCreateIfNeeded(chrome::DIR_USER_DATA
,
354 user_data_dir
, false, true);
355 // Save inaccessible or invalid paths so the user may be prompted later.
356 if (specified_directory_was_invalid
)
357 chrome::SetInvalidSpecifiedUserDataDir(user_data_dir
);
359 // Warn and fail early if the process fails to get a user data directory.
360 if (!PathService::Get(chrome::DIR_USER_DATA
, &user_data_dir
)) {
361 // If an invalid command-line or policy override was specified, the user
362 // will be given an error with that value. Otherwise, use the directory
363 // returned by PathService (or the fallback default directory) in the error.
364 if (!specified_directory_was_invalid
) {
365 // PathService::Get() returns false and yields an empty path if it fails
366 // to create DIR_USER_DATA. Retrieve the default value manually to display
367 // a more meaningful error to the user in that case.
368 if (user_data_dir
.empty())
369 chrome::GetDefaultUserDataDirectory(&user_data_dir
);
370 chrome::SetInvalidSpecifiedUserDataDir(user_data_dir
);
373 // The browser process (which is identified by an empty |process_type|) will
374 // handle the error later; other processes that need the dir crash here.
375 CHECK(process_type
.empty()) << "Unable to get the user data directory "
376 << "for process type: " << process_type
;
379 // Append the fallback user data directory to the commandline. Otherwise,
380 // child or service processes will attempt to use the invalid directory.
381 if (specified_directory_was_invalid
)
382 command_line
->AppendSwitchPath(switches::kUserDataDir
, user_data_dir
);
387 ChromeMainDelegate::ChromeMainDelegate() {
388 #if defined(OS_ANDROID)
389 // On Android the main entry point time is the time when the Java code starts.
390 // This happens before the shared library containing this code is even loaded.
391 // The Java startup code has recorded that time, but the C++ code can't fetch it
392 // from the Java side until it has initialized the JNI. See
393 // ChromeMainDelegateAndroid.
395 startup_metric_utils::RecordMainEntryPointTime();
399 ChromeMainDelegate::~ChromeMainDelegate() {
402 bool ChromeMainDelegate::BasicStartupComplete(int* exit_code
) {
403 #if defined(OS_CHROMEOS)
404 chromeos::BootTimesLoader::Get()->SaveChromeMainStats();
407 const CommandLine
& command_line
= *CommandLine::ForCurrentProcess();
409 #if defined(OS_MACOSX)
410 // Give the browser process a longer treadmill, since crashes
411 // there have more impact.
412 const bool is_browser
= !command_line
.HasSwitch(switches::kProcessType
);
413 ObjcEvilDoers::ZombieEnable(true, is_browser
? 10000 : 1000);
415 SetUpBundleOverrides();
416 chrome::common::mac::EnableCFBundleBlocker();
419 Profiling::ProcessStarted();
421 #if defined(OS_POSIX)
422 if (HandleVersionSwitches(command_line
)) {
424 return true; // Got a --version switch; exit with a success error code.
426 #if !defined(OS_MACOSX) && !defined(OS_CHROMEOS)
427 // This will directly exit if the user asked for help.
428 HandleHelpSwitches(command_line
);
433 // Must do this before any other usage of command line!
434 if (HasDeprecatedArguments(command_line
.GetCommandLineString())) {
440 chrome::RegisterPathProvider();
441 #if defined(OS_CHROMEOS)
442 chromeos::RegisterPathProvider();
444 #if !defined(DISABLE_NACL) && defined(OS_LINUX)
445 nacl::RegisterPathProvider();
448 // No support for ANDROID yet as DiagnosticsController needs wchar support.
449 // TODO(gspencer): That's not true anymore, or at least there are no w-string
450 // references anymore. Not sure if that means this can be enabled on Android or
451 // not though. As there is no easily accessible command line on Android, I'm
452 // not sure this is a big deal.
453 #if !defined(OS_ANDROID) && !defined(CHROME_MULTIPLE_DLL_CHILD)
454 // If we are in diagnostics mode this is the end of the line: after the
455 // diagnostics are run the process will invariably exit.
456 if (command_line
.HasSwitch(switches::kDiagnostics
)) {
457 diagnostics::DiagnosticsWriter::FormatType format
=
458 diagnostics::DiagnosticsWriter::HUMAN
;
459 if (command_line
.HasSwitch(switches::kDiagnosticsFormat
)) {
460 std::string format_str
=
461 command_line
.GetSwitchValueASCII(switches::kDiagnosticsFormat
);
462 if (format_str
== "machine") {
463 format
= diagnostics::DiagnosticsWriter::MACHINE
;
464 } else if (format_str
== "log") {
465 format
= diagnostics::DiagnosticsWriter::LOG
;
467 DCHECK_EQ("human", format_str
);
471 diagnostics::DiagnosticsWriter
writer(format
);
472 *exit_code
= diagnostics::DiagnosticsController::GetInstance()->Run(
473 command_line
, &writer
);
474 diagnostics::DiagnosticsController::GetInstance()->ClearResults();
479 #if defined(OS_CHROMEOS)
480 // Initialize primary user homedir (in multi-profile session) as it may be
481 // passed as a command line switch.
482 base::FilePath homedir
;
483 if (command_line
.HasSwitch(chromeos::switches::kHomedir
)) {
484 homedir
= base::FilePath(
485 command_line
.GetSwitchValueASCII(chromeos::switches::kHomedir
));
486 PathService::OverrideAndCreateIfNeeded(
487 base::DIR_HOME
, homedir
, true, false);
490 // If we are recovering from a crash on ChromeOS, then we will do some
491 // recovery using the diagnostics module, and then continue on. We fake up a
492 // command line to tell it that we want it to recover, and to preserve the
493 // original command line.
494 if (command_line
.HasSwitch(chromeos::switches::kLoginUser
) ||
495 command_line
.HasSwitch(switches::kDiagnosticsRecovery
)) {
497 // The statistics subsystem needs get initialized soon enough for the
498 // statistics to be collected. It's safe to call this more than once.
499 base::StatisticsRecorder::Initialize();
501 CommandLine
interim_command_line(command_line
.GetProgram());
502 const char* kSwitchNames
[] = {switches::kUserDataDir
, };
503 interim_command_line
.CopySwitchesFrom(
504 command_line
, kSwitchNames
, arraysize(kSwitchNames
));
505 interim_command_line
.AppendSwitch(switches::kDiagnostics
);
506 interim_command_line
.AppendSwitch(switches::kDiagnosticsRecovery
);
508 diagnostics::DiagnosticsWriter::FormatType format
=
509 diagnostics::DiagnosticsWriter::LOG
;
510 if (command_line
.HasSwitch(switches::kDiagnosticsFormat
)) {
511 std::string format_str
=
512 command_line
.GetSwitchValueASCII(switches::kDiagnosticsFormat
);
513 if (format_str
== "machine") {
514 format
= diagnostics::DiagnosticsWriter::MACHINE
;
515 } else if (format_str
== "human") {
516 format
= diagnostics::DiagnosticsWriter::HUMAN
;
518 DCHECK_EQ("log", format_str
);
522 diagnostics::DiagnosticsWriter
writer(format
);
523 int diagnostics_exit_code
=
524 diagnostics::DiagnosticsController::GetInstance()->Run(command_line
,
526 if (diagnostics_exit_code
) {
527 // Diagnostics has failed somehow, so we exit.
528 *exit_code
= diagnostics_exit_code
;
532 // Now we run the actual recovery tasks.
533 int recovery_exit_code
=
534 diagnostics::DiagnosticsController::GetInstance()->RunRecovery(
535 command_line
, &writer
);
537 if (recovery_exit_code
) {
538 // Recovery has failed somehow, so we exit.
539 *exit_code
= recovery_exit_code
;
542 } else { // Not running diagnostics or recovery.
543 diagnostics::DiagnosticsController::GetInstance()->RecordRegularStartup();
547 content::SetContentClient(&chrome_content_client_
);
552 #if defined(OS_MACOSX)
553 void ChromeMainDelegate::InitMacCrashReporter(
554 const base::CommandLine
& command_line
,
555 const std::string
& process_type
) {
556 // TODO(mark): Right now, InitCrashReporter() needs to be called after
557 // CommandLine::Init() and chrome::RegisterPathProvider(). Ideally,
558 // Breakpad initialization could occur sooner, preferably even before the
559 // framework dylib is even loaded, to catch potential early crashes.
560 breakpad::InitCrashReporter(process_type
);
563 bool is_debug_build
= false;
565 bool is_debug_build
= true;
568 // Details on when we enable Apple's Crash reporter.
571 // In debug mode it takes Apple's crash reporter eons to generate a crash
575 // * We only pass crashes for foreground processes to Apple's Crash
576 // reporter. At the time of this writing, that means just the Browser
578 // * If Breakpad is enabled, it will pass browser crashes to Crash Reporter
580 // * If Breakpad is disabled, we only turn on Crash Reporter for the
581 // Browser process in release mode.
582 if (!command_line
.HasSwitch(switches::kDisableBreakpad
)) {
583 bool disable_apple_crash_reporter
= is_debug_build
||
584 base::mac::IsBackgroundOnlyProcess();
585 if (!breakpad::IsCrashReporterEnabled() && disable_apple_crash_reporter
) {
586 base::mac::DisableOSCrashDumps();
590 // Mac Chrome is packaged with a main app bundle and a helper app bundle.
591 // The main app bundle should only be used for the browser process, so it
592 // should never see a --type switch (switches::kProcessType). Likewise,
593 // the helper should always have a --type switch.
595 // This check is done this late so there is already a call to
596 // base::mac::IsBackgroundOnlyProcess(), so there is no change in
597 // startup/initialization order.
599 // The helper's Info.plist marks it as a background only app.
600 if (base::mac::IsBackgroundOnlyProcess()) {
601 CHECK(command_line
.HasSwitch(switches::kProcessType
) &&
602 !process_type
.empty())
603 << "Helper application requires --type.";
605 // In addition, some helper flavors only work with certain process types.
606 base::FilePath executable
;
607 if (PathService::Get(base::FILE_EXE
, &executable
) &&
608 executable
.value().size() >= 3) {
609 std::string last_three
=
610 executable
.value().substr(executable
.value().size() - 3);
612 if (last_three
== " EH") {
613 CHECK(process_type
== switches::kPluginProcess
||
614 process_type
== switches::kUtilityProcess
)
615 << "Executable-heap process requires --type="
616 << switches::kPluginProcess
<< " or "
617 << switches::kUtilityProcess
<< ", saw " << process_type
;
618 } else if (last_three
== " NP") {
619 CHECK_EQ(switches::kNaClLoaderProcess
, process_type
)
620 << "Non-PIE process requires --type="
621 << switches::kNaClLoaderProcess
<< ", saw " << process_type
;
623 CHECK(process_type
!= switches::kPluginProcess
&&
624 process_type
!= switches::kNaClLoaderProcess
)
625 << "Non-executable-heap PIE process is intolerant of --type="
626 << switches::kPluginProcess
<< " and "
627 << switches::kNaClLoaderProcess
<< ", saw " << process_type
;
631 CHECK(!command_line
.HasSwitch(switches::kProcessType
) &&
632 process_type
.empty())
633 << "Main application forbids --type, saw " << process_type
;
636 if (breakpad::IsCrashReporterEnabled())
637 breakpad::InitCrashProcessInfo(process_type
);
639 #endif // defined(OS_MACOSX)
641 void ChromeMainDelegate::PreSandboxStartup() {
642 const CommandLine
& command_line
= *CommandLine::ForCurrentProcess();
643 std::string process_type
=
644 command_line
.GetSwitchValueASCII(switches::kProcessType
);
646 #if defined(OS_POSIX)
647 breakpad::SetBreakpadClient(g_chrome_breakpad_client
.Pointer());
650 #if defined(OS_MACOSX)
651 // On the Mac, the child executable lives at a predefined location within
652 // the app bundle's versioned directory.
653 PathService::Override(content::CHILD_PROCESS_EXE
,
654 chrome::GetVersionedDirectory().
655 Append(chrome::kHelperProcessExecutablePath
));
657 InitMacCrashReporter(command_line
, process_type
);
661 child_process_logging::Init();
663 #if defined(ARCH_CPU_ARM_FAMILY) && (defined(OS_ANDROID) || defined(OS_LINUX))
664 // Create an instance of the CPU class to parse /proc/cpuinfo and cache
669 // Initialize the user data dir for any process type that needs it.
670 if (chrome::ProcessNeedsProfileDir(process_type
))
671 InitializeUserDataDir();
673 stats_counter_timer_
.reset(new base::StatsCounterTimer("Chrome.Init"));
674 startup_timer_
.reset(new base::StatsScope
<base::StatsCounterTimer
>
675 (*stats_counter_timer_
));
677 // Enable the heap profiler as early as possible!
678 EnableHeapProfiler(command_line
);
680 // Enable Message Loop related state asap.
681 if (command_line
.HasSwitch(switches::kMessageLoopHistogrammer
))
682 base::MessageLoop::EnableHistogrammer(true);
684 #if !defined(OS_ANDROID)
685 // Android does InitLogging when library is loaded. Skip here.
686 logging::OldFileDeletionState file_state
=
687 logging::APPEND_TO_OLD_LOG_FILE
;
688 if (process_type
.empty()) {
689 file_state
= logging::DELETE_OLD_LOG_FILE
;
691 logging::InitChromeLogging(command_line
, file_state
);
695 // TODO(zturner): Throbber icons are still stored in chrome.dll, this can be
696 // killed once those are merged into resources.pak. See
697 // GlassBrowserFrameView::InitThrobberIcons() and http://crbug.com/368327.
698 ui::SetResourcesDataDLL(_AtlBaseModule
.GetResourceInstance());
701 if (SubprocessNeedsResourceBundle(process_type
)) {
702 // Initialize ResourceBundle which handles files loaded from external
703 // sources. The language should have been passed in to us from the
704 // browser process as a command line flag.
705 #if defined(DISABLE_NACL)
706 DCHECK(command_line
.HasSwitch(switches::kLang
) ||
707 process_type
== switches::kZygoteProcess
||
708 process_type
== switches::kGpuProcess
||
709 process_type
== switches::kPpapiBrokerProcess
||
710 process_type
== switches::kPpapiPluginProcess
);
712 DCHECK(command_line
.HasSwitch(switches::kLang
) ||
713 process_type
== switches::kZygoteProcess
||
714 process_type
== switches::kGpuProcess
||
715 process_type
== switches::kNaClLoaderProcess
||
716 process_type
== switches::kPpapiBrokerProcess
||
717 process_type
== switches::kPpapiPluginProcess
);
720 // TODO(markusheintz): The command line flag --lang is actually processed
721 // by the CommandLinePrefStore, and made available through the PrefService
722 // via the preference prefs::kApplicationLocale. The browser process uses
723 // the --lang flag to pass the value of the PrefService in here. Maybe
724 // this value could be passed in a different way.
725 const std::string locale
=
726 command_line
.GetSwitchValueASCII(switches::kLang
);
727 #if defined(OS_ANDROID)
728 // The renderer sandbox prevents us from accessing our .pak files directly.
729 // Therefore file descriptors to the .pak files that we need are passed in
730 // at process creation time.
731 int locale_pak_fd
= base::GlobalDescriptors::GetInstance()->MaybeGet(
732 kAndroidLocalePakDescriptor
);
733 CHECK(locale_pak_fd
!= -1);
734 ResourceBundle::InitSharedInstanceWithPakFile(base::File(locale_pak_fd
),
737 int extra_pak_keys
[] = {
738 kAndroidChrome100PercentPakDescriptor
,
739 kAndroidUIResourcesPakDescriptor
,
741 for (size_t i
= 0; i
< arraysize(extra_pak_keys
); ++i
) {
743 base::GlobalDescriptors::GetInstance()->MaybeGet(extra_pak_keys
[i
]);
745 ResourceBundle::GetSharedInstance().AddDataPackFromFile(
746 base::File(pak_fd
), ui::SCALE_FACTOR_100P
);
749 base::i18n::SetICUDefaultLocale(locale
);
750 const std::string loaded_locale
= locale
;
752 const std::string loaded_locale
=
753 ResourceBundle::InitSharedInstanceWithLocale(locale
, NULL
);
755 base::FilePath resources_pack_path
;
756 PathService::Get(chrome::FILE_RESOURCES_PACK
, &resources_pack_path
);
757 ResourceBundle::GetSharedInstance().AddDataPackFromPath(
758 resources_pack_path
, ui::SCALE_FACTOR_NONE
);
760 CHECK(!loaded_locale
.empty()) << "Locale could not be found for " <<
763 #if !defined(CHROME_MULTIPLE_DLL_BROWSER)
764 if (process_type
== switches::kUtilityProcess
||
765 process_type
== switches::kZygoteProcess
) {
766 chrome::ChromeContentUtilityClient::PreSandboxStartup();
771 #if defined(OS_POSIX) && !defined(OS_MACOSX)
772 // Zygote needs to call InitCrashReporter() in RunZygote().
773 if (process_type
!= switches::kZygoteProcess
) {
774 #if defined(OS_ANDROID)
775 if (process_type
.empty())
776 breakpad::InitCrashReporter(process_type
);
778 breakpad::InitNonBrowserCrashReporterForAndroid(process_type
);
779 #else // !defined(OS_ANDROID)
780 breakpad::InitCrashReporter(process_type
);
781 #endif // defined(OS_ANDROID)
783 #endif // defined(OS_POSIX) && !defined(OS_MACOSX)
785 // After all the platform Breakpads have been initialized, store the command
786 // line for crash reporting.
787 crash_keys::SetSwitchesFromCommandLine(&command_line
);
790 void ChromeMainDelegate::SandboxInitialized(const std::string
& process_type
) {
791 startup_timer_
->Stop(); // End of Startup Time Measurement.
793 // Note: If you are adding a new process type below, be sure to adjust the
794 // AdjustLinuxOOMScore function too.
795 #if defined(OS_LINUX)
796 AdjustLinuxOOMScore(process_type
);
799 SuppressWindowsErrorDialogs();
803 int ChromeMainDelegate::RunProcess(
804 const std::string
& process_type
,
805 const content::MainFunctionParams
& main_function_params
) {
806 // ANDROID doesn't support "service", so no ServiceProcessMain, and arraysize
807 // doesn't support empty array. So we comment out the block for Android.
808 #if !defined(OS_ANDROID)
809 static const MainFunction kMainFunctions
[] = {
810 #if defined(ENABLE_FULL_PRINTING) && !defined(CHROME_MULTIPLE_DLL_CHILD)
811 { switches::kServiceProcess
, ServiceProcessMain
},
814 #if defined(OS_MACOSX)
815 { switches::kRelauncherProcess
,
816 mac_relauncher::internal::RelauncherMain
},
819 // This entry is not needed on Linux, where the NaCl loader
820 // process is launched via nacl_helper instead.
821 #if !defined(DISABLE_NACL) && !defined(CHROME_MULTIPLE_DLL_BROWSER) && \
823 { switches::kNaClLoaderProcess
, NaClMain
},
825 { "<invalid>", NULL
}, // To avoid constant array of size 0
826 // when DISABLE_NACL and CHROME_MULTIPLE_DLL_CHILD
827 #endif // DISABLE_NACL
830 for (size_t i
= 0; i
< arraysize(kMainFunctions
); ++i
) {
831 if (process_type
== kMainFunctions
[i
].name
)
832 return kMainFunctions
[i
].function(main_function_params
);
839 void ChromeMainDelegate::ProcessExiting(const std::string
& process_type
) {
840 if (SubprocessNeedsResourceBundle(process_type
))
841 ResourceBundle::CleanupSharedInstance();
842 #if !defined(OS_ANDROID)
843 logging::CleanupChromeLogging();
845 // Android doesn't use InitChromeLogging, so we close the log file manually.
846 logging::CloseLogFile();
847 #endif // !defined(OS_ANDROID)
850 #if defined(OS_MACOSX)
851 bool ChromeMainDelegate::ProcessRegistersWithSystemProcess(
852 const std::string
& process_type
) {
853 return process_type
== switches::kNaClLoaderProcess
;
856 bool ChromeMainDelegate::ShouldSendMachPort(const std::string
& process_type
) {
857 return process_type
!= switches::kRelauncherProcess
&&
858 process_type
!= switches::kServiceProcess
;
861 bool ChromeMainDelegate::DelaySandboxInitialization(
862 const std::string
& process_type
) {
863 // NaClLoader does this in NaClMainPlatformDelegate::EnableSandbox().
864 // No sandbox needed for relauncher.
865 return process_type
== switches::kNaClLoaderProcess
||
866 process_type
== switches::kRelauncherProcess
;
868 #elif defined(OS_POSIX) && !defined(OS_ANDROID)
869 void ChromeMainDelegate::ZygoteStarting(
870 ScopedVector
<content::ZygoteForkDelegate
>* delegates
) {
871 #if !defined(DISABLE_NACL)
872 nacl::AddNaClZygoteForkDelegates(delegates
);
876 void ChromeMainDelegate::ZygoteForked() {
877 Profiling::ProcessStarted();
878 if (Profiling::BeingProfiled()) {
879 base::debug::RestartProfilingAfterFork();
880 SetUpProfilingShutdownHandler();
883 // Needs to be called after we have chrome::DIR_USER_DATA. BrowserMain sets
884 // this up for the browser process in a different manner.
885 const CommandLine
* command_line
= CommandLine::ForCurrentProcess();
886 std::string process_type
=
887 command_line
->GetSwitchValueASCII(switches::kProcessType
);
888 breakpad::InitCrashReporter(process_type
);
890 // Reset the command line for the newly spawned process.
891 crash_keys::SetSwitchesFromCommandLine(command_line
);
896 content::ContentBrowserClient
*
897 ChromeMainDelegate::CreateContentBrowserClient() {
898 #if defined(CHROME_MULTIPLE_DLL_CHILD)
901 return g_chrome_content_browser_client
.Pointer();
905 content::ContentPluginClient
* ChromeMainDelegate::CreateContentPluginClient() {
906 #if defined(CHROME_MULTIPLE_DLL_BROWSER)
909 return g_chrome_content_plugin_client
.Pointer();
913 content::ContentRendererClient
*
914 ChromeMainDelegate::CreateContentRendererClient() {
915 #if defined(CHROME_MULTIPLE_DLL_BROWSER)
918 return g_chrome_content_renderer_client
.Pointer();
922 content::ContentUtilityClient
*
923 ChromeMainDelegate::CreateContentUtilityClient() {
924 #if defined(CHROME_MULTIPLE_DLL_BROWSER)
927 return g_chrome_content_utility_client
.Pointer();