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<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.
LoadMemoryProfiler()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.
HasDeprecatedArguments(const std::wstring & command_line)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.
SuppressWindowsErrorDialogs()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)
AdjustLinuxOOMScore(const std::string & process_type)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.
EnableHeapProfiler(const CommandLine & command_line)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.
SubprocessNeedsResourceBundle(const std::string & process_type)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.
HandleVersionSwitches(const CommandLine & command_line)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.
HandleHelpSwitches(const CommandLine & 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) && !defined(OS_ANDROID)
SIGTERMProfilingShutdown(int signal)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
SetUpProfilingShutdownHandler()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 // !defined(OS_MACOSX) && !defined(OS_ANDROID)
309
310 #endif // OS_POSIX
311
312 struct MainFunction {
313 const char* name;
314 int (*function)(const content::MainFunctionParams&);
315 };
316
317 } // namespace
318
ChromeMainDelegate()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
~ChromeMainDelegate()331 ChromeMainDelegate::~ChromeMainDelegate() {
332 }
333
BasicStartupComplete(int * exit_code)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)
InitMacCrashReporter(const CommandLine & command_line,const std::string & process_type)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(process_type);
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(process_type);
559 }
560 #endif // defined(OS_MACOSX)
561
PreSandboxStartup()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 process_type == switches::kZygoteProcess) {
701 chrome::ChromeContentUtilityClient::PreSandboxStartup();
702 }
703 #endif
704 }
705
706 #if defined(OS_POSIX) && !defined(OS_MACOSX)
707 // Zygote needs to call InitCrashReporter() in RunZygote().
708 if (process_type != switches::kZygoteProcess) {
709 #if defined(OS_ANDROID)
710 if (process_type.empty())
711 breakpad::InitCrashReporter(process_type);
712 else
713 breakpad::InitNonBrowserCrashReporterForAndroid(process_type);
714 #else // !defined(OS_ANDROID)
715 breakpad::InitCrashReporter(process_type);
716 #endif // defined(OS_ANDROID)
717 }
718 #endif // defined(OS_POSIX) && !defined(OS_MACOSX)
719
720 // After all the platform Breakpads have been initialized, store the command
721 // line for crash reporting.
722 crash_keys::SetSwitchesFromCommandLine(&command_line);
723 }
724
SandboxInitialized(const std::string & process_type)725 void ChromeMainDelegate::SandboxInitialized(const std::string& process_type) {
726 startup_timer_->Stop(); // End of Startup Time Measurement.
727
728 // Note: If you are adding a new process type below, be sure to adjust the
729 // AdjustLinuxOOMScore function too.
730 #if defined(OS_LINUX)
731 AdjustLinuxOOMScore(process_type);
732 #endif
733 #if defined(OS_WIN)
734 SuppressWindowsErrorDialogs();
735 #endif
736 }
737
RunProcess(const std::string & process_type,const content::MainFunctionParams & main_function_params)738 int ChromeMainDelegate::RunProcess(
739 const std::string& process_type,
740 const content::MainFunctionParams& main_function_params) {
741 // ANDROID doesn't support "service", so no ServiceProcessMain, and arraysize
742 // doesn't support empty array. So we comment out the block for Android.
743 #if !defined(OS_ANDROID)
744 static const MainFunction kMainFunctions[] = {
745 #if defined(ENABLE_FULL_PRINTING) && !defined(CHROME_MULTIPLE_DLL_CHILD)
746 { switches::kServiceProcess, ServiceProcessMain },
747 #endif
748
749 #if defined(OS_MACOSX)
750 { switches::kRelauncherProcess,
751 mac_relauncher::internal::RelauncherMain },
752 #endif
753
754 // This entry is not needed on Linux, where the NaCl loader
755 // process is launched via nacl_helper instead.
756 #if !defined(DISABLE_NACL) && !defined(CHROME_MULTIPLE_DLL_BROWSER) && \
757 !defined(OS_LINUX)
758 { switches::kNaClLoaderProcess, NaClMain },
759 #else
760 { "<invalid>", NULL }, // To avoid constant array of size 0
761 // when DISABLE_NACL and CHROME_MULTIPLE_DLL_CHILD
762 #endif // DISABLE_NACL
763 };
764
765 for (size_t i = 0; i < arraysize(kMainFunctions); ++i) {
766 if (process_type == kMainFunctions[i].name)
767 return kMainFunctions[i].function(main_function_params);
768 }
769 #endif
770
771 return -1;
772 }
773
ProcessExiting(const std::string & process_type)774 void ChromeMainDelegate::ProcessExiting(const std::string& process_type) {
775 if (SubprocessNeedsResourceBundle(process_type))
776 ResourceBundle::CleanupSharedInstance();
777 #if !defined(OS_ANDROID)
778 logging::CleanupChromeLogging();
779 #else
780 // Android doesn't use InitChromeLogging, so we close the log file manually.
781 logging::CloseLogFile();
782 #endif // !defined(OS_ANDROID)
783 }
784
785 #if defined(OS_MACOSX)
ProcessRegistersWithSystemProcess(const std::string & process_type)786 bool ChromeMainDelegate::ProcessRegistersWithSystemProcess(
787 const std::string& process_type) {
788 return process_type == switches::kNaClLoaderProcess;
789 }
790
ShouldSendMachPort(const std::string & process_type)791 bool ChromeMainDelegate::ShouldSendMachPort(const std::string& process_type) {
792 return process_type != switches::kRelauncherProcess &&
793 process_type != switches::kServiceProcess;
794 }
795
DelaySandboxInitialization(const std::string & process_type)796 bool ChromeMainDelegate::DelaySandboxInitialization(
797 const std::string& process_type) {
798 // NaClLoader does this in NaClMainPlatformDelegate::EnableSandbox().
799 // No sandbox needed for relauncher.
800 return process_type == switches::kNaClLoaderProcess ||
801 process_type == switches::kRelauncherProcess;
802 }
803 #elif defined(OS_POSIX) && !defined(OS_ANDROID)
ZygoteStarting()804 content::ZygoteForkDelegate* ChromeMainDelegate::ZygoteStarting() {
805 #if defined(DISABLE_NACL)
806 return NULL;
807 #else
808 return new NaClForkDelegate();
809 #endif
810 }
811
ZygoteForked()812 void ChromeMainDelegate::ZygoteForked() {
813 Profiling::ProcessStarted();
814 if (Profiling::BeingProfiled()) {
815 base::debug::RestartProfilingAfterFork();
816 SetUpProfilingShutdownHandler();
817 }
818
819 // Needs to be called after we have chrome::DIR_USER_DATA. BrowserMain sets
820 // this up for the browser process in a different manner.
821 const CommandLine* command_line = CommandLine::ForCurrentProcess();
822 std::string process_type =
823 command_line->GetSwitchValueASCII(switches::kProcessType);
824 breakpad::InitCrashReporter(process_type);
825
826 // Reset the command line for the newly spawned process.
827 crash_keys::SetSwitchesFromCommandLine(command_line);
828 }
829
830 #endif // OS_MACOSX
831
832 content::ContentBrowserClient*
CreateContentBrowserClient()833 ChromeMainDelegate::CreateContentBrowserClient() {
834 #if defined(CHROME_MULTIPLE_DLL_CHILD)
835 return NULL;
836 #else
837 return &g_chrome_content_browser_client.Get();
838 #endif
839 }
840
CreateContentPluginClient()841 content::ContentPluginClient* ChromeMainDelegate::CreateContentPluginClient() {
842 #if defined(CHROME_MULTIPLE_DLL_BROWSER)
843 return NULL;
844 #else
845 return &g_chrome_content_plugin_client.Get();
846 #endif
847 }
848
849 content::ContentRendererClient*
CreateContentRendererClient()850 ChromeMainDelegate::CreateContentRendererClient() {
851 #if defined(CHROME_MULTIPLE_DLL_BROWSER)
852 return NULL;
853 #else
854 return &g_chrome_content_renderer_client.Get();
855 #endif
856 }
857
858 content::ContentUtilityClient*
CreateContentUtilityClient()859 ChromeMainDelegate::CreateContentUtilityClient() {
860 #if defined(CHROME_MULTIPLE_DLL_BROWSER)
861 return NULL;
862 #else
863 return &g_chrome_content_utility_client.Get();
864 #endif
865 }
866