Support SizeClassIdiom on iOS7.
[chromium-blink-merge.git] / chrome / app / chrome_main_delegate.cc
blobdcc8c3b647f459ddac137f624271c0e1eb8e58e1
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 base::string16& command_line) {
156 const wchar_t kChromeHtml[] = L"chromehtml:";
157 base::string16 command_line_lower = base::ToLowerASCII(command_line);
158 // We are only searching for ASCII characters so this is OK.
159 return (command_line_lower.find(kChromeHtml) != base::string16::npos);
162 // If we try to access a path that is not currently available, we want the call
163 // to fail rather than show an error dialog.
164 void SuppressWindowsErrorDialogs() {
165 UINT new_flags = SEM_FAILCRITICALERRORS |
166 SEM_NOOPENFILEERRORBOX;
168 // Preserve existing error mode.
169 UINT existing_flags = SetErrorMode(new_flags);
170 SetErrorMode(existing_flags | new_flags);
173 bool IsSandboxedProcess() {
174 typedef bool (*IsSandboxedProcessFunc)();
175 IsSandboxedProcessFunc is_sandboxed_process_func =
176 reinterpret_cast<IsSandboxedProcessFunc>(
177 GetProcAddress(GetModuleHandle(NULL), "IsSandboxedProcess"));
178 return is_sandboxed_process_func && is_sandboxed_process_func();
181 #endif // defined(OS_WIN)
183 #if defined(OS_LINUX)
184 static void AdjustLinuxOOMScore(const std::string& process_type) {
185 // Browsers and zygotes should still be killable, but killed last.
186 const int kZygoteScore = 0;
187 // The minimum amount to bump a score by. This is large enough that
188 // even if it's translated into the old values, it will still go up
189 // by at least one.
190 const int kScoreBump = 100;
191 // This is the lowest score that renderers and extensions start with
192 // in the OomPriorityManager.
193 const int kRendererScore = chrome::kLowestRendererOomScore;
194 // For "miscellaneous" things, we want them after renderers,
195 // but before plugins.
196 const int kMiscScore = kRendererScore - kScoreBump;
197 // We want plugins to die after the renderers.
198 const int kPluginScore = kMiscScore - kScoreBump;
199 int score = -1;
201 DCHECK(kMiscScore > 0);
202 DCHECK(kPluginScore > 0);
204 if (process_type == switches::kPluginProcess ||
205 process_type == switches::kPpapiPluginProcess) {
206 score = kPluginScore;
207 } else if (process_type == switches::kPpapiBrokerProcess) {
208 // The broker should be killed before the PPAPI plugin.
209 score = kPluginScore + kScoreBump;
210 } else if (process_type == switches::kUtilityProcess ||
211 process_type == switches::kGpuProcess ||
212 process_type == switches::kServiceProcess) {
213 score = kMiscScore;
214 #ifndef DISABLE_NACL
215 } else if (process_type == switches::kNaClLoaderProcess ||
216 process_type == switches::kNaClLoaderNonSfiProcess) {
217 score = kPluginScore;
218 #endif
219 } else if (process_type == switches::kZygoteProcess ||
220 process_type.empty()) {
221 // For zygotes and unlabeled process types, we want to still make
222 // them killable by the OOM killer.
223 score = kZygoteScore;
224 } else if (process_type == switches::kRendererProcess) {
225 LOG(WARNING) << "process type 'renderer' "
226 << "should be created through the zygote.";
227 // When debugging, this process type can end up being run directly, but
228 // this isn't the typical path for assigning the OOM score for it. Still,
229 // we want to assign a score that is somewhat representative for debugging.
230 score = kRendererScore;
231 } else {
232 NOTREACHED() << "Unknown process type";
234 if (score > -1)
235 base::AdjustOOMScore(base::GetCurrentProcId(), score);
237 #endif // defined(OS_LINUX)
239 // Returns true if this subprocess type needs the ResourceBundle initialized
240 // and resources loaded.
241 bool SubprocessNeedsResourceBundle(const std::string& process_type) {
242 return
243 #if defined(OS_WIN) || defined(OS_MACOSX)
244 // Windows needs resources for the default/null plugin.
245 // Mac needs them for the plugin process name.
246 process_type == switches::kPluginProcess ||
247 #endif
248 #if defined(OS_POSIX) && !defined(OS_MACOSX)
249 // The zygote process opens the resources for the renderers.
250 process_type == switches::kZygoteProcess ||
251 #endif
252 #if defined(OS_MACOSX)
253 // Mac needs them too for scrollbar related images and for sandbox
254 // profiles.
255 #if !defined(DISABLE_NACL)
256 process_type == switches::kNaClLoaderProcess ||
257 #endif
258 process_type == switches::kPpapiPluginProcess ||
259 process_type == switches::kPpapiBrokerProcess ||
260 process_type == switches::kGpuProcess ||
261 #endif
262 process_type == switches::kRendererProcess ||
263 process_type == switches::kUtilityProcess;
266 #if defined(OS_POSIX)
267 // Check for --version and --product-version; return true if we encountered
268 // one of these switches and should exit now.
269 bool HandleVersionSwitches(const base::CommandLine& command_line) {
270 #if !defined(OS_MACOSX)
271 if (command_line.HasSwitch(switches::kProductVersion)) {
272 printf("%s\n", version_info::GetVersionNumber().c_str());
273 return true;
275 #endif
277 if (command_line.HasSwitch(switches::kVersion)) {
278 printf("%s %s %s\n",
279 version_info::GetProductName().c_str(),
280 version_info::GetVersionNumber().c_str(),
281 chrome::GetChannelString().c_str());
282 return true;
285 return false;
288 #if !defined(OS_MACOSX) && !defined(OS_CHROMEOS)
289 // Show the man page if --help or -h is on the command line.
290 void HandleHelpSwitches(const base::CommandLine& command_line) {
291 if (command_line.HasSwitch(switches::kHelp) ||
292 command_line.HasSwitch(switches::kHelpShort)) {
293 base::FilePath binary(command_line.argv()[0]);
294 execlp("man", "man", binary.BaseName().value().c_str(), NULL);
295 PLOG(FATAL) << "execlp failed";
298 #endif
300 #if !defined(OS_MACOSX) && !defined(OS_ANDROID)
301 void SIGTERMProfilingShutdown(int signal) {
302 Profiling::Stop();
303 struct sigaction sigact;
304 memset(&sigact, 0, sizeof(sigact));
305 sigact.sa_handler = SIG_DFL;
306 CHECK(sigaction(SIGTERM, &sigact, NULL) == 0);
307 raise(signal);
310 void SetUpProfilingShutdownHandler() {
311 struct sigaction sigact;
312 sigact.sa_handler = SIGTERMProfilingShutdown;
313 sigact.sa_flags = SA_RESETHAND;
314 sigemptyset(&sigact.sa_mask);
315 CHECK(sigaction(SIGTERM, &sigact, NULL) == 0);
317 #endif // !defined(OS_MACOSX) && !defined(OS_ANDROID)
319 #endif // OS_POSIX
321 struct MainFunction {
322 const char* name;
323 int (*function)(const content::MainFunctionParams&);
326 // Initializes the user data dir. Must be called before InitializeLocalState().
327 void InitializeUserDataDir() {
328 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
329 base::FilePath user_data_dir =
330 command_line->GetSwitchValuePath(switches::kUserDataDir);
331 std::string process_type =
332 command_line->GetSwitchValueASCII(switches::kProcessType);
334 #if defined(OS_LINUX)
335 // On Linux, Chrome does not support running multiple copies under different
336 // DISPLAYs, so the profile directory can be specified in the environment to
337 // support the virtual desktop use-case.
338 if (user_data_dir.empty()) {
339 std::string user_data_dir_string;
340 scoped_ptr<base::Environment> environment(base::Environment::Create());
341 if (environment->GetVar("CHROME_USER_DATA_DIR", &user_data_dir_string) &&
342 base::IsStringUTF8(user_data_dir_string)) {
343 user_data_dir = base::FilePath::FromUTF8Unsafe(user_data_dir_string);
346 #endif
347 #if defined(OS_MACOSX) || defined(OS_WIN)
348 policy::path_parser::CheckUserDataDirPolicy(&user_data_dir);
349 #endif
351 // On Windows, trailing separators leave Chrome in a bad state.
352 // See crbug.com/464616.
353 if (user_data_dir.EndsWithSeparator())
354 user_data_dir = user_data_dir.StripTrailingSeparators();
356 const bool specified_directory_was_invalid = !user_data_dir.empty() &&
357 !PathService::OverrideAndCreateIfNeeded(chrome::DIR_USER_DATA,
358 user_data_dir, false, true);
359 // Save inaccessible or invalid paths so the user may be prompted later.
360 if (specified_directory_was_invalid)
361 chrome::SetInvalidSpecifiedUserDataDir(user_data_dir);
363 // Warn and fail early if the process fails to get a user data directory.
364 if (!PathService::Get(chrome::DIR_USER_DATA, &user_data_dir)) {
365 // If an invalid command-line or policy override was specified, the user
366 // will be given an error with that value. Otherwise, use the directory
367 // returned by PathService (or the fallback default directory) in the error.
368 if (!specified_directory_was_invalid) {
369 // PathService::Get() returns false and yields an empty path if it fails
370 // to create DIR_USER_DATA. Retrieve the default value manually to display
371 // a more meaningful error to the user in that case.
372 if (user_data_dir.empty())
373 chrome::GetDefaultUserDataDirectory(&user_data_dir);
374 chrome::SetInvalidSpecifiedUserDataDir(user_data_dir);
377 // The browser process (which is identified by an empty |process_type|) will
378 // handle the error later; other processes that need the dir crash here.
379 CHECK(process_type.empty()) << "Unable to get the user data directory "
380 << "for process type: " << process_type;
383 // Append the fallback user data directory to the commandline. Otherwise,
384 // child or service processes will attempt to use the invalid directory.
385 if (specified_directory_was_invalid)
386 command_line->AppendSwitchPath(switches::kUserDataDir, user_data_dir);
389 } // namespace
391 ChromeMainDelegate::ChromeMainDelegate() {
392 #if defined(OS_ANDROID)
393 // On Android the main entry point time is the time when the Java code starts.
394 // This happens before the shared library containing this code is even loaded.
395 // The Java startup code has recorded that time, but the C++ code can't fetch it
396 // from the Java side until it has initialized the JNI. See
397 // ChromeMainDelegateAndroid.
398 #else
399 startup_metric_utils::RecordMainEntryPointTime();
400 #endif
403 ChromeMainDelegate::~ChromeMainDelegate() {
406 bool ChromeMainDelegate::BasicStartupComplete(int* exit_code) {
407 #if defined(OS_CHROMEOS)
408 chromeos::BootTimesRecorder::Get()->SaveChromeMainStats();
409 #endif
411 const base::CommandLine& command_line =
412 *base::CommandLine::ForCurrentProcess();
415 #if defined(OS_WIN)
416 // Browser should not be sandboxed.
417 const bool is_browser = !command_line.HasSwitch(switches::kProcessType);
418 if (is_browser && IsSandboxedProcess()) {
419 *exit_code = chrome::RESULT_CODE_INVALID_SANDBOX_STATE;
420 return true;
422 #endif
424 #if defined(OS_MACOSX)
425 // Give the browser process a longer treadmill, since crashes
426 // there have more impact.
427 const bool is_browser = !command_line.HasSwitch(switches::kProcessType);
428 ObjcEvilDoers::ZombieEnable(true, is_browser ? 10000 : 1000);
430 SetUpBundleOverrides();
431 chrome::common::mac::EnableCFBundleBlocker();
432 #endif
434 Profiling::ProcessStarted();
436 base::trace_event::TraceLog::GetInstance()->SetArgumentFilterPredicate(
437 base::Bind(&IsTraceEventArgsWhitelisted));
439 #if defined(OS_WIN)
440 v8_breakpad_support::SetUp();
441 #endif
443 #if defined(OS_POSIX)
444 if (HandleVersionSwitches(command_line)) {
445 *exit_code = 0;
446 return true; // Got a --version switch; exit with a success error code.
448 #if !defined(OS_MACOSX) && !defined(OS_CHROMEOS)
449 // This will directly exit if the user asked for help.
450 HandleHelpSwitches(command_line);
451 #endif
452 #endif // OS_POSIX
454 #if defined(OS_WIN)
455 // Must do this before any other usage of command line!
456 if (HasDeprecatedArguments(command_line.GetCommandLineString())) {
457 *exit_code = 1;
458 return true;
461 InstallHandleHooks();
462 #endif
464 chrome::RegisterPathProvider();
465 #if defined(OS_CHROMEOS)
466 chromeos::RegisterPathProvider();
467 #endif
468 #if !defined(DISABLE_NACL) && defined(OS_LINUX)
469 nacl::RegisterPathProvider();
470 #endif
472 ContentSettingsPattern::SetNonWildcardDomainNonPortScheme(
473 extensions::kExtensionScheme);
475 // No support for ANDROID yet as DiagnosticsController needs wchar support.
476 // TODO(gspencer): That's not true anymore, or at least there are no w-string
477 // references anymore. Not sure if that means this can be enabled on Android or
478 // not though. As there is no easily accessible command line on Android, I'm
479 // not sure this is a big deal.
480 #if !defined(OS_ANDROID) && !defined(CHROME_MULTIPLE_DLL_CHILD)
481 // If we are in diagnostics mode this is the end of the line: after the
482 // diagnostics are run the process will invariably exit.
483 if (command_line.HasSwitch(switches::kDiagnostics)) {
484 diagnostics::DiagnosticsWriter::FormatType format =
485 diagnostics::DiagnosticsWriter::HUMAN;
486 if (command_line.HasSwitch(switches::kDiagnosticsFormat)) {
487 std::string format_str =
488 command_line.GetSwitchValueASCII(switches::kDiagnosticsFormat);
489 if (format_str == "machine") {
490 format = diagnostics::DiagnosticsWriter::MACHINE;
491 } else if (format_str == "log") {
492 format = diagnostics::DiagnosticsWriter::LOG;
493 } else {
494 DCHECK_EQ("human", format_str);
498 diagnostics::DiagnosticsWriter writer(format);
499 *exit_code = diagnostics::DiagnosticsController::GetInstance()->Run(
500 command_line, &writer);
501 diagnostics::DiagnosticsController::GetInstance()->ClearResults();
502 return true;
504 #endif
506 #if defined(OS_CHROMEOS)
507 // Initialize primary user homedir (in multi-profile session) as it may be
508 // passed as a command line switch.
509 base::FilePath homedir;
510 if (command_line.HasSwitch(chromeos::switches::kHomedir)) {
511 homedir = base::FilePath(
512 command_line.GetSwitchValueASCII(chromeos::switches::kHomedir));
513 PathService::OverrideAndCreateIfNeeded(
514 base::DIR_HOME, homedir, true, false);
517 // If we are recovering from a crash on ChromeOS, then we will do some
518 // recovery using the diagnostics module, and then continue on. We fake up a
519 // command line to tell it that we want it to recover, and to preserve the
520 // original command line.
521 if (command_line.HasSwitch(chromeos::switches::kLoginUser) ||
522 command_line.HasSwitch(switches::kDiagnosticsRecovery)) {
523 // The statistics subsystem needs get initialized soon enough for the
524 // statistics to be collected. It's safe to call this more than once.
525 base::StatisticsRecorder::Initialize();
527 base::CommandLine interim_command_line(command_line.GetProgram());
528 const char* const kSwitchNames[] = {switches::kUserDataDir, };
529 interim_command_line.CopySwitchesFrom(
530 command_line, kSwitchNames, arraysize(kSwitchNames));
531 interim_command_line.AppendSwitch(switches::kDiagnostics);
532 interim_command_line.AppendSwitch(switches::kDiagnosticsRecovery);
534 diagnostics::DiagnosticsWriter::FormatType format =
535 diagnostics::DiagnosticsWriter::LOG;
536 if (command_line.HasSwitch(switches::kDiagnosticsFormat)) {
537 std::string format_str =
538 command_line.GetSwitchValueASCII(switches::kDiagnosticsFormat);
539 if (format_str == "machine") {
540 format = diagnostics::DiagnosticsWriter::MACHINE;
541 } else if (format_str == "human") {
542 format = diagnostics::DiagnosticsWriter::HUMAN;
543 } else {
544 DCHECK_EQ("log", format_str);
548 diagnostics::DiagnosticsWriter writer(format);
549 int diagnostics_exit_code =
550 diagnostics::DiagnosticsController::GetInstance()->Run(command_line,
551 &writer);
552 if (diagnostics_exit_code) {
553 // Diagnostics has failed somehow, so we exit.
554 *exit_code = diagnostics_exit_code;
555 return true;
558 // Now we run the actual recovery tasks.
559 int recovery_exit_code =
560 diagnostics::DiagnosticsController::GetInstance()->RunRecovery(
561 command_line, &writer);
563 if (recovery_exit_code) {
564 // Recovery has failed somehow, so we exit.
565 *exit_code = recovery_exit_code;
566 return true;
568 } else { // Not running diagnostics or recovery.
569 diagnostics::DiagnosticsController::GetInstance()->RecordRegularStartup();
571 #endif
573 content::SetContentClient(&chrome_content_client_);
575 return false;
578 #if defined(OS_MACOSX)
579 void ChromeMainDelegate::InitMacCrashReporter(
580 const base::CommandLine& command_line,
581 const std::string& process_type) {
582 // TODO(mark): Right now, InitializeCrashpad() needs to be called after
583 // CommandLine::Init() and chrome::RegisterPathProvider(). Ideally, Crashpad
584 // initialization could occur sooner, preferably even before the framework
585 // dylib is even loaded, to catch potential early crashes.
586 crash_reporter::InitializeCrashpad(process_type);
588 const bool browser_process = process_type.empty();
589 if (!browser_process) {
590 std::string metrics_client_id =
591 command_line.GetSwitchValueASCII(switches::kMetricsClientID);
592 crash_keys::SetMetricsClientIdFromGUID(metrics_client_id);
595 // Mac Chrome is packaged with a main app bundle and a helper app bundle.
596 // The main app bundle should only be used for the browser process, so it
597 // should never see a --type switch (switches::kProcessType). Likewise,
598 // the helper should always have a --type switch.
600 // This check is done this late so there is already a call to
601 // base::mac::IsBackgroundOnlyProcess(), so there is no change in
602 // startup/initialization order.
604 // The helper's Info.plist marks it as a background only app.
605 if (base::mac::IsBackgroundOnlyProcess()) {
606 CHECK(command_line.HasSwitch(switches::kProcessType) &&
607 !process_type.empty())
608 << "Helper application requires --type.";
610 // In addition, some helper flavors only work with certain process types.
611 base::FilePath executable;
612 if (PathService::Get(base::FILE_EXE, &executable) &&
613 executable.value().size() >= 3) {
614 std::string last_three =
615 executable.value().substr(executable.value().size() - 3);
617 if (last_three == " EH") {
618 CHECK(process_type == switches::kPluginProcess ||
619 process_type == switches::kUtilityProcess)
620 << "Executable-heap process requires --type="
621 << switches::kPluginProcess << " or "
622 << switches::kUtilityProcess << ", saw " << process_type;
623 } else if (last_three == " NP") {
624 #if !defined(DISABLE_NACL)
625 CHECK_EQ(switches::kNaClLoaderProcess, process_type)
626 << "Non-PIE process requires --type="
627 << switches::kNaClLoaderProcess << ", saw " << process_type;
628 #endif
629 } else {
630 #if defined(DISABLE_NACL)
631 CHECK(process_type != switches::kPluginProcess)
632 << "Non-executable-heap PIE process is intolerant of --type="
633 << switches::kPluginProcess;
634 #else
635 CHECK(process_type != switches::kPluginProcess &&
636 process_type != switches::kNaClLoaderProcess)
637 << "Non-executable-heap PIE process is intolerant of --type="
638 << switches::kPluginProcess << " and "
639 << switches::kNaClLoaderProcess << ", saw " << process_type;
640 #endif
643 } else {
644 CHECK(!command_line.HasSwitch(switches::kProcessType) &&
645 process_type.empty())
646 << "Main application forbids --type, saw " << process_type;
649 #endif // defined(OS_MACOSX)
651 void ChromeMainDelegate::PreSandboxStartup() {
652 const base::CommandLine& command_line =
653 *base::CommandLine::ForCurrentProcess();
654 std::string process_type =
655 command_line.GetSwitchValueASCII(switches::kProcessType);
657 #if defined(OS_POSIX)
658 crash_reporter::SetCrashReporterClient(g_chrome_crash_client.Pointer());
659 #endif
661 #if defined(OS_MACOSX)
662 // On the Mac, the child executable lives at a predefined location within
663 // the app bundle's versioned directory.
664 PathService::Override(content::CHILD_PROCESS_EXE,
665 chrome::GetVersionedDirectory().
666 Append(chrome::kHelperProcessExecutablePath));
668 InitMacCrashReporter(command_line, process_type);
669 #endif
671 #if defined(OS_WIN)
672 child_process_logging::Init();
673 #endif
674 #if defined(ARCH_CPU_ARM_FAMILY) && (defined(OS_ANDROID) || defined(OS_LINUX))
675 // Create an instance of the CPU class to parse /proc/cpuinfo and cache
676 // cpu_brand info.
677 base::CPU cpu_info;
678 #endif
680 // Initialize the user data dir for any process type that needs it.
681 if (chrome::ProcessNeedsProfileDir(process_type))
682 InitializeUserDataDir();
684 // Register component_updater PathProvider after DIR_USER_DATA overidden by
685 // command line flags. Maybe move the chrome PathProvider down here also?
686 component_updater::RegisterPathProvider(chrome::DIR_USER_DATA);
688 // Enable Message Loop related state asap.
689 if (command_line.HasSwitch(switches::kMessageLoopHistogrammer))
690 base::MessageLoop::EnableHistogrammer(true);
692 #if !defined(OS_ANDROID)
693 // Android does InitLogging when library is loaded. Skip here.
694 logging::OldFileDeletionState file_state =
695 logging::APPEND_TO_OLD_LOG_FILE;
696 if (process_type.empty()) {
697 file_state = logging::DELETE_OLD_LOG_FILE;
699 logging::InitChromeLogging(command_line, file_state);
700 #endif
702 #if defined(OS_WIN)
703 // TODO(zturner): Throbber icons are still stored in chrome.dll, this can be
704 // killed once those are merged into resources.pak. See
705 // GlassBrowserFrameView::InitThrobberIcons() and http://crbug.com/368327.
706 ui::SetResourcesDataDLL(_AtlBaseModule.GetResourceInstance());
707 #endif
709 if (SubprocessNeedsResourceBundle(process_type)) {
710 // Initialize ResourceBundle which handles files loaded from external
711 // sources. The language should have been passed in to us from the
712 // browser process as a command line flag.
713 #if defined(DISABLE_NACL)
714 DCHECK(command_line.HasSwitch(switches::kLang) ||
715 process_type == switches::kZygoteProcess ||
716 process_type == switches::kGpuProcess ||
717 process_type == switches::kPpapiBrokerProcess ||
718 process_type == switches::kPpapiPluginProcess);
719 #else
720 DCHECK(command_line.HasSwitch(switches::kLang) ||
721 process_type == switches::kZygoteProcess ||
722 process_type == switches::kGpuProcess ||
723 process_type == switches::kNaClLoaderProcess ||
724 process_type == switches::kPpapiBrokerProcess ||
725 process_type == switches::kPpapiPluginProcess);
726 #endif
728 // TODO(markusheintz): The command line flag --lang is actually processed
729 // by the CommandLinePrefStore, and made available through the PrefService
730 // via the preference prefs::kApplicationLocale. The browser process uses
731 // the --lang flag to pass the value of the PrefService in here. Maybe
732 // this value could be passed in a different way.
733 const std::string locale =
734 command_line.GetSwitchValueASCII(switches::kLang);
735 #if defined(OS_ANDROID)
736 // The renderer sandbox prevents us from accessing our .pak files directly.
737 // Therefore file descriptors to the .pak files that we need are passed in
738 // at process creation time.
739 auto global_descriptors = base::GlobalDescriptors::GetInstance();
740 int pak_fd = global_descriptors->Get(kAndroidLocalePakDescriptor);
741 base::MemoryMappedFile::Region pak_region =
742 global_descriptors->GetRegion(kAndroidLocalePakDescriptor);
743 ResourceBundle::InitSharedInstanceWithPakFileRegion(base::File(pak_fd),
744 pak_region);
746 int extra_pak_keys[] = {
747 kAndroidChrome100PercentPakDescriptor,
748 kAndroidUIResourcesPakDescriptor,
750 for (size_t i = 0; i < arraysize(extra_pak_keys); ++i) {
751 pak_fd = global_descriptors->Get(extra_pak_keys[i]);
752 pak_region = global_descriptors->GetRegion(extra_pak_keys[i]);
753 ResourceBundle::GetSharedInstance().AddDataPackFromFileRegion(
754 base::File(pak_fd), pak_region, ui::SCALE_FACTOR_100P);
757 base::i18n::SetICUDefaultLocale(locale);
758 const std::string loaded_locale = locale;
759 #else
760 const std::string loaded_locale =
761 ui::ResourceBundle::InitSharedInstanceWithLocale(
762 locale, NULL, ui::ResourceBundle::LOAD_COMMON_RESOURCES);
764 base::FilePath resources_pack_path;
765 PathService::Get(chrome::FILE_RESOURCES_PACK, &resources_pack_path);
766 ResourceBundle::GetSharedInstance().AddDataPackFromPath(
767 resources_pack_path, ui::SCALE_FACTOR_NONE);
768 #endif
769 CHECK(!loaded_locale.empty()) << "Locale could not be found for " <<
770 locale;
773 #if !defined(CHROME_MULTIPLE_DLL_BROWSER)
774 if (process_type == switches::kUtilityProcess ||
775 process_type == switches::kZygoteProcess) {
776 ChromeContentUtilityClient::PreSandboxStartup();
779 chrome::InitializePDF();
780 #endif
782 #if defined(OS_POSIX) && !defined(OS_MACOSX)
783 // Zygote needs to call InitCrashReporter() in RunZygote().
784 if (process_type != switches::kZygoteProcess) {
785 #if defined(OS_ANDROID)
786 if (process_type.empty()) {
787 breakpad::InitCrashReporter(process_type);
788 chrome::android::InitJavaExceptionReporter();
789 } else {
790 breakpad::InitNonBrowserCrashReporterForAndroid(process_type);
792 #else // !defined(OS_ANDROID)
793 breakpad::InitCrashReporter(process_type);
794 #endif // defined(OS_ANDROID)
796 #endif // defined(OS_POSIX) && !defined(OS_MACOSX)
798 // After all the platform Breakpads have been initialized, store the command
799 // line for crash reporting.
800 crash_keys::SetSwitchesFromCommandLine(&command_line);
803 void ChromeMainDelegate::SandboxInitialized(const std::string& process_type) {
804 // Note: If you are adding a new process type below, be sure to adjust the
805 // AdjustLinuxOOMScore function too.
806 #if defined(OS_LINUX)
807 AdjustLinuxOOMScore(process_type);
808 #endif
809 #if defined(OS_WIN)
810 SuppressWindowsErrorDialogs();
811 #endif
813 #if defined(CHROME_MULTIPLE_DLL_CHILD) || !defined(CHROME_MULTIPLE_DLL_BROWSER)
814 #if !defined(DISABLE_NACL)
815 ChromeContentClient::SetNaClEntryFunctions(
816 nacl_plugin::PPP_GetInterface,
817 nacl_plugin::PPP_InitializeModule,
818 nacl_plugin::PPP_ShutdownModule);
819 #endif
820 #if defined(ENABLE_PLUGINS)
821 ChromeContentClient::SetPDFEntryFunctions(
822 chrome_pdf::PPP_GetInterface,
823 chrome_pdf::PPP_InitializeModule,
824 chrome_pdf::PPP_ShutdownModule);
825 #endif
826 #endif
829 int ChromeMainDelegate::RunProcess(
830 const std::string& process_type,
831 const content::MainFunctionParams& main_function_params) {
832 // ANDROID doesn't support "service", so no ServiceProcessMain, and arraysize
833 // doesn't support empty array. So we comment out the block for Android.
834 #if !defined(OS_ANDROID)
835 static const MainFunction kMainFunctions[] = {
836 #if defined(ENABLE_PRINT_PREVIEW) && !defined(CHROME_MULTIPLE_DLL_CHILD)
837 { switches::kServiceProcess, ServiceProcessMain },
838 #endif
840 #if defined(OS_MACOSX)
841 { switches::kRelauncherProcess,
842 mac_relauncher::internal::RelauncherMain },
843 #endif
845 // This entry is not needed on Linux, where the NaCl loader
846 // process is launched via nacl_helper instead.
847 #if !defined(DISABLE_NACL) && !defined(CHROME_MULTIPLE_DLL_BROWSER) && \
848 !defined(OS_LINUX)
849 { switches::kNaClLoaderProcess, NaClMain },
850 #else
851 { "<invalid>", NULL }, // To avoid constant array of size 0
852 // when DISABLE_NACL and CHROME_MULTIPLE_DLL_CHILD
853 #endif // DISABLE_NACL
856 for (size_t i = 0; i < arraysize(kMainFunctions); ++i) {
857 if (process_type == kMainFunctions[i].name)
858 return kMainFunctions[i].function(main_function_params);
860 #endif
862 return -1;
865 void ChromeMainDelegate::ProcessExiting(const std::string& process_type) {
866 if (SubprocessNeedsResourceBundle(process_type))
867 ResourceBundle::CleanupSharedInstance();
868 #if !defined(OS_ANDROID)
869 logging::CleanupChromeLogging();
870 #else
871 // Android doesn't use InitChromeLogging, so we close the log file manually.
872 logging::CloseLogFile();
873 #endif // !defined(OS_ANDROID)
875 #if defined(OS_WIN)
876 RemoveHandleHooks();
877 #endif
880 #if defined(OS_MACOSX)
881 bool ChromeMainDelegate::ProcessRegistersWithSystemProcess(
882 const std::string& process_type) {
883 #if defined(DISABLE_NACL)
884 return false;
885 #else
886 return process_type == switches::kNaClLoaderProcess;
887 #endif
890 bool ChromeMainDelegate::ShouldSendMachPort(const std::string& process_type) {
891 return process_type != switches::kRelauncherProcess &&
892 process_type != switches::kServiceProcess;
895 bool ChromeMainDelegate::DelaySandboxInitialization(
896 const std::string& process_type) {
897 #if !defined(DISABLE_NACL)
898 // NaClLoader does this in NaClMainPlatformDelegate::EnableSandbox().
899 // No sandbox needed for relauncher.
900 if (process_type == switches::kNaClLoaderProcess)
901 return true;
902 #endif
903 return process_type == switches::kRelauncherProcess;
905 #elif defined(OS_POSIX) && !defined(OS_ANDROID)
906 void ChromeMainDelegate::ZygoteStarting(
907 ScopedVector<content::ZygoteForkDelegate>* delegates) {
908 #if !defined(DISABLE_NACL)
909 nacl::AddNaClZygoteForkDelegates(delegates);
910 #endif
913 void ChromeMainDelegate::ZygoteForked() {
914 Profiling::ProcessStarted();
915 if (Profiling::BeingProfiled()) {
916 base::debug::RestartProfilingAfterFork();
917 SetUpProfilingShutdownHandler();
920 // Needs to be called after we have chrome::DIR_USER_DATA. BrowserMain sets
921 // this up for the browser process in a different manner.
922 const base::CommandLine* command_line =
923 base::CommandLine::ForCurrentProcess();
924 std::string process_type =
925 command_line->GetSwitchValueASCII(switches::kProcessType);
926 breakpad::InitCrashReporter(process_type);
928 // Reset the command line for the newly spawned process.
929 crash_keys::SetSwitchesFromCommandLine(command_line);
932 #endif // OS_MACOSX
934 content::ContentBrowserClient*
935 ChromeMainDelegate::CreateContentBrowserClient() {
936 #if defined(CHROME_MULTIPLE_DLL_CHILD)
937 return NULL;
938 #else
939 return g_chrome_content_browser_client.Pointer();
940 #endif
943 content::ContentPluginClient* ChromeMainDelegate::CreateContentPluginClient() {
944 #if defined(CHROME_MULTIPLE_DLL_BROWSER)
945 return NULL;
946 #else
947 return g_chrome_content_plugin_client.Pointer();
948 #endif
951 content::ContentRendererClient*
952 ChromeMainDelegate::CreateContentRendererClient() {
953 #if defined(CHROME_MULTIPLE_DLL_BROWSER)
954 return NULL;
955 #else
956 return g_chrome_content_renderer_client.Pointer();
957 #endif
960 content::ContentUtilityClient*
961 ChromeMainDelegate::CreateContentUtilityClient() {
962 #if defined(CHROME_MULTIPLE_DLL_BROWSER)
963 return NULL;
964 #else
965 return g_chrome_content_utility_client.Pointer();
966 #endif
969 bool ChromeMainDelegate::ShouldEnableProfilerRecording() {
970 switch (chrome::GetChannel()) {
971 case version_info::Channel::UNKNOWN:
972 case version_info::Channel::CANARY:
973 return true;
974 case version_info::Channel::DEV:
975 case version_info::Channel::BETA:
976 case version_info::Channel::STABLE:
977 default:
978 // Don't enable instrumentation.
979 return false;