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