Upstream version 10.38.220.0
[platform/framework/web/crosswalk.git] / src / chrome / app / chrome_main_delegate.cc
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.
4
5 #include "chrome/app/chrome_main_delegate.h"
6
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"
42
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
52
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/breakpad/app/breakpad_mac.h"
61 #include "ui/base/l10n/l10n_util_mac.h"
62 #endif
63
64 #if defined(OS_POSIX)
65 #include <locale.h>
66 #include <signal.h>
67 #include "chrome/app/chrome_breakpad_client.h"
68 #include "components/breakpad/app/breakpad_client.h"
69 #endif
70
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
75
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
82
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
90
91 #if defined(USE_X11)
92 #include <stdlib.h>
93 #include <string.h>
94 #include "ui/base/x/x11_util.h"
95 #endif
96
97 #if defined(OS_POSIX) && !defined(OS_MACOSX)
98 #include "components/breakpad/app/breakpad_linux.h"
99 #endif
100
101 #if defined(OS_LINUX)
102 #include "base/environment.h"
103 #endif
104
105 #if defined(OS_MACOSX) || defined(OS_WIN)
106 #include "chrome/browser/policy/policy_path_parser.h"
107 #endif
108
109 #if !defined(DISABLE_NACL)
110 #include "components/nacl/common/nacl_switches.h"
111 #endif
112
113 #if !defined(CHROME_MULTIPLE_DLL_CHILD)
114 base::LazyInstance<chrome::ChromeContentBrowserClient>
115     g_chrome_content_browser_client = LAZY_INSTANCE_INITIALIZER;
116 #endif
117
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
126
127 #if defined(OS_POSIX)
128 base::LazyInstance<chrome::ChromeBreakpadClient>::Leaky
129     g_chrome_breakpad_client = LAZY_INSTANCE_INITIALIZER;
130 #endif
131
132 extern int NaClMain(const content::MainFunctionParams&);
133 extern int ServiceProcessMain(const content::MainFunctionParams&);
134
135 namespace {
136
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);
148 }
149
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;
155
156   // Preserve existing error mode.
157   UINT existing_flags = SetErrorMode(new_flags);
158   SetErrorMode(existing_flags | new_flags);
159 }
160
161 #endif  // defined(OS_WIN)
162
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;
180
181   DCHECK(kMiscScore > 0);
182   DCHECK(kPluginScore > 0);
183
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";
213   }
214   if (score > -1)
215     base::AdjustOOMScore(base::GetCurrentProcId(), score);
216 }
217 #endif  // defined(OS_LINUX)
218
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;
244 }
245
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;
251
252 #if !defined(OS_MACOSX)
253   if (command_line.HasSwitch(switches::kProductVersion)) {
254     printf("%s\n", version_info.Version().c_str());
255     return true;
256   }
257 #endif
258
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;
265   }
266
267   return false;
268 }
269
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";
278   }
279 }
280 #endif
281
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);
290 }
291
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);
298 }
299 #endif  // !defined(OS_MACOSX) && !defined(OS_ANDROID)
300
301 #endif  // OS_POSIX
302
303 struct MainFunction {
304   const char* name;
305   int (*function)(const content::MainFunctionParams&);
306 };
307
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);
315
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);
326     }
327   }
328 #endif
329 #if defined(OS_MACOSX) || defined(OS_WIN)
330   policy::path_parser::CheckUserDataDirPolicy(&user_data_dir);
331 #endif
332
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);
339
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);
352     }
353
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;
358   }
359
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);
364 }
365
366 }  // namespace
367
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
378 }
379
380 ChromeMainDelegate::~ChromeMainDelegate() {
381 }
382
383 bool ChromeMainDelegate::BasicStartupComplete(int* exit_code) {
384 #if defined(OS_CHROMEOS)
385   chromeos::BootTimesLoader::Get()->SaveChromeMainStats();
386 #endif
387
388   const CommandLine& command_line = *CommandLine::ForCurrentProcess();
389
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);
395
396   SetUpBundleOverrides();
397   chrome::common::mac::EnableCFBundleBlocker();
398 #endif
399
400   Profiling::ProcessStarted();
401
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.
406   }
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
412
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;
418   }
419 #endif
420
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
428
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);
449       }
450     }
451
452     diagnostics::DiagnosticsWriter writer(format);
453     *exit_code = diagnostics::DiagnosticsController::GetInstance()->Run(
454         command_line, &writer);
455     diagnostics::DiagnosticsController::GetInstance()->ClearResults();
456     return true;
457   }
458 #endif
459
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);
469   }
470
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)) {
477
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();
481
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);
488
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);
500       }
501     }
502
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;
511     }
512
513     // Now we run the actual recovery tasks.
514     int recovery_exit_code =
515         diagnostics::DiagnosticsController::GetInstance()->RunRecovery(
516             command_line, &writer);
517
518     if (recovery_exit_code) {
519       // Recovery has failed somehow, so we exit.
520       *exit_code = recovery_exit_code;
521       return true;
522     }
523   } else {  // Not running diagnostics or recovery.
524     diagnostics::DiagnosticsController::GetInstance()->RecordRegularStartup();
525   }
526 #endif
527
528   content::SetContentClient(&chrome_content_client_);
529
530   return false;
531 }
532
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);
542
543 #if defined(NDEBUG)
544   bool is_debug_build = false;
545 #else
546   bool is_debug_build = true;
547 #endif
548
549   // Details on when we enable Apple's Crash reporter.
550   //
551   // Motivation:
552   //    In debug mode it takes Apple's crash reporter eons to generate a crash
553   // dump.
554   //
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 (!command_line.HasSwitch(switches::kDisableBreakpad)) {
564     bool disable_apple_crash_reporter = is_debug_build ||
565         base::mac::IsBackgroundOnlyProcess();
566     if (!breakpad::IsCrashReporterEnabled() && disable_apple_crash_reporter) {
567       base::mac::DisableOSCrashDumps();
568     }
569   }
570
571   // Mac Chrome is packaged with a main app bundle and a helper app bundle.
572   // The main app bundle should only be used for the browser process, so it
573   // should never see a --type switch (switches::kProcessType).  Likewise,
574   // the helper should always have a --type switch.
575   //
576   // This check is done this late so there is already a call to
577   // base::mac::IsBackgroundOnlyProcess(), so there is no change in
578   // startup/initialization order.
579
580   // The helper's Info.plist marks it as a background only app.
581   if (base::mac::IsBackgroundOnlyProcess()) {
582     CHECK(command_line.HasSwitch(switches::kProcessType) &&
583           !process_type.empty())
584         << "Helper application requires --type.";
585
586     // In addition, some helper flavors only work with certain process types.
587     base::FilePath executable;
588     if (PathService::Get(base::FILE_EXE, &executable) &&
589         executable.value().size() >= 3) {
590       std::string last_three =
591           executable.value().substr(executable.value().size() - 3);
592
593       if (last_three == " EH") {
594         CHECK(process_type == switches::kPluginProcess ||
595               process_type == switches::kUtilityProcess)
596             << "Executable-heap process requires --type="
597             << switches::kPluginProcess << " or "
598             << switches::kUtilityProcess << ", saw " << process_type;
599       } else if (last_three == " NP") {
600 #if !defined(DISABLE_NACL)
601         CHECK_EQ(switches::kNaClLoaderProcess, process_type)
602             << "Non-PIE process requires --type="
603             << switches::kNaClLoaderProcess << ", saw " << process_type;
604 #endif
605       } else {
606 #if defined(DISABLE_NACL)
607         CHECK(process_type != switches::kPluginProcess)
608             << "Non-executable-heap PIE process is intolerant of --type="
609             << switches::kPluginProcess;
610 #else
611         CHECK(process_type != switches::kPluginProcess &&
612               process_type != switches::kNaClLoaderProcess)
613             << "Non-executable-heap PIE process is intolerant of --type="
614             << switches::kPluginProcess << " and "
615             << switches::kNaClLoaderProcess << ", saw " << process_type;
616 #endif
617       }
618     }
619   } else {
620     CHECK(!command_line.HasSwitch(switches::kProcessType) &&
621           process_type.empty())
622         << "Main application forbids --type, saw " << process_type;
623   }
624
625   if (breakpad::IsCrashReporterEnabled())
626     breakpad::InitCrashProcessInfo(process_type);
627 }
628 #endif  // defined(OS_MACOSX)
629
630 void ChromeMainDelegate::PreSandboxStartup() {
631   const CommandLine& command_line = *CommandLine::ForCurrentProcess();
632   std::string process_type =
633       command_line.GetSwitchValueASCII(switches::kProcessType);
634
635 #if defined(OS_POSIX)
636   breakpad::SetBreakpadClient(g_chrome_breakpad_client.Pointer());
637 #endif
638
639 #if defined(OS_MACOSX)
640   // On the Mac, the child executable lives at a predefined location within
641   // the app bundle's versioned directory.
642   PathService::Override(content::CHILD_PROCESS_EXE,
643                         chrome::GetVersionedDirectory().
644                         Append(chrome::kHelperProcessExecutablePath));
645
646   InitMacCrashReporter(command_line, process_type);
647 #endif
648
649 #if defined(OS_WIN)
650   child_process_logging::Init();
651 #endif
652 #if defined(ARCH_CPU_ARM_FAMILY) && (defined(OS_ANDROID) || defined(OS_LINUX))
653   // Create an instance of the CPU class to parse /proc/cpuinfo and cache
654   // cpu_brand info.
655   base::CPU cpu_info;
656 #endif
657
658   // Initialize the user data dir for any process type that needs it.
659   if (chrome::ProcessNeedsProfileDir(process_type))
660     InitializeUserDataDir();
661
662   // Register component_updater PathProvider after DIR_USER_DATA overidden by
663   // command line flags. Maybe move the chrome PathProvider down here also?
664   component_updater::RegisterPathProvider(chrome::DIR_USER_DATA);
665
666   stats_counter_timer_.reset(new base::StatsCounterTimer("Chrome.Init"));
667   startup_timer_.reset(new base::StatsScope<base::StatsCounterTimer>
668                        (*stats_counter_timer_));
669
670   // Enable Message Loop related state asap.
671   if (command_line.HasSwitch(switches::kMessageLoopHistogrammer))
672     base::MessageLoop::EnableHistogrammer(true);
673
674 #if !defined(OS_ANDROID)
675   // Android does InitLogging when library is loaded. Skip here.
676   logging::OldFileDeletionState file_state =
677       logging::APPEND_TO_OLD_LOG_FILE;
678   if (process_type.empty()) {
679     file_state = logging::DELETE_OLD_LOG_FILE;
680   }
681   logging::InitChromeLogging(command_line, file_state);
682 #endif
683
684 #if defined(OS_WIN)
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());
689 #endif
690
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);
701 #else
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);
708 #endif
709
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     int locale_pak_fd = base::GlobalDescriptors::GetInstance()->MaybeGet(
722         kAndroidLocalePakDescriptor);
723     CHECK(locale_pak_fd != -1);
724     ResourceBundle::InitSharedInstanceWithPakFileRegion(
725         base::File(locale_pak_fd), base::MemoryMappedFile::Region::kWholeFile);
726
727     int extra_pak_keys[] = {
728       kAndroidChrome100PercentPakDescriptor,
729       kAndroidUIResourcesPakDescriptor,
730     };
731     for (size_t i = 0; i < arraysize(extra_pak_keys); ++i) {
732       int pak_fd =
733           base::GlobalDescriptors::GetInstance()->MaybeGet(extra_pak_keys[i]);
734       CHECK(pak_fd != -1);
735       ResourceBundle::GetSharedInstance().AddDataPackFromFile(
736           base::File(pak_fd), ui::SCALE_FACTOR_100P);
737     }
738
739     base::i18n::SetICUDefaultLocale(locale);
740     const std::string loaded_locale = locale;
741 #else
742     const std::string loaded_locale =
743         ui::ResourceBundle::InitSharedInstanceWithLocale(
744             locale, NULL, ui::ResourceBundle::LOAD_COMMON_RESOURCES);
745
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);
750 #endif
751     CHECK(!loaded_locale.empty()) << "Locale could not be found for " <<
752         locale;
753
754 #if !defined(CHROME_MULTIPLE_DLL_BROWSER)
755     if (process_type == switches::kUtilityProcess ||
756         process_type == switches::kZygoteProcess) {
757       ChromeContentUtilityClient::PreSandboxStartup();
758     }
759 #endif
760   }
761
762 #if defined(OS_POSIX) && !defined(OS_MACOSX)
763   // Zygote needs to call InitCrashReporter() in RunZygote().
764   if (process_type != switches::kZygoteProcess) {
765 #if defined(OS_ANDROID)
766     if (process_type.empty())
767       breakpad::InitCrashReporter(process_type);
768     else
769       breakpad::InitNonBrowserCrashReporterForAndroid(process_type);
770 #else  // !defined(OS_ANDROID)
771     breakpad::InitCrashReporter(process_type);
772 #endif  // defined(OS_ANDROID)
773   }
774 #endif  // defined(OS_POSIX) && !defined(OS_MACOSX)
775
776   // After all the platform Breakpads have been initialized, store the command
777   // line for crash reporting.
778   crash_keys::SetSwitchesFromCommandLine(&command_line);
779 }
780
781 void ChromeMainDelegate::SandboxInitialized(const std::string& process_type) {
782   startup_timer_->Stop();  // End of Startup Time Measurement.
783
784   // Note: If you are adding a new process type below, be sure to adjust the
785   // AdjustLinuxOOMScore function too.
786 #if defined(OS_LINUX)
787   AdjustLinuxOOMScore(process_type);
788 #endif
789 #if defined(OS_WIN)
790   SuppressWindowsErrorDialogs();
791 #endif
792 }
793
794 int ChromeMainDelegate::RunProcess(
795     const std::string& process_type,
796     const content::MainFunctionParams& main_function_params) {
797   // ANDROID doesn't support "service", so no ServiceProcessMain, and arraysize
798   // doesn't support empty array. So we comment out the block for Android.
799 #if !defined(OS_ANDROID)
800   static const MainFunction kMainFunctions[] = {
801 #if defined(ENABLE_FULL_PRINTING) && !defined(CHROME_MULTIPLE_DLL_CHILD)
802     { switches::kServiceProcess,     ServiceProcessMain },
803 #endif
804
805 #if defined(OS_MACOSX)
806     { switches::kRelauncherProcess,
807       mac_relauncher::internal::RelauncherMain },
808 #endif
809
810     // This entry is not needed on Linux, where the NaCl loader
811     // process is launched via nacl_helper instead.
812 #if !defined(DISABLE_NACL) && !defined(CHROME_MULTIPLE_DLL_BROWSER) && \
813     !defined(OS_LINUX)
814     { switches::kNaClLoaderProcess,  NaClMain },
815 #else
816     { "<invalid>", NULL },  // To avoid constant array of size 0
817                             // when DISABLE_NACL and CHROME_MULTIPLE_DLL_CHILD
818 #endif  // DISABLE_NACL
819   };
820
821   for (size_t i = 0; i < arraysize(kMainFunctions); ++i) {
822     if (process_type == kMainFunctions[i].name)
823       return kMainFunctions[i].function(main_function_params);
824   }
825 #endif
826
827   return -1;
828 }
829
830 void ChromeMainDelegate::ProcessExiting(const std::string& process_type) {
831   if (SubprocessNeedsResourceBundle(process_type))
832     ResourceBundle::CleanupSharedInstance();
833 #if !defined(OS_ANDROID)
834   logging::CleanupChromeLogging();
835 #else
836   // Android doesn't use InitChromeLogging, so we close the log file manually.
837   logging::CloseLogFile();
838 #endif  // !defined(OS_ANDROID)
839 }
840
841 #if defined(OS_MACOSX)
842 bool ChromeMainDelegate::ProcessRegistersWithSystemProcess(
843     const std::string& process_type) {
844 #if defined(DISABLE_NACL)
845   return false;
846 #else
847   return process_type == switches::kNaClLoaderProcess;
848 #endif
849 }
850
851 bool ChromeMainDelegate::ShouldSendMachPort(const std::string& process_type) {
852   return process_type != switches::kRelauncherProcess &&
853       process_type != switches::kServiceProcess;
854 }
855
856 bool ChromeMainDelegate::DelaySandboxInitialization(
857     const std::string& process_type) {
858 #if !defined(DISABLE_NACL)
859   // NaClLoader does this in NaClMainPlatformDelegate::EnableSandbox().
860   // No sandbox needed for relauncher.
861   if (process_type == switches::kNaClLoaderProcess)
862     return true;
863 #endif
864   return process_type == switches::kRelauncherProcess;
865 }
866 #elif defined(OS_POSIX) && !defined(OS_ANDROID)
867 void ChromeMainDelegate::ZygoteStarting(
868     ScopedVector<content::ZygoteForkDelegate>* delegates) {
869 #if !defined(DISABLE_NACL)
870   nacl::AddNaClZygoteForkDelegates(delegates);
871 #endif
872 }
873
874 void ChromeMainDelegate::ZygoteForked() {
875   Profiling::ProcessStarted();
876   if (Profiling::BeingProfiled()) {
877     base::debug::RestartProfilingAfterFork();
878     SetUpProfilingShutdownHandler();
879   }
880
881   // Needs to be called after we have chrome::DIR_USER_DATA.  BrowserMain sets
882   // this up for the browser process in a different manner.
883   const CommandLine* command_line = CommandLine::ForCurrentProcess();
884   std::string process_type =
885       command_line->GetSwitchValueASCII(switches::kProcessType);
886   breakpad::InitCrashReporter(process_type);
887
888   // Reset the command line for the newly spawned process.
889   crash_keys::SetSwitchesFromCommandLine(command_line);
890 }
891
892 #endif  // OS_MACOSX
893
894 #if defined(OS_WIN)
895 bool ChromeMainDelegate::ShouldEnableTerminationOnHeapCorruption() {
896   return !ShouldExperimentallyDisableTerminateOnHeapCorruption();
897 }
898 #endif  // OS_WIN
899
900 content::ContentBrowserClient*
901 ChromeMainDelegate::CreateContentBrowserClient() {
902 #if defined(CHROME_MULTIPLE_DLL_CHILD)
903   return NULL;
904 #else
905   return g_chrome_content_browser_client.Pointer();
906 #endif
907 }
908
909 content::ContentPluginClient* ChromeMainDelegate::CreateContentPluginClient() {
910 #if defined(CHROME_MULTIPLE_DLL_BROWSER)
911   return NULL;
912 #else
913   return g_chrome_content_plugin_client.Pointer();
914 #endif
915 }
916
917 content::ContentRendererClient*
918 ChromeMainDelegate::CreateContentRendererClient() {
919 #if defined(CHROME_MULTIPLE_DLL_BROWSER)
920   return NULL;
921 #else
922   return g_chrome_content_renderer_client.Pointer();
923 #endif
924 }
925
926 content::ContentUtilityClient*
927 ChromeMainDelegate::CreateContentUtilityClient() {
928 #if defined(CHROME_MULTIPLE_DLL_BROWSER)
929   return NULL;
930 #else
931   return g_chrome_content_utility_client.Pointer();
932 #endif
933 }