Updating trunk VERSION from 2139.0 to 2140.0
[chromium-blink-merge.git] / chrome / app / chrome_main_delegate.cc
blob5de4cc5257567257d916ae5ecab9a8c5388d70f3
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"
9 #include "base/cpu.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/component_updater/component_updater_paths.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"
43 #if defined(OS_WIN)
44 #include <atlbase.h>
45 #include <malloc.h>
46 #include <algorithm>
47 #include "chrome/common/child_process_logging.h"
48 #include "chrome/common/terminate_on_heap_corruption_experiment_win.h"
49 #include "sandbox/win/src/sandbox.h"
50 #include "ui/base/resource/resource_bundle_win.h"
51 #endif
53 #if defined(OS_MACOSX)
54 #include "base/mac/mac_util.h"
55 #include "base/mac/os_crash_dumps.h"
56 #include "chrome/app/chrome_main_mac.h"
57 #include "chrome/browser/mac/relauncher.h"
58 #include "chrome/common/mac/cfbundle_blocker.h"
59 #include "chrome/common/mac/objc_zombie.h"
60 #include "components/crash/app/breakpad_mac.h"
61 #include "ui/base/l10n/l10n_util_mac.h"
62 #endif
64 #if defined(OS_POSIX)
65 #include <locale.h>
66 #include <signal.h>
67 #include "chrome/app/chrome_breakpad_client.h"
68 #include "components/crash/app/breakpad_client.h"
69 #endif
71 #if !defined(DISABLE_NACL) && defined(OS_LINUX)
72 #include "components/nacl/common/nacl_paths.h"
73 #include "components/nacl/zygote/nacl_fork_delegate_linux.h"
74 #endif
76 #if defined(OS_CHROMEOS)
77 #include "base/sys_info.h"
78 #include "chrome/browser/chromeos/boot_times_loader.h"
79 #include "chromeos/chromeos_paths.h"
80 #include "chromeos/chromeos_switches.h"
81 #endif
83 #if defined(OS_ANDROID)
84 #include "chrome/common/descriptors_android.h"
85 #else
86 // Diagnostics is only available on non-android platforms.
87 #include "chrome/browser/diagnostics/diagnostics_controller.h"
88 #include "chrome/browser/diagnostics/diagnostics_writer.h"
89 #endif
91 #if defined(USE_X11)
92 #include <stdlib.h>
93 #include <string.h>
94 #include "ui/base/x/x11_util.h"
95 #endif
97 #if defined(OS_POSIX) && !defined(OS_MACOSX)
98 #include "components/crash/app/breakpad_linux.h"
99 #endif
101 #if defined(OS_LINUX)
102 #include "base/environment.h"
103 #endif
105 #if defined(OS_MACOSX) || defined(OS_WIN)
106 #include "chrome/browser/policy/policy_path_parser.h"
107 #endif
109 #if !defined(DISABLE_NACL)
110 #include "components/nacl/common/nacl_switches.h"
111 #endif
113 #if !defined(CHROME_MULTIPLE_DLL_CHILD)
114 base::LazyInstance<chrome::ChromeContentBrowserClient>
115 g_chrome_content_browser_client = LAZY_INSTANCE_INITIALIZER;
116 #endif
118 #if !defined(CHROME_MULTIPLE_DLL_BROWSER)
119 base::LazyInstance<ChromeContentRendererClient>
120 g_chrome_content_renderer_client = LAZY_INSTANCE_INITIALIZER;
121 base::LazyInstance<ChromeContentUtilityClient>
122 g_chrome_content_utility_client = LAZY_INSTANCE_INITIALIZER;
123 base::LazyInstance<chrome::ChromeContentPluginClient>
124 g_chrome_content_plugin_client = LAZY_INSTANCE_INITIALIZER;
125 #endif
127 #if defined(OS_POSIX)
128 base::LazyInstance<chrome::ChromeBreakpadClient>::Leaky
129 g_chrome_breakpad_client = LAZY_INSTANCE_INITIALIZER;
130 #endif
132 extern int NaClMain(const content::MainFunctionParams&);
133 extern int ServiceProcessMain(const content::MainFunctionParams&);
135 namespace {
137 #if defined(OS_WIN)
138 // Early versions of Chrome incorrectly registered a chromehtml: URL handler,
139 // which gives us nothing but trouble. Avoid launching chrome this way since
140 // some apps fail to properly escape arguments.
141 bool HasDeprecatedArguments(const std::wstring& command_line) {
142 const wchar_t kChromeHtml[] = L"chromehtml:";
143 std::wstring command_line_lower = command_line;
144 // We are only searching for ASCII characters so this is OK.
145 base::StringToLowerASCII(&command_line_lower);
146 std::wstring::size_type pos = command_line_lower.find(kChromeHtml);
147 return (pos != std::wstring::npos);
150 // If we try to access a path that is not currently available, we want the call
151 // to fail rather than show an error dialog.
152 void SuppressWindowsErrorDialogs() {
153 UINT new_flags = SEM_FAILCRITICALERRORS |
154 SEM_NOOPENFILEERRORBOX;
156 // Preserve existing error mode.
157 UINT existing_flags = SetErrorMode(new_flags);
158 SetErrorMode(existing_flags | new_flags);
161 #endif // defined(OS_WIN)
163 #if defined(OS_LINUX)
164 static void AdjustLinuxOOMScore(const std::string& process_type) {
165 // Browsers and zygotes should still be killable, but killed last.
166 const int kZygoteScore = 0;
167 // The minimum amount to bump a score by. This is large enough that
168 // even if it's translated into the old values, it will still go up
169 // by at least one.
170 const int kScoreBump = 100;
171 // This is the lowest score that renderers and extensions start with
172 // in the OomPriorityManager.
173 const int kRendererScore = chrome::kLowestRendererOomScore;
174 // For "miscellaneous" things, we want them after renderers,
175 // but before plugins.
176 const int kMiscScore = kRendererScore - kScoreBump;
177 // We want plugins to die after the renderers.
178 const int kPluginScore = kMiscScore - kScoreBump;
179 int score = -1;
181 DCHECK(kMiscScore > 0);
182 DCHECK(kPluginScore > 0);
184 if (process_type == switches::kPluginProcess ||
185 process_type == switches::kPpapiPluginProcess) {
186 score = kPluginScore;
187 } else if (process_type == switches::kPpapiBrokerProcess) {
188 // The broker should be killed before the PPAPI plugin.
189 score = kPluginScore + kScoreBump;
190 } else if (process_type == switches::kUtilityProcess ||
191 process_type == switches::kGpuProcess ||
192 process_type == switches::kServiceProcess) {
193 score = kMiscScore;
194 #ifndef DISABLE_NACL
195 } else if (process_type == switches::kNaClLoaderProcess ||
196 process_type == switches::kNaClLoaderNonSfiProcess) {
197 score = kPluginScore;
198 #endif
199 } else if (process_type == switches::kZygoteProcess ||
200 process_type.empty()) {
201 // For zygotes and unlabeled process types, we want to still make
202 // them killable by the OOM killer.
203 score = kZygoteScore;
204 } else if (process_type == switches::kRendererProcess) {
205 LOG(WARNING) << "process type 'renderer' "
206 << "should be created through the zygote.";
207 // When debugging, this process type can end up being run directly, but
208 // this isn't the typical path for assigning the OOM score for it. Still,
209 // we want to assign a score that is somewhat representative for debugging.
210 score = kRendererScore;
211 } else {
212 NOTREACHED() << "Unknown process type";
214 if (score > -1)
215 base::AdjustOOMScore(base::GetCurrentProcId(), score);
217 #endif // defined(OS_LINUX)
219 // Returns true if this subprocess type needs the ResourceBundle initialized
220 // and resources loaded.
221 bool SubprocessNeedsResourceBundle(const std::string& process_type) {
222 return
223 #if defined(OS_WIN) || defined(OS_MACOSX)
224 // Windows needs resources for the default/null plugin.
225 // Mac needs them for the plugin process name.
226 process_type == switches::kPluginProcess ||
227 #endif
228 #if defined(OS_POSIX) && !defined(OS_MACOSX)
229 // The zygote process opens the resources for the renderers.
230 process_type == switches::kZygoteProcess ||
231 #endif
232 #if defined(OS_MACOSX)
233 // Mac needs them too for scrollbar related images and for sandbox
234 // profiles.
235 #if !defined(DISABLE_NACL)
236 process_type == switches::kNaClLoaderProcess ||
237 #endif
238 process_type == switches::kPpapiPluginProcess ||
239 process_type == switches::kPpapiBrokerProcess ||
240 process_type == switches::kGpuProcess ||
241 #endif
242 process_type == switches::kRendererProcess ||
243 process_type == switches::kUtilityProcess;
246 #if defined(OS_POSIX)
247 // Check for --version and --product-version; return true if we encountered
248 // one of these switches and should exit now.
249 bool HandleVersionSwitches(const CommandLine& command_line) {
250 const chrome::VersionInfo version_info;
252 #if !defined(OS_MACOSX)
253 if (command_line.HasSwitch(switches::kProductVersion)) {
254 printf("%s\n", version_info.Version().c_str());
255 return true;
257 #endif
259 if (command_line.HasSwitch(switches::kVersion)) {
260 printf("%s %s %s\n",
261 version_info.Name().c_str(),
262 version_info.Version().c_str(),
263 chrome::VersionInfo::GetVersionStringModifier().c_str());
264 return true;
267 return false;
270 #if !defined(OS_MACOSX) && !defined(OS_CHROMEOS)
271 // Show the man page if --help or -h is on the command line.
272 void HandleHelpSwitches(const CommandLine& command_line) {
273 if (command_line.HasSwitch(switches::kHelp) ||
274 command_line.HasSwitch(switches::kHelpShort)) {
275 base::FilePath binary(command_line.argv()[0]);
276 execlp("man", "man", binary.BaseName().value().c_str(), NULL);
277 PLOG(FATAL) << "execlp failed";
280 #endif
282 #if !defined(OS_MACOSX) && !defined(OS_ANDROID)
283 void SIGTERMProfilingShutdown(int signal) {
284 Profiling::Stop();
285 struct sigaction sigact;
286 memset(&sigact, 0, sizeof(sigact));
287 sigact.sa_handler = SIG_DFL;
288 CHECK(sigaction(SIGTERM, &sigact, NULL) == 0);
289 raise(signal);
292 void SetUpProfilingShutdownHandler() {
293 struct sigaction sigact;
294 sigact.sa_handler = SIGTERMProfilingShutdown;
295 sigact.sa_flags = SA_RESETHAND;
296 sigemptyset(&sigact.sa_mask);
297 CHECK(sigaction(SIGTERM, &sigact, NULL) == 0);
299 #endif // !defined(OS_MACOSX) && !defined(OS_ANDROID)
301 #endif // OS_POSIX
303 struct MainFunction {
304 const char* name;
305 int (*function)(const content::MainFunctionParams&);
308 // Initializes the user data dir. Must be called before InitializeLocalState().
309 void InitializeUserDataDir() {
310 CommandLine* command_line = CommandLine::ForCurrentProcess();
311 base::FilePath user_data_dir =
312 command_line->GetSwitchValuePath(switches::kUserDataDir);
313 std::string process_type =
314 command_line->GetSwitchValueASCII(switches::kProcessType);
316 #if defined(OS_LINUX)
317 // On Linux, Chrome does not support running multiple copies under different
318 // DISPLAYs, so the profile directory can be specified in the environment to
319 // support the virtual desktop use-case.
320 if (user_data_dir.empty()) {
321 std::string user_data_dir_string;
322 scoped_ptr<base::Environment> environment(base::Environment::Create());
323 if (environment->GetVar("CHROME_USER_DATA_DIR", &user_data_dir_string) &&
324 base::IsStringUTF8(user_data_dir_string)) {
325 user_data_dir = base::FilePath::FromUTF8Unsafe(user_data_dir_string);
328 #endif
329 #if defined(OS_MACOSX) || defined(OS_WIN)
330 policy::path_parser::CheckUserDataDirPolicy(&user_data_dir);
331 #endif
333 const bool specified_directory_was_invalid = !user_data_dir.empty() &&
334 !PathService::OverrideAndCreateIfNeeded(chrome::DIR_USER_DATA,
335 user_data_dir, false, true);
336 // Save inaccessible or invalid paths so the user may be prompted later.
337 if (specified_directory_was_invalid)
338 chrome::SetInvalidSpecifiedUserDataDir(user_data_dir);
340 // Warn and fail early if the process fails to get a user data directory.
341 if (!PathService::Get(chrome::DIR_USER_DATA, &user_data_dir)) {
342 // If an invalid command-line or policy override was specified, the user
343 // will be given an error with that value. Otherwise, use the directory
344 // returned by PathService (or the fallback default directory) in the error.
345 if (!specified_directory_was_invalid) {
346 // PathService::Get() returns false and yields an empty path if it fails
347 // to create DIR_USER_DATA. Retrieve the default value manually to display
348 // a more meaningful error to the user in that case.
349 if (user_data_dir.empty())
350 chrome::GetDefaultUserDataDirectory(&user_data_dir);
351 chrome::SetInvalidSpecifiedUserDataDir(user_data_dir);
354 // The browser process (which is identified by an empty |process_type|) will
355 // handle the error later; other processes that need the dir crash here.
356 CHECK(process_type.empty()) << "Unable to get the user data directory "
357 << "for process type: " << process_type;
360 // Append the fallback user data directory to the commandline. Otherwise,
361 // child or service processes will attempt to use the invalid directory.
362 if (specified_directory_was_invalid)
363 command_line->AppendSwitchPath(switches::kUserDataDir, user_data_dir);
366 } // namespace
368 ChromeMainDelegate::ChromeMainDelegate() {
369 #if defined(OS_ANDROID)
370 // On Android the main entry point time is the time when the Java code starts.
371 // This happens before the shared library containing this code is even loaded.
372 // The Java startup code has recorded that time, but the C++ code can't fetch it
373 // from the Java side until it has initialized the JNI. See
374 // ChromeMainDelegateAndroid.
375 #else
376 startup_metric_utils::RecordMainEntryPointTime();
377 #endif
380 ChromeMainDelegate::~ChromeMainDelegate() {
383 bool ChromeMainDelegate::BasicStartupComplete(int* exit_code) {
384 #if defined(OS_CHROMEOS)
385 chromeos::BootTimesLoader::Get()->SaveChromeMainStats();
386 #endif
388 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
390 #if defined(OS_MACOSX)
391 // Give the browser process a longer treadmill, since crashes
392 // there have more impact.
393 const bool is_browser = !command_line.HasSwitch(switches::kProcessType);
394 ObjcEvilDoers::ZombieEnable(true, is_browser ? 10000 : 1000);
396 SetUpBundleOverrides();
397 chrome::common::mac::EnableCFBundleBlocker();
398 #endif
400 Profiling::ProcessStarted();
402 #if defined(OS_POSIX)
403 if (HandleVersionSwitches(command_line)) {
404 *exit_code = 0;
405 return true; // Got a --version switch; exit with a success error code.
407 #if !defined(OS_MACOSX) && !defined(OS_CHROMEOS)
408 // This will directly exit if the user asked for help.
409 HandleHelpSwitches(command_line);
410 #endif
411 #endif // OS_POSIX
413 #if defined(OS_WIN)
414 // Must do this before any other usage of command line!
415 if (HasDeprecatedArguments(command_line.GetCommandLineString())) {
416 *exit_code = 1;
417 return true;
419 #endif
421 chrome::RegisterPathProvider();
422 #if defined(OS_CHROMEOS)
423 chromeos::RegisterPathProvider();
424 #endif
425 #if !defined(DISABLE_NACL) && defined(OS_LINUX)
426 nacl::RegisterPathProvider();
427 #endif
429 // No support for ANDROID yet as DiagnosticsController needs wchar support.
430 // TODO(gspencer): That's not true anymore, or at least there are no w-string
431 // references anymore. Not sure if that means this can be enabled on Android or
432 // not though. As there is no easily accessible command line on Android, I'm
433 // not sure this is a big deal.
434 #if !defined(OS_ANDROID) && !defined(CHROME_MULTIPLE_DLL_CHILD)
435 // If we are in diagnostics mode this is the end of the line: after the
436 // diagnostics are run the process will invariably exit.
437 if (command_line.HasSwitch(switches::kDiagnostics)) {
438 diagnostics::DiagnosticsWriter::FormatType format =
439 diagnostics::DiagnosticsWriter::HUMAN;
440 if (command_line.HasSwitch(switches::kDiagnosticsFormat)) {
441 std::string format_str =
442 command_line.GetSwitchValueASCII(switches::kDiagnosticsFormat);
443 if (format_str == "machine") {
444 format = diagnostics::DiagnosticsWriter::MACHINE;
445 } else if (format_str == "log") {
446 format = diagnostics::DiagnosticsWriter::LOG;
447 } else {
448 DCHECK_EQ("human", format_str);
452 diagnostics::DiagnosticsWriter writer(format);
453 *exit_code = diagnostics::DiagnosticsController::GetInstance()->Run(
454 command_line, &writer);
455 diagnostics::DiagnosticsController::GetInstance()->ClearResults();
456 return true;
458 #endif
460 #if defined(OS_CHROMEOS)
461 // Initialize primary user homedir (in multi-profile session) as it may be
462 // passed as a command line switch.
463 base::FilePath homedir;
464 if (command_line.HasSwitch(chromeos::switches::kHomedir)) {
465 homedir = base::FilePath(
466 command_line.GetSwitchValueASCII(chromeos::switches::kHomedir));
467 PathService::OverrideAndCreateIfNeeded(
468 base::DIR_HOME, homedir, true, false);
471 // If we are recovering from a crash on ChromeOS, then we will do some
472 // recovery using the diagnostics module, and then continue on. We fake up a
473 // command line to tell it that we want it to recover, and to preserve the
474 // original command line.
475 if (command_line.HasSwitch(chromeos::switches::kLoginUser) ||
476 command_line.HasSwitch(switches::kDiagnosticsRecovery)) {
478 // The statistics subsystem needs get initialized soon enough for the
479 // statistics to be collected. It's safe to call this more than once.
480 base::StatisticsRecorder::Initialize();
482 CommandLine interim_command_line(command_line.GetProgram());
483 const char* kSwitchNames[] = {switches::kUserDataDir, };
484 interim_command_line.CopySwitchesFrom(
485 command_line, kSwitchNames, arraysize(kSwitchNames));
486 interim_command_line.AppendSwitch(switches::kDiagnostics);
487 interim_command_line.AppendSwitch(switches::kDiagnosticsRecovery);
489 diagnostics::DiagnosticsWriter::FormatType format =
490 diagnostics::DiagnosticsWriter::LOG;
491 if (command_line.HasSwitch(switches::kDiagnosticsFormat)) {
492 std::string format_str =
493 command_line.GetSwitchValueASCII(switches::kDiagnosticsFormat);
494 if (format_str == "machine") {
495 format = diagnostics::DiagnosticsWriter::MACHINE;
496 } else if (format_str == "human") {
497 format = diagnostics::DiagnosticsWriter::HUMAN;
498 } else {
499 DCHECK_EQ("log", format_str);
503 diagnostics::DiagnosticsWriter writer(format);
504 int diagnostics_exit_code =
505 diagnostics::DiagnosticsController::GetInstance()->Run(command_line,
506 &writer);
507 if (diagnostics_exit_code) {
508 // Diagnostics has failed somehow, so we exit.
509 *exit_code = diagnostics_exit_code;
510 return true;
513 // Now we run the actual recovery tasks.
514 int recovery_exit_code =
515 diagnostics::DiagnosticsController::GetInstance()->RunRecovery(
516 command_line, &writer);
518 if (recovery_exit_code) {
519 // Recovery has failed somehow, so we exit.
520 *exit_code = recovery_exit_code;
521 return true;
523 } else { // Not running diagnostics or recovery.
524 diagnostics::DiagnosticsController::GetInstance()->RecordRegularStartup();
526 #endif
528 content::SetContentClient(&chrome_content_client_);
530 return false;
533 #if defined(OS_MACOSX)
534 void ChromeMainDelegate::InitMacCrashReporter(
535 const base::CommandLine& command_line,
536 const std::string& process_type) {
537 // TODO(mark): Right now, InitCrashReporter() needs to be called after
538 // CommandLine::Init() and chrome::RegisterPathProvider(). Ideally,
539 // Breakpad initialization could occur sooner, preferably even before the
540 // framework dylib is even loaded, to catch potential early crashes.
541 breakpad::InitCrashReporter(process_type);
543 #if defined(NDEBUG)
544 bool is_debug_build = false;
545 #else
546 bool is_debug_build = true;
547 #endif
549 // Details on when we enable Apple's Crash reporter.
551 // Motivation:
552 // In debug mode it takes Apple's crash reporter eons to generate a crash
553 // dump.
555 // What we do:
556 // * We only pass crashes for foreground processes to Apple's Crash
557 // reporter. At the time of this writing, that means just the Browser
558 // process.
559 // * If Breakpad is enabled, it will pass browser crashes to Crash Reporter
560 // itself.
561 // * If Breakpad is disabled, we only turn on Crash Reporter for the
562 // Browser process in release mode.
563 if (base::mac::IsBackgroundOnlyProcess() ||
564 breakpad::IsCrashReporterEnabled() ||
565 is_debug_build) {
566 base::mac::DisableOSCrashDumps();
569 // Mac Chrome is packaged with a main app bundle and a helper app bundle.
570 // The main app bundle should only be used for the browser process, so it
571 // should never see a --type switch (switches::kProcessType). Likewise,
572 // the helper should always have a --type switch.
574 // This check is done this late so there is already a call to
575 // base::mac::IsBackgroundOnlyProcess(), so there is no change in
576 // startup/initialization order.
578 // The helper's Info.plist marks it as a background only app.
579 if (base::mac::IsBackgroundOnlyProcess()) {
580 CHECK(command_line.HasSwitch(switches::kProcessType) &&
581 !process_type.empty())
582 << "Helper application requires --type.";
584 // In addition, some helper flavors only work with certain process types.
585 base::FilePath executable;
586 if (PathService::Get(base::FILE_EXE, &executable) &&
587 executable.value().size() >= 3) {
588 std::string last_three =
589 executable.value().substr(executable.value().size() - 3);
591 if (last_three == " EH") {
592 CHECK(process_type == switches::kPluginProcess ||
593 process_type == switches::kUtilityProcess)
594 << "Executable-heap process requires --type="
595 << switches::kPluginProcess << " or "
596 << switches::kUtilityProcess << ", saw " << process_type;
597 } else if (last_three == " NP") {
598 #if !defined(DISABLE_NACL)
599 CHECK_EQ(switches::kNaClLoaderProcess, process_type)
600 << "Non-PIE process requires --type="
601 << switches::kNaClLoaderProcess << ", saw " << process_type;
602 #endif
603 } else {
604 #if defined(DISABLE_NACL)
605 CHECK(process_type != switches::kPluginProcess)
606 << "Non-executable-heap PIE process is intolerant of --type="
607 << switches::kPluginProcess;
608 #else
609 CHECK(process_type != switches::kPluginProcess &&
610 process_type != switches::kNaClLoaderProcess)
611 << "Non-executable-heap PIE process is intolerant of --type="
612 << switches::kPluginProcess << " and "
613 << switches::kNaClLoaderProcess << ", saw " << process_type;
614 #endif
617 } else {
618 CHECK(!command_line.HasSwitch(switches::kProcessType) &&
619 process_type.empty())
620 << "Main application forbids --type, saw " << process_type;
623 if (breakpad::IsCrashReporterEnabled())
624 breakpad::InitCrashProcessInfo(process_type);
626 #endif // defined(OS_MACOSX)
628 void ChromeMainDelegate::PreSandboxStartup() {
629 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
630 std::string process_type =
631 command_line.GetSwitchValueASCII(switches::kProcessType);
633 #if defined(OS_POSIX)
634 breakpad::SetBreakpadClient(g_chrome_breakpad_client.Pointer());
635 #endif
637 #if defined(OS_MACOSX)
638 // On the Mac, the child executable lives at a predefined location within
639 // the app bundle's versioned directory.
640 PathService::Override(content::CHILD_PROCESS_EXE,
641 chrome::GetVersionedDirectory().
642 Append(chrome::kHelperProcessExecutablePath));
644 InitMacCrashReporter(command_line, process_type);
645 #endif
647 #if defined(OS_WIN)
648 child_process_logging::Init();
649 #endif
650 #if defined(ARCH_CPU_ARM_FAMILY) && (defined(OS_ANDROID) || defined(OS_LINUX))
651 // Create an instance of the CPU class to parse /proc/cpuinfo and cache
652 // cpu_brand info.
653 base::CPU cpu_info;
654 #endif
656 // Initialize the user data dir for any process type that needs it.
657 if (chrome::ProcessNeedsProfileDir(process_type))
658 InitializeUserDataDir();
660 // Register component_updater PathProvider after DIR_USER_DATA overidden by
661 // command line flags. Maybe move the chrome PathProvider down here also?
662 component_updater::RegisterPathProvider(chrome::DIR_USER_DATA);
664 stats_counter_timer_.reset(new base::StatsCounterTimer("Chrome.Init"));
665 startup_timer_.reset(new base::StatsScope<base::StatsCounterTimer>
666 (*stats_counter_timer_));
668 // Enable Message Loop related state asap.
669 if (command_line.HasSwitch(switches::kMessageLoopHistogrammer))
670 base::MessageLoop::EnableHistogrammer(true);
672 #if !defined(OS_ANDROID)
673 // Android does InitLogging when library is loaded. Skip here.
674 logging::OldFileDeletionState file_state =
675 logging::APPEND_TO_OLD_LOG_FILE;
676 if (process_type.empty()) {
677 file_state = logging::DELETE_OLD_LOG_FILE;
679 logging::InitChromeLogging(command_line, file_state);
680 #endif
682 #if defined(OS_WIN)
683 // TODO(zturner): Throbber icons are still stored in chrome.dll, this can be
684 // killed once those are merged into resources.pak. See
685 // GlassBrowserFrameView::InitThrobberIcons() and http://crbug.com/368327.
686 ui::SetResourcesDataDLL(_AtlBaseModule.GetResourceInstance());
687 #endif
689 if (SubprocessNeedsResourceBundle(process_type)) {
690 // Initialize ResourceBundle which handles files loaded from external
691 // sources. The language should have been passed in to us from the
692 // browser process as a command line flag.
693 #if defined(DISABLE_NACL)
694 DCHECK(command_line.HasSwitch(switches::kLang) ||
695 process_type == switches::kZygoteProcess ||
696 process_type == switches::kGpuProcess ||
697 process_type == switches::kPpapiBrokerProcess ||
698 process_type == switches::kPpapiPluginProcess);
699 #else
700 DCHECK(command_line.HasSwitch(switches::kLang) ||
701 process_type == switches::kZygoteProcess ||
702 process_type == switches::kGpuProcess ||
703 process_type == switches::kNaClLoaderProcess ||
704 process_type == switches::kPpapiBrokerProcess ||
705 process_type == switches::kPpapiPluginProcess);
706 #endif
708 // TODO(markusheintz): The command line flag --lang is actually processed
709 // by the CommandLinePrefStore, and made available through the PrefService
710 // via the preference prefs::kApplicationLocale. The browser process uses
711 // the --lang flag to pass the value of the PrefService in here. Maybe
712 // this value could be passed in a different way.
713 const std::string locale =
714 command_line.GetSwitchValueASCII(switches::kLang);
715 #if defined(OS_ANDROID)
716 // The renderer sandbox prevents us from accessing our .pak files directly.
717 // Therefore file descriptors to the .pak files that we need are passed in
718 // at process creation time.
719 int locale_pak_fd = base::GlobalDescriptors::GetInstance()->MaybeGet(
720 kAndroidLocalePakDescriptor);
721 CHECK(locale_pak_fd != -1);
722 ResourceBundle::InitSharedInstanceWithPakFileRegion(
723 base::File(locale_pak_fd), base::MemoryMappedFile::Region::kWholeFile);
725 int extra_pak_keys[] = {
726 kAndroidChrome100PercentPakDescriptor,
727 kAndroidUIResourcesPakDescriptor,
729 for (size_t i = 0; i < arraysize(extra_pak_keys); ++i) {
730 int pak_fd =
731 base::GlobalDescriptors::GetInstance()->MaybeGet(extra_pak_keys[i]);
732 CHECK(pak_fd != -1);
733 ResourceBundle::GetSharedInstance().AddDataPackFromFile(
734 base::File(pak_fd), ui::SCALE_FACTOR_100P);
737 base::i18n::SetICUDefaultLocale(locale);
738 const std::string loaded_locale = locale;
739 #else
740 const std::string loaded_locale =
741 ui::ResourceBundle::InitSharedInstanceWithLocale(
742 locale, NULL, ui::ResourceBundle::LOAD_COMMON_RESOURCES);
744 base::FilePath resources_pack_path;
745 PathService::Get(chrome::FILE_RESOURCES_PACK, &resources_pack_path);
746 ResourceBundle::GetSharedInstance().AddDataPackFromPath(
747 resources_pack_path, ui::SCALE_FACTOR_NONE);
748 #endif
749 CHECK(!loaded_locale.empty()) << "Locale could not be found for " <<
750 locale;
752 #if !defined(CHROME_MULTIPLE_DLL_BROWSER)
753 if (process_type == switches::kUtilityProcess ||
754 process_type == switches::kZygoteProcess) {
755 ChromeContentUtilityClient::PreSandboxStartup();
757 #endif
760 #if defined(OS_POSIX) && !defined(OS_MACOSX)
761 // Zygote needs to call InitCrashReporter() in RunZygote().
762 if (process_type != switches::kZygoteProcess) {
763 #if defined(OS_ANDROID)
764 if (process_type.empty())
765 breakpad::InitCrashReporter(process_type);
766 else
767 breakpad::InitNonBrowserCrashReporterForAndroid(process_type);
768 #else // !defined(OS_ANDROID)
769 breakpad::InitCrashReporter(process_type);
770 #endif // defined(OS_ANDROID)
772 #endif // defined(OS_POSIX) && !defined(OS_MACOSX)
774 // After all the platform Breakpads have been initialized, store the command
775 // line for crash reporting.
776 crash_keys::SetSwitchesFromCommandLine(&command_line);
779 void ChromeMainDelegate::SandboxInitialized(const std::string& process_type) {
780 startup_timer_->Stop(); // End of Startup Time Measurement.
782 // Note: If you are adding a new process type below, be sure to adjust the
783 // AdjustLinuxOOMScore function too.
784 #if defined(OS_LINUX)
785 AdjustLinuxOOMScore(process_type);
786 #endif
787 #if defined(OS_WIN)
788 SuppressWindowsErrorDialogs();
789 #endif
792 int ChromeMainDelegate::RunProcess(
793 const std::string& process_type,
794 const content::MainFunctionParams& main_function_params) {
795 // ANDROID doesn't support "service", so no ServiceProcessMain, and arraysize
796 // doesn't support empty array. So we comment out the block for Android.
797 #if !defined(OS_ANDROID)
798 static const MainFunction kMainFunctions[] = {
799 #if defined(ENABLE_FULL_PRINTING) && !defined(CHROME_MULTIPLE_DLL_CHILD)
800 { switches::kServiceProcess, ServiceProcessMain },
801 #endif
803 #if defined(OS_MACOSX)
804 { switches::kRelauncherProcess,
805 mac_relauncher::internal::RelauncherMain },
806 #endif
808 // This entry is not needed on Linux, where the NaCl loader
809 // process is launched via nacl_helper instead.
810 #if !defined(DISABLE_NACL) && !defined(CHROME_MULTIPLE_DLL_BROWSER) && \
811 !defined(OS_LINUX)
812 { switches::kNaClLoaderProcess, NaClMain },
813 #else
814 { "<invalid>", NULL }, // To avoid constant array of size 0
815 // when DISABLE_NACL and CHROME_MULTIPLE_DLL_CHILD
816 #endif // DISABLE_NACL
819 for (size_t i = 0; i < arraysize(kMainFunctions); ++i) {
820 if (process_type == kMainFunctions[i].name)
821 return kMainFunctions[i].function(main_function_params);
823 #endif
825 return -1;
828 void ChromeMainDelegate::ProcessExiting(const std::string& process_type) {
829 if (SubprocessNeedsResourceBundle(process_type))
830 ResourceBundle::CleanupSharedInstance();
831 #if !defined(OS_ANDROID)
832 logging::CleanupChromeLogging();
833 #else
834 // Android doesn't use InitChromeLogging, so we close the log file manually.
835 logging::CloseLogFile();
836 #endif // !defined(OS_ANDROID)
839 #if defined(OS_MACOSX)
840 bool ChromeMainDelegate::ProcessRegistersWithSystemProcess(
841 const std::string& process_type) {
842 #if defined(DISABLE_NACL)
843 return false;
844 #else
845 return process_type == switches::kNaClLoaderProcess;
846 #endif
849 bool ChromeMainDelegate::ShouldSendMachPort(const std::string& process_type) {
850 return process_type != switches::kRelauncherProcess &&
851 process_type != switches::kServiceProcess;
854 bool ChromeMainDelegate::DelaySandboxInitialization(
855 const std::string& process_type) {
856 #if !defined(DISABLE_NACL)
857 // NaClLoader does this in NaClMainPlatformDelegate::EnableSandbox().
858 // No sandbox needed for relauncher.
859 if (process_type == switches::kNaClLoaderProcess)
860 return true;
861 #endif
862 return process_type == switches::kRelauncherProcess;
864 #elif defined(OS_POSIX) && !defined(OS_ANDROID)
865 void ChromeMainDelegate::ZygoteStarting(
866 ScopedVector<content::ZygoteForkDelegate>* delegates) {
867 #if !defined(DISABLE_NACL)
868 nacl::AddNaClZygoteForkDelegates(delegates);
869 #endif
872 void ChromeMainDelegate::ZygoteForked() {
873 Profiling::ProcessStarted();
874 if (Profiling::BeingProfiled()) {
875 base::debug::RestartProfilingAfterFork();
876 SetUpProfilingShutdownHandler();
879 // Needs to be called after we have chrome::DIR_USER_DATA. BrowserMain sets
880 // this up for the browser process in a different manner.
881 const CommandLine* command_line = CommandLine::ForCurrentProcess();
882 std::string process_type =
883 command_line->GetSwitchValueASCII(switches::kProcessType);
884 breakpad::InitCrashReporter(process_type);
886 // Reset the command line for the newly spawned process.
887 crash_keys::SetSwitchesFromCommandLine(command_line);
890 #endif // OS_MACOSX
892 #if defined(OS_WIN)
893 bool ChromeMainDelegate::ShouldEnableTerminationOnHeapCorruption() {
894 return !ShouldExperimentallyDisableTerminateOnHeapCorruption();
896 #endif // OS_WIN
898 content::ContentBrowserClient*
899 ChromeMainDelegate::CreateContentBrowserClient() {
900 #if defined(CHROME_MULTIPLE_DLL_CHILD)
901 return NULL;
902 #else
903 return g_chrome_content_browser_client.Pointer();
904 #endif
907 content::ContentPluginClient* ChromeMainDelegate::CreateContentPluginClient() {
908 #if defined(CHROME_MULTIPLE_DLL_BROWSER)
909 return NULL;
910 #else
911 return g_chrome_content_plugin_client.Pointer();
912 #endif
915 content::ContentRendererClient*
916 ChromeMainDelegate::CreateContentRendererClient() {
917 #if defined(CHROME_MULTIPLE_DLL_BROWSER)
918 return NULL;
919 #else
920 return g_chrome_content_renderer_client.Pointer();
921 #endif
924 content::ContentUtilityClient*
925 ChromeMainDelegate::CreateContentUtilityClient() {
926 #if defined(CHROME_MULTIPLE_DLL_BROWSER)
927 return NULL;
928 #else
929 return g_chrome_content_utility_client.Pointer();
930 #endif