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