Switch global error menu icon to vectorized MD asset
[chromium-blink-merge.git] / chrome / app / chrome_main_delegate.cc
blob9338b895325f9174b91b47d7820465724608ab5c
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/process/process_info.h"
19 #include "base/strings/string_util.h"
20 #include "base/time/time.h"
21 #include "base/trace_event/trace_event_impl.h"
22 #include "build/build_config.h"
23 #include "chrome/browser/chrome_content_browser_client.h"
24 #include "chrome/browser/defaults.h"
25 #include "chrome/common/channel_info.h"
26 #include "chrome/common/chrome_constants.h"
27 #include "chrome/common/chrome_content_client.h"
28 #include "chrome/common/chrome_paths.h"
29 #include "chrome/common/chrome_paths_internal.h"
30 #include "chrome/common/chrome_result_codes.h"
31 #include "chrome/common/chrome_switches.h"
32 #include "chrome/common/crash_keys.h"
33 #include "chrome/common/logging_chrome.h"
34 #include "chrome/common/profiling.h"
35 #include "chrome/common/switch_utils.h"
36 #include "chrome/common/trace_event_args_whitelist.h"
37 #include "chrome/common/url_constants.h"
38 #include "chrome/plugin/chrome_content_plugin_client.h"
39 #include "chrome/renderer/chrome_content_renderer_client.h"
40 #include "chrome/utility/chrome_content_utility_client.h"
41 #include "components/component_updater/component_updater_paths.h"
42 #include "components/content_settings/core/common/content_settings_pattern.h"
43 #include "components/startup_metric_utils/startup_metric_utils.h"
44 #include "components/version_info/version_info.h"
45 #include "content/public/common/content_client.h"
46 #include "content/public/common/content_paths.h"
47 #include "extensions/common/constants.h"
48 #include "ui/base/ui_base_switches.h"
50 #if defined(OS_WIN)
51 #include <atlbase.h>
52 #include <malloc.h>
53 #include <algorithm>
54 #include "chrome/app/close_handle_hook_win.h"
55 #include "chrome/common/child_process_logging.h"
56 #include "chrome/common/v8_breakpad_support_win.h"
57 #include "sandbox/win/src/sandbox.h"
58 #include "ui/base/resource/resource_bundle_win.h"
59 #endif
61 #if defined(OS_MACOSX)
62 #include "base/mac/foundation_util.h"
63 #include "chrome/app/chrome_main_mac.h"
64 #include "chrome/browser/mac/relauncher.h"
65 #include "chrome/common/mac/cfbundle_blocker.h"
66 #include "chrome/common/mac/objc_zombie.h"
67 #include "components/crash/app/crashpad_mac.h"
68 #include "ui/base/l10n/l10n_util_mac.h"
69 #endif
71 #if defined(OS_POSIX)
72 #include <locale.h>
73 #include <signal.h>
74 #include "chrome/app/chrome_crash_reporter_client.h"
75 #include "components/crash/app/crash_reporter_client.h"
76 #endif
78 #if !defined(DISABLE_NACL) && defined(OS_LINUX)
79 #include "components/nacl/common/nacl_paths.h"
80 #include "components/nacl/zygote/nacl_fork_delegate_linux.h"
81 #endif
83 #if defined(OS_CHROMEOS)
84 #include "base/sys_info.h"
85 #include "chrome/browser/chromeos/boot_times_recorder.h"
86 #include "chromeos/chromeos_paths.h"
87 #include "chromeos/chromeos_switches.h"
88 #endif
90 #if defined(OS_ANDROID)
91 #include "chrome/browser/android/java_exception_reporter.h"
92 #include "chrome/common/descriptors_android.h"
93 #else
94 // Diagnostics is only available on non-android platforms.
95 #include "chrome/browser/diagnostics/diagnostics_controller.h"
96 #include "chrome/browser/diagnostics/diagnostics_writer.h"
97 #endif
99 #if defined(USE_X11)
100 #include <stdlib.h>
101 #include <string.h>
102 #include "ui/base/x/x11_util.h"
103 #endif
105 #if defined(OS_POSIX) && !defined(OS_MACOSX)
106 #include "components/crash/app/breakpad_linux.h"
107 #endif
109 #if defined(OS_LINUX)
110 #include "base/environment.h"
111 #endif
113 #if defined(OS_MACOSX) || defined(OS_WIN)
114 #include "chrome/browser/policy/policy_path_parser.h"
115 #endif
117 #if !defined(DISABLE_NACL)
118 #include "components/nacl/common/nacl_switches.h"
119 #include "components/nacl/renderer/plugin/ppapi_entrypoints.h"
120 #endif
122 #if defined(ENABLE_PLUGINS) && (defined(CHROME_MULTIPLE_DLL_CHILD) || \
123 !defined(CHROME_MULTIPLE_DLL_BROWSER))
124 #include "pdf/pdf.h"
125 #endif
127 #if !defined(CHROME_MULTIPLE_DLL_BROWSER)
128 #include "chrome/child/pdf_child_init.h"
130 base::LazyInstance<ChromeContentRendererClient>
131 g_chrome_content_renderer_client = LAZY_INSTANCE_INITIALIZER;
132 base::LazyInstance<ChromeContentUtilityClient>
133 g_chrome_content_utility_client = LAZY_INSTANCE_INITIALIZER;
134 base::LazyInstance<chrome::ChromeContentPluginClient>
135 g_chrome_content_plugin_client = LAZY_INSTANCE_INITIALIZER;
136 #endif
138 #if !defined(CHROME_MULTIPLE_DLL_CHILD)
139 base::LazyInstance<chrome::ChromeContentBrowserClient>
140 g_chrome_content_browser_client = LAZY_INSTANCE_INITIALIZER;
141 #endif
143 #if defined(OS_POSIX)
144 base::LazyInstance<chrome::ChromeCrashReporterClient>::Leaky
145 g_chrome_crash_client = LAZY_INSTANCE_INITIALIZER;
146 #endif
148 extern int NaClMain(const content::MainFunctionParams&);
149 extern int ServiceProcessMain(const content::MainFunctionParams&);
151 namespace {
153 #if defined(OS_WIN)
154 // Early versions of Chrome incorrectly registered a chromehtml: URL handler,
155 // which gives us nothing but trouble. Avoid launching chrome this way since
156 // some apps fail to properly escape arguments.
157 bool HasDeprecatedArguments(const base::string16& command_line) {
158 const wchar_t kChromeHtml[] = L"chromehtml:";
159 base::string16 command_line_lower = base::ToLowerASCII(command_line);
160 // We are only searching for ASCII characters so this is OK.
161 return (command_line_lower.find(kChromeHtml) != base::string16::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_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
395 // Record the startup process creation time on supported platforms.
396 startup_metric_utils::RecordStartupProcessCreationTime(
397 base::CurrentProcessInfo::CreationTime());
398 #endif
400 // On Android the main entry point time is the time when the Java code starts.
401 // This happens before the shared library containing this code is even loaded.
402 // The Java startup code has recorded that time, but the C++ code can't fetch it
403 // from the Java side until it has initialized the JNI. See
404 // ChromeMainDelegateAndroid.
405 #if !defined(OS_ANDROID)
406 startup_metric_utils::RecordMainEntryPointTime(base::Time::Now());
407 #endif
410 ChromeMainDelegate::~ChromeMainDelegate() {
413 bool ChromeMainDelegate::BasicStartupComplete(int* exit_code) {
414 #if defined(OS_CHROMEOS)
415 chromeos::BootTimesRecorder::Get()->SaveChromeMainStats();
416 #endif
418 const base::CommandLine& command_line =
419 *base::CommandLine::ForCurrentProcess();
422 #if defined(OS_WIN)
423 // Browser should not be sandboxed.
424 const bool is_browser = !command_line.HasSwitch(switches::kProcessType);
425 if (is_browser && IsSandboxedProcess()) {
426 *exit_code = chrome::RESULT_CODE_INVALID_SANDBOX_STATE;
427 return true;
429 #endif
431 #if defined(OS_MACOSX)
432 // Give the browser process a longer treadmill, since crashes
433 // there have more impact.
434 const bool is_browser = !command_line.HasSwitch(switches::kProcessType);
435 ObjcEvilDoers::ZombieEnable(true, is_browser ? 10000 : 1000);
437 SetUpBundleOverrides();
438 chrome::common::mac::EnableCFBundleBlocker();
439 #endif
441 Profiling::ProcessStarted();
443 base::trace_event::TraceLog::GetInstance()->SetArgumentFilterPredicate(
444 base::Bind(&IsTraceEventArgsWhitelisted));
446 #if defined(OS_WIN)
447 v8_breakpad_support::SetUp();
448 #endif
450 #if defined(OS_POSIX)
451 if (HandleVersionSwitches(command_line)) {
452 *exit_code = 0;
453 return true; // Got a --version switch; exit with a success error code.
455 #if !defined(OS_MACOSX) && !defined(OS_CHROMEOS)
456 // This will directly exit if the user asked for help.
457 HandleHelpSwitches(command_line);
458 #endif
459 #endif // OS_POSIX
461 #if defined(OS_WIN)
462 // Must do this before any other usage of command line!
463 if (HasDeprecatedArguments(command_line.GetCommandLineString())) {
464 *exit_code = 1;
465 return true;
468 InstallHandleHooks();
469 #endif
471 chrome::RegisterPathProvider();
472 #if defined(OS_CHROMEOS)
473 chromeos::RegisterPathProvider();
474 #endif
475 #if !defined(DISABLE_NACL) && defined(OS_LINUX)
476 nacl::RegisterPathProvider();
477 #endif
479 ContentSettingsPattern::SetNonWildcardDomainNonPortScheme(
480 extensions::kExtensionScheme);
482 // No support for ANDROID yet as DiagnosticsController needs wchar support.
483 // TODO(gspencer): That's not true anymore, or at least there are no w-string
484 // references anymore. Not sure if that means this can be enabled on Android or
485 // not though. As there is no easily accessible command line on Android, I'm
486 // not sure this is a big deal.
487 #if !defined(OS_ANDROID) && !defined(CHROME_MULTIPLE_DLL_CHILD)
488 // If we are in diagnostics mode this is the end of the line: after the
489 // diagnostics are run the process will invariably exit.
490 if (command_line.HasSwitch(switches::kDiagnostics)) {
491 diagnostics::DiagnosticsWriter::FormatType format =
492 diagnostics::DiagnosticsWriter::HUMAN;
493 if (command_line.HasSwitch(switches::kDiagnosticsFormat)) {
494 std::string format_str =
495 command_line.GetSwitchValueASCII(switches::kDiagnosticsFormat);
496 if (format_str == "machine") {
497 format = diagnostics::DiagnosticsWriter::MACHINE;
498 } else if (format_str == "log") {
499 format = diagnostics::DiagnosticsWriter::LOG;
500 } else {
501 DCHECK_EQ("human", format_str);
505 diagnostics::DiagnosticsWriter writer(format);
506 *exit_code = diagnostics::DiagnosticsController::GetInstance()->Run(
507 command_line, &writer);
508 diagnostics::DiagnosticsController::GetInstance()->ClearResults();
509 return true;
511 #endif
513 #if defined(OS_CHROMEOS)
514 // Initialize primary user homedir (in multi-profile session) as it may be
515 // passed as a command line switch.
516 base::FilePath homedir;
517 if (command_line.HasSwitch(chromeos::switches::kHomedir)) {
518 homedir = base::FilePath(
519 command_line.GetSwitchValueASCII(chromeos::switches::kHomedir));
520 PathService::OverrideAndCreateIfNeeded(
521 base::DIR_HOME, homedir, true, false);
524 // If we are recovering from a crash on ChromeOS, then we will do some
525 // recovery using the diagnostics module, and then continue on. We fake up a
526 // command line to tell it that we want it to recover, and to preserve the
527 // original command line.
528 if (command_line.HasSwitch(chromeos::switches::kLoginUser) ||
529 command_line.HasSwitch(switches::kDiagnosticsRecovery)) {
530 // The statistics subsystem needs get initialized soon enough for the
531 // statistics to be collected. It's safe to call this more than once.
532 base::StatisticsRecorder::Initialize();
534 base::CommandLine interim_command_line(command_line.GetProgram());
535 const char* const kSwitchNames[] = {switches::kUserDataDir, };
536 interim_command_line.CopySwitchesFrom(
537 command_line, kSwitchNames, arraysize(kSwitchNames));
538 interim_command_line.AppendSwitch(switches::kDiagnostics);
539 interim_command_line.AppendSwitch(switches::kDiagnosticsRecovery);
541 diagnostics::DiagnosticsWriter::FormatType format =
542 diagnostics::DiagnosticsWriter::LOG;
543 if (command_line.HasSwitch(switches::kDiagnosticsFormat)) {
544 std::string format_str =
545 command_line.GetSwitchValueASCII(switches::kDiagnosticsFormat);
546 if (format_str == "machine") {
547 format = diagnostics::DiagnosticsWriter::MACHINE;
548 } else if (format_str == "human") {
549 format = diagnostics::DiagnosticsWriter::HUMAN;
550 } else {
551 DCHECK_EQ("log", format_str);
555 diagnostics::DiagnosticsWriter writer(format);
556 int diagnostics_exit_code =
557 diagnostics::DiagnosticsController::GetInstance()->Run(command_line,
558 &writer);
559 if (diagnostics_exit_code) {
560 // Diagnostics has failed somehow, so we exit.
561 *exit_code = diagnostics_exit_code;
562 return true;
565 // Now we run the actual recovery tasks.
566 int recovery_exit_code =
567 diagnostics::DiagnosticsController::GetInstance()->RunRecovery(
568 command_line, &writer);
570 if (recovery_exit_code) {
571 // Recovery has failed somehow, so we exit.
572 *exit_code = recovery_exit_code;
573 return true;
575 } else { // Not running diagnostics or recovery.
576 diagnostics::DiagnosticsController::GetInstance()->RecordRegularStartup();
578 #endif
580 content::SetContentClient(&chrome_content_client_);
582 return false;
585 #if defined(OS_MACOSX)
586 void ChromeMainDelegate::InitMacCrashReporter(
587 const base::CommandLine& command_line,
588 const std::string& process_type) {
589 // TODO(mark): Right now, InitializeCrashpad() needs to be called after
590 // CommandLine::Init() and chrome::RegisterPathProvider(). Ideally, Crashpad
591 // initialization could occur sooner, preferably even before the framework
592 // dylib is even loaded, to catch potential early crashes.
593 crash_reporter::InitializeCrashpad(process_type);
595 const bool browser_process = process_type.empty();
596 if (!browser_process) {
597 std::string metrics_client_id =
598 command_line.GetSwitchValueASCII(switches::kMetricsClientID);
599 crash_keys::SetMetricsClientIdFromGUID(metrics_client_id);
602 // Mac Chrome is packaged with a main app bundle and a helper app bundle.
603 // The main app bundle should only be used for the browser process, so it
604 // should never see a --type switch (switches::kProcessType). Likewise,
605 // the helper should always have a --type switch.
607 // This check is done this late so there is already a call to
608 // base::mac::IsBackgroundOnlyProcess(), so there is no change in
609 // startup/initialization order.
611 // The helper's Info.plist marks it as a background only app.
612 if (base::mac::IsBackgroundOnlyProcess()) {
613 CHECK(command_line.HasSwitch(switches::kProcessType) &&
614 !process_type.empty())
615 << "Helper application requires --type.";
617 // In addition, some helper flavors only work with certain process types.
618 base::FilePath executable;
619 if (PathService::Get(base::FILE_EXE, &executable) &&
620 executable.value().size() >= 3) {
621 std::string last_three =
622 executable.value().substr(executable.value().size() - 3);
624 if (last_three == " EH") {
625 CHECK(process_type == switches::kPluginProcess ||
626 process_type == switches::kUtilityProcess)
627 << "Executable-heap process requires --type="
628 << switches::kPluginProcess << " or "
629 << switches::kUtilityProcess << ", saw " << process_type;
630 } else {
631 CHECK(process_type != switches::kPluginProcess)
632 << "Non-executable-heap PIE process is intolerant of --type="
633 << switches::kPluginProcess;
636 } else {
637 CHECK(!command_line.HasSwitch(switches::kProcessType) &&
638 process_type.empty())
639 << "Main application forbids --type, saw " << process_type;
642 #endif // defined(OS_MACOSX)
644 void ChromeMainDelegate::PreSandboxStartup() {
645 const base::CommandLine& command_line =
646 *base::CommandLine::ForCurrentProcess();
647 std::string process_type =
648 command_line.GetSwitchValueASCII(switches::kProcessType);
650 #if defined(OS_POSIX)
651 crash_reporter::SetCrashReporterClient(g_chrome_crash_client.Pointer());
652 #endif
654 #if defined(OS_MACOSX)
655 // On the Mac, the child executable lives at a predefined location within
656 // the app bundle's versioned directory.
657 PathService::Override(content::CHILD_PROCESS_EXE,
658 chrome::GetVersionedDirectory().
659 Append(chrome::kHelperProcessExecutablePath));
661 InitMacCrashReporter(command_line, process_type);
662 #endif
664 #if defined(OS_WIN)
665 child_process_logging::Init();
666 #endif
667 #if defined(ARCH_CPU_ARM_FAMILY) && (defined(OS_ANDROID) || defined(OS_LINUX))
668 // Create an instance of the CPU class to parse /proc/cpuinfo and cache
669 // cpu_brand info.
670 base::CPU cpu_info;
671 #endif
673 // Initialize the user data dir for any process type that needs it.
674 if (chrome::ProcessNeedsProfileDir(process_type))
675 InitializeUserDataDir();
677 // Register component_updater PathProvider after DIR_USER_DATA overidden by
678 // command line flags. Maybe move the chrome PathProvider down here also?
679 component_updater::RegisterPathProvider(chrome::DIR_USER_DATA);
681 // Enable Message Loop related state asap.
682 if (command_line.HasSwitch(switches::kMessageLoopHistogrammer))
683 base::MessageLoop::EnableHistogrammer(true);
685 #if !defined(OS_ANDROID)
686 // Android does InitLogging when library is loaded. Skip here.
687 logging::OldFileDeletionState file_state =
688 logging::APPEND_TO_OLD_LOG_FILE;
689 if (process_type.empty()) {
690 file_state = logging::DELETE_OLD_LOG_FILE;
692 logging::InitChromeLogging(command_line, file_state);
693 #endif
695 #if defined(OS_WIN)
696 // TODO(zturner): Throbber icons are still stored in chrome.dll, this can be
697 // killed once those are merged into resources.pak. See
698 // GlassBrowserFrameView::InitThrobberIcons() and http://crbug.com/368327.
699 ui::SetResourcesDataDLL(_AtlBaseModule.GetResourceInstance());
700 #endif
702 if (SubprocessNeedsResourceBundle(process_type)) {
703 // Initialize ResourceBundle which handles files loaded from external
704 // sources. The language should have been passed in to us from the
705 // browser process as a command line flag.
706 #if defined(DISABLE_NACL)
707 DCHECK(command_line.HasSwitch(switches::kLang) ||
708 process_type == switches::kZygoteProcess ||
709 process_type == switches::kGpuProcess ||
710 process_type == switches::kPpapiBrokerProcess ||
711 process_type == switches::kPpapiPluginProcess);
712 #else
713 DCHECK(command_line.HasSwitch(switches::kLang) ||
714 process_type == switches::kZygoteProcess ||
715 process_type == switches::kGpuProcess ||
716 process_type == switches::kNaClLoaderProcess ||
717 process_type == switches::kPpapiBrokerProcess ||
718 process_type == switches::kPpapiPluginProcess);
719 #endif
721 // TODO(markusheintz): The command line flag --lang is actually processed
722 // by the CommandLinePrefStore, and made available through the PrefService
723 // via the preference prefs::kApplicationLocale. The browser process uses
724 // the --lang flag to pass the value of the PrefService in here. Maybe
725 // this value could be passed in a different way.
726 const std::string locale =
727 command_line.GetSwitchValueASCII(switches::kLang);
728 #if defined(OS_ANDROID)
729 // The renderer sandbox prevents us from accessing our .pak files directly.
730 // Therefore file descriptors to the .pak files that we need are passed in
731 // at process creation time.
732 auto global_descriptors = base::GlobalDescriptors::GetInstance();
733 int pak_fd = global_descriptors->Get(kAndroidLocalePakDescriptor);
734 base::MemoryMappedFile::Region pak_region =
735 global_descriptors->GetRegion(kAndroidLocalePakDescriptor);
736 ResourceBundle::InitSharedInstanceWithPakFileRegion(base::File(pak_fd),
737 pak_region);
739 int extra_pak_keys[] = {
740 kAndroidChrome100PercentPakDescriptor,
741 kAndroidUIResourcesPakDescriptor,
743 for (size_t i = 0; i < arraysize(extra_pak_keys); ++i) {
744 pak_fd = global_descriptors->Get(extra_pak_keys[i]);
745 pak_region = global_descriptors->GetRegion(extra_pak_keys[i]);
746 ResourceBundle::GetSharedInstance().AddDataPackFromFileRegion(
747 base::File(pak_fd), pak_region, ui::SCALE_FACTOR_100P);
750 base::i18n::SetICUDefaultLocale(locale);
751 const std::string loaded_locale = locale;
752 #else
753 const std::string loaded_locale =
754 ui::ResourceBundle::InitSharedInstanceWithLocale(
755 locale, NULL, ui::ResourceBundle::LOAD_COMMON_RESOURCES);
757 base::FilePath resources_pack_path;
758 PathService::Get(chrome::FILE_RESOURCES_PACK, &resources_pack_path);
759 ResourceBundle::GetSharedInstance().AddDataPackFromPath(
760 resources_pack_path, ui::SCALE_FACTOR_NONE);
761 #endif
762 CHECK(!loaded_locale.empty()) << "Locale could not be found for " <<
763 locale;
766 #if !defined(CHROME_MULTIPLE_DLL_BROWSER)
767 if (process_type == switches::kUtilityProcess ||
768 process_type == switches::kZygoteProcess) {
769 ChromeContentUtilityClient::PreSandboxStartup();
772 chrome::InitializePDF();
773 #endif
775 #if defined(OS_POSIX) && !defined(OS_MACOSX)
776 // Zygote needs to call InitCrashReporter() in RunZygote().
777 if (process_type != switches::kZygoteProcess) {
778 #if defined(OS_ANDROID)
779 if (process_type.empty()) {
780 breakpad::InitCrashReporter(process_type);
781 chrome::android::InitJavaExceptionReporter();
782 } else {
783 breakpad::InitNonBrowserCrashReporterForAndroid(process_type);
785 #else // !defined(OS_ANDROID)
786 breakpad::InitCrashReporter(process_type);
787 #endif // defined(OS_ANDROID)
789 #endif // defined(OS_POSIX) && !defined(OS_MACOSX)
791 // After all the platform Breakpads have been initialized, store the command
792 // line for crash reporting.
793 crash_keys::SetSwitchesFromCommandLine(&command_line);
796 void ChromeMainDelegate::SandboxInitialized(const std::string& process_type) {
797 // Note: If you are adding a new process type below, be sure to adjust the
798 // AdjustLinuxOOMScore function too.
799 #if defined(OS_LINUX)
800 AdjustLinuxOOMScore(process_type);
801 #endif
802 #if defined(OS_WIN)
803 SuppressWindowsErrorDialogs();
804 #endif
806 #if defined(CHROME_MULTIPLE_DLL_CHILD) || !defined(CHROME_MULTIPLE_DLL_BROWSER)
807 #if !defined(DISABLE_NACL)
808 ChromeContentClient::SetNaClEntryFunctions(
809 nacl_plugin::PPP_GetInterface,
810 nacl_plugin::PPP_InitializeModule,
811 nacl_plugin::PPP_ShutdownModule);
812 #endif
813 #if defined(ENABLE_PLUGINS) && defined(ENABLE_PDF)
814 ChromeContentClient::SetPDFEntryFunctions(
815 chrome_pdf::PPP_GetInterface,
816 chrome_pdf::PPP_InitializeModule,
817 chrome_pdf::PPP_ShutdownModule);
818 #endif
819 #endif
822 int ChromeMainDelegate::RunProcess(
823 const std::string& process_type,
824 const content::MainFunctionParams& main_function_params) {
825 // ANDROID doesn't support "service", so no ServiceProcessMain, and arraysize
826 // doesn't support empty array. So we comment out the block for Android.
827 #if !defined(OS_ANDROID)
828 static const MainFunction kMainFunctions[] = {
829 #if defined(ENABLE_PRINT_PREVIEW) && !defined(CHROME_MULTIPLE_DLL_CHILD)
830 { switches::kServiceProcess, ServiceProcessMain },
831 #endif
833 #if defined(OS_MACOSX)
834 { switches::kRelauncherProcess,
835 mac_relauncher::internal::RelauncherMain },
836 #endif
838 // This entry is not needed on Linux, where the NaCl loader
839 // process is launched via nacl_helper instead.
840 #if !defined(DISABLE_NACL) && !defined(CHROME_MULTIPLE_DLL_BROWSER) && \
841 !defined(OS_LINUX)
842 { switches::kNaClLoaderProcess, NaClMain },
843 #else
844 { "<invalid>", NULL }, // To avoid constant array of size 0
845 // when DISABLE_NACL and CHROME_MULTIPLE_DLL_CHILD
846 #endif // DISABLE_NACL
849 for (size_t i = 0; i < arraysize(kMainFunctions); ++i) {
850 if (process_type == kMainFunctions[i].name)
851 return kMainFunctions[i].function(main_function_params);
853 #endif
855 return -1;
858 void ChromeMainDelegate::ProcessExiting(const std::string& process_type) {
859 if (SubprocessNeedsResourceBundle(process_type))
860 ResourceBundle::CleanupSharedInstance();
861 #if !defined(OS_ANDROID)
862 logging::CleanupChromeLogging();
863 #else
864 // Android doesn't use InitChromeLogging, so we close the log file manually.
865 logging::CloseLogFile();
866 #endif // !defined(OS_ANDROID)
868 #if defined(OS_WIN)
869 RemoveHandleHooks();
870 #endif
873 #if defined(OS_MACOSX)
874 bool ChromeMainDelegate::ProcessRegistersWithSystemProcess(
875 const std::string& process_type) {
876 #if defined(DISABLE_NACL)
877 return false;
878 #else
879 return process_type == switches::kNaClLoaderProcess;
880 #endif
883 bool ChromeMainDelegate::ShouldSendMachPort(const std::string& process_type) {
884 return process_type != switches::kRelauncherProcess &&
885 process_type != switches::kServiceProcess;
888 bool ChromeMainDelegate::DelaySandboxInitialization(
889 const std::string& process_type) {
890 #if !defined(DISABLE_NACL)
891 // NaClLoader does this in NaClMainPlatformDelegate::EnableSandbox().
892 // No sandbox needed for relauncher.
893 if (process_type == switches::kNaClLoaderProcess)
894 return true;
895 #endif
896 return process_type == switches::kRelauncherProcess;
898 #elif defined(OS_POSIX) && !defined(OS_ANDROID)
899 void ChromeMainDelegate::ZygoteStarting(
900 ScopedVector<content::ZygoteForkDelegate>* delegates) {
901 #if !defined(DISABLE_NACL)
902 nacl::AddNaClZygoteForkDelegates(delegates);
903 #endif
906 void ChromeMainDelegate::ZygoteForked() {
907 Profiling::ProcessStarted();
908 if (Profiling::BeingProfiled()) {
909 base::debug::RestartProfilingAfterFork();
910 SetUpProfilingShutdownHandler();
913 // Needs to be called after we have chrome::DIR_USER_DATA. BrowserMain sets
914 // this up for the browser process in a different manner.
915 const base::CommandLine* command_line =
916 base::CommandLine::ForCurrentProcess();
917 std::string process_type =
918 command_line->GetSwitchValueASCII(switches::kProcessType);
919 breakpad::InitCrashReporter(process_type);
921 // Reset the command line for the newly spawned process.
922 crash_keys::SetSwitchesFromCommandLine(command_line);
925 #endif // OS_MACOSX
927 content::ContentBrowserClient*
928 ChromeMainDelegate::CreateContentBrowserClient() {
929 #if defined(CHROME_MULTIPLE_DLL_CHILD)
930 return NULL;
931 #else
932 return g_chrome_content_browser_client.Pointer();
933 #endif
936 content::ContentPluginClient* ChromeMainDelegate::CreateContentPluginClient() {
937 #if defined(CHROME_MULTIPLE_DLL_BROWSER)
938 return NULL;
939 #else
940 return g_chrome_content_plugin_client.Pointer();
941 #endif
944 content::ContentRendererClient*
945 ChromeMainDelegate::CreateContentRendererClient() {
946 #if defined(CHROME_MULTIPLE_DLL_BROWSER)
947 return NULL;
948 #else
949 return g_chrome_content_renderer_client.Pointer();
950 #endif
953 content::ContentUtilityClient*
954 ChromeMainDelegate::CreateContentUtilityClient() {
955 #if defined(CHROME_MULTIPLE_DLL_BROWSER)
956 return NULL;
957 #else
958 return g_chrome_content_utility_client.Pointer();
959 #endif
962 bool ChromeMainDelegate::ShouldEnableProfilerRecording() {
963 switch (chrome::GetChannel()) {
964 case version_info::Channel::UNKNOWN:
965 case version_info::Channel::CANARY:
966 return true;
967 case version_info::Channel::DEV:
968 case version_info::Channel::BETA:
969 case version_info::Channel::STABLE:
970 default:
971 // Don't enable instrumentation.
972 return false;