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