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