Disable view source for Developer Tools.
[chromium-blink-merge.git] / chrome / app / chrome_main_delegate.cc
blob2b695480b0644b4c5f4436e83118a6b6e8df6410
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/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"
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
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
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
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
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
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
94 #if defined(USE_X11)
95 #include <stdlib.h>
96 #include <string.h>
97 #include "ui/base/x/x11_util.h"
98 #endif
100 #if defined(OS_POSIX) && !defined(OS_MACOSX)
101 #include "components/breakpad/app/breakpad_linux.h"
102 #endif
104 #if !defined(CHROME_MULTIPLE_DLL_CHILD)
105 base::LazyInstance<chrome::ChromeContentBrowserClient>
106 g_chrome_content_browser_client = LAZY_INSTANCE_INITIALIZER;
107 #endif
109 #if !defined(CHROME_MULTIPLE_DLL_BROWSER)
110 base::LazyInstance<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
118 #if defined(OS_POSIX)
119 base::LazyInstance<chrome::ChromeBreakpadClient>::Leaky
120 g_chrome_breakpad_client = LAZY_INSTANCE_INITIALIZER;
121 #endif
123 extern int NaClMain(const content::MainFunctionParams&);
124 extern int ServiceProcessMain(const content::MainFunctionParams&);
126 namespace {
128 #if defined(OS_WIN)
129 const wchar_t kProfilingDll[] = L"memory_watcher.dll";
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;
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);
150 // If we try to access a path that is not currently available, we want the call
151 // to fail rather than show an error dialog.
152 void SuppressWindowsErrorDialogs() {
153 UINT new_flags = SEM_FAILCRITICALERRORS |
154 SEM_NOOPENFILEERRORBOX;
156 // Preserve existing error mode.
157 UINT existing_flags = SetErrorMode(new_flags);
158 SetErrorMode(existing_flags | new_flags);
161 #endif // defined(OS_WIN)
163 #if defined(OS_LINUX)
164 static void AdjustLinuxOOMScore(const std::string& process_type) {
165 // Browsers and zygotes should still be killable, but killed last.
166 const int kZygoteScore = 0;
167 // The minimum amount to bump a score by. This is large enough that
168 // even if it's translated into the old values, it will still go up
169 // by at least one.
170 const int kScoreBump = 100;
171 // This is the lowest score that renderers and extensions start with
172 // in the OomPriorityManager.
173 const int kRendererScore = chrome::kLowestRendererOomScore;
174 // For "miscellaneous" things, we want them after renderers,
175 // but before plugins.
176 const int kMiscScore = kRendererScore - kScoreBump;
177 // We want plugins to die after the renderers.
178 const int kPluginScore = kMiscScore - kScoreBump;
179 int score = -1;
181 DCHECK(kMiscScore > 0);
182 DCHECK(kPluginScore > 0);
184 if (process_type == switches::kPluginProcess ||
185 process_type == switches::kPpapiPluginProcess) {
186 score = kPluginScore;
187 } else if (process_type == switches::kPpapiBrokerProcess) {
188 // The broker should be killed before the PPAPI plugin.
189 score = kPluginScore + kScoreBump;
190 } else if (process_type == switches::kUtilityProcess ||
191 process_type == switches::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";
214 if (score > -1)
215 base::AdjustOOMScore(base::GetCurrentProcId(), score);
217 #endif // defined(OS_LINUX)
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
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 // Needed for scrollbar related images.
238 process_type == switches::kWorkerProcess ||
239 #endif
240 #if defined(OS_POSIX) && !defined(OS_MACOSX)
241 // The zygote process opens the resources for the renderers.
242 process_type == switches::kZygoteProcess ||
243 #endif
244 #if defined(OS_MACOSX)
245 // Mac needs them too for scrollbar related images and for sandbox
246 // profiles.
247 process_type == switches::kNaClLoaderProcess ||
248 process_type == switches::kPpapiPluginProcess ||
249 process_type == switches::kPpapiBrokerProcess ||
250 process_type == switches::kGpuProcess ||
251 #endif
252 process_type == switches::kRendererProcess ||
253 process_type == switches::kUtilityProcess;
256 #if defined(OS_POSIX)
257 // Check for --version and --product-version; return true if we encountered
258 // one of these switches and should exit now.
259 bool HandleVersionSwitches(const CommandLine& command_line) {
260 const chrome::VersionInfo version_info;
262 #if !defined(OS_MACOSX)
263 if (command_line.HasSwitch(switches::kProductVersion)) {
264 printf("%s\n", version_info.Version().c_str());
265 return true;
267 #endif
269 if (command_line.HasSwitch(switches::kVersion)) {
270 printf("%s %s %s\n",
271 version_info.Name().c_str(),
272 version_info.Version().c_str(),
273 chrome::VersionInfo::GetVersionStringModifier().c_str());
274 return true;
277 return false;
280 #if !defined(OS_MACOSX) && !defined(OS_CHROMEOS)
281 // Show the man page if --help or -h is on the command line.
282 void HandleHelpSwitches(const CommandLine& command_line) {
283 if (command_line.HasSwitch(switches::kHelp) ||
284 command_line.HasSwitch(switches::kHelpShort)) {
285 base::FilePath binary(command_line.argv()[0]);
286 execlp("man", "man", binary.BaseName().value().c_str(), NULL);
287 PLOG(FATAL) << "execlp failed";
290 #endif
292 #if !defined(OS_MACOSX) && !defined(OS_ANDROID)
293 void SIGTERMProfilingShutdown(int signal) {
294 Profiling::Stop();
295 struct sigaction sigact;
296 memset(&sigact, 0, sizeof(sigact));
297 sigact.sa_handler = SIG_DFL;
298 CHECK(sigaction(SIGTERM, &sigact, NULL) == 0);
299 raise(signal);
302 void SetUpProfilingShutdownHandler() {
303 struct sigaction sigact;
304 sigact.sa_handler = SIGTERMProfilingShutdown;
305 sigact.sa_flags = SA_RESETHAND;
306 sigemptyset(&sigact.sa_mask);
307 CHECK(sigaction(SIGTERM, &sigact, NULL) == 0);
309 #endif // !defined(OS_MACOSX) && !defined(OS_ANDROID)
311 #endif // OS_POSIX
313 struct MainFunction {
314 const char* name;
315 int (*function)(const content::MainFunctionParams&);
318 } // namespace
320 ChromeMainDelegate::ChromeMainDelegate() {
321 #if defined(OS_ANDROID)
322 // On Android the main entry point time is the time when the Java code starts.
323 // This happens before the shared library containing this code is even loaded.
324 // The Java startup code has recorded that time, but the C++ code can't fetch it
325 // from the Java side until it has initialized the JNI. See
326 // ChromeMainDelegateAndroid.
327 #else
328 startup_metric_utils::RecordMainEntryPointTime();
329 #endif
332 ChromeMainDelegate::~ChromeMainDelegate() {
335 bool ChromeMainDelegate::BasicStartupComplete(int* exit_code) {
336 #if defined(OS_CHROMEOS)
337 chromeos::BootTimesLoader::Get()->SaveChromeMainStats();
338 #endif
340 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
342 #if defined(OS_MACOSX)
343 // Give the browser process a longer treadmill, since crashes
344 // there have more impact.
345 const bool is_browser = !command_line.HasSwitch(switches::kProcessType);
346 ObjcEvilDoers::ZombieEnable(true, is_browser ? 10000 : 1000);
348 SetUpBundleOverrides();
349 chrome::common::mac::EnableCFBundleBlocker();
350 #endif
352 Profiling::ProcessStarted();
354 #if defined(OS_POSIX)
355 if (HandleVersionSwitches(command_line)) {
356 *exit_code = 0;
357 return true; // Got a --version switch; exit with a success error code.
359 #if !defined(OS_MACOSX) && !defined(OS_CHROMEOS)
360 // This will directly exit if the user asked for help.
361 HandleHelpSwitches(command_line);
362 #endif
363 #endif // OS_POSIX
365 #if defined(OS_WIN)
366 // Must do this before any other usage of command line!
367 if (HasDeprecatedArguments(command_line.GetCommandLineString())) {
368 *exit_code = 1;
369 return true;
371 #endif
373 chrome::RegisterPathProvider();
374 #if defined(OS_CHROMEOS)
375 chromeos::RegisterPathProvider();
376 #endif
377 #if !defined(DISABLE_NACL) && defined(OS_LINUX)
378 nacl::RegisterPathProvider();
379 #endif
381 // No support for ANDROID yet as DiagnosticsController needs wchar support.
382 // TODO(gspencer): That's not true anymore, or at least there are no w-string
383 // references anymore. Not sure if that means this can be enabled on Android or
384 // not though. As there is no easily accessible command line on Android, I'm
385 // not sure this is a big deal.
386 #if !defined(OS_ANDROID) && !defined(CHROME_MULTIPLE_DLL_CHILD)
387 // If we are in diagnostics mode this is the end of the line: after the
388 // diagnostics are run the process will invariably exit.
389 if (command_line.HasSwitch(switches::kDiagnostics)) {
390 diagnostics::DiagnosticsWriter::FormatType format =
391 diagnostics::DiagnosticsWriter::HUMAN;
392 if (command_line.HasSwitch(switches::kDiagnosticsFormat)) {
393 std::string format_str =
394 command_line.GetSwitchValueASCII(switches::kDiagnosticsFormat);
395 if (format_str == "machine") {
396 format = diagnostics::DiagnosticsWriter::MACHINE;
397 } else if (format_str == "log") {
398 format = diagnostics::DiagnosticsWriter::LOG;
399 } else {
400 DCHECK_EQ("human", format_str);
404 diagnostics::DiagnosticsWriter writer(format);
405 *exit_code = diagnostics::DiagnosticsController::GetInstance()->Run(
406 command_line, &writer);
407 diagnostics::DiagnosticsController::GetInstance()->ClearResults();
408 return true;
410 #endif
412 #if defined(OS_CHROMEOS)
413 // If we are recovering from a crash on ChromeOS, then we will do some
414 // recovery using the diagnostics module, and then continue on. We fake up a
415 // command line to tell it that we want it to recover, and to preserve the
416 // original command line.
417 if (command_line.HasSwitch(chromeos::switches::kLoginUser) ||
418 command_line.HasSwitch(switches::kDiagnosticsRecovery)) {
420 // The statistics subsystem needs get initialized soon enough for the
421 // statistics to be collected. It's safe to call this more than once.
422 base::StatisticsRecorder::Initialize();
424 CommandLine interim_command_line(command_line.GetProgram());
425 const char* kSwitchNames[] = {switches::kUserDataDir, };
426 interim_command_line.CopySwitchesFrom(
427 command_line, kSwitchNames, arraysize(kSwitchNames));
428 interim_command_line.AppendSwitch(switches::kDiagnostics);
429 interim_command_line.AppendSwitch(switches::kDiagnosticsRecovery);
431 diagnostics::DiagnosticsWriter::FormatType format =
432 diagnostics::DiagnosticsWriter::LOG;
433 if (command_line.HasSwitch(switches::kDiagnosticsFormat)) {
434 std::string format_str =
435 command_line.GetSwitchValueASCII(switches::kDiagnosticsFormat);
436 if (format_str == "machine") {
437 format = diagnostics::DiagnosticsWriter::MACHINE;
438 } else if (format_str == "human") {
439 format = diagnostics::DiagnosticsWriter::HUMAN;
440 } else {
441 DCHECK_EQ("log", format_str);
445 diagnostics::DiagnosticsWriter writer(format);
446 int diagnostics_exit_code =
447 diagnostics::DiagnosticsController::GetInstance()->Run(command_line,
448 &writer);
449 if (diagnostics_exit_code) {
450 // Diagnostics has failed somehow, so we exit.
451 *exit_code = diagnostics_exit_code;
452 return true;
455 // Now we run the actual recovery tasks.
456 int recovery_exit_code =
457 diagnostics::DiagnosticsController::GetInstance()->RunRecovery(
458 command_line, &writer);
460 if (recovery_exit_code) {
461 // Recovery has failed somehow, so we exit.
462 *exit_code = recovery_exit_code;
463 return true;
465 } else { // Not running diagnostics or recovery.
466 diagnostics::DiagnosticsController::GetInstance()->RecordRegularStartup();
468 #endif
470 content::SetContentClient(&chrome_content_client_);
472 return false;
475 #if defined(OS_MACOSX)
476 void ChromeMainDelegate::InitMacCrashReporter(const CommandLine& command_line,
477 const std::string& process_type) {
478 // TODO(mark): Right now, InitCrashReporter() needs to be called after
479 // CommandLine::Init() and chrome::RegisterPathProvider(). Ideally,
480 // Breakpad initialization could occur sooner, preferably even before the
481 // framework dylib is even loaded, to catch potential early crashes.
482 breakpad::InitCrashReporter(process_type);
484 #if defined(NDEBUG)
485 bool is_debug_build = false;
486 #else
487 bool is_debug_build = true;
488 #endif
490 // Details on when we enable Apple's Crash reporter.
492 // Motivation:
493 // In debug mode it takes Apple's crash reporter eons to generate a crash
494 // dump.
496 // What we do:
497 // * We only pass crashes for foreground processes to Apple's Crash
498 // reporter. At the time of this writing, that means just the Browser
499 // process.
500 // * If Breakpad is enabled, it will pass browser crashes to Crash Reporter
501 // itself.
502 // * If Breakpad is disabled, we only turn on Crash Reporter for the
503 // Browser process in release mode.
504 if (!command_line.HasSwitch(switches::kDisableBreakpad)) {
505 bool disable_apple_crash_reporter = is_debug_build ||
506 base::mac::IsBackgroundOnlyProcess();
507 if (!breakpad::IsCrashReporterEnabled() && disable_apple_crash_reporter) {
508 base::mac::DisableOSCrashDumps();
512 // Mac Chrome is packaged with a main app bundle and a helper app bundle.
513 // The main app bundle should only be used for the browser process, so it
514 // should never see a --type switch (switches::kProcessType). Likewise,
515 // the helper should always have a --type switch.
517 // This check is done this late so there is already a call to
518 // base::mac::IsBackgroundOnlyProcess(), so there is no change in
519 // startup/initialization order.
521 // The helper's Info.plist marks it as a background only app.
522 if (base::mac::IsBackgroundOnlyProcess()) {
523 CHECK(command_line.HasSwitch(switches::kProcessType) &&
524 !process_type.empty())
525 << "Helper application requires --type.";
527 // In addition, some helper flavors only work with certain process types.
528 base::FilePath executable;
529 if (PathService::Get(base::FILE_EXE, &executable) &&
530 executable.value().size() >= 3) {
531 std::string last_three =
532 executable.value().substr(executable.value().size() - 3);
534 if (last_three == " EH") {
535 CHECK(process_type == switches::kPluginProcess ||
536 process_type == switches::kUtilityProcess)
537 << "Executable-heap process requires --type="
538 << switches::kPluginProcess << " or "
539 << switches::kUtilityProcess << ", saw " << process_type;
540 } else if (last_three == " NP") {
541 CHECK_EQ(switches::kNaClLoaderProcess, process_type)
542 << "Non-PIE process requires --type="
543 << switches::kNaClLoaderProcess << ", saw " << process_type;
544 } else {
545 CHECK(process_type != switches::kPluginProcess &&
546 process_type != switches::kNaClLoaderProcess)
547 << "Non-executable-heap PIE process is intolerant of --type="
548 << switches::kPluginProcess << " and "
549 << switches::kNaClLoaderProcess << ", saw " << process_type;
552 } else {
553 CHECK(!command_line.HasSwitch(switches::kProcessType) &&
554 process_type.empty())
555 << "Main application forbids --type, saw " << process_type;
558 if (breakpad::IsCrashReporterEnabled())
559 breakpad::InitCrashProcessInfo(process_type);
561 #endif // defined(OS_MACOSX)
563 void ChromeMainDelegate::PreSandboxStartup() {
564 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
565 std::string process_type =
566 command_line.GetSwitchValueASCII(switches::kProcessType);
568 #if defined(OS_POSIX)
569 breakpad::SetBreakpadClient(g_chrome_breakpad_client.Pointer());
570 #endif
572 #if defined(OS_MACOSX)
573 // On the Mac, the child executable lives at a predefined location within
574 // the app bundle's versioned directory.
575 PathService::Override(content::CHILD_PROCESS_EXE,
576 chrome::GetVersionedDirectory().
577 Append(chrome::kHelperProcessExecutablePath));
579 InitMacCrashReporter(command_line, process_type);
580 #endif
582 #if defined(OS_WIN)
583 child_process_logging::Init();
584 #endif
586 // Notice a user data directory override if any
587 base::FilePath user_data_dir =
588 command_line.GetSwitchValuePath(switches::kUserDataDir);
589 #if defined(OS_LINUX)
590 // On Linux, Chrome does not support running multiple copies under different
591 // DISPLAYs, so the profile directory can be specified in the environment to
592 // support the virtual desktop use-case.
593 if (user_data_dir.empty()) {
594 std::string user_data_dir_string;
595 scoped_ptr<base::Environment> environment(base::Environment::Create());
596 if (environment->GetVar("CHROME_USER_DATA_DIR", &user_data_dir_string) &&
597 IsStringUTF8(user_data_dir_string)) {
598 user_data_dir = base::FilePath::FromUTF8Unsafe(user_data_dir_string);
601 #endif
602 #if defined(OS_MACOSX) || defined(OS_WIN)
603 policy::path_parser::CheckUserDataDirPolicy(&user_data_dir);
604 #endif
605 if (!user_data_dir.empty()) {
606 CHECK(PathService::OverrideAndCreateIfNeeded(
607 chrome::DIR_USER_DATA,
608 user_data_dir,
609 chrome::ProcessNeedsProfileDir(process_type)));
612 stats_counter_timer_.reset(new base::StatsCounterTimer("Chrome.Init"));
613 startup_timer_.reset(new base::StatsScope<base::StatsCounterTimer>
614 (*stats_counter_timer_));
616 // Enable the heap profiler as early as possible!
617 EnableHeapProfiler(command_line);
619 // Enable Message Loop related state asap.
620 if (command_line.HasSwitch(switches::kMessageLoopHistogrammer))
621 base::MessageLoop::EnableHistogrammer(true);
623 #if !defined(OS_ANDROID)
624 // Android does InitLogging when library is loaded. Skip here.
625 logging::OldFileDeletionState file_state =
626 logging::APPEND_TO_OLD_LOG_FILE;
627 if (process_type.empty()) {
628 file_state = logging::DELETE_OLD_LOG_FILE;
630 logging::InitChromeLogging(command_line, file_state);
631 #endif
633 #if defined(OS_WIN)
634 // TODO(darin): Kill this once http://crbug.com/52609 is fixed.
635 ui::SetResourcesDataDLL(_AtlBaseModule.GetResourceInstance());
636 #endif
638 if (SubprocessNeedsResourceBundle(process_type)) {
639 // Initialize ResourceBundle which handles files loaded from external
640 // sources. The language should have been passed in to us from the
641 // browser process as a command line flag.
642 #if defined(DISABLE_NACL)
643 DCHECK(command_line.HasSwitch(switches::kLang) ||
644 process_type == switches::kZygoteProcess ||
645 process_type == switches::kGpuProcess ||
646 process_type == switches::kPpapiBrokerProcess ||
647 process_type == switches::kPpapiPluginProcess);
648 #else
649 DCHECK(command_line.HasSwitch(switches::kLang) ||
650 process_type == switches::kZygoteProcess ||
651 process_type == switches::kGpuProcess ||
652 process_type == switches::kNaClLoaderProcess ||
653 process_type == switches::kPpapiBrokerProcess ||
654 process_type == switches::kPpapiPluginProcess);
655 #endif
657 // TODO(markusheintz): The command line flag --lang is actually processed
658 // by the CommandLinePrefStore, and made available through the PrefService
659 // via the preference prefs::kApplicationLocale. The browser process uses
660 // the --lang flag to pass the value of the PrefService in here. Maybe
661 // this value could be passed in a different way.
662 const std::string locale =
663 command_line.GetSwitchValueASCII(switches::kLang);
664 #if defined(OS_ANDROID)
665 // The renderer sandbox prevents us from accessing our .pak files directly.
666 // Therefore file descriptors to the .pak files that we need are passed in
667 // at process creation time.
668 int locale_pak_fd = base::GlobalDescriptors::GetInstance()->MaybeGet(
669 kAndroidLocalePakDescriptor);
670 CHECK(locale_pak_fd != -1);
671 ResourceBundle::InitSharedInstanceWithPakFile(base::File(locale_pak_fd),
672 false);
674 int extra_pak_keys[] = {
675 kAndroidChrome100PercentPakDescriptor,
676 kAndroidUIResourcesPakDescriptor,
678 for (size_t i = 0; i < arraysize(extra_pak_keys); ++i) {
679 int pak_fd =
680 base::GlobalDescriptors::GetInstance()->MaybeGet(extra_pak_keys[i]);
681 CHECK(pak_fd != -1);
682 ResourceBundle::GetSharedInstance().AddDataPackFromFile(
683 base::File(pak_fd), ui::SCALE_FACTOR_100P);
686 base::i18n::SetICUDefaultLocale(locale);
687 const std::string loaded_locale = locale;
688 #else
689 const std::string loaded_locale =
690 ResourceBundle::InitSharedInstanceWithLocale(locale, NULL);
692 base::FilePath resources_pack_path;
693 PathService::Get(chrome::FILE_RESOURCES_PACK, &resources_pack_path);
694 ResourceBundle::GetSharedInstance().AddDataPackFromPath(
695 resources_pack_path, ui::SCALE_FACTOR_NONE);
696 #endif
697 CHECK(!loaded_locale.empty()) << "Locale could not be found for " <<
698 locale;
700 #if !defined(CHROME_MULTIPLE_DLL_BROWSER)
701 if (process_type == switches::kUtilityProcess ||
702 process_type == switches::kZygoteProcess) {
703 chrome::ChromeContentUtilityClient::PreSandboxStartup();
705 #endif
708 #if defined(OS_POSIX) && !defined(OS_MACOSX)
709 // Zygote needs to call InitCrashReporter() in RunZygote().
710 if (process_type != switches::kZygoteProcess) {
711 #if defined(OS_ANDROID)
712 if (process_type.empty())
713 breakpad::InitCrashReporter(process_type);
714 else
715 breakpad::InitNonBrowserCrashReporterForAndroid(process_type);
716 #else // !defined(OS_ANDROID)
717 breakpad::InitCrashReporter(process_type);
718 #endif // defined(OS_ANDROID)
720 #endif // defined(OS_POSIX) && !defined(OS_MACOSX)
722 // After all the platform Breakpads have been initialized, store the command
723 // line for crash reporting.
724 crash_keys::SetSwitchesFromCommandLine(&command_line);
727 void ChromeMainDelegate::SandboxInitialized(const std::string& process_type) {
728 startup_timer_->Stop(); // End of Startup Time Measurement.
730 // Note: If you are adding a new process type below, be sure to adjust the
731 // AdjustLinuxOOMScore function too.
732 #if defined(OS_LINUX)
733 AdjustLinuxOOMScore(process_type);
734 #endif
735 #if defined(OS_WIN)
736 SuppressWindowsErrorDialogs();
737 #endif
740 int ChromeMainDelegate::RunProcess(
741 const std::string& process_type,
742 const content::MainFunctionParams& main_function_params) {
743 // ANDROID doesn't support "service", so no ServiceProcessMain, and arraysize
744 // doesn't support empty array. So we comment out the block for Android.
745 #if !defined(OS_ANDROID)
746 static const MainFunction kMainFunctions[] = {
747 #if defined(ENABLE_FULL_PRINTING) && !defined(CHROME_MULTIPLE_DLL_CHILD)
748 { switches::kServiceProcess, ServiceProcessMain },
749 #endif
751 #if defined(OS_MACOSX)
752 { switches::kRelauncherProcess,
753 mac_relauncher::internal::RelauncherMain },
754 #endif
756 // This entry is not needed on Linux, where the NaCl loader
757 // process is launched via nacl_helper instead.
758 #if !defined(DISABLE_NACL) && !defined(CHROME_MULTIPLE_DLL_BROWSER) && \
759 !defined(OS_LINUX)
760 { switches::kNaClLoaderProcess, NaClMain },
761 #else
762 { "<invalid>", NULL }, // To avoid constant array of size 0
763 // when DISABLE_NACL and CHROME_MULTIPLE_DLL_CHILD
764 #endif // DISABLE_NACL
767 for (size_t i = 0; i < arraysize(kMainFunctions); ++i) {
768 if (process_type == kMainFunctions[i].name)
769 return kMainFunctions[i].function(main_function_params);
771 #endif
773 return -1;
776 void ChromeMainDelegate::ProcessExiting(const std::string& process_type) {
777 if (SubprocessNeedsResourceBundle(process_type))
778 ResourceBundle::CleanupSharedInstance();
779 #if !defined(OS_ANDROID)
780 logging::CleanupChromeLogging();
781 #else
782 // Android doesn't use InitChromeLogging, so we close the log file manually.
783 logging::CloseLogFile();
784 #endif // !defined(OS_ANDROID)
787 #if defined(OS_MACOSX)
788 bool ChromeMainDelegate::ProcessRegistersWithSystemProcess(
789 const std::string& process_type) {
790 return process_type == switches::kNaClLoaderProcess;
793 bool ChromeMainDelegate::ShouldSendMachPort(const std::string& process_type) {
794 return process_type != switches::kRelauncherProcess &&
795 process_type != switches::kServiceProcess;
798 bool ChromeMainDelegate::DelaySandboxInitialization(
799 const std::string& process_type) {
800 // NaClLoader does this in NaClMainPlatformDelegate::EnableSandbox().
801 // No sandbox needed for relauncher.
802 return process_type == switches::kNaClLoaderProcess ||
803 process_type == switches::kRelauncherProcess;
805 #elif defined(OS_POSIX) && !defined(OS_ANDROID)
806 content::ZygoteForkDelegate* ChromeMainDelegate::ZygoteStarting() {
807 #if defined(DISABLE_NACL)
808 return NULL;
809 #else
810 return new NaClForkDelegate();
811 #endif
814 void ChromeMainDelegate::ZygoteForked() {
815 Profiling::ProcessStarted();
816 if (Profiling::BeingProfiled()) {
817 base::debug::RestartProfilingAfterFork();
818 SetUpProfilingShutdownHandler();
821 // Needs to be called after we have chrome::DIR_USER_DATA. BrowserMain sets
822 // this up for the browser process in a different manner.
823 const CommandLine* command_line = CommandLine::ForCurrentProcess();
824 std::string process_type =
825 command_line->GetSwitchValueASCII(switches::kProcessType);
826 breakpad::InitCrashReporter(process_type);
828 // Reset the command line for the newly spawned process.
829 crash_keys::SetSwitchesFromCommandLine(command_line);
832 #endif // OS_MACOSX
834 content::ContentBrowserClient*
835 ChromeMainDelegate::CreateContentBrowserClient() {
836 #if defined(CHROME_MULTIPLE_DLL_CHILD)
837 return NULL;
838 #else
839 return &g_chrome_content_browser_client.Get();
840 #endif
843 content::ContentPluginClient* ChromeMainDelegate::CreateContentPluginClient() {
844 #if defined(CHROME_MULTIPLE_DLL_BROWSER)
845 return NULL;
846 #else
847 return &g_chrome_content_plugin_client.Get();
848 #endif
851 content::ContentRendererClient*
852 ChromeMainDelegate::CreateContentRendererClient() {
853 #if defined(CHROME_MULTIPLE_DLL_BROWSER)
854 return NULL;
855 #else
856 return &g_chrome_content_renderer_client.Get();
857 #endif
860 content::ContentUtilityClient*
861 ChromeMainDelegate::CreateContentUtilityClient() {
862 #if defined(CHROME_MULTIPLE_DLL_BROWSER)
863 return NULL;
864 #else
865 return &g_chrome_content_utility_client.Get();
866 #endif