Updating XTBs based on .GRDs from branch master
[chromium-blink-merge.git] / chrome / app / chrome_main_delegate.cc
blob031a0a10ba99e8f604fddfaafa8d5a968324df4c
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/base_paths.h"
8 #include "base/command_line.h"
9 #include "base/cpu.h"
10 #include "base/files/file_path.h"
11 #include "base/i18n/rtl.h"
12 #include "base/lazy_instance.h"
13 #include "base/message_loop/message_loop.h"
14 #include "base/metrics/statistics_recorder.h"
15 #include "base/path_service.h"
16 #include "base/process/memory.h"
17 #include "base/process/process_handle.h"
18 #include "base/strings/string_util.h"
19 #include "base/trace_event/trace_event_impl.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/common/channel_info.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_result_codes.h"
29 #include "chrome/common/chrome_switches.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/switch_utils.h"
34 #include "chrome/common/trace_event_args_whitelist.h"
35 #include "chrome/common/url_constants.h"
36 #include "chrome/plugin/chrome_content_plugin_client.h"
37 #include "chrome/renderer/chrome_content_renderer_client.h"
38 #include "chrome/utility/chrome_content_utility_client.h"
39 #include "components/component_updater/component_updater_paths.h"
40 #include "components/content_settings/core/common/content_settings_pattern.h"
41 #include "components/startup_metric_utils/startup_metric_utils.h"
42 #include "components/version_info/version_info.h"
43 #include "content/public/common/content_client.h"
44 #include "content/public/common/content_paths.h"
45 #include "extensions/common/constants.h"
46 #include "ui/base/ui_base_switches.h"
48 #if defined(OS_WIN)
49 #include <atlbase.h>
50 #include <malloc.h>
51 #include <algorithm>
52 #include "chrome/app/close_handle_hook_win.h"
53 #include "chrome/common/child_process_logging.h"
54 #include "chrome/common/v8_breakpad_support_win.h"
55 #include "sandbox/win/src/sandbox.h"
56 #include "ui/base/resource/resource_bundle_win.h"
57 #endif
59 #if defined(OS_MACOSX)
60 #include "base/mac/foundation_util.h"
61 #include "chrome/app/chrome_main_mac.h"
62 #include "chrome/browser/mac/relauncher.h"
63 #include "chrome/common/mac/cfbundle_blocker.h"
64 #include "chrome/common/mac/objc_zombie.h"
65 #include "components/crash/app/crashpad_mac.h"
66 #include "ui/base/l10n/l10n_util_mac.h"
67 #endif
69 #if defined(OS_POSIX)
70 #include <locale.h>
71 #include <signal.h>
72 #include "chrome/app/chrome_crash_reporter_client.h"
73 #include "components/crash/app/crash_reporter_client.h"
74 #endif
76 #if !defined(DISABLE_NACL) && defined(OS_LINUX)
77 #include "components/nacl/common/nacl_paths.h"
78 #include "components/nacl/zygote/nacl_fork_delegate_linux.h"
79 #endif
81 #if defined(OS_CHROMEOS)
82 #include "base/sys_info.h"
83 #include "chrome/browser/chromeos/boot_times_recorder.h"
84 #include "chromeos/chromeos_paths.h"
85 #include "chromeos/chromeos_switches.h"
86 #endif
88 #if defined(OS_ANDROID)
89 #include "chrome/browser/android/java_exception_reporter.h"
90 #include "chrome/common/descriptors_android.h"
91 #else
92 // Diagnostics is only available on non-android platforms.
93 #include "chrome/browser/diagnostics/diagnostics_controller.h"
94 #include "chrome/browser/diagnostics/diagnostics_writer.h"
95 #endif
97 #if defined(USE_X11)
98 #include <stdlib.h>
99 #include <string.h>
100 #include "ui/base/x/x11_util.h"
101 #endif
103 #if defined(OS_POSIX) && !defined(OS_MACOSX)
104 #include "components/crash/app/breakpad_linux.h"
105 #endif
107 #if defined(OS_LINUX)
108 #include "base/environment.h"
109 #endif
111 #if defined(OS_MACOSX) || defined(OS_WIN)
112 #include "chrome/browser/policy/policy_path_parser.h"
113 #endif
115 #if !defined(DISABLE_NACL)
116 #include "components/nacl/common/nacl_switches.h"
117 #include "components/nacl/renderer/plugin/ppapi_entrypoints.h"
118 #endif
120 #if defined(ENABLE_PLUGINS) && (defined(CHROME_MULTIPLE_DLL_CHILD) || \
121 !defined(CHROME_MULTIPLE_DLL_BROWSER))
122 #include "pdf/pdf.h"
123 #endif
125 #if !defined(CHROME_MULTIPLE_DLL_BROWSER)
126 #include "chrome/child/pdf_child_init.h"
128 base::LazyInstance<ChromeContentRendererClient>
129 g_chrome_content_renderer_client = LAZY_INSTANCE_INITIALIZER;
130 base::LazyInstance<ChromeContentUtilityClient>
131 g_chrome_content_utility_client = LAZY_INSTANCE_INITIALIZER;
132 base::LazyInstance<chrome::ChromeContentPluginClient>
133 g_chrome_content_plugin_client = LAZY_INSTANCE_INITIALIZER;
134 #endif
136 #if !defined(CHROME_MULTIPLE_DLL_CHILD)
137 base::LazyInstance<chrome::ChromeContentBrowserClient>
138 g_chrome_content_browser_client = LAZY_INSTANCE_INITIALIZER;
139 #endif
141 #if defined(OS_POSIX)
142 base::LazyInstance<chrome::ChromeCrashReporterClient>::Leaky
143 g_chrome_crash_client = LAZY_INSTANCE_INITIALIZER;
144 #endif
146 extern int NaClMain(const content::MainFunctionParams&);
147 extern int ServiceProcessMain(const content::MainFunctionParams&);
149 namespace {
151 #if defined(OS_WIN)
152 // Early versions of Chrome incorrectly registered a chromehtml: URL handler,
153 // which gives us nothing but trouble. Avoid launching chrome this way since
154 // some apps fail to properly escape arguments.
155 bool HasDeprecatedArguments(const std::wstring& command_line) {
156 const wchar_t kChromeHtml[] = L"chromehtml:";
157 std::wstring command_line_lower = command_line;
158 // We are only searching for ASCII characters so this is OK.
159 base::StringToLowerASCII(&command_line_lower);
160 std::wstring::size_type pos = command_line_lower.find(kChromeHtml);
161 return (pos != std::wstring::npos);
164 // If we try to access a path that is not currently available, we want the call
165 // to fail rather than show an error dialog.
166 void SuppressWindowsErrorDialogs() {
167 UINT new_flags = SEM_FAILCRITICALERRORS |
168 SEM_NOOPENFILEERRORBOX;
170 // Preserve existing error mode.
171 UINT existing_flags = SetErrorMode(new_flags);
172 SetErrorMode(existing_flags | new_flags);
175 bool IsSandboxedProcess() {
176 typedef bool (*IsSandboxedProcessFunc)();
177 IsSandboxedProcessFunc is_sandboxed_process_func =
178 reinterpret_cast<IsSandboxedProcessFunc>(
179 GetProcAddress(GetModuleHandle(NULL), "IsSandboxedProcess"));
180 return is_sandboxed_process_func && is_sandboxed_process_func();
183 #endif // defined(OS_WIN)
185 #if defined(OS_LINUX)
186 static void AdjustLinuxOOMScore(const std::string& process_type) {
187 // Browsers and zygotes should still be killable, but killed last.
188 const int kZygoteScore = 0;
189 // The minimum amount to bump a score by. This is large enough that
190 // even if it's translated into the old values, it will still go up
191 // by at least one.
192 const int kScoreBump = 100;
193 // This is the lowest score that renderers and extensions start with
194 // in the OomPriorityManager.
195 const int kRendererScore = chrome::kLowestRendererOomScore;
196 // For "miscellaneous" things, we want them after renderers,
197 // but before plugins.
198 const int kMiscScore = kRendererScore - kScoreBump;
199 // We want plugins to die after the renderers.
200 const int kPluginScore = kMiscScore - kScoreBump;
201 int score = -1;
203 DCHECK(kMiscScore > 0);
204 DCHECK(kPluginScore > 0);
206 if (process_type == switches::kPluginProcess ||
207 process_type == switches::kPpapiPluginProcess) {
208 score = kPluginScore;
209 } else if (process_type == switches::kPpapiBrokerProcess) {
210 // The broker should be killed before the PPAPI plugin.
211 score = kPluginScore + kScoreBump;
212 } else if (process_type == switches::kUtilityProcess ||
213 process_type == switches::kGpuProcess ||
214 process_type == switches::kServiceProcess) {
215 score = kMiscScore;
216 #ifndef DISABLE_NACL
217 } else if (process_type == switches::kNaClLoaderProcess ||
218 process_type == switches::kNaClLoaderNonSfiProcess) {
219 score = kPluginScore;
220 #endif
221 } else if (process_type == switches::kZygoteProcess ||
222 process_type.empty()) {
223 // For zygotes and unlabeled process types, we want to still make
224 // them killable by the OOM killer.
225 score = kZygoteScore;
226 } else if (process_type == switches::kRendererProcess) {
227 LOG(WARNING) << "process type 'renderer' "
228 << "should be created through the zygote.";
229 // When debugging, this process type can end up being run directly, but
230 // this isn't the typical path for assigning the OOM score for it. Still,
231 // we want to assign a score that is somewhat representative for debugging.
232 score = kRendererScore;
233 } else {
234 NOTREACHED() << "Unknown process type";
236 if (score > -1)
237 base::AdjustOOMScore(base::GetCurrentProcId(), score);
239 #endif // defined(OS_LINUX)
241 // Returns true if this subprocess type needs the ResourceBundle initialized
242 // and resources loaded.
243 bool SubprocessNeedsResourceBundle(const std::string& process_type) {
244 return
245 #if defined(OS_WIN) || defined(OS_MACOSX)
246 // Windows needs resources for the default/null plugin.
247 // Mac needs them for the plugin process name.
248 process_type == switches::kPluginProcess ||
249 #endif
250 #if defined(OS_POSIX) && !defined(OS_MACOSX)
251 // The zygote process opens the resources for the renderers.
252 process_type == switches::kZygoteProcess ||
253 #endif
254 #if defined(OS_MACOSX)
255 // Mac needs them too for scrollbar related images and for sandbox
256 // profiles.
257 #if !defined(DISABLE_NACL)
258 process_type == switches::kNaClLoaderProcess ||
259 #endif
260 process_type == switches::kPpapiPluginProcess ||
261 process_type == switches::kPpapiBrokerProcess ||
262 process_type == switches::kGpuProcess ||
263 #endif
264 process_type == switches::kRendererProcess ||
265 process_type == switches::kUtilityProcess;
268 #if defined(OS_POSIX)
269 // Check for --version and --product-version; return true if we encountered
270 // one of these switches and should exit now.
271 bool HandleVersionSwitches(const base::CommandLine& command_line) {
272 #if !defined(OS_MACOSX)
273 if (command_line.HasSwitch(switches::kProductVersion)) {
274 printf("%s\n", version_info::GetVersionNumber().c_str());
275 return true;
277 #endif
279 if (command_line.HasSwitch(switches::kVersion)) {
280 printf("%s %s %s\n",
281 version_info::GetProductName().c_str(),
282 version_info::GetVersionNumber().c_str(),
283 chrome::GetChannelString().c_str());
284 return true;
287 return false;
290 #if !defined(OS_MACOSX) && !defined(OS_CHROMEOS)
291 // Show the man page if --help or -h is on the command line.
292 void HandleHelpSwitches(const base::CommandLine& command_line) {
293 if (command_line.HasSwitch(switches::kHelp) ||
294 command_line.HasSwitch(switches::kHelpShort)) {
295 base::FilePath binary(command_line.argv()[0]);
296 execlp("man", "man", binary.BaseName().value().c_str(), NULL);
297 PLOG(FATAL) << "execlp failed";
300 #endif
302 #if !defined(OS_MACOSX) && !defined(OS_ANDROID)
303 void SIGTERMProfilingShutdown(int signal) {
304 Profiling::Stop();
305 struct sigaction sigact;
306 memset(&sigact, 0, sizeof(sigact));
307 sigact.sa_handler = SIG_DFL;
308 CHECK(sigaction(SIGTERM, &sigact, NULL) == 0);
309 raise(signal);
312 void SetUpProfilingShutdownHandler() {
313 struct sigaction sigact;
314 sigact.sa_handler = SIGTERMProfilingShutdown;
315 sigact.sa_flags = SA_RESETHAND;
316 sigemptyset(&sigact.sa_mask);
317 CHECK(sigaction(SIGTERM, &sigact, NULL) == 0);
319 #endif // !defined(OS_MACOSX) && !defined(OS_ANDROID)
321 #endif // OS_POSIX
323 struct MainFunction {
324 const char* name;
325 int (*function)(const content::MainFunctionParams&);
328 // Initializes the user data dir. Must be called before InitializeLocalState().
329 void InitializeUserDataDir() {
330 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
331 base::FilePath user_data_dir =
332 command_line->GetSwitchValuePath(switches::kUserDataDir);
333 std::string process_type =
334 command_line->GetSwitchValueASCII(switches::kProcessType);
336 #if defined(OS_LINUX)
337 // On Linux, Chrome does not support running multiple copies under different
338 // DISPLAYs, so the profile directory can be specified in the environment to
339 // support the virtual desktop use-case.
340 if (user_data_dir.empty()) {
341 std::string user_data_dir_string;
342 scoped_ptr<base::Environment> environment(base::Environment::Create());
343 if (environment->GetVar("CHROME_USER_DATA_DIR", &user_data_dir_string) &&
344 base::IsStringUTF8(user_data_dir_string)) {
345 user_data_dir = base::FilePath::FromUTF8Unsafe(user_data_dir_string);
348 #endif
349 #if defined(OS_MACOSX) || defined(OS_WIN)
350 policy::path_parser::CheckUserDataDirPolicy(&user_data_dir);
351 #endif
353 // On Windows, trailing separators leave Chrome in a bad state.
354 // See crbug.com/464616.
355 if (user_data_dir.EndsWithSeparator())
356 user_data_dir = user_data_dir.StripTrailingSeparators();
358 const bool specified_directory_was_invalid = !user_data_dir.empty() &&
359 !PathService::OverrideAndCreateIfNeeded(chrome::DIR_USER_DATA,
360 user_data_dir, false, true);
361 // Save inaccessible or invalid paths so the user may be prompted later.
362 if (specified_directory_was_invalid)
363 chrome::SetInvalidSpecifiedUserDataDir(user_data_dir);
365 // Warn and fail early if the process fails to get a user data directory.
366 if (!PathService::Get(chrome::DIR_USER_DATA, &user_data_dir)) {
367 // If an invalid command-line or policy override was specified, the user
368 // will be given an error with that value. Otherwise, use the directory
369 // returned by PathService (or the fallback default directory) in the error.
370 if (!specified_directory_was_invalid) {
371 // PathService::Get() returns false and yields an empty path if it fails
372 // to create DIR_USER_DATA. Retrieve the default value manually to display
373 // a more meaningful error to the user in that case.
374 if (user_data_dir.empty())
375 chrome::GetDefaultUserDataDirectory(&user_data_dir);
376 chrome::SetInvalidSpecifiedUserDataDir(user_data_dir);
379 // The browser process (which is identified by an empty |process_type|) will
380 // handle the error later; other processes that need the dir crash here.
381 CHECK(process_type.empty()) << "Unable to get the user data directory "
382 << "for process type: " << process_type;
385 // Append the fallback user data directory to the commandline. Otherwise,
386 // child or service processes will attempt to use the invalid directory.
387 if (specified_directory_was_invalid)
388 command_line->AppendSwitchPath(switches::kUserDataDir, user_data_dir);
391 } // namespace
393 ChromeMainDelegate::ChromeMainDelegate() {
394 #if defined(OS_ANDROID)
395 // On Android the main entry point time is the time when the Java code starts.
396 // This happens before the shared library containing this code is even loaded.
397 // The Java startup code has recorded that time, but the C++ code can't fetch it
398 // from the Java side until it has initialized the JNI. See
399 // ChromeMainDelegateAndroid.
400 #else
401 startup_metric_utils::RecordMainEntryPointTime();
402 #endif
405 ChromeMainDelegate::~ChromeMainDelegate() {
408 bool ChromeMainDelegate::BasicStartupComplete(int* exit_code) {
409 #if defined(OS_CHROMEOS)
410 chromeos::BootTimesRecorder::Get()->SaveChromeMainStats();
411 #endif
413 const base::CommandLine& command_line =
414 *base::CommandLine::ForCurrentProcess();
417 #if defined(OS_WIN)
418 // Browser should not be sandboxed.
419 const bool is_browser = !command_line.HasSwitch(switches::kProcessType);
420 if (is_browser && IsSandboxedProcess()) {
421 *exit_code = chrome::RESULT_CODE_INVALID_SANDBOX_STATE;
422 return true;
424 #endif
426 #if defined(OS_MACOSX)
427 // Give the browser process a longer treadmill, since crashes
428 // there have more impact.
429 const bool is_browser = !command_line.HasSwitch(switches::kProcessType);
430 ObjcEvilDoers::ZombieEnable(true, is_browser ? 10000 : 1000);
432 SetUpBundleOverrides();
433 chrome::common::mac::EnableCFBundleBlocker();
434 #endif
436 Profiling::ProcessStarted();
438 base::trace_event::TraceLog::GetInstance()->SetArgumentFilterPredicate(
439 base::Bind(&IsTraceEventArgsWhitelisted));
441 #if defined(OS_WIN)
442 v8_breakpad_support::SetUp();
443 #endif
445 #if defined(OS_POSIX)
446 if (HandleVersionSwitches(command_line)) {
447 *exit_code = 0;
448 return true; // Got a --version switch; exit with a success error code.
450 #if !defined(OS_MACOSX) && !defined(OS_CHROMEOS)
451 // This will directly exit if the user asked for help.
452 HandleHelpSwitches(command_line);
453 #endif
454 #endif // OS_POSIX
456 #if defined(OS_WIN)
457 // Must do this before any other usage of command line!
458 if (HasDeprecatedArguments(command_line.GetCommandLineString())) {
459 *exit_code = 1;
460 return true;
463 InstallCloseHandleHooks();
464 #endif
466 chrome::RegisterPathProvider();
467 #if defined(OS_CHROMEOS)
468 chromeos::RegisterPathProvider();
469 #endif
470 #if !defined(DISABLE_NACL) && defined(OS_LINUX)
471 nacl::RegisterPathProvider();
472 #endif
474 ContentSettingsPattern::SetNonWildcardDomainNonPortScheme(
475 extensions::kExtensionScheme);
477 // No support for ANDROID yet as DiagnosticsController needs wchar support.
478 // TODO(gspencer): That's not true anymore, or at least there are no w-string
479 // references anymore. Not sure if that means this can be enabled on Android or
480 // not though. As there is no easily accessible command line on Android, I'm
481 // not sure this is a big deal.
482 #if !defined(OS_ANDROID) && !defined(CHROME_MULTIPLE_DLL_CHILD)
483 // If we are in diagnostics mode this is the end of the line: after the
484 // diagnostics are run the process will invariably exit.
485 if (command_line.HasSwitch(switches::kDiagnostics)) {
486 diagnostics::DiagnosticsWriter::FormatType format =
487 diagnostics::DiagnosticsWriter::HUMAN;
488 if (command_line.HasSwitch(switches::kDiagnosticsFormat)) {
489 std::string format_str =
490 command_line.GetSwitchValueASCII(switches::kDiagnosticsFormat);
491 if (format_str == "machine") {
492 format = diagnostics::DiagnosticsWriter::MACHINE;
493 } else if (format_str == "log") {
494 format = diagnostics::DiagnosticsWriter::LOG;
495 } else {
496 DCHECK_EQ("human", format_str);
500 diagnostics::DiagnosticsWriter writer(format);
501 *exit_code = diagnostics::DiagnosticsController::GetInstance()->Run(
502 command_line, &writer);
503 diagnostics::DiagnosticsController::GetInstance()->ClearResults();
504 return true;
506 #endif
508 #if defined(OS_CHROMEOS)
509 // Initialize primary user homedir (in multi-profile session) as it may be
510 // passed as a command line switch.
511 base::FilePath homedir;
512 if (command_line.HasSwitch(chromeos::switches::kHomedir)) {
513 homedir = base::FilePath(
514 command_line.GetSwitchValueASCII(chromeos::switches::kHomedir));
515 PathService::OverrideAndCreateIfNeeded(
516 base::DIR_HOME, homedir, true, false);
519 // If we are recovering from a crash on ChromeOS, then we will do some
520 // recovery using the diagnostics module, and then continue on. We fake up a
521 // command line to tell it that we want it to recover, and to preserve the
522 // original command line.
523 if (command_line.HasSwitch(chromeos::switches::kLoginUser) ||
524 command_line.HasSwitch(switches::kDiagnosticsRecovery)) {
525 // The statistics subsystem needs get initialized soon enough for the
526 // statistics to be collected. It's safe to call this more than once.
527 base::StatisticsRecorder::Initialize();
529 base::CommandLine interim_command_line(command_line.GetProgram());
530 const char* const kSwitchNames[] = {switches::kUserDataDir, };
531 interim_command_line.CopySwitchesFrom(
532 command_line, kSwitchNames, arraysize(kSwitchNames));
533 interim_command_line.AppendSwitch(switches::kDiagnostics);
534 interim_command_line.AppendSwitch(switches::kDiagnosticsRecovery);
536 diagnostics::DiagnosticsWriter::FormatType format =
537 diagnostics::DiagnosticsWriter::LOG;
538 if (command_line.HasSwitch(switches::kDiagnosticsFormat)) {
539 std::string format_str =
540 command_line.GetSwitchValueASCII(switches::kDiagnosticsFormat);
541 if (format_str == "machine") {
542 format = diagnostics::DiagnosticsWriter::MACHINE;
543 } else if (format_str == "human") {
544 format = diagnostics::DiagnosticsWriter::HUMAN;
545 } else {
546 DCHECK_EQ("log", format_str);
550 diagnostics::DiagnosticsWriter writer(format);
551 int diagnostics_exit_code =
552 diagnostics::DiagnosticsController::GetInstance()->Run(command_line,
553 &writer);
554 if (diagnostics_exit_code) {
555 // Diagnostics has failed somehow, so we exit.
556 *exit_code = diagnostics_exit_code;
557 return true;
560 // Now we run the actual recovery tasks.
561 int recovery_exit_code =
562 diagnostics::DiagnosticsController::GetInstance()->RunRecovery(
563 command_line, &writer);
565 if (recovery_exit_code) {
566 // Recovery has failed somehow, so we exit.
567 *exit_code = recovery_exit_code;
568 return true;
570 } else { // Not running diagnostics or recovery.
571 diagnostics::DiagnosticsController::GetInstance()->RecordRegularStartup();
573 #endif
575 content::SetContentClient(&chrome_content_client_);
577 return false;
580 #if defined(OS_MACOSX)
581 void ChromeMainDelegate::InitMacCrashReporter(
582 const base::CommandLine& command_line,
583 const std::string& process_type) {
584 // TODO(mark): Right now, InitializeCrashpad() needs to be called after
585 // CommandLine::Init() and chrome::RegisterPathProvider(). Ideally, Crashpad
586 // initialization could occur sooner, preferably even before the framework
587 // dylib is even loaded, to catch potential early crashes.
588 crash_reporter::InitializeCrashpad(process_type);
590 const bool browser_process = process_type.empty();
591 if (!browser_process) {
592 std::string metrics_client_id =
593 command_line.GetSwitchValueASCII(switches::kMetricsClientID);
594 crash_keys::SetMetricsClientIdFromGUID(metrics_client_id);
597 // Mac Chrome is packaged with a main app bundle and a helper app bundle.
598 // The main app bundle should only be used for the browser process, so it
599 // should never see a --type switch (switches::kProcessType). Likewise,
600 // the helper should always have a --type switch.
602 // This check is done this late so there is already a call to
603 // base::mac::IsBackgroundOnlyProcess(), so there is no change in
604 // startup/initialization order.
606 // The helper's Info.plist marks it as a background only app.
607 if (base::mac::IsBackgroundOnlyProcess()) {
608 CHECK(command_line.HasSwitch(switches::kProcessType) &&
609 !process_type.empty())
610 << "Helper application requires --type.";
612 // In addition, some helper flavors only work with certain process types.
613 base::FilePath executable;
614 if (PathService::Get(base::FILE_EXE, &executable) &&
615 executable.value().size() >= 3) {
616 std::string last_three =
617 executable.value().substr(executable.value().size() - 3);
619 if (last_three == " EH") {
620 CHECK(process_type == switches::kPluginProcess ||
621 process_type == switches::kUtilityProcess)
622 << "Executable-heap process requires --type="
623 << switches::kPluginProcess << " or "
624 << switches::kUtilityProcess << ", saw " << process_type;
625 } else if (last_three == " NP") {
626 #if !defined(DISABLE_NACL)
627 CHECK_EQ(switches::kNaClLoaderProcess, process_type)
628 << "Non-PIE process requires --type="
629 << switches::kNaClLoaderProcess << ", saw " << process_type;
630 #endif
631 } else {
632 #if defined(DISABLE_NACL)
633 CHECK(process_type != switches::kPluginProcess)
634 << "Non-executable-heap PIE process is intolerant of --type="
635 << switches::kPluginProcess;
636 #else
637 CHECK(process_type != switches::kPluginProcess &&
638 process_type != switches::kNaClLoaderProcess)
639 << "Non-executable-heap PIE process is intolerant of --type="
640 << switches::kPluginProcess << " and "
641 << switches::kNaClLoaderProcess << ", saw " << process_type;
642 #endif
645 } else {
646 CHECK(!command_line.HasSwitch(switches::kProcessType) &&
647 process_type.empty())
648 << "Main application forbids --type, saw " << process_type;
651 #endif // defined(OS_MACOSX)
653 void ChromeMainDelegate::PreSandboxStartup() {
654 const base::CommandLine& command_line =
655 *base::CommandLine::ForCurrentProcess();
656 std::string process_type =
657 command_line.GetSwitchValueASCII(switches::kProcessType);
659 #if defined(OS_POSIX)
660 crash_reporter::SetCrashReporterClient(g_chrome_crash_client.Pointer());
661 #endif
663 #if defined(OS_MACOSX)
664 // On the Mac, the child executable lives at a predefined location within
665 // the app bundle's versioned directory.
666 PathService::Override(content::CHILD_PROCESS_EXE,
667 chrome::GetVersionedDirectory().
668 Append(chrome::kHelperProcessExecutablePath));
670 InitMacCrashReporter(command_line, process_type);
671 #endif
673 #if defined(OS_WIN)
674 child_process_logging::Init();
675 #endif
676 #if defined(ARCH_CPU_ARM_FAMILY) && (defined(OS_ANDROID) || defined(OS_LINUX))
677 // Create an instance of the CPU class to parse /proc/cpuinfo and cache
678 // cpu_brand info.
679 base::CPU cpu_info;
680 #endif
682 // Initialize the user data dir for any process type that needs it.
683 if (chrome::ProcessNeedsProfileDir(process_type))
684 InitializeUserDataDir();
686 // Register component_updater PathProvider after DIR_USER_DATA overidden by
687 // command line flags. Maybe move the chrome PathProvider down here also?
688 component_updater::RegisterPathProvider(chrome::DIR_USER_DATA);
690 // Enable Message Loop related state asap.
691 if (command_line.HasSwitch(switches::kMessageLoopHistogrammer))
692 base::MessageLoop::EnableHistogrammer(true);
694 #if !defined(OS_ANDROID)
695 // Android does InitLogging when library is loaded. Skip here.
696 logging::OldFileDeletionState file_state =
697 logging::APPEND_TO_OLD_LOG_FILE;
698 if (process_type.empty()) {
699 file_state = logging::DELETE_OLD_LOG_FILE;
701 logging::InitChromeLogging(command_line, file_state);
702 #endif
704 #if defined(OS_WIN)
705 // TODO(zturner): Throbber icons are still stored in chrome.dll, this can be
706 // killed once those are merged into resources.pak. See
707 // GlassBrowserFrameView::InitThrobberIcons() and http://crbug.com/368327.
708 ui::SetResourcesDataDLL(_AtlBaseModule.GetResourceInstance());
709 #endif
711 if (SubprocessNeedsResourceBundle(process_type)) {
712 // Initialize ResourceBundle which handles files loaded from external
713 // sources. The language should have been passed in to us from the
714 // browser process as a command line flag.
715 #if defined(DISABLE_NACL)
716 DCHECK(command_line.HasSwitch(switches::kLang) ||
717 process_type == switches::kZygoteProcess ||
718 process_type == switches::kGpuProcess ||
719 process_type == switches::kPpapiBrokerProcess ||
720 process_type == switches::kPpapiPluginProcess);
721 #else
722 DCHECK(command_line.HasSwitch(switches::kLang) ||
723 process_type == switches::kZygoteProcess ||
724 process_type == switches::kGpuProcess ||
725 process_type == switches::kNaClLoaderProcess ||
726 process_type == switches::kPpapiBrokerProcess ||
727 process_type == switches::kPpapiPluginProcess);
728 #endif
730 // TODO(markusheintz): The command line flag --lang is actually processed
731 // by the CommandLinePrefStore, and made available through the PrefService
732 // via the preference prefs::kApplicationLocale. The browser process uses
733 // the --lang flag to pass the value of the PrefService in here. Maybe
734 // this value could be passed in a different way.
735 const std::string locale =
736 command_line.GetSwitchValueASCII(switches::kLang);
737 #if defined(OS_ANDROID)
738 // The renderer sandbox prevents us from accessing our .pak files directly.
739 // Therefore file descriptors to the .pak files that we need are passed in
740 // at process creation time.
741 auto global_descriptors = base::GlobalDescriptors::GetInstance();
742 int pak_fd = global_descriptors->Get(kAndroidLocalePakDescriptor);
743 base::MemoryMappedFile::Region pak_region =
744 global_descriptors->GetRegion(kAndroidLocalePakDescriptor);
745 ResourceBundle::InitSharedInstanceWithPakFileRegion(base::File(pak_fd),
746 pak_region);
748 int extra_pak_keys[] = {
749 kAndroidChrome100PercentPakDescriptor,
750 kAndroidUIResourcesPakDescriptor,
752 for (size_t i = 0; i < arraysize(extra_pak_keys); ++i) {
753 pak_fd = global_descriptors->Get(extra_pak_keys[i]);
754 pak_region = global_descriptors->GetRegion(extra_pak_keys[i]);
755 ResourceBundle::GetSharedInstance().AddDataPackFromFileRegion(
756 base::File(pak_fd), pak_region, ui::SCALE_FACTOR_100P);
759 base::i18n::SetICUDefaultLocale(locale);
760 const std::string loaded_locale = locale;
761 #else
762 const std::string loaded_locale =
763 ui::ResourceBundle::InitSharedInstanceWithLocale(
764 locale, NULL, ui::ResourceBundle::LOAD_COMMON_RESOURCES);
766 base::FilePath resources_pack_path;
767 PathService::Get(chrome::FILE_RESOURCES_PACK, &resources_pack_path);
768 ResourceBundle::GetSharedInstance().AddDataPackFromPath(
769 resources_pack_path, ui::SCALE_FACTOR_NONE);
770 #endif
771 CHECK(!loaded_locale.empty()) << "Locale could not be found for " <<
772 locale;
775 #if !defined(CHROME_MULTIPLE_DLL_BROWSER)
776 if (process_type == switches::kUtilityProcess ||
777 process_type == switches::kZygoteProcess) {
778 ChromeContentUtilityClient::PreSandboxStartup();
781 chrome::InitializePDF();
782 #endif
784 #if defined(OS_POSIX) && !defined(OS_MACOSX)
785 // Zygote needs to call InitCrashReporter() in RunZygote().
786 if (process_type != switches::kZygoteProcess) {
787 #if defined(OS_ANDROID)
788 if (process_type.empty()) {
789 breakpad::InitCrashReporter(process_type);
790 chrome::android::InitJavaExceptionReporter();
791 } else {
792 breakpad::InitNonBrowserCrashReporterForAndroid(process_type);
794 #else // !defined(OS_ANDROID)
795 breakpad::InitCrashReporter(process_type);
796 #endif // defined(OS_ANDROID)
798 #endif // defined(OS_POSIX) && !defined(OS_MACOSX)
800 // After all the platform Breakpads have been initialized, store the command
801 // line for crash reporting.
802 crash_keys::SetSwitchesFromCommandLine(&command_line);
805 void ChromeMainDelegate::SandboxInitialized(const std::string& process_type) {
806 // Note: If you are adding a new process type below, be sure to adjust the
807 // AdjustLinuxOOMScore function too.
808 #if defined(OS_LINUX)
809 AdjustLinuxOOMScore(process_type);
810 #endif
811 #if defined(OS_WIN)
812 SuppressWindowsErrorDialogs();
813 #endif
815 #if defined(CHROME_MULTIPLE_DLL_CHILD) || !defined(CHROME_MULTIPLE_DLL_BROWSER)
816 #if !defined(DISABLE_NACL)
817 ChromeContentClient::SetNaClEntryFunctions(
818 nacl_plugin::PPP_GetInterface,
819 nacl_plugin::PPP_InitializeModule,
820 nacl_plugin::PPP_ShutdownModule);
821 #endif
822 #if defined(ENABLE_PLUGINS)
823 ChromeContentClient::SetPDFEntryFunctions(
824 chrome_pdf::PPP_GetInterface,
825 chrome_pdf::PPP_InitializeModule,
826 chrome_pdf::PPP_ShutdownModule);
827 #endif
828 #endif
831 int ChromeMainDelegate::RunProcess(
832 const std::string& process_type,
833 const content::MainFunctionParams& main_function_params) {
834 // ANDROID doesn't support "service", so no ServiceProcessMain, and arraysize
835 // doesn't support empty array. So we comment out the block for Android.
836 #if !defined(OS_ANDROID)
837 static const MainFunction kMainFunctions[] = {
838 #if defined(ENABLE_PRINT_PREVIEW) && !defined(CHROME_MULTIPLE_DLL_CHILD)
839 { switches::kServiceProcess, ServiceProcessMain },
840 #endif
842 #if defined(OS_MACOSX)
843 { switches::kRelauncherProcess,
844 mac_relauncher::internal::RelauncherMain },
845 #endif
847 // This entry is not needed on Linux, where the NaCl loader
848 // process is launched via nacl_helper instead.
849 #if !defined(DISABLE_NACL) && !defined(CHROME_MULTIPLE_DLL_BROWSER) && \
850 !defined(OS_LINUX)
851 { switches::kNaClLoaderProcess, NaClMain },
852 #else
853 { "<invalid>", NULL }, // To avoid constant array of size 0
854 // when DISABLE_NACL and CHROME_MULTIPLE_DLL_CHILD
855 #endif // DISABLE_NACL
858 for (size_t i = 0; i < arraysize(kMainFunctions); ++i) {
859 if (process_type == kMainFunctions[i].name)
860 return kMainFunctions[i].function(main_function_params);
862 #endif
864 return -1;
867 void ChromeMainDelegate::ProcessExiting(const std::string& process_type) {
868 if (SubprocessNeedsResourceBundle(process_type))
869 ResourceBundle::CleanupSharedInstance();
870 #if !defined(OS_ANDROID)
871 logging::CleanupChromeLogging();
872 #else
873 // Android doesn't use InitChromeLogging, so we close the log file manually.
874 logging::CloseLogFile();
875 #endif // !defined(OS_ANDROID)
877 #if defined(OS_WIN)
878 RemoveCloseHandleHooks();
879 #endif
882 #if defined(OS_MACOSX)
883 bool ChromeMainDelegate::ProcessRegistersWithSystemProcess(
884 const std::string& process_type) {
885 #if defined(DISABLE_NACL)
886 return false;
887 #else
888 return process_type == switches::kNaClLoaderProcess;
889 #endif
892 bool ChromeMainDelegate::ShouldSendMachPort(const std::string& process_type) {
893 return process_type != switches::kRelauncherProcess &&
894 process_type != switches::kServiceProcess;
897 bool ChromeMainDelegate::DelaySandboxInitialization(
898 const std::string& process_type) {
899 #if !defined(DISABLE_NACL)
900 // NaClLoader does this in NaClMainPlatformDelegate::EnableSandbox().
901 // No sandbox needed for relauncher.
902 if (process_type == switches::kNaClLoaderProcess)
903 return true;
904 #endif
905 return process_type == switches::kRelauncherProcess;
907 #elif defined(OS_POSIX) && !defined(OS_ANDROID)
908 void ChromeMainDelegate::ZygoteStarting(
909 ScopedVector<content::ZygoteForkDelegate>* delegates) {
910 #if !defined(DISABLE_NACL)
911 nacl::AddNaClZygoteForkDelegates(delegates);
912 #endif
915 void ChromeMainDelegate::ZygoteForked() {
916 Profiling::ProcessStarted();
917 if (Profiling::BeingProfiled()) {
918 base::debug::RestartProfilingAfterFork();
919 SetUpProfilingShutdownHandler();
922 // Needs to be called after we have chrome::DIR_USER_DATA. BrowserMain sets
923 // this up for the browser process in a different manner.
924 const base::CommandLine* command_line =
925 base::CommandLine::ForCurrentProcess();
926 std::string process_type =
927 command_line->GetSwitchValueASCII(switches::kProcessType);
928 breakpad::InitCrashReporter(process_type);
930 // Reset the command line for the newly spawned process.
931 crash_keys::SetSwitchesFromCommandLine(command_line);
934 #endif // OS_MACOSX
936 content::ContentBrowserClient*
937 ChromeMainDelegate::CreateContentBrowserClient() {
938 #if defined(CHROME_MULTIPLE_DLL_CHILD)
939 return NULL;
940 #else
941 return g_chrome_content_browser_client.Pointer();
942 #endif
945 content::ContentPluginClient* ChromeMainDelegate::CreateContentPluginClient() {
946 #if defined(CHROME_MULTIPLE_DLL_BROWSER)
947 return NULL;
948 #else
949 return g_chrome_content_plugin_client.Pointer();
950 #endif
953 content::ContentRendererClient*
954 ChromeMainDelegate::CreateContentRendererClient() {
955 #if defined(CHROME_MULTIPLE_DLL_BROWSER)
956 return NULL;
957 #else
958 return g_chrome_content_renderer_client.Pointer();
959 #endif
962 content::ContentUtilityClient*
963 ChromeMainDelegate::CreateContentUtilityClient() {
964 #if defined(CHROME_MULTIPLE_DLL_BROWSER)
965 return NULL;
966 #else
967 return g_chrome_content_utility_client.Pointer();
968 #endif
971 bool ChromeMainDelegate::ShouldEnableProfilerRecording() {
972 switch (chrome::GetChannel()) {
973 case version_info::Channel::UNKNOWN:
974 case version_info::Channel::CANARY:
975 return true;
976 case version_info::Channel::DEV:
977 case version_info::Channel::BETA:
978 case version_info::Channel::STABLE:
979 default:
980 // Don't enable instrumentation.
981 return false;